ntfy-server/db/test/test.go

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

65 lines
1.7 KiB
Go
Raw Normal View History

2026-02-20 15:36:12 -05:00
package dbtest
import (
"fmt"
"net/url"
"os"
"testing"
"github.com/stretchr/testify/require"
2026-03-10 22:17:40 -04:00
"heckel.io/ntfy/v2/db"
2026-03-02 19:52:36 -05:00
"heckel.io/ntfy/v2/db/pg"
2026-02-20 15:36:12 -05:00
"heckel.io/ntfy/v2/util"
)
const testPoolMaxConns = "2"
2026-02-21 10:36:09 -05:00
// CreateTestPostgresSchema creates a temporary PostgreSQL schema and returns the DSN pointing to it.
2026-02-20 15:36:12 -05:00
// It registers a cleanup function to drop the schema when the test finishes.
// If NTFY_TEST_DATABASE_URL is not set, the test is skipped.
2026-02-21 10:36:09 -05:00
func CreateTestPostgresSchema(t *testing.T) string {
2026-02-20 15:36:12 -05:00
t.Helper()
dsn := os.Getenv("NTFY_TEST_DATABASE_URL")
if dsn == "" {
t.Skip("NTFY_TEST_DATABASE_URL not set")
}
schema := fmt.Sprintf("test_%s", util.RandomString(10))
u, err := url.Parse(dsn)
require.Nil(t, err)
q := u.Query()
q.Set("pool_max_conns", testPoolMaxConns)
u.RawQuery = q.Encode()
dsn = u.String()
2026-03-11 21:07:58 -04:00
setupHost, err := pg.Open(dsn)
2026-02-20 15:36:12 -05:00
require.Nil(t, err)
2026-03-11 21:07:58 -04:00
_, err = setupHost.DB.Exec(fmt.Sprintf("CREATE SCHEMA %s", schema))
2026-02-20 15:36:12 -05:00
require.Nil(t, err)
2026-03-11 21:07:58 -04:00
require.Nil(t, setupHost.DB.Close())
2026-02-20 15:36:12 -05:00
q.Set("search_path", schema)
u.RawQuery = q.Encode()
schemaDSN := u.String()
t.Cleanup(func() {
2026-03-11 21:07:58 -04:00
cleanHost, err := pg.Open(dsn)
2026-02-20 15:36:12 -05:00
if err == nil {
2026-03-11 21:07:58 -04:00
cleanHost.DB.Exec(fmt.Sprintf("DROP SCHEMA %s CASCADE", schema))
cleanHost.DB.Close()
2026-02-20 15:36:12 -05:00
}
})
return schemaDSN
}
2026-03-10 22:17:40 -04:00
// CreateTestPostgres creates a temporary PostgreSQL schema and returns an open *db.DB connection to it.
2026-02-20 15:36:12 -05:00
// It registers cleanup functions to close the DB and drop the schema when the test finishes.
// If NTFY_TEST_DATABASE_URL is not set, the test is skipped.
2026-03-10 22:17:40 -04:00
func CreateTestPostgres(t *testing.T) *db.DB {
2026-02-20 15:36:12 -05:00
t.Helper()
2026-02-21 10:36:09 -05:00
schemaDSN := CreateTestPostgresSchema(t)
2026-03-11 21:07:58 -04:00
testHost, err := pg.Open(schemaDSN)
2026-02-20 15:36:12 -05:00
require.Nil(t, err)
2026-03-11 21:07:58 -04:00
d := db.New(testHost, nil)
2026-02-20 15:36:12 -05:00
t.Cleanup(func() {
2026-03-10 22:17:40 -04:00
d.Close()
2026-02-20 15:36:12 -05:00
})
2026-03-10 22:17:40 -04:00
return d
2026-02-20 15:36:12 -05:00
}