@nikhil-qeas/api-core 0.4.2 → 0.5.1
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 +63 -0
- package/README.md +135 -14
- package/bin/qe-api.js +99 -26
- package/dist/auth/oauth2.d.ts +40 -0
- package/dist/auth/oauth2.js +138 -0
- package/dist/auth/token-manager.d.ts +13 -2
- package/dist/auth/token-manager.js +13 -1
- package/dist/contracts/ajv.d.ts +15 -0
- package/dist/contracts/ajv.js +37 -0
- package/dist/contracts/openapi.d.ts +19 -5
- package/dist/contracts/openapi.js +109 -26
- package/dist/http/api-client.d.ts +20 -2
- package/dist/http/api-client.js +68 -11
- package/dist/http/retry.d.ts +42 -0
- package/dist/http/retry.js +53 -0
- package/dist/http/types.d.ts +11 -1
- package/dist/index.d.ts +11 -3
- package/dist/index.js +4 -0
- package/dist/reporting/allure-adapter.d.ts +3 -3
- package/dist/reporting/metrics.d.ts +3 -0
- package/dist/reporting/metrics.js +6 -4
- package/dist/reporting/redaction.js +50 -2
- package/dist/testing/openapi-coverage.d.ts +116 -0
- package/dist/testing/openapi-coverage.js +296 -0
- package/package.json +28 -5
- package/templates/project/README.md +53 -0
- package/templates/project/__dot__env.example +14 -0
- package/templates/project/__dot__gitignore +7 -0
- package/templates/project/__dot__gitlab-ci.yml +25 -0
- package/templates/project/config/mocha.config.json +8 -0
- package/templates/project/eslint.config.mjs +27 -0
- package/templates/project/openapi/openapi.json +83 -0
- package/templates/project/src/clients/api.ts +32 -0
- package/templates/project/src/config/environment.ts +29 -0
- package/templates/project/src/contracts/openapi.ts +15 -0
- package/templates/project/src/observability.ts +15 -0
- package/templates/project/tests/contract/openapi.contract.spec.ts +33 -0
- package/templates/project/tests/security/authentication.spec.ts +36 -0
- package/templates/project/tests/setup/hooks.ts +17 -0
- package/templates/project/tests/smoke/health.spec.ts +17 -0
- package/templates/project/tests/support/mock-api.ts +66 -0
- package/templates/project/tsconfig.json +14 -0
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
# __PROJECT_NAME__
|
|
2
|
+
|
|
3
|
+
API automation project generated with `@nikhil-qeas/api-core`: TypeScript, Mocha, OpenAPI contract checks, spec-driven coverage, OAuth2 with automatic token renewal, safe retries, ESLint and GitLab CI.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
npm install
|
|
7
|
+
npm run check # typecheck + lint + all tests
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
Commit `package-lock.json`: the CI pipeline uses `npm ci`.
|
|
11
|
+
|
|
12
|
+
The sample tests start a local mock API (`tests/support/mock-api.ts`) and need no environment, credentials or network. Nothing here connects to a real system until you point `API_BASE_URL` at one.
|
|
13
|
+
|
|
14
|
+
## Layout
|
|
15
|
+
|
|
16
|
+
| Path | Purpose |
|
|
17
|
+
|---|---|
|
|
18
|
+
| `openapi/openapi.json` | The API's OpenAPI document. **Replace it with your API's spec**: contract checks and coverage both read it. |
|
|
19
|
+
| `src/clients/api.ts` | `createApiClient()`: retries with backoff and `Retry-After`, OAuth2 when `OAUTH_*` is set, metrics and coverage hooks. Add production guards and approvals here. |
|
|
20
|
+
| `src/config/environment.ts` | Reads `API_BASE_URL` and the optional `OAUTH_*` settings. |
|
|
21
|
+
| `src/contracts/openapi.ts` | Loads the spec and builds the Ajv-backed contract validator. |
|
|
22
|
+
| `src/observability.ts` | Run-wide metrics and OpenAPI coverage collectors. |
|
|
23
|
+
| `tests/smoke`, `contract`, `security` | Working samples. Add `regression` and `negative` suites beside them. |
|
|
24
|
+
| `tests/setup/hooks.ts` | After the run: writes `reports/coverage/api.md` and `api.json` and can enforce a minimum. |
|
|
25
|
+
| `tests/support/mock-api.ts` | The local mock API and token endpoint the samples use. Delete it once you test a real environment. |
|
|
26
|
+
| `.env.example` | Every setting, with comments. Copy to `.env` locally; use your CI secret store in pipelines. |
|
|
27
|
+
|
|
28
|
+
## Commands
|
|
29
|
+
|
|
30
|
+
| Command | What it does |
|
|
31
|
+
|---|---|
|
|
32
|
+
| `npm test` | Every test. |
|
|
33
|
+
| `npm run test:smoke` / `test:contract` / `test:security` | Tests whose title contains `@smoke` / `@contract` / `@security`. Tag your own `describe` titles the same way. |
|
|
34
|
+
| `npm run test:ci` | Everything, with JUnit XML in `reports/junit/results.xml` for the pipeline. |
|
|
35
|
+
| `npm run lint` | ESLint with type-aware rules: an unawaited request is a check that silently never runs. |
|
|
36
|
+
| `npm run audit:security` | `npm audit` for high-severity advisories. |
|
|
37
|
+
|
|
38
|
+
## Contract checks and coverage
|
|
39
|
+
|
|
40
|
+
```ts
|
|
41
|
+
const contract = await contractValidator();
|
|
42
|
+
contract.assertResponse({ method: 'GET', path: '/accounts/{id}', status: response.status, response });
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
Use the spec's path template, not the concrete URL. After every run `reports/coverage/api.md` lists the operations and documented responses the suite exercised, responses the API returned that the spec does not declare, and requests that match no operation. Set `QE_COVERAGE_MIN_OPERATIONS=80` on full runs to fail when coverage drops. Coverage counts requests, not passes.
|
|
46
|
+
|
|
47
|
+
## Authentication
|
|
48
|
+
|
|
49
|
+
Set `OAUTH_TOKEN_URL`, `OAUTH_CLIENT_ID`, `OAUTH_CLIENT_SECRET` (and optionally `OAUTH_SCOPE`) and `createApiClient()` sends a bearer token automatically. When the server answers 401 the client renews the token and resends once. Use `skipAuth: true` or your own `Authorization` header on a request for negative tests. `tests/security/authentication.spec.ts` shows both against the mock API.
|
|
50
|
+
|
|
51
|
+
## Safety
|
|
52
|
+
|
|
53
|
+
Store credentials in your CI secret store, never in source control or logs. Writes against shared or production-like systems need their own approvals: `QE_ALLOW_MUTATIONS` stays `false` by default, and `createApiClient()` is the place to enforce environment guards. The core library's `assertRequestPolicy` and `rejectUnsafeEnvironment` help.
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
QE_ENV=local
|
|
2
|
+
QE_ALLOW_MUTATIONS=false
|
|
3
|
+
# API under test. The sample tests start their own local mock API and do not need this.
|
|
4
|
+
# API_BASE_URL=https://test.example.invalid
|
|
5
|
+
|
|
6
|
+
# OAuth2 client credentials. Leave unset for an API without authentication.
|
|
7
|
+
# Store real values in your CI/CD secret store, never in this file.
|
|
8
|
+
# OAUTH_TOKEN_URL=https://idp.example.invalid/oauth/token
|
|
9
|
+
# OAUTH_CLIENT_ID=
|
|
10
|
+
# OAUTH_CLIENT_SECRET=
|
|
11
|
+
# OAUTH_SCOPE=
|
|
12
|
+
|
|
13
|
+
# Fail the run when fewer than this percentage of OpenAPI operations were exercised (use on full runs only).
|
|
14
|
+
# QE_COVERAGE_MIN_OPERATIONS=80
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
stages: [verify, test]
|
|
2
|
+
|
|
3
|
+
default:
|
|
4
|
+
image: node:22-bookworm-slim
|
|
5
|
+
|
|
6
|
+
verify:
|
|
7
|
+
stage: verify
|
|
8
|
+
script:
|
|
9
|
+
- npm ci
|
|
10
|
+
- npm run typecheck
|
|
11
|
+
- npm run lint
|
|
12
|
+
- npm run audit:security
|
|
13
|
+
|
|
14
|
+
test:
|
|
15
|
+
stage: test
|
|
16
|
+
script:
|
|
17
|
+
- npm ci
|
|
18
|
+
- npm run test:ci
|
|
19
|
+
artifacts:
|
|
20
|
+
when: always
|
|
21
|
+
reports:
|
|
22
|
+
junit: reports/junit/results.xml
|
|
23
|
+
paths:
|
|
24
|
+
- reports/junit/
|
|
25
|
+
- reports/coverage/
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import js from '@eslint/js';
|
|
2
|
+
import globals from 'globals';
|
|
3
|
+
import tseslint from 'typescript-eslint';
|
|
4
|
+
import { defineConfig } from 'eslint/config';
|
|
5
|
+
|
|
6
|
+
export default defineConfig(
|
|
7
|
+
{ ignores: ['node_modules/', 'reports/'] },
|
|
8
|
+
js.configs.recommended,
|
|
9
|
+
{
|
|
10
|
+
// Type-aware rules matter most in a test project: an unawaited request is a check that silently never runs.
|
|
11
|
+
files: ['**/*.ts'],
|
|
12
|
+
extends: [tseslint.configs.recommendedTypeChecked],
|
|
13
|
+
languageOptions: {
|
|
14
|
+
globals: { ...globals.node, ...globals.mocha },
|
|
15
|
+
parserOptions: { projectService: true, tsconfigRootDir: import.meta.dirname }
|
|
16
|
+
},
|
|
17
|
+
rules: {
|
|
18
|
+
'@typescript-eslint/consistent-type-imports': ['error', { fixStyle: 'inline-type-imports' }],
|
|
19
|
+
'@typescript-eslint/no-floating-promises': 'error',
|
|
20
|
+
'@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_', varsIgnorePattern: '^_' }]
|
|
21
|
+
}
|
|
22
|
+
},
|
|
23
|
+
{
|
|
24
|
+
files: ['**/*.mjs'],
|
|
25
|
+
languageOptions: { globals: globals.node }
|
|
26
|
+
}
|
|
27
|
+
);
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
{
|
|
2
|
+
"openapi": "3.0.3",
|
|
3
|
+
"info": {
|
|
4
|
+
"title": "Sample API (replace with your API's OpenAPI document)",
|
|
5
|
+
"version": "1.0.0"
|
|
6
|
+
},
|
|
7
|
+
"paths": {
|
|
8
|
+
"/health": {
|
|
9
|
+
"get": {
|
|
10
|
+
"operationId": "health",
|
|
11
|
+
"tags": ["ops"],
|
|
12
|
+
"responses": {
|
|
13
|
+
"200": {
|
|
14
|
+
"description": "The service is up",
|
|
15
|
+
"content": { "application/json": { "schema": { "$ref": "#/components/schemas/Health" } } }
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
},
|
|
20
|
+
"/accounts/{id}": {
|
|
21
|
+
"get": {
|
|
22
|
+
"operationId": "getAccount",
|
|
23
|
+
"tags": ["accounts"],
|
|
24
|
+
"parameters": [{ "name": "id", "in": "path", "required": true, "schema": { "type": "string" } }],
|
|
25
|
+
"responses": {
|
|
26
|
+
"200": {
|
|
27
|
+
"description": "The account",
|
|
28
|
+
"content": { "application/json": { "schema": { "$ref": "#/components/schemas/Account" } } }
|
|
29
|
+
},
|
|
30
|
+
"404": {
|
|
31
|
+
"description": "No such account",
|
|
32
|
+
"content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } }
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
},
|
|
37
|
+
"/secure/profile": {
|
|
38
|
+
"get": {
|
|
39
|
+
"operationId": "getProfile",
|
|
40
|
+
"tags": ["security"],
|
|
41
|
+
"responses": {
|
|
42
|
+
"200": {
|
|
43
|
+
"description": "The authenticated caller",
|
|
44
|
+
"content": { "application/json": { "schema": { "$ref": "#/components/schemas/Profile" } } }
|
|
45
|
+
},
|
|
46
|
+
"401": {
|
|
47
|
+
"description": "Missing or invalid access token",
|
|
48
|
+
"content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } }
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
},
|
|
54
|
+
"components": {
|
|
55
|
+
"schemas": {
|
|
56
|
+
"Health": {
|
|
57
|
+
"type": "object",
|
|
58
|
+
"required": ["status"],
|
|
59
|
+
"properties": { "status": { "type": "string", "enum": ["ok"] } }
|
|
60
|
+
},
|
|
61
|
+
"Account": {
|
|
62
|
+
"type": "object",
|
|
63
|
+
"required": ["id", "status"],
|
|
64
|
+
"additionalProperties": false,
|
|
65
|
+
"properties": {
|
|
66
|
+
"id": { "type": "string" },
|
|
67
|
+
"status": { "type": "string", "enum": ["open", "closed"] },
|
|
68
|
+
"balance": { "type": "number" }
|
|
69
|
+
}
|
|
70
|
+
},
|
|
71
|
+
"Profile": {
|
|
72
|
+
"type": "object",
|
|
73
|
+
"required": ["user"],
|
|
74
|
+
"properties": { "user": { "type": "string" } }
|
|
75
|
+
},
|
|
76
|
+
"Error": {
|
|
77
|
+
"type": "object",
|
|
78
|
+
"required": ["error"],
|
|
79
|
+
"properties": { "error": { "type": "string" } }
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { ApiClient, TokenManager, clientCredentialsProvider } from '@nikhil-qeas/api-core';
|
|
2
|
+
import type { ApiClientConfig } from '@nikhil-qeas/api-core';
|
|
3
|
+
import { oauthSettings, targetBaseUrl } from '../config/environment.js';
|
|
4
|
+
import { recordEvent } from '../observability.js';
|
|
5
|
+
|
|
6
|
+
let sharedTokens: TokenManager | undefined;
|
|
7
|
+
/** One token cache per process, so every client and test shares the same access token. */
|
|
8
|
+
function tokensFromEnvironment(): TokenManager | undefined {
|
|
9
|
+
const settings = oauthSettings();
|
|
10
|
+
if (!settings) return undefined;
|
|
11
|
+
sharedTokens ??= new TokenManager(clientCredentialsProvider(settings));
|
|
12
|
+
return sharedTokens;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Client for the API under test.
|
|
17
|
+
* - Retries safe requests with backoff and honors Retry-After; mutations are never retried after an ambiguous failure.
|
|
18
|
+
* - Authenticates with OAuth2 client credentials when OAUTH_* is configured, and renews the token once on a 401.
|
|
19
|
+
* - Feeds every request to the metrics and OpenAPI coverage collectors.
|
|
20
|
+
* Add project-specific approvals (production guards, allowed hosts) here before connecting real environments.
|
|
21
|
+
*/
|
|
22
|
+
export function createApiClient(baseUrl: string = targetBaseUrl(), overrides: Partial<ApiClientConfig> = {}): ApiClient {
|
|
23
|
+
const tokens = tokensFromEnvironment();
|
|
24
|
+
return new ApiClient({
|
|
25
|
+
baseUrl,
|
|
26
|
+
timeoutMs: 15_000,
|
|
27
|
+
maxSafeRetries: 1,
|
|
28
|
+
onEvent: recordEvent,
|
|
29
|
+
...(tokens ? { auth: { tokens } } : {}),
|
|
30
|
+
...overrides
|
|
31
|
+
});
|
|
32
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { requireEnv } from '@nikhil-qeas/api-core';
|
|
2
|
+
|
|
3
|
+
/** Base URL of the API under test (API_BASE_URL). */
|
|
4
|
+
export function targetBaseUrl(env: NodeJS.ProcessEnv = process.env): string {
|
|
5
|
+
const value = env.API_BASE_URL;
|
|
6
|
+
if (!value) throw new Error('API_BASE_URL is required');
|
|
7
|
+
const url = new URL(value);
|
|
8
|
+
if (!['http:', 'https:'].includes(url.protocol)) throw new Error('HTTP(S) required');
|
|
9
|
+
return value;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface OAuthSettings {
|
|
13
|
+
tokenUrl: string;
|
|
14
|
+
clientId: string;
|
|
15
|
+
clientSecret: string;
|
|
16
|
+
scope?: string;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** OAuth2 client-credentials settings, or undefined when OAUTH_TOKEN_URL is not set (an API without authentication). */
|
|
20
|
+
export function oauthSettings(env: NodeJS.ProcessEnv = process.env): OAuthSettings | undefined {
|
|
21
|
+
if (!env.OAUTH_TOKEN_URL) return undefined;
|
|
22
|
+
const required = requireEnv(['OAUTH_TOKEN_URL', 'OAUTH_CLIENT_ID', 'OAUTH_CLIENT_SECRET'], env);
|
|
23
|
+
return {
|
|
24
|
+
tokenUrl: required.OAUTH_TOKEN_URL,
|
|
25
|
+
clientId: required.OAUTH_CLIENT_ID,
|
|
26
|
+
clientSecret: required.OAUTH_CLIENT_SECRET,
|
|
27
|
+
...(env.OAUTH_SCOPE ? { scope: env.OAUTH_SCOPE } : {})
|
|
28
|
+
};
|
|
29
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { createOpenApiValidator } from '@nikhil-qeas/api-core';
|
|
3
|
+
import type { OpenApiDocument, OpenApiValidator } from '@nikhil-qeas/api-core';
|
|
4
|
+
|
|
5
|
+
const SPEC_FILE = new URL('../../openapi/openapi.json', import.meta.url);
|
|
6
|
+
|
|
7
|
+
/** The OpenAPI document that contract checks and coverage use. Replace openapi/openapi.json with your API's spec. */
|
|
8
|
+
export function loadSpec(): OpenApiDocument {
|
|
9
|
+
return JSON.parse(readFileSync(SPEC_FILE, 'utf8')) as OpenApiDocument;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** Validates responses against the spec. Failure messages name the violated schema locations, never response data. */
|
|
13
|
+
export function contractValidator(): Promise<OpenApiValidator> {
|
|
14
|
+
return createOpenApiValidator(loadSpec(), { errorDetail: 'schema' });
|
|
15
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { MetricsCollector, OpenApiCoverage } from '@nikhil-qeas/api-core';
|
|
2
|
+
import type { HttpEvent } from '@nikhil-qeas/api-core';
|
|
3
|
+
import { loadSpec } from './contracts/openapi.js';
|
|
4
|
+
|
|
5
|
+
/** Request timings, errors and retry counts for the whole run. */
|
|
6
|
+
export const metrics = new MetricsCollector();
|
|
7
|
+
|
|
8
|
+
/** Which operations and documented responses of the OpenAPI spec the run exercised. Exclude what you do not test, e.g. ['GET /health']. */
|
|
9
|
+
export const coverage = new OpenApiCoverage(loadSpec(), { exclude: [] });
|
|
10
|
+
|
|
11
|
+
/** Event sink for ApiClient: every request and retry is recorded for the end-of-run report. */
|
|
12
|
+
export function recordEvent(event: HttpEvent): void {
|
|
13
|
+
metrics.record(event);
|
|
14
|
+
coverage.recordEvent(event);
|
|
15
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { ApiResult, OpenApiValidator } from '@nikhil-qeas/api-core';
|
|
2
|
+
import { createApiClient } from '../../src/clients/api.js';
|
|
3
|
+
import { contractValidator } from '../../src/contracts/openapi.js';
|
|
4
|
+
import { startMockApi } from '../support/mock-api.js';
|
|
5
|
+
import type { MockApi } from '../support/mock-api.js';
|
|
6
|
+
|
|
7
|
+
// Each test calls the API and checks the response against openapi/openapi.json:
|
|
8
|
+
// status declared, content type declared, body matching the schema. Use the spec's path template, e.g. /accounts/{id}.
|
|
9
|
+
describe('@contract responses match openapi/openapi.json', () => {
|
|
10
|
+
let mock: MockApi;
|
|
11
|
+
let contract: OpenApiValidator;
|
|
12
|
+
before(async () => {
|
|
13
|
+
mock = await startMockApi();
|
|
14
|
+
contract = await contractValidator();
|
|
15
|
+
});
|
|
16
|
+
after(async () => { await mock.close(); });
|
|
17
|
+
|
|
18
|
+
const conforms = (template: string, response: ApiResult): void => {
|
|
19
|
+
contract.assertResponse({ method: 'GET', path: template, status: response.status, response });
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
it('GET /health', async () => {
|
|
23
|
+
conforms('/health', await createApiClient(mock.baseUrl).request({ method: 'GET', path: '/health' }));
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
it('GET /accounts/{id} for an existing account', async () => {
|
|
27
|
+
conforms('/accounts/{id}', await createApiClient(mock.baseUrl).request({ method: 'GET', path: '/accounts/42' }));
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
it('GET /accounts/{id} for a missing account (404)', async () => {
|
|
31
|
+
conforms('/accounts/{id}', await createApiClient(mock.baseUrl).request({ method: 'GET', path: '/accounts/missing' }));
|
|
32
|
+
});
|
|
33
|
+
});
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import { TokenManager, clientCredentialsProvider, expectStatus } from '@nikhil-qeas/api-core';
|
|
3
|
+
import type { ApiClient } from '@nikhil-qeas/api-core';
|
|
4
|
+
import { createApiClient } from '../../src/clients/api.js';
|
|
5
|
+
import { startMockApi } from '../support/mock-api.js';
|
|
6
|
+
import type { MockApi } from '../support/mock-api.js';
|
|
7
|
+
|
|
8
|
+
describe('@security authentication', () => {
|
|
9
|
+
let mock: MockApi;
|
|
10
|
+
before(async () => { mock = await startMockApi(); });
|
|
11
|
+
after(async () => { await mock.close(); });
|
|
12
|
+
|
|
13
|
+
const authenticatedClient = (): ApiClient => createApiClient(mock.baseUrl, {
|
|
14
|
+
auth: { tokens: new TokenManager(clientCredentialsProvider({ tokenUrl: mock.tokenUrl, clientId: 'qa-client', clientSecret: 'qa-secret' })) }
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
it('sends the access token, and renews it once when the server rejects it', async () => {
|
|
18
|
+
const api = authenticatedClient();
|
|
19
|
+
expectStatus(await api.request({ method: 'GET', path: '/secure/profile' }), 200);
|
|
20
|
+
mock.revokeTokens(); // the server no longer accepts the token the client holds
|
|
21
|
+
const retried = await api.request({ method: 'GET', path: '/secure/profile' });
|
|
22
|
+
expectStatus(retried, 200);
|
|
23
|
+
assert.equal(retried.reauthenticated, true);
|
|
24
|
+
assert.equal(mock.tokensIssued(), 2);
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
it('rejects a request that carries no token', async () => {
|
|
28
|
+
expectStatus(await authenticatedClient().request({ method: 'GET', path: '/secure/profile', skipAuth: true }), 401);
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
it('rejects a deliberately invalid token and does not retry it', async () => {
|
|
32
|
+
const response = await authenticatedClient().request({ method: 'GET', path: '/secure/profile', headers: { Authorization: 'Bearer not-a-real-token' } });
|
|
33
|
+
expectStatus(response, 401);
|
|
34
|
+
assert.equal(response.attempts, 1);
|
|
35
|
+
});
|
|
36
|
+
});
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { coverage, metrics } from '../../src/observability.js';
|
|
2
|
+
|
|
3
|
+
/** Mocha root hooks: after the whole run, write the coverage report and optionally enforce a minimum. */
|
|
4
|
+
export const mochaHooks = {
|
|
5
|
+
async afterAll(): Promise<void> {
|
|
6
|
+
await coverage.write('reports/coverage/api.md', 'markdown');
|
|
7
|
+
await coverage.write('reports/coverage/api.json');
|
|
8
|
+
const { operations, responses } = coverage.report();
|
|
9
|
+
const { total, retries } = metrics.summary();
|
|
10
|
+
console.log(
|
|
11
|
+
`\nAPI coverage: ${operations.covered}/${operations.total} operations (${operations.percent}%), ` +
|
|
12
|
+
`${responses.covered}/${responses.total} documented responses. Requests: ${total}, retries: ${retries}. Report: reports/coverage/api.md`
|
|
13
|
+
);
|
|
14
|
+
const minimum = process.env.QE_COVERAGE_MIN_OPERATIONS;
|
|
15
|
+
if (minimum) coverage.assertCoverage({ minOperations: Number(minimum), failOnUndocumented: true });
|
|
16
|
+
}
|
|
17
|
+
};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import { expectStatus } from '@nikhil-qeas/api-core';
|
|
3
|
+
import { createApiClient } from '../../src/clients/api.js';
|
|
4
|
+
import { startMockApi } from '../support/mock-api.js';
|
|
5
|
+
import type { MockApi } from '../support/mock-api.js';
|
|
6
|
+
|
|
7
|
+
describe('@smoke API health', () => {
|
|
8
|
+
let mock: MockApi;
|
|
9
|
+
before(async () => { mock = await startMockApi(); });
|
|
10
|
+
after(async () => { await mock.close(); });
|
|
11
|
+
|
|
12
|
+
it('answers the health check', async () => {
|
|
13
|
+
const response = await createApiClient(mock.baseUrl).request({ method: 'GET', path: '/health' });
|
|
14
|
+
expectStatus(response, 200);
|
|
15
|
+
assert.deepEqual(response.body, { status: 'ok' });
|
|
16
|
+
});
|
|
17
|
+
});
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { createServer } from 'node:http';
|
|
2
|
+
import type { ServerResponse } from 'node:http';
|
|
3
|
+
import { once } from 'node:events';
|
|
4
|
+
import type { AddressInfo } from 'node:net';
|
|
5
|
+
|
|
6
|
+
/** A local stand-in for an API and its OAuth2 token endpoint, so the sample tests run anywhere without a real environment. */
|
|
7
|
+
export interface MockApi {
|
|
8
|
+
baseUrl: string;
|
|
9
|
+
tokenUrl: string;
|
|
10
|
+
/** Number of access tokens issued so far. */
|
|
11
|
+
tokensIssued(): number;
|
|
12
|
+
/** Invalidate the current access token on the server, as an expiry or revocation would. */
|
|
13
|
+
revokeTokens(): void;
|
|
14
|
+
close(): Promise<void>;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function send(res: ServerResponse, status: number, body: unknown): void {
|
|
18
|
+
res.statusCode = status;
|
|
19
|
+
res.setHeader('content-type', 'application/json');
|
|
20
|
+
res.end(JSON.stringify(body));
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export async function startMockApi(): Promise<MockApi> {
|
|
24
|
+
let issued = 0;
|
|
25
|
+
let validToken: string | undefined;
|
|
26
|
+
const server = createServer((req, res) => {
|
|
27
|
+
req.resume();
|
|
28
|
+
const { pathname } = new URL(req.url ?? '/', 'http://localhost');
|
|
29
|
+
if (req.method === 'POST' && pathname === '/oauth/token') {
|
|
30
|
+
issued++;
|
|
31
|
+
validToken = `tok-${issued}`;
|
|
32
|
+
send(res, 200, { access_token: validToken, token_type: 'Bearer', expires_in: 3600 });
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
if (req.method === 'GET' && pathname === '/health') {
|
|
36
|
+
send(res, 200, { status: 'ok' });
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
const account = /^\/accounts\/([^/]+)$/.exec(pathname);
|
|
40
|
+
if (req.method === 'GET' && account) {
|
|
41
|
+
const id = decodeURIComponent(account[1] ?? '');
|
|
42
|
+
if (id === 'missing') send(res, 404, { error: 'not_found' });
|
|
43
|
+
else send(res, 200, { id, status: 'open', balance: 12.5 });
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
if (req.method === 'GET' && pathname === '/secure/profile') {
|
|
47
|
+
if (validToken !== undefined && req.headers.authorization === `Bearer ${validToken}`) send(res, 200, { user: 'qa-bot' });
|
|
48
|
+
else send(res, 401, { error: 'invalid_token' });
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
send(res, 404, { error: 'not_found' });
|
|
52
|
+
});
|
|
53
|
+
server.listen(0, '127.0.0.1');
|
|
54
|
+
await once(server, 'listening');
|
|
55
|
+
const origin = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
|
|
56
|
+
return {
|
|
57
|
+
baseUrl: origin,
|
|
58
|
+
tokenUrl: `${origin}/oauth/token`,
|
|
59
|
+
tokensIssued: () => issued,
|
|
60
|
+
revokeTokens: () => { validToken = undefined; },
|
|
61
|
+
close: () => new Promise<void>(resolve => {
|
|
62
|
+
server.closeAllConnections();
|
|
63
|
+
server.close(() => resolve());
|
|
64
|
+
})
|
|
65
|
+
};
|
|
66
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
{
|
|
2
|
+
"compilerOptions": {
|
|
3
|
+
"target": "ES2022",
|
|
4
|
+
"module": "NodeNext",
|
|
5
|
+
"moduleResolution": "NodeNext",
|
|
6
|
+
"strict": true,
|
|
7
|
+
"esModuleInterop": true,
|
|
8
|
+
"types": ["node", "mocha"],
|
|
9
|
+
"resolveJsonModule": true,
|
|
10
|
+
"noEmit": true,
|
|
11
|
+
"skipLibCheck": true
|
|
12
|
+
},
|
|
13
|
+
"include": ["src/**/*.ts", "tests/**/*.ts"]
|
|
14
|
+
}
|