//go:build integration package integration_test import ( "context" "encoding/json" "fmt" "net/http" "slices" "strings" "testing" "github.com/google/uuid" "lincodex/backend/internal/domain" "lincodex/backend/internal/usecase/assessment" ) // choiceTableBankFamilies returns the families of a bank that offers every new // answer format: a choice family whose distractors come from error models, a // table family with integer answers, and a table family with choice answers. // They reuse the rubric and the identity of the first demo family. func choiceTableBankFamilies(t *testing.T, base assessment.BundleFamily) []assessment.BundleFamily { t.Helper() choice := base choice.Key = "choice-lru-hits" choice.SeedGenerator = domain.AssessmentSeedGenerator{ Algorithm: "lru_hits_choice.v1", Parameters: map[string]domain.AssessmentParameterRange{ "accesses": {Min: 12, Max: 30}, "keys": {Min: 4, Max: 8}, "capacity": {Min: 2, Max: 4}, }, StatementTemplate: "A cache of capacity {{.capacity}} drops its least recently used key when it is full. Keys are read in this order: {{.sequence}}. How many reads find their key in the cache?", } choice.AnswerKey = domain.AssessmentAnswerKey{AnswerFormat: domain.AnswerFormatChoice, ReferenceSolution: "Simulate the cache."} integerTable := base integerTable.Key = "table-integer-limits" integerTable.SeedGenerator = domain.AssessmentSeedGenerator{ StatementTemplate: "A pool opens {{.connections}} connections at most and each request holds one for {{.seconds}} seconds. How many requests per minute can it serve at most?", Table: &domain.AssessmentVariantTable{Rows: []domain.AssessmentVariantRow{ {Values: map[string]string{"connections": "10", "seconds": "2"}, Answer: "300"}, {Values: map[string]string{"connections": "4", "seconds": "3"}, Answer: "80"}, {Values: map[string]string{"connections": "6", "seconds": "5"}, Answer: "72"}, {Values: map[string]string{"connections": "20", "seconds": "1"}, Answer: "1200"}, }}, } integerTable.AnswerKey = domain.AssessmentAnswerKey{AnswerFormat: domain.AnswerFormatInteger, ReferenceSolution: "Multiply by sixty and divide by the hold time."} choiceTable := base choiceTable.Key = "table-choice-status" choiceTable.SeedGenerator = domain.AssessmentSeedGenerator{ StatementTemplate: "Which status code does an API return for {{.situation}}?", Table: &domain.AssessmentVariantTable{Rows: []domain.AssessmentVariantRow{ {Values: map[string]string{"situation": "a resource that does not exist"}, Answer: "404", Distractors: []string{"400", "410", "500"}}, {Values: map[string]string{"situation": "a call without credentials"}, Answer: "401", Distractors: []string{"403", "407", "511"}}, {Values: map[string]string{"situation": "an update on a stale version"}, Answer: "412", Distractors: []string{"409", "422", "428"}}, }}, } choiceTable.AnswerKey = domain.AssessmentAnswerKey{AnswerFormat: domain.AnswerFormatChoice, ReferenceSolution: "Match the situation to the status code."} return []assessment.BundleFamily{choice, integerTable, choiceTable} } // allowedItemKeys are the fields that a candidate item may carry per format. var allowedItemContentKeys = map[string][]string{ "number": {"format", "unit"}, "choice": {"format", "multiple", "options"}, } func TestAssessmentChoiceAndTableFamiliesAreServedAndGradedOverHTTP(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) source := loadDemoBundleFile(t) source.Families = choiceTableBankFamilies(t, source.Families[0]) seedAssessmentAttemptHTTPBankFrom(ctx, t, harness.pool, nil, source) // The bank holds both kinds of generator: the table families are stored // with hash scheme 2 and the algorithmic family with scheme 1. for scheme, want := range map[int]bool{1: true, 2: true} { var stored int if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM assessment_families WHERE hash_scheme = $1`, scheme).Scan(&stored); err != nil || (stored > 0) != want { t.Fatalf("families with hash scheme %d = %d, %v, want some", scheme, stored, err) } } passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass) if err != nil { t.Fatalf("HashNewPassword() error = %v", err) } candidate := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "choice-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.140:1234") if response := assessmentAttemptQuestionnaireRequest(t, harness, cookie.Value, csrf, "203.0.113.141: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.142:1234") create := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", assessmentAttemptCreateBody(t, "backend"), sessionHTTPTestOrigin, cookie.Value, csrf, "choice-flow-create", "203.0.113.143:1234") if create.Code != http.StatusCreated { t.Fatalf("create real attempt = %d %s; logs: %s", create.Code, create.Body.String(), harness.logs.String()) } var attempt assessmentAnswerHTTPAttempt if err := json.Unmarshal(create.Body.Bytes(), &attempt); err != nil || attempt.ID == uuid.Nil || attempt.CurrentItem == nil { t.Fatalf("created attempt = %+v, decode error %v", attempt, err) } items := readAssessmentAnswerHTTPItems(t, ctx, harness, attempt.ID) formats := make(map[string]int) for _, item := range items { formats[item.Variant.AnswerFormat]++ } if formats[domain.AnswerFormatChoice] < 2 || formats[domain.AnswerFormatInteger] < 1 { t.Fatalf("frozen formats = %v, want at least two choice items and one integer item", formats) } attemptsPath := "/api/v1/me/assessment-attempts/" + attempt.ID.String() assertCandidateItem := func(label string, body []byte, item assessmentAnswerHTTPItem) { t.Helper() assertAssessmentChoiceItemDTO(t, label, body, item) } assertCandidateItem("create response", create.Body.Bytes(), items[0]) // Answers: a choice item alternates between a wrong and a correct option // (starting wrong), and every other item is answered correctly. version, choiceIndex := attempt.Version, 0 var wantCorrect []bool for _, item := range items { correct := true if item.Variant.AnswerFormat == domain.AnswerFormatChoice { correct = choiceIndex%2 == 1 choiceIndex++ } wantCorrect = append(wantCorrect, correct) if item.Ordinal == 1 { assertChoiceAnswerProblems(t, harness, attemptsPath, cookie.Value, csrf, version, item) } body := assessmentAnswerHTTPBodyWithCorrectness(t, version, item, correct) response := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, attemptsPath+"/answers", string(body), sessionHTTPTestOrigin, cookie.Value, csrf, fmt.Sprintf("choice-flow-item-%d", item.Ordinal), fmt.Sprintf("203.0.113.%d:1234", 150+item.Ordinal)) var next assessmentAnswerHTTPAttempt if response.Code != http.StatusOK || json.Unmarshal(response.Body.Bytes(), &next) != nil || next.Version != version+1 { t.Fatalf("answer item %d = %d %s, want version %d", item.Ordinal, response.Code, response.Body.String(), version+1) } if int(item.Ordinal) < len(items) { assertCandidateItem(fmt.Sprintf("response after item %d", item.Ordinal), response.Body.Bytes(), items[item.Ordinal]) } version = next.Version } // The wrong-then-correct alternation of the choice items reached the // result through the key: the server scored the first max_points items. finalizeBody, err := json.Marshal(map[string]int64{"expected_version": version}) if err != nil { t.Fatalf("marshal finalization: %v", err) } finalized := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, attemptsPath+"/finalize", string(finalizeBody), sessionHTTPTestOrigin, cookie.Value, csrf, "choice-flow-finalize", "203.0.113.190:1234") if finalized.Code != http.StatusOK { t.Fatalf("finalize = %d %s", finalized.Code, finalized.Body.String()) } result := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, attemptsPath+"/result", "", "", cookie.Value, "", "", "203.0.113.191:1234") var document struct { BasicScore struct { Points int `json:"points"` MaxPoints int `json:"max_points"` } `json:"basic_score"` } if result.Code != http.StatusOK || json.Unmarshal(result.Body.Bytes(), &document) != nil || document.BasicScore.MaxPoints < 1 { t.Fatalf("result = %d %s, want a basic score", result.Code, result.Body.String()) } wantPoints := 0 for _, correct := range wantCorrect[:document.BasicScore.MaxPoints] { if correct { wantPoints++ } } if document.BasicScore.Points != wantPoints || wantPoints == document.BasicScore.MaxPoints { t.Fatalf("score = %d of %d, want %d: every wrong choice scores nothing and every correct one scores", document.BasicScore.Points, document.BasicScore.MaxPoints, wantPoints) } for _, private := range []string{"ReferenceAnswer", "answer_key", "option_ids", "distractor"} { if strings.Contains(result.Body.String(), private) { t.Fatalf("result exposes %q: %s", private, result.Body.String()) } } // Every accepted answer left a signal observation; a choice is observed as // an answer of a small answer space, like an integer. var observed, choiceObserved int if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM assessment_answer_observations WHERE attempt_id=$1`, attempt.ID).Scan(&observed); err != nil || observed != len(items) { t.Fatalf("answer observations = %d, %v, want %d", observed, err, len(items)) } if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM assessment_answer_observations WHERE attempt_id=$1 AND answer_format='integer'`, attempt.ID).Scan(&choiceObserved); err != nil || choiceObserved != formats[domain.AnswerFormatChoice]+formats[domain.AnswerFormatInteger] { t.Fatalf("observations of the integer class = %d, %v, want %d", choiceObserved, err, formats[domain.AnswerFormatChoice]+formats[domain.AnswerFormatInteger]) } } // assertAssessmentChoiceItemDTO checks that the candidate sees the item of // the attempt in the allowlisted shape: for a choice item the opaque option // IDs and texts in the stored order, and no key or service field anywhere. func assertAssessmentChoiceItemDTO(t *testing.T, label string, body []byte, item assessmentAnswerHTTPItem) { t.Helper() var document struct { CurrentItem map[string]json.RawMessage `json:"current_item"` } if err := json.Unmarshal(body, &document); err != nil || document.CurrentItem == nil { t.Fatalf("%s: no current item in %s (%v)", label, body, err) } var itemKeys []string for key := range document.CurrentItem { itemKeys = append(itemKeys, key) } slices.Sort(itemKeys) var id uuid.UUID if !slices.Equal(itemKeys, []string{"content", "id", "prompt", "sequence"}) || json.Unmarshal(document.CurrentItem["id"], &id) != nil || id != item.ID { t.Fatalf("%s: item keys %v for item %s, want exactly content, id, prompt, and sequence of %s", label, itemKeys, id, item.ID) } var content map[string]json.RawMessage if err := json.Unmarshal(document.CurrentItem["content"], &content); err != nil { t.Fatalf("%s: decode content: %v", label, err) } var format string if err := json.Unmarshal(content["format"], &format); err != nil { t.Fatalf("%s: decode content format: %v", label, err) } var contentKeys []string for key := range content { contentKeys = append(contentKeys, key) } slices.Sort(contentKeys) if want, known := allowedItemContentKeys[format]; !known || !slices.Equal(contentKeys, want) { t.Fatalf("%s: content of format %q has keys %v, want %v", label, format, contentKeys, want) } if item.Variant.AnswerFormat == domain.AnswerFormatChoice { var options []map[string]string if err := json.Unmarshal(content["options"], &options); err != nil || len(options) != len(item.Variant.Options) { t.Fatalf("%s: options = %v, %v, want %d", label, options, err, len(item.Variant.Options)) } for position, option := range options { stored := item.Variant.Options[position] if len(option) != 2 || option["id"] != stored.ID || option["text"] != stored.Text { t.Fatalf("%s: option %d = %v, want only the ID and the text of the stored option", label, position, option) } } if string(content["multiple"]) != "false" { t.Fatalf("%s: multiple = %s, want false", label, content["multiple"]) } } for _, private := range []string{"ReferenceAnswer", "reference", "answer_key", "distractor", "mistake", "correct", "\"seed\"", "variant", "\"row\""} { if strings.Contains(string(body), private) { t.Fatalf("%s: candidate response contains %q: %s", label, private, body) } } } // assertChoiceAnswerProblems checks that an option the item does not have and // a selection of two options are refused as invalid input, without an answer // being stored. It is a no-op for an item that is not a choice. func assertChoiceAnswerProblems( t *testing.T, harness *assessmentAttemptHTTPHarness, attemptsPath, session, csrf string, version int64, item assessmentAnswerHTTPItem, ) { t.Helper() if item.Variant.AnswerFormat != domain.AnswerFormatChoice { return } for name, selection := range map[string][]string{ "an option of no item": {"onotanoption"}, "two options at once": {item.Variant.Options[0].ID, item.Variant.Options[1].ID}, } { encoded, err := json.Marshal(map[string]any{ "expected_version": version, "item_id": item.ID, "answer": map[string]any{"format": "choice", "option_ids": selection}, }) if err != nil { t.Fatalf("marshal %s: %v", name, err) } response := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, attemptsPath+"/answers", string(encoded), sessionHTTPTestOrigin, session, csrf, "choice-flow-bad-"+strings.ReplaceAll(name, " ", "-"), "203.0.113.149:1234") if response.Code != http.StatusBadRequest { t.Fatalf("answer with %s = %d %s, want 400", name, response.Code, response.Body.String()) } } }