RequireLogIs asserts that the logs produced by function f contain string s.
(t testing.TB, s string, f func())
| 21 | |
| 22 | // RequireLogIs asserts that the logs produced by function f contain string s. |
| 23 | func requireLogIs(t testing.TB, s string, f func()) { |
| 24 | b := bytes.Buffer{} |
| 25 | |
| 26 | config := &ConsoleLoggerConfig{ |
| 27 | ColorEnabled: Ptr(false), |
| 28 | } |
| 29 | tempLogger, err := NewConsoleLogger(TestCtx(t), false, config) |
| 30 | require.NoError(t, err) |
| 31 | tempLogger.logger.SetOutput(&b) |
| 32 | timestampLength := len(time.Now().Format(ISO8601Format) + " ") |
| 33 | |
| 34 | // Temporarily override logger output for the given function call |
| 35 | oldLogger := consoleLogger.Swap(tempLogger) |
| 36 | defer func() { |
| 37 | consoleLogger.Store(oldLogger) |
| 38 | }() |
| 39 | |
| 40 | f() |
| 41 | |
| 42 | var log string |
| 43 | var originalLog string |
| 44 | // Allow time for logs to be printed |
| 45 | retry := func() (shouldRetry bool, err error, value interface{}) { |
| 46 | originalLog = b.String() |
| 47 | if len(originalLog) < timestampLength { |
| 48 | return false, nil, nil |
| 49 | } |
| 50 | log = originalLog[timestampLength:] |
| 51 | if log == s { |
| 52 | return false, nil, nil |
| 53 | } |
| 54 | return true, nil, nil |
| 55 | } |
| 56 | err, _ = RetryLoop(TestCtx(t), "wait for logs", retry, CreateSleeperFunc(10, 100)) |
| 57 | |
| 58 | require.NoError(t, err, "Console logs did not contain %q, got %q", s, originalLog) |
| 59 | } |
| 60 | |
| 61 | func RequireLogMessage(t testing.TB, ctx context.Context, expectedMessage string, logString string) { |
| 62 | requireLogIs(t, expectedMessage, func() { InfofCtx(ctx, KeyAll, standardMessage) }) |
no test coverage detected