510 lines
24 KiB
Go
510 lines
24 KiB
Go
//go:build integration
|
|
|
|
package integration_test
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
"lincodex/backend/internal/adapter/secondary/postgres"
|
|
"lincodex/backend/internal/domain"
|
|
"lincodex/backend/internal/port/outbound"
|
|
"lincodex/backend/internal/usecase/assessment"
|
|
assessmentpolicy "lincodex/backend/internal/usecase/policy"
|
|
)
|
|
|
|
type assessmentAvailabilityHTTPGrade struct {
|
|
Grade string `json:"grade"`
|
|
Status string `json:"status"`
|
|
Mode *string `json:"mode"`
|
|
TimeLimitSeconds *int32 `json:"time_limit_seconds"`
|
|
MaxSessions *int32 `json:"max_sessions"`
|
|
MaxItems *int32 `json:"max_items"`
|
|
PracticeRequired *bool `json:"practice_required"`
|
|
}
|
|
|
|
type assessmentAvailabilityHTTPSpecialization struct {
|
|
Specialization string `json:"specialization"`
|
|
ActiveAttempt *uuid.UUID `json:"active_attempt_id"`
|
|
Grades []assessmentAvailabilityHTTPGrade `json:"grades"`
|
|
}
|
|
|
|
type assessmentAvailabilityHTTPProjection struct {
|
|
Specializations []assessmentAvailabilityHTTPSpecialization `json:"specializations"`
|
|
}
|
|
|
|
func TestAssessmentAvailabilityHTTPIsCandidateScopedAndReadOnly(t *testing.T) {
|
|
env := bootstrap(t, postgresService, redisService)
|
|
ctx, cancel := context.WithTimeout(t.Context(), assessmentAttemptHTTPTimeout)
|
|
defer cancel()
|
|
databaseURL := env.createIsolatedDatabase(ctx, t)
|
|
applyMigrations(ctx, t, databaseURL)
|
|
isolatedEnv := *env
|
|
isolatedEnv.Config.DatabaseURL = databaseURL
|
|
harness := newAssessmentAttemptHTTPHarness(ctx, t, &isolatedEnv)
|
|
seedAssessmentAttemptHTTPBank(ctx, t, harness.pool)
|
|
|
|
passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass)
|
|
if err != nil {
|
|
t.Fatalf("HashNewPassword() error = %v", err)
|
|
}
|
|
candidate := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "availability-http-candidate@example.test", passwordHash, true)
|
|
if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step='candidate_questionnaire' WHERE id=$1", candidate.ID); err != nil {
|
|
t.Fatalf("set candidate onboarding step: %v", err)
|
|
}
|
|
candidateCookie, candidateCSRF := loginConsentHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address(), "203.0.113.50:1234")
|
|
|
|
unauthenticated := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, "/api/v1/me/assessment-availability", "", "", "", "", "", "203.0.113.51:1234")
|
|
requireSessionProblem(t, unauthenticated, http.StatusUnauthorized, "unauthenticated")
|
|
employer := createAssessmentAvailabilityEmployer(ctx, t, harness.sessionHTTPHarness, "availability-http-employer@example.test", passwordHash)
|
|
employerCookie, _ := loginConsentHTTP(t, harness.sessionHTTPHarness, employer.Email.Address(), "203.0.113.52:1234")
|
|
employerRead := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, "/api/v1/me/assessment-availability", "", "", employerCookie.Value, "", "", "203.0.113.53:1234")
|
|
requireSessionProblem(t, employerRead, http.StatusForbidden, "forbidden")
|
|
|
|
path := "/api/v1/me/assessment-availability"
|
|
emptyRead := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, path, "", "", candidateCookie.Value, "", "", "203.0.113.54:1234")
|
|
var emptyProjection struct {
|
|
Specializations []json.RawMessage `json:"specializations"`
|
|
}
|
|
if emptyRead.Code != http.StatusOK || emptyRead.Header().Get("Cache-Control") != "no-store" ||
|
|
json.Unmarshal(emptyRead.Body.Bytes(), &emptyProjection) != nil || emptyProjection.Specializations == nil || len(emptyProjection.Specializations) != 0 {
|
|
t.Fatalf("availability before questionnaire = %d %s, Cache-Control=%q, want empty candidate projection",
|
|
emptyRead.Code, emptyRead.Body.String(), emptyRead.Header().Get("Cache-Control"))
|
|
}
|
|
if response := assessmentAttemptQuestionnaireRequest(t, harness, candidateCookie.Value, candidateCSRF, "203.0.113.55:1234"); response.Code != http.StatusOK {
|
|
t.Fatalf("save candidate questionnaire = %d %s", response.Code, response.Body.String())
|
|
}
|
|
grantCurrentAttemptConsent(t, harness, candidateCookie, candidateCSRF, "203.0.113.56:1234")
|
|
|
|
available := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, path, "", "", candidateCookie.Value, "", "", "203.0.113.57:1234")
|
|
var initial assessmentAvailabilityHTTPProjection
|
|
if available.Code != http.StatusOK || available.Header().Get("Cache-Control") != "no-store" ||
|
|
json.Unmarshal(available.Body.Bytes(), &initial) != nil || len(initial.Specializations) != 2 {
|
|
t.Fatalf("availability after questionnaire = %d %s, Cache-Control=%q, want both saved specializations",
|
|
available.Code, available.Body.String(), available.Header().Get("Cache-Control"))
|
|
}
|
|
backend := findAssessmentAvailabilitySpecialization(t, initial, "backend")
|
|
for _, target := range []string{"intern", "junior"} {
|
|
grade := findAssessmentAvailabilityGrade(t, backend, target)
|
|
if grade.Status != "available" || grade.Mode == nil || *grade.Mode != "demo_basic" ||
|
|
grade.TimeLimitSeconds == nil || *grade.TimeLimitSeconds != 72*60*60 ||
|
|
grade.MaxSessions == nil || *grade.MaxSessions != 1 || grade.MaxItems == nil || *grade.MaxItems != 13 ||
|
|
grade.PracticeRequired == nil || *grade.PracticeRequired {
|
|
t.Fatalf("backend %s availability = %+v, response=%s, want the published demo_basic start limits",
|
|
target, grade, available.Body.String())
|
|
}
|
|
}
|
|
|
|
// The questionnaire self-assesses junior, while this request selects the
|
|
// offered intern bank. The stored questionnaire grade is not a target gate.
|
|
created := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts",
|
|
assessmentAttemptCreateBodyWithGrade(t, "backend", "intern"), sessionHTTPTestOrigin,
|
|
candidateCookie.Value, candidateCSRF, "availability-create-different-grade", "203.0.113.58:1234")
|
|
var activeAttempt assessmentAnswerHTTPAttempt
|
|
if created.Code != http.StatusCreated || json.Unmarshal(created.Body.Bytes(), &activeAttempt) != nil || activeAttempt.ID == uuid.Nil {
|
|
t.Fatalf("create attempt at offered grade different from self-assessment = %d %s", created.Code, created.Body.String())
|
|
}
|
|
|
|
// Re-login immediately before the read-only measurement so the session
|
|
// activity coalescing window cannot obscure a write caused by the GET.
|
|
candidateCookie, candidateCSRF = loginConsentHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address(), "203.0.113.59:1234")
|
|
token, err := domain.ParseSecretToken(candidateCookie.Value)
|
|
if err != nil {
|
|
t.Fatalf("parse synthetic session token for state comparison: %v", err)
|
|
}
|
|
tokenHash := token.Hash()
|
|
type availabilityReadState struct {
|
|
attemptVersion int64
|
|
sessionsUsed int32
|
|
updatedAt time.Time
|
|
sessionSeenAt time.Time
|
|
attemptRows int64
|
|
itemRows int64
|
|
answeredItems int64
|
|
idempotency int64
|
|
}
|
|
readAvailabilityState := func() availabilityReadState {
|
|
t.Helper()
|
|
var state availabilityReadState
|
|
if err := harness.pool.QueryRow(ctx, "SELECT version, sessions_used, updated_at FROM assessment_attempts WHERE id=$1", activeAttempt.ID).
|
|
Scan(&state.attemptVersion, &state.sessionsUsed, &state.updatedAt); err != nil {
|
|
t.Fatalf("read attempt state before/after availability: %v", err)
|
|
}
|
|
if err := harness.pool.QueryRow(ctx, "SELECT last_seen_at FROM sessions WHERE token_hash=$1", tokenHash[:]).Scan(&state.sessionSeenAt); err != nil {
|
|
t.Fatalf("read session activity before/after availability: %v", err)
|
|
}
|
|
if err := harness.pool.QueryRow(ctx, `
|
|
SELECT (SELECT count(*) FROM assessment_attempts WHERE user_id=$1 AND kind='root'),
|
|
(SELECT count(*) FROM assessment_attempt_items WHERE attempt_id=$2),
|
|
(SELECT count(*) FROM assessment_attempt_items WHERE attempt_id=$2 AND answered_at IS NOT NULL),
|
|
(SELECT count(*) FROM idempotency_records)`, candidate.ID, activeAttempt.ID).
|
|
Scan(&state.attemptRows, &state.itemRows, &state.answeredItems, &state.idempotency); err != nil {
|
|
t.Fatalf("read attempt/quota state before/after availability: %v", err)
|
|
}
|
|
return state
|
|
}
|
|
before := readAvailabilityState()
|
|
for index := 0; index < 2; index++ {
|
|
response := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, path, "", "", candidateCookie.Value, "", "", "203.0.113.60:1234")
|
|
var current assessmentAvailabilityHTTPProjection
|
|
if response.Code != http.StatusOK || response.Header().Get("Cache-Control") != "no-store" ||
|
|
json.Unmarshal(response.Body.Bytes(), ¤t) != nil {
|
|
t.Fatalf("repeated availability GET %d = %d %s, Cache-Control=%q", index+1, response.Code,
|
|
response.Body.String(), response.Header().Get("Cache-Control"))
|
|
}
|
|
backend = findAssessmentAvailabilitySpecialization(t, current, "backend")
|
|
if backend.ActiveAttempt == nil || *backend.ActiveAttempt != activeAttempt.ID {
|
|
t.Fatalf("repeated availability GET %d active attempt = %v, want %s", index+1, backend.ActiveAttempt, activeAttempt.ID)
|
|
}
|
|
for _, grade := range backend.Grades {
|
|
if grade.Status != "active_attempt" {
|
|
t.Fatalf("backend grade %s status = %q while an attempt is active", grade.Grade, grade.Status)
|
|
}
|
|
}
|
|
}
|
|
after := readAvailabilityState()
|
|
if before.attemptVersion != after.attemptVersion || before.sessionsUsed != after.sessionsUsed ||
|
|
!before.updatedAt.Equal(after.updatedAt) || !before.sessionSeenAt.Equal(after.sessionSeenAt) ||
|
|
before.attemptRows != after.attemptRows || before.itemRows != after.itemRows ||
|
|
before.answeredItems != after.answeredItems || before.idempotency != after.idempotency {
|
|
t.Fatalf("availability GET wrote state: before=%+v after=%+v", before, after)
|
|
}
|
|
|
|
adaptive := domain.DemoProductPolicyV2()
|
|
adaptive.Assessment.Calibration = domain.AssessmentCalibrationCalibrated
|
|
adaptive.Assessment.Attempt.RealMode = domain.AssessmentRealModeAdaptive
|
|
adaptive.Assessment.Attempt.BasicPassMark = 0
|
|
publisher := assessmentpolicy.NewPublisher(postgres.NewPolicyStore(harness.pool).Policies(), time.Now)
|
|
adaptiveVersion, err := publisher.Publish(ctx, assessmentpolicy.PublishInput{
|
|
Key: domain.ProductPolicyKey, Kind: domain.PolicyKindCalibrated, Author: policyTestAuthor, Policy: adaptive,
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("publish explicit adaptive policy for unavailable-mode check: %v", err)
|
|
}
|
|
adaptiveBank := assessment.NewBank(postgres.NewTransactor(harness.pool))
|
|
adaptiveFixture := assessmentFixture{
|
|
ctx: ctx, pool: harness.pool, store: postgres.NewAssessmentBankStore(harness.pool),
|
|
transactor: postgres.NewTransactor(harness.pool), bank: adaptiveBank,
|
|
demoBundle: loadDemoBundleFile(t),
|
|
}
|
|
adaptiveRequired, err := domain.RequiredPublishedAssessmentFamilies(adaptiveVersion.Policy())
|
|
if err != nil {
|
|
t.Fatalf("read adaptive policy family requirement: %v", err)
|
|
}
|
|
var publishedBackendFamilies int32
|
|
if err := harness.pool.QueryRow(ctx, `
|
|
SELECT count(DISTINCT family_key)::integer
|
|
FROM assessment_families
|
|
WHERE category='backend' AND lifecycle='published' AND review_status='approved'`).Scan(&publishedBackendFamilies); err != nil {
|
|
t.Fatalf("count current backend families for adaptive opening: %v", err)
|
|
}
|
|
if publishedBackendFamilies < adaptiveRequired {
|
|
adaptiveBundle := adaptiveFixture.reviewedBundle(int(adaptiveRequired - publishedBackendFamilies))
|
|
adaptiveBundle.Name = "availability-adaptive-backend"
|
|
adaptiveBundle.Category = "backend"
|
|
for index := range adaptiveBundle.Families {
|
|
adaptiveBundle.Families[index].Key = fmt.Sprintf("availability-adaptive-backend-%02d", index+1)
|
|
adaptiveBundle.Families[index].Specialization = string(domain.SpecializationBackend)
|
|
}
|
|
if _, err := adaptiveBank.ImportBundle(ctx, adaptiveBundle); err != nil {
|
|
t.Fatalf("import additional reviewed backend families for adaptive opening: %v", err)
|
|
}
|
|
publishAssessmentAttemptFixtureFamilies(ctx, t, adaptiveBank, adaptiveBundle)
|
|
}
|
|
openAssessmentAttemptFixtureCategory(
|
|
ctx, t, adaptiveBank, adaptiveVersion.ID(), domain.AssessmentCategory("backend"),
|
|
domain.SpecializationBackend, domain.GradeJunior,
|
|
)
|
|
adaptiveCandidate := createSessionHTTPUser(
|
|
ctx, t, harness.sessionHTTPHarness, "availability-adaptive-candidate@example.test", passwordHash, true,
|
|
)
|
|
if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step='candidate_questionnaire' WHERE id=$1", adaptiveCandidate.ID); err != nil {
|
|
t.Fatalf("set adaptive candidate onboarding step: %v", err)
|
|
}
|
|
adaptiveCookie, adaptiveCSRF := loginConsentHTTP(
|
|
t, harness.sessionHTTPHarness, adaptiveCandidate.Email.Address(), "203.0.113.63:1234",
|
|
)
|
|
if response := assessmentAvailabilityBackendQuestionnaireRequest(t, harness, adaptiveCookie.Value, adaptiveCSRF, "203.0.113.64:1234"); response.Code != http.StatusOK {
|
|
t.Fatalf("save adaptive candidate questionnaire = %d %s", response.Code, response.Body.String())
|
|
}
|
|
grantCurrentAttemptConsent(t, harness, adaptiveCookie, adaptiveCSRF, "203.0.113.65:1234")
|
|
unsupported := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, path, "", "", adaptiveCookie.Value, "", "", "203.0.113.66:1234")
|
|
requireSessionProblem(t, unsupported, http.StatusNotImplemented, "not_implemented")
|
|
var rootCountBefore, idempotencyBefore int64
|
|
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM assessment_attempts WHERE user_id=$1 AND kind='root'", adaptiveCandidate.ID).
|
|
Scan(&rootCountBefore); err != nil {
|
|
t.Fatalf("read adaptive candidate root attempt count before denied POST: %v", err)
|
|
}
|
|
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM idempotency_records").Scan(&idempotencyBefore); err != nil {
|
|
t.Fatalf("read idempotency count before denied adaptive POST: %v", err)
|
|
}
|
|
adaptiveCreate := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts",
|
|
assessmentAttemptCreateBodyWithGrade(t, "backend", "junior"), sessionHTTPTestOrigin,
|
|
adaptiveCookie.Value, adaptiveCSRF, "availability-create-adaptive-denied", "203.0.113.67:1234")
|
|
requireSessionProblem(t, adaptiveCreate, http.StatusConflict, "state_conflict")
|
|
var rootCountAfter int64
|
|
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM assessment_attempts WHERE user_id=$1 AND kind='root'", adaptiveCandidate.ID).
|
|
Scan(&rootCountAfter); err != nil {
|
|
t.Fatalf("read root attempts after unsupported adaptive create: %v", err)
|
|
}
|
|
var idempotencyAfter int64
|
|
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM idempotency_records").Scan(&idempotencyAfter); err != nil {
|
|
t.Fatalf("read idempotency count after denied adaptive POST: %v", err)
|
|
}
|
|
if rootCountAfter != rootCountBefore {
|
|
t.Fatalf("unsupported adaptive create changed root attempt count from %d to %d", rootCountBefore, rootCountAfter)
|
|
}
|
|
if idempotencyAfter != idempotencyBefore+1 {
|
|
t.Fatalf("unsupported adaptive create idempotency row count = %d, want one immutable 409 outcome after %d", idempotencyAfter, idempotencyBefore)
|
|
}
|
|
replayedAdaptiveCreate := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts",
|
|
assessmentAttemptCreateBodyWithGrade(t, "backend", "junior"), sessionHTTPTestOrigin,
|
|
adaptiveCookie.Value, adaptiveCSRF, "availability-create-adaptive-denied", "203.0.113.68:1234")
|
|
requireSessionProblem(t, replayedAdaptiveCreate, http.StatusConflict, "state_conflict")
|
|
var idempotencyAfterReplay int64
|
|
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM idempotency_records").Scan(&idempotencyAfterReplay); err != nil {
|
|
t.Fatalf("read idempotency count after adaptive 409 replay: %v", err)
|
|
}
|
|
if idempotencyAfterReplay != idempotencyAfter {
|
|
t.Fatalf("adaptive 409 replay added idempotency rows: before replay=%d after=%d", idempotencyAfter, idempotencyAfterReplay)
|
|
}
|
|
}
|
|
|
|
func assessmentAvailabilityBackendQuestionnaireRequest(
|
|
t *testing.T,
|
|
harness *assessmentAttemptHTTPHarness,
|
|
cookie, csrf, remoteAddr string,
|
|
) *httptest.ResponseRecorder {
|
|
t.Helper()
|
|
body, err := json.Marshal(map[string]any{
|
|
"expected_version": 0,
|
|
"specializations": []any{
|
|
map[string]any{
|
|
"specialization": "backend", "self_assessed_grade": "junior", "task_languages": []string{"go"},
|
|
"stack": []string{}, "experience": nil,
|
|
},
|
|
},
|
|
"work_context": map[string]any{"work_formats": []string{"remote"}},
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("marshal backend-only adaptive questionnaire: %v", err)
|
|
}
|
|
return assessmentAttemptHTTPRequest(t, harness, http.MethodPut, "/api/v1/me/questionnaire", string(body),
|
|
sessionHTTPTestOrigin, cookie, csrf, "", remoteAddr)
|
|
}
|
|
|
|
func createAssessmentAvailabilityEmployer(
|
|
ctx context.Context,
|
|
t *testing.T,
|
|
harness *sessionHTTPHarness,
|
|
email string,
|
|
passwordHash domain.PasswordHash,
|
|
) 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: harness.clock.Now().Truncate(time.Microsecond),
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("NewUser(employer) error = %v", err)
|
|
}
|
|
if err := harness.store.Users().Create(ctx, user); err != nil {
|
|
t.Fatalf("Create synthetic employer: %v", err)
|
|
}
|
|
verified, err := harness.store.Users().MarkEmailVerified(ctx, user.ID, user.RegistrationVersion,
|
|
harness.clock.Now().Add(time.Microsecond))
|
|
if err != nil {
|
|
t.Fatalf("MarkEmailVerified(employer) error = %v", err)
|
|
}
|
|
return verified
|
|
}
|
|
|
|
func findAssessmentAvailabilitySpecialization(
|
|
t *testing.T,
|
|
availability assessmentAvailabilityHTTPProjection,
|
|
want string,
|
|
) assessmentAvailabilityHTTPSpecialization {
|
|
t.Helper()
|
|
for _, specialization := range availability.Specializations {
|
|
if specialization.Specialization == want {
|
|
return specialization
|
|
}
|
|
}
|
|
t.Fatalf("availability does not contain specialization %q", want)
|
|
return assessmentAvailabilityHTTPSpecialization{}
|
|
}
|
|
|
|
func findAssessmentAvailabilityGrade(
|
|
t *testing.T,
|
|
specialization assessmentAvailabilityHTTPSpecialization,
|
|
want string,
|
|
) assessmentAvailabilityHTTPGrade {
|
|
t.Helper()
|
|
for _, grade := range specialization.Grades {
|
|
if grade.Grade == want {
|
|
return grade
|
|
}
|
|
}
|
|
t.Fatalf("availability for %q does not contain grade %q", specialization.Specialization, want)
|
|
return assessmentAvailabilityHTTPGrade{}
|
|
}
|
|
|
|
func TestAssessmentDisclosedFamilyCutoffUsesItemDisclosureTime(t *testing.T) {
|
|
env := bootstrap(t, postgresService, redisService)
|
|
ctx, cancel := context.WithTimeout(t.Context(), assessmentAttemptHTTPTimeout)
|
|
defer cancel()
|
|
databaseURL := env.createIsolatedDatabase(ctx, t)
|
|
applyMigrations(ctx, t, databaseURL)
|
|
isolatedEnv := *env
|
|
isolatedEnv.Config.DatabaseURL = databaseURL
|
|
harness := newAssessmentAttemptHTTPHarness(ctx, t, &isolatedEnv)
|
|
seedAssessmentAttemptHTTPBank(ctx, t, harness.pool)
|
|
|
|
passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass)
|
|
if err != nil {
|
|
t.Fatalf("HashNewPassword() error = %v", err)
|
|
}
|
|
candidate := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "availability-owner@example.test", passwordHash, true)
|
|
if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step='candidate_questionnaire' WHERE id=$1", candidate.ID); err != nil {
|
|
t.Fatalf("set candidate onboarding step: %v", err)
|
|
}
|
|
cookie, csrf := loginConsentHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address(), "203.0.113.40:1234")
|
|
if response := assessmentAttemptQuestionnaireRequest(t, harness, cookie.Value, csrf, "203.0.113.41:1234"); response.Code != http.StatusOK {
|
|
t.Fatalf("save candidate questionnaire = %d %s", response.Code, response.Body.String())
|
|
}
|
|
grantCurrentAttemptConsent(t, harness, cookie, csrf, "203.0.113.42:1234")
|
|
|
|
create := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts",
|
|
assessmentAttemptCreateBody(t, "backend"), sessionHTTPTestOrigin, cookie.Value, csrf,
|
|
"availability-disclosure-create", "203.0.113.43:1234")
|
|
var attempt assessmentAnswerHTTPAttempt
|
|
if create.Code != http.StatusCreated || json.Unmarshal(create.Body.Bytes(), &attempt) != nil || attempt.ID == uuid.Nil {
|
|
t.Fatalf("create real attempt = %d %s", create.Code, create.Body.String())
|
|
}
|
|
items := readAssessmentAnswerHTTPItems(t, ctx, harness, attempt.ID)
|
|
if len(items) < 3 {
|
|
t.Fatalf("frozen item count = %d, want at least three items", len(items))
|
|
}
|
|
var createdAt time.Time
|
|
if err := harness.pool.QueryRow(ctx, "SELECT created_at FROM assessment_attempts WHERE id=$1", attempt.ID).Scan(&createdAt); err != nil {
|
|
t.Fatalf("read attempt creation time: %v", err)
|
|
}
|
|
since := createdAt.UTC().Add(time.Microsecond)
|
|
|
|
firstAnswer := assessmentAnswerHTTPBodyWithCorrectness(t, attempt.Version, items[0], false)
|
|
accepted := assessmentAttemptHTTPRequest(t, harness, http.MethodPost,
|
|
"/api/v1/me/assessment-attempts/"+attempt.ID.String()+"/answers", string(firstAnswer),
|
|
sessionHTTPTestOrigin, cookie.Value, csrf, "availability-disclosure-answer", "203.0.113.44:1234")
|
|
if accepted.Code != http.StatusOK {
|
|
t.Fatalf("answer first item = %d %s", accepted.Code, accepted.Body.String())
|
|
}
|
|
_, answeredAt := readAssessmentAnswerHTTPItem(t, ctx, harness, attempt.ID, items[0].ID)
|
|
if !answeredAt.After(since) {
|
|
t.Fatalf("first answer timestamp %s must be after cutoff %s to establish distinct disclosure times", answeredAt, since)
|
|
}
|
|
|
|
familyKey := func(itemID uuid.UUID) domain.AssessmentFamilyKey {
|
|
t.Helper()
|
|
var stored string
|
|
if err := harness.pool.QueryRow(ctx, "SELECT family_key FROM assessment_attempt_items WHERE attempt_id=$1 AND id=$2", attempt.ID, itemID).Scan(&stored); err != nil {
|
|
t.Fatalf("read frozen item family key: %v", err)
|
|
}
|
|
key, err := domain.ParseAssessmentFamilyKey(stored)
|
|
if err != nil {
|
|
t.Fatalf("parse frozen item family key: %v", err)
|
|
}
|
|
return key
|
|
}
|
|
firstKey, secondKey, thirdKey := familyKey(items[0].ID), familyKey(items[1].ID), familyKey(items[2].ID)
|
|
var disclosed []domain.AssessmentFamilyKey
|
|
transactor := postgres.NewTransactor(harness.pool)
|
|
if err := transactor.WithinTransaction(ctx, func(txctx context.Context, unit outbound.UnitOfWork) error {
|
|
var readErr error
|
|
disclosed, readErr = unit.AssessmentAttempts().ListDisclosedFamilyKeys(txctx, candidate.ID, since)
|
|
return readErr
|
|
}); err != nil {
|
|
t.Fatalf("read disclosed family keys after the rolling cutoff: %v", err)
|
|
}
|
|
contains := func(want domain.AssessmentFamilyKey) bool {
|
|
for _, key := range disclosed {
|
|
if key == want {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
if contains(firstKey) || !contains(secondKey) || contains(thirdKey) {
|
|
t.Fatalf("disclosed families = %v; want first excluded, second included, and future third excluded", disclosed)
|
|
}
|
|
|
|
var countBefore int32
|
|
var latestBefore bool
|
|
if err := transactor.WithinTransaction(ctx, func(txctx context.Context, unit outbound.UnitOfWork) error {
|
|
var readErr error
|
|
countBefore, readErr = unit.AssessmentAttempts().CountRootAttemptsSince(txctx, candidate.ID, nil, createdAt.Add(-time.Second))
|
|
if readErr != nil {
|
|
return readErr
|
|
}
|
|
_, latestBefore, readErr = unit.AssessmentAttempts().GetLatestRootForSpecialization(
|
|
txctx, candidate.ID, domain.SpecializationBackend, nil,
|
|
)
|
|
return readErr
|
|
}); err != nil {
|
|
t.Fatalf("read eligible root quota and retry history: %v", err)
|
|
}
|
|
if countBefore != 1 || !latestBefore {
|
|
t.Fatalf("eligible root before platform failure = count %d/latest %v, want 1/true", countBefore, latestBefore)
|
|
}
|
|
if _, err := harness.pool.Exec(ctx, `
|
|
WITH failure_time AS (SELECT clock_timestamp() AS at)
|
|
UPDATE assessment_attempts
|
|
SET state='insufficient_bank',
|
|
updated_at=failure_time.at,
|
|
ended_at=failure_time.at,
|
|
version=version+1
|
|
FROM failure_time
|
|
WHERE id=$1`, attempt.ID); err != nil {
|
|
t.Fatalf("mark isolated attempt as a system bank failure: %v", err)
|
|
}
|
|
var countAfter int32
|
|
var latestAfter bool
|
|
var quotaAfter outbound.AssessmentRootQuotaSnapshot
|
|
if err := transactor.WithinTransaction(ctx, func(txctx context.Context, unit outbound.UnitOfWork) error {
|
|
var readErr error
|
|
countAfter, readErr = unit.AssessmentAttempts().CountRootAttemptsSince(txctx, candidate.ID, nil, createdAt.Add(-time.Second))
|
|
if readErr != nil {
|
|
return readErr
|
|
}
|
|
_, latestAfter, readErr = unit.AssessmentAttempts().GetLatestRootForSpecialization(
|
|
txctx, candidate.ID, domain.SpecializationBackend, nil,
|
|
)
|
|
if readErr != nil {
|
|
return readErr
|
|
}
|
|
asOf, timeErr := unit.AssessmentBank().DatabaseTime(txctx)
|
|
if timeErr != nil {
|
|
return timeErr
|
|
}
|
|
quotaAfter, readErr = unit.AssessmentAttempts().GetRootQuotaSnapshot(
|
|
txctx, candidate.ID, createdAt.Add(-time.Second), asOf, 24*time.Hour, 1,
|
|
)
|
|
return readErr
|
|
}); err != nil {
|
|
t.Fatalf("read quota and retry history after platform failure: %v", err)
|
|
}
|
|
if countAfter != 0 || latestAfter || quotaAfter.Count != 0 || quotaAfter.AvailableAt != nil {
|
|
t.Fatalf("platform failure remains in availability history: count=%d latest=%v quota=%+v, want excluded", countAfter, latestAfter, quotaAfter)
|
|
}
|
|
}
|