main: rework the way the mock logger is passed

Pass the mock logger directly to `run()` instead of mocking
`logrus.New`. Doing the later leads to a data race when multiple
parallel tests modify the (global) `var logrusNew logrus.New`.

Thanks to Tomas Hozza for reporting.
This commit is contained in:
Michael Vogt 2024-06-06 17:36:31 +02:00
parent 95b4a9e250
commit 8ebefbdbc9
3 changed files with 7 additions and 24 deletions

View file

@ -4,9 +4,6 @@ import (
"os"
"path/filepath"
"testing"
"github.com/sirupsen/logrus"
logrusTest "github.com/sirupsen/logrus/hooks/test"
)
var (
@ -15,19 +12,6 @@ var (
HandleIncludedSources = handleIncludedSources
)
func MockLogger() (hook *logrusTest.Hook, restore func()) {
saved := logrusNew
logger, hook := logrusTest.NewNullLogger()
logrusNew = func() *logrus.Logger {
return logger
}
logger.SetLevel(logrus.DebugLevel)
return hook, func() {
logrusNew = saved
}
}
func MockOsbuildBinary(t *testing.T, new string) (restore func()) {
t.Helper()

View file

@ -16,8 +16,6 @@ import (
// based on the excellent post
// https://grafana.com/blog/2024/02/09/how-i-write-http-services-in-go-after-13-years/
var logrusNew = logrus.New
func newServer(logger *logrus.Logger, config *Config) http.Handler {
mux := http.NewServeMux()
addRoutes(mux, logger, config)
@ -27,11 +25,10 @@ func newServer(logger *logrus.Logger, config *Config) http.Handler {
return handler
}
func run(ctx context.Context, args []string, getenv func(string) string) error {
func run(ctx context.Context, args []string, getenv func(string) string, logger *logrus.Logger) error {
ctx, cancel := signal.NotifyContext(ctx, os.Interrupt)
defer cancel()
logger := logrusNew()
config, err := newConfigFromCmdline(args)
if err != nil {
return err
@ -75,8 +72,9 @@ func run(ctx context.Context, args []string, getenv func(string) string) error {
}
func main() {
logger := logrus.New()
ctx := context.Background()
if err := run(ctx, os.Args, os.Getenv); err != nil {
if err := run(ctx, os.Args, os.Getenv, logger); err != nil {
fmt.Fprintf(os.Stderr, "%s\n", err)
os.Exit(1)
}

View file

@ -8,6 +8,7 @@ import (
"testing"
"time"
"github.com/sirupsen/logrus"
logrusTest "github.com/sirupsen/logrus/hooks/test"
"github.com/stretchr/testify/assert"
@ -57,8 +58,8 @@ func runTestServer(t *testing.T) (baseURL, buildBaseDir string, loggerHook *logr
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
loggerHook, restore := main.MockLogger()
defer restore()
logger, loggerHook := logrusTest.NewNullLogger()
logger.SetLevel(logrus.DebugLevel)
args := []string{
"-host", host,
@ -66,7 +67,7 @@ func runTestServer(t *testing.T) (baseURL, buildBaseDir string, loggerHook *logr
"-build-path", buildBaseDir,
}
go func() {
_ = main.Run(ctx, args, os.Getenv)
_ = main.Run(ctx, args, os.Getenv, logger)
}()
err := waitReady(ctx, defaultTimeout, baseURL)