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
20 changes: 16 additions & 4 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@
"composer run-example:generators",
"composer run-example:json",
"composer run-example:matchers",
"composer run-example:or-matcher",
"composer run-example:message",
"composer run-example:multipart",
"composer run-example:protobuf-async-message",
Expand All @@ -94,6 +95,7 @@
"composer run-example:generators:windows",
"composer run-example:json:windows",
"composer run-example:matchers:windows",
"composer run-example:or-matcher:windows",
"composer run-example:message:windows",
"composer run-example:multipart:windows",
"composer run-example:protobuf-async-message:windows",
Expand Down Expand Up @@ -129,6 +131,11 @@
"cd example/matchers/consumer && phpunit --process-isolation",
"cd example/matchers/provider && phpunit --process-isolation"
],
"run-example:or-matcher:windows": [
"powershell -Command \"if (Test-Path 'example/or-matcher/pacts/orMatcherConsumer-orMatcherProvider.json') { Remove-Item 'example/or-matcher/pacts/orMatcherConsumer-orMatcherProvider.json' }\"",
"cd example/or-matcher/consumer && phpunit --process-isolation",
"cd example/or-matcher/provider && phpunit --process-isolation"
],
"run-example:message:windows": [
"powershell -Command \"if (Test-Path 'example/message/pacts/messageConsumer-messageProvider.json') { Remove-Item 'example/message/pacts/messageConsumer-messageProvider.json' }\"",
"cd example/message/consumer && phpunit --process-isolation",
Expand Down Expand Up @@ -192,6 +199,11 @@
"cd example/matchers/consumer && phpunit",
"cd example/matchers/provider && phpunit"
],
"run-example:or-matcher": [
"rm -f example/or-matcher/pacts/orMatcherConsumer-orMatcherProvider.json",
"cd example/or-matcher/consumer && phpunit",
"cd example/or-matcher/provider && phpunit"
],
"run-example:message": [
"rm -f example/message/pacts/messageConsumer-messageProvider.json",
"cd example/message/consumer && phpunit",
Expand Down Expand Up @@ -244,20 +256,20 @@
"extra": {
"downloads": {
"pact-ffi-headers": {
"version": "0.5.10",
"url": "https://github.com/pact-foundation/pact-reference/releases/download/libpact_ffi-v{$version}/pact.h",
"version": "0.5.13-or.1",
"url": "https://github.com/YOU54F/pact-reference/releases/download/libpact_ffi-v{$version}/pact.h",
"path": "bin/pact-ffi-headers/pact.h"
},
"pact-ffi-lib": {
"version": "0.5.10",
"version": "0.5.13-or.1",
"variables": {
"{$prefix}": "PHP_OS_FAMILY === 'Windows' ? 'pact_ffi' : 'libpact_ffi'",
"{$os}": "PHP_OS === 'Darwin' ? 'macos' : strtolower(PHP_OS_FAMILY)",
"{$architecture}": "in_array(php_uname('m'), ['arm64', 'aarch64']) ? 'aarch64' : 'x86_64'",
"{$musl}": "PHP_OS === 'Linux' && musl() === true ? '-musl' : ''",
"{$extension}": "PHP_OS_FAMILY === 'Windows' ? 'dll' : (PHP_OS === 'Darwin' ? 'dylib' : 'so')"
},
"url": "https://github.com/pact-foundation/pact-reference/releases/download/libpact_ffi-v{$version}/{$prefix}-{$os}-{$architecture}{$musl}.{$extension}.gz",
"url": "https://github.com/YOU54F/pact-reference/releases/download/libpact_ffi-v{$version}/{$prefix}-{$os}-{$architecture}{$musl}.{$extension}.gz",
"path": "bin/pact-ffi-lib/pact.{$extension}"
},
"pact-stub-server": {
Expand Down
72 changes: 72 additions & 0 deletions docs/consumer.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,78 @@ uuid | Regex to match a uuid. | Value (Defaults to ce118b6e-d8e1-11e7-9296-cec27
ipv4Address | Regex to match a ipv4 address. | Value (Defaults to 127.0.0.13) | $matcher->ipv4Address('127.0.0.1')
ipv6Address | Regex to match a ipv6 address. | Value (Defaults to ::ffff:192.0.2.128) | $matcher->ipv6Address('::ffff:192.0.2.1')
email | Regex to match an address. | Value (hello@pact.io) | $matcher->email('hello@pact.io')
nullValue | Match a null value. | none | $matcher->nullValue()
matchAll | Match if all the matchers match (combined with AND). | Value, Matchers | $matcher->matchAll(['key' => 'value'], [$matcher->atLeast(1), $matcher->atMost(2)])
matchAny | Match if at least one of the matchers matches (combined with OR). See [Combining matchers with OR](#combining-matchers-with-or). | Value, Matchers | $matcher->matchAny('Fred', [$matcher->like(null), $matcher->nullValue()])
likeOrNull | Match a value of the same type as the example, or null. Shortcut for `matchAny` with `like` and `nullValue`. | Value | $matcher->likeOrNull('Fred')

### Combining matchers with OR

> [!NOTE]
> This requires pact_ffi TODO(version with pact-foundation/pact-reference#601) or later. Older versions combine the
> matchers with AND, so a value can never match both `like` and `nullValue`.

`matchAny` applies several matchers to the same value, and the value matches if at least one of them matches. The
first argument is the example value, the second is the list of alternatives.

```php
$matcher = new Matcher();

$response = new ProviderResponse();
$response
->setStatus(200)
->addHeader('Content-Type', 'application/json')
->setBody([
// A string, or null
'nickname' => $matcher->likeOrNull('Fred'),
// A string of digits, or 'unknown'
'age' => $matcher->matchAny('42', [
$matcher->regex(null, '^\d+$'),
$matcher->regex(null, '^unknown$'),
]),
// An object, or null. The matchers inside the object still apply when it is not null.
'address' => $matcher->matchAny(
[
'street' => 'Main St',
'number' => $matcher->integerV3(42),
],
[
$matcher->like(null),
$matcher->nullValue(),
]
),
]);
```

`'address'` is written to the pact file as:

```json
"$.address": {
"combine": "OR",
"matchers": [{ "match": "type" }, { "match": "null" }]
},
"$.address.number": {
"combine": "AND",
"matchers": [{ "match": "integer" }]
}
```

`matchAny` works for bodies, headers and query parameters.

Things to keep in mind:

* Only the example value is used in the consumer test: the mock server always returns it, so your consumer code is
never tested with the other alternatives (e.g. with `null`). Write a separate test (or interaction) if your code has to
handle them.
* Every alternative is checked against the actual value, using the example value as the expected value. So matchers
that compare with the expected value (like `like` or `equal`) can only describe the example value. For example,
`$matcher->matchAny('10', [$matcher->regex(null, '^\d+$'), $matcher->equal('all')])` does not accept `'all'`, use
`$matcher->regex(null, '^all$')` instead.
* Put all the alternatives in the list of matchers. The example value can not be a matcher, and `matchAll`/`matchAny`
can not be nested.
* `matchAny` is not supported by plugins (matching expressions can not combine matchers with OR).

See [example/or-matcher](../example/or-matcher) for a full example.

## Build the Interaction

Expand Down
6 changes: 6 additions & 0 deletions example/or-matcher/consumer/autoload.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?php

/** @var Composer\Autoload\ClassLoader $loader */
$loader = require __DIR__ . '/../../../vendor/autoload.php';
$loader->addPsr4('OrMatcherConsumer\\', __DIR__ . '/src');
$loader->addPsr4('OrMatcherConsumer\\Tests\\', __DIR__ . '/tests');
11 changes: 11 additions & 0 deletions example/or-matcher/consumer/phpunit.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="./autoload.php" colors="true">
<testsuites>
<testsuite name="PhpPact Example Tests">
<directory>./tests</directory>
</testsuite>
</testsuites>
<php>
<env name="PACT_LOGLEVEL" value="DEBUG"/>
</php>
</phpunit>
29 changes: 29 additions & 0 deletions example/or-matcher/consumer/src/Service/HttpClientService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

namespace OrMatcherConsumer\Service;

use GuzzleHttp\Client;
use Psr\Http\Message\ResponseInterface;

class HttpClientService
{
private Client $httpClient;

public function __construct(private string $baseUri)
{
$this->httpClient = new Client();
}

/**
* @param array<string, mixed> $user
*/
public function updateUser(array $user, string $limit, string $apiVersion): ResponseInterface
{
return $this->httpClient->put("{$this->baseUri}/users/1", [
'headers' => ['Accept' => 'application/json', 'X-Api-Version' => $apiVersion],
'query' => ['limit' => $limit],
'json' => $user,
'http_errors' => false,
]);
}
}
187 changes: 187 additions & 0 deletions example/or-matcher/consumer/tests/Service/OrMatcherTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
<?php

namespace OrMatcherConsumer\Tests\Service;

use OrMatcherConsumer\Service\HttpClientService;
use PhpPact\Consumer\InteractionBuilder;
use PhpPact\Consumer\Matcher\Matcher;
use PhpPact\Consumer\Model\ConsumerRequest;
use PhpPact\Consumer\Model\ProviderResponse;
use PhpPact\Standalone\MockService\MockServerConfig;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;

class OrMatcherTest extends TestCase
{
private Matcher $matcher;
private MockServerConfig $config;
private InteractionBuilder $builder;

public function setUp(): void
{
$this->matcher = new Matcher();

$request = new ConsumerRequest();
$request
->setMethod('PUT')
->setPath('/users/1')
// A query value that is either a number, or 'all'.
// Every alternative is checked against the example value ('10'), so `equal('all')` would not work here.
->addQueryParameter('limit', $this->matcher->matchAny('10', [
$this->matcher->regex(null, '^\d+$'),
$this->matcher->regex(null, '^all$'),
]))
// A header value that is either a number, or 'latest'
->addHeader('X-Api-Version', $this->matcher->matchAny('2', [
$this->matcher->regex(null, '^\d+$'),
$this->matcher->regex(null, '^latest$'),
]))
->addHeader('Content-Type', 'application/json')
->setBody([
// A string, or null
'nickname' => $this->matcher->likeOrNull('Fred'),
// An object, or null. The rules inside the object still apply when it is not null.
'address' => $this->matcher->likeOrNull([
'street' => 'Main St',
'number' => $this->matcher->integerV3(42),
]),
]);

$response = new ProviderResponse();
$response
->setStatus(200)
->addHeader('Content-Type', 'application/json')
->setBody([
'id' => $this->matcher->integerV3(1),
'nickname' => $this->matcher->likeOrNull('Fred'),
// Same as `likeOrNull`, using `matchAny` and `nullValue` directly
'address' => $this->matcher->matchAny(
[
'street' => 'Main St',
'number' => $this->matcher->integerV3(42),
],
[
$this->matcher->like(null),
$this->matcher->nullValue(),
]
),
]);

$this->config = new MockServerConfig();
$this->config
->setConsumer('orMatcherConsumer')
->setProvider('orMatcherProvider')
->setPactDir(__DIR__.'/../../../pacts')
->setPactSpecificationVersion('4.0.0');
if ($logLevel = \getenv('PACT_LOGLEVEL')) {
$this->config->setLogLevel($logLevel);
}
$this->builder = new InteractionBuilder($this->config);
$this->builder
->uponReceiving('A put request to /users/{id}')
->with($request)
->willRespondWith($response);
}

/**
* @return iterable<string, array{array<string, mixed>, string, string}>
*/
public static function matchingRequests(): iterable
{
yield 'example values' => [['nickname' => 'Fred', 'address' => ['street' => 'Main St', 'number' => 42]], '10', '2'];
yield 'first alternatives' => [['nickname' => 'Bob', 'address' => ['street' => 'High St', 'number' => 7]], '25', '3'];
yield 'second alternatives' => [['nickname' => null, 'address' => null], 'all', 'latest'];
}

/**
* @param array<string, mixed> $user
*/
#[DataProvider('matchingRequests')]
public function testMatchingRequest(array $user, string $limit, string $apiVersion): void
{
$service = new HttpClientService($this->config->getBaseUri());
$response = $service->updateUser($user, $limit, $apiVersion);
$verifyResult = $this->builder->verify();

$this->assertTrue($verifyResult);
$this->assertSame(200, $response->getStatusCode());
// Only the example value is returned by the mock server, so the consumer code is only tested with it.
$this->assertEquals([
'id' => 1,
'nickname' => 'Fred',
'address' => ['street' => 'Main St', 'number' => 42],
], \json_decode($response->getBody(), true, 512, JSON_THROW_ON_ERROR));

$this->assertPactFileHasOrRules();
}

/**
* @return iterable<string, array{array<string, mixed>, string, string}>
*/
public static function nonMatchingRequests(): iterable
{
$user = ['nickname' => 'Fred', 'address' => ['street' => 'Main St', 'number' => 42]];
yield 'nickname is neither a string nor null' => [['nickname' => 123] + $user, '10', '2'];
yield 'address is neither an object nor null' => [['address' => 'nowhere'] + $user, '10', '2'];
yield 'address number is not an integer' => [['address' => ['street' => 'Main St', 'number' => '42']] + $user, '10', '2'];
yield 'limit is neither a number nor all' => [$user, 'many', '2'];
yield 'api version is neither a number nor latest' => [$user, '10', 'beta'];
}

/**
* @param array<string, mixed> $user
*/
#[DataProvider('nonMatchingRequests')]
public function testNonMatchingRequest(array $user, string $limit, string $apiVersion): void
{
$service = new HttpClientService($this->config->getBaseUri());
$response = $service->updateUser($user, $limit, $apiVersion);
$verifyResult = $this->builder->verify();

$this->assertFalse($verifyResult);
$this->assertSame(500, $response->getStatusCode());
}

private function assertPactFileHasOrRules(): void
{
$pactFile = $this->config->getPactDir() . '/orMatcherConsumer-orMatcherProvider.json';
$this->assertFileExists($pactFile);
$pact = \json_decode((string) \file_get_contents($pactFile), true, 512, JSON_THROW_ON_ERROR);
$this->assertIsArray($pact);
$this->assertIsArray($pact['interactions']);
$this->assertCount(1, $pact['interactions']);
$interaction = $pact['interactions'][0];
$this->assertIsArray($interaction);
$this->assertIsArray($interaction['request']);
$this->assertIsArray($interaction['response']);

$typeOrNull = ['combine' => 'OR', 'matchers' => [['match' => 'type'], ['match' => 'null']]];
$numberOr = static fn (string $regex): array => [
'combine' => 'OR',
'matchers' => [['match' => 'regex', 'regex' => '^\d+$'], ['match' => 'regex', 'regex' => $regex]],
];

$this->assertEquals([
'body' => [
'$.nickname' => $typeOrNull,
'$.address' => $typeOrNull,
'$.address.number' => ['combine' => 'AND', 'matchers' => [['match' => 'integer']]],
],
'header' => [
'X-Api-Version' => $numberOr('^latest$'),
],
'query' => [
'limit' => $numberOr('^all$'),
],
], $interaction['request']['matchingRules'] ?? null);

$this->assertEquals([
'body' => [
'$.id' => ['combine' => 'AND', 'matchers' => [['match' => 'integer']]],
'$.nickname' => $typeOrNull,
'$.address' => $typeOrNull,
'$.address.number' => ['combine' => 'AND', 'matchers' => [['match' => 'integer']]],
],
], $interaction['response']['matchingRules'] ?? null);
}
}
Loading
Loading