You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
76 lines
1.8 KiB
Go
76 lines
1.8 KiB
Go
package tests
|
|
|
|
// Optional DB-backed repository integration test, enabled only when TEST_POSTGRES_URL is set.
|
|
|
|
import (
|
|
"context"
|
|
"net/url"
|
|
"os"
|
|
"strconv"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
domain "knowfoolery/backend/services/question-bank-service/internal/domain/question"
|
|
qent "knowfoolery/backend/services/question-bank-service/internal/infra/persistence/ent"
|
|
sharedpostgres "knowfoolery/backend/shared/infra/database/postgres"
|
|
)
|
|
|
|
// TestRepositoryLifecycle creates and fetches a question against a real Postgres instance when enabled.
|
|
func TestRepositoryLifecycle(t *testing.T) {
|
|
dsn := os.Getenv("TEST_POSTGRES_URL")
|
|
if dsn == "" {
|
|
t.Skip("TEST_POSTGRES_URL not set")
|
|
}
|
|
|
|
cfg := sharedpostgres.DefaultConfig()
|
|
parsed, err := url.Parse(dsn)
|
|
if err != nil {
|
|
t.Fatalf("parse TEST_POSTGRES_URL: %v", err)
|
|
}
|
|
cfg.Host = parsed.Hostname()
|
|
if p, convErr := strconv.Atoi(parsed.Port()); convErr == nil {
|
|
cfg.Port = p
|
|
}
|
|
if parsed.User != nil {
|
|
cfg.User = parsed.User.Username()
|
|
pw, _ := parsed.User.Password()
|
|
cfg.Password = pw
|
|
}
|
|
cfg.Database = strings.TrimPrefix(parsed.Path, "/")
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
defer cancel()
|
|
|
|
client, err := sharedpostgres.NewClient(ctx, cfg)
|
|
if err != nil {
|
|
t.Fatalf("new client: %v", err)
|
|
}
|
|
defer client.Close()
|
|
|
|
repo := qent.NewQuestionRepository(client)
|
|
if err := repo.EnsureSchema(ctx); err != nil {
|
|
t.Fatalf("ensure schema: %v", err)
|
|
}
|
|
|
|
created, err := repo.Create(ctx, &domain.Question{
|
|
Theme: "Science",
|
|
Text: "What is H2O?",
|
|
Answer: "water",
|
|
Hint: "liquid",
|
|
Difficulty: domain.DifficultyEasy,
|
|
IsActive: true,
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("create: %v", err)
|
|
}
|
|
|
|
got, err := repo.GetByID(ctx, created.ID)
|
|
if err != nil {
|
|
t.Fatalf("get: %v", err)
|
|
}
|
|
if got.ID != created.ID {
|
|
t.Fatalf("id mismatch")
|
|
}
|
|
}
|