@sun-asterisk/sungen 3.2.7 → 3.2.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/commands/delivery.d.ts +25 -0
- package/dist/cli/commands/delivery.d.ts.map +1 -1
- package/dist/cli/commands/delivery.js +23 -1
- package/dist/cli/commands/delivery.js.map +1 -1
- package/dist/exporters/api-testcase-formatter.d.ts.map +1 -1
- package/dist/exporters/api-testcase-formatter.js +80 -4
- package/dist/exporters/api-testcase-formatter.js.map +1 -1
- package/dist/exporters/csv-exporter.d.ts.map +1 -1
- package/dist/exporters/csv-exporter.js +6 -1
- package/dist/exporters/csv-exporter.js.map +1 -1
- package/dist/exporters/types.d.ts +5 -0
- package/dist/exporters/types.d.ts.map +1 -1
- package/dist/generators/test-generator/adapters/playwright/templates/steps/assertions/column-cell-assertion.hbs +3 -3
- package/dist/generators/test-generator/adapters/playwright/templates/steps/assertions/table-empty.hbs +1 -1
- package/dist/generators/test-generator/adapters/playwright/templates/steps/assertions/table-match-data.hbs +2 -2
- package/dist/generators/test-generator/adapters/playwright/templates/steps/assertions/table-row-count.hbs +1 -1
- package/dist/generators/test-generator/adapters/playwright/templates/steps/assertions/table-row-exists.hbs +2 -2
- package/dist/generators/test-generator/adapters/playwright/templates/steps/assertions/table-row-not-exists.hbs +2 -2
- package/dist/generators/test-generator/step-mapper.d.ts +6 -2
- package/dist/generators/test-generator/step-mapper.d.ts.map +1 -1
- package/dist/generators/test-generator/step-mapper.js +10 -6
- package/dist/generators/test-generator/step-mapper.js.map +1 -1
- package/dist/orchestrator/templates/ai-src/commands/create-test.md +2 -2
- package/dist/orchestrator/templates/ai-src/commands/run-test.md +1 -1
- package/dist/orchestrator/templates/ai-src/skills/sungen-api-design/SKILL.md +8 -0
- package/dist/orchestrator/templates/ai-src/skills/sungen-error-mapping/SKILL.md +12 -1
- package/dist/orchestrator/templates/ai-src/skills/sungen-gherkin-syntax/SKILL.md +28 -0
- package/dist/orchestrator/templates/ai-src/skills/sungen-selector-fix/SKILL.md +3 -0
- package/dist/orchestrator/templates/specs-api.d.ts +14 -2
- package/dist/orchestrator/templates/specs-api.d.ts.map +1 -1
- package/dist/orchestrator/templates/specs-api.js +38 -14
- package/dist/orchestrator/templates/specs-api.js.map +1 -1
- package/dist/orchestrator/templates/specs-api.ts +43 -14
- package/dist/orchestrator/templates/specs-db.d.ts +10 -2
- package/dist/orchestrator/templates/specs-db.d.ts.map +1 -1
- package/dist/orchestrator/templates/specs-db.js +98 -6
- package/dist/orchestrator/templates/specs-db.js.map +1 -1
- package/dist/orchestrator/templates/specs-db.ts +77 -8
- package/package.json +7 -4
- package/src/cli/commands/delivery.ts +24 -4
- package/src/exporters/api-testcase-formatter.ts +77 -4
- package/src/exporters/csv-exporter.ts +6 -1
- package/src/exporters/types.ts +5 -0
- package/src/generators/test-generator/adapters/playwright/templates/steps/assertions/column-cell-assertion.hbs +3 -3
- package/src/generators/test-generator/adapters/playwright/templates/steps/assertions/table-empty.hbs +1 -1
- package/src/generators/test-generator/adapters/playwright/templates/steps/assertions/table-match-data.hbs +2 -2
- package/src/generators/test-generator/adapters/playwright/templates/steps/assertions/table-row-count.hbs +1 -1
- package/src/generators/test-generator/adapters/playwright/templates/steps/assertions/table-row-exists.hbs +2 -2
- package/src/generators/test-generator/adapters/playwright/templates/steps/assertions/table-row-not-exists.hbs +2 -2
- package/src/generators/test-generator/step-mapper.ts +10 -6
- package/src/orchestrator/templates/ai-src/commands/create-test.md +2 -2
- package/src/orchestrator/templates/ai-src/commands/run-test.md +1 -1
- package/src/orchestrator/templates/ai-src/skills/sungen-api-design/SKILL.md +8 -0
- package/src/orchestrator/templates/ai-src/skills/sungen-error-mapping/SKILL.md +12 -1
- package/src/orchestrator/templates/ai-src/skills/sungen-gherkin-syntax/SKILL.md +28 -0
- package/src/orchestrator/templates/ai-src/skills/sungen-selector-fix/SKILL.md +3 -0
- package/src/orchestrator/templates/specs-api.ts +43 -14
- package/src/orchestrator/templates/specs-db.ts +77 -8
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
{{~#if isGiven~}}
|
|
2
2
|
{
|
|
3
|
-
const rows = {{> locator}}.locator('tbody').getByRole('row');
|
|
3
|
+
const rows = {{> locator}}.locator('tbody').getByRole('row', { includeHidden: true }).filter({ visible: true });
|
|
4
4
|
{{#each assertions}}
|
|
5
5
|
{{this}}
|
|
6
6
|
{{/each~}}
|
|
7
7
|
}
|
|
8
8
|
{{~else~}}
|
|
9
9
|
{
|
|
10
|
-
const rows = {{> locator}}.locator('tbody').getByRole('row');
|
|
10
|
+
const rows = {{> locator}}.locator('tbody').getByRole('row', { includeHidden: true }).filter({ visible: true });
|
|
11
11
|
{{#each assertions}}
|
|
12
12
|
{{this}}
|
|
13
13
|
{{/each~}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
await expect({{> locator}}.locator('tbody').getByRole('row')).toHaveCount({{expectedCount}});
|
|
1
|
+
await expect({{> locator}}.locator('tbody').getByRole('row', { includeHidden: true }).filter({ visible: true })).toHaveCount({{expectedCount}});
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{{~#if isGiven}}
|
|
2
|
-
const tableRow = {{> locator}}.getByRole('row').filter({ hasText: '{{escapeQuotes filterValue}}' });
|
|
2
|
+
const tableRow = {{> locator}}.getByRole('row', { includeHidden: true }).filter({ hasText: '{{escapeQuotes filterValue}}' }).filter({ visible: true });
|
|
3
3
|
await tableRow.waitFor();
|
|
4
4
|
{{~else}}
|
|
5
|
-
const tableRow = {{> locator}}.getByRole('row').filter({ hasText: '{{escapeQuotes filterValue}}' });
|
|
5
|
+
const tableRow = {{> locator}}.getByRole('row', { includeHidden: true }).filter({ hasText: '{{escapeQuotes filterValue}}' }).filter({ visible: true });
|
|
6
6
|
await expect(tableRow).toBeVisible();
|
|
7
7
|
{{~/if}}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
{{~#if isGiven}}
|
|
2
|
-
await {{> locator}}.getByRole('row').filter({ hasText: '{{escapeQuotes filterValue}}' }).waitFor({ state: 'hidden' });
|
|
2
|
+
await {{> locator}}.getByRole('row', { includeHidden: true }).filter({ hasText: '{{escapeQuotes filterValue}}' }).filter({ visible: true }).waitFor({ state: 'hidden' });
|
|
3
3
|
{{~else}}
|
|
4
|
-
await expect({{> locator}}.getByRole('row').filter({ hasText: '{{escapeQuotes filterValue}}' })).toHaveCount(0);
|
|
4
|
+
await expect({{> locator}}.getByRole('row', { includeHidden: true }).filter({ hasText: '{{escapeQuotes filterValue}}' }).filter({ visible: true })).toHaveCount(0);
|
|
5
5
|
{{~/if}}
|
|
@@ -229,8 +229,12 @@ export class StepMapper {
|
|
|
229
229
|
* Generate column assertion scoped to the current row.
|
|
230
230
|
* Uses columns config for exact cell targeting (nth), or filter fallback.
|
|
231
231
|
*
|
|
232
|
-
* With columns: await expect(tableRow.getByRole('cell').nth(index)).toHaveText('value');
|
|
233
|
-
* Without: await expect(tableRow.getByRole('cell').filter({ hasText: 'value' })).toBeVisible();
|
|
232
|
+
* With columns: await expect(tableRow.getByRole('cell', { includeHidden: true }).filter({ visible: true }).nth(index)).toHaveText('value');
|
|
233
|
+
* Without: await expect(tableRow.getByRole('cell', { includeHidden: true }).filter({ hasText: 'value' }).filter({ visible: true })).toBeVisible();
|
|
234
|
+
*
|
|
235
|
+
* includeHidden + visible filter: when a modal (e.g. Radix Dialog) is open the
|
|
236
|
+
* background gets aria-hidden="true", which empties plain getByRole() even though
|
|
237
|
+
* the cells are still rendered — measure what the user SEES, not the a11y tree.
|
|
234
238
|
*/
|
|
235
239
|
private generateRowScopedColumnAssertion(step: ParsedStep): MappedStep {
|
|
236
240
|
const columnRef = step.selectorRef || '';
|
|
@@ -259,16 +263,16 @@ export class StepMapper {
|
|
|
259
263
|
if (columnIndex !== undefined) {
|
|
260
264
|
// Exact cell: nth(index) + toHaveText
|
|
261
265
|
if (isGiven) {
|
|
262
|
-
code = `await expect(tableRow.getByRole('cell').nth(${columnIndex})).toHaveText('${escapedValue}');`;
|
|
266
|
+
code = `await expect(tableRow.getByRole('cell', { includeHidden: true }).filter({ visible: true }).nth(${columnIndex})).toHaveText('${escapedValue}');`;
|
|
263
267
|
} else {
|
|
264
|
-
code = `await expect(tableRow.getByRole('cell').nth(${columnIndex})).toHaveText('${escapedValue}');`;
|
|
268
|
+
code = `await expect(tableRow.getByRole('cell', { includeHidden: true }).filter({ visible: true }).nth(${columnIndex})).toHaveText('${escapedValue}');`;
|
|
265
269
|
}
|
|
266
270
|
} else {
|
|
267
271
|
// Fallback: filter by text
|
|
268
272
|
if (isGiven) {
|
|
269
|
-
code = `await tableRow.getByRole('cell').filter({ hasText: '${escapedValue}' }).waitFor();`;
|
|
273
|
+
code = `await tableRow.getByRole('cell', { includeHidden: true }).filter({ hasText: '${escapedValue}' }).filter({ visible: true }).waitFor();`;
|
|
270
274
|
} else {
|
|
271
|
-
code = `await expect(tableRow.getByRole('cell').filter({ hasText: '${escapedValue}' })).toBeVisible();`;
|
|
275
|
+
code = `await expect(tableRow.getByRole('cell', { includeHidden: true }).filter({ hasText: '${escapedValue}' }).filter({ visible: true })).toBeVisible();`;
|
|
272
276
|
}
|
|
273
277
|
}
|
|
274
278
|
|
|
@@ -149,7 +149,7 @@ If the unit is **api-first** (`qa/api/<name>/` or `qa/api/flows/<name>/`), the d
|
|
|
149
149
|
|
|
150
150
|
{{#cap parallel-subagents}}
|
|
151
151
|
4. Follow the `sungen-tc-generation` skill for section identification, viewpoint generation, and output format. **Viewpoint loading discipline:** `sungen-viewpoint` is a **router** — from the page-type (form / list / detail / auth / dashboard …) read **only the matching group file(s)** (e.g. a login screen → group-e-identity; a product list → group-c-data-explore), never all five groups. This keeps the generation context lean. **For flows**, use the "Flow Test Generation" section in the skill. When requirements exist, use the "Requirements-Driven Generation" strategy. **For Tier 1**, apply the **Lightweight Guard** — verify required fields, validation rules, business rules, security checks, and key state transitions all have TCs after generation. **For Tier 2+**, **MUST** apply the full **Mapping Contract** — walk every `spec.md` section top-to-bottom and produce the indicated TCs per Table 1; handle `test-viewpoint.md` per Table 2. Do not silently skip sections.
|
|
152
|
-
5. Generate `.feature` + `test-data.yaml` following `sungen-gherkin-syntax` and `sungen-tc-generation`. **Partition the work into shards and generate them in parallel** when there are ≥2.
|
|
152
|
+
5. Generate `.feature` + `test-data.yaml` following `sungen-gherkin-syntax` and `sungen-tc-generation`. **Partition the work into shards and generate them in parallel** when there are ≥2. **If a scenario needs `@query` DB verification**, check the datasource `engine` first — unsupported engine → follow `sungen-gherkin-syntax` § "Unsupported DB engine — fallback" instead of authoring `@query` steps.
|
|
153
153
|
|
|
154
154
|
**5a. Decide the shards.** A shard is one **coverage unit** sized for parallelism — NOT the 5 coarse viewpoint-router groups (a screen loads only 1–2 of those). Use **either**:
|
|
155
155
|
- one **viewpoint theme** per shard — a `VP-` prefix from the viewpoint overview (`VP-SEC`, `VP-ERROR-EMPTY-STATE`, `VP-CAROUSEL`, …) — preferred when the viewpoint overview is rich (test-2/home had 47 items across many themes); **or**
|
|
@@ -192,7 +192,7 @@ If the unit is **api-first** (`qa/api/<name>/` or `qa/api/flows/<name>/`), the d
|
|
|
192
192
|
{{/cap}}
|
|
193
193
|
{{^cap parallel-subagents}}
|
|
194
194
|
4. Follow the `sungen-tc-generation` skill for section identification, viewpoint generation, and output format. **For flows**, use the "Flow Test Generation" section in the skill. When requirements exist, use the "Requirements-Driven Generation" strategy. **For Tier 1**, apply the **Lightweight Guard** — verify required fields, validation rules, business rules, security checks, and key state transitions all have TCs after generation. **For Tier 2+**, **MUST** apply the full **Mapping Contract** — walk every `spec.md` section top-to-bottom and produce the indicated TCs per Table 1; handle `test-viewpoint.md` per Table 2. Do not silently skip sections. Present sections as a numbered list and let user pick.
|
|
195
|
-
5. Generate or update `.feature` + `test-data.yaml` following `sungen-gherkin-syntax` and `sungen-tc-generation` skills. Generate **group-by-group** (one viewpoint group at a time, tier-by-tier `Write`/`Edit` batches) to stay under the output-token cap. **For flows**: use `[Screen:Element]` namespace format, namespace test-data by phase, add `@flow` tag.
|
|
195
|
+
5. Generate or update `.feature` + `test-data.yaml` following `sungen-gherkin-syntax` and `sungen-tc-generation` skills. Generate **group-by-group** (one viewpoint group at a time, tier-by-tier `Write`/`Edit` batches) to stay under the output-token cap. **For flows**: use `[Screen:Element]` namespace format, namespace test-data by phase, add `@flow` tag. **If a scenario needs `@query` DB verification**, check the datasource `engine` first — unsupported engine → follow `sungen-gherkin-syntax` § "Unsupported DB engine — fallback" instead of authoring `@query` steps.
|
|
196
196
|
> **No parallel fan-out here.** Copilot has no sub-agents, so generation is sequential (the Claude Code variant fans out one `sungen-generator` per viewpoint group and merges). Same output, no speedup.
|
|
197
197
|
5.4. **Depth self-check (deterministic — BEFORE the audit).** Run `sungen depth-lint --screen ${input:name}`. It splits every shallow business-critical scenario into **DEEPEN IN PLACE** (add a real value assertion — the printed `template` is a theme-keyed hint, apply judgment to the actual claim; never fake one onto a visibility/behavior scenario) and **CROSS-SCREEN** (route to a flow / tag `@manual:Mx` + reason — removes it from the depth denominator honestly). Act on both, re-run until `deepen` is empty (or only honest over-counts remain), THEN gate. Lifts first-pass `businessDepth` mechanically instead of via 2–3 repair rounds.
|
|
198
198
|
5.5. **Quality gate & repair (harness — always run).** Per `sungen-harness-audit`: run `sungen audit --screen ${input:name}` (structural), THEN do an **independent semantic review inline** using the `sungen-reviewer` criteria (does each scenario's steps PROVE its title/viewpoint? observable Thens? business-critical assertion depth?). Merge both sets of issues; if gate FAILs / findings exist, repair (budget 3) and re-audit — GATE missing theme → generate it (cross-screen → **automate it in the flow** via `/sungen:add-flow`, NOT a full `@manual` screen duplicate — `sungen audit` flags an automatable `@manual` as `MANUAL-AUTOMATABLE`; reserve `@manual:Mx` for true judgment/missing-capability); DEPTH → add data assertions; BALANCE → add business-core first; TRACE → align VP ids. Never fake a pass.
|
|
@@ -126,7 +126,7 @@ If the unit is **api-first**, skip every selector/capture phase (an API test has
|
|
|
126
126
|
|
|
127
127
|
## Pre-run (phased — per `sungen-selector-fix` skill)
|
|
128
128
|
|
|
129
|
-
1. Verify `<base>/<name>/` has `.feature` + `test-data.yaml`.
|
|
129
|
+
1. Verify `<base>/<name>/` has `.feature` + `test-data.yaml`. **If the feature has `@query` steps**, check the resolved datasource `engine` in `qa/datasources.yaml` — unsupported engine → follow the `sungen-gherkin-syntax` skill § "Unsupported DB engine — fallback" before compiling (do not attempt a direct connect).
|
|
130
130
|
2. **Phase 0 — Selector Pre-gen**: if `selectors.yaml` is missing/empty or doesn't cover the feature file's `[Reference]`s, apply the following decision tree before running Phase 0 from `sungen-selector-fix`:
|
|
131
131
|
|
|
132
132
|
```
|
|
@@ -72,6 +72,14 @@ A flow (`create → login → delete`) is a **Functional integration** test, **n
|
|
|
72
72
|
## File upload (real files)
|
|
73
73
|
`body:` carries only scalar fields — to send a **real file**, declare it in the catalog entry; the runtime reads the fixture from disk. Two forms, by how the server accepts the file:
|
|
74
74
|
- **`files:`** → `multipart/form-data`, the file is a form part: `files: { file: { path: ":avatar", mimeType: image/png } }` (+ optional text `body:` fields alongside). Shorthand `files: { file: ":avatar" }`.
|
|
75
|
+
- **Multiple files under ONE field name** → make the field's value an **array** (each element a spec or shorthand string):
|
|
76
|
+
```yaml
|
|
77
|
+
files:
|
|
78
|
+
gift_image:
|
|
79
|
+
- ":gift_image_1" # test-data: gift_image_1 → fixtures/a.png
|
|
80
|
+
- ":gift_image_2" # test-data: gift_image_2 → fixtures/b.png
|
|
81
|
+
```
|
|
82
|
+
Each element binds its own `:param` from test-data. Use this for endpoints that accept a list of files under the same field — a single object value can only hold one file. **Automate multi-file uploads with `@api`; don't defer to `@manual`.** (File uploads use Playwright's `FormData` multipart, which requires **`@playwright/test` ≥ 1.44** — the version sungen installs by default; only projects pinned to an older Playwright need to upgrade.)
|
|
75
83
|
- **`bodyFile:`** → raw binary body (the whole body IS the file's bytes, e.g. `application/octet-stream`): `bodyFile: { path: ":image", mimeType: application/octet-stream }`.
|
|
76
84
|
|
|
77
85
|
Fixture path resolves cwd-relative/absolute first, else `qa/fixtures/<path>` (drop sample files there, reference by name from `test-data`). An empty resolved file param omits the part → use for missing-file `@cases` error rows. `files:`/`bodyFile:` are mutually exclusive. **Automate the upload success case with `@api`** — don't defer it to `@manual`.
|
|
@@ -91,7 +91,7 @@ needs any of these, it is a **finding for QA** — surface it in the run summary
|
|
|
91
91
|
| toHaveValue mismatch | Expected value differs from actual | Fix value in test-data |
|
|
92
92
|
| toContainText mismatch | Partial text not found | Fix expected partial text in test-data |
|
|
93
93
|
| toBeVisible timeout | Element exists but hidden, or name wrong | Check: is element conditionally visible? Wrong name? Inside dialog? |
|
|
94
|
-
| toHaveCount mismatch | Row count differs | Fix expected count in test-data. Verify: is table loaded? Filtered? |
|
|
94
|
+
| toHaveCount mismatch | Row count differs | Fix expected count in test-data. Verify: is table loaded? Filtered? If `Received: 0` while a dialog is open → aria-hidden trap, see **Table-Specific Errors** |
|
|
95
95
|
|
|
96
96
|
### Assertion type rule
|
|
97
97
|
|
|
@@ -111,6 +111,7 @@ If `toHaveText` fails on an input → the Gherkin step has the wrong target type
|
|
|
111
111
|
| `tableRow is not defined` | Column assertion without preceding row scope step | The Gherkin is missing a row-scope step — this is a **QA authoring gap → report it, let it FAIL**. Do NOT add the step during run-test (the Gherkin is frozen). |
|
|
112
112
|
| `toHaveText` on cell fails (with columns) | Wrong column index in `columns` config | Re-count columns in snapshot (0-indexed). Fix `index` in selectors.yaml |
|
|
113
113
|
| `toBeVisible` on cell fails (no columns) | `filter({ hasText })` didn't match | Check exact cell text in snapshot. Fix value in test-data |
|
|
114
|
+
| Row/cell count reads 0 while a dialog is open, rows visibly present behind it | **aria-hidden trap**: the modal (Radix/MUI/HeadlessUI…) sets `aria-hidden="true"` on the background; plain `getByRole('row'/'cell')` reads the a11y tree, which is empty behind a modal. Twin symptom: count-0 assertions (`table is empty`, `row not exists`) false-PASS under the same condition | Re-run `sungen generate` — table locators from sungen ≥3.2.8 emit `getByRole(…, { includeHidden: true }).filter({ visible: true })` and are immune. Do NOT edit the expected count or weaken the assertion — the rows exist; the old locator measured the wrong tree |
|
|
114
115
|
| Row filter matches 0 rows | Filter text doesn't match any row content | Re-snapshot → find actual row text. Fix filter value in test-data |
|
|
115
116
|
| Row filter matches multiple rows | Filter text is too generic (matches multiple rows) | Use more specific filter text (unique identifier like email, ID) |
|
|
116
117
|
| Table not found | Wrong table name or table not rendered | Re-snapshot → copy exact table accessible name |
|
|
@@ -153,6 +154,16 @@ If `toHaveText` fails on an input → the Gherkin step has the wrong target type
|
|
|
153
154
|
|
|
154
155
|
---
|
|
155
156
|
|
|
157
|
+
## API Request Errors (`@api` / catalog)
|
|
158
|
+
|
|
159
|
+
| Error | Diagnosis | Fix |
|
|
160
|
+
|---|---|---|
|
|
161
|
+
| `400 "Unexpected field"` on a file upload | Endpoint accepts **multiple files under one field**, but the catalog declared a single file (one part sent) | In `apis.yaml`, make that `files:` field an **array** — one `:param` per file: `files: { gift_image: [":gift_image_1", ":gift_image_2"] }`. Add matching `test-data` paths. This is a real automatable case — do NOT defer to `@manual`. |
|
|
162
|
+
| `415 Unsupported Media Type` on upload | Sent multipart where the endpoint wants a raw binary body (or vice-versa) | Use `bodyFile:` (raw binary body) instead of `files:` (multipart part), or the reverse — they are mutually exclusive. |
|
|
163
|
+
| `fixture "…" not found` | The referenced file isn't on disk | Drop the sample file under `qa/fixtures/` and reference it by name from `test-data`. |
|
|
164
|
+
|
|
165
|
+
---
|
|
166
|
+
|
|
156
167
|
## Performance & Infrastructure Errors → Fix in `specs/base.ts`
|
|
157
168
|
|
|
158
169
|
All generated `.spec.ts` import from `specs/base.ts` — shared context caching, navigation, overlay cleanup. AI **can and should** tune `base.ts` to match the project.
|
|
@@ -118,6 +118,34 @@ Scenario: ...
|
|
|
118
118
|
|
|
119
119
|
Path access on a bound result: `{{q.count}}`/`{{q.length}}`, `{{q.first.col}}`, `{{q.last.col}}`, `{{q[2].col}}`, `{{q.col}}` (= first row's col). `expect A is B` also supports `is at least` / `is at most` / `is not`. Tier-2 declarative (trivial inline, no catalog): `User see [<table>] row where [<col>] is {{v}} [has [<col2>] = "x"]`, `… no row where …`, `… count is {{n}}`. Full grammar + catalog/datasource/secret rules → **Advanced → Database** doc. Only emit DB steps when the project has a `database/` catalog / `datasources.yaml`.
|
|
120
120
|
|
|
121
|
+
### Unsupported DB engine — fallback (ask, don't improvise)
|
|
122
|
+
|
|
123
|
+
Direct SQL verification (`@query`, the Data Driver) only supports these engines: **`{postgres, sqlite, mysql}`**. When a datasource's `engine` (or the DB the user describes) is **outside this set** — e.g. Cosmos NoSQL, MongoDB, Cassandra, DynamoDB:
|
|
124
|
+
|
|
125
|
+
1. **Do not** attempt a direct connect. **Do not** improvise a verification method.
|
|
126
|
+
2. Present a fixed `AskUserQuestion` with exactly these 3 branches (always these, no others invented):
|
|
127
|
+
- **@api** — verify state via the project's internal API (route to the API driver).
|
|
128
|
+
- **@manual** — emit a `@manual` step + manual-check guidance (e.g. Cosmos Data Explorer, `az cosmosdb`, the vendor CLI).
|
|
129
|
+
- **Proxy / read-replica SQL** — if the user can supply a SQL-compatible endpoint (including Azure Cosmos DB **for PostgreSQL** / Citus), treat it as `engine: postgres` (or `mysql`) and use the normal Data Driver path above.
|
|
130
|
+
3. **Recommend, don't decide.** Check the project for signals and put the best-fit branch **first**, tagged **"(Recommended)"** with a one-line reason:
|
|
131
|
+
- a project API driver / `qa/api/` catalog / `PEERCONNE_URL`-style internal API exists → **@api** first;
|
|
132
|
+
- else the user hints at a SQL-compatible replica/proxy → **proxy-SQL** first;
|
|
133
|
+
- else → **@manual** first.
|
|
134
|
+
The other two branches plus an **"Other"** option (user describes their own approach) stay available.
|
|
135
|
+
4. **The user always overrides** — they may pick any branch or "Other" regardless of the recommendation.
|
|
136
|
+
5. **Never auto-run** a branch and never silently pick one on the user's behalf — the question must always be asked.
|
|
137
|
+
|
|
138
|
+
Example:
|
|
139
|
+
```
|
|
140
|
+
AskUserQuestion:
|
|
141
|
+
question: "This datasource's engine (cosmos-nosql) isn't in {postgres, sqlite, mysql} — direct SQL connect isn't supported. How should DB state be verified?"
|
|
142
|
+
options:
|
|
143
|
+
- "@api — verify via the project's internal API (Recommended: qa/api/ catalog found)"
|
|
144
|
+
- "@manual — emit a @manual step + Cosmos Data Explorer / az cosmosdb check"
|
|
145
|
+
- "Proxy / read-replica SQL — supply a SQL-compatible endpoint (e.g. Cosmos DB for PostgreSQL) → engine: postgres"
|
|
146
|
+
- "Other — describe your own verification approach"
|
|
147
|
+
```
|
|
148
|
+
|
|
121
149
|
### API response assertions (optional API Driver)
|
|
122
150
|
|
|
123
151
|
An `@api:<name>` call binds the response to `{{name}}` = `{ status, ok, body, headers }` (+ `ok_count`/`status_counts` under `@concurrent`). Assert with the same `expect A is B` grammar + path access:
|
|
@@ -282,9 +282,12 @@ Report results. Do NOT enter another fix loop here.
|
|
|
282
282
|
| `toHaveText` / `toHaveValue` mismatch | Wrong expected data | `test-data.yaml` |
|
|
283
283
|
| `page.goto` error | Wrong URL | page selector in `selectors.yaml` |
|
|
284
284
|
| `frame` error | Element inside iframe | add `frame` field |
|
|
285
|
+
| `role` selector resolves to 0 elements **while a dialog is open**, element visibly rendered behind it | aria-hidden trap — the modal sets `aria-hidden="true"` on the background; role locators read the a11y tree | see aria-hidden note below — NOT a name mismatch, don't churn the selector name |
|
|
285
286
|
|
|
286
287
|
**Group by root cause** — if 5 tests fail because `[Submit]` button has a different name, that's 1 fix, not 5.
|
|
287
288
|
|
|
289
|
+
> **aria-hidden trap** (element exists in the screenshot, locator says 0, a modal is open): compiled TABLE steps are immune from sungen ≥3.2.8 (`includeHidden` + `visible` filter) — if the failing generated code lacks that, re-run `sungen generate` first. For a **user-defined `role` selector** asserted while a dialog is open, the selector name is NOT the problem: prefer restructuring the scenario to assert after the dialog closes; if asserting behind the modal is genuinely intended, switch that selector to `testid` or an allowed `locator` CSS (both DOM-based, immune to aria-hidden). Never "fix" it by renaming the role.
|
|
290
|
+
|
|
288
291
|
**Check `test-results/` first** — Playwright captures failure screenshots automatically. Use these to diagnose before any MCP exploration.
|
|
289
292
|
|
|
290
293
|
### Step 2: Targeted MCP Exploration
|
|
@@ -80,6 +80,46 @@ export function resolveFixture(p: string, label: string): string {
|
|
|
80
80
|
throw new Error(`API Driver: ${label} — fixture "${p}" not found (looked in ${direct} and qa/fixtures/${p}).`);
|
|
81
81
|
}
|
|
82
82
|
|
|
83
|
+
/**
|
|
84
|
+
* Build the multipart FormData body for a file-upload request. A field's value may be a single spec
|
|
85
|
+
* OR an array of specs — an array sends MULTIPLE files under the SAME field name, which a plain object
|
|
86
|
+
* cannot express (a repeated key would overwrite). FormData.append keeps every part, so the request
|
|
87
|
+
* carries all files. Text `body` values ride along as form fields. An empty resolved path omits that
|
|
88
|
+
* part (the missing-file / wrong-type error row). Exported for unit test (assert form.getAll entries).
|
|
89
|
+
*
|
|
90
|
+
* Blob (not File): the global File constructor only exists on Node ≥20 while this package supports
|
|
91
|
+
* Node ≥18; Blob is available on 18+. FormData wraps Blob + filename into a File part internally, so
|
|
92
|
+
* the wire result is identical.
|
|
93
|
+
*/
|
|
94
|
+
export function buildMultipart(
|
|
95
|
+
files: Record<string, FileSpec | FileSpec[]>,
|
|
96
|
+
body: unknown,
|
|
97
|
+
params: Record<string, any>,
|
|
98
|
+
label: string,
|
|
99
|
+
): FormData {
|
|
100
|
+
const form = new FormData();
|
|
101
|
+
// Append file parts first. A field's value may be a single spec or an array (multiple files under
|
|
102
|
+
// one name); FormData.append keeps every part where a plain object would overwrite on a repeated key.
|
|
103
|
+
for (const [field, raw] of Object.entries(files)) {
|
|
104
|
+
for (const s of Array.isArray(raw) ? raw : [raw]) {
|
|
105
|
+
const spec = typeof s === 'string' ? { path: s } : s;
|
|
106
|
+
const fpath = substituteRaw(String(spec.path), params);
|
|
107
|
+
if (!fpath) continue; // empty param → omit the part (a missing-file / wrong-type error row)
|
|
108
|
+
const resolved = resolveFixture(fpath, label);
|
|
109
|
+
const filename = spec.filename ?? path.basename(resolved);
|
|
110
|
+
const blob = new Blob([fs.readFileSync(resolved)], { type: spec.mimeType ?? inferMime(filename) });
|
|
111
|
+
form.append(spec.name ?? field, blob, filename);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
// Text body fields ride along — but skip any name already added as a file part, so a catalog that
|
|
115
|
+
// declares the same key in both body: and files: sends ONE part (the file wins), matching the prior
|
|
116
|
+
// plain-object behaviour rather than emitting a duplicate field a strict server would reject.
|
|
117
|
+
if (body && typeof body === 'object')
|
|
118
|
+
for (const [k, v] of Object.entries(body as Record<string, unknown>))
|
|
119
|
+
if (!form.has(k)) form.append(k, typeof v === 'string' ? v : JSON.stringify(v));
|
|
120
|
+
return form;
|
|
121
|
+
}
|
|
122
|
+
|
|
83
123
|
/**
|
|
84
124
|
* Join a datasource base URL with a catalog path. Concatenate rather than rely on Playwright's
|
|
85
125
|
* baseURL resolution: an absolute path (`/user/1`) resolves against the base ORIGIN and would drop
|
|
@@ -113,7 +153,7 @@ class ApiClient {
|
|
|
113
153
|
*/
|
|
114
154
|
async call(
|
|
115
155
|
label: string,
|
|
116
|
-
req: { method: string; path: string; body?: unknown; encoding?: 'json' | 'form' | 'multipart'; files?: Record<string, FileSpec>; bodyFile?: FileSpec; headers?: Record<string, string>; timeout?: number; datasource?: string },
|
|
156
|
+
req: { method: string; path: string; body?: unknown; encoding?: 'json' | 'form' | 'multipart'; files?: Record<string, FileSpec | FileSpec[]>; bodyFile?: FileSpec; headers?: Record<string, string>; timeout?: number; datasource?: string },
|
|
117
157
|
params: Record<string, any> = {},
|
|
118
158
|
opts: { storageState?: string } = {},
|
|
119
159
|
): Promise<{ status: number; ok: boolean; body: any; headers: Record<string, string> }> {
|
|
@@ -150,21 +190,10 @@ class ApiClient {
|
|
|
150
190
|
headers['content-type'] = spec.mimeType ?? 'application/octet-stream';
|
|
151
191
|
}
|
|
152
192
|
} else if (req.files && Object.keys(req.files).length) {
|
|
153
|
-
const mp: Record<string, any> = {};
|
|
154
|
-
if (body && typeof body === 'object')
|
|
155
|
-
for (const [k, v] of Object.entries(body as Record<string, unknown>)) mp[k] = typeof v === 'string' ? v : JSON.stringify(v);
|
|
156
|
-
for (const [field, raw] of Object.entries(req.files)) {
|
|
157
|
-
const spec = typeof raw === 'string' ? { path: raw } : raw;
|
|
158
|
-
const fpath = substituteRaw(String(spec.path), params);
|
|
159
|
-
if (!fpath) continue; // empty param → omit the part (a missing-file / wrong-type error row)
|
|
160
|
-
const resolved = resolveFixture(fpath, label);
|
|
161
|
-
const filename = spec.filename ?? path.basename(resolved);
|
|
162
|
-
mp[spec.name ?? field] = { name: filename, mimeType: spec.mimeType ?? inferMime(filename), buffer: fs.readFileSync(resolved) };
|
|
163
|
-
}
|
|
164
193
|
// Playwright generates the multipart/form-data Content-Type (with boundary); drop any datasource
|
|
165
194
|
// default Content-Type so it doesn't conflict with / duplicate the generated one.
|
|
166
195
|
deleteHeader(headers, 'content-type');
|
|
167
|
-
bodyOpt.multipart =
|
|
196
|
+
bodyOpt.multipart = buildMultipart(req.files, body, params, label);
|
|
168
197
|
} else if (body !== undefined) {
|
|
169
198
|
const enc = req.encoding ?? 'json';
|
|
170
199
|
if (enc === 'form') bodyOpt.form = body;
|
|
@@ -201,7 +230,7 @@ class ApiClient {
|
|
|
201
230
|
*/
|
|
202
231
|
async callN(
|
|
203
232
|
label: string,
|
|
204
|
-
req: { method: string; path: string; body?: unknown; encoding?: 'json' | 'form' | 'multipart'; files?: Record<string, FileSpec>; bodyFile?: FileSpec; headers?: Record<string, string>; timeout?: number; datasource?: string },
|
|
233
|
+
req: { method: string; path: string; body?: unknown; encoding?: 'json' | 'form' | 'multipart'; files?: Record<string, FileSpec | FileSpec[]>; bodyFile?: FileSpec; headers?: Record<string, string>; timeout?: number; datasource?: string },
|
|
205
234
|
params: Record<string, any> = {},
|
|
206
235
|
n = 1,
|
|
207
236
|
opts: { storageState?: string } = {},
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
* table/column identifiers are validated against a strict allowlist pattern (identifiers
|
|
7
7
|
* can't be bound as parameters). Secrets come from .env.qa / process.env, never inline.
|
|
8
8
|
*
|
|
9
|
-
* Engines: PostgreSQL (`pg`) and SQLite (`better-sqlite3`), lazy-loaded on first use.
|
|
9
|
+
* Engines: PostgreSQL (`pg`), MySQL (`mysql2`), and SQLite (`better-sqlite3`), lazy-loaded on first use.
|
|
10
10
|
* Config: a `datasources.yaml` at the project root (or qa/), with ${VAR} resolved from env.
|
|
11
11
|
*
|
|
12
12
|
* DO NOT EDIT — regenerated by `sungen generate`.
|
|
@@ -21,6 +21,10 @@ const ident = (s: string): string => {
|
|
|
21
21
|
return s;
|
|
22
22
|
};
|
|
23
23
|
|
|
24
|
+
// Single source of truth for the "not supported" error message below and for the mysql/sqlite
|
|
25
|
+
// placeholder rewrite condition (`rewritePlaceholders`) — keep engine names in sync with `DataSourceConfig.engine`.
|
|
26
|
+
const SUPPORTED_ENGINES = ['postgres', 'sqlite', 'mysql'] as const;
|
|
27
|
+
|
|
24
28
|
interface SshConfig {
|
|
25
29
|
host: string; // jump host reachable from the runner
|
|
26
30
|
port?: number; // default 22
|
|
@@ -37,8 +41,8 @@ interface DataSourceConfig {
|
|
|
37
41
|
readonly?: boolean;
|
|
38
42
|
statement_timeout_ms?: number;
|
|
39
43
|
max_rows?: number;
|
|
40
|
-
//
|
|
41
|
-
// still run on the runner; only
|
|
44
|
+
// Fallback path: tunnel the DB SOCKET through an SSH bastion. DB-only — the browser/E2E
|
|
45
|
+
// still run on the runner; only DB traffic crosses. See docs/spec/sungen_data_driver_ssh_tunnel_spec.md.
|
|
42
46
|
ssh?: SshConfig;
|
|
43
47
|
}
|
|
44
48
|
|
|
@@ -120,12 +124,38 @@ function loadConfig(): Record<string, DataSourceConfig> {
|
|
|
120
124
|
return doc.datasources;
|
|
121
125
|
}
|
|
122
126
|
|
|
127
|
+
/**
|
|
128
|
+
* `build()` always emits PG-style `$1..$n` placeholders; mysql2/better-sqlite3 both bind with `?`.
|
|
129
|
+
* Only real placeholders are rewritten — a `$1` sitting inside a single-quoted string literal (e.g.
|
|
130
|
+
* a catalog query `WHERE label = '$1 off'`) is left untouched. SQL escapes an inner quote by doubling
|
|
131
|
+
* it (`''`), which the simple in-string toggle handles (an even number of quotes returns to the same state).
|
|
132
|
+
*/
|
|
133
|
+
export function rewritePlaceholders(engine: string, sql: string): string {
|
|
134
|
+
if (engine !== 'sqlite' && engine !== 'mysql') return sql;
|
|
135
|
+
let out = '';
|
|
136
|
+
let inStr = false;
|
|
137
|
+
for (let i = 0; i < sql.length; i++) {
|
|
138
|
+
const c = sql[i];
|
|
139
|
+
if (c === "'") { inStr = !inStr; out += c; continue; }
|
|
140
|
+
if (!inStr && c === '$' && sql[i + 1] >= '0' && sql[i + 1] <= '9') {
|
|
141
|
+
let j = i + 1;
|
|
142
|
+
while (j < sql.length && sql[j] >= '0' && sql[j] <= '9') j++;
|
|
143
|
+
out += '?';
|
|
144
|
+
i = j - 1;
|
|
145
|
+
continue;
|
|
146
|
+
}
|
|
147
|
+
out += c;
|
|
148
|
+
}
|
|
149
|
+
return out;
|
|
150
|
+
}
|
|
151
|
+
|
|
123
152
|
type Engine = { query(sql: string, params: any[]): Promise<any[]>; };
|
|
124
153
|
|
|
125
154
|
class DataSource {
|
|
126
155
|
private configs: Record<string, DataSourceConfig> | null = null;
|
|
127
156
|
private engines = new Map<string, Engine>();
|
|
128
157
|
private tunnels: Array<{ close: () => void }> = [];
|
|
158
|
+
private mysqlPools: Array<{ end: () => Promise<void> }> = [];
|
|
129
159
|
|
|
130
160
|
private cfg(name?: string): { key: string; conf: DataSourceConfig } {
|
|
131
161
|
if (!this.configs) this.configs = loadConfig();
|
|
@@ -142,7 +172,7 @@ class DataSource {
|
|
|
142
172
|
let engine: Engine;
|
|
143
173
|
if (conf.engine === 'postgres') {
|
|
144
174
|
let connectionString = conf.url;
|
|
145
|
-
if (conf.ssh) { //
|
|
175
|
+
if (conf.ssh) { // Fallback path: tunnel the DB socket through a bastion
|
|
146
176
|
const u = new URL(conf.url);
|
|
147
177
|
const t = await openSshTunnel(conf.ssh, u.hostname, Number(u.port || 5432));
|
|
148
178
|
this.tunnels.push(t);
|
|
@@ -152,20 +182,59 @@ class DataSource {
|
|
|
152
182
|
const { Pool } = require('pg');
|
|
153
183
|
const pool = new Pool({ connectionString, max: 2, statement_timeout: conf.statement_timeout_ms ?? 4000 });
|
|
154
184
|
engine = { query: async (sql, params) => (await pool.query(sql, params)).rows };
|
|
185
|
+
} else if (conf.engine === 'mysql') {
|
|
186
|
+
let connectionString = conf.url;
|
|
187
|
+
if (conf.ssh) { // Fallback path: tunnel the DB socket through a bastion
|
|
188
|
+
const u = new URL(conf.url);
|
|
189
|
+
const t = await openSshTunnel(conf.ssh, u.hostname, Number(u.port || 3306));
|
|
190
|
+
this.tunnels.push(t);
|
|
191
|
+
u.hostname = t.host; u.port = String(t.port); // rewrite host:port → 127.0.0.1:<tunnel> (keep user/pass/db/query)
|
|
192
|
+
connectionString = u.toString();
|
|
193
|
+
}
|
|
194
|
+
const mysql = require('mysql2/promise');
|
|
195
|
+
const pool = mysql.createPool({ uri: connectionString, connectionLimit: 2 });
|
|
196
|
+
this.mysqlPools.push(pool);
|
|
197
|
+
// mysql2 ignores the mysqljs per-query `timeout` field, and destroying the connection does
|
|
198
|
+
// not interrupt an in-flight query — so bound the wait client-side by racing the query
|
|
199
|
+
// against a timer. On overrun we reject and destroy the connection (removes it from the pool
|
|
200
|
+
// rather than releasing a still-busy socket); on success we release it back.
|
|
201
|
+
const timeoutMs = conf.statement_timeout_ms ?? 4000;
|
|
202
|
+
engine = {
|
|
203
|
+
query: async (sql, params) => {
|
|
204
|
+
const conn = await pool.getConnection();
|
|
205
|
+
const qp = conn.query(sql, params);
|
|
206
|
+
qp.catch(() => { /* swallow the post-timeout rejection from the abandoned query */ });
|
|
207
|
+
let timer: NodeJS.Timeout | undefined;
|
|
208
|
+
let timedOut = false;
|
|
209
|
+
const guard = new Promise<never>((_, reject) => {
|
|
210
|
+
timer = setTimeout(() => { timedOut = true; reject(new Error(`Data Driver: mysql query exceeded ${timeoutMs}ms — aborted.`)); }, timeoutMs);
|
|
211
|
+
});
|
|
212
|
+
try {
|
|
213
|
+
const [rows] = await Promise.race([qp, guard]);
|
|
214
|
+
return rows as any[];
|
|
215
|
+
} finally {
|
|
216
|
+
clearTimeout(timer);
|
|
217
|
+
if (timedOut) { try { conn.destroy(); } catch { /* best-effort */ } }
|
|
218
|
+
else { try { conn.release(); } catch { /* already gone */ } }
|
|
219
|
+
}
|
|
220
|
+
},
|
|
221
|
+
};
|
|
155
222
|
} else if (conf.engine === 'sqlite') {
|
|
156
223
|
if (conf.ssh) console.warn(`Data Driver: datasource "${key}" sets ssh: but engine is sqlite (file-based) — ssh ignored.`);
|
|
157
224
|
const Database = require('better-sqlite3');
|
|
158
225
|
const db = new Database(conf.url.replace(/^sqlite:/, ''), { readonly: conf.readonly !== false });
|
|
159
226
|
engine = { query: async (sql, params) => db.prepare(sql).all(...params) };
|
|
160
227
|
} else {
|
|
161
|
-
throw new Error(`Data Driver: engine "${conf.engine}" not supported
|
|
228
|
+
throw new Error(`Data Driver: engine "${conf.engine}" not supported (supported: ${SUPPORTED_ENGINES.join(' | ')}). For non-SQL stores (Cosmos NoSQL, Mongo…) verify via @api or @manual.`);
|
|
162
229
|
}
|
|
163
230
|
this.engines.set(key, engine);
|
|
164
231
|
return { engine, conf };
|
|
165
232
|
}
|
|
166
233
|
|
|
167
|
-
/** Close
|
|
234
|
+
/** Close open MySQL pools + SSH tunnels (optional explicit teardown; tunnels are unref'd so the process exits regardless). */
|
|
168
235
|
close(): void {
|
|
236
|
+
for (const p of this.mysqlPools) { try { void p.end(); } catch { /* best-effort */ } }
|
|
237
|
+
this.mysqlPools = [];
|
|
169
238
|
for (const t of this.tunnels) t.close();
|
|
170
239
|
this.tunnels = [];
|
|
171
240
|
}
|
|
@@ -211,9 +280,9 @@ class DataSource {
|
|
|
211
280
|
expect(n, `Expected ${count} row(s) in "${table}"${cols.length ? ' where ' + desc(filter) : ''} — found ${n}`).toBe(Number(count));
|
|
212
281
|
}
|
|
213
282
|
|
|
214
|
-
/** Rewrites $1/$2 placeholders to `?` for
|
|
283
|
+
/** Rewrites $1/$2 placeholders to `?` for engines that don't support PG-style positional params. */
|
|
215
284
|
private sqlFor(conf: DataSourceConfig, sql: string): string {
|
|
216
|
-
return conf.engine
|
|
285
|
+
return rewritePlaceholders(conf.engine, sql);
|
|
217
286
|
}
|
|
218
287
|
|
|
219
288
|
// --- Named queries (catalog-backed; SQL is resolved + embedded at compile time) -----------
|