Files
lincodex/backend/integration_test/questionnaire_http_test.go
T

697 lines
33 KiB
Go

//go:build integration
package integration_test
import (
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"net/http"
"net/http/httptest"
"slices"
"strings"
"sync"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
httpadapter "lincodex/backend/internal/adapter/primary/http"
"lincodex/backend/internal/adapter/primary/http/problem"
v1 "lincodex/backend/internal/adapter/primary/http/v1"
"lincodex/backend/internal/adapter/secondary/argon2id"
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/adapter/secondary/prometheus"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/usecase/assessment"
"lincodex/backend/internal/usecase/health"
"lincodex/backend/internal/usecase/identity"
"lincodex/backend/internal/usecase/policy"
profileusecase "lincodex/backend/internal/usecase/profile"
questionnaireusecase "lincodex/backend/internal/usecase/questionnaire"
)
const candidateQuestionnaireHTTPTimeout = 6 * time.Minute
func TestCandidateQuestionnaireOverHTTP(t *testing.T) {
env := bootstrap(t, postgresService, redisService)
ctx, cancel := context.WithTimeout(t.Context(), candidateQuestionnaireHTTPTimeout)
defer cancel()
databaseURL := env.createIsolatedDatabase(ctx, t)
applyMigrations(ctx, t, databaseURL)
isolatedEnv := *env
isolatedEnv.Config.DatabaseURL = databaseURL
harness := newCandidateQuestionnaireHTTPHarness(ctx, t, &isolatedEnv)
initialCatalog := questionnaireCatalogHTTP(t, harness)
assertCatalogAvailability(t, initialCatalog, "backend", "in_development", nil, nil)
bankFixture := seedQuestionnaireCatalogBank(ctx, t, harness.pool)
passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass)
if err != nil {
t.Fatalf("HashNewPassword() error = %v", err)
}
now := harness.clock.Now()
candidate := createSessionHTTPUser(ctx, t, harness, "questionnaire-owner@example.test", passwordHash, true)
otherCandidate := createSessionHTTPUser(ctx, t, harness, "questionnaire-other@example.test", passwordHash, true)
employer := createQuestionnaireHTTPEmployer(ctx, t, harness, "questionnaire-employer@example.test", passwordHash, now)
if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step = 'candidate_questionnaire' WHERE id = $1", candidate.ID); err != nil {
t.Fatalf("set candidate questionnaire onboarding step: %v", err)
}
candidateLogin := loginCandidateQuestionnaireHTTP(t, harness, candidate.Email.Address(), "192.0.2.201:1234")
otherLogin := loginCandidateQuestionnaireHTTP(t, harness, otherCandidate.Email.Address(), "192.0.2.202:1234")
employerLogin := loginCandidateQuestionnaireHTTP(t, harness, employer.Email.Address(), "192.0.2.203:1234")
publicCatalogResponse := harness.request(t, http.MethodGet, "/api/v1/specializations", "", "", "", "", "192.0.2.204:1234")
if publicCatalogResponse.Code != http.StatusOK {
t.Fatalf("public catalog without a session = %d %s, want 200", publicCatalogResponse.Code, publicCatalogResponse.Body.String())
}
currentCatalog := decodeSpecializationCatalog(t, publicCatalogResponse.Body.Bytes())
assertCatalogAvailability(t, currentCatalog, "backend", "available", []string{"junior"}, []string{"go"})
guestRead := harness.request(t, http.MethodGet, "/api/v1/me/questionnaire", "", sessionHTTPTestOrigin, "", "", "192.0.2.205:1234")
requireSessionProblem(t, guestRead, http.StatusUnauthorized, "unauthenticated")
initial := questionnaireHTTPRequest(t, harness, http.MethodGet, "", candidateLogin.cookie, "", "192.0.2.206:1234")
if initial.Code != http.StatusOK || initial.Header().Get("Cache-Control") != "no-store" {
t.Fatalf("empty questionnaire = %d Cache-Control=%q: %s", initial.Code, initial.Header().Get("Cache-Control"), initial.Body.String())
}
var empty questionnaireHTTPResponse
if err := json.Unmarshal(initial.Body.Bytes(), &empty); err != nil {
t.Fatalf("decode empty questionnaire: %v", err)
}
if empty.Version != 0 || len(empty.Specializations) != 0 || string(empty.WorkContext) != "null" || string(empty.UpdatedAt) != "null" {
t.Fatalf("empty questionnaire = %+v, want version zero with null context and time", empty)
}
firstSave := questionnaireHTTPRequest(t, harness, http.MethodPut,
questionnaireUpdateBody(t, 0, "backend", "junior", []string{"go"}, []string{"PostgreSQL"}, 18, 6),
candidateLogin.cookie, candidateLogin.csrf, "192.0.2.207:1234")
if firstSave.Code != http.StatusOK || firstSave.Header().Get("Cache-Control") != "no-store" {
t.Fatalf("save questionnaire = %d Cache-Control=%q: %s", firstSave.Code, firstSave.Header().Get("Cache-Control"), firstSave.Body.String())
}
var saved questionnaireHTTPResponse
if err := json.Unmarshal(firstSave.Body.Bytes(), &saved); err != nil {
t.Fatalf("decode saved questionnaire: %v", err)
}
if saved.Version != 1 || len(saved.Specializations) != 1 || saved.Specializations[0].SelfAssessedGrade != "junior" ||
len(saved.Specializations[0].TaskLanguages) != 1 || saved.Specializations[0].TaskLanguages[0] != "go" ||
saved.Specializations[0].Experience == nil || saved.Specializations[0].Experience.CommercialMonths != 18 ||
saved.Specializations[0].Experience.AcademicMonths != 6 || len(saved.Specializations[0].Stack) != 1 || saved.Specializations[0].Stack[0] != "PostgreSQL" {
t.Fatalf("saved questionnaire = %+v, want backend/junior/go version 1", saved)
}
assertQuestionnaireRows(t, ctx, harness, candidate.ID, 1, "backend", "junior", "go", "PostgreSQL", 18, 6)
assertQuestionnaireOnboarding(t, ctx, harness, candidate.ID, "candidate_assessment")
assertQuestionnaireExperienceConstraint(t, ctx, harness, otherCandidate.ID)
staleWrite := questionnaireHTTPRequest(t, harness, http.MethodPut,
questionnaireUpdateBody(t, 0, "backend", "junior", []string{"go"}, []string{"gRPC"}, 18, 6),
candidateLogin.cookie, candidateLogin.csrf, "192.0.2.208:1234")
requireSessionProblem(t, staleWrite, http.StatusPreconditionFailed, "version_conflict")
assertQuestionnaireRows(t, ctx, harness, candidate.ID, 1, "backend", "junior", "go", "PostgreSQL", 18, 6)
noOp := questionnaireHTTPRequest(t, harness, http.MethodPut,
questionnaireUpdateBody(t, 0, "backend", "junior", []string{"go"}, []string{"PostgreSQL"}, 18, 6),
candidateLogin.cookie, candidateLogin.csrf, "192.0.2.209:1234")
if noOp.Code != http.StatusOK {
t.Fatalf("stale identical questionnaire retry = %d %s, want 200", noOp.Code, noOp.Body.String())
}
var noOpResponse questionnaireHTTPResponse
if err := json.Unmarshal(noOp.Body.Bytes(), &noOpResponse); err != nil || noOpResponse.Version != 1 {
t.Fatalf("stale identical retry response = %+v, decode error %v; want version 1", noOpResponse, err)
}
badLanguage := questionnaireHTTPRequest(t, harness, http.MethodPut,
questionnaireUpdateBody(t, 1, "backend", "junior", []string{"python"}, []string{"PostgreSQL"}, 18, 6),
candidateLogin.cookie, candidateLogin.csrf, "192.0.2.210:1234")
if badLanguage.Code != http.StatusBadRequest || !strings.Contains(badLanguage.Body.String(), "/specializations/0/task_languages/0") {
t.Fatalf("unoffered task language = %d %s, want field validation", badLanguage.Code, badLanguage.Body.String())
}
assertQuestionnaireRows(t, ctx, harness, candidate.ID, 1, "backend", "junior", "go", "PostgreSQL", 18, 6)
forbiddenFieldBody := questionnaireUpdateWithUnknownField(t,
questionnaireUpdateBody(t, 1, "backend", "junior", []string{"go"}, []string{"PostgreSQL"}, 18, 6),
"confirmed_grade", "senior")
forbiddenField := questionnaireHTTPRequest(t, harness, http.MethodPut, forbiddenFieldBody,
candidateLogin.cookie, candidateLogin.csrf, "192.0.2.211:1234")
if forbiddenField.Code != http.StatusBadRequest {
t.Fatalf("questionnaire update with confirmed_grade = %d %s, want 400", forbiddenField.Code, forbiddenField.Body.String())
}
assertQuestionnaireRows(t, ctx, harness, candidate.ID, 1, "backend", "junior", "go", "PostgreSQL", 18, 6)
otherRead := questionnaireHTTPRequest(t, harness, http.MethodGet, "", otherLogin.cookie, "", "192.0.2.212:1234")
var other questionnaireHTTPResponse
if otherRead.Code != http.StatusOK || json.Unmarshal(otherRead.Body.Bytes(), &other) != nil || other.Version != 0 || len(other.Specializations) != 0 {
t.Fatalf("other candidate questionnaire = %d %s, want private version-0 questionnaire", otherRead.Code, otherRead.Body.String())
}
otherDevelopmentSave := questionnaireHTTPRequest(t, harness, http.MethodPut,
questionnaireUpdateBody(t, 0, "ds_ml", "junior", nil, []string{"Python"}, 0, 0),
otherLogin.cookie, otherLogin.csrf, "192.0.2.213:1234")
if otherDevelopmentSave.Code != http.StatusOK {
t.Fatalf("save a specialization with no available bank and no task language = %d %s, want 200", otherDevelopmentSave.Code, otherDevelopmentSave.Body.String())
}
employerRead := questionnaireHTTPRequest(t, harness, http.MethodGet, "", employerLogin.cookie, "", "192.0.2.214:1234")
requireSessionProblem(t, employerRead, http.StatusForbidden, "forbidden")
// A self-assessed Senior grade remains a private claim. It cannot create a
// confirmed category or a profile claim by itself.
seniorSave := questionnaireHTTPRequest(t, harness, http.MethodPut,
questionnaireUpdateBody(t, 1, "backend", "senior", []string{"go"}, []string{"PostgreSQL"}, 18, 6),
candidateLogin.cookie, candidateLogin.csrf, "192.0.2.215:1234")
if seniorSave.Code != http.StatusOK {
t.Fatalf("save Senior self-assessment = %d %s, want 200", seniorSave.Code, seniorSave.Body.String())
}
var senior questionnaireHTTPResponse
if err := json.Unmarshal(seniorSave.Body.Bytes(), &senior); err != nil || senior.Version != 2 || senior.Specializations[0].SelfAssessedGrade != "senior" {
t.Fatalf("Senior questionnaire = %+v, decode error %v", senior, err)
}
profileRead := harness.request(t, http.MethodGet, "/api/v1/me/profile", "", sessionHTTPTestOrigin,
candidateLogin.cookie, "", "192.0.2.216:1234")
var profile struct {
Version int64 `json:"version"`
ConfirmedCategories []json.RawMessage `json:"confirmed_categories"`
}
if profileRead.Code != http.StatusOK || json.Unmarshal(profileRead.Body.Bytes(), &profile) != nil ||
profile.Version != 0 || len(profile.ConfirmedCategories) != 0 {
t.Fatalf("profile after a Senior self-assessment = %d %s, want no confirmed category", profileRead.Code, profileRead.Body.String())
}
// A later onboarding step never moves backwards on an identical retry.
if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step = 'completed' WHERE id = $1", candidate.ID); err != nil {
t.Fatalf("move candidate to completed onboarding: %v", err)
}
if response := questionnaireHTTPRequest(t, harness, http.MethodPut,
questionnaireUpdateBody(t, 1, "backend", "senior", []string{"go"}, []string{"PostgreSQL"}, 18, 6),
candidateLogin.cookie, candidateLogin.csrf, "192.0.2.217:1234"); response.Code != http.StatusOK {
t.Fatalf("questionnaire retry after onboarding completion = %d %s", response.Code, response.Body.String())
}
assertQuestionnaireOnboarding(t, ctx, harness, candidate.ID, "completed")
// Two different changes from the same version race; exactly one wins and
// the stale writer leaves the winner's whole body intact.
firstConcurrent := questionnaireUpdateBody(t, 2, "backend", "senior", []string{"go"}, []string{"gRPC"}, 18, 6)
secondConcurrent := questionnaireUpdateBody(t, 2, "backend", "senior", []string{"go"}, []string{"Redis"}, 18, 6)
concurrentResponses := make([]*httptest.ResponseRecorder, 2)
start := make(chan struct{})
var wait sync.WaitGroup
for index, body := range []string{firstConcurrent, secondConcurrent} {
wait.Add(1)
go func(index int, body string) {
defer wait.Done()
<-start
concurrentResponses[index] = questionnaireHTTPRequest(t, harness, http.MethodPut, body,
candidateLogin.cookie, candidateLogin.csrf, fmt.Sprintf("192.0.2.%d:1234", 218+index))
}(index, body)
}
close(start)
wait.Wait()
accepted, conflicted := 0, 0
for _, response := range concurrentResponses {
switch response.Code {
case http.StatusOK:
accepted++
case http.StatusPreconditionFailed:
conflicted++
default:
t.Fatalf("concurrent questionnaire save = %d %s, want 200 or 412", response.Code, response.Body.String())
}
}
if accepted != 1 || conflicted != 1 {
t.Fatalf("concurrent questionnaire results = %d accepted, %d conflicted; want one each", accepted, conflicted)
}
var storedVersion int64
var storedStack string
if err := harness.pool.QueryRow(ctx, `
SELECT questionnaire.version, specialization.stack[1]
FROM candidate_questionnaires AS questionnaire
JOIN candidate_questionnaire_specializations AS specialization USING (user_id)
WHERE questionnaire.user_id = $1`, candidate.ID).Scan(&storedVersion, &storedStack); err != nil {
t.Fatalf("read concurrent questionnaire winner: %v", err)
}
if storedVersion != 3 || (storedStack != "gRPC" && storedStack != "Redis") {
t.Fatalf("concurrent stored questionnaire = version %d stack %q, want version 3 and one complete winner", storedVersion, storedStack)
}
// Simultaneous identical saves return the one committed winner to both
// callers without creating a second version or replacing its answer rows.
identicalBody := questionnaireUpdateBody(t, 3, "backend", "senior", []string{"go"}, []string{"Fargate"}, 18, 6)
identicalResponses := make([]*httptest.ResponseRecorder, 2)
start = make(chan struct{})
for index := range identicalResponses {
wait.Add(1)
go func(index int) {
defer wait.Done()
<-start
identicalResponses[index] = questionnaireHTTPRequest(t, harness, http.MethodPut, identicalBody,
candidateLogin.cookie, candidateLogin.csrf, fmt.Sprintf("192.0.2.%d:1234", 223+index))
}(index)
}
close(start)
wait.Wait()
for _, response := range identicalResponses {
if response.Code != http.StatusOK {
t.Fatalf("concurrent identical questionnaire save = %d %s, want 200", response.Code, response.Body.String())
}
var result questionnaireHTTPResponse
if err := json.Unmarshal(response.Body.Bytes(), &result); err != nil || result.Version != 4 ||
len(result.Specializations) != 1 || result.Specializations[0].Stack[0] != "Fargate" {
t.Fatalf("concurrent identical save response = %+v, decode error %v; want same version-4 winner", result, err)
}
}
if err := harness.pool.QueryRow(ctx, `
SELECT questionnaire.version, specialization.stack[1]
FROM candidate_questionnaires AS questionnaire
JOIN candidate_questionnaire_specializations AS specialization USING (user_id)
WHERE questionnaire.user_id = $1`, candidate.ID).Scan(&storedVersion, &storedStack); err != nil {
t.Fatalf("read identical questionnaire winner: %v", err)
}
if storedVersion != 4 || storedStack != "Fargate" {
t.Fatalf("identical concurrent stored questionnaire = version %d stack %q, want version 4 and Fargate", storedVersion, storedStack)
}
secondLogin := loginCandidateQuestionnaireHTTP(t, harness, candidate.Email.Address(), "192.0.2.220:1234")
harness.pool.Close()
harness = newCandidateQuestionnaireHTTPHarness(ctx, t, &isolatedEnv)
bankFixture.bank = assessment.NewBank(postgresadapter.NewTransactor(harness.pool))
bankFixture.publisher = policy.NewPublisher(postgresadapter.NewPolicyStore(harness.pool).Policies(), time.Now)
restartedRead := questionnaireHTTPRequest(t, harness, http.MethodGet, "", secondLogin.cookie, "", "192.0.2.221:1234")
var restarted questionnaireHTTPResponse
if restartedRead.Code != http.StatusOK || json.Unmarshal(restartedRead.Body.Bytes(), &restarted) != nil ||
restarted.Version != 4 || len(restarted.Specializations) != 1 || restarted.Specializations[0].SelfAssessedGrade != "senior" ||
restarted.Specializations[0].Stack[0] != storedStack {
t.Fatalf("questionnaire after re-login and handler restart = %d %s, want version 4 and persisted winner", restartedRead.Code, restartedRead.Body.String())
}
assertQuestionnaireRows(t, ctx, harness, candidate.ID, 4, "backend", "senior", "go", storedStack, 18, 6)
// A new policy version makes the old opening ineligible for the public
// catalog. Reopening under that policy restores availability only while the
// pinned published-family manifest still meets its recorded threshold.
policyVersion, err := bankFixture.publisher.Publish(ctx, policy.PublishInput{
Key: domain.ProductPolicyKey, Kind: domain.PolicyKindCalibrated,
Author: policyTestAuthor, Policy: integrationPolicy(11),
})
if err != nil {
t.Fatalf("Publish(replacement catalog policy) error = %v", err)
}
assertCatalogAvailability(t, questionnaireCatalogHTTP(t, harness), "backend", "in_development", nil, nil)
if _, err := bankFixture.bank.OpenCategory(ctx, assessment.OpenCategoryInput{
Category: assessmentCategory, GradingPolicyID: policyVersion.ID(), OpenedBy: fixtureOpener,
CatalogMetadata: &bankFixture.metadata,
}); err != nil {
t.Fatalf("OpenCategory(replacement catalog policy) error = %v", err)
}
assertCatalogAvailability(t, questionnaireCatalogHTTP(t, harness), "backend", "available", []string{"junior"}, []string{"go"})
if _, err := bankFixture.bank.RetireFamily(ctx, bankFixture.firstFamilyKey, 1, fixturePublisher); err != nil {
t.Fatalf("RetireFamily(under-covered catalog) error = %v", err)
}
assertCatalogAvailability(t, questionnaireCatalogHTTP(t, harness), "backend", "in_development", nil, nil)
questionnaireAfterBankChange := questionnaireHTTPRequest(t, harness, http.MethodGet, "", secondLogin.cookie, "", "192.0.2.222:1234")
var preserved questionnaireHTTPResponse
if questionnaireAfterBankChange.Code != http.StatusOK || json.Unmarshal(questionnaireAfterBankChange.Body.Bytes(), &preserved) != nil ||
preserved.Version != 4 || len(preserved.Specializations) != 1 || preserved.Specializations[0].Stack[0] != storedStack {
t.Fatalf("questionnaire after bank coverage change = %d %s, want persisted version 4", questionnaireAfterBankChange.Code, questionnaireAfterBankChange.Body.String())
}
for _, privateValue := range []string{
candidate.Email.Address(), otherCandidate.Email.Address(), employer.Email.Address(),
"PostgreSQL", "gRPC", "Redis",
} {
if strings.Contains(harness.logs.String(), privateValue) {
t.Fatalf("questionnaire HTTP logs contain private value %q", privateValue)
}
}
}
type questionnaireHTTPResponse struct {
Version int64 `json:"version"`
Specializations []questionnaireHTTPSpecialization `json:"specializations"`
WorkContext json.RawMessage `json:"work_context"`
UpdatedAt json.RawMessage `json:"updated_at"`
}
type questionnaireHTTPSpecialization struct {
Specialization string `json:"specialization"`
SelfAssessedGrade string `json:"self_assessed_grade"`
TaskLanguages []string `json:"task_languages"`
Stack []string `json:"stack"`
Experience *struct {
CommercialMonths int32 `json:"commercial_months"`
AcademicMonths int32 `json:"academic_months"`
} `json:"experience"`
}
type questionnaireCatalogResponse struct {
Directions []struct {
Code string `json:"code"`
Specializations []struct {
Code string `json:"code"`
TestAvailability struct {
Status string `json:"status"`
Grades []string `json:"grades"`
TaskLanguages []string `json:"task_languages"`
Note *string `json:"note"`
} `json:"test_availability"`
} `json:"specializations"`
} `json:"directions"`
}
type questionnaireLogin struct {
cookie string
csrf string
}
type questionnaireBankFixture struct {
bank *assessment.Bank
publisher *policy.Publisher
metadata domain.AssessmentCategoryCatalogMetadata
firstFamilyKey domain.AssessmentFamilyKey
}
func seedQuestionnaireCatalogBank(ctx context.Context, t *testing.T, pool *pgxpool.Pool) questionnaireBankFixture {
t.Helper()
transactor := postgresadapter.NewTransactor(pool)
bank := assessment.NewBank(transactor)
store := postgresadapter.NewAssessmentBankStore(pool)
publisher := policy.NewPublisher(postgresadapter.NewPolicyStore(pool).Policies(), time.Now)
fixture := assessmentFixture{
ctx: ctx, pool: pool, store: store, transactor: transactor, bank: bank,
publisher: publisher, demoBundle: loadDemoBundleFile(t),
}
if _, err := bank.ImportBundle(ctx, fixture.demoBundle); err != nil {
t.Fatalf("ImportBundle(unreviewed base bundle) error = %v", err)
}
unreviewedAvailability, err := bank.SpecializationAvailability(ctx)
if err != nil || len(unreviewedAvailability) != 0 {
t.Fatalf("catalog availability after importing an unreviewed draft = %v, %v; want no rows", unreviewedAvailability, err)
}
policyVersion, err := publisher.Publish(ctx, policy.PublishInput{
Key: domain.ProductPolicyKey, Kind: domain.PolicyKindCalibrated,
Author: policyTestAuthor, Policy: integrationPolicy(11),
})
if err != nil {
t.Fatalf("Publish(questionnaire grading policy) error = %v", err)
}
required, err := domain.RequiredPublishedAssessmentFamilies(policyVersion.Policy())
if err != nil {
t.Fatalf("RequiredPublishedAssessmentFamilies() error = %v", err)
}
reviewed := fixture.reviewedBundle(int(required))
if _, err := bank.ImportBundle(ctx, reviewed); err != nil {
t.Fatalf("ImportBundle(reviewed questionnaire fixture) error = %v", err)
}
for _, family := range reviewed.Families {
if _, err := bank.PublishFamily(ctx, domain.AssessmentFamilyKey(family.Key), family.Version, fixturePublisher); err != nil {
t.Fatalf("PublishFamily(%s) error = %v", family.Key, err)
}
}
metadata, err := domain.NewAssessmentCategoryCatalogMetadata(
domain.SpecializationBackend, domain.GradeJunior, []domain.TaskLanguageCode{domain.TaskLanguageGo},
)
if err != nil {
t.Fatalf("NewAssessmentCategoryCatalogMetadata() error = %v", err)
}
if _, err := bank.OpenCategory(ctx, assessment.OpenCategoryInput{
Category: assessmentCategory, GradingPolicyID: policyVersion.ID(), OpenedBy: fixtureOpener,
CatalogMetadata: &metadata,
}); err != nil {
t.Fatalf("OpenCategory(reviewed questionnaire fixture) error = %v", err)
}
return questionnaireBankFixture{
bank: bank, publisher: publisher, metadata: metadata,
firstFamilyKey: domain.AssessmentFamilyKey(reviewed.Families[0].Key),
}
}
func newCandidateQuestionnaireHTTPHarness(ctx context.Context, t *testing.T, env *testEnvironment) *sessionHTTPHarness {
t.Helper()
pool := env.newPool(ctx, t)
store := postgresadapter.NewIdentityStore(pool)
hasher, err := argon2id.NewHasher(1)
if err != nil {
t.Fatalf("NewHasher() error = %v", err)
}
credentials := identity.NewCredentials(hasher)
keyring, err := identity.NewKeyring([]byte(env.Config.IdentityKeySecret))
if err != nil {
t.Fatalf("NewKeyring() error = %v", err)
}
clock := &testClock{now: time.Now().UTC().Truncate(time.Microsecond)}
transactor := postgresadapter.NewTransactor(pool)
sessions, err := identity.NewSessionService(identity.SessionDependencies{
Transactor: transactor, Users: store.Users(), Sessions: store.Sessions(),
Credentials: credentials, Limiter: env.Redis, Keyring: keyring, Clock: clock.Now,
}, identity.SessionSettings{
ClientHourlyLimit: int64(env.Config.IdentityClientHourlyLimit), EmailHourlyLimit: int64(env.Config.IdentityLoginEmailHourlyLimit),
IdleTimeout: env.Config.IdentitySessionIdleTimeout, AbsoluteLifetime: env.Config.IdentitySessionAbsoluteLifetime,
})
if err != nil {
t.Fatalf("NewSessionService() error = %v", err)
}
logs := &strings.Builder{}
logger := slog.New(slog.NewJSONHandler(logs, nil))
responder := problem.NewResponder(logger)
healthHandler := v1.NewHealthHandler(health.NewReadiness(env.Postgres), time.Second)
identityHandler := v1.NewIdentityHandler(nil, v1.WithSessionService(sessions), v1.WithPublicOrigin(env.Config.AppPublicURL))
profileHandler := v1.NewProfileHandler(profileusecase.NewService(transactor, clock.Now))
questionnaireHandler := v1.NewQuestionnaireHandler(questionnaireusecase.NewService(transactor, clock.Now))
catalogHandler := v1.NewCatalogHandler(assessment.NewBank(transactor))
handler := v1.NewHandler(healthHandler, responder,
v1.WithIdentity(identityHandler), v1.WithProfile(profileHandler),
v1.WithQuestionnaire(questionnaireHandler), v1.WithCatalog(catalogHandler),
)
router, err := httpadapter.NewRouter(healthHandler, handler, identityHandler.SessionSecurity(), responder,
prometheus.New(), logger, nil)
if err != nil {
t.Fatalf("NewRouter() error = %v", err)
}
return &sessionHTTPHarness{pool: pool, store: store, router: router, credentials: credentials, clock: clock, logs: logs}
}
func createQuestionnaireHTTPEmployer(
ctx context.Context,
t *testing.T,
harness *sessionHTTPHarness,
email string,
passwordHash domain.PasswordHash,
registeredAt time.Time,
) domain.User {
t.Helper()
address, err := domain.NewEmailAddress(email)
if err != nil {
t.Fatalf("NewEmailAddress() error = %v", err)
}
user, err := domain.NewUser(domain.Registration{
Email: address, PasswordHash: passwordHash, Scenario: domain.ScenarioEmployer, RegisteredAt: registeredAt,
})
if err != nil {
t.Fatalf("NewUser(employer) error = %v", err)
}
if err := harness.store.Users().Create(ctx, user); err != nil {
t.Fatalf("Create(employer) error = %v", err)
}
verified, err := harness.store.Users().MarkEmailVerified(ctx, user.ID, user.RegistrationVersion, registeredAt.Add(time.Microsecond))
if err != nil {
t.Fatalf("MarkEmailVerified(employer) error = %v", err)
}
return verified
}
func loginCandidateQuestionnaireHTTP(t *testing.T, harness *sessionHTTPHarness, email, remoteAddr string) questionnaireLogin {
t.Helper()
response := loginSessionHTTP(t, harness, email, sessionHTTPTestPass, sessionHTTPTestOrigin, "", remoteAddr)
if response.Code != http.StatusCreated {
t.Fatalf("login questionnaire account = %d %s", response.Code, response.Body.String())
}
cookie := requireSessionCookie(t, response)
var body struct {
CSRFToken string `json:"csrf_token"`
}
if err := json.Unmarshal(response.Body.Bytes(), &body); err != nil || body.CSRFToken == "" {
t.Fatalf("decode questionnaire login response: %v", err)
}
return questionnaireLogin{cookie: cookie.Value, csrf: body.CSRFToken}
}
func questionnaireHTTPRequest(
t *testing.T,
harness *sessionHTTPHarness,
method, body, cookie, csrf, remoteAddr string,
) *httptest.ResponseRecorder {
t.Helper()
return harness.request(t, method, "/api/v1/me/questionnaire", body, sessionHTTPTestOrigin, cookie, csrf, remoteAddr)
}
func questionnaireUpdateBody(
t *testing.T,
version int64,
specialization, grade string,
languages, stack []string,
commercialMonths, academicMonths int,
) string {
t.Helper()
if languages == nil {
languages = []string{}
}
if stack == nil {
stack = []string{}
}
var experience any
if commercialMonths != 0 || academicMonths != 0 {
experience = map[string]any{"commercial_months": commercialMonths, "academic_months": academicMonths}
}
encoded, err := json.Marshal(map[string]any{
"expected_version": version,
"specializations": []any{map[string]any{
"specialization": specialization, "self_assessed_grade": grade,
"task_languages": languages, "stack": stack, "experience": experience,
}},
"work_context": map[string]any{"work_formats": []string{"remote"}},
})
if err != nil {
t.Fatalf("marshal questionnaire request: %v", err)
}
return string(encoded)
}
func questionnaireUpdateWithUnknownField(t *testing.T, requestBody, field string, value any) string {
t.Helper()
var body map[string]any
if err := json.Unmarshal([]byte(requestBody), &body); err != nil {
t.Fatalf("decode questionnaire request fixture: %v", err)
}
body[field] = value
encoded, err := json.Marshal(body)
if err != nil {
t.Fatalf("marshal questionnaire request with %s: %v", field, err)
}
return string(encoded)
}
func questionnaireCatalogHTTP(t *testing.T, harness *sessionHTTPHarness) questionnaireCatalogResponse {
t.Helper()
response := harness.request(t, http.MethodGet, "/api/v1/specializations", "", "", "", "", "192.0.2.200:1234")
if response.Code != http.StatusOK {
t.Fatalf("GetSpecializationCatalog() = %d %s, want 200", response.Code, response.Body.String())
}
return decodeSpecializationCatalog(t, response.Body.Bytes())
}
func decodeSpecializationCatalog(t *testing.T, encoded []byte) questionnaireCatalogResponse {
t.Helper()
var catalog questionnaireCatalogResponse
if err := json.Unmarshal(encoded, &catalog); err != nil {
t.Fatalf("decode specialization catalog: %v", err)
}
return catalog
}
func assertCatalogAvailability(t *testing.T, catalog questionnaireCatalogResponse, code, status string, grades, languages []string) {
t.Helper()
for _, direction := range catalog.Directions {
for _, specialization := range direction.Specializations {
if specialization.Code != code {
continue
}
actual := specialization.TestAvailability
if actual.Status != status || !slices.Equal(actual.Grades, grades) || !slices.Equal(actual.TaskLanguages, languages) {
t.Fatalf("catalog availability for %s = %+v; want %s grades=%v languages=%v", code, actual, status, grades, languages)
}
if status == "in_development" && (actual.Note == nil || *actual.Note != "Тест в разработке.") {
t.Fatalf("catalog development note for %s = %v, want fixed note", code, actual.Note)
}
if status == "available" && actual.Note != nil {
t.Fatalf("catalog availability note for %s = %q, want null", code, *actual.Note)
}
return
}
}
t.Fatalf("catalog is missing specialization %s", code)
}
func assertQuestionnaireRows(
t *testing.T,
ctx context.Context,
harness *sessionHTTPHarness,
userID uuid.UUID,
wantVersion int64,
specialization, grade, language, stack string,
commercialMonths, academicMonths int32,
) {
t.Helper()
var count int
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM candidate_questionnaires WHERE user_id = $1", userID).Scan(&count); err != nil {
t.Fatalf("count questionnaire rows: %v", err)
}
wantRows := 1
if wantVersion == 0 {
wantRows = 0
}
if count != wantRows {
t.Fatalf("questionnaire rows = %d, want %d", count, wantRows)
}
if wantVersion == 0 {
return
}
var version int64
var storedSpecialization, storedGrade, storedLanguage, storedStack string
var storedCommercial, storedAcademic int32
if err := harness.pool.QueryRow(ctx, `
SELECT questionnaire.version, answer.specialization, answer.self_assessed_grade,
answer.task_languages[1], answer.stack[1], answer.commercial_months, answer.academic_months
FROM candidate_questionnaires AS questionnaire
JOIN candidate_questionnaire_specializations AS answer USING (user_id)
WHERE questionnaire.user_id = $1`, userID).Scan(
&version, &storedSpecialization, &storedGrade, &storedLanguage, &storedStack, &storedCommercial, &storedAcademic,
); err != nil {
t.Fatalf("read stored questionnaire: %v", err)
}
if version != wantVersion || storedSpecialization != specialization || storedGrade != grade || storedLanguage != language ||
storedStack != stack || storedCommercial != commercialMonths || storedAcademic != academicMonths {
t.Fatalf("stored questionnaire = version %d %s/%s/%s/%s/%d/%d; want %d %s/%s/%s/%s/%d/%d",
version, storedSpecialization, storedGrade, storedLanguage, storedStack, storedCommercial, storedAcademic,
wantVersion, specialization, grade, language, stack, commercialMonths, academicMonths)
}
}
func assertQuestionnaireOnboarding(t *testing.T, ctx context.Context, harness *sessionHTTPHarness, userID uuid.UUID, want string) {
t.Helper()
var step string
if err := harness.pool.QueryRow(ctx, "SELECT onboarding_step FROM users WHERE id = $1", userID).Scan(&step); err != nil {
t.Fatalf("read questionnaire onboarding step: %v", err)
}
if step != want {
t.Fatalf("questionnaire onboarding step = %q, want %q", step, want)
}
}
func assertQuestionnaireExperienceConstraint(t *testing.T, ctx context.Context, harness *sessionHTTPHarness, userID uuid.UUID) {
t.Helper()
tx, err := harness.pool.Begin(ctx)
if err != nil {
t.Fatalf("begin questionnaire constraint check: %v", err)
}
defer func() {
if err := tx.Rollback(ctx); err != nil && !errors.Is(err, pgx.ErrTxClosed) {
t.Errorf("rollback questionnaire constraint check: %v", err)
}
}()
if _, err := tx.Exec(ctx, `
INSERT INTO candidate_questionnaires (user_id, version, work_formats, created_at, updated_at)
VALUES ($1, 1, ARRAY['remote']::text[], statement_timestamp(), statement_timestamp())`, userID); err != nil {
t.Fatalf("insert empty questionnaire row for DB constraint check: %v", err)
}
_, err = tx.Exec(ctx, `
INSERT INTO candidate_questionnaire_specializations
(user_id, ordinal, specialization, self_assessed_grade, task_languages, stack, commercial_months, academic_months)
VALUES ($1, 0, 'backend', 'junior', ARRAY[]::text[], ARRAY[]::text[], 18, NULL)`, userID)
var pgError *pgconn.PgError
if !errors.As(err, &pgError) || pgError.Code != "23514" || pgError.ConstraintName != "candidate_questionnaire_specializations_experience" {
t.Fatalf("one-sided experience month value error = %v, want experience CHECK", err)
}
}