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
22 changes: 16 additions & 6 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,8 @@
"composer run-example:xml",
"composer run-example:graphql",
"composer run-example:form-urlencoded",
"composer run-example:server-sent-events"
"composer run-example:server-sent-events",
"composer run-example:repeated-headers"
],
"run-examples:windows": [
"composer run-example:binary:windows",
Expand All @@ -102,7 +103,8 @@
"composer run-example:xml:windows",
"composer run-example:graphql:windows",
"composer run-example:form-urlencoded:windows",
"composer run-example:server-sent-events:windows"
"composer run-example:server-sent-events:windows",
"composer run-example:repeated-headers:windows"
],
"run-example:binary:windows": [
"powershell -Command \"if (Test-Path 'example/binary/pacts/binaryConsumer-binaryProvider.json') { Remove-Item 'example/binary/pacts/binaryConsumer-binaryProvider.json' }\"",
Expand Down Expand Up @@ -239,25 +241,33 @@
"rm -f example/server-sent-events/pacts/sseConsumer-sseProvider.json",
"cd example/server-sent-events/consumer && phpunit",
"cd example/server-sent-events/provider && phpunit"
],
"run-example:repeated-headers:windows": [
"powershell -Command \"if (Test-Path 'example/repeated-headers/pacts/repeatedHeadersConsumer-repeatedHeadersProvider.json') { Remove-Item 'example/repeated-headers/pacts/repeatedHeadersConsumer-repeatedHeadersProvider.json' }\"",
"cd example/repeated-headers/consumer && phpunit --process-isolation"
],
"run-example:repeated-headers": [
"rm -f example/repeated-headers/pacts/repeatedHeadersConsumer-repeatedHeadersProvider.json",
"cd example/repeated-headers/consumer && phpunit"
]
},
"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-rc.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-rc.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
6 changes: 6 additions & 0 deletions example/repeated-headers/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('RepeatedHeadersConsumer\\', __DIR__ . '/src');
$loader->addPsr4('RepeatedHeadersConsumer\\Tests\\', __DIR__ . '/tests');
8 changes: 8 additions & 0 deletions example/repeated-headers/consumer/phpunit.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="./autoload.php" colors="true">
<testsuites>
<testsuite name="PhpPact Example Tests">
<directory>./tests</directory>
</testsuite>
</testsuites>
</phpunit>
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<?php

namespace RepeatedHeadersConsumer\Service;

use Psr\Http\Message\UriInterface;
use RuntimeException;

/**
* Sends a request with each header field line written exactly as given.
*
* HTTP clients such as Guzzle merge, reorder or reject repeated header lines,
* so the request is written to a plain TCP socket instead.
*/
class HttpClientService
{
public function __construct(private UriInterface $baseUri)
{
}

/**
* @param array<array{string, string}> $fieldLines list of [name, value] pairs, one per field line
*
* @return int the response status code
*/
public function getHeaders(array $fieldLines): int
{
$host = $this->baseUri->getHost();
$port = (int) $this->baseUri->getPort();
$socket = stream_socket_client("tcp://{$host}:{$port}", $errorCode, $errorMessage, 5);
if ($socket === false) {
throw new RuntimeException(sprintf('Can not connect to %s:%d: %s (%d)', $host, $port, $errorMessage, $errorCode));
}

try {
stream_set_timeout($socket, 5);
$request = "GET /headers HTTP/1.1\r\n";
$request .= "Host: {$host}:{$port}\r\n";
foreach ($fieldLines as [$name, $value]) {
$request .= "{$name}: {$value}\r\n";
}
$request .= "Connection: close\r\n\r\n";
fwrite($socket, $request);

$statusLine = fgets($socket);
if ($statusLine === false || !preg_match('/^HTTP\/1\.[01] (\d{3})/', $statusLine, $matches)) {
throw new RuntimeException(sprintf('Invalid status line: %s', var_export($statusLine, true)));
}
// Drain the rest of the response so the mock server finishes handling the request.
stream_get_contents($socket);

return (int) $matches[1];
} finally {
fclose($socket);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
<?php

namespace RepeatedHeadersConsumer\Tests\Service;

use PhpPact\Consumer\InteractionBuilder;
use PhpPact\Consumer\Matcher\Matcher;
use PhpPact\Consumer\Matcher\Model\MatcherInterface;
use PhpPact\Consumer\Model\ConsumerRequest;
use PhpPact\Consumer\Model\ProviderResponse;
use PhpPact\Log\Enum\LogLevel;
use PhpPact\Log\Logger;
use PhpPact\Log\Model\Buffer;
use PhpPact\Standalone\MockService\MockServerConfig;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
use RepeatedHeadersConsumer\Service\HttpClientService;

/**
* Repeated request headers, matched by the mock server following RFC 9110 §5.3:
* a header sent as several field lines is equivalent to one line with the
* values joined by ", ".
*
* The expected values are added one per index, by passing an array to `addHeader`.
* The request is sent over a raw socket so that each field line reaches the
* mock server as written.
*/
class RepeatedHeadersTest extends TestCase
{
private const DEPRECATION_WARNING = 'RFC 9110 §5.3';

private static Matcher $matcher;

public static function setUpBeforeClass(): void
{
self::$matcher = new Matcher();

// Capture the FFI logs in memory, so the tests can assert on warnings.
// The buffer sink must be applied before any mock server is started.
$logger = Logger::instance();
$logger->attach(new Buffer(LogLevel::WARN));
$logger->apply();
}

/**
* @return iterable<string, array{string, array<MatcherInterface|string>, array<array{string, string}>, bool}>
*/
public static function repeatedHeaderProvider(): iterable
{
yield 'H1 two field lines match two values' => [
'X-Request',
['a', 'b'],
[['X-Request', 'a'], ['X-Request', 'b']],
true,
];
yield 'H2 one comma-joined field line matches two values' => [
'X-Request',
['a', 'b'],
[['X-Request', 'a, b']],
true,
];
yield 'H3 values containing commas, one per field line' => [
'X-Sunset',
['Sat, 01 Jan 2028 00:00:00 GMT', 'Sun, 02 Jan 2028 00:00:00 GMT'],
[['X-Sunset', 'Sat, 01 Jan 2028 00:00:00 GMT'], ['X-Sunset', 'Sun, 02 Jan 2028 00:00:00 GMT']],
true,
];
yield 'H4 Content-Type is not a list, so a comma-joined line does not match' => [
'Content-Type',
['text/plain', 'text/html'],
[['Content-Type', 'text/plain, text/html']],
false,
];
yield 'H5 Cache-Control comma-joined field line matches two values' => [
'Cache-Control',
['no-cache', 'no-store'],
[['Cache-Control', 'no-cache, no-store']],
true,
];
yield 'H8a Link values containing commas, one per field line' => [
'Link',
['<https://a.example/x,y>; rel="a"', '<https://b.example/>; rel="b"'],
[['Link', '<https://a.example/x,y>; rel="a"'], ['Link', '<https://b.example/>; rel="b"']],
true,
];
yield 'H8b Link values containing commas, one comma-joined field line' => [
'Link',
['<https://a.example/x,y>; rel="a"', '<https://b.example/>; rel="b"'],
[['Link', '<https://a.example/x,y>; rel="a", <https://b.example/>; rel="b"']],
true,
];
}

/**
* @param array<MatcherInterface|string> $expectedValues
* @param array<array{string, string}> $fieldLines
*/
#[DataProvider('repeatedHeaderProvider')]
public function testRepeatedHeader(string $header, array $expectedValues, array $fieldLines, bool $shouldMatch): void
{
[$status, $matched, $mismatches] = $this->runInteraction((string) $this->dataName(), $header, $expectedValues, $fieldLines);

if ($shouldMatch) {
$this->assertSame(200, $status);
$this->assertTrue($matched, $mismatches);
} else {
$this->assertNotSame(200, $status);
$this->assertFalse($matched);
$this->assertNotEmpty(json_decode($mismatches, true), $mismatches);
}
}

public function testH6aRegexMatcherPerIndexMatchesWithoutWarning(): void
{
$regex = '^first-\d+$';
[$status, $matched, $mismatches, $logs] = $this->runInteraction(
'H6a one regex matcher per index',
'X-Request',
[self::$matcher->regex('first-1', $regex), self::$matcher->regex('first-2', $regex)],
[['X-Request', 'first-42'], ['X-Request', 'first-99']],
);

$this->assertSame(200, $status);
$this->assertTrue($matched, $mismatches);
$this->assertStringNotContainsString(self::DEPRECATION_WARNING, $logs);
}

/**
* Whitespace inside a quoted-string is literal (RFC 9110 §5.6.4), so the
* expected `"x , y"` does not match the sent `"x, y"`, and there is no
* per-line fallback that would log the deprecation warning.
*/
public function testH6bQuotedValueWhitespaceIsLiteralAndDoesNotMatch(): void
{
[$status, $matched, $mismatches, $logs] = $this->runInteraction(
'H6b quoted value containing a comma, one per field line',
'X-Request',
['"x , y"', 'z'],
[['X-Request', '"x, y"'], ['X-Request', 'z']],
);

$this->assertNotSame(200, $status);
$this->assertFalse($matched);
$this->assertNotEmpty(json_decode($mismatches, true), $mismatches);
$this->assertStringNotContainsString(self::DEPRECATION_WARNING, $logs);
}

/**
* @param array<MatcherInterface|string> $expectedValues
* @param array<array{string, string}> $fieldLines
*
* @return array{int, bool, string, string} status, matched, mismatches, mock server logs
*/
private function runInteraction(string $description, string $header, array $expectedValues, array $fieldLines): array
{
$request = new ConsumerRequest();
$request
->setMethod('GET')
->setPath('/headers')
->addHeader($header, $expectedValues);

$response = new ProviderResponse();
$response->setStatus(200);

$config = new MockServerConfig();
$config
->setConsumer('repeatedHeadersConsumer')
->setProvider('repeatedHeadersProvider')
->setPactSpecificationVersion('3.0.0')
->setPactDir(__DIR__ . '/../../../pacts');

$builder = new InteractionBuilder($config);
$builder
->uponReceiving($description)
->with($request)
->willRespondWith($response);

$status = (new HttpClientService($config->getBaseUri()))->getHeaders($fieldLines);

// The mock server is cleaned up by `verify()`. Its mismatches and logs (it logs
// to its own buffer, not the one returned by `Logger::fetchBuffer()`) are kept
// in the verify result.
$matched = $builder->verify();
$result = $builder->getVerifyResult();
$this->assertNotNull($result);

return [$status, $matched, $result->mismatches, $result->logs];
}
}
Loading
Loading