# Reference: Testing

How BikeBuddy instantiates the [test strategy playbook](../../TEST_STRATEGY.md):
which layer owns what, which tools and thresholds are in force, and which risks
are covered, partly covered, or not covered yet. The playbook stays generic;
real paths, numbers and issues live here. Commands are in the
[Developer guide](../how-to/developer-guide.md); load testing has its own
[guide](../how-to/load-testing.md).

## The shape

| Playbook piece            | BikeBuddy                                                                                                                               |
| ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| Static frontend           | `frontend/src/` on GitHub Pages under `/BikeBuddy/`, service worker `sw.js`                                                             |
| Serverless API            | Azure Functions (Flex Consumption), one handler per folder in `functions/src/`                                                          |
| Auth middleware           | `functions/src/middleware/authMiddleware.js`, Entra External ID; `SKIP_AUTH` dev bypass, `ENTRA_OIDC_METADATA_URL` loopback test issuer |
| Partition-scoped read     | `functions/src/lib/ownedTour.js`: reads the tour from the caller's `/userId` partition                                                  |
| Document DB               | Cosmos DB: `tours` and `tracks` by `/userId`, `users` by `/id`, `deletions` queue                                                       |
| Blob store + signed URLs  | Azure Blob, `${userId}/` prefixes, read-only SAS from `functions/src/lib/blobStorage.js`                                                |
| Out-of-band deletion job  | `.github/workflows/process-deletions.yml` → `functions/scripts/process-deletions.js`                                                    |
| Local stack (integration) | Cosmos emulator + Azurite (`.github/actions/start-local-stack`); the suite starts its own `func` host on :7072 with a local OIDC issuer |

## Who owns what

| Behaviour                                                                  | Layer                                    | Where                                                                                                                                                                                                                                   |
| -------------------------------------------------------------------------- | ---------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Token validation (issuer, audience, alg, expiry, key id, scope)            | Middleware unit, test-signed             | `functions/src/middleware/authMiddleware.test.js`; `test/unit/tokens.test.js` runs every harness token through `authenticate()`; `test/unit/localIssuer.test.js` does it over HTTP against the local issuer                             |
| Status paths, write ordering, 404 outside the caller's tour                | Handler unit                             | `functions/src/<Name>/index.test.js`, handlers called with injected `auth` and containers                                                                                                                                               |
| GPX parsing, simplification, validation, EXIF GPS                          | Unit + property + mutation               | `functions/src/lib/*.test.js`, `*.property.test.js` (fast-check)                                                                                                                                                                        |
| Frontend pure logic (URL state, stats, upload queue, SAS cache)            | Unit + property + mutation               | `frontend/test/*.test.js`, `frontend/test/properties.test.js`                                                                                                                                                                           |
| HTTP lifecycle through the real host                                       | Integration                              | `functions/test/integration/*.test.js` against Cosmos emulator + Azurite + `func`, one fresh identity per file                                                                                                                          |
| Authorization: every endpoint × owner, other user, 10 rejected credentials | Integration, two identities, real tokens | `authorization-tokens.test.js`, `authorization-isolation.test.js`, `account-deletion.test.js`, `signed-urls.test.js`; the route list `endpoints.js` is checked against every `app.http()` registration by `test/unit/endpoints.test.js` |
| Deletion job, backfills, operator scripts                                  | Unit + mutation                          | `functions/scripts/lib/*.test.js` with fakes (dry run writes nothing; only GUIDs reach Graph)                                                                                                                                           |
| Hot-query shape and payload bounds                                         | Integration (cost guards)                | `query-cost.test.js` (single partition, bounded pages), `map-budget.test.js` (point and byte budget)                                                                                                                                    |
| Base path, theme, URL state, empty and error states                        | E2E static, API mocked                   | `e2e/tests/` on `staticTest` from `e2e/fixtures/api-mocks.ts` (answers from `api-responses.ts`, held to the handlers)                                                                                                                   |
| Journeys: upload, edit, photos, delete, account, language                  | E2E full stack                           | `e2e/tests-fullstack/` on `fullstackTest`: seeds through the API (`seed.ts`), checks blobs and documents in `store.ts`; page objects in `e2e/pages/` reached through `on(page)`                                                         |
| Accessibility                                                              | Runtime, in both E2E suites              | `e2e/axe.ts` via `on(page).a11y.check()`; `frontend/test/contrast.test.js` pins colour-token contrast                                                                                                                                   |
| Frontend lab performance                                                   | Lighthouse CI                            | `e2e/lighthouse/lighthouserc.signed-out.json`, `lighthouserc.signed-in.json`                                                                                                                                                            |
| Headers, CORS, error disclosure                                            | DAST, passive                            | `scripts/quality/zap.sh`, rules in `.zap/rules-frontend.tsv`, `.zap/rules-api.tsv`, API from `.zap/openapi.yaml`                                                                                                                        |
| Latency and backend statistics                                             | Manual load test                         | `load/` (k6), `.github/workflows/k6-load-test.yml` (manual only)                                                                                                                                                                        |
| Module boundaries, dead code, SAST, smells, IaC, workflows                 | Static analysis                          | dependency-cruiser, Knip, OpenGrep, ESLint + SonarJS, TFLint + Trivy, `tofu test` (mock providers), zizmor + actionlint                                                                                                                 |

Locators live only in the page objects: element ids for singletons
(`#btn-upload`), `data-testid` for repeated rows, tiles and pins, and role
locators only for Leaflet's own controls. The app exposes state for waiting on:
`#map[data-tiles]`, `#map[data-zoom]`, `#map[data-zooming]`,
`#tour-list[data-click-guard]` and `aria-current` on the open row. No spec
sleeps; the one timed input is the long-press hold (the app's 500 ms plus a
stated margin). Every test fails on a `pageerror` or `console.error` unless it
allows that error by pattern (`allowedConsoleErrors`), and both suites answer
basemap tiles with a blank image, so no test reaches the network. Both block
service workers, so every
request goes through the routes. Neither suite retries.

## Tools and thresholds

Numbers live in the files named here; this table only points at them. Raised
when a change makes room, never lowered.

| Gate                   | Tool                | Threshold                                                                                                                                             | Source                                                                            |
| ---------------------- | ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- |
| Unit coverage          | Vitest (v8)         | 99 % global (statements, branches, functions, lines) per package; 100 % per file on the mutation list; no `autoUpdate`                                | `functions/vitest.config.js`, `frontend/vitest.config.js`                         |
| Mutation scope + floor | Stryker             | 41 functions modules (incl. `scripts/lib/`, the integration guard and token minter), 21 frontend modules; the same list sets the 100 % per-file floor | `mutation-targets.mjs`                                                            |
| Mutation score         | Stryker             | break 99 % for both packages (measured 100 % in both)                                                                                                 | `functions/stryker.config.mjs`, `frontend/stryker.config.mjs`                     |
| E2E coverage           | V8 via monocart     | static 55 % lines / 47 % functions; full stack 73 % / 72 %                                                                                            | `e2e/coverage.ts`                                                                 |
| Property tests         | fast-check          | 200 runs per property; replay with `FC_SEED` / `FC_PATH`                                                                                              | `functions/test/fast-check.setup.js`, `frontend/test/fast-check.setup.js`         |
| Accessibility          | axe-core            | zero violations, WCAG 2.x A/AA + best practice; no exclusions                                                                                         | `e2e/axe.ts`                                                                      |
| Lighthouse, signed out | Lighthouse CI       | performance ≥ 0.8, accessibility = 1, best practices ≥ 0.9, SEO ≥ 0.9, LCP ≤ 5000 ms, TBT ≤ 300 ms, CLS ≤ 0.1, median of 3                            | `e2e/lighthouse/lighthouserc.signed-out.json`                                     |
| Lighthouse, signed in  | Lighthouse CI       | the same as signed out, from runner measurements (developer guide, "Run Lighthouse")                                                                  | `e2e/lighthouse/lighthouserc.signed-in.json`                                      |
| DAST                   | OWASP ZAP (passive) | FAIL only on the listed rules (error disclosure, permissive CORS, cookie flags); header rules the static host cannot meet are IGNORE with a reason    | `.zap/rules-frontend.tsv`, `.zap/rules-api.tsv`                                   |
| Load                   | k6                  | not a gate; per-scenario p95 limits at the `normal` profile, calibrated from two runs per flow on a GitHub runner (#621)                              | `load/lib/options.js`, [load-testing guide](../how-to/load-testing.md#thresholds) |
| Cost guards            | Vitest integration  | tour list: caller's partition on every page, `ceil(n / MAX_ITEMS_PER_REQUEST)` round trips; map: point budget, ≤ 4 MiB                                | `functions/test/integration/query-cost.test.js`, `map-budget.test.js`             |

## Risk table

Every open security or data-loss issue, with the layer that should catch it
and what catches it today. **Covered**: a test fails if the risk comes back.
**Partly**: some of it is pinned. **Not**: nothing fails today.

| Issue | Risk                                                                                 | Owning layer                       | Status  | Evidence                                                                                                                                                                                                                                                                                                                                     |
| ----- | ------------------------------------------------------------------------------------ | ---------------------------------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| #567  | Cross-user read/write by tour or image id (IDOR)                                     | Integration, two identities        | Covered | Every tour-scoped route answers another user 404, identical to a nonexistent id, and the owner reads back an unchanged tour (`authorization-isolation.test.js`); handler unit tests assert the caller's partition                                                                                                                            |
| #569  | An ID token is accepted as an access token (no `scp` check)                          | Middleware unit + integration      | Covered | `authenticate` requires `scp` to name `access_as_user` (`authMiddleware.test.js`); the matrix sends an ID token, an unscoped and a wrongly scoped token to every route (`authorization-tokens.test.js`)                                                                                                                                      |
| #545  | Empty Entra variables deploy the production API with `SKIP_AUTH=true`                | Middleware unit + IaC test         | Covered | The middleware throws if `SKIP_AUTH` meets a configured tenant (unit-tested); `infrastructure/tests/auth.tftest.hcl` plans with mock providers: empty or blank Entra values fail the Function App's precondition, and `SKIP_AUTH` is never in its app settings                                                                               |
| #537  | Unauthenticated requests drain the JWKS rate limiter → 500 for everyone              | Middleware unit + local issuer     | Covered | `signingKeyCache.test.js`: junk kids cost at most one fetch per 5 minutes and a valid kid still resolves; `localIssuer.test.js` sends 20 junk-kid tokens to a cold instance over HTTP, then a valid one                                                                                                                                      |
| #571  | JWKS URI pinned forever, hard failure at metadata TTL, no fetch timeout              | Middleware unit                    | Covered | The key set follows a changed `jwks_uri` and outlives a failed refresh for a day (`signingKeyCache.test.js`); so does the metadata, fetched with a timeout signal (`authMiddleware.test.js`)                                                                                                                                                 |
| #620  | SAS URLs broader than one read-only, short-lived blob under the caller's prefix      | Unit on the adapter + integration  | Covered | `blobStorage.test.js` parses a real signature (`sp=r`, `sr=b`, expiry); `signed-urls.test.js` reads its blob, gets 403 for a write, a sibling and another user's blob                                                                                                                                                                        |
| #562  | MSAL tokens in `localStorage` on the shared origin                                   | Design decision, not a test        | Not     | `cacheLocation: 'localStorage'` in `frontend/src/ui/api.js`                                                                                                                                                                                                                                                                                  |
| #557  | Frontend does not handle 401 / expired tokens                                        | Unit (lib) + static e2e            | Covered | `session.test.js`: one shared silent renewal, one retry of a 401 with a forced refresh, then the session ends; `session-expired.spec.ts`: the sign-in toast recovers; `entra-sign-in.spec.ts`: the real MSAL against a fake tenant (redirect sign-in, renewal past the 24-hour refresh token, no loop, sign-out)                             |
| #558  | Function App lacks `https_only`; production CORS allows `http://localhost:4280`      | IaC test                           | Covered | `infrastructure/tests/transport.tftest.hcl` fails without `https_only` or TLS 1.2 on the Function App, with its basic-auth publishing credentials on, and on any non-HTTPS origin in its CORS list or the storage account's                                                                                                                  |
| #560  | Production CSP too wide                                                              | DAST + review                      | Covered | `productionCsp.test.js` (unit, mutation-tested) and `productionCspPage.test.js` (the real page) hold the deploy's rewrite to exact hosts without Azurite; the smoke test checks the served page; ZAP rule 10038 stays IGNORE because the static host cannot send headers                                                                     |
| #561  | Long-lived subscription-wide SP secret readable by every deploy job                  | CI/CD review                       | Partly  | `ARM_*` and the state key only on the OpenTofu job; Core Tools pinned in one composite action and installed before `azure/login`; the deletion job installs without scripts before its login. OIDC federation and a narrower principal need Azure-side setup                                                                                 |
| #563  | Deploy not gated on CI, not ordered, no smoke test                                   | Pipeline structure                 | Covered | `deploy.yml` ships only a commit a green CI Gate run tested on `main` (`workflow_run`), manual runs only from `main`; frontend after Functions; `infrastructure smoke-test` checks health, the 401 and the site                                                                                                                              |
| #539  | Auto-merged Dependabot PRs never deploy                                              | Pipeline structure                 | Covered | The daily drift check in `deploy.yml` (`infrastructure pick-release`) runs CI Gate on `main` when production lags it and deploys once it passes; auto-merge stays devDependency patches only                                                                                                                                                 |
| #564  | Vendored MSAL and Leaflet get no update PRs                                          | Supply-chain automation            | Covered | Pinned as exact `frontend` devDependencies; the `verify-vendor` hook fails while `vendor/` differs from `node_modules`                                                                                                                                                                                                                       |
| #543  | Stateful resources lack destroy guards under `tofu apply -auto-approve`              | IaC scan                           | Covered | `prevent_destroy` on the resource group, Cosmos account, database, three containers, storage account and `gpx-files`; TFLint's rule is on, with one per-resource exception (`deployments`); `provision.sh` refuses any plan that deletes or replaces a resource before it applies the saved plan                                             |
| #541  | No backup/restore for user data                                                      | IaC test + restore drill           | Partly  | `infrastructure/tests/backup.tftest.hcl` pins Cosmos continuous 7-day backup, blob versioning, 14-day blob and container soft delete and version expiry; no restore drill has been run                                                                                                                                                       |
| #568  | Photos live in an unmanaged `tour-images` container                                  | IaC                                | Covered | `azurerm_storage_container.tour_images` carries `prevent_destroy`, which TFLint's rule requires; `provision.sh` imports the existing container once, and the unused `images` container left state through a `removed` block                                                                                                                  |
| #575  | GPX edge cases: `Math.min` stack overflow, bad timestamp, negative duration, comment | Unit + property                    | Covered | `parseGpx.test.js` pins the stack overflow, an unreadable `<time>`, out-of-order timestamps and per-segment totals (#552); a property keeps any timestamp order non-negative; `fileSignatures.test.js` accepts leading comments                                                                                                              |
| #576  | GPX parsing blocks the event loop                                                    | Unit (real worker thread)          | Covered | `parseGpxOffThread.test.js` parses on a real worker and pins the error classes across the thread, the 512 MB heap cap and the two-at-a-time queue; `parseGpx.test.js` pins five-decimal coordinates                                                                                                                                          |
| #546  | `/api/map` point budget not enforced                                                 | Integration cost guard + unit      | Covered | `map-budget.test.js` pins the hard budget for 100 km tracks; `mapBudget.test.js` holds 200 × 100 km random-walk rides (1,000,000 points) to 100,000 points in under 10 s (about 1 s locally), and the property tests pin exactly-the-budget, endpoints and order                                                                             |
| #550  | Upload size limit does not bound memory (no HTTP streaming)                          | Integration, real host             | Covered | `functionsApp.test.js` pins `enableHttpStream`, a dependency-cruiser rule makes every handler load it; `tours.test.js` (integration) sends an 11 MB chunked body without `Content-Length` and gets 400                                                                                                                                       |
| #572  | 20-photo cap bypassable by concurrent uploads; exactly-10 MB files rejected          | Integration (concurrent) + unit    | Covered | Five concurrent uploads to a tour with 18 photos get two 201s and three 400s (`tours.test.js`), as does a 10 MB GPX with its real Content-Length; the ETag retry, the refusal and the rollback are unit-tested                                                                                                                               |
| #553  | Deleting a tour leaves its photos and thumbnails                                     | Handler unit + E2E full stack      | Covered | `DeleteTour` unit tests with a prefix-aware blob fake; the full-stack journey checks the GPX, photo and thumbnail blobs are gone                                                                                                                                                                                                             |
| #573  | Inconsistent partial-failure handling (orphaned blobs, 500s on races)                | Handler unit, failing fakes        | Covered | Upload rollbacks rethrow (with the rollback's own error), deletes go document first then `deleteIfExists`, `DeleteImage` re-reads a vanished tour as 404                                                                                                                                                                                     |
| #555  | A failed blob container init is cached forever                                       | Unit                               | Covered | `settle.test.js`: `onceUntilFailure` shares one container init and retries after a rejected one; `blobStorage.js` builds both containers with it                                                                                                                                                                                             |
| #538  | Account deletion can orphan data (queue keyed by oid, `GetMe` recreates the user)    | Integration + job unit             | Covered | `account-deletion.test.js`: the user's list, export and signed URLs are empty or 404 and another user is untouched; a caller with an `oid` is queued with its `userId`, and `GET/PATCH /me` and uploads then answer 410 and create nothing; `deletionJob.test.js` purges before Graph and keeps the entry when the purge fails               |
| #540  | Data export omits GPX files and photos                                               | Integration                        | Covered | `ExportData` unit tests sign each GPX and photo from the token's user id; `signed-urls.test.js` reads the exported GPX and photo; the isolation matrix checks every export link stays under the caller's prefix                                                                                                                              |
| #551  | `GET /api/me` overwrites the user's chosen display name with the token claim         | Handler unit + integration + E2E   | Covered | Claims fill only empty fields (`test/unit/profile.test.js`, `me.test.js`); the full-stack rename survives a reload                                                                                                                                                                                                                           |
| #570  | Deletion job deletes blind, leaves Entra soft delete, logs object ids                | Unit on the job                    | Partly  | Only GUIDs reach Graph, URL-encoded; logs are masked; one failure never stops the run (`scripts/lib/deletionJob.test.js`); purging Entra's soft-deleted users is open                                                                                                                                                                        |
| #617  | Deletion job has no dry-run mode                                                     | Unit on the job + dry run          | Covered | `--dry-run` has no Graph client at all; manual workflow runs default to it                                                                                                                                                                                                                                                                   |
| #565  | Full-stack E2E cleanup wipes whatever `COSMOS_CONNECTION_STRING` points to           | E2E fixture guard                  | Covered | `e2e/emulator-guard.ts` refuses a non-local Cosmos or non-Azurite blob store before any client exists; the reset touches only the dev user's partition and blob prefix                                                                                                                                                                       |
| #618  | Integration cleanup trusts `COSMOS_CONNECTION_STRING`                                | Integration setup guard            | Covered | `test/integration/emulatorGuard.js` runs first in `globalSetup` and before `query-cost` builds its client                                                                                                                                                                                                                                    |
| #577  | No schema versioning; backfill scripts lack dry run and batching                     | Handler unit (old shape) + dry run | Covered | New tours and users carry `schemaVersion`; the backfills (stats, thumbnails, schema version) are dry by default, paged, unit-tested and run through `./buddy.sh maintenance backfill`; the old-shape shims go once the schema-version dry run reports nothing left                                                                           |
| #549  | No per-user quotas or rate limiting                                                  | Design + cost guards               | Partly  | Per-request cost is bounded by the two guards; per-user volume is not                                                                                                                                                                                                                                                                        |
| #544  | Service worker serves stale JS/CSS                                                   | Unit                               | Covered | `frontend/test/sw.test.js` runs `sw.js` in a fake worker scope: modules come from the network and refresh the cache, the cache answers only offline, and the precache bypasses the HTTP cache                                                                                                                                                |
| #559  | Undo-able deletes are lost when the tab closes                                       | DOM-layer unit + E2E               | Covered | `pendingActions.test.js` (flush, undo after commit); static e2e `delete-on-leave.spec.ts` (a hidden page sends the delete at once, a later Undo is too late, a 404 counts as deleted); full stack `tours.spec.ts` (Undo keeps the tour; a list reloaded in the window leaves the pending tour out). A browser killed outright still loses it |
| #574  | Contract duplication and DTO drift                                                   | Contract check                     | Partly  | `frontendContract.test.js` holds the photo cap, the 10 MB limit, every name/description `maxlength`, the languages and every API error key to the frontend; `endpoints.test.js` holds `.zap/openapi.yaml` to the registered GET routes; `e2eMockContract.test.js` holds the static E2E mocks to the handlers' answers                        |
| #556  | Account keys instead of managed identity                                             | Design, not a test                 | Not     | Revisit the playbook's §0 when it lands                                                                                                                                                                                                                                                                                                      |

## Known gaps

Measured against the playbook. Each has an issue unless marked **no issue**
(deliberate, not a defect).

- **`frontend/src/ui/` is mostly untested at unit level** (#557, #559): only the
  i18n runtime, line-style storage and upload request have tests; the rest is
  exercised by Playwright.
- **No post-deploy smoke test** (#563).
- **Contract** (#574): each tour document still stores an absolute
  `gpxFileUrl`, which no response uses. The static suite's mocks
  (`e2e/fixtures/api-responses.ts`) are checked: `e2eMockContract.test.js`
  runs the real handlers over the same account and fails when an answer
  differs from the mock's. So is `.zap/openapi.yaml`: `endpoints.test.js`
  fails while it lists anything but the registered GET routes.
- **Direct DB seeding** (**no issue**, deliberate): `query-cost.test.js` seeds
  150 tours straight into Cosmos under a throwaway user, to measure the
  adapter. Every other test seeds through the API.
- **One identity in the full-stack suite** (#567): the browser suites still run
  as the `SKIP_AUTH` dev user with `workers: 1`; each test resets only that
  user's partition and blob prefix, before and after. Test-signed tokens reach
  the integration suite only.
- **Mutation blind spots**: `ignoreStatic` skips top-level limit constants;
  `db.js` and `blobStorage.js` are outside the mutation list and the
  integration suite does not reach all their paths (`parseMultipart.js` joined
  the list in #567).
- **Two emulator guards** (**no issue**): `functions/test/integration/emulatorGuard.js`
  and `e2e/emulator-guard.ts` repeat the same checks in two languages; a third
  user extracts them.
