@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
|
@@ -194,6 +194,131 @@
|
|
|
194
194
|
}
|
|
195
195
|
}
|
|
196
196
|
}
|
|
197
|
+
},
|
|
198
|
+
"/oauth/token": {
|
|
199
|
+
"post": {
|
|
200
|
+
"operationId": "issueToken",
|
|
201
|
+
"tags": [
|
|
202
|
+
"security"
|
|
203
|
+
],
|
|
204
|
+
"requestBody": {
|
|
205
|
+
"required": true,
|
|
206
|
+
"content": {
|
|
207
|
+
"application/x-www-form-urlencoded": {
|
|
208
|
+
"schema": {
|
|
209
|
+
"$ref": "#/components/schemas/TokenRequest"
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
},
|
|
214
|
+
"responses": {
|
|
215
|
+
"200": {
|
|
216
|
+
"description": "A new access token",
|
|
217
|
+
"content": {
|
|
218
|
+
"application/json": {
|
|
219
|
+
"schema": {
|
|
220
|
+
"$ref": "#/components/schemas/TokenResponse"
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
},
|
|
225
|
+
"400": {
|
|
226
|
+
"description": "The request was invalid",
|
|
227
|
+
"content": {
|
|
228
|
+
"application/json": {
|
|
229
|
+
"schema": {
|
|
230
|
+
"$ref": "#/components/schemas/Error"
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
},
|
|
235
|
+
"415": {
|
|
236
|
+
"description": "The content type is not supported",
|
|
237
|
+
"content": {
|
|
238
|
+
"application/json": {
|
|
239
|
+
"schema": {
|
|
240
|
+
"$ref": "#/components/schemas/Error"
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
},
|
|
248
|
+
"/accounts/{id}/documents": {
|
|
249
|
+
"post": {
|
|
250
|
+
"operationId": "uploadDocument",
|
|
251
|
+
"tags": [
|
|
252
|
+
"accounts"
|
|
253
|
+
],
|
|
254
|
+
"parameters": [
|
|
255
|
+
{
|
|
256
|
+
"name": "id",
|
|
257
|
+
"in": "path",
|
|
258
|
+
"required": true,
|
|
259
|
+
"schema": {
|
|
260
|
+
"type": "string"
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
],
|
|
264
|
+
"requestBody": {
|
|
265
|
+
"required": true,
|
|
266
|
+
"content": {
|
|
267
|
+
"multipart/form-data": {
|
|
268
|
+
"schema": {
|
|
269
|
+
"$ref": "#/components/schemas/DocumentUpload"
|
|
270
|
+
},
|
|
271
|
+
"encoding": {
|
|
272
|
+
"file": {
|
|
273
|
+
"contentType": "application/pdf, image/png"
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
},
|
|
279
|
+
"responses": {
|
|
280
|
+
"201": {
|
|
281
|
+
"description": "The document was stored",
|
|
282
|
+
"content": {
|
|
283
|
+
"application/json": {
|
|
284
|
+
"schema": {
|
|
285
|
+
"$ref": "#/components/schemas/Document"
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
},
|
|
290
|
+
"400": {
|
|
291
|
+
"description": "The request was invalid",
|
|
292
|
+
"content": {
|
|
293
|
+
"application/json": {
|
|
294
|
+
"schema": {
|
|
295
|
+
"$ref": "#/components/schemas/Error"
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
},
|
|
300
|
+
"404": {
|
|
301
|
+
"description": "No such account",
|
|
302
|
+
"content": {
|
|
303
|
+
"application/json": {
|
|
304
|
+
"schema": {
|
|
305
|
+
"$ref": "#/components/schemas/Error"
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
},
|
|
310
|
+
"415": {
|
|
311
|
+
"description": "The content type is not supported",
|
|
312
|
+
"content": {
|
|
313
|
+
"application/json": {
|
|
314
|
+
"schema": {
|
|
315
|
+
"$ref": "#/components/schemas/Error"
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
}
|
|
197
322
|
}
|
|
198
323
|
},
|
|
199
324
|
"components": {
|
|
@@ -236,6 +361,16 @@
|
|
|
236
361
|
"initialDeposit": {
|
|
237
362
|
"type": "number",
|
|
238
363
|
"minimum": 0
|
|
364
|
+
},
|
|
365
|
+
"webhookUrl": {
|
|
366
|
+
"type": "string",
|
|
367
|
+
"format": "uri",
|
|
368
|
+
"description": "Where the API reports changes to this account. Must be a public http or https address."
|
|
369
|
+
},
|
|
370
|
+
"accountNumber": {
|
|
371
|
+
"type": "string",
|
|
372
|
+
"readOnly": true,
|
|
373
|
+
"description": "Assigned by the server. Sending it has no effect."
|
|
239
374
|
}
|
|
240
375
|
}
|
|
241
376
|
},
|
|
@@ -295,6 +430,104 @@
|
|
|
295
430
|
"minimum": 0
|
|
296
431
|
}
|
|
297
432
|
}
|
|
433
|
+
},
|
|
434
|
+
"TokenRequest": {
|
|
435
|
+
"type": "object",
|
|
436
|
+
"required": [
|
|
437
|
+
"grant_type",
|
|
438
|
+
"client_id",
|
|
439
|
+
"client_secret"
|
|
440
|
+
],
|
|
441
|
+
"additionalProperties": false,
|
|
442
|
+
"properties": {
|
|
443
|
+
"grant_type": {
|
|
444
|
+
"type": "string",
|
|
445
|
+
"enum": [
|
|
446
|
+
"client_credentials"
|
|
447
|
+
]
|
|
448
|
+
},
|
|
449
|
+
"client_id": {
|
|
450
|
+
"type": "string",
|
|
451
|
+
"minLength": 1,
|
|
452
|
+
"maxLength": 100
|
|
453
|
+
},
|
|
454
|
+
"client_secret": {
|
|
455
|
+
"type": "string",
|
|
456
|
+
"minLength": 1,
|
|
457
|
+
"maxLength": 200
|
|
458
|
+
},
|
|
459
|
+
"scope": {
|
|
460
|
+
"type": "string",
|
|
461
|
+
"maxLength": 200
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
},
|
|
465
|
+
"TokenResponse": {
|
|
466
|
+
"type": "object",
|
|
467
|
+
"required": [
|
|
468
|
+
"access_token",
|
|
469
|
+
"token_type"
|
|
470
|
+
],
|
|
471
|
+
"properties": {
|
|
472
|
+
"access_token": {
|
|
473
|
+
"type": "string"
|
|
474
|
+
},
|
|
475
|
+
"token_type": {
|
|
476
|
+
"type": "string",
|
|
477
|
+
"enum": [
|
|
478
|
+
"Bearer"
|
|
479
|
+
]
|
|
480
|
+
},
|
|
481
|
+
"expires_in": {
|
|
482
|
+
"type": "integer"
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
},
|
|
486
|
+
"DocumentUpload": {
|
|
487
|
+
"type": "object",
|
|
488
|
+
"required": [
|
|
489
|
+
"file",
|
|
490
|
+
"kind"
|
|
491
|
+
],
|
|
492
|
+
"additionalProperties": false,
|
|
493
|
+
"properties": {
|
|
494
|
+
"file": {
|
|
495
|
+
"type": "string",
|
|
496
|
+
"format": "binary"
|
|
497
|
+
},
|
|
498
|
+
"kind": {
|
|
499
|
+
"type": "string",
|
|
500
|
+
"enum": [
|
|
501
|
+
"statement",
|
|
502
|
+
"identity",
|
|
503
|
+
"other"
|
|
504
|
+
]
|
|
505
|
+
},
|
|
506
|
+
"note": {
|
|
507
|
+
"type": "string",
|
|
508
|
+
"maxLength": 100
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
},
|
|
512
|
+
"Document": {
|
|
513
|
+
"type": "object",
|
|
514
|
+
"required": [
|
|
515
|
+
"id",
|
|
516
|
+
"kind",
|
|
517
|
+
"size"
|
|
518
|
+
],
|
|
519
|
+
"properties": {
|
|
520
|
+
"id": {
|
|
521
|
+
"type": "string"
|
|
522
|
+
},
|
|
523
|
+
"kind": {
|
|
524
|
+
"type": "string"
|
|
525
|
+
},
|
|
526
|
+
"size": {
|
|
527
|
+
"type": "integer",
|
|
528
|
+
"minimum": 0
|
|
529
|
+
}
|
|
530
|
+
}
|
|
298
531
|
}
|
|
299
532
|
},
|
|
300
533
|
"securitySchemes": {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { ApiClient, TokenManager, assertRequestPolicy, clientCredentialsProvider } from '@nikhil-qeas/api-core';
|
|
2
2
|
import type { ApiClientConfig, ApiRequest, ApiResult, SecurityPolicy } from '@nikhil-qeas/api-core';
|
|
3
|
-
import { oauthSettings, requestPolicy, targetBaseUrl } from '../environment.js';
|
|
4
|
-
import { recordEvent } from '../observability.js';
|
|
3
|
+
import { oauthSettings, requestPolicy, targetBaseUrl, traceEnabled } from '../environment.js';
|
|
4
|
+
import { currentTrace, recordEvent } from '../observability.js';
|
|
5
5
|
|
|
6
6
|
let sharedTokens: TokenManager | undefined;
|
|
7
7
|
/** One token cache per process, so every client and test shares the same access token. */
|
|
@@ -37,6 +37,7 @@ class PolicyEnforcingClient extends ApiClient {
|
|
|
37
37
|
* - Read-only unless QE_ALLOW_MUTATIONS=true and QE_APPROVAL=approved (never in production): see requestPolicy().
|
|
38
38
|
* - Retries safe requests with backoff and honors Retry-After; mutations are never retried after an ambiguous failure.
|
|
39
39
|
* - Authenticates with OAuth2 client credentials when OAUTH_* is configured, and renews the token once on a 401.
|
|
40
|
+
* - Sends a W3C traceparent when QE_TRACE=true, one trace per test, so a failed test can be found in the API's tracing backend.
|
|
40
41
|
* - Feeds every request to the metrics and OpenAPI coverage collectors.
|
|
41
42
|
*/
|
|
42
43
|
export function createApiClient(baseUrl: string = targetBaseUrl(), overrides: Partial<ApiClientConfig> = {}): ApiClient {
|
|
@@ -48,6 +49,7 @@ export function createApiClient(baseUrl: string = targetBaseUrl(), overrides: Pa
|
|
|
48
49
|
maxSafeRetries: 1,
|
|
49
50
|
onEvent: recordEvent,
|
|
50
51
|
...(tokens ? { auth: { tokens } } : {}),
|
|
52
|
+
...(traceEnabled() ? { trace: { traceId: currentTrace } } : {}),
|
|
51
53
|
...overrides
|
|
52
54
|
}, policy);
|
|
53
55
|
}
|
|
@@ -29,6 +29,14 @@ export function oauthSettings(env: NodeJS.ProcessEnv = process.env): OAuthSettin
|
|
|
29
29
|
};
|
|
30
30
|
}
|
|
31
31
|
|
|
32
|
+
/**
|
|
33
|
+
* Whether every request carries a W3C `traceparent` header (QE_TRACE=true), one trace per test, so a failed test can be found in the
|
|
34
|
+
* API's tracing backend. Off by default, because it adds a header to every request.
|
|
35
|
+
*/
|
|
36
|
+
export function traceEnabled(env: NodeJS.ProcessEnv = process.env): boolean {
|
|
37
|
+
return env.QE_TRACE === 'true';
|
|
38
|
+
}
|
|
39
|
+
|
|
32
40
|
/**
|
|
33
41
|
* What the run may send (QE_ENV, QE_ALLOW_MUTATIONS, QE_APPROVAL).
|
|
34
42
|
* Runs are read-only: POST, PUT, PATCH and DELETE are refused unless QE_ALLOW_MUTATIONS=true and QE_APPROVAL=approved,
|
|
@@ -1,13 +1,27 @@
|
|
|
1
|
-
import { MetricsCollector, OpenApiCoverage } from '@nikhil-qeas/api-core';
|
|
1
|
+
import { MetricsCollector, MochaResultCollector, OpenApiCoverage, newTraceId } from '@nikhil-qeas/api-core';
|
|
2
2
|
import type { HttpEvent } from '@nikhil-qeas/api-core';
|
|
3
3
|
import { loadSpec } from './openapi.js';
|
|
4
4
|
|
|
5
5
|
/** Request timings, errors and retry counts for the whole run. */
|
|
6
6
|
export const metrics = new MetricsCollector();
|
|
7
7
|
|
|
8
|
+
/** The final outcome of every test, recorded by the root hooks for the HTML report. */
|
|
9
|
+
export const results = new MochaResultCollector();
|
|
10
|
+
|
|
8
11
|
/** Which operations and documented responses of the OpenAPI spec the run exercised. Exclude what you do not test, e.g. ['GET /health']. */
|
|
9
12
|
export const coverage = new OpenApiCoverage(loadSpec(), { exclude: [] });
|
|
10
13
|
|
|
14
|
+
let currentTraceId: string | undefined;
|
|
15
|
+
/** Starts a new trace. The root hook calls it before every test, so all requests of one test join one trace (see QE_TRACE). */
|
|
16
|
+
export function startTrace(): string {
|
|
17
|
+
currentTraceId = newTraceId();
|
|
18
|
+
return currentTraceId;
|
|
19
|
+
}
|
|
20
|
+
/** The trace id of the running test, or undefined before the first test. */
|
|
21
|
+
export function currentTrace(): string | undefined {
|
|
22
|
+
return currentTraceId;
|
|
23
|
+
}
|
|
24
|
+
|
|
11
25
|
/** Event sink for ApiClient: every request and retry is recorded for the end-of-run report. */
|
|
12
26
|
export function recordEvent(event: HttpEvent): void {
|
|
13
27
|
metrics.record(event);
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { expectLoad, runLoad, summarizeLoad } from '@nikhil-qeas/api-core';
|
|
2
|
+
import { createApiClient } from '../../src/clients/api.js';
|
|
3
|
+
import { startMockApi } from '../support/mock-api.js';
|
|
4
|
+
import type { MockApi } from '../support/mock-api.js';
|
|
5
|
+
|
|
6
|
+
// A performance smoke test: a few dozen requests, a few at a time, with limits on latency and on failures. It catches an endpoint that
|
|
7
|
+
// became slow or started failing under a little concurrency. It is not a load test (it is capped at 1000 requests and 50 at a time):
|
|
8
|
+
// use k6 or Gatling for that. The limits below are generous so the sample passes anywhere; set yours from what the API promises.
|
|
9
|
+
// The first requests (warm-up) are sent before the measured ones and left out of the figures. The run stops early after repeated
|
|
10
|
+
// failures, and because it goes through createApiClient() a read-only run cannot turn it into a write load.
|
|
11
|
+
describe('@performance health check', () => {
|
|
12
|
+
let mock: MockApi;
|
|
13
|
+
before(async () => { mock = await startMockApi(); });
|
|
14
|
+
after(async () => { await mock.close(); });
|
|
15
|
+
|
|
16
|
+
it('answers 50 requests, 5 at a time, without failures and within the latency budget', async () => {
|
|
17
|
+
const api = createApiClient(mock.baseUrl);
|
|
18
|
+
const report = await runLoad(() => api.request({ method: 'GET', path: '/health' }), { requests: 50, concurrency: 5 });
|
|
19
|
+
console.log(` ${summarizeLoad(report)}`);
|
|
20
|
+
expectLoad(report, { p95Ms: 1000, maxMs: 5000 }); // no failures are allowed unless you pass maxErrorRate
|
|
21
|
+
});
|
|
22
|
+
});
|
|
@@ -11,7 +11,9 @@ describe('@security authentication', () => {
|
|
|
11
11
|
after(async () => { await mock.close(); });
|
|
12
12
|
|
|
13
13
|
const authenticatedClient = (): ApiClient => createApiClient(mock.baseUrl, {
|
|
14
|
-
|
|
14
|
+
// The mock's token endpoint (TokenRequest in openapi/openapi.json) takes the client credentials in the form body. The default is an
|
|
15
|
+
// HTTP Basic header: use whichever your API's token endpoint expects.
|
|
16
|
+
auth: { tokens: new TokenManager(clientCredentialsProvider({ tokenUrl: mock.tokenUrl, clientId: 'qa-client', clientSecret: 'qa-secret', clientAuth: 'body' })) }
|
|
15
17
|
});
|
|
16
18
|
|
|
17
19
|
it('sends the access token, and renews it once when the server rejects it', async () => {
|
|
@@ -3,9 +3,16 @@ import { createApiClient } from '../../src/clients/api.js';
|
|
|
3
3
|
import { loadSpec } from '../../src/openapi.js';
|
|
4
4
|
import { useMockWithApprovedWrites } from '../support/approved-writes.js';
|
|
5
5
|
|
|
6
|
-
//
|
|
7
|
-
// must refuse a request with none, with an invalid token or API key, and
|
|
8
|
-
// A server that only checks that an Authorization header
|
|
6
|
+
// Security cases generated from openapi/openapi.json, so they follow the spec when you replace it:
|
|
7
|
+
// authentication every operation that requires credentials must refuse a request with none, with an invalid token or API key, and
|
|
8
|
+
// with credentials of the wrong type, using 401 or 403. A server that only checks that an Authorization header
|
|
9
|
+
// exists fails. Public operations (`security: []`) are skipped.
|
|
10
|
+
// mass assignment a client must not be able to set what the server owns: read-only properties the spec declares, and (unless the
|
|
11
|
+
// spec forbids extra properties) privileged names such as isAdmin and role. The API must reject the request or
|
|
12
|
+
// ignore the properties; it fails when a response returns a value that was sent.
|
|
13
|
+
// SSRF fields that hold an address (a URI format, or a name such as url, callback, webhook or redirect) must refuse the
|
|
14
|
+
// cloud metadata address, loopback and private addresses and local files with a 4xx. Skip this suite if your API
|
|
15
|
+
// deliberately checks addresses only when it fetches them.
|
|
9
16
|
const cases = new OpenApiCases(loadSpec());
|
|
10
17
|
|
|
11
18
|
describe('@security protected operations refuse missing and wrong credentials', () => {
|
|
@@ -22,3 +29,33 @@ describe('@security protected operations refuse missing and wrong credentials',
|
|
|
22
29
|
});
|
|
23
30
|
}
|
|
24
31
|
});
|
|
32
|
+
|
|
33
|
+
describe('@security the API does not apply properties a client must not set', () => {
|
|
34
|
+
const mock = useMockWithApprovedWrites();
|
|
35
|
+
for (const operation of cases.operations()) {
|
|
36
|
+
const injected = cases.massAssignment(operation);
|
|
37
|
+
if (!injected.length) continue;
|
|
38
|
+
describe(`${operation.method} ${operation.path}`, () => {
|
|
39
|
+
for (const testCase of injected) {
|
|
40
|
+
it(testCase.description, async () => {
|
|
41
|
+
assertCaseOutcome(await createApiClient(mock().baseUrl).request(testCase.request), testCase);
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
describe('@security the API refuses addresses it must not contact', () => {
|
|
49
|
+
const mock = useMockWithApprovedWrites();
|
|
50
|
+
for (const operation of cases.operations()) {
|
|
51
|
+
const addresses = cases.ssrf(operation);
|
|
52
|
+
if (!addresses.length) continue;
|
|
53
|
+
describe(`${operation.method} ${operation.path}`, () => {
|
|
54
|
+
for (const testCase of addresses) {
|
|
55
|
+
it(testCase.description, async () => {
|
|
56
|
+
assertCaseOutcome(await createApiClient(mock().baseUrl).request(testCase.request), testCase);
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
});
|
|
@@ -1,15 +1,42 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { failedHooks, writeHtmlReport } from '@nikhil-qeas/api-core';
|
|
2
|
+
import { traceEnabled } from '../../src/environment.js';
|
|
3
|
+
import { coverage, currentTrace, metrics, results, startTrace } from '../../src/observability.js';
|
|
2
4
|
|
|
3
|
-
/**
|
|
5
|
+
/**
|
|
6
|
+
* Mocha root hooks. Before every test: a new trace (used when QE_TRACE=true). After every test: its final outcome is recorded for the
|
|
7
|
+
* HTML report (a test that is retried is recorded once, when the retries are over). After the whole run: the coverage report with an
|
|
8
|
+
* optional minimum, and reports/html/index.html.
|
|
9
|
+
*/
|
|
4
10
|
export const mochaHooks = {
|
|
5
|
-
|
|
11
|
+
beforeEach(): void {
|
|
12
|
+
startTrace(); // every request this test sends joins one trace
|
|
13
|
+
},
|
|
14
|
+
afterEach(this: Mocha.Context): void {
|
|
15
|
+
const test = this.currentTest;
|
|
16
|
+
if (!test) return;
|
|
17
|
+
// The id to search for in the API's tracing backend to see what the server did during a failed test.
|
|
18
|
+
if (traceEnabled() && test.state === 'failed') console.log(` trace id of the failed test: ${currentTrace() ?? 'none'}`);
|
|
19
|
+
results.record(test, traceEnabled() ? { traceId: currentTrace() } : {});
|
|
20
|
+
},
|
|
21
|
+
async afterAll(this: Mocha.Context): Promise<void> {
|
|
6
22
|
await coverage.write('reports/coverage/api.md', 'markdown');
|
|
7
23
|
await coverage.write('reports/coverage/api.json');
|
|
8
24
|
const { operations, responses } = coverage.report();
|
|
9
|
-
const { total, retries } = metrics.summary();
|
|
25
|
+
const { total, retries, p95Ms } = metrics.summary();
|
|
26
|
+
// A failed before or after hook is not a test, so no test record shows it: say so, or the report would look green on a red run.
|
|
27
|
+
const root = this.test?.parent;
|
|
28
|
+
const brokenHooks = root ? failedHooks(root) : [];
|
|
29
|
+
await writeHtmlReport('reports/html/index.html', results.results(), {
|
|
30
|
+
facts: [
|
|
31
|
+
['API coverage', `${operations.covered} of ${operations.total} operations (${operations.percent}%), ${responses.covered} of ${responses.total} documented responses`],
|
|
32
|
+
['Requests', `${total} sent, ${retries} retried, 95th percentile ${p95Ms} ms`]
|
|
33
|
+
],
|
|
34
|
+
problems: brokenHooks.length ? [`${brokenHooks.length} hook${brokenHooks.length === 1 ? '' : 's'} failed, so the tests they guard did not run and are not listed here: ${brokenHooks.slice(0, 5).join('; ')}`] : [],
|
|
35
|
+
messages: true // the messages are scrubbed and shortened, and the console and JUnit report already show them
|
|
36
|
+
});
|
|
10
37
|
console.log(
|
|
11
38
|
`\nAPI coverage: ${operations.covered}/${operations.total} operations (${operations.percent}%), ` +
|
|
12
|
-
`${responses.covered}/${responses.total} documented responses. Requests: ${total}, retries: ${retries}.
|
|
39
|
+
`${responses.covered}/${responses.total} documented responses. Requests: ${total}, retries: ${retries}. Reports: reports/coverage/api.md, reports/html/index.html`
|
|
13
40
|
);
|
|
14
41
|
const minimum = process.env.QE_COVERAGE_MIN_OPERATIONS;
|
|
15
42
|
if (minimum) coverage.assertCoverage({ minOperations: Number(minimum), failOnUndocumented: true });
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import { expectStatus, parseTraceparent } from '@nikhil-qeas/api-core';
|
|
3
|
+
import { createApiClient } from '../../src/clients/api.js';
|
|
4
|
+
import { currentTrace } from '../../src/observability.js';
|
|
5
|
+
import { startMockApi } from '../support/mock-api.js';
|
|
6
|
+
import type { MockApi } from '../support/mock-api.js';
|
|
7
|
+
|
|
8
|
+
// With QE_TRACE=true every request carries a W3C `traceparent` header and all requests of one test share one trace id, so a failed
|
|
9
|
+
// test can be found in the API's tracing backend: its trace id is printed right after it. The suite switches tracing on for itself.
|
|
10
|
+
describe('@smoke tracing', () => {
|
|
11
|
+
let mock: MockApi;
|
|
12
|
+
let saved: string | undefined;
|
|
13
|
+
let traceOfFirstTest: string | undefined;
|
|
14
|
+
before(async () => {
|
|
15
|
+
mock = await startMockApi();
|
|
16
|
+
saved = process.env.QE_TRACE;
|
|
17
|
+
process.env.QE_TRACE = 'true';
|
|
18
|
+
});
|
|
19
|
+
after(async () => {
|
|
20
|
+
if (saved === undefined) delete process.env.QE_TRACE;
|
|
21
|
+
else process.env.QE_TRACE = saved;
|
|
22
|
+
await mock.close();
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
const lastTrace = (): string | undefined => {
|
|
26
|
+
const sent = mock.traceparents();
|
|
27
|
+
const header = sent[sent.length - 1];
|
|
28
|
+
return header === undefined ? undefined : parseTraceparent(header)?.traceId;
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
it('sends one trace id with every request of a test, and a new span for each request', async () => {
|
|
32
|
+
const api = createApiClient(mock.baseUrl);
|
|
33
|
+
expectStatus(await api.request({ method: 'GET', path: '/health' }), 200);
|
|
34
|
+
expectStatus(await api.request({ method: 'GET', path: '/health' }), 200);
|
|
35
|
+
const sent = mock.traceparents().map(header => parseTraceparent(header));
|
|
36
|
+
assert.equal(sent.length, 2, 'both requests carried a valid traceparent');
|
|
37
|
+
assert.equal(sent[0]?.traceId, currentTrace());
|
|
38
|
+
assert.equal(sent[1]?.traceId, currentTrace());
|
|
39
|
+
assert.notEqual(sent[0]?.spanId, sent[1]?.spanId);
|
|
40
|
+
traceOfFirstTest = currentTrace();
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
it('puts the next test in a trace of its own', async () => {
|
|
44
|
+
expectStatus(await createApiClient(mock.baseUrl).request({ method: 'GET', path: '/health' }), 200);
|
|
45
|
+
assert.equal(lastTrace(), currentTrace());
|
|
46
|
+
assert.notEqual(lastTrace(), traceOfFirstTest);
|
|
47
|
+
});
|
|
48
|
+
});
|