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

217 lines
8.8 KiB
Go

package v1
import (
"context"
"encoding/base64"
"encoding/binary"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/adapter/primary/http/api"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
supportcase "lincodex/backend/internal/usecase/supportcase"
)
func TestSupportCaseCreateCommandMapsManualRequestWithoutPriorAttempt(t *testing.T) {
request := api.SupportCaseCreate{
Type: api.SupportCaseCreateManualAssessmentSupportCaseCreate,
SupportCaseCreateManualAssessment: api.SupportCaseCreateManualAssessment{
Type: api.SupportCaseCreateManualAssessmentTypeManualAssessment,
Description: api.SupportCaseDescription("Please assess my Go skills."),
AssessmentTarget: api.SupportCaseAssessmentTarget{
Specialization: api.SpecializationCodeBackend,
Grade: api.GradeCodeJunior,
},
},
}
command, valid := supportCaseCreateCommand(request)
if !valid || command.Type != domain.SupportCaseTypeManualAssessment || command.Description != "Please assess my Go skills." ||
command.AssessmentTarget == nil || command.AssessmentTarget.Specialization != domain.SpecializationBackend ||
command.AssessmentTarget.Grade != domain.GradeJunior || command.Object != nil {
t.Fatalf("supportCaseCreateCommand() = %+v, %v; want a standalone manual-assessment request", command, valid)
}
}
func TestSupportCaseCursorIsBoundToOwnerAndStoredPrecision(t *testing.T) {
ownerID := uuid.Must(uuid.NewV7())
position := outbound.SupportCaseListPosition{
CreatedAt: time.Date(2026, time.October, 7, 10, 0, 0, 123456000, time.UTC),
ID: domain.SupportCaseID(uuid.Must(uuid.NewV7())),
}
cursor, err := encodeSupportCaseCursor(ownerID, position)
if err != nil {
t.Fatalf("encodeSupportCaseCursor() error = %v", err)
}
decoded, err := decodeSupportCaseCursor(cursor, ownerID)
if err != nil || decoded.ID != position.ID || !decoded.CreatedAt.Equal(position.CreatedAt) {
t.Fatalf("decodeSupportCaseCursor() = %+v, %v, want %+v", decoded, err, position)
}
if _, err := decodeSupportCaseCursor(cursor, uuid.Must(uuid.NewV7())); err == nil {
t.Fatal("decodeSupportCaseCursor() accepted a cursor from another owner")
}
if _, err := encodeSupportCaseCursor(ownerID, outbound.SupportCaseListPosition{
CreatedAt: position.CreatedAt.Add(time.Nanosecond), ID: position.ID,
}); err == nil {
t.Fatal("encodeSupportCaseCursor() accepted precision PostgreSQL cannot preserve")
}
for _, invalidTime := range []time.Time{
time.Unix(-1, 0).UTC(),
time.Date(10000, time.January, 1, 0, 0, 0, 0, time.UTC),
} {
if _, err := encodeSupportCaseCursor(ownerID, outbound.SupportCaseListPosition{CreatedAt: invalidTime, ID: position.ID}); err == nil {
t.Errorf("encodeSupportCaseCursor() accepted unsupported time %v", invalidTime)
}
}
for name, mutate := range map[string]func([]byte){
"out-of-range year": func(value []byte) {
binary.BigEndian.PutUint64(value[17:25], uint64(time.Date(10000, time.January, 1, 0, 0, 0, 0, time.UTC).Unix()))
},
"sub-microsecond precision": func(value []byte) {
binary.BigEndian.PutUint32(value[25:29], 1)
},
} {
t.Run(name, func(t *testing.T) {
value, err := base64.RawURLEncoding.DecodeString(cursor)
if err != nil {
t.Fatalf("DecodeString() error = %v", err)
}
mutate(value)
invalid := base64.RawURLEncoding.EncodeToString(value)
if _, err := decodeSupportCaseCursor(invalid, ownerID); err == nil {
t.Fatal("decodeSupportCaseCursor() accepted an unsupported position")
}
})
}
}
func TestSupportCaseRateLimitErrorPreservesRetryAfter(t *testing.T) {
result, err := supportCaseCreateFailure(principalTestContext(), &supportcase.RateLimitedError{
RetryAfter: 1500 * time.Millisecond,
})
if err != nil {
t.Fatalf("supportCaseCreateFailure() error = %v", err)
}
response, ok := result.(*api.TooManyRequestsHeaders)
if !ok {
t.Fatalf("supportCaseCreateFailure() result = %T, want *TooManyRequestsHeaders", result)
}
if seconds, present := response.RetryAfter.Get(); !present || seconds != 2 {
t.Fatalf("Retry-After = %d, %v; want 2 seconds", seconds, present)
}
}
func TestSupportCaseReadAuthorizationFailuresUseDocumented401(t *testing.T) {
for _, operation := range []string{"get", "list"} {
for _, failure := range []error{supportcase.ErrForbidden, supportcase.ErrEmailNotVerified} {
t.Run(operation+"/"+failure.Error(), func(t *testing.T) {
operations := &supportOperationsStub{getError: failure, listError: failure}
handler := NewSupportHandler(operations)
if operation == "get" {
result, err := handler.GetMySupportCase(principalTestContext(), api.GetMySupportCaseParams{CaseID: uuid.Must(uuid.NewV7())})
if err != nil {
t.Fatalf("GetMySupportCase() error = %v", err)
}
if _, ok := result.(*api.GetMySupportCaseUnauthorized); !ok {
t.Fatalf("GetMySupportCase() result = %T, want documented 401", result)
}
return
}
result, err := handler.ListMySupportCases(principalTestContext(), api.ListMySupportCasesParams{})
if err != nil {
t.Fatalf("ListMySupportCases() error = %v", err)
}
if _, ok := result.(*api.ListMySupportCasesUnauthorized); !ok {
t.Fatalf("ListMySupportCases() result = %T, want documented 401", result)
}
})
}
}
}
func TestSupportCaseHandlerBindsCreateToPrincipalAndReturnsNoStore(t *testing.T) {
ctx := principalTestContext()
principal, ok := PrincipalFromContext(ctx)
if !ok {
t.Fatal("principalTestContext() did not set a principal")
}
createdAt := time.Date(2026, time.October, 7, 10, 0, 0, 0, time.UTC)
responseTarget, err := domain.DemoSupportPolicy().ResponseTarget(domain.SupportCaseTypeSupport, 4, createdAt)
if err != nil {
t.Fatalf("ResponseTarget() error = %v", err)
}
supportCase, err := domain.NewSupportCase(domain.NewSupportCaseInput{
Number: "SC-2026-000123", OwnerID: principal.UserID, Type: domain.SupportCaseTypeSupport,
Description: "Please help with my account.", ResponseTarget: responseTarget, CreatedAt: createdAt,
})
if err != nil {
t.Fatalf("NewSupportCase() error = %v", err)
}
operations := &supportOperationsStub{createResult: supportcase.CreateResult{Case: supportCase}}
handler := NewSupportHandler(operations)
request := api.SupportCaseCreate{
Type: api.SupportCaseCreateSupportSupportCaseCreate,
SupportCaseCreateSupport: api.SupportCaseCreateSupport{
Type: api.SupportCaseCreateSupportTypeSupport,
Description: api.SupportCaseDescription("Please help with my account."),
},
}
result, err := handler.CreateMySupportCase(ctx, request, api.CreateMySupportCaseParams{IdempotencyKey: "support-key-1"})
if err != nil {
t.Fatalf("CreateMySupportCase() error = %v", err)
}
response, ok := result.(*api.SupportCaseHeaders)
if !ok {
t.Fatalf("CreateMySupportCase() result type = %T, want *SupportCaseHeaders", result)
}
if response.CacheControl != api.CacheControlNoStoreNoStore || response.Response.ID != supportCase.ID().UUID() ||
response.Response.Type != api.SupportCaseTypeSupport || response.Response.Description != "Please help with my account." {
t.Fatalf("CreateMySupportCase() response = %+v", response)
}
if operations.createCommand.ActorID != principal.UserID || operations.createCommand.IdempotencyKey != "support-key-1" ||
operations.createCommand.Description != "Please help with my account." || len(operations.createCommand.CanonicalBody) == 0 {
t.Fatalf("create command did not preserve authenticated scope and body: %+v", operations.createCommand)
}
}
func TestSupportCaseHandlerRejectsMissingPrincipalBeforeCallingOperations(t *testing.T) {
operations := &supportOperationsStub{}
handler := NewSupportHandler(operations)
_, err := handler.GetMySupportCase(context.Background(), api.GetMySupportCaseParams{CaseID: uuid.Must(uuid.NewV7())})
if err != nil {
t.Fatalf("GetMySupportCase() error = %v", err)
}
if operations.getCalls != 0 {
t.Fatalf("operations.GetMyCase calls = %d, want none", operations.getCalls)
}
}
type supportOperationsStub struct {
createCommand supportcase.CreateCommand
createResult supportcase.CreateResult
createError error
getResult domain.SupportCase
getError error
getCalls int
listPage outbound.SupportCaseListPage
listError error
}
func (stub *supportOperationsStub) Create(_ context.Context, command supportcase.CreateCommand) (supportcase.CreateResult, error) {
stub.createCommand = command
return stub.createResult, stub.createError
}
func (stub *supportOperationsStub) GetMyCase(_ context.Context, _ uuid.UUID, _ domain.SupportCaseID) (domain.SupportCase, error) {
stub.getCalls++
return stub.getResult, stub.getError
}
func (stub *supportOperationsStub) ListMyCases(_ context.Context, _ supportcase.ListCommand) (outbound.SupportCaseListPage, error) {
return stub.listPage, stub.listError
}
var _ SupportOperations = (*supportOperationsStub)(nil)