test: add self-contained integration environment

Separate schema migrations from environment-specific fixtures, run the full API workflow against a disposable PostgreSQL Testcontainer, and provide seeded development and UI test environments.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
Daniel Noulet 2026-09-19 21:11:20 +02:00
parent 6153017b62
commit 6969f79015
18 changed files with 772 additions and 269 deletions

View file

@ -0,0 +1,9 @@
INSERT INTO traits (name, normalized) VALUES
('Go', 'go'),
('PostgreSQL', 'postgresql'),
('Docker', 'docker'),
('React', 'react'),
('TypeScript', 'typescript'),
('Kubernetes', 'kubernetes'),
('Backend', 'backend')
ON CONFLICT (normalized) DO NOTHING;

View file

@ -0,0 +1,87 @@
INSERT INTO users (email, password_hash, role)
VALUES ('interviewer@go-guess.local', crypt('admin123', gen_salt('bf')), 'interviewer')
ON CONFLICT (email) DO NOTHING;
INSERT INTO job_postings (title, description, seniority, position, status, duration_minutes)
SELECT 'Senior Go Backend Engineer', 'Build reliable APIs for passenger-facing railway systems.',
'Senior', 'Backend Engineer', 'published', 60
WHERE NOT EXISTS (SELECT 1 FROM job_postings WHERE title = 'Senior Go Backend Engineer');
INSERT INTO job_postings (title, description, seniority, position, status, duration_minutes)
SELECT 'Full-stack Product Engineer', 'Deliver accessible operational tools from database to browser.',
'Medior', 'Full-stack Engineer', 'published', 45
WHERE NOT EXISTS (SELECT 1 FROM job_postings WHERE title = 'Full-stack Product Engineer');
INSERT INTO questions (text, type, reference_answer)
SELECT 'How do you design graceful shutdown for an HTTP service?', 'open',
'Stop accepting work, cancel dependent operations, drain active requests, and close resources within a deadline.'
WHERE NOT EXISTS (SELECT 1 FROM questions WHERE text = 'How do you design graceful shutdown for an HTTP service?');
INSERT INTO questions (text, type)
SELECT 'Which construct protects shared data across goroutines?', 'radio'
WHERE NOT EXISTS (SELECT 1 FROM questions WHERE text = 'Which construct protects shared data across goroutines?');
INSERT INTO questions (text, type, reference_answer, code_snippet)
SELECT 'Review this component and identify unnecessary renders.', 'code_review',
'Use a stable key and avoid recreating expensive derived values when the candidates input has not changed.',
E'function CandidateList({ candidates }) {\n return candidates.map((candidate, index) => (\n <CandidateCard key={index} candidate={candidate} />\n ));\n}'
WHERE NOT EXISTS (SELECT 1 FROM questions WHERE text = 'Review this component and identify unnecessary renders.');
INSERT INTO question_options (question_id, text)
SELECT q.id, option.text
FROM questions q
CROSS JOIN (VALUES ('sync.Mutex'), ('context.Context'), ('http.Client')) AS option(text)
WHERE q.text = 'Which construct protects shared data across goroutines?'
AND NOT EXISTS (SELECT 1 FROM question_options existing WHERE existing.question_id = q.id);
INSERT INTO job_posting_questions (job_posting_id, question_id)
SELECT j.id, q.id
FROM job_postings j
JOIN questions q ON q.text IN (
'How do you design graceful shutdown for an HTTP service?',
'Which construct protects shared data across goroutines?'
)
WHERE j.title = 'Senior Go Backend Engineer'
ON CONFLICT DO NOTHING;
INSERT INTO job_posting_questions (job_posting_id, question_id)
SELECT j.id, q.id
FROM job_postings j
JOIN questions q ON q.text = 'Review this component and identify unnecessary renders.'
WHERE j.title = 'Full-stack Product Engineer'
ON CONFLICT DO NOTHING;
INSERT INTO job_posting_labels (job_posting_id, trait_id)
SELECT j.id, t.id FROM job_postings j JOIN traits t ON t.normalized IN ('backend', 'go')
WHERE j.title = 'Senior Go Backend Engineer' ON CONFLICT DO NOTHING;
INSERT INTO job_required_skills (job_posting_id, trait_id)
SELECT j.id, t.id FROM job_postings j JOIN traits t ON t.normalized IN ('go', 'postgresql', 'docker')
WHERE j.title = 'Senior Go Backend Engineer' ON CONFLICT DO NOTHING;
INSERT INTO job_additional_skills (job_posting_id, trait_id)
SELECT j.id, t.id FROM job_postings j JOIN traits t ON t.normalized = 'kubernetes'
WHERE j.title = 'Senior Go Backend Engineer' ON CONFLICT DO NOTHING;
INSERT INTO job_posting_labels (job_posting_id, trait_id)
SELECT j.id, t.id FROM job_postings j JOIN traits t ON t.normalized IN ('react', 'typescript')
WHERE j.title = 'Full-stack Product Engineer' ON CONFLICT DO NOTHING;
INSERT INTO job_required_skills (job_posting_id, trait_id)
SELECT j.id, t.id FROM job_postings j JOIN traits t ON t.normalized IN ('go', 'react', 'typescript')
WHERE j.title = 'Full-stack Product Engineer' ON CONFLICT DO NOTHING;
INSERT INTO job_additional_skills (job_posting_id, trait_id)
SELECT j.id, t.id FROM job_postings j JOIN traits t ON t.normalized = 'docker'
WHERE j.title = 'Full-stack Product Engineer' ON CONFLICT DO NOTHING;
INSERT INTO participants (first_name, last_name, birthday, email, contact_info, cv, cv_filename)
VALUES
('Ada', 'Lovelace', '1990-12-10', 'ada@example.com', '+32 470 00 00 01',
convert_to('Senior backend engineer with Go, PostgreSQL and Docker experience.', 'UTF8'), 'ada-cv.txt'),
('Grace', 'Hopper', '1988-12-09', 'grace@example.com', '+32 470 00 00 02',
convert_to('Full-stack developer working with Go, React and TypeScript.', 'UTF8'), 'grace-cv.txt')
ON CONFLICT (email) DO NOTHING;
INSERT INTO participant_traits (participant_id, trait_id)
SELECT p.id, t.id FROM participants p JOIN traits t ON t.normalized IN ('go', 'postgresql', 'docker')
WHERE p.email = 'ada@example.com' ON CONFLICT DO NOTHING;
INSERT INTO participant_traits (participant_id, trait_id)
SELECT p.id, t.id FROM participants p JOIN traits t ON t.normalized IN ('go', 'react', 'typescript')
WHERE p.email = 'grace@example.com' ON CONFLICT DO NOTHING;

View file

@ -0,0 +1,38 @@
package seed
import (
"context"
"database/sql"
"embed"
"fmt"
)
//go:embed *.sql
var files embed.FS
func Apply(ctx context.Context, db *sql.DB, environment string) error {
if _, err := apply(ctx, db, "common.sql"); err != nil {
return err
}
switch environment {
case "", "production":
return nil
case "development", "test":
_, err := apply(ctx, db, environment+".sql")
return err
default:
return fmt.Errorf("unsupported APP_ENV %q", environment)
}
}
func apply(ctx context.Context, db *sql.DB, filename string) (sql.Result, error) {
content, err := files.ReadFile(filename)
if err != nil {
return nil, fmt.Errorf("read seed %s: %w", filename, err)
}
result, err := db.ExecContext(ctx, string(content))
if err != nil {
return nil, fmt.Errorf("apply seed %s: %w", filename, err)
}
return result, nil
}

View file

@ -0,0 +1,40 @@
INSERT INTO users (email, password_hash, role)
VALUES ('integration@example.com', crypt('integration-password', gen_salt('bf')), 'interviewer')
ON CONFLICT (email) DO NOTHING;
INSERT INTO job_postings (title, description, seniority, position, status, duration_minutes)
SELECT 'Integration Backend Engineer', 'Deterministic job fixture for API and UI integration tests.',
'Senior', 'Backend Engineer', 'published', 30
WHERE NOT EXISTS (SELECT 1 FROM job_postings WHERE title = 'Integration Backend Engineer');
INSERT INTO questions (text, type, reference_answer)
SELECT 'Explain graceful shutdown.', 'open',
'Stop new work, cancel dependencies, drain requests, and close resources.'
WHERE NOT EXISTS (SELECT 1 FROM questions WHERE text = 'Explain graceful shutdown.');
INSERT INTO questions (text, type, reference_answer, code_snippet)
SELECT 'Review the error handling.', 'code_review', 'Return or log the error instead of discarding it.',
E'func save() error {\n persist()\n return nil\n}'
WHERE NOT EXISTS (SELECT 1 FROM questions WHERE text = 'Review the error handling.');
INSERT INTO job_posting_questions (job_posting_id, question_id)
SELECT j.id, q.id FROM job_postings j
JOIN questions q ON q.text IN ('Explain graceful shutdown.', 'Review the error handling.')
WHERE j.title = 'Integration Backend Engineer'
ON CONFLICT DO NOTHING;
INSERT INTO job_posting_labels (job_posting_id, trait_id)
SELECT j.id, t.id FROM job_postings j JOIN traits t ON t.normalized = 'backend'
WHERE j.title = 'Integration Backend Engineer' ON CONFLICT DO NOTHING;
INSERT INTO job_required_skills (job_posting_id, trait_id)
SELECT j.id, t.id FROM job_postings j JOIN traits t ON t.normalized IN ('go', 'postgresql')
WHERE j.title = 'Integration Backend Engineer' ON CONFLICT DO NOTHING;
INSERT INTO participants (first_name, last_name, birthday, email, contact_info, cv, cv_filename)
VALUES ('Integration', 'Candidate', '1992-04-15', 'candidate.integration@example.com',
'+32 470 00 00 99', convert_to('Backend engineer using Go and PostgreSQL.', 'UTF8'), 'integration-cv.txt')
ON CONFLICT (email) DO NOTHING;
INSERT INTO participant_traits (participant_id, trait_id)
SELECT p.id, t.id FROM participants p JOIN traits t ON t.normalized IN ('backend', 'go', 'postgresql')
WHERE p.email = 'candidate.integration@example.com' ON CONFLICT DO NOTHING;

View file

@ -0,0 +1,272 @@
//go:build integration
package integration
import (
"bytes"
"context"
"database/sql"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"runtime"
"testing"
"time"
"github.com/pressly/goose/v3"
"github.com/testcontainers/testcontainers-go"
tcpostgres "github.com/testcontainers/testcontainers-go/modules/postgres"
"github.com/testcontainers/testcontainers-go/wait"
"gorm.io/driver/postgres"
"gorm.io/gorm"
"github.com/danyel/go-guess/backend/internal/database/repository"
"github.com/danyel/go-guess/backend/internal/database/seed"
"github.com/danyel/go-guess/backend/internal/security"
"github.com/danyel/go-guess/backend/internal/service"
"github.com/danyel/go-guess/backend/internal/web/handler"
webmodel "github.com/danyel/go-guess/backend/internal/web/model"
"github.com/danyel/go-guess/backend/internal/web/router"
)
var testServer *httptest.Server
func TestMain(m *testing.M) {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
defer cancel()
container, err := tcpostgres.Run(
ctx,
"postgres:18-alpine",
tcpostgres.WithDatabase("go_guess_test"),
tcpostgres.WithUsername("go_guess"),
tcpostgres.WithPassword("go_guess"),
testcontainers.WithWaitStrategy(
wait.ForLog("database system is ready to accept connections").
WithOccurrence(2).
WithStartupTimeout(60*time.Second),
),
)
if err != nil {
fmt.Fprintln(os.Stderr, "start PostgreSQL test container:", err)
os.Exit(1)
}
databaseURL, err := container.ConnectionString(ctx, "sslmode=disable")
if err != nil {
fmt.Fprintln(os.Stderr, "get PostgreSQL connection string:", err)
os.Exit(1)
}
sqlDB, err := sql.Open("pgx", databaseURL)
if err != nil {
fmt.Fprintln(os.Stderr, "open PostgreSQL:", err)
_ = container.Terminate(context.Background())
os.Exit(1)
}
if err := goose.SetDialect("postgres"); err != nil {
fmt.Fprintln(os.Stderr, "set Goose dialect:", err)
os.Exit(1)
}
_, filename, _, _ := runtime.Caller(0)
migrations := filepath.Join(filepath.Dir(filename), "..", "..", "migrations")
if err := goose.Up(sqlDB, migrations); err != nil {
fmt.Fprintln(os.Stderr, "apply migrations:", err)
os.Exit(1)
}
if err := seed.Apply(ctx, sqlDB, "test"); err != nil {
fmt.Fprintln(os.Stderr, "apply test seed:", err)
os.Exit(1)
}
if err := seed.Apply(ctx, sqlDB, "test"); err != nil {
fmt.Fprintln(os.Stderr, "reapply idempotent test seed:", err)
os.Exit(1)
}
gormDB, err := gorm.Open(postgres.Open(databaseURL), &gorm.Config{})
if err != nil {
fmt.Fprintln(os.Stderr, "open GORM connection:", err)
os.Exit(1)
}
store := repository.New(gormDB)
tokens := security.NewTokenManager("integration-test-secret-at-least-32-bytes", time.Hour)
invitations := service.NewInvitationService(store, "http://example.test")
testServer = httptest.NewServer(router.New(
handler.New(
service.NewAuthService(store, tokens),
service.NewJobService(store),
service.NewQuestionService(store),
service.NewParticipantService(store),
invitations,
10,
"http://example.test",
),
tokens,
"http://example.test",
))
code := m.Run()
testServer.Close()
_ = sqlDB.Close()
cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), 30*time.Second)
_ = container.Terminate(cleanupCtx)
cleanupCancel()
os.Exit(code)
}
func TestCompleteInterviewWorkflow(t *testing.T) {
var login webmodel.LoginResponse
requestJSON(t, http.MethodPost, "/api/auth/login", "", map[string]any{
"email": "integration@example.com", "password": "integration-password",
}, http.StatusOK, &login)
if login.Token == "" {
t.Fatal("login did not return a token")
}
var participants []webmodel.ParticipantResponse
requestJSON(t, http.MethodGet, "/api/participants", login.Token, nil, http.StatusOK, &participants)
var participantID uint
for _, participant := range participants {
if participant.Email == "candidate.integration@example.com" {
participantID = participant.ID
}
}
if participantID == 0 {
t.Fatal("test participant was not seeded")
}
var question webmodel.QuestionResponse
requestJSON(t, http.MethodPost, "/api/questions", login.Token, map[string]any{
"text": "Review this error handling.", "type": "code_review",
"codeSnippet": "func run() error {\n execute()\n return nil\n}",
"referenceAnswer": "Return the execute error.", "options": []string{},
}, http.StatusCreated, &question)
requestJSON(t, http.MethodPut, fmt.Sprintf("/api/questions/%d", question.ID), login.Token, map[string]any{
"text": "Review this ignored error.", "type": "code_review",
"codeSnippet": "func run() error {\n execute()\n return nil\n}",
"referenceAnswer": "Propagate the execute error.", "options": []string{},
}, http.StatusOK, &question)
var jobs []webmodel.JobResponse
requestJSON(t, http.MethodGet, "/api/jobs", login.Token, nil, http.StatusOK, &jobs)
var jobID uint
for _, job := range jobs {
if job.Title == "Integration Backend Engineer" {
jobID = job.ID
}
}
if jobID == 0 {
t.Fatal("test job was not seeded")
}
requestJSON(t, http.MethodPost,
fmt.Sprintf("/api/jobs/%d/questions/%d", jobID, question.ID),
login.Token, nil, http.StatusNoContent, nil)
var matches []webmodel.CandidateResponse
requestJSON(t, http.MethodGet, fmt.Sprintf("/api/jobs/%d/candidates", jobID),
login.Token, nil, http.StatusOK, &matches)
if len(matches) == 0 || matches[0].Participant.ID != participantID {
t.Fatalf("seeded participant was not a candidate: %#v", matches)
}
var invitation webmodel.InvitationResponse
requestJSON(t, http.MethodPost, fmt.Sprintf("/api/jobs/%d/invitations", jobID),
login.Token, map[string]any{"participantId": participantID}, http.StatusCreated, &invitation)
if invitation.Token == "" || invitation.ParticipantURL != "http://example.test/participant/"+invitation.Token {
t.Fatalf("unexpected invitation: %#v", invitation)
}
var welcome webmodel.InterviewResponse
publicBody := requestJSON(t, http.MethodGet, "/api/interviews/"+invitation.Token,
"", nil, http.StatusOK, &welcome)
if bytes.Contains(publicBody, []byte("referenceAnswer")) || welcome.Invitation.Status != "pending" {
t.Fatalf("invalid public welcome response: %s", publicBody)
}
var started webmodel.InterviewResponse
requestJSON(t, http.MethodPost, "/api/interviews/"+invitation.Token+"/accept",
"", nil, http.StatusOK, &started)
if started.Invitation.Status != "accepted" || started.Invitation.AcceptedAt == nil {
t.Fatalf("interview was not accepted: %#v", started.Invitation)
}
answer := "The execute error must be returned to the caller."
requestJSON(t, http.MethodPut,
fmt.Sprintf("/api/interviews/%s/answers/%d", invitation.Token, question.ID),
"", map[string]any{"answer": answer}, http.StatusNoContent, nil)
requestJSON(t, http.MethodPost, "/api/interviews/"+invitation.Token+"/finish",
"", nil, http.StatusOK, &started)
if started.Invitation.Status != "completed" {
t.Fatalf("interview was not completed: %#v", started.Invitation)
}
var review webmodel.InvitationReviewResponse
requestJSON(t, http.MethodGet,
fmt.Sprintf("/api/jobs/%d/invitations/%d", jobID, invitation.ID),
login.Token, nil, http.StatusOK, &review)
if review.Answers[question.ID] != answer {
t.Fatalf("saved answer missing from review: %#v", review.Answers)
}
found := false
for _, item := range review.Job.Questions {
if item.ID == question.ID {
found = item.ReferenceAnswer == "Propagate the execute error." && item.CodeSnippet != ""
}
}
if !found {
t.Fatalf("review did not include interviewer question context: %#v", review.Job.Questions)
}
}
func requestJSON(
t *testing.T,
method string,
path string,
token string,
body any,
wantStatus int,
target any,
) []byte {
t.Helper()
var requestBody io.Reader
if body != nil {
encoded, err := json.Marshal(body)
if err != nil {
t.Fatal(err)
}
requestBody = bytes.NewReader(encoded)
}
request, err := http.NewRequest(method, testServer.URL+path, requestBody)
if err != nil {
t.Fatal(err)
}
if body != nil {
request.Header.Set("Content-Type", "application/json")
}
if token != "" {
request.Header.Set("Authorization", "Bearer "+token)
}
response, err := http.DefaultClient.Do(request)
if err != nil {
t.Fatal(err)
}
defer response.Body.Close()
content, err := io.ReadAll(response.Body)
if err != nil {
t.Fatal(err)
}
if response.StatusCode != wantStatus {
t.Fatalf("%s %s: expected %d, got %d: %s", method, path, wantStatus, response.StatusCode, content)
}
if target != nil {
if err := json.Unmarshal(content, target); err != nil {
t.Fatalf("decode %s %s: %v: %s", method, path, err, content)
}
}
return content
}