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
@@ -6,7 +6,7 @@ Use unit tests for domain and application behavior, component tests for frontend
|
||||
|
||||
Contract changes need bundle and lint checks, regeneration of affected consumers, and generated drift checks. Infrastructure changes need rendered Compose configuration and the validator for each changed monitoring or deployment file.
|
||||
|
||||
The technical deployment smoke checks service routes and infrastructure readiness. It does not validate a candidate or employer workflow. The deploy test-e2e target is reserved and currently fails with a deferred message until the business-flow suite exists.
|
||||
The technical deployment smoke checks service routes and infrastructure readiness. It does not validate a candidate or employer workflow. The deploy test-e2e target runs the Playwright suite against an isolated throwaway stack; it currently covers only the SPA, API health, and error routes, so a pass does not validate a business workflow.
|
||||
|
||||
Do not report ranking accuracy, assessment validity, production latency, load capacity, privacy correctness, or model quality without the corresponding measured test and its dataset, environment, and limits. Planned targets and synthetic examples are not results.
|
||||
|
||||
|
||||
+5
-3
@@ -11,6 +11,8 @@ CHECK_ENV_FILE := $(ROOT)/.env.example
|
||||
CORE_FILE := $(ROOT)/deploy/docker/docker-compose.yml
|
||||
ML_FILE := $(ROOT)/deploy/docker/docker-compose.ml.yml
|
||||
MONITORING_FILE := $(ROOT)/deploy/docker/docker-compose.monitoring.yml
|
||||
E2E_FILE := $(ROOT)/deploy/docker/docker-compose.e2e.yml
|
||||
PLAYWRIGHT_VERSION := $(shell sed -n 's/^ *"@playwright\/test": "\([^"]*\)",\{0,1\}$$/\1/p' "$(ROOT)/frontend/package.json")
|
||||
|
||||
.PHONY: help config build up down logs monitoring-config monitoring-up monitoring-down monitoring-logs ml-config ml-build ml-up ml-down ml-logs check smoke test-e2e
|
||||
|
||||
@@ -24,6 +26,7 @@ config: ## Render all Compose files with safe example values
|
||||
APP_PROJECT="$(APP_PROJECT)" APP_NETWORK="$(APP_NETWORK)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p "$(APP_PROJECT)" -f "$(CORE_FILE)" config --quiet
|
||||
APP_PROJECT="$(APP_PROJECT)" APP_NETWORK="$(APP_NETWORK)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p "$(ML_PROJECT)" -f "$(ML_FILE)" config --quiet
|
||||
APP_PROJECT="$(APP_PROJECT)" APP_NETWORK="$(APP_NETWORK)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p "$(MONITORING_PROJECT)" -f "$(MONITORING_FILE)" config --quiet
|
||||
APP_PROJECT=lincodex-e2e-config APP_NETWORK=lincodex-e2e-config_default PLAYWRIGHT_VERSION="$(PLAYWRIGHT_VERSION)" E2E_UID=1000 E2E_GID=1000 E2E_SPEC_DIR="$(ROOT)/frontend/e2e" E2E_ARTIFACTS_DIR="$(ROOT)/frontend/test-results/e2e" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p lincodex-e2e-config -f "$(CORE_FILE)" -f "$(E2E_FILE)" --profile e2e config --quiet
|
||||
|
||||
build: ## Build local frontend and backend images
|
||||
APP_PROJECT="$(APP_PROJECT)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p "$(APP_PROJECT)" -f "$(CORE_FILE)" build
|
||||
@@ -78,6 +81,5 @@ check: config ## Validate all Compose files without starting services
|
||||
smoke: ## Start an isolated stack and check infrastructure health routes
|
||||
@bash scripts/smoke.sh
|
||||
|
||||
test-e2e: ## Reserved for the future synthetic business-flow E2E suite
|
||||
@printf '%s\n' 'test-e2e is deferred until the synthetic business-flow suite is implemented.' >&2
|
||||
@exit 2
|
||||
test-e2e: ## Run the Playwright suite against an isolated throwaway stack
|
||||
@bash scripts/e2e.sh
|
||||
+3
-2
@@ -7,8 +7,9 @@ Configuration for running the application with Docker Compose and Nginx.
|
||||
- `docker/docker-compose.yml` starts the core stack with PostgreSQL, Redis, SeaweedFS, and Kafka.
|
||||
- `docker/docker-compose.ml.yml` and `docker/docker-compose.monitoring.yml` run ML and monitoring as separate projects.
|
||||
- `nginx/` configures frontend serving and API proxying.
|
||||
- `scripts/` contains the isolated stack smoke check.
|
||||
- `docker/docker-compose.e2e.yml` is an overlay used only by the browser suite: it removes the frontend host port and adds the Playwright runner.
|
||||
- `scripts/` contains the isolated stack smoke check and the browser E2E runner.
|
||||
|
||||
Dockerfiles live in service directories and `.env.example` at the repository root. From the root, `make -C deploy config` checks Compose and `make -C deploy up` starts the core stack after `.env` is prepared. Start monitoring separately with `make -C deploy monitoring-up`.
|
||||
Dockerfiles live in service directories and `.env.example` at the repository root. From the root, `make -C deploy config` checks Compose and `make -C deploy up` starts the core stack after `.env` is prepared. Start monitoring separately with `make -C deploy monitoring-up`. `make -C deploy test-e2e` runs the Playwright suite against a throwaway stack under a unique project name and removes it afterwards; see [TESTING.md](../docs/en/TESTING.md#browser-e2e-suite).
|
||||
|
||||
See the [deployment guide](../docs/en/DEPLOY.md).
|
||||
+3
-2
@@ -7,8 +7,9 @@
|
||||
- `docker/docker-compose.yml` поднимает основной стек с PostgreSQL, Redis, SeaweedFS и Kafka.
|
||||
- `docker/docker-compose.ml.yml` и `docker/docker-compose.monitoring.yml` запускают ML и мониторинг отдельными проектами.
|
||||
- `nginx/` содержит конфигурацию раздачи frontend и проксирования API.
|
||||
- `scripts/` содержит smoke-проверку изолированного стека.
|
||||
- `docker/docker-compose.e2e.yml` - overlay только для браузерного набора: убирает host-порт frontend и добавляет запуск Playwright.
|
||||
- `scripts/` содержит smoke-проверку изолированного стека и запуск браузерных E2E.
|
||||
|
||||
Dockerfile лежат в каталогах сервисов, `.env.example` - в корне репозитория. Из корня: `make -C deploy config` проверяет Compose, `make -C deploy up` запускает основной стек после подготовки `.env`. Мониторинг включается отдельно через `make -C deploy monitoring-up`.
|
||||
Dockerfile лежат в каталогах сервисов, `.env.example` - в корне репозитория. Из корня: `make -C deploy config` проверяет Compose, `make -C deploy up` запускает основной стек после подготовки `.env`. Мониторинг включается отдельно через `make -C deploy monitoring-up`. `make -C deploy test-e2e` запускает набор Playwright на одноразовом стеке с уникальным именем проекта и удаляет его после прогона; см. [TESTING.md](../docs/ru/TESTING.md#браузерный-e2e-набор).
|
||||
|
||||
Подробнее: [развертывание](../docs/ru/DEPLOY.md).
|
||||
@@ -0,0 +1,40 @@
|
||||
# Overlay for the isolated browser suite. Only deploy/scripts/e2e.sh combines
|
||||
# it with docker-compose.yml, under a unique project name and a generated
|
||||
# throwaway env file; never apply it to the working stand.
|
||||
services:
|
||||
frontend:
|
||||
# The browser shares this container's network namespace, so the stand
|
||||
# publishes no host port and cannot collide with a running stand.
|
||||
ports: !reset []
|
||||
|
||||
playwright:
|
||||
# The tag must match @playwright/test in frontend/package.json; the runner
|
||||
# reads the version from there.
|
||||
image: mcr.microsoft.com/playwright:v${PLAYWRIGHT_VERSION:?Set PLAYWRIGHT_VERSION}-noble
|
||||
profiles: ["e2e"]
|
||||
# localhost:8080 inside this namespace is the frontend Nginx, so the
|
||||
# browser origin equals the loopback APP_PUBLIC_URL the backend accepts.
|
||||
network_mode: service:frontend
|
||||
user: "${E2E_UID:?Set E2E_UID}:${E2E_GID:?Set E2E_GID}"
|
||||
init: true
|
||||
working_dir: /workspace/frontend
|
||||
environment:
|
||||
HOME: /tmp
|
||||
CI: ${E2E_CI:-}
|
||||
E2E_BASE_URL: http://localhost:8080
|
||||
E2E_ARTIFACTS_DIR: /artifacts
|
||||
# Only the dependencies installed from frontend/pnpm-lock.yaml and the
|
||||
# suite are read; results go to the separate writable mount.
|
||||
volumes:
|
||||
- ../../frontend:/workspace/frontend:ro
|
||||
- ${E2E_SPEC_DIR:?Set E2E_SPEC_DIR}:/workspace/frontend/e2e:ro
|
||||
- ${E2E_ARTIFACTS_DIR:?Set E2E_ARTIFACTS_DIR}:/artifacts
|
||||
command: ["node", "node_modules/@playwright/test/cli.js", "test"]
|
||||
cap_drop: [ALL]
|
||||
security_opt: ["no-new-privileges:true"]
|
||||
shm_size: 1gb
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "2.0"
|
||||
memory: 2G
|
||||
@@ -9,7 +9,7 @@ services:
|
||||
POSTGRES_EXPORTER_PASSWORD: ${POSTGRES_EXPORTER_PASSWORD:-}
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql
|
||||
- ./initdb/10-postgres-exporter.sh:/docker-entrypoint-initdb.d/10-postgres-exporter.sh:ro
|
||||
- ./initdb/10-postgres-exporter.sql:/docker-entrypoint-initdb.d/10-postgres-exporter.sql:ro
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U \"$${POSTGRES_USER}\" -d \"$${POSTGRES_DB}\""]
|
||||
interval: 10s
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
if [[ -z "${POSTGRES_EXPORTER_USER:-}" && -z "${POSTGRES_EXPORTER_PASSWORD:-}" ]]; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
: "${POSTGRES_EXPORTER_USER:?POSTGRES_EXPORTER_USER and POSTGRES_EXPORTER_PASSWORD must both be set}"
|
||||
: "${POSTGRES_EXPORTER_PASSWORD:?POSTGRES_EXPORTER_USER and POSTGRES_EXPORTER_PASSWORD must both be set}"
|
||||
|
||||
psql \
|
||||
--username "$POSTGRES_USER" \
|
||||
--dbname "$POSTGRES_DB" \
|
||||
--set=exporter_user="$POSTGRES_EXPORTER_USER" \
|
||||
--set=exporter_password="$POSTGRES_EXPORTER_PASSWORD" <<'SQL'
|
||||
SELECT format('CREATE ROLE %I LOGIN PASSWORD %L', :'exporter_user', :'exporter_password')
|
||||
WHERE NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = :'exporter_user')
|
||||
\gexec
|
||||
|
||||
GRANT pg_monitor TO :"exporter_user";
|
||||
SQL
|
||||
@@ -0,0 +1,38 @@
|
||||
-- Creates the optional PostgreSQL metrics login on first volume
|
||||
-- initialization. The image entrypoint runs *.sql files with psql
|
||||
-- (ON_ERROR_STOP=1, as POSTGRES_USER in POSTGRES_DB), independent of file
|
||||
-- mode, unlike *.sh files, which it executes or sources depending on the
|
||||
-- executable bit reported by the bind mount. \getenv needs psql 15 or newer.
|
||||
--
|
||||
-- Both credentials empty or unset: nothing happens. Exactly one set: the
|
||||
-- initialization fails. Both set: the role is created if missing and gets
|
||||
-- pg_monitor.
|
||||
|
||||
\getenv exporter_user POSTGRES_EXPORTER_USER
|
||||
\getenv exporter_password POSTGRES_EXPORTER_PASSWORD
|
||||
\if :{?exporter_user}
|
||||
\else
|
||||
\set exporter_user ''
|
||||
\endif
|
||||
\if :{?exporter_password}
|
||||
\else
|
||||
\set exporter_password ''
|
||||
\endif
|
||||
|
||||
SELECT :'exporter_user' <> '' AS has_exporter_user,
|
||||
:'exporter_password' <> '' AS has_exporter_password
|
||||
\gset
|
||||
|
||||
\if :has_exporter_user
|
||||
\if :has_exporter_password
|
||||
SELECT format('CREATE ROLE %I LOGIN PASSWORD %L', :'exporter_user', :'exporter_password')
|
||||
WHERE NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = :'exporter_user')
|
||||
\gexec
|
||||
|
||||
GRANT pg_monitor TO :"exporter_user";
|
||||
\else
|
||||
DO $$ BEGIN RAISE EXCEPTION 'POSTGRES_EXPORTER_USER and POSTGRES_EXPORTER_PASSWORD must both be set'; END $$;
|
||||
\endif
|
||||
\elif :has_exporter_password
|
||||
DO $$ BEGIN RAISE EXCEPTION 'POSTGRES_EXPORTER_USER and POSTGRES_EXPORTER_PASSWORD must both be set'; END $$;
|
||||
\endif
|
||||
@@ -0,0 +1,163 @@
|
||||
#!/usr/bin/env bash
|
||||
# Runs the Playwright suite against an isolated, throwaway Compose stand.
|
||||
#
|
||||
# Each run gets a unique project name, a generated env file with random
|
||||
# secrets and EMAIL_PROVIDER=disabled, no host port, and fresh volumes. The
|
||||
# stand, its volumes, and its locally built images are removed on every exit.
|
||||
# Artifacts of the last run stay in frontend/test-results/e2e.
|
||||
#
|
||||
# Optional environment:
|
||||
# E2E_SPEC_DIR directory with specs to run instead of frontend/e2e, for
|
||||
# example a scratch copy while debugging the suite.
|
||||
set -euo pipefail
|
||||
|
||||
root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)
|
||||
compose_file="$root/deploy/docker/docker-compose.yml"
|
||||
e2e_file="$root/deploy/docker/docker-compose.e2e.yml"
|
||||
frontend_dir="$root/frontend"
|
||||
artifacts_dir="$frontend_dir/test-results/e2e"
|
||||
spec_dir="${E2E_SPEC_DIR:-$frontend_dir/e2e}"
|
||||
|
||||
suffix=$(od -An -N4 -tx1 /dev/urandom | tr -d ' \n')
|
||||
project="lincodex-e2e-$suffix"
|
||||
network="${project}_default"
|
||||
env_file=""
|
||||
started=0
|
||||
|
||||
random_secret() {
|
||||
od -An -N24 -tx1 /dev/urandom | tr -d ' \n'
|
||||
}
|
||||
|
||||
fail() {
|
||||
printf '%s\n' "$1" >&2
|
||||
exit 2
|
||||
}
|
||||
|
||||
# Read the exact @playwright/test version; the browser image tag must match it.
|
||||
declared=$(sed -n 's/^ *"@playwright\/test": "\([^"]*\)",\{0,1\}$/\1/p' "$frontend_dir/package.json")
|
||||
[[ "$declared" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] ||
|
||||
fail "frontend/package.json must pin @playwright/test to an exact version, found '$declared'."
|
||||
installed_manifest="$frontend_dir/node_modules/@playwright/test/package.json"
|
||||
[[ -f "$installed_manifest" ]] ||
|
||||
fail 'Frontend dependencies are missing. Run make -C frontend install first.'
|
||||
installed=$(sed -n 's/^ *"version": "\([^"]*\)",\{0,1\}$/\1/p' "$installed_manifest")
|
||||
[[ "$installed" == "$declared" ]] ||
|
||||
fail "Installed @playwright/test $installed differs from $declared. Run make -C frontend install."
|
||||
[[ -d "$spec_dir" ]] || fail "Spec directory $spec_dir does not exist."
|
||||
spec_dir=$(cd "$spec_dir" && pwd)
|
||||
for dockerfile in "$root/backend/Dockerfile" "$root/frontend/Dockerfile"; do
|
||||
[[ -f "$dockerfile" ]] || fail "Missing required build file $dockerfile."
|
||||
done
|
||||
|
||||
# Compose runs with a cleared environment: shell variables such as
|
||||
# EMAIL_PROVIDER, RESEND_API_KEY, or COMPOSE_FILE must not leak into the
|
||||
# stand. Only Docker client settings pass through.
|
||||
docker_env=(PATH="$PATH" HOME="$HOME")
|
||||
while IFS='=' read -r name _; do
|
||||
case "$name" in
|
||||
DOCKER_* | BUILDKIT_* | TMPDIR) docker_env+=("$name=${!name}") ;;
|
||||
esac
|
||||
done < <(env)
|
||||
|
||||
compose() {
|
||||
env -i "${docker_env[@]}" \
|
||||
APP_PROJECT="$project" APP_NETWORK="$network" \
|
||||
PLAYWRIGHT_VERSION="$declared" E2E_CI="${CI:-}" \
|
||||
E2E_UID="$(id -u)" E2E_GID="$(id -g)" \
|
||||
E2E_SPEC_DIR="$spec_dir" E2E_ARTIFACTS_DIR="$artifacts_dir" \
|
||||
docker compose \
|
||||
--env-file "$env_file" \
|
||||
-p "$project" \
|
||||
-f "$compose_file" \
|
||||
-f "$e2e_file" \
|
||||
"$@"
|
||||
}
|
||||
|
||||
for volume in "${project}_postgres_data" "${project}_seaweedfs_data" "${project}_kafka_data"; do
|
||||
if docker volume inspect "$volume" >/dev/null 2>&1; then
|
||||
fail "Refusing to use existing E2E volume $volume."
|
||||
fi
|
||||
done
|
||||
if docker network inspect "$network" >/dev/null 2>&1; then
|
||||
fail "Refusing to use existing E2E network $network."
|
||||
fi
|
||||
if [[ -n "$(docker ps -aq --filter "label=com.docker.compose.project=$project")" ]]; then
|
||||
fail "Refusing to use existing Compose project $project."
|
||||
fi
|
||||
|
||||
cleanup() {
|
||||
local result=$?
|
||||
trap - EXIT INT TERM
|
||||
if ((started)); then
|
||||
if ((result != 0)); then
|
||||
compose logs --no-color --timestamps >"$artifacts_dir/stand.log" 2>&1 || true
|
||||
printf 'Stand logs: %s\n' "$artifacts_dir/stand.log" >&2
|
||||
fi
|
||||
if ! compose --profile e2e down --volumes --remove-orphans --rmi local; then
|
||||
printf 'E2E cleanup failed; inspect only the %s Compose project.\n' "$project" >&2
|
||||
result=1
|
||||
fi
|
||||
fi
|
||||
[[ -z "$env_file" ]] || rm -f "$env_file"
|
||||
printf 'E2E artifacts: %s\n' "$artifacts_dir"
|
||||
exit "$result"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
trap 'exit 130' INT
|
||||
trap 'exit 143' TERM
|
||||
|
||||
mkdir -p "$artifacts_dir"
|
||||
rm -f "$artifacts_dir/stand.log"
|
||||
|
||||
# Throwaway configuration with synthetic secrets. The backend sends no mail,
|
||||
# and APP_PUBLIC_URL is the origin the browser uses inside the stand.
|
||||
env_file=$(mktemp "${TMPDIR:-/tmp}/lincodex-e2e-env.XXXXXX")
|
||||
chmod 600 "$env_file"
|
||||
cat >"$env_file" <<EOF
|
||||
POSTGRES_DB=lincodex
|
||||
POSTGRES_USER=lincodex
|
||||
POSTGRES_PASSWORD=$(random_secret)
|
||||
REDIS_PASSWORD=$(random_secret)
|
||||
SEAWEEDFS_ACCESS_KEY=e2e-$suffix
|
||||
SEAWEEDFS_SECRET_KEY=$(random_secret)
|
||||
SEAWEEDFS_BUCKET=lincodex
|
||||
KAFKA_CLUSTER_ID=$(head -c 16 /dev/urandom | base64 | tr '+/' '-_' | tr -d '=\n')
|
||||
EMAIL_PROVIDER=disabled
|
||||
EMAIL_FROM=no-reply@example.com
|
||||
EMAIL_TIMEOUT=10s
|
||||
APP_PUBLIC_URL=http://localhost:8080
|
||||
PASSWORD_HASH_CONCURRENCY=1
|
||||
POSTGRES_EXPORTER_USER=
|
||||
POSTGRES_EXPORTER_PASSWORD=
|
||||
EOF
|
||||
|
||||
printf 'E2E project: %s (Playwright %s)\n' "$project" "$declared"
|
||||
compose config --quiet
|
||||
compose --profile e2e config --quiet
|
||||
started=1
|
||||
compose up --build -d --wait --wait-timeout 180
|
||||
|
||||
# The backend has no Compose health check; wait until it reports PostgreSQL,
|
||||
# Redis, and SeaweedFS ready before the browser starts.
|
||||
ready=0
|
||||
for _ in {1..60}; do
|
||||
if [[ "$(compose exec -T frontend wget -q -O - http://backend:8080/readyz 2>/dev/null || true)" == '{"status":"ready"}' ]]; then
|
||||
ready=1
|
||||
break
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
((ready)) || {
|
||||
printf '%s\n' 'Timed out waiting for backend readiness.' >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
set +e
|
||||
compose run --rm --no-deps -T playwright
|
||||
status=$?
|
||||
set -e
|
||||
if ((status != 0)); then
|
||||
printf 'Playwright failed with exit code %s; traces and screenshots are in %s/results.\n' \
|
||||
"$status" "$artifacts_dir" >&2
|
||||
fi
|
||||
exit "$status"
|
||||
@@ -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 сценариями двух ролей и явно синтетического кандидата без ФСП.
|
||||
|
||||
Критические будущие проверки:
|
||||
|
||||
|
||||
@@ -6,3 +6,5 @@ src/shared/api/schemas/
|
||||
scripts/fixtures/
|
||||
pnpm-lock.yaml
|
||||
.orval-compat-*/
|
||||
test-results/
|
||||
playwright-report/
|
||||
@@ -11,6 +11,7 @@ A React and TypeScript SPA built with Vite and organized using FSD. The interfac
|
||||
- `src/shared/ui/` holds design tokens, fonts, logos, and primitives; `src/shared/config/` holds route paths; `src/shared/api/` holds the API client with generated endpoints, Zod schemas, and MSW mocks.
|
||||
- `codegen/orval.config.ts` configures generation from the shared OpenAPI contract.
|
||||
- `scripts/` checks FSD boundaries and Orval compatibility with the OpenAPI 3.2 fixture.
|
||||
- `e2e/` holds Playwright specs and `playwright.config.ts` configures them; they run only against a Compose stack.
|
||||
|
||||
From the repository root, `make -C frontend dev` starts development and `make -C frontend check` runs checks and builds the app. In Docker, Nginx serves the built files using configuration from `deploy/nginx/`.
|
||||
|
||||
@@ -79,4 +80,6 @@ Accessibility: every shell starts with a skip link to `main`, has landmarks and
|
||||
|
||||
Vitest runs in the Node environment with no DOM library. Routes are rendered through React Router's static handler and checked as HTML: shells, landmarks, the skip link, the active item, redirects, and not-found pages. State tests render components to markup; the query-error test runs the real `QueryClient` with the generated health operation and a stubbed `fetch`. Clicks and focus movement are checked manually in a browser; automated interaction tests need a DOM environment, which is a separate dependency decision.
|
||||
|
||||
Playwright specs in `e2e/` run in a real Chromium against the built frontend and backend: `make -C deploy test-e2e` starts a throwaway Compose stack and runs them in the official Playwright image, so no browser is installed on the host. Vitest excludes `e2e/`; `make -C frontend typecheck` and lint cover the specs. Artifacts of the last run are in `test-results/e2e/`. Details: [TESTING.md](../docs/en/TESTING.md#browser-e2e-suite).
|
||||
|
||||
See the [development guide](../docs/en/DEVELOPMENT.md).
|
||||
@@ -11,6 +11,7 @@ SPA на React и TypeScript со сборкой Vite и структурой FS
|
||||
- `src/shared/ui/` - токены дизайна, шрифты, логотипы и примитивы; `src/shared/config/` - пути маршрутов; `src/shared/api/` - API-клиент со сгенерированными endpoints, схемами Zod и MSW-моками.
|
||||
- `codegen/orval.config.ts` - генерация из общего OpenAPI-контракта.
|
||||
- `scripts/` - проверки границ FSD и совместимости Orval с фикстурой OpenAPI 3.2.
|
||||
- `e2e/` - спецификации Playwright, их настройки в `playwright.config.ts`; запускаются только на Compose-стеке.
|
||||
|
||||
Из корня: `make -C frontend dev` запускает разработку, `make -C frontend check` - проверки и сборку. В Docker собранные файлы раздает Nginx с конфигурацией из `deploy/nginx/`.
|
||||
|
||||
@@ -79,4 +80,6 @@ JetBrains Mono 2.304 (SIL OFL 1.1) раздается с нашего серве
|
||||
|
||||
Vitest работает в окружении Node без DOM-библиотеки. Маршруты отрисовываются через статический обработчик React Router и проверяются как HTML: оболочки, ориентиры, ссылка пропуска, активный пункт, перенаправления и страницы "не найдено". Тесты состояний отрисовывают компоненты в разметку; тест ошибки запроса запускает настоящий `QueryClient` со сгенерированной операцией health и подмененным `fetch`. Нажатия и перемещение фокуса проверяются вручную в браузере; автоматические тесты взаимодействия требуют DOM-окружения, а это отдельное решение о зависимости.
|
||||
|
||||
Спецификации Playwright из `e2e/` выполняются в настоящем Chromium на собранных frontend и backend: `make -C deploy test-e2e` поднимает одноразовый Compose-стек и запускает их в официальном образе Playwright, поэтому браузер на хост не ставится. Vitest исключает `e2e/`; `make -C frontend typecheck` и lint проверяют спецификации. Артефакты последнего прогона лежат в `test-results/e2e/`. Подробнее: [TESTING.md](../docs/ru/TESTING.md#браузерный-e2e-набор).
|
||||
|
||||
Подробнее: [разработка](../docs/ru/DEVELOPMENT.md).
|
||||
Vendored
+3
@@ -0,0 +1,3 @@
|
||||
// The Playwright config reads its settings from the environment. The project
|
||||
// does not depend on @types/node, so declare only the access the config uses.
|
||||
declare const process: { readonly env: Readonly<Record<string, string | undefined>> };
|
||||
@@ -0,0 +1,48 @@
|
||||
import { expect, test } from "@playwright/test";
|
||||
|
||||
// Technical smoke of the real stand: the built SPA behind Nginx, the Go API
|
||||
// behind the /api proxy, and the error routes of both. It needs no data and
|
||||
// checks no candidate or employer workflow.
|
||||
|
||||
test("start page renders the SPA in Russian", async ({ page }) => {
|
||||
await page.goto("/");
|
||||
|
||||
await expect(page.locator("html")).toHaveAttribute("lang", "ru");
|
||||
await expect(
|
||||
page.getByRole("heading", { level: 1, name: "Протокол подтвержденных навыков" }),
|
||||
).toBeVisible();
|
||||
});
|
||||
|
||||
test("status page shows a live API", async ({ page }) => {
|
||||
const healthz = page.waitForResponse(
|
||||
(response) => new URL(response.url()).pathname === "/api/v1/healthz",
|
||||
);
|
||||
await page.goto("/status");
|
||||
|
||||
await expect(page.getByRole("heading", { level: 1, name: "Технический статус" })).toBeVisible();
|
||||
expect((await healthz).status()).toBe(200);
|
||||
await expect(page.locator("dt", { hasText: "Статус" }).locator("+ dd")).toHaveText("ok");
|
||||
});
|
||||
|
||||
test("API healthz answers through the frontend proxy", async ({ request }) => {
|
||||
const response = await request.get("/api/v1/healthz");
|
||||
|
||||
expect(response.status()).toBe(200);
|
||||
expect(await response.json()).toEqual({ status: "ok" });
|
||||
});
|
||||
|
||||
test("unknown SPA route shows the not-found page", async ({ page }) => {
|
||||
await page.goto("/e2e-missing-page");
|
||||
|
||||
await expect(page.getByRole("heading", { level: 1, name: "Страница не найдена" })).toBeVisible();
|
||||
await expect(page.getByText("/e2e-missing-page")).toBeVisible();
|
||||
await expect(page.getByRole("link", { name: "На главную" })).toHaveAttribute("href", "/");
|
||||
});
|
||||
|
||||
test("unknown API route returns a not_found problem", async ({ request }) => {
|
||||
const response = await request.get("/api/v1/missing");
|
||||
|
||||
expect(response.status()).toBe(404);
|
||||
expect(response.headers()["content-type"]).toMatch(/^application\/problem\+json\b/);
|
||||
expect(await response.json()).toMatchObject({ status: 404, code: "not_found" });
|
||||
});
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"extends": "../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"lib": ["ES2022", "DOM"],
|
||||
"types": []
|
||||
},
|
||||
"include": ["./**/*.ts", "../playwright.config.ts"]
|
||||
}
|
||||
@@ -12,9 +12,9 @@
|
||||
"fmt": "prettier --write .",
|
||||
"fmt:check": "prettier --check .",
|
||||
"lint": "pnpm run lint:eslint && pnpm run lint:css",
|
||||
"lint:eslint": "eslint src codegen scripts/*.mjs *.mjs --max-warnings=0",
|
||||
"lint:eslint": "eslint src codegen e2e scripts/*.mjs *.mjs playwright.config.ts --max-warnings=0",
|
||||
"lint:css": "stylelint 'src/**/*.css' --max-warnings=0",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"typecheck": "tsc --noEmit && tsc --noEmit -p e2e/tsconfig.json",
|
||||
"test": "vitest run",
|
||||
"test:fsd": "node ./scripts/test-fsd-boundaries.mjs",
|
||||
"check": "pnpm run fmt:check && pnpm run lint && pnpm run typecheck && pnpm run test && pnpm run test:fsd && pnpm run build",
|
||||
@@ -31,6 +31,7 @@
|
||||
"devDependencies": {
|
||||
"@eslint/js": "10.0.1",
|
||||
"@faker-js/faker": "10.6.0",
|
||||
"@playwright/test": "1.63.0",
|
||||
"@types/react": "19.3.0",
|
||||
"@types/react-dom": "19.3.0",
|
||||
"@typescript/native": "npm:typescript@7.0.2",
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { defineConfig, devices } from "@playwright/test";
|
||||
|
||||
// deploy/scripts/e2e.sh starts an isolated Compose stand and runs this suite
|
||||
// in the Playwright image that shares the frontend container's network
|
||||
// namespace, so the browser reaches the stand at http://localhost:8080.
|
||||
const baseURL = process.env.E2E_BASE_URL;
|
||||
if (!baseURL) {
|
||||
throw new Error("Set E2E_BASE_URL or run the suite with `make -C deploy test-e2e`.");
|
||||
}
|
||||
|
||||
// The suite creates synthetic data as it grows. Refuse any origin other than
|
||||
// a local stand so a misconfigured run cannot reach a shared environment.
|
||||
const allowedHosts = new Set(["localhost", "127.0.0.1", "[::1]"]);
|
||||
if (!allowedHosts.has(new URL(baseURL).hostname)) {
|
||||
throw new Error(`E2E_BASE_URL must point to a local stand, got ${baseURL}.`);
|
||||
}
|
||||
|
||||
const artifactsDir = process.env.E2E_ARTIFACTS_DIR ?? "test-results/e2e";
|
||||
|
||||
export default defineConfig({
|
||||
testDir: "./e2e",
|
||||
outputDir: `${artifactsDir}/results`,
|
||||
forbidOnly: Boolean(process.env.CI),
|
||||
retries: 0,
|
||||
reporter: [["list"], ["html", { outputFolder: `${artifactsDir}/report`, open: "never" }]],
|
||||
use: {
|
||||
baseURL,
|
||||
locale: "ru-RU",
|
||||
trace: "retain-on-failure",
|
||||
screenshot: "only-on-failure",
|
||||
video: "off",
|
||||
},
|
||||
projects: [{ name: "chromium", use: { ...devices["Desktop Chrome"] } }],
|
||||
});
|
||||
Generated
+28
@@ -188,6 +188,9 @@ importers:
|
||||
'@faker-js/faker':
|
||||
specifier: 10.6.0
|
||||
version: 10.6.0
|
||||
'@playwright/test':
|
||||
specifier: 1.63.0
|
||||
version: 1.63.0
|
||||
'@types/react':
|
||||
specifier: 19.3.0
|
||||
version: 19.3.0
|
||||
@@ -787,6 +790,11 @@ packages:
|
||||
'@oxc-project/types@0.152.0':
|
||||
resolution: {integrity: sha512-oM/5rLBm2tPkg0iBgkH/FOeR3PCDpY19GTgAZjMFM8h9WI9VW7cLgzp6nwtarYKmovavIQZ+Fe/RKX/8C8O/Rw==}
|
||||
|
||||
'@playwright/test@1.63.0':
|
||||
resolution: {integrity: sha512-oxMK4vllB9RK5NQ2l1pq1IfOf2AvnEuj/vYGDj0H2nMtmtZpKtCwt/l00GEO6xjGfpBNAvjovvYdCm50dRQkpQ==}
|
||||
engines: {node: '>=20'}
|
||||
hasBin: true
|
||||
|
||||
'@rolldown/binding-android-arm-eabi@1.2.12':
|
||||
resolution: {integrity: sha512-dB/a1214qKfHMXCpgqR4OZT+jS4kTyEXbQGJPqzobt5EwH5rX080pxE37alt3RzvR1bf1Yz/yGqRfrYAxuPw0A==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
@@ -2164,6 +2172,16 @@ packages:
|
||||
resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==}
|
||||
engines: {node: '>=12'}
|
||||
|
||||
playwright-core@1.63.0:
|
||||
resolution: {integrity: sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg==}
|
||||
engines: {node: '>=20'}
|
||||
hasBin: true
|
||||
|
||||
playwright@1.63.0:
|
||||
resolution: {integrity: sha512-+7ziBLidS4NaNCdt57SUDT+wYmmd5fmiQejUic/kb+YsYSCPyOOE9sebzMjNmQrsnNpDJqd4WHvV/8lfKfUDUg==}
|
||||
engines: {node: '>=20'}
|
||||
hasBin: true
|
||||
|
||||
postcss-safe-parser@7.1.0:
|
||||
resolution: {integrity: sha512-1WzZxRLaAFwEh6Do+zyGpjWV3nGJNxxhuh7Ubu/q1ICImMgZJnLwhoaEpRbG4pJppp2Y1ncL9ffA2f+LhrefQg==}
|
||||
engines: {node: '>=18.0'}
|
||||
@@ -3138,6 +3156,10 @@ snapshots:
|
||||
|
||||
'@oxc-project/types@0.152.0': {}
|
||||
|
||||
'@playwright/test@1.63.0':
|
||||
dependencies:
|
||||
playwright: 1.63.0
|
||||
|
||||
'@rolldown/binding-android-arm-eabi@1.2.12':
|
||||
optional: true
|
||||
|
||||
@@ -4346,6 +4368,12 @@ snapshots:
|
||||
|
||||
picomatch@4.0.7: {}
|
||||
|
||||
playwright-core@1.63.0: {}
|
||||
|
||||
playwright@1.63.0:
|
||||
dependencies:
|
||||
playwright-core: 1.63.0
|
||||
|
||||
postcss-safe-parser@7.1.0(postcss@8.5.28):
|
||||
dependencies:
|
||||
postcss: 8.5.28
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import react from "@vitejs/plugin-react";
|
||||
import { defineConfig } from "vitest/config";
|
||||
import { configDefaults, defineConfig } from "vitest/config";
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
@@ -13,6 +13,8 @@ export default defineConfig({
|
||||
},
|
||||
test: {
|
||||
environment: "node",
|
||||
// Playwright specs run against the Compose stand, not in Vitest.
|
||||
exclude: [...configDefaults.exclude, "e2e/**"],
|
||||
restoreMocks: true,
|
||||
},
|
||||
});
|
||||
Reference in new issue
Block a user