1352 lines
67 KiB
Go
1352 lines
67 KiB
Go
//go:build integration
|
|
|
|
package integration_test
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"math"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"reflect"
|
|
"slices"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
httpadapter "lincodex/backend/internal/adapter/primary/http"
|
|
apiadapter "lincodex/backend/internal/adapter/primary/http/api"
|
|
v1 "lincodex/backend/internal/adapter/primary/http/v1"
|
|
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
|
|
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
|
|
"lincodex/backend/internal/domain"
|
|
"lincodex/backend/internal/port/outbound"
|
|
"lincodex/backend/internal/usecase/anonymousprofile"
|
|
"lincodex/backend/internal/usecase/assessment"
|
|
"lincodex/backend/internal/usecase/candidateprivacy"
|
|
"lincodex/backend/internal/usecase/candidateview"
|
|
"lincodex/backend/internal/usecase/companyquota"
|
|
"lincodex/backend/internal/usecase/evidence"
|
|
"lincodex/backend/internal/usecase/matching"
|
|
needusecase "lincodex/backend/internal/usecase/need"
|
|
"lincodex/backend/internal/usecase/organization"
|
|
"lincodex/backend/internal/usecase/policy"
|
|
profileusecase "lincodex/backend/internal/usecase/profile"
|
|
)
|
|
|
|
const matchSearchHTTPTimeout = 15 * time.Minute
|
|
|
|
// matchScoreTolerance covers the six-decimal rounding of the response.
|
|
const matchScoreTolerance = 1.5e-6
|
|
|
|
type matchSearchHarness struct {
|
|
*assessmentAttemptHTTPHarness
|
|
key domain.CandidateViewPseudonymKey
|
|
}
|
|
|
|
func newMatchSearchHarness(ctx context.Context, t *testing.T, env *testEnvironment) *matchSearchHarness {
|
|
t.Helper()
|
|
var key domain.CandidateViewPseudonymKey
|
|
var organizationHandler *v1.OrganizationHandler
|
|
harness := newAssessmentAttemptHTTPHarnessWithMiddleware(ctx, t, env,
|
|
assessment.AssessmentCategoryDecisionSettings{SyntheticDemoAssignmentsEnabled: true},
|
|
func(parts assessmentHarnessParts) []v1.HandlerOption {
|
|
var err error
|
|
if key, err = parts.keyring.CandidateViewPseudonymKey(); err != nil {
|
|
t.Fatalf("CandidateViewPseudonymKey() error = %v", err)
|
|
}
|
|
projector := anonymousprofile.NewService(postgresadapter.NewPrivacyCohortStore(parts.pool), key, parts.clock.Now)
|
|
quota := companyquota.NewService(parts.clock.Now)
|
|
views, err := candidateview.NewService(candidateview.Dependencies{
|
|
Transactor: parts.transactor, Projector: projector, PseudonymKey: key, Clock: parts.clock.Now,
|
|
Quota: func(ctx context.Context, unit outbound.UnitOfWork, organization domain.Organization, candidateID uuid.UUID) (outbound.CompanyQuotaDecision, error) {
|
|
return quota.ReserveCardView(ctx, unit, organization, candidateID)
|
|
},
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("candidateview.NewService() error = %v", err)
|
|
}
|
|
settings, err := candidateprivacy.NewService(candidateprivacy.Dependencies{Transactor: parts.transactor, Clock: parts.clock.Now})
|
|
if err != nil {
|
|
t.Fatalf("candidateprivacy.NewService() error = %v", err)
|
|
}
|
|
organizationService, err := organization.NewService(organization.Dependencies{
|
|
Transactor: parts.transactor, Keyring: parts.keyring, Clock: parts.clock.Now,
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("organization.NewService() error = %v", err)
|
|
}
|
|
needService, err := needusecase.NewService(needusecase.Dependencies{
|
|
Transactor: parts.transactor, Keyring: parts.keyring, Clock: parts.clock.Now,
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("need.NewService() error = %v", err)
|
|
}
|
|
search, err := matching.NewService(matching.Dependencies{
|
|
Transactor: parts.transactor, Cards: views.ListVisibleCards, Clock: parts.clock.Now,
|
|
Views: func(ctx context.Context, unit outbound.UnitOfWork, actorID, organizationID uuid.UUID) (matching.ViewSession, error) {
|
|
session, err := views.BeginSearchViews(ctx, unit, actorID, organizationID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return session, nil
|
|
},
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("matching.NewService() error = %v", err)
|
|
}
|
|
evidenceService, err := evidence.NewService(evidence.Dependencies{
|
|
Transactor: parts.transactor, AuthorizeCategories: views.AuthorizeCategoriesSection,
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("evidence.NewService() error = %v", err)
|
|
}
|
|
organizationHandler = v1.NewOrganizationHandler(organizationService, env.Config.AppPublicURL)
|
|
return []v1.HandlerOption{
|
|
v1.WithEvidence(v1.NewEvidenceHandler(evidenceService)),
|
|
v1.WithPrivacy(v1.NewPrivacyHandler(views, settings, env.Config.AppPublicURL)),
|
|
v1.WithProfile(v1.NewProfileHandler(profileusecase.NewService(parts.transactor, parts.clock.Now))),
|
|
v1.WithOrganization(organizationHandler),
|
|
v1.WithNeed(v1.NewNeedHandler(needService)),
|
|
v1.WithMatches(v1.NewMatchHandler(search)),
|
|
}
|
|
},
|
|
func() []apiadapter.Middleware {
|
|
return []apiadapter.Middleware{httpadapter.NewCompanyContextMiddleware(organizationHandler)}
|
|
})
|
|
return &matchSearchHarness{assessmentAttemptHTTPHarness: harness, key: key}
|
|
}
|
|
|
|
type matchEntryBody struct {
|
|
CandidateHandle string `json:"candidate_handle"`
|
|
Specialization string `json:"specialization"`
|
|
ConfirmationStatus string `json:"confirmation_status"`
|
|
DeclaredGrade *string `json:"declared_grade"`
|
|
Category *struct {
|
|
Specialization string `json:"specialization"`
|
|
Grade string `json:"grade"`
|
|
} `json:"category"`
|
|
Strength *string `json:"strength"`
|
|
PublicContext struct {
|
|
Stack []string `json:"stack"`
|
|
ExperienceBand *string `json:"experience_band"`
|
|
WorkFormats []string `json:"work_formats"`
|
|
SalaryCompatibility *string `json:"salary_compatibility"`
|
|
} `json:"public_context"`
|
|
EvidenceSummary []struct {
|
|
Code string `json:"code"`
|
|
State string `json:"state"`
|
|
} `json:"evidence_summary"`
|
|
Components map[string]*float64 `json:"components"`
|
|
UnknownFlags []struct {
|
|
Component string `json:"component"`
|
|
Reason string `json:"reason"`
|
|
} `json:"unknown_flags"`
|
|
}
|
|
|
|
func (entry matchEntryBody) component(name string) float64 {
|
|
if value := entry.Components[name]; value != nil {
|
|
return *value
|
|
}
|
|
return math.NaN()
|
|
}
|
|
|
|
func (entry matchEntryBody) summary() []string {
|
|
items := make([]string, 0, len(entry.EvidenceSummary))
|
|
for _, item := range entry.EvidenceSummary {
|
|
items = append(items, item.Code+":"+item.State)
|
|
}
|
|
return items
|
|
}
|
|
|
|
func (entry matchEntryBody) flags() []string {
|
|
flags := make([]string, 0, len(entry.UnknownFlags))
|
|
for _, flag := range entry.UnknownFlags {
|
|
flags = append(flags, flag.Component+":"+flag.Reason)
|
|
}
|
|
return flags
|
|
}
|
|
|
|
type matchSearchBody struct {
|
|
Source map[string]any `json:"source"`
|
|
Groups struct {
|
|
Main []matchEntryBody `json:"main"`
|
|
Near []matchEntryBody `json:"near"`
|
|
Unconfirmed []matchEntryBody `json:"unconfirmed"`
|
|
} `json:"groups"`
|
|
Truncated bool `json:"truncated"`
|
|
}
|
|
|
|
func (body matchSearchBody) handles() map[string]string {
|
|
handles := make(map[string]string)
|
|
for group, entries := range map[string][]matchEntryBody{"main": body.Groups.Main, "near": body.Groups.Near, "unconfirmed": body.Groups.Unconfirmed} {
|
|
for _, entry := range entries {
|
|
handles[entry.CandidateHandle+"/"+entry.Specialization] = group
|
|
}
|
|
}
|
|
return handles
|
|
}
|
|
|
|
func TestMatchSearchOverHTTP(t *testing.T) {
|
|
env := bootstrap(t, postgresService, redisService)
|
|
ctx, cancel := context.WithTimeout(t.Context(), matchSearchHTTPTimeout)
|
|
defer cancel()
|
|
databaseURL := env.createIsolatedDatabase(ctx, t)
|
|
applyMigrations(ctx, t, databaseURL)
|
|
isolatedEnv := *env
|
|
isolatedEnv.Config.DatabaseURL = databaseURL
|
|
harness := newMatchSearchHarness(ctx, t, &isolatedEnv)
|
|
// The scenarios below read banks of 11 and 16 entries, so the group limit is
|
|
// widened here; the demo value is checked by its own subtest.
|
|
wideLimit := func(product *domain.ProductPolicy) { product.Matching.MaxResultsPerGroup = 100 }
|
|
widePolicy := domain.DemoProductPolicyV4()
|
|
wideLimit(&widePolicy)
|
|
bank := seedAssessmentCategoryHTTPBank(ctx, t, harness.pool, widePolicy, true)
|
|
threshold := passPoints(int(bank.policy.Policy().Assessment.StopRule.MaxScoredItems), int(bank.policy.Policy().Assessment.Attempt.BasicPassMark))
|
|
client := &categoryHTTPClient{harness: harness.assessmentAttemptHTTPHarness, ctx: ctx}
|
|
transactor := postgresadapter.NewTransactor(harness.pool)
|
|
|
|
now := time.Now().UTC().Truncate(time.Microsecond)
|
|
identity := identityFixture{ctx: ctx, pool: harness.pool, store: harness.store, now: now}
|
|
organizations := organizationFixture{ctx: ctx, pool: harness.pool, identity: identity, transactor: transactor, now: now}
|
|
privacy := candidatePrivacyFixture{
|
|
ctx: ctx, pool: harness.pool, queries: sqlc.New(harness.pool), identity: identity,
|
|
organizations: organizations, ledger: postgresadapter.NewConsentStore(harness.pool), now: now,
|
|
}
|
|
|
|
const profileMarkers = "Private Marker"
|
|
allFields := []string{"categories", "stack", "experience", "self_assessment", "work_formats"}
|
|
unconfirmedFields := []string{"stack", "self_assessment", "work_formats"}
|
|
profileBody := func(stack []string, roles map[string]string) string {
|
|
stackItems := make([]map[string]any, 0, len(stack))
|
|
for _, tag := range stack {
|
|
stackItems = append(stackItems, map[string]any{"tag": tag, "status": "confirmed"})
|
|
}
|
|
roleItems := make([]map[string]any, 0, len(roles))
|
|
for _, specialization := range []string{"backend", "network_engineer"} {
|
|
if grade, ok := roles[specialization]; ok {
|
|
roleItems = append(roleItems, map[string]any{"specialization": specialization, "self_assessed_grade": grade, "status": "confirmed"})
|
|
}
|
|
}
|
|
body, err := json.Marshal(map[string]any{
|
|
"expected_version": 0,
|
|
"full_name": map[string]any{"value": profileMarkers + " Name", "status": "confirmed"},
|
|
"contacts": map[string]any{
|
|
"email": map[string]any{"value": "private-marker-contact@example.test", "status": "confirmed"}, "phone": nil, "telegram": nil,
|
|
},
|
|
"stack": stackItems, "roles": roleItems,
|
|
"experience": []any{map[string]any{
|
|
"employer_name": profileMarkers + " Employer", "specialization": "backend", "started_on": "2020-01",
|
|
"ended_on": "2023-12", "summary": profileMarkers + " Summary", "status": "confirmed",
|
|
}},
|
|
"confirmed_parallel_periods": []any{}, "soft_skills": []any{},
|
|
"terms": map[string]any{
|
|
"location": map[string]any{"value": profileMarkers + " Location", "status": "confirmed"}, "relocation": nil,
|
|
"salary_minimum": map[string]any{"value": map[string]any{
|
|
"amount": 731000, "currency": "RUB", "period": "month", "tax_basis": "net",
|
|
}, "status": "confirmed"},
|
|
},
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("marshal profile: %v", err)
|
|
}
|
|
return string(body)
|
|
}
|
|
call := func(who categoryHTTPCandidate, method, path, body string) (int, []byte) {
|
|
t.Helper()
|
|
return client.call(t, who, method, path, body, "")
|
|
}
|
|
mustCall := func(who categoryHTTPCandidate, method, path, body string, want int) []byte {
|
|
t.Helper()
|
|
status, response := call(who, method, path, body)
|
|
if status != want {
|
|
t.Fatalf("%s %s for %s = %d %s, want %d", method, path, who.email, status, response, want)
|
|
}
|
|
return response
|
|
}
|
|
// publish saves a profile and publishes the given card fields through the
|
|
// real candidate operations: the profile, the C2 consent, and the
|
|
// publication setting.
|
|
publish := func(who categoryHTTPCandidate, stack []string, roles map[string]string, fields []string) {
|
|
t.Helper()
|
|
mustCall(who, http.MethodPut, "/api/v1/me/profile", profileBody(stack, roles), http.StatusOK)
|
|
mustCall(who, http.MethodPut, "/api/v1/me/consents/c2", fmt.Sprintf(`{"text_version":%q,"accepted":true}`, privacyC2Version), http.StatusOK)
|
|
encoded, err := json.Marshal(fields)
|
|
if err != nil {
|
|
t.Fatalf("marshal fields: %v", err)
|
|
}
|
|
mustCall(who, http.MethodPut, "/api/v1/me/privacy/publication",
|
|
fmt.Sprintf(`{"expected_version":0,"state":"published","fields":%s}`, encoded), http.StatusOK)
|
|
}
|
|
passing := func(who categoryHTTPCandidate) attemptRun {
|
|
t.Helper()
|
|
run := client.run(t, who, "backend", "intern", func(int) int { return threshold })
|
|
if run.result["outcome"] != "confirmed" || decisionOf(t, run.result)["status"] != "assigned" {
|
|
t.Fatalf("passing run of %s = %v, want a confirmed assigned category", who.email, run.result)
|
|
}
|
|
return run
|
|
}
|
|
|
|
bothRoles := map[string]string{"backend": "junior", "network_engineer": "middle"}
|
|
backendRole := map[string]string{"backend": "junior"}
|
|
|
|
// G1: confirmed Backend with the Go tag; seven candidates so that each
|
|
// organization still sees six after one is hidden from it.
|
|
withGo := make([]categoryHTTPCandidate, 0, 7)
|
|
for index := range 7 {
|
|
member := client.candidate(t, fmt.Sprintf("match-go-%d@example.test", index))
|
|
passing(member)
|
|
publish(member, []string{"go"}, bothRoles, allFields)
|
|
withGo = append(withGo, member)
|
|
}
|
|
// G2: the same confirmed category without any stack tag.
|
|
withoutStack := make([]categoryHTTPCandidate, 0, 5)
|
|
var promotionSource attemptRun
|
|
for index := range 5 {
|
|
member := client.candidate(t, fmt.Sprintf("match-plain-%d@example.test", index))
|
|
run := passing(member)
|
|
if index == 4 {
|
|
promotionSource = run
|
|
}
|
|
publish(member, nil, bothRoles, allFields)
|
|
withoutStack = append(withoutStack, member)
|
|
}
|
|
// U: a declared Backend without a confirmed grade. One of them failed the
|
|
// attempt, which must change nothing in the result.
|
|
declaredOnly := make([]categoryHTTPCandidate, 0, 5)
|
|
for index := range 5 {
|
|
member := client.candidate(t, fmt.Sprintf("match-declared-%d@example.test", index))
|
|
if index == 0 {
|
|
failed := client.run(t, member, "backend", "intern", func(int) int { return threshold - 1 })
|
|
if failed.result["outcome"] != "not_confirmed" {
|
|
t.Fatalf("failing run = %v, want not_confirmed", failed.result["outcome"])
|
|
}
|
|
}
|
|
publish(member, []string{"go"}, backendRole, unconfirmedFields)
|
|
declaredOnly = append(declaredOnly, member)
|
|
}
|
|
|
|
employer := client.employer(t, "match-employer@example.test")
|
|
foreign := client.employer(t, "match-foreign@example.test")
|
|
recruiter := client.employer(t, "match-recruiter@example.test")
|
|
candidateOnly := client.candidate(t, "match-candidate-only@example.test")
|
|
orgA := organizations.create(t, domain.User{ID: employer.id}, organizations.completeProfile(t, "Match organization A"), now)
|
|
orgB := organizations.create(t, domain.User{ID: employer.id}, organizations.completeProfile(t, "Match organization B"), now)
|
|
foreignOrg := organizations.create(t, domain.User{ID: foreign.id}, organizations.completeProfile(t, "Match foreign organization"), now)
|
|
insertOrganizationHTTPMembership(ctx, t, harness.sessionHTTPHarness, orgA.ID(), recruiter.id, "recruiter", "active", now)
|
|
hiddenFromA, hiddenFromB := withGo[0], withGo[1]
|
|
privacy.hide(t, hiddenFromA.id, orgA.ID(), now)
|
|
privacy.hide(t, hiddenFromB.id, orgB.ID(), now)
|
|
// The policy and the organizations take effect when they are stored, which
|
|
// is after the clock of the harness was read.
|
|
harness.clock.Set(time.Now().UTC().Truncate(time.Microsecond))
|
|
|
|
candidateIDs := make(map[uuid.UUID]string)
|
|
for _, group := range [][]categoryHTTPCandidate{withGo, withoutStack, declaredOnly} {
|
|
for _, member := range group {
|
|
candidateIDs[member.id] = member.email
|
|
}
|
|
}
|
|
aliasIn := func(organizationID, candidateID uuid.UUID) string {
|
|
t.Helper()
|
|
alias, err := harness.key.ForOrganization(organizationID, candidateID)
|
|
if err != nil {
|
|
t.Fatalf("ForOrganization() error = %v", err)
|
|
}
|
|
return alias
|
|
}
|
|
candidateOfHandle := func(organizationID uuid.UUID) map[string]uuid.UUID {
|
|
handles := make(map[string]uuid.UUID, len(candidateIDs))
|
|
for id := range candidateIDs {
|
|
handles[aliasIn(organizationID, id)] = id
|
|
}
|
|
return handles
|
|
}
|
|
searchPath := func(organizationID uuid.UUID) string {
|
|
return fmt.Sprintf("/api/v1/organizations/%s/matches", organizationID)
|
|
}
|
|
search := func(who categoryHTTPCandidate, organizationID uuid.UUID, body string) (matchSearchBody, *httptest.ResponseRecorder) {
|
|
t.Helper()
|
|
response := harness.request(t, http.MethodPost, searchPath(organizationID), body, sessionHTTPTestOrigin, who.cookie, who.csrf, client.remote())
|
|
var decoded matchSearchBody
|
|
if response.Code == http.StatusOK {
|
|
if err := json.Unmarshal(response.Body.Bytes(), &decoded); err != nil {
|
|
t.Fatalf("decode search result: %v\n%s", err, response.Body.String())
|
|
}
|
|
}
|
|
return decoded, response
|
|
}
|
|
mustSearch := func(organizationID uuid.UUID, body string) matchSearchBody {
|
|
t.Helper()
|
|
result, response := search(employer, organizationID, body)
|
|
if response.Code != http.StatusOK || response.Header().Get("Cache-Control") != "no-store" {
|
|
t.Fatalf("search = %d Cache-Control=%q %s, want a no-store 200", response.Code, response.Header().Get("Cache-Control"), response.Body.String())
|
|
}
|
|
return result
|
|
}
|
|
handlesOf := func(entries []matchEntryBody) []string {
|
|
handles := make([]string, 0, len(entries))
|
|
for _, entry := range entries {
|
|
handles = append(handles, entry.CandidateHandle)
|
|
}
|
|
return handles
|
|
}
|
|
handlesFor := func(organizationID uuid.UUID, groups ...[]categoryHTTPCandidate) []string {
|
|
var handles []string
|
|
for _, group := range groups {
|
|
for _, member := range group {
|
|
handles = append(handles, aliasIn(organizationID, member.id))
|
|
}
|
|
}
|
|
slices.Sort(handles)
|
|
return handles
|
|
}
|
|
sortedHandles := func(entries []matchEntryBody) []string {
|
|
handles := handlesOf(entries)
|
|
slices.Sort(handles)
|
|
return handles
|
|
}
|
|
almost := func(got, want float64) bool { return math.Abs(got-want) <= matchScoreTolerance }
|
|
assertScores := func(t *testing.T, label string, entries []matchEntryBody, want map[string]float64) {
|
|
t.Helper()
|
|
for _, entry := range entries {
|
|
for name, value := range want {
|
|
if got := entry.component(name); !almost(got, value) {
|
|
t.Errorf("%s entry %s %s = %v, want %v", label, entry.Specialization, name, got, value)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
// assertOrder checks the documented order of a group from the internal
|
|
// identifiers that the test knows and the response never shows.
|
|
assertOrder := func(t *testing.T, organizationID uuid.UUID, entries []matchEntryBody, confirmed bool) {
|
|
t.Helper()
|
|
candidates := candidateOfHandle(organizationID)
|
|
for index := 1; index < len(entries); index++ {
|
|
previous, current := entries[index-1], entries[index]
|
|
var previousKeys, currentKeys []float64
|
|
if confirmed {
|
|
previousKeys = []float64{previous.component("rank_score"), previous.component("coverage")}
|
|
currentKeys = []float64{current.component("rank_score"), current.component("coverage")}
|
|
} else {
|
|
previousKeys = []float64{previous.component("fit"), previous.component("coverage")}
|
|
currentKeys = []float64{current.component("fit"), current.component("coverage")}
|
|
}
|
|
for key := range previousKeys {
|
|
if previousKeys[key] > currentKeys[key] {
|
|
break
|
|
}
|
|
if previousKeys[key] < currentKeys[key] {
|
|
t.Fatalf("entry %d precedes %d although its scores are lower: %v then %v", index-1, index, previousKeys, currentKeys)
|
|
}
|
|
if key == len(previousKeys)-1 {
|
|
previousID, currentID := candidates[previous.CandidateHandle].String(), candidates[current.CandidateHandle].String()
|
|
if previousID > currentID || (previousID == currentID && previous.Specialization > current.Specialization) {
|
|
t.Fatalf("equal scores are not ordered by the internal identifier: %s before %s", previousID, currentID)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
countRows := func(query string, args ...any) int {
|
|
t.Helper()
|
|
var count int
|
|
if err := harness.pool.QueryRow(ctx, query, args...).Scan(&count); err != nil {
|
|
t.Fatalf("count rows: %v", err)
|
|
}
|
|
return count
|
|
}
|
|
revealedBy := func(organizationID uuid.UUID) int {
|
|
t.Helper()
|
|
return countRows(`SELECT count(*) FROM company_card_view_quota_usage WHERE organization_id = $1`, organizationID)
|
|
}
|
|
historyOf := func(candidateID, organizationID uuid.UUID) [][]string {
|
|
t.Helper()
|
|
rows, err := harness.pool.Query(ctx, `SELECT field_codes FROM candidate_card_access_events
|
|
WHERE candidate_id = $1 AND organization_id = $2 AND kind = 'card_viewed' ORDER BY occurred_at, id`, candidateID, organizationID)
|
|
if err != nil {
|
|
t.Fatalf("read access history: %v", err)
|
|
}
|
|
defer rows.Close()
|
|
var history [][]string
|
|
for rows.Next() {
|
|
var fields []string
|
|
if err := rows.Scan(&fields); err != nil {
|
|
t.Fatalf("scan access history: %v", err)
|
|
}
|
|
history = append(history, fields)
|
|
}
|
|
return history
|
|
}
|
|
clockOffset := time.Minute
|
|
publishPolicy := func(change func(*domain.ProductPolicy)) {
|
|
t.Helper()
|
|
product := domain.DemoProductPolicyV4()
|
|
wideLimit(&product)
|
|
if change != nil {
|
|
change(&product)
|
|
}
|
|
publisher := policy.NewPublisher(postgresadapter.NewPolicyStore(harness.pool).Policies(), time.Now)
|
|
if _, err := publisher.Publish(ctx, policy.PublishInput{
|
|
Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, Author: policyTestAuthor, Policy: product,
|
|
}); err != nil {
|
|
t.Fatalf("Publish(policy) error = %v", err)
|
|
}
|
|
clockOffset += time.Minute
|
|
harness.clock.Set(time.Now().UTC().Add(clockOffset).Truncate(time.Microsecond))
|
|
}
|
|
createNeed := func(organizationID uuid.UUID, body, key string) (uuid.UUID, int64) {
|
|
t.Helper()
|
|
status, response := client.call(t, employer, http.MethodPost, fmt.Sprintf("/api/v1/organizations/%s/needs", organizationID), body, key)
|
|
var need struct {
|
|
ID uuid.UUID `json:"id"`
|
|
Version int64 `json:"version"`
|
|
RequirementsVersion int64 `json:"requirements_version"`
|
|
}
|
|
if status != http.StatusCreated || json.Unmarshal(response, &need) != nil || need.ID == uuid.Nil {
|
|
t.Fatalf("create need = %d %s, want 201", status, response)
|
|
}
|
|
return need.ID, need.RequirementsVersion
|
|
}
|
|
patchNeed := func(organizationID, needID uuid.UUID, body string) (version, requirementsVersion int64) {
|
|
t.Helper()
|
|
status, response := client.call(t, employer, http.MethodPatch, fmt.Sprintf("/api/v1/organizations/%s/needs/%s", organizationID, needID), body, "")
|
|
var need struct {
|
|
Version int64 `json:"version"`
|
|
RequirementsVersion int64 `json:"requirements_version"`
|
|
}
|
|
if status != http.StatusOK || json.Unmarshal(response, &need) != nil {
|
|
t.Fatalf("patch need = %d %s, want 200", status, response)
|
|
}
|
|
return need.Version, need.RequirementsVersion
|
|
}
|
|
needRequest := func(needID uuid.UUID, version int64, filters string) string {
|
|
body := fmt.Sprintf(`{"need_id":%q,"requirements_version":%d`, needID, version)
|
|
if filters != "" {
|
|
body += `,"filters":` + filters
|
|
}
|
|
return body + "}"
|
|
}
|
|
|
|
// The standing cohort sizes: each organization sees six of the seven
|
|
// candidates with the Go tag and all five of the others.
|
|
t.Run("the bank search applies visibility and hiding before any group and keeps an unconfirmed category visible", func(t *testing.T) {
|
|
bankA := mustSearch(orgA.ID(), `{"filters":{"confirmed_category":{"specialization":"backend","grade":"intern"}}}`)
|
|
if bankA.Truncated {
|
|
t.Fatal("a result under the group limit and the allowance is flagged as truncated")
|
|
}
|
|
wantA := handlesFor(orgA.ID(), withGo[1:], withoutStack)
|
|
if got := sortedHandles(bankA.Groups.Main); !slices.Equal(got, wantA) || len(bankA.Groups.Near) != 0 || len(bankA.Groups.Unconfirmed) != 0 {
|
|
t.Fatalf("organization A confirmed bank = %d main, %d near, %d unconfirmed; want exactly the eleven visible confirmed candidates",
|
|
len(bankA.Groups.Main), len(bankA.Groups.Near), len(bankA.Groups.Unconfirmed))
|
|
}
|
|
if slices.Contains(handlesOf(bankA.Groups.Main), aliasIn(orgA.ID(), hiddenFromA.id)) {
|
|
t.Fatal("organization A received a candidate that hides it")
|
|
}
|
|
bankB := mustSearch(orgB.ID(), `{"filters":{"confirmed_category":{"specialization":"backend","grade":"intern"}}}`)
|
|
wantB := handlesFor(orgB.ID(), append([]categoryHTTPCandidate{withGo[0]}, withGo[2:]...), withoutStack)
|
|
if got := sortedHandles(bankB.Groups.Main); !slices.Equal(got, wantB) {
|
|
t.Fatalf("organization B main handles = %v, want %v", got, wantB)
|
|
}
|
|
if slices.Contains(handlesOf(bankB.Groups.Main), aliasIn(orgB.ID(), hiddenFromB.id)) {
|
|
t.Fatal("organization B received a candidate that hides it")
|
|
}
|
|
// The same candidate has a different handle in each organization.
|
|
if aliasIn(orgA.ID(), withGo[2].id) == aliasIn(orgB.ID(), withGo[2].id) {
|
|
t.Fatal("organizations share a candidate handle")
|
|
}
|
|
|
|
for _, entry := range append(bankA.Groups.Main, bankB.Groups.Main...) {
|
|
if entry.ConfirmationStatus != "confirmed" || entry.Category == nil || entry.Category.Specialization != "backend" ||
|
|
entry.Category.Grade != "intern" || entry.Strength == nil || *entry.Strength != "standard" {
|
|
t.Fatalf("confirmed entry = %+v, want the confirmed Backend intern category", entry)
|
|
}
|
|
if entry.Components["percentile"] != nil || entry.component("competition") != 0 || !almost(entry.component("semantics"), 0.5) ||
|
|
!slices.Contains(entry.flags(), "semantics:ml_unavailable") || !slices.Contains(entry.flags(), "percentile:cohort_below_30") {
|
|
t.Fatalf("confirmed entry components = %v flags %v, want neutral Sem, no percentile, and V = 0", entry.Components, entry.flags())
|
|
}
|
|
}
|
|
|
|
// Without a filter the same bank also lists the specializations that
|
|
// are only declared; a missing confirmation never hides a profile.
|
|
general := mustSearch(orgA.ID(), `{"filters":{}}`)
|
|
if len(general.Groups.Main) != 11 || len(general.Groups.Near) != 0 {
|
|
t.Fatalf("general search = %d main, %d near, want eleven main and no near without a request for skills", len(general.Groups.Main), len(general.Groups.Near))
|
|
}
|
|
var networks, backendDeclared []string
|
|
for _, entry := range general.Groups.Unconfirmed {
|
|
switch entry.Specialization {
|
|
case "network_engineer":
|
|
networks = append(networks, entry.CandidateHandle)
|
|
case "backend":
|
|
backendDeclared = append(backendDeclared, entry.CandidateHandle)
|
|
}
|
|
if entry.ConfirmationStatus != "unconfirmed" || entry.Category != nil || entry.Strength != nil {
|
|
t.Fatalf("unconfirmed entry = %+v, want no category and no strength", entry)
|
|
}
|
|
}
|
|
slices.Sort(networks)
|
|
slices.Sort(backendDeclared)
|
|
if !slices.Equal(networks, handlesFor(orgA.ID(), withGo[1:], withoutStack)) ||
|
|
!slices.Equal(backendDeclared, handlesFor(orgA.ID(), declaredOnly)) || len(general.Groups.Unconfirmed) != 11+5 {
|
|
t.Fatalf("unconfirmed group = %d entries (networks %d, declared Backend %d), want 16", len(general.Groups.Unconfirmed), len(networks), len(backendDeclared))
|
|
}
|
|
assertScores(t, "general unconfirmed", general.Groups.Unconfirmed, map[string]float64{"fit": 0.5, "coverage": 0.5})
|
|
assertScores(t, "general confirmed", general.Groups.Main, map[string]float64{"fit": 0.5, "coverage": 0.5, "rank_score": 0.45125})
|
|
if source, _ := general.Source["kind"].(string); source != "bank" {
|
|
t.Fatalf("source = %v, want the bank basis", general.Source)
|
|
}
|
|
})
|
|
|
|
var needID uuid.UUID
|
|
var needRequirementsV1 int64
|
|
var firstNeedSearch, secondNeedSearch matchSearchBody
|
|
var secondRequirementsVersion int64
|
|
t.Run("a need search scores the confirmed requirements and the explanation follows the same components", func(t *testing.T) {
|
|
needID, needRequirementsV1 = createNeed(orgA.ID(),
|
|
`{"title":"Payments backend","specialization":{"value":"backend","status":"confirmed"},"required_skills":[{"name":"Go","status":"confirmed"}]}`,
|
|
"match-need-1")
|
|
firstNeedSearch = mustSearch(orgA.ID(), needRequest(needID, needRequirementsV1, ""))
|
|
if source := firstNeedSearch.Source; source["kind"] != "need" || source["need_id"] != needID.String() || source["requirements_version"] != float64(needRequirementsV1) {
|
|
t.Fatalf("source = %v, want the need snapshot", source)
|
|
}
|
|
// A Go tag is a stated claim worth 0.25 and meets the near threshold; a
|
|
// backend measurement is broader than the requested skill, worth
|
|
// 0.6 * 1.0 * 0.4 = 0.24, and falls below it.
|
|
if got, want := sortedHandles(firstNeedSearch.Groups.Main), handlesFor(orgA.ID(), withGo[1:]); !slices.Equal(got, want) {
|
|
t.Fatalf("main = %v, want the six candidates with the Go tag", got)
|
|
}
|
|
if got, want := sortedHandles(firstNeedSearch.Groups.Near), handlesFor(orgA.ID(), withoutStack); !slices.Equal(got, want) {
|
|
t.Fatalf("near = %v, want the five candidates without the tag", got)
|
|
}
|
|
if got, want := sortedHandles(firstNeedSearch.Groups.Unconfirmed), handlesFor(orgA.ID(), declaredOnly); !slices.Equal(got, want) {
|
|
t.Fatalf("unconfirmed = %v, want the five declared Backend profiles, and no other specialization of a Backend need", got)
|
|
}
|
|
assertScores(t, "main", firstNeedSearch.Groups.Main, map[string]float64{"coverage": 0.25, "fit": 0.3125, "rank_score": 0.366641})
|
|
assertScores(t, "near", firstNeedSearch.Groups.Near, map[string]float64{"coverage": 0.24, "fit": 0.305, "rank_score": 0.363256})
|
|
assertScores(t, "unconfirmed", firstNeedSearch.Groups.Unconfirmed, map[string]float64{"coverage": 0.25, "fit": 0.3125})
|
|
wantMain := []string{"confirmed_category:supports", "declared_grade:declared_only", "required_skill_evidence:declared_only"}
|
|
wantNear := []string{"confirmed_category:supports", "declared_grade:declared_only", "required_skill_evidence:partial"}
|
|
wantUnconfirmed := []string{"declared_grade:declared_only", "required_skill_evidence:declared_only"}
|
|
for _, check := range []struct {
|
|
entries []matchEntryBody
|
|
want []string
|
|
}{{firstNeedSearch.Groups.Main, wantMain}, {firstNeedSearch.Groups.Near, wantNear}, {firstNeedSearch.Groups.Unconfirmed, wantUnconfirmed}} {
|
|
for _, entry := range check.entries {
|
|
if got := entry.summary(); !slices.Equal(got, check.want) {
|
|
t.Fatalf("explanation of %s = %v, want %v", entry.Specialization, got, check.want)
|
|
}
|
|
}
|
|
}
|
|
|
|
// Changing the required skills moves the numbers, the groups, and the
|
|
// explanation together.
|
|
version, requirementsVersion := patchNeed(orgA.ID(), needID,
|
|
`{"expected_version":1,"required_skills":[{"name":"Go","status":"confirmed"},{"name":"Kafka","status":"confirmed"}]}`)
|
|
secondRequirementsVersion = requirementsVersion
|
|
if requirementsVersion != version || requirementsVersion == needRequirementsV1 {
|
|
t.Fatalf("requirements version after the change = %d (version %d), want a new snapshot", requirementsVersion, version)
|
|
}
|
|
secondNeedSearch = mustSearch(orgA.ID(), needRequest(needID, requirementsVersion, ""))
|
|
if len(secondNeedSearch.Groups.Main) != 0 || len(secondNeedSearch.Groups.Near) != 11 || len(secondNeedSearch.Groups.Unconfirmed) != 5 {
|
|
t.Fatalf("second search = %d main, %d near, %d unconfirmed, want every confirmed profile in near", len(secondNeedSearch.Groups.Main), len(secondNeedSearch.Groups.Near), len(secondNeedSearch.Groups.Unconfirmed))
|
|
}
|
|
for _, entry := range secondNeedSearch.Groups.Near {
|
|
if entry.PublicContext.Stack == nil {
|
|
assertScores(t, "near without a tag", []matchEntryBody{entry}, map[string]float64{"coverage": 0.24, "fit": 0.305, "rank_score": 0.363256})
|
|
continue
|
|
}
|
|
// (2 * 0.25 + 2 * 0.24) / 4 = 0.245
|
|
assertScores(t, "near with the Go tag", []matchEntryBody{entry}, map[string]float64{"coverage": 0.245, "fit": 0.30875, "rank_score": 0.364948})
|
|
if got := entry.summary(); !slices.Equal(got, []string{"confirmed_category:supports", "declared_grade:declared_only", "required_skill_evidence:partial"}) {
|
|
t.Fatalf("explanation with the Kafka requirement = %v", got)
|
|
}
|
|
}
|
|
// (2 * 0.25 + 2 * 0) / 4 = 0.125: Kafka has no evidence, and that is a gap, not a ban.
|
|
assertScores(t, "unconfirmed", secondNeedSearch.Groups.Unconfirmed, map[string]float64{"coverage": 0.125, "fit": 0.21875})
|
|
for _, entry := range secondNeedSearch.Groups.Unconfirmed {
|
|
if got := entry.summary(); !slices.Equal(got, []string{"declared_grade:declared_only", "required_skill_evidence:partial"}) {
|
|
t.Fatalf("explanation of an unconfirmed entry with the Kafka requirement = %v", got)
|
|
}
|
|
}
|
|
|
|
// The first snapshot is immutable: it answers as it did.
|
|
again := mustSearch(orgA.ID(), needRequest(needID, needRequirementsV1, ""))
|
|
if !jsonEqual(t, again, firstNeedSearch) {
|
|
t.Fatal("the search of the first requirements version changed after the need was edited")
|
|
}
|
|
// A title edit makes a need version but no requirements version.
|
|
titleVersion, titleRequirements := patchNeed(orgA.ID(), needID, `{"expected_version":2,"title":"Payments backend team"}`)
|
|
if titleVersion != 3 || titleRequirements != secondRequirementsVersion {
|
|
t.Fatalf("title edit = version %d, requirements %d, want 3 and %d", titleVersion, titleRequirements, secondRequirementsVersion)
|
|
}
|
|
if _, response := search(employer, orgA.ID(), needRequest(needID, titleVersion, "")); response.Code != http.StatusNotFound {
|
|
t.Fatalf("search by a need version that is not a requirements version = %d, want 404", response.Code)
|
|
}
|
|
if _, response := search(employer, orgA.ID(), needRequest(needID, secondRequirementsVersion+5, "")); response.Code != http.StatusNotFound {
|
|
t.Fatalf("search by an unknown requirements version = %d, want 404", response.Code)
|
|
}
|
|
// Another organization cannot search a need it does not own.
|
|
if _, response := search(employer, orgB.ID(), needRequest(needID, needRequirementsV1, "")); response.Code != http.StatusNotFound {
|
|
t.Fatalf("search of a need of another organization = %d, want 404", response.Code)
|
|
}
|
|
if _, response := search(employer, orgA.ID(), needRequest(uuid.New(), 1, "")); response.Code != http.StatusNotFound {
|
|
t.Fatalf("search of an unknown need = %d, want 404", response.Code)
|
|
}
|
|
// A need without a confirmed specialization searches every
|
|
// specialization, and the unconfirmed group then mixes them: Fit
|
|
// decides, then coverage, then the internal identifier.
|
|
anyID, anyVersion := createNeed(orgA.ID(),
|
|
`{"title":"Any specialization","required_skills":[{"name":"Go","status":"confirmed"},{"name":"Kafka","status":"confirmed"}]}`,
|
|
"match-need-any")
|
|
anySearch := mustSearch(orgA.ID(), needRequest(anyID, anyVersion, ""))
|
|
if len(anySearch.Groups.Main) != 0 || len(anySearch.Groups.Near) != 11 || len(anySearch.Groups.Unconfirmed) != 16 {
|
|
t.Fatalf("search without a need specialization = %d main, %d near, %d unconfirmed, want 0, 11, 16",
|
|
len(anySearch.Groups.Main), len(anySearch.Groups.Near), len(anySearch.Groups.Unconfirmed))
|
|
}
|
|
// The five Networks entries of candidates without the Go tag have no
|
|
// evidence for either skill and come last, as a gap and not as a ban.
|
|
lastFive := anySearch.Groups.Unconfirmed[11:]
|
|
for _, entry := range lastFive {
|
|
if entry.Specialization != "network_engineer" || entry.component("coverage") != 0 || !almost(entry.component("fit"), 0.125) {
|
|
t.Fatalf("last unconfirmed entry = %+v %v, want a Networks entry without evidence", entry.Specialization, entry.Components)
|
|
}
|
|
if got := entry.summary(); !slices.Equal(got, []string{"declared_grade:declared_only", "required_skill_evidence:gap"}) {
|
|
t.Fatalf("explanation of an entry without evidence = %v", got)
|
|
}
|
|
}
|
|
assertScores(t, "unconfirmed with evidence", anySearch.Groups.Unconfirmed[:11], map[string]float64{"coverage": 0.125, "fit": 0.21875})
|
|
assertOrder(t, orgA.ID(), anySearch.Groups.Unconfirmed, false)
|
|
assertOrder(t, orgA.ID(), anySearch.Groups.Near, true)
|
|
// A different specialization filter than the need leaves nothing.
|
|
empty := mustSearch(orgA.ID(), needRequest(needID, needRequirementsV1, `{"specialization":"frontend"}`))
|
|
if len(empty.Groups.Main)+len(empty.Groups.Near)+len(empty.Groups.Unconfirmed) != 0 {
|
|
t.Fatalf("search with a specialization filter that contradicts the need returned entries: %+v", empty.Groups)
|
|
}
|
|
})
|
|
|
|
t.Run("the same data and policy give the same order and scores, and each organization its own handles", func(t *testing.T) {
|
|
request := needRequest(needID, needRequirementsV1, "")
|
|
var first []byte
|
|
for range 3 {
|
|
_, response := search(employer, orgA.ID(), request)
|
|
if response.Code != http.StatusOK {
|
|
t.Fatalf("repeat search = %d %s", response.Code, response.Body.String())
|
|
}
|
|
if first == nil {
|
|
first = bytes.Clone(response.Body.Bytes())
|
|
} else if !bytes.Equal(first, response.Body.Bytes()) {
|
|
t.Fatalf("repeat search changed:\n%s\n%s", first, response.Body.Bytes())
|
|
}
|
|
}
|
|
assertOrder(t, orgA.ID(), firstNeedSearch.Groups.Main, true)
|
|
assertOrder(t, orgA.ID(), firstNeedSearch.Groups.Near, true)
|
|
assertOrder(t, orgA.ID(), firstNeedSearch.Groups.Unconfirmed, false)
|
|
assertOrder(t, orgA.ID(), secondNeedSearch.Groups.Near, true)
|
|
// Organization B sees the bank through its own handles and its own
|
|
// hiding, with the same scores.
|
|
bank := `{"filters":{"specialization":"backend"}}`
|
|
forA, forB := mustSearch(orgA.ID(), bank), mustSearch(orgB.ID(), bank)
|
|
for _, handle := range handlesOf(forB.Groups.Main) {
|
|
if slices.Contains(handlesOf(forA.Groups.Main), handle) {
|
|
t.Fatalf("handle %s is shared by two organizations", handle)
|
|
}
|
|
}
|
|
if slices.Contains(handlesOf(forB.Groups.Main), aliasIn(orgB.ID(), hiddenFromB.id)) || !slices.Contains(handlesOf(forB.Groups.Main), aliasIn(orgB.ID(), hiddenFromA.id)) {
|
|
t.Fatal("organization B does not get exactly the cards that are not hidden from B")
|
|
}
|
|
})
|
|
|
|
t.Run("a candidate keeps a separate state for each specialization", func(t *testing.T) {
|
|
general := mustSearch(orgA.ID(), `{"filters":{}}`)
|
|
member := withGo[3]
|
|
handle := aliasIn(orgA.ID(), member.id)
|
|
var confirmedEntry, networkEntry *matchEntryBody
|
|
for index := range general.Groups.Main {
|
|
if general.Groups.Main[index].CandidateHandle == handle {
|
|
confirmedEntry = &general.Groups.Main[index]
|
|
}
|
|
}
|
|
for index := range general.Groups.Unconfirmed {
|
|
if general.Groups.Unconfirmed[index].CandidateHandle == handle {
|
|
networkEntry = &general.Groups.Unconfirmed[index]
|
|
}
|
|
}
|
|
if confirmedEntry == nil || networkEntry == nil || confirmedEntry.Specialization != "backend" || networkEntry.Specialization != "network_engineer" {
|
|
t.Fatalf("entries of one handle = %+v and %+v, want confirmed Backend and unconfirmed Networks", confirmedEntry, networkEntry)
|
|
}
|
|
if confirmedEntry.DeclaredGrade == nil || *confirmedEntry.DeclaredGrade != "junior" ||
|
|
networkEntry.DeclaredGrade == nil || *networkEntry.DeclaredGrade != "middle" {
|
|
t.Fatalf("declared grades = %v and %v, want junior for Backend and middle for Networks", confirmedEntry.DeclaredGrade, networkEntry.DeclaredGrade)
|
|
}
|
|
if got := networkEntry.flags(); !slices.Equal(got, []string{
|
|
"semantics:ml_unavailable", "assessment:no_confirmation_for_specialization", "salary_compatibility:not_in_public_card", "domain:need_field_unconfirmed",
|
|
}) {
|
|
t.Fatalf("unknown flags of the unconfirmed entry = %v", got)
|
|
}
|
|
// The unconfirmed object holds a fit and a coverage and nothing else:
|
|
// no theta, T, P, percentile, or rank score.
|
|
if len(networkEntry.Components) != 2 || networkEntry.Components["fit"] == nil || networkEntry.Components["coverage"] == nil {
|
|
t.Fatalf("unconfirmed components = %v, want only fit and coverage", networkEntry.Components)
|
|
}
|
|
// A search for Networks shows Backend's confirmation nowhere.
|
|
networks := mustSearch(orgA.ID(), `{"filters":{"specialization":"network_engineer"}}`)
|
|
if len(networks.Groups.Main)+len(networks.Groups.Near) != 0 || len(networks.Groups.Unconfirmed) != 11 {
|
|
t.Fatalf("Networks search = %d confirmed, %d unconfirmed, want 11 unconfirmed and no transferred confirmation",
|
|
len(networks.Groups.Main)+len(networks.Groups.Near), len(networks.Groups.Unconfirmed))
|
|
}
|
|
// An explicit filter on a confirmed grade or category excludes every
|
|
// unconfirmed profile; a declared grade is a separate claim.
|
|
for _, filters := range []string{
|
|
`{"confirmed_grade":"intern"}`, `{"confirmed_category":{"specialization":"backend","grade":"intern"}}`, `{"confirmation_status":"confirmed"}`,
|
|
} {
|
|
filtered := mustSearch(orgA.ID(), fmt.Sprintf(`{"filters":%s}`, filters))
|
|
if len(filtered.Groups.Unconfirmed) != 0 || len(filtered.Groups.Main) != 11 {
|
|
t.Fatalf("filters %s = %d main, %d unconfirmed, want only the confirmed profiles", filters, len(filtered.Groups.Main), len(filtered.Groups.Unconfirmed))
|
|
}
|
|
}
|
|
if filtered := mustSearch(orgA.ID(), `{"filters":{"confirmed_grade":"senior"}}`); len(filtered.Groups.Main)+len(filtered.Groups.Unconfirmed) != 0 {
|
|
t.Fatalf("a confirmed senior filter matched %d entries, want none", len(filtered.Groups.Main)+len(filtered.Groups.Unconfirmed))
|
|
}
|
|
onlyUnconfirmed := mustSearch(orgA.ID(), `{"filters":{"confirmation_status":"unconfirmed"}}`)
|
|
if len(onlyUnconfirmed.Groups.Main)+len(onlyUnconfirmed.Groups.Near) != 0 || len(onlyUnconfirmed.Groups.Unconfirmed) != 16 {
|
|
t.Fatalf("unconfirmed-only search = %d entries, want the 16 unconfirmed", len(onlyUnconfirmed.Groups.Unconfirmed))
|
|
}
|
|
declared := mustSearch(orgA.ID(), `{"filters":{"declared_grade":"middle"}}`)
|
|
if len(declared.Groups.Main)+len(declared.Groups.Near) != 0 || len(declared.Groups.Unconfirmed) != 11 {
|
|
t.Fatalf("declared middle search = %d entries, want the 11 Networks declarations and no confirmed entry", len(declared.Groups.Unconfirmed))
|
|
}
|
|
// Safe card conditions and stack filters narrow the visible set.
|
|
stack := mustSearch(orgA.ID(), `{"filters":{"stack":["go"]}}`)
|
|
if len(stack.Groups.Main) != 6 || len(stack.Groups.Unconfirmed) != 6+5 {
|
|
t.Fatalf("stack filter = %d main, %d unconfirmed, want the six candidates with the tag and their entries", len(stack.Groups.Main), len(stack.Groups.Unconfirmed))
|
|
}
|
|
conditions := mustSearch(orgA.ID(), `{"filters":{"conditions":{"work_formats":["office"]}}}`)
|
|
if len(conditions.Groups.Main)+len(conditions.Groups.Near)+len(conditions.Groups.Unconfirmed) != 0 {
|
|
t.Fatal("a work format that no card offers matched a candidate")
|
|
}
|
|
remote := mustSearch(orgA.ID(), `{"filters":{"conditions":{"work_formats":["remote","office"],"salary_compatibility":"compatible"}}}`)
|
|
if len(remote.Groups.Main)+len(remote.Groups.Near)+len(remote.Groups.Unconfirmed) != 0 {
|
|
t.Fatal("an unknown salary compatibility satisfied a compatibility filter")
|
|
}
|
|
if remoteOnly := mustSearch(orgA.ID(), `{"filters":{"conditions":{"work_formats":["remote"]}}}`); len(remoteOnly.Groups.Main) != 11 {
|
|
t.Fatalf("remote filter = %d main, want 11", len(remoteOnly.Groups.Main))
|
|
}
|
|
})
|
|
|
|
t.Run("a failed promotion keeps the confirmed category and leaves no trace in the result", func(t *testing.T) {
|
|
member := withoutStack[4]
|
|
before := mustSearch(orgA.ID(), `{"filters":{"confirmed_category":{"specialization":"backend","grade":"intern"}}}`)
|
|
// The promotion interval counts on database time, so the finished
|
|
// intern attempt is moved past it instead of waiting for days.
|
|
moveFinishedAttemptBack(t, ctx, harness.pool, promotionSource.id, categoryHTTPPromotionGap)
|
|
failed := client.run(t, member, "backend", "junior", func(int) int { return threshold - 1 })
|
|
if failed.result["outcome"] != "not_confirmed" || failed.result["previous_confirmed_grade"] != "intern" {
|
|
t.Fatalf("failed promotion = %v, want not_confirmed with the intern grade in force", failed.result)
|
|
}
|
|
after := mustSearch(orgA.ID(), `{"filters":{"confirmed_category":{"specialization":"backend","grade":"intern"}}}`)
|
|
if !jsonEqual(t, before, after) {
|
|
t.Fatal("a failed promotion changed the search result: the confirmed grade must stay and the failure must not count")
|
|
}
|
|
})
|
|
|
|
t.Run("the response holds no contact, minimum, identifier, failure, or percentile", func(t *testing.T) {
|
|
_, response := search(employer, orgA.ID(), `{"filters":{}}`)
|
|
text := response.Body.String()
|
|
for _, forbidden := range []string{
|
|
profileMarkers, "private-marker-contact", "731000", "email", "phone", "telegram", "salary_minimum", "full_name", "location",
|
|
"theta", "not_confirmed", "failed", "attempt", "answer", "score_id", "fsp", "FSP", "policy", orgA.ID().String(), orgB.ID().String(),
|
|
} {
|
|
if strings.Contains(text, forbidden) {
|
|
t.Fatalf("search result contains %q: %s", forbidden, text)
|
|
}
|
|
}
|
|
for id, email := range candidateIDs {
|
|
if strings.Contains(text, id.String()) || strings.Contains(text, email) {
|
|
t.Fatalf("search result contains an account identifier or email of %s", email)
|
|
}
|
|
}
|
|
// The candidate whose attempt failed is scored exactly like the others
|
|
// who declared the same profile: no failure and no missing FSP is a penalty.
|
|
var reference *matchEntryBody
|
|
for index, entry := range mustSearch(orgA.ID(), `{"filters":{"specialization":"backend","confirmation_status":"unconfirmed"}}`).Groups.Unconfirmed {
|
|
if index == 0 {
|
|
reference = &entry
|
|
continue
|
|
}
|
|
if entry.component("fit") != reference.component("fit") || entry.component("coverage") != reference.component("coverage") {
|
|
t.Fatalf("an unconfirmed entry is scored differently from its twin: %v vs %v", entry.Components, reference.Components)
|
|
}
|
|
}
|
|
})
|
|
|
|
t.Run("a search is charged like card reads and the candidate sees it in the access history", func(t *testing.T) {
|
|
// Each organization has paid once for each candidate it was shown: the
|
|
// sixteen visible ones, never the candidate who hides it, and the
|
|
// organizations are counted independently.
|
|
if got := revealedBy(orgA.ID()); got != 16 {
|
|
t.Fatalf("organization A paid for %d candidates, want 16", got)
|
|
}
|
|
if got := revealedBy(orgB.ID()); got != 16 {
|
|
t.Fatalf("organization B paid for %d candidates, want 16", got)
|
|
}
|
|
if countRows(`SELECT count(*) FROM company_card_view_quota_usage WHERE organization_id = $1 AND candidate_id = $2`, orgA.ID(), hiddenFromA.id) != 0 ||
|
|
countRows(`SELECT count(*) FROM company_card_view_quota_usage WHERE organization_id = $1 AND candidate_id = $2`, orgB.ID(), hiddenFromB.id) != 0 {
|
|
t.Fatal("an organization paid for a candidate who hides it")
|
|
}
|
|
if countRows(`SELECT count(*) FROM candidate_card_access_events WHERE candidate_id = $1 AND organization_id = $2`, hiddenFromA.id, orgA.ID()) != 0 {
|
|
t.Fatal("a candidate who hides the organization has a card view from it")
|
|
}
|
|
// The history names the fields actually returned: a candidate with a
|
|
// confirmed category shows all five published fields in a full search and
|
|
// a declared profile never shows the ones it did not publish.
|
|
confirmedHistory := historyOf(withGo[3].id, orgA.ID())
|
|
fullFields := []string{"categories", "experience", "self_assessment", "stack", "work_formats"}
|
|
full := false
|
|
for _, fields := range confirmedHistory {
|
|
full = full || slices.Equal(fields, fullFields)
|
|
for _, field := range fields {
|
|
if !slices.Contains(fullFields, field) {
|
|
t.Fatalf("history of a confirmed candidate names %q, which no entry shows", field)
|
|
}
|
|
}
|
|
}
|
|
if len(confirmedHistory) == 0 || !full {
|
|
t.Fatalf("history of a confirmed candidate = %v, want card views including the five fields", confirmedHistory)
|
|
}
|
|
declaredHistory := historyOf(declaredOnly[1].id, orgA.ID())
|
|
if len(declaredHistory) == 0 {
|
|
t.Fatal("a declared candidate has no card view in the history")
|
|
}
|
|
for _, fields := range declaredHistory {
|
|
if !slices.Equal(fields, []string{"self_assessment", "stack", "work_formats"}) {
|
|
t.Fatalf("history of a declared candidate = %v, want only the published declared fields", fields)
|
|
}
|
|
}
|
|
// Repeating the search charges nothing new, and a card read afterwards
|
|
// does not charge a second time.
|
|
before := revealedBy(orgA.ID())
|
|
mustSearch(orgA.ID(), `{"filters":{}}`)
|
|
if revealedBy(orgA.ID()) != before {
|
|
t.Fatal("a repeated search charged the organization again")
|
|
}
|
|
// A search that is refused writes nothing.
|
|
eventsBefore := countRows(`SELECT count(*) FROM candidate_card_access_events`)
|
|
if _, response := search(recruiter, orgA.ID(), `{"filters":{}}`); response.Code != http.StatusForbidden {
|
|
t.Fatalf("recruiter search = %d, want 403", response.Code)
|
|
}
|
|
if countRows(`SELECT count(*) FROM candidate_card_access_events`) != eventsBefore || revealedBy(orgA.ID()) != before {
|
|
t.Fatal("a refused search charged or recorded")
|
|
}
|
|
})
|
|
|
|
t.Run("a profile published without a grade appears last, a confirmed filter excludes it, and a revoked C2 removes it", func(t *testing.T) {
|
|
extra := client.candidate(t, "match-declared-extra@example.test")
|
|
handle := aliasIn(orgA.ID(), extra.id)
|
|
candidateIDs[extra.id] = extra.email
|
|
listed := func() string {
|
|
result := mustSearch(orgA.ID(), `{"filters":{}}`)
|
|
return result.handles()[handle+"/backend"]
|
|
}
|
|
if listed() != "" {
|
|
t.Fatal("an unpublished profile is listed")
|
|
}
|
|
publish(extra, []string{"go"}, backendRole, unconfirmedFields)
|
|
if group := listed(); group != "unconfirmed" {
|
|
t.Fatalf("a profile published without a grade is in group %q, want unconfirmed", group)
|
|
}
|
|
for _, filters := range []string{`{"confirmed_grade":"intern"}`, `{"confirmation_status":"confirmed"}`, `{"confirmed_category":{"specialization":"backend","grade":"junior"}}`} {
|
|
if _, listed := mustSearch(orgA.ID(), fmt.Sprintf(`{"filters":%s}`, filters)).handles()[handle+"/backend"]; listed {
|
|
t.Fatalf("filters %s kept an unconfirmed profile", filters)
|
|
}
|
|
}
|
|
mustCall(extra, http.MethodDelete, "/api/v1/me/consents/c2", "", http.StatusNoContent)
|
|
if group := listed(); group != "" {
|
|
t.Fatalf("a profile whose C2 was revoked is still in group %q", group)
|
|
}
|
|
})
|
|
|
|
t.Run("a card that the cohort rules suppress is not searched, and a listed handle opens as a card", func(t *testing.T) {
|
|
single := client.candidate(t, "match-unique@example.test")
|
|
candidateIDs[single.id] = single.email
|
|
publish(single, []string{"kafka"}, map[string]string{"backend": "senior"}, unconfirmedFields)
|
|
handle := aliasIn(orgA.ID(), single.id)
|
|
general := mustSearch(orgA.ID(), `{"filters":{}}`)
|
|
if _, listed := general.handles()[handle+"/backend"]; listed {
|
|
t.Fatal("a profile alone in its cohort is listed although its card would not open")
|
|
}
|
|
if got := harness.request(t, http.MethodGet, fmt.Sprintf("/api/v1/organizations/%s/candidate-cards/%s", orgA.ID(), handle), "",
|
|
"", employer.cookie, "", client.remote()); got.Code != http.StatusNotFound {
|
|
t.Fatalf("card of the suppressed profile = %d, want 404", got.Code)
|
|
}
|
|
if countRows(`SELECT count(*) FROM company_card_view_quota_usage WHERE organization_id = $1 AND candidate_id = $2`, orgA.ID(), single.id) != 0 ||
|
|
len(historyOf(single.id, orgA.ID())) != 0 {
|
|
t.Fatal("a suppressed profile was charged or recorded")
|
|
}
|
|
opened := general.Groups.Main[0].CandidateHandle
|
|
openedID := candidateOfHandle(orgA.ID())[opened]
|
|
paid, seen := revealedBy(orgA.ID()), len(historyOf(openedID, orgA.ID()))
|
|
if got := harness.request(t, http.MethodGet, fmt.Sprintf("/api/v1/organizations/%s/candidate-cards/%s", orgA.ID(), opened), "",
|
|
"", employer.cookie, "", client.remote()); got.Code != http.StatusOK {
|
|
t.Fatalf("card of a listed handle = %d %s, want 200", got.Code, got.Body.String())
|
|
}
|
|
// The candidate was already paid for by the search, so opening the card
|
|
// charges nothing again, and the card read is one more history entry.
|
|
if revealedBy(orgA.ID()) != paid || len(historyOf(openedID, orgA.ID())) != seen+1 {
|
|
t.Fatalf("after the card read: paid %d (was %d), history %d (was %d), want no new charge and one new entry",
|
|
revealedBy(orgA.ID()), paid, len(historyOf(openedID, orgA.ID())), seen)
|
|
}
|
|
})
|
|
|
|
t.Run("only the active owner of the organization may search, and the body is closed", func(t *testing.T) {
|
|
body := `{"filters":{}}`
|
|
path := searchPath(orgA.ID())
|
|
unauthenticated := harness.request(t, http.MethodPost, path, body, sessionHTTPTestOrigin, "", "", client.remote())
|
|
requireSessionProblem(t, unauthenticated, http.StatusUnauthorized, "unauthenticated")
|
|
if _, response := search(candidateOnly, orgA.ID(), body); response.Code != http.StatusForbidden {
|
|
t.Fatalf("candidate account search = %d, want 403", response.Code)
|
|
}
|
|
if _, response := search(foreign, orgA.ID(), body); response.Code != http.StatusNotFound {
|
|
t.Fatalf("search of an organization without membership = %d, want 404", response.Code)
|
|
}
|
|
if _, response := search(employer, uuid.New(), body); response.Code != http.StatusNotFound {
|
|
t.Fatalf("search of an unknown organization = %d, want 404", response.Code)
|
|
}
|
|
// A recruiter has an active membership, which grants nothing without
|
|
// the owner role in the minimal milestone.
|
|
if _, response := search(recruiter, orgA.ID(), body); response.Code != http.StatusForbidden {
|
|
t.Fatalf("recruiter search = %d, want 403", response.Code)
|
|
}
|
|
noCSRF := harness.request(t, http.MethodPost, path, body, sessionHTTPTestOrigin, employer.cookie, "", client.remote())
|
|
requireSessionProblem(t, noCSRF, http.StatusForbidden, "csrf_check_failed")
|
|
foreignOrigin := harness.request(t, http.MethodPost, path, body, "https://attacker.example", employer.cookie, employer.csrf, client.remote())
|
|
requireSessionProblem(t, foreignOrigin, http.StatusForbidden, "csrf_check_failed")
|
|
for _, invalid := range []string{
|
|
`{"filters":{"unknown":1}}`, `{"filters":{"stack":["go","go"]}}`, `{"filters":{"confirmed_grade":"principal"}}`,
|
|
`{"filters":{"conditions":{"salary_compatibility":"maybe"}}}`, `{"filters":{},"need_id":"` + uuid.NewString() + `"}`, `{}`,
|
|
} {
|
|
if _, response := search(employer, orgA.ID(), invalid); response.Code != http.StatusBadRequest {
|
|
t.Fatalf("search with body %s = %d %s, want 400", invalid, response.Code, response.Body.String())
|
|
}
|
|
}
|
|
_ = foreignOrg
|
|
})
|
|
|
|
t.Run("the batch evidence read equals the single read and honors hiding", func(t *testing.T) {
|
|
categories := []domain.CandidateViewCategory{{Specialization: domain.SpecializationBackend, Grade: domain.GradeIntern, Strength: domain.CandidateViewStrengthStandard}}
|
|
members := []categoryHTTPCandidate{withGo[0], withGo[2], withoutStack[0], declaredOnly[0]}
|
|
requests := make([]outbound.EvidenceCandidateCategories, 0, len(members))
|
|
for _, member := range members {
|
|
requests = append(requests, outbound.EvidenceCandidateCategories{CandidateID: member.id, Categories: categories})
|
|
}
|
|
err := transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
|
batch, err := unit.Evidence().ListOrganizationFactsBatch(ctx, orgA.ID(), requests)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for _, member := range members {
|
|
single, err := unit.Evidence().ListOrganizationFacts(ctx, orgA.ID(), member.id, categories)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if len(batch[member.id]) != len(single) || len(single) > 0 && !reflect.DeepEqual(batch[member.id], single) {
|
|
t.Errorf("batch facts of %s = %v, single = %v", member.email, batch[member.id], single)
|
|
}
|
|
}
|
|
// The candidate who hides organization A and the candidate without a
|
|
// published category have no fact in the batch.
|
|
if len(batch[hiddenFromA.id]) != 0 || len(batch[declaredOnly[0].id]) != 0 || len(batch[withGo[2].id]) != 1 {
|
|
t.Errorf("batch = %v, want one fact for a visible confirmed candidate and none for hidden or declared ones", batch)
|
|
}
|
|
counts, err := unit.Evidence().CountComparableRealCategories(ctx, []outbound.CategoryKey{{Specialization: domain.SpecializationBackend, Grade: domain.GradeIntern}})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if len(counts) != 0 {
|
|
t.Errorf("real cohort counts = %v, want none: every stored category is a synthetic demonstration", counts)
|
|
}
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("read evidence in a batch: %v", err)
|
|
}
|
|
})
|
|
|
|
t.Run("the allowance of an organization ends the output and the group limit cuts it, without a total", func(t *testing.T) {
|
|
// Organizations of one owner share the E0 pool, so this one gets an owner of its own.
|
|
ownerC := client.employer(t, "match-employer-c@example.test")
|
|
orgC := organizations.create(t, domain.User{ID: ownerC.id}, organizations.completeProfile(t, "Match organization C"), now)
|
|
bounded := func(product *domain.ProductPolicy) {
|
|
product.OrganizationQuotas.TierE0.DistinctCardViewsPerWindow = 8
|
|
}
|
|
publishPolicy(bounded)
|
|
searchC := func() (matchSearchBody, string) {
|
|
result, response := search(ownerC, orgC.ID(), `{"filters":{}}`)
|
|
if response.Code != http.StatusOK {
|
|
t.Fatalf("search of organization C = %d %s", response.Code, response.Body.String())
|
|
}
|
|
return result, response.Body.String()
|
|
}
|
|
first, firstBody := searchC()
|
|
returned := len(first.Groups.Main) + len(first.Groups.Near) + len(first.Groups.Unconfirmed)
|
|
if !first.Truncated || len(first.Groups.Main) != 8 || returned != 8 || revealedBy(orgC.ID()) != 8 {
|
|
t.Fatalf("first search = %d main, %d near, %d unconfirmed, truncated %v, paid %d; want eight confirmed entries, the flag, and eight paid",
|
|
len(first.Groups.Main), len(first.Groups.Near), len(first.Groups.Unconfirmed), first.Truncated, revealedBy(orgC.ID()))
|
|
}
|
|
for _, forbidden := range []string{"total", "count", "remaining", "quota"} {
|
|
if strings.Contains(firstBody, forbidden) {
|
|
t.Fatalf("a truncated result exposes %q: %s", forbidden, firstBody)
|
|
}
|
|
}
|
|
assertOrder(t, orgC.ID(), first.Groups.Main, true)
|
|
// The same search again returns the same entries and charges nothing.
|
|
if _, secondBody := searchC(); secondBody != firstBody || revealedBy(orgC.ID()) != 8 {
|
|
t.Fatal("a repeated search of an exhausted organization changed or charged")
|
|
}
|
|
// Each returned candidate has the card view in the history, and opening
|
|
// the card of a returned handle is free, while the ninth candidate's card
|
|
// is refused by the same allowance.
|
|
candidates := candidateOfHandle(orgC.ID())
|
|
for _, entry := range first.Groups.Main {
|
|
if len(historyOf(candidates[entry.CandidateHandle], orgC.ID())) < 2 {
|
|
t.Fatalf("a returned candidate has %d card views from organization C, want one for each search",
|
|
len(historyOf(candidates[entry.CandidateHandle], orgC.ID())))
|
|
}
|
|
}
|
|
cardPath := func(handle string) string {
|
|
return fmt.Sprintf("/api/v1/organizations/%s/candidate-cards/%s", orgC.ID(), handle)
|
|
}
|
|
if got := harness.request(t, http.MethodGet, cardPath(first.Groups.Main[0].CandidateHandle), "", "", ownerC.cookie, "", client.remote()); got.Code != http.StatusOK ||
|
|
revealedBy(orgC.ID()) != 8 {
|
|
t.Fatalf("card of a paid candidate = %d, paid %d, want 200 and no new charge", got.Code, revealedBy(orgC.ID()))
|
|
}
|
|
unpaid := ""
|
|
for _, group := range [][]categoryHTTPCandidate{withGo, withoutStack, declaredOnly} {
|
|
for _, member := range group {
|
|
if countRows(`SELECT count(*) FROM company_card_view_quota_usage WHERE organization_id = $1 AND candidate_id = $2`, orgC.ID(), member.id) == 0 {
|
|
unpaid = aliasIn(orgC.ID(), member.id)
|
|
}
|
|
}
|
|
}
|
|
if got := harness.request(t, http.MethodGet, cardPath(unpaid), "", "", ownerC.cookie, "", client.remote()); got.Code != http.StatusTooManyRequests {
|
|
t.Fatalf("card of an unpaid candidate = %d, want 429 from the same allowance", got.Code)
|
|
}
|
|
// The organizations pay independently of each other.
|
|
if revealedBy(orgA.ID()) < 16 || revealedBy(orgB.ID()) != 16 {
|
|
t.Fatalf("paid by A and B = %d and %d, want the counts of earlier searches untouched", revealedBy(orgA.ID()), revealedBy(orgB.ID()))
|
|
}
|
|
|
|
// The group limit cuts the output of an organization that still has
|
|
// allowance, ranks the whole bank first, and also raises the flag.
|
|
publishPolicy(func(product *domain.ProductPolicy) { product.Matching.MaxResultsPerGroup = 4 })
|
|
paidBefore := revealedBy(orgA.ID())
|
|
cut := mustSearch(orgA.ID(), `{"filters":{}}`)
|
|
if len(cut.Groups.Main) != 4 || len(cut.Groups.Unconfirmed) != 4 || !cut.Truncated {
|
|
t.Fatalf("limited search = %d main, %d unconfirmed, truncated %v, want both groups cut at four and the flag",
|
|
len(cut.Groups.Main), len(cut.Groups.Unconfirmed), cut.Truncated)
|
|
}
|
|
if revealedBy(orgA.ID()) != paidBefore {
|
|
t.Fatal("a limited search charged candidates that were already paid for")
|
|
}
|
|
// The head of the cut group is the head of the full ranking.
|
|
publishPolicy(nil)
|
|
full := mustSearch(orgA.ID(), `{"filters":{}}`)
|
|
if full.Truncated || !slices.Equal(handlesOf(cut.Groups.Main), handlesOf(full.Groups.Main[:4])) ||
|
|
!slices.Equal(handlesOf(cut.Groups.Unconfirmed), handlesOf(full.Groups.Unconfirmed[:4])) {
|
|
t.Fatal("the limited result is not the head of the full ranking")
|
|
}
|
|
})
|
|
|
|
t.Run("the demo group limit is 10, at most 30 reveals for a search, below the daily allowance", func(t *testing.T) {
|
|
demo := domain.DemoMatchingPolicy().MaxResultsPerGroup
|
|
if demo != 10 || 3*demo >= domain.DemoProductPolicyV4().OrganizationQuotas.TierE0.DistinctCardViewsPerWindow {
|
|
t.Fatalf("demo group limit = %d, want 10 and three groups under the E0 allowance", demo)
|
|
}
|
|
publishPolicy(func(product *domain.ProductPolicy) { product.Matching.MaxResultsPerGroup = demo })
|
|
paid := revealedBy(orgA.ID())
|
|
cut := mustSearch(orgA.ID(), `{"filters":{}}`)
|
|
if len(cut.Groups.Main) != 10 || len(cut.Groups.Unconfirmed) != 10 || !cut.Truncated || revealedBy(orgA.ID()) != paid {
|
|
t.Fatalf("demo-limited search = %d main, %d unconfirmed, truncated %v, paid %d (was %d); want both groups at 10 and the flag",
|
|
len(cut.Groups.Main), len(cut.Groups.Unconfirmed), cut.Truncated, revealedBy(orgA.ID()), paid)
|
|
}
|
|
publishPolicy(nil)
|
|
})
|
|
|
|
t.Run("two concurrent searches of one organization never charge beyond the allowance", func(t *testing.T) {
|
|
ownerD := client.employer(t, "match-employer-d@example.test")
|
|
orgD := organizations.create(t, domain.User{ID: ownerD.id}, organizations.completeProfile(t, "Match organization D"), now)
|
|
publishPolicy(func(product *domain.ProductPolicy) { product.OrganizationQuotas.TierE0.DistinctCardViewsPerWindow = 8 })
|
|
type outcome struct {
|
|
status int
|
|
body string
|
|
}
|
|
const parallel = 4
|
|
outcomes := make(chan outcome, parallel)
|
|
remotes := make([]string, parallel)
|
|
for index := range remotes {
|
|
remotes[index] = client.remote()
|
|
}
|
|
var group sync.WaitGroup
|
|
for _, remote := range remotes {
|
|
group.Add(1)
|
|
go func() {
|
|
defer group.Done()
|
|
response := harness.request(t, http.MethodPost, searchPath(orgD.ID()), `{"filters":{}}`, sessionHTTPTestOrigin, ownerD.cookie, ownerD.csrf, remote)
|
|
outcomes <- outcome{status: response.Code, body: response.Body.String()}
|
|
}()
|
|
}
|
|
group.Wait()
|
|
close(outcomes)
|
|
var bodies []string
|
|
for result := range outcomes {
|
|
if result.status != http.StatusOK {
|
|
t.Fatalf("concurrent search = %d %s, want 200; log: %s", result.status, result.body, harness.logs.String())
|
|
}
|
|
bodies = append(bodies, result.body)
|
|
}
|
|
if got := revealedBy(orgD.ID()); got != 8 {
|
|
t.Fatalf("organization D paid for %d candidates under concurrent searches, want exactly 8", got)
|
|
}
|
|
paid := make(map[string]bool)
|
|
for id := range candidateIDs {
|
|
if countRows(`SELECT count(*) FROM company_card_view_quota_usage WHERE organization_id = $1 AND candidate_id = $2`, orgD.ID(), id) == 1 {
|
|
paid[aliasIn(orgD.ID(), id)] = true
|
|
}
|
|
}
|
|
for _, body := range bodies {
|
|
var decoded matchSearchBody
|
|
if err := json.Unmarshal([]byte(body), &decoded); err != nil {
|
|
t.Fatalf("decode concurrent result: %v", err)
|
|
}
|
|
if !decoded.Truncated || len(decoded.Groups.Main) != 8 || len(decoded.Groups.Near)+len(decoded.Groups.Unconfirmed) != 0 {
|
|
t.Fatalf("concurrent result = %d main, truncated %v, want eight paid entries and the flag", len(decoded.Groups.Main), decoded.Truncated)
|
|
}
|
|
for _, handle := range handlesOf(decoded.Groups.Main) {
|
|
if !paid[handle] {
|
|
t.Fatalf("a response holds %s, a candidate the organization did not pay for", handle)
|
|
}
|
|
}
|
|
}
|
|
for _, body := range bodies[1:] {
|
|
if body != bodies[0] {
|
|
t.Fatal("two concurrent searches of one organization answered differently")
|
|
}
|
|
}
|
|
publishPolicy(nil)
|
|
})
|
|
|
|
t.Run("concurrent card reads, evidence reads, and searches of one organization neither deadlock nor overcharge", func(t *testing.T) {
|
|
ownerF := client.employer(t, "match-employer-f@example.test")
|
|
orgF := organizations.create(t, domain.User{ID: ownerF.id}, organizations.completeProfile(t, "Match organization F"), now)
|
|
visible := make([]categoryHTTPCandidate, 0, 17)
|
|
for _, group := range [][]categoryHTTPCandidate{withGo, withoutStack, declaredOnly} {
|
|
visible = append(visible, group...)
|
|
}
|
|
type outcome struct {
|
|
what string
|
|
status int
|
|
}
|
|
run := func(jobs []func() outcome) []outcome {
|
|
results := make(chan outcome, len(jobs))
|
|
var group sync.WaitGroup
|
|
for _, job := range jobs {
|
|
group.Add(1)
|
|
go func() {
|
|
defer group.Done()
|
|
results <- job()
|
|
}()
|
|
}
|
|
group.Wait()
|
|
close(results)
|
|
var all []outcome
|
|
for result := range results {
|
|
all = append(all, result)
|
|
}
|
|
return all
|
|
}
|
|
card := func(member categoryHTTPCandidate, suffix string) func() outcome {
|
|
remote := client.remote()
|
|
path := fmt.Sprintf("/api/v1/organizations/%s/candidate-cards/%s%s", orgF.ID(), aliasIn(orgF.ID(), member.id), suffix)
|
|
return func() outcome {
|
|
response := harness.request(t, http.MethodGet, path, "", "", ownerF.cookie, "", remote)
|
|
return outcome{what: "card" + suffix, status: response.Code}
|
|
}
|
|
}
|
|
searchJob := func() func() outcome {
|
|
remote := client.remote()
|
|
return func() outcome {
|
|
response := harness.request(t, http.MethodPost, searchPath(orgF.ID()), `{"filters":{}}`, sessionHTTPTestOrigin, ownerF.cookie, ownerF.csrf, remote)
|
|
return outcome{what: "search", status: response.Code}
|
|
}
|
|
}
|
|
check := func(results []outcome) {
|
|
t.Helper()
|
|
for _, result := range results {
|
|
if result.status != http.StatusOK {
|
|
t.Fatalf("concurrent %s = %d, want 200; log: %s", result.what, result.status, harness.logs.String())
|
|
}
|
|
}
|
|
if strings.Contains(harness.logs.String(), "40P01") {
|
|
t.Fatal("a concurrent read of one organization hit a deadlock")
|
|
}
|
|
}
|
|
|
|
// Several card reads of one organization at once.
|
|
var jobs []func() outcome
|
|
for _, member := range visible[:6] {
|
|
jobs = append(jobs, card(member, ""))
|
|
}
|
|
check(run(jobs))
|
|
if got := revealedBy(orgF.ID()); got != 6 {
|
|
t.Fatalf("six concurrent card reads charged %d candidates, want 6", got)
|
|
}
|
|
|
|
// A mixed round: searches, card reads, and evidence reads together.
|
|
jobs = []func() outcome{searchJob(), searchJob()}
|
|
for _, member := range visible[3:9] {
|
|
jobs = append(jobs, card(member, ""), card(member, "/evidence"))
|
|
}
|
|
check(run(jobs))
|
|
if got := revealedBy(orgF.ID()); got != len(visible) {
|
|
t.Fatalf("the mixed round charged %d candidates, want %d: one row for each visible candidate and no more", got, len(visible))
|
|
}
|
|
if countRows(`SELECT count(*) FROM (SELECT candidate_id FROM company_card_view_quota_usage WHERE organization_id = $1
|
|
GROUP BY candidate_id HAVING count(*) > 1) AS repeated`, orgF.ID()) != 0 {
|
|
t.Fatal("a candidate was charged twice")
|
|
}
|
|
})
|
|
|
|
t.Run("the skill taxonomy is part of the policy version", func(t *testing.T) {
|
|
request := needRequest(needID, needRequirementsV1, "")
|
|
withTaxonomy := mustSearch(orgA.ID(), request)
|
|
publishPolicy(func(product *domain.ProductPolicy) { product.Matching.SkillTaxonomy = nil })
|
|
without := mustSearch(orgA.ID(), request)
|
|
if len(withTaxonomy.Groups.Near) != 5 || len(without.Groups.Near) != 5 {
|
|
t.Fatalf("near = %d and %d, want the five candidates without the tag in both", len(withTaxonomy.Groups.Near), len(without.Groups.Near))
|
|
}
|
|
assertScores(t, "near with the taxonomy", withTaxonomy.Groups.Near, map[string]float64{"coverage": 0.24})
|
|
assertScores(t, "near without the taxonomy", without.Groups.Near, map[string]float64{"coverage": 0})
|
|
assertScores(t, "main without the taxonomy", without.Groups.Main, map[string]float64{"coverage": 0.25})
|
|
publishPolicy(nil)
|
|
})
|
|
|
|
t.Run("a policy without the matching section fails closed", func(t *testing.T) {
|
|
publisher := policy.NewPublisher(postgresadapter.NewPolicyStore(harness.pool).Policies(), time.Now)
|
|
if _, err := publisher.Publish(ctx, policy.PublishInput{
|
|
Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, Author: policyTestAuthor, Policy: domain.DemoProductPolicyV3(),
|
|
}); err != nil {
|
|
t.Fatalf("Publish(policy without matching) error = %v", err)
|
|
}
|
|
clockOffset += time.Minute
|
|
harness.clock.Set(time.Now().UTC().Add(clockOffset).Truncate(time.Microsecond))
|
|
if _, response := search(employer, orgA.ID(), `{"filters":{}}`); response.Code != http.StatusInternalServerError {
|
|
t.Fatalf("search under a policy without matching = %d %s, want 500 and no ranking from defaults", response.Code, response.Body.String())
|
|
}
|
|
})
|
|
}
|