
# Thymian
**Add resilience and HTTP conformance to your API development workflow**
[](https://github.com/thymianofficial/thymian/blob/main/LICENSE)
[](https://github.com/thymianofficial/thymian/actions/workflows/ci.yaml)
[](https://thymian.dev)
[](https://discord.gg/TRSwCxbz9f)
[](https://www.reddit.com/r/ThymianOfficial/)
[](https://x.com/thymiandev)
## @thymian/rules-testing
Test a rule through the real engine of a validation context it declares. You build the API the rule is tested against as a Thymian format with the factories of `@thymian/core-testing`, hand it to `createRuleTester`, and get back plain data: one execution per transaction of the format. No test framework is required or assumed.
## Installation
```bash
npm install --save-dev @thymian/rules-testing @thymian/core-testing
```
## Usage
```typescript
import { addTransaction, createBadRequestResponse, createCreatedResponse, createGetRequest, createOkResponse, createPostRequest, createRequiredParameter, createThymianFormat } from '@thymian/core-testing';
import { createRuleTester } from '@thymian/rules-testing';
import createdResponsesHaveLocation from './created-responses-have-location.rule.js';
const format = createThymianFormat();
const launchesListed = addTransaction(format, createGetRequest({ path: '/launches' }), createOkResponse());
const launchCreated = addTransaction(format, createPostRequest({ path: '/launches' }), createCreatedResponse({ headers: { location: createRequiredParameter() } }));
// One operation with two answers is two transactions on the same request.
const createAstronaut = createPostRequest({ path: '/astronauts' });
const astronautCreated = addTransaction(format, createAstronaut, createCreatedResponse());
const astronautRejected = addTransaction(format, createAstronaut, createBadRequestResponse());
const ruleTester = createRuleTester(createdResponsesHaveLocation);
const expected = [
{ location: { elementId: launchesListed }, status: 'notApplicable' },
{ location: { elementId: launchCreated }, status: 'passed' },
{
location: { elementId: astronautCreated },
status: 'failed',
severity: 'warn',
message: 'A 201 Created response must name the new resource in a Location header',
},
{ location: { elementId: astronautRejected }, status: 'notApplicable' },
];
expect(await ruleTester.runLint(format)).toMatchObject(expected);
expect(await ruleTester.runTest(format)).toMatchObject(expected);
expect(await ruleTester.runAnalyze(format)).toMatchObject(expected);
```
`createRuleTester(rule)` gives one method per validation context: `runLint` evaluates the rule in `static`, with the context `thymian lint` uses, `runTest` in `test`, with the one `thymian test` uses, `runAnalyze` in `analytics`, with the one `thymian analyze` uses. Each returns a list of the same shape in the same order. Calling the method of a context the rule does not declare throws.
### The server in `test`
`test` opens no port and sends nothing over the network. The tester builds each request from the format, with the examples the format carries, and the request is answered in-process.
**Without your saying anything, the server answers as the format declares:** the conforming response of a transaction has the declared status, every declared header (required or not) with a value, the declared media type as `content-type`, and a body where the response declares a schema. A value is the first example of its schema, else its `const`, first `enum` member or `default`, else the plainest value of its type. So a format gives the same result in `test` as in `static`.
**A server that deviates** is a function. It is given the id of the transaction the request is aimed at, the conforming response and the request that was sent, and returns the response:
```typescript
await ruleTester.runTest(format, {
respond: ({ transaction, conforming }) => (transaction === launchCreated ? { ...conforming, headers: {} } : conforming),
});
```
Here `launchCreated` is `failed`: the server dropped the `Location` header the format declares. One condition can change many answers, for example `conforming.statusCode >= 400`. One operation with two answers gets two requests, one aimed at each transaction.
The tester does not ask the rule about a transaction in `test`, and gives a `reason`, when:
- **The live pair is outside the rule's applicability**, for example because the server answers another status than the transaction declares. The transaction is `notApplicable`, as `thymian test` reports it.
- **The request cannot be built**, for example for a path parameter without an example: give its schema one, `createRequiredParameter({ schema: createStringSchema({ examples: ['apollo-11'] }) })`. The transaction is `skipped`.
### The traffic in `analytics`
`analytics` reads no recording from disk: the analyzer is handed traffic held in memory, with the format present, as `thymian analyze` hands it a HAR file together with the specification.
**The traffic is every transaction of the format recorded once, conforming:** the request the tester would send for it, with the examples the format carries and the media type the format declares for it as `content-type`, answered with the conforming response described above. So a rule that judges a transaction by what the format declares gives the same executions in `analytics` as in `static` and `test`.
Each pair is recorded the way traffic read from a HAR file is by default, as a user agent talking to an origin server, so a rule that speaks about one participant (`.appliesTo('server')`) is asked about it.
The analyzer locates an execution on the transaction of the format the recorded pair matches, so you name a transaction by the same id as in the other contexts. A rule that reads captured transactions or whole traces locates an execution on the label it is given: it keeps that location and is listed in the place of the transaction the recorded pair matched (see **Order** below). An execution the rule locates on any other string keeps that location and comes last.
The analyzer recognises a transaction in a recording by method, origin, path, status and media types, as it does for real traffic. Where that does not single out the transaction you added, `analytics` differs from `static` and `test`: two answers of one request with the same status and media type match neither, so both are `notApplicable` and an execution on their recording keeps its label; and a recording of `/launches/{id}` with the example `latest` is taken for a transaction on the literal path `/launches/latest` when the format has one. And the label of a recording names the method, the URL, the status and the response's media type, but not the request's: where recordings of two transactions share one, an execution on it comes after the transactions, and both transactions are listed as if the rule had said nothing about them.
A request that cannot be built, for example for a path parameter without an example, makes `analytics` throw and name the transaction: there is nothing to record for it. Give the parameter's schema an example, as for `test`.
A `default` transaction is not recorded: its response declares no status to answer with. It is listed with the transactions that were never recorded, as `notApplicable`. To record one, name the status it answers with in `recorded`.
**Traffic you hand in** replaces it. `traffic` is a list of recorded pairs, each a request and its response as plain HTTP objects. `recorded(format, transactionId, overrides?)` gives the conforming pair of a transaction, so you write only what deviates:
```typescript
import { createRuleTester, recorded } from '@thymian/rules-testing';
const executions = await ruleTester.runAnalyze(format, {
traffic: [recorded(format, launchCreated), recorded(format, launchCreated, { response: { headers: {} } })],
});
expect(executions).toMatchObject([
{ location: { elementId: launchCreated }, status: 'passed' },
{ location: { elementId: launchCreated }, status: 'failed' },
{ location: { elementId: launchesListed }, status: 'notApplicable' },
// ...every other transaction of the format, none of them recorded
]);
```
A transaction may be recorded several times, and each recording is judged on its own: here the second one dropped the `Location` header the format declares. The list is then in another order than for `static`: one entry per recording, in traffic order; then the transactions that were never recorded, as `notApplicable`; then executions on any other location.
An override replaces a field of the conforming request or response as a whole: `{ request: { headers: { authorization: 'Bearer apollo' } } }` records exactly that request header, which is how a rule about a request header is tested. One thing is kept: the media type the format declares is still named as `content-type`, because the analyzer recognises the transaction by it, unless the headers you give name a `content-type` themselves. `recorded` throws for an id the format has no transaction with, for a request that cannot be built, and for a `default` transaction unless the override names its status: `{ response: { statusCode: 503 } }`.
A recording that the analyzer matches to no transaction of the format has no transaction to appear on. When its request still matches an operation and only the response is undocumented, for example one with another status or media type, what the rule says about it is located on that operation's request node. Otherwise, for example for another path, it is located on a free string, the label of the recording. Either way it comes last:
```typescript
const executions = await ruleTester.runAnalyze(format, {
traffic: [recorded(format, launchCreated, { request: { path: '/probes' }, response: { headers: {} } })],
});
expect(executions.at(-1)).toMatchObject({ location: expect.stringContaining('/probes'), status: 'failed' });
```
The analyzer names the transaction an execution is about, not the recording. For a transaction recorded several times, `createRuleTester` therefore also runs the rule on each of its recordings alone to learn which one an execution belongs to. A rule that compares recordings with each other says something else about a recording that stands alone; what such a rule reports on the transaction then appears on every recording of it.
### Any rule runs
**A rule that ships with severity `off`** runs like any other, so a rule that is only switched on by a config or a profile is testable as it ships. A `failed` execution carries the severity the rule declares, here `off`.
**A rule with options** gets them from `createRuleTester(rule, { options })`, handed to the rule function as the `options` of the rule's entry in a config are. One call is one configuration:
```typescript
const format = createThymianFormat();
const launchCreated = addTransaction(format, createPostRequest({ path: '/launches' }), createCreatedResponse({ headers: { location: createRequiredParameter() } }));
expect(await createRuleTester(createdResponsesHaveHeader, { options: { header: 'location' } }).runLint(format)).toMatchObject([{ location: { elementId: launchCreated }, status: 'passed' }]);
expect(await createRuleTester(createdResponsesHaveHeader, { options: { header: 'etag' } }).runLint(format)).toMatchObject([{ location: { elementId: launchCreated }, status: 'failed' }]);
```
Options the rule's options schema does not accept make `createRuleTester` throw, as a config with them is rejected when it is loaded.
### Grouped rules
A rule that compares several transactions with each other (`validateGroupedCommonHttpTransactions`) is handed each group with its key and its members, and says who is at fault by the location it returns. Both readings come back per transaction, in all three contexts:
- **It returns the location of one member:** that transaction is `failed`, and the other members of the group are `passed`.
- **It returns the group key:** every member of the group is `failed`, and each of these executions carries the key as `group`.
```typescript
const launchRead = addTransaction(format, createGetRequest({ path: '/launches' }), createOkResponse({ headers: { etag: createRequiredParameter() } }));
const launchReplaced = addTransaction(format, createPutRequest({ path: '/launches' }), createOkResponse());
// A rule that groups by `url()` and returns the key of a group whose answers disagree about ETag
expect(await createRuleTester(resourcesSendEtagConsistently).runLint(format)).toMatchObject([
{ location: { elementId: launchRead }, status: 'failed', group: expect.stringContaining('/launches') },
{ location: { elementId: launchReplaced }, status: 'failed', group: expect.stringContaining('/launches') },
]);
```
The key is what the context grouped by, spelled as that context spells it: grouped by `url()`, `static` and `test` give `https://localhost:443/launches` where `analytics` gives `https://localhost/launches`. In `test` the tester sends the requests of a group together. A member the server answers outside the rule's applicability is not judged: it is `notApplicable`, with a `reason`, and the rule judges the other members.
### What comes back
A list of executions. Each one has:
| Field | Meaning |
| ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `location` | Where the engine located it. For a transaction: `{ elementType: 'edge', elementId: