leader_test.go54 lines, 1.3 KB
| 1 | package jobs_test |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "log/slog" |
| 6 | "sync" |
| 7 | "testing" |
| 8 | "time" |
| 9 | |
| 10 | "github.com/fiston-user/payments/internal/platform/jobs" |
| 11 | ) |
| 12 | |
| 13 | // TestOneLeader runs two replicas' electors on one lock: one leads, the other |
| 14 | // waits, and takes over when the first one's replica goes away. |
| 15 | func TestOneLeader(t *testing.T) { |
| 16 | t.Parallel() |
| 17 | if testing.Short() { |
| 18 | t.Skip("integration test") |
| 19 | } |
| 20 | leaders := make(chan string, 2) |
| 21 | var wg sync.WaitGroup |
| 22 | t.Cleanup(wg.Wait) // t.Context() is done by then: every elector stops |
| 23 | elect := func(ctx context.Context, name string) { |
| 24 | e := jobs.NewElector(postgresURL, t.Name(), slog.New(slog.DiscardHandler)) |
| 25 | e.Retry = 50 * time.Millisecond |
| 26 | wg.Go(func() { |
| 27 | e.Run(ctx, func(ctx context.Context) { |
| 28 | leaders <- name |
| 29 | <-ctx.Done() // lead until told to stop |
| 30 | }) |
| 31 | }) |
| 32 | } |
| 33 | // expect waits a second for the next leader: want, or nobody, for "". |
| 34 | expect := func(want string) { |
| 35 | t.Helper() |
| 36 | select { |
| 37 | case got := <-leaders: |
| 38 | if got != want { |
| 39 | t.Fatalf("%s leads, want %q", got, want) |
| 40 | } |
| 41 | case <-time.After(time.Second): |
| 42 | if want != "" { |
| 43 | t.Fatalf("nobody leads, want %s", want) |
| 44 | } |
| 45 | } |
| 46 | } |
| 47 | a, stopA := context.WithCancel(t.Context()) |
| 48 | elect(a, "a") |
| 49 | expect("a") |
| 50 | elect(t.Context(), "b") |
| 51 | expect("") // a still leads: b waits |
| 52 | stopA() // a's replica goes away |
| 53 | expect("b") |
| 54 | } |