Files
lincodex/backend/internal/adapter/primary/http/v1/assessment_test.go
T

238 lines
11 KiB
Go

package v1
import (
"context"
"errors"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/adapter/primary/http/api"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
assessmentusecase "lincodex/backend/internal/usecase/assessment"
)
func TestCreateAssessmentAttemptMapsRootAndPublicSnapshot(t *testing.T) {
userID := uuid.New()
snapshot := assessmentPublicSnapshot()
operations := &assessmentOperationsStub{create: outbound.AssessmentAttemptCreateResult{
Outcome: outbound.AssessmentAttemptCreateOutcome{StatusCode: 201, Response: snapshot},
}}
handler := NewAssessmentHandler(operations)
request := api.NewAssessmentQualifiedAttemptCreateAssessmentAttemptCreate(api.AssessmentQualifiedAttemptCreate{
Kind: api.AssessmentQualifiedAttemptCreateKindRoot, Specialization: "backend", TargetGrade: "junior",
TaskLanguage: api.NewNilTaskLanguage(api.TaskLanguage("go")),
})
response, err := handler.CreateMyAssessmentAttempt(principalForTest(userID), request, api.CreateMyAssessmentAttemptParams{IdempotencyKey: "create-key"})
if err != nil {
t.Fatalf("CreateMyAssessmentAttempt() error = %v", err)
}
if operations.createCalls != 1 || operations.createCommand.ActorID != userID || operations.createCommand.Kind != domain.AssessmentAttemptKindRoot ||
operations.createCommand.IdempotencyKey != "create-key" || operations.createCommand.Specialization == nil ||
*operations.createCommand.Specialization != "backend" || operations.createCommand.TargetGrade == nil ||
*operations.createCommand.TargetGrade != "junior" || operations.createCommand.TaskLanguage == nil ||
*operations.createCommand.TaskLanguage != "go" {
t.Fatalf("CreateAttempt() command = %+v, calls %d", operations.createCommand, operations.createCalls)
}
headers, ok := response.(*api.AssessmentAttemptHeaders)
if !ok || headers.CacheControl != api.CacheControlNoStoreNoStore {
t.Fatalf("create response = %T %+v, want no-store headers", response, response)
}
qualified, ok := headers.Response.GetAssessmentQualifiedAttempt()
if !ok || qualified.ID != snapshot.ID.UUID() || qualified.Version != api.AssessmentAttemptVersion(snapshot.Version) ||
qualified.CurrentItem.IsNull() || qualified.Progress.MaxItems != snapshot.MaxItems ||
qualified.Versions.AlgorithmVersion != api.AssessmentVersionLabel(snapshot.AlgorithmVersion) {
t.Fatalf("qualified attempt response = %+v, %v", qualified, ok)
}
item, ok := qualified.CurrentItem.Get()
if !ok || item.Prompt != "Choose the number" || !item.Content.IsNumberItemContent() {
t.Fatalf("current item = %+v, %v", item, ok)
}
}
func TestCreateAssessmentAttemptMapsPersistedConflictAndRejectsGuest(t *testing.T) {
operations := &assessmentOperationsStub{create: outbound.AssessmentAttemptCreateResult{
Outcome: outbound.AssessmentAttemptCreateOutcome{StatusCode: 409, ProblemCode: "state_conflict"},
}}
handler := NewAssessmentHandler(operations)
request := api.NewAssessmentExpressAttemptCreateAssessmentAttemptCreate(api.AssessmentExpressAttemptCreate{
Kind: api.AssessmentExpressAttemptCreateKindDemoExpress,
})
response, err := handler.CreateMyAssessmentAttempt(principalForTest(uuid.New()), request, api.CreateMyAssessmentAttemptParams{IdempotencyKey: "blocked"})
if err != nil {
t.Fatalf("CreateMyAssessmentAttempt() error = %v", err)
}
if _, ok := response.(*api.CreateMyAssessmentAttemptConflict); !ok {
t.Fatalf("state conflict response = %T, want conflict", response)
}
if operations.createCommand.Kind != domain.AssessmentAttemptKindDemoExpress || operations.createCommand.Specialization != nil {
t.Fatalf("express command = %+v", operations.createCommand)
}
response, err = handler.CreateMyAssessmentAttempt(context.Background(), request, api.CreateMyAssessmentAttemptParams{IdempotencyKey: "blocked"})
if err != nil {
t.Fatalf("guest CreateMyAssessmentAttempt() error = %v", err)
}
if _, ok := response.(*api.CreateMyAssessmentAttemptUnauthorized); !ok || operations.createCalls != 1 {
t.Fatalf("guest create response = %T, operations called %d", response, operations.createCalls)
}
}
func TestStartAndReadAssessmentAttemptUseVerifiedPrincipal(t *testing.T) {
userID := uuid.New()
snapshot := assessmentPublicSnapshot()
operations := &assessmentOperationsStub{
read: snapshot,
start: outbound.AssessmentAttemptSessionResult{Response: snapshot},
}
handler := NewAssessmentHandler(operations)
ctx := principalForTest(userID)
read, err := handler.GetMyAssessmentAttempt(ctx, api.GetMyAssessmentAttemptParams{AttemptID: snapshot.ID.UUID()})
if err != nil {
t.Fatalf("GetMyAssessmentAttempt() error = %v", err)
}
if operations.readUserID != userID || operations.readAttemptID != snapshot.ID {
t.Fatalf("GetMyAttempt() IDs = %s/%s", operations.readUserID, operations.readAttemptID)
}
if _, ok := read.(*api.AssessmentAttemptHeaders); !ok {
t.Fatalf("read response = %T, want attempt headers", read)
}
started, err := handler.StartMyAssessmentAttemptSession(ctx, &api.AssessmentAttemptSessionStart{
ExpectedVersion: api.AssessmentAttemptVersion(7),
}, api.StartMyAssessmentAttemptSessionParams{AttemptID: snapshot.ID.UUID(), IdempotencyKey: "session-key"})
if err != nil {
t.Fatalf("StartMyAssessmentAttemptSession() error = %v", err)
}
if operations.startCommand.ActorID != userID || operations.startCommand.AttemptID != snapshot.ID ||
operations.startCommand.ExpectedVersion != 7 || operations.startCommand.IdempotencyKey != "session-key" {
t.Fatalf("StartSession() command = %+v", operations.startCommand)
}
if _, ok := started.(*api.AssessmentAttemptHeaders); !ok {
t.Fatalf("start response = %T, want attempt headers", started)
}
}
func TestAssessmentAttemptFailuresMapWithoutExposingInternalErrors(t *testing.T) {
operations := &assessmentOperationsStub{startErr: assessmentusecase.ErrAttemptVersionConflict}
handler := NewAssessmentHandler(operations)
response, err := handler.StartMyAssessmentAttemptSession(principalForTest(uuid.New()),
&api.AssessmentAttemptSessionStart{ExpectedVersion: 3},
api.StartMyAssessmentAttemptSessionParams{AttemptID: uuid.New(), IdempotencyKey: "key"})
if err != nil {
t.Fatalf("StartMyAssessmentAttemptSession() error = %v", err)
}
problem, ok := response.(*api.StartMyAssessmentAttemptSessionPreconditionFailed)
if !ok || api.Problem(*problem).Code != api.ProblemCodeVersionConflict {
t.Fatalf("version conflict response = %T %+v", response, response)
}
operations.readErr = assessmentusecase.ErrAttemptNotFound
read, err := handler.GetMyAssessmentAttempt(principalForTest(uuid.New()), api.GetMyAssessmentAttemptParams{AttemptID: uuid.New()})
if err != nil {
t.Fatalf("GetMyAssessmentAttempt() error = %v", err)
}
if _, ok := read.(*api.GetMyAssessmentAttemptNotFound); !ok {
t.Fatalf("missing attempt response = %T", read)
}
operations.createErr = &assessmentusecase.AttemptFieldError{Pointer: "/task_language", Reason: "is not available"}
create, err := handler.CreateMyAssessmentAttempt(principalForTest(uuid.New()), api.NewAssessmentQualifiedAttemptCreateAssessmentAttemptCreate(
api.AssessmentQualifiedAttemptCreate{Kind: api.AssessmentQualifiedAttemptCreateKindRoot, Specialization: "backend", TargetGrade: "junior"},
), api.CreateMyAssessmentAttemptParams{IdempotencyKey: "key"})
if err != nil {
t.Fatalf("CreateMyAssessmentAttempt() error = %v", err)
}
badRequest, ok := create.(*api.CreateMyAssessmentAttemptBadRequest)
if !ok || len(api.Problem(*badRequest).Errors) != 1 || api.Problem(*badRequest).Errors[0].Pointer != "/task_language" {
t.Fatalf("validation response = %T %+v", create, create)
}
operations.startErr = errors.New("private database detail")
if _, err := handler.StartMyAssessmentAttemptSession(principalForTest(uuid.New()),
&api.AssessmentAttemptSessionStart{ExpectedVersion: 1},
api.StartMyAssessmentAttemptSessionParams{AttemptID: uuid.New(), IdempotencyKey: "key"}); err == nil || err.Error() != "private database detail" {
t.Fatalf("unexpected internal error mapping = %v", err)
}
}
func TestConfirmedAttemptResultDoesNotInferStoredGradeFromTarget(t *testing.T) {
result := assessmentusecase.AssessmentAttemptResult{
Attempt: domain.AssessmentAttemptPublicSnapshot{
Kind: domain.AssessmentAttemptKindRoot, TargetGrade: domainCodePointer(domain.GradeCode("junior")),
},
Outcome: domain.AssessmentAttemptOutcomeConfirmed,
}
fields, err := assessmentRealResultFields(result)
if err != nil {
t.Fatalf("assessmentRealResultFields() error = %v", err)
}
if !fields.confirmedGrade.IsNull() {
t.Fatalf("confirmed grade = %+v, want null until a stored grade decision exists", fields.confirmedGrade)
}
}
type assessmentOperationsStub struct {
availabilityCalls int
availabilityUserID uuid.UUID
availability assessmentusecase.AssessmentAvailability
availabilityErr error
createCalls int
createCommand assessmentusecase.CreateAttemptCommand
create outbound.AssessmentAttemptCreateResult
createErr error
read domain.AssessmentAttemptPublicSnapshot
readUserID uuid.UUID
readAttemptID domain.AssessmentAttemptID
readErr error
startCommand assessmentusecase.StartAttemptSessionCommand
start outbound.AssessmentAttemptSessionResult
startErr error
}
func (stub *assessmentOperationsStub) GetMyAssessmentAvailability(
_ context.Context,
userID uuid.UUID,
) (assessmentusecase.AssessmentAvailability, error) {
stub.availabilityCalls++
stub.availabilityUserID = userID
return stub.availability, stub.availabilityErr
}
func (stub *assessmentOperationsStub) CreateAttempt(_ context.Context, command assessmentusecase.CreateAttemptCommand) (outbound.AssessmentAttemptCreateResult, error) {
stub.createCalls++
stub.createCommand = command
return stub.create, stub.createErr
}
func (stub *assessmentOperationsStub) GetMyAttempt(_ context.Context, userID uuid.UUID, attemptID domain.AssessmentAttemptID) (domain.AssessmentAttemptPublicSnapshot, error) {
stub.readUserID, stub.readAttemptID = userID, attemptID
return stub.read, stub.readErr
}
func (stub *assessmentOperationsStub) StartSession(_ context.Context, command assessmentusecase.StartAttemptSessionCommand) (outbound.AssessmentAttemptSessionResult, error) {
stub.startCommand = command
return stub.start, stub.startErr
}
func principalForTest(userID uuid.UUID) context.Context {
return context.WithValue(context.Background(), principalContextKey{}, Principal{UserID: userID, EmailVerified: true})
}
func assessmentPublicSnapshot() domain.AssessmentAttemptPublicSnapshot {
started := time.Date(2026, time.October, 7, 12, 0, 0, 0, time.UTC)
return domain.AssessmentAttemptPublicSnapshot{
ID: domain.AssessmentAttemptID(uuid.New()), Version: 7, Kind: domain.AssessmentAttemptKindRoot,
Mode: domain.AssessmentAttemptModeDemoBasic, State: domain.AssessmentAttemptStateInProgress,
Specialization: domainCodePointer(domain.SpecializationCode("backend")), TargetGrade: domainCodePointer(domain.GradeCode("junior")),
PolicyVersion: 2, BankVersion: "bank-v1", AlgorithmVersion: "assessment.v1", StartedAt: started,
ExpiresAt: started.Add(30 * time.Minute), MaxItems: 10, SessionsUsed: 1, MaxSessions: 2, IdleTimeout: 1800,
CurrentItem: &domain.AssessmentAttemptPublicItem{ID: uuid.New(), Sequence: 1, Prompt: "Choose the number",
Content: domain.AssessmentAttemptPublicItemContent{Format: "number"}}, Practices: []domain.AssessmentAttemptPublicPractice{},
}
}
func domainCodePointer[T ~string](value T) *T {
return &value
}