testdb.go68 lines, 2.1 KB
| 1 | // Package testdb gives integration tests a real Postgres database, and a real Redis. |
| 2 | package testdb |
| 3 | |
| 4 | import ( |
| 5 | "context" |
| 6 | "errors" |
| 7 | "testing" |
| 8 | |
| 9 | "github.com/fiston-user/murmur/internal/platform/postgres" |
| 10 | "github.com/fiston-user/murmur/internal/platform/redisx" |
| 11 | "github.com/jackc/pgx/v5" |
| 12 | "github.com/jackc/pgx/v5/pgconn" |
| 13 | "github.com/jackc/pgx/v5/pgxpool" |
| 14 | "github.com/redis/go-redis/v9" |
| 15 | ) |
| 16 | |
| 17 | // The Compose Postgres (make up). Tests get a database of their own, never the one the API uses. |
| 18 | const ( |
| 19 | adminURL = "postgres://murmur:murmur@localhost:5432/murmur?sslmode=disable&connect_timeout=5" |
| 20 | testURL = "postgres://murmur:murmur@localhost:5432/murmur_test?sslmode=disable&connect_timeout=5" |
| 21 | ) |
| 22 | |
| 23 | // New returns a pool on murmur_test, migrated, with every table empty. |
| 24 | func New(t *testing.T) *pgxpool.Pool { |
| 25 | t.Helper() |
| 26 | ctx := context.Background() |
| 27 | |
| 28 | admin, err := pgx.Connect(ctx, adminURL) |
| 29 | if err != nil { |
| 30 | t.Fatalf("connect to postgres (did you run make up?): %v", err) |
| 31 | } |
| 32 | defer admin.Close(ctx) |
| 33 | _, err = admin.Exec(ctx, `create database murmur_test`) |
| 34 | var pgErr *pgconn.PgError |
| 35 | if err != nil && !(errors.As(err, &pgErr) && pgErr.Code == "42P04") { // duplicate_database |
| 36 | t.Fatalf("create murmur_test: %v", err) |
| 37 | } |
| 38 | |
| 39 | if err := postgres.Migrate(testURL); err != nil { |
| 40 | t.Fatalf("migrate murmur_test: %v", err) |
| 41 | } |
| 42 | pool, err := postgres.Connect(ctx, testURL, 0) |
| 43 | if err != nil { |
| 44 | t.Fatalf("connect to murmur_test: %v", err) |
| 45 | } |
| 46 | t.Cleanup(pool.Close) |
| 47 | if _, err := pool.Exec(ctx, ` |
| 48 | truncate users, posts, follows, jobs, likes, like_deltas, notifications |
| 49 | restart identity`); err != nil { |
| 50 | t.Fatalf("empty the tables: %v", err) |
| 51 | } |
| 52 | return pool |
| 53 | } |
| 54 | |
| 55 | // Redis returns a client on database 1 of the Compose Redis, emptied. The API uses database 0. |
| 56 | func Redis(t *testing.T) *redis.Client { |
| 57 | t.Helper() |
| 58 | ctx := context.Background() |
| 59 | rdb, err := redisx.Connect(ctx, "redis://localhost:6379/1") |
| 60 | if err != nil { |
| 61 | t.Fatalf("connect to redis (did you run make up?): %v", err) |
| 62 | } |
| 63 | t.Cleanup(func() { rdb.Close() }) |
| 64 | if err := rdb.FlushDB(ctx).Err(); err != nil { |
| 65 | t.Fatalf("empty redis database 1: %v", err) |
| 66 | } |
| 67 | return rdb |
| 68 | } |