chore: cleanup handle_test

This commit is contained in:
Bastien Riviere 2024-02-09 19:35:23 +01:00
parent 30d3db9d5e
commit e9b7f7ab4b
Signed by: babariviere
GPG key ID: 4E5F0839249F162E

View file

@ -15,45 +15,57 @@ import (
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
) )
func withServer(f func(handler oas.Handler)) { func prepare(t *testing.T) oas.Handler {
name := fmt.Sprintf("test%d", time.Now().Unix()) name := fmt.Sprintf("test%d", time.Now().Unix())
ctx := context.TODO() connCfg, err := pgx.ParseConfig(os.Getenv("DATABASE_URL"))
root, err := pgx.Connect(ctx, os.Getenv("DATABASE_URL"))
if err != nil { if err != nil {
log.Fatal(err) t.Fatal(err)
} }
ctx := context.TODO()
root, err := pgx.ConnectConfig(ctx, connCfg)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
root.Close(ctx)
})
if _, err = root.Exec(ctx, "CREATE DATABASE "+name+";"); err != nil { if _, err = root.Exec(ctx, "CREATE DATABASE "+name+";"); err != nil {
log.Fatal("failed to create database", name) t.Fatal("failed to create database", name)
} }
defer func() { t.Cleanup(func() {
root.Exec(ctx, "DROP DATABASE "+name+";") root.Exec(ctx, "DROP DATABASE "+name+";")
}() })
// TODO: substitute from DATABASE_URL instead connCfg.Database = name
conn, err := pgx.Connect(ctx, "postgres://short:short@localhost:5432/"+name) conn, err := pgx.ConnectConfig(ctx, connCfg)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
t.Cleanup(func() {
conn.Close(ctx)
})
schema, err := os.ReadFile("../../sql/schema.sql") schema, err := os.ReadFile("../../sql/schema.sql")
if err != nil { if err != nil {
log.Fatal(err) t.Fatal(err)
} }
conn.Exec(ctx, string(schema)) conn.Exec(ctx, string(schema))
f(api.NewHandler("http://test", db.New(conn))) return api.NewHandler("http://test", db.New(conn))
conn.Close(ctx)
} }
func TestCreateURL(t *testing.T) { func TestCreateURL(t *testing.T) {
h := prepare(t)
cases := []string{ cases := []string{
"http://test.com", "http://test.com",
"http://github.com", "http://github.com",
"abcdef", // FIXME: should not pass but it works... "abcdef", // FIXME: should not pass but it works...
} }
withServer(func(h oas.Handler) {
for _, url := range cases { for _, url := range cases {
shortenRes, err := h.CreateShortURL(context.TODO(), &oas.CreateShortURLReq{ shortenRes, err := h.CreateShortURL(context.TODO(), &oas.CreateShortURLReq{
URL: url, URL: url,
@ -86,5 +98,4 @@ func TestCreateURL(t *testing.T) {
t.Errorf("supplied %q but got %q during redirect", url, redirect.Location.Value) t.Errorf("supplied %q but got %q during redirect", url, redirect.Location.Value)
} }
} }
})
} }