diff --git a/backend/integration_test/assessment_attempt_http_test.go b/backend/integration_test/assessment_attempt_http_test.go index 6fa21ed..25229e6 100644 --- a/backend/integration_test/assessment_attempt_http_test.go +++ b/backend/integration_test/assessment_attempt_http_test.go @@ -1095,3 +1095,132 @@ func waitForAttemptIdleDeadline(t *testing.T, ctx context.Context, pool *pgxpool } t.Fatal("assessment attempt idle deadline did not pass during the row lock") } + +// TestDemoExpressActiveAttemptOverHTTP covers an express run the candidate +// leaves unfinished. The availability read has no express field by contract, +// so the candidate keeps the identifier from the 201 response or replays the +// Idempotency-Key of that creation. A new start is refused while the run is +// active and succeeds once the run's own deadline has passed. +func TestDemoExpressActiveAttemptOverHTTP(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), assessmentAttemptHTTPTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + applyMigrations(ctx, t, databaseURL) + isolatedEnv := *env + isolatedEnv.Config.DatabaseURL = databaseURL + harness := newAssessmentAttemptHTTPHarness(ctx, t, &isolatedEnv) + seedAssessmentAttemptHTTPBank(ctx, t, harness.pool) + + passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass) + if err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + candidate := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "express-resume@example.test", passwordHash, true) + cookie, csrf := loginConsentHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address(), "192.0.2.201:1234") + body := `{"kind":"demo_express"}` + + first := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", body, + sessionHTTPTestOrigin, cookie.Value, csrf, "express-first", "192.0.2.202:1234") + if first.Code != http.StatusCreated { + t.Fatalf("create express = %d %s", first.Code, first.Body.String()) + } + firstID := assessmentAttemptIDOf(t, first) + + // Another key is refused while the first run is active, and creates nothing. + second := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", body, + sessionHTTPTestOrigin, cookie.Value, csrf, "express-second", "192.0.2.203:1234") + requireSessionProblem(t, second, http.StatusConflict, "state_conflict") + assertAttemptCount(t, ctx, harness.pool, 1) + + // The creation key replays the stored 201, which returns the identifier of + // the active run. + replay := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", body, + sessionHTTPTestOrigin, cookie.Value, csrf, "express-first", "192.0.2.204:1234") + assertAssessmentAttemptReplay(t, "express-first while active", first, replay) + + active := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, "/api/v1/me/assessment-attempts/"+firstID.String(), "", + "", cookie.Value, "", "", "192.0.2.205:1234") + if state := assessmentAttemptStateOf(t, active); active.Code != http.StatusOK || state != "in_progress" { + t.Fatalf("read active express = %d state %q, want 200 in_progress", active.Code, state) + } + + // The run ends at its own deadline. The fixture moves the run's clock fields + // back instead of waiting for the policy duration, and the next start commits + // the due transition. + ageDemoExpressAttempt(t, ctx, harness.pool, firstID, 10*time.Minute) + third := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", body, + sessionHTTPTestOrigin, cookie.Value, csrf, "express-third", "192.0.2.206:1234") + if third.Code != http.StatusCreated { + t.Fatalf("create express after the deadline = %d %s", third.Code, third.Body.String()) + } + assertAttemptCount(t, ctx, harness.pool, 2) + + ended := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, "/api/v1/me/assessment-attempts/"+firstID.String(), "", + "", cookie.Value, "", "", "192.0.2.207:1234") + if state := assessmentAttemptStateOf(t, ended); ended.Code != http.StatusOK || state != "expired" { + t.Fatalf("read the first express after its deadline = %d state %q, want 200 expired", ended.Code, state) + } + result := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, "/api/v1/me/assessment-attempts/"+firstID.String()+"/result", "", + "", cookie.Value, "", "", "192.0.2.208:1234") + var summary struct { + Outcome string `json:"outcome"` + Summary string `json:"summary"` + } + if err := json.Unmarshal(result.Body.Bytes(), &summary); err != nil || result.Code != http.StatusOK || + summary.Outcome != "demonstration" || summary.Summary != "Тренировочный запуск завершился до окончания: он не оценивает и не подтверждает уровень." { + t.Fatalf("result of the expired express = %d %s, decode error %v", result.Code, result.Body.String(), err) + } +} + +// assessmentAttemptIDOf reads the identifier of an attempt response. +func assessmentAttemptIDOf(t *testing.T, response *httptest.ResponseRecorder) uuid.UUID { + t.Helper() + var snapshot struct { + ID uuid.UUID `json:"id"` + } + if err := json.Unmarshal(response.Body.Bytes(), &snapshot); err != nil || snapshot.ID == uuid.Nil { + t.Fatalf("attempt response %d %s has no identifier: %v", response.Code, response.Body.String(), err) + } + return snapshot.ID +} + +// assessmentAttemptStateOf reads the state of an attempt response. +func assessmentAttemptStateOf(t *testing.T, response *httptest.ResponseRecorder) string { + t.Helper() + var snapshot struct { + State string `json:"state"` + } + if err := json.Unmarshal(response.Body.Bytes(), &snapshot); err != nil { + t.Fatalf("decode attempt response %d %s: %v", response.Code, response.Body.String(), err) + } + return snapshot.State +} + +// ageDemoExpressAttempt moves an attempt and its clock fields back by by, with +// the triggers off for this one transaction, so that its deadline has passed. +// The shift keeps every ordering constraint because all fields move together. +func ageDemoExpressAttempt(t *testing.T, ctx context.Context, pool *pgxpool.Pool, attemptID uuid.UUID, by time.Duration) { + t.Helper() + tx, err := pool.Begin(ctx) + if err != nil { + t.Fatalf("begin express aging fixture: %v", err) + } + defer func() { _ = tx.Rollback(ctx) }() + if _, err := tx.Exec(ctx, `SET LOCAL session_replication_role = replica`); err != nil { + t.Fatalf("disable triggers for the express aging fixture: %v", err) + } + shift := fmt.Sprintf("%d seconds", int64(by.Seconds())) + command, err := tx.Exec(ctx, ` + UPDATE assessment_attempts + SET created_at = created_at - $2::interval, updated_at = updated_at - $2::interval, + expires_at = expires_at - $2::interval, session_started_at = session_started_at - $2::interval, + last_activity_at = last_activity_at - $2::interval + WHERE id = $1 AND kind = 'demo_express'`, attemptID, shift) + if err != nil || command.RowsAffected() != 1 { + t.Fatalf("age express attempt = %d rows, error %v", command.RowsAffected(), err) + } + if err := tx.Commit(ctx); err != nil { + t.Fatalf("commit express aging fixture: %v", err) + } +} diff --git a/backend/integration_test/demo_seed_test.go b/backend/integration_test/demo_seed_test.go index 30c4912..87636f5 100644 --- a/backend/integration_test/demo_seed_test.go +++ b/backend/integration_test/demo_seed_test.go @@ -224,13 +224,14 @@ func TestDemoSeedCommand(t *testing.T) { } second, err := stand.run(t, nil, "seed", "--actor", "operator:another-operator") - if err != nil || !strings.Contains(second, "created 0 records") { - t.Fatalf("second seed = %q, %v, want nothing created", second, err) + if err != nil || !strings.Contains(second, "created 0 records") || strings.Contains(second, "updated:") { + t.Fatalf("second seed = %q, %v, want nothing created or updated", second, err) } if afterSecond := stand.inventory(t); afterSecond != afterFirst { t.Fatalf("inventory changed on the repeat:\nfirst:\n%s\nsecond:\n%s", afterFirst, afterSecond) } + assertDemoSeedOnboarding(t, stand) assertDemoSeedMarkers(t, stand) assertDemoSeedPermissions(t, stand) assertDemoSeedVisibleCohort(t, stand) @@ -252,6 +253,79 @@ func TestDemoSeedCommand(t *testing.T) { t.Fatal("the visitor account changed") } }) + + t.Run("repairs the onboarding step of a stand seeded before the step was set", func(t *testing.T) { + stand := newDemoSeedStand(ctx, t, env) + first, err := stand.run(t, nil, "seed", "--actor", demoSeedActor) + if err != nil { + t.Fatalf("first seed error = %v (output %q)", err, first) + } + afterFirst := stand.inventory(t) + // An earlier seed left every candidate at the consent step. One prepared + // candidate has moved on to a later step, which a repair must keep. + if _, err := stand.pool.Exec(stand.ctx, ` + UPDATE users SET onboarding_step = 'candidate_consents' + WHERE scenario = 'candidate' AND email_normalized LIKE '%@' || $1`, seedusecase.SyntheticDomain); err != nil { + t.Fatalf("set the consent step on every candidate: %v", err) + } + if _, err := stand.pool.Exec(stand.ctx, `UPDATE users SET onboarding_step = 'completed' WHERE email_normalized = $1`, + demoEmail("prepared-1")); err != nil { + t.Fatalf("move one candidate past the assessment: %v", err) + } + + repaired, err := stand.run(t, nil, "seed", "--actor", demoSeedActor) + if err != nil || !strings.Contains(repaired, "created 0 records") || strings.Count(repaired, "updated: onboarding of ") != 6 { + t.Fatalf("repairing seed = %q, %v, want six updated steps and no created record", repaired, err) + } + if step := stand.onboardingStep(t, demoEmail("prepared-1")); step != "completed" { + t.Fatalf("a later step of prepared-1 = %q, want completed kept", step) + } + if at := stand.count(t, `SELECT count(*) FROM users WHERE scenario = 'candidate' + AND email_normalized LIKE '%@' || $1 AND onboarding_step = 'candidate_assessment'`, seedusecase.SyntheticDomain); at != 6 { + t.Fatalf("candidates repaired to the assessment step = %d, want six", at) + } + if afterRepair := stand.inventory(t); afterRepair != afterFirst { + t.Fatalf("inventory changed by the repair:\nfirst:\n%s\nrepaired:\n%s", afterFirst, afterRepair) + } + + again, err := stand.run(t, nil, "seed", "--actor", demoSeedActor) + if err != nil || !strings.Contains(again, "created 0 records") || strings.Contains(again, "updated:") { + t.Fatalf("seed after the repair = %q, %v, want nothing created or updated", again, err) + } + }) +} + +// onboardingStep reads the saved onboarding step of one account. +func (stand demoSeedStand) onboardingStep(t *testing.T, email string) string { + t.Helper() + var step string + if err := stand.pool.QueryRow(stand.ctx, `SELECT onboarding_step FROM users WHERE email_normalized = $1`, email).Scan(&step); err != nil { + t.Fatalf("read onboarding step of %s: %v", email, err) + } + return step +} + +// assertDemoSeedOnboarding checks that every synthetic candidate, the +// self-service one and the prepared ones alike, stands at the step that a +// saved questionnaire leaves, and that the employers are unchanged. +func assertDemoSeedOnboarding(t *testing.T, stand demoSeedStand) { + t.Helper() + const candidates = 7 + if total := stand.count(t, `SELECT count(*) FROM users WHERE scenario = 'candidate' AND email_normalized LIKE '%@' || $1`, + seedusecase.SyntheticDomain); total != candidates { + t.Fatalf("synthetic candidates = %d, want %d", total, candidates) + } + if at := stand.count(t, `SELECT count(*) FROM users WHERE scenario = 'candidate' + AND email_normalized LIKE '%@' || $1 AND onboarding_step = 'candidate_assessment'`, seedusecase.SyntheticDomain); at != candidates { + t.Errorf("candidates at the assessment step = %d, want %d", at, candidates) + } + if step := stand.onboardingStep(t, demoEmail("candidate")); step != "candidate_assessment" { + t.Errorf("the self-service candidate step = %q, want candidate_assessment", step) + } + if employers := stand.count(t, `SELECT count(*) FROM users WHERE scenario = 'employer' AND onboarding_step = 'employer_company' + AND email_normalized LIKE '%@' || $1`, seedusecase.SyntheticDomain); employers != 2 { + t.Errorf("synthetic employers at employer_company = %d, want 2", employers) + } } // assertDemoSeedMarkers checks that every organization and profile of the seed @@ -429,6 +503,10 @@ func assertExpressAssignsNoCategory(t *testing.T, stand demoSeedStand) { if outcome := stand.count(t, `SELECT count(*) FROM assessment_attempts WHERE id = $1 AND outcome = 'demonstration'`, express.ID().UUID()); outcome != 1 { t.Fatalf("express outcome rows = %d, want one demonstration outcome", outcome) } + result, err := attempts.GetMyResult(stand.ctx, candidateID, express.ID()) + if err != nil || result.Summary != "Это тренировочный запуск: он не оценивает и не подтверждает уровень." { + t.Fatalf("express result summary = %q, %v, want the Russian training text", result.Summary, err) + } if facts := stand.count(t, `SELECT count(*) FROM skill_evidence_facts`); facts != factsBefore { t.Fatalf("evidence facts after the express = %d, want %d", facts, factsBefore) } diff --git a/backend/internal/adapter/primary/cli/demoseed/command.go b/backend/internal/adapter/primary/cli/demoseed/command.go index 02517f9..8bef964 100644 --- a/backend/internal/adapter/primary/cli/demoseed/command.go +++ b/backend/internal/adapter/primary/cli/demoseed/command.go @@ -234,6 +234,9 @@ func ExecuteSeed(ctx context.Context, seeder Seeder, input seedusecase.Input, ou for _, item := range report.Created { fmt.Fprintf(&text, "created: %s\n", item) } + for _, item := range report.Updated { + fmt.Fprintf(&text, "updated: %s\n", item) + } for _, login := range report.Logins { fmt.Fprintf(&text, "login: %s (%s)\n", login.Email, login.Role) } diff --git a/backend/internal/adapter/secondary/postgres/demo_seed.go b/backend/internal/adapter/secondary/postgres/demo_seed.go index 37ede9a..703224c 100644 --- a/backend/internal/adapter/secondary/postgres/demo_seed.go +++ b/backend/internal/adapter/secondary/postgres/demo_seed.go @@ -6,6 +6,7 @@ import ( "encoding/json" "errors" "fmt" + "time" "github.com/google/uuid" "github.com/jackc/pgx/v5" @@ -204,6 +205,33 @@ func insertTrainingBinding(ctx context.Context, tx pgx.Tx, binding outbound.Demo return nil } +// AdvanceCandidateOnboarding moves a verified candidate with a saved +// questionnaire from an earlier candidate step to candidate_assessment. The +// statement is the questionnaire transition of the product repository, +// widened to the earlier steps, and it touches no later step. It bumps the +// account version as the product transitions do. +func (store *DemoSeedStore) AdvanceCandidateOnboarding(ctx context.Context, userID uuid.UUID, at time.Time) (bool, error) { + const location = "DemoSeedStore.AdvanceCandidateOnboarding" + result, err := store.pool.Exec(ctx, ` + UPDATE users + SET + onboarding_step = 'candidate_assessment', + version = users.version + 1, + updated_at = GREATEST(users.updated_at, $2::timestamptz) + WHERE users.id = $1 + AND users.scenario = 'candidate' + AND users.email_verified_at IS NOT NULL + AND users.onboarding_step IN ('candidate_consents', 'candidate_profile', 'candidate_questionnaire') + AND EXISTS ( + SELECT 1 FROM candidate_questionnaires AS questionnaire + WHERE questionnaire.user_id = users.id + )`, userID, at) + if err != nil { + return false, fmt.Errorf("%s - advance onboarding: %w", location, sanitizeConnectError(err)) + } + return result.RowsAffected() == 1, nil +} + // Inventory counts the records of synthetic accounts and of the seed's bank // categories in one read-only statement. func (store *DemoSeedStore) Inventory( diff --git a/backend/internal/port/outbound/demo_seed.go b/backend/internal/port/outbound/demo_seed.go index a0e122e..f0c4d5d 100644 --- a/backend/internal/port/outbound/demo_seed.go +++ b/backend/internal/port/outbound/demo_seed.go @@ -3,6 +3,7 @@ package outbound import ( "context" "errors" + "time" "github.com/google/uuid" @@ -89,6 +90,15 @@ type DemoSeedStore interface { // count differs from ItemCount. BindTrainingBank(ctx context.Context, binding DemoTrainingBinding) error + // AdvanceCandidateOnboarding sets the saved onboarding step of a verified + // candidate to candidate_assessment, the step that a saved questionnaire + // leaves, when the step is still an earlier candidate step and the + // questionnaire is saved. No product transition moves the consent step, + // and the profile and questionnaire transitions apply only from their own + // step, so a stand whose rows were saved earlier needs this statement. It + // never moves a later step back, and it reports whether it changed the step. + AdvanceCandidateOnboarding(ctx context.Context, userID uuid.UUID, at time.Time) (bool, error) + // Inventory counts the seed's records on the stand. Inventory(ctx context.Context, syntheticDomain string, categories []string) (DemoInventory, error) } diff --git a/backend/internal/usecase/assessment/finalize.go b/backend/internal/usecase/assessment/finalize.go index 9a43fc3..d6c0963 100644 --- a/backend/internal/usecase/assessment/finalize.go +++ b/backend/internal/usecase/assessment/finalize.go @@ -311,9 +311,18 @@ func (service *AttemptService) persistFinalizedAttempt( return nil } +// expressResultSummary is the user-facing text of a finished express run. The +// product UI is in Russian, and the text is stored in the immutable result, so +// a run finished before this text changed keeps the text it was stored with. +const expressResultSummary = "Это тренировочный запуск: он не оценивает и не подтверждает уровень." + +// expressEndedSummary is the text of an express run that expired or was left +// unfinished. Like expressResultSummary, it is stored in the immutable result. +const expressEndedSummary = "Тренировочный запуск завершился до окончания: он не оценивает и не подтверждает уровень." + func assessmentFinalizedResultPresentation(kind domain.AssessmentAttemptKind) (string, []string) { if kind == domain.AssessmentAttemptKindDemoExpress { - return "This training run is educational only. It does not assess or confirm a grade.", []string{"demonstration_only"} + return expressResultSummary, []string{"demonstration_only"} } return "", []string{"uncalibrated_thresholds", "demo_bank", "practice_not_included", "unproctored"} } @@ -411,7 +420,7 @@ func terminalAttemptResult(attempt domain.AssessmentAttempt) (AssessmentAttemptR switch snapshot.Kind { case domain.AssessmentAttemptKindDemoExpress: result.Outcome = domain.AssessmentAttemptOutcomeDemonstration - result.Summary = "This training run ended before completion. It does not assess or confirm a grade." + result.Summary = expressEndedSummary case domain.AssessmentAttemptKindRoot, domain.AssessmentAttemptKindCorrective: result.Limitations = []string{"uncalibrated_thresholds", "demo_bank", "practice_not_included", "unproctored"} result.Outcome = domain.AssessmentAttemptOutcomeNotDetermined diff --git a/backend/internal/usecase/demoseed/seeder.go b/backend/internal/usecase/demoseed/seeder.go index bb95ae9..871bcb6 100644 --- a/backend/internal/usecase/demoseed/seeder.go +++ b/backend/internal/usecase/demoseed/seeder.go @@ -84,11 +84,13 @@ type Input struct { Password domain.Password } -// Report lists what one run created and what it found. It holds addresses -// of synthetic accounts and identifiers only. +// Report lists what one run created, what it changed in an existing record, +// and what it found. It holds addresses of synthetic accounts and identifiers +// only. type Report struct { PolicyVersion int32 Created []string + Updated []string Present []string Logins []Login PreparedAttempts []PreparedAttempt @@ -114,6 +116,13 @@ func (report *Report) record(created bool, item string) { report.Present = append(report.Present, item) } +// update notes a change to a record that already existed. It is kept apart +// from the created records, so a repeated run that repairs a stand reports no +// new record. +func (report *Report) update(item string) { + report.Updated = append(report.Updated, item) +} + // Seed builds the demo world or finds it complete. func (seeder *Seeder) Seed(ctx context.Context, input Input) (Report, error) { const location = "Seeder.Seed" @@ -565,8 +574,9 @@ func (seeder *Seeder) ensureMembership(ctx context.Context, organizationID, user } // ensureCandidate gives a candidate its consents, manual profile, and -// questionnaire; a prepared candidate also gets the prepared full attempt and -// a published card. It returns the prepared attempt, or a zero ID. +// questionnaire, then sets the onboarding step that the questionnaire leaves; +// a prepared candidate also gets the prepared full attempt and a published +// card. It returns the prepared attempt, or a zero ID. func (seeder *Seeder) ensureCandidate( ctx context.Context, spec accountSpec, @@ -593,6 +603,9 @@ func (seeder *Seeder) ensureCandidate( return domain.AssessmentAttemptID{}, fmt.Errorf("%s - %w", location, err) } report.record(created, "questionnaire of "+spec.email()) + if err := seeder.ensureOnboarding(ctx, user.ID, spec.email(), report); err != nil { + return domain.AssessmentAttemptID{}, fmt.Errorf("%s - %w", location, err) + } if spec.role != rolePrepared { return domain.AssessmentAttemptID{}, nil } @@ -609,6 +622,20 @@ func (seeder *Seeder) ensureCandidate( return attemptID, nil } +// ensureOnboarding leaves the candidate at candidate_assessment, the step that +// a saved questionnaire leaves in the ordinary flow. A stand that already has +// the step, or a later one, is unchanged, so a repeat reports no update. +func (seeder *Seeder) ensureOnboarding(ctx context.Context, userID uuid.UUID, email string, report *Report) error { + changed, err := seeder.deps.Store.AdvanceCandidateOnboarding(ctx, userID, seeder.now()) + if err != nil { + return fmt.Errorf("advance onboarding of %s: %w", email, err) + } + if changed { + report.update("onboarding of " + email + " at candidate_assessment") + } + return nil +} + // grantConsent grants the current text of the purpose; a repeat of the same // version is idempotent in the ledger. func (seeder *Seeder) grantConsent(ctx context.Context, subjectID uuid.UUID, purpose domain.ConsentPurpose) error { diff --git a/docs/en/TESTING.md b/docs/en/TESTING.md index 88471dd..2b0f569 100644 --- a/docs/en/TESTING.md +++ b/docs/en/TESTING.md @@ -538,9 +538,10 @@ What these tests do not show: a real invitation event through Kafka and the rela - Without the isolated mode, also against an unreachable database, every subcommand refuses, and nothing is written. - A database with an ordinary account and no seed is refused by both the seed and the reset check; the account and the policy stay as they were. - The first seed creates nine confirmed synthetic accounts, two organizations, three memberships (the owner of Alpha is a recruiter of Beta), six prepared attempts with results, current synthetic categories, evidence, and published cards, the seed policy version, 28 published families, one opening, one attestation, and one training binding. A second seed by another operator creates nothing and prints the same inventory. +- Every synthetic candidate stands at the onboarding step `candidate_assessment`, which a saved questionnaire leaves, and both employers stand at `employer_company`. A stand whose candidates were left at the consent step is repaired by one more run: it prints an `updated` line for each candidate on an earlier step, keeps a candidate on a later step, creates nothing, and keeps the inventory the same. - Every organization, profile name, and prepared profile carries its synthetic or prepared marker, and every category is an uncalibrated `synthetic_demo` category. - The owner of Alpha sees exactly the six prepared cards through the card listing that the search uses, and not the unpublished self-service candidate. -- A perfect express run of the self-service candidate through the attempt operations draws three items from the training category, ends as `demonstration`, and adds no category and no evidence; the same candidate can then start the full test. +- A perfect express run of the self-service candidate through the attempt operations draws three items from the training category, ends as `demonstration` with the Russian training summary, and adds no category and no evidence; the same candidate can then start the full test. - After an ordinary account registers on the seeded database, the reset check refuses and counts it, a repeated seed still creates nothing, and the account is unchanged. `make -C deploy check-demo` (part of `make -C deploy check`) runs `deploy/scripts/demo.sh` against a recording stub of the docker CLI: every action refuses without `DEMO_MODE=isolated`, with a project name that equals `APP_PROJECT` or lacks `demo`, with an invalid actor, or without the env file, before any Docker command; a project volume without the demo label is refused before any Compose command; a refused reset check stops the reset before `down`; a reset addresses only the demo project and seeds again; `down` keeps the volumes; a release manifest that cannot be restored stops `seed` and `reset` before any Compose command, and `down` ignores it. With the docker CLI it also renders the overlay: only the frontend is published, on loopback; the seed container has only the default network, a read-only root, and the explicit profile; every volume carries the demo label; the demo backend enables synthetic categories; the release overlay names the seed image `lincodex.invalid/demo-seed:` with `pull_policy: never`; and the backend images do not contain the command. diff --git a/docs/ru/TESTING.md b/docs/ru/TESTING.md index c1098c4..184253d 100644 --- a/docs/ru/TESTING.md +++ b/docs/ru/TESTING.md @@ -538,9 +538,10 @@ Unit-тесты (`make -C backend test`) проверяют правила жу - Без изолированного режима, в том числе против недоступной базы, каждая подкоманда отказывает и ничего не записывает. - База с обычным аккаунтом и без seed отклоняется и seed, и проверкой сброса; аккаунт и политика остаются прежними. - Первый seed создает девять подтвержденных синтетических аккаунтов, две организации, три членства (владелец «Альфы» - рекрутер «Беты»), шесть подготовленных попыток с результатами, текущими синтетическими категориями, доказательствами и опубликованными карточками, версию политики seed, 28 опубликованных семейств, одно открытие, одну аттестацию и одну учебную привязку. Повторный seed от другого оператора ничего не создает и печатает тот же перечень. +- Каждый синтетический кандидат находится на шаге онбординга `candidate_assessment`, который оставляет сохраненная анкета, а оба работодателя - на `employer_company`. Стенд, на котором кандидаты остались на шаге согласий, исправляется еще одним запуском: он печатает строку `updated` для каждого кандидата на более раннем шаге, сохраняет кандидата на более позднем шаге, ничего не создает и оставляет перечень прежним. - Каждая организация, имя профиля и подготовленный профиль содержат пометку о синтетических данных или о подготовке, а каждая категория - неоткалиброванная категория `synthetic_demo`. - Владелец «Альфы» видит ровно шесть подготовленных карточек через тот же список карточек, что использует поиск, и не видит неопубликованного кандидата для самостоятельного прохождения. -- Безошибочное экспресс-прохождение этого кандидата через операции попытки берет три задания из учебной категории, завершается результатом `demonstration` и не добавляет ни категории, ни доказательства; после этого тот же кандидат может начать полный тест. +- Безошибочное экспресс-прохождение этого кандидата через операции попытки берет три задания из учебной категории, завершается результатом `demonstration` с русским текстом итога учебного запуска и не добавляет ни категории, ни доказательства; после этого тот же кандидат может начать полный тест. - После регистрации обычного аккаунта в заполненной базе проверка сброса отказывает и учитывает его, повторный seed по-прежнему ничего не создает, а аккаунт не меняется. `make -C deploy check-demo` (часть `make -C deploy check`) запускает `deploy/scripts/demo.sh` с записывающей заглушкой docker CLI: каждое действие отказывает без `DEMO_MODE=isolated`, с именем проекта, равным `APP_PROJECT` или без `demo`, с неверным исполнителем или без env-файла, до любой команды Docker; том проекта без демонстрационной метки отклоняется до любой команды Compose; отказ проверки сброса останавливает сброс до `down`; сброс обращается только к демонстрационному проекту и заново заполняет его; `down` сохраняет тома; манифест выпуска, который нельзя восстановить, останавливает `seed` и `reset` до любой команды Compose, а `down` его не использует. При наличии docker CLI тест также рендерит overlay: опубликован только frontend и только на loopback; у контейнера seed только сеть default, корень только для чтения и явный профиль; у каждого тома есть демонстрационная метка; демонстрационный backend включает синтетические категории; release-overlay называет образ seed `lincodex.invalid/demo-seed:` с `pull_policy: never`; backend-образы команду не содержат.