feat(profile): add the manual candidate profile contract and storage
This commit is contained in:
1 parent
d21fd49a42
commit
e52ffe7bcb
97 files changed
+20442
-63
No files matched your search
@@ -0,0 +1,612 @@
|
||||
//go:build integration
|
||||
|
||||
package integration_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"slices"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
|
||||
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
|
||||
"lincodex/backend/internal/domain"
|
||||
)
|
||||
|
||||
const (
|
||||
candidateProfileTestTimeout = 3 * time.Minute
|
||||
// concurrentProfileSaves advance one profile at once from the same
|
||||
// version, each on its own connection.
|
||||
concurrentProfileSaves = 8
|
||||
// candidateProfileMigrationVersion creates candidateProfileTables.
|
||||
candidateProfileMigrationVersion = 13
|
||||
)
|
||||
|
||||
var (
|
||||
candidateProfilesTable = pgx.Identifier{"candidate_profiles"}
|
||||
candidateProfileClaimsTable = pgx.Identifier{"candidate_profile_claims"}
|
||||
// candidateProfileTables reference users, so a TRUNCATE of users names
|
||||
// them through usersDependentTables.
|
||||
candidateProfileTables = []pgx.Identifier{candidateProfileClaimsTable, candidateProfilesTable}
|
||||
)
|
||||
|
||||
// candidateProfileFixture works on the bootstrap database. The tables are
|
||||
// truncated between subtests.
|
||||
type candidateProfileFixture struct {
|
||||
ctx context.Context
|
||||
pool *pgxpool.Pool
|
||||
queries *sqlc.Queries
|
||||
identity identityFixture
|
||||
now time.Time
|
||||
}
|
||||
|
||||
func TestCandidateProfileStorage(t *testing.T) {
|
||||
env := bootstrap(t, postgresService)
|
||||
ctx, cancel := context.WithTimeout(t.Context(), candidateProfileTestTimeout)
|
||||
defer cancel()
|
||||
pool := env.newPool(ctx, t)
|
||||
now := time.Now().UTC().Truncate(time.Microsecond)
|
||||
fixture := candidateProfileFixture{
|
||||
ctx: ctx,
|
||||
pool: pool,
|
||||
queries: sqlc.New(pool),
|
||||
identity: identityFixture{ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: now},
|
||||
now: now,
|
||||
}
|
||||
reset := func(t *testing.T) {
|
||||
t.Helper()
|
||||
truncateTables(ctx, t, pool, usersDependentTables...)
|
||||
}
|
||||
|
||||
t.Run("saves a profile without a file, the ML service, or an FSP account", func(t *testing.T) {
|
||||
reset(t)
|
||||
candidate := fixture.candidate(t, "candidate@example.com")
|
||||
|
||||
// Only the name: no resume, no import, no link of any kind.
|
||||
saved := fixture.save(t, candidate.ID, domain.CandidateProfileInput{
|
||||
FullName: confirmedDecision("Anna Sokolova"),
|
||||
}, 0)
|
||||
if saved.Version() != 1 {
|
||||
t.Fatalf("saved version = %d, want 1 for the first save", saved.Version())
|
||||
}
|
||||
read := fixture.load(t, candidate.ID)
|
||||
name, ok := read.Content().FullName()
|
||||
if !ok || name.Value() != "Anna Sokolova" || name.Source().Origin() != domain.ProfileOriginManual || name.Source().TrustLevel() != 0 {
|
||||
t.Fatalf("stored name = %v, want a manual claim of trust level 0", ok)
|
||||
}
|
||||
if _, ok := read.Content().Phone(); ok {
|
||||
t.Fatal("a field that was not sent came back set")
|
||||
}
|
||||
|
||||
// A profile row with no claim at all is allowed too.
|
||||
other := fixture.candidate(t, "empty@example.com")
|
||||
fixture.save(t, other.ID, domain.CandidateProfileInput{FullName: confirmedDecision("Placeholder")}, 0)
|
||||
fixture.save(t, other.ID, domain.CandidateProfileInput{}, 1)
|
||||
if empty := fixture.load(t, other.ID); empty.Version() != 2 || !empty.Content().Equal(domain.CandidateProfileContent{}) {
|
||||
t.Fatalf("empty profile = version %d, want version 2 with no claim", empty.Version())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a complete profile survives the round trip with its provenance", func(t *testing.T) {
|
||||
reset(t)
|
||||
candidate := fixture.candidate(t, "candidate@example.com")
|
||||
input := domain.CandidateProfileInput{
|
||||
FullName: confirmedDecision("Анна Соколова"),
|
||||
Email: confirmedDecision("anna.sokolova@example.com"),
|
||||
Phone: confirmedDecision("+79000000000"),
|
||||
Telegram: confirmedDecision("@anna_sokolova"),
|
||||
Stack: []domain.ProfileClaimInput[string]{{Value: "PostgreSQL", Status: domain.ProfileClaimConfirmed}, {Value: "Kafka", Status: domain.ProfileClaimConfirmed}},
|
||||
Roles: []domain.ProfileClaimInput[domain.ProfileRole]{
|
||||
{Value: domain.ProfileRole{Specialization: domain.SpecializationBackend, SelfAssessedGrade: domain.GradeMiddle}, Status: domain.ProfileClaimConfirmed},
|
||||
{Value: domain.ProfileRole{Specialization: domain.SpecializationQA}, Status: domain.ProfileClaimConfirmed},
|
||||
},
|
||||
Experience: []domain.ProfileClaimInput[domain.ProfileExperience]{{
|
||||
Value: domain.ProfileExperience{EmployerName: "Example Payments", Specialization: domain.SpecializationBackend, StartedOn: "2022-03", Summary: "Первая строка\nВторая строка"},
|
||||
Status: domain.ProfileClaimConfirmed,
|
||||
}, {
|
||||
Value: domain.ProfileExperience{Specialization: domain.SpecializationQA, StartedOn: "2020-01", EndedOn: "2022-02"},
|
||||
Status: domain.ProfileClaimConfirmed,
|
||||
}},
|
||||
SoftSkills: []domain.ProfileClaimInput[string]{{Value: "Mentoring", Status: domain.ProfileClaimConfirmed}},
|
||||
Location: confirmedDecision("Казань"),
|
||||
Relocation: confirmedDecision(true),
|
||||
SalaryMinimum: confirmedDecision(domain.ProfileSalaryMinimum{Amount: 180000, TaxBasis: domain.ProfileTaxNet}),
|
||||
}
|
||||
saved := fixture.save(t, candidate.ID, input, 0)
|
||||
read := fixture.load(t, candidate.ID)
|
||||
if !read.Content().Equal(saved.Content()) || read.Version() != 1 || !read.CreatedAt().Equal(fixture.now) || !read.UpdatedAt().Equal(fixture.now) {
|
||||
t.Fatalf("read profile = version %d, equal %v, want the saved content at version 1", read.Version(), read.Content().Equal(saved.Content()))
|
||||
}
|
||||
|
||||
// A suggestion stored by an import keeps its provenance, and the
|
||||
// candidate's confirmation keeps it and adds the time.
|
||||
fixture.insertSuggestion(t, candidate.ID, "contact_phone", 0, `"+79000001111"`)
|
||||
withSuggestion := fixture.load(t, candidate.ID)
|
||||
suggestion, ok := withSuggestion.Content().Phone()
|
||||
if !ok || suggestion.Status() != domain.ProfileClaimExtracted || suggestion.Source().Quote() != "Tel.: +7 900 000-11-11" ||
|
||||
suggestion.Source().ExtractionVersion() != "resume-rules.2026-10.1" || suggestion.Source().TrustLevel() != 0 {
|
||||
t.Fatal("the stored suggestion lost its provenance")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("the tables hold no link to a file, the ML service, or an FSP account", func(t *testing.T) {
|
||||
reset(t)
|
||||
rows, err := pool.Query(ctx, `
|
||||
SELECT table_name, column_name
|
||||
FROM information_schema.columns
|
||||
WHERE table_schema = 'public' AND table_name IN ('candidate_profiles', 'candidate_profile_claims')`)
|
||||
if err != nil {
|
||||
t.Fatalf("select columns: %v", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
var columns []string
|
||||
for rows.Next() {
|
||||
var table, column string
|
||||
if err := rows.Scan(&table, &column); err != nil {
|
||||
t.Fatalf("scan column: %v", err)
|
||||
}
|
||||
columns = append(columns, table+"."+column)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
t.Fatalf("read columns: %v", err)
|
||||
}
|
||||
slices.Sort(columns)
|
||||
want := []string{
|
||||
"candidate_profile_claims.confirmed_at", "candidate_profile_claims.extraction_version", "candidate_profile_claims.kind",
|
||||
"candidate_profile_claims.ordinal", "candidate_profile_claims.origin", "candidate_profile_claims.quote",
|
||||
"candidate_profile_claims.status", "candidate_profile_claims.trust_level", "candidate_profile_claims.user_id",
|
||||
"candidate_profile_claims.value",
|
||||
"candidate_profiles.created_at", "candidate_profiles.updated_at", "candidate_profiles.user_id", "candidate_profiles.version",
|
||||
}
|
||||
if !slices.Equal(columns, want) {
|
||||
t.Fatalf("columns = %v, want exactly %v: no file, ML, FSP, grade, or category column", columns, want)
|
||||
}
|
||||
|
||||
// The only foreign keys point at the account and at the profile row.
|
||||
var references []string
|
||||
fkRows, err := pool.Query(ctx, `
|
||||
SELECT conrelid::regclass::text || ' -> ' || confrelid::regclass::text
|
||||
FROM pg_constraint
|
||||
WHERE contype = 'f' AND conrelid IN ('candidate_profiles'::regclass, 'candidate_profile_claims'::regclass)`)
|
||||
if err != nil {
|
||||
t.Fatalf("select foreign keys: %v", err)
|
||||
}
|
||||
defer fkRows.Close()
|
||||
for fkRows.Next() {
|
||||
var reference string
|
||||
if err := fkRows.Scan(&reference); err != nil {
|
||||
t.Fatalf("scan foreign key: %v", err)
|
||||
}
|
||||
references = append(references, reference)
|
||||
}
|
||||
slices.Sort(references)
|
||||
if !slices.Equal(references, []string{"candidate_profile_claims -> candidate_profiles", "candidate_profiles -> users"}) {
|
||||
t.Fatalf("foreign keys = %v, want only the account and the profile row", references)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("constraints refuse a claim that breaks a rule of the contract", func(t *testing.T) {
|
||||
reset(t)
|
||||
candidate := fixture.candidate(t, "candidate@example.com")
|
||||
fixture.save(t, candidate.ID, domain.CandidateProfileInput{FullName: confirmedDecision("Anna")}, 0)
|
||||
|
||||
type claim struct {
|
||||
kind, value, status, origin string
|
||||
ordinal int
|
||||
trust int
|
||||
quote, extraction *string
|
||||
confirmed bool
|
||||
}
|
||||
good := claim{kind: "stack", value: `"Go"`, status: "confirmed", origin: "manual", ordinal: 5, confirmed: true}
|
||||
tests := []struct {
|
||||
name string
|
||||
mutate func(*claim)
|
||||
constraint string
|
||||
}{
|
||||
{"trust level above zero", func(c *claim) { c.trust = 1 }, "candidate_profile_claims_trust_level_zero"},
|
||||
{"unknown kind", func(c *claim) { c.kind = "confirmed_grade" }, "candidate_profile_claims_kind_ordinal"},
|
||||
{"single field at a position", func(c *claim) { c.kind, c.value, c.ordinal = "full_name", `"Anna"`, 1 }, "candidate_profile_claims_kind_ordinal"},
|
||||
{"list past its limit", func(c *claim) { c.ordinal = 30 }, "candidate_profile_claims_kind_ordinal"},
|
||||
// Also breaks the confirmation rule, which sorts first.
|
||||
{"unknown status", func(c *claim) { c.status = "verified" }, "candidate_profile_claims_confirmation"},
|
||||
{"unknown origin", func(c *claim) { c.origin = "fsp" }, "candidate_profile_claims_origin_known"},
|
||||
{"confirmed without a time", func(c *claim) { c.confirmed = false }, "candidate_profile_claims_confirmation"},
|
||||
{"manual with a quote", func(c *claim) { q := "quote"; c.quote = &q }, "candidate_profile_claims_origin_provenance"},
|
||||
{"import without an extractor version", func(c *claim) { c.origin = "imported" }, "candidate_profile_claims_origin_provenance"},
|
||||
{"suggestion that is manual", func(c *claim) { c.status, c.confirmed = "extracted", false }, "candidate_profile_claims_origin_provenance"},
|
||||
{"extractor version with a space", func(c *claim) { v := "a b"; c.origin, c.extraction = "imported", &v }, "candidate_profile_claims_extraction_version_format"},
|
||||
{"stack tag with surrounding whitespace", func(c *claim) { c.value = `" Go"` }, "candidate_profile_claims_stack_value"},
|
||||
{"stack tag that is not a string", func(c *claim) { c.value = `12` }, "candidate_profile_claims_stack_value"},
|
||||
{"phone outside E.164", func(c *claim) { c.kind, c.value, c.ordinal = "contact_phone", `"8 900 000"`, 0 }, "candidate_profile_claims_contact_phone_value"},
|
||||
{"telegram without the at sign", func(c *claim) { c.kind, c.value, c.ordinal = "contact_telegram", `"anna"`, 0 }, "candidate_profile_claims_contact_telegram_value"},
|
||||
{"relocation that is not a boolean", func(c *claim) { c.kind, c.value, c.ordinal = "terms_relocation", `"yes"`, 0 }, "candidate_profile_claims_terms_relocation_value"},
|
||||
{"salary that is not a multiple of 1000", func(c *claim) {
|
||||
c.kind, c.value, c.ordinal = "terms_salary_minimum", `{"amount":180500,"currency":"RUB","period":"month","tax_basis":"net"}`, 0
|
||||
}, "candidate_profile_claims_terms_salary_minimum_value"},
|
||||
{"salary in another currency", func(c *claim) {
|
||||
c.kind, c.value, c.ordinal = "terms_salary_minimum", `{"amount":180000,"currency":"USD","period":"month","tax_basis":"net"}`, 0
|
||||
}, "candidate_profile_claims_terms_salary_minimum_value"},
|
||||
{"role with a confirmed grade key", func(c *claim) {
|
||||
c.kind, c.value, c.ordinal = "role", `{"specialization":"backend","self_assessed_grade":null,"confirmed_grade":"senior"}`, 0
|
||||
}, "candidate_profile_claims_role_value"},
|
||||
{"role with an unknown grade", func(c *claim) {
|
||||
c.kind, c.value, c.ordinal = "role", `{"specialization":"backend","self_assessed_grade":"lead"}`, 0
|
||||
}, "candidate_profile_claims_role_value"},
|
||||
{"experience that ends before it starts", func(c *claim) {
|
||||
c.kind, c.ordinal = "experience", 0
|
||||
c.value = `{"employer_name":null,"specialization":"qa","started_on":"2024-05","ended_on":"2024-04","summary":null}`
|
||||
}, "candidate_profile_claims_experience_value"},
|
||||
{"experience month out of range", func(c *claim) {
|
||||
c.kind, c.ordinal = "experience", 0
|
||||
c.value = `{"employer_name":null,"specialization":"qa","started_on":"2024-13","ended_on":null,"summary":null}`
|
||||
}, "candidate_profile_claims_experience_value"},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
c := good
|
||||
test.mutate(&c)
|
||||
err := fixture.insertRaw(candidate.ID, c.kind, c.ordinal, c.value, c.status, c.origin, c.trust, c.quote, c.extraction, c.confirmed)
|
||||
assertConstraintViolation(t, err, "23514", test.constraint)
|
||||
})
|
||||
}
|
||||
|
||||
// The same row without the mutation is accepted, so each refusal
|
||||
// above comes from its own rule.
|
||||
if err := fixture.insertRaw(candidate.ID, good.kind, good.ordinal, good.value, good.status, good.origin, 0, nil, nil, true); err != nil {
|
||||
t.Fatalf("insert of the valid claim error = %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a tag, a skill, and a role specialization are stored once", func(t *testing.T) {
|
||||
reset(t)
|
||||
candidate := fixture.candidate(t, "candidate@example.com")
|
||||
fixture.save(t, candidate.ID, domain.CandidateProfileInput{FullName: confirmedDecision("Anna")}, 0)
|
||||
insert := func(kind string, ordinal int, value string) error {
|
||||
return fixture.insertRaw(candidate.ID, kind, ordinal, value, "confirmed", "manual", 0, nil, nil, true)
|
||||
}
|
||||
if err := insert("stack", 0, `"Go"`); err != nil {
|
||||
t.Fatalf("insert tag error = %v", err)
|
||||
}
|
||||
assertConstraintViolation(t, insert("stack", 1, `"Go"`), "23505", "candidate_profile_claims_stack_key")
|
||||
if err := insert("soft_skill", 0, `"Mentoring"`); err != nil {
|
||||
t.Fatalf("insert skill error = %v", err)
|
||||
}
|
||||
assertConstraintViolation(t, insert("soft_skill", 1, `"Mentoring"`), "23505", "candidate_profile_claims_soft_skill_key")
|
||||
if err := insert("role", 0, `{"specialization":"backend","self_assessed_grade":null}`); err != nil {
|
||||
t.Fatalf("insert role error = %v", err)
|
||||
}
|
||||
assertConstraintViolation(t, insert("role", 1, `{"specialization":"backend","self_assessed_grade":"junior"}`), "23505", "candidate_profile_claims_role_specialization_key")
|
||||
assertConstraintViolation(t, insert("role", 0, `{"specialization":"qa","self_assessed_grade":null}`), "23505", "candidate_profile_claims_pkey")
|
||||
})
|
||||
|
||||
t.Run("a profile needs an account and claims need a profile", func(t *testing.T) {
|
||||
reset(t)
|
||||
err := fixture.insertRawProfile(uuid.Must(uuid.NewV7()), 1)
|
||||
assertConstraintViolation(t, err, "23503", "candidate_profiles_user_id_fkey")
|
||||
|
||||
candidate := fixture.candidate(t, "candidate@example.com")
|
||||
assertConstraintViolation(t, fixture.insertRawProfile(candidate.ID, 0), "23514", "candidate_profiles_version_positive")
|
||||
err = fixture.insertRaw(candidate.ID, "full_name", 0, `"Anna"`, "confirmed", "manual", 0, nil, nil, true)
|
||||
assertConstraintViolation(t, err, "23503", "candidate_profile_claims_user_id_fkey")
|
||||
})
|
||||
|
||||
t.Run("erasing the account removes the profile and its claims", func(t *testing.T) {
|
||||
reset(t)
|
||||
candidate := fixture.candidate(t, "candidate@example.com")
|
||||
fixture.save(t, candidate.ID, domain.CandidateProfileInput{
|
||||
FullName: confirmedDecision("Anna"), Phone: confirmedDecision("+79000000000"),
|
||||
}, 0)
|
||||
if _, err := pool.Exec(ctx, `DELETE FROM users WHERE id = $1`, candidate.ID); err != nil {
|
||||
t.Fatalf("delete the account: %v", err)
|
||||
}
|
||||
for _, table := range candidateProfileTables {
|
||||
var count int
|
||||
if err := pool.QueryRow(ctx, `SELECT count(*) FROM `+table.Sanitize()).Scan(&count); err != nil || count != 0 {
|
||||
t.Fatalf("%s rows after the erasure = %d, %v, want 0", table[0], count, err)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("the version guards against a lost concurrent edit", func(t *testing.T) {
|
||||
reset(t)
|
||||
candidate := fixture.candidate(t, "candidate@example.com")
|
||||
fixture.save(t, candidate.ID, domain.CandidateProfileInput{FullName: confirmedDecision("Anna")}, 0)
|
||||
|
||||
// A second first save loses: the row exists.
|
||||
if _, err := fixture.queries.InsertCandidateProfile(ctx, sqlc.InsertCandidateProfileParams{UserID: pgtype.UUID{Bytes: candidate.ID, Valid: true}, At: pgTime(now)}); !errors.Is(err, pgx.ErrNoRows) {
|
||||
t.Fatalf("second InsertCandidateProfile() error = %v, want no row", err)
|
||||
}
|
||||
// A stale expected version matches no row.
|
||||
stale := sqlc.AdvanceCandidateProfileVersionParams{UserID: pgtype.UUID{Bytes: candidate.ID, Valid: true}, ExpectedVersion: 7, At: pgTime(now)}
|
||||
if _, err := fixture.queries.AdvanceCandidateProfileVersion(ctx, stale); !errors.Is(err, pgx.ErrNoRows) {
|
||||
t.Fatalf("AdvanceCandidateProfileVersion(stale) error = %v, want no row", err)
|
||||
}
|
||||
if got := fixture.load(t, candidate.ID).Version(); got != 1 {
|
||||
t.Fatalf("version after a stale advance = %d, want 1", got)
|
||||
}
|
||||
|
||||
// Eight savers read version 1 and race: exactly one wins.
|
||||
pool := env.newPoolWithMaxConns(ctx, t, concurrentProfileSaves)
|
||||
queries := sqlc.New(pool)
|
||||
var (
|
||||
group sync.WaitGroup
|
||||
mutex sync.Mutex
|
||||
winners int
|
||||
)
|
||||
for range concurrentProfileSaves {
|
||||
group.Go(func() {
|
||||
_, err := queries.AdvanceCandidateProfileVersion(ctx, sqlc.AdvanceCandidateProfileVersionParams{
|
||||
UserID: pgtype.UUID{Bytes: candidate.ID, Valid: true}, ExpectedVersion: 1, At: pgTime(now.Add(time.Minute)),
|
||||
})
|
||||
mutex.Lock()
|
||||
defer mutex.Unlock()
|
||||
switch {
|
||||
case err == nil:
|
||||
winners++
|
||||
case !errors.Is(err, pgx.ErrNoRows):
|
||||
t.Errorf("AdvanceCandidateProfileVersion() error = %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
group.Wait()
|
||||
if winners != 1 {
|
||||
t.Fatalf("%d concurrent saves advanced version 1, want exactly one", winners)
|
||||
}
|
||||
if got := fixture.load(t, candidate.ID).Version(); got != 2 {
|
||||
t.Fatalf("version after the race = %d, want 2", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("two concurrent first saves: one wins and the other sees a conflict", func(t *testing.T) {
|
||||
reset(t)
|
||||
candidate := fixture.candidate(t, "candidate@example.com")
|
||||
pool := env.newPoolWithMaxConns(ctx, t, concurrentProfileSaves)
|
||||
queries := sqlc.New(pool)
|
||||
var (
|
||||
group sync.WaitGroup
|
||||
mutex sync.Mutex
|
||||
winners int
|
||||
losers int
|
||||
)
|
||||
for range concurrentProfileSaves {
|
||||
group.Go(func() {
|
||||
_, err := queries.InsertCandidateProfile(ctx, sqlc.InsertCandidateProfileParams{UserID: pgtype.UUID{Bytes: candidate.ID, Valid: true}, At: pgTime(now)})
|
||||
mutex.Lock()
|
||||
defer mutex.Unlock()
|
||||
switch {
|
||||
case err == nil:
|
||||
winners++
|
||||
case errors.Is(err, pgx.ErrNoRows):
|
||||
losers++ // the caller answers version_conflict
|
||||
default:
|
||||
t.Errorf("InsertCandidateProfile() error = %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
group.Wait()
|
||||
if winners != 1 || losers != concurrentProfileSaves-1 {
|
||||
t.Fatalf("first saves: %d won and %d lost, want one winner and the rest conflicts", winners, losers)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("an earlier application clock never violates the update time rule", func(t *testing.T) {
|
||||
reset(t)
|
||||
candidate := fixture.candidate(t, "candidate@example.com")
|
||||
fixture.save(t, candidate.ID, domain.CandidateProfileInput{FullName: confirmedDecision("Anna")}, 0)
|
||||
advanced, err := fixture.queries.AdvanceCandidateProfileVersion(ctx, sqlc.AdvanceCandidateProfileVersionParams{
|
||||
UserID: pgtype.UUID{Bytes: candidate.ID, Valid: true}, ExpectedVersion: 1, At: pgTime(now.Add(-time.Hour)),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("AdvanceCandidateProfileVersion(earlier time) error = %v, want no CHECK violation", err)
|
||||
}
|
||||
if advanced.Version != 2 || !advanced.UpdatedAt.Time.Equal(now) {
|
||||
t.Fatalf("advanced = version %d at %v, want version 2 keeping %v", advanced.Version, advanced.UpdatedAt.Time, now)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("each account keeps its own profile", func(t *testing.T) {
|
||||
reset(t)
|
||||
first := fixture.candidate(t, "first@example.com")
|
||||
second := fixture.candidate(t, "second@example.com")
|
||||
fixture.save(t, first.ID, domain.CandidateProfileInput{FullName: confirmedDecision("First Person")}, 0)
|
||||
fixture.save(t, second.ID, domain.CandidateProfileInput{FullName: confirmedDecision("Second Person")}, 0)
|
||||
name, _ := fixture.load(t, second.ID).Content().FullName()
|
||||
if name.Value() != "Second Person" {
|
||||
t.Fatal("an account read the profile of another account")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestCandidateProfileMigrationRollsBack(t *testing.T) {
|
||||
env := bootstrap(t, postgresService)
|
||||
ctx, cancel := context.WithTimeout(t.Context(), candidateProfileTestTimeout)
|
||||
defer cancel()
|
||||
databaseURL := env.createIsolatedDatabase(ctx, t)
|
||||
migrator := newMigrator(t, databaseURL)
|
||||
pool := newPoolFor(ctx, t, databaseURL)
|
||||
if _, err := migrator.Up(ctx); err != nil {
|
||||
t.Fatalf("Up() error = %v", err)
|
||||
}
|
||||
assertTablesExist(ctx, t, pool, true, "candidate_profiles", "candidate_profile_claims")
|
||||
for {
|
||||
result, err := migrator.DownOne(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("DownOne() error = %v", err)
|
||||
}
|
||||
if result.Version == candidateProfileMigrationVersion {
|
||||
break
|
||||
}
|
||||
}
|
||||
assertTablesExist(ctx, t, pool, false, "candidate_profiles", "candidate_profile_claims")
|
||||
assertTablesExist(ctx, t, pool, true, "users")
|
||||
}
|
||||
|
||||
func confirmedDecision[V comparable](value V) *domain.ProfileClaimInput[V] {
|
||||
return &domain.ProfileClaimInput[V]{Value: value, Status: domain.ProfileClaimConfirmed}
|
||||
}
|
||||
|
||||
func pgTime(at time.Time) pgtype.Timestamptz { return pgtype.Timestamptz{Time: at, Valid: true} }
|
||||
|
||||
func (fixture candidateProfileFixture) candidate(t *testing.T, email string) domain.User {
|
||||
t.Helper()
|
||||
return fixture.identity.createUser(t, email, domain.ScenarioCandidate, fixture.now.Add(-time.Hour))
|
||||
}
|
||||
|
||||
// save applies input to the stored profile with the domain rules and stores
|
||||
// the result the way a repository does: a first save inserts version 1, and a
|
||||
// later one advances the version over expectedVersion and replaces the
|
||||
// claims, in one transaction.
|
||||
func (fixture candidateProfileFixture) save(t *testing.T, userID uuid.UUID, input domain.CandidateProfileInput, expectedVersion int64) domain.CandidateProfile {
|
||||
t.Helper()
|
||||
profile := fixture.loadOrEmpty(t, userID)
|
||||
if profile.Version() != expectedVersion {
|
||||
t.Fatalf("stored version = %d, want %d", profile.Version(), expectedVersion)
|
||||
}
|
||||
updated, _, err := profile.Replace(input, expectedVersion, fixture.now)
|
||||
if err != nil {
|
||||
t.Fatalf("Replace() error = %v", err)
|
||||
}
|
||||
rows, err := updated.Content().StoredClaims()
|
||||
if err != nil {
|
||||
t.Fatalf("StoredClaims() error = %v", err)
|
||||
}
|
||||
|
||||
tx, err := fixture.pool.Begin(fixture.ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("begin: %v", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(fixture.ctx) }()
|
||||
queries := fixture.queries.WithTx(tx)
|
||||
id := pgtype.UUID{Bytes: userID, Valid: true}
|
||||
if expectedVersion == 0 {
|
||||
_, err = queries.InsertCandidateProfile(fixture.ctx, sqlc.InsertCandidateProfileParams{UserID: id, At: pgTime(fixture.now)})
|
||||
} else {
|
||||
_, err = queries.AdvanceCandidateProfileVersion(fixture.ctx, sqlc.AdvanceCandidateProfileVersionParams{UserID: id, ExpectedVersion: expectedVersion, At: pgTime(fixture.now)})
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("store the profile row: %v", err)
|
||||
}
|
||||
if err := queries.DeleteCandidateProfileClaims(fixture.ctx, id); err != nil {
|
||||
t.Fatalf("delete claims: %v", err)
|
||||
}
|
||||
for _, row := range rows {
|
||||
err := queries.InsertCandidateProfileClaim(fixture.ctx, sqlc.InsertCandidateProfileClaimParams{
|
||||
UserID: id, Kind: row.Kind, Ordinal: int16(row.Ordinal), Value: row.Value, Status: row.Status, Origin: row.Origin,
|
||||
Quote: optionalText(row.Quote), ExtractionVersion: optionalText(row.ExtractionVersion), ConfirmedAt: optionalTime(row.ConfirmedAt),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("insert claim %s: %v", row.Kind, err)
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(fixture.ctx); err != nil {
|
||||
t.Fatalf("commit: %v", err)
|
||||
}
|
||||
return fixture.load(t, userID)
|
||||
}
|
||||
|
||||
func optionalText(value string) pgtype.Text { return pgtype.Text{String: value, Valid: value != ""} }
|
||||
|
||||
func optionalTime(value time.Time) pgtype.Timestamptz {
|
||||
return pgtype.Timestamptz{Time: value, Valid: !value.IsZero()}
|
||||
}
|
||||
|
||||
// loadOrEmpty reads the profile with the one statement a repository uses, so
|
||||
// the version and the claims come from one snapshot. An account without a
|
||||
// profile gets the empty profile of version 0.
|
||||
func (fixture candidateProfileFixture) loadOrEmpty(t *testing.T, userID uuid.UUID) domain.CandidateProfile {
|
||||
t.Helper()
|
||||
rows, err := fixture.queries.ReadCandidateProfile(fixture.ctx, pgtype.UUID{Bytes: userID, Valid: true})
|
||||
if err != nil {
|
||||
t.Fatalf("ReadCandidateProfile() error = %v", err)
|
||||
}
|
||||
if len(rows) == 0 {
|
||||
empty, err := domain.EmptyCandidateProfile(userID)
|
||||
if err != nil {
|
||||
t.Fatalf("EmptyCandidateProfile() error = %v", err)
|
||||
}
|
||||
return empty
|
||||
}
|
||||
stored := domain.StoredCandidateProfile{UserID: userID, Version: rows[0].Version, CreatedAt: rows[0].CreatedAt.Time, UpdatedAt: rows[0].UpdatedAt.Time}
|
||||
for _, row := range rows {
|
||||
if !row.Kind.Valid {
|
||||
continue // a profile without claims: the LEFT JOIN row has none
|
||||
}
|
||||
stored.Claims = append(stored.Claims, domain.StoredProfileClaim{
|
||||
Kind: row.Kind.String, Ordinal: int(row.Ordinal.Int16), Value: row.Value, Status: row.Status.String, Origin: row.Origin.String,
|
||||
TrustLevel: int(row.TrustLevel.Int16), Quote: row.Quote.String, ExtractionVersion: row.ExtractionVersion.String,
|
||||
ConfirmedAt: row.ConfirmedAt.Time,
|
||||
})
|
||||
}
|
||||
profile, err := domain.RestoreCandidateProfile(stored)
|
||||
if err != nil {
|
||||
t.Fatalf("RestoreCandidateProfile() error = %v", err)
|
||||
}
|
||||
return profile
|
||||
}
|
||||
|
||||
func (fixture candidateProfileFixture) load(t *testing.T, userID uuid.UUID) domain.CandidateProfile {
|
||||
t.Helper()
|
||||
profile := fixture.loadOrEmpty(t, userID)
|
||||
if profile.Version() == 0 {
|
||||
t.Fatal("the account has no stored profile")
|
||||
}
|
||||
return profile
|
||||
}
|
||||
|
||||
// insertSuggestion stores an unconfirmed claim of an import, which no
|
||||
// operation produces yet, over the stored one of the same kind and position.
|
||||
func (fixture candidateProfileFixture) insertSuggestion(t *testing.T, userID uuid.UUID, kind string, ordinal int, value string) {
|
||||
t.Helper()
|
||||
quote, version := "Tel.: +7 900 000-11-11", "resume-rules.2026-10.1"
|
||||
if _, err := fixture.pool.Exec(fixture.ctx, `DELETE FROM candidate_profile_claims WHERE user_id = $1 AND kind = $2 AND ordinal = $3`, userID, kind, ordinal); err != nil {
|
||||
t.Fatalf("remove the stored claim: %v", err)
|
||||
}
|
||||
if err := fixture.insertRaw(userID, kind, ordinal, value, "extracted", "extracted_from_resume", 0, "e, &version, false); err != nil {
|
||||
t.Fatalf("insert the suggestion: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (fixture candidateProfileFixture) insertRaw(
|
||||
userID uuid.UUID, kind string, ordinal int, value, status, origin string, trust int, quote, extraction *string, confirmed bool,
|
||||
) error {
|
||||
var confirmedAt any
|
||||
if confirmed {
|
||||
confirmedAt = fixture.now
|
||||
}
|
||||
_, err := fixture.pool.Exec(fixture.ctx, `
|
||||
INSERT INTO candidate_profile_claims
|
||||
(user_id, kind, ordinal, value, status, origin, trust_level, quote, extraction_version, confirmed_at)
|
||||
VALUES ($1, $2, $3, $4::jsonb, $5, $6, $7, $8, $9, $10)`,
|
||||
userID, kind, ordinal, value, status, origin, trust, quote, extraction, confirmedAt)
|
||||
return err
|
||||
}
|
||||
|
||||
func (fixture candidateProfileFixture) insertRawProfile(userID uuid.UUID, version int64) error {
|
||||
_, err := fixture.pool.Exec(fixture.ctx,
|
||||
`INSERT INTO candidate_profiles (user_id, version, created_at, updated_at) VALUES ($1, $2, $3, $3)`,
|
||||
userID, version, fixture.now)
|
||||
return err
|
||||
}
|
||||
|
||||
// assertConstraintViolation checks the SQLSTATE and the constraint name, never
|
||||
// the message: a failing row can quote the personal data it held. PostgreSQL
|
||||
// reports the first failing CHECK in name order, so a row that breaks two
|
||||
// rules names the one that sorts first; a caller lists the acceptable ones.
|
||||
func assertConstraintViolation(t *testing.T, err error, code string, constraints ...string) {
|
||||
t.Helper()
|
||||
var pgError *pgconn.PgError
|
||||
if !errors.As(err, &pgError) {
|
||||
t.Fatalf("error = %v, want a PostgreSQL error %s on %v", err, code, constraints)
|
||||
}
|
||||
if pgError.Code != code || !slices.Contains(constraints, pgError.ConstraintName) {
|
||||
t.Fatalf("error = %s on %q, want %s on one of %v", pgError.Code, pgError.ConstraintName, code, constraints)
|
||||
}
|
||||
}
|
||||
@@ -41,7 +41,7 @@ var (
|
||||
// usersDependentTables is every table that references users, directly or
|
||||
// through another table of the list. A TRUNCATE of users must name all of
|
||||
// them, so a migration that adds such a table adds it here.
|
||||
usersDependentTables = slices.Concat(identityTables, deliveryTables, consentTables, organizationTables)
|
||||
usersDependentTables = slices.Concat(identityTables, deliveryTables, consentTables, organizationTables, candidateProfileTables)
|
||||
)
|
||||
|
||||
// organizationFixture works on the bootstrap database. The tables are
|
||||
|
||||
Reference in new issue
Block a user