Debian Codegraph @

db/test/test.go

raw
1 package dbtest
2
3 import (
4 "fmt"
5 "net/url"
6 "os"
7 "testing"
8
9 "github.com/stretchr/testify/require"
10 "heckel.io/ntfy/v2/db"
11 "heckel.io/ntfy/v2/db/pg"
12 "heckel.io/ntfy/v2/util"
13 )
14
15 const testPoolMaxConns = "2"
16
17 // CreateTestPostgresSchema creates a temporary PostgreSQL schema and returns the DSN pointing to it.
18 // It registers a cleanup function to drop the schema when the test finishes.
19 // If NTFY_TEST_DATABASE_URL is not set, the test is skipped.
20 func CreateTestPostgresSchema(t *testing.T) string {
21 t.Helper()
22 dsn := os.Getenv("NTFY_TEST_DATABASE_URL")
23 if dsn == "" {
24 t.Skip("NTFY_TEST_DATABASE_URL not set")
25 }
26 schema := fmt.Sprintf("test_%s", util.RandomString(10))
27 u, err := url.Parse(dsn)
28 require.Nil(t, err)
29 q := u.Query()
30 q.Set("pool_max_conns", testPoolMaxConns)
31 u.RawQuery = q.Encode()
32 dsn = u.String()
33 setupHost, err := pg.Open(dsn)
34 require.Nil(t, err)
35 _, err = setupHost.DB.Exec(fmt.Sprintf("CREATE SCHEMA %s", schema))
36 require.Nil(t, err)
37 require.Nil(t, setupHost.DB.Close())
38 q.Set("search_path", schema)
39 u.RawQuery = q.Encode()
40 schemaDSN := u.String()
41 t.Cleanup(func() {
42 cleanHost, err := pg.Open(dsn)
43 if err == nil {
44 cleanHost.DB.Exec(fmt.Sprintf("DROP SCHEMA %s CASCADE", schema))
45 cleanHost.DB.Close()
46 }
47 })
48 return schemaDSN
49 }
50
51 // CreateTestPostgres creates a temporary PostgreSQL schema and returns an open *db.DB connection to it.
52 // It registers cleanup functions to close the DB and drop the schema when the test finishes.
53 // If NTFY_TEST_DATABASE_URL is not set, the test is skipped.
54 func CreateTestPostgres(t *testing.T) *db.DB {
55 t.Helper()
56 schemaDSN := CreateTestPostgresSchema(t)
57 testHost, err := pg.Open(schemaDSN)
58 require.Nil(t, err)
59 d := db.New(testHost, nil)
60 t.Cleanup(func() {
61 d.Close()
62 })
63 return d
64 }