docs(concept): passer les 59 fiches de doctrine en anglais
Convention du projet pour la documentation projet. Traduction fidèle, sans changement de fond : mêmes fiches, mêmes sections, mêmes liens. Le lint est identique à la baseline (59 leaves, 0 nouveau lien cassé, wikilinks bit-à-bit inchangés) et aucun `.feature` n'a été touché. Le `summary:` du frontmatter est traduit lui aussi — c'est ce que le hook affiche dans l'index, il porte autant que le corps. RESTENT EN FRANÇAIS, délibérément : - les fichiers .feature (convention explicite du projet : Etant donné/Quand/Alors) et le bloc Gherkin cité dans brief_2026-07-06 ; - les libellés d'interface cités en prose (« Entrer », « ✓ Je participe », « Voir tous les participants », « participant inconnu »…) : ce sont des chaînes réelles de l'app, pas de la prose ; - les noms de scénarios BDD ; - les `triggers.keywords` des _overview : jetons de matching du hook, et la conversation reste en français — les traduire aurait cassé la livraison. EFFET SECONDAIRE UTILE : relire intégralement a fait remonter des contradictions et des péremptions que personne ne voyait section par section. Notées, non corrigées (hors périmètre de la traduction) : - rule_document-per-entity décrit la lecture via readEntities/readUnion/ registerDoc/bumpRead, que rule_app-uses-sdk-surface-only déclare SUPPRIMÉS au profit de watchShape/useShapeQuery. Une règle qui décrit des APIs retirées est activement trompeuse — à traiter en priorité. - brief_2026-07-06 §P3 réaffirme « prouvé par l'e2e D.2, sans reload » juste après l'encadré qui déclare cette phrase fausse et sur-cadrée. - knowledge_data-modes cite useShapeWithDefaults() là où useShapeQuery est documenté ailleurs. - knowledge_stack-and-commands : build:orm pointe ./src/shapes/* alors que les shapes vivent sous src/shared/shapes/. - knowledge_screens / knowledge_routing : ConnectScreen décrit comme absent du registre mais présent en route. - brief_2026-05-18 : « identifié si connecté » était ambigu en français (session ouverte vs est une connexion) ; l'anglais a forcé à trancher — rendu par « if a connection », à confirmer côté produit. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_014GbGgNEHRejVKoREvFuDFg
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
---
|
||||
type: _overview
|
||||
summary: BDD Cucumber/Gherkin en français sur 3 couches (@ui, @data, @e2e) — setup, contrat de couches (quoi tester où), harness broker réel, et le piège des vestiges source-grep
|
||||
summary: BDD Cucumber/Gherkin in French across 3 layers (@ui, @data, @e2e) — setup, layer contract (what to test where), real broker harness, and the source-grep leftovers pitfall
|
||||
triggers:
|
||||
keywords: [cucumber, gherkin, bdd, feature, scenario, scénario, step, steps, "@ui", "@data", "@e2e", playwright, broker, harness, wallet, world, hooks, renderHelper, multibrowser, multi-navigateur, "@multibrowser", "@private-wallet", "@shared-wallet", storageState, "@wip"]
|
||||
paths: ["src/modules/*/features/**", "src/modules/*/steps/**", "src/shared/steps/**", "src/shared/support/**", "src/shared/test-harness/**", "cucumber.json"]
|
||||
@@ -8,30 +8,30 @@ triggers:
|
||||
|
||||
# BDD testing
|
||||
|
||||
Tests BDD **Cucumber/Gherkin en français** (`Etant donné`, `Quand`, `Alors`) sur **3 couches** de coût croissant.
|
||||
BDD tests written in **Cucumber/Gherkin in French** (`Etant donné`, `Quand`, `Alors`) across **3 layers** of increasing cost.
|
||||
|
||||
**À lire avant d'écrire un test :** [[rule_test-layer-contracts]] — chaque couche répond à une question distincte ; mélanger produit des tests fragiles. C'est la règle qui décide *où* va une assertion.
|
||||
**Read before writing a test:** [[rule_test-layer-contracts]] — each layer answers a distinct question; mixing them produces brittle tests. That is the rule which decides *where* an assertion belongs.
|
||||
|
||||
## Les 3 couches
|
||||
## The 3 layers
|
||||
|
||||
```
|
||||
/\ @e2e app réelle dans l'iframe broker — parcours critiques
|
||||
/\ @e2e real app inside the broker iframe — critical journeys
|
||||
/ \
|
||||
/----\ @data mutations & persistance via broker NextGraph réel
|
||||
/----\ @data mutations & persistence through the real NextGraph broker
|
||||
/------\
|
||||
/ @ui \ rendu d'écran in-process (happy-dom + seed) — le gros du volume
|
||||
/ @ui \ in-process screen rendering (happy-dom + seed) — the bulk of the volume
|
||||
/__________\
|
||||
```
|
||||
|
||||
## Liens
|
||||
## Links
|
||||
|
||||
- [[rule_test-layer-contracts]] — quoi tester à chaque couche (le contrat)
|
||||
- [[knowledge_cucumber-setup]] — config, layout, scripts, fichiers auto-générés
|
||||
- [[knowledge_ui-layer]] — couche `@ui` : render helper, fixtures, bons/anti patterns
|
||||
- [[knowledge_data-layer-broker]] — couche `@data` : harness broker, cycle de vie wallet, bridge
|
||||
- [[knowledge_e2e-layer]] — couche `@e2e` : app réelle dans l'iframe
|
||||
- [[knowledge_multibrowser-harness]] — plusieurs navigateurs isolés × modèle de wallet (private/shared), injection storageState
|
||||
- [[caveat_reconnexion-froide-local-vs-broker]] — « page fraîche » ≠ démarrage à froid : quel montage prouve la durabilité broker, et lequel relit le local
|
||||
- [[decision_2026-03-12_headless-wallet-creation]] — pourquoi le wallet de test est créé en UI headless
|
||||
- [[caveat_source-grep-vestiges]] — vestiges de l'ère « analyse de source » dans `world.ts`
|
||||
- [[cookbook_add-scenario]] — ajouter un scénario/step (couches, piège de sérialisation `evaluate`, `@wip`)
|
||||
- [[rule_test-layer-contracts]] — what to test at each layer (the contract)
|
||||
- [[knowledge_cucumber-setup]] — config, layout, scripts, auto-generated files
|
||||
- [[knowledge_ui-layer]] — the `@ui` layer: render helper, fixtures, good and bad patterns
|
||||
- [[knowledge_data-layer-broker]] — the `@data` layer: broker harness, wallet lifecycle, bridge
|
||||
- [[knowledge_e2e-layer]] — the `@e2e` layer: the real app inside the iframe
|
||||
- [[knowledge_multibrowser-harness]] — several isolated browsers × wallet model (private/shared), storageState injection
|
||||
- [[caveat_reconnexion-froide-local-vs-broker]] — a "fresh page" is not a cold start: which setup proves broker durability, and which one just re-reads local
|
||||
- [[decision_2026-03-12_headless-wallet-creation]] — why the test wallet is created through a headless UI
|
||||
- [[caveat_source-grep-vestiges]] — leftovers from the "source analysis" era in `world.ts`
|
||||
- [[cookbook_add-scenario]] — adding a scenario/step (layers, `evaluate` serialization pitfall, `@wip`)
|
||||
|
||||
@@ -1,85 +1,54 @@
|
||||
---
|
||||
type: caveat
|
||||
summary: Une « page fraîche » ouverte via ctx.newPage() sur le contexte Chromium PERSISTANT ne prouve JAMAIS la durabilité broker — elle relit l'IndexedDB local du même profil. Seul un contexte non-persistant issu de freshBrowser, amorcé uniquement par le storageState capturé au BeforeAll, tranche broker-vs-local.
|
||||
summary: A "fresh page" opened via ctx.newPage() on the PERSISTENT Chromium context NEVER proves broker durability — it re-reads the local IndexedDB of the very same profile. Only a non-persistent context spawned from freshBrowser, seeded solely by the storageState captured at BeforeAll, settles broker-vs-local.
|
||||
last_checked: 2026-07-27
|
||||
---
|
||||
|
||||
# Piège : « page fraîche » ≠ démarrage à froid (local vs broker)
|
||||
# Pitfall: a "fresh page" is not a cold start (local vs broker)
|
||||
|
||||
Les scénarios de **reconnexion** posent tous la même question — *l'utilisateur retrouve-t-il ses
|
||||
propres données après avoir fermé et rouvert ?* — mais **selon le contexte navigateur choisi, ils
|
||||
ne répondent pas à la même question**. C'est le piège : le montage le plus naturel (`ctx.newPage()`)
|
||||
donne un vert qui ne prouve rien sur le broker.
|
||||
**Reconnection** scenarios all ask the same question — *does the user get their own data back after closing and reopening?* — but **depending on the browser context chosen, they do not answer the same question**. That is the pitfall: the most natural setup (`ctx.newPage()`) yields a green that proves nothing about the broker.
|
||||
|
||||
## Les deux montages, et ce que chacun prouve
|
||||
## The two setups, and what each one proves
|
||||
|
||||
| Montage | Où | Ce qu'il prouve | Ce qu'il ne prouve PAS |
|
||||
| Setup | Where | What it proves | What it does NOT prove |
|
||||
|---|---|---|---|
|
||||
| `this.page!.context().newPage()` — page fraîche sur le contexte **persistant** (`.playwright-profile`) | `reconnexion.steps.ts` (@data), `reconnexion-persistance.steps.ts` (@e2e) | nouveau login broker → **session verifier fraîche** (mémoire vide), remontage complet des providers | rien sur la **durabilité broker** : le profil détient **encore les repos locaux** en IndexedDB, un lecteur « frais » peut donc rouvrir **depuis le local** |
|
||||
| `spawnContext('shared')` — contexte **non-persistant** issu de `freshBrowser` | `reconnexion-froide-sans-local.steps.ts` (@data) | la donnée **a atteint le broker** (ou non) | rien sur le parcours UI réel (c'est le harness, pas l'app) |
|
||||
| `this.page!.context().newPage()` — fresh page on the **persistent** context (`.playwright-profile`) | `reconnexion.steps.ts` (@data), `reconnexion-persistance.steps.ts` (@e2e) | a new broker login → **fresh verifier session** (empty memory), full remount of the providers | nothing about **broker durability**: the profile **still holds the local repos** in IndexedDB, so a "fresh" reader may well reopen **from local** |
|
||||
| `spawnContext('shared')` — **non-persistent** context spawned from `freshBrowser` | `reconnexion-froide-sans-local.steps.ts` (@data) | that the data **reached the broker** (or did not) | nothing about the real UI journey (this is the harness, not the app) |
|
||||
|
||||
**Invariant.** Toute assertion de la forme « l'écriture est durable côté broker » **exige** le second
|
||||
montage. Écrire cette assertion sur une page fraîche du contexte persistant produit un test
|
||||
faussement vert (ou un rouge qu'on impute au broker alors qu'il est local/timing).
|
||||
**Invariant.** Any assertion of the form "the write is durable broker-side" **requires** the second setup. Making that assertion on a fresh page of the persistent context produces a false green (or a red blamed on the broker when it is really local/timing).
|
||||
|
||||
## Ce qui rend le verdict « no-local » valide (à ne pas casser)
|
||||
## What makes the "no-local" verdict valid (do not break it)
|
||||
|
||||
Trois conditions, toutes vérifiées dans `reconnexion-froide-sans-local.steps.ts` :
|
||||
Three conditions, all met in `reconnexion-froide-sans-local.steps.ts`:
|
||||
|
||||
1. **Process séparé** — `freshBrowser` est un `chromium.launch` non-persistant, distinct du profil
|
||||
porteur du wallet (cf. [[knowledge_multibrowser-harness]] pour l'isolation prouvée jusqu'à
|
||||
l'origine broker).
|
||||
2. **Partition hermétique** — chaque `newContext()` Playwright a son propre stockage ; aucun
|
||||
IndexedDB partagé avec la page d'écriture.
|
||||
3. **Le seul état pré-injecté est `pool.sharedWalletState`**, capturé **une fois au `BeforeAll`**,
|
||||
donc **avant** que le scénario n'écrive quoi que ce soit → le snapshot **ne peut pas** contenir la
|
||||
donnée sous test.
|
||||
1. **Separate process** — `freshBrowser` is a non-persistent `chromium.launch`, distinct from the profile carrying the wallet (see [[knowledge_multibrowser-harness]] for the isolation proven all the way to the broker origin).
|
||||
2. **Hermetic partition** — every Playwright `newContext()` has its own storage; no IndexedDB shared with the writing page.
|
||||
3. **The only pre-injected state is `pool.sharedWalletState`**, captured **once at `BeforeAll`**, hence **before** the scenario writes anything → the snapshot **cannot** contain the data under test.
|
||||
|
||||
> **Impact si on touche à la capture du storageState** (`hooks.ts` `BeforeAll` → `pool.sharedWalletState`) :
|
||||
> la déplacer plus tard, la ré-capturer par scénario, ou y ajouter un warm-up qui écrit des données
|
||||
> **invalide silencieusement** le verdict de tous les scénarios « à froid sans local » — ils
|
||||
> passeraient au vert en relisant le snapshot. Le step **échoue franchement** si
|
||||
> `sharedWalletState` est absent (c'est voulu : pas de verdict plutôt qu'un faux verdict).
|
||||
> **Impact if you touch the storageState capture** (`hooks.ts` `BeforeAll` → `pool.sharedWalletState`): moving it later, re-capturing it per scenario, or adding a warm-up that writes data **silently invalidates** the verdict of every "cold, no local" scenario — they would turn green by re-reading the snapshot. The step **fails outright** when `sharedWalletState` is missing (by design: no verdict beats a false verdict).
|
||||
|
||||
## Reconnexion ≠ isolation : c'est l'identifiant qui décide
|
||||
## Reconnection is not isolation — the identifier decides
|
||||
|
||||
`isolation.steps.ts` et `reconnexion.steps.ts` montent **la même mécanique** (page fraîche + un
|
||||
identifiant injecté dans `localStorage['festipod.account.identifier']` via `addInitScript`, avant
|
||||
tout script, sur toutes les origines). Une seule chose les sépare :
|
||||
`isolation.steps.ts` and `reconnexion.steps.ts` set up **the same machinery** (fresh page plus an identifier injected into `localStorage['festipod.account.identifier']` via `addInitScript`, before any script, on every origin). Only one thing tells them apart:
|
||||
|
||||
- **reconnexion** : on réinjecte `this.freshIdentifier` — **la MÊME identité** que la page d'écriture.
|
||||
- **isolation** : on frappe un **nouvel** identifiant → identité B distincte.
|
||||
- **reconnection**: `this.freshIdentifier` is re-injected — **the SAME identity** as the writing page.
|
||||
- **isolation**: a **new** identifier is minted → a distinct identity B.
|
||||
|
||||
Changer cet identifiant transforme donc silencieusement un test de reconnexion en test d'isolation
|
||||
(et réciproquement). `this.freshIdentifier` est posé par le `Before` de `hooks.ts` pour **tout**
|
||||
scénario `@data`/`@e2e` mono-navigateur.
|
||||
Changing that identifier therefore silently turns a reconnection test into an isolation test (and the other way round). `this.freshIdentifier` is set by the `Before` hook in `hooks.ts` for **every** single-browser `@data`/`@e2e` scenario.
|
||||
|
||||
## Lecture : réactive, même quand on « attend longtemps »
|
||||
## Reads stay reactive, even when "waiting a long time"
|
||||
|
||||
Les `Then` de reconnexion lisent l'état **réactif** (`homeEventTitles` sur le bridge, via
|
||||
`waitForFunction`) — jamais une boucle de re-lecture broker ([[rule_no-broker-polling]]). Le step de
|
||||
diagnostic long (« … en laissant jusqu'à 60 secondes à la barrière avec rechargements ») boucle bien,
|
||||
mais sur **l'état réactif déjà poussé** + des **rechargements complets** de la page (chaque reload =
|
||||
nouveau montage = nouvelle tentative de barrière de sync) : c'est le fallback pragmatique explicitement
|
||||
autorisé par la règle, pas du polling broker. Le distinguo à garder : *observer l'état réactif* ↔
|
||||
*ré-émettre une lecture broker*.
|
||||
The reconnection `Then` steps read the **reactive** state (`homeEventTitles` on the bridge, via `waitForFunction`) — never a broker re-read loop ([[rule_no-broker-polling]]). The long diagnostic step (« … en laissant jusqu'à 60 secondes à la barrière avec rechargements ») does loop, but over the **reactive state already pushed** plus **full page reloads** (each reload = new mount = new sync-barrier attempt): that is the pragmatic fallback the rule explicitly allows, not broker polling. The distinction to keep in mind — *observing the reactive state* versus *re-issuing a broker read*.
|
||||
|
||||
## État courant des scénarios
|
||||
## Current state of the scenarios
|
||||
|
||||
`reconnexion-froide-sans-local.feature`, le scénario `@reconnexion-pause` de
|
||||
`reconnexion-meme-identite.feature` et `reconnexion-persistance-e2e.feature` sont **`@wip`** : ce sont
|
||||
des **instruments de diagnostic** (ils impriment un verdict sur stdout / en pièce jointe Cucumber),
|
||||
pas des gardes de régression. `@wip` est exclu du run par défaut (`cucumber.json`) — les lancer
|
||||
explicitement avec `--tags`. Le scénario **non-`@wip`** de `reconnexion-meme-identite.feature`, lui,
|
||||
est une vraie garde et doit rester vert.
|
||||
`reconnexion-froide-sans-local.feature`, the `@reconnexion-pause` scenario of `reconnexion-meme-identite.feature` and `reconnexion-persistance-e2e.feature` are **`@wip`**: they are **diagnostic instruments** (they print a verdict to stdout / as a Cucumber attachment), not regression guards. `@wip` is excluded from the default run (`cucumber.json`) — run them explicitly with `--tags`. The **non-`@wip`** scenario of `reconnexion-meme-identite.feature`, on the other hand, is a genuine guard and must stay green.
|
||||
|
||||
> Le *pourquoi* côté NextGraph (ce qu'une écriture doit franchir pour être durable, comportement du
|
||||
> socket, réouverture des repos) appartient au SDK `@ng-eventually/client` — pas à ce repo. Ici on ne
|
||||
> décrit que **le montage de test qui rend un verdict lisible**.
|
||||
> The *why* on the NextGraph side (what a write must clear to be durable, socket behaviour, repo reopening) belongs to the `@ng-eventually/client` SDK — not to this repo. Here we only describe **the test setup that produces a readable verdict**.
|
||||
|
||||
## Liens
|
||||
## Links
|
||||
|
||||
- [[knowledge_data-layer-broker]] — la couche `@data` mono-navigateur (profil persistant).
|
||||
- [[knowledge_data-layer-broker]] — the single-browser `@data` layer (persistent profile).
|
||||
- [[knowledge_multibrowser-harness]] — `freshBrowser`, `spawnContext`, `pool.sharedWalletState`.
|
||||
- [[knowledge_e2e-layer]] — le pendant `@e2e` (app réelle) du montage « fermer et rouvrir ».
|
||||
- [[rule_no-broker-polling]] — la ligne rouge que les steps d'attente ne doivent pas franchir.
|
||||
- [[knowledge_e2e-layer]] — the `@e2e` counterpart (real app) of the "close and reopen" setup.
|
||||
- [[rule_no-broker-polling]] — the red line waiting steps must not cross.
|
||||
|
||||
@@ -1,21 +1,21 @@
|
||||
---
|
||||
type: caveat
|
||||
summary: world.ts garde des vestiges de l'ère « analyse de source » (screenFileMap, screenFieldDetectors, screenExpectedContent, screenRequiredFields ; hasText/hasField/hasElement à fallback source) — à supprimer une fois la migration @ui vers le DOM rendu terminée
|
||||
summary: world.ts still carries leftovers from the "source analysis" era (screenFileMap, screenFieldDetectors, screenExpectedContent, screenRequiredFields; hasText/hasField/hasElement with a source fallback) — to be deleted once the @ui migration to the rendered DOM is complete
|
||||
last_checked: 2026-06-15
|
||||
---
|
||||
|
||||
# Caveat : vestiges d'analyse de source dans `world.ts`
|
||||
# Caveat: source-analysis leftovers in `world.ts`
|
||||
|
||||
La suite `@ui` **précède** le contrat de couches ([[rule_test-layer-contracts]]). Des restes de l'ère « grep sur le code source » subsistent et **ne doivent pas être étendus** :
|
||||
The `@ui` suite **predates** the layer contract ([[rule_test-layer-contracts]]). Remnants of the "grep the source code" era are still around and **must not be extended**:
|
||||
|
||||
- `world.ts:screenFileMap`, `screenFieldDetectors`, `screenExpectedContent`, `screenRequiredFields` — mappings de l'approche analyse-de-source.
|
||||
- `hasText` / `hasField` / `hasElement` — **préfèrent désormais le DOM rendu** mais **retombent sur la source** pour que les steps non migrés continuent de marcher pendant la transition.
|
||||
- `world.ts:screenFileMap`, `screenFieldDetectors`, `screenExpectedContent`, `screenRequiredFields` — mappings from the source-analysis approach.
|
||||
- `hasText` / `hasField` / `hasElement` — they now **prefer the rendered DOM** but **fall back to the source** so that unmigrated steps keep working during the transition.
|
||||
|
||||
## Plan de migration (en cours)
|
||||
## Migration plan (in progress)
|
||||
|
||||
1. Réécrire les assertions grep-source → requêtes DOM via le render helper.
|
||||
2. Supprimer les tests sur détails d'implémentation (`/showDuplicateWarning/`, `/importableEvents/`, regex sur JSX).
|
||||
3. Déplacer les assertions comportementales vers `@e2e` quand pas déjà couvertes.
|
||||
4. Retirer les checks de contenu `@e2e` redondants avec `@ui`.
|
||||
1. Rewrite grep-the-source assertions as DOM queries through the render helper.
|
||||
2. Delete tests that assert implementation details (`/showDuplicateWarning/`, `/importableEvents/`, regexes over JSX).
|
||||
3. Move behavioural assertions to `@e2e` where they are not already covered.
|
||||
4. Drop the `@e2e` content checks that duplicate `@ui`.
|
||||
|
||||
Une fois la migration terminée, les 4 maps vestiges peuvent disparaître au profit d'assertions sur le DOM rendu + seed. **Tant qu'elles existent, ne pas s'appuyer dessus pour de nouveaux tests.**
|
||||
Once the migration is done, the 4 leftover maps can go away in favour of assertions on the rendered DOM plus seed data. **As long as they exist, do not rely on them for new tests.**
|
||||
|
||||
@@ -1,35 +1,21 @@
|
||||
---
|
||||
type: caveat
|
||||
summary: Le wallet de test partagé (.playwright-profile) accumule des données à chaque run ; passé un seuil, les sparql_query ancrées au private store hangent (>15s) et toute la suite @data échoue au setup — repartir d'un profil frais restaure des lectures ~1s
|
||||
summary: The shared test wallet (.playwright-profile) accumulates data on every run; past a threshold, sparql_query calls anchored to the private store hang (>15s) and the whole @data suite fails during setup — starting from a fresh profile restores ~1s reads
|
||||
last_checked: 2026-07-06
|
||||
---
|
||||
|
||||
# Piège : le wallet de test se gonfle et fait *hang* les lectures @data
|
||||
# Pitfall: the test wallet bloats and makes @data reads hang
|
||||
|
||||
Le profil Chromium persistant `.playwright-profile` (racine du working tree) porte le **wallet
|
||||
partagé** ouvert par toute la suite `@data`/`@e2e`. Ce wallet **accumule des données à chaque
|
||||
run** : comptes shim (un par scénario, via l'identifiant frais `freshScenarioIdentifier`), docs
|
||||
d'entités seedés, dépôts d'inbox historiques… Le private store est le **point d'ancrage du shim**
|
||||
(résolution de compte) et est interrogé par **toute** lecture/écriture (`resolveAccount`,
|
||||
`listMyEntityDocs`, …).
|
||||
The persistent Chromium profile `.playwright-profile` (at the root of the working tree) carries the **shared wallet** opened by the whole `@data`/`@e2e` suite. That wallet **accumulates data on every run**: shim accounts (one per scenario, through the fresh identifier `freshScenarioIdentifier`), seeded entity docs, historical inbox deposits… The private store is the **anchor point of the shim** (account resolution) and is queried by **every** read and write (`resolveAccount`, `listMyEntityDocs`, …).
|
||||
|
||||
**Symptôme.** Passé un certain volume (observé ~99 Mo de profil), une `sparql_query` **ancrée au
|
||||
private store** ne revient plus sous 15 s — elle *hang*. Comme la résolution de compte est sur le
|
||||
chemin de **chaque** read/write, **toute la suite @data échoue au setup** (0 événement chargé,
|
||||
timeouts), sans erreur explicite. Diagnostic vérifié : sur un wallet frais la même requête revient
|
||||
en **~1,5 s** et le seed complète normalement.
|
||||
**Symptom.** Past a certain volume (observed around 99 MB of profile), a `sparql_query` **anchored to the private store** stops returning within 15 s — it hangs. Since account resolution sits on the path of **every** read/write, **the entire @data suite fails during setup** (0 events loaded, timeouts), with no explicit error. Verified diagnosis: on a fresh wallet the same query comes back in **~1.5 s** and the seed completes normally.
|
||||
|
||||
**Contournement.** Mettre le profil gonflé de côté et laisser le hook d'auth (beforeAll) en
|
||||
recréer un frais :
|
||||
**Workaround.** Move the bloated profile aside and let the auth hook (beforeAll) recreate a fresh one:
|
||||
|
||||
```bash
|
||||
mv .playwright-profile /tmp/festipod-bloated-$(date +%s)
|
||||
```
|
||||
|
||||
L'identifiant frais par scénario (`freshScenarioIdentifier`) borne le *registre* des comptes mais
|
||||
**pas** la croissance physique du private store partagé — d'où la récurrence. Une hygiène durable
|
||||
(purge périodique / wallet jetable par run) reste à mettre en place ; en attendant, si les
|
||||
`resolveAccount failed`/timeouts réapparaissent, repartir d'un profil frais.
|
||||
The per-scenario fresh identifier (`freshScenarioIdentifier`) bounds the account *registry* but **not** the physical growth of the shared private store — hence the recurrence. Durable hygiene (periodic purge / throwaway wallet per run) still has to be put in place; until then, if the `resolveAccount failed` errors and timeouts come back, start again from a fresh profile.
|
||||
|
||||
> Le *pourquoi* côté broker (comment une requête ancrée touche le repo du private store) appartient
|
||||
> au SDK `@ng-eventually/client`, pas ici — ce caveat ne décrit que la conséquence côté tests.
|
||||
> The *why* on the broker side (how an anchored query reaches the private store repo) belongs to the `@ng-eventually/client` SDK, not here — this caveat only describes the consequence on the test side.
|
||||
|
||||
@@ -1,29 +1,29 @@
|
||||
---
|
||||
type: cookbook
|
||||
summary: Procédure pour ajouter un scénario/step BDD — .feature français taggé, steps par couche, piège de sérialisation de appFrame.evaluate (passer les args, pas de closure), ajouter les helpers aux DEUX harness, tag @wip pour le non-implémenté
|
||||
summary: How to add a BDD scenario/step — a tagged French .feature, steps per layer, the appFrame.evaluate serialization pitfall (pass arguments, no closures), add helpers to BOTH harnesses, @wip tag for what is not implemented yet
|
||||
---
|
||||
|
||||
# Cookbook : ajouter un scénario / un step
|
||||
# Cookbook: adding a scenario / a step
|
||||
|
||||
1. **Écrire le `.feature`** : `src/modules/{module}/features/us-N-slug.feature`, `# language: fr`, tag de tête `@CATEGORIE @priority-N`, et un tag de couche par scénario (`@ui` / `@data` / `@e2e`). Mots-clés FR : `Fonctionnalité`, `Contexte` (Background), `Scénario`, `Étant donné`/`Quand`/`Alors`. Tagger `@wip` un scénario dont les steps ne sont pas encore écrits.
|
||||
1. **Write the `.feature`**: `src/modules/{module}/features/us-N-slug.feature`, `# language: fr`, a header tag `@CATEGORIE @priority-N`, and one layer tag per scenario (`@ui` / `@data` / `@e2e`). French keywords: `Fonctionnalité`, `Contexte` (Background), `Scénario`, `Étant donné`/`Quand`/`Alors`. Tag `@wip` any scenario whose steps are not written yet.
|
||||
|
||||
2. **Choisir la couche** (cf. [[rule_test-layer-contracts]]) : assertion de rendu → `@ui` ; mutation/persistance → `@data` ; parcours complet → `@e2e`.
|
||||
2. **Pick the layer** (see [[rule_test-layer-contracts]]): rendering assertion → `@ui`; mutation/persistence → `@data`; full journey → `@e2e`.
|
||||
|
||||
3. **Écrire les steps** dans `src/modules/{module}/steps/{ui,data,e2e}/*.steps.ts` (ou `src/shared/steps/ui/` si cross-domaine). Signature : `async function (this: FestipodWorld, …)`. Importer `FestipodWorld` depuis `../../../../shared/support/world` (ajuster le chemin relatif).
|
||||
3. **Write the steps** in `src/modules/{module}/steps/{ui,data,e2e}/*.steps.ts` (or `src/shared/steps/ui/` if cross-domain). Signature: `async function (this: FestipodWorld, …)`. Import `FestipodWorld` from `../../../../shared/support/world` (adjust the relative path).
|
||||
|
||||
4. **Accès aux données selon la couche** :
|
||||
- `@ui` : `this.renderedDoc` / `this.getDomText()` / `this.hasText(...)` après `navigateTo(...)` (voir [[knowledge_ui-layer]]).
|
||||
- `@data`/`@e2e` : `await this.appFrame!.evaluate(fn, ...args)` sur le bridge `window.__testData` (voir [[knowledge_data-layer-broker]]).
|
||||
4. **Data access, per layer**:
|
||||
- `@ui`: `this.renderedDoc` / `this.getDomText()` / `this.hasText(...)` after `navigateTo(...)` (see [[knowledge_ui-layer]]).
|
||||
- `@data`/`@e2e`: `await this.appFrame!.evaluate(fn, ...args)` on the `window.__testData` bridge (see [[knowledge_data-layer-broker]]).
|
||||
|
||||
5. **⚠️ Piège de sérialisation `appFrame.evaluate`** : la fonction passée s'exécute **dans l'iframe**, les variables du step **ne sont pas capturées** (closures perdues). **Passer toute valeur en argument** :
|
||||
5. **⚠️ `appFrame.evaluate` serialization pitfall**: the function you pass runs **inside the iframe**, and the step's variables **are not captured** (closures are lost). **Pass every value as an argument**:
|
||||
```ts
|
||||
// ❌ const title = eventTitle; await appFrame.evaluate(() => td.getEventByTitle(title)) // title undefined
|
||||
// ❌ const title = eventTitle; await appFrame.evaluate(() => td.getEventByTitle(title)) // title is undefined
|
||||
// ✅ await appFrame.evaluate((t) => td.getEventByTitle(t), eventTitle)
|
||||
```
|
||||
Toujours `await` (oublier → assertion avant résolution).
|
||||
Always `await` (forgetting it means asserting before the promise resolves).
|
||||
|
||||
6. **Si tu ajoutes une opération de données** : exposer le helper sur `window.__testData` dans **les deux** harness (`src/shared/test-harness/harness.tsx` ET `harness-ng.tsx`) — sinon le fallback mock diverge du broker réel.
|
||||
6. **If you add a data operation**: expose the helper on `window.__testData` in **both** harnesses (`src/shared/test-harness/harness.tsx` AND `harness-ng.tsx`) — otherwise the mock fallback drifts away from the real broker.
|
||||
|
||||
7. **Câbler un écran testé** : si le nom français de l'écran ne se résout pas vers son `id`, ajouter un alias dans `screenNameMap` (`src/shared/steps/ui/navigation.steps.ts`).
|
||||
7. **Wire up a screen under test**: if the French screen name does not resolve to its `id`, add an alias in `screenNameMap` (`src/shared/steps/ui/navigation.steps.ts`).
|
||||
|
||||
8. **Lancer** : `bun run test:cucumber` (tout) ou `bun run test:data` (@data). Rapport : `reports/cucumber-report.html`. Le `@data`/`@e2e` exige le wallet de test (`bun run test:auth-setup` au premier coup si besoin, sinon création auto — cf. [[decision_2026-03-12_headless-wallet-creation]]).
|
||||
8. **Run**: `bun run test:cucumber` (everything) or `bun run test:data` (@data). Report: `reports/cucumber-report.html`. `@data`/`@e2e` require the test wallet (`bun run test:auth-setup` on the first go if needed, otherwise it is created automatically — see [[decision_2026-03-12_headless-wallet-creation]]).
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
type: decision
|
||||
summary: Décision 2026-03-12 — créer le wallet de test en automatisant l'UI broker headless (Playwright) plutôt que par API NG, car ça teste le vrai flux d'auth et évite de reverse-engineer l'API d'inscription
|
||||
summary: Decision 2026-03-12 — create the test wallet by automating the broker UI headlessly (Playwright) rather than through the NG API, because it exercises the real auth flow and avoids reverse-engineering the sign-up API
|
||||
---
|
||||
|
||||
# Automated Headless Wallet Creation for CI
|
||||
@@ -10,28 +10,28 @@ summary: Décision 2026-03-12 — créer le wallet de test en automatisant l'UI
|
||||
|
||||
## Context
|
||||
|
||||
Les tests `@data` exigent un wallet NextGraph dans un profil Chromium persistant. Avant, le premier run exigeait une interaction manuelle (navigateur visible, création de wallet à la main) → bloquait le CI.
|
||||
`@data` tests require a NextGraph wallet inside a persistent Chromium profile. Previously, the first run required manual interaction (visible browser, wallet created by hand) → CI was blocked.
|
||||
|
||||
## Options Considered
|
||||
|
||||
### Option A: création programmatique du wallet via SDK NG
|
||||
Appeler `ng.wallet_create()` depuis Node/Bun, sans UI.
|
||||
- **Pour** : plus rapide, pas de navigateur.
|
||||
- **Contre** : `@ng-org/web` est browser-only (WASM + postMessage) ; il faudrait reverse-engineer l'API d'inscription d'`account.nextgraph.eu` ; ne teste pas le vrai flux d'auth.
|
||||
### Option A: create the wallet programmatically through the NG SDK
|
||||
Call `ng.wallet_create()` from Node/Bun, without any UI.
|
||||
- **Pros**: faster, no browser needed.
|
||||
- **Cons**: `@ng-org/web` is browser-only (WASM + postMessage); we would have to reverse-engineer the sign-up API of `account.nextgraph.eu`; it does not exercise the real auth flow.
|
||||
|
||||
### Option B: automatiser le flux UI headless
|
||||
Piloter via Playwright la même UI de création de wallet, en headless.
|
||||
- **Pour** : teste le vrai flux auth/login de bout en bout ; pas de reverse-engineering ; même profil persistant réutilisé ; CI-ready sans étape manuelle.
|
||||
- **Contre** : dépend de `nextgraph.eu`/`account.nextgraph.eu` joignables ; fragile aux changements d'UI NextGraph ; +~27s au premier run.
|
||||
### Option B: automate the UI flow headlessly
|
||||
Drive the very same wallet-creation UI with Playwright, in headless mode.
|
||||
- **Pros**: exercises the real auth/login flow end to end; no reverse-engineering; the same persistent profile is reused; CI-ready with no manual step.
|
||||
- **Cons**: depends on `nextgraph.eu`/`account.nextgraph.eu` being reachable; brittle to NextGraph UI changes; adds ~27s to the first run.
|
||||
|
||||
## Decision
|
||||
|
||||
**Option B** — automatiser l'UI broker. Le flux de création (navigate → Create Wallet → ToS → username/password → submit) est lui-même un test légitime de la feature d'auth. La dépendance aux services externes est acceptable puisque les tests dépendent déjà du broker joignable.
|
||||
**Option B** — automate the broker UI. The creation flow (navigate → Create Wallet → ToS → username/password → submit) is itself a legitimate test of the auth feature. Depending on external services is acceptable since the tests already depend on the broker being reachable.
|
||||
|
||||
## Consequences
|
||||
|
||||
**Positif :** tests pleinement CI-ready (zéro interaction) ; flux auth testé en passant ; `bun run test:data` part d'un état propre.
|
||||
**Négatif :** exige un accès internet (nextgraph.eu, account.nextgraph.eu) ; fragile aux changements d'UI NextGraph (textes de boutons, IDs de formulaire).
|
||||
**Risque :** rate-limiting d'`account.nextgraph.eu` si le CI recrée souvent des wallets.
|
||||
**Positive:** fully CI-ready tests (zero interaction); the auth flow gets tested along the way; `bun run test:data` starts from a clean state.
|
||||
**Negative:** requires internet access (nextgraph.eu, account.nextgraph.eu); brittle to NextGraph UI changes (button texts, form IDs).
|
||||
**Risk:** rate-limiting from `account.nextgraph.eu` if CI recreates wallets often.
|
||||
|
||||
> Mécanique de cycle de vie détaillée : [[knowledge_data-layer-broker]].
|
||||
> Detailed lifecycle mechanics: [[knowledge_data-layer-broker]].
|
||||
|
||||
@@ -1,46 +1,46 @@
|
||||
---
|
||||
type: knowledge
|
||||
summary: Config Cucumber (cucumber.json, langue fr, loader tsx), layout des features/steps colocalisés par module, steps partagés dans shared/steps/, et les scripts qui génèrent features.ts/testResults.ts/stepDefinitions.ts
|
||||
summary: Cucumber config (cucumber.json, fr language, tsx loader), layout of features/steps colocated per module, shared steps under shared/steps/, and the scripts that generate features.ts/testResults.ts/stepDefinitions.ts
|
||||
---
|
||||
|
||||
# Setup Cucumber
|
||||
# Cucumber setup
|
||||
|
||||
26 fichiers `.feature` (US-1 à US-26), tous en **français**, taggés `@CATEGORIE @priority-N` (catégories EVENT, WORKSHOP, USER, MEETING, NOTIF).
|
||||
26 `.feature` files (US-1 to US-26), all in **French**, tagged `@CATEGORIE @priority-N` (categories EVENT, WORKSHOP, USER, MEETING, NOTIF).
|
||||
|
||||
## Layout
|
||||
|
||||
Features et steps **colocalisés avec leur module** :
|
||||
Features and steps are **colocated with their module**:
|
||||
|
||||
```
|
||||
src/modules/event/features/us-13-creer-evenement.feature
|
||||
src/modules/event/steps/{ui,data,e2e}/
|
||||
```
|
||||
|
||||
Steps **partagés** (cross-domaine) dans `src/shared/steps/ui/` :
|
||||
- `navigation.steps.ts` — navigation, auth, clics/sélections, assertions section/bouton/champ
|
||||
- `form.steps.ts` — validation de champs, champs requis, import/duplicate
|
||||
- `screen.steps.ts` — contenu d'écran (participants, events, profils, QR)
|
||||
**Shared** (cross-domain) steps live in `src/shared/steps/ui/`:
|
||||
- `navigation.steps.ts` — navigation, auth, clicks/selections, section/button/field assertions
|
||||
- `form.steps.ts` — field validation, required fields, import/duplicate
|
||||
- `screen.steps.ts` — screen content (participants, events, profiles, QR)
|
||||
|
||||
Les noms français des écrans (`"accueil"`, `"détail événement"`, `"mon profil"`…) mappent vers les IDs d'écran via `screenNameMap`.
|
||||
The French screen names (`"accueil"`, `"détail événement"`, `"mon profil"`…) map to screen IDs through `screenNameMap`.
|
||||
|
||||
Tags de scénario : `@ui` / `@data` / `@e2e` (couche) + **`@wip`** pour un scénario dont les steps ne sont pas encore implémentés **ou dont le comportement applicatif n'est pas encore fiable** (usage : marquer un attendu réel qui échoue à cause d'un bug produit, pas un test obsolète — ex. historique : la désinscription qui ne se reflétait pas dans l'UI, `@wip` **levé** depuis sa résolution T02.c, cf [[caveat_participation-deletion]]). **`@wip` est EXCLU du run par défaut** (`cucumber.json: "tags": "not @wip"`) : ces scénarios documentent un attendu sans casser la suite ; retirer le `@wip` quand c'est fiable. Un `Contexte` (Background) fréquent — « Étant donné que je suis connecté » — ne fait que poser un flag `isAuthenticated`, pas d'auth réelle en `@ui`.
|
||||
Scenario tags: `@ui` / `@data` / `@e2e` (layer) plus **`@wip`** for a scenario whose steps are not implemented yet **or whose application behaviour is not reliable yet** (intended use: flagging a genuine expectation that fails because of a product bug, not marking an obsolete test — historical example: sign-up cancellation not being reflected in the UI, `@wip` **lifted** once it was fixed in T02.c, see [[caveat_participation-deletion]]). **`@wip` is EXCLUDED from the default run** (`cucumber.json: "tags": "not @wip"`): those scenarios document an expectation without breaking the suite; drop the `@wip` once they are reliable. A common `Contexte` (Background) — « Étant donné que je suis connecté » — merely sets an `isAuthenticated` flag, there is no real auth in `@ui`.
|
||||
|
||||
## Config
|
||||
|
||||
`cucumber.json` : `import` de `src/shared/support/**`, `src/shared/steps/**`, `src/modules/*/steps/**` ; `paths` = `src/modules/*/features/**`; `tags: "not @wip"` (exclut les scénarios WIP) ; `language: fr`. **Runner = Node + tsx**, pas Bun — les plugins (Playwright, happy-dom) ne chargent pas en import Bun natif. Ne pas « bunifier » `cucumber:run`/`test:data`. ⚠️ Le runner doit pointer sur l'**entrée JS réelle du paquet** (`node_modules/@cucumber/cucumber/bin/cucumber.js`), **jamais** sur `node_modules/.bin/cucumber-js` : selon l'installeur, `.bin/` contient un **shim shell** (pas du JS) que `node --import tsx/esm` ne peut pas exécuter.
|
||||
`cucumber.json`: `import` of `src/shared/support/**`, `src/shared/steps/**`, `src/modules/*/steps/**`; `paths` = `src/modules/*/features/**`; `tags: "not @wip"` (excludes WIP scenarios); `language: fr`. **Runner = Node + tsx**, not Bun — the plugins (Playwright, happy-dom) do not load under a native Bun import. Do not "bunify" `cucumber:run`/`test:data`. ⚠️ The runner must point at the package's **actual JS entry** (`node_modules/@cucumber/cucumber/bin/cucumber.js`), **never** at `node_modules/.bin/cucumber-js`: depending on the installer, `.bin/` holds a **shell shim** (not JS) that `node --import tsx/esm` cannot execute.
|
||||
|
||||
## Le harness de test est buildé à la demande
|
||||
## The test harness is built on demand
|
||||
|
||||
Les harness `@data`/`@e2e` (`src/shared/test-harness/harness.tsx`, `harness-ng.tsx`) **ne sont pas** buildés par `build.ts`. Le `BeforeAll` de `hooks.ts` les compile **à la demande** (`bun build` → `dist/test-harness*.js`). Le wallet de test peut être créé d'avance via `bun run test:auth-setup` (`scripts/setup-test-auth.ts`), sinon il est créé automatiquement au premier run (cf. [[decision_2026-03-12_headless-wallet-creation]]).
|
||||
The `@data`/`@e2e` harnesses (`src/shared/test-harness/harness.tsx`, `harness-ng.tsx`) are **not** built by `build.ts`. The `BeforeAll` hook in `hooks.ts` compiles them **on demand** (`bun build` → `dist/test-harness*.js`). The test wallet can be created ahead of time with `bun run test:auth-setup` (`scripts/setup-test-auth.ts`); otherwise it is created automatically on the first run (see [[decision_2026-03-12_headless-wallet-creation]]).
|
||||
|
||||
## Fichiers auto-générés
|
||||
## Auto-generated files
|
||||
|
||||
Des scripts `scripts/` parsent features/steps en data TS consommée par l'outil de parcours :
|
||||
Scripts under `scripts/` parse features and steps into TS data consumed by the browsing tool:
|
||||
|
||||
| Script | Entrée | Sortie |
|
||||
| Script | Input | Output |
|
||||
|---|---|---|
|
||||
| `parse-features.ts` | `*/features/*.feature` | `src/shared/data/features.ts` |
|
||||
| `parse-test-results.ts` | `reports/cucumber-report.json` | `src/shared/data/testResults.ts` |
|
||||
| `extract-step-definitions.ts` | `shared/steps/ui/*.ts` | `src/shared/data/stepDefinitions.ts` |
|
||||
|
||||
Lancer : `bun run test:cucumber` (tout), `bun run test:data` (@data). Après ajout de steps : `bun run steps:extract`.
|
||||
Run: `bun run test:cucumber` (everything), `bun run test:data` (@data). After adding steps: `bun run steps:extract`.
|
||||
|
||||
@@ -1,71 +1,42 @@
|
||||
---
|
||||
type: knowledge
|
||||
summary: Couche @data — Playwright pilote Chromium (profil persistant) qui s'authentifie au broker NextGraph réel chargeant harness-ng.tsx en iframe ; cycle de vie wallet automatisé (création + login bootstrap), bridge window.__testData, fallback mock ; isolation par identifiant virtuel frais (this.freshIdentifier), plus de purge par scénario
|
||||
summary: The @data layer — Playwright drives Chromium (persistent profile), which logs into the real NextGraph broker that loads harness-ng.tsx in an iframe; automated wallet lifecycle (creation + bootstrap login), window.__testData bridge, mock fallback; per-scenario isolation through a fresh virtual identifier (this.freshIdentifier), no more per-scenario purge
|
||||
last_checked: 2026-07-27
|
||||
---
|
||||
|
||||
# Couche `@data` (broker réel)
|
||||
# The `@data` layer (real broker)
|
||||
|
||||
`@data` teste le **vrai pipeline NextGraph** via un broker, pas des données mockées.
|
||||
`@data` exercises the **real NextGraph pipeline** through a broker, not mocked data.
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
Cucumber → Playwright (Chromium, profil persistant)
|
||||
→ broker wallet login (automatisé)
|
||||
→ broker charge le harness en iframe (http://127.0.0.1:{port})
|
||||
Cucumber → Playwright (Chromium, persistent profile)
|
||||
→ broker wallet login (automated)
|
||||
→ broker loads the harness in an iframe (http://127.0.0.1:{port})
|
||||
→ harness-ng.tsx (init → useShape → ORM → broker)
|
||||
→ bridge window.__testData
|
||||
→ window.__testData bridge
|
||||
```
|
||||
|
||||
**Dual mode** : broker réel (`harness-ng.tsx`, défaut) ou fallback mock (`harness.tsx`, DeepSignalSets standalone si le build NG échoue).
|
||||
**Dual mode**: real broker (`harness-ng.tsx`, the default) or mock fallback (`harness.tsx`, standalone DeepSignalSets if the NG build fails).
|
||||
|
||||
## Cycle de vie du wallet (automatisé, CI-ready)
|
||||
## Wallet lifecycle (automated, CI-ready)
|
||||
|
||||
- **Premier run** : pas de marker `.wallet-ready` → Chromium headless crée le wallet (`nextgraph.eu` → Create Wallet → ToS sur `account.nextgraph.eu` → username/password → submit), **puis se logge** — ce login initial est requis pour amorcer la session (sauvé en localStorage) ; sans lui, les écritures ne passeraient pas. Marker écrit.
|
||||
- **Runs suivants** : marker trouvé → login automatisé (click Login → wallet → password → submit) → harness en iframe → `window.__testData.ready`.
|
||||
- Credentials wallet : `festipod-tests` / `festipod-tests`.
|
||||
- **First run**: no `.wallet-ready` marker → headless Chromium creates the wallet (`nextgraph.eu` → Create Wallet → ToS on `account.nextgraph.eu` → username/password → submit), **then logs in** — that initial login is required to bootstrap the session (saved in localStorage); without it, writes would not go through. Marker written.
|
||||
- **Subsequent runs**: marker found → automated login (click Login → wallet → password → submit) → harness in the iframe → `window.__testData.ready`.
|
||||
- Wallet credentials: `festipod-tests` / `festipod-tests`.
|
||||
|
||||
> Le choix « automatiser l'UI headless plutôt que créer le wallet par API » est tranché dans [[decision_2026-03-12_headless-wallet-creation]].
|
||||
> The choice of "automating the headless UI rather than creating the wallet through an API" is settled in [[decision_2026-03-12_headless-wallet-creation]].
|
||||
|
||||
## Détails techniques
|
||||
## Technical details
|
||||
|
||||
- **Flags Chromium** (`--disable-web-security`, `--allow-insecure-localhost`, désactivation de Private Network Access) : nécessaires car le broker public charge un harness `http://127.0.0.1` en iframe.
|
||||
- **Profil persistant** `.playwright-profile/` (gitignored, wallet en localStorage) — exige le vrai binaire Chrome, pas `chrome-headless-shell`.
|
||||
- **Serveur HTTP** lancé en `BeforeAll` (port auto), sert le HTML + `/harness.js` (fichiers séparés — le script inline casse à cause de caractères spéciaux du bundle).
|
||||
- **Bridge = le vrai chemin app (per-entité).** Depuis le passage à *un document par entité*
|
||||
(concept `data-layer`, [[rule_document-per-entity]]), le bridge `window.__testData`
|
||||
(`events`/`users`/`participations`, `joinEvent`/`leaveEvent`/`isParticipating`/
|
||||
`getEventParticipants`, `loadTestData`) **délègue au contexte de données de l'app**
|
||||
(`appData` via `FestipodDataProvider`) — c'est le chemin per-entité réel des écrans, pas une
|
||||
lecture au niveau du store-racine. Le harness monte donc l'**`AccountProvider`** et se logge
|
||||
par défaut (`@mariedupont`) pour établir l'identité courante (sans quoi le filtre ReadCap ne
|
||||
laisserait passer que le public). Il lit `appData` via une **ref vivante** (un snapshot capturé
|
||||
devient périmé après un re-rendu de seed).
|
||||
- Chemins probes de bas niveau conservés (scope store-racine `protectedNuri`) pour les
|
||||
scénarios ReadCap/isolation qui *gouvernent* ce document : `rawJoin`/`rawParticipations`,
|
||||
`governDocument`/`governProtected`/`documentNuri`, `FilterProbe`/`FanoutProbe`.
|
||||
- **Identité avant écriture.** Une `Participation` a un `fp:user` obligatoire ; comme la lecture
|
||||
du profil peut retarder derrière les events publics, les steps attendent
|
||||
`ensureCurrentUser()` avant `joinEvent` (sinon participation écrite sans user → jetée en
|
||||
lecture, ne fait jamais l'aller-retour) et attendent (`waitForFunction`) que la participation
|
||||
soit relue.
|
||||
- **Isolation par scénario = identifiant virtuel frais, PAS de purge.** Le `Before` @data mint un
|
||||
identifiant unique par scénario (`freshScenarioIdentifier` dans `hooks.ts`), l'expose en
|
||||
`this.freshIdentifier` sur le World, et l'injecte par `addInitScript` dans
|
||||
`localStorage['festipod.account.identifier']` **sur toutes les origines** (y compris l'iframe
|
||||
harness sur 127.0.0.1) — avant tout script. Le shim sert alors un **compte virtuel frais et vide**,
|
||||
dont le registre part vide *par construction* : **rien à purger**. L'ancien reset par scénario
|
||||
(`window.__testData.resetDataState()`, un SPARQL DELETE des records
|
||||
`urn:ng-eventually:shim:Account` sur le graphe ancre) **n'est plus appelé** — il coûtait jusqu'à
|
||||
10 s prélevés sur le budget 60 s du `Before`, déjà mangé par le login broker. Le helper existe
|
||||
encore sur le bridge (`harness-ng.tsx`) mais n'est plus dans le chemin par défaut : ne pas le
|
||||
remettre dans le `Before` sans mesurer.
|
||||
- **Ce que l'identifiant frais NE borne PAS** : la croissance *physique* du wallet partagé — voir
|
||||
[[caveat_wallet-bloat-hang]] (profil à mettre de côté quand les lectures ancrées se mettent à
|
||||
*hang*).
|
||||
- `this.freshIdentifier` est aussi ce qui distingue un test de **reconnexion** (même identifiant
|
||||
réinjecté) d'un test d'**isolation** (nouvel identifiant) — cf.
|
||||
[[caveat_reconnexion-froide-local-vs-broker]].
|
||||
- Le seed connecté reste **allégé** (peu de docs) car chaque `docCreate` est un aller-retour broker
|
||||
sériel ~2s.
|
||||
- **Chromium flags** (`--disable-web-security`, `--allow-insecure-localhost`, Private Network Access turned off): necessary because the public broker loads a `http://127.0.0.1` harness in an iframe.
|
||||
- **Persistent profile** `.playwright-profile/` (gitignored, wallet in localStorage) — requires the real Chrome binary, not `chrome-headless-shell`.
|
||||
- **HTTP server** started in `BeforeAll` (auto-assigned port), serving the HTML plus `/harness.js` (separate files — an inline script breaks because of special characters in the bundle).
|
||||
- **The bridge is the real app path (per entity).** Since the move to *one document per entity* (concept `data-layer`, [[rule_document-per-entity]]), the `window.__testData` bridge (`events`/`users`/`participations`, `joinEvent`/`leaveEvent`/`isParticipating`/`getEventParticipants`, `loadTestData`) **delegates to the app's data context** (`appData` through `FestipodDataProvider`) — this is the real per-entity path the screens use, not a read at root-store level. The harness therefore mounts the **`AccountProvider`** and logs in by default (`@mariedupont`) to establish the current identity (without it the ReadCap filter would only let public data through). It reads `appData` through a **live ref** (a captured snapshot goes stale after a seed re-render).
|
||||
- Low-level probe paths are kept (root-store scope `protectedNuri`) for the ReadCap/isolation scenarios that *govern* that document: `rawJoin`/`rawParticipations`, `governDocument`/`governProtected`/`documentNuri`, `FilterProbe`/`FanoutProbe`.
|
||||
- **Identity before writing.** A `Participation` has a mandatory `fp:user`; since reading the profile can lag behind the public events, the steps wait for `ensureCurrentUser()` before `joinEvent` (otherwise a participation is written without a user → dropped on read, and never makes the round trip) and then wait (`waitForFunction`) for the participation to be read back.
|
||||
- **Per-scenario isolation = a fresh virtual identifier, NOT a purge.** The @data `Before` hook mints a unique identifier per scenario (`freshScenarioIdentifier` in `hooks.ts`), exposes it as `this.freshIdentifier` on the World, and injects it via `addInitScript` into `localStorage['festipod.account.identifier']` **on every origin** (including the harness iframe on 127.0.0.1) — before any script. The shim then serves a **fresh, empty virtual account**, whose registry starts empty *by construction*: **nothing to purge**. The old per-scenario reset (`window.__testData.resetDataState()`, a SPARQL DELETE of the `urn:ng-eventually:shim:Account` records on the anchor graph) is **no longer called** — it cost up to 10 s taken out of the 60 s budget of the `Before` hook, already eaten by the broker login. The helper still exists on the bridge (`harness-ng.tsx`) but is no longer on the default path: do not put it back into the `Before` hook without measuring.
|
||||
- **What the fresh identifier does NOT bound**: the *physical* growth of the shared wallet — see [[caveat_wallet-bloat-hang]] (profile to be moved aside when anchored reads start to hang).
|
||||
- `this.freshIdentifier` is also what distinguishes a **reconnection** test (same identifier re-injected) from an **isolation** test (new identifier) — see [[caveat_reconnexion-froide-local-vs-broker]].
|
||||
- The connected seed stays **lightweight** (few docs) because each `docCreate` is a serial broker round trip of about 2s.
|
||||
|
||||
@@ -1,107 +1,77 @@
|
||||
---
|
||||
type: knowledge
|
||||
summary: Couche @e2e — Playwright boote l'app RÉELLE (pas un harness) dans l'iframe broker, interagit via appFrame.evaluate()/locator(), réutilise setupBrokerPage() de @data ; teste navigation/redirects/clics, pas de fallback mock ; identité par scénario (this.freshIdentifier) + barrière d'accès désactivée par init script ; idiome « fermer et rouvrir » pour les scénarios de reconnexion
|
||||
summary: The @e2e layer — Playwright boots the REAL app (not a harness) inside the broker iframe, interacts through appFrame.evaluate()/locator(), reuses setupBrokerPage() from @data; tests navigation/redirects/clicks, no mock fallback; per-scenario identity (this.freshIdentifier) plus the access barrier disabled by init script; "close and reopen" idiom for reconnection scenarios
|
||||
last_checked: 2026-07-27
|
||||
---
|
||||
|
||||
# Couche `@e2e` (app réelle)
|
||||
# The `@e2e` layer (real app)
|
||||
|
||||
`@e2e` teste l'**UI de l'app réelle** tournant dans l'iframe broker — contrairement à `@data` qui charge un harness de test.
|
||||
`@e2e` tests the **UI of the real app** running inside the broker iframe — unlike `@data`, which loads a test harness.
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
Cucumber → Playwright (Chromium, profil persistant)
|
||||
Cucumber → Playwright (Chromium, persistent profile)
|
||||
→ https://nextgraph.net/redir/#/?o=http://127.0.0.1:{appPort}
|
||||
→ login broker (automatisé, même mécanique que @data)
|
||||
→ broker charge la VRAIE APP en iframe
|
||||
→ app rend avec NextGraphProvider auto-connectant
|
||||
→ steps via appFrame.evaluate() + locators Playwright
|
||||
→ broker login (automated, same machinery as @data)
|
||||
→ broker loads the REAL APP in an iframe
|
||||
→ app renders with a self-connecting NextGraphProvider
|
||||
→ steps through appFrame.evaluate() + Playwright locators
|
||||
```
|
||||
|
||||
**Serveur app** : lancé en `BeforeAll` (`spawn('bun', ['src/index.ts'], { env: { PORT } })`, poll jusqu'à réponse HTTP, tué en `AfterAll`). Réutilise le helper `setupBrokerPage()` de `@data` (redirect, login, découverte de l'iframe).
|
||||
**App server**: started in `BeforeAll` (`spawn('bun', ['src/index.ts'], { env: { PORT } })`, polled until it answers over HTTP, killed in `AfterAll`). It reuses the `setupBrokerPage()` helper from `@data` (redirect, login, iframe discovery).
|
||||
|
||||
## Step definitions
|
||||
|
||||
Dans les modules (ex. `src/modules/auth/steps/e2e/connexion.steps.ts`) :
|
||||
- `this.appFrame!.evaluate()` — JS dans l'iframe app (navigation hash/path, checks de contenu)
|
||||
- `this.appFrame!.locator()` — éléments DOM
|
||||
- `this.appFrame!.waitForFunction()` — poll d'état attendu
|
||||
- `SCREEN_MARKERS` — map ID d'écran → texte unique de vérification
|
||||
Inside the modules (e.g. `src/modules/auth/steps/e2e/connexion.steps.ts`):
|
||||
- `this.appFrame!.evaluate()` — JS inside the app iframe (hash/path navigation, content checks)
|
||||
- `this.appFrame!.locator()` — DOM elements
|
||||
- `this.appFrame!.waitForFunction()` — poll for an expected state
|
||||
- `SCREEN_MARKERS` — map from screen ID to a unique verification text
|
||||
|
||||
Navigation : `window.history.pushState` + dispatch `popstate` (routing path-based, cf. `app-architecture`).
|
||||
Navigation: `window.history.pushState` plus a `popstate` dispatch (path-based routing, see `app-architecture`).
|
||||
|
||||
## Différences avec `@data`
|
||||
## Differences from `@data`
|
||||
|
||||
| Aspect | `@data` | `@e2e` |
|
||||
|---|---|---|
|
||||
| Chargé en iframe | harness (`harness-ng.tsx`) | app réelle (`src/index.ts`) |
|
||||
| Signal ready | `window.__testData.ready` | `root.innerHTML.length > 100` |
|
||||
| Interaction | bridge `evaluate()` | `evaluate()` + locators |
|
||||
| Fallback mock | oui | **non** (broker réel requis) |
|
||||
| Teste | opérations données | comportement UI (nav, redirects, clics) |
|
||||
| Loaded in the iframe | harness (`harness-ng.tsx`) | real app (`src/index.ts`) |
|
||||
| Ready signal | `window.__testData.ready` | `root.innerHTML.length > 100` |
|
||||
| Interaction | `evaluate()` bridge | `evaluate()` + locators |
|
||||
| Mock fallback | yes | **no** (real broker required) |
|
||||
| Tests | data operations | UI behaviour (nav, redirects, clicks) |
|
||||
|
||||
> **Ne pas re-vérifier en `@e2e` ce que `@ui` couvre déjà** — `@e2e` doit casser quand la *collaboration* entre couches casse, pas quand une icône change (cf. [[rule_test-layer-contracts]]).
|
||||
> **Do not re-check in `@e2e` what `@ui` already covers** — `@e2e` must break when the *collaboration* between layers breaks, not when an icon changes (see [[rule_test-layer-contracts]]).
|
||||
|
||||
## Identité du scénario + barrière d'accès
|
||||
## Scenario identity + access barrier
|
||||
|
||||
Deux réglages posés par le `Before` de `hooks.ts` conditionnent **tout** scénario `@e2e` :
|
||||
Two settings applied by the `Before` hook in `hooks.ts` govern **every** `@e2e` scenario:
|
||||
|
||||
- **`this.freshIdentifier`** — un identifiant virtuel **unique par scénario**, injecté par
|
||||
`addInitScript` dans `localStorage['festipod.account.identifier']` sur **toutes** les origines
|
||||
avant tout script. L'app réelle boote donc directement sur cette identité, et chaque scénario part
|
||||
d'un espace vide. C'est la **même** mécanique qu'en `@data` (même champ du World).
|
||||
- **Barrière d'accès désactivée** — `browserContext.addInitScript` pose
|
||||
`globalThis.__FESTIPOD_ACCESS_GATE_DISABLED__ = true` sur le contexte **persistant** : `@e2e` voit
|
||||
l'app, pas l'`AccessGateScreen`. Les contextes **frais** (`@humain`, cf.
|
||||
[[knowledge_multibrowser-harness]]) n'héritent pas de ce réglage → barrière ON chez eux.
|
||||
- **`this.freshIdentifier`** — a virtual identifier **unique to each scenario**, injected via `addInitScript` into `localStorage['festipod.account.identifier']` on **every** origin before any script. The real app therefore boots straight into that identity, and each scenario starts from an empty space. This is the **same** machinery as in `@data` (same World field).
|
||||
- **Access barrier disabled** — `browserContext.addInitScript` sets `globalThis.__FESTIPOD_ACCESS_GATE_DISABLED__ = true` on the **persistent** context: `@e2e` sees the app, not the `AccessGateScreen`. **Fresh** contexts (`@humain`, see [[knowledge_multibrowser-harness]]) do not inherit that setting → the barrier is ON for them.
|
||||
|
||||
> **Impact :** toute page ouverte à la main dans un step (`ctx.newPage()`) doit **re-poser les deux
|
||||
> init scripts elle-même** — `addInitScript` du contexte ne s'applique qu'aux pages du contexte, et
|
||||
> l'identifiant doit être écrit **avant** le premier script de l'app.
|
||||
> **Impact:** any page opened by hand inside a step (`ctx.newPage()`) must **re-apply both init scripts itself** — the context's `addInitScript` only applies to pages of that context, and the identifier must be written **before** the app's first script.
|
||||
|
||||
## Idiome « fermer et rouvrir » (scénarios de reconnexion)
|
||||
## The "close and reopen" idiom (reconnection scenarios)
|
||||
|
||||
`reconnexion-persistance-e2e.feature` / `src/modules/event/steps/e2e/reconnexion-persistance.steps.ts`
|
||||
reproduisent, dans la VRAIE app, le parcours « je crée, je ferme, je reviens » :
|
||||
`reconnexion-persistance-e2e.feature` / `src/modules/event/steps/e2e/reconnexion-persistance.steps.ts` reproduce the "I create, I close, I come back" journey inside the REAL app:
|
||||
|
||||
1. **Création par le vrai formulaire** — le step pilote l'assistant de création réel au DOM
|
||||
(assistant en 3 étapes, sélection par *placeholder* : nom de l'événement, lieu ; bouton de
|
||||
soumission par son libellé). ⚠️ **Ces steps sont couplés aux libellés FR de l'écran de création** :
|
||||
renommer un placeholder ou le bouton de soumission casse le scénario, pas l'app.
|
||||
2. **Réouverture** — seconde page sur le **même** contexte persistant, avec la **même**
|
||||
`this.freshIdentifier` + la barrière désactivée, puis `pool.setupBrokerPage(page, pool.appUrl!)`
|
||||
→ nouveau login broker, session verifier fraîche.
|
||||
3. **Preuve** — le step capture la console des **deux** pages et publie un résumé via `this.attach`
|
||||
(pièce jointe Cucumber) + stdout ; un dump brut des lignes de connexion/sync est **opt-in** par
|
||||
la variable d'environnement `RECO_RAW_DUMP=1` (bruyant, coupé par défaut).
|
||||
1. **Creation through the real form** — the step drives the actual creation wizard at DOM level (3-step wizard, selection by *placeholder*: event name, venue; submit button by its label). ⚠️ **These steps are coupled to the French labels of the creation screen**: renaming a placeholder or the submit button breaks the scenario, not the app.
|
||||
2. **Reopening** — a second page on the **same** persistent context, with the **same** `this.freshIdentifier` and the barrier disabled, then `pool.setupBrokerPage(page, pool.appUrl!)` → new broker login, fresh verifier session.
|
||||
3. **Proof** — the step captures the console of **both** pages and publishes a summary through `this.attach` (Cucumber attachment) plus stdout; a raw dump of the connection/sync lines is **opt-in** through the `RECO_RAW_DUMP=1` environment variable (noisy, off by default).
|
||||
|
||||
> **Limite à connaître** : ce montage prouve la reconnexion *du parcours*, **pas** la durabilité
|
||||
> broker de l'écriture — la seconde page partage l'IndexedDB du profil persistant. Voir
|
||||
> [[caveat_reconnexion-froide-local-vs-broker]] pour le montage qui, lui, tranche broker-vs-local.
|
||||
> **Limitation to know about**: this setup proves the reconnection *of the journey*, **not** the broker durability of the write — the second page shares the IndexedDB of the persistent profile. See [[caveat_reconnexion-froide-local-vs-broker]] for the setup that does settle broker-vs-local.
|
||||
|
||||
Le scénario est **`@wip`** (instrument de diagnostic, exclu du run par défaut).
|
||||
The scenario is **`@wip`** (diagnostic instrument, excluded from the default run).
|
||||
|
||||
## Smoke `@smoke` — garde la classe « page blanche une fois connecté »
|
||||
## `@smoke` — guarding the "blank page once connected" class
|
||||
|
||||
`@e2e @smoke` (`src/modules/home/features/accueil-connecte-rend.feature`) garde une
|
||||
CLASSE de régression : un crash de rendu qui ne survient QUE une fois l'app connectée
|
||||
et montée sur des données réelles (symptôme : seul le bandeau de l'iframe broker
|
||||
s'affiche, `#root` reste vide). Le smoke réutilise le boot du hook `Before` @e2e,
|
||||
navigue vers l'accueil connecté et asserte DEUX choses :
|
||||
1. **HomeScreen a réellement monté** — présence de marqueurs forts (`.app-navbar` +
|
||||
bouton `[aria-label="Relayer un événement"]`), absents d'un spinner / du bandeau
|
||||
broker. Un `throw` dans un composant/provider monté après connexion démonte l'arbre
|
||||
(aucun `ErrorBoundary`) → ces marqueurs disparaissent → rouge.
|
||||
2. **Zéro erreur runtime** — `this.pageErrors` (voir ci-dessous) doit être vide.
|
||||
`@e2e @smoke` (`src/modules/home/features/accueil-connecte-rend.feature`) guards a CLASS of regression: a rendering crash that happens ONLY once the app is connected and mounted on real data (symptom: only the broker iframe banner shows, `#root` stays empty). The smoke test reuses the boot from the @e2e `Before` hook, navigates to the connected home screen and asserts TWO things:
|
||||
1. **HomeScreen really mounted** — presence of strong markers (`.app-navbar` plus the `[aria-label="Relayer un événement"]` button), absent from a spinner or from the broker banner. A `throw` inside a component/provider mounted after connection unmounts the tree (there is no `ErrorBoundary`) → those markers disappear → red.
|
||||
2. **Zero runtime errors** — `this.pageErrors` (see below) must be empty.
|
||||
|
||||
Le hook `Before` @e2e **collecte** désormais dans le World les `pageerror` +
|
||||
`console.error` de la page app (champ `pageErrors`, réinitialisé par scénario) — c'est
|
||||
ce qui rend l'assertion « pas d'erreur » possible. Le run par défaut de `bun run
|
||||
validate` exécute `@smoke and not @wip` (pas tout `@e2e`, pour rester rapide).
|
||||
**Preuve de détection** : un `throw` en tête de `HomeScreen` fait virer le smoke au
|
||||
rouge ; sans lui, vert.
|
||||
The @e2e `Before` hook now **collects** the app page's `pageerror` and `console.error` events into the World (field `pageErrors`, reset per scenario) — that is what makes the "no error" assertion possible. The default run of `bun run validate` executes `@smoke and not @wip` (not all of `@e2e`, to stay fast). **Detection proof**: a `throw` at the top of `HomeScreen` turns the smoke test red; without it, green.
|
||||
|
||||
## Fichiers clés
|
||||
## Key files
|
||||
|
||||
`src/shared/support/hooks.ts` (lifecycle Playwright + collecte `pageErrors`), `world.ts` (champs `page`/`appFrame`/`pageErrors`), `scripts/debug-browser.ts` (debug headed), `.playwright-profile{,-debug}/` (gitignored).
|
||||
`src/shared/support/hooks.ts` (Playwright lifecycle + `pageErrors` collection), `world.ts` (fields `page`/`appFrame`/`pageErrors`), `scripts/debug-browser.ts` (headed debugging), `.playwright-profile{,-debug}/` (gitignored).
|
||||
|
||||
@@ -1,70 +1,70 @@
|
||||
---
|
||||
type: knowledge
|
||||
summary: Harness multi-navigateur sur DEUX axes orthogonaux — nombre de navigateurs (machinerie, contextes frais isolés via un freshBrowser non-persistant) ET modèle de wallet (own/@private-wallet vs shared/@shared-wallet) ; shared provisionné par injection storageState (test) ; e2e @humain qui valide le mécanisme produit RÉEL via la vraie app staging (fichier .ngw téléchargé depuis l'écran → import nextgraph.eu « Import a Wallet File » → Entrer → connecté) ; convention @wip exclue via cucumber.json
|
||||
summary: Multi-browser harness along TWO orthogonal axes — number of browsers (the machinery, isolated fresh contexts spawned from a non-persistent freshBrowser) AND wallet model (own/@private-wallet vs shared/@shared-wallet); shared is provisioned by storageState injection (test-only); an @humain e2e validates the REAL product mechanism through the real staging app (.ngw file downloaded from the screen → nextgraph.eu "Import a Wallet File" → Entrer → connected); @wip convention excluded through cucumber.json
|
||||
last_checked: 2026-06-16
|
||||
---
|
||||
|
||||
# Harness multi-navigateur (private-wallet vs shared-wallet)
|
||||
# Multi-browser harness (private-wallet vs shared-wallet)
|
||||
|
||||
Capacité du harness `@data`/`@e2e` à piloter **plusieurs navigateurs isolés** dans un même scénario, sous **deux axes orthogonaux**. Permet de tester à la fois le modèle « chacun son wallet » (`@private-wallet`) et le modèle « wallet partagé entre navigateurs » (`@shared-wallet`).
|
||||
The ability of the `@data`/`@e2e` harness to drive **several isolated browsers** within a single scenario, along **two orthogonal axes**. It makes it possible to test both the "everyone has their own wallet" model (`@private-wallet`) and the "wallet shared between browsers" model (`@shared-wallet`).
|
||||
|
||||
## Les deux axes (orthogonaux)
|
||||
## The two axes (orthogonal)
|
||||
|
||||
| Axe | Ce qu'il décide | Exprimé par |
|
||||
| Axis | What it decides | Expressed by |
|
||||
|---|---|---|
|
||||
| **Nombre de navigateurs** (machinerie) | 1..N contextes nommés isolés | `openBrowser(name, …)` + steps `… dans le navigateur "X"` |
|
||||
| **Modèle de wallet** | identité NG distincte vs partagée | **phrasing du step + tag** (voir ci-dessous) |
|
||||
| **Number of browsers** (machinery) | 1..N isolated named contexts | `openBrowser(name, …)` + steps `… dans le navigateur "X"` |
|
||||
| **Wallet model** | distinct vs shared NG identity | **step phrasing + tag** (see below) |
|
||||
|
||||
Ne **pas** confondre `@multibrowser` (plusieurs navigateurs) avec `@shared-wallet` (même wallet) : on fait du multibrowser **en private** (chacun son wallet) **et en shared** (wallet partagé), et on compare les deux setups avec les **mêmes** steps de comportement.
|
||||
Do **not** confuse `@multibrowser` (several browsers) with `@shared-wallet` (same wallet): we run multibrowser **in private** (everyone with their own wallet) **and in shared** (shared wallet), and compare both setups with the **same** behavioural steps.
|
||||
|
||||
## Modèle de wallet : phrasing + tags
|
||||
## Wallet model: phrasing + tags
|
||||
|
||||
- `Étant donné un navigateur "A" avec son propre wallet` → modèle **own**, tag `@private-wallet`.
|
||||
- `Étant donné un navigateur "A" avec le wallet partagé` → modèle **shared**, tag `@shared-wallet`.
|
||||
- Tag umbrella `@multibrowser` (feature entière).
|
||||
- `Étant donné un navigateur "A" avec son propre wallet` → **own** model, tag `@private-wallet`.
|
||||
- `Étant donné un navigateur "A" avec le wallet partagé` → **shared** model, tag `@shared-wallet`.
|
||||
- Umbrella tag `@multibrowser` (whole feature).
|
||||
|
||||
## Architecture (où vit quoi)
|
||||
## Architecture (where things live)
|
||||
|
||||
- **`src/shared/support/browserPool.ts`** — état partagé + fabrique. Hors du contexte Chromium **persistant** porteur du wallet partagé (legacy mono-navigateur `@data`/`@e2e`, **inchangé**, cf. [[knowledge_data-layer-broker]]), le harness lance un navigateur **non-persistant** `freshBrowser` (`chromium.launch`) qui mint des contextes frais et isolés à la demande (`spawnContext(wallet)`). Module importé par `hooks.ts` (cycle de vie) et `world.ts` (usage par scénario) — pas de cycle d'import.
|
||||
- **`world.ts`** — API : `openBrowser(name, wallet)`, `browser(name)`, `loadAppInBrowser(name, 'app'|'harness')`, `closeBrowsers()` ; registre `browsers: Map<name, NamedBrowser>`. Navigateurs nommés fermés en `After`, `freshBrowser` en `AfterAll`.
|
||||
- **`hooks.ts`** — un scénario taggé `@multibrowser` **ne reçoit pas** la page unique legacy ; les steps ouvrent les navigateurs. Exige le mode broker réel (`freshBrowser` indispo en fallback mock).
|
||||
- **`src/shared/support/browserPool.ts`** — shared state + factory. Outside the **persistent** Chromium context that carries the shared wallet (legacy single-browser `@data`/`@e2e`, **unchanged**, see [[knowledge_data-layer-broker]]), the harness launches a **non-persistent** browser `freshBrowser` (`chromium.launch`) which mints fresh isolated contexts on demand (`spawnContext(wallet)`). The module is imported by `hooks.ts` (lifecycle) and `world.ts` (per-scenario use) — no import cycle.
|
||||
- **`world.ts`** — API: `openBrowser(name, wallet)`, `browser(name)`, `loadAppInBrowser(name, 'app'|'harness')`, `closeBrowsers()`; registry `browsers: Map<name, NamedBrowser>`. Named browsers are closed in `After`, `freshBrowser` in `AfterAll`.
|
||||
- **`hooks.ts`** — a scenario tagged `@multibrowser` **does not get** the legacy single page; the steps open the browsers themselves. Requires the real broker mode (`freshBrowser` is unavailable in the mock fallback).
|
||||
|
||||
## Provisioning du wallet
|
||||
## Wallet provisioning
|
||||
|
||||
- **own** : `newContext()` vide → identité NG distincte / pas de wallet.
|
||||
- **shared** : `newContext({ storageState })`, où `storageState` est **capturé une fois** au `BeforeAll` depuis le profil persistant (warm-up via `setupBrokerPage` puis `browserContext.storageState()`), exposé par `pool.sharedWalletState`. **Vérifié empiriquement (2026-06-16)** : les origines `nextgraph.eu` + `nextgraph.net` round-trippent dans les contextes frais, et deux navigateurs **shared** atteignent tous deux l'app **connectée** à NextGraph (`window.__testData.ready`) **sans login manuel**.
|
||||
- **own**: empty `newContext()` → distinct NG identity / no wallet.
|
||||
- **shared**: `newContext({ storageState })`, where `storageState` is **captured once** at `BeforeAll` from the persistent profile (warm-up through `setupBrokerPage`, then `browserContext.storageState()`), exposed as `pool.sharedWalletState`. **Empirically verified (2026-06-16)**: the `nextgraph.eu` and `nextgraph.net` origins round-trip into the fresh contexts, and two **shared** browsers both reach the app **connected** to NextGraph (`window.__testData.ready`) **without any manual login**.
|
||||
|
||||
> Ce provisioning est **de test** — distinct du mécanisme **produit** (import assisté par FICHIER). Le scénario shared-wallet par storageState **court-circuite l'import** ; pour valider le mécanisme RÉEL, voir l'e2e `@humain` ci-dessous.
|
||||
> This provisioning is **test-only** — distinct from the **product** mechanism (FILE-assisted import). The shared-wallet scenario using storageState **bypasses the import**; to validate the REAL mechanism, see the `@humain` e2e below.
|
||||
|
||||
## Parcours humain — e2e du mécanisme produit (vert)
|
||||
## Human journey — e2e of the product mechanism (green)
|
||||
|
||||
Scénario `@humain` : valide le flux RÉEL de distribution du wallet **de bout en bout, via la vraie app**, pas l'injection de test. Un navigateur vierge ouvre l'app staging → l'`AccessGateScreen` propose le **fichier** + le **mot de passe** → on télécharge le fichier **depuis l'écran**, on vérifie que le mot de passe affiché **égale** celui du wallet → import sur `nextgraph.eu` « Import a Wallet File » → retour → on **saisit un identifiant** puis clic « Entrer » (nommer l'espace et ouvrir le wallet = un seul acte, cf. concept `app-security` [[decision_2026-07-06_identifier-at-access-barrier]]) → app connectée, arrivée directe sur l'accueil (plus d'écran « nom d'utilisateur » séparé).
|
||||
The `@humain` scenario validates the REAL wallet distribution flow **end to end, through the real app**, not through test injection. A blank browser opens the staging app → the `AccessGateScreen` offers the **file** and the **password** → the file is downloaded **from the screen**, the displayed password is checked to **equal** the wallet's own → import on `nextgraph.eu` "Import a Wallet File" → back to the app → an **identifier is typed in**, then a click on « Entrer » (naming the space and opening the wallet are a single act, see concept `app-security` [[decision_2026-07-06_identifier-at-access-barrier]]) → app connected, landing straight on the home screen (no more separate « nom d'utilisateur » screen).
|
||||
|
||||
- **Wallet e2e** : un fichier `.ngw` (`festipod-e2e-tests`, mot de passe = identifiant) placé **à la racine du worktree** ; `findE2eWalletFile()` le localise (`*.ngw`). Gitignoré → chaque environnement doit l'ajouter (sinon erreur claire).
|
||||
- `pool.ensureStagingApp()` (`hooks.ts`) — build **isolé** `bun run build.ts --outdir=dist-staging` (barrière d'accès **ON par défaut** ; mot de passe gravé + **fichier copié** en `/shared-wallet.ngw`, cf. `build.ts`), servi statiquement. Mémoïsé, lazy (seul `@humain` le paie).
|
||||
- **Bypass de la barrière pour `@e2e`** : le harness fait `browserContext.addInitScript` sur le **contexte persistant** pour poser `globalThis.__FESTIPOD_ACCESS_GATE_DISABLED__ = true` (s'applique à l'iframe app avant ses scripts) → `@e2e` voit l'app directement, pas la barrière. Les contextes frais (`@humain`) n'y touchent pas → barrière ON. L'ancien `LoginScreen` `/login` a été retiré.
|
||||
- `pool.importWalletViaFile(page, filePath, password)` — `nextgraph.eu/#/wallet/login` → `setInputFiles('input[type=file]')` (attendre que la SPA rende, sinon `EncryptionError`) → champ password → unlock.
|
||||
- `pool.completeBrokerLogin(page, appUrl, walletPassword?)` — moitié « login broker » extraite de `setupBrokerPage`. **Attente robuste** : après le redirect (multi-hop), attend l'iframe app OU le lien « Click here to login with your wallet », puis déverrouille avec le mot de passe. La session broker n'étant **pas** persistée entre lancements, ce login wallet est requis à chaque run (warm-up + `@e2e` + `@humain`).
|
||||
- **e2e wallet**: a `.ngw` file (`festipod-e2e-tests`, password = identifier) placed **at the root of the worktree**; `findE2eWalletFile()` locates it (`*.ngw`). Gitignored → each environment has to add it (otherwise a clear error is raised).
|
||||
- `pool.ensureStagingApp()` (`hooks.ts`) — an **isolated** build `bun run build.ts --outdir=dist-staging` (access barrier **ON by default**; password baked in and the **file copied** to `/shared-wallet.ngw`, see `build.ts`), served statically. Memoized and lazy (only `@humain` pays for it).
|
||||
- **Barrier bypass for `@e2e`**: the harness calls `browserContext.addInitScript` on the **persistent** context to set `globalThis.__FESTIPOD_ACCESS_GATE_DISABLED__ = true` (which applies to the app iframe before its scripts) → `@e2e` sees the app directly, not the barrier. Fresh contexts (`@humain`) leave it alone → barrier ON. The old `/login` `LoginScreen` has been removed.
|
||||
- `pool.importWalletViaFile(page, filePath, password)` — `nextgraph.eu/#/wallet/login` → `setInputFiles('input[type=file]')` (wait for the SPA to render, otherwise `EncryptionError`) → password field → unlock.
|
||||
- `pool.completeBrokerLogin(page, appUrl, walletPassword?)` — the "broker login" half extracted from `setupBrokerPage`. **Robust waiting**: after the (multi-hop) redirect, it waits for either the app iframe or the "Click here to login with your wallet" link, then unlocks with the password. Since the broker session is **not** persisted between launches, this wallet login is required on every run (warm-up + `@e2e` + `@humain`).
|
||||
|
||||
> **C'est l'e2e qui garantit que ça marche pour un humain réel** : Festipod fournit le BON fichier + mot de passe, et ce fichier importé donne un wallet fonctionnel sur un device vierge. Le scénario `@shared-wallet` (storageState) reste un raccourci de provisioning de test, il ne valide pas l'import.
|
||||
> **The e2e is what guarantees it works for a real human**: Festipod hands out the RIGHT file plus password, and importing that file yields a working wallet on a blank device. The `@shared-wallet` scenario (storageState) remains a test provisioning shortcut, it does not validate the import.
|
||||
|
||||
## Isolation (garantie à 3 niveaux, prouvée par les scénarios)
|
||||
## Isolation (guaranteed at 3 levels, proven by the scenarios)
|
||||
|
||||
1. `freshBrowser` est un **process séparé** du profil persistant porteur du wallet → un navigateur **own** démarre **sans wallet**.
|
||||
2. Chaque `newContext()` est une **partition de stockage hermétique** (garantie Playwright).
|
||||
3. Isolation prouvée non seulement sur l'origine **locale** (`127.0.0.1`) mais aussi sur l'**origine broker** `nextgraph.net` **où vit réellement le wallet** (sonde localStorage écrite dans A absente de B).
|
||||
1. `freshBrowser` runs in a **separate process** from the persistent profile carrying the wallet → an **own** browser starts **with no wallet**.
|
||||
2. Every `newContext()` is a **hermetic storage partition** (Playwright guarantee).
|
||||
3. Isolation is proven not only on the **local** origin (`127.0.0.1`) but also on the **broker origin** `nextgraph.net` **where the wallet actually lives** (a localStorage probe written in A is absent from B).
|
||||
|
||||
## Fichiers
|
||||
## Files
|
||||
|
||||
- Feature : `src/modules/workshop/features/multibrowser-harness.feature`.
|
||||
- Steps : `src/modules/workshop/steps/data/multibrowser.steps.ts`.
|
||||
- Route `/blank` ajoutée au serveur harness (`hooks.ts`) : page minimale **sans stack NG**, pour les checks d'isolation localStorage.
|
||||
- Feature: `src/modules/workshop/features/multibrowser-harness.feature`.
|
||||
- Steps: `src/modules/workshop/steps/data/multibrowser.steps.ts`.
|
||||
- A `/blank` route added to the harness server (`hooks.ts`): a minimal page **with no NG stack**, for the localStorage isolation checks.
|
||||
|
||||
## Convention `@wip` (désormais appliquée)
|
||||
## The `@wip` convention (now enforced)
|
||||
|
||||
`cucumber.json` (profile `default`) porte `"tags": "not @wip"`. Le `cookbook_add-scenario` prescrivait `@wip` pour le non-implémenté mais ce n'était **exclu nulle part** ; maintenant `not @wip` s'**AND** avec les filtres CLI (ex. `--tags @data` → `(not @wip) and @data`, vérifié).
|
||||
`cucumber.json` (profile `default`) carries `"tags": "not @wip"`. `cookbook_add-scenario` prescribed `@wip` for anything unimplemented, but it was **excluded nowhere**; now `not @wip` is **AND**ed with the CLI filters (e.g. `--tags @data` → `(not @wip) and @data`, verified).
|
||||
|
||||
## Liens
|
||||
## Links
|
||||
|
||||
- [[knowledge_data-layer-broker]] — la couche `@data` mono-navigateur (profil persistant) que cette capability étend.
|
||||
- [[cookbook_add-scenario]] — convention `@wip`, pièges de steps.
|
||||
- [[knowledge_data-layer-broker]] — the single-browser `@data` layer (persistent profile) that this capability extends.
|
||||
- [[cookbook_add-scenario]] — the `@wip` convention, step pitfalls.
|
||||
|
||||
@@ -1,57 +1,47 @@
|
||||
---
|
||||
type: knowledge
|
||||
summary: Couche @ui — renderHelper.tsx rend tout écran dans LocalDataProvider + happy-dom, world.renderCurrentScreen() l'invoque à chaque navigateTo, assertions sur le DOM rendu avec les fixtures de seed déterministes ; piège des écrans qui lisent un global injecté au build (barrière d'accès → import lazy obligatoire)
|
||||
summary: The @ui layer — renderHelper.tsx renders any screen inside LocalDataProvider + happy-dom, world.renderCurrentScreen() invokes it on every navigateTo, assertions run against the rendered DOM with the deterministic seed fixtures; pitfall of screens reading a global injected at build time (access barrier → lazy import mandatory)
|
||||
last_checked: 2026-07-27
|
||||
---
|
||||
|
||||
# Couche `@ui`
|
||||
# The `@ui` layer
|
||||
|
||||
`@ui` rend un écran avec `LocalDataProvider` (seed) + `RouterProvider` via happy-dom, puis assert sur le **DOM rendu**.
|
||||
`@ui` renders a screen with `LocalDataProvider` (seed) plus `RouterProvider` through happy-dom, then asserts on the **rendered DOM**.
|
||||
|
||||
- Helper : `src/shared/test-harness/renderHelper.tsx` (installe les globals happy-dom, enveloppe l'écran). Invoqué depuis `world.ts:renderCurrentScreen()` à chaque `navigateTo(...)`.
|
||||
- Fixtures déterministes (`src/shared/data/seedData.ts`, voir concept `data-layer`) : `Marie Dupont`/`@mariedupont` = currentUser, `Jean Durand`/`@jeandurand` existe, 5 events, etc.
|
||||
- Helper: `src/shared/test-harness/renderHelper.tsx` (installs the happy-dom globals, wraps the screen). Invoked from `world.ts:renderCurrentScreen()` on every `navigateTo(...)`.
|
||||
- Deterministic fixtures (`src/shared/data/seedData.ts`, see concept `data-layer`): `Marie Dupont`/`@mariedupont` = currentUser, `Jean Durand`/`@jeandurand` exists, 5 events, and so on.
|
||||
|
||||
## Bons patterns d'assertion
|
||||
## Good assertion patterns
|
||||
|
||||
```ts
|
||||
// Texte visible
|
||||
// Visible text
|
||||
expect(this.getDomText()).to.include('Marie Dupont');
|
||||
// Présence d'élément par classe/rôle
|
||||
// Element present, by class/role
|
||||
expect(this.renderedDoc!.querySelector('.app-avatar')).to.not.be.null;
|
||||
// Rendu conditionnel (rempli vs vide)
|
||||
// Conditional rendering (filled vs empty)
|
||||
expect(this.renderedDoc!.querySelectorAll('.app-card').length).to.be.greaterThan(0);
|
||||
// Champ requis rendu avec label + astérisque
|
||||
// Required field rendered with a label and an asterisk
|
||||
const labels = Array.from(this.renderedDoc!.querySelectorAll('p')).map(p => p.textContent ?? '');
|
||||
expect(labels.some(t => t.includes("Nom de l'événement *"))).to.be.true;
|
||||
```
|
||||
|
||||
## Champs & helpers de `FestipodWorld` (`src/shared/support/world.ts`)
|
||||
## `FestipodWorld` fields & helpers (`src/shared/support/world.ts`)
|
||||
|
||||
- `renderedDoc: Document | null` — le DOM happy-dom rendu (peuplé par `renderCurrentScreen()`, appelé à chaque `navigateTo(...)`).
|
||||
- `currentScreenId: string | null` — l'écran courant.
|
||||
- Helpers d'assertion : `getDomText()` (texte du DOM), `hasText(t)`, `hasField(name)`, `hasElement(selector)` — ils **préfèrent le DOM rendu** mais **retombent sur la source** des écrans pour les steps non migrés (vestige, voir [[caveat_source-grep-vestiges]]).
|
||||
- `renderedDoc: Document | null` — the rendered happy-dom DOM (populated by `renderCurrentScreen()`, called on every `navigateTo(...)`).
|
||||
- `currentScreenId: string | null` — the current screen.
|
||||
- Assertion helpers: `getDomText()` (DOM text), `hasText(t)`, `hasField(name)`, `hasElement(selector)` — they **prefer the rendered DOM** but **fall back to the screens' source** for unmigrated steps (a leftover, see [[caveat_source-grep-vestiges]]).
|
||||
|
||||
## ⚠️ Écrans qui lisent un global injecté au **build** (barrière d'accès)
|
||||
## ⚠️ Screens that read a global injected at **build** time (access barrier)
|
||||
|
||||
`src/modules/auth/sharedWallet.ts` **capture au moment de l'évaluation du module** un global posé par
|
||||
`build.ts` (`__FESTIPOD_SHARED_WALLET_PASSWORD__`). Le harness `@ui` tourne sous Node **sans passer
|
||||
par le build** → ce global est absent, `hasSharedWallet()` retourne faux, et comme le **wallet
|
||||
partagé est le seul mode supporté** (concept `app-security`), `AccessGateScreen` rend sa branche
|
||||
**erreur de configuration** : **aucun champ identifiant** dans le DOM → tous les steps de la barrière
|
||||
échouent avec un message trompeur (« champ introuvable »).
|
||||
`src/modules/auth/sharedWallet.ts` **captures, at module evaluation time**, a global set by `build.ts` (`__FESTIPOD_SHARED_WALLET_PASSWORD__`). The `@ui` harness runs under Node **without going through the build** → that global is missing, `hasSharedWallet()` returns false, and since the **shared wallet is the only supported mode** (concept `app-security`), `AccessGateScreen` renders its **configuration error** branch: **no identifier field at all** in the DOM → every barrier step fails with a misleading message ("field not found").
|
||||
|
||||
**Le montage obligatoire** (appliqué dans `src/modules/auth/steps/ui/barriere-acces.steps.ts`) :
|
||||
**The mandatory setup** (applied in `src/modules/auth/steps/ui/barriere-acces.steps.ts`):
|
||||
|
||||
1. poser le global **en tête du module de steps**, avant tout import de l'écran ;
|
||||
2. **importer l'écran paresseusement** (`await import(...)` mémoïsé) — un `import` statique serait
|
||||
**hissé au-dessus** de l'affectation et `sharedWallet.ts` capturerait une valeur vide.
|
||||
1. set the global **at the top of the steps module**, before any import of the screen;
|
||||
2. **import the screen lazily** (memoized `await import(...)`) — a static `import` would be **hoisted above** the assignment and `sharedWallet.ts` would capture an empty value.
|
||||
|
||||
> **Impacts si tu touches à ça :**
|
||||
> - Ajouter un `import` statique de `AccessGateScreen` (ou de tout module qui atteint
|
||||
> `sharedWallet.ts`) dans **n'importe quel** fichier de steps `@ui` ré-introduit le bug — Cucumber
|
||||
> charge tous les modules de steps, l'écran serait évalué avant que le global soit posé.
|
||||
> - Le déterminisme actuel repose sur le fait que **ce fichier est le seul** module `@ui` à atteindre
|
||||
> `sharedWallet.ts`. Un second point d'entrée rendrait l'ordre d'évaluation non garanti → il
|
||||
> faudrait alors déplacer l'injection du global dans le support partagé, pas la dupliquer.
|
||||
> **Impact if you touch this:**
|
||||
> - Adding a static `import` of `AccessGateScreen` (or of any module that reaches `sharedWallet.ts`) in **any** `@ui` steps file re-introduces the bug — Cucumber loads every steps module, so the screen would be evaluated before the global is set.
|
||||
> - The current determinism relies on **this file being the only** `@ui` module that reaches `sharedWallet.ts`. A second entry point would make the evaluation order unguaranteed → the global injection would then have to move into the shared support, not be duplicated.
|
||||
|
||||
> Les classes `app-*` confirment le thème moderne (cf. `app-architecture`). Les anti-patterns (regex sur source, détails d'implémentation) sont proscrits par [[rule_test-layer-contracts]]. Pour écrire un nouveau scénario, voir [[cookbook_add-scenario]].
|
||||
> The `app-*` classes confirm the modern theme (see `app-architecture`). Anti-patterns (regexes over the source, implementation details) are banned by [[rule_test-layer-contracts]]. To write a new scenario, see [[cookbook_add-scenario]].
|
||||
|
||||
@@ -1,52 +1,27 @@
|
||||
---
|
||||
type: rule
|
||||
summary: Ne JAMAIS poller le broker (re-lire en boucle « c'est là ? »). NextGraph est par abonnement — la donnée arrive par PUSH, et le 1er `State` d'un `doc_subscribe` est la barrière de sync déterministe (après lui : présence garantie / absence définitive). Tests ET app attendent le push / l'état réactif settlé, jamais une boucle de re-lecture broker.
|
||||
summary: NEVER poll the broker (re-reading in a loop "is it there yet?"). NextGraph is subscription-based — data arrives by PUSH, and the first `State` of a `doc_subscribe` is the deterministic sync barrier (after it — presence guaranteed, absence definitive). Tests AND app wait for the push / for the reactive state to settle, never a broker re-read loop.
|
||||
last_checked: 2026-07-09
|
||||
---
|
||||
|
||||
# Ne jamais poller le broker — attendre l'abonnement
|
||||
# Never poll the broker — wait for the subscription
|
||||
|
||||
NextGraph est **par abonnement (réactif)**. Une lecture n'est PAS « interroge en
|
||||
boucle jusqu'à ce que ça apparaisse » ; c'est « abonne-toi, réagis au push ». Le
|
||||
**1er `State`** d'un `doc_subscribe` marque la fin de la synchronisation initiale
|
||||
(barrière synchrone) : après lui, la **présence** d'une donnée est **garantie** et
|
||||
l'**absence** est **définitive**. Contrat vérifié empiriquement côté SDK
|
||||
(`@ng-eventually/client`, test e2e « CONTRAT 3 »).
|
||||
NextGraph is **subscription-based (reactive)**. A read is NOT "query in a loop until it shows up"; it is "subscribe, react to the push". The **first `State`** of a `doc_subscribe` marks the end of the initial synchronization (a synchronous barrier): after it, the **presence** of a piece of data is **guaranteed** and its **absence** is **definitive**. Contract verified empirically on the SDK side (`@ng-eventually/client`, e2e test « CONTRAT 3 »).
|
||||
|
||||
## L'anti-pattern à bannir
|
||||
## The anti-pattern to ban
|
||||
|
||||
```
|
||||
for (i = 0; i < N; i++) { if (await authParticipationCount(...) === X) break; sleep(500); }
|
||||
```
|
||||
|
||||
Toute boucle qui **re-interroge le broker** (`authParticipationCount`,
|
||||
`listMyEntityDocs`, `sparql_query` répétés) pour « attendre » une donnée est
|
||||
proscrite : elle masque le vrai mécanisme, fragilise le test (timeout deviné), et
|
||||
contredit frontalement le modèle NextGraph. C'est la remarque qui a fait supprimer
|
||||
l'ancien caveat qui, à tort, érigeait le polling en pratique.
|
||||
Any loop that **re-queries the broker** (repeated `authParticipationCount`, `listMyEntityDocs`, `sparql_query`) in order to "wait" for data is forbidden: it hides the real mechanism, makes the test brittle (guessed timeout), and directly contradicts the NextGraph model. That remark is what caused the deletion of the old caveat which wrongly held polling up as a practice.
|
||||
|
||||
## Ce qu'il faut faire
|
||||
## What to do instead
|
||||
|
||||
Attendre le **push réactif**. En pratique (app ET test) : l'état réactif
|
||||
(`AD().*` alimenté par `subscribeDoc` dans le contexte de données) se met à jour
|
||||
**au push**. On attend que CET état reflète l'attendu — on **observe l'état réactif
|
||||
settlé**, on ne ré-émet PAS de lecture broker. Le mécanisme de données est
|
||||
l'abonnement ; l'attente ne fait qu'**observer le résultat réactif**.
|
||||
Wait for the **reactive push**. In practice (app AND test): the reactive state (`AD().*` fed by `subscribeDoc` in the data context) updates **on push**. We wait for THAT state to reflect the expectation — we **observe the settled reactive state**, we do NOT re-issue a broker read. The data mechanism is the subscription; waiting only **observes the reactive result**.
|
||||
|
||||
- App : l'écran est déjà réactif (`subscribeDoc` → re-render au push) — pas de poll
|
||||
applicatif, pas de spinner piloté par timeout deviné (si un état d'attente est
|
||||
voulu, il vient de la barrière d'abonnement native, pas d'un signal ajouté).
|
||||
- Test : **un helper qui attend le push/la barrière de façon fiable est bienvenu**
|
||||
(fiabilise sans fragiliser). Ce qui est banni, c'est la **boucle de re-lecture**,
|
||||
pas l'attente d'un signal.
|
||||
- **Fallback pragmatique** : si attendre strictement le push/signal s'avère fragile
|
||||
d'une manière ou d'une autre, un **intervalle court** (`setInterval` / re-check
|
||||
rapproché) qui **observe l'état réactif DÉJÀ mis à jour** (l'état local alimenté
|
||||
par l'abonnement — PAS une re-lecture broker) est acceptable : c'est au plus près
|
||||
de ce que vit l'utilisateur, qui **attend** simplement que l'écran (réactif) se
|
||||
mette à jour. La ligne rouge est invariante : **ne jamais re-interroger le broker
|
||||
en boucle** ; observer l'état réactif settlé, oui.
|
||||
- App: the screen is already reactive (`subscribeDoc` → re-render on push) — no application-level polling, no spinner driven by a guessed timeout (if a waiting state is wanted, it comes from the native subscription barrier, not from an added signal).
|
||||
- Test: **a helper that reliably waits for the push/barrier is welcome** (it makes things reliable without making them brittle). What is banned is the **re-read loop**, not waiting for a signal.
|
||||
- **Pragmatic fallback**: if strictly waiting for the push/signal turns out to be brittle one way or another, a **short interval** (`setInterval` / closely spaced re-checks) that **observes the ALREADY updated reactive state** (the local state fed by the subscription — NOT a broker re-read) is acceptable: it is as close as it gets to what the user experiences, simply **waiting** for the (reactive) screen to update. The red line is invariant: **never re-query the broker in a loop**; observing the settled reactive state, yes.
|
||||
|
||||
Voir aussi [[caveat_wallet-bloat-hang]] (autre source de flakiness @data,
|
||||
orthogonale). Le mécanisme non-polling côté lib (`open-repo` : subscribe + attendre
|
||||
le 1er State + lire) vit dans le repo `@ng-eventually/client`, pas ici.
|
||||
See also [[caveat_wallet-bloat-hang]] (another source of @data flakiness, orthogonal to this one). The non-polling mechanism on the library side (`open-repo`: subscribe + wait for the first State + read) lives in the `@ng-eventually/client` repo, not here.
|
||||
|
||||
@@ -1,29 +1,29 @@
|
||||
---
|
||||
type: rule
|
||||
summary: Chaque couche BDD répond à une question distincte — @ui = rendu (DOM + seed), @data = mutations/persistance broker, @e2e = collaboration des couches sur un parcours ; descendre chaque assertion à la couche la plus basse qui peut y répondre
|
||||
summary: Each BDD layer answers a distinct question — @ui = rendering (DOM + seed), @data = broker mutations/persistence, @e2e = collaboration of the layers over a journey; push every assertion down to the lowest layer that can answer it
|
||||
---
|
||||
|
||||
# Règle : contrat des couches de test
|
||||
# Rule: the test layer contract
|
||||
|
||||
Chaque couche répond à **une question distincte**. Mélanger les préoccupations produit des tests fragiles qui cassent au refactor sans attraper de vraie régression. **Descendre toute assertion à la couche la plus basse qui peut y répondre.**
|
||||
Each layer answers **one distinct question**. Mixing concerns produces brittle tests that break on refactors without catching any real regression. **Push every assertion down to the lowest layer that can answer it.**
|
||||
|
||||
- **`@ui` — couche affichage.** Rend un écran avec `LocalDataProvider` (seed) + happy-dom et assert sur le DOM. Vérifie que *données connues → l'écran montre le texte et les éléments attendus*. **Ne teste pas** la navigation, les mutations, ni la persistance.
|
||||
- **`@ui` — display layer.** Renders a screen with `LocalDataProvider` (seed) plus happy-dom and asserts on the DOM. Checks that *given known data, the screen shows the expected text and elements*. **Does not test** navigation, mutations or persistence.
|
||||
|
||||
- **`@data` — couche données.** Pilote des mutations ORM via le **broker NextGraph réel** (harness headless, pas d'UI app). Vérifie que *les opérations sur shapes sont persistées et observables dans le wallet*. Pas de DOM ici — utiliser le bridge `window.__testData`.
|
||||
- **`@data` — data layer.** Drives ORM mutations through the **real NextGraph broker** (headless harness, no app UI). Checks that *shape operations are persisted and observable in the wallet*. No DOM here — use the `window.__testData` bridge.
|
||||
|
||||
- **`@e2e` — couche intégration.** Boote l'app réelle dans l'iframe broker (Playwright/Chromium). Vérifie que *les couches collaborent pour livrer un parcours* (créer → lister → modifier → recharger → toujours là). **Rare** : 1 scénario par chemin critique ; **ne jamais dupliquer** un check de contenu `@ui`.
|
||||
- **`@e2e` — integration layer.** Boots the real app inside the broker iframe (Playwright/Chromium). Checks that *the layers collaborate to deliver a journey* (create → list → edit → reload → still there). **Rare**: 1 scenario per critical path; **never duplicate** a `@ui` content check.
|
||||
|
||||
## Pourquoi le coût impose la pyramide
|
||||
## Why cost dictates the pyramid
|
||||
|
||||
`@ui` tourne in-process (instantané) ; `@data` boote un broker (~50s) ; `@e2e` boote broker + app + navigateur (~2min). Une affirmation de rendu appartient à `@ui`, pas à `@e2e`.
|
||||
`@ui` runs in-process (instant); `@data` boots a broker (~50s); `@e2e` boots broker + app + browser (~2min). A rendering claim belongs to `@ui`, not to `@e2e`.
|
||||
|
||||
## Anti-patterns `@ui` à proscrire
|
||||
## `@ui` anti-patterns to ban
|
||||
|
||||
```ts
|
||||
// ❌ regex sur la source : couple le test à la structure du code
|
||||
// ❌ regex over the source: couples the test to the structure of the code
|
||||
expect(/<Title[^>]*>Marie Dupont<\/Title>/.test(source)).to.be.true;
|
||||
// ❌ détails d'implémentation
|
||||
// ❌ implementation details
|
||||
expect(/showDuplicateWarning/.test(source)).to.be.true;
|
||||
```
|
||||
|
||||
Préférer des assertions sur le **DOM rendu** + données de seed (voir [[knowledge_ui-layer]]). Les helpers/maps d'analyse de source sont des vestiges en voie de suppression : [[caveat_source-grep-vestiges]].
|
||||
Prefer assertions on the **rendered DOM** plus seed data (see [[knowledge_ui-layer]]). The source-analysis helpers and maps are leftovers on their way out: [[caveat_source-grep-vestiges]].
|
||||
|
||||
Reference in New Issue
Block a user