2022-01-17 16:02:15 +01:00
|
|
|
<?php
|
|
|
|
|
|
|
|
declare(strict_types=1);
|
|
|
|
|
|
|
|
namespace App\Test\Helper;
|
|
|
|
|
|
|
|
use \WireMock\Client\WireMock;
|
2022-01-27 15:43:33 +01:00
|
|
|
use \WireMock\Client\ValueMatchingStrategy;
|
|
|
|
use \WireMock\Client\RequestPatternBuilder;
|
|
|
|
use \WireMock\Stubbing\StubMapping;
|
2022-01-17 16:02:15 +01:00
|
|
|
|
|
|
|
trait WireMockTestTrait
|
|
|
|
{
|
|
|
|
/** @var WireMock */
|
|
|
|
private $wiremock;
|
|
|
|
|
|
|
|
/** @var array<mixed> */
|
2023-04-06 18:00:46 +02:00
|
|
|
private $config;
|
2022-01-17 16:02:15 +01:00
|
|
|
|
|
|
|
public function initializeWireMock(): void
|
|
|
|
{
|
2023-04-06 18:00:46 +02:00
|
|
|
$this->config = [
|
|
|
|
'hostname' => $_ENV['WIREMOCK_HOST'] ?? 'localhost',
|
|
|
|
'port' => $_ENV['WIREMOCK_PORT'] ?? 8080
|
|
|
|
];
|
|
|
|
|
2022-01-17 16:02:15 +01:00
|
|
|
$this->wiremock = WireMock::create(
|
2023-04-06 18:00:46 +02:00
|
|
|
$this->config['hostname'],
|
|
|
|
$this->config['port']
|
2022-01-17 16:02:15 +01:00
|
|
|
);
|
|
|
|
|
|
|
|
if (!$this->wiremock->isAlive()) {
|
2022-01-27 15:43:33 +01:00
|
|
|
throw new \Exception('Failed to connect to WireMock server.');
|
2022-01-17 16:02:15 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
$this->clearWireMockStubs();
|
|
|
|
}
|
|
|
|
|
|
|
|
public function clearWireMockStubs(): void
|
|
|
|
{
|
|
|
|
$this->wiremock->resetToDefault();
|
|
|
|
}
|
|
|
|
|
|
|
|
public function getWireMock(): WireMock
|
|
|
|
{
|
|
|
|
return $this->wiremock;
|
|
|
|
}
|
|
|
|
|
|
|
|
public function getWireMockBaseUrl(): string
|
|
|
|
{
|
|
|
|
return sprintf('http://%s:%s', $this->config['hostname'], $this->config['port']);
|
|
|
|
}
|
2022-01-27 15:43:33 +01:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Verify all WireMock stubs were called.
|
|
|
|
*
|
|
|
|
* @return void
|
|
|
|
*/
|
|
|
|
public function verifyAllStubsCalled(): void
|
|
|
|
{
|
|
|
|
$stubs = $this->wiremock->listAllStubMappings()->getMappings();
|
|
|
|
foreach ((array)$stubs as $stub) {
|
|
|
|
$this->verifyStubCalled($stub);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Verify the WireMock stub was called.
|
|
|
|
*
|
|
|
|
* @param StubMapping $stub
|
|
|
|
* @return void
|
|
|
|
*/
|
|
|
|
public function verifyStubCalled(StubMapping $stub): void
|
|
|
|
{
|
|
|
|
$validator = new RequestPatternBuilder($stub->getRequest()->getMethod(), $stub->getRequest()->getUrlMatchingStrategy());
|
|
|
|
|
|
|
|
// validate headers
|
|
|
|
$headers = $stub->getRequest()->getHeaders();
|
|
|
|
if (is_array($headers)) {
|
|
|
|
foreach ($headers as $header => $rule) {
|
2022-05-17 09:28:26 +02:00
|
|
|
$validator = $validator->withHeader($header, $rule);
|
2022-01-27 15:43:33 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// TODO: Add body matching
|
|
|
|
// TODO: Add query matching
|
|
|
|
// TODO: Add cookie matching
|
|
|
|
|
|
|
|
$this->wiremock->verify($validator);
|
|
|
|
}
|
2022-01-17 16:02:15 +01:00
|
|
|
}
|