Skip to content

Commit 025581d

Browse files
test: add CMS journey and REST API contract suite (#28)
Closes #6 ## What changed - **`setup` project:** logs in through the admin panel and saves `storageState`. Credentials come from `E2E_ADMIN_EMAIL` and `E2E_ADMIN_PASSWORD`, validated at startup. - **`api` project:** 19 tests for `/api/pages` and `/api/posts`, with zod and `expectJson`. `request` is anonymous; a session is requested explicitly through the `adminRequest` fixture. - **`admin` project:** a page edited and published in the admin panel reaches a visitor, after the visitor's first request cached it. - **KI-6:** a newly published post is missing from `/posts`, tracked with `test.fail`. - **KI-7:** REST validation errors lose their field details once an admin route has initialized Payload first, tracked with `test.fail`. - **Lint:** secrets in `fill`/`type` and dynamic `expect` messages are rejected, because both become step titles in the published report. Every test creates its own uniquely named data and deletes it in teardown. ## How RED was seen - First run: `Cannot find module tests/helpers/auth-state`. - Each green-born test was mutated and failed on its own expectation. The full table is in `docs/PROJECT_SESSION_SUMMARY.md`. - KI-6 was confirmed without the marker. A control proved the locator finds a seeded post in the same listing. - KI-7 was found by the first CI run and reproduced with `CI=1`. On a server whose first route was the API, it reports `Expected to fail, but passed`. ## Validation - `pnpm check` passes. - CI mode with no server running (`CI=1 pnpm test:e2e`): 62 of 62. - Same mode with `--repeat-each=3 --retries=0`: 184 of 184. ## Note for local runs A `.env` created before this change needs the two new variables from `.env.example`. The run stops at startup without them. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent ad6e89f commit 025581d

19 files changed

Lines changed: 772 additions & 10 deletions

‎.env.example‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,3 +15,7 @@ CRON_SECRET=local-only-cron-secret-not-for-production
1515

1616
# Used to validate preview requests
1717
PREVIEW_SECRET=local-only-preview-secret-not-for-production
18+
19+
# Admin that the E2E suite logs in as: the demo author created by the seed
20+
E2E_ADMIN_EMAIL=demo-author@example.com
21+
E2E_ADMIN_PASSWORD=password

‎.github/workflows/ci.yml‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,9 @@ jobs:
139139
# The job runs in a container, so the service is reached by its label
140140
DATABASE_URL: postgresql://payload:payload@postgres:5432/payload
141141
NEXT_PUBLIC_SERVER_URL: http://localhost:3000
142+
# The demo author from the template's public seed, in a disposable database
143+
E2E_ADMIN_EMAIL: demo-author@example.com
144+
E2E_ADMIN_PASSWORD: password
142145
outputs:
143146
pages-artifact: ${{ steps.pages-artifact.outcome }}
144147

‎.gitignore‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ node_modules/
2020
/playwright-report/
2121
/blob-report/
2222
/playwright/.cache/
23+
/playwright/.auth/
2324

2425
# TypeScript incremental build cache
2526
*.tsbuildinfo

‎README.md‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,11 @@ pnpm test:e2e # starts `pnpm start`, or reuses a runni
3030
pnpm exec playwright show-report # opens the HTML report
3131
```
3232

33-
The tests run against the production build, so run `pnpm build` again after changing the app. Projects: `chromium` (desktop), `mobile` (375x812) and `reduced-motion`. Defects found in the app are listed in [`docs/KNOWN_ISSUES.md`](docs/KNOWN_ISSUES.md).
33+
The tests run against the production build, so run `pnpm build` again after changing the app. Projects: `setup` (admin login), `api` (REST contract of `/api/pages` and `/api/posts`), `admin` (journey from the admin panel to the frontend), `chromium` (desktop), `mobile` (375x812) and `reduced-motion`.
34+
35+
The suite logs in with `E2E_ADMIN_EMAIL` and `E2E_ADMIN_PASSWORD`. A `.env` created before they were added to `.env.example` needs both lines, and the run stops at startup without them.
36+
37+
Defects found in the app are listed in [`docs/KNOWN_ISSUES.md`](docs/KNOWN_ISSUES.md).
3438

3539
## Continuous integration
3640

‎config/eslint.suite.config.mjs‎

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,8 +38,30 @@ export default defineConfig(
3838
files: ['tests/**/*.ts'],
3939
extends: [playwright.configs['flat/recommended']],
4040
rules: {
41-
// Counts the helper that asserts each focus stop as an assertion
42-
'playwright/expect-expect': ['warn', { assertFunctionPatterns: ['^expectFocusWalk$'] }],
41+
// Helpers that assert count as assertions: each focus stop, each contract
42+
'playwright/expect-expect': [
43+
'warn',
44+
{ assertFunctionPatterns: ['^expectFocusWalk$', '^expectJson$'] },
45+
],
46+
'no-restricted-syntax': [
47+
'error',
48+
// Input steps are titled with the value (`Fill "<value>"`), and the
49+
// report is published. The value is the 1st argument on a locator and
50+
// the 2nd on page/frame (`page.fill(selector, value)`).
51+
...[0, 1].flatMap((position) =>
52+
['name', 'property.name'].map((key) => ({
53+
selector: `CallExpression[callee.property.name=/^(fill|type|pressSequentially|insertText)$/][arguments.${String(position)}.${key}=/password|secret|token/i]`,
54+
message: 'The step title would show this secret in the report: use fillSecret.',
55+
})),
56+
),
57+
// An expect message becomes the step title even when the assertion
58+
// passes, so one built from data (a body, a token) gets published.
59+
...['callee.name', 'callee.object.name'].map((callee) => ({
60+
selector: `CallExpression[${callee}='expect'][arguments.1][arguments.1.type!='Literal'][arguments.1.type!='ObjectExpression']`,
61+
message:
62+
'This message is the step title even on success: use a constant, or expectJson (body only on failure).',
63+
})),
64+
],
4365
'playwright/no-focused-test': 'error',
4466
'playwright/no-wait-for-timeout': 'error',
4567
'playwright/prefer-web-first-assertions': 'error',

‎config/playwright.config.ts‎

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,19 @@ import 'dotenv/config'
22

33
import { defineConfig, devices } from '@playwright/test'
44

5-
import { parseEnv } from '../scripts/env'
5+
import { parseEnv, parseTestEnv } from '../scripts/env'
6+
import { ADMIN_STATE } from '../tests/helpers/auth-state'
67

78
const { NEXT_PUBLIC_SERVER_URL: baseURL } = parseEnv()
9+
// Here and not only in the setup: a missing credential must stop the run
10+
// before the build is served, not fail it from inside a test
11+
parseTestEnv()
812

913
const desktop = { ...devices['Desktop Chrome'], channel: 'chromium' }
1014

1115
const MOBILE_SPECS = /\.mobile\.spec\.ts$/
1216
const REDUCED_MOTION_SPECS = /\.reduced-motion\.spec\.ts$/
17+
const ADMIN_SPECS = /\.admin\.spec\.ts$/
1318

1419
// The template's playwright.config.ts stays as generated. Paths here are
1520
// relative to this file, so they point back to the repository root.
@@ -27,9 +32,27 @@ export default defineConfig({
2732
trace: 'on-first-retry',
2833
},
2934
projects: [
35+
{
36+
name: 'setup',
37+
testMatch: /\.setup\.ts$/,
38+
use: desktop,
39+
},
40+
{
41+
name: 'api',
42+
testDir: '../tests/api',
43+
// No storageState: `request` is an anonymous visitor here, and a test
44+
// that needs a session asks for it through the adminRequest fixture
45+
dependencies: ['setup'],
46+
},
47+
{
48+
name: 'admin',
49+
testMatch: ADMIN_SPECS,
50+
use: { ...desktop, storageState: ADMIN_STATE },
51+
dependencies: ['setup'],
52+
},
3053
{
3154
name: 'chromium',
32-
testIgnore: [MOBILE_SPECS, REDUCED_MOTION_SPECS],
55+
testIgnore: [MOBILE_SPECS, REDUCED_MOTION_SPECS, ADMIN_SPECS],
3356
use: desktop,
3457
},
3558
{

‎docs/KNOWN_ISSUES.md‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,3 +47,19 @@ Issues are numbered in the order they were found.
4747
- **Cause:** `src/app/(frontend)/globals.css` sets `html { opacity: 0 }` until `data-theme` is set, and only JavaScript sets it (`InitTheme`, then `ThemeProvider`). The rule prevents a flash of the wrong theme, at the cost of depending on JavaScript.
4848
- **Impact:** moderate. Few visitors browse without JavaScript, but for them, and on a failed bundle load, the whole site is blank.
4949
- **Test:** `the page is visible`, in `tests/e2e/accessibility.spec.ts`.
50+
51+
## KI-6: A newly published post is missing from the posts listing
52+
53+
- **Observed:** a post published through the admin or the REST API is live at `/posts/<slug>`, but `/posts` keeps serving the cached list without it (`x-nextjs-cache: HIT`).
54+
- **Expected:** publishing a post updates the listing that links to it.
55+
- **Cause:** `/posts` is `force-static` with `revalidate = 600` in `src/app/(frontend)/posts/page.tsx`, and the `revalidatePost` hook in `src/collections/Posts/hooks/revalidatePost.ts` only invalidates `/posts/<slug>` and the sitemap tag.
56+
- **Impact:** moderate. Readers cannot find a new post from the listing for at least 10 minutes, and the first request after that still gets the old list while the page regenerates.
57+
- **Test:** `a published post appears in the posts listing`, in `tests/e2e/cms.admin.spec.ts`.
58+
59+
## KI-7: REST validation errors lose their field details once the admin panel has loaded first
60+
61+
- **Observed:** when the first route to initialize Payload in a server process is an admin page, a `400` from the REST API has only `{"errors":[{"message":"The following fields are invalid: ..."}]}`. When an API route comes first, the same request also returns `name` and `data.errors`, with the path and message of each field. The state lasts until the server restarts. Static routes such as `/` and `/posts` do not count, because they do not initialize Payload.
62+
- **Expected:** the error body does not depend on which route was requested first, and clients can map each error to its field.
63+
- **Cause:** `formatErrors` in `payload/dist/utilities/formatErrors.js` only keeps `name` and `data` when `incoming instanceof ValidationError`. The likely reason it is false is that the admin and API routes get separate bundled copies of the class. The dependence on the first route is measured; the separate copies are inferred.
64+
- **Impact:** low. The status and the summary message stay correct, but a REST client cannot highlight individual fields.
65+
- **Test:** `a validation error details each invalid field`, in `tests/api/pages.spec.ts`.

‎docs/PROJECT_SESSION_SUMMARY.md‎

Lines changed: 71 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,14 +8,14 @@ Estado do projeto entre chats. Lido no início de cada missão (ver `.github/cop
88

99
| Item | Estado |
1010
| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
11-
| Missão atual | Missão 4 — Acessibilidade e teclado (#5), concluída com o merge do PR da missão |
12-
| Próxima missão | Missão 5 — CMS de ponta a ponta e API (#6) |
11+
| Missão atual | Missão 5 — CMS de ponta a ponta e API (#6), concluída com o merge do PR da missão |
12+
| Próxima missão | Missão 6 — Paridade no GitLab CI (#7) |
1313
| PRs abertos | Dependabot #13 a #16, #23 e #24, à espera de avaliação um por vez; o #24 sobe o Playwright para 1.64.1 e reprova no `e2e` até a imagem ser atualizada (#21) |
1414
| Ambiente local | `compose.yaml` com `postgres:18`, env validado com zod, migration inicial e seed via Local API; passos no README |
1515
| Portões | Jobs `check`, `audit`, `secret-scan`, `workflow-audit` e `e2e`, todos no `needs` do `ci-passed`, único check do ruleset; `publish-report` só em push na `main` |
1616
| Travas do agente | `.claude/settings.json` nega merge `--admin`, force push, push na `main` e leitura/escrita do `.env` (Bash e PowerShell); fronteira real é o ruleset da `main` |
1717
| Baseline | 1º commit da `main` (`f0154df`): app gerado por `create-payload-app@3.93.0 -t website -d postgres`, intacto |
18-
| Testes | 40 E2E no build de produção: 4 do template e 36 próprios, em `chromium`, `mobile` e `reduced-motion`; 5 são `test.fail` (KI-1 a KI-5) |
18+
| Testes | 61 no build de produção: 4 do template e 57 próprios (19 de API e 2 da jornada do CMS novos), em `api`, `admin`, `chromium`, `mobile` e `reduced-motion`, mais o `setup` de login; 7 são `test.fail` (KI-1 a KI-7) |
1919

2020
## Plano de missões
2121

@@ -319,3 +319,71 @@ Validação: suíte inteira com `--repeat-each=3 --workers=1 --retries=0` deu 12
319319
### Fontes consultadas
320320

321321
Em 08/11/2026: [Playwright: testes de acessibilidade](https://playwright.dev/docs/accessibility-testing); [WAI-ARIA APG: combobox](https://www.w3.org/WAI/ARIA/apg/patterns/combobox/) e [exemplo select-only](https://www.w3.org/WAI/ARIA/apg/patterns/combobox/examples/combobox-select-only/); [WCAG 2.2: Focus Order](https://www.w3.org/WAI/WCAG22/Understanding/focus-order.html). Regras e tags do axe conferidas em `axe-core` 4.14.0 (`axe.getRules`, `axe.js`). Critérios citados no `KNOWN_ISSUES.md`: [WCAG 1.4.3](https://www.w3.org/WAI/WCAG22/Understanding/contrast-minimum.html) e [`aria-hidden-focus` → 4.1.2](https://dequeuniversity.com/rules/axe/4.11/aria-hidden-focus).
322+
323+
## Missão 5 (#6)
324+
325+
### Decisões
326+
327+
- **O contrato vem da medição:** a doc da REST API da Payload não define os corpos de resposta (só a do login). Os schemas zod em `tests/helpers/cms-contract.ts` saíram de respostas reais. Objetos abertos, para campo novo não quebrar contrato (julgamento nosso); `populatedAuthors` é estrito, porque um campo a mais ali, como e-mail, seria vazamento.
328+
- **`request` anônimo, admin explícito:** o projeto `api` não tem `storageState`, e quem precisa de sessão pede a fixture `adminRequest`. Assim, esquecer a sessão reprova o teste, e um teste de "anônimo não pode" nunca roda autenticado sem querer. O projeto `admin` segue o padrão da doc, com `storageState` no projeto.
329+
- **Dados por teste:** `createPage` e `createPost` criam com sufixo único e apagam no teardown. O teardown aceita 200 e 404 (o próprio teste pode ter apagado) e reprova no resto.
330+
- **A jornada edita o `hero.richText`, não o `title`:** o `title` não é renderizado no frontend. O visitante abre a página antes da edição para ela ficar em cache (`MISS → HIT`, e `MISS` depois de publicar), então o teste prova a invalidação. Arranjo pela API e ação pela UI, como recomenda a doc de API testing.
331+
- **`visitorPage` sem sessão, com `storageState` vazio explícito:** o que o público vê, sem a barra de admin.
332+
- **Posts de contrato ficam em rascunho:** publicar entraria nas listagens lidas pelos testes da homepage. CRUD completo fica em `pages`, que tem as mesmas operações. A exceção é o teste do KI-6, que apaga o post no teardown.
333+
- **Credenciais em `parseTestEnv`, separado de `parseEnv`:** só a execução dos testes precisa delas, e os scripts de banco não devem reprovar por isso. A validação roda na config, antes de o servidor subir.
334+
- **Lint adaptado do starter kit:** `no-restricted-syntax` barra segredo em `fill`/`type` e mensagem dinâmica em `expect`, porque ambos viram título de passo no relatório publicado; `expectJson` conta como asserção. `expectStatus` e `expectFound` do starter kit não vieram (YAGNI).
335+
336+
### Como o RED foi visto
337+
338+
Primeiro passo: `Cannot find module '.../tests/helpers/auth-state'`. KI-6 confirmado sem marcação antes de virar `test.fail`: `getByRole('link', { name: 'Post post-...' })`, `element(s) not found`; no controle, o mesmo localizador achou um post do seed e o `/posts` respondeu `x-nextjs-cache: HIT`.
339+
340+
Mutações, todas desfeitas:
341+
342+
| Alvo | Mutação | Erro observado |
343+
| ---------------------------------------- | ---------------------------------------- | -------------------------------------------------- |
344+
| Cada um dos 18 testes de API | Expectativa de status, campo ou total | Falha na própria expectativa, teste a teste |
345+
| Estado após escrita recusada e rascunhos | `totalDocs`, título e 404 no lugar de 200 | `Expected: 1, Received: 0`; `Expected HTTP 404, received 200` |
346+
| Passos seguintes de `refuses anonymous writes` | 403 para 401 em `PATCH` e `DELETE` | `Expected HTTP 401, received 403` |
347+
| ID no contrato | `string`, como em `payload-types.ts` | `Invalid input: expected string, received number` |
348+
| Autor público | Schema só com `id` | `Unrecognized key: "name"` |
349+
| Erro de validação | `literal('Probe')` | `Invalid input: expected "Probe"` |
350+
| Visitante vê a edição | `after` deveria sumir | `toBeHidden`, `Received: visible` |
351+
| Texto antigo some | `before` deveria continuar | `element(s) not found` |
352+
| `test.fail` percebe correção | Listagem procurando post do seed | `Expected to fail, but passed` |
353+
| Senha errada | `E2E_ADMIN_PASSWORD=wrong` | `setup` reprova, dependente em `did not run` |
354+
| Senha ausente | Variável removida | `E2E_ADMIN_PASSWORD: is required`, antes do servidor |
355+
| Lint | `fill(password)`, `expect(x, template)`, teste sem asserção | `use fillSecret`, `step title`, `Test has no assertions` |
356+
| `.gitignore` | `git check-ignore` | `/playwright/.auth/` casa com `admin.json` |
357+
358+
Validação: suíte inteira com `--repeat-each=3 --workers=1 --retries=0` deu 181 de 181 (60 × 3, mais 1 do `setup`: dependência não é repetida).
359+
360+
### Achados
361+
362+
- **KI-6:** post publicado não aparece em `/posts` por pelo menos 10 minutos.
363+
- **`keyboard.insertText` não funciona no Lexical:** a seleção some e o texto volta, mesmo 1,5 s depois. Não era espera. Com teclas reais (`keyboard.type`) funciona. Uma sonda que registrou o estado a cada passo mostrou isso.
364+
- **Anônimo recebe 403, não 401**, e rascunho anônimo responde 404: não revela que o documento existe.
365+
- **`.env` local desatualizado:** quem já tem `.env` precisa acrescentar `E2E_ADMIN_EMAIL` e `E2E_ADMIN_PASSWORD`; o README avisa. O agente seguiu sem ler o arquivo: variáveis de processo a partir do `.env.example`.
366+
- **Cada login acrescenta uma entrada em `sessions` no usuário demo.** É o único efeito sobre dados do seed, e nenhum teste lê esse campo.
367+
368+
### Fontes consultadas
369+
370+
Em 08/11/2026: [Playwright: autenticação](https://playwright.dev/docs/auth), [API testing](https://playwright.dev/docs/api-testing) e [fixtures](https://playwright.dev/docs/test-fixtures); [Payload: REST API](https://payloadcms.com/docs/rest-api/overview) e [operações de autenticação](https://payloadcms.com/docs/authentication/operations). `expectJson` e `fillSecret` adaptados de `playwright-qa-starter-kit`.
371+
372+
### Revisão independente
373+
374+
- **Aplicado:** a jornada publicava sem esperar o estado do formulário. O Lexical repassa o valor ao formulário de forma adiada, e o editor mostra o texto antes disso (leitura do código da Payload; a falha não foi reproduzida). Agora o teste espera o rascunho salvo pelo autosave conter o texto novo. Mutação: `Expected substring: "After the edit ... probe"`.
375+
- **Aplicado:** o teste de autor público não olhava `authors`, onde um vazamento apareceria se `Users` deixasse de ser restrito. O contrato agora aceita só ids. Mutação: `expected object, received number`.
376+
- **Aplicado:** o comentário do `fillSecret` omitia que o trace guarda o valor. A proteção vale só para títulos de passo, e a senha usada é a do seed público. Sonda com um reporter próprio: `Evaluate` com `fillSecret` e `Fill "password"` com `fill`. Uma primeira sonda com `--reporter=json` saiu vazia, porque esse reporter só traz `test.step`, e vazio não contou como prova.
377+
- **Registrado, sem mudança:** o KI-6 pode dar `Expected to fail, but passed` se, com o cache de `/posts` vencido (mais de 600 s) e mais de um worker, outro teste regenerar a listagem enquanto o post existe. Não ocorre no CI (`workers: 1`, build recente, suíte curta).
378+
379+
Depois das correções: `pnpm check` verde, jornada com `--repeat-each=10` deu 11 de 11 (com o `setup`) e a suíte inteira com workers padrão deu 61 de 61.
380+
381+
### Falha no primeiro CI (KI-7)
382+
383+
- **Erro observado:** `rejects a page without its required fields` reprovou nas 3 tentativas: o `400` veio só com `{errors:[{message}]}`, sem `name` e `data`.
384+
- **Causa raiz:** a forma do erro depende da primeira rota que inicializa a Payload no processo. Com `/admin/login` primeiro, a resposta perde os detalhes; com `/api/pages`, `/` ou `/posts` primeiro, vem completa (`/` e `/posts` são estáticas e não inicializam a Payload). O `formatErrors` só mantém os campos com `instanceof ValidationError`; cópias separadas da classe por empacotamento são inferência.
385+
- **Por que passou localmente:** todas as execuções reusaram um servidor que subi à mão, cujo primeiro acesso foi `/api/pages`. No CI o `webServer` sobe o processo e o `setup` entra primeiro no admin. Build limpo no Windows e imagem do CI em Linux, ambos com a API primeiro, deram resposta completa: não era o sistema operacional.
386+
- **Correção:** o contrato afirma o que vale nos dois estados (400 e a mensagem com os campos), e a perda de detalhes é o `test.fail` do KI-7. Com a API primeiro: `Expected to fail, but passed`. Mutação da mensagem: `Expected: "...Probe, Content > Layout, Slug"`.
387+
- **Prevenção:** validar com `CI=1` e sem servidor no ar, que é como o CI roda. Um servidor reusado carrega o estado de quem o usou antes.
388+
389+
Validação em modo CI: 62 de 62, e com `--repeat-each=3 --retries=0`, 184 de 184 (61 × 3, mais 1 do `setup`).

0 commit comments

Comments
 (0)