short/internal/api/handler_test.go

102 lines
2.1 KiB
Go
Raw Permalink Normal View History

2024-01-29 21:13:08 +00:00
package api_test
import (
"context"
"fmt"
"log"
"os"
"strings"
"testing"
"time"
"github.com/babariviere/short/internal/api"
"github.com/babariviere/short/internal/db"
"github.com/babariviere/short/internal/oas"
"github.com/jackc/pgx/v5"
)
2024-02-09 18:35:23 +00:00
func prepare(t *testing.T) oas.Handler {
2024-01-29 21:13:08 +00:00
name := fmt.Sprintf("test%d", time.Now().Unix())
2024-02-09 18:35:23 +00:00
connCfg, err := pgx.ParseConfig(os.Getenv("DATABASE_URL"))
if err != nil {
t.Fatal(err)
}
2024-01-29 21:13:08 +00:00
ctx := context.TODO()
2024-02-09 18:35:23 +00:00
root, err := pgx.ConnectConfig(ctx, connCfg)
2024-01-29 21:13:08 +00:00
if err != nil {
2024-02-09 18:35:23 +00:00
t.Fatal(err)
2024-01-29 21:13:08 +00:00
}
2024-02-09 18:35:23 +00:00
t.Cleanup(func() {
root.Close(ctx)
})
2024-01-29 21:13:08 +00:00
if _, err = root.Exec(ctx, "CREATE DATABASE "+name+";"); err != nil {
2024-02-09 18:35:23 +00:00
t.Fatal("failed to create database", name)
2024-01-29 21:13:08 +00:00
}
2024-02-09 18:35:23 +00:00
t.Cleanup(func() {
2024-01-29 21:13:08 +00:00
root.Exec(ctx, "DROP DATABASE "+name+";")
2024-02-09 18:35:23 +00:00
})
2024-01-29 21:13:08 +00:00
2024-02-09 18:35:23 +00:00
connCfg.Database = name
conn, err := pgx.ConnectConfig(ctx, connCfg)
2024-01-29 21:13:08 +00:00
if err != nil {
log.Fatal(err)
}
2024-02-09 18:35:23 +00:00
t.Cleanup(func() {
conn.Close(ctx)
})
2024-01-29 21:13:08 +00:00
schema, err := os.ReadFile("../../sql/schema.sql")
if err != nil {
2024-02-09 18:35:23 +00:00
t.Fatal(err)
2024-01-29 21:13:08 +00:00
}
conn.Exec(ctx, string(schema))
2024-02-09 18:35:23 +00:00
return api.NewHandler("http://test", db.New(conn))
2024-01-29 21:13:08 +00:00
}
func TestCreateURL(t *testing.T) {
2024-02-09 18:35:23 +00:00
h := prepare(t)
2024-01-29 21:13:08 +00:00
cases := []string{
"http://test.com",
"http://github.com",
"abcdef", // FIXME: should not pass but it works...
}
2024-02-09 18:35:23 +00:00
for _, url := range cases {
shortenRes, err := h.CreateShortURL(context.TODO(), &oas.CreateShortURLReq{
URL: url,
})
if err != nil {
t.Errorf("failed to create url %q: %v", url, err)
continue
2024-01-29 21:13:08 +00:00
}
2024-02-09 18:35:23 +00:00
shorten, ok := shortenRes.(*oas.CreateShortURLCreated)
if !ok {
t.Errorf("expected 201 status code, got 400 for url %q", url)
continue
}
res, err := h.RedirectLongURL(context.TODO(), oas.RedirectLongURLParams{
Hash: strings.TrimPrefix(shorten.Shorten, "http://test/"),
})
if err != nil {
t.Errorf("failed to get redirect url for %q: %v", url, err)
continue
}
redirect, ok := res.(*oas.RedirectLongURLTemporaryRedirect)
if !ok {
t.Errorf("expected 307 status code, got 404 for url %q with shorten %q", url, shorten.Shorten)
}
if redirect.Location.Value != url {
t.Errorf("supplied %q but got %q during redirect", url, redirect.Location.Value)
}
}
2024-01-29 21:13:08 +00:00
}