| 1 | package replica |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "testing" |
| 6 | |
| 7 | "github.com/fiston-user/murmur/internal/platform/testdb" |
| 8 | "github.com/jackc/pgx/v5/pgxpool" |
| 9 | ) |
| 10 | |
| 11 | // Two pools on the one test database stand in for the primary and the replica. |
| 12 | // What matters is which of the two a read gets. |
| 13 | func TestFor(t *testing.T) { |
| 14 | ctx := context.Background() |
| 15 | primary, spare, rdb := testdb.New(t), testdb.New(t), testdb.Redis(t) |
| 16 | r := New(primary, spare, rdb) |
| 17 | r.usable.Store(true) |
| 18 | for _, step := range []struct { |
| 19 | name string |
| 20 | do func() |
| 21 | user int64 |
| 22 | want *pgxpool.Pool |
| 23 | }{ |
| 24 | {"nobody reads the replica", func() {}, 0, spare}, |
| 25 | {"so does a user who wrote nothing", func() {}, 7, spare}, |
| 26 | {"a user who just wrote reads the primary", func() { r.Wrote(ctx, 7) }, 7, primary}, |
| 27 | {"everybody else still reads the replica", func() {}, 8, spare}, |
| 28 | {"a replica that is behind is read by nobody", func() { r.usable.Store(false) }, 8, primary}, |
| 29 | } { |
| 30 | step.do() |
| 31 | if got := r.For(ctx, step.user); got != step.want { |
| 32 | t.Errorf("%s: got the wrong pool", step.name) |
| 33 | } |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | // A database that is not a replica is never taken for one. |
| 38 | func TestCheck(t *testing.T) { |
| 39 | primary := testdb.New(t) |
| 40 | r := New(primary, primary, nil) |
| 41 | r.usable.Store(true) |
| 42 | r.check(context.Background()) |
| 43 | if r.usable.Load() { |
| 44 | t.Error("the primary was taken for a replica") |
| 45 | } |
| 46 | } |