Files
lincodex/backend/integration_test/manual_assessment_request_test.go
T

303 lines
17 KiB
Go

//go:build integration
package integration_test
import (
"context"
"encoding/json"
"fmt"
"net/http"
"testing"
"time"
"github.com/google/uuid"
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/usecase/consent"
)
const manualAssessmentHTTPTimeout = 8 * time.Minute
const manualAssessmentBody = `{"type":"manual_assessment","description":"I do not consent to automated categorization.","assessment_target":{"specialization":"backend","grade":"junior"}}`
// TestManualAssessmentRequestAfterC3Refusal drives the real router through a
// C3 refusal and the manual assessment request that replaces the automated
// path. The request must neither depend on C3 nor change it, and it must leave
// existing attempts and results untouched.
func TestManualAssessmentRequestAfterC3Refusal(t *testing.T) {
env := bootstrap(t, postgresService, redisService)
ctx, cancel := context.WithTimeout(t.Context(), manualAssessmentHTTPTimeout)
defer cancel()
databaseURL := env.createIsolatedDatabase(ctx, t)
applyMigrations(ctx, t, databaseURL)
isolatedEnv := *env
isolatedEnv.Config.DatabaseURL = databaseURL
harness := newSupportCaseHTTPHarness(ctx, t, &isolatedEnv)
productPolicy, _, _, _ := seedSupportManualRubric(ctx, t, harness)
passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass)
if err != nil {
t.Fatalf("HashNewPassword() error = %v", err)
}
reader := consent.NewQueryService(postgresadapter.NewConsentStore(harness.pool), time.Now)
t.Run("refusal before the first test", func(t *testing.T) {
candidate := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "manual-before-test@example.test", passwordHash, true)
cookie, csrf := loginConsentHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address(), "198.51.100.10:1234")
grantManualAssessmentC3(t, harness, cookie, csrf, "198.51.100.11:1234")
revokeManualAssessmentC3(t, harness, cookie, csrf, "198.51.100.12:1234")
requireManualAssessmentC3Inactive(ctx, t, reader, candidate.ID)
consentBefore := consentLedgerSnapshot(ctx, t, harness, candidate.ID)
created := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", manualAssessmentBody,
cookie.Value, csrf, "manual-before-test-1", "198.51.100.13:1234")
var request supportCaseHTTPResponse
if created.Code != http.StatusCreated || json.Unmarshal(created.Body.Bytes(), &request) != nil {
t.Fatalf("manual request after C3 revocation = %d %s, want 201", created.Code, created.Body.String())
}
if request.Type != "manual_assessment" || request.Status != "waiting_expert" || request.Decision != nil ||
request.RubricVersion == nil || *request.RubricVersion != productPolicy.Version() {
t.Fatalf("created request = %+v, want waiting_expert without a decision, pinned to rubric version %d", request, productPolicy.Version())
}
if len(request.History) != 2 || request.History[1].Actor != "system" || request.History[1].Status != "waiting_expert" {
t.Fatalf("request history = %+v, want creation and a system move to the expert queue", request.History)
}
if request.AssessmentTarget == nil || request.AssessmentTarget.Specialization != "backend" || request.AssessmentTarget.Grade != "junior" ||
request.Description != "I do not consent to automated categorization." {
t.Fatalf("request target/reason = %+v / %q, want backend junior and the stated reason", request.AssessmentTarget, request.Description)
}
read := supportCaseHTTP(t, harness, http.MethodGet, "/api/v1/me/support-cases/"+request.ID, "", cookie.Value, "", "", "198.51.100.14:1234")
if read.Code != http.StatusOK || read.Body.String() != created.Body.String() {
t.Fatalf("manual request GET = %d %s, want the created case %s", read.Code, read.Body.String(), created.Body.String())
}
// The request is not a consent action and not an assessment action.
requireManualAssessmentC3Inactive(ctx, t, reader, candidate.ID)
if after := consentLedgerSnapshot(ctx, t, harness, candidate.ID); after != consentBefore {
t.Fatalf("manual request changed the consent ledger or its events:\nbefore %s\nafter %s", consentBefore, after)
}
if got := userAssessmentSnapshot(ctx, t, harness, candidate.ID); got != "[]|[]" {
t.Fatalf("manual request created assessment rows %s, want no attempt and no result", got)
}
// A page reload loses the form's idempotency key: a new key must not
// create a second case, and the same key still replays the first.
reload := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", manualAssessmentBody,
cookie.Value, csrf, "manual-before-test-2", "198.51.100.15:1234")
requireSessionProblem(t, reload, http.StatusConflict, "state_conflict")
replay := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", manualAssessmentBody,
cookie.Value, csrf, "manual-before-test-1", "198.51.100.16:1234")
if replay.Code != http.StatusCreated || replay.Body.String() != created.Body.String() {
t.Fatalf("same-key replay = %d %s, want the original case", replay.Code, replay.Body.String())
}
assertSupportCaseCount(t, ctx, harness, candidate.ID, 1)
if after := consentLedgerSnapshot(ctx, t, harness, candidate.ID); after != consentBefore {
t.Fatalf("repeated manual requests changed the consent ledger or its events")
}
})
t.Run("unavailable rubric is stored as unavailable", func(t *testing.T) {
candidate := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "manual-no-rubric@example.test", passwordHash, true)
cookie, csrf := loginConsentHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address(), "198.51.100.20:1234")
body := `{"type":"manual_assessment","description":"No automated bank exists for this target.","assessment_target":{"specialization":"backend","grade":"senior"}}`
created := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", body,
cookie.Value, csrf, "manual-no-rubric-1", "198.51.100.21:1234")
var request supportCaseHTTPResponse
if created.Code != http.StatusCreated || json.Unmarshal(created.Body.Bytes(), &request) != nil ||
request.Status != "waiting_expert" || request.RubricVersion != nil || request.Decision != nil {
t.Fatalf("manual request without a published rubric = %d %s, want waiting_expert with a null rubric version", created.Code, created.Body.String())
}
var storedVersion *int32
var storedOpening *uuid.UUID
if err := harness.pool.QueryRow(ctx, `SELECT rubric_version, rubric_opening_id FROM support_cases WHERE id = $1::uuid`, request.ID).
Scan(&storedVersion, &storedOpening); err != nil || storedVersion != nil || storedOpening != nil {
t.Fatalf("stored rubric pin = %v/%v, %v; want none", storedVersion, storedOpening, err)
}
})
t.Run("failed first test and missing attempt reference", func(t *testing.T) {
candidate := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "manual-after-failure@example.test", passwordHash, true)
cookie, csrf := loginConsentHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address(), "198.51.100.30:1234")
attemptID := completeManualAssessmentFixtureAttempt(ctx, t, harness, candidate.ID, cookie, csrf, "198.51.100.3", false)
revokeManualAssessmentC3(t, harness, cookie, csrf, "198.51.100.39:1234")
requireManualAssessmentC3Inactive(ctx, t, reader, candidate.ID)
// The snapshot is taken after the revocation on purpose: the fixture attempt
// needs a granted C3, so the ledger legitimately changes until then. Only
// changes made by the manual request itself are being checked.
consentBefore := consentLedgerSnapshot(ctx, t, harness, candidate.ID)
assessmentBefore := userAssessmentSnapshot(ctx, t, harness, candidate.ID)
if assessmentBefore == "[]|[]" {
t.Fatal("fixture did not store a failed attempt and its result")
}
// The refusal and the failed first test do not block the request. The
// failed attempt is accepted as the optional reference; it is not changed.
withReferenceBody := fmt.Sprintf(`{"type":"manual_assessment","description":"Please assess this specialization.","assessment_target":{"specialization":"backend","grade":"junior"},"object":{"type":"assessment_attempt","id":%q}}`, attemptID)
withReference := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", withReferenceBody,
cookie.Value, csrf, "manual-failure-1", "198.51.100.40:1234")
var referenced supportCaseHTTPResponse
if withReference.Code != http.StatusCreated || json.Unmarshal(withReference.Body.Bytes(), &referenced) != nil ||
referenced.Status != "waiting_expert" || referenced.Decision != nil {
t.Fatalf("manual request referencing the failed attempt = %d %s, want waiting_expert without a decision", withReference.Code, withReference.Body.String())
}
if got := userAssessmentSnapshot(ctx, t, harness, candidate.ID); got != assessmentBefore {
t.Fatalf("manual request changed attempts or results:\nbefore %s\nafter %s", assessmentBefore, got)
}
if after := consentLedgerSnapshot(ctx, t, harness, candidate.ID); after != consentBefore {
t.Fatal("manual request changed the consent ledger or its events")
}
requireManualAssessmentC3Inactive(ctx, t, reader, candidate.ID)
// A reload creates a new key: still one open case, attempts unchanged.
reload := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", withReferenceBody,
cookie.Value, csrf, "manual-failure-2", "198.51.100.41:1234")
requireSessionProblem(t, reload, http.StatusConflict, "state_conflict")
assertSupportCaseCount(t, ctx, harness, candidate.ID, 1)
if got := userAssessmentSnapshot(ctx, t, harness, candidate.ID); got != assessmentBefore {
t.Fatalf("repeated manual request changed attempts or results:\nbefore %s\nafter %s", assessmentBefore, got)
}
})
t.Run("confirmed result is kept", func(t *testing.T) {
candidate := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "manual-after-confirmation@example.test", passwordHash, true)
cookie, csrf := loginConsentHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address(), "198.51.100.50:1234")
completeManualAssessmentFixtureAttempt(ctx, t, harness, candidate.ID, cookie, csrf, "198.51.100.5", true)
revokeManualAssessmentC3(t, harness, cookie, csrf, "198.51.100.59:1234")
assessmentBefore := userAssessmentSnapshot(ctx, t, harness, candidate.ID)
created := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", manualAssessmentBody,
cookie.Value, csrf, "manual-confirmed-1", "198.51.100.60:1234")
if created.Code != http.StatusCreated {
t.Fatalf("manual request after a confirmed result = %d %s, want 201", created.Code, created.Body.String())
}
if got := userAssessmentSnapshot(ctx, t, harness, candidate.ID); got != assessmentBefore {
t.Fatalf("manual request changed the confirmed result or attempts:\nbefore %s\nafter %s", assessmentBefore, got)
}
requireManualAssessmentC3Inactive(ctx, t, reader, candidate.ID)
})
}
func grantManualAssessmentC3(t *testing.T, harness *supportCaseHTTPHarness, cookie *http.Cookie, csrf, remoteAddr string) {
t.Helper()
text := harness.request(t, http.MethodGet, "/api/v1/me/consent-texts/c3", "", "", cookie.Value, "", remoteAddr)
var current struct {
TextVersion string `json:"text_version"`
}
if text.Code != http.StatusOK || json.Unmarshal(text.Body.Bytes(), &current) != nil || current.TextVersion == "" {
t.Fatalf("read current C3 text = %d %s", text.Code, text.Body.String())
}
if grant := consentGrantHTTP(t, harness.sessionHTTPHarness, cookie, csrf, "c3", current.TextVersion, sessionHTTPTestOrigin); grant.Code != http.StatusOK {
t.Fatalf("grant C3 = %d %s", grant.Code, grant.Body.String())
}
}
func revokeManualAssessmentC3(t *testing.T, harness *supportCaseHTTPHarness, cookie *http.Cookie, csrf, remoteAddr string) {
t.Helper()
revoked := harness.request(t, http.MethodDelete, "/api/v1/me/consents/c3", "", sessionHTTPTestOrigin, cookie.Value, csrf, remoteAddr)
if revoked.Code != http.StatusNoContent {
t.Fatalf("revoke C3 = %d %s, want 204", revoked.Code, revoked.Body.String())
}
}
func requireManualAssessmentC3Inactive(ctx context.Context, t *testing.T, reader *consent.QueryService, subject uuid.UUID) {
t.Helper()
active, err := reader.HasCurrentConsent(ctx, subject, domain.ConsentPurposeAutoCategorization)
if err != nil || active {
t.Fatalf("current C3 = %v, %v; want no active C3", active, err)
}
}
// consentLedgerSnapshot returns every consent row and the count of consent
// events of the subject, so a test can prove a command left both unchanged.
func consentLedgerSnapshot(ctx context.Context, t *testing.T, harness *supportCaseHTTPHarness, subject uuid.UUID) string {
t.Helper()
var records string
var events int64
if err := harness.pool.QueryRow(ctx, `SELECT COALESCE(jsonb_agg(to_jsonb(record) ORDER BY record.id)::text, '[]')
FROM consent_records AS record WHERE record.subject_id = $1`, subject).Scan(&records); err != nil {
t.Fatalf("read consent ledger: %v", err)
}
if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM outbox_events
WHERE event_type LIKE 'consent.%' AND payload->>'subject_id' = $1`, subject.String()).Scan(&events); err != nil {
t.Fatalf("count consent events: %v", err)
}
return fmt.Sprintf("%s|events=%d", records, events)
}
// userAssessmentSnapshot returns the attempts and the immutable results of one
// account as stable JSON, joined by "|".
func userAssessmentSnapshot(ctx context.Context, t *testing.T, harness *supportCaseHTTPHarness, userID uuid.UUID) string {
t.Helper()
var attempts, results string
if err := harness.pool.QueryRow(ctx, `SELECT COALESCE(jsonb_agg(to_jsonb(attempt) ORDER BY attempt.id)::text, '[]')
FROM assessment_attempts AS attempt WHERE attempt.user_id = $1`, userID).Scan(&attempts); err != nil {
t.Fatalf("read assessment attempts: %v", err)
}
if err := harness.pool.QueryRow(ctx, `SELECT COALESCE(jsonb_agg(to_jsonb(result) ORDER BY result.attempt_id)::text, '[]')
FROM assessment_attempt_results AS result WHERE result.user_id = $1`, userID).Scan(&results); err != nil {
t.Fatalf("read assessment results: %v", err)
}
return attempts + "|" + results
}
// completeManualAssessmentFixtureAttempt grants C3 (an automated attempt needs
// it), runs one real Backend/Junior attempt to completion, and answers every
// item correctly or incorrectly.
func completeManualAssessmentFixtureAttempt(
ctx context.Context,
t *testing.T,
harness *supportCaseHTTPHarness,
userID uuid.UUID,
cookie *http.Cookie,
csrf, remotePrefix string,
correct bool,
) uuid.UUID {
t.Helper()
attemptHarness := &assessmentAttemptHTTPHarness{sessionHTTPHarness: harness.sessionHTTPHarness, keyring: harness.keyring}
if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step='candidate_questionnaire' WHERE id=$1", userID); err != nil {
t.Fatalf("set candidate onboarding step: %v", err)
}
questionnaire := `{"expected_version":0,"specializations":[{"specialization":"backend","self_assessed_grade":"junior","task_languages":["go"],"stack":[],"experience":null}],"work_context":{"work_formats":["remote"]}}`
if response := assessmentAttemptHTTPRequest(t, attemptHarness, http.MethodPut, "/api/v1/me/questionnaire", questionnaire,
sessionHTTPTestOrigin, cookie.Value, csrf, "", remotePrefix+"1:1234"); response.Code != http.StatusOK {
t.Fatalf("save candidate questionnaire = %d %s", response.Code, response.Body.String())
}
grantManualAssessmentC3(t, harness, cookie, csrf, remotePrefix+"2:1234")
create := assessmentAttemptHTTPRequest(t, attemptHarness, http.MethodPost, "/api/v1/me/assessment-attempts",
assessmentAttemptCreateBody(t, "backend"), sessionHTTPTestOrigin, cookie.Value, csrf, "manual-fixture-create-"+userID.String(), remotePrefix+"3:1234")
var attempt assessmentAnswerHTTPAttempt
if create.Code != http.StatusCreated || json.Unmarshal(create.Body.Bytes(), &attempt) != nil || attempt.ID == uuid.Nil {
t.Fatalf("create fixture attempt = %d %s", create.Code, create.Body.String())
}
version := attempt.Version
for _, item := range readAssessmentAnswerHTTPItems(t, ctx, attemptHarness, attempt.ID) {
body := assessmentAnswerHTTPBodyWithCorrectness(t, version, item, correct)
response := assessmentAttemptHTTPRequest(t, attemptHarness, http.MethodPost,
"/api/v1/me/assessment-attempts/"+attempt.ID.String()+"/answers", string(body),
sessionHTTPTestOrigin, cookie.Value, csrf, fmt.Sprintf("manual-fixture-answer-%s-%d", userID, item.Ordinal), remotePrefix+"4:1234")
var next assessmentAnswerHTTPAttempt
if response.Code != http.StatusOK || json.Unmarshal(response.Body.Bytes(), &next) != nil {
t.Fatalf("answer fixture item %d = %d %s", item.Ordinal, response.Code, response.Body.String())
}
version = next.Version
}
finalizeBody := fmt.Sprintf(`{"expected_version":%d}`, version)
finalized := assessmentAttemptHTTPRequest(t, attemptHarness, http.MethodPost,
"/api/v1/me/assessment-attempts/"+attempt.ID.String()+"/finalize", finalizeBody,
sessionHTTPTestOrigin, cookie.Value, csrf, "manual-fixture-finalize-"+userID.String(), remotePrefix+"5:1234")
var completed assessmentAnswerHTTPAttempt
if finalized.Code != http.StatusOK || json.Unmarshal(finalized.Body.Bytes(), &completed) != nil || completed.State != "completed" {
t.Fatalf("finalize fixture attempt = %d %s, want completed", finalized.Code, finalized.Body.String())
}
wantOutcome := "not_confirmed"
if correct {
wantOutcome = "confirmed"
}
var outcome string
if err := harness.pool.QueryRow(ctx, `SELECT outcome FROM assessment_attempt_results WHERE attempt_id = $1`, attempt.ID).Scan(&outcome); err != nil || outcome != wantOutcome {
t.Fatalf("stored fixture outcome = %q, %v; want %q", outcome, err, wantOutcome)
}
return attempt.ID
}