test(e2e): run Playwright against an isolated Compose stand
This commit is contained in:
1 parent
7a5105acc7
commit
4cd7d060bd
23 files changed
+431
-41
No files matched your search
@@ -56,7 +56,7 @@ What exists now:
|
||||
- CI jobs in .github/workflows/ci.yml: `api`, `backend`, `integration` (matrix of two shards), `frontend`, `ml`, `codegen`, `infrastructure`, `security`, `security-images`, `smoke`, and the required `aggregate` result. See [TESTING.md](TESTING.md) for sharding.
|
||||
- Observability: Prometheus, Loki, Alloy, Grafana with provisioned datasources and dashboards, and PostgreSQL, Redis, and node exporters. The React app does not send telemetry yet.
|
||||
|
||||
Not implemented yet: registration and login (their contract is declared; the operations answer 501 or 401), consents, profiles, the questionnaire and assessment, the company cabinet, needs and matching, invitations and contacts, the Resend and SMTP transports and mail delivery, the Go Kafka client, the outbox relay, notifications, support, and an end-to-end business suite. backend/db/migrations/ contains the outbox table, the identity storage tables (`users`, `email_tokens`, `sessions`), and the `policy_versions` table and no other business schema; no product rule reads the policy yet; registration, verification, and session behavior on top of that storage comes in later tasks, product usecase and adapter directories other than the password hashing and policy pieces contain only placeholders, and `make -C deploy test-e2e` is a deferred placeholder that exits with an error. The target design is in [ARCHITECTURE.md](ARCHITECTURE.md).
|
||||
Not implemented yet: registration and login (their contract is declared; the operations answer 501 or 401), consents, profiles, the questionnaire and assessment, the company cabinet, needs and matching, invitations and contacts, the Resend and SMTP transports and mail delivery, the Go Kafka client, the outbox relay, notifications, support, and an end-to-end business suite. backend/db/migrations/ contains the outbox table, the identity storage tables (`users`, `email_tokens`, `sessions`), and the `policy_versions` table and no other business schema; no product rule reads the policy yet; registration, verification, and session behavior on top of that storage comes in later tasks, product usecase and adapter directories other than the password hashing and policy pieces contain only placeholders, and `make -C deploy test-e2e` runs only a technical Playwright smoke of the SPA, API health, and error routes on a throwaway stack, not a business flow (see [TESTING.md](TESTING.md#browser-e2e-suite)). The target design is in [ARCHITECTURE.md](ARCHITECTURE.md).
|
||||
|
||||
## Install and work loop
|
||||
|
||||
@@ -138,7 +138,7 @@ S3 storage connects through the outbound `ObjectStorage` port and `backend/inter
|
||||
|
||||
The frontend is a React/Vite SPA. Keep FSD boundaries as product screens are added.
|
||||
|
||||
Implemented frontend scaffold: a React Router data router with public routes and separate candidate and employer cabinet shells, a TanStack Query client over the shared same-origin `apiRequest`, brand tokens in CSS variables, and shared primitives for loading, empty, error, forbidden, and saving states. JetBrains Mono 2.304 is self-hosted from the brandbook with its OFL license. Sign-in, registration, email confirmation, support, and cabinet screens are placeholders; business screens are later tasks. /status is a technical API liveness page, not product readiness. Vitest runs in the Node environment without a DOM, so clicks and keyboard focus are verified manually in a browser until the Playwright suite exists. See [frontend/README.en.md](../../frontend/README.en.md). Generated transport types are not automatically entity models. MSW supports UI development; its fixtures do not prove that the API is implemented.
|
||||
Implemented frontend scaffold: a React Router data router with public routes and separate candidate and employer cabinet shells, a TanStack Query client over the shared same-origin `apiRequest`, brand tokens in CSS variables, and shared primitives for loading, empty, error, forbidden, and saving states. JetBrains Mono 2.304 is self-hosted from the brandbook with its OFL license. Sign-in, registration, email confirmation, support, and cabinet screens are placeholders; business screens are later tasks. /status is a technical API liveness page, not product readiness. Vitest runs in the Node environment without a DOM. The Playwright suite in `frontend/e2e/` loads pages in Chromium but does not yet test interactions, so clicks and keyboard focus are verified manually in a browser until it covers them. See [frontend/README.en.md](../../frontend/README.en.md). Generated transport types are not automatically entity models. MSW supports UI development; its fixtures do not prove that the API is implemented.
|
||||
|
||||
ML runs as a separate FastAPI process. It currently provides operational health/readiness only. Readiness stays at 503 without a model. Do not add placeholder inference that looks like a real result.
|
||||
|
||||
|
||||
+19
-2
@@ -26,9 +26,10 @@ Useful focused commands:
|
||||
| make -C ml check-generated | Pydantic models match the ML bundle without rewriting files |
|
||||
| make -C deploy config | Render Compose configurations without starting them |
|
||||
| make -C deploy smoke | Isolated technical smoke of service health routes |
|
||||
| make -C deploy test-e2e | Playwright browser suite against an isolated throwaway stack |
|
||||
| make -C observability check | Validate Prometheus, Loki, Alloy, and dashboard JSON |
|
||||
|
||||
make -C deploy test-e2e is reserved and currently exits nonzero with a message that the business-flow suite is deferred. Do not count this as a passing E2E run.
|
||||
make -C deploy test-e2e currently runs a technical browser suite, not a business-flow suite; see [Browser E2E suite](#browser-e2e-suite).
|
||||
|
||||
make -C ml check-generated uses datamodel-code-generator --check: a mismatch fails the check and leaves the models file unchanged. Prepare the bundle with make -C api bundle before checking; use make -C ml generate to update Python models. Generated models do not establish inference functionality or support for every OpenAPI 3.2 feature.
|
||||
|
||||
@@ -42,6 +43,22 @@ API verification checks the OpenAPI subset exercised by pinned tools, fixtures,
|
||||
|
||||
Deployment smoke checks infrastructure routes, Compose startup, PostgreSQL/Redis/SeaweedFS readiness, Redis authentication and cache configuration, rejection of anonymous SeaweedFS bucket access, and the backend startup log for `EMAIL_PROVIDER=disabled`. It stops Redis and SeaweedFS in turn to verify that /readyz returns 503 while /api/v1/healthz remains available, then verifies readiness recovery after each dependency restarts. It sends no mail and does not check mail delivery, contact release, protection of product data, ML robustness, ranking quality, PDF export, or the two-role flow. A separate monitoring check does not verify the core database or end-to-end telemetry from the application.
|
||||
|
||||
## Browser E2E suite
|
||||
|
||||
`make -C deploy test-e2e` runs the Playwright suite from `frontend/e2e/` in Chromium against the real frontend and backend images. It needs Docker and frontend dependencies installed with `make -C frontend install`; no browser is installed on the host. `deploy/scripts/e2e.sh` does the following:
|
||||
|
||||
- Reads the exact `@playwright/test` version from `frontend/package.json`, checks that the installed package matches it, and runs the suite in the official `mcr.microsoft.com/playwright:v<version>-noble` image with `frontend/` mounted read-only.
|
||||
- Starts the core stack under a unique project `lincodex-e2e-<random>` with fresh volumes and a generated throwaway env file: random passwords, `EMAIL_PROVIDER=disabled`, no mail transport settings. Shell variables other than Docker client settings do not reach Compose. The run refuses to reuse an existing project, network, or volume.
|
||||
- Publishes no host port. The browser container shares the frontend container's network namespace, so it opens `http://localhost:8080`, the same loopback origin as `APP_PUBLIC_URL`. The Playwright config refuses a base URL outside a loopback host.
|
||||
- Waits for backend readiness, runs the suite with retries disabled, and returns its exit code; make reports any failure as exit status 2.
|
||||
- Removes the containers, volumes, network, locally built images, and env file on every exit, including failures and interrupts. Only the cached Playwright image and the build cache remain.
|
||||
|
||||
Artifacts of the last run are in `frontend/test-results/e2e/`, which Git ignores; the runner prints the path. `report/` holds the HTML report (`pnpm exec playwright show-report test-results/e2e/report` from `frontend/`). For each failed test, `results/` keeps `trace.zip` and a screenshot (`pnpm exec playwright show-trace <trace.zip>` needs a local browser; trace.playwright.dev opens the file without one). After a failed run, `stand.log` holds the stack logs. `E2E_SPEC_DIR=<dir>` runs specs from another directory, such as a scratch copy, against the same isolated stack.
|
||||
|
||||
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. Later business tests create their own synthetic users and records through the public API in the fresh stack of each run; they do not use shared fixtures or real data.
|
||||
|
||||
The 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 does not run it yet.
|
||||
|
||||
## Integration test bootstrap
|
||||
|
||||
The shared helper lives in `backend/integration_test/bootstrap_test.go`. Calling `env := bootstrap(t)` starts PostgreSQL, Redis, and SeaweedFS, waits for adapter readiness, and returns an environment with configuration and clients. To test one adapter, use `bootstrap(t, postgresService)`, `bootstrap(t, redisService)`, or `bootstrap(t, seaweedfsService)`. Multiple services can be selected.
|
||||
@@ -70,7 +87,7 @@ Go unit tests should exercise domain/usecase rules with explicit inputs, results
|
||||
|
||||
Isolate test data by database/schema or run scenarios with a sequential reset. Do not run parallel cases against shared truncation. Reuse the bootstrap environment within a parent test; independent tests create their own environments. Integration CI must not silently skip tests when its container runtime is unavailable.
|
||||
|
||||
Validate contract changes with bundle, lint, codegen for every Go, TypeScript, and Python consumer, and generated drift, including new untracked files. Frontend component tests do not replace browser tests of the complete flow. After product implementation, add Playwright for both roles and a synthetic candidate without FSP history.
|
||||
Validate contract changes with bundle, lint, codegen for every Go, TypeScript, and Python consumer, and generated drift, including new untracked files. Frontend component tests do not replace browser tests of the complete flow. After product implementation, extend the Playwright suite with both roles and a synthetic candidate without FSP history.
|
||||
|
||||
Critical future checks:
|
||||
|
||||
|
||||
@@ -56,7 +56,7 @@ Frontend зависимости выбираются из актуальных s
|
||||
- CI jobs в .github/workflows/ci.yml: `api`, `backend`, `integration` (matrix из двух шардов), `frontend`, `ml`, `codegen`, `infrastructure`, `security`, `security-images`, `smoke` и обязательный итог `aggregate`. Шардирование описано в [TESTING.md](TESTING.md).
|
||||
- Observability: Prometheus, Loki, Alloy, Grafana с provisioned datasources и dashboards, exporters для PostgreSQL, Redis и node. React-приложение пока не отправляет телеметрию.
|
||||
|
||||
Еще не реализованы: регистрация и вход (их контракт объявлен; операции отвечают 501 или 401), согласия, профили, анкета и тестирование, кабинет компании, потребности и подбор, приглашения и контакты, транспорты Resend и SMTP и отправка почты, Go клиент Kafka, relay для outbox, уведомления, поддержка и бизнес-E2E suite. В backend/db/migrations/ есть таблица outbox, таблицы хранения identity (`users`, `email_tokens`, `sessions`) и таблица `policy_versions`, другой бизнес-схемы нет; ни одно продуктовое правило пока не читает политику; регистрация, подтверждение и сессии поверх этого хранения появятся в следующих задачах, каталоги продуктовых usecase и адаптеров, кроме частей для хеширования паролей и политики, содержат только заглушки, а `make -C deploy test-e2e` остается отложенной заглушкой и завершается ошибкой. Целевая архитектура описана в [ARCHITECTURE.md](ARCHITECTURE.md).
|
||||
Еще не реализованы: регистрация и вход (их контракт объявлен; операции отвечают 501 или 401), согласия, профили, анкета и тестирование, кабинет компании, потребности и подбор, приглашения и контакты, транспорты Resend и SMTP и отправка почты, Go клиент Kafka, relay для outbox, уведомления, поддержка и бизнес-E2E suite. В backend/db/migrations/ есть таблица outbox, таблицы хранения identity (`users`, `email_tokens`, `sessions`) и таблица `policy_versions`, другой бизнес-схемы нет; ни одно продуктовое правило пока не читает политику; регистрация, подтверждение и сессии поверх этого хранения появятся в следующих задачах, каталоги продуктовых usecase и адаптеров, кроме частей для хеширования паролей и политики, содержат только заглушки, а `make -C deploy test-e2e` запускает только технический smoke на Playwright для SPA, health API и маршрутов ошибок на одноразовом стеке, а не бизнес-сценарий (см. [TESTING.md](TESTING.md#браузерный-e2e-набор)). Целевая архитектура описана в [ARCHITECTURE.md](ARCHITECTURE.md).
|
||||
|
||||
## Установка и цикл работы
|
||||
|
||||
@@ -138,7 +138,7 @@ S3-хранилище подключено через outbound-порт `ObjectS
|
||||
|
||||
Frontend строится как React/Vite SPA. При разработке продуктовых экранов соблюдайте FSD границы.
|
||||
|
||||
Реализованный каркас frontend: data router React Router с публичными маршрутами и отдельными оболочками кабинетов кандидата и работодателя, клиент TanStack Query поверх общего `apiRequest` того же origin, токены бренда в CSS variables и общие примитивы состояний загрузки, пустого результата, ошибки, запрета доступа и сохранения. JetBrains Mono 2.304 раздается с нашего сервера из брендбука вместе с лицензией OFL. Вход, регистрация, подтверждение почты, поддержка и экраны кабинетов - заготовки; бизнес-экраны делаются отдельными задачами. /status - техническая страница доступности API, а не показатель готовности продукта. Vitest работает в окружении Node без DOM, поэтому нажатия и фокус клавиатуры проверяются вручную в браузере, пока нет набора Playwright. Подробнее: [frontend/README.md](../../frontend/README.md). Generated API transport не превращается в entity model сам по себе. MSW полезен для интерфейсной разработки, но его fixture не подтверждает API реализации.
|
||||
Реализованный каркас frontend: data router React Router с публичными маршрутами и отдельными оболочками кабинетов кандидата и работодателя, клиент TanStack Query поверх общего `apiRequest` того же origin, токены бренда в CSS variables и общие примитивы состояний загрузки, пустого результата, ошибки, запрета доступа и сохранения. JetBrains Mono 2.304 раздается с нашего сервера из брендбука вместе с лицензией OFL. Вход, регистрация, подтверждение почты, поддержка и экраны кабинетов - заготовки; бизнес-экраны делаются отдельными задачами. /status - техническая страница доступности API, а не показатель готовности продукта. Vitest работает в окружении Node без DOM. Набор Playwright в `frontend/e2e/` открывает страницы в Chromium, но пока не проверяет взаимодействия, поэтому нажатия и фокус клавиатуры проверяются вручную в браузере, пока набор их не покрывает. Подробнее: [frontend/README.md](../../frontend/README.md). Generated API transport не превращается в entity model сам по себе. MSW полезен для интерфейсной разработки, но его fixture не подтверждает API реализации.
|
||||
|
||||
ML - отдельный FastAPI процесс. Сейчас он предоставляет только operational health/readiness. Readiness остается 503 без модели. Не добавляйте placeholder inference, который выглядит как рабочий результат.
|
||||
|
||||
|
||||
+19
-2
@@ -26,9 +26,10 @@ make test запускает backend, frontend и ML тесты. make check та
|
||||
| make -C ml check-generated | Соответствие Pydantic-моделей ML bundle без перезаписи файлов |
|
||||
| make -C deploy config | Рендер Compose конфигураций без запуска |
|
||||
| make -C deploy smoke | Изолированный технический smoke по service health routes |
|
||||
| make -C deploy test-e2e | Браузерный набор Playwright на изолированном одноразовом стеке |
|
||||
| make -C observability check | Проверку Prometheus, Loki, Alloy и dashboard JSON |
|
||||
|
||||
make -C deploy test-e2e сейчас зарезервирован и завершается ненулевым кодом с сообщением о том, что бизнес flow suite отложен. Не считайте это успешным E2E запуском.
|
||||
make -C deploy test-e2e сейчас запускает технический браузерный набор, а не проверку бизнес-сценариев; см. [Браузерный E2E набор](#браузерный-e2e-набор).
|
||||
|
||||
make -C ml check-generated использует datamodel-code-generator --check: расхождение завершает проверку ошибкой, а файл моделей остается неизменным. Перед проверкой обновите bundle через make -C api bundle; для обновления Python-моделей используйте make -C ml generate. Сгенерированные модели не подтверждают наличие inference или поддержку всех возможностей OpenAPI 3.2.
|
||||
|
||||
@@ -42,6 +43,22 @@ API verify проверяет выбранный OpenAPI subset через pinne
|
||||
|
||||
Deployment smoke проверяет инфраструктурные маршруты, запуск Compose, готовность PostgreSQL/Redis/SeaweedFS, аутентификацию и настройки кеша Redis, отказ SeaweedFS в анонимном доступе к bucket и запись в логе запуска backend о `EMAIL_PROVIDER=disabled`. Он поочередно останавливает Redis и SeaweedFS и проверяет, что /readyz возвращает 503, а /api/v1/healthz остается доступным, затем проверяет восстановление готовности после запуска зависимости. Он не отправляет писем и не проверяет доставку почты, получение контактов, защищенность бизнес-данных, устойчивость ML, точность ранжирования, PDF экспорт или сценарий двух ролей. Отдельная проверка мониторинга не подтверждает core database или end-to-end доставку данных от приложения.
|
||||
|
||||
## Браузерный E2E набор
|
||||
|
||||
`make -C deploy test-e2e` запускает набор Playwright из `frontend/e2e/` в Chromium на настоящих образах frontend и backend. Нужны Docker и зависимости frontend, установленные через `make -C frontend install`; браузер на хост не ставится. `deploy/scripts/e2e.sh` делает следующее:
|
||||
|
||||
- Читает точную версию `@playwright/test` из `frontend/package.json`, проверяет, что установлена та же версия, и запускает набор в официальном образе `mcr.microsoft.com/playwright:v<version>-noble`, где `frontend/` смонтирован только для чтения.
|
||||
- Поднимает основной стек под уникальным проектом `lincodex-e2e-<random>` со свежими томами и сгенерированным одноразовым env-файлом: случайные пароли, `EMAIL_PROVIDER=disabled`, без настроек почтового транспорта. Переменные оболочки, кроме настроек Docker-клиента, в Compose не попадают. Запуск отказывается переиспользовать существующие проект, сеть или том.
|
||||
- Не публикует host-порт. Контейнер браузера разделяет сетевое пространство контейнера frontend и открывает `http://localhost:8080`, тот же loopback origin, что и `APP_PUBLIC_URL`. Конфигурация Playwright отклоняет base URL вне loopback-хоста.
|
||||
- Ждет готовности backend, запускает набор без повторов и возвращает его код завершения; make сообщает о любой ошибке кодом 2.
|
||||
- При любом завершении, включая ошибку и прерывание, удаляет контейнеры, тома, сеть, локально собранные образы и env-файл. Остаются только закешированный образ Playwright и кеш сборки.
|
||||
|
||||
Артефакты последнего прогона лежат в `frontend/test-results/e2e/`, который игнорируется Git; путь печатается в конце. В `report/` лежит HTML-отчет (`pnpm exec playwright show-report test-results/e2e/report` из `frontend/`). Для каждого упавшего теста `results/` сохраняет `trace.zip` и снимок экрана (`pnpm exec playwright show-trace <trace.zip>` требует локального браузера; trace.playwright.dev открывает файл без него). После неуспешного прогона `stand.log` содержит логи стека. `E2E_SPEC_DIR=<dir>` запускает спецификации из другого каталога, например из временной копии, на таком же изолированном стеке.
|
||||
|
||||
Текущий набор (`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 в свежем стеке каждого прогона; общие фикстуры и реальные данные не используются.
|
||||
|
||||
Набор не проверяет сценарии кандидата и работодателя, вход, доставку почты, отказы зависимостей (их проверяет deployment smoke), браузеры кроме desktop Chromium, верстку и доступность. В CI он пока не запускается.
|
||||
|
||||
## Bootstrap интеграционных тестов
|
||||
|
||||
Общий helper находится в `backend/integration_test/bootstrap_test.go`. Вызов `env := bootstrap(t)` поднимает PostgreSQL, Redis и SeaweedFS, дожидается готовности адаптеров и возвращает окружение с конфигурацией и клиентами. Для проверки одного адаптера используйте `bootstrap(t, postgresService)`, `bootstrap(t, redisService)` или `bootstrap(t, seaweedfsService)`. Можно передать несколько сервисов.
|
||||
@@ -70,7 +87,7 @@ CI запускает отдельную matrix из двух integration jobs
|
||||
|
||||
Общие тестовые данные должны быть изолированы по БД/схеме или сбрасываться последовательно. Не запускайте параллельные сценарии с общим truncate. Переиспользуйте окружение bootstrap внутри родительского теста; независимые тесты создают свои окружения. Integration job не должен молча пропускать тесты при отсутствии runtime.
|
||||
|
||||
Контракты проверяются через bundle, lint, codegen всех Go, TypeScript и Python потребителей и generated drift, включая новые untracked файлы. Frontend component tests не заменяют браузерный тест сквозного пути. После реализации продукта добавить Playwright для двух ролей и явно синтетического кандидата без ФСП.
|
||||
Контракты проверяются через bundle, lint, codegen всех Go, TypeScript и Python потребителей и generated drift, включая новые untracked файлы. Frontend component tests не заменяют браузерный тест сквозного пути. После реализации продукта расширить набор Playwright сценариями двух ролей и явно синтетического кандидата без ФСП.
|
||||
|
||||
Критические будущие проверки:
|
||||
|
||||
|
||||
Reference in new issue
Block a user