feat: persist candidate questionnaires and enforce company quotas
This commit is contained in:
1 parent
73c7caa225
commit
3a61a8e8bb
51 files changed
+6280
-38
No files matched your search
@@ -0,0 +1,529 @@
|
||||
//go:build integration
|
||||
|
||||
package integration_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
"lincodex/backend/internal/usecase/companyquota"
|
||||
"lincodex/backend/internal/usecase/policy"
|
||||
)
|
||||
|
||||
const companyQuotaTestTimeout = 5 * time.Minute
|
||||
|
||||
type companyQuotaFixture struct {
|
||||
ctx context.Context
|
||||
pool *pgxpool.Pool
|
||||
clock *testClock
|
||||
transactor *postgresadapter.Transactor
|
||||
service *companyquota.Service
|
||||
organizations organizationFixture
|
||||
policies outbound.PolicyRepository
|
||||
version domain.PolicyVersion
|
||||
}
|
||||
|
||||
func TestCompanyQuota(t *testing.T) {
|
||||
env := bootstrap(t, postgresService)
|
||||
ctx, cancel := context.WithTimeout(t.Context(), companyQuotaTestTimeout)
|
||||
defer cancel()
|
||||
databaseURL := env.createIsolatedDatabase(ctx, t)
|
||||
applyMigrations(ctx, t, databaseURL)
|
||||
pool := newPoolFor(ctx, t, databaseURL)
|
||||
|
||||
clock := &testClock{now: time.Now().UTC().Add(5 * time.Minute).Truncate(time.Microsecond)}
|
||||
identity := identityFixture{ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: clock.Now()}
|
||||
transactor := postgresadapter.NewTransactor(pool)
|
||||
organizationFixture := organizationFixture{
|
||||
ctx: ctx, pool: pool, identity: identity, transactor: transactor, now: clock.Now(),
|
||||
}
|
||||
policyStore := postgresadapter.NewPolicyStore(pool)
|
||||
if _, err := policy.NewPublisher(policyStore.Policies(), clock.Now).EnsureDemoProductPolicy(ctx); err != nil {
|
||||
t.Fatalf("EnsureDemoProductPolicy() error = %v", err)
|
||||
}
|
||||
version, err := policyStore.Policies().GetEffective(ctx, domain.ProductPolicyKey, clock.Now())
|
||||
if err != nil {
|
||||
t.Fatalf("GetEffective(product) error = %v", err)
|
||||
}
|
||||
fixture := companyQuotaFixture{
|
||||
ctx: ctx, pool: pool, clock: clock, transactor: transactor,
|
||||
service: companyquota.NewService(clock.Now), organizations: organizationFixture,
|
||||
policies: policyStore.Policies(), version: version,
|
||||
}
|
||||
|
||||
t.Run("E0 shares limits across requests and concurrent final reservations", func(t *testing.T) {
|
||||
organization, _ := fixture.newOrganization(t, "e0-boundary", domain.OrganizationVerificationE0)
|
||||
var firstCandidate uuid.UUID
|
||||
var boundaryCandidate uuid.UUID
|
||||
for range 9 {
|
||||
fixture.reserveInvitationAllowed(t, organization, uuid.New())
|
||||
}
|
||||
for index := range 49 {
|
||||
candidateID := fixture.newCandidateID(t)
|
||||
if index == 0 {
|
||||
firstCandidate = candidateID
|
||||
} else if index == 1 {
|
||||
boundaryCandidate = candidateID
|
||||
}
|
||||
fixture.reserveCardViewAllowed(t, organization, candidateID)
|
||||
}
|
||||
|
||||
type result struct {
|
||||
decision outbound.CompanyQuotaDecision
|
||||
err error
|
||||
kind string
|
||||
}
|
||||
start := make(chan struct{})
|
||||
results := make(chan result, 4)
|
||||
var workers sync.WaitGroup
|
||||
for range 2 {
|
||||
workers.Add(1)
|
||||
go func() {
|
||||
defer workers.Done()
|
||||
<-start
|
||||
decision, err := fixture.reserveInvitation(organization, uuid.New())
|
||||
results <- result{decision: decision, err: err, kind: "invitation"}
|
||||
}()
|
||||
}
|
||||
for range 2 {
|
||||
candidateID := fixture.newCandidateID(t)
|
||||
workers.Add(1)
|
||||
go func() {
|
||||
defer workers.Done()
|
||||
<-start
|
||||
decision, err := fixture.reserveCardView(organization, candidateID)
|
||||
results <- result{decision: decision, err: err, kind: "view"}
|
||||
}()
|
||||
}
|
||||
close(start)
|
||||
workers.Wait()
|
||||
close(results)
|
||||
|
||||
allowedInvitations, deniedInvitations := 0, 0
|
||||
allowedViews, deniedViews := 0, 0
|
||||
for result := range results {
|
||||
if result.err != nil {
|
||||
t.Fatalf("concurrent quota reservation error = %v", result.err)
|
||||
}
|
||||
switch result.kind {
|
||||
case "invitation":
|
||||
if result.decision.Allowed && result.decision.RetryAt.IsZero() {
|
||||
allowedInvitations++
|
||||
} else if !result.decision.Allowed && result.decision.RetryAt.Equal(fixture.clock.Now().Add(7*24*time.Hour)) {
|
||||
deniedInvitations++
|
||||
} else {
|
||||
t.Fatalf("unexpected invitation decision: %+v", result.decision)
|
||||
}
|
||||
case "view":
|
||||
if result.decision.Allowed && result.decision.RetryAt.IsZero() {
|
||||
allowedViews++
|
||||
} else if !result.decision.Allowed && result.decision.RetryAt.Equal(fixture.clock.Now().Add(24*time.Hour)) {
|
||||
deniedViews++
|
||||
} else {
|
||||
t.Fatalf("unexpected card-view decision: %+v", result.decision)
|
||||
}
|
||||
default:
|
||||
t.Fatalf("unexpected reservation kind %q", result.kind)
|
||||
}
|
||||
}
|
||||
if allowedInvitations != 1 || deniedInvitations != 1 || allowedViews != 1 || deniedViews != 1 {
|
||||
t.Fatalf("concurrent invitation/view results: allowed=%d/%d denied=%d/%d", allowedInvitations, allowedViews, deniedInvitations, deniedViews)
|
||||
}
|
||||
fixture.assertQuotaRowCounts(t, organization.ID(), 10, 50)
|
||||
fixture.assertStoredEvidence(t, organization.ID(), domain.OrganizationVerificationE0, domain.OrganizationBasisConfirmedEmail)
|
||||
|
||||
// A repeated card in the active window is shared by the organization.
|
||||
fixture.clock.Advance(23 * time.Hour)
|
||||
repeated, err := fixture.reserveCardView(organization, firstCandidate)
|
||||
if err != nil || !repeated.Allowed || !repeated.Reused {
|
||||
t.Fatalf("ReserveCardView(repeat) = %+v, %v; want an organization-level reuse", repeated, err)
|
||||
}
|
||||
fixture.clock.Set(fixture.clock.Now().Add(time.Hour))
|
||||
atDay := fixture.clock.Now()
|
||||
for _, step := range []struct {
|
||||
name string
|
||||
id uuid.UUID
|
||||
call func(domain.Organization, uuid.UUID) (outbound.CompanyQuotaDecision, error)
|
||||
}{
|
||||
{name: "card view at the 24-hour boundary", id: boundaryCandidate, call: fixture.reserveCardView},
|
||||
{name: "invitation remains charged during the first day", id: uuid.New(), call: fixture.reserveInvitation},
|
||||
} {
|
||||
decision, err := step.call(organization, step.id)
|
||||
if err != nil {
|
||||
t.Fatalf("%s error = %v", step.name, err)
|
||||
}
|
||||
if step.name == "card view at the 24-hour boundary" {
|
||||
if !decision.Allowed || decision.Reused {
|
||||
t.Fatalf("%s decision = %+v, want a new allowed view", step.name, decision)
|
||||
}
|
||||
} else if decision.Allowed || !decision.RetryAt.Equal(atDay.Add(6*24*time.Hour)) {
|
||||
t.Fatalf("%s decision = %+v, want retry at the 7-day boundary", step.name, decision)
|
||||
}
|
||||
}
|
||||
fixture.assertActiveQuotaCounts(t, organization.ID(), atDay, 10, 2)
|
||||
fixture.assertQuotaRowCounts(t, organization.ID(), 10, 2)
|
||||
|
||||
fixture.clock.Set(atDay.Add(6 * 24 * time.Hour))
|
||||
newInvitation := uuid.New()
|
||||
decision, err := fixture.reserveInvitation(organization, newInvitation)
|
||||
if err != nil || !decision.Allowed || decision.Reused {
|
||||
t.Fatalf("ReserveInvitation(at 7 days) = %+v, %v; want a new allowed invitation", decision, err)
|
||||
}
|
||||
fixture.assertActiveQuotaCounts(t, organization.ID(), fixture.clock.Now(), 1, 0)
|
||||
|
||||
// The same invitation ID stays idempotent beyond the rolling window,
|
||||
// independently of any request idempotency key used by its caller.
|
||||
oldInvitationID := uuid.New()
|
||||
fixture.reserveInvitationAllowed(t, organization, oldInvitationID)
|
||||
fixture.clock.Advance(8 * 24 * time.Hour)
|
||||
reused, err := fixture.reserveInvitation(organization, oldInvitationID)
|
||||
if err != nil || !reused.Allowed || !reused.Reused {
|
||||
t.Fatalf("ReserveInvitation(old ID after 8 days) = %+v, %v; want retained idempotent usage", reused, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("E1 enforces the stored 40 and 150 limits", func(t *testing.T) {
|
||||
organization, _ := fixture.newOrganization(t, "e1-boundary", domain.OrganizationVerificationE1)
|
||||
for range 40 {
|
||||
fixture.reserveInvitationAllowed(t, organization, uuid.New())
|
||||
}
|
||||
deniedInvitation, err := fixture.reserveInvitation(organization, uuid.New())
|
||||
if err != nil || deniedInvitation.Allowed || !deniedInvitation.RetryAt.Equal(fixture.clock.Now().Add(7*24*time.Hour)) {
|
||||
t.Fatalf("E1 invitation 41 = %+v, %v; want denial for one week", deniedInvitation, err)
|
||||
}
|
||||
for range 150 {
|
||||
fixture.reserveCardViewAllowed(t, organization, fixture.newCandidateID(t))
|
||||
}
|
||||
deniedView, err := fixture.reserveCardView(organization, fixture.newCandidateID(t))
|
||||
if err != nil || deniedView.Allowed || !deniedView.RetryAt.Equal(fixture.clock.Now().Add(24*time.Hour)) {
|
||||
t.Fatalf("E1 card view 151 = %+v, %v; want denial for 24 hours", deniedView, err)
|
||||
}
|
||||
fixture.assertQuotaRowCounts(t, organization.ID(), 40, 150)
|
||||
fixture.assertStoredEvidence(t, organization.ID(), domain.OrganizationVerificationE1, domain.OrganizationBasisCorporateDomain)
|
||||
})
|
||||
|
||||
t.Run("active E2 policy permits verified organizations and rejects a forged tier snapshot", func(t *testing.T) {
|
||||
policyDocument := domain.DemoProductPolicyV1()
|
||||
policyDocument.OrganizationQuotas.TierE2.Active = true
|
||||
activePolicy, err := policy.NewPublisher(fixture.policies, fixture.clock.Now).Publish(fixture.ctx, policy.PublishInput{
|
||||
Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, Author: "system:quota-test",
|
||||
EffectiveAt: fixture.clock.Now(), Policy: policyDocument,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("publish active E2 policy: %v", err)
|
||||
}
|
||||
if quota := activePolicy.Policy().OrganizationQuotas.TierE2; !quota.Active ||
|
||||
quota.InvitationsPerWindow != 100 || quota.DistinctCardViewsPerWindow != 400 {
|
||||
t.Fatalf("active E2 policy limits = %+v, want 100 invitations and 400 views", quota)
|
||||
}
|
||||
fixture.version = activePolicy
|
||||
|
||||
verified, _ := fixture.newOrganization(t, "active-e2", domain.OrganizationVerificationE2)
|
||||
invitation, err := fixture.reserveInvitation(verified, uuid.New())
|
||||
if err != nil || !invitation.Allowed || invitation.Reused {
|
||||
t.Fatalf("ReserveInvitation(verified E2) = %+v, %v; want an allowed new reservation", invitation, err)
|
||||
}
|
||||
view, err := fixture.reserveCardView(verified, fixture.newCandidateID(t))
|
||||
if err != nil || !view.Allowed || view.Reused {
|
||||
t.Fatalf("ReserveCardView(verified E2) = %+v, %v; want an allowed new reservation", view, err)
|
||||
}
|
||||
fixture.assertQuotaRowCounts(t, verified.ID(), 1, 1)
|
||||
fixture.assertStoredEvidence(t, verified.ID(), domain.OrganizationVerificationE2, domain.OrganizationBasisRequisitesAndAuthority)
|
||||
|
||||
e0Organization, _ := fixture.newOrganization(t, "forged-e2", domain.OrganizationVerificationE0)
|
||||
forgedE2, err := domain.RestoreOrganization(domain.StoredOrganization{
|
||||
ID: e0Organization.ID(), Name: e0Organization.Profile().Name(),
|
||||
VerificationLevel: string(domain.OrganizationVerificationE2),
|
||||
VerificationBasis: string(domain.OrganizationBasisRequisitesAndAuthority),
|
||||
VerificationChangedAt: fixture.clock.Now().Add(-time.Minute),
|
||||
Version: e0Organization.Version(), CreatedAt: e0Organization.CreatedAt(), UpdatedAt: e0Organization.UpdatedAt(),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("restore forged E2 snapshot for E0 organization: %v", err)
|
||||
}
|
||||
forgedQuota, err := domain.NewCompanyQuota(forgedE2, activePolicy, fixture.clock.Now())
|
||||
if err != nil {
|
||||
t.Fatalf("build forged E2 snapshot: %v", err)
|
||||
}
|
||||
if err := fixture.reserveWithSnapshot(e0Organization, forgedQuota, uuid.New()); !errors.Is(err, outbound.ErrCompanyQuotaSnapshotChanged) {
|
||||
t.Fatalf("reserve with forged E2 snapshot against stored E0 organization error = %v, want snapshot mismatch", err)
|
||||
}
|
||||
fixture.assertQuotaRowCounts(t, e0Organization.ID(), 0, 0)
|
||||
})
|
||||
|
||||
t.Run("a repeated view refreshes monotonically when application time moves backward", func(t *testing.T) {
|
||||
organization, _ := fixture.newOrganization(t, "view-clock", domain.OrganizationVerificationE0)
|
||||
candidateID := fixture.newCandidateID(t)
|
||||
fixture.reserveCardViewAllowed(t, organization, candidateID)
|
||||
firstSeen := fixture.clock.Now()
|
||||
fixture.clock.Advance(time.Hour)
|
||||
fixture.reserveCardViewReused(t, organization, candidateID)
|
||||
fixture.clock.Set(firstSeen.Add(30 * time.Minute))
|
||||
fixture.reserveCardViewReused(t, organization, candidateID)
|
||||
|
||||
var lastSeen time.Time
|
||||
if err := fixture.pool.QueryRow(fixture.ctx, `
|
||||
SELECT last_seen_at FROM company_card_view_quota_usage
|
||||
WHERE organization_id = $1 AND candidate_id = $2`, organization.ID(), candidateID).Scan(&lastSeen); err != nil {
|
||||
t.Fatalf("read repeated view timestamp: %v", err)
|
||||
}
|
||||
if !lastSeen.Equal(firstSeen.Add(time.Hour)) {
|
||||
t.Fatalf("last_seen_at = %s, want monotonic time %s", lastSeen, firstSeen.Add(time.Hour))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("candidate deletion clears card-view data but leaves invitation quota evidence", func(t *testing.T) {
|
||||
organization, _ := fixture.newOrganization(t, "candidate-delete", domain.OrganizationVerificationE0)
|
||||
candidateID := fixture.newCandidateID(t)
|
||||
fixture.reserveInvitationAllowed(t, organization, candidateID)
|
||||
fixture.reserveCardViewAllowed(t, organization, candidateID)
|
||||
|
||||
if _, err := fixture.pool.Exec(fixture.ctx, `DELETE FROM users WHERE id = $1`, candidateID); err != nil {
|
||||
t.Fatalf("delete candidate: %v", err)
|
||||
}
|
||||
fixture.assertQuotaRowCounts(t, organization.ID(), 1, 0)
|
||||
})
|
||||
|
||||
t.Run("rollback and stale trust or policy snapshots write no usage", func(t *testing.T) {
|
||||
organization, _ := fixture.newOrganization(t, "snapshot-check", domain.OrganizationVerificationE0)
|
||||
quota := fixture.quota(t, organization, fixture.version)
|
||||
rollbackMarker := errors.New("test transaction rollback")
|
||||
err := fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
decision, err := unit.CompanyQuotas().ReserveInvitation(ctx, quota, uuid.New())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !decision.Allowed {
|
||||
return errors.New("test invitation was unexpectedly denied")
|
||||
}
|
||||
return rollbackMarker
|
||||
})
|
||||
if !errors.Is(err, rollbackMarker) {
|
||||
t.Fatalf("transaction rollback error = %v, want marker", err)
|
||||
}
|
||||
fixture.assertQuotaRowCounts(t, organization.ID(), 0, 0)
|
||||
|
||||
if _, err := fixture.pool.Exec(fixture.ctx, `
|
||||
UPDATE organizations
|
||||
SET verification_level = 'e1', verification_basis = 'corporate_domain', verification_changed_at = $2
|
||||
WHERE id = $1`, organization.ID(), fixture.clock.Now().Add(-time.Minute)); err != nil {
|
||||
t.Fatalf("change stored organization verification: %v", err)
|
||||
}
|
||||
staleTrustErr := fixture.reserveWithSnapshot(organization, quota, uuid.New())
|
||||
if !errors.Is(staleTrustErr, outbound.ErrCompanyQuotaSnapshotChanged) {
|
||||
t.Fatalf("reserve with stale organization trust error = %v, want snapshot mismatch", staleTrustErr)
|
||||
}
|
||||
fixture.assertQuotaRowCounts(t, organization.ID(), 0, 0)
|
||||
|
||||
policyOrganization, _ := fixture.newOrganization(t, "policy-check", domain.OrganizationVerificationE0)
|
||||
stalePolicyQuota := fixture.quota(t, policyOrganization, fixture.version)
|
||||
publisher := policy.NewPublisher(fixture.policies, fixture.clock.Now)
|
||||
_, err = publisher.Publish(fixture.ctx, policy.PublishInput{
|
||||
Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, Author: "system:quota-test",
|
||||
EffectiveAt: fixture.clock.Now(), Policy: domain.DemoProductPolicyV1(),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("publish next effective product policy: %v", err)
|
||||
}
|
||||
stalePolicyErr := fixture.reserveWithSnapshot(policyOrganization, stalePolicyQuota, uuid.New())
|
||||
if !errors.Is(stalePolicyErr, outbound.ErrCompanyQuotaSnapshotChanged) {
|
||||
t.Fatalf("reserve with stale policy error = %v, want snapshot mismatch", stalePolicyErr)
|
||||
}
|
||||
fixture.assertQuotaRowCounts(t, policyOrganization.ID(), 0, 0)
|
||||
})
|
||||
|
||||
t.Run("inactive E2 and E3 fail closed before recording usage", func(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
level domain.OrganizationVerificationLevel
|
||||
basis domain.OrganizationVerificationBasis
|
||||
}{
|
||||
{name: "inactive E2", level: domain.OrganizationVerificationE2, basis: domain.OrganizationBasisRequisitesAndAuthority},
|
||||
{name: "E3", level: domain.OrganizationVerificationE3, basis: domain.OrganizationBasisManualReview},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
organization, _ := fixture.newOrganization(t, "denied-"+string(test.level), test.level)
|
||||
_, err := fixture.reserveInvitation(organization, uuid.New())
|
||||
if !errors.Is(err, domain.ErrCompanyQuotaDenied) {
|
||||
t.Fatalf("ReserveInvitation(%s) error = %v, want fail-closed denial", test.level, err)
|
||||
}
|
||||
fixture.assertQuotaRowCounts(t, organization.ID(), 0, 0)
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func (fixture companyQuotaFixture) newOrganization(
|
||||
t *testing.T,
|
||||
name string,
|
||||
level domain.OrganizationVerificationLevel,
|
||||
) (domain.Organization, domain.User) {
|
||||
t.Helper()
|
||||
owner := fixture.organizations.employer(t, fmt.Sprintf("quota-%s-%s@example.test", name, uuid.NewString()))
|
||||
organization := fixture.organizations.create(t, owner, mustOrganizationProfile(t, domain.OrganizationProfileInput{Name: "Quota " + name}), fixture.clock.Now().Add(-time.Minute))
|
||||
if level != domain.OrganizationVerificationE0 {
|
||||
basis := domain.OrganizationBasisCorporateDomain
|
||||
switch level {
|
||||
case domain.OrganizationVerificationE2:
|
||||
basis = domain.OrganizationBasisRequisitesAndAuthority
|
||||
case domain.OrganizationVerificationE3:
|
||||
basis = domain.OrganizationBasisManualReview
|
||||
}
|
||||
if _, err := fixture.pool.Exec(fixture.ctx, `
|
||||
UPDATE organizations
|
||||
SET verification_level = $2, verification_basis = $3, verification_changed_at = $4
|
||||
WHERE id = $1`, organization.ID(), string(level), string(basis), fixture.clock.Now().Add(-time.Minute)); err != nil {
|
||||
t.Fatalf("set %s verification fixture: %v", level, err)
|
||||
}
|
||||
}
|
||||
stored, _, err := fixture.organizations.read(owner.ID, organization.ID())
|
||||
if err != nil {
|
||||
t.Fatalf("read %s organization: %v", level, err)
|
||||
}
|
||||
return stored, owner
|
||||
}
|
||||
|
||||
func (fixture companyQuotaFixture) newCandidateID(t *testing.T) uuid.UUID {
|
||||
t.Helper()
|
||||
candidate := fixture.organizations.identity.createUser(
|
||||
t,
|
||||
fmt.Sprintf("quota-candidate-%s@example.test", uuid.NewString()),
|
||||
domain.ScenarioCandidate,
|
||||
fixture.clock.Now().Add(-time.Hour),
|
||||
)
|
||||
return candidate.ID
|
||||
}
|
||||
|
||||
func (fixture companyQuotaFixture) quota(t *testing.T, organization domain.Organization, version domain.PolicyVersion) domain.CompanyQuota {
|
||||
t.Helper()
|
||||
quota, err := domain.NewCompanyQuota(organization, version, fixture.clock.Now())
|
||||
if err != nil {
|
||||
t.Fatalf("NewCompanyQuota() error = %v", err)
|
||||
}
|
||||
return quota
|
||||
}
|
||||
|
||||
func (fixture companyQuotaFixture) reserveInvitation(organization domain.Organization, invitationID uuid.UUID) (outbound.CompanyQuotaDecision, error) {
|
||||
var decision outbound.CompanyQuotaDecision
|
||||
err := fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
var err error
|
||||
decision, err = fixture.service.ReserveInvitation(ctx, unit, organization, invitationID)
|
||||
return err
|
||||
})
|
||||
return decision, err
|
||||
}
|
||||
|
||||
func (fixture companyQuotaFixture) reserveCardView(organization domain.Organization, candidateID uuid.UUID) (outbound.CompanyQuotaDecision, error) {
|
||||
var decision outbound.CompanyQuotaDecision
|
||||
err := fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
var err error
|
||||
decision, err = fixture.service.ReserveCardView(ctx, unit, organization, candidateID)
|
||||
return err
|
||||
})
|
||||
return decision, err
|
||||
}
|
||||
|
||||
func (fixture companyQuotaFixture) reserveWithSnapshot(organization domain.Organization, quota domain.CompanyQuota, invitationID uuid.UUID) error {
|
||||
return fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
_, err := unit.CompanyQuotas().ReserveInvitation(ctx, quota, invitationID)
|
||||
return err
|
||||
})
|
||||
}
|
||||
|
||||
func (fixture companyQuotaFixture) reserveInvitationAllowed(t *testing.T, organization domain.Organization, invitationID uuid.UUID) {
|
||||
t.Helper()
|
||||
decision, err := fixture.reserveInvitation(organization, invitationID)
|
||||
if err != nil || !decision.Allowed || decision.Reused || !decision.RetryAt.IsZero() {
|
||||
t.Fatalf("ReserveInvitation() = %+v, %v; want a new allowed reservation", decision, err)
|
||||
}
|
||||
}
|
||||
|
||||
func (fixture companyQuotaFixture) reserveCardViewAllowed(t *testing.T, organization domain.Organization, candidateID uuid.UUID) {
|
||||
t.Helper()
|
||||
decision, err := fixture.reserveCardView(organization, candidateID)
|
||||
if err != nil || !decision.Allowed || decision.Reused || !decision.RetryAt.IsZero() {
|
||||
t.Fatalf("ReserveCardView() = %+v, %v; want a new allowed reservation", decision, err)
|
||||
}
|
||||
}
|
||||
|
||||
func (fixture companyQuotaFixture) reserveCardViewReused(t *testing.T, organization domain.Organization, candidateID uuid.UUID) {
|
||||
t.Helper()
|
||||
decision, err := fixture.reserveCardView(organization, candidateID)
|
||||
if err != nil || !decision.Allowed || !decision.Reused || !decision.RetryAt.IsZero() {
|
||||
t.Fatalf("ReserveCardView(repeat) = %+v, %v; want an allowed reuse", decision, err)
|
||||
}
|
||||
}
|
||||
|
||||
func (fixture companyQuotaFixture) assertQuotaRowCounts(t *testing.T, organizationID uuid.UUID, invitations, views int64) {
|
||||
t.Helper()
|
||||
var gotInvitations, gotViews int64
|
||||
if err := fixture.pool.QueryRow(fixture.ctx, `
|
||||
SELECT count(*) FROM company_invitation_quota_usage WHERE organization_id = $1`, organizationID).Scan(&gotInvitations); err != nil {
|
||||
t.Fatalf("count invitation quota rows: %v", err)
|
||||
}
|
||||
if err := fixture.pool.QueryRow(fixture.ctx, `
|
||||
SELECT count(*) FROM company_card_view_quota_usage WHERE organization_id = $1`, organizationID).Scan(&gotViews); err != nil {
|
||||
t.Fatalf("count card-view quota rows: %v", err)
|
||||
}
|
||||
if gotInvitations != invitations || gotViews != views {
|
||||
t.Fatalf("quota rows for organization = invitations %d, views %d; want %d/%d", gotInvitations, gotViews, invitations, views)
|
||||
}
|
||||
}
|
||||
|
||||
func (fixture companyQuotaFixture) assertActiveQuotaCounts(t *testing.T, organizationID uuid.UUID, at time.Time, invitations, views int64) {
|
||||
t.Helper()
|
||||
var gotInvitations, gotViews int64
|
||||
if err := fixture.pool.QueryRow(fixture.ctx, `
|
||||
SELECT count(*) FROM company_invitation_quota_usage
|
||||
WHERE organization_id = $1 AND reserved_at > $2`, organizationID, at.Add(-7*24*time.Hour)).Scan(&gotInvitations); err != nil {
|
||||
t.Fatalf("count active invitation quota rows: %v", err)
|
||||
}
|
||||
if err := fixture.pool.QueryRow(fixture.ctx, `
|
||||
SELECT count(*) FROM company_card_view_quota_usage
|
||||
WHERE organization_id = $1 AND last_seen_at > $2`, organizationID, at.Add(-24*time.Hour)).Scan(&gotViews); err != nil {
|
||||
t.Fatalf("count active card-view quota rows: %v", err)
|
||||
}
|
||||
if gotInvitations != invitations || gotViews != views {
|
||||
t.Fatalf("active quota rows at %s = invitations %d, views %d; want %d/%d", at, gotInvitations, gotViews, invitations, views)
|
||||
}
|
||||
}
|
||||
|
||||
func (fixture companyQuotaFixture) assertStoredEvidence(
|
||||
t *testing.T,
|
||||
organizationID uuid.UUID,
|
||||
level domain.OrganizationVerificationLevel,
|
||||
basis domain.OrganizationVerificationBasis,
|
||||
) {
|
||||
t.Helper()
|
||||
var invitationPolicy, viewPolicy uuid.UUID
|
||||
var invitationLevel, viewLevel string
|
||||
var invitationBasis, viewBasis string
|
||||
if err := fixture.pool.QueryRow(fixture.ctx, `
|
||||
SELECT policy_version_id, verification_level, verification_basis
|
||||
FROM company_invitation_quota_usage WHERE organization_id = $1
|
||||
ORDER BY reserved_at LIMIT 1`, organizationID).Scan(&invitationPolicy, &invitationLevel, &invitationBasis); err != nil {
|
||||
t.Fatalf("read invitation quota evidence: %v", err)
|
||||
}
|
||||
if err := fixture.pool.QueryRow(fixture.ctx, `
|
||||
SELECT policy_version_id, verification_level, verification_basis
|
||||
FROM company_card_view_quota_usage WHERE organization_id = $1
|
||||
ORDER BY last_seen_at LIMIT 1`, organizationID).Scan(&viewPolicy, &viewLevel, &viewBasis); err != nil {
|
||||
t.Fatalf("read card-view quota evidence: %v", err)
|
||||
}
|
||||
if invitationPolicy != fixture.version.ID().UUID() || viewPolicy != fixture.version.ID().UUID() ||
|
||||
invitationLevel != string(level) || viewLevel != string(level) ||
|
||||
invitationBasis != string(basis) || viewBasis != string(basis) {
|
||||
t.Fatalf("stored quota evidence = invitation %s/%s/%s view %s/%s/%s, want policy %s and %s/%s",
|
||||
invitationPolicy, invitationLevel, invitationBasis, viewPolicy, viewLevel, viewBasis, fixture.version.ID(), level, basis)
|
||||
}
|
||||
}
|
||||
@@ -39,12 +39,16 @@ var (
|
||||
// organizationTables are emptied together: memberships reference both
|
||||
// users and organizations. Creation snapshots reference idempotency records.
|
||||
organizationTables = []pgx.Identifier{
|
||||
{"company_invitation_quota_usage"}, {"company_card_view_quota_usage"},
|
||||
organizationCreationResultsTable, membershipsTable, organizationRepresentativesTable, organizationsTable,
|
||||
}
|
||||
candidateQuestionnaireTables = []pgx.Identifier{
|
||||
{"candidate_questionnaire_specializations"}, {"candidate_questionnaires"},
|
||||
}
|
||||
// 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, candidateProfileTables, candidatePrivacyTables)
|
||||
usersDependentTables = slices.Concat(identityTables, deliveryTables, consentTables, organizationTables, candidateProfileTables, candidateQuestionnaireTables, candidatePrivacyTables)
|
||||
)
|
||||
|
||||
// organizationFixture works on the bootstrap database. The tables are
|
||||
|
||||
@@ -242,7 +242,9 @@ func TestPolicyVersions(t *testing.T) {
|
||||
SET document = jsonb_set(document, '{invitations,max_pending_per_need}', '99') WHERE id = $1`, args: []any{id}},
|
||||
{name: "delete", sql: `DELETE FROM policy_versions WHERE id = $1`, args: []any{id}},
|
||||
{name: "delete of every row", sql: `DELETE FROM policy_versions`},
|
||||
{name: "truncate", sql: `TRUNCATE policy_versions`},
|
||||
// Include referencing quota tables so PostgreSQL reaches the
|
||||
// immutable-policy trigger instead of its foreign-key precheck.
|
||||
{name: "truncate", sql: `TRUNCATE policy_versions, company_invitation_quota_usage, company_card_view_quota_usage`},
|
||||
}
|
||||
for _, statement := range statements {
|
||||
_, err := fixture.pool.Exec(ctx, statement.sql, statement.args...)
|
||||
|
||||
@@ -0,0 +1,696 @@
|
||||
//go:build integration
|
||||
|
||||
package integration_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
httpadapter "lincodex/backend/internal/adapter/primary/http"
|
||||
"lincodex/backend/internal/adapter/primary/http/problem"
|
||||
v1 "lincodex/backend/internal/adapter/primary/http/v1"
|
||||
"lincodex/backend/internal/adapter/secondary/argon2id"
|
||||
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
|
||||
"lincodex/backend/internal/adapter/secondary/prometheus"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/usecase/assessment"
|
||||
"lincodex/backend/internal/usecase/health"
|
||||
"lincodex/backend/internal/usecase/identity"
|
||||
"lincodex/backend/internal/usecase/policy"
|
||||
profileusecase "lincodex/backend/internal/usecase/profile"
|
||||
questionnaireusecase "lincodex/backend/internal/usecase/questionnaire"
|
||||
)
|
||||
|
||||
const candidateQuestionnaireHTTPTimeout = 6 * time.Minute
|
||||
|
||||
func TestCandidateQuestionnaireOverHTTP(t *testing.T) {
|
||||
env := bootstrap(t, postgresService, redisService)
|
||||
ctx, cancel := context.WithTimeout(t.Context(), candidateQuestionnaireHTTPTimeout)
|
||||
defer cancel()
|
||||
databaseURL := env.createIsolatedDatabase(ctx, t)
|
||||
applyMigrations(ctx, t, databaseURL)
|
||||
isolatedEnv := *env
|
||||
isolatedEnv.Config.DatabaseURL = databaseURL
|
||||
harness := newCandidateQuestionnaireHTTPHarness(ctx, t, &isolatedEnv)
|
||||
initialCatalog := questionnaireCatalogHTTP(t, harness)
|
||||
assertCatalogAvailability(t, initialCatalog, "backend", "in_development", nil, nil)
|
||||
bankFixture := seedQuestionnaireCatalogBank(ctx, t, harness.pool)
|
||||
|
||||
passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass)
|
||||
if err != nil {
|
||||
t.Fatalf("HashNewPassword() error = %v", err)
|
||||
}
|
||||
now := harness.clock.Now()
|
||||
candidate := createSessionHTTPUser(ctx, t, harness, "questionnaire-owner@example.test", passwordHash, true)
|
||||
otherCandidate := createSessionHTTPUser(ctx, t, harness, "questionnaire-other@example.test", passwordHash, true)
|
||||
employer := createQuestionnaireHTTPEmployer(ctx, t, harness, "questionnaire-employer@example.test", passwordHash, now)
|
||||
if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step = 'candidate_questionnaire' WHERE id = $1", candidate.ID); err != nil {
|
||||
t.Fatalf("set candidate questionnaire onboarding step: %v", err)
|
||||
}
|
||||
candidateLogin := loginCandidateQuestionnaireHTTP(t, harness, candidate.Email.Address(), "192.0.2.201:1234")
|
||||
otherLogin := loginCandidateQuestionnaireHTTP(t, harness, otherCandidate.Email.Address(), "192.0.2.202:1234")
|
||||
employerLogin := loginCandidateQuestionnaireHTTP(t, harness, employer.Email.Address(), "192.0.2.203:1234")
|
||||
|
||||
publicCatalogResponse := harness.request(t, http.MethodGet, "/api/v1/specializations", "", "", "", "", "192.0.2.204:1234")
|
||||
if publicCatalogResponse.Code != http.StatusOK {
|
||||
t.Fatalf("public catalog without a session = %d %s, want 200", publicCatalogResponse.Code, publicCatalogResponse.Body.String())
|
||||
}
|
||||
currentCatalog := decodeSpecializationCatalog(t, publicCatalogResponse.Body.Bytes())
|
||||
assertCatalogAvailability(t, currentCatalog, "backend", "available", []string{"junior"}, []string{"go"})
|
||||
|
||||
guestRead := harness.request(t, http.MethodGet, "/api/v1/me/questionnaire", "", sessionHTTPTestOrigin, "", "", "192.0.2.205:1234")
|
||||
requireSessionProblem(t, guestRead, http.StatusUnauthorized, "unauthenticated")
|
||||
|
||||
initial := questionnaireHTTPRequest(t, harness, http.MethodGet, "", candidateLogin.cookie, "", "192.0.2.206:1234")
|
||||
if initial.Code != http.StatusOK || initial.Header().Get("Cache-Control") != "no-store" {
|
||||
t.Fatalf("empty questionnaire = %d Cache-Control=%q: %s", initial.Code, initial.Header().Get("Cache-Control"), initial.Body.String())
|
||||
}
|
||||
var empty questionnaireHTTPResponse
|
||||
if err := json.Unmarshal(initial.Body.Bytes(), &empty); err != nil {
|
||||
t.Fatalf("decode empty questionnaire: %v", err)
|
||||
}
|
||||
if empty.Version != 0 || len(empty.Specializations) != 0 || string(empty.WorkContext) != "null" || string(empty.UpdatedAt) != "null" {
|
||||
t.Fatalf("empty questionnaire = %+v, want version zero with null context and time", empty)
|
||||
}
|
||||
|
||||
firstSave := questionnaireHTTPRequest(t, harness, http.MethodPut,
|
||||
questionnaireUpdateBody(t, 0, "backend", "junior", []string{"go"}, []string{"PostgreSQL"}, 18, 6),
|
||||
candidateLogin.cookie, candidateLogin.csrf, "192.0.2.207:1234")
|
||||
if firstSave.Code != http.StatusOK || firstSave.Header().Get("Cache-Control") != "no-store" {
|
||||
t.Fatalf("save questionnaire = %d Cache-Control=%q: %s", firstSave.Code, firstSave.Header().Get("Cache-Control"), firstSave.Body.String())
|
||||
}
|
||||
var saved questionnaireHTTPResponse
|
||||
if err := json.Unmarshal(firstSave.Body.Bytes(), &saved); err != nil {
|
||||
t.Fatalf("decode saved questionnaire: %v", err)
|
||||
}
|
||||
if saved.Version != 1 || len(saved.Specializations) != 1 || saved.Specializations[0].SelfAssessedGrade != "junior" ||
|
||||
len(saved.Specializations[0].TaskLanguages) != 1 || saved.Specializations[0].TaskLanguages[0] != "go" ||
|
||||
saved.Specializations[0].Experience == nil || saved.Specializations[0].Experience.CommercialMonths != 18 ||
|
||||
saved.Specializations[0].Experience.AcademicMonths != 6 || len(saved.Specializations[0].Stack) != 1 || saved.Specializations[0].Stack[0] != "PostgreSQL" {
|
||||
t.Fatalf("saved questionnaire = %+v, want backend/junior/go version 1", saved)
|
||||
}
|
||||
assertQuestionnaireRows(t, ctx, harness, candidate.ID, 1, "backend", "junior", "go", "PostgreSQL", 18, 6)
|
||||
assertQuestionnaireOnboarding(t, ctx, harness, candidate.ID, "candidate_assessment")
|
||||
assertQuestionnaireExperienceConstraint(t, ctx, harness, otherCandidate.ID)
|
||||
|
||||
staleWrite := questionnaireHTTPRequest(t, harness, http.MethodPut,
|
||||
questionnaireUpdateBody(t, 0, "backend", "junior", []string{"go"}, []string{"gRPC"}, 18, 6),
|
||||
candidateLogin.cookie, candidateLogin.csrf, "192.0.2.208:1234")
|
||||
requireSessionProblem(t, staleWrite, http.StatusPreconditionFailed, "version_conflict")
|
||||
assertQuestionnaireRows(t, ctx, harness, candidate.ID, 1, "backend", "junior", "go", "PostgreSQL", 18, 6)
|
||||
|
||||
noOp := questionnaireHTTPRequest(t, harness, http.MethodPut,
|
||||
questionnaireUpdateBody(t, 0, "backend", "junior", []string{"go"}, []string{"PostgreSQL"}, 18, 6),
|
||||
candidateLogin.cookie, candidateLogin.csrf, "192.0.2.209:1234")
|
||||
if noOp.Code != http.StatusOK {
|
||||
t.Fatalf("stale identical questionnaire retry = %d %s, want 200", noOp.Code, noOp.Body.String())
|
||||
}
|
||||
var noOpResponse questionnaireHTTPResponse
|
||||
if err := json.Unmarshal(noOp.Body.Bytes(), &noOpResponse); err != nil || noOpResponse.Version != 1 {
|
||||
t.Fatalf("stale identical retry response = %+v, decode error %v; want version 1", noOpResponse, err)
|
||||
}
|
||||
|
||||
badLanguage := questionnaireHTTPRequest(t, harness, http.MethodPut,
|
||||
questionnaireUpdateBody(t, 1, "backend", "junior", []string{"python"}, []string{"PostgreSQL"}, 18, 6),
|
||||
candidateLogin.cookie, candidateLogin.csrf, "192.0.2.210:1234")
|
||||
if badLanguage.Code != http.StatusBadRequest || !strings.Contains(badLanguage.Body.String(), "/specializations/0/task_languages/0") {
|
||||
t.Fatalf("unoffered task language = %d %s, want field validation", badLanguage.Code, badLanguage.Body.String())
|
||||
}
|
||||
assertQuestionnaireRows(t, ctx, harness, candidate.ID, 1, "backend", "junior", "go", "PostgreSQL", 18, 6)
|
||||
|
||||
forbiddenFieldBody := questionnaireUpdateWithUnknownField(t,
|
||||
questionnaireUpdateBody(t, 1, "backend", "junior", []string{"go"}, []string{"PostgreSQL"}, 18, 6),
|
||||
"confirmed_grade", "senior")
|
||||
forbiddenField := questionnaireHTTPRequest(t, harness, http.MethodPut, forbiddenFieldBody,
|
||||
candidateLogin.cookie, candidateLogin.csrf, "192.0.2.211:1234")
|
||||
if forbiddenField.Code != http.StatusBadRequest {
|
||||
t.Fatalf("questionnaire update with confirmed_grade = %d %s, want 400", forbiddenField.Code, forbiddenField.Body.String())
|
||||
}
|
||||
assertQuestionnaireRows(t, ctx, harness, candidate.ID, 1, "backend", "junior", "go", "PostgreSQL", 18, 6)
|
||||
|
||||
otherRead := questionnaireHTTPRequest(t, harness, http.MethodGet, "", otherLogin.cookie, "", "192.0.2.212:1234")
|
||||
var other questionnaireHTTPResponse
|
||||
if otherRead.Code != http.StatusOK || json.Unmarshal(otherRead.Body.Bytes(), &other) != nil || other.Version != 0 || len(other.Specializations) != 0 {
|
||||
t.Fatalf("other candidate questionnaire = %d %s, want private version-0 questionnaire", otherRead.Code, otherRead.Body.String())
|
||||
}
|
||||
otherDevelopmentSave := questionnaireHTTPRequest(t, harness, http.MethodPut,
|
||||
questionnaireUpdateBody(t, 0, "ds_ml", "junior", nil, []string{"Python"}, 0, 0),
|
||||
otherLogin.cookie, otherLogin.csrf, "192.0.2.213:1234")
|
||||
if otherDevelopmentSave.Code != http.StatusOK {
|
||||
t.Fatalf("save a specialization with no available bank and no task language = %d %s, want 200", otherDevelopmentSave.Code, otherDevelopmentSave.Body.String())
|
||||
}
|
||||
|
||||
employerRead := questionnaireHTTPRequest(t, harness, http.MethodGet, "", employerLogin.cookie, "", "192.0.2.214:1234")
|
||||
requireSessionProblem(t, employerRead, http.StatusForbidden, "forbidden")
|
||||
|
||||
// A self-assessed Senior grade remains a private claim. It cannot create a
|
||||
// confirmed category or a profile claim by itself.
|
||||
seniorSave := questionnaireHTTPRequest(t, harness, http.MethodPut,
|
||||
questionnaireUpdateBody(t, 1, "backend", "senior", []string{"go"}, []string{"PostgreSQL"}, 18, 6),
|
||||
candidateLogin.cookie, candidateLogin.csrf, "192.0.2.215:1234")
|
||||
if seniorSave.Code != http.StatusOK {
|
||||
t.Fatalf("save Senior self-assessment = %d %s, want 200", seniorSave.Code, seniorSave.Body.String())
|
||||
}
|
||||
var senior questionnaireHTTPResponse
|
||||
if err := json.Unmarshal(seniorSave.Body.Bytes(), &senior); err != nil || senior.Version != 2 || senior.Specializations[0].SelfAssessedGrade != "senior" {
|
||||
t.Fatalf("Senior questionnaire = %+v, decode error %v", senior, err)
|
||||
}
|
||||
profileRead := harness.request(t, http.MethodGet, "/api/v1/me/profile", "", sessionHTTPTestOrigin,
|
||||
candidateLogin.cookie, "", "192.0.2.216:1234")
|
||||
var profile struct {
|
||||
Version int64 `json:"version"`
|
||||
ConfirmedCategories []json.RawMessage `json:"confirmed_categories"`
|
||||
}
|
||||
if profileRead.Code != http.StatusOK || json.Unmarshal(profileRead.Body.Bytes(), &profile) != nil ||
|
||||
profile.Version != 0 || len(profile.ConfirmedCategories) != 0 {
|
||||
t.Fatalf("profile after a Senior self-assessment = %d %s, want no confirmed category", profileRead.Code, profileRead.Body.String())
|
||||
}
|
||||
|
||||
// A later onboarding step never moves backwards on an identical retry.
|
||||
if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step = 'completed' WHERE id = $1", candidate.ID); err != nil {
|
||||
t.Fatalf("move candidate to completed onboarding: %v", err)
|
||||
}
|
||||
if response := questionnaireHTTPRequest(t, harness, http.MethodPut,
|
||||
questionnaireUpdateBody(t, 1, "backend", "senior", []string{"go"}, []string{"PostgreSQL"}, 18, 6),
|
||||
candidateLogin.cookie, candidateLogin.csrf, "192.0.2.217:1234"); response.Code != http.StatusOK {
|
||||
t.Fatalf("questionnaire retry after onboarding completion = %d %s", response.Code, response.Body.String())
|
||||
}
|
||||
assertQuestionnaireOnboarding(t, ctx, harness, candidate.ID, "completed")
|
||||
|
||||
// Two different changes from the same version race; exactly one wins and
|
||||
// the stale writer leaves the winner's whole body intact.
|
||||
firstConcurrent := questionnaireUpdateBody(t, 2, "backend", "senior", []string{"go"}, []string{"gRPC"}, 18, 6)
|
||||
secondConcurrent := questionnaireUpdateBody(t, 2, "backend", "senior", []string{"go"}, []string{"Redis"}, 18, 6)
|
||||
concurrentResponses := make([]*httptest.ResponseRecorder, 2)
|
||||
start := make(chan struct{})
|
||||
var wait sync.WaitGroup
|
||||
for index, body := range []string{firstConcurrent, secondConcurrent} {
|
||||
wait.Add(1)
|
||||
go func(index int, body string) {
|
||||
defer wait.Done()
|
||||
<-start
|
||||
concurrentResponses[index] = questionnaireHTTPRequest(t, harness, http.MethodPut, body,
|
||||
candidateLogin.cookie, candidateLogin.csrf, fmt.Sprintf("192.0.2.%d:1234", 218+index))
|
||||
}(index, body)
|
||||
}
|
||||
close(start)
|
||||
wait.Wait()
|
||||
accepted, conflicted := 0, 0
|
||||
for _, response := range concurrentResponses {
|
||||
switch response.Code {
|
||||
case http.StatusOK:
|
||||
accepted++
|
||||
case http.StatusPreconditionFailed:
|
||||
conflicted++
|
||||
default:
|
||||
t.Fatalf("concurrent questionnaire save = %d %s, want 200 or 412", response.Code, response.Body.String())
|
||||
}
|
||||
}
|
||||
if accepted != 1 || conflicted != 1 {
|
||||
t.Fatalf("concurrent questionnaire results = %d accepted, %d conflicted; want one each", accepted, conflicted)
|
||||
}
|
||||
var storedVersion int64
|
||||
var storedStack string
|
||||
if err := harness.pool.QueryRow(ctx, `
|
||||
SELECT questionnaire.version, specialization.stack[1]
|
||||
FROM candidate_questionnaires AS questionnaire
|
||||
JOIN candidate_questionnaire_specializations AS specialization USING (user_id)
|
||||
WHERE questionnaire.user_id = $1`, candidate.ID).Scan(&storedVersion, &storedStack); err != nil {
|
||||
t.Fatalf("read concurrent questionnaire winner: %v", err)
|
||||
}
|
||||
if storedVersion != 3 || (storedStack != "gRPC" && storedStack != "Redis") {
|
||||
t.Fatalf("concurrent stored questionnaire = version %d stack %q, want version 3 and one complete winner", storedVersion, storedStack)
|
||||
}
|
||||
|
||||
// Simultaneous identical saves return the one committed winner to both
|
||||
// callers without creating a second version or replacing its answer rows.
|
||||
identicalBody := questionnaireUpdateBody(t, 3, "backend", "senior", []string{"go"}, []string{"Fargate"}, 18, 6)
|
||||
identicalResponses := make([]*httptest.ResponseRecorder, 2)
|
||||
start = make(chan struct{})
|
||||
for index := range identicalResponses {
|
||||
wait.Add(1)
|
||||
go func(index int) {
|
||||
defer wait.Done()
|
||||
<-start
|
||||
identicalResponses[index] = questionnaireHTTPRequest(t, harness, http.MethodPut, identicalBody,
|
||||
candidateLogin.cookie, candidateLogin.csrf, fmt.Sprintf("192.0.2.%d:1234", 223+index))
|
||||
}(index)
|
||||
}
|
||||
close(start)
|
||||
wait.Wait()
|
||||
for _, response := range identicalResponses {
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("concurrent identical questionnaire save = %d %s, want 200", response.Code, response.Body.String())
|
||||
}
|
||||
var result questionnaireHTTPResponse
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &result); err != nil || result.Version != 4 ||
|
||||
len(result.Specializations) != 1 || result.Specializations[0].Stack[0] != "Fargate" {
|
||||
t.Fatalf("concurrent identical save response = %+v, decode error %v; want same version-4 winner", result, err)
|
||||
}
|
||||
}
|
||||
if err := harness.pool.QueryRow(ctx, `
|
||||
SELECT questionnaire.version, specialization.stack[1]
|
||||
FROM candidate_questionnaires AS questionnaire
|
||||
JOIN candidate_questionnaire_specializations AS specialization USING (user_id)
|
||||
WHERE questionnaire.user_id = $1`, candidate.ID).Scan(&storedVersion, &storedStack); err != nil {
|
||||
t.Fatalf("read identical questionnaire winner: %v", err)
|
||||
}
|
||||
if storedVersion != 4 || storedStack != "Fargate" {
|
||||
t.Fatalf("identical concurrent stored questionnaire = version %d stack %q, want version 4 and Fargate", storedVersion, storedStack)
|
||||
}
|
||||
|
||||
secondLogin := loginCandidateQuestionnaireHTTP(t, harness, candidate.Email.Address(), "192.0.2.220:1234")
|
||||
harness.pool.Close()
|
||||
harness = newCandidateQuestionnaireHTTPHarness(ctx, t, &isolatedEnv)
|
||||
bankFixture.bank = assessment.NewBank(postgresadapter.NewTransactor(harness.pool))
|
||||
bankFixture.publisher = policy.NewPublisher(postgresadapter.NewPolicyStore(harness.pool).Policies(), time.Now)
|
||||
restartedRead := questionnaireHTTPRequest(t, harness, http.MethodGet, "", secondLogin.cookie, "", "192.0.2.221:1234")
|
||||
var restarted questionnaireHTTPResponse
|
||||
if restartedRead.Code != http.StatusOK || json.Unmarshal(restartedRead.Body.Bytes(), &restarted) != nil ||
|
||||
restarted.Version != 4 || len(restarted.Specializations) != 1 || restarted.Specializations[0].SelfAssessedGrade != "senior" ||
|
||||
restarted.Specializations[0].Stack[0] != storedStack {
|
||||
t.Fatalf("questionnaire after re-login and handler restart = %d %s, want version 4 and persisted winner", restartedRead.Code, restartedRead.Body.String())
|
||||
}
|
||||
assertQuestionnaireRows(t, ctx, harness, candidate.ID, 4, "backend", "senior", "go", storedStack, 18, 6)
|
||||
|
||||
// A new policy version makes the old opening ineligible for the public
|
||||
// catalog. Reopening under that policy restores availability only while the
|
||||
// pinned published-family manifest still meets its recorded threshold.
|
||||
policyVersion, err := bankFixture.publisher.Publish(ctx, policy.PublishInput{
|
||||
Key: domain.ProductPolicyKey, Kind: domain.PolicyKindCalibrated,
|
||||
Author: policyTestAuthor, Policy: integrationPolicy(11),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Publish(replacement catalog policy) error = %v", err)
|
||||
}
|
||||
assertCatalogAvailability(t, questionnaireCatalogHTTP(t, harness), "backend", "in_development", nil, nil)
|
||||
if _, err := bankFixture.bank.OpenCategory(ctx, assessment.OpenCategoryInput{
|
||||
Category: assessmentCategory, GradingPolicyID: policyVersion.ID(), OpenedBy: fixtureOpener,
|
||||
CatalogMetadata: &bankFixture.metadata,
|
||||
}); err != nil {
|
||||
t.Fatalf("OpenCategory(replacement catalog policy) error = %v", err)
|
||||
}
|
||||
assertCatalogAvailability(t, questionnaireCatalogHTTP(t, harness), "backend", "available", []string{"junior"}, []string{"go"})
|
||||
if _, err := bankFixture.bank.RetireFamily(ctx, bankFixture.firstFamilyKey, 1, fixturePublisher); err != nil {
|
||||
t.Fatalf("RetireFamily(under-covered catalog) error = %v", err)
|
||||
}
|
||||
assertCatalogAvailability(t, questionnaireCatalogHTTP(t, harness), "backend", "in_development", nil, nil)
|
||||
questionnaireAfterBankChange := questionnaireHTTPRequest(t, harness, http.MethodGet, "", secondLogin.cookie, "", "192.0.2.222:1234")
|
||||
var preserved questionnaireHTTPResponse
|
||||
if questionnaireAfterBankChange.Code != http.StatusOK || json.Unmarshal(questionnaireAfterBankChange.Body.Bytes(), &preserved) != nil ||
|
||||
preserved.Version != 4 || len(preserved.Specializations) != 1 || preserved.Specializations[0].Stack[0] != storedStack {
|
||||
t.Fatalf("questionnaire after bank coverage change = %d %s, want persisted version 4", questionnaireAfterBankChange.Code, questionnaireAfterBankChange.Body.String())
|
||||
}
|
||||
|
||||
for _, privateValue := range []string{
|
||||
candidate.Email.Address(), otherCandidate.Email.Address(), employer.Email.Address(),
|
||||
"PostgreSQL", "gRPC", "Redis",
|
||||
} {
|
||||
if strings.Contains(harness.logs.String(), privateValue) {
|
||||
t.Fatalf("questionnaire HTTP logs contain private value %q", privateValue)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type questionnaireHTTPResponse struct {
|
||||
Version int64 `json:"version"`
|
||||
Specializations []questionnaireHTTPSpecialization `json:"specializations"`
|
||||
WorkContext json.RawMessage `json:"work_context"`
|
||||
UpdatedAt json.RawMessage `json:"updated_at"`
|
||||
}
|
||||
|
||||
type questionnaireHTTPSpecialization struct {
|
||||
Specialization string `json:"specialization"`
|
||||
SelfAssessedGrade string `json:"self_assessed_grade"`
|
||||
TaskLanguages []string `json:"task_languages"`
|
||||
Stack []string `json:"stack"`
|
||||
Experience *struct {
|
||||
CommercialMonths int32 `json:"commercial_months"`
|
||||
AcademicMonths int32 `json:"academic_months"`
|
||||
} `json:"experience"`
|
||||
}
|
||||
|
||||
type questionnaireCatalogResponse struct {
|
||||
Directions []struct {
|
||||
Code string `json:"code"`
|
||||
Specializations []struct {
|
||||
Code string `json:"code"`
|
||||
TestAvailability struct {
|
||||
Status string `json:"status"`
|
||||
Grades []string `json:"grades"`
|
||||
TaskLanguages []string `json:"task_languages"`
|
||||
Note *string `json:"note"`
|
||||
} `json:"test_availability"`
|
||||
} `json:"specializations"`
|
||||
} `json:"directions"`
|
||||
}
|
||||
|
||||
type questionnaireLogin struct {
|
||||
cookie string
|
||||
csrf string
|
||||
}
|
||||
|
||||
type questionnaireBankFixture struct {
|
||||
bank *assessment.Bank
|
||||
publisher *policy.Publisher
|
||||
metadata domain.AssessmentCategoryCatalogMetadata
|
||||
firstFamilyKey domain.AssessmentFamilyKey
|
||||
}
|
||||
|
||||
func seedQuestionnaireCatalogBank(ctx context.Context, t *testing.T, pool *pgxpool.Pool) questionnaireBankFixture {
|
||||
t.Helper()
|
||||
transactor := postgresadapter.NewTransactor(pool)
|
||||
bank := assessment.NewBank(transactor)
|
||||
store := postgresadapter.NewAssessmentBankStore(pool)
|
||||
publisher := policy.NewPublisher(postgresadapter.NewPolicyStore(pool).Policies(), time.Now)
|
||||
fixture := assessmentFixture{
|
||||
ctx: ctx, pool: pool, store: store, transactor: transactor, bank: bank,
|
||||
publisher: publisher, demoBundle: loadDemoBundleFile(t),
|
||||
}
|
||||
if _, err := bank.ImportBundle(ctx, fixture.demoBundle); err != nil {
|
||||
t.Fatalf("ImportBundle(unreviewed base bundle) error = %v", err)
|
||||
}
|
||||
unreviewedAvailability, err := bank.SpecializationAvailability(ctx)
|
||||
if err != nil || len(unreviewedAvailability) != 0 {
|
||||
t.Fatalf("catalog availability after importing an unreviewed draft = %v, %v; want no rows", unreviewedAvailability, err)
|
||||
}
|
||||
policyVersion, err := publisher.Publish(ctx, policy.PublishInput{
|
||||
Key: domain.ProductPolicyKey, Kind: domain.PolicyKindCalibrated,
|
||||
Author: policyTestAuthor, Policy: integrationPolicy(11),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Publish(questionnaire grading policy) error = %v", err)
|
||||
}
|
||||
required, err := domain.RequiredPublishedAssessmentFamilies(policyVersion.Policy())
|
||||
if err != nil {
|
||||
t.Fatalf("RequiredPublishedAssessmentFamilies() error = %v", err)
|
||||
}
|
||||
reviewed := fixture.reviewedBundle(int(required))
|
||||
if _, err := bank.ImportBundle(ctx, reviewed); err != nil {
|
||||
t.Fatalf("ImportBundle(reviewed questionnaire fixture) error = %v", err)
|
||||
}
|
||||
for _, family := range reviewed.Families {
|
||||
if _, err := bank.PublishFamily(ctx, domain.AssessmentFamilyKey(family.Key), family.Version, fixturePublisher); err != nil {
|
||||
t.Fatalf("PublishFamily(%s) error = %v", family.Key, err)
|
||||
}
|
||||
}
|
||||
metadata, err := domain.NewAssessmentCategoryCatalogMetadata(
|
||||
domain.SpecializationBackend, domain.GradeJunior, []domain.TaskLanguageCode{domain.TaskLanguageGo},
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("NewAssessmentCategoryCatalogMetadata() error = %v", err)
|
||||
}
|
||||
if _, err := bank.OpenCategory(ctx, assessment.OpenCategoryInput{
|
||||
Category: assessmentCategory, GradingPolicyID: policyVersion.ID(), OpenedBy: fixtureOpener,
|
||||
CatalogMetadata: &metadata,
|
||||
}); err != nil {
|
||||
t.Fatalf("OpenCategory(reviewed questionnaire fixture) error = %v", err)
|
||||
}
|
||||
return questionnaireBankFixture{
|
||||
bank: bank, publisher: publisher, metadata: metadata,
|
||||
firstFamilyKey: domain.AssessmentFamilyKey(reviewed.Families[0].Key),
|
||||
}
|
||||
}
|
||||
|
||||
func newCandidateQuestionnaireHTTPHarness(ctx context.Context, t *testing.T, env *testEnvironment) *sessionHTTPHarness {
|
||||
t.Helper()
|
||||
pool := env.newPool(ctx, t)
|
||||
store := postgresadapter.NewIdentityStore(pool)
|
||||
hasher, err := argon2id.NewHasher(1)
|
||||
if err != nil {
|
||||
t.Fatalf("NewHasher() error = %v", err)
|
||||
}
|
||||
credentials := identity.NewCredentials(hasher)
|
||||
keyring, err := identity.NewKeyring([]byte(env.Config.IdentityKeySecret))
|
||||
if err != nil {
|
||||
t.Fatalf("NewKeyring() error = %v", err)
|
||||
}
|
||||
clock := &testClock{now: time.Now().UTC().Truncate(time.Microsecond)}
|
||||
transactor := postgresadapter.NewTransactor(pool)
|
||||
sessions, err := identity.NewSessionService(identity.SessionDependencies{
|
||||
Transactor: transactor, Users: store.Users(), Sessions: store.Sessions(),
|
||||
Credentials: credentials, Limiter: env.Redis, Keyring: keyring, Clock: clock.Now,
|
||||
}, identity.SessionSettings{
|
||||
ClientHourlyLimit: int64(env.Config.IdentityClientHourlyLimit), EmailHourlyLimit: int64(env.Config.IdentityLoginEmailHourlyLimit),
|
||||
IdleTimeout: env.Config.IdentitySessionIdleTimeout, AbsoluteLifetime: env.Config.IdentitySessionAbsoluteLifetime,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewSessionService() error = %v", err)
|
||||
}
|
||||
logs := &strings.Builder{}
|
||||
logger := slog.New(slog.NewJSONHandler(logs, nil))
|
||||
responder := problem.NewResponder(logger)
|
||||
healthHandler := v1.NewHealthHandler(health.NewReadiness(env.Postgres), time.Second)
|
||||
identityHandler := v1.NewIdentityHandler(nil, v1.WithSessionService(sessions), v1.WithPublicOrigin(env.Config.AppPublicURL))
|
||||
profileHandler := v1.NewProfileHandler(profileusecase.NewService(transactor, clock.Now))
|
||||
questionnaireHandler := v1.NewQuestionnaireHandler(questionnaireusecase.NewService(transactor, clock.Now))
|
||||
catalogHandler := v1.NewCatalogHandler(assessment.NewBank(transactor))
|
||||
handler := v1.NewHandler(healthHandler, responder,
|
||||
v1.WithIdentity(identityHandler), v1.WithProfile(profileHandler),
|
||||
v1.WithQuestionnaire(questionnaireHandler), v1.WithCatalog(catalogHandler),
|
||||
)
|
||||
router, err := httpadapter.NewRouter(healthHandler, handler, identityHandler.SessionSecurity(), responder,
|
||||
prometheus.New(), logger, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewRouter() error = %v", err)
|
||||
}
|
||||
return &sessionHTTPHarness{pool: pool, store: store, router: router, credentials: credentials, clock: clock, logs: logs}
|
||||
}
|
||||
|
||||
func createQuestionnaireHTTPEmployer(
|
||||
ctx context.Context,
|
||||
t *testing.T,
|
||||
harness *sessionHTTPHarness,
|
||||
email string,
|
||||
passwordHash domain.PasswordHash,
|
||||
registeredAt time.Time,
|
||||
) domain.User {
|
||||
t.Helper()
|
||||
address, err := domain.NewEmailAddress(email)
|
||||
if err != nil {
|
||||
t.Fatalf("NewEmailAddress() error = %v", err)
|
||||
}
|
||||
user, err := domain.NewUser(domain.Registration{
|
||||
Email: address, PasswordHash: passwordHash, Scenario: domain.ScenarioEmployer, RegisteredAt: registeredAt,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewUser(employer) error = %v", err)
|
||||
}
|
||||
if err := harness.store.Users().Create(ctx, user); err != nil {
|
||||
t.Fatalf("Create(employer) error = %v", err)
|
||||
}
|
||||
verified, err := harness.store.Users().MarkEmailVerified(ctx, user.ID, user.RegistrationVersion, registeredAt.Add(time.Microsecond))
|
||||
if err != nil {
|
||||
t.Fatalf("MarkEmailVerified(employer) error = %v", err)
|
||||
}
|
||||
return verified
|
||||
}
|
||||
|
||||
func loginCandidateQuestionnaireHTTP(t *testing.T, harness *sessionHTTPHarness, email, remoteAddr string) questionnaireLogin {
|
||||
t.Helper()
|
||||
response := loginSessionHTTP(t, harness, email, sessionHTTPTestPass, sessionHTTPTestOrigin, "", remoteAddr)
|
||||
if response.Code != http.StatusCreated {
|
||||
t.Fatalf("login questionnaire account = %d %s", response.Code, response.Body.String())
|
||||
}
|
||||
cookie := requireSessionCookie(t, response)
|
||||
var body struct {
|
||||
CSRFToken string `json:"csrf_token"`
|
||||
}
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &body); err != nil || body.CSRFToken == "" {
|
||||
t.Fatalf("decode questionnaire login response: %v", err)
|
||||
}
|
||||
return questionnaireLogin{cookie: cookie.Value, csrf: body.CSRFToken}
|
||||
}
|
||||
|
||||
func questionnaireHTTPRequest(
|
||||
t *testing.T,
|
||||
harness *sessionHTTPHarness,
|
||||
method, body, cookie, csrf, remoteAddr string,
|
||||
) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
return harness.request(t, method, "/api/v1/me/questionnaire", body, sessionHTTPTestOrigin, cookie, csrf, remoteAddr)
|
||||
}
|
||||
|
||||
func questionnaireUpdateBody(
|
||||
t *testing.T,
|
||||
version int64,
|
||||
specialization, grade string,
|
||||
languages, stack []string,
|
||||
commercialMonths, academicMonths int,
|
||||
) string {
|
||||
t.Helper()
|
||||
if languages == nil {
|
||||
languages = []string{}
|
||||
}
|
||||
if stack == nil {
|
||||
stack = []string{}
|
||||
}
|
||||
var experience any
|
||||
if commercialMonths != 0 || academicMonths != 0 {
|
||||
experience = map[string]any{"commercial_months": commercialMonths, "academic_months": academicMonths}
|
||||
}
|
||||
encoded, err := json.Marshal(map[string]any{
|
||||
"expected_version": version,
|
||||
"specializations": []any{map[string]any{
|
||||
"specialization": specialization, "self_assessed_grade": grade,
|
||||
"task_languages": languages, "stack": stack, "experience": experience,
|
||||
}},
|
||||
"work_context": map[string]any{"work_formats": []string{"remote"}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("marshal questionnaire request: %v", err)
|
||||
}
|
||||
return string(encoded)
|
||||
}
|
||||
|
||||
func questionnaireUpdateWithUnknownField(t *testing.T, requestBody, field string, value any) string {
|
||||
t.Helper()
|
||||
var body map[string]any
|
||||
if err := json.Unmarshal([]byte(requestBody), &body); err != nil {
|
||||
t.Fatalf("decode questionnaire request fixture: %v", err)
|
||||
}
|
||||
body[field] = value
|
||||
encoded, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal questionnaire request with %s: %v", field, err)
|
||||
}
|
||||
return string(encoded)
|
||||
}
|
||||
|
||||
func questionnaireCatalogHTTP(t *testing.T, harness *sessionHTTPHarness) questionnaireCatalogResponse {
|
||||
t.Helper()
|
||||
response := harness.request(t, http.MethodGet, "/api/v1/specializations", "", "", "", "", "192.0.2.200:1234")
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("GetSpecializationCatalog() = %d %s, want 200", response.Code, response.Body.String())
|
||||
}
|
||||
return decodeSpecializationCatalog(t, response.Body.Bytes())
|
||||
}
|
||||
|
||||
func decodeSpecializationCatalog(t *testing.T, encoded []byte) questionnaireCatalogResponse {
|
||||
t.Helper()
|
||||
var catalog questionnaireCatalogResponse
|
||||
if err := json.Unmarshal(encoded, &catalog); err != nil {
|
||||
t.Fatalf("decode specialization catalog: %v", err)
|
||||
}
|
||||
return catalog
|
||||
}
|
||||
|
||||
func assertCatalogAvailability(t *testing.T, catalog questionnaireCatalogResponse, code, status string, grades, languages []string) {
|
||||
t.Helper()
|
||||
for _, direction := range catalog.Directions {
|
||||
for _, specialization := range direction.Specializations {
|
||||
if specialization.Code != code {
|
||||
continue
|
||||
}
|
||||
actual := specialization.TestAvailability
|
||||
if actual.Status != status || !slices.Equal(actual.Grades, grades) || !slices.Equal(actual.TaskLanguages, languages) {
|
||||
t.Fatalf("catalog availability for %s = %+v; want %s grades=%v languages=%v", code, actual, status, grades, languages)
|
||||
}
|
||||
if status == "in_development" && (actual.Note == nil || *actual.Note != "Тест в разработке.") {
|
||||
t.Fatalf("catalog development note for %s = %v, want fixed note", code, actual.Note)
|
||||
}
|
||||
if status == "available" && actual.Note != nil {
|
||||
t.Fatalf("catalog availability note for %s = %q, want null", code, *actual.Note)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
t.Fatalf("catalog is missing specialization %s", code)
|
||||
}
|
||||
|
||||
func assertQuestionnaireRows(
|
||||
t *testing.T,
|
||||
ctx context.Context,
|
||||
harness *sessionHTTPHarness,
|
||||
userID uuid.UUID,
|
||||
wantVersion int64,
|
||||
specialization, grade, language, stack string,
|
||||
commercialMonths, academicMonths int32,
|
||||
) {
|
||||
t.Helper()
|
||||
var count int
|
||||
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM candidate_questionnaires WHERE user_id = $1", userID).Scan(&count); err != nil {
|
||||
t.Fatalf("count questionnaire rows: %v", err)
|
||||
}
|
||||
wantRows := 1
|
||||
if wantVersion == 0 {
|
||||
wantRows = 0
|
||||
}
|
||||
if count != wantRows {
|
||||
t.Fatalf("questionnaire rows = %d, want %d", count, wantRows)
|
||||
}
|
||||
if wantVersion == 0 {
|
||||
return
|
||||
}
|
||||
var version int64
|
||||
var storedSpecialization, storedGrade, storedLanguage, storedStack string
|
||||
var storedCommercial, storedAcademic int32
|
||||
if err := harness.pool.QueryRow(ctx, `
|
||||
SELECT questionnaire.version, answer.specialization, answer.self_assessed_grade,
|
||||
answer.task_languages[1], answer.stack[1], answer.commercial_months, answer.academic_months
|
||||
FROM candidate_questionnaires AS questionnaire
|
||||
JOIN candidate_questionnaire_specializations AS answer USING (user_id)
|
||||
WHERE questionnaire.user_id = $1`, userID).Scan(
|
||||
&version, &storedSpecialization, &storedGrade, &storedLanguage, &storedStack, &storedCommercial, &storedAcademic,
|
||||
); err != nil {
|
||||
t.Fatalf("read stored questionnaire: %v", err)
|
||||
}
|
||||
if version != wantVersion || storedSpecialization != specialization || storedGrade != grade || storedLanguage != language ||
|
||||
storedStack != stack || storedCommercial != commercialMonths || storedAcademic != academicMonths {
|
||||
t.Fatalf("stored questionnaire = version %d %s/%s/%s/%s/%d/%d; want %d %s/%s/%s/%s/%d/%d",
|
||||
version, storedSpecialization, storedGrade, storedLanguage, storedStack, storedCommercial, storedAcademic,
|
||||
wantVersion, specialization, grade, language, stack, commercialMonths, academicMonths)
|
||||
}
|
||||
}
|
||||
|
||||
func assertQuestionnaireOnboarding(t *testing.T, ctx context.Context, harness *sessionHTTPHarness, userID uuid.UUID, want string) {
|
||||
t.Helper()
|
||||
var step string
|
||||
if err := harness.pool.QueryRow(ctx, "SELECT onboarding_step FROM users WHERE id = $1", userID).Scan(&step); err != nil {
|
||||
t.Fatalf("read questionnaire onboarding step: %v", err)
|
||||
}
|
||||
if step != want {
|
||||
t.Fatalf("questionnaire onboarding step = %q, want %q", step, want)
|
||||
}
|
||||
}
|
||||
|
||||
func assertQuestionnaireExperienceConstraint(t *testing.T, ctx context.Context, harness *sessionHTTPHarness, userID uuid.UUID) {
|
||||
t.Helper()
|
||||
tx, err := harness.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("begin questionnaire constraint check: %v", err)
|
||||
}
|
||||
defer func() {
|
||||
if err := tx.Rollback(ctx); err != nil && !errors.Is(err, pgx.ErrTxClosed) {
|
||||
t.Errorf("rollback questionnaire constraint check: %v", err)
|
||||
}
|
||||
}()
|
||||
if _, err := tx.Exec(ctx, `
|
||||
INSERT INTO candidate_questionnaires (user_id, version, work_formats, created_at, updated_at)
|
||||
VALUES ($1, 1, ARRAY['remote']::text[], statement_timestamp(), statement_timestamp())`, userID); err != nil {
|
||||
t.Fatalf("insert empty questionnaire row for DB constraint check: %v", err)
|
||||
}
|
||||
_, err = tx.Exec(ctx, `
|
||||
INSERT INTO candidate_questionnaire_specializations
|
||||
(user_id, ordinal, specialization, self_assessed_grade, task_languages, stack, commercial_months, academic_months)
|
||||
VALUES ($1, 0, 'backend', 'junior', ARRAY[]::text[], ARRAY[]::text[], 18, NULL)`, userID)
|
||||
var pgError *pgconn.PgError
|
||||
if !errors.As(err, &pgError) || pgError.Code != "23514" || pgError.ConstraintName != "candidate_questionnaire_specializations_experience" {
|
||||
t.Fatalf("one-sided experience month value error = %v, want experience CHECK", err)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user