Files
lincodex/backend/integration_test/assessment_answer_http_test.go
T

477 lines
24 KiB
Go

//go:build integration
package integration_test
import (
"context"
"encoding/json"
"fmt"
"net/http"
"strconv"
"strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgtype"
"lincodex/backend/internal/domain"
)
func TestAssessmentAnswerAndResultPersistAcrossRouterReconstruction(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, "answer-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,
"answer-flow-create", "203.0.113.43:1234")
if create.Code != http.StatusCreated {
t.Fatalf("create real attempt = %d %s; logs: %s", create.Code, create.Body.String(), harness.logs.String())
}
var publicAttempt assessmentAnswerHTTPAttempt
if err := json.Unmarshal(create.Body.Bytes(), &publicAttempt); err != nil || publicAttempt.ID == uuid.Nil || publicAttempt.CurrentItem == nil {
t.Fatalf("created attempt = %+v, decode error %v", publicAttempt, err)
}
items := readAssessmentAnswerHTTPItems(t, ctx, harness, publicAttempt.ID)
if len(items) < 2 || items[0].ID != publicAttempt.CurrentItem.ID {
t.Fatalf("frozen item count/current item = %d/%s, want ordered item list starting at current item", len(items), publicAttempt.CurrentItem.ID)
}
finalizePath := "/api/v1/me/assessment-attempts/" + publicAttempt.ID.String() + "/finalize"
finalizeBody, err := json.Marshal(map[string]int64{"expected_version": publicAttempt.Version})
if err != nil {
t.Fatalf("marshal early finalize: %v", err)
}
earlyFinalize := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, finalizePath, string(finalizeBody),
sessionHTTPTestOrigin, cookie.Value, csrf, "answer-flow-early-finalize", "203.0.113.44:1234")
var pendingProblem struct {
Code string `json:"code"`
PendingItemIDs []uuid.UUID `json:"pending_item_ids"`
}
if earlyFinalize.Code != http.StatusConflict || json.Unmarshal(earlyFinalize.Body.Bytes(), &pendingProblem) != nil ||
pendingProblem.Code != "state_conflict" || len(pendingProblem.PendingItemIDs) != len(items) {
t.Fatalf("early finalize = %d %s, want state_conflict with %d pending item IDs", earlyFinalize.Code, earlyFinalize.Body.String(), len(items))
}
for index, item := range items {
if pendingProblem.PendingItemIDs[index] != item.ID {
t.Fatalf("pending item %d = %s, want frozen item %s", index, pendingProblem.PendingItemIDs[index], item.ID)
}
}
finalizeReplay := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, finalizePath, string(finalizeBody),
sessionHTTPTestOrigin, cookie.Value, csrf, "answer-flow-early-finalize", "203.0.113.44:1234")
if finalizeReplay.Code != earlyFinalize.Code ||
assessmentHTTPBodyWithoutTraceID(t, finalizeReplay.Body.String()) != assessmentHTTPBodyWithoutTraceID(t, earlyFinalize.Body.String()) {
t.Fatalf("early finalize replay = %d %s, want stored %d %s", finalizeReplay.Code, finalizeReplay.Body.String(), earlyFinalize.Code, earlyFinalize.Body.String())
}
firstAnswer := assessmentAnswerHTTPBodyWithCorrectness(t, publicAttempt.Version, items[0], false)
withClientScore := strings.TrimSuffix(string(firstAnswer), "}") + `,"score":100}`
clientScore := assessmentAttemptHTTPRequest(t, harness, http.MethodPost,
"/api/v1/me/assessment-attempts/"+publicAttempt.ID.String()+"/answers", withClientScore,
sessionHTTPTestOrigin, cookie.Value, csrf, "answer-flow-first", "203.0.113.45:1234")
if clientScore.Code != http.StatusBadRequest {
t.Fatalf("answer with client score = %d %s, want rejected request", clientScore.Code, clientScore.Body.String())
}
answerScope := harness.keyring.IdempotencyScope("assessment_attempt.answer", "answer-flow-first", candidate.ID.String())
var badScoreOutcomeCount int64
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM idempotency_records WHERE scope_hash=$1", answerScope[:]).Scan(&badScoreOutcomeCount); err != nil || badScoreOutcomeCount != 0 {
t.Fatalf("invalid client score reserved idempotency row count=%d error=%v, want zero", badScoreOutcomeCount, err)
}
firstAccepted := assessmentAttemptHTTPRequest(t, harness, http.MethodPost,
"/api/v1/me/assessment-attempts/"+publicAttempt.ID.String()+"/answers", string(firstAnswer),
sessionHTTPTestOrigin, cookie.Value, csrf, "answer-flow-first", "203.0.113.45:1234")
var firstSnapshot assessmentAnswerHTTPAttempt
if firstAccepted.Code != http.StatusOK || json.Unmarshal(firstAccepted.Body.Bytes(), &firstSnapshot) != nil ||
firstSnapshot.Version != publicAttempt.Version+1 || firstSnapshot.CurrentItem == nil || firstSnapshot.CurrentItem.ID != items[1].ID {
t.Fatalf("first answer = %d %s, want next frozen item and incremented version", firstAccepted.Code, firstAccepted.Body.String())
}
storedAnswer, answeredAt := readAssessmentAnswerHTTPItem(t, ctx, harness, publicAttempt.ID, items[0].ID)
if len(storedAnswer) == 0 || answeredAt.IsZero() {
t.Fatalf("first answer storage = bytes %d, answered_at %s; want canonical answer and server time", len(storedAnswer), answeredAt)
}
answerReplay := assessmentAttemptHTTPRequest(t, harness, http.MethodPost,
"/api/v1/me/assessment-attempts/"+publicAttempt.ID.String()+"/answers", string(firstAnswer),
sessionHTTPTestOrigin, cookie.Value, csrf, "answer-flow-first", "203.0.113.45:1234")
if answerReplay.Code != firstAccepted.Code || answerReplay.Body.String() != firstAccepted.Body.String() {
t.Fatalf("answer replay = %d %s, want stored %d %s", answerReplay.Code, answerReplay.Body.String(), firstAccepted.Code, firstAccepted.Body.String())
}
// A reconstructed service graph and router read the committed answer and
// its server timestamp from PostgreSQL, not the old handler's memory.
harness.pool.Close()
harness = newAssessmentAttemptHTTPHarness(ctx, t, &isolatedEnv)
readPath := "/api/v1/me/assessment-attempts/" + publicAttempt.ID.String()
reconstructedRead := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, readPath, "", "",
cookie.Value, "", "", "203.0.113.46:1234")
var reconstructedAttempt assessmentAnswerHTTPAttempt
if reconstructedRead.Code != http.StatusOK || json.Unmarshal(reconstructedRead.Body.Bytes(), &reconstructedAttempt) != nil ||
reconstructedAttempt.Version != firstSnapshot.Version || reconstructedAttempt.CurrentItem == nil ||
reconstructedAttempt.CurrentItem.ID != firstSnapshot.CurrentItem.ID {
t.Fatalf("GET after router reconstruction = %d %s, want version %d and item %s", reconstructedRead.Code, reconstructedRead.Body.String(), firstSnapshot.Version, firstSnapshot.CurrentItem.ID)
}
reconstructedAnswer, reconstructedAnsweredAt := readAssessmentAnswerHTTPItem(t, ctx, harness, publicAttempt.ID, items[0].ID)
if string(reconstructedAnswer) != string(storedAnswer) || !reconstructedAnsweredAt.Equal(answeredAt) {
t.Fatalf("answer after router reconstruction differs: bytes equal=%v timestamp=%s want %s", string(reconstructedAnswer) == string(storedAnswer), reconstructedAnsweredAt, answeredAt)
}
currentVersion := reconstructedAttempt.Version
for _, item := range items[1:] {
body := assessmentAnswerHTTPBody(t, currentVersion, item)
response := assessmentAttemptHTTPRequest(t, harness, http.MethodPost,
"/api/v1/me/assessment-attempts/"+publicAttempt.ID.String()+"/answers", string(body),
sessionHTTPTestOrigin, cookie.Value, csrf, fmt.Sprintf("answer-flow-item-%d", item.Ordinal),
fmt.Sprintf("203.0.113.%d:1234", 50+item.Ordinal))
var next assessmentAnswerHTTPAttempt
if response.Code != http.StatusOK || json.Unmarshal(response.Body.Bytes(), &next) != nil || next.Version != currentVersion+1 {
t.Fatalf("answer frozen item %d = %d %s, want version %d", item.Ordinal, response.Code, response.Body.String(), currentVersion+1)
}
if item.Ordinal < int32(len(items)) && (next.CurrentItem == nil || next.CurrentItem.ID != items[item.Ordinal].ID) {
t.Fatalf("answer item %d returned current item %+v, want %s", item.Ordinal, next.CurrentItem, items[item.Ordinal].ID)
}
if item.Ordinal == int32(len(items)) && (next.State != "ready_to_finalize" || next.CurrentItem != nil) {
t.Fatalf("final answer returned state=%s current_item=%+v, want ready_to_finalize", next.State, next.CurrentItem)
}
currentVersion = next.Version
}
finalizeBody, err = json.Marshal(map[string]int64{"expected_version": currentVersion})
if err != nil {
t.Fatalf("marshal finalization: %v", err)
}
finalized := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, finalizePath, string(finalizeBody),
sessionHTTPTestOrigin, cookie.Value, csrf, "answer-flow-finalize", "203.0.113.90:1234")
var completed assessmentAnswerHTTPAttempt
if finalized.Code != http.StatusOK || json.Unmarshal(finalized.Body.Bytes(), &completed) != nil || completed.State != "completed" {
t.Fatalf("finalize complete attempt = %d %s, want completed", finalized.Code, finalized.Body.String())
}
resultPath := readPath + "/result"
resultResponse := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, resultPath, "", "",
cookie.Value, "", "", "203.0.113.91:1234")
var realResult map[string]any
if resultResponse.Code != http.StatusOK || json.Unmarshal(resultResponse.Body.Bytes(), &realResult) != nil ||
realResult["attempt_id"] != publicAttempt.ID.String() || realResult["outcome"] != "confirmed" {
t.Fatalf("read completed result = %d %s, want persisted confirmed result", resultResponse.Code, resultResponse.Body.String())
}
score, ok := realResult["basic_score"].(map[string]any)
points, pointsOK := score["points"].(float64)
maxPoints, maxPointsOK := score["max_points"].(float64)
if !ok || !pointsOK || !maxPointsOK || points != maxPoints-1 || score["pass_points"] == nil {
t.Fatalf("real result basic score = %#v, want one incorrect server-scored item", realResult["basic_score"])
}
sameKeyFinalize := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, finalizePath, string(finalizeBody),
sessionHTTPTestOrigin, cookie.Value, csrf, "answer-flow-finalize", "203.0.113.94:1234")
if sameKeyFinalize.Code != finalized.Code || sameKeyFinalize.Body.String() != finalized.Body.String() {
t.Fatalf("completed finalize replay = %d %s, want stored %d %s", sameKeyFinalize.Code, sameKeyFinalize.Body.String(), finalized.Code, finalized.Body.String())
}
newFinalizeBody, err := json.Marshal(map[string]int64{"expected_version": completed.Version})
if err != nil {
t.Fatalf("marshal completed finalize retry: %v", err)
}
newKeyFinalize := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, finalizePath, string(newFinalizeBody),
sessionHTTPTestOrigin, cookie.Value, csrf, "answer-flow-finalize-again", "203.0.113.95:1234")
if newKeyFinalize.Code != finalized.Code || newKeyFinalize.Body.String() != finalized.Body.String() {
t.Fatalf("new-key completed finalize = %d %s, want existing terminal projection %d %s", newKeyFinalize.Code, newKeyFinalize.Body.String(), finalized.Code, finalized.Body.String())
}
var resultRowCount int64
var persistedVersion int64
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM assessment_attempt_results WHERE attempt_id=$1", publicAttempt.ID).Scan(&resultRowCount); err != nil {
t.Fatalf("count immutable result rows: %v", err)
}
if err := harness.pool.QueryRow(ctx, "SELECT version FROM assessment_attempts WHERE id=$1", publicAttempt.ID).Scan(&persistedVersion); err != nil {
t.Fatalf("read finalized attempt version: %v", err)
}
if resultRowCount != 1 || persistedVersion != completed.Version {
t.Fatalf("finalize retries left %d result rows and version %d, want one row and version %d", resultRowCount, persistedVersion, completed.Version)
}
resultSnapshot, productPolicyID, openingID, rawScore, passMark, rawScoreValid := readAssessmentAttemptHTTPResult(t, ctx, harness, publicAttempt.ID)
if resultSnapshot["outcome"] != "confirmed" || !rawScoreValid || rawScore != int16(score["points"].(float64)) {
t.Fatalf("stored result outcome/score = %v/%d (valid %v), API result = %v/%v", resultSnapshot["outcome"], rawScore, rawScoreValid, realResult["outcome"], score["points"])
}
pins, ok := resultSnapshot["pins"].(map[string]any)
if !ok || pins["product_policy_version_id"] != productPolicyID.String() || pins["opening_id"] != openingID.String() ||
!strings.Contains(stringMustJSON(t, resultSnapshot), `"product_policy_version_id":"`+productPolicyID.String()+`"`) {
t.Fatalf("stored result pin IDs are not UUID strings: %#v", resultSnapshot["pins"])
}
if passMark < 1 || strings.Contains(resultResponse.Body.String(), "ReferenceAnswer") || strings.Contains(resultResponse.Body.String(), "answer_key") {
t.Fatalf("result exposed private source or lost its stored pass mark: body=%s pass_mark=%d", resultResponse.Body.String(), passMark)
}
// The result projection is read from the immutable stored snapshot after a
// second router/pool reconstruction and stays byte-for-byte stable.
harness.pool.Close()
harness = newAssessmentAttemptHTTPHarness(ctx, t, &isolatedEnv)
restartedResult := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, resultPath, "", "",
cookie.Value, "", "", "203.0.113.92:1234")
if restartedResult.Code != http.StatusOK || restartedResult.Body.String() != resultResponse.Body.String() {
t.Fatalf("result after router reconstruction = %d %s, want stored projection %s", restartedResult.Code, restartedResult.Body.String(), resultResponse.Body.String())
}
var rootAttemptsBeforeExpress int64
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM assessment_attempts WHERE user_id=$1 AND kind='root'", candidate.ID).Scan(&rootAttemptsBeforeExpress); err != nil {
t.Fatalf("count real attempts before express completion: %v", err)
}
trainingCreate := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", `{"kind":"demo_express"}`,
sessionHTTPTestOrigin, cookie.Value, csrf, "answer-flow-express-create", "203.0.113.93:1234")
var training assessmentAnswerHTTPAttempt
if trainingCreate.Code != http.StatusCreated || json.Unmarshal(trainingCreate.Body.Bytes(), &training) != nil || training.ID == uuid.Nil {
t.Fatalf("create express attempt = %d %s", trainingCreate.Code, trainingCreate.Body.String())
}
trainingItems := readAssessmentAnswerHTTPItems(t, ctx, harness, training.ID)
trainingVersion := training.Version
for _, item := range trainingItems {
body := assessmentAnswerHTTPBody(t, trainingVersion, item)
response := assessmentAttemptHTTPRequest(t, harness, http.MethodPost,
"/api/v1/me/assessment-attempts/"+training.ID.String()+"/answers", string(body),
sessionHTTPTestOrigin, cookie.Value, csrf, fmt.Sprintf("answer-flow-express-%d", item.Ordinal),
fmt.Sprintf("203.0.113.%d:1234", 100+item.Ordinal))
var next assessmentAnswerHTTPAttempt
if response.Code != http.StatusOK || json.Unmarshal(response.Body.Bytes(), &next) != nil || next.Version != trainingVersion+1 {
t.Fatalf("answer express item %d = %d %s", item.Ordinal, response.Code, response.Body.String())
}
trainingVersion = next.Version
}
trainingFinalizeBody, err := json.Marshal(map[string]int64{"expected_version": trainingVersion})
if err != nil {
t.Fatalf("marshal express finalization: %v", err)
}
trainingFinalized := assessmentAttemptHTTPRequest(t, harness, http.MethodPost,
"/api/v1/me/assessment-attempts/"+training.ID.String()+"/finalize", string(trainingFinalizeBody),
sessionHTTPTestOrigin, cookie.Value, csrf, "answer-flow-express-finalize", "203.0.113.110:1234")
if trainingFinalized.Code != http.StatusOK {
t.Fatalf("finalize express attempt = %d %s", trainingFinalized.Code, trainingFinalized.Body.String())
}
trainingResultResponse := assessmentAttemptHTTPRequest(t, harness, http.MethodGet,
"/api/v1/me/assessment-attempts/"+training.ID.String()+"/result", "", "", cookie.Value, "", "", "203.0.113.111:1234")
var trainingResult map[string]any
if trainingResultResponse.Code != http.StatusOK || json.Unmarshal(trainingResultResponse.Body.Bytes(), &trainingResult) != nil ||
trainingResult["outcome"] != "demonstration" || trainingResult["mode"] != "demo_express" ||
trainingResult["basic_score"] != nil || trainingResult["confirmed_grade"] != nil || trainingResult["specialization"] != nil {
t.Fatalf("express result = %d %s, want demonstration without score or grade", trainingResultResponse.Code, trainingResultResponse.Body.String())
}
_, _, _, expressRawScore, _, expressRawScoreValid := readAssessmentAttemptHTTPResult(t, ctx, harness, training.ID)
if expressRawScoreValid {
t.Fatalf("express result stored raw score %d, want SQL NULL", expressRawScore)
}
var rootAttemptsAfterExpress int64
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM assessment_attempts WHERE user_id=$1 AND kind='root'", candidate.ID).Scan(&rootAttemptsAfterExpress); err != nil {
t.Fatalf("count real attempts after express completion: %v", err)
}
if rootAttemptsAfterExpress != rootAttemptsBeforeExpress {
t.Fatalf("express completion changed real root quota count from %d to %d", rootAttemptsBeforeExpress, rootAttemptsAfterExpress)
}
}
type assessmentAnswerHTTPAttempt struct {
ID uuid.UUID `json:"id"`
Version int64 `json:"version"`
State string `json:"state"`
CurrentItem *struct {
ID uuid.UUID `json:"id"`
} `json:"current_item"`
}
type assessmentAnswerHTTPItem struct {
ID uuid.UUID
Ordinal int32
Variant domain.AssessmentVariant
}
func readAssessmentAnswerHTTPItems(
t *testing.T,
ctx context.Context,
harness *assessmentAttemptHTTPHarness,
attemptID uuid.UUID,
) []assessmentAnswerHTTPItem {
t.Helper()
rows, err := harness.pool.Query(ctx, `SELECT id, ordinal, variant FROM assessment_attempt_items WHERE attempt_id=$1 ORDER BY ordinal`, attemptID)
if err != nil {
t.Fatalf("read frozen assessment items: %v", err)
}
defer rows.Close()
items := make([]assessmentAnswerHTTPItem, 0)
for rows.Next() {
var item assessmentAnswerHTTPItem
var encoded []byte
if err := rows.Scan(&item.ID, &item.Ordinal, &encoded); err != nil {
t.Fatalf("scan frozen assessment item: %v", err)
}
item.Variant, err = domain.UnmarshalAssessmentAttemptVariant(encoded)
if err != nil {
t.Fatalf("restore frozen assessment variant: %v", err)
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
t.Fatalf("iterate frozen assessment items: %v", err)
}
return items
}
func readAssessmentAnswerHTTPItem(
t *testing.T,
ctx context.Context,
harness *assessmentAttemptHTTPHarness,
attemptID, itemID uuid.UUID,
) ([]byte, time.Time) {
t.Helper()
var answer []byte
var answeredAt time.Time
if err := harness.pool.QueryRow(ctx, `SELECT answer, answered_at FROM assessment_attempt_items WHERE attempt_id=$1 AND id=$2`,
attemptID, itemID).Scan(&answer, &answeredAt); err != nil {
t.Fatalf("read stored answer and server time: %v", err)
}
return answer, answeredAt.UTC()
}
func assessmentAnswerHTTPBody(t *testing.T, version int64, item assessmentAnswerHTTPItem) []byte {
return assessmentAnswerHTTPBodyWithCorrectness(t, version, item, true)
}
func assessmentAnswerHTTPBodyWithCorrectness(
t *testing.T,
version int64,
item assessmentAnswerHTTPItem,
wantCorrect bool,
) []byte {
t.Helper()
var answer []byte
switch item.Variant.AnswerFormat {
case domain.AnswerFormatInteger:
reference, err := strconv.ParseInt(item.Variant.ReferenceAnswer, 10, 64)
if err != nil {
t.Fatalf("parse frozen answer key %q: %v", item.Variant.ReferenceAnswer, err)
}
if !wantCorrect {
reference++
}
answer = []byte(fmt.Sprintf(`{"format":"number","number":%d}`, reference))
case domain.AnswerFormatIntegerSequence:
parts := strings.Fields(item.Variant.ReferenceAnswer)
if !wantCorrect && len(parts) < 2 {
t.Fatalf("frozen sequence answer %q has fewer than two tasks", item.Variant.ReferenceAnswer)
}
elements := make([]string, 0, len(parts))
for _, part := range parts {
elements = append(elements, "job_"+part)
}
if !wantCorrect {
elements[0], elements[1] = elements[1], elements[0]
}
var err error
answer, err = json.Marshal(struct {
Format string `json:"format"`
ElementIDs []string `json:"element_ids"`
}{Format: "order", ElementIDs: elements})
if err != nil {
t.Fatalf("marshal order answer: %v", err)
}
case domain.AnswerFormatChoice:
chosen, err := strconv.Atoi(item.Variant.ReferenceAnswer)
if err != nil || chosen < 0 || chosen >= len(item.Variant.Options) {
t.Fatalf("frozen choice key %q does not name one of %d options", item.Variant.ReferenceAnswer, len(item.Variant.Options))
}
if !wantCorrect {
chosen = (chosen + 1) % len(item.Variant.Options)
}
answer, err = json.Marshal(struct {
Format string `json:"format"`
OptionIDs []string `json:"option_ids"`
}{Format: "choice", OptionIDs: []string{item.Variant.Options[chosen].ID}})
if err != nil {
t.Fatalf("marshal choice answer: %v", err)
}
default:
t.Fatalf("unsupported fixture answer format %q", item.Variant.AnswerFormat)
}
_, correct, err := domain.CanonicalAssessmentAnswerForVariant(answer, item.Variant)
if err != nil || correct != wantCorrect {
t.Fatalf("fixture answer for item %s has correctness %v, want %v: error %v", item.ID, correct, wantCorrect, err)
}
body, err := json.Marshal(struct {
ExpectedVersion int64 `json:"expected_version"`
ItemID uuid.UUID `json:"item_id"`
Answer json.RawMessage `json:"answer"`
}{ExpectedVersion: version, ItemID: item.ID, Answer: answer})
if err != nil {
t.Fatalf("marshal answer command: %v", err)
}
return body
}
func readAssessmentAttemptHTTPResult(
t *testing.T,
ctx context.Context,
harness *assessmentAttemptHTTPHarness,
attemptID uuid.UUID,
) (map[string]any, uuid.UUID, uuid.UUID, int16, int32, bool) {
t.Helper()
var encoded []byte
var productPolicyID uuid.UUID
var storedOpeningID pgtype.UUID
var rawScore pgtype.Int2
var passMark pgtype.Int4
if err := harness.pool.QueryRow(ctx, `
SELECT result_snapshot, product_policy_version_id, opening_id, raw_score, pass_mark_basis_points
FROM assessment_attempt_results WHERE attempt_id=$1`, attemptID).
Scan(&encoded, &productPolicyID, &storedOpeningID, &rawScore, &passMark); err != nil {
t.Fatalf("read immutable assessment result row: %v", err)
}
var openingID uuid.UUID
if storedOpeningID.Valid {
openingID = uuid.UUID(storedOpeningID.Bytes)
}
var document map[string]any
if err := json.Unmarshal(encoded, &document); err != nil {
t.Fatalf("decode immutable assessment result document: %v", err)
}
if !rawScore.Valid || !passMark.Valid {
return document, productPolicyID, openingID, 0, 0, rawScore.Valid
}
return document, productPolicyID, openingID, rawScore.Int16, passMark.Int32, rawScore.Valid
}
func stringMustJSON(t *testing.T, value any) string {
t.Helper()
encoded, err := json.Marshal(value)
if err != nil {
t.Fatalf("marshal result snapshot for assertion: %v", err)
}
return string(encoded)
}
func assessmentHTTPBodyWithoutTraceID(t *testing.T, body string) string {
t.Helper()
var document map[string]json.RawMessage
if err := json.Unmarshal([]byte(body), &document); err != nil {
t.Fatalf("decode HTTP problem response: %v", err)
}
delete(document, "trace_id")
encoded, err := json.Marshal(document)
if err != nil {
t.Fatalf("marshal HTTP problem response: %v", err)
}
return string(encoded)
}