From 67985d88e6d6c52a43031a484329bd9b260313e0 Mon Sep 17 00:00:00 2001 From: Eugene Sumin <95425330+e-sumin@users.noreply.github.com> Date: Thu, 21 Mar 2024 14:25:48 +0100 Subject: [PATCH] fix(tests): Fix flaky TestCloneGlobalLogger (#2775) * fix(tests): Fix flaky TestCloneGlobalLogger * Rename test hook --- pkg/log/log_test.go | 46 ++++++++++++++++++--------------------------- 1 file changed, 18 insertions(+), 28 deletions(-) diff --git a/pkg/log/log_test.go b/pkg/log/log_test.go index b6ccf5f52f..96c2e91c6d 100644 --- a/pkg/log/log_test.go +++ b/pkg/log/log_test.go @@ -197,28 +197,7 @@ func (s *LogSuite) TestLogLevel(c *C) { } func (s *LogSuite) TestCloneGlobalLogger(c *C) { - done := make(chan struct{}) - defer close(done) - - capturedMessages := make([]*logrus.Entry, 0) - newTestHook := func(ctx context.Context) *FluentbitHook { - ec := make(chan *logrus.Entry, defaultEntryBufferCount) - - go func(in <-chan *logrus.Entry) { - for { - select { - case e := <-in: - capturedMessages = append(capturedMessages, e) - case <-done: - return - } - } - }(ec) - - return &FluentbitHook{logs: ec} - } - - hook := newTestHook(context.TODO()) + hook := newTestLogHook() log.AddHook(hook) actual := cloneGlobalLogger() c.Assert(actual.Formatter, Equals, log.Formatter) @@ -232,7 +211,7 @@ func (s *LogSuite) TestCloneGlobalLogger(c *C) { actual.SetReportCaller(true) actual.SetLevel(logrus.ErrorLevel) actual.SetOutput(&bytes.Buffer{}) - actual.AddHook(&testLogHook{}) + actual.AddHook(&logHook{}) c.Assert(actual.Formatter, Not(Equals), log.Formatter) c.Assert(actual.ReportCaller, Not(Equals), log.ReportCaller) @@ -241,19 +220,30 @@ func (s *LogSuite) TestCloneGlobalLogger(c *C) { c.Assert(actual.Hooks, Not(DeepEquals), log.Hooks) log.Println("Test message") - c.Assert(len(capturedMessages), Equals, 1) - c.Assert(capturedMessages[0].Message, Equals, "Test message") + c.Assert(len(hook.capturedMessages), Equals, 1) + c.Assert(hook.capturedMessages[0].Message, Equals, "Test message") } -type testLogHook struct{} +type logHook struct { + capturedMessages []*logrus.Entry +} -func (t *testLogHook) Levels() []logrus.Level { +func newTestLogHook() *logHook { + return &logHook{ + capturedMessages: make([]*logrus.Entry, 0), + } +} + +func (t *logHook) Levels() []logrus.Level { return []logrus.Level{ logrus.InfoLevel, logrus.DebugLevel, } } -func (t *testLogHook) Fire(*logrus.Entry) error { +func (t *logHook) Fire(entry *logrus.Entry) error { + if t.capturedMessages != nil { + t.capturedMessages = append(t.capturedMessages, entry) + } return nil }