Compare commits

...

2 commits

Author SHA1 Message Date
f16e279f58 35 - Add prod image SPA serving, health endpoint, and Forgejo CI
All checks were successful
CI / backend (push) Successful in 20m34s
CI / frontend (push) Successful in 1m2s
CI / e2e (push) Successful in 21m57s
2026-06-30 21:07:45 +02:00
196cbfbb69 62 - Close coverage gaps, enable TS strict, add coverage thresholds 2026-06-28 23:26:24 +02:00
28 changed files with 1118 additions and 27 deletions

256
.forgejo/workflows/ci.yml Normal file
View file

@ -0,0 +1,256 @@
name: CI
# Tests + static analysis + lint. Runs on every push to a release branch and on
# PRs targeting main. The production image is built/pushed separately and ONLY on
# a v* tag (see image.yml) — never here.
on:
push:
branches: ['release/*']
pull_request:
branches: [main]
jobs:
backend:
runs-on: docker
container:
image: catthehacker/ubuntu:act-latest
services:
database:
image: postgres:16-alpine
env:
POSTGRES_DB: buckets
POSTGRES_USER: buckets
POSTGRES_PASSWORD: buckets
options: >-
--health-cmd "pg_isready -U buckets -d buckets"
--health-interval 5s
--health-timeout 5s
--health-retries 10
env:
# Point the test suite at the CI postgres service (host = service name).
DATABASE_URL: postgresql://buckets:buckets@database:5432/buckets?serverVersion=16&charset=utf8
steps:
- uses: https://data.forgejo.org/actions/checkout@v4
- name: Set up PHP
uses: https://github.com/shivammathur/setup-php@v2
with:
php-version: '8.4'
extensions: pdo_pgsql, mbstring, xml, dom, intl, zip
coverage: pcov
- name: Cache Composer dependencies
uses: https://data.forgejo.org/actions/cache@v4
with:
path: ~/.composer/cache
key: composer-${{ hashFiles('composer.lock') }}
restore-keys: composer-
- name: Install Composer dependencies
run: composer install --no-interaction --prefer-dist
- name: Lint (php-cs-fixer)
run: vendor/bin/php-cs-fixer check --diff
env:
PHP_CS_FIXER_IGNORE_ENV: '1'
- name: Static analysis (PHPStan)
run: vendor/bin/phpstan analyse --memory-limit=1G -c phpstan.dist.neon
- name: Create test database
run: php bin/console --env=test doctrine:database:create --if-not-exists
- name: Run migrations
run: php bin/console --env=test doctrine:migrations:migrate --no-interaction
- name: Tests with coverage
run: php bin/phpunit --coverage-clover coverage.xml
# Backend sits at ~98.8% clover element coverage (a few framework-glue
# elements are @codeCoverageIgnore'd in the text report but still counted
# in the clover XML). Gate at a 95% floor: catches real backslide without
# demanding an unreachable 100% off the raw clover metric (mirrors the
# frontend's vite.config thresholds, which are floors, not 100).
- name: Enforce coverage threshold
run: |
MIN=95
COVERAGE=$(php -r '
$xml = @simplexml_load_file("coverage.xml");
if ($xml === false || !isset($xml->project->metrics)) { echo "0"; exit; }
$m = $xml->project->metrics;
$el = (int) $m["elements"];
$cov = (int) $m["coveredelements"];
echo $el > 0 ? round(($cov / $el) * 100, 2) : 0;
')
echo "Coverage: ${COVERAGE}% (minimum ${MIN}%)"
php -r "exit((float)\$argv[1] >= (float)\$argv[2] ? 0 : 1);" "$COVERAGE" "$MIN" \
|| { echo "::error::Coverage ${COVERAGE}% is below the ${MIN}% threshold"; exit 1; }
frontend:
runs-on: docker
container:
image: catthehacker/ubuntu:act-latest
defaults:
run:
working-directory: frontend
steps:
- uses: https://data.forgejo.org/actions/checkout@v4
# Node is preinstalled in catthehacker/ubuntu:act-latest (no setup-node
# needed). npm ci is lockfile-driven, so the image's npm version is fine;
# the *production* frontend build pins NPM_VERSION inside the Dockerfile.
- name: Cache npm dependencies
uses: https://data.forgejo.org/actions/cache@v4
with:
path: ~/.npm
key: npm-${{ hashFiles('frontend/package-lock.json') }}
restore-keys: npm-
- name: Install dependencies
run: npm ci
- name: Lint (oxlint)
run: npm run lint
- name: Format check (Prettier)
run: npm run format:check
- name: Type check (tsc)
run: npx tsc -b
# Coverage thresholds are enforced inside vite.config.ts (test:coverage
# fails on backslide) — no separate gate step needed.
- name: Tests with coverage
run: npm run test:coverage
# End-to-end smoke tests. Unlike local (where compose stands up dev services),
# CI builds the PRODUCTION image and runs Playwright against it — so e2e
# exercises the real shipped artifact: the SPA served by Caddy with same-origin
# /api/* routing (Phase A). The prod entrypoint waits for the DB and runs
# migrations itself, so no separate migrate step is needed here.
#
# NOTE: this BUILDS the prod image to test against; it never PUSHES it. Image
# publishing stays tag-gated (see image.yml). Building-to-test on release/* is
# deliberate and does not cross the publish lock.
e2e:
runs-on: docker
container:
image: catthehacker/ubuntu:act-latest
needs: [backend, frontend]
steps:
- uses: https://data.forgejo.org/actions/checkout@v4
- name: Set up Docker Buildx
uses: https://data.forgejo.org/docker/setup-buildx-action@v3
- name: Build production image
uses: https://data.forgejo.org/docker/build-push-action@v5
with:
context: .
target: frankenphp_prod
build-args: |
NPM_VERSION=11.17.0
push: false
load: true
tags: buckets-prod:e2e
# Stand up postgres + the app as plain `docker run` containers on an
# explicitly-created network. We do NOT use a `services:` postgres + the
# `job.container.network` context here: that field is GitHub-specific and
# support in Forgejo's act_runner is unreliable, so an empty value would
# silently drop `app` onto the default bridge where it can't resolve the
# DB by hostname. Creating the network ourselves keeps name resolution
# under our control and portable across runner versions.
#
# Pre-clean first: if a prior run crashed mid-job on a shared Docker
# daemon, the leftover containers/network would make `create`/`run --name`
# fail on "name already in use". `|| true` keeps a clean first run quiet.
- name: Create the e2e network
run: |
docker rm -f app database 2>/dev/null || true
docker network rm e2e-net 2>/dev/null || true
docker network create e2e-net
# Playwright runs INSIDE this job container and targets the app by hostname
# (E2E_BASE_URL=http://app:80), so the job container must share e2e-net to
# resolve `app`. With a `services:` block the runner wires this up for us;
# since we manage the network ourselves, connect the job container — its
# $HOSTNAME is the container id act_runner assigned us (Docker's default
# hostname). If a future runner overrides the hostname this step fails
# LOUDLY (network connect errors) rather than silently — acceptable since
# the whole e2e job is unverified on the real runner until the first
# release/* push.
- name: Join the job container to the e2e network
run: docker network connect e2e-net "$HOSTNAME"
- name: Start the database
run: |
docker run -d --name database --network e2e-net \
-e POSTGRES_DB=buckets \
-e POSTGRES_USER=buckets \
-e POSTGRES_PASSWORD=buckets \
--health-cmd "pg_isready -U buckets -d buckets" \
--health-interval 5s --health-timeout 5s --health-retries 10 \
postgres:16-alpine
- name: Wait for the database to be healthy
run: |
for i in $(seq 1 30); do
if [ "$(docker inspect -f '{{.State.Health.Status}}' database)" = "healthy" ]; then
echo "Database is up."; exit 0
fi
echo "Waiting for database... ($i)"; sleep 2
done
echo "Database did not become healthy — dumping logs:"; docker logs database; exit 1
- name: Start the app
run: |
docker run -d --name app --network e2e-net \
-e SERVER_NAME=":80" \
-e APP_SECRET=ci-e2e-secret \
-e DATABASE_URL="postgresql://buckets:buckets@database:5432/buckets?serverVersion=16&charset=utf8" \
-e MERCURE_PUBLISHER_JWT_KEY="!ChangeThisMercureHubJWTSecretKey!" \
-e MERCURE_SUBSCRIBER_JWT_KEY="!ChangeThisMercureHubJWTSecretKey!" \
buckets-prod:e2e
# Wait for a FULLY healthy app, not just a reachable one: check the body
# for "db":"ok" (same precision as the compose healthcheck), so a 503 from
# an app that booted but can't reach the DB fails HERE with a clear "did
# not become healthy" message instead of confusingly mid-Playwright.
- name: Wait for the app to be healthy
run: |
for i in $(seq 1 60); do
if docker exec app php -r 'exit(str_contains((string) @file_get_contents("http://127.0.0.1:80/api/health"), "\"db\":\"ok\"") ? 0 : 1);' 2>/dev/null; then
echo "App is up."; exit 0
fi
echo "Waiting for app... ($i)"; sleep 2
done
echo "App did not become healthy — dumping logs:"; docker logs app; exit 1
# Node is preinstalled in the runner image (see frontend job note), but the
# Chromium binary is not — install it (with OS deps) before running.
- name: Install Playwright dependencies
working-directory: e2e
run: npm ci
- name: Install Playwright browser
working-directory: e2e
run: npx playwright install --with-deps chromium
- name: Run Playwright tests
working-directory: e2e
env:
# Target the app container by name on the shared job network.
E2E_BASE_URL: http://app:80
run: npm test
- name: Dump app logs on failure
if: failure()
run: docker logs app || true

View file

@ -0,0 +1,46 @@
name: Build and Push Production Image
# Builds the production image and pushes it to the Forgejo registry.
# TAG-PUSH ONLY: triggers exclusively on a v* tag (e.g. v0.3.0) — never on a
# branch push or PR. This matches the release flow: merge to main → CI green →
# cut a v* tag → that tag (and only that tag) builds + publishes the image.
on:
push:
tags: ['v*']
jobs:
build:
runs-on: docker
container:
image: catthehacker/ubuntu:act-latest
steps:
- uses: https://data.forgejo.org/actions/checkout@v4
- name: Set up Docker Buildx
uses: https://data.forgejo.org/docker/setup-buildx-action@v3
- name: Login to Forgejo Registry
uses: https://data.forgejo.org/docker/login-action@v3
with:
registry: forge.lvl0.xyz
# Forgejo mirrors GitHub's context naming, so `github.actor` resolves to
# the user who pushed the tag (there is no `forgejo.actor`).
username: ${{ github.actor }}
password: ${{ secrets.REGISTRY_TOKEN }}
- name: Build and push
uses: https://data.forgejo.org/docker/build-push-action@v5
with:
context: .
# The repo Dockerfile is multi-target; the production stage is
# frankenphp_prod (compiles the frontend in frontend_builder + bundles
# the dist into the FrankenPHP image).
target: frankenphp_prod
build-args: |
NPM_VERSION=11.17.0
platforms: linux/amd64
push: true
tags: |
forge.lvl0.xyz/lvl0/buckets:${{ github.ref_name }}
forge.lvl0.xyz/lvl0/buckets:latest

View file

@ -8,6 +8,23 @@ FROM dunglas/frankenphp:1-php8.4 AS frankenphp_upstream
# https://docs.docker.com/reference/compose-file/build/#target
# Frontend build: compile the React/Vite SPA to static assets (frontend/dist),
# copied into the prod image's web root below. npm pinned to match the project
# (NPM_VERSION — same single source as the dev images, passed as a build arg).
FROM node:22-alpine AS frontend_builder
ARG NPM_VERSION
WORKDIR /frontend
RUN npm install -g "npm@${NPM_VERSION}"
# Install deps from the lockfile first (cache-friendly), then build.
COPY --link frontend/package.json frontend/package-lock.json ./
RUN npm ci
COPY --link frontend/ ./
RUN npm run build
# Base FrankenPHP image
FROM frankenphp_upstream AS frankenphp_base
@ -98,6 +115,9 @@ RUN composer install --no-cache --prefer-dist --no-dev --no-autoloader --no-scri
# copy sources
COPY --link --exclude=frankenphp/ . ./
# Built SPA → a dedicated static root Caddy serves for all non-/api routes.
COPY --link --from=frontend_builder /frontend/dist ./frontend-dist
RUN <<-EOF
mkdir -p var/cache var/log var/share
composer dump-autoload --classmap-authoritative --no-dev
@ -117,8 +137,9 @@ RUN <<-'EOF'
apt-get update
apt-get install -y --no-install-recommends libtree
mkdir -p /tmp/libs
BINARIES=(frankenphp php file)
for target in $(printf '%s\n' "${BINARIES[@]}" | xargs -I{} which {}) \
# POSIX sh — podman runs heredocs under /bin/sh regardless of the SHELL
# directive, so no bash arrays here (space-separated list + word splitting).
for target in $(for b in frankenphp php file; do which "$b"; done) \
$(find "$(php -r 'echo ini_get("extension_dir");')" -maxdepth 2 -name "*.so"); do
libtree -pv "$target" 2>/dev/null | grep -oP '(?:── )\K/\S+(?= \[)' | while IFS= read -r lib; do
[ -f "$lib" ] && cp -n "$lib" /tmp/libs/

View file

@ -30,6 +30,30 @@ services:
extra_hosts:
# Ensure that host.docker.internal is correctly defined on Linux
- host.docker.internal:host-gateway
# Marks php healthy only once the backend can serve a request AND reach the
# DB (GET /api/health → {status:ok,db:ok}). Overrides the image's baked-in
# HEALTHCHECK (which only probes Caddy's :2019/metrics = "web server alive",
# no DB). This is observability only — nothing in the dev path *blocks* on it
# (the e2e race-prevention lives in the CI e2e job, which waits on
# /api/health before Playwright; gating `frontend` on it here only risks
# hanging `dev-up`).
# Use 127.0.0.1, NOT localhost: the container resolves localhost to ::1
# (IPv6) first, but FrankenPHP binds :80 on IPv4 → an IPv6 probe is refused
# and the container never goes healthy (same gotcha as #52). The probe is a
# SINGLE `php -r` expression: podman feeds the test args straight to the
# binary and does NOT preserve a multi-statement script (newlines collapse →
# parse error), so keep it to one expression — `str_contains` the body for
# the healthy marker, exit 0/1.
healthcheck:
test:
- CMD
- php
- -r
- exit(str_contains((string) @file_get_contents("http://127.0.0.1:80/api/health"), "\"db\":\"ok\"") ? 0 : 1);
interval: 10s
timeout: 5s
retries: 5
start_period: 30s
tty: true
# Standalone React/Vite SPA (dev only — not in compose.prod.yaml; see #33/#35).
@ -50,6 +74,11 @@ services:
- "${VITE_PORT:-5173}:5173"
command: sh -c "npm install && npm run dev -- --host 0.0.0.0 --port 5173"
depends_on:
# Start php first, but DON'T gate on its health — a not-yet-ready backend
# only means the Vite proxy 502s a few early /api calls until php boots,
# which self-heals. Gating on `service_healthy` here turned a flaky/slow
# php healthcheck into a `dev-up` hang. e2e (CI) does the real readiness
# wait on /api/health itself before driving the browser.
- php
environment:
# Reliable file-watching under the bind-mount.

View file

@ -44,6 +44,12 @@
# Disable Topics tracking if not enabled explicitly: https://github.com/jkarlin/topics
header ?Permissions-Policy "browsing-topics=()"
# Backend (Symfony) owns /api/* and Mercure; everything else is the SPA.
# `route` preserves declaration order so the backend matchers win before the
# SPA catch-all.
@backend path /api/* /.well-known/mercure*
handle @backend {
@phpRoute {
not path /.well-known/mercure*
not file {path}
@ -64,3 +70,13 @@
hide *.php
}
}
# Single-page app: serve built static assets, falling back to index.html so
# client-side routes (/login, /register, …) resolve. The dist is copied to
# /app/frontend-dist by the prod image build (see Dockerfile).
handle {
root * /app/frontend-dist
try_files {path} /index.html
file_server
}
}

1
frontend/.gitignore vendored
View file

@ -10,6 +10,7 @@ lerna-debug.log*
node_modules
dist
dist-ssr
coverage
*.local
# Editor directories and files

View file

@ -1,4 +1,5 @@
node_modules
dist
coverage
package-lock.json
*.tsbuildinfo

View file

@ -21,6 +21,7 @@
"@types/react": "^19.2.17",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^6.0.2",
"@vitest/coverage-v8": "^4.1.9",
"jsdom": "^29.1.1",
"msw": "^2.14.6",
"oxlint": "^1.69.0",
@ -105,17 +106,42 @@
"node": ">=6.9.0"
}
},
"node_modules/@babel/helper-string-parser": {
"version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz",
"integrity": "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@babel/helper-validator-identifier": {
"version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz",
"integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==",
"dev": true,
"license": "MIT",
"peer": true,
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@babel/parser": {
"version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.7.tgz",
"integrity": "sha512-hnORnjP/1P/zFEndoeX+n+t1RwWRJiJpM/jO7FW32Kn9r5+sJB2JWOdYo4L6k78j15eCwY3Gm/7364B1EMwtNg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@babel/types": "^7.29.7"
},
"bin": {
"parser": "bin/babel-parser.js"
},
"engines": {
"node": ">=6.0.0"
}
},
"node_modules/@babel/runtime": {
"version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.7.tgz",
@ -126,6 +152,30 @@
"node": ">=6.9.0"
}
},
"node_modules/@babel/types": {
"version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.7.tgz",
"integrity": "sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@babel/helper-string-parser": "^7.29.7",
"@babel/helper-validator-identifier": "^7.29.7"
},
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@bcoe/v8-coverage": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/@bcoe/v8-coverage/-/v8-coverage-1.0.2.tgz",
"integrity": "sha512-6zABk/ECA/QYSCQ1NGiVwwbQerUCZ+TQbp64Q3AgmfNvurHH0j8TtXa1qbShXA6qqkpAj4V5W8pP6mLe1mcMqA==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=18"
}
},
"node_modules/@bramus/specificity": {
"version": "2.4.2",
"resolved": "https://registry.npmjs.org/@bramus/specificity/-/specificity-2.4.2.tgz",
@ -1620,6 +1670,37 @@
}
}
},
"node_modules/@vitest/coverage-v8": {
"version": "4.1.9",
"resolved": "https://registry.npmjs.org/@vitest/coverage-v8/-/coverage-v8-4.1.9.tgz",
"integrity": "sha512-G9/lgqibheLVBDRuya45EbsEXTYcWoSG+TLg7i2axuzx0Eq62eXn+aWXyaVdV5vKvFSWd6ywcX8hA7la9Pvu8g==",
"dev": true,
"license": "MIT",
"dependencies": {
"@bcoe/v8-coverage": "^1.0.2",
"@vitest/utils": "4.1.9",
"ast-v8-to-istanbul": "^1.0.0",
"istanbul-lib-coverage": "^3.2.2",
"istanbul-lib-report": "^3.0.1",
"istanbul-reports": "^3.2.0",
"magicast": "^0.5.2",
"obug": "^2.1.1",
"std-env": "^4.0.0-rc.1",
"tinyrainbow": "^3.1.0"
},
"funding": {
"url": "https://opencollective.com/vitest"
},
"peerDependencies": {
"@vitest/browser": "4.1.9",
"vitest": "4.1.9"
},
"peerDependenciesMeta": {
"@vitest/browser": {
"optional": true
}
}
},
"node_modules/@vitest/expect": {
"version": "4.1.9",
"resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.9.tgz",
@ -1777,6 +1858,25 @@
"node": ">=12"
}
},
"node_modules/ast-v8-to-istanbul": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/ast-v8-to-istanbul/-/ast-v8-to-istanbul-1.0.4.tgz",
"integrity": "sha512-0bC0/4bTSrnwdhU3IsZDwEdojvuPrSg59OYZfKsLRtJZ0u8VBx9DebfqqG8bRdCC0I7vjgxmPi41P0lpkhJHtA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@jridgewell/trace-mapping": "^0.3.31",
"estree-walker": "^3.0.3",
"js-tokens": "^10.0.0"
}
},
"node_modules/ast-v8-to-istanbul/node_modules/js-tokens": {
"version": "10.0.0",
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-10.0.0.tgz",
"integrity": "sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q==",
"dev": true,
"license": "MIT"
},
"node_modules/bidi-js": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/bidi-js/-/bidi-js-1.0.3.tgz",
@ -2104,6 +2204,16 @@
"node": "^12.22.0 || ^14.16.0 || ^16.0.0 || >=17.0.0"
}
},
"node_modules/has-flag": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",
"integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/headers-polyfill": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/headers-polyfill/-/headers-polyfill-5.0.1.tgz",
@ -2128,6 +2238,13 @@
"node": "^20.19.0 || ^22.12.0 || >=24.0.0"
}
},
"node_modules/html-escaper": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz",
"integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==",
"dev": true,
"license": "MIT"
},
"node_modules/indent-string": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/indent-string/-/indent-string-4.0.0.tgz",
@ -2162,6 +2279,45 @@
"dev": true,
"license": "MIT"
},
"node_modules/istanbul-lib-coverage": {
"version": "3.2.2",
"resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.2.tgz",
"integrity": "sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==",
"dev": true,
"license": "BSD-3-Clause",
"engines": {
"node": ">=8"
}
},
"node_modules/istanbul-lib-report": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.1.tgz",
"integrity": "sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==",
"dev": true,
"license": "BSD-3-Clause",
"dependencies": {
"istanbul-lib-coverage": "^3.0.0",
"make-dir": "^4.0.0",
"supports-color": "^7.1.0"
},
"engines": {
"node": ">=10"
}
},
"node_modules/istanbul-reports": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.2.0.tgz",
"integrity": "sha512-HGYWWS/ehqTV3xN10i23tkPkpH46MLCIMFNCaaKNavAXTF1RkqxawEPtnjnGZ6XKSInBKkiOA5BKS+aZiY3AvA==",
"dev": true,
"license": "BSD-3-Clause",
"dependencies": {
"html-escaper": "^2.0.0",
"istanbul-lib-report": "^3.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/jiti": {
"version": "2.7.0",
"resolved": "https://registry.npmjs.org/jiti/-/jiti-2.7.0.tgz",
@ -2513,6 +2669,34 @@
"@jridgewell/sourcemap-codec": "^1.5.5"
}
},
"node_modules/magicast": {
"version": "0.5.3",
"resolved": "https://registry.npmjs.org/magicast/-/magicast-0.5.3.tgz",
"integrity": "sha512-pVKE4UdSQ7DvHzivsCIFx2BJn1mHG6KsyrFcaxFx6tONdneEuThrDx0Cj3AMg58KyN4pzYT+LHOotxDQDjNvkw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@babel/parser": "^7.29.3",
"@babel/types": "^7.29.0",
"source-map-js": "^1.2.1"
}
},
"node_modules/make-dir": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/make-dir/-/make-dir-4.0.0.tgz",
"integrity": "sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==",
"dev": true,
"license": "MIT",
"dependencies": {
"semver": "^7.5.3"
},
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/mdn-data": {
"version": "2.27.1",
"resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.27.1.tgz",
@ -2936,6 +3120,19 @@
"integrity": "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==",
"license": "MIT"
},
"node_modules/semver": {
"version": "7.8.5",
"resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",
"integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",
"dev": true,
"license": "ISC",
"bin": {
"semver": "bin/semver.js"
},
"engines": {
"node": ">=10"
}
},
"node_modules/set-cookie-parser": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-3.1.1.tgz",
@ -3045,6 +3242,19 @@
"node": ">=8"
}
},
"node_modules/supports-color": {
"version": "7.2.0",
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",
"integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==",
"dev": true,
"license": "MIT",
"dependencies": {
"has-flag": "^4.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/symbol-tree": {
"version": "3.2.4",
"resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz",

View file

@ -11,6 +11,7 @@
"format:check": "prettier --check .",
"test": "vitest run",
"test:watch": "vitest",
"test:coverage": "vitest run --coverage",
"preview": "vite preview"
},
"dependencies": {
@ -27,6 +28,7 @@
"@types/react": "^19.2.17",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^6.0.2",
"@vitest/coverage-v8": "^4.1.9",
"jsdom": "^29.1.1",
"msw": "^2.14.6",
"oxlint": "^1.69.0",

View file

@ -1,7 +1,7 @@
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { delay, http, HttpResponse } from 'msw'
import { describe, expect, it } from 'vitest'
import { describe, expect, it, vi } from 'vitest'
import { server } from '../test/server'
import { AuthProvider } from './AuthProvider'
import { useAuth } from './useAuth'
@ -59,6 +59,29 @@ describe('AuthProvider', () => {
expect(screen.getByTestId('user-email')).toHaveTextContent('')
})
it('treats a non-401 probe failure as unauthenticated and logs it', async () => {
const spy = vi.spyOn(console, 'error').mockImplementation(() => {})
server.use(
http.get('http://localhost/api/me', () =>
HttpResponse.json({ message: 'boom' }, { status: 500 }),
),
)
render(
<AuthProvider>
<AuthProbe />
</AuthProvider>,
)
// A backend outage shouldn't strand the app in `loading` — it resolves to
// unauthenticated, but unlike a 401 it's logged (it's not a normal "no
// session" answer).
expect(await screen.findByText('unauthenticated')).toBeInTheDocument()
expect(spy).toHaveBeenCalled()
spy.mockRestore()
})
it('does not flash a resolved status while the auth probe is loading', async () => {
server.use(
http.get('http://localhost/api/me', async () => {

View file

@ -93,6 +93,32 @@ describe('LoginPage', () => {
expect(screen.queryByText('SCENARIOS')).not.toBeInTheDocument()
})
it('shows a generic error for a non-401 failure', async () => {
server.use(
http.get('http://localhost/api/me', () =>
HttpResponse.json({ message: 'unauthorized' }, { status: 401 }),
),
http.post('http://localhost/api/login', () =>
HttpResponse.json({ message: 'boom' }, { status: 500 }),
),
)
const user = userEvent.setup()
render(
<MemoryRouter initialEntries={['/login']}>
<AppWithLogin />
</MemoryRouter>,
)
await user.type(await screen.findByLabelText(/email/i), 'a@b.com')
await user.type(screen.getByLabelText(/password/i), 'correct-password')
await user.click(screen.getByRole('button', { name: /log in/i }))
expect(await screen.findByText(/login failed/i)).toBeInTheDocument()
expect(screen.queryByText('SCENARIOS')).not.toBeInTheDocument()
})
it('disables the submit button while the request is in flight', async () => {
server.use(
http.get('http://localhost/api/me', () =>

View file

@ -137,6 +137,32 @@ describe('RegisterPage', () => {
expect(screen.queryByText('LOGIN')).not.toBeInTheDocument()
})
it('shows a generic error for a non-422 failure', async () => {
server.use(
http.get('http://localhost/api/me', () =>
HttpResponse.json({ message: 'unauthorized' }, { status: 401 }),
),
http.post('http://localhost/api/register', () =>
HttpResponse.json({ message: 'boom' }, { status: 500 }),
),
)
const user = userEvent.setup()
render(
<MemoryRouter initialEntries={['/register']}>
<AppWithRegister />
</MemoryRouter>,
)
await user.type(await screen.findByLabelText(/email/i), 'new@example.com')
await user.type(screen.getByLabelText(/password/i), 'correct-horse-battery')
await user.click(screen.getByRole('button', { name: /register/i }))
expect(await screen.findByText(/registration failed/i)).toBeInTheDocument()
expect(screen.queryByText('LOGIN')).not.toBeInTheDocument()
})
it('disables the submit button while the request is in flight', async () => {
server.use(
http.get('http://localhost/api/me', () =>

View file

@ -0,0 +1,16 @@
import { renderHook } from '@testing-library/react'
import { describe, expect, it, vi } from 'vitest'
import { useAuth } from './useAuth'
describe('useAuth', () => {
it('throws when used outside an AuthProvider', () => {
// Silence the expected React error-boundary console noise for this throw.
const spy = vi.spyOn(console, 'error').mockImplementation(() => {})
expect(() => renderHook(() => useAuth())).toThrow(
/must be used within an AuthProvider/i,
)
spy.mockRestore()
})
})

View file

@ -0,0 +1,40 @@
import { render } from '@testing-library/react'
import { describe, expect, it } from 'vitest'
import DigitalProgressBar from './DigitalProgressBar'
describe('DigitalProgressBar', () => {
it('fills all three color zones when full (red, amber, green)', () => {
const { container } = render(
<DigitalProgressBar current={1000} capacity={1000} />,
)
// A full bar fills every index, so all three zone classes appear.
expect(container.querySelectorAll('.bg-chart-1').length).toBeGreaterThan(0)
expect(container.querySelectorAll('.bg-chart-2').length).toBeGreaterThan(0)
expect(container.querySelectorAll('.bg-chart-3').length).toBeGreaterThan(0)
})
it('renders 20 bars regardless of fill level', () => {
const { container } = render(
<DigitalProgressBar current={250} capacity={1000} />,
)
// The grid container's direct children are the 20 bars.
const grid = container.firstElementChild
expect(grid?.children.length).toBe(20)
// Partial fill leaves the rest as dimmed empties.
expect(
container.querySelectorAll('.bg-chart-1\\/10').length,
).toBeGreaterThan(0)
})
it('shows no filled bars when capacity is zero (guards divide-by-zero)', () => {
const { container } = render(
<DigitalProgressBar current={500} capacity={0} />,
)
// capacity<=0 → filledBars 0 → no zone-colored bars, all empties.
expect(container.querySelectorAll('.bg-chart-2').length).toBe(0)
expect(container.querySelectorAll('.bg-chart-3').length).toBe(0)
})
})

View file

@ -12,14 +12,28 @@ const BAR_COUNT = 20
* both reference the same source so they can't drift. `upTo` is the exclusive
* upper bound of each zone.
*/
const ZONES = [
interface Zone {
upTo: number
token: string
className: string
}
// The green zone is also the guaranteed fallback for any index at/above the
// last threshold, so it's named separately to keep the return type non-optional.
const GREEN_ZONE: Zone = {
upTo: BAR_COUNT,
token: 'var(--chart-3)',
className: 'bg-chart-3',
}
const ZONES: readonly Zone[] = [
{ upTo: 10, token: 'var(--chart-1)', className: 'bg-chart-1' },
{ upTo: 18, token: 'var(--chart-2)', className: 'bg-chart-2' },
{ upTo: BAR_COUNT, token: 'var(--chart-3)', className: 'bg-chart-3' },
] as const
GREEN_ZONE,
]
function getZone(index: number) {
return ZONES.find((zone) => index < zone.upTo) ?? ZONES[ZONES.length - 1]
function getZone(index: number): Zone {
return ZONES.find((zone) => index < zone.upTo) ?? GREEN_ZONE
}
export default function DigitalProgressBar({

View file

@ -36,3 +36,77 @@ describe('api.postJson', () => {
expect((error as ApiError).status).toBe(401)
})
})
describe('api path guard', () => {
it('throws if a path already includes the /api prefix', async () => {
// Callers pass `/login`, not `/api/login` — the client prepends BASE.
await expect(api.get('/api/login')).rejects.toThrow(/must not include/i)
})
})
describe('api.get', () => {
it('sends Accept: application/ld+json and returns the parsed body', async () => {
let accept: string | null = null
server.use(
http.get('http://localhost/api/scenarios', ({ request }) => {
accept = request.headers.get('Accept')
return HttpResponse.json({ member: [] })
}),
)
const result = await api.get<{ member: unknown[] }>('/scenarios')
expect(accept).toBe('application/ld+json')
expect(result).toEqual({ member: [] })
})
})
describe('api.post', () => {
it('sends Content-Type: application/ld+json (API Platform write format)', async () => {
let contentType: string | null = null
server.use(
http.post('http://localhost/api/buckets', async ({ request }) => {
contentType = request.headers.get('Content-Type')
return HttpResponse.json({ '@id': '/api/buckets/1' }, { status: 201 })
}),
)
await api.post('/buckets', { name: 'Rent' })
expect(contentType).toBe('application/ld+json')
})
})
describe('api.patch', () => {
it('sends Content-Type: application/merge-patch+json', async () => {
let contentType: string | null = null
server.use(
http.patch('http://localhost/api/buckets/1', async ({ request }) => {
contentType = request.headers.get('Content-Type')
return HttpResponse.json({ '@id': '/api/buckets/1' })
}),
)
await api.patch('/buckets/1', { name: 'Rent' })
expect(contentType).toBe('application/merge-patch+json')
})
})
describe('api.delete', () => {
it('resolves to undefined on a 204 No Content', async () => {
server.use(
http.delete(
'http://localhost/api/buckets/1',
() => new HttpResponse(null, { status: 204 }),
),
)
const result = await api.delete('/buckets/1')
expect(result).toBeUndefined()
})
})

View file

@ -16,6 +16,8 @@
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUncheckedIndexedAccess": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,

View file

@ -14,6 +14,8 @@
"noEmit": true,
/* Linting */
"strict": true,
"noUncheckedIndexedAccess": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,

View file

@ -15,6 +15,26 @@ export default defineConfig({
setupFiles: ['./src/test/setup.ts'],
// Keep the future Playwright e2e suite out of the Vitest run.
exclude: ['**/node_modules/**', '**/dist/**', 'e2e/**'],
coverage: {
provider: 'v8',
include: ['src/**/*.{ts,tsx}'],
exclude: [
'src/main.tsx', // app mount point — no logic to test
'src/**/*.test.{ts,tsx}', // the tests themselves
'src/test/**', // test harness (MSW server/setup)
'src/vite-env.d.ts',
'src/types/**', // type-only declarations
],
// Floors set a touch below current (≈98% lines) to catch regressions
// without being brittle. Raise as coverage climbs; the goal is "no silent
// backslide", not gaming a round number.
thresholds: {
statements: 95,
branches: 90,
functions: 95,
lines: 95,
},
},
},
server: {
host: '0.0.0.0',

View file

@ -110,6 +110,23 @@ pkgs.mkShell {
$COMPOSE exec -e XDEBUG_MODE=coverage php php bin/phpunit --coverage-text --colors=never "$@"
}
dev-coverage-check() {
# Backend coverage gate: PHPUnit 13 has no native "fail under N%" option,
# so run the report and fail if the Lines % drops below the floor (95%).
# Floor set a touch below current (~99.7%) to catch regressions, not game.
local floor=95
local out pct
out=$($COMPOSE exec -e XDEBUG_MODE=coverage php php bin/phpunit --coverage-text --colors=never "$@")
echo "$out"
pct=$(echo "$out" | grep -oE 'Lines:[[:space:]]+[0-9]+\.[0-9]+%' | grep -oE '[0-9]+\.[0-9]+' | head -1)
if [ -z "$pct" ]; then echo " could not parse coverage %"; return 1; fi
# integer compare (drop decimals) against the floor
if [ "''${pct%.*}" -lt "$floor" ]; then
echo " backend line coverage $pct% is below the $floor% floor"; return 1
fi
echo " backend line coverage $pct% (floor $floor%)"
}
dev-stan() {
# Warm the dev cache so phpstan-symfony can read the compiled container, then analyse.
$COMPOSE exec php php bin/console cache:warmup --quiet
@ -134,6 +151,11 @@ pkgs.mkShell {
$COMPOSE exec frontend npm test "$@"
}
dev-fe-coverage() {
# Vitest run with the v8 coverage report.
$COMPOSE exec frontend npm run test:coverage "$@"
}
dev-fe-test-watch() {
$COMPOSE exec frontend npm run test:watch "$@"
}
@ -179,13 +201,10 @@ pkgs.mkShell {
dev-check-all() {
# Thorough gate: everything in dev-check, but with COVERAGE instead of the
# plain test runs, plus the Playwright e2e. Slow; needs the stack up.
# NOTE: frontend coverage (dev-fe-coverage) is not wired yet — added in #62
# alongside the @vitest/coverage-v8 setup; until then this runs the plain
# frontend test suite for the frontend leg.
echo " backend: coverage" && dev-coverage \
echo " backend: coverage" && dev-coverage-check \
&& echo " backend: phpstan" && dev-stan \
&& echo " backend: cs" && dev-cs \
&& echo " frontend: tests (coverage pending #62)" && dev-fe-test \
&& echo " frontend: coverage" && dev-fe-coverage \
&& echo " frontend: lint" && dev-fe-lint \
&& echo " frontend: cs" && dev-fe-cs \
&& echo " frontend: build" && dev-fe-build \
@ -291,6 +310,7 @@ pkgs.mkShell {
echo " dev-fe-cs [args] Check frontend formatting (Prettier)"
echo " dev-fe-cs-fix Apply frontend formatting"
echo " dev-fe-build Build the frontend (tsc + vite build)"
echo " dev-fe-coverage Frontend Vitest run with coverage report"
echo " dev-e2e [args] Run Playwright e2e smoke suite (container)"
echo " dev-check Fast gate: all back+front tests/stan/cs/build"
echo " dev-check-all Thorough gate: dev-check + coverage + e2e"

View file

@ -0,0 +1,37 @@
<?php
namespace App\Controller;
use Doctrine\DBAL\Connection;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Attribute\Route;
final class HealthController extends AbstractController
{
/**
* Liveness/readiness probe public, used by container healthchecks and CI.
* Returns 200 when the app is up and the database is reachable, 503 if the
* DB ping fails.
*/
#[Route('/api/health', name: 'api_health', methods: ['GET'])]
public function health(Connection $connection, LoggerInterface $logger): JsonResponse
{
try {
$connection->executeQuery('SELECT 1');
} catch (\Throwable $e) {
// The 503 body stays generic (no leak), but log the cause so a
// flapping health check is diagnosable from app logs, not just from
// the healthcheck's own retry count.
$logger->error('Health check failed: database unreachable', ['exception' => $e]);
return $this->json(
['status' => 'error', 'db' => 'unreachable'],
JsonResponse::HTTP_SERVICE_UNAVAILABLE,
);
}
return $this->json(['status' => 'ok', 'db' => 'ok']);
}
}

View file

@ -11,6 +11,12 @@ class Kernel extends BaseKernel
/**
* @return list<string> An array of allowed values for APP_ENV
*
* Called by the framework via reflection (env validation), never by app
* code same reason it's PHPStan-ignored. Excluded from coverage rather
* than exercised by a contrived test.
*
* @codeCoverageIgnore
*/
private function getAllowedEnvs(): array
{

View file

@ -21,6 +21,12 @@ class UserRepository extends ServiceEntityRepository implements PasswordUpgrader
/**
* Used to upgrade (rehash) the user's password automatically over time.
*
* Symfony maker-generated PasswordUpgraderInterface boilerplate with no
* app-specific logic excluded from coverage rather than tested with a
* contrived case.
*
* @codeCoverageIgnore
*/
public function upgradePassword(PasswordAuthenticatedUserInterface $user, string $newHashedPassword): void
{

View file

@ -0,0 +1,86 @@
<?php
namespace App\Tests\Doctrine;
use ApiPlatform\Doctrine\Orm\Util\QueryNameGenerator;
use App\Doctrine\ScenarioOwnerExtension;
use App\Entity\Scenario;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use PHPUnit\Framework\MockObject\Stub;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Bundle\SecurityBundle\Security;
/**
* Unit-covers the AbstractOwnerScopeExtension base via its simplest concrete
* subclass (Scenario owns the `owner` column directly). The HTTP-level
* functional tests always run authenticated against their own resource, so the
* base's two early-return guards (wrong resource class, anonymous user) are only
* reachable here in isolation.
*/
final class ScenarioOwnerExtensionTest extends KernelTestCase
{
private function queryBuilder(): \Doctrine\ORM\QueryBuilder
{
self::bootKernel();
/** @var EntityManagerInterface $em */
$em = self::getContainer()->get(EntityManagerInterface::class);
return $em->createQueryBuilder()
->select('s')
->from(Scenario::class, 's');
}
private function extensionWithUser(?object $user): ScenarioOwnerExtension
{
/** @var Security&Stub $security */
$security = $this->createStub(Security::class);
$security->method('getUser')->willReturn($user);
return new ScenarioOwnerExtension($security);
}
public function testAddsOwnerFilterForAnAuthenticatedUserOnItsOwnResource(): void
{
$qb = $this->queryBuilder();
$extension = $this->extensionWithUser(new User());
$extension->applyToCollection($qb, new QueryNameGenerator(), Scenario::class);
self::assertStringContainsStringIgnoringCase(
'.owner = :',
(string) $qb->getDQL(),
'An authenticated read of its own resource must be scoped to the owner.',
);
}
public function testDoesNothingForAResourceItDoesNotGuard(): void
{
$qb = $this->queryBuilder();
$extension = $this->extensionWithUser(new User());
// Bucket is guarded by a different extension — this one must no-op.
$extension->applyToCollection($qb, new QueryNameGenerator(), \App\Entity\Bucket::class);
self::assertStringNotContainsString(
'owner',
(string) $qb->getDQL(),
'The extension must not touch queries for a resource it does not guard.',
);
}
public function testDoesNothingForAnAnonymousRequest(): void
{
$qb = $this->queryBuilder();
$extension = $this->extensionWithUser(null);
$extension->applyToItem($qb, new QueryNameGenerator(), Scenario::class, ['id' => 'x']);
self::assertStringNotContainsString(
'owner',
(string) $qb->getDQL(),
'With no authenticated user the extension must not add an owner filter '
.'(it is a fail-safe behind the resource-level ROLE_USER wall).',
);
}
}

View file

@ -0,0 +1,57 @@
<?php
namespace App\Tests\Functional;
use Doctrine\DBAL\Connection;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
final class HealthApiTest extends WebTestCase
{
public function testItReportsHealthyWithoutAuthentication(): void
{
$client = static::createClient();
$client->request('GET', '/api/health');
$response = $client->getResponse();
self::assertSame(
200,
$response->getStatusCode(),
'GET /api/health must return 200 and require no authentication.',
);
$body = json_decode((string) $response->getContent(), true);
self::assertIsArray($body);
self::assertSame('ok', $body['status'] ?? null);
self::assertSame('ok', $body['db'] ?? null);
}
public function testItReportsUnhealthyWhenTheDatabaseIsUnreachable(): void
{
$client = static::createClient();
// Swap the DBAL connection for a stub that fails the ping, simulating an
// unreachable database without touching the real one. Overriding the
// bare Connection::class id is what the controller actually receives:
// autowiring keys by FQCN, so the `Connection $connection` parameter
// resolves to this same service.
$connection = $this->createStub(Connection::class);
$connection->method('executeQuery')
->willThrowException(new \RuntimeException('connection refused'));
static::getContainer()->set(Connection::class, $connection);
$client->request('GET', '/api/health');
$response = $client->getResponse();
self::assertSame(503, $response->getStatusCode());
$body = json_decode((string) $response->getContent(), true);
self::assertIsArray($body);
self::assertSame('error', $body['status'] ?? null);
self::assertSame('unreachable', $body['db'] ?? null);
}
}

View file

@ -8,7 +8,9 @@ use App\Enum\BucketAllocationType;
use App\Enum\BucketType;
use App\Validator\BufferOnlyForFixedLimit;
use App\Validator\BufferOnlyForFixedLimitValidator;
use App\Validator\SingleOverflowPerScenario;
use Symfony\Component\Validator\ConstraintValidatorInterface;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Test\ConstraintValidatorTestCase;
/**
@ -21,6 +23,22 @@ final class BufferOnlyForFixedLimitValidatorTest extends ConstraintValidatorTest
return new BufferOnlyForFixedLimitValidator();
}
public function testThrowsWhenGivenTheWrongConstraintType(): void
{
$bucket = $this->makeBucket(BucketAllocationType::FIXED_LIMIT, '0.00');
$this->expectException(UnexpectedTypeException::class);
$this->validator->validate($bucket, new SingleOverflowPerScenario());
}
public function testNonBucketValueIsIgnored(): void
{
$this->validator->validate('not a bucket', new BufferOnlyForFixedLimit());
$this->assertNoViolation();
}
public function testFixedLimitWithNonZeroBufferIsValid(): void
{
$bucket = $this->makeBucket(BucketAllocationType::FIXED_LIMIT, '1.50');

View file

@ -8,7 +8,9 @@ use App\Enum\BucketAllocationType;
use App\Enum\BucketType;
use App\Validator\CompatibleAllocationType;
use App\Validator\CompatibleAllocationTypeValidator;
use App\Validator\SingleOverflowPerScenario;
use Symfony\Component\Validator\ConstraintValidatorInterface;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Test\ConstraintValidatorTestCase;
/**
@ -21,6 +23,22 @@ final class CompatibleAllocationTypeValidatorTest extends ConstraintValidatorTes
return new CompatibleAllocationTypeValidator();
}
public function testThrowsWhenGivenTheWrongConstraintType(): void
{
$bucket = $this->makeBucket(BucketType::OVERFLOW, BucketAllocationType::UNLIMITED);
$this->expectException(UnexpectedTypeException::class);
$this->validator->validate($bucket, new SingleOverflowPerScenario());
}
public function testNonBucketValueIsIgnored(): void
{
$this->validator->validate('not a bucket', new CompatibleAllocationType());
$this->assertNoViolation();
}
public function testOverflowWithUnlimitedIsValid(): void
{
$bucket = $this->makeBucket(BucketType::OVERFLOW, BucketAllocationType::UNLIMITED);

View file

@ -7,10 +7,12 @@ use App\Entity\Scenario;
use App\Enum\BucketAllocationType;
use App\Enum\BucketType;
use App\Repository\BucketRepository;
use App\Validator\BufferOnlyForFixedLimit;
use App\Validator\SingleOverflowPerScenario;
use App\Validator\SingleOverflowPerScenarioValidator;
use PHPUnit\Framework\MockObject\Stub;
use Symfony\Component\Validator\ConstraintValidatorInterface;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Test\ConstraintValidatorTestCase;
/**
@ -27,6 +29,22 @@ final class SingleOverflowPerScenarioValidatorTest extends ConstraintValidatorTe
return new SingleOverflowPerScenarioValidator($this->bucketRepository);
}
public function testThrowsWhenGivenTheWrongConstraintType(): void
{
$bucket = $this->makeBucket(BucketType::OVERFLOW);
$this->expectException(UnexpectedTypeException::class);
$this->validator->validate($bucket, new BufferOnlyForFixedLimit());
}
public function testNonBucketValueIsIgnored(): void
{
$this->validator->validate('not a bucket', new SingleOverflowPerScenario());
$this->assertNoViolation();
}
public function testOverflowBucketIsValidWhenRepositoryReportsNoOtherOverflowBuckets(): void
{
$this->bucketRepository