@nikhil-qeas/api-core 0.7.0 → 0.8.0
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/CHANGELOG.md +33 -0
- package/README.md +82 -7
- package/bin/qe-api.js +1 -0
- package/dist/http/api-client.d.ts +15 -0
- package/dist/http/api-client.js +41 -4
- package/dist/http/trace.d.ts +26 -0
- package/dist/http/trace.js +43 -0
- package/dist/http/types.d.ts +6 -0
- package/dist/index.d.ts +11 -4
- package/dist/index.js +5 -2
- package/dist/integrations/mocha.d.ts +32 -0
- package/dist/integrations/mocha.js +81 -0
- package/dist/reporting/html-report.d.ts +23 -0
- package/dist/reporting/html-report.js +118 -0
- package/dist/reporting/junit.d.ts +11 -2
- package/dist/reporting/junit.js +9 -3
- package/dist/reporting/redaction.d.ts +6 -0
- package/dist/reporting/redaction.js +10 -0
- package/dist/testing/load.d.ts +85 -0
- package/dist/testing/load.js +134 -0
- package/dist/testing/spec-cases.d.ts +46 -8
- package/dist/testing/spec-cases.js +292 -22
- package/package.json +1 -1
- package/templates/project/README.md +39 -6
- package/templates/project/__dot__env.example +4 -0
- package/templates/project/__dot__gitlab-ci.yml +1 -0
- package/templates/project/openapi/openapi.json +233 -0
- package/templates/project/src/clients/api.ts +4 -2
- package/templates/project/src/environment.ts +8 -0
- package/templates/project/src/observability.ts +15 -1
- package/templates/project/tests/performance/health.spec.ts +22 -0
- package/templates/project/tests/security/authentication.spec.ts +3 -1
- package/templates/project/tests/security/spec-cases.spec.ts +40 -3
- package/templates/project/tests/setup/hooks.ts +32 -5
- package/templates/project/tests/smoke/tracing.spec.ts +48 -0
- package/templates/project/tests/support/mock-api.ts +114 -5
|
@@ -1,4 +1,66 @@
|
|
|
1
1
|
import { performance } from 'node:perf_hooks';
|
|
2
|
+
import { scrubText } from '../reporting/redaction.js';
|
|
3
|
+
const MAX_MESSAGE_CHARS = 2000;
|
|
4
|
+
const MAX_MESSAGE_LINES = 40;
|
|
5
|
+
const ANSI_ESCAPE = new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*[A-Za-z]`, 'g');
|
|
6
|
+
// Mocha's own `currentRetry()` (0 for the first attempt, 1 after one retry) is read when it exists, but it is not part of this type: the Mocha type
|
|
7
|
+
// definitions declare it protected, which would make `this.currentTest` unassignable here.
|
|
8
|
+
function retriesOf(test) {
|
|
9
|
+
const retry = test.currentRetry;
|
|
10
|
+
const count = typeof retry === 'function' ? retry.call(test) : 0;
|
|
11
|
+
return typeof count === 'number' && Number.isInteger(count) && count > 0 ? count : 0;
|
|
12
|
+
}
|
|
13
|
+
const HOOK_KINDS = ['beforeAll', 'beforeEach', 'afterEach', 'afterAll'];
|
|
14
|
+
function isRecord(value) { return typeof value === 'object' && value !== null; }
|
|
15
|
+
/**
|
|
16
|
+
* The hooks (before, after) that failed anywhere under a suite, as text. A failed hook is not a test, so no test record shows it, and the
|
|
17
|
+
* tests it guards never ran: a report built from tests alone would look green on a red run. Call it from a root `afterAll` hook with
|
|
18
|
+
* `this.test?.parent`. It reads Mocha's `getHooks`, which the Mocha type definitions do not declare, so it takes any suite.
|
|
19
|
+
*/
|
|
20
|
+
export function failedHooks(root) {
|
|
21
|
+
const found = [];
|
|
22
|
+
const visit = (suite, depth) => {
|
|
23
|
+
if (!isRecord(suite) || depth > 100)
|
|
24
|
+
return;
|
|
25
|
+
const getHooks = suite.getHooks;
|
|
26
|
+
const title = typeof suite.fullTitle === 'function' ? suite.fullTitle.call(suite) : '';
|
|
27
|
+
if (typeof getHooks === 'function') {
|
|
28
|
+
for (const kind of HOOK_KINDS) {
|
|
29
|
+
const hooks = getHooks.call(suite, kind);
|
|
30
|
+
for (const hook of Array.isArray(hooks) ? hooks : []) {
|
|
31
|
+
if (isRecord(hook) && hook.state === 'failed')
|
|
32
|
+
found.push(`${typeof title === 'string' && title !== '' ? title : '(root)'}: ${typeof hook.title === 'string' ? hook.title : kind}`);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
for (const child of Array.isArray(suite.suites) ? suite.suites : [])
|
|
37
|
+
visit(child, depth + 1);
|
|
38
|
+
};
|
|
39
|
+
visit(root, 0);
|
|
40
|
+
return found;
|
|
41
|
+
}
|
|
42
|
+
/** A failure as one short, printable text: control characters and colors removed, credentials masked, long output cut. */
|
|
43
|
+
export function failureText(error) {
|
|
44
|
+
if (error === undefined || error === null)
|
|
45
|
+
return undefined;
|
|
46
|
+
let text;
|
|
47
|
+
if (error instanceof Error)
|
|
48
|
+
text = `${error.name}: ${error.message}`;
|
|
49
|
+
else if (typeof error === 'string')
|
|
50
|
+
text = error;
|
|
51
|
+
else if (typeof error === 'object' && 'message' in error && typeof error.message === 'string')
|
|
52
|
+
text = error.message;
|
|
53
|
+
else
|
|
54
|
+
text = 'A value that is not an error was thrown';
|
|
55
|
+
const printable = Array.from(text.replace(ANSI_ESCAPE, '').replace(/\r\n?/g, '\n')).filter(char => {
|
|
56
|
+
const code = char.charCodeAt(0);
|
|
57
|
+
return code === 9 || code === 10 || (code >= 32 && code !== 127);
|
|
58
|
+
}).join('');
|
|
59
|
+
const lines = scrubText(printable).split('\n');
|
|
60
|
+
const kept = lines.slice(0, MAX_MESSAGE_LINES).join('\n');
|
|
61
|
+
const more = lines.length > MAX_MESSAGE_LINES ? `\n... ${lines.length - MAX_MESSAGE_LINES} more lines` : '';
|
|
62
|
+
return kept.length > MAX_MESSAGE_CHARS ? `${kept.slice(0, MAX_MESSAGE_CHARS)}...` : `${kept}${more}`;
|
|
63
|
+
}
|
|
2
64
|
/** No dependency on Mocha itself; register this callback from mocha root hooks. */
|
|
3
65
|
export class MochaResultCollector {
|
|
4
66
|
rows = [];
|
|
@@ -9,5 +71,24 @@ export class MochaResultCollector {
|
|
|
9
71
|
this.starts.delete(fullTitle);
|
|
10
72
|
this.rows.push({ name: fullTitle, suite, status, durationMs: began === undefined ? 0 : Math.round(performance.now() - began) });
|
|
11
73
|
}
|
|
74
|
+
/**
|
|
75
|
+
* Records a test from a root `afterEach` hook, once, when it has its final outcome: Mocha runs `afterEach` after every attempt, and an
|
|
76
|
+
* attempt that will be retried has no state yet, so it returns false and nothing is recorded. A test that passed after retries is kept
|
|
77
|
+
* with the number of retries it needed (that is a flaky test, and it should not hide). A failure's text is kept scrubbed and shortened
|
|
78
|
+
* (see `failureText`); the reports leave it out unless asked. Tests marked `it.skip` never reach this hook.
|
|
79
|
+
*/
|
|
80
|
+
record(test, details = {}) {
|
|
81
|
+
const pending = test.state === 'pending' || test.isPending?.() === true;
|
|
82
|
+
if (test.state !== 'passed' && test.state !== 'failed' && !pending)
|
|
83
|
+
return false;
|
|
84
|
+
const status = pending ? 'skipped' : test.state === 'passed' ? 'passed' : 'failed';
|
|
85
|
+
const retries = details.retries ?? retriesOf(test);
|
|
86
|
+
const message = status === 'failed' ? failureText(test.err) : undefined;
|
|
87
|
+
this.rows.push({
|
|
88
|
+
name: test.fullTitle(), suite: test.parent?.fullTitle() ?? '', status, durationMs: Math.round(test.duration ?? 0),
|
|
89
|
+
...(retries > 0 ? { retries } : {}), ...(message !== undefined ? { message } : {}), ...(details.traceId !== undefined ? { traceId: details.traceId } : {})
|
|
90
|
+
});
|
|
91
|
+
return true;
|
|
92
|
+
}
|
|
12
93
|
results() { return this.rows.map(row => ({ ...row })); }
|
|
13
94
|
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { TestCaseResult } from './junit.js';
|
|
2
|
+
export interface HtmlReportOptions {
|
|
3
|
+
/** Default "API test report". */
|
|
4
|
+
title?: string | undefined;
|
|
5
|
+
/** Name and value pairs under the summary, e.g. `['API coverage', '7 of 7 operations (100%)']`. */
|
|
6
|
+
facts?: ReadonlyArray<readonly [string, string]> | undefined;
|
|
7
|
+
/** Warnings shown above everything, e.g. that some tests did not run, so a green-looking report is never mistaken for a green run. */
|
|
8
|
+
notes?: readonly string[] | undefined;
|
|
9
|
+
/** Reasons the run failed that are not tests, such as a failed before hook (see `failedHooks`). Shown in red, and the verdict is FAILED whatever the tests say. */
|
|
10
|
+
problems?: readonly string[] | undefined;
|
|
11
|
+
/** Show each failure's message. The collector has already scrubbed and shortened it, but a message can still quote data, so the default is false. */
|
|
12
|
+
messages?: boolean | undefined;
|
|
13
|
+
/** Default: now. */
|
|
14
|
+
generatedAt?: Date | undefined;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* One self-contained HTML page: the verdict, failures first (with the trace id to look up and, when asked, the message), the tests that
|
|
18
|
+
* only passed after retries, the slowest tests, and every test by suite. No scripts and no external files: a content-security-policy
|
|
19
|
+
* forbids both, and every test title, message and fact is escaped. Failure messages are left out unless `messages` is true.
|
|
20
|
+
*/
|
|
21
|
+
export declare function renderHtmlReport(results: readonly TestCaseResult[], options?: HtmlReportOptions): string;
|
|
22
|
+
/** Writes the report (see `renderHtmlReport`) and creates its folder. The file is readable by its owner only, like the other reports. */
|
|
23
|
+
export declare function writeHtmlReport(path: string, results: readonly TestCaseResult[], options?: HtmlReportOptions): Promise<void>;
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { mkdir, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { dirname } from 'node:path';
|
|
3
|
+
const SLOWEST = 10;
|
|
4
|
+
const STYLE = `
|
|
5
|
+
:root{color-scheme:light dark;--bg:#fff;--fg:#1c2128;--muted:#656d76;--line:#d0d7de;--pass:#1a7f37;--fail:#cf222e;--skip:#6e7781;--flaky:#9a6700;--soft:#f6f8fa}
|
|
6
|
+
@media (prefers-color-scheme:dark){:root{--bg:#0d1117;--fg:#e6edf3;--muted:#8b949e;--line:#30363d;--pass:#3fb950;--fail:#f85149;--skip:#8b949e;--flaky:#d29922;--soft:#161b22}}
|
|
7
|
+
body{margin:0 auto;max-width:960px;padding:24px 16px;background:var(--bg);color:var(--fg);font:14px/1.5 system-ui,sans-serif}
|
|
8
|
+
h1{font-size:22px;margin:0 0 4px}h2{font-size:17px;margin:28px 0 8px;border-bottom:1px solid var(--line);padding-bottom:4px}h3{font-size:14px;margin:18px 0 4px}
|
|
9
|
+
.muted{color:var(--muted)}.verdict{font-weight:600;font-size:16px;margin:12px 0}.pass{color:var(--pass)}.fail{color:var(--fail)}.skip{color:var(--skip)}.flaky{color:var(--flaky)}
|
|
10
|
+
.note{border-left:4px solid var(--flaky);background:var(--soft);padding:8px 12px;margin:8px 0}.note.problem{border-left-color:var(--fail)}
|
|
11
|
+
table{border-collapse:collapse;width:100%}td,th{padding:4px 8px;border-bottom:1px solid var(--line);text-align:left;vertical-align:top}th{color:var(--muted);font-weight:600}
|
|
12
|
+
td.s{width:56px;font-weight:600;font-size:12px}td.n{white-space:nowrap;text-align:right;color:var(--muted);width:80px}
|
|
13
|
+
details{border:1px solid var(--line);border-radius:6px;margin:8px 0;padding:6px 12px}summary{cursor:pointer;font-weight:600}
|
|
14
|
+
pre{background:var(--soft);padding:8px 12px;border-radius:6px;overflow-x:auto;white-space:pre-wrap;word-break:break-word}code{background:var(--soft);padding:1px 5px;border-radius:4px}
|
|
15
|
+
.stats{display:flex;flex-wrap:wrap;gap:8px 24px;margin:8px 0}.stats div{min-width:72px}.stats b{display:block;font-size:20px}
|
|
16
|
+
`;
|
|
17
|
+
function escapeHtml(text) {
|
|
18
|
+
return text.replace(/[&<>"']/g, character => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[character] ?? character);
|
|
19
|
+
}
|
|
20
|
+
function duration(ms) { return ms >= 1000 ? `${(ms / 1000).toFixed(1)} s` : `${Math.round(ms)} ms`; }
|
|
21
|
+
function plural(count, one, many) { return `${count} ${count === 1 ? one : many}`; }
|
|
22
|
+
const isFlaky = (result) => result.status === 'passed' && (result.retries ?? 0) > 0;
|
|
23
|
+
function verdictOf(result) {
|
|
24
|
+
if (result.status === 'failed')
|
|
25
|
+
return { word: 'FAIL', css: 'fail' };
|
|
26
|
+
if (result.status === 'skipped')
|
|
27
|
+
return { word: 'SKIP', css: 'skip' };
|
|
28
|
+
return isFlaky(result) ? { word: 'FLAKY', css: 'flaky' } : { word: 'PASS', css: 'pass' };
|
|
29
|
+
}
|
|
30
|
+
function shortName(result) {
|
|
31
|
+
return result.suite !== '' && result.name.startsWith(`${result.suite} `) ? result.name.slice(result.suite.length + 1) : result.name;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* One self-contained HTML page: the verdict, failures first (with the trace id to look up and, when asked, the message), the tests that
|
|
35
|
+
* only passed after retries, the slowest tests, and every test by suite. No scripts and no external files: a content-security-policy
|
|
36
|
+
* forbids both, and every test title, message and fact is escaped. Failure messages are left out unless `messages` is true.
|
|
37
|
+
*/
|
|
38
|
+
export function renderHtmlReport(results, options = {}) {
|
|
39
|
+
const title = options.title ?? 'API test report';
|
|
40
|
+
const failed = results.filter(result => result.status === 'failed');
|
|
41
|
+
const skipped = results.filter(result => result.status === 'skipped');
|
|
42
|
+
const flaky = results.filter(isFlaky);
|
|
43
|
+
const passed = results.filter(result => result.status === 'passed');
|
|
44
|
+
const totalMs = results.reduce((sum, result) => sum + result.durationMs, 0);
|
|
45
|
+
const out = [];
|
|
46
|
+
out.push(`<h1>${escapeHtml(title)}</h1>`, `<div class="muted">Generated ${escapeHtml((options.generatedAt ?? new Date()).toISOString())}</div>`);
|
|
47
|
+
const problems = options.problems ?? [];
|
|
48
|
+
for (const problem of problems)
|
|
49
|
+
out.push(`<div class="note problem">${escapeHtml(problem)}</div>`);
|
|
50
|
+
for (const note of options.notes ?? [])
|
|
51
|
+
out.push(`<div class="note">${escapeHtml(note)}</div>`);
|
|
52
|
+
if (failed.length || problems.length) {
|
|
53
|
+
const parts = [failed.length ? `${plural(failed.length, 'test', 'tests')} of ${results.length} failed` : '', problems.length ? `${plural(problems.length, 'problem', 'problems')} outside the tests` : ''].filter(Boolean);
|
|
54
|
+
out.push(`<div class="verdict fail">FAILED: ${parts.join(', and ')}</div>`);
|
|
55
|
+
}
|
|
56
|
+
else if (results.length === 0)
|
|
57
|
+
out.push('<div class="verdict muted">No tests were recorded</div>');
|
|
58
|
+
else
|
|
59
|
+
out.push(`<div class="verdict pass">PASSED: ${plural(passed.length, 'test', 'tests')}${flaky.length ? `, ${flaky.length} of them only after retries` : ''}</div>`);
|
|
60
|
+
out.push('<div class="stats">', `<div><b>${results.length}</b>tests</div>`, `<div><b class="pass">${passed.length}</b>passed</div>`, `<div><b class="fail">${failed.length}</b>failed</div>`, `<div><b class="skip">${skipped.length}</b>skipped</div>`, `<div><b class="flaky">${flaky.length}</b>flaky</div>`, `<div><b>${escapeHtml(duration(totalMs))}</b>in tests</div>`, '</div>');
|
|
61
|
+
if (options.facts?.length) {
|
|
62
|
+
out.push('<table>', ...options.facts.map(([name, value]) => `<tr><th>${escapeHtml(name)}</th><td>${escapeHtml(value)}</td></tr>`), '</table>');
|
|
63
|
+
}
|
|
64
|
+
if (failed.length) {
|
|
65
|
+
out.push('<h2>Failures</h2>');
|
|
66
|
+
for (const result of failed) {
|
|
67
|
+
out.push(`<details open><summary class="fail">FAIL <span class="muted">${escapeHtml(result.suite)}</span> ${escapeHtml(shortName(result))} <span class="muted">${escapeHtml(duration(result.durationMs))}</span></summary>`);
|
|
68
|
+
if ((result.retries ?? 0) > 0)
|
|
69
|
+
out.push(`<p>Still failing after ${plural(result.retries ?? 0, 'retry', 'retries')}.</p>`);
|
|
70
|
+
if (result.traceId !== undefined)
|
|
71
|
+
out.push(`<p>Trace id: <code>${escapeHtml(result.traceId)}</code></p>`);
|
|
72
|
+
if (options.messages === true && result.message !== undefined)
|
|
73
|
+
out.push(`<pre>${escapeHtml(result.message)}</pre>`);
|
|
74
|
+
else
|
|
75
|
+
out.push('<p class="muted">The failure message is not included in this report.</p>');
|
|
76
|
+
out.push('</details>');
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
if (flaky.length) {
|
|
80
|
+
out.push('<h2>Passed only after retries</h2>', '<p class="muted">These tests failed at least once and then passed. A test that needs a retry is a flaky test: fix it instead of relying on the retry.</p>', '<table>');
|
|
81
|
+
for (const result of flaky)
|
|
82
|
+
out.push(`<tr><td class="s flaky">FLAKY</td><td>${escapeHtml(result.name)}${result.traceId === undefined ? '' : ` <code>${escapeHtml(result.traceId)}</code>`}</td><td class="n">${escapeHtml(plural(result.retries ?? 0, 'retry', 'retries'))}</td></tr>`);
|
|
83
|
+
out.push('</table>');
|
|
84
|
+
}
|
|
85
|
+
const slowest = results.filter(result => result.status !== 'skipped').sort((a, b) => b.durationMs - a.durationMs || a.name.localeCompare(b.name)).slice(0, SLOWEST);
|
|
86
|
+
if (slowest.length) {
|
|
87
|
+
out.push(`<h2>Slowest ${plural(slowest.length, 'test', 'tests')}</h2>`, '<table>');
|
|
88
|
+
for (const result of slowest)
|
|
89
|
+
out.push(`<tr><td>${escapeHtml(result.name)}</td><td class="n">${escapeHtml(duration(result.durationMs))}</td></tr>`);
|
|
90
|
+
out.push('</table>');
|
|
91
|
+
}
|
|
92
|
+
if (results.length) {
|
|
93
|
+
out.push('<h2>All tests</h2>');
|
|
94
|
+
const suites = new Map();
|
|
95
|
+
for (const result of results)
|
|
96
|
+
suites.set(result.suite, [...(suites.get(result.suite) ?? []), result]);
|
|
97
|
+
for (const [suite, members] of suites) {
|
|
98
|
+
out.push(`<h3>${escapeHtml(suite === '' ? '(no suite)' : suite)}</h3>`, '<table>');
|
|
99
|
+
for (const result of members) {
|
|
100
|
+
const { word, css } = verdictOf(result);
|
|
101
|
+
out.push(`<tr><td class="s ${css}">${word}</td><td>${escapeHtml(shortName(result))}${isFlaky(result) ? ` <span class="flaky">(${escapeHtml(plural(result.retries ?? 0, 'retry', 'retries'))})</span>` : ''}</td><td class="n">${escapeHtml(duration(result.durationMs))}</td></tr>`);
|
|
102
|
+
}
|
|
103
|
+
out.push('</table>');
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
return `<!doctype html>
|
|
107
|
+
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
108
|
+
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'">
|
|
109
|
+
<title>${escapeHtml(title)}</title><style>${STYLE}</style></head><body>
|
|
110
|
+
${out.join('\n')}
|
|
111
|
+
</body></html>
|
|
112
|
+
`;
|
|
113
|
+
}
|
|
114
|
+
/** Writes the report (see `renderHtmlReport`) and creates its folder. The file is readable by its owner only, like the other reports. */
|
|
115
|
+
export async function writeHtmlReport(path, results, options = {}) {
|
|
116
|
+
await mkdir(dirname(path), { recursive: true });
|
|
117
|
+
await writeFile(path, renderHtmlReport(results, options), { encoding: 'utf8', mode: 0o600 });
|
|
118
|
+
}
|
|
@@ -3,7 +3,16 @@ export interface TestCaseResult {
|
|
|
3
3
|
suite: string;
|
|
4
4
|
durationMs: number;
|
|
5
5
|
status: 'passed' | 'failed' | 'skipped';
|
|
6
|
+
/** Why it failed. The collector keeps it scrubbed and shortened; reports leave it out unless asked. */
|
|
6
7
|
message?: string;
|
|
8
|
+
/** How many retries a test needed. A test that passed after retries is flaky. */
|
|
9
|
+
retries?: number;
|
|
10
|
+
/** The trace the test's requests joined, to look up what the server did. */
|
|
11
|
+
traceId?: string;
|
|
7
12
|
}
|
|
8
|
-
|
|
9
|
-
|
|
13
|
+
export interface JunitOptions {
|
|
14
|
+
/** Put each failure's message in the file. Default false: a failure says only "Test failed", because a message can quote data. */
|
|
15
|
+
messages?: boolean | undefined;
|
|
16
|
+
}
|
|
17
|
+
/** Metadata-only JUnit writer; never include request payloads, secrets or response bodies in messages. Messages are opt-in. */
|
|
18
|
+
export declare function writeJunit(path: string, cases: readonly TestCaseResult[], options?: JunitOptions): Promise<void>;
|
package/dist/reporting/junit.js
CHANGED
|
@@ -1,12 +1,18 @@
|
|
|
1
1
|
import { mkdir, writeFile } from 'node:fs/promises';
|
|
2
2
|
import { dirname } from 'node:path';
|
|
3
3
|
function escapeXml(input) { return input.replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]); }
|
|
4
|
-
/** Metadata-only JUnit writer; never include request payloads, secrets or response bodies in messages. */
|
|
5
|
-
export async function writeJunit(path, cases) {
|
|
4
|
+
/** Metadata-only JUnit writer; never include request payloads, secrets or response bodies in messages. Messages are opt-in. */
|
|
5
|
+
export async function writeJunit(path, cases, options = {}) {
|
|
6
6
|
const failed = cases.filter(c => c.status === 'failed').length;
|
|
7
7
|
const skipped = cases.filter(c => c.status === 'skipped').length;
|
|
8
8
|
const rows = cases.map(c => {
|
|
9
|
-
|
|
9
|
+
let content = '';
|
|
10
|
+
if (c.status === 'skipped')
|
|
11
|
+
content = '<skipped/>';
|
|
12
|
+
else if (c.status === 'failed') {
|
|
13
|
+
const message = options.messages === true ? c.message : undefined;
|
|
14
|
+
content = message === undefined ? '<failure message="Test failed"/>' : `<failure message="${escapeXml(message.split('\n', 1)[0] ?? '')}">${escapeXml(message)}</failure>`;
|
|
15
|
+
}
|
|
10
16
|
return `<testcase classname="${escapeXml(c.suite)}" name="${escapeXml(c.name)}" time="${(c.durationMs / 1000).toFixed(3)}">${content}</testcase>`;
|
|
11
17
|
}).join('');
|
|
12
18
|
const xml = `<?xml version="1.0" encoding="UTF-8"?><testsuite name="qe-api" tests="${cases.length}" failures="${failed}" skipped="${skipped}">${rows}</testsuite>`;
|
|
@@ -2,5 +2,11 @@
|
|
|
2
2
|
export declare function keyWords(key: string): string[];
|
|
3
3
|
/** Names what a string looks like when it holds a credential, or undefined. Never returns the value itself. */
|
|
4
4
|
export declare function credentialIn(text: string): string | undefined;
|
|
5
|
+
/**
|
|
6
|
+
* Masks credentials in free text that reaches a report, such as a failure message: everything `redact` masks in a string (Authorization
|
|
7
|
+
* values, JWTs, Luhn-valid card numbers) plus private key blocks and cloud access keys. It cannot know what else is private: a message
|
|
8
|
+
* that quotes data still quotes it, which is why reports leave messages out unless asked.
|
|
9
|
+
*/
|
|
10
|
+
export declare function scrubText(text: string): string;
|
|
5
11
|
/** For structured event metadata only. Never attach raw banking payloads to test reports. */
|
|
6
12
|
export declare function redact(value: unknown, depth?: number): unknown;
|
|
@@ -70,6 +70,16 @@ function scrubString(text) {
|
|
|
70
70
|
return digits.length >= 13 && digits.length <= 19 && passesLuhn(digits) ? REDACTED : match;
|
|
71
71
|
});
|
|
72
72
|
}
|
|
73
|
+
const PRIVATE_KEY_BLOCK = /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g;
|
|
74
|
+
const CLOUD_ACCESS_KEY = /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g;
|
|
75
|
+
/**
|
|
76
|
+
* Masks credentials in free text that reaches a report, such as a failure message: everything `redact` masks in a string (Authorization
|
|
77
|
+
* values, JWTs, Luhn-valid card numbers) plus private key blocks and cloud access keys. It cannot know what else is private: a message
|
|
78
|
+
* that quotes data still quotes it, which is why reports leave messages out unless asked.
|
|
79
|
+
*/
|
|
80
|
+
export function scrubText(text) {
|
|
81
|
+
return scrubString(text.replace(PRIVATE_KEY_BLOCK, REDACTED).replace(CLOUD_ACCESS_KEY, REDACTED));
|
|
82
|
+
}
|
|
73
83
|
/** For structured event metadata only. Never attach raw banking payloads to test reports. */
|
|
74
84
|
export function redact(value, depth = 0) {
|
|
75
85
|
if (depth > 15)
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/** A performance smoke test is not a load generator: these limits are fixed. Use a dedicated tool (k6, Gatling) for real load. */
|
|
2
|
+
export declare const MAX_LOAD_REQUESTS = 1000;
|
|
3
|
+
export declare const MAX_LOAD_CONCURRENCY = 50;
|
|
4
|
+
export declare const MAX_LOAD_WARMUP = 20;
|
|
5
|
+
export interface LoadOptions {
|
|
6
|
+
/** Requests that are measured. Default 50, at most 1000. */
|
|
7
|
+
requests?: number | undefined;
|
|
8
|
+
/** Requests in flight at once. Default 5, at most 50. */
|
|
9
|
+
concurrency?: number | undefined;
|
|
10
|
+
/** Requests sent first, one phase before the measured ones, and left out of the figures (connections, caches, cold starts). Default 3, at most 20. */
|
|
11
|
+
warmup?: number | undefined;
|
|
12
|
+
/** Stop sending once this many requests (warm-up included) have failed, so a broken endpoint is not hammered. Default 25 or the total, whichever is smaller. */
|
|
13
|
+
abortAfterFailures?: number | undefined;
|
|
14
|
+
/** What counts as success. Default: a status below 400. A request that throws always fails. */
|
|
15
|
+
isSuccess?: ((status: number) => boolean) | undefined;
|
|
16
|
+
/** Stop sending when this signal aborts. */
|
|
17
|
+
signal?: AbortSignal | undefined;
|
|
18
|
+
/** Milliseconds from any fixed origin, for tests with a fake clock. Default `performance.now`. */
|
|
19
|
+
now?: (() => number) | undefined;
|
|
20
|
+
}
|
|
21
|
+
export interface LatencyStats {
|
|
22
|
+
min: number;
|
|
23
|
+
mean: number;
|
|
24
|
+
p50: number;
|
|
25
|
+
p90: number;
|
|
26
|
+
p95: number;
|
|
27
|
+
p99: number;
|
|
28
|
+
max: number;
|
|
29
|
+
}
|
|
30
|
+
export interface LoadReport {
|
|
31
|
+
/** Measured requests that finished (warm-up is not counted). */
|
|
32
|
+
requests: number;
|
|
33
|
+
succeeded: number;
|
|
34
|
+
failed: number;
|
|
35
|
+
/** failed / requests, from 0 to 1; 0 when nothing was measured. */
|
|
36
|
+
errorRate: number;
|
|
37
|
+
concurrency: number;
|
|
38
|
+
warmup: number;
|
|
39
|
+
/** Warm-up requests that failed. They count towards `abortAfterFailures` but not towards the figures. */
|
|
40
|
+
warmupFailures: number;
|
|
41
|
+
/** From the first measured request starting to the last one finishing, in ms. */
|
|
42
|
+
durationMs: number;
|
|
43
|
+
/** Measured requests per second over `durationMs`; 0 when that is 0. */
|
|
44
|
+
throughput: number;
|
|
45
|
+
/** In ms, measured around each call to `send`. Percentiles use the nearest-rank method. */
|
|
46
|
+
latency: LatencyStats;
|
|
47
|
+
/** Measured responses by status, e.g. `{ '200': 48, '503': 2 }`. */
|
|
48
|
+
statuses: Record<string, number>;
|
|
49
|
+
/** Measured requests that threw, by error name. */
|
|
50
|
+
errors: Record<string, number>;
|
|
51
|
+
/** True when sending stopped before the planned number of requests. */
|
|
52
|
+
aborted: boolean;
|
|
53
|
+
abortReason?: string | undefined;
|
|
54
|
+
}
|
|
55
|
+
export interface LoadLimits {
|
|
56
|
+
/** Latency ceilings in ms: the figure must be at or below the limit. */
|
|
57
|
+
p50Ms?: number | undefined;
|
|
58
|
+
p90Ms?: number | undefined;
|
|
59
|
+
p95Ms?: number | undefined;
|
|
60
|
+
p99Ms?: number | undefined;
|
|
61
|
+
meanMs?: number | undefined;
|
|
62
|
+
maxMs?: number | undefined;
|
|
63
|
+
/** The highest share of failed requests allowed, from 0 to 1. Default 0: no failures. */
|
|
64
|
+
maxErrorRate?: number | undefined;
|
|
65
|
+
/** The lowest throughput allowed, in requests per second. */
|
|
66
|
+
minThroughput?: number | undefined;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Sends `send()` many times, a few at once, and measures how long each takes: a performance smoke test. It runs a warm-up phase that is
|
|
70
|
+
* not counted, then the measured requests, and reports latency percentiles, throughput, statuses and error names (never bodies).
|
|
71
|
+
* `send` is yours: pass `() => api.request(...)` with a client that enforces your execution policy and a read-only run cannot produce
|
|
72
|
+
* write traffic, because every refused request throws and the run stops after `abortAfterFailures` of them.
|
|
73
|
+
* Latency is measured around each call to `send`, so it includes the client's own work and any retries.
|
|
74
|
+
*/
|
|
75
|
+
export declare function runLoad(send: () => Promise<{
|
|
76
|
+
status: number;
|
|
77
|
+
}>, options?: LoadOptions): Promise<LoadReport>;
|
|
78
|
+
/** One line for the log: what ran, how fast, and what came back. */
|
|
79
|
+
export declare function summarizeLoad(report: LoadReport): string;
|
|
80
|
+
/**
|
|
81
|
+
* Fails when the report breaks a limit, and lists every limit it breaks. No failures are allowed unless `maxErrorRate` says otherwise;
|
|
82
|
+
* a run that stopped early or measured nothing always fails. A limit that is not a finite number of at least 0 throws, because a
|
|
83
|
+
* comparison with it would silently pass. Returns the report.
|
|
84
|
+
*/
|
|
85
|
+
export declare function expectLoad(report: LoadReport, limits?: LoadLimits): LoadReport;
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import { performance } from 'node:perf_hooks';
|
|
3
|
+
/** A performance smoke test is not a load generator: these limits are fixed. Use a dedicated tool (k6, Gatling) for real load. */
|
|
4
|
+
export const MAX_LOAD_REQUESTS = 1000;
|
|
5
|
+
export const MAX_LOAD_CONCURRENCY = 50;
|
|
6
|
+
export const MAX_LOAD_WARMUP = 20;
|
|
7
|
+
const DEFAULT_REQUESTS = 50;
|
|
8
|
+
const DEFAULT_CONCURRENCY = 5;
|
|
9
|
+
const DEFAULT_WARMUP = 3;
|
|
10
|
+
const DEFAULT_ABORT_AFTER = 25;
|
|
11
|
+
function bounded(name, value, min, max) {
|
|
12
|
+
if (!Number.isInteger(value) || value < min || value > max)
|
|
13
|
+
throw new Error(`${name} must be a whole number from ${min} to ${max}${name === 'requests' || name === 'concurrency' || name === 'warmup' ? ' (a smoke test is not a load generator: use k6 or Gatling for real load)' : ''}`);
|
|
14
|
+
return value;
|
|
15
|
+
}
|
|
16
|
+
function nearestRank(sorted, percentile) {
|
|
17
|
+
const rank = Math.max(1, Math.ceil(percentile / 100 * sorted.length));
|
|
18
|
+
return sorted[Math.min(rank, sorted.length) - 1] ?? 0;
|
|
19
|
+
}
|
|
20
|
+
const tenth = (value) => Math.round(value * 10) / 10;
|
|
21
|
+
/**
|
|
22
|
+
* Sends `send()` many times, a few at once, and measures how long each takes: a performance smoke test. It runs a warm-up phase that is
|
|
23
|
+
* not counted, then the measured requests, and reports latency percentiles, throughput, statuses and error names (never bodies).
|
|
24
|
+
* `send` is yours: pass `() => api.request(...)` with a client that enforces your execution policy and a read-only run cannot produce
|
|
25
|
+
* write traffic, because every refused request throws and the run stops after `abortAfterFailures` of them.
|
|
26
|
+
* Latency is measured around each call to `send`, so it includes the client's own work and any retries.
|
|
27
|
+
*/
|
|
28
|
+
export async function runLoad(send, options = {}) {
|
|
29
|
+
const requests = bounded('requests', options.requests ?? DEFAULT_REQUESTS, 1, MAX_LOAD_REQUESTS);
|
|
30
|
+
const warmup = bounded('warmup', options.warmup ?? DEFAULT_WARMUP, 0, MAX_LOAD_WARMUP);
|
|
31
|
+
const concurrency = bounded('concurrency', options.concurrency ?? DEFAULT_CONCURRENCY, 1, MAX_LOAD_CONCURRENCY);
|
|
32
|
+
const abortAfter = bounded('abortAfterFailures', options.abortAfterFailures ?? Math.min(requests + warmup, DEFAULT_ABORT_AFTER), 1, requests + warmup);
|
|
33
|
+
const isSuccess = options.isSuccess ?? ((status) => status < 400);
|
|
34
|
+
const now = options.now ?? (() => performance.now());
|
|
35
|
+
const samples = [];
|
|
36
|
+
let failures = 0;
|
|
37
|
+
let warmupFailures = 0;
|
|
38
|
+
let abortReason;
|
|
39
|
+
const phase = async (count, measured) => {
|
|
40
|
+
let next = 0;
|
|
41
|
+
const worker = async () => {
|
|
42
|
+
while (next < count && abortReason === undefined && options.signal?.aborted !== true) {
|
|
43
|
+
next += 1;
|
|
44
|
+
const started = now();
|
|
45
|
+
let status;
|
|
46
|
+
let error;
|
|
47
|
+
try {
|
|
48
|
+
status = (await send()).status;
|
|
49
|
+
if (typeof status !== 'number')
|
|
50
|
+
error = 'NoStatus';
|
|
51
|
+
}
|
|
52
|
+
catch (caught) {
|
|
53
|
+
error = caught instanceof Error ? caught.name : 'Error';
|
|
54
|
+
}
|
|
55
|
+
const ended = now();
|
|
56
|
+
const ok = error === undefined && status !== undefined && isSuccess(status);
|
|
57
|
+
if (!ok) {
|
|
58
|
+
failures += 1;
|
|
59
|
+
if (!measured)
|
|
60
|
+
warmupFailures += 1;
|
|
61
|
+
if (failures >= abortAfter && abortReason === undefined)
|
|
62
|
+
abortReason = `stopped after ${failures} failure${failures === 1 ? '' : 's'}`;
|
|
63
|
+
}
|
|
64
|
+
if (measured)
|
|
65
|
+
samples.push({ started, ended, status, error, ok });
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
await Promise.all(Array.from({ length: Math.min(concurrency, count) }, worker));
|
|
69
|
+
};
|
|
70
|
+
if (warmup > 0)
|
|
71
|
+
await phase(warmup, false);
|
|
72
|
+
await phase(requests, true);
|
|
73
|
+
if (abortReason === undefined && options.signal?.aborted === true && samples.length < requests)
|
|
74
|
+
abortReason = 'aborted by the caller';
|
|
75
|
+
const latencies = samples.map(sample => sample.ended - sample.started).sort((a, b) => a - b);
|
|
76
|
+
const statuses = {};
|
|
77
|
+
const errors = {};
|
|
78
|
+
for (const sample of samples) {
|
|
79
|
+
if (sample.error !== undefined)
|
|
80
|
+
errors[sample.error] = (errors[sample.error] ?? 0) + 1;
|
|
81
|
+
else if (sample.status !== undefined)
|
|
82
|
+
statuses[String(sample.status)] = (statuses[String(sample.status)] ?? 0) + 1;
|
|
83
|
+
}
|
|
84
|
+
const failed = samples.filter(sample => !sample.ok).length;
|
|
85
|
+
const durationMs = samples.length ? Math.max(...samples.map(sample => sample.ended)) - Math.min(...samples.map(sample => sample.started)) : 0;
|
|
86
|
+
return {
|
|
87
|
+
requests: samples.length, succeeded: samples.length - failed, failed, errorRate: samples.length ? failed / samples.length : 0,
|
|
88
|
+
concurrency, warmup, warmupFailures, durationMs: tenth(durationMs), throughput: durationMs > 0 ? tenth(samples.length / (durationMs / 1000)) : 0,
|
|
89
|
+
latency: latencies.length
|
|
90
|
+
? { min: tenth(latencies[0] ?? 0), mean: tenth(latencies.reduce((sum, value) => sum + value, 0) / latencies.length), p50: tenth(nearestRank(latencies, 50)), p90: tenth(nearestRank(latencies, 90)), p95: tenth(nearestRank(latencies, 95)), p99: tenth(nearestRank(latencies, 99)), max: tenth(latencies[latencies.length - 1] ?? 0) }
|
|
91
|
+
: { min: 0, mean: 0, p50: 0, p90: 0, p95: 0, p99: 0, max: 0 },
|
|
92
|
+
statuses, errors, aborted: abortReason !== undefined, abortReason
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
const percent = (rate) => `${tenth(rate * 100)}%`;
|
|
96
|
+
const counts = (table) => Object.entries(table).map(([name, count]) => `${name}×${count}`).join(', ');
|
|
97
|
+
/** One line for the log: what ran, how fast, and what came back. */
|
|
98
|
+
export function summarizeLoad(report) {
|
|
99
|
+
const { latency } = report;
|
|
100
|
+
const outcome = [Object.keys(report.statuses).length ? `statuses ${counts(report.statuses)}` : '', Object.keys(report.errors).length ? `errors ${counts(report.errors)}` : ''].filter(Boolean).join('; ');
|
|
101
|
+
return `${report.requests} requests (${report.warmup} warm-up), ${report.concurrency} at a time, ${report.durationMs} ms, ${report.throughput} requests/s; latency ms: min ${latency.min}, mean ${latency.mean}, p50 ${latency.p50}, p90 ${latency.p90}, p95 ${latency.p95}, p99 ${latency.p99}, max ${latency.max}${outcome ? `; ${outcome}` : ''}${report.aborted ? `; ${report.abortReason ?? 'stopped early'}` : ''}`;
|
|
102
|
+
}
|
|
103
|
+
const LATENCY_LIMITS = [['p50', 'p50Ms'], ['p90', 'p90Ms'], ['p95', 'p95Ms'], ['p99', 'p99Ms'], ['mean', 'meanMs'], ['max', 'maxMs']];
|
|
104
|
+
/**
|
|
105
|
+
* Fails when the report breaks a limit, and lists every limit it breaks. No failures are allowed unless `maxErrorRate` says otherwise;
|
|
106
|
+
* a run that stopped early or measured nothing always fails. A limit that is not a finite number of at least 0 throws, because a
|
|
107
|
+
* comparison with it would silently pass. Returns the report.
|
|
108
|
+
*/
|
|
109
|
+
export function expectLoad(report, limits = {}) {
|
|
110
|
+
for (const [name, value] of Object.entries(limits)) {
|
|
111
|
+
if (value !== undefined && (!Number.isFinite(value) || value < 0))
|
|
112
|
+
throw new Error(`Load limit ${name} must be a number of at least 0`);
|
|
113
|
+
}
|
|
114
|
+
if (limits.maxErrorRate !== undefined && limits.maxErrorRate > 1)
|
|
115
|
+
throw new Error('Load limit maxErrorRate is a share from 0 to 1');
|
|
116
|
+
const problems = [];
|
|
117
|
+
if (report.aborted)
|
|
118
|
+
problems.push(`the run ${report.abortReason ?? 'stopped early'}`);
|
|
119
|
+
else if (report.requests === 0)
|
|
120
|
+
problems.push('no request was measured');
|
|
121
|
+
const allowed = limits.maxErrorRate ?? 0;
|
|
122
|
+
if (report.errorRate > allowed)
|
|
123
|
+
problems.push(`error rate ${percent(report.errorRate)} (${report.failed} of ${report.requests}) is above ${percent(allowed)}`);
|
|
124
|
+
for (const [label, key] of LATENCY_LIMITS) {
|
|
125
|
+
const limit = limits[key];
|
|
126
|
+
if (limit !== undefined && report.latency[label] > limit)
|
|
127
|
+
problems.push(`${label} latency ${report.latency[label]} ms is above ${limit} ms`);
|
|
128
|
+
}
|
|
129
|
+
if (limits.minThroughput !== undefined && report.throughput < limits.minThroughput)
|
|
130
|
+
problems.push(`throughput ${report.throughput} requests/s is below ${limits.minThroughput}`);
|
|
131
|
+
if (problems.length)
|
|
132
|
+
assert.fail(`Load check failed:\n- ${problems.join('\n- ')}\n${summarizeLoad(report)}`);
|
|
133
|
+
return report;
|
|
134
|
+
}
|
|
@@ -1,7 +1,12 @@
|
|
|
1
1
|
import type { OpenApiDocument, RequestCheck } from '../contracts/openapi.js';
|
|
2
2
|
import type { ApiRequest, ApiResult, Method, Query } from '../http/types.js';
|
|
3
3
|
type Primitive = string | number | boolean;
|
|
4
|
-
export type CaseKind = 'valid' | 'negative' | 'fuzz' | 'security';
|
|
4
|
+
export type CaseKind = 'valid' | 'negative' | 'fuzz' | 'security' | 'mass-assignment' | 'ssrf';
|
|
5
|
+
/** A property a mass-assignment case adds to the request, with the distinctive value it is sent with. */
|
|
6
|
+
export interface InjectedProperty {
|
|
7
|
+
name: string;
|
|
8
|
+
value: string | number;
|
|
9
|
+
}
|
|
5
10
|
export interface OperationRef {
|
|
6
11
|
method: Method;
|
|
7
12
|
path: string;
|
|
@@ -9,11 +14,17 @@ export interface OperationRef {
|
|
|
9
14
|
export interface OperationInfo extends OperationRef {
|
|
10
15
|
operationId?: string | undefined;
|
|
11
16
|
tags: string[];
|
|
12
|
-
/** True when the operation takes a JSON request body
|
|
17
|
+
/** True when the operation takes a JSON request body. */
|
|
13
18
|
jsonBody: boolean;
|
|
19
|
+
/**
|
|
20
|
+
* The kind of request body cases are generated for: JSON, else `application/x-www-form-urlencoded`, else `multipart/form-data`.
|
|
21
|
+
* A form or multipart body gets cases when its required properties are text, numbers, booleans, lists of those, or (multipart) files;
|
|
22
|
+
* nested objects have no plain encoding, so such an operation gets parameter cases only.
|
|
23
|
+
*/
|
|
24
|
+
bodyKind?: 'json' | 'form' | 'multipart' | undefined;
|
|
14
25
|
/** True when the operation needs credentials: it (or the document) declares a security requirement and none of the alternatives is optional. */
|
|
15
26
|
protected: boolean;
|
|
16
|
-
/** Request body content types
|
|
27
|
+
/** Request body content types no cases are generated for: XML and the like, and any form or multipart type a JSON body took precedence over. */
|
|
17
28
|
unsupportedBody: string[];
|
|
18
29
|
}
|
|
19
30
|
export interface GeneratedCase {
|
|
@@ -26,17 +37,23 @@ export interface GeneratedCase {
|
|
|
26
37
|
/** The OpenAPI path template. The concrete path is in `request.path`. */
|
|
27
38
|
path: string;
|
|
28
39
|
description: string;
|
|
29
|
-
/**
|
|
30
|
-
|
|
40
|
+
/**
|
|
41
|
+
* What a conforming API does: accept ('success'), reject with a 4xx ('rejected'), or at least not fail with a 5xx ('survives').
|
|
42
|
+
* 'denied': refuse the credentials. 'not-applied': reject the request, or accept it without applying the added properties
|
|
43
|
+
* (the response must not return the values that were sent).
|
|
44
|
+
*/
|
|
45
|
+
expect: 'success' | 'rejected' | 'survives' | 'denied' | 'not-applied';
|
|
31
46
|
/** For 'denied': the statuses that count as a proper refusal. Usually 401 and 403; 400 is also accepted for malformed credentials. */
|
|
32
47
|
accept?: readonly number[] | undefined;
|
|
33
|
-
/**
|
|
48
|
+
/** For 'not-applied': the properties that were added, and the values to look for in the response. */
|
|
49
|
+
injected?: readonly InjectedProperty[] | undefined;
|
|
50
|
+
/** True when the request breaks a rule the schema states. For a JSON request `OpenApiValidator.assertRequest(check)` then throws. False for transport-level breakage such as malformed JSON. */
|
|
34
51
|
violatesSchema: boolean;
|
|
35
52
|
/** What was done to the otherwise valid request, e.g. "body.name: minLength". */
|
|
36
53
|
violates?: string | undefined;
|
|
37
54
|
/** Send this with `ApiClient.request`. */
|
|
38
55
|
request: ApiRequest;
|
|
39
|
-
/** The same request as spec-checkable parts, for `OpenApiValidator.assertRequest`. Present
|
|
56
|
+
/** The same request as spec-checkable parts, for `OpenApiValidator.assertRequest`. Present for negative cases of operations with a JSON body or none; form and multipart requests have none. */
|
|
40
57
|
check?: RequestCheck | undefined;
|
|
41
58
|
}
|
|
42
59
|
export interface OpenApiCasesOptions {
|
|
@@ -45,6 +62,7 @@ export interface OpenApiCasesOptions {
|
|
|
45
62
|
pathParams?: Readonly<Record<string, Primitive>> | undefined;
|
|
46
63
|
query?: Query | undefined;
|
|
47
64
|
headers?: Readonly<Record<string, string>> | undefined;
|
|
65
|
+
/** The body. For a form or multipart operation, an object of its fields (a file's content as text). */
|
|
48
66
|
json?: unknown;
|
|
49
67
|
}>> | undefined;
|
|
50
68
|
/** At most this many fuzz cases per operation, chosen deterministically. Default 60. */
|
|
@@ -80,6 +98,22 @@ export declare class OpenApiCases {
|
|
|
80
98
|
* authentication, has none. The requests are sent without the client's own credentials (`skipAuth`).
|
|
81
99
|
*/
|
|
82
100
|
security(reference: OperationRef): GeneratedCase[];
|
|
101
|
+
/**
|
|
102
|
+
* Mass-assignment cases for a POST, PUT or PATCH with a JSON object body: a client must not be able to set what the server owns.
|
|
103
|
+
* One case per read-only property the spec declares (sent with a distinctive value), plus one that adds privileged names the spec
|
|
104
|
+
* does not declare (`isAdmin`, `role`, ...) unless it forbids extra properties. Expect `assertCaseOutcome` to pass when the API
|
|
105
|
+
* rejects the request, or accepts it without returning the values that were sent; it fails when a value comes back. A response that
|
|
106
|
+
* merely mirrors the request body will be flagged. Booleans, enums and constants are not tried: no value would stand out.
|
|
107
|
+
*/
|
|
108
|
+
massAssignment(reference: OperationRef): GeneratedCase[];
|
|
109
|
+
/**
|
|
110
|
+
* Server-side request forgery cases: every string field that looks like an address the server may fetch or redirect to (a query
|
|
111
|
+
* parameter or top-level body property with a URI format, or named like url, uri, link, callback, webhook, redirect, href or
|
|
112
|
+
* endpoint) is sent, one at a time, the cloud metadata address, loopback and private addresses, and a local file. Expect a 4xx.
|
|
113
|
+
* An API that deliberately checks addresses only when it fetches them will fail these cases; skip them for such an API. If the API
|
|
114
|
+
* is vulnerable, the server really does contact these addresses, so run them only against an environment that may be probed.
|
|
115
|
+
*/
|
|
116
|
+
ssrf(reference: OperationRef): GeneratedCase[];
|
|
83
117
|
private buildOperation;
|
|
84
118
|
/** The wrong credentials worth trying for the schemes the requirements name. */
|
|
85
119
|
private credentialsFor;
|
|
@@ -93,6 +127,10 @@ export declare class OpenApiCases {
|
|
|
93
127
|
/**
|
|
94
128
|
* Judges a response to a generated case. The message names the case and the rule it broke, and never includes the response body.
|
|
95
129
|
* 'success': 2xx. 'rejected': 4xx (accepting invalid input, or failing with a 5xx, is a defect). 'survives': anything below 500.
|
|
130
|
+
* 'denied': a refusal of the credentials. 'not-applied': a 4xx, or a 2xx whose body does not return the values that were sent
|
|
131
|
+
* (this one needs the whole response, because it reads the body; the message names the properties, never their values).
|
|
96
132
|
*/
|
|
97
|
-
export declare function assertCaseOutcome(response: Pick<ApiResult, 'status'
|
|
133
|
+
export declare function assertCaseOutcome(response: Pick<ApiResult, 'status'> & {
|
|
134
|
+
body?: unknown;
|
|
135
|
+
}, testCase: Pick<GeneratedCase, 'expect' | 'description' | 'method' | 'path' | 'violates' | 'accept' | 'injected'>): void;
|
|
98
136
|
export {};
|