Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
83 changes: 83 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,63 @@ jobs:
|| contains(needs.*.result, 'cancelled')
|| contains(needs.*.result, 'skipped')

# TEMPORARY (revert before merge): builds @pact-foundation/pact-core from
# YOU54F/pact-js-core feat/or-matcher, whose CI prebuilds the native addon against the
# pact_ffi 0.5.13-or.1 prerelease from YOU54F/pact-reference, and hands the
# JS build plus those prebuilds to the test jobs.
pact-core-rc:
name: Fetch pact-core build (pact_ffi rc)
runs-on: ubuntu-latest
env:
PACT_CORE_REPO: YOU54F/pact-js-core
PACT_CORE_BRANCH: feat/or-matcher
GH_TOKEN: ${{ github.token }}

steps:
- name: Find the latest pact-js-core run with prebuilds
id: run
run: |
run_id=$(gh run list --repo "$PACT_CORE_REPO" --branch "$PACT_CORE_BRANCH" \
--workflow build-and-test.yml --event pull_request \
--json databaseId,headSha -L 1 -q '.[0].databaseId')
sha=$(gh run view "$run_id" --repo "$PACT_CORE_REPO" --json headSha -q .headSha)
echo "Using $PACT_CORE_REPO run $run_id at $sha"
echo "id=$run_id" >> "$GITHUB_OUTPUT"
echo "sha=$sha" >> "$GITHUB_OUTPUT"

- name: Checkout pact-js-core
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
repository: ${{ env.PACT_CORE_REPO }}
ref: ${{ steps.run.outputs.sha }}
path: pact-js-core

- name: Setup Node.JS
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: ${{ env.STABLE_NODE_VERSION }}

- name: Build pact-core JS
working-directory: pact-js-core
run: |
npm ci --ignore-scripts
npm run build
grep -n "PACT_FFI_VERSION =" src/ffi/index.ts

- name: Assemble pact-core with prebuilds
run: |
gh run download "${{ steps.run.outputs.id }}" --repo "$PACT_CORE_REPO" -p 'artifact-*' -D artifacts
mkdir -p pact-core-rc
cp -R pact-js-core/dist pact-core-rc/dist
for f in artifacts/*/*.tar.gz; do tar -xzf "$f" -C pact-core-rc; done
find pact-core-rc/prebuilds -type f

- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7
with:
name: pact-core-rc
path: pact-core-rc
if-no-files-found: error

lint:
name: Lint
runs-on: ubuntu-latest
Expand Down Expand Up @@ -113,6 +170,7 @@ jobs:
with Node ${{ matrix.node-version }}

runs-on: ${{ matrix.os }}
needs: [pact-core-rc]

strategy:
fail-fast: false
Expand All @@ -137,6 +195,19 @@ jobs:
cache: npm

- run: npm ci
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
name: pact-core-rc
path: pact-core-rc
- name: Use pact-core build with pact_ffi rc (revert before merge)
shell: bash
run: |
rm -rf node_modules/@pact-foundation/pact-core/dist
cp -R pact-core-rc/dist node_modules/@pact-foundation/pact-core/dist
echo "PACT_PREBUILD_LOCATION=$(node -p "require('path').resolve('pact-core-rc')")" >> "$GITHUB_ENV"
- name: Check the loaded pact_ffi version
shell: bash
run: node -e "const v=require('@pact-foundation/pact-core').getFfiLib('info').pactffiVersion(); console.log('pact_ffi', v); if (v !== '0.5.13-or.1') process.exit(1)"
- run: npm test
shell: bash

Expand All @@ -161,6 +232,7 @@ jobs:
with Node ${{ matrix.node-version }}

runs-on: ubuntu-latest
needs: [pact-core-rc]
container:
image: node:${{ matrix.node-version }}-alpine

Expand All @@ -174,6 +246,17 @@ jobs:
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1

- run: npm ci
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
name: pact-core-rc
path: pact-core-rc
- name: Use pact-core build with pact_ffi rc (revert before merge)
run: |
rm -rf node_modules/@pact-foundation/pact-core/dist
cp -R pact-core-rc/dist node_modules/@pact-foundation/pact-core/dist
echo "PACT_PREBUILD_LOCATION=$(node -p "require('path').resolve('pact-core-rc')")" >> "$GITHUB_ENV"
- name: Check the loaded pact_ffi version
run: node -e "const v=require('@pact-foundation/pact-core').getFfiLib('info').pactffiVersion(); console.log('pact_ffi', v); if (v !== '0.5.13-or.1') process.exit(1)"
- run: npm test

examples:
Expand Down
66 changes: 66 additions & 0 deletions docs/matching.md
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,9 @@ const animalBodyExpectation = {
| `eachKeyMatches` | example: object, rules: Matcher[] | Object where the _keys_ must match the supplied matching rules and the values are ignored. |
| `eachValueMatches` | example: object, rules: Matcher[] | Object where the _values_ must match the supplied matching rules and keys are ignored. |
| `fromProviderState` | expression: string, exampleValue: string | Sets a type matcher and a provider state generator. See the section below. |
| `anyOf` | matchers... | Value that must match at least one of the given matchers (the matchers are combined with OR). The example is taken from the first matcher. See the section below. |
| `likeOrNull` | template | Value that must be null, or match the template by type (e.g. an optional object). Shorthand for `anyOf(like(template), nullValue())`. |
| `stringOrNull` | example?: string | Value that must be null, or a string. The `integerOrNull`, `decimalOrNull`, `numberOrNull`, `booleanOrNull`, `regexOrNull` and `uuidOrNull` matchers work the same way, taking the same parameters as the matcher they combine with `nullValue`. |

#### Array contains matcher

Expand Down Expand Up @@ -265,6 +268,69 @@ these can be used to match a hypermedia format like Siren, see [Example Pact + S
}
```

#### Combining matchers with OR

> [!NOTE]
> Requires a version of the Pact FFI that supports `pact:matcher:combine` ([pact-reference#601](https://github.com/pact-foundation/pact-reference/pull/601)), which is
> included in `@pact-foundation/pact-core` TODO: version. With older versions the matchers are combined with AND, so the consumer test will fail.

The `anyOf` matching function applies several matchers to the same value, and matching succeeds if at least one of
them matches. This is written to the pact file as a list of matching rules combined with `OR`, which is supported by the
V3 and V4 specifications. It can be used for bodies, headers and query parameters.

The `*OrNull` functions (`likeOrNull`, `stringOrNull`, `integerOrNull`, `decimalOrNull`, `numberOrNull`, `booleanOrNull`,
`regexOrNull` and `uuidOrNull`) are shorthand for the most common case, a value that can also be `null`.

```js
const { MatchersV3 } = require('@pact-foundation/pact');
const { anyOf, integer, likeOrNull, nullValue, regex, string, stringOrNull, uuid } = MatchersV3;

const body = {
// a string or null
name: anyOf(string('Fred'), nullValue()), // same as stringOrNull('Fred')
// an ID that is either a number or a UUID
id: anyOf(regex(/^\d+$/, '42'), uuid()),
// an optional object: either null, or an object whose `number` is an integer
address: likeOrNull({
street: string('Main St'),
number: integer(42),
}),
};
```

The `name` attribute is sent to the Pact FFI as:

```json
{
"pact:matcher:type": [{ "pact:matcher:type": "type" }, { "pact:matcher:type": "null" }],
"pact:matcher:combine": "OR",
"value": "Fred"
}
```

and written to the pact file as:

```json
"$.name": {
"combine": "OR",
"matchers": [{ "match": "type" }, { "match": "null" }]
}
```

Things to be aware of:

- **Only the example is exercised in the consumer test.** The example value is taken from the first matcher (e.g. `'Fred'`
above), so the consumer code is only tested against that value. The other alternatives (e.g. `null`) are only checked
when the provider is verified, so make sure your consumer code handles them, for example with separate interactions or
unit tests. Use OR with care.
- Order the matchers so that the one with the example you want to use comes first.
- Matchers nested in the example of the first matcher (like `integer(42)` in `address` above) still apply to the children
of the value when it is not null.
- Matchers that compare against the example, like `like`, can only describe the shape of that example. For instance,
`likeOrNull({...})` accepts an object of the same shape or null, but not an array.
- Each path can only have a single list of rules. Put all the alternatives in the one `anyOf` call, rather than wrapping
another matcher in the example. Nested `anyOf` calls are flattened into a single list.

#### Provider State Injected Values

The `fromProviderState` matching function allows values to be generated based on values returned from the provider state callbacks. This should be used for the cases were database entries have auto-generated values and these values need to be used in the URLs or query parameters.
Expand Down
154 changes: 154 additions & 0 deletions src/orMatchers.integration.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
import axios from 'axios';

import fs = require('node:fs');
import path = require('node:path');

import { MatchersV3 } from './v3';
import { PactV4 } from './v4';

const { anyOf, integer, likeOrNull, nullValue, regex, string, uuid } =
MatchersV3;

// Requires a version of the Pact FFI that supports `pact:matcher:combine`
// (pact-foundation/pact-reference#601)
describe('Matchers combined with OR', () => {
const pactFilePath = path.resolve(
process.cwd(),
'pacts',
'or-matcher-consumer-or-matcher-provider.json',
);
const description = 'a request to create a user with optional fields';
const id = 'e2490de5-5bd3-43d5-b7c4-526e33f71304';

type Address = { street: string; number: unknown } | null;
type RequestOptions = {
name?: unknown;
address?: Address;
query?: string;
header?: string;
};

const executeRequest = ({
name = 'Fred',
address = { street: 'Main St', number: 42 },
query = '42',
header = '42',
}: RequestOptions = {}) =>
new PactV4({
consumer: 'or-matcher-consumer',
provider: 'or-matcher-provider',
})
.addInteraction()
.uponReceiving(description)
.withRequest('POST', '/users', (builder) => {
builder
.query({ id: anyOf(regex(/^\d+$/, '42'), uuid(id)) })
.headers({ 'x-request-id': anyOf(regex(/^\d+$/, '42'), uuid(id)) })
.jsonBody({
name: anyOf(string('Fred'), nullValue()),
address: likeOrNull({
street: string('Main St'),
number: integer(42),
}),
});
})
.willRespondWith(201, (builder) => {
builder.jsonBody({ name: anyOf(string('Fred'), nullValue()) });
})
.executeTest(async (server) => {
const res = await axios.post(
`${server.url}/users`,
{ name, address },
{
params: { id: query },
headers: { 'x-request-id': header },
validateStatus: () => true,
},
);
return res;
});

beforeAll(() => {
if (fs.existsSync(pactFilePath)) {
fs.unlinkSync(pactFilePath);
}
});

it('matches the example values, and returns the example from the first matcher', async () => {
const res = await executeRequest();
expect(res?.status).toEqual(201);
expect(res?.data).toEqual({ name: 'Fred' });
});

it('matches the other alternatives', async () => {
const res = await executeRequest({
name: null,
address: null,
query: id,
header: id,
});
expect(res?.status).toEqual(201);
});

it('applies the matchers nested in the example of an optional object', async () => {
await expect(
executeRequest({ address: { street: 'Other St', number: 7 } }),
).resolves.toBeDefined();
await expect(
executeRequest({ address: { street: 'Main St', number: '42' } }),
).rejects.toThrow(/Test failed/);
});

it('fails when the body value matches none of the alternatives', async () => {
await expect(executeRequest({ name: 123 })).rejects.toThrow(/Test failed/);
});

it('fails when a header matches none of the alternatives', async () => {
await expect(executeRequest({ header: 'abc' })).rejects.toThrow(
/Test failed/,
);
});

it('fails when a query parameter matches none of the alternatives', async () => {
await expect(executeRequest({ query: 'abc' })).rejects.toThrow(
/Test failed/,
);
});

it('writes the rules combined with OR to the pact file', () => {
const pact = JSON.parse(fs.readFileSync(pactFilePath, 'utf8'));
const interaction = pact.interactions.find(
(i: { description: string }) => i.description === description,
);
const requestRules = interaction.request.matchingRules;
const orRegexOrUuid = {
combine: 'OR',
matchers: [
{ match: 'regex', regex: '^\\d+$' },
{
match: 'regex',
regex: '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}',
},
],
};

expect(requestRules.body['$.name']).toEqual({
combine: 'OR',
matchers: [{ match: 'type' }, { match: 'null' }],
});
expect(requestRules.body['$.address']).toEqual({
combine: 'OR',
matchers: [{ match: 'type' }, { match: 'null' }],
});
expect(requestRules.body['$.address.number']).toEqual({
combine: 'AND',
matchers: [{ match: 'integer' }],
});
expect(requestRules.header['x-request-id']).toEqual(orRegexOrUuid);
expect(requestRules.query.id).toEqual(orRegexOrUuid);
expect(interaction.response.matchingRules.body['$.name']).toEqual({
combine: 'OR',
matchers: [{ match: 'type' }, { match: 'null' }],
});
});
});
Loading
Loading