test(e2e): cover the minimal MVP path end to end on the real backend
This commit is contained in:
1 parent
89932b8714
commit
9909120286
11 files changed
+1084
-5
No files matched your search
@@ -16,6 +16,7 @@ RUN CGO_ENABLED=0 GOOS=linux go build -tags=e2e -buildvcs=false -trimpath -ldfla
|
||||
RUN CGO_ENABLED=0 GOOS=linux go build -tags=e2e -buildvcs=false -trimpath -ldflags="-s -w" -o /out/consent-fixture ./cmd/consent-fixture
|
||||
RUN CGO_ENABLED=0 GOOS=linux go build -tags=e2e -buildvcs=false -trimpath -ldflags="-s -w" -o /out/company-fixture ./cmd/company-fixture
|
||||
RUN CGO_ENABLED=0 GOOS=linux go build -tags=e2e -buildvcs=false -trimpath -ldflags="-s -w" -o /out/questionnaire-fixture ./cmd/questionnaire-fixture
|
||||
RUN CGO_ENABLED=0 GOOS=linux go build -buildvcs=false -trimpath -ldflags="-s -w" -o /out/assessment-category-attest ./cmd/assessment-category-attest
|
||||
|
||||
FROM ${RUNTIME_IMAGE}
|
||||
|
||||
@@ -27,6 +28,7 @@ COPY --from=build /out/app /app
|
||||
COPY --from=build /out/consent-fixture /consent-fixture
|
||||
COPY --from=build /out/company-fixture /company-fixture
|
||||
COPY --from=build /out/questionnaire-fixture /questionnaire-fixture
|
||||
COPY --from=build /out/assessment-category-attest /assessment-category-attest
|
||||
EXPOSE 8080 9090
|
||||
USER nonroot:nonroot
|
||||
ENTRYPOINT ["/app"]
|
||||
@@ -18,6 +18,10 @@ services:
|
||||
# The browser suite delivers the synthetic inbox event through the real
|
||||
# pipeline; the production default is off.
|
||||
NOTIFICATION_SYNTHETIC_ENABLED: "true"
|
||||
# The fixture bank is synthetic, so a passed full test may receive the
|
||||
# uncalibrated demonstration category after the runner attests the
|
||||
# opening. Ordinary and release E2E keep the default false.
|
||||
ASSESSMENT_DEMO_CATEGORIES_ENABLED: "true"
|
||||
depends_on:
|
||||
mail-fixture:
|
||||
condition: service_healthy
|
||||
@@ -31,6 +35,7 @@ services:
|
||||
E2E_MAIL_FIXTURE: "1"
|
||||
E2E_COMPANY_FIXTURE: "1"
|
||||
E2E_QUESTIONNAIRE_FIXTURE: "1"
|
||||
E2E_DEMO_CATEGORIES: "1"
|
||||
E2E_CONSENT_FIXTURE: "1"
|
||||
E2E_COMPANY_FIXTURE_URL: http://company-fixture:8081/company/memberships/revoke
|
||||
E2E_COMPANY_FIXTURE_TOKEN: ${E2E_COMPANY_FIXTURE_TOKEN:?Set the per-run company fixture token}
|
||||
|
||||
@@ -266,6 +266,12 @@ try {
|
||||
compose exec -T backend /consent-fixture
|
||||
# Publish an explicitly reviewed synthetic bank for the questionnaire flow.
|
||||
compose exec -T -e E2E_QUESTIONNAIRE_FIXTURE=1 backend /questionnaire-fixture
|
||||
# Attest that opening as a synthetic demonstration source, so a passed full
|
||||
# test of this stand receives the uncalibrated category. The backend of
|
||||
# this overlay alone enables the runtime gate.
|
||||
compose exec -T backend /assessment-category-attest attest \
|
||||
--specialization backend --grade junior --task-language go \
|
||||
--actor operator:e2e-category-attestor
|
||||
fi
|
||||
|
||||
playwright_command=(node node_modules/@playwright/test/cli.js test)
|
||||
|
||||
@@ -117,6 +117,8 @@ class ComposeMailFixtureTest(unittest.TestCase):
|
||||
self.assertNotIn(name, rendered["services"]["playwright"].get("environment", {}))
|
||||
self.assertNotIn("E2E_QUESTIONNAIRE_FIXTURE", backend["environment"])
|
||||
self.assertNotIn("E2E_QUESTIONNAIRE_FIXTURE", rendered["services"]["playwright"].get("environment", {}))
|
||||
self.assertEqual(backend["environment"]["ASSESSMENT_DEMO_CATEGORIES_ENABLED"], "false")
|
||||
self.assertNotIn("E2E_DEMO_CATEGORIES", rendered["services"]["playwright"].get("environment", {}))
|
||||
|
||||
def test_fixture_uses_an_e2e_build_and_fixed_synthetic_credentials(self):
|
||||
services = self.fixture["services"]
|
||||
@@ -138,6 +140,8 @@ class ComposeMailFixtureTest(unittest.TestCase):
|
||||
self.assertEqual(services["playwright"]["environment"]["E2E_QUESTIONNAIRE_FIXTURE"], "1")
|
||||
self.assertNotIn("E2E_QUESTIONNAIRE_FIXTURE", backend["environment"])
|
||||
self.assertNotIn("questionnaire-fixture", (ROOT / "backend" / "Dockerfile").read_text())
|
||||
self.assertEqual(backend["environment"]["ASSESSMENT_DEMO_CATEGORIES_ENABLED"], "true")
|
||||
self.assertEqual(services["playwright"]["environment"]["E2E_DEMO_CATEGORIES"], "1")
|
||||
self.assertNotIn("E2E_MAIL_FIXTURE", services["frontend"].get("environment", {}))
|
||||
|
||||
def test_fixture_has_no_host_port_storage_network_or_outbound_route(self):
|
||||
|
||||
+2
-2
@@ -82,7 +82,7 @@ The full inventory and the seed rules are in [Isolated demo stand](#isolated-dem
|
||||
2. On the same page start the Backend Junior full test with Go: 25 items, a 72-hour deadline, two work sessions, no practice. After it completes, the result is compared with the pass mark of the demo policy; a passed test receives an uncalibrated synthetic category, a failed one the result `not_confirmed`. The result and the history open at `/candidate/results`.
|
||||
3. Prepared candidate: sign in as `prepared-1@demo.lincodex.test` and open the results, the skill evidence, and the privacy settings with the published card.
|
||||
4. Employer: sign in as `employer-alpha@demo.lincodex.test`, select "Alpha", create a need, and open the search (`/employer/candidates`). The main group holds the six prepared cards with the flags `ml_unavailable` and `cohort_below_30`; a card and its evidence open from the results. In "Beta" the same account is a recruiter, and search answers 403: in the minimal release only the owner can search.
|
||||
5. Invitations: the company creates an invitation with the "Invite" button of a search result, sends it, and keeps the address of the invitation page: it holds `invitation_id`. The prepared candidate accepts the invitation at `/candidate/invitations`, choosing the contacts and the consent C4, and the company reads the disclosed contacts on the same invitation page. The company's invitation list is still a placeholder, so keep the page address.
|
||||
5. Invitations: the company creates an invitation with the "Invite" button of the first card of the main group, fills in the tasks and the team description (the need does not fill them), sends it, and keeps the address of the invitation page: it holds `invitation_id`. Equal cards keep a fixed order, and the first one belongs to `prepared-1@demo.lincodex.test`. This candidate accepts the invitation at `/candidate/invitations`, choosing the contacts and the consent C4, and the company reads the disclosed contacts on the same invitation page. The company's invitation list is still a placeholder, so keep the page address.
|
||||
|
||||
The eight-minute step-by-step guide with links to the screens and the logins is on the stand at `/demo`; the start page has the button "Open the jury guide". The guide exists only in the demonstration stand build.
|
||||
|
||||
@@ -90,7 +90,7 @@ The eight-minute step-by-step guide with links to the screens and the logins is
|
||||
|
||||
- FSP: there is no integration in any mode. This build has no off or mock switch, no fixture provider, and no call to an external API. The profile is filled in manually, linking an FSP ID is optional and not available yet, and the path to a category goes through the questionnaire and the test. The project has no official access to FSP data and does not promise it; an FSP link through a fixture provider is planned (see [ARCHITECTURE.md](ARCHITECTURE.md#identity-fsp-and-privacy)).
|
||||
- ML: the core and demo stands do not start ML and do not call it. Search uses the neutral semantic similarity 0.5 and marks it with the `ml_unavailable` flag. `make -C deploy ml-up` starts a separate service without a model: `/healthz` answers 200 and `/readyz` 503. The core needs no GPU or external inference key and reads none.
|
||||
- Data: the demo stand holds synthetic data only. Addresses on the reserved domain `@demo.lincodex.test` never receive mail, names are marked as synthetic, categories have the source `synthetic_demo` and are uncalibrated, and the item families are synthetic and had no subject review. Do not register real people on this stand. Only the demo overlay enables synthetic categories (`ASSESSMENT_DEMO_CATEGORIES_ENABLED=true`); `.env.example` sets `false`.
|
||||
- Data: the demo stand holds synthetic data only. Addresses on the reserved domain `@demo.lincodex.test` never receive mail, names are marked as synthetic, categories have the source `synthetic_demo` and are uncalibrated, and the item families are synthetic and had no subject review. Do not register real people on this stand. Synthetic categories are enabled (`ASSESSMENT_DEMO_CATEGORIES_ENABLED=true`) only by the demo overlay and by the overlay of the isolated registration browser suite (see [TESTING.md](TESTING.md#minimal-path-from-registration-to-disclosed-contacts)); `.env.example` sets `false`.
|
||||
|
||||
### 6. Checks
|
||||
|
||||
|
||||
@@ -457,6 +457,23 @@ The isolated mail overlay sets `IDENTITY_CLIENT_HOURLY_LIMIT=200` because all br
|
||||
|
||||
`assessment.spec.ts` uses the same isolated fixture. It saves both languages and explicitly selects Python, then completes the full attempt with keyboard navigation at 360px and waits for finalization and the server result. It separately exercises express training with the resumption of an unfinished run after a reload (409 to a new start, then 201 for the stored key), offline answer submission, replay after a malformed success response, reload, and resuming saved progress. Explicit screenshots cover 360px and 1280px. These synthetic checks validate the application flow, not assessment calibration.
|
||||
|
||||
## Minimal path from registration to disclosed contacts
|
||||
|
||||
In the registration mode the overlay `docker-compose.e2e-mail.yml` sets `ASSESSMENT_DEMO_CATEGORIES_ENABLED=true` on the test backend and gives Playwright `E2E_DEMO_CATEGORIES=1`. After `questionnaire-fixture`, the runner attests the opened Backend Junior category with the operator command `/assessment-category-attest` from the test backend image, so a passed full test of this stand receives the uncalibrated `synthetic_demo` category, as on the demo stand. The ordinary and release suites keep the default `false`, and `make -C deploy check-e2e-mail` checks both settings.
|
||||
|
||||
`frontend/e2e/acceptance-path.spec.ts` walks the minimal path on the real backend without an FSP ID. Five candidates register with the link from the received message, fill the profile and the questionnaire, grant C3, solve every item of the full test from its statement, and publish an identical card after an explicit C2, because a card is shown only in a group of five. The spec then checks:
|
||||
|
||||
- the result `confirmed` with the category decision `assigned`, `demo_basic_pass_mark`, `synthetic_demo`; a reload in the middle of the attempt returns the same attempt without a second answer, and the result history keeps one entry after a reload and a step back and forward in the browser history;
|
||||
- a need, the search by its requirements version with the five confirmed entries and the explanation from the server, a filter by the declared grade senior that removes all five cards and keeps only cards of other specs with that grade, and the unchanged result of the first requirements version after the need is edited;
|
||||
- three invitations bound to the first requirements version, delivered once each; no search result, invitation list, or organization notification holds an email, a phone, or a name;
|
||||
- an acceptance in the browser with the email only, after which a reload and a history step add no record, there is one C4 record for the organization, and the organization reads only the email;
|
||||
- two concurrent acceptances of one invitation with different keys: both answer 200 with the same body, one C4 record and one grant;
|
||||
- a decline without access and the refusal 409 `state_conflict` of a new invitation for the same pair;
|
||||
- a second company that gets 404 or a field error, never data, for the need, the search by that need, the cards, the invitations, and the contacts of the first one;
|
||||
- C2 revocation that closes the contact read and the cards of the earlier result at once (the four remaining cards fall below the group of five and are suppressed too), and a new C2 and publication that reopen the cards but not the grant of the accepted invitation.
|
||||
|
||||
The spec does not check the planned transitions without an operation (withdrawal, cancellation by the candidate, the counter offer, the interview, the closed final), the 20-invitation limit per need and the expiry (backend integration tests cover them), category recommendations for a need, which stay `pending`, or a PDF. Traces and screenshots are off; the data are synthetic.
|
||||
|
||||
## Candidate visibility tests
|
||||
|
||||
Unit tests (`make -C backend test`) check the visibility rules without a database:
|
||||
|
||||
+2
-2
@@ -82,7 +82,7 @@ Docker Engine с Compose plugin, GNU make, python3 (цели `deploy` запус
|
||||
2. Там же начните полный тест Backend Junior с Go: 25 заданий, срок 72 часа, две рабочие сессии, без практики. После завершения результат сравнивается с порогом демонстрационной политики; пройденный тест получает неоткалиброванную синтетическую категорию, непройденный - результат `not_confirmed`. Результат и история открываются в `/candidate/results`.
|
||||
3. Подготовленный кандидат: войдите как `prepared-1@demo.lincodex.test` и откройте результаты, доказательства навыка и настройки приватности с опубликованной карточкой.
|
||||
4. Работодатель: войдите как `employer-alpha@demo.lincodex.test`, выберите "Альфу", создайте потребность и откройте подбор (`/employer/candidates`). Основная группа содержит шесть подготовленных карточек с отметками `ml_unavailable` и `cohort_below_30`; карточка и ее доказательства открываются из выдачи. В "Бете" тот же аккаунт - рекрутер, и поиск отвечает 403: в минимальном выпуске искать может только владелец.
|
||||
5. Приглашения: компания создает приглашение кнопкой "Пригласить" в результате поиска, отправляет его и сохраняет адрес страницы: в нем `invitation_id`. Подготовленный кандидат принимает приглашение в `/candidate/invitations`, выбрав контакты и согласие C4, а компания читает переданные контакты на той же странице приглашения. Список приглашений компании пока заготовка, поэтому адрес страницы нужен.
|
||||
5. Приглашения: компания создает приглашение кнопкой "Пригласить" у первой карточки основной группы, вписывает задачи и описание команды (потребность их не заполняет), отправляет его и сохраняет адрес страницы: в нем `invitation_id`. Одинаковые карточки идут в постоянном порядке, и первая принадлежит `prepared-1@demo.lincodex.test`. Этот кандидат принимает приглашение в `/candidate/invitations`, выбрав контакты и согласие C4, а компания читает переданные контакты на той же странице приглашения. Список приглашений компании пока заготовка, поэтому адрес страницы нужен.
|
||||
|
||||
Пошаговый гид на восемь минут со ссылками на экраны и логинами открыт на стенде по адресу `/demo`; на главной есть кнопка "Открыть гид для жюри". Гид есть только в сборке демонстрационного стенда.
|
||||
|
||||
@@ -90,7 +90,7 @@ Docker Engine с Compose plugin, GNU make, python3 (цели `deploy` запус
|
||||
|
||||
- ФСП: интеграции нет ни в каком режиме. В этой сборке нет переключателя off или mock, fixture-провайдера и обращений к внешнему API. Профиль заполняется вручную, привязка ФСП ID необязательна и пока недоступна, а путь до категории проходит через анкету и тест. Проект не имеет официального доступа к данным ФСП и не обещает его; связь с ФСП через fixture-провайдер запланирована (см. [ARCHITECTURE.md](ARCHITECTURE.md#идентификация-фсп-и-приватность)).
|
||||
- ML: основной и демонстрационный стенды не запускают ML и не обращаются к нему. Поиск подставляет нейтральную смысловую близость 0.5 и отмечает это флагом `ml_unavailable`. `make -C deploy ml-up` запускает отдельный сервис без модели: `/healthz` отвечает 200, `/readyz` - 503. GPU и ключи внешнего inference ядру не нужны и не читаются.
|
||||
- Данные: демонстрационный стенд содержит только синтетические данные. Адреса на зарезервированном домене `@demo.lincodex.test` никогда не получают почту, названия помечены как синтетические, категории имеют источник `synthetic_demo` и не откалиброваны, а семейства заданий синтетические и не прошли предметную проверку. Не регистрируйте на этом стенде реальных людей. Синтетические категории включает только демонстрационный overlay (`ASSESSMENT_DEMO_CATEGORIES_ENABLED=true`); в `.env.example` значение `false`.
|
||||
- Данные: демонстрационный стенд содержит только синтетические данные. Адреса на зарезервированном домене `@demo.lincodex.test` никогда не получают почту, названия помечены как синтетические, категории имеют источник `synthetic_demo` и не откалиброваны, а семейства заданий синтетические и не прошли предметную проверку. Не регистрируйте на этом стенде реальных людей. Синтетические категории (`ASSESSMENT_DEMO_CATEGORIES_ENABLED=true`) включают только демонстрационный overlay и overlay изолированного браузерного набора регистрации (см. [TESTING.md](TESTING.md#минимальный-путь-от-регистрации-до-раскрытых-контактов)); в `.env.example` значение `false`.
|
||||
|
||||
### 6. Проверки
|
||||
|
||||
|
||||
@@ -457,6 +457,23 @@ Unit-тесты (`make -C backend test`) проверяют правила жу
|
||||
|
||||
`assessment.spec.ts` использует тот же изолированный fixture. Он сохраняет оба языка и явно выбирает Python, затем проходит полную попытку клавиатурой на 360 px и ожидает завершения и результата от сервера. Отдельно проверяются express-режим с продолжением незавершенного запуска после перезагрузки (409 на новое начало, затем 201 по сохраненному ключу), отправка ответа без сети, повтор после некорректного успешного ответа, обновление страницы и продолжение сохраненной попытки. Явные снимки покрывают 360 и 1280 px. Синтетические проверки подтверждают работу приложения, но не калибровку оценки.
|
||||
|
||||
## Минимальный путь от регистрации до раскрытых контактов
|
||||
|
||||
В режиме регистрации overlay `docker-compose.e2e-mail.yml` выставляет тестовому backend `ASSESSMENT_DEMO_CATEGORIES_ENABLED=true` и передает Playwright `E2E_DEMO_CATEGORIES=1`. После `questionnaire-fixture` runner аттестует открытую категорию Backend Junior операторской командой `/assessment-category-attest` из тестового backend-образа, поэтому пройденный полный тест на этом стенде получает некалиброванную категорию `synthetic_demo`, как на демонстрационном стенде. Обычный и релизный наборы сохраняют значение по умолчанию `false`, а `make -C deploy check-e2e-mail` проверяет обе настройки.
|
||||
|
||||
`frontend/e2e/acceptance-path.spec.ts` проходит минимальный путь на настоящем backend без ФСП ID. Пять кандидатов регистрируются по ссылке из полученного письма, заполняют профиль и анкету, дают C3, решают каждое задание полного теста по его условию и после явного C2 публикуют одинаковую карточку, потому что карточка показывается только в группе из пяти. Затем spec проверяет:
|
||||
|
||||
- результат `confirmed` с решением о категории `assigned`, `demo_basic_pass_mark`, `synthetic_demo`; перезагрузка посреди попытки возвращает ту же попытку без второго ответа, а история результатов хранит одну запись после перезагрузки и шага назад и вперед по истории браузера;
|
||||
- потребность, поиск по ее версии требований с пятью подтвержденными записями и объяснением от сервера, фильтр по заявленному грейду senior, который убирает все пять карточек и оставляет только чужие карточки с этим грейдом, и неизменный результат первой версии требований после правки потребности;
|
||||
- три приглашения, привязанные к первой версии требований и доставленные по одному разу; ни результат поиска, ни список приглашений, ни уведомления организации не содержат email, телефон или имя;
|
||||
- принятие в браузере только с email, после которого перезагрузка и шаг по истории не добавляют записей, для организации есть одна запись C4, а организация читает только email;
|
||||
- два одновременных принятия одного приглашения с разными ключами: оба отвечают 200 с одинаковым телом, одна запись C4 и один grant;
|
||||
- отказ без доступа и отказ 409 `state_conflict` в новом приглашении для той же пары;
|
||||
- вторую компанию, которая получает 404 или ошибку поля, но не данные, для потребности, поиска по этой потребности, карточек, приглашений и контактов первой;
|
||||
- отзыв C2, который сразу закрывает чтение контактов и карточки прежнего результата (оставшиеся четыре карточки оказываются меньше группы из пяти и тоже скрываются), и новые C2 и публикацию, которые открывают карточки, но не grant принятого приглашения.
|
||||
|
||||
Spec не проверяет запланированные переходы без операции (отзыв приглашения компанией, отмену участия кандидатом, встречное предложение, интервью, закрытый финал), лимит 20 приглашений на потребность и истечение срока (их покрывают интеграционные тесты backend), рекомендации категорий для потребности, которые остаются `pending`, и PDF. Трассировка и снимки выключены, данные синтетические.
|
||||
|
||||
## Тесты видимости кандидата
|
||||
|
||||
Модульные тесты (`make -C backend test`) проверяют правила видимости без базы:
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -75,7 +75,7 @@ export const guideRoles: readonly GuideRole[] = [
|
||||
link: { label: "Открыть подбор", to: paths.employer.candidates },
|
||||
},
|
||||
{
|
||||
text: "Нажмите «Пригласить» у одного из подготовленных кандидатов. Большая часть условий уже заполнена из потребности; выберите тип предложения и канал связи, отметьте хотя бы один формат работы и для каждого условия пакета укажите «Предусмотрено» с описанием. Затем нажмите «Отправить приглашение» и сохраните адрес страницы: в нем invitation_id, по нему открывается приглашение после ответа кандидата.",
|
||||
text: "Нажмите «Пригласить» у первой карточки основной группы: одинаковые карточки идут в постоянном порядке, и первая принадлежит prepared-1, который ответит на приглашение. Название роли, специализация, грейд, технологии и вилка уже заполнены из потребности. Впишите «Задачи» (по одной в строке) и «Команда» (размер и роли, без имен), выберите тип предложения и канал связи, отметьте хотя бы один формат работы и для каждого условия пакета укажите «Предусмотрено» с описанием. Затем нажмите «Отправить приглашение» и сохраните адрес страницы: в нем invitation_id, по нему открывается приглашение после ответа кандидата.",
|
||||
link: null,
|
||||
},
|
||||
],
|
||||
|
||||
@@ -84,6 +84,20 @@ describe("jury guide page", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("sends the invitation to the candidate who answers it and names the fields a need leaves empty", () => {
|
||||
const steps = guideRoles.flatMap((role) => role.steps.map((step) => step.text));
|
||||
const invite = steps.find((text) => text.includes("«Пригласить»")) ?? "";
|
||||
|
||||
// The need of the route has no tasks, and a need never carries a team, so
|
||||
// the invitation form refuses to leave its first step until both are set.
|
||||
expect(invite).toContain("«Задачи»");
|
||||
expect(invite).toContain("«Команда»");
|
||||
// Equal cards keep a fixed order, and the first one belongs to prepared-1,
|
||||
// the account that answers the invitation in the next block.
|
||||
expect(invite).toContain("первой карточки");
|
||||
expect(invite).toContain("prepared-1");
|
||||
});
|
||||
|
||||
it("states the limits: mail may be off and real people must not register", () => {
|
||||
const html = render();
|
||||
|
||||
|
||||
Reference in new issue
Block a user