|
| 1 | +package tests |
| 2 | + |
| 3 | +import ( |
| 4 | + "strings" |
| 5 | + "testing" |
| 6 | + |
| 7 | + "go.uber.org/zap/zaptest/observer" |
| 8 | +) |
| 9 | + |
| 10 | +// AssertLogEventually waits until at least one log message containing the |
| 11 | +// specified msg is emitted. |
| 12 | +// NOTE: This does not "pop" messages so it cannot be used multiple times to |
| 13 | +// check for new instances of the same msg. See AssertLogCountEventually instead. |
| 14 | +// |
| 15 | +// Get a *observer.ObservedLogs like so: |
| 16 | +// |
| 17 | +// observedZapCore, observedLogs := observer.New(zap.DebugLevel) |
| 18 | +// lggr := logger.TestLogger(t, observedZapCore) |
| 19 | +func AssertLogEventually(t *testing.T, observedLogs *observer.ObservedLogs, msg string) { |
| 20 | + AssertLogCountEventually(t, observedLogs, msg, 1) |
| 21 | +} |
| 22 | + |
| 23 | +// AssertLogCountEventually waits until at least count log message containing the |
| 24 | +// specified msg is emitted |
| 25 | +func AssertLogCountEventually(t *testing.T, observedLogs *observer.ObservedLogs, msg string, count int) { |
| 26 | + AssertEventually(t, func() bool { |
| 27 | + i := 0 |
| 28 | + for _, l := range observedLogs.All() { |
| 29 | + if strings.Contains(l.Message, msg) { |
| 30 | + i++ |
| 31 | + if i >= count { |
| 32 | + return true |
| 33 | + } |
| 34 | + } |
| 35 | + } |
| 36 | + return false |
| 37 | + }) |
| 38 | +} |
| 39 | + |
| 40 | +// RequireLogMessage fails the test if emitted logs don't contain the given message |
| 41 | +func RequireLogMessage(t *testing.T, observedLogs *observer.ObservedLogs, msg string) { |
| 42 | + for _, l := range observedLogs.All() { |
| 43 | + if strings.Contains(l.Message, msg) { |
| 44 | + return |
| 45 | + } |
| 46 | + } |
| 47 | + t.Log("observed logs", observedLogs.All()) |
| 48 | + t.Fatalf("expected observed logs to contain msg %q, but it didn't", msg) |
| 49 | +} |
0 commit comments