package db import ( "context" "errors" "io" "log/slog" "testing" "time" ) var quietLogger = slog.New(slog.NewTextHandler(io.Discard, nil)) func TestWaitFor_RetriesUntilTheDatabaseAnswers(t *testing.T) { calls := 0 err := waitFor(context.Background(), quietLogger, time.Millisecond, time.Second, func(context.Context) error { calls++ if calls < 3 { return errors.New("connection refused") } return nil }) if err != nil { t.Fatalf("waitFor = %v, want nil once the third attempt connects", err) } if calls != 3 { t.Errorf("attempts = %d, want 3 (two refusals, then success)", calls) } } func TestWaitFor_GivesUpWithTheLastError(t *testing.T) { refused := errors.New("password authentication failed") err := waitFor(context.Background(), quietLogger, time.Millisecond, 20*time.Millisecond, func(context.Context) error { return refused }) if !errors.Is(err, refused) { t.Fatalf("waitFor = %v, want it to carry the last connection error", err) } } func TestWaitFor_StopsWhenShutdownBegins(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) cancel() start := time.Now() err := waitFor(ctx, quietLogger, time.Hour, time.Hour, func(context.Context) error { return errors.New("connection refused") }) if !errors.Is(err, context.Canceled) { t.Fatalf("waitFor = %v, want context.Canceled", err) } if time.Since(start) > time.Second { t.Errorf("waitFor took %s after cancel, want an immediate return", time.Since(start)) } } func TestWaitReady_EmptyURLIsAnErrorNotAWait(t *testing.T) { if err := WaitReady(context.Background(), "", quietLogger); err == nil { t.Fatal("WaitReady(\"\") = nil, want an error") } }