test(i18n): compare the {{…}} variables of each key between fr.json and en.json (#480) #490

Merged
maximus merged 3 commits from issue-480-i18n-interpolation-guard into main 2026-10-24 18:10:12 +00:00
2 changed files with 163 additions and 9 deletions

View file

@ -139,7 +139,7 @@ Chaque règle cite sa source. Elles valent quel que soit le niveau : une PR norm
### i18n et documentation
- Toute chaîne visible passe par i18next, dans `fr.json` et `en.json` à la fois (mêmes clés, vérifiées par `src/i18n/locales.keys.test.ts`) ; aucun texte en dur dans un composant. — `CLAUDE.md` « Internationalisation (i18n) », `.claude/rules/i18n.md`, #453
- Toute chaîne visible passe par i18next, dans `fr.json` et `en.json` à la fois (mêmes clés et mêmes variables `{{…}}`, vérifiées par `src/i18n/locales.keys.test.ts`) ; aucun texte en dur dans un composant. — `CLAUDE.md` « Internationalisation (i18n) », `.claude/rules/i18n.md`, #453, #480
- Un changement visible ajoute une entrée sous `[Unreleased]` dans `CHANGELOG.md` et `CHANGELOG.fr.md`. — `CLAUDE.md` « Documentation technique » (Règle CHANGELOG)
- Un changement d'usage met à jour `docs/guide-utilisateur.md` et les clés `docs.*` ; un service, un hook, une commande, une page ou une table de plus met à jour `docs/architecture.md` ; une décision structurante a son ADR. — `CLAUDE.md` « Documentation technique »
@ -182,7 +182,7 @@ Les trois premiers viennent du skill global `pr-review`, corrigés pour ce dép
- **Un vert de `check-rust` ne dit rien de l'audit** : son étape `cargo audit` est `continue-on-error`. Lire le journal : `cargo-audit` écrit `1 vulnerability found` mais `N vulnerabilities found` (chercher `vulnerabilit(y|ies) found`), et le journal de `check-rust` contient des codes ANSI à retirer avant tout `grep`. Un `audit.yml` vert veut dire « zéro advisory hors de la liste acceptée », pas « zéro advisory ». — `CLAUDE.md` « CI/CD », [ADR 0018](docs/adr/0018-suppression-advisories-non-atteignables.md), #447
- **Windows n'est compilé qu'à la release.** La CI des PR ne compile que pour Linux : sans `cargo xwin check`, une casse Windows apparaît le jour du tag. — `docs/architecture.md` « `release.yml` — Build et publication », #455
- **Tests sans jsdom.** Un rendu par `renderToStaticMarkup` ne lance ni effet ni clic : ce qui en dépend n'est prouvé que par un test qui passe par `src/test/hookHarness.ts` (effets joués par `commit()`, gestionnaires appelés depuis l'arbre rendu). Le harnais ne rend pas de nouveau après un setter et laisse les enfants à l'état d'éléments : lire ce que le test exerce avant de le créditer. — `docs/architecture.md` « Tests (vitest sans jsdom) »
- **Faux `t`.** Un faux `t` qui rend la clé brute rend invisible un `t` oublié : les tests prennent `src/test/i18nMock.ts`, gardé par `src/__integration__/i18n-mock-guard.test.ts`. Une clé présente dans une seule langue fait échouer la garde `src/i18n/locales.keys.test.ts`, qui ne compare que les clés des deux fichiers : un texte resté dans l'autre langue (du français dans `en.json`) la passe, et une clé que le code appelle sans qu'aucun des deux fichiers la déclare lui échappe aussi. — `docs/architecture.md` « Faux `t` marqué », #389, #453
- **Faux `t`.** Un faux `t` qui rend la clé brute rend invisible un `t` oublié : les tests prennent `src/test/i18nMock.ts`, gardé par `src/__integration__/i18n-mock-guard.test.ts`. Une clé présente dans une seule langue fait échouer la garde `src/i18n/locales.keys.test.ts`, comme une clé dont les variables `{{…}}` diffèrent d'un fichier à l'autre, option de format comprise (#480). Elle ne compare rien d'autre des valeurs et ne lit pas le code : un texte resté dans l'autre langue (du français dans `en.json`) la passe, et une clé que le code appelle sans qu'aucun des deux fichiers la déclare lui échappe aussi, comme une variable que les deux fichiers écrivent de la même façon sans que l'appel la passe. — `docs/architecture.md` « Faux `t` marqué », #389, #453, #480
- **Sous-chaîne du markup.** `not.toContain("disabled")` sur le HTML rendu bute sur une classe Tailwind (`disabled:opacity-50`) : tester l'attribut (`disabled=""`). — PR #452
- **Booléen lié en texte.** tauri-plugin-sql stocke un booléen JS en texte `'true'`, qu'une condition `= 1` ne trouve pas : défaut resté invisible de la v0.1.0 à #390. — [ADR 0021](docs/adr/0021-migrations-profils-secondaires.md)
- **Transaction hors verrou.** Un `BEGIN` et son `COMMIT` envoyés par deux `db.execute` peuvent partir sur deux connexions du pool et laisser un verrou zombie (« database is locked », v0.10.0) : toujours `withTransaction` et son handle. — `docs/architecture.md` « Accès DB et transactions »

View file

@ -1,4 +1,5 @@
// Guard: fr.json and en.json declare the same keys (#453).
// Guard: fr.json and en.json declare the same keys (#453), and each key the
// same interpolation variables (#480).
//
// i18next serves fr.json, the default language, and en.json, the fallback
// (`src/i18n/config.ts`). A key written in fr.json only shows raw to an
@ -8,11 +9,20 @@
//
// A key is the dotted path of a leaf, array indices included
// (`docs.dashboard.features.6`) and plural suffixes too
// (`import.sources.fileCount_one`). Values are never compared: a text left
// untranslated in the other file passes. A path that is an array in one file
// (`import.sources.fileCount_one`). A path that is an array in one file
// and an object in the other, or a leaf in one and an object or an array in
// the other, is a gap as well: `t(key, { returnObjects: true })` would hand
// the component another shape.
//
// Of the values, only the `{{…}}` tokens are compared (#480): a text left
// untranslated in the other file passes. A key that writes `{{count}}` in
// fr.json and `{{n}}` in en.json shows a raw `{{…}}` in one of the two
// languages, and a format option left out on one side (`{{filter}}` against
// `{{filter, lowercase}}`) keeps the capital the sentence meant to drop: each
// leaf both files hold carries one set of tokens, format options included.
// Neither file nests a key (`$t(…)`) or writes the unescaped form (`{{- …}}`)
// yet: a nested key would not be compared, and `{{- name}}` would read as the
// token `- name`, a gap against `{{name}}`.
import { describe, it, expect } from "vitest";
import fr from "./locales/fr.json";
@ -20,24 +30,41 @@ import en from "./locales/en.json";
type NodeKind = "object" | "array" | "leaf";
/** Every node under the root of a locale tree, by dotted path (array indices included), with its kind. */
function nodesOf(tree: unknown): Map<string, NodeKind> {
const nodes = new Map<string, NodeKind>();
/**
* Calls `onNode` for every node under the root of a locale tree, with its
* dotted path (array indices included), its kind and its value.
*/
function walk(tree: unknown, onNode: (path: string, kind: NodeKind, value: unknown) => void): void {
const visit = (value: unknown, path: string[]): void => {
const kind: NodeKind = Array.isArray(value)
? "array"
: typeof value === "object" && value !== null
? "object"
: "leaf";
if (path.length > 0) nodes.set(path.join("."), kind);
if (path.length > 0) onNode(path.join("."), kind, value);
if (kind === "leaf") return;
// An array's entries are its indices, as strings: `features.6`.
for (const [key, item] of Object.entries(value as object)) visit(item, [...path, key]);
};
visit(tree, []);
}
/** Every node under the root of a locale tree, by dotted path (array indices included), with its kind. */
function nodesOf(tree: unknown): Map<string, NodeKind> {
const nodes = new Map<string, NodeKind>();
walk(tree, (path, kind) => nodes.set(path, kind));
return nodes;
}
/** Every leaf of a locale tree, by the dotted path `nodesOf` gives it, with its text. */
function leavesOf(tree: unknown): Map<string, string> {
const leaves = new Map<string, string>();
walk(tree, (path, kind, value) => {
if (kind === "leaf") leaves.set(path, String(value));
});
return leaves;
}
/**
* The keys of `from` that `into` lacks, sorted: the leaves of `from` with
* nothing at the same path in `into`. A path `into` holds with another kind is
@ -63,6 +90,48 @@ function kindGaps(
.sort();
}
/**
* The `{{…}}` tokens of a text, sorted, each once. A token is what i18next
* reads between `{{` and the next `}}`, format options included
* (`filter, lowercase`), without the whitespace i18next ignores: around the
* name and around each format option.
*/
function variablesOf(text: string): string[] {
const tokens = [...text.matchAll(/\{\{(.+?)\}\}/g)].map(([, inner]) =>
inner
.split(",")
.map((part) => part.trim())
.join(", "),
);
return [...new Set(tokens)].sort();
}
/**
* The leaves both maps hold with other `{{…}}` tokens, sorted, as
* `path: {{a}}, {{b}} in <a>; {{a}}, {{c}} in <b>`, every token of each side
* listed. A path only one side holds, or holds with another kind, is left to
* `missingKeys` and `kindGaps`.
*/
function variableGaps(
a: Map<string, string>,
b: Map<string, string>,
nameA: string,
nameB: string,
): string[] {
const listed = (tokens: string[]): string =>
tokens.length > 0 ? tokens.map((token) => `{{${token}}}`).join(", ") : "no variable";
const gaps: string[] = [];
for (const [path, text] of a) {
const other = b.get(path);
if (other === undefined) continue;
const inA = variablesOf(text);
const inB = variablesOf(other);
const same = inA.length === inB.length && inA.every((token, i) => token === inB[i]);
if (!same) gaps.push(`${path}: ${listed(inA)} in ${nameA}; ${listed(inB)} in ${nameB}`);
}
return gaps.sort();
}
const FR = nodesOf(fr);
const EN = nodesOf(en);
@ -127,3 +196,88 @@ describe("locale keys: the comparison (#453)", () => {
expect(kindGaps(a, b, "a", "b")).toEqual([]);
});
});
const FR_LEAVES = leavesOf(fr);
const EN_LEAVES = leavesOf(en);
describe("locale values: interpolation variables (#480)", () => {
it("reads the tokens of each file, format options included", () => {
// The canary: texts read as empty, or tokens read as nothing, would make
// the comparison pass on nothing, and so would one file read twice.
for (const [name, leaves] of [["fr.json", FR_LEAVES], ["en.json", EN_LEAVES]] as const) {
expect(variablesOf(leaves.get("import.rootFiles.message_one") ?? ""), name).toEqual([
"count",
"folder",
"names",
]);
expect(variablesOf(leaves.get("onboarding.card.transactions.uncategorized") ?? ""), name).toContain(
"filter, lowercase",
);
}
expect(EN_LEAVES.get("import.rootFiles.message_one"), "en.json and fr.json are read apart").not.toBe(
FR_LEAVES.get("import.rootFiles.message_one"),
);
});
it("gives every leaf both files hold the same {{…}} tokens", () => {
expect(variableGaps(FR_LEAVES, EN_LEAVES, "fr.json", "en.json"), "leaves with other variables").toEqual([]);
});
});
describe("locale values: the variable comparison (#480)", () => {
const gaps = (a: object, b: object): string[] => variableGaps(leavesOf(a), leavesOf(b), "a", "b");
it("reads each token whole, format options included, sorted and each once", () => {
expect(variablesOf("{{names}}: {{count}} files in {{folder}}")).toEqual(["count", "folder", "names"]);
expect(variablesOf("Only {{filter, lowercase}} ones")).toEqual(["filter, lowercase"]);
expect(variablesOf("{{n}} of {{n}}")).toEqual(["n"]);
expect(variablesOf("No variable")).toEqual([]);
});
it("drops only the whitespace i18next ignores, around the name and each format option", () => {
expect(variablesOf("{{ count }}, {{filter,lowercase}}, {{ filter , lowercase }}")).toEqual([
"count",
"filter, lowercase",
]);
});
it("names a variable renamed on one side, with every token of each side", () => {
expect(gaps({ x: "{{count}} in {{folder}}" }, { x: "{{count}} in {{dir}}" })).toEqual([
"x: {{count}}, {{folder}} in a; {{count}}, {{dir}} in b",
]);
});
it("names a variable missing on either side", () => {
expect(gaps({ x: "{{count}} files" }, { x: "Files" })).toEqual(["x: {{count}} in a; no variable in b"]);
expect(gaps({ x: "Files" }, { x: "{{count}} files" })).toEqual(["x: no variable in a; {{count}} in b"]);
expect(gaps({ x: "{{a}} and {{b}}" }, { x: "{{b}}" })).toEqual(["x: {{a}}, {{b}} in a; {{b}} in b"]);
});
it("holds another format option, or none, on one side as a gap", () => {
expect(gaps({ x: "Only {{filter, lowercase}}" }, { x: "Only {{filter}}" })).toEqual([
"x: {{filter, lowercase}} in a; {{filter}} in b",
]);
expect(gaps({ x: "{{filter, lowercase}}" }, { x: "{{filter, uppercase}}" })).toEqual([
"x: {{filter, lowercase}} in a; {{filter, uppercase}} in b",
]);
});
it("lists every leaf in gap, array items included, not only the first", () => {
expect(
gaps(
{ z: "{{a}}", list: ["{{n}}", "{{m}}"], same: "{{s}}" },
{ z: "{{b}}", list: ["{{n}}", "{{k}}"], same: "{{s}}" },
),
).toEqual(["list.1: {{m}} in a; {{k}} in b", "z: {{a}} in a; {{b}} in b"]);
});
it("passes the same variables in another order, a repeated variable and a key without variable", () => {
expect(gaps({ x: "{{a}}, then {{b}}" }, { x: "{{b}}, then {{a}}" })).toEqual([]);
expect(gaps({ x: "{{count}} of {{count}}" }, { x: "{{count}}" })).toEqual([]);
expect(gaps({ x: "Annuler" }, { x: "Cancel" })).toEqual([]);
});
it("leaves a path one side lacks, or holds with another kind, to the key comparison", () => {
expect(gaps({ only: "{{a}}", x: { y: "{{a}}" } }, { x: "{{b}}" })).toEqual([]);
});
});