Files
lincodex/backend/internal/domain/candidate_test.go
T

565 lines
27 KiB
Go

package domain
import (
"bytes"
"errors"
"fmt"
"log/slog"
"reflect"
"strings"
"testing"
"time"
"github.com/google/uuid"
)
var candidateTestTime = time.Date(2026, 10, 6, 9, 0, 0, 0, time.UTC)
// confirmed wraps a value as a confirmed decision.
func confirmed[V comparable](value V) *ProfileClaimInput[V] {
return &ProfileClaimInput[V]{Value: value, Status: ProfileClaimConfirmed}
}
func confirmedItems[V comparable](values ...V) []ProfileClaimInput[V] {
items := make([]ProfileClaimInput[V], 0, len(values))
for _, value := range values {
items = append(items, ProfileClaimInput[V]{Value: value, Status: ProfileClaimConfirmed})
}
return items
}
func completeCandidateProfileInput() CandidateProfileInput {
return CandidateProfileInput{
FullName: confirmed("Anna Sokolova"),
Email: confirmed("anna.sokolova@example.com"),
Phone: confirmed("+79000000000"),
Telegram: confirmed("@anna_sokolova"),
Stack: confirmedItems("PostgreSQL", "Kafka"),
Roles: confirmedItems(ProfileRole{Specialization: SpecializationBackend, SelfAssessedGrade: GradeMiddle}),
Experience: confirmedItems(ProfileExperience{
EmployerName: "Example Payments", Specialization: SpecializationBackend,
StartedOn: "2022-03", Summary: "Moved the payout service to an event model.",
}),
SoftSkills: confirmedItems("Mentoring"),
Location: confirmed("Kazan"),
Relocation: confirmed(false),
SalaryMinimum: confirmed(ProfileSalaryMinimum{Amount: 180000, TaxBasis: ProfileTaxNet}),
}
}
func mustCandidateContent(t *testing.T, stored CandidateProfileContent, input CandidateProfileInput, at time.Time) CandidateProfileContent {
t.Helper()
content, err := ResolveCandidateProfileContent(stored, input, at)
if err != nil {
t.Fatalf("ResolveCandidateProfileContent() error = %v", err)
}
return content
}
// suggestedContent builds stored content with imported, unconfirmed claims
// the way storage restores them, because no operation produces them yet.
func suggestedContent(t *testing.T) CandidateProfileContent {
t.Helper()
suggestion := func(kind string, ordinal int, value string) StoredProfileClaim {
return StoredProfileClaim{
Kind: kind, Ordinal: ordinal, Value: []byte(value), Status: "extracted", Origin: "extracted_from_resume",
Quote: "from the resume", ExtractionVersion: "resume-rules.2026-10.1",
}
}
content, err := RestoreCandidateProfileContent([]StoredProfileClaim{
suggestion(profileKindPhone, 0, `"+79000000000"`),
suggestion(profileKindStack, 0, `"Kafka"`),
suggestion(profileKindStack, 1, `"gRPC"`),
})
if err != nil {
t.Fatalf("RestoreCandidateProfileContent() error = %v", err)
}
return content
}
func TestResolveCandidateProfileContentStoresManualClaimsWithTrustLevelZero(t *testing.T) {
content := mustCandidateContent(t, CandidateProfileContent{}, completeCandidateProfileInput(), candidateTestTime)
name, ok := content.FullName()
if !ok || name.Value() != "Anna Sokolova" || name.Status() != ProfileClaimConfirmed {
t.Fatalf("full name = %v, %v, want a confirmed claim", name.Value(), ok)
}
source := name.Source()
if source.Origin() != ProfileOriginManual || source.TrustLevel() != 0 || source.Quote() != "" ||
source.ExtractionVersion() != "" || !source.ConfirmedAt().Equal(candidateTestTime) {
t.Fatalf("source = origin %s, trust %d, confirmed %v, want a manual claim at the save time", source.Origin(), source.TrustLevel(), source.ConfirmedAt())
}
salary, ok := content.SalaryMinimum()
if !ok || salary.Value() != (ProfileSalaryMinimum{Amount: 180000, TaxBasis: ProfileTaxNet}) {
t.Fatalf("salary minimum = %v, %v, want the given amount", salary.Value(), ok)
}
if roles := content.Roles(); len(roles) != 1 || roles[0].Value().SelfAssessedGrade != GradeMiddle {
t.Fatalf("roles = %d, want the self-assessed role", len(roles))
}
if len(content.Stack()) != 2 || len(content.SoftSkills()) != 1 || len(content.Experience()) != 1 {
t.Fatal("lists were not stored")
}
for _, claim := range content.Stack() {
if claim.Source().TrustLevel() != ProfileClaimTrustLevel {
t.Fatalf("trust level = %d, want %d for every claim", claim.Source().TrustLevel(), ProfileClaimTrustLevel)
}
}
}
func TestResolveCandidateProfileContentLeavesAbsentFieldsUnknown(t *testing.T) {
stored := mustCandidateContent(t, CandidateProfileContent{}, completeCandidateProfileInput(), candidateTestTime)
content := mustCandidateContent(t, stored, CandidateProfileInput{}, candidateTestTime.Add(time.Hour))
if _, ok := content.FullName(); ok {
t.Fatal("a field sent as null kept its value, want it removed")
}
if _, ok := content.SalaryMinimum(); ok {
t.Fatal("a salary sent as null kept its value, want it removed")
}
if len(content.Stack()) != 0 || len(content.Roles()) != 0 {
t.Fatal("an empty list kept its items, want the list replaced")
}
}
func TestSuggestionsStayUnconfirmedUntilTheCandidateConfirmsThem(t *testing.T) {
stored := suggestedContent(t)
phone, _ := stored.Phone()
if phone.Status() != ProfileClaimExtracted || phone.Source().TrustLevel() != 0 || !phone.Source().ConfirmedAt().IsZero() {
t.Fatalf("restored suggestion = %v, trust %d, want an unconfirmed claim of trust level 0", phone.Status(), phone.Source().TrustLevel())
}
later := candidateTestTime.Add(time.Hour)
t.Run("extracted keeps a stored suggestion unconfirmed and unchanged", func(t *testing.T) {
input := CandidateProfileInput{
Phone: &ProfileClaimInput[string]{Value: "+79000000000", Status: ProfileClaimExtracted},
Stack: []ProfileClaimInput[string]{{Value: "Kafka", Status: ProfileClaimExtracted}, {Value: "gRPC", Status: ProfileClaimExtracted}},
}
content := mustCandidateContent(t, stored, input, later)
if !content.Equal(stored) {
t.Fatal("a form sent back unchanged altered the stored suggestions")
}
})
t.Run("confirmed confirms a suggestion and keeps its origin and quote", func(t *testing.T) {
input := CandidateProfileInput{Phone: confirmed("+79000000000"), Stack: confirmedItems("Kafka")}
content := mustCandidateContent(t, stored, input, later)
phone, _ := content.Phone()
source := phone.Source()
if phone.Status() != ProfileClaimConfirmed || source.Origin() != ProfileOriginExtractedFromResume ||
source.Quote() != "from the resume" || source.ExtractionVersion() != "resume-rules.2026-10.1" ||
!source.ConfirmedAt().Equal(later) || source.TrustLevel() != 0 {
t.Fatalf("confirmed suggestion = %s from %s, want confirmed at %v with the import provenance and trust level 0", phone.Status(), source.Origin(), later)
}
})
t.Run("confirmed with another value makes the claim manual", func(t *testing.T) {
content := mustCandidateContent(t, stored, CandidateProfileInput{Phone: confirmed("+79000000001")}, later)
phone, _ := content.Phone()
if phone.Source().Origin() != ProfileOriginManual || phone.Source().Quote() != "" {
t.Fatalf("changed suggestion origin = %s, want manual without the old quote", phone.Source().Origin())
}
})
t.Run("extracted for a value that is not a stored suggestion is refused", func(t *testing.T) {
input := CandidateProfileInput{
Stack: []ProfileClaimInput[string]{{Value: "Kafka", Status: ProfileClaimExtracted}, {Value: "Made up", Status: ProfileClaimExtracted}},
}
assertProfileFieldError(t, resolveErr(stored, input, later), "/stack/1/status")
})
t.Run("a confirmed value cannot go back to a suggestion", func(t *testing.T) {
confirmedStored := mustCandidateContent(t, stored, CandidateProfileInput{Phone: confirmed("+79000000000")}, later)
input := CandidateProfileInput{Phone: &ProfileClaimInput[string]{Value: "+79000000000", Status: ProfileClaimExtracted}}
assertProfileFieldError(t, resolveErr(confirmedStored, input, later), "/contacts/phone/status")
})
}
func resolveErr(stored CandidateProfileContent, input CandidateProfileInput, at time.Time) error {
_, err := ResolveCandidateProfileContent(stored, input, at)
return err
}
func assertProfileFieldError(t *testing.T, err error, pointer string) {
t.Helper()
var fieldError *CandidateProfileFieldError
if !errors.Is(err, ErrInvalidCandidateProfile) || !errors.As(err, &fieldError) {
t.Fatalf("error = %v, want ErrInvalidCandidateProfile with a field pointer", err)
}
if fieldError.Pointer != pointer {
t.Fatalf("pointer = %q, want %q (reason %q)", fieldError.Pointer, pointer, fieldError.Reason)
}
}
func TestResolveCandidateProfileContentRejectsInvalidValuesWithPointers(t *testing.T) {
long := strings.Repeat("a", 201)
tests := []struct {
name string
mutate func(*CandidateProfileInput)
pointer string
}{
{"full name with surrounding whitespace", func(in *CandidateProfileInput) { in.FullName = confirmed(" Anna") }, "/full_name/value"},
{"full name too long", func(in *CandidateProfileInput) { in.FullName = confirmed(long) }, "/full_name/value"},
{"email without a domain", func(in *CandidateProfileInput) { in.Email = confirmed("anna") }, "/contacts/email/value"},
{"phone outside E.164", func(in *CandidateProfileInput) { in.Phone = confirmed("8 900 000 00 00") }, "/contacts/phone/value"},
{"telegram without the at sign", func(in *CandidateProfileInput) { in.Telegram = confirmed("anna_sokolova") }, "/contacts/telegram/value"},
{"status missing", func(in *CandidateProfileInput) { in.FullName = &ProfileClaimInput[string]{Value: "Anna"} }, "/full_name/status"},
{"location with a line break", func(in *CandidateProfileInput) { in.Location = confirmed("Kazan\nTatarstan") }, "/terms/location/value"},
{"salary below the step", func(in *CandidateProfileInput) {
in.SalaryMinimum = confirmed(ProfileSalaryMinimum{Amount: 180500, TaxBasis: ProfileTaxNet})
}, "/terms/salary_minimum/value/amount"},
{"salary above the bound", func(in *CandidateProfileInput) {
in.SalaryMinimum = confirmed(ProfileSalaryMinimum{Amount: 101_000_000, TaxBasis: ProfileTaxNet})
}, "/terms/salary_minimum/value/amount"},
{"salary without a tax basis", func(in *CandidateProfileInput) {
in.SalaryMinimum = confirmed(ProfileSalaryMinimum{Amount: 180000})
}, "/terms/salary_minimum/value/tax_basis"},
{"stack tag with surrounding whitespace", func(in *CandidateProfileInput) { in.Stack = confirmedItems("Go", "Kafka ") }, "/stack/1/tag"},
{"stack tag repeated without regard to case", func(in *CandidateProfileInput) { in.Stack = confirmedItems("Kafka", "go", "KAFKA") }, "/stack/2/tag"},
{"too many tags", func(in *CandidateProfileInput) {
in.Stack = confirmedItems(make([]string, maxProfileStackItems+1)...)
}, "/stack"},
{"soft skill repeated", func(in *CandidateProfileInput) { in.SoftSkills = confirmedItems("Mentoring", "mentoring") }, "/soft_skills/1/skill"},
{"role with an unknown specialization", func(in *CandidateProfileInput) {
in.Roles = confirmedItems(ProfileRole{Specialization: "go"})
}, "/roles/0/specialization"},
{"role with an unknown grade", func(in *CandidateProfileInput) {
in.Roles = confirmedItems(ProfileRole{Specialization: SpecializationBackend, SelfAssessedGrade: "lead"})
}, "/roles/0/self_assessed_grade"},
{"role repeats a specialization", func(in *CandidateProfileInput) {
in.Roles = confirmedItems(ProfileRole{Specialization: SpecializationBackend}, ProfileRole{Specialization: SpecializationQA}, ProfileRole{Specialization: SpecializationBackend, SelfAssessedGrade: GradeJunior})
}, "/roles/2/specialization"},
{"experience month in a wrong format", func(in *CandidateProfileInput) {
in.Experience = confirmedItems(ProfileExperience{Specialization: SpecializationQA, StartedOn: "2024-3"})
}, "/experience/0/started_on"},
{"experience ends before it starts", func(in *CandidateProfileInput) {
in.Experience = confirmedItems(ProfileExperience{Specialization: SpecializationQA, StartedOn: "2024-05", EndedOn: "2024-04"})
}, "/experience/0/ended_on"},
{"experience starts in the future", func(in *CandidateProfileInput) {
in.Experience = confirmedItems(ProfileExperience{Specialization: SpecializationQA, StartedOn: "2026-11"})
}, "/experience/0/started_on"},
{"experience summary too long", func(in *CandidateProfileInput) {
in.Experience = confirmedItems(ProfileExperience{Specialization: SpecializationQA, StartedOn: "2024-05", Summary: strings.Repeat("a", maxProfileSummaryRunes+1)})
}, "/experience/0/summary"},
{"employer with a line break", func(in *CandidateProfileInput) {
in.Experience = confirmedItems(ProfileExperience{EmployerName: "A\nB", Specialization: SpecializationQA, StartedOn: "2024-05"})
}, "/experience/0/employer_name"},
{"too many roles", func(in *CandidateProfileInput) {
roles := make([]ProfileRole, len(specializationCodes)+1)
for index := range roles {
roles[index] = ProfileRole{Specialization: SpecializationBackend}
}
in.Roles = confirmedItems(roles...)
}, "/roles"},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
input := completeCandidateProfileInput()
test.mutate(&input)
err := resolveErr(CandidateProfileContent{}, input, candidateTestTime)
assertProfileFieldError(t, err, test.pointer)
})
}
}
func TestProfileErrorsNeverQuoteSubmittedValues(t *testing.T) {
const secret = "secret-phone-9000000000"
input := completeCandidateProfileInput()
input.Phone = confirmed(secret)
err := resolveErr(CandidateProfileContent{}, input, candidateTestTime)
if err == nil || strings.Contains(err.Error(), secret) {
t.Fatalf("error = %v, want a failure that does not repeat the submitted value", err)
}
}
func TestResolveCandidateProfileContentNormalizesValues(t *testing.T) {
input := completeCandidateProfileInput()
input.Experience = confirmedItems(ProfileExperience{Specialization: SpecializationQA, StartedOn: "2024-05", Summary: "one\r\ntwo"})
content := mustCandidateContent(t, CandidateProfileContent{}, input, candidateTestTime)
if got := content.Experience()[0].Value().Summary; got != "one\ntwo" {
t.Fatalf("summary = %q, want CRLF normalized to LF", got)
}
}
func TestCandidateProfileReplaceTellsAChangeFromANoOp(t *testing.T) {
userID := uuid.Must(uuid.NewV7())
empty, err := EmptyCandidateProfile(userID)
if err != nil || empty.Version() != 0 || !empty.CreatedAt().IsZero() {
t.Fatalf("EmptyCandidateProfile() = version %d, %v, want version 0", empty.Version(), err)
}
saved, changed, err := empty.Replace(completeCandidateProfileInput(), 0, candidateTestTime)
if err != nil || !changed {
t.Fatalf("Replace() = changed %v, %v, want a change", changed, err)
}
if saved.Version() != 0 || !saved.UpdatedAt().Equal(candidateTestTime) || !saved.CreatedAt().Equal(candidateTestTime) {
t.Fatalf("saved = version %d at %v, want the version left to storage", saved.Version(), saved.UpdatedAt())
}
// Sending the same decisions again changes nothing and keeps the
// confirmation time of the stored claims.
again, changed, err := saved.Replace(completeCandidateProfileInput(), 0, candidateTestTime.Add(time.Hour))
if err != nil || changed {
t.Fatalf("Replace(unchanged) = changed %v, %v, want a no-op", changed, err)
}
name, _ := again.Content().FullName()
if !name.Source().ConfirmedAt().Equal(candidateTestTime) || !again.UpdatedAt().Equal(candidateTestTime) {
t.Fatal("a no-op moved the confirmation or update time")
}
// A time before the last update, from clock skew, never moves it back.
edited := completeCandidateProfileInput()
edited.Location = confirmed("Moscow")
skewed, changed, err := saved.Replace(edited, 0, candidateTestTime.Add(-time.Minute))
if err != nil || !changed || !skewed.UpdatedAt().Equal(candidateTestTime) {
t.Fatalf("Replace(skewed clock) = changed %v, updated %v, %v, want the last update kept", changed, skewed.UpdatedAt(), err)
}
if _, _, err := (CandidateProfile{}).Replace(completeCandidateProfileInput(), 0, candidateTestTime); !errors.Is(err, ErrInvalidCandidateProfile) {
t.Fatalf("Replace(zero profile) error = %v, want ErrInvalidCandidateProfile", err)
}
if _, err := EmptyCandidateProfile(uuid.Nil); !errors.Is(err, ErrInvalidCandidateProfile) {
t.Fatalf("EmptyCandidateProfile(nil) error = %v, want ErrInvalidCandidateProfile", err)
}
}
func TestStoredClaimsRoundTripThroughRestore(t *testing.T) {
stored := suggestedContent(t)
input := completeCandidateProfileInput()
input.Phone = &ProfileClaimInput[string]{Value: "+79000000000", Status: ProfileClaimExtracted}
input.Stack = append(confirmedItems("PostgreSQL"), ProfileClaimInput[string]{Value: "Kafka", Status: ProfileClaimExtracted})
content := mustCandidateContent(t, stored, input, candidateTestTime)
rows, err := content.StoredClaims()
if err != nil {
t.Fatalf("StoredClaims() error = %v", err)
}
for _, row := range rows {
if row.TrustLevel != 0 {
t.Fatalf("row %s has trust level %d, want 0", row.Kind, row.TrustLevel)
}
}
restored, err := RestoreCandidateProfileContent(rows)
if err != nil || !restored.Equal(content) {
t.Fatalf("RestoreCandidateProfileContent() = equal %v, %v, want the same content", restored.Equal(content), err)
}
reversed := slicesReversed(rows)
if again, err := RestoreCandidateProfileContent(reversed); err != nil || !again.Equal(content) {
t.Fatalf("restore of rows in another order = equal %v, %v, want the same content", again.Equal(content), err)
}
}
func slicesReversed(rows []StoredProfileClaim) []StoredProfileClaim {
reversed := make([]StoredProfileClaim, len(rows))
for index, row := range rows {
reversed[len(rows)-1-index] = row
}
return reversed
}
func TestRestoreCandidateProfileContentRefusesRowsThatBreakARule(t *testing.T) {
manual := func(kind string, ordinal int, value string) StoredProfileClaim {
return StoredProfileClaim{Kind: kind, Ordinal: ordinal, Value: []byte(value), Status: "confirmed", Origin: "manual", ConfirmedAt: candidateTestTime}
}
tests := []struct {
name string
rows []StoredProfileClaim
}{
{"unknown kind", []StoredProfileClaim{manual("confirmed_grade", 0, `"senior"`)}},
{"trust level above zero", []StoredProfileClaim{func() StoredProfileClaim {
row := manual(profileKindFullName, 0, `"Anna"`)
row.TrustLevel = 1
return row
}()}},
{"manual claim with a quote", []StoredProfileClaim{func() StoredProfileClaim {
row := manual(profileKindFullName, 0, `"Anna"`)
row.Quote = "quote"
return row
}()}},
{"suggestion without an extractor version", []StoredProfileClaim{{Kind: profileKindFullName, Value: []byte(`"Anna"`), Status: "extracted", Origin: "imported"}}},
{"confirmed claim without a time", []StoredProfileClaim{{Kind: profileKindFullName, Value: []byte(`"Anna"`), Status: "confirmed", Origin: "manual"}}},
{"role with a confirmed grade key", []StoredProfileClaim{manual(profileKindRole, 0, `{"specialization":"backend","self_assessed_grade":null,"confirmed_grade":"senior"}`)}},
{"role with an unknown specialization", []StoredProfileClaim{manual(profileKindRole, 0, `{"specialization":"go","self_assessed_grade":null}`)}},
{"value of a wrong type", []StoredProfileClaim{manual(profileKindRelocation, 0, `"yes"`)}},
{"value with trailing data", []StoredProfileClaim{manual(profileKindFullName, 0, `"Anna" "Anna"`)}},
{"single field twice", []StoredProfileClaim{manual(profileKindFullName, 0, `"Anna"`), manual(profileKindFullName, 0, `"Anna"`)}},
{"list with a gap", []StoredProfileClaim{manual(profileKindStack, 1, `"Go"`)}},
{"list repeats an item", []StoredProfileClaim{manual(profileKindStack, 0, `"Go"`), manual(profileKindStack, 1, `"go"`)}},
{"salary in another currency", []StoredProfileClaim{manual(profileKindSalaryMinimum, 0, `{"amount":180000,"currency":"USD","period":"month","tax_basis":"net"}`)}},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
_, err := RestoreCandidateProfileContent(test.rows)
if !errors.Is(err, ErrInvalidCandidateProfile) {
t.Fatalf("RestoreCandidateProfileContent() error = %v, want ErrInvalidCandidateProfile", err)
}
if strings.Contains(err.Error(), "Anna") {
t.Fatalf("error = %v, want it not to quote a stored value", err)
}
})
}
}
func TestRestoreCandidateProfileValidatesTheRow(t *testing.T) {
userID := uuid.Must(uuid.NewV7())
stored := StoredCandidateProfile{UserID: userID, Version: 2, CreatedAt: candidateTestTime, UpdatedAt: candidateTestTime.Add(time.Hour)}
profile, err := RestoreCandidateProfile(stored)
if err != nil || profile.Version() != 2 || profile.UserID() != userID {
t.Fatalf("RestoreCandidateProfile() = version %d, %v, want the stored profile", profile.Version(), err)
}
for name, mutate := range map[string]func(*StoredCandidateProfile){
"nil user": func(row *StoredCandidateProfile) { row.UserID = uuid.Nil },
"version zero": func(row *StoredCandidateProfile) { row.Version = 0 },
"update before it": func(row *StoredCandidateProfile) { row.UpdatedAt = row.CreatedAt.Add(-time.Second) },
} {
row := stored
mutate(&row)
if _, err := RestoreCandidateProfile(row); !errors.Is(err, ErrInvalidCandidateProfile) {
t.Errorf("%s: error = %v, want ErrInvalidCandidateProfile", name, err)
}
}
}
// The profile types must offer no way to state a confirmed grade or a
// category: a confirmed category comes only from an assessment result.
func TestProfileTypesHaveNoConfirmedGradeOrCategory(t *testing.T) {
forbidden := []string{"confirmed", "category", "trust"}
for _, typ := range []reflect.Type{
reflect.TypeFor[ProfileRole](), reflect.TypeFor[ProfileExperience](), reflect.TypeFor[ProfileSalaryMinimum](),
reflect.TypeFor[CandidateProfileInput](), reflect.TypeFor[CandidateProfileContent](), reflect.TypeFor[CandidateProfile](),
} {
for index := range typ.NumField() {
name := strings.ToLower(typ.Field(index).Name)
for _, word := range forbidden {
if strings.Contains(name, word) {
t.Errorf("%s has a field %q, want none that names a confirmed grade, a category, or a trust level", typ.Name(), typ.Field(index).Name)
}
}
}
}
if got := reflect.TypeFor[ProfileRole]().NumField(); got != 2 {
t.Errorf("ProfileRole has %d fields, want the specialization and the self-assessed grade only", got)
}
}
func TestRestoreProfileClaimRefusesInconsistentStatus(t *testing.T) {
manual, err := NewManualProfileClaimSource(candidateTestTime)
if err != nil {
t.Fatalf("NewManualProfileClaimSource() error = %v", err)
}
if _, err := RestoreProfileClaim("x", ProfileClaimExtracted, manual); !errors.Is(err, ErrInvalidCandidateProfile) {
t.Errorf("manual suggestion error = %v, want ErrInvalidCandidateProfile", err)
}
if _, err := RestoreProfileClaim("x", ProfileClaimStatus("unknown"), manual); !errors.Is(err, ErrInvalidCandidateProfile) {
t.Errorf("unknown status error = %v, want ErrInvalidCandidateProfile", err)
}
if _, err := RestoreProfileClaim("x", ProfileClaimConfirmed, ProfileClaimSource{}); !errors.Is(err, ErrInvalidCandidateProfile) {
t.Errorf("zero source error = %v, want ErrInvalidCandidateProfile", err)
}
if _, err := NewManualProfileClaimSource(time.Time{}); !errors.Is(err, ErrInvalidCandidateProfile) {
t.Errorf("zero time error = %v, want ErrInvalidCandidateProfile", err)
}
}
func TestCandidateProfileValuesAreRedacted(t *testing.T) {
const name, summary, quote = "Anna Sokolova", "Moved the payout service", "from the resume"
userID := uuid.Must(uuid.NewV7())
empty, err := EmptyCandidateProfile(userID)
if err != nil {
t.Fatalf("EmptyCandidateProfile() error = %v", err)
}
input := completeCandidateProfileInput()
profile, _, err := empty.Replace(input, 0, candidateTestTime)
if err != nil {
t.Fatalf("Replace() error = %v", err)
}
claim, _ := profile.Content().FullName()
experience := profile.Content().Experience()[0]
salary, _ := profile.Content().SalaryMinimum()
suggested, _ := suggestedContent(t).Phone()
type holder struct {
Profile CandidateProfile
Content CandidateProfileContent
Claim ProfileClaim[string]
Experience ProfileClaim[ProfileExperience]
Salary ProfileClaim[ProfileSalaryMinimum]
Suggestion ProfileClaim[string]
Source ProfileClaimSource
}
value := holder{profile, profile.Content(), claim, experience, salary, suggested, suggested.Source()}
var logged bytes.Buffer
slog.New(slog.NewTextHandler(&logged, nil)).Info("profile", "profile", profile, "claim", claim, "holder", value)
outputs := []string{
fmt.Sprintf("%v %+v %#v %s", value, value, value, value),
fmt.Sprintf("%v %+v %#v", profile, profile, profile),
fmt.Sprintf("%v %+v %#v", experience.Value(), salary.Value(), claim),
logged.String(),
}
for _, output := range outputs {
for _, secret := range []string{name, summary, quote, "+79000000000", "180000", "Kazan", "Example Payments"} {
if strings.Contains(output, secret) {
t.Errorf("output %q leaks %q", output, secret)
}
}
}
}
// A client holding an old version gets a version conflict, not a validation
// error, when its decision depends on claims that another save changed.
func TestCandidateProfileReplaceChecksTheVersionBeforeStateDependentRules(t *testing.T) {
userID := uuid.Must(uuid.NewV7())
// Version 5 holds the phone confirmed by another tab.
stored, err := RestoreCandidateProfile(StoredCandidateProfile{
UserID: userID, Version: 5, CreatedAt: candidateTestTime, UpdatedAt: candidateTestTime,
Claims: []StoredProfileClaim{{
Kind: profileKindPhone, Value: []byte(`"+79000000000"`), Status: "confirmed", Origin: "extracted_from_resume",
Quote: "q", ExtractionVersion: "resume-rules.1", ConfirmedAt: candidateTestTime,
}},
})
if err != nil {
t.Fatalf("RestoreCandidateProfile() error = %v", err)
}
later := candidateTestTime.Add(time.Hour)
staleExtracted := CandidateProfileInput{Phone: &ProfileClaimInput[string]{Value: "+79000000000", Status: ProfileClaimExtracted}}
t.Run("stale extracted decision is a conflict", func(t *testing.T) {
if _, _, err := stored.Replace(staleExtracted, 4, later); !errors.Is(err, ErrCandidateProfileVersionConflict) {
t.Fatalf("error = %v, want ErrCandidateProfileVersionConflict", err)
}
})
t.Run("current version keeps the validation error", func(t *testing.T) {
assertProfileFieldError(t, errOnly(stored.Replace(staleExtracted, 5, later)), "/contacts/phone/status")
})
t.Run("stale body rule stays a validation error", func(t *testing.T) {
bad := CandidateProfileInput{Phone: confirmed("8 900")}
assertProfileFieldError(t, errOnly(stored.Replace(bad, 4, later)), "/contacts/phone/value")
})
t.Run("stale unchanged body is a no-op", func(t *testing.T) {
unchanged := CandidateProfileInput{Phone: confirmed("+79000000000")}
got, changed, err := stored.Replace(unchanged, 4, later)
if err != nil || changed || got.Version() != 5 {
t.Fatalf("Replace() = changed %v, %v, want a no-op", changed, err)
}
})
t.Run("stale changed body is a conflict", func(t *testing.T) {
changedBody := CandidateProfileInput{Phone: confirmed("+79000000001")}
if _, _, err := stored.Replace(changedBody, 4, later); !errors.Is(err, ErrCandidateProfileVersionConflict) {
t.Fatalf("error = %v, want ErrCandidateProfileVersionConflict", err)
}
})
t.Run("a future version never existed", func(t *testing.T) {
unchanged := CandidateProfileInput{Phone: confirmed("+79000000000")}
for _, version := range []int64{6, 99, -1} {
if _, _, err := stored.Replace(unchanged, version, later); !errors.Is(err, ErrCandidateProfileVersionConflict) {
t.Fatalf("version %d error = %v, want ErrCandidateProfileVersionConflict", version, err)
}
}
})
}
func errOnly(_ CandidateProfile, _ bool, err error) error { return err }