diff --git a/internal/sww/sww_test.go b/internal/sww/sww_test.go index 84b9b1f..fbff72f 100644 --- a/internal/sww/sww_test.go +++ b/internal/sww/sww_test.go @@ -92,6 +92,31 @@ func (o *output) line(t *testing.T, key, value string) map[string]any { return nil } +// lineBeforeExit returns the first line whose msg is msg, waiting for it +// while sww runs. It waits as long as that takes, so that a slow start +// cannot fail the test, and fails the test if sww exits first. +func (o *output) lineBeforeExit( + t *testing.T, msg string, exited <-chan int, +) map[string]any { + t.Helper() + + for { + fields := o.findLine(t, func(fields map[string]any) bool { + return fields["msg"] == msg + }) + if fields != nil { + return fields + } + + select { + case status := <-exited: + t.Fatalf("exit status %d while waiting for a line with msg %q; output:\n%s", + status, msg, o.text()) + case <-time.After(pollInterval): + } + } +} + // findLine returns the first line written so far for which matches is true, or // nil. func (o *output) findLine( @@ -236,11 +261,12 @@ func TestServesUntilToldToStop(t *testing.T) { }() // The default rule file is read. - if rules := out.line(t, "msg", "read the rule files")["rules"]; rules != 12.0 { + readRules := out.lineBeforeExit(t, "read the rule files", exited) + if rules := readRules["rules"]; rules != 12.0 { t.Errorf("read %v rules from the default rule file, want 12", rules) } - starting := out.line(t, "msg", "starting") + starting := out.lineBeforeExit(t, "starting", exited) wantStartingLine(t, starting, dir) addr, _ := starting["address"].(string) @@ -286,7 +312,7 @@ func TestLogLevelHoldsBackTheLessSevereProcessLines(t *testing.T) { }, out) }() - out.line(t, "msg", "fetching a list failed") + out.lineBeforeExit(t, "fetching a list failed", exited) stop() select { @@ -1261,7 +1287,7 @@ func runUntilStopped( exited <- run(ctx, env, out) }() - addr, _ := out.line(t, "msg", "starting")["address"].(string) + addr, _ := out.lineBeforeExit(t, "starting", exited)["address"].(string) use("http://" + addr + "/") stop()