@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
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,39 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to `@nikhil-qeas/api-core`. The format follows [Keep a Changelog](https://keepachangelog.com/), and the project uses semantic versioning (while below 1.0, minor versions may contain behavior changes, which are listed under "Changed").
|
|
4
4
|
|
|
5
|
+
## [0.8.0] - 2026-11-23
|
|
6
|
+
|
|
7
|
+
This release adds a performance smoke test, an HTML test report, trace propagation, mass-assignment and SSRF cases, and generated cases for form and multipart request bodies. Nothing was removed from the library API, and the new options (`trace` and `requestIdHeader` on the client; `traceId` on a request; `messages` on `writeJunit`) all default to the old behavior, so code that only imports the package needs no edits. Two things change for code that uses `OpenApiCases`, and both are listed under Changed: operations with form or multipart bodies now get body cases, and two TypeScript unions gained members. New projects from `qe-api init` get new sample suites and a report; existing generated projects are unaffected.
|
|
8
|
+
|
|
9
|
+
### Added
|
|
10
|
+
|
|
11
|
+
- **HTML test report.** `writeHtmlReport(path, results, options)` and `renderHtmlReport` produce one self-contained page: the verdict, failures first (with the trace id, and the message when asked), tests that passed only after retries, the slowest ten, every test by suite, and `facts` and `notes` you supply. It has no scripts and loads nothing, a content-security-policy forbids both, every dynamic string is escaped, and it works in dark mode and on a phone. `problems` lists what is not a test, and makes the verdict FAILED whatever the listed tests did.
|
|
12
|
+
- **`MochaResultCollector.record(test, { traceId, retries })`** records a Mocha test from a root `afterEach` hook once, with its final outcome: a failed attempt that will be retried is not recorded, and a test that passed after retries is recorded with how many it needed, so flaky tests show instead of hiding behind a pass. Failure messages are kept scrubbed (new `scrubText`: Authorization values, JWTs, card numbers, private keys and cloud keys), stripped of colors and control characters, and cut to 40 lines and 2000 characters (`failureText`). `failedHooks(rootSuite)` lists failed `before` and `after` hooks, which are not tests and have no record, so a report can say FAILED instead of PASSED when a hook broke a run. `TestCaseResult` gains `retries` and `traceId`; new types `MochaTestLike`, `HtmlReportOptions` and `JunitOptions`.
|
|
13
|
+
- **`writeJunit(path, results, { messages: true })`** writes each failure's message (escaped, with its first line as the attribute). The default is unchanged: a failure says only "Test failed".
|
|
14
|
+
- **Form and multipart request bodies get generated cases.** Until now an operation whose body is `application/x-www-form-urlencoded` or `multipart/form-data` got parameter cases only. `OpenApiCases` now builds valid, negative, fuzz, authentication, mass-assignment and SSRF cases for them, sent as `request.form` or `request.multipart`. Because every field is text, the cases use text-aware values, as parameters do: text that cannot be read as the declared number or boolean, a value outside an enum, a missing required field, a value too short or long, a list with too few or too many items (a list repeats the field name) and an extra field where the spec forbids it. "A string for an integer" and an empty list are not violations there, so they are not generated. A `format: binary` (or `contentMediaType`) property is sent as a file part with the content type from `encoding`. `OperationInfo.bodyKind` says which kind of body cases are built for (JSON, else form, else multipart); form and multipart cases have no `check`; a body with a required nested object or a list of objects has no plain encoding and gets parameter cases only. Fuzz adds a `__proto__[polluted]` field in place of the JSON nesting and `__proto__` cases.
|
|
15
|
+
- **Performance smoke tests.** `runLoad(send, options)` calls a function many times, a few at a time, after a warm-up phase that is left out of the figures, and returns counts, the error rate, duration, throughput, nearest-rank latency percentiles (`p50` to `p99`, `min`, `mean`, `max`), statuses by code and errors by name, never bodies or messages. `expectLoad(report, limits)` fails listing every broken limit (`p50Ms` to `maxMs`, `maxErrorRate` with a default of no failures, `minThroughput`); a run that stopped early or measured nothing never passes, and an invalid limit throws. `summarizeLoad` gives one line for the log. It is a smoke test, not a load generator: at most 1000 requests, 50 at a time and 20 warm-up requests (`MAX_LOAD_REQUESTS`, `MAX_LOAD_CONCURRENCY`, `MAX_LOAD_WARMUP`), and it stops after `abortAfterFailures` failures (default 25) so a broken endpoint is not hammered. With a client that enforces a read-only policy a write load is refused before anything is sent.
|
|
16
|
+
- **Trace propagation.** `ApiClient` accepts `trace: true` (or a `TraceConfig`) and sends a W3C `traceparent` header, so a failed test can be found in the API's tracing backend. The trace id is a new one per request, a fixed one, or whatever a function returns for each request (for example the running test's id); `sampled` defaults to true. Every attempt of a retried request is a new span of the same trace. The trace id is reported as `result.traceId` and on `retry`, `success` and `network-error` events. `ApiRequest.traceId` overrides the setting for one request, and a `traceparent` header the caller sets is sent exactly as written and never duplicated. An invalid trace id throws before anything is sent. New exports: `newTraceId`, `newSpanId`, `formatTraceparent`, `parseTraceparent`, `isTraceId`, `TraceConfig`, `ParsedTraceparent`. This propagates context only: no spans are exported, and `tracestate` and `baggage` are not sent.
|
|
17
|
+
- **`requestIdHeader`** sends each request's id (`result.requestId`, the same on every attempt) in a header such as `X-Request-Id`, unless the request sets that header itself.
|
|
18
|
+
- **Mass-assignment cases.** `OpenApiCases.massAssignment(op)` builds, for a POST, PUT or PATCH with a JSON, form or multipart object body, one case per read-only property the spec declares (sent with a distinctive value) and one that adds privileged names the spec does not declare (`isAdmin`, `role`, `ownerId`, `userId`, `balance`, `verified`), unless the spec forbids extra properties. `assertCaseOutcome` judges them (`expect: 'not-applied'`): a 4xx passes, a 2xx passes unless the response returns a value that was sent, and the failure names the property, never the value. Because it reads the body, it needs the whole response, not only its status, and says so if given only a status.
|
|
19
|
+
- **SSRF cases.** `OpenApiCases.ssrf(op)` sends each address-like string field (a `uri` format, or a name such as `url`, `callback`, `webhook` or `redirect`) in the query or the top level of the body the cloud metadata address, loopback and private addresses, and a local file, and expects a 4xx.
|
|
20
|
+
- New case kinds `'mass-assignment'` and `'ssrf'`, `GeneratedCase.injected` and the `InjectedProperty` type.
|
|
21
|
+
|
|
22
|
+
### Changed
|
|
23
|
+
|
|
24
|
+
- **Operations with form or multipart bodies now get body cases (runtime).** `OpenApiCases` used to build parameter cases only for an operation whose body is `application/x-www-form-urlencoded` or `multipart/form-data`, and `valid()` sent no body for it. Now `valid`, `negative`, `fuzz`, `security`, `massAssignment` and `ssrf` build body cases for it, so a suite that loops over every operation sends more, different requests than before, including writes and hostile values, to those operations. A read-only run still refuses the writes before sending. `OperationInfo.bodyKind` tells the kinds apart (`jsonBody` stays false for them), and `unsupportedBody` no longer lists a form or multipart type that is used for cases.
|
|
25
|
+
- **`CaseKind` and `GeneratedCase.expect` gained members (TypeScript only).** `CaseKind` adds `'mass-assignment'` and `'ssrf'`, and `expect` adds `'not-applied'`, so code that switches over them exhaustively must handle the new values. `assertCaseOutcome` now accepts a response that has a `body`, and needs the body to judge a `'not-applied'` case.
|
|
26
|
+
- **Generated projects** write `reports/html/index.html` after every run (and the pipeline keeps it as an artifact). A root `afterEach` hook records each test's final outcome, the root `afterAll` hook writes the page with the API coverage and request figures, names any failed hook, and includes scrubbed failure messages (`messages: true`, which the console and the JUnit report already show). `npm run test:ci -- --retries 2` retries failing tests, and the report lists the ones that only passed on a retry. Existing generated projects are unaffected; to get the report, copy `tests/setup/hooks.ts`, `src/observability.ts` and the `reports/html/` line of `.gitlab-ci.yml` from a new project.
|
|
27
|
+
- **Generated projects** document two more operations in the sample spec: `POST /oauth/token` (a form body) and `POST /accounts/{id}/documents` (a multipart upload with a file), and the mock validates both. The generated negative, fuzz and security suites build cases for them without any change. The sample `authentication.spec.ts` now asks for `clientAuth: 'body'`, because the mock's token endpoint takes the client credentials in the form body; the library default is an HTTP Basic header.
|
|
28
|
+
- **Generated projects** gain `tests/performance/health.spec.ts` (`@performance`: 50 requests, 5 at a time, with a generous latency budget and no failures allowed) and the script `test:performance`.
|
|
29
|
+
- **Generated projects** gain opt-in tracing: with `QE_TRACE=true` the client sends a `traceparent` header, a root hook starts a new trace before every test so all requests of a test share one, and a failed test prints its trace id. Off by default, so requests are unchanged. The mock records the `traceparent` headers it receives, and `tests/smoke/tracing.spec.ts` shows the behavior. A root `beforeEach` hook now runs for every test (it only generates an id).
|
|
30
|
+
- **Generated projects.** The sample `NewAccount` gains `webhookUrl` (a `uri`) and a read-only `accountNumber`; the mock accepts and ignores `accountNumber` and refuses a `webhookUrl` that is not a public http or https address. `tests/security/spec-cases.spec.ts` gains two suites, mass assignment and SSRF (7 cases for the sample). Existing generated projects are unaffected; copy the new suites from a scratch project to get them.
|
|
31
|
+
|
|
32
|
+
### Notes for upgrading
|
|
33
|
+
|
|
34
|
+
- **Already generated a project?** Nothing changes for it. To get the new features, generate a scratch project with this version (`npx --yes --package @nikhil-qeas/api-core@0.8.0 qe-api init scratch-project`) and copy what you want: `tests/setup/hooks.ts`, `src/observability.ts` and the `reports/html/` line of `.gitlab-ci.yml` for the HTML report; `tests/performance/` and the `test:performance` script; `tests/smoke/tracing.spec.ts` with the `QE_TRACE` parts of `src/environment.ts` and `src/clients/api.ts`; the two new suites in `tests/security/spec-cases.spec.ts`; and the new operations and validation in `openapi/openapi.json` and `tests/support/mock-api.ts` if you keep the samples.
|
|
35
|
+
- **If you loop over `cases.operations()` against a real environment**, operations with form or multipart bodies now send body requests too (see Changed). Run them only where hostile writes are acceptable, and note that the SSRF cases make a vulnerable server contact the internal addresses they carry.
|
|
36
|
+
- **Flaky tests.** `npm run test:ci -- --retries 2` retries failing tests in a generated project, and the HTML report lists the ones that only passed on a retry. Retries cannot be set from a hook; they come from Mocha's configuration.
|
|
37
|
+
|
|
5
38
|
## [0.7.0] - 2026-11-23
|
|
6
39
|
|
|
7
40
|
This release adds testing capabilities: test cases generated from your OpenAPI spec, security checks, GraphQL, and everyday helpers for polling, matching, uploads and cookies. Nothing was removed from the library API, and the new options (`cookies` on the client; `multipart`, `skipCookies`, `responseType` and `readOnly` on a request) all default to the old behavior, so code that only imports the package needs no edits. The one TypeScript-level change is listed under Changed. New projects from `qe-api init` get new sample suites; existing generated projects are unaffected.
|
package/README.md
CHANGED
|
@@ -7,7 +7,7 @@ A reusable TypeScript API test utility library and project initializer. Public n
|
|
|
7
7
|
**Generate a complete new project:**
|
|
8
8
|
|
|
9
9
|
```bash
|
|
10
|
-
npx --yes --package @nikhil-qeas/api-core@0.
|
|
10
|
+
npx --yes --package @nikhil-qeas/api-core@0.8.0 qe-api init my-api-project
|
|
11
11
|
cd my-api-project
|
|
12
12
|
npm install
|
|
13
13
|
npm run check
|
|
@@ -25,7 +25,7 @@ The generated project is wired to everything in this package and runs out of the
|
|
|
25
25
|
**Add utilities to an existing project:**
|
|
26
26
|
|
|
27
27
|
```bash
|
|
28
|
-
npm install --save-dev @nikhil-qeas/api-core@0.
|
|
28
|
+
npm install --save-dev @nikhil-qeas/api-core@0.8.0
|
|
29
29
|
```
|
|
30
30
|
|
|
31
31
|
Installing the package does **not** modify your source tree: utilities live under `node_modules`. Run the generator explicitly when you want a new project. The CLI refuses to overwrite an existing directory.
|
|
@@ -36,12 +36,14 @@ Installing the package does **not** modify your source tree: utilities live unde
|
|
|
36
36
|
- Token cache with OAuth2 client-credentials and refresh-token providers, and automatic re-authentication on HTTP 401
|
|
37
37
|
- OpenAPI 3.0/3.1 response and request validation, with a ready-made Ajv backend (`createOpenApiValidator`)
|
|
38
38
|
- Spec-driven negative and fuzz test generation (`OpenApiCases`)
|
|
39
|
-
- Security testing basics: authentication cases from the spec
|
|
39
|
+
- Security testing basics: authentication, mass-assignment and SSRF cases from the spec, an authorization matrix, sensitive-data and security-header checks
|
|
40
|
+
- Performance smoke tests (`runLoad`, `expectLoad`): bounded concurrent requests with latency percentiles, error rate and throughput limits
|
|
41
|
+
- Trace propagation (W3C `traceparent`) and request-id headers, so a failed test can be found in the API's tracing backend
|
|
40
42
|
- GraphQL (`GraphQLClient`): queries and mutations over HTTP, the `errors` array checked, and queries recognised as reads so a read-only run allows them
|
|
41
43
|
- Everyday helpers: polling (`waitFor`), partial matching and JSONPath (`expectBody`, `match`, `jsonPath`), multipart uploads, binary downloads and cookies
|
|
42
44
|
- Synthetic test data and cleanup helpers
|
|
43
45
|
- In-process concurrency and execution context
|
|
44
|
-
- JUnit, runner-neutral Mocha result collection and metadata-only Allure adapter
|
|
46
|
+
- JUnit, runner-neutral Mocha result collection, a self-contained HTML report (failures first, flaky tests, failed hooks) and metadata-only Allure adapter
|
|
45
47
|
- Spec-driven endpoint coverage from an OpenAPI document (`OpenApiCoverage`), plus a manual scenario registry
|
|
46
48
|
- Safety policies, simple metrics and data redaction
|
|
47
49
|
|
|
@@ -158,14 +160,15 @@ for (const operation of cases.operations({ methods: ['POST'] })) {
|
|
|
158
160
|
- **`assertCaseOutcome(response, testCase)`** judges the answer by the case's expectation. Messages name the case and the rule it broke and never quote the response.
|
|
159
161
|
- **It claims only what it can be sure of.** A case is built only when the rule is unambiguous: nothing is generated from `oneOf`/`anyOf` schemas (what breaks one alternative may satisfy another), `readOnly` properties are never sent, and null is not offered to nullable fields. Every case that breaks the schema carries a `check` that `validator.assertRequest(testCase.check)` rejects, which is how the library's own tests prove the cases are really invalid.
|
|
160
162
|
- **Known-good values:** pass `baselines` (`{ 'POST /accounts': { json: {...}, pathParams: {...}, query: {...}, headers: {...} } }`) when the generator cannot invent a valid value (business rules, complex patterns).
|
|
161
|
-
- **
|
|
163
|
+
- **Form and multipart bodies.** `operation.bodyKind` says which body cases are built for: JSON first, else `application/x-www-form-urlencoded`, else `multipart/form-data`. A form or multipart body is sent as `request.form` or `request.multipart`, and every field is text, so its cases use text-aware values, as parameters do: text that cannot be read as the declared number or boolean, an enum value that is not allowed, a missing required field, a value that is too short or long, a list with too few or too many items (a list repeats the field name), and an extra field where the spec forbids it. "A string for an integer" is not a violation there, and an empty list is not either (it sends nothing, the same as the field missing). A multipart property with `format: binary` (or a `contentMediaType`) is sent as a file part with the content type from `encoding` (the first of a list), and the sampled text as its content. Fuzz values go into every text and number field, and into file content. Mass-assignment, SSRF and authentication cases work on form and multipart bodies too. Form and multipart cases have no `check`, because `OpenApiValidator.assertRequest` validates JSON bodies. Supply known-good fields as `baselines: { 'POST /oauth/token': { json: { grant_type: 'client_credentials', client_id: '...' } } }`.
|
|
164
|
+
- **Limits:** XML and other body types, and form or multipart bodies with a required nested object (or a list of objects), which have no plain encoding, are listed in `operation.unsupportedBody` or get parameter cases only; cookie parameters, `not`, `if/then/else` and `dependentRequired` are not modeled. Header parameters get missing and invalid-value cases but are not fuzzed, because the HTTP stack rejects bad header values before the API sees them. `Authorization`, `Content-Type` and `Accept` parameters are left to the client.
|
|
162
165
|
- **These cases send writes and hostile payloads.** Run them only against an environment that may be written to. In a generated project the write guard refuses them until you approve writes.
|
|
163
166
|
|
|
164
167
|
**Request validation.** `OpenApiValidator.assertRequest({ method, path: '/accounts/{id}', pathParams, query, headers, json })` checks a request against its operation: required parameters present, values matching their schemas (query text such as `'10'` is read as the declared integer), a body when one is required, a declared content type, and a body matching its schema. Use it to make sure your own tests send conforming requests. Messages name the parameter or body, never the value.
|
|
165
168
|
|
|
166
169
|
## Security testing basics
|
|
167
170
|
|
|
168
|
-
|
|
171
|
+
Six checks for common API weaknesses (OWASP API Security Top 10: broken authentication, broken object-level and function-level authorization, mass assignment, excessive data exposure, server-side request forgery, security misconfiguration). They are tests of *your* API's behavior, not a scanner: they send requests an API should refuse, so run them only against environments where that is acceptable.
|
|
169
172
|
|
|
170
173
|
**1. Authentication cases from the spec.** `cases.security(op)` returns cases for operations the spec protects (`security` on the operation, or on the document and not overridden with `security: []`; an empty requirement `{}` among the alternatives makes authentication optional, so no cases are built). Credentials are removed from the client (`skipAuth`), then each case sends:
|
|
171
174
|
|
|
@@ -201,7 +204,79 @@ Refusals are sent before grants, so a destructive request that wrongly succeeds
|
|
|
201
204
|
|
|
202
205
|
**4. Security headers: `expectSecurityHeaders(response, options)`.** Fails (at `failOn`, default `'medium'`) when `X-Content-Type-Options: nosniff` is missing; with `https: true`, when `Strict-Transport-Security` is missing or its `max-age` is under six months; with `sensitive: true`, when `Cache-Control` lacks `no-store`. It reports as low severity: a `Server` header with a version number, `X-Powered-By` and `X-AspNet-Version`, and `Access-Control-Allow-Origin: *`, which becomes high when credentials are also allowed. `checkSecurityHeaders` returns the findings; `ignore` accepts the headers you accept. Messages name the header and never its value.
|
|
203
206
|
|
|
204
|
-
**
|
|
207
|
+
**5. Mass assignment: `cases.massAssignment(op)`.** A client must not be able to set what the server owns. For a POST, PUT or PATCH with a JSON, form or multipart object body it builds one case per read-only property the spec declares, sent with a distinctive value (`readOnly` string and number properties; booleans, enums and constants would not stand out and are skipped), and one case that adds privileged names the spec does not declare (`isAdmin`, `role`, `ownerId`, `userId`, `balance`, `verified`), unless the spec forbids extra properties or already declares the name. `assertCaseOutcome` passes a 4xx, and passes a 2xx that does not return what was sent; it fails when the response returns a sent value, found at any depth and under another spelling (`is_admin`, a number returned as text), and names the property, never the value. A server that stores a value but does not return it is not caught, and a response that merely mirrors the request body is flagged. The judging reads the body, so pass `assertCaseOutcome` the whole response.
|
|
208
|
+
|
|
209
|
+
```ts
|
|
210
|
+
for (const testCase of cases.massAssignment(operation)) {
|
|
211
|
+
it(testCase.description, async () => assertCaseOutcome(await api.request(testCase.request), testCase));
|
|
212
|
+
}
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
**6. Server-side request forgery: `cases.ssrf(op)`.** Every string field that holds an address (a query parameter or top-level body property with a `uri`, `url` or `uri-reference` format, or a name with the word `url`, `uri`, `link`, `callback`, `webhook`, `redirect`, `href` or `endpoint`) is sent, one at a time, the cloud metadata address, a loopback address with a port, `localhost`, the IPv6 loopback address, a private network address and a local file. The API must answer 4xx. An API that deliberately checks addresses only when it fetches them fails these cases, so skip them for such an API. Against a vulnerable API the server really contacts the address, so run these only where that is acceptable. Case ids are `METHOD /path mass-assignment #n` and `METHOD /path ssrf #n`.
|
|
216
|
+
|
|
217
|
+
**What this does not cover:** it does not find injection flaws (SQL, command, template), test rate limiting, forge tokens, scan for vulnerable dependencies or replace a penetration test. Mass-assignment and SSRF cases look at what the response says; they cannot see what the server did with the value afterwards, and SSRF cases cannot prove a fetch happened. It checks that an API refuses what its spec says it should refuse, and that responses do not give away what they should not.
|
|
218
|
+
|
|
219
|
+
## Performance smoke tests
|
|
220
|
+
|
|
221
|
+
```ts
|
|
222
|
+
import { expectLoad, runLoad, summarizeLoad } from '@nikhil-qeas/api-core';
|
|
223
|
+
|
|
224
|
+
const report = await runLoad(() => api.request({ method: 'GET', path: '/accounts/42' }), { requests: 50, concurrency: 5 });
|
|
225
|
+
console.log(summarizeLoad(report));
|
|
226
|
+
expectLoad(report, { p95Ms: 300, maxErrorRate: 0.02, minThroughput: 20 });
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
This catches an endpoint that became slow, or started failing, under a little concurrency. It is not a load test.
|
|
230
|
+
|
|
231
|
+
- **`runLoad(send, options)`** calls `send()` (any function that returns something with a `status`) `requests` times, `concurrency` at a time. A warm-up phase (`warmup`, default 3) runs first and is left out of every figure. The report has the counts, the error rate, the duration and throughput, `latency` (`min`, `mean`, `p50`, `p90`, `p95`, `p99`, `max` in ms, nearest-rank percentiles), `statuses` by code and `errors` by error name. It never holds a response body or an error message. Latency is measured around each call to `send`, so it includes the client's own work and retries.
|
|
232
|
+
- **`expectLoad(report, limits)`** fails and lists every limit that is broken: `p50Ms`, `p90Ms`, `p95Ms`, `p99Ms`, `meanMs`, `maxMs` (a figure equal to its limit passes), `maxErrorRate` (a share from 0 to 1; default 0, so no failures are allowed) and `minThroughput`. A run that stopped early or measured nothing never passes, and a limit that is not a finite number of at least 0 throws instead of silently passing.
|
|
233
|
+
- **Failure means a status of 400 or more, or a request that threw.** Change it with `isSuccess: status => status < 500` when a 404 is expected.
|
|
234
|
+
- **Hard limits.** At most 1000 requests, 50 at a time and 20 warm-up requests, and these cannot be raised: use k6 or Gatling for real load. The run stops sending after `abortAfterFailures` failures (default 25, warm-up included), so a broken endpoint is not hammered; requests already in flight finish. `signal` stops it on demand.
|
|
235
|
+
- **Read-only runs stay read-only.** `send` is yours, so use a client that enforces your execution policy (the generated project's `createApiClient()` does): a POST load is then refused before anything is sent, every call throws, and the run stops after the allowed failures.
|
|
236
|
+
- **Timing depends on the machine.** Numbers from a laptop, a shared CI runner and a test environment differ; set limits with headroom, and prefer percentiles over the maximum. Use `now` to inject a clock in tests of your own.
|
|
237
|
+
|
|
238
|
+
## Test reports and flaky tests
|
|
239
|
+
|
|
240
|
+
```ts
|
|
241
|
+
import { MochaResultCollector, failedHooks, writeHtmlReport } from '@nikhil-qeas/api-core';
|
|
242
|
+
|
|
243
|
+
const results = new MochaResultCollector();
|
|
244
|
+
export const mochaHooks = { // a Mocha root hook plugin
|
|
245
|
+
afterEach(this: Mocha.Context) { if (this.currentTest) results.record(this.currentTest); },
|
|
246
|
+
async afterAll(this: Mocha.Context) {
|
|
247
|
+
const broken = this.test?.parent ? failedHooks(this.test.parent) : [];
|
|
248
|
+
await writeHtmlReport('reports/html/index.html', results.results(), {
|
|
249
|
+
messages: true,
|
|
250
|
+
problems: broken.length ? [`${broken.length} hooks failed: ${broken.join('; ')}`] : []
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
};
|
|
254
|
+
```
|
|
255
|
+
|
|
256
|
+
Generated projects already do this; run `npm run test:ci -- --retries 2` there to retry failing tests.
|
|
257
|
+
|
|
258
|
+
- **`MochaResultCollector.record(test, { traceId })`** takes a Mocha test from a root `afterEach` hook and records it once, with its final outcome. Mocha runs `afterEach` after every attempt, and an attempt that will be retried has no state yet, so nothing is recorded for it: a test that fails twice and then passes is one record, `passed`, with `retries: 2`. That is a flaky test, and the reports list it as one instead of hiding it behind a pass. A failure's message is kept scrubbed (`scrubText`: Authorization values, JWTs, card numbers, private keys, cloud keys), stripped of colors and control characters, and cut to 40 lines and 2000 characters (`failureText`). Retries are set in Mocha's configuration (`--retries 2`); setting them from a root hook does nothing. Tests marked `it.skip` are not recorded, because Mocha runs no hook for them.
|
|
259
|
+
- **`writeHtmlReport(path, results, options)`** writes one page: the verdict, failures first (with the trace id, and the message when `messages: true`), the tests that passed only after retries, the slowest ten, every test by suite, and any `facts` you give (coverage, request figures). It is self-contained: no scripts, no files to load, a content-security-policy that forbids both, and every test title, message and fact is escaped. It works in dark mode and on a phone. Failure messages are left out unless `messages` is true, because a message can quote data (an assertion that compares two bodies prints both).
|
|
260
|
+
- **A failed hook is not a test.** If a `before` hook fails, its tests never run and have no record, so a report built from tests alone would say PASSED on a failed run. `failedHooks(rootSuite)` lists the failed hooks (it reads Mocha's `getHooks`, which Mocha's type definitions do not declare, so it accepts any suite), and `problems` makes the report say FAILED, name them, and show the problem in red whatever the listed tests did. `renderHtmlReport` returns the page as text, and `notes` adds neutral warnings.
|
|
261
|
+
- **`writeJunit(path, results, { messages: true })`** now writes each failure's message (escaped, with the first line as the attribute). The default is unchanged: a failure says only "Test failed". `TestCaseResult` gains `retries` and `traceId`.
|
|
262
|
+
- **Not Mocha-only.** `TestCaseResult` is a plain object (`name`, `suite`, `status`, `durationMs`, and optionally `message`, `retries`, `traceId`), so any runner can feed the writers.
|
|
263
|
+
|
|
264
|
+
## Tracing and correlation
|
|
265
|
+
|
|
266
|
+
```ts
|
|
267
|
+
const api = new ApiClient({ baseUrl: process.env.QE_BASE_URL!, trace: true }); // a new trace per request
|
|
268
|
+
const result = await api.request({ method: 'GET', path: '/accounts/42' });
|
|
269
|
+
console.log(result.traceId); // search for this id in Jaeger, Tempo, Datadog, ... to see what the server did
|
|
270
|
+
```
|
|
271
|
+
|
|
272
|
+
When a test fails in CI, the first question is what the server did. `trace` makes every request carry a W3C `traceparent` header (`00-<trace id>-<span id>-01`), and the trace id comes back on the result and on every event.
|
|
273
|
+
|
|
274
|
+
- **One trace per test.** `trace: { traceId: () => idOfTheRunningTest }` calls the function for each request, so every request of a test lands in one trace; when it returns `undefined` the request gets a trace of its own. A fixed id works too, and `sampled: false` clears the sampled flag (default: sampled, since test traffic is worth keeping). `ApiRequest.traceId` overrides the setting for one request, and sends a `traceparent` even when the client does not trace.
|
|
275
|
+
- **Retries.** Every attempt of a retried request is a new span of the same trace, so the failed attempts show up next to the one that worked. The `retry`, `success` and `network-error` events all carry `traceId`.
|
|
276
|
+
- **Your own header wins.** A `traceparent` header you set on a request or in `defaultHeaders` is sent exactly as written (a deliberately malformed one works for negative tests), never duplicated, and its trace id is the one reported.
|
|
277
|
+
- **Request ids.** `requestIdHeader: 'X-Request-Id'` also sends the request's id (`result.requestId`) in that header, the same on every attempt, unless the request sets it itself. Use it to correlate with logs that have no tracing.
|
|
278
|
+
- **Helpers:** `newTraceId()`, `newSpanId()`, `formatTraceparent()`, `parseTraceparent()`, `isTraceId()`. An invalid trace id throws before anything is sent, not even a token request.
|
|
279
|
+
- **What this is not.** It propagates trace context; it does not export spans, needs no OpenTelemetry SDK, and records nothing. `tracestate` and `baggage` are not sent. It helps only when the API under test joins incoming traces (many gateways and services do; some strip the header). Generated projects wire it up with `QE_TRACE=true`.
|
|
205
280
|
|
|
206
281
|
## Retries, backoff and Retry-After
|
|
207
282
|
|
package/bin/qe-api.js
CHANGED
|
@@ -48,6 +48,7 @@ function projectPackage(name) {
|
|
|
48
48
|
'test:security': `${MOCHA} --grep "@security"`,
|
|
49
49
|
'test:negative': `${MOCHA} --grep "@negative"`,
|
|
50
50
|
'test:fuzz': `${MOCHA} --grep "@fuzz"`,
|
|
51
|
+
'test:performance': `${MOCHA} --grep "@performance"`,
|
|
51
52
|
'test:ci': `node -e "require('node:fs').mkdirSync('reports/junit',{recursive:true})" && ${MOCHA} --reporter xunit --reporter-option output=reports/junit/results.xml`,
|
|
52
53
|
check: 'npm run typecheck && npm run lint && npm test',
|
|
53
54
|
'audit:security': 'npm audit --audit-level=high'
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { TokenSource } from '../auth/token-manager.js';
|
|
2
2
|
import { CookieJar } from './cookies.js';
|
|
3
3
|
import type { RetryConfig } from './retry.js';
|
|
4
|
+
import type { TraceConfig } from './trace.js';
|
|
4
5
|
import type { ApiRequest, ApiResult, EventSink, RequestSigner } from './types.js';
|
|
5
6
|
export declare class ApiTransportError extends Error {
|
|
6
7
|
readonly kind: 'network' | 'timeout';
|
|
@@ -30,6 +31,15 @@ export interface ApiClientConfig extends RetryConfig {
|
|
|
30
31
|
maxSafeRetries?: number;
|
|
31
32
|
signer?: RequestSigner;
|
|
32
33
|
defaultHeaders?: Record<string, string>;
|
|
34
|
+
/**
|
|
35
|
+
* Send a W3C `traceparent` header so the server side can show what each request did (`true` for a new trace per request, or a
|
|
36
|
+
* `TraceConfig`, for example to put all requests of one test in one trace). Every attempt of a retried request gets its own span
|
|
37
|
+
* in the same trace. The trace id comes back as `result.traceId` and on events. Off by default. This propagates context; it does
|
|
38
|
+
* not export spans.
|
|
39
|
+
*/
|
|
40
|
+
trace?: boolean | TraceConfig;
|
|
41
|
+
/** Also send the request's id (the `requestId` on results and events) in this header, e.g. `X-Request-Id`, the same on every attempt. */
|
|
42
|
+
requestIdHeader?: string;
|
|
33
43
|
onEvent?: EventSink;
|
|
34
44
|
fetchImpl?: typeof fetch;
|
|
35
45
|
}
|
|
@@ -43,5 +53,10 @@ export declare class ApiClient {
|
|
|
43
53
|
/** The cookie jar, when `cookies` is enabled. */
|
|
44
54
|
readonly cookies: CookieJar | undefined;
|
|
45
55
|
constructor(cfg: ApiClientConfig);
|
|
56
|
+
/**
|
|
57
|
+
* The trace a request joins, and how each attempt announces it. A `traceparent` header the caller set always wins (it is sent as
|
|
58
|
+
* it is, so a deliberately malformed one works for negative tests) and only supplies the trace id reported back.
|
|
59
|
+
*/
|
|
60
|
+
private traceFor;
|
|
46
61
|
request<T = unknown>(req: ApiRequest): Promise<ApiResult<T>>;
|
|
47
62
|
}
|
package/dist/http/api-client.js
CHANGED
|
@@ -2,6 +2,7 @@ import { randomUUID } from 'node:crypto';
|
|
|
2
2
|
import { CookieJar } from './cookies.js';
|
|
3
3
|
import { encodeMultipart } from './multipart.js';
|
|
4
4
|
import { backoffDelay, resolveRetryPolicy, retryDelay } from './retry.js';
|
|
5
|
+
import { formatTraceparent, isTraceId, newSpanId, newTraceId, parseTraceparent } from './trace.js';
|
|
5
6
|
export class ApiTransportError extends Error {
|
|
6
7
|
kind;
|
|
7
8
|
constructor(message, kind, options) {
|
|
@@ -63,6 +64,13 @@ function hasHeader(headers, name) {
|
|
|
63
64
|
const wanted = name.toLowerCase();
|
|
64
65
|
return Object.keys(headers).some(key => key.toLowerCase() === wanted);
|
|
65
66
|
}
|
|
67
|
+
function headerValue(headers, name) {
|
|
68
|
+
const wanted = name.toLowerCase();
|
|
69
|
+
const key = Object.keys(headers).find(candidate => candidate.toLowerCase() === wanted);
|
|
70
|
+
return key === undefined ? undefined : headers[key];
|
|
71
|
+
}
|
|
72
|
+
const HEADER_NAME = /^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/;
|
|
73
|
+
const BAD_TRACE_ID = 'A trace id is 32 lowercase hex digits and not all zeros';
|
|
66
74
|
/** Browserless, dependency-light HTTP engine. Keeps signed request bytes identical to transmitted bytes. */
|
|
67
75
|
export class ApiClient {
|
|
68
76
|
cfg;
|
|
@@ -79,6 +87,28 @@ export class ApiClient {
|
|
|
79
87
|
this.fetcher = cfg.fetchImpl ?? fetch;
|
|
80
88
|
this.retryPolicy = resolveRetryPolicy(cfg);
|
|
81
89
|
this.cookies = cfg.cookies === true ? new CookieJar() : cfg.cookies === false ? undefined : cfg.cookies;
|
|
90
|
+
if (cfg.requestIdHeader !== undefined && !HEADER_NAME.test(cfg.requestIdHeader))
|
|
91
|
+
throw new Error('requestIdHeader is not a valid header name');
|
|
92
|
+
if (typeof cfg.trace === 'object' && typeof cfg.trace.traceId === 'string' && !isTraceId(cfg.trace.traceId))
|
|
93
|
+
throw new Error(BAD_TRACE_ID);
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* The trace a request joins, and how each attempt announces it. A `traceparent` header the caller set always wins (it is sent as
|
|
97
|
+
* it is, so a deliberately malformed one works for negative tests) and only supplies the trace id reported back.
|
|
98
|
+
*/
|
|
99
|
+
traceFor(req, callerTraceparent) {
|
|
100
|
+
if (callerTraceparent !== undefined)
|
|
101
|
+
return { traceId: parseTraceparent(callerTraceparent)?.traceId, traceparent: undefined };
|
|
102
|
+
if (req.traceId === undefined && !this.cfg.trace)
|
|
103
|
+
return { traceId: undefined, traceparent: undefined };
|
|
104
|
+
const config = typeof this.cfg.trace === 'object' ? this.cfg.trace : undefined;
|
|
105
|
+
const configured = typeof config?.traceId === 'function' ? config.traceId() : config?.traceId;
|
|
106
|
+
const chosen = req.traceId ?? configured;
|
|
107
|
+
if (chosen !== undefined && !isTraceId(chosen))
|
|
108
|
+
throw new Error(BAD_TRACE_ID);
|
|
109
|
+
const traceId = chosen ?? newTraceId();
|
|
110
|
+
const sampled = config?.sampled !== false;
|
|
111
|
+
return { traceId, traceparent: () => formatTraceparent(traceId, newSpanId(), sampled) };
|
|
82
112
|
}
|
|
83
113
|
async request(req) {
|
|
84
114
|
assertPath(req.path);
|
|
@@ -102,6 +132,8 @@ export class ApiClient {
|
|
|
102
132
|
const canRetry = retryAllowed(req.method, req.idempotent === true);
|
|
103
133
|
const retryCount = canRetry ? Math.min(Math.max(0, req.retry ?? this.cfg.maxSafeRetries ?? 1), 5) : 0;
|
|
104
134
|
const requestId = randomUUID();
|
|
135
|
+
const trace = this.traceFor(req, headerValue({ ...this.cfg.defaultHeaders, ...req.headers }, 'traceparent')); // before anything is sent: a bad trace id fails the request
|
|
136
|
+
const traceMarker = trace.traceId === undefined ? {} : { traceId: trace.traceId };
|
|
105
137
|
const started = performance.now();
|
|
106
138
|
const auth = this.cfg.auth;
|
|
107
139
|
const authHeader = auth?.header ?? 'Authorization';
|
|
@@ -110,7 +142,7 @@ export class ApiClient {
|
|
|
110
142
|
const policy = this.retryPolicy;
|
|
111
143
|
// Reports an attempt that is followed by another one, so retries are visible instead of hidden inside `attempts`.
|
|
112
144
|
const emitRetry = (attempt, attemptStarted, reason, retryInMs, extra) => {
|
|
113
|
-
this.cfg.onEvent?.({ kind: 'retry', method: req.method, path: req.path, durationMs: Math.round(performance.now() - attemptStarted), attempts: attempt, requestId, reason, retryInMs, ...extra });
|
|
145
|
+
this.cfg.onEvent?.({ kind: 'retry', method: req.method, path: req.path, durationMs: Math.round(performance.now() - attemptStarted), attempts: attempt, requestId, reason, retryInMs, ...traceMarker, ...extra });
|
|
114
146
|
};
|
|
115
147
|
for (let attempt = 1;; attempt++) {
|
|
116
148
|
const attemptStarted = performance.now();
|
|
@@ -132,6 +164,11 @@ export class ApiClient {
|
|
|
132
164
|
usedToken = (await auth.tokens.tokens()).accessToken;
|
|
133
165
|
headers[authHeader] = auth.scheme === '' ? usedToken : `${auth.scheme ?? 'Bearer'} ${usedToken}`;
|
|
134
166
|
}
|
|
167
|
+
// Each attempt is its own span of the same trace; the request id stays the same across attempts.
|
|
168
|
+
if (trace.traceparent !== undefined)
|
|
169
|
+
headers.traceparent = trace.traceparent();
|
|
170
|
+
if (this.cfg.requestIdHeader !== undefined && !hasHeader(headers, this.cfg.requestIdHeader))
|
|
171
|
+
headers[this.cfg.requestIdHeader] = requestId;
|
|
135
172
|
// Signature is regenerated each attempt; pass the exact body bytes, never a reserialized object.
|
|
136
173
|
Object.assign(headers, await this.cfg.signer?.({ method: req.method, path: req.path, exactBody: typeof payload === 'string' ? payload : textDecoder.decode(payload), exactBodyBytes: payloadBytes, requestId, attempt }));
|
|
137
174
|
const timeoutMs = req.timeoutMs ?? this.cfg.timeoutMs ?? 15_000;
|
|
@@ -151,7 +188,7 @@ export class ApiClient {
|
|
|
151
188
|
await policy.clock.sleep(wait);
|
|
152
189
|
continue;
|
|
153
190
|
}
|
|
154
|
-
this.cfg.onEvent?.({ kind: 'network-error', method: req.method, path: req.path, error: isTimeout ? 'timeout' : 'network', durationMs: Math.round(performance.now() - started), attempts: attempt, requestId });
|
|
191
|
+
this.cfg.onEvent?.({ kind: 'network-error', method: req.method, path: req.path, error: isTimeout ? 'timeout' : 'network', durationMs: Math.round(performance.now() - started), attempts: attempt, requestId, ...traceMarker });
|
|
155
192
|
throw new ApiTransportError(`${req.method} ${req.path} ${isTimeout ? 'timed out' : 'failed to connect'}`, isTimeout ? 'timeout' : 'network');
|
|
156
193
|
}
|
|
157
194
|
{
|
|
@@ -187,8 +224,8 @@ export class ApiClient {
|
|
|
187
224
|
}
|
|
188
225
|
const elapsed = Math.round(performance.now() - started);
|
|
189
226
|
const marker = reauthenticated ? { reauthenticated: true } : {};
|
|
190
|
-
this.cfg.onEvent?.({ kind: 'success', method: req.method, path: req.path, status: response.status, durationMs: elapsed, attempts: attempt, requestId, ...marker });
|
|
191
|
-
return { status: response.status, statusText: response.statusText, headers: Object.fromEntries(response.headers), body: (bytes ?? parse(text, response.headers.get('content-type'))), text, durationMs: elapsed, attempts: attempt, requestId, ...marker };
|
|
227
|
+
this.cfg.onEvent?.({ kind: 'success', method: req.method, path: req.path, status: response.status, durationMs: elapsed, attempts: attempt, requestId, ...traceMarker, ...marker });
|
|
228
|
+
return { status: response.status, statusText: response.statusText, headers: Object.fromEntries(response.headers), body: (bytes ?? parse(text, response.headers.get('content-type'))), text, durationMs: elapsed, attempts: attempt, requestId, ...traceMarker, ...marker };
|
|
192
229
|
}
|
|
193
230
|
}
|
|
194
231
|
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/** Join requests to a trace the server side can show (W3C Trace Context). */
|
|
2
|
+
export interface TraceConfig {
|
|
3
|
+
/**
|
|
4
|
+
* The trace every request joins: 32 lowercase hex digits, not all zeros. A function is called for each request, for example to
|
|
5
|
+
* return the id of the running test so that all its requests land in one trace; when it returns undefined the request gets a new
|
|
6
|
+
* trace. Default: a new trace for every request.
|
|
7
|
+
*/
|
|
8
|
+
traceId?: string | (() => string | undefined) | undefined;
|
|
9
|
+
/** Ask the server side to record the trace (the `sampled` flag). Default true: test traffic is worth keeping. */
|
|
10
|
+
sampled?: boolean | undefined;
|
|
11
|
+
}
|
|
12
|
+
export interface ParsedTraceparent {
|
|
13
|
+
traceId: string;
|
|
14
|
+
spanId: string;
|
|
15
|
+
sampled: boolean;
|
|
16
|
+
}
|
|
17
|
+
/** True for a trace id the W3C format allows: 32 lowercase hex digits that are not all zeros. */
|
|
18
|
+
export declare function isTraceId(value: unknown): value is string;
|
|
19
|
+
/** A new random trace id. */
|
|
20
|
+
export declare function newTraceId(): string;
|
|
21
|
+
/** A new random span id: one per attempt, so a retried request shows as separate spans of one trace. */
|
|
22
|
+
export declare function newSpanId(): string;
|
|
23
|
+
/** The `traceparent` header value. Throws for an id the format does not allow, because a server would silently ignore it. */
|
|
24
|
+
export declare function formatTraceparent(traceId: string, spanId: string, sampled?: boolean): string;
|
|
25
|
+
/** Reads a `traceparent` header value (version 00). Undefined for anything that is not exactly that format. */
|
|
26
|
+
export declare function parseTraceparent(header: string): ParsedTraceparent | undefined;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
const TRACE_ID = /^[0-9a-f]{32}$/;
|
|
3
|
+
const SPAN_ID = /^[0-9a-f]{16}$/;
|
|
4
|
+
const TRACEPARENT = /^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/;
|
|
5
|
+
const NO_TRACE = '0'.repeat(32);
|
|
6
|
+
const NO_SPAN = '0'.repeat(16);
|
|
7
|
+
/** True for a trace id the W3C format allows: 32 lowercase hex digits that are not all zeros. */
|
|
8
|
+
export function isTraceId(value) { return typeof value === 'string' && TRACE_ID.test(value) && value !== NO_TRACE; }
|
|
9
|
+
function isSpanId(value) { return typeof value === 'string' && SPAN_ID.test(value) && value !== NO_SPAN; }
|
|
10
|
+
/** A new random trace id. */
|
|
11
|
+
export function newTraceId() {
|
|
12
|
+
let id;
|
|
13
|
+
do {
|
|
14
|
+
id = randomBytes(16).toString('hex');
|
|
15
|
+
} while (id === NO_TRACE);
|
|
16
|
+
return id;
|
|
17
|
+
}
|
|
18
|
+
/** A new random span id: one per attempt, so a retried request shows as separate spans of one trace. */
|
|
19
|
+
export function newSpanId() {
|
|
20
|
+
let id;
|
|
21
|
+
do {
|
|
22
|
+
id = randomBytes(8).toString('hex');
|
|
23
|
+
} while (id === NO_SPAN);
|
|
24
|
+
return id;
|
|
25
|
+
}
|
|
26
|
+
/** The `traceparent` header value. Throws for an id the format does not allow, because a server would silently ignore it. */
|
|
27
|
+
export function formatTraceparent(traceId, spanId, sampled = true) {
|
|
28
|
+
if (!isTraceId(traceId))
|
|
29
|
+
throw new Error('A trace id is 32 lowercase hex digits and not all zeros');
|
|
30
|
+
if (!isSpanId(spanId))
|
|
31
|
+
throw new Error('A span id is 16 lowercase hex digits and not all zeros');
|
|
32
|
+
return `00-${traceId}-${spanId}-${sampled ? '01' : '00'}`;
|
|
33
|
+
}
|
|
34
|
+
/** Reads a `traceparent` header value (version 00). Undefined for anything that is not exactly that format. */
|
|
35
|
+
export function parseTraceparent(header) {
|
|
36
|
+
const match = TRACEPARENT.exec(header);
|
|
37
|
+
if (!match)
|
|
38
|
+
return undefined;
|
|
39
|
+
const [, traceId, spanId, flags] = match;
|
|
40
|
+
if (!isTraceId(traceId) || !isSpanId(spanId) || flags === undefined)
|
|
41
|
+
return undefined;
|
|
42
|
+
return { traceId, spanId, sampled: (Number.parseInt(flags, 16) & 1) === 1 };
|
|
43
|
+
}
|
package/dist/http/types.d.ts
CHANGED
|
@@ -26,6 +26,8 @@ export interface ApiRequest {
|
|
|
26
26
|
skipAuth?: boolean;
|
|
27
27
|
/** Send this request without the client's cookies, and do not keep the cookies it sets (negative session tests). */
|
|
28
28
|
skipCookies?: boolean;
|
|
29
|
+
/** Put this request in this trace (32 lowercase hex digits), overriding the client's `trace` setting, and send a `traceparent` header even when the client does not trace. A `traceparent` header you set yourself always wins. */
|
|
30
|
+
traceId?: string;
|
|
29
31
|
/** 'binary' returns the response body as a Uint8Array in `body` (downloads), with an empty `text`. Default: text, parsed as JSON when the content type says so. */
|
|
30
32
|
responseType?: 'auto' | 'binary';
|
|
31
33
|
}
|
|
@@ -40,6 +42,8 @@ export interface ApiResult<T = unknown> {
|
|
|
40
42
|
requestId: string;
|
|
41
43
|
/** Present and true when a 401 made the client renew its token and resend the request once. */
|
|
42
44
|
reauthenticated?: boolean;
|
|
45
|
+
/** The trace this request joined, when it was traced: search for it in the tracing backend to see what the server did. */
|
|
46
|
+
traceId?: string;
|
|
43
47
|
}
|
|
44
48
|
export interface RequestContext {
|
|
45
49
|
readonly method: Method;
|
|
@@ -63,6 +67,8 @@ export interface HttpEvent {
|
|
|
63
67
|
kind: 'success' | 'network-error' | 'retry';
|
|
64
68
|
error?: string;
|
|
65
69
|
reauthenticated?: boolean;
|
|
70
|
+
/** The trace the request joined, when it was traced. */
|
|
71
|
+
traceId?: string;
|
|
66
72
|
/** Only on 'retry' events: why another attempt follows. */
|
|
67
73
|
reason?: 'status' | 'network' | 'timeout' | 'reauthenticate';
|
|
68
74
|
/** Only on 'retry' events: how long the client waits before the next attempt, in ms. */
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
export { ApiClient, ApiTransportError, encodeForm } from './http/api-client.js';
|
|
2
|
+
export { formatTraceparent, isTraceId, newSpanId, newTraceId, parseTraceparent } from './http/trace.js';
|
|
3
|
+
export type { ParsedTraceparent, TraceConfig } from './http/trace.js';
|
|
2
4
|
export type { ApiClientConfig, ApiAuth } from './http/api-client.js';
|
|
3
5
|
export { parseRetryAfter } from './http/retry.js';
|
|
4
6
|
export type { RetryConfig, ClientClock } from './http/retry.js';
|
|
@@ -19,7 +21,7 @@ export { encodeMultipart } from './http/multipart.js';
|
|
|
19
21
|
export type { MultipartPart, EncodedMultipart } from './http/multipart.js';
|
|
20
22
|
export type { Validator } from './contracts/assertions.js';
|
|
21
23
|
export { requireEnv, envEnum } from './config/env.js';
|
|
22
|
-
export { redact } from './reporting/redaction.js';
|
|
24
|
+
export { redact, scrubText } from './reporting/redaction.js';
|
|
23
25
|
export { createRunId } from './testing/run-id.js';
|
|
24
26
|
export { validateSchema, assertSchema } from './contracts/schema.js';
|
|
25
27
|
export type { Schema, SchemaResult } from './contracts/schema.js';
|
|
@@ -27,11 +29,15 @@ export { loadProjectConfig } from './config/project-config.js';
|
|
|
27
29
|
export type { ProjectConfig } from './config/project-config.js';
|
|
28
30
|
export { TestDataFactory, TestCleanup } from './testing/data-factory.js';
|
|
29
31
|
export { Semaphore } from './testing/concurrency.js';
|
|
32
|
+
export { MAX_LOAD_CONCURRENCY, MAX_LOAD_REQUESTS, MAX_LOAD_WARMUP, expectLoad, runLoad, summarizeLoad } from './testing/load.js';
|
|
33
|
+
export type { LatencyStats, LoadLimits, LoadOptions, LoadReport } from './testing/load.js';
|
|
30
34
|
export { selectByTags } from './testing/tag-selection.js';
|
|
31
35
|
export { MetricsCollector } from './reporting/metrics.js';
|
|
32
36
|
export type { ApiMetrics } from './reporting/metrics.js';
|
|
33
37
|
export { writeJunit } from './reporting/junit.js';
|
|
34
|
-
export type { TestCaseResult } from './reporting/junit.js';
|
|
38
|
+
export type { JunitOptions, TestCaseResult } from './reporting/junit.js';
|
|
39
|
+
export { renderHtmlReport, writeHtmlReport } from './reporting/html-report.js';
|
|
40
|
+
export type { HtmlReportOptions } from './reporting/html-report.js';
|
|
35
41
|
export { OpenApiValidator } from './contracts/openapi.js';
|
|
36
42
|
export type { OpenApiDocument, JsonSchemaCompiler, ContractCheck, RequestCheck, OpenApiValidatorOptions } from './contracts/openapi.js';
|
|
37
43
|
export { createAjvCompiler, createOpenApiValidator } from './contracts/ajv.js';
|
|
@@ -44,7 +50,8 @@ export type { DocumentOperation, ExpectedGraphQLError, GraphQLAssertOptions, Gra
|
|
|
44
50
|
export type { SecurityPolicy } from './security/policy.js';
|
|
45
51
|
export { attachSafeMetadata } from './reporting/allure-adapter.js';
|
|
46
52
|
export type { AllureWriter } from './reporting/allure-adapter.js';
|
|
47
|
-
export { MochaResultCollector } from './integrations/mocha.js';
|
|
53
|
+
export { MochaResultCollector, failedHooks, failureText } from './integrations/mocha.js';
|
|
54
|
+
export type { MochaTestLike } from './integrations/mocha.js';
|
|
48
55
|
export { CoverageRegistry } from './testing/coverage.js';
|
|
49
56
|
export type { CoverageRecord } from './testing/coverage.js';
|
|
50
57
|
export { OpenApiCases, assertCaseOutcome } from './testing/spec-cases.js';
|
|
@@ -54,6 +61,6 @@ export { findSensitiveData, expectNoSensitiveData } from './security/sensitive-d
|
|
|
54
61
|
export type { SensitiveFinding, SensitiveDataOptions } from './security/sensitive-data.js';
|
|
55
62
|
export { checkSecurityHeaders, expectSecurityHeaders } from './security/headers.js';
|
|
56
63
|
export type { HeaderFinding, SecurityHeaderOptions, Severity } from './security/headers.js';
|
|
57
|
-
export type { GeneratedCase, CaseKind, OperationInfo, OperationRef, OpenApiCasesOptions } from './testing/spec-cases.js';
|
|
64
|
+
export type { GeneratedCase, CaseKind, InjectedProperty, OperationInfo, OperationRef, OpenApiCasesOptions } from './testing/spec-cases.js';
|
|
58
65
|
export { OpenApiCoverage } from './testing/openapi-coverage.js';
|
|
59
66
|
export type { OpenApiCoverageOptions, OpenApiCoverageReport, OpenApiCoverageSnapshot, OperationCoverage, CoverageStat, CoverageThresholds } from './testing/openapi-coverage.js';
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
export { ApiClient, ApiTransportError, encodeForm } from './http/api-client.js';
|
|
2
|
+
export { formatTraceparent, isTraceId, newSpanId, newTraceId, parseTraceparent } from './http/trace.js';
|
|
2
3
|
export { parseRetryAfter } from './http/retry.js';
|
|
3
4
|
export { TokenManager } from './auth/token-manager.js';
|
|
4
5
|
export { clientCredentialsProvider, refreshTokenProvider, OAuth2Error } from './auth/oauth2.js';
|
|
@@ -9,22 +10,24 @@ export { waitFor, WaitTimeoutError } from './testing/wait-for.js';
|
|
|
9
10
|
export { CookieJar } from './http/cookies.js';
|
|
10
11
|
export { encodeMultipart } from './http/multipart.js';
|
|
11
12
|
export { requireEnv, envEnum } from './config/env.js';
|
|
12
|
-
export { redact } from './reporting/redaction.js';
|
|
13
|
+
export { redact, scrubText } from './reporting/redaction.js';
|
|
13
14
|
export { createRunId } from './testing/run-id.js';
|
|
14
15
|
export { validateSchema, assertSchema } from './contracts/schema.js';
|
|
15
16
|
export { loadProjectConfig } from './config/project-config.js';
|
|
16
17
|
export { TestDataFactory, TestCleanup } from './testing/data-factory.js';
|
|
17
18
|
export { Semaphore } from './testing/concurrency.js';
|
|
19
|
+
export { MAX_LOAD_CONCURRENCY, MAX_LOAD_REQUESTS, MAX_LOAD_WARMUP, expectLoad, runLoad, summarizeLoad } from './testing/load.js';
|
|
18
20
|
export { selectByTags } from './testing/tag-selection.js';
|
|
19
21
|
export { MetricsCollector } from './reporting/metrics.js';
|
|
20
22
|
export { writeJunit } from './reporting/junit.js';
|
|
23
|
+
export { renderHtmlReport, writeHtmlReport } from './reporting/html-report.js';
|
|
21
24
|
export { OpenApiValidator } from './contracts/openapi.js';
|
|
22
25
|
export { createAjvCompiler, createOpenApiValidator } from './contracts/ajv.js';
|
|
23
26
|
export { ExecutionContext } from './testing/execution-context.js';
|
|
24
27
|
export { assertRequestPolicy, rejectUnsafeEnvironment } from './security/policy.js';
|
|
25
28
|
export { GraphQLClient, expectGraphQLError, expectGraphQLSuccess, operationKind, parseOperations } from './graphql/graphql.js';
|
|
26
29
|
export { attachSafeMetadata } from './reporting/allure-adapter.js';
|
|
27
|
-
export { MochaResultCollector } from './integrations/mocha.js';
|
|
30
|
+
export { MochaResultCollector, failedHooks, failureText } from './integrations/mocha.js';
|
|
28
31
|
export { CoverageRegistry } from './testing/coverage.js';
|
|
29
32
|
export { OpenApiCases, assertCaseOutcome } from './testing/spec-cases.js';
|
|
30
33
|
export { AuthorizationMatrix } from './security/authorization-matrix.js';
|
|
@@ -1,9 +1,41 @@
|
|
|
1
1
|
import type { TestCaseResult } from '../reporting/junit.js';
|
|
2
|
+
/** What the collector reads from a Mocha test: `Mocha.Test` fits, and so does a plain object in a test of your own. */
|
|
3
|
+
export interface MochaTestLike {
|
|
4
|
+
fullTitle(): string;
|
|
5
|
+
parent?: {
|
|
6
|
+
fullTitle(): string;
|
|
7
|
+
} | undefined;
|
|
8
|
+
/** 'passed', 'failed' or 'pending' once the test has its final outcome; undefined for an attempt that will be retried. */
|
|
9
|
+
state?: string | undefined;
|
|
10
|
+
duration?: number | undefined;
|
|
11
|
+
err?: unknown;
|
|
12
|
+
isPending?: (() => boolean) | undefined;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* 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
|
|
16
|
+
* 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
|
|
17
|
+
* `this.test?.parent`. It reads Mocha's `getHooks`, which the Mocha type definitions do not declare, so it takes any suite.
|
|
18
|
+
*/
|
|
19
|
+
export declare function failedHooks(root: {
|
|
20
|
+
fullTitle(): string;
|
|
21
|
+
}): string[];
|
|
22
|
+
/** A failure as one short, printable text: control characters and colors removed, credentials masked, long output cut. */
|
|
23
|
+
export declare function failureText(error: unknown): string | undefined;
|
|
2
24
|
/** No dependency on Mocha itself; register this callback from mocha root hooks. */
|
|
3
25
|
export declare class MochaResultCollector {
|
|
4
26
|
private readonly rows;
|
|
5
27
|
private readonly starts;
|
|
6
28
|
start(fullTitle: string): void;
|
|
7
29
|
finish(fullTitle: string, suite: string, status: TestCaseResult['status']): void;
|
|
30
|
+
/**
|
|
31
|
+
* Records a test from a root `afterEach` hook, once, when it has its final outcome: Mocha runs `afterEach` after every attempt, and an
|
|
32
|
+
* 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
|
|
33
|
+
* 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
|
|
34
|
+
* (see `failureText`); the reports leave it out unless asked. Tests marked `it.skip` never reach this hook.
|
|
35
|
+
*/
|
|
36
|
+
record(test: MochaTestLike, details?: {
|
|
37
|
+
traceId?: string | undefined;
|
|
38
|
+
retries?: number | undefined;
|
|
39
|
+
}): boolean;
|
|
8
40
|
results(): readonly TestCaseResult[];
|
|
9
41
|
}
|