feat(frontend): keep focus, field errors and unsent answers on the minimal path

This commit is contained in:
shira committed 2026-10-09 21:32:55 +03:00
1 parent d4903a3796
commit c94434cd09
12 files changed
+1174 -18

No files matched your search

+20 -1
View File
@@ -71,7 +71,7 @@ Playwright receives `E2E_MAIL_FIXTURE=1`, `E2E_MAILBOX_URL=http://mail-fixture:8
The current suite (`frontend/e2e/smoke.spec.ts`) checks that the SPA serves `/` with `lang="ru"` and its heading, that `/status` shows the technical page with a live API, that `/api/v1/healthz` returns 200 `{"status":"ok"}` through the frontend proxy, that an unknown SPA route shows the not-found page, and that `/api/v1/missing` returns 404 `application/problem+json` with code `not_found`. It needs no data. Business tests use synthetic data in each fresh stack: registration through the public API and the separately documented test fixture for consent scopes. No real data are used.
The ordinary technical suite does not cover candidate or employer workflows, sign-in, mail delivery, dependency failures (deployment smoke covers those), browsers other than desktop Chromium, layout, or accessibility. CI runs the suite in the `e2e` job after `backend`, `frontend`, and `infrastructure` pass: `make -C frontend install`, then `make -C deploy test-e2e`. The job needs no repository secrets or root `.env`; each run uses its own generated env file and fresh stand. On failure CI uploads the `e2e-diagnostics-attempt-<n>` artifact with `report/`, `results/` (traces and screenshots), and `stand.log` for 14 days. Hidden files and the env file are not uploaded. The `e2e` result is part of the required aggregate.
The ordinary technical suite does not cover candidate or employer workflows, sign-in, mail delivery, dependency failures (deployment smoke covers those), browsers other than desktop Chromium, or screen readers. Its stubbed checks of the minimal path states, focus, and overflow are described in [Minimal path states and accessibility](#minimal-path-states-and-accessibility). CI runs the suite in the `e2e` job after `backend`, `frontend`, and `infrastructure` pass: `make -C frontend install`, then `make -C deploy test-e2e`. The job needs no repository secrets or root `.env`; each run uses its own generated env file and fresh stand. On failure CI uploads the `e2e-diagnostics-attempt-<n>` artifact with `report/`, `results/` (traces and screenshots), and `stand.log` for 14 days. Hidden files and the env file are not uploaded. The `e2e` result is part of the required aggregate.
The registration-mode suite additionally runs `frontend/e2e/auth-registration.spec.ts`: candidate and employer registration with visible C1, real local resend and a distinct received message, same-tab replacement of the verification link, wrong-password retry, confirmation without automatic login, sign-in, and restoring the server step after reload. It checks keyboard focus and overflow at 360, 768, and 1280 pixels. Expired-link rendering uses a controlled problem response; actual token expiry is covered by backend integration tests. Only this isolated overlay sets `VERIFICATION_MAIL_MIN_INTERVAL=1s`; normal and release environments retain their configured interval. Auth traces, failure screenshots, and video are disabled; explicit review screenshots show only token-free states and synthetic addresses. No external mail or production edge flow is verified.
@@ -85,6 +85,25 @@ The same command also seeds a second synthetic candidate for `frontend/e2e/priva
`frontend/e2e/company-management.spec.ts` creates a company, retries a lost response with the same key and body, edits the profile, and compares its preview with the API. Controlled responses check CSRF recovery, version conflict, and a delayed response. A separate `company-fixture` performs real revocation: Go build tag `e2e`, an explicit enable flag, a random bearer token per run, no published port, and only the internal network. It validates two synthetic verified employer accounts, adds a successor owner, and revokes the original owner in one transaction while preserving the mandatory-owner constraint. The browser with its original cookie checks real API denial and removal from its directory. The control endpoint is absent from the ordinary backend and release image; its URL and token reach only the test process through `E2E_COMPANY_FIXTURE_URL` and `E2E_COMPANY_FIXTURE_TOKEN`.
## Minimal path states and accessibility
`frontend/e2e/minimal-path-a11y.spec.ts` checks the states, the keyboard path, and the error binding of the sign-in, the candidate test start and profile, the candidate inbox, and the candidate invitation screen. Failures come from route interception, so no data is needed on the stand: HTTP 500 and 403 answers, a dropped connection, and the empty and forbidden answers. Each stubbed screen is checked at 360, 768, and 1280 px for horizontal overflow; the real-backend assessment check covers 360 and 768 px. Each control reached with Tab must match `:focus-visible` and draw a focus outline. The stubbed part runs in both `make -C deploy test-e2e` and `make -C deploy test-e2e-registration`. The one real-backend test runs only in the registration mode, because it needs the mail and questionnaire fixtures.
The other screens of the minimal path are covered by their existing specs: the employer candidate search and match list (`match-search.spec.ts`: a failed search with a retry, a refused search, an empty result, confirmed and declared grades as text, keyboard reach at every width), the invitation compose (`invitation-compose.spec.ts`: errors bound to fields, a lost send response retried with the same key, overflow at 360, 768, and 1280 px), registration and confirmation (`auth-registration.spec.ts`), and the profile and questionnaire (`profile-edit.spec.ts`, `questionnaire.spec.ts`).
Checklist for the minimal path. Each item is checked by the spec named in brackets; the result is the outcome of the last run of that spec.
- Sign-in [`minimal-path-a11y.spec.ts`]: Tab reaches both fields and the submit control with a visible outline at 360, 768, and 1280 px. An empty submit marks both fields `aria-invalid` and gives each one its message through `aria-describedby`. A failed answer keeps the typed email and keeps the focus in the form. While the answer is pending, the password field stays focused and read-only; it is not disabled, because a disabled field drops the focus.
- Candidate profile [`minimal-path-a11y.spec.ts`]: a loading text while the profile loads, an alert with a retry after a failed load, and no retry after an access refusal.
- Candidate test start [`minimal-path-a11y.spec.ts`]: an alert with a retry after a failed availability read; a candidate without a specialization sees the empty state with a link to the questionnaire.
- Candidate inbox [`minimal-path-a11y.spec.ts`]: a loading text; a server error or a dropped connection gives an alert with a retry that works from the keyboard; the empty state; no retry after an access refusal; each card names the company, the role, and the state as text.
- Candidate invitation [`minimal-path-a11y.spec.ts`]: an alert with a retry after a failed load; a failed decline keeps the chosen reason and the comment and moves the focus to the alert; the declined state is shown as text.
- Assessment on a phone with the real backend [`minimal-path-a11y.spec.ts`, registration mode]: an unsent numeric answer survives a reload at 360 px, and the stored copy is removed when the answer is accepted.
- Employer match list and invitation compose: see the specs named above; the compose page is also checked at 768 px.
- Not covered by these checks: screen reader output, the contrast of the focus outline, and zoom above 200 percent. They were not checked by hand in this pass.
An unsent answer is kept in `sessionStorage` of the same browser tab, under a key that names the attempt and the item. It is never sent to the server. A reload restores it only when it fits the item; a stored value larger than 64 KiB is not kept; a blocked or full store leaves the answer in the form only. An accepted answer removes the stored copy. Answers accepted by the server come from the server after a reload.
## Release manifest tests
`make -C deploy check-release` runs `deploy/scripts/test_release_manifest.py` with the Python standard library and without Docker. It fails when go.mod, the `GO_IMAGE` default, and `GOTOOLCHAIN=local` in backend/Dockerfile or backend/Dockerfile.demo-seed stop pinning Go 1.26.8, or when a service Dockerfile uses a base image that is not a pinnable `*_IMAGE` build argument, including an external image in `COPY --from` or `RUN --mount=from`. On fake image, Compose, and container data it checks that:
+20 -1
View File
@@ -71,7 +71,7 @@ Playwright получает `E2E_MAIL_FIXTURE=1`, `E2E_MAILBOX_URL=http://mail-f
Текущий набор (`frontend/e2e/smoke.spec.ts`) проверяет, что SPA отдает `/` с `lang="ru"` и заголовком, что `/status` показывает техническую страницу с живым API, что `/api/v1/healthz` через прокси frontend возвращает 200 `{"status":"ok"}`, что неизвестный маршрут SPA показывает страницу "не найдено" и что `/api/v1/missing` возвращает 404 `application/problem+json` с кодом `not_found`. Данные ему не нужны. Бизнес-тесты используют синтетические данные в свежем стеке каждого прогона: регистрацию через публичный API и отдельно описанный тестовый fixture для scope согласий. Реальные данные не используются.
Обычный технический набор не проверяет сценарии кандидата и работодателя, вход, доставку почты, отказы зависимостей (их проверяет deployment smoke), браузеры кроме desktop Chromium, верстку и доступность. CI запускает набор в job `e2e` после успешных `backend`, `frontend` и `infrastructure`: `make -C frontend install`, затем `make -C deploy test-e2e`. Секреты репозитория и корневой `.env` не нужны; каждый прогон использует свой сгенерированный env-файл и свежий стенд. При ошибке CI загружает артефакт `e2e-diagnostics-attempt-<n>` с `report/`, `results/` (трассы и снимки экрана) и `stand.log` на 14 дней. Скрытые файлы и env-файл не загружаются. Результат `e2e` входит в обязательный aggregate.
Обычный технический набор не проверяет сценарии кандидата и работодателя, вход, доставку почты, отказы зависимостей (их проверяет deployment smoke), браузеры кроме desktop Chromium и программы чтения с экрана. Его проверки заглушками основного пути (состояния, фокус и переполнение) описаны в разделе [Состояния и доступность основного пути](#состояния-и-доступность-основного-пути). CI запускает набор в job `e2e` после успешных `backend`, `frontend` и `infrastructure`: `make -C frontend install`, затем `make -C deploy test-e2e`. Секреты репозитория и корневой `.env` не нужны; каждый прогон использует свой сгенерированный env-файл и свежий стенд. При ошибке CI загружает артефакт `e2e-diagnostics-attempt-<n>` с `report/`, `results/` (трассы и снимки экрана) и `stand.log` на 14 дней. Скрытые файлы и env-файл не загружаются. Результат `e2e` входит в обязательный aggregate.
Режим регистрации дополнительно запускает `frontend/e2e/auth-registration.spec.ts`: регистрацию кандидата и работодателя с видимым C1, реальную локальную повторную отправку с получением нового письма, замену ссылки подтверждения в той же вкладке, повтор после неверного пароля, подтверждение без автоматического входа, вход и восстановление серверного шага после обновления. Проверяются фокус клавиатуры и отсутствие переполнения на 360, 768 и 1280 px. Отображение просроченной ссылки использует управляемый problem-ответ; реальное истечение токена проверяют backend integration tests. Только изолированный overlay задает `VERIFICATION_MAIL_MIN_INTERVAL=1s`; обычная среда и выпуск сохраняют свой настроенный интервал. Для auth-тестов отключены трассы, снимки при ошибках и видео; явные снимки для проверки показывают состояния без токенов и синтетические адреса. Внешняя почта и рабочий edge-путь не проверялись.
@@ -85,6 +85,25 @@ Playwright получает `E2E_MAIL_FIXTURE=1`, `E2E_MAILBOX_URL=http://mail-f
`frontend/e2e/company-management.spec.ts` создает компанию, повторяет запрос после потери ответа с тем же ключом и телом, изменяет профиль и сравнивает предпросмотр с API. Управляемые ответы проверяют восстановление после CSRF-ошибки, конфликт версии и задержанный ответ. Реальный отзыв выполняет отдельный `company-fixture`: Go build tag `e2e`, явный флаг, случайный bearer token на каждый прогон, без опубликованного порта и только во внутренней сети. Утилита проверяет два синтетических подтвержденных employer-аккаунта, добавляет владельца-преемника и отзывает исходного владельца в одной транзакции, сохраняя ограничение обязательного владельца. Браузер с прежней cookie проверяет отказ реального API и исчезновение компании из своей директории. Контрольный endpoint отсутствует в обычном backend и release-образе; его URL и токен передаются только тестовому процессу через `E2E_COMPANY_FIXTURE_URL` и `E2E_COMPANY_FIXTURE_TOKEN`.
## Состояния и доступность основного пути
`frontend/e2e/minimal-path-a11y.spec.ts` проверяет состояния, путь с клавиатуры и привязку ошибок на экранах входа, начала проверки знаний, профиля кандидата, входящих приглашений и отдельного приглашения кандидата. Отказы создаются перехватом запросов, поэтому на стенде не нужны данные: ответы HTTP 500 и 403, обрыв соединения, пустые и запрещенные ответы. Каждый экран с заглушками проверяется при 360, 768 и 1280 px на горизонтальное переполнение; проверка с настоящим backend покрывает 360 и 768 px. Каждый элемент, до которого доходит Tab, должен соответствовать `:focus-visible` и рисовать контур фокуса. Часть с перехватом запускается и в `make -C deploy test-e2e`, и в `make -C deploy test-e2e-registration`. Один тест с настоящим backend запускается только в режиме регистрации, потому что ему нужны почтовый и анкетный fixture.
Остальные экраны основного пути покрыты существующими спецификациями: поиск кандидатов и список совпадений работодателя (`match-search.spec.ts`: неуспешный поиск с повтором, отказ в поиске, пустой результат, подтвержденный и заявленный грейд текстом, достижение элементов с клавиатуры при каждой ширине), составление приглашения (`invitation-compose.spec.ts`: ошибки, привязанные к полям, потерянный ответ на отправку с повтором под тем же ключом, переполнение при 360, 768 и 1280 px), регистрация и подтверждение (`auth-registration.spec.ts`), профиль и анкета (`profile-edit.spec.ts`, `questionnaire.spec.ts`).
Чек-лист основного пути. Каждый пункт проверяет спецификация, указанная в скобках; результат - итог последнего прогона этой спецификации.
- Вход [`minimal-path-a11y.spec.ts`]: Tab доходит до обоих полей и кнопки отправки с видимым контуром при 360, 768 и 1280 px. Пустая отправка помечает оба поля `aria-invalid` и связывает каждое поле с его текстом через `aria-describedby`. Неуспешный ответ сохраняет введенную почту и оставляет фокус в форме. Пока ответ ожидается, поле пароля остается в фокусе и только для чтения; оно не отключается, потому что отключенное поле теряет фокус.
- Профиль кандидата [`minimal-path-a11y.spec.ts`]: текст загрузки, пока профиль загружается; сообщение с кнопкой повтора после неуспешной загрузки; без повтора после отказа в доступе.
- Начало пробной проверки кандидата [`minimal-path-a11y.spec.ts`]: сообщение с кнопкой повтора после неуспешного чтения доступности; кандидат без специализации видит пустое состояние со ссылкой на анкету.
- Входящие приглашения кандидата [`minimal-path-a11y.spec.ts`]: текст загрузки; ошибка сервера или обрыв соединения дают сообщение с кнопкой повтора, которая работает с клавиатуры; пустое состояние; без повтора после отказа в доступе; каждая карточка называет компанию, роль и состояние текстом.
- Приглашение кандидата [`minimal-path-a11y.spec.ts`]: сообщение с кнопкой повтора после неуспешной загрузки; неуспешный отказ сохраняет выбранную причину и комментарий и переводит фокус на сообщение; состояние "отклонено" показано текстом.
- Проверка на телефоне с настоящим backend [`minimal-path-a11y.spec.ts`, режим регистрации]: неотправленный числовой ответ переживает перезагрузку при 360 px, а сохраненная копия удаляется, когда ответ принят.
- Список совпадений работодателя и составление приглашения: см. спецификации выше; страница составления дополнительно проверяется при 768 px.
- Эти проверки не покрывают: вывод для программ чтения с экрана, контраст контура фокуса и масштаб выше 200 процентов. В этом проходе они вручную не проверялись.
Неотправленный ответ хранится в `sessionStorage` той же вкладки браузера под ключом, который называет попытку и задание. На сервер он не отправляется. Перезагрузка восстанавливает его, только если значение подходит заданию; сохраненное значение больше 64 KiB не сохраняется; заблокированное или переполненное хранилище оставляет ответ только в форме. Принятый ответ удаляет сохраненную копию. Ответы, принятые сервером, после перезагрузки берутся с сервера.
## Тесты манифеста выпуска
`make -C deploy check-release` запускает `deploy/scripts/test_release_manifest.py` на стандартной библиотеке Python и без Docker. Тест падает, если go.mod, значение `GO_IMAGE` по умолчанию и `GOTOOLCHAIN=local` в backend/Dockerfile или backend/Dockerfile.demo-seed перестают закреплять Go 1.26.8 или если Dockerfile сервиса использует базовый образ не через закрепляемый build-аргумент `*_IMAGE`, в том числе внешний образ в `COPY --from` или `RUN --mount=from`. На подставных данных образов, Compose и контейнеров он проверяет, что: