539 lines
25 KiB
Go
539 lines
25 KiB
Go
//go:build integration
|
|
|
|
package integration_test
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"log/slog"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
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/health"
|
|
"lincodex/backend/internal/usecase/identity"
|
|
profileusecase "lincodex/backend/internal/usecase/profile"
|
|
)
|
|
|
|
const candidateProfileHTTPTestTimeout = 5 * time.Minute
|
|
|
|
func TestCandidateProfileOverHTTP(t *testing.T) {
|
|
env := bootstrap(t, postgresService, redisService)
|
|
ctx, cancel := context.WithTimeout(t.Context(), candidateProfileHTTPTestTimeout)
|
|
defer cancel()
|
|
harness := newCandidateProfileHTTPHarness(ctx, t, env)
|
|
truncateTables(ctx, t, harness.pool, usersDependentTables...)
|
|
|
|
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, "profile-owner@example.test", passwordHash, true)
|
|
otherCandidate := createSessionHTTPUser(ctx, t, harness, "profile-other@example.test", passwordHash, true)
|
|
employer := createOrganizationHTTPUser(ctx, t, harness, "profile-employer@example.test", passwordHash, domain.ScenarioEmployer, true, now)
|
|
for _, user := range []domain.User{candidate, otherCandidate} {
|
|
if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step = 'candidate_profile' WHERE id = $1", user.ID); err != nil {
|
|
t.Fatalf("set candidate profile onboarding step: %v", err)
|
|
}
|
|
}
|
|
candidateCookie, candidateCSRF := loginCandidateProfileHTTP(t, harness, candidate.Email.Address())
|
|
otherCookie, otherCSRF := loginCandidateProfileHTTP(t, harness, otherCandidate.Email.Address())
|
|
employerCookie, _ := loginCandidateProfileHTTP(t, harness, employer.Email.Address())
|
|
|
|
initial := candidateProfileHTTPRequest(t, harness, http.MethodGet, "", candidateCookie, "", "192.0.2.101:1234")
|
|
if initial.Code != http.StatusOK || initial.Header().Get("Cache-Control") != "no-store" {
|
|
t.Fatalf("empty profile = %d Cache-Control=%q, want 200 no-store: %s", initial.Code, initial.Header().Get("Cache-Control"), initial.Body.String())
|
|
}
|
|
var emptyResponse candidateProfileHTTPResponse
|
|
if err := json.Unmarshal(initial.Body.Bytes(), &emptyResponse); err != nil {
|
|
t.Fatalf("decode empty profile: %v", err)
|
|
}
|
|
if emptyResponse.Version != 0 || emptyResponse.FullName.Status != "unknown" || len(emptyResponse.ExperienceOverlaps) != 0 {
|
|
t.Fatalf("empty profile = %+v, want version 0 and no overlapping periods", emptyResponse)
|
|
}
|
|
|
|
missingAcknowledgement := candidateProfileHTTPRequest(t, harness, http.MethodPut,
|
|
candidateProfileUpdateBody(t, 0, "Private Profile Owner", false), candidateCookie, candidateCSRF, "192.0.2.102:1234")
|
|
if missingAcknowledgement.Code != http.StatusBadRequest || !strings.Contains(missingAcknowledgement.Body.String(), "/experience/1/started_on") {
|
|
t.Fatalf("overlapping periods without acknowledgement = %d %s, want field validation", missingAcknowledgement.Code, missingAcknowledgement.Body.String())
|
|
}
|
|
assertCandidateProfileRows(t, ctx, harness, candidate.ID, 0, 0)
|
|
assertCandidateProfileOnboarding(t, ctx, harness, candidate.ID, "candidate_profile")
|
|
|
|
firstSave := candidateProfileHTTPRequest(t, harness, http.MethodPut,
|
|
candidateProfileUpdateBody(t, 0, "Private Profile Owner", true), candidateCookie, candidateCSRF, "192.0.2.103:1234")
|
|
if firstSave.Code != http.StatusOK || firstSave.Header().Get("Cache-Control") != "no-store" {
|
|
t.Fatalf("save profile = %d Cache-Control=%q: %s", firstSave.Code, firstSave.Header().Get("Cache-Control"), firstSave.Body.String())
|
|
}
|
|
var saved candidateProfileHTTPResponse
|
|
if err := json.Unmarshal(firstSave.Body.Bytes(), &saved); err != nil {
|
|
t.Fatalf("decode saved profile: %v", err)
|
|
}
|
|
if saved.Version != 1 || saved.FullName.Value == nil || *saved.FullName.Value != "Private Profile Owner" ||
|
|
len(saved.ExperienceOverlaps) != 1 || saved.ExperienceOverlaps[0].Status != "confirmed" ||
|
|
len(saved.ConfirmedCategories) != 0 {
|
|
t.Fatalf("saved profile = %+v, want version 1 with confirmed period overlap", saved)
|
|
}
|
|
assertCandidateProfileRows(t, ctx, harness, candidate.ID, 1, 1)
|
|
assertCandidateProfileOnboarding(t, ctx, harness, candidate.ID, "candidate_questionnaire")
|
|
assertCandidateProfileHistoryCannotBeUpdated(t, ctx, harness, candidate.ID)
|
|
|
|
reversedPeriod := candidateProfileHTTPRequest(t, harness, http.MethodPut,
|
|
candidateProfileUpdateWithExperience(t, 1, "Private Profile Owner", 0, "2021-01", "2020-12"),
|
|
candidateCookie, candidateCSRF, "192.0.2.111:1234")
|
|
if reversedPeriod.Code != http.StatusBadRequest || !strings.Contains(reversedPeriod.Body.String(), "/experience/0/ended_on") {
|
|
t.Fatalf("reversed experience period = %d %s, want a fixed ended_on validation error", reversedPeriod.Code, reversedPeriod.Body.String())
|
|
}
|
|
futurePeriod := candidateProfileHTTPRequest(t, harness, http.MethodPut,
|
|
candidateProfileUpdateWithExperience(t, 1, "Private Profile Owner", 1, "2999-01", nil),
|
|
candidateCookie, candidateCSRF, "192.0.2.112:1234")
|
|
if futurePeriod.Code != http.StatusBadRequest || !strings.Contains(futurePeriod.Body.String(), "/experience/1/started_on") {
|
|
t.Fatalf("future experience period = %d %s, want a fixed started_on validation error", futurePeriod.Code, futurePeriod.Body.String())
|
|
}
|
|
for _, forbiddenField := range []struct {
|
|
name string
|
|
value any
|
|
}{
|
|
{name: "confirmed_categories", value: []any{map[string]any{"specialization": "backend", "grade": "senior"}}},
|
|
{name: "user_id", value: uuid.NewString()},
|
|
} {
|
|
body := candidateProfileUpdateWithUnknownField(t,
|
|
candidateProfileUpdateBody(t, 1, "Private Profile Owner", true), forbiddenField.name, forbiddenField.value)
|
|
response := candidateProfileHTTPRequest(t, harness, http.MethodPut, body, candidateCookie, candidateCSRF, "192.0.2.113:1234")
|
|
if response.Code != http.StatusBadRequest {
|
|
t.Fatalf("profile update with %s = %d %s, want 400", forbiddenField.name, response.Code, response.Body.String())
|
|
}
|
|
}
|
|
assertCandidateProfileRows(t, ctx, harness, candidate.ID, 1, 1)
|
|
assertCandidateProfileOnboarding(t, ctx, harness, candidate.ID, "candidate_questionnaire")
|
|
|
|
stale := candidateProfileHTTPRequest(t, harness, http.MethodPut,
|
|
candidateProfileUpdateBody(t, 0, "Stale Profile Name", true), candidateCookie, candidateCSRF, "192.0.2.104:1234")
|
|
requireSessionProblem(t, stale, http.StatusPreconditionFailed, "version_conflict")
|
|
assertCandidateProfileRows(t, ctx, harness, candidate.ID, 1, 1)
|
|
|
|
noOp := candidateProfileHTTPRequest(t, harness, http.MethodPut,
|
|
candidateProfileUpdateBody(t, 1, "Private Profile Owner", true), candidateCookie, candidateCSRF, "192.0.2.105:1234")
|
|
if noOp.Code != http.StatusOK {
|
|
t.Fatalf("no-op profile save = %d %s, want 200", noOp.Code, noOp.Body.String())
|
|
}
|
|
assertCandidateProfileRows(t, ctx, harness, candidate.ID, 1, 1)
|
|
|
|
otherRead := candidateProfileHTTPRequest(t, harness, http.MethodGet, "", otherCookie, "", "192.0.2.106:1234")
|
|
var otherProfile candidateProfileHTTPResponse
|
|
if otherRead.Code != http.StatusOK || json.Unmarshal(otherRead.Body.Bytes(), &otherProfile) != nil ||
|
|
otherProfile.Version != 0 || otherProfile.FullName.Value != nil {
|
|
t.Fatalf("another candidate's profile = %d %s, want an empty version-0 profile", otherRead.Code, otherRead.Body.String())
|
|
}
|
|
employerRead := candidateProfileHTTPRequest(t, harness, http.MethodGet, "", employerCookie, "", "192.0.2.107:1234")
|
|
requireSessionProblem(t, employerRead, http.StatusForbidden, "forbidden")
|
|
for _, foreignPath := range []string{
|
|
"/api/v1/me/profile/" + otherCandidate.ID.String(),
|
|
"/api/v1/me/profile/" + uuid.NewString(),
|
|
} {
|
|
foreignRead := harness.request(t, http.MethodGet, foreignPath, "", sessionHTTPTestOrigin, candidateCookie, "", "192.0.2.114:1234")
|
|
if foreignRead.Code != http.StatusNotFound || strings.Contains(foreignRead.Body.String(), "Private Profile Owner") {
|
|
t.Fatalf("foreign profile path %s = %d %s, want a non-disclosing 404", foreignPath, foreignRead.Code, foreignRead.Body.String())
|
|
}
|
|
}
|
|
|
|
// A no-op on an unsaved profile advances onboarding without inventing a
|
|
// profile version or a history row.
|
|
emptySave := candidateProfileHTTPRequest(t, harness, http.MethodPut,
|
|
candidateEmptyProfileUpdateBody(t), otherCookie, otherCSRF, "192.0.2.108:1234")
|
|
if emptySave.Code != http.StatusOK {
|
|
t.Fatalf("empty profile save = %d %s, want 200", emptySave.Code, emptySave.Body.String())
|
|
}
|
|
assertCandidateProfileRows(t, ctx, harness, otherCandidate.ID, 0, 0)
|
|
assertCandidateProfileOnboarding(t, ctx, harness, otherCandidate.ID, "candidate_questionnaire")
|
|
|
|
if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step = 'candidate_profile' WHERE id = $1", candidate.ID); err != nil {
|
|
t.Fatalf("reset candidate onboarding for rollback test: %v", err)
|
|
}
|
|
removeHistoryFailure := installCandidateProfileHistoryInsertFailure(t, ctx, harness)
|
|
historyFailure := candidateProfileHTTPRequest(t, harness, http.MethodPut,
|
|
candidateProfileUpdateBody(t, 1, "Failed History Write", true), candidateCookie, candidateCSRF, "192.0.2.115:1234")
|
|
if historyFailure.Code != http.StatusInternalServerError {
|
|
t.Fatalf("profile save with history failure = %d %s, want 500", historyFailure.Code, historyFailure.Body.String())
|
|
}
|
|
removeHistoryFailure()
|
|
assertCandidateProfileRows(t, ctx, harness, candidate.ID, 1, 1)
|
|
assertCandidateProfileOnboarding(t, ctx, harness, candidate.ID, "candidate_profile")
|
|
|
|
// Failure after history insertion must also roll back the profile and
|
|
// history when the onboarding transition fails in the same transaction.
|
|
removeOnboardingFailure := installCandidateProfileOnboardingFailure(t, ctx, harness)
|
|
rollbackAttempt := candidateProfileHTTPRequest(t, harness, http.MethodPut,
|
|
candidateProfileUpdateBody(t, 1, "Private Profile Owner Updated", true), candidateCookie, candidateCSRF, "192.0.2.116:1234")
|
|
if rollbackAttempt.Code != http.StatusInternalServerError {
|
|
t.Fatalf("profile save with onboarding failure = %d %s, want 500", rollbackAttempt.Code, rollbackAttempt.Body.String())
|
|
}
|
|
removeOnboardingFailure()
|
|
assertCandidateProfileRows(t, ctx, harness, candidate.ID, 1, 1)
|
|
assertCandidateProfileOnboarding(t, ctx, harness, candidate.ID, "candidate_profile")
|
|
unchanged := candidateProfileHTTPRequest(t, harness, http.MethodGet, "", candidateCookie, "", "192.0.2.117:1234")
|
|
var unchangedProfile candidateProfileHTTPResponse
|
|
if unchanged.Code != http.StatusOK || json.Unmarshal(unchanged.Body.Bytes(), &unchangedProfile) != nil ||
|
|
unchangedProfile.FullName.Value == nil || *unchangedProfile.FullName.Value != "Private Profile Owner" {
|
|
t.Fatalf("profile after failed transaction = %d %s, want old claims", unchanged.Code, unchanged.Body.String())
|
|
}
|
|
updated := candidateProfileHTTPRequest(t, harness, http.MethodPut,
|
|
candidateProfileUpdateBody(t, 1, "Private Profile Owner Updated", true), candidateCookie, candidateCSRF, "192.0.2.118:1234")
|
|
var updatedProfile candidateProfileHTTPResponse
|
|
if updated.Code != http.StatusOK || json.Unmarshal(updated.Body.Bytes(), &updatedProfile) != nil ||
|
|
updatedProfile.Version != 2 || updatedProfile.FullName.Value == nil || *updatedProfile.FullName.Value != "Private Profile Owner Updated" {
|
|
t.Fatalf("profile save after rolled-back attempt = %d %s, want version 2", updated.Code, updated.Body.String())
|
|
}
|
|
assertCandidateProfileRows(t, ctx, harness, candidate.ID, 2, 2)
|
|
assertCandidateProfileOnboarding(t, ctx, harness, candidate.ID, "candidate_questionnaire")
|
|
|
|
// Once onboarding has moved past the profile step, saving again does not
|
|
// move it back or override its current step.
|
|
if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step = 'candidate_assessment' WHERE id = $1", candidate.ID); err != nil {
|
|
t.Fatalf("move onboarding to a later step: %v", err)
|
|
}
|
|
if response := candidateProfileHTTPRequest(t, harness, http.MethodPut,
|
|
candidateProfileUpdateBody(t, 2, "Private Profile Owner Updated", true), candidateCookie, candidateCSRF, "192.0.2.109:1234"); response.Code != http.StatusOK {
|
|
t.Fatalf("profile save after later onboarding step = %d %s", response.Code, response.Body.String())
|
|
}
|
|
assertCandidateProfileOnboarding(t, ctx, harness, candidate.ID, "candidate_assessment")
|
|
|
|
for _, privateValue := range []string{
|
|
candidate.Email.Address(), otherCandidate.Email.Address(), employer.Email.Address(),
|
|
"Private Profile Owner", "Private Profile Owner Updated", "Stale Profile Name", "Failed History Write",
|
|
"Example Private Employer", "Private career history",
|
|
} {
|
|
if strings.Contains(harness.logs.String(), privateValue) {
|
|
t.Fatalf("profile HTTP logs contain private value %q", privateValue)
|
|
}
|
|
}
|
|
|
|
// Rebuild the handlers and pool while retaining the session cookie. The
|
|
// profile and append-only history remain in PostgreSQL across restarts.
|
|
harness.pool.Close()
|
|
harness = newCandidateProfileHTTPHarness(ctx, t, env)
|
|
restartedRead := candidateProfileHTTPRequest(t, harness, http.MethodGet, "", candidateCookie, "", "192.0.2.110:1234")
|
|
var restarted candidateProfileHTTPResponse
|
|
if restartedRead.Code != http.StatusOK || json.Unmarshal(restartedRead.Body.Bytes(), &restarted) != nil ||
|
|
restarted.Version != 2 || restarted.FullName.Value == nil || *restarted.FullName.Value != "Private Profile Owner Updated" ||
|
|
len(restarted.ExperienceOverlaps) != 1 || restarted.ExperienceOverlaps[0].Status != "confirmed" {
|
|
t.Fatalf("profile after handler restart = %d %s, want version 2 and stored confirmation", restartedRead.Code, restartedRead.Body.String())
|
|
}
|
|
assertCandidateProfileRows(t, ctx, harness, candidate.ID, 2, 2)
|
|
}
|
|
|
|
type candidateProfileHTTPResponse struct {
|
|
Version int64 `json:"version"`
|
|
FullName struct {
|
|
Status string `json:"status"`
|
|
Value *string `json:"value"`
|
|
} `json:"full_name"`
|
|
ExperienceOverlaps []struct {
|
|
FirstIndex int `json:"first_index"`
|
|
SecondIndex int `json:"second_index"`
|
|
Status string `json:"status"`
|
|
} `json:"experience_overlaps"`
|
|
ConfirmedCategories []json.RawMessage `json:"confirmed_categories"`
|
|
}
|
|
|
|
func newCandidateProfileHTTPHarness(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)}
|
|
sessions, err := identity.NewSessionService(identity.SessionDependencies{
|
|
Transactor: postgresadapter.NewTransactor(pool), 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(postgresadapter.NewTransactor(pool), clock.Now))
|
|
handler := v1.NewHandler(healthHandler, responder,
|
|
v1.WithIdentity(identityHandler), v1.WithProfile(profileHandler),
|
|
)
|
|
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 loginCandidateProfileHTTP(t *testing.T, harness *sessionHTTPHarness, email string) (string, string) {
|
|
t.Helper()
|
|
response := loginSessionHTTP(t, harness, email, sessionHTTPTestPass, sessionHTTPTestOrigin, "", "192.0.2.100:1234")
|
|
if response.Code != http.StatusCreated {
|
|
t.Fatalf("login profile 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 login CSRF token: %v", err)
|
|
}
|
|
return cookie.Value, body.CSRFToken
|
|
}
|
|
|
|
func candidateProfileHTTPRequest(
|
|
t *testing.T,
|
|
harness *sessionHTTPHarness,
|
|
method, body, cookie, csrf, remoteAddr string,
|
|
) *httptest.ResponseRecorder {
|
|
t.Helper()
|
|
return harness.request(t, method, "/api/v1/me/profile", body, sessionHTTPTestOrigin, cookie, csrf, remoteAddr)
|
|
}
|
|
|
|
func candidateProfileUpdateBody(t *testing.T, version int64, name string, confirmOverlap bool) string {
|
|
t.Helper()
|
|
experience := []map[string]any{
|
|
{
|
|
"employer_name": "Example Private Employer", "specialization": "backend", "started_on": "2021-01",
|
|
"ended_on": "2022-06", "summary": "Private career history", "status": "confirmed",
|
|
},
|
|
{
|
|
"employer_name": "Second Private Employer", "specialization": "backend", "started_on": "2022-01",
|
|
"ended_on": "2023-04", "summary": "Another private result", "status": "confirmed",
|
|
},
|
|
}
|
|
acknowledgements := []map[string]any{}
|
|
if confirmOverlap {
|
|
acknowledgements = append(acknowledgements, map[string]any{
|
|
"first_index": 0, "second_index": 1,
|
|
"first_period": map[string]any{"started_on": "2021-01", "ended_on": "2022-06"},
|
|
"second_period": map[string]any{"started_on": "2022-01", "ended_on": "2023-04"},
|
|
})
|
|
}
|
|
body, err := json.Marshal(map[string]any{
|
|
"expected_version": version,
|
|
"full_name": map[string]any{"value": name, "status": "confirmed"},
|
|
"contacts": map[string]any{"email": nil, "phone": nil, "telegram": nil},
|
|
"stack": []any{},
|
|
"roles": []any{},
|
|
"experience": experience,
|
|
"confirmed_parallel_periods": acknowledgements,
|
|
"soft_skills": []any{},
|
|
"terms": map[string]any{"location": nil, "relocation": nil, "salary_minimum": nil},
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("marshal profile update: %v", err)
|
|
}
|
|
return string(body)
|
|
}
|
|
|
|
func candidateProfileUpdateWithExperience(
|
|
t *testing.T,
|
|
version int64,
|
|
name string,
|
|
index int,
|
|
startedOn string,
|
|
endedOn any,
|
|
) string {
|
|
t.Helper()
|
|
var body map[string]any
|
|
if err := json.Unmarshal([]byte(candidateProfileUpdateBody(t, version, name, true)), &body); err != nil {
|
|
t.Fatalf("decode profile update fixture: %v", err)
|
|
}
|
|
experience, ok := body["experience"].([]any)
|
|
if !ok || index < 0 || index >= len(experience) {
|
|
t.Fatalf("profile update fixture has no experience at index %d", index)
|
|
}
|
|
item, ok := experience[index].(map[string]any)
|
|
if !ok {
|
|
t.Fatalf("profile update fixture experience at index %d has the wrong type", index)
|
|
}
|
|
item["started_on"] = startedOn
|
|
item["ended_on"] = endedOn
|
|
encoded, err := json.Marshal(body)
|
|
if err != nil {
|
|
t.Fatalf("marshal profile update fixture: %v", err)
|
|
}
|
|
return string(encoded)
|
|
}
|
|
|
|
func candidateProfileUpdateWithUnknownField(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 profile update fixture: %v", err)
|
|
}
|
|
body[field] = value
|
|
encoded, err := json.Marshal(body)
|
|
if err != nil {
|
|
t.Fatalf("marshal profile update with %s: %v", field, err)
|
|
}
|
|
return string(encoded)
|
|
}
|
|
|
|
func candidateEmptyProfileUpdateBody(t *testing.T) string {
|
|
t.Helper()
|
|
body, err := json.Marshal(map[string]any{
|
|
"expected_version": 0,
|
|
"full_name": nil,
|
|
"contacts": map[string]any{"email": nil, "phone": nil, "telegram": nil},
|
|
"stack": []any{}, "roles": []any{}, "experience": []any{},
|
|
"confirmed_parallel_periods": []any{}, "soft_skills": []any{},
|
|
"terms": map[string]any{"location": nil, "relocation": nil, "salary_minimum": nil},
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("marshal empty profile update: %v", err)
|
|
}
|
|
return string(body)
|
|
}
|
|
|
|
func assertCandidateProfileRows(t *testing.T, ctx context.Context, harness *sessionHTTPHarness, userID uuid.UUID, version, history int64) {
|
|
t.Helper()
|
|
var profileCount, historyCount int64
|
|
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM candidate_profiles WHERE user_id = $1", userID).Scan(&profileCount); err != nil {
|
|
t.Fatalf("count stored profiles: %v", err)
|
|
}
|
|
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM candidate_profile_history WHERE user_id = $1", userID).Scan(&historyCount); err != nil {
|
|
t.Fatalf("count profile history: %v", err)
|
|
}
|
|
wantProfileCount := int64(0)
|
|
if version > 0 {
|
|
wantProfileCount = 1
|
|
}
|
|
if profileCount != wantProfileCount || historyCount != history {
|
|
t.Fatalf("profile rows = %d, history rows = %d; want %d and %d", profileCount, historyCount, wantProfileCount, history)
|
|
}
|
|
if version > 0 {
|
|
var storedVersion int64
|
|
if err := harness.pool.QueryRow(ctx, "SELECT version FROM candidate_profiles WHERE user_id = $1", userID).Scan(&storedVersion); err != nil {
|
|
t.Fatalf("read stored profile version: %v", err)
|
|
}
|
|
if storedVersion != version {
|
|
t.Fatalf("stored profile version = %d, want %d", storedVersion, version)
|
|
}
|
|
}
|
|
}
|
|
|
|
func assertCandidateProfileOnboarding(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 onboarding step: %v", err)
|
|
}
|
|
if step != want {
|
|
t.Fatalf("onboarding step = %q, want %q", step, want)
|
|
}
|
|
}
|
|
|
|
func assertCandidateProfileHistoryCannotBeUpdated(t *testing.T, ctx context.Context, harness *sessionHTTPHarness, userID uuid.UUID) {
|
|
t.Helper()
|
|
if _, err := harness.pool.Exec(ctx, "UPDATE candidate_profile_history SET snapshot = snapshot WHERE user_id = $1", userID); err == nil {
|
|
t.Fatal("candidate profile history accepted an UPDATE")
|
|
}
|
|
}
|
|
|
|
func installCandidateProfileHistoryInsertFailure(t *testing.T, ctx context.Context, harness *sessionHTTPHarness) func() {
|
|
t.Helper()
|
|
const functionName = "reject_candidate_profile_history_insert_for_http_test"
|
|
const triggerName = "candidate_profile_http_reject_history_insert"
|
|
if _, err := harness.pool.Exec(ctx, `
|
|
CREATE FUNCTION reject_candidate_profile_history_insert_for_http_test() RETURNS trigger
|
|
LANGUAGE plpgsql AS $$
|
|
BEGIN
|
|
RAISE EXCEPTION 'candidate profile history HTTP test failure';
|
|
END;
|
|
$$`); err != nil {
|
|
t.Fatalf("create history failure function: %v", err)
|
|
}
|
|
removed := false
|
|
remove := func() {
|
|
if removed {
|
|
return
|
|
}
|
|
cleanupCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
defer cancel()
|
|
if _, err := harness.pool.Exec(cleanupCtx, "DROP TRIGGER IF EXISTS "+triggerName+" ON candidate_profile_history"); err != nil {
|
|
t.Errorf("drop history failure trigger: %v", err)
|
|
}
|
|
if _, err := harness.pool.Exec(cleanupCtx, "DROP FUNCTION IF EXISTS "+functionName+"()"); err != nil {
|
|
t.Errorf("drop history failure function: %v", err)
|
|
}
|
|
removed = true
|
|
}
|
|
t.Cleanup(remove)
|
|
if _, err := harness.pool.Exec(ctx, `
|
|
CREATE TRIGGER candidate_profile_http_reject_history_insert
|
|
BEFORE INSERT ON candidate_profile_history
|
|
FOR EACH ROW EXECUTE FUNCTION reject_candidate_profile_history_insert_for_http_test()`); err != nil {
|
|
t.Fatalf("create history failure trigger: %v", err)
|
|
}
|
|
return remove
|
|
}
|
|
|
|
func installCandidateProfileOnboardingFailure(t *testing.T, ctx context.Context, harness *sessionHTTPHarness) func() {
|
|
t.Helper()
|
|
const functionName = "reject_candidate_profile_onboarding_advance_for_http_test"
|
|
const triggerName = "candidate_profile_http_reject_onboarding_advance"
|
|
if _, err := harness.pool.Exec(ctx, `
|
|
CREATE FUNCTION reject_candidate_profile_onboarding_advance_for_http_test() RETURNS trigger
|
|
LANGUAGE plpgsql AS $$
|
|
BEGIN
|
|
IF OLD.onboarding_step = 'candidate_profile' AND NEW.onboarding_step = 'candidate_questionnaire' THEN
|
|
RAISE EXCEPTION 'candidate profile HTTP test failure';
|
|
END IF;
|
|
RETURN NEW;
|
|
END;
|
|
$$`); err != nil {
|
|
t.Fatalf("create onboarding failure function: %v", err)
|
|
}
|
|
removed := false
|
|
remove := func() {
|
|
if removed {
|
|
return
|
|
}
|
|
cleanupCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
defer cancel()
|
|
if _, err := harness.pool.Exec(cleanupCtx, "DROP TRIGGER IF EXISTS "+triggerName+" ON users"); err != nil {
|
|
t.Errorf("drop onboarding failure trigger: %v", err)
|
|
}
|
|
if _, err := harness.pool.Exec(cleanupCtx, "DROP FUNCTION IF EXISTS "+functionName+"()"); err != nil {
|
|
t.Errorf("drop onboarding failure function: %v", err)
|
|
}
|
|
removed = true
|
|
}
|
|
t.Cleanup(remove)
|
|
if _, err := harness.pool.Exec(ctx, `
|
|
CREATE TRIGGER candidate_profile_http_reject_onboarding_advance
|
|
BEFORE UPDATE ON users
|
|
FOR EACH ROW EXECUTE FUNCTION reject_candidate_profile_onboarding_advance_for_http_test()`); err != nil {
|
|
t.Fatalf("create onboarding failure trigger: %v", err)
|
|
}
|
|
return remove
|
|
}
|