Skip to content

Commit

Permalink
chore: Add generators example
Browse files Browse the repository at this point in the history
  • Loading branch information
tienvx committed Nov 29, 2023
1 parent 0d4e29d commit ea31ea3
Show file tree
Hide file tree
Showing 8 changed files with 505 additions and 1 deletion.
5 changes: 4 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,10 @@
"XmlProvider\\Tests\\": "example/xml/provider/tests",
"MatchersConsumer\\": "example/matchers/consumer/src",
"MatchersConsumer\\Tests\\": "example/matchers/consumer/tests",
"MatchersProvider\\Tests\\": "example/matchers/provider/tests"
"MatchersProvider\\Tests\\": "example/matchers/provider/tests",
"GeneratorsConsumer\\": "example/generators/consumer/src",
"GeneratorsConsumer\\Tests\\": "example/generators/consumer/tests",
"GeneratorsProvider\\Tests\\": "example/generators/provider/tests"
}
},
"scripts": {
Expand Down
11 changes: 11 additions & 0 deletions example/generators/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="../../../vendor/autoload.php" colors="true">
<testsuites>
<testsuite name="PhpPact Example Tests">
<directory>./tests</directory>
</testsuite>
</testsuites>
<php>
<env name="PACT_LOGLEVEL" value="DEBUG"/>
</php>
</phpunit>
28 changes: 28 additions & 0 deletions example/generators/consumer/src/Service/HttpClientService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

namespace GeneratorsConsumer\Service;

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

class HttpClientService
{
private Client $httpClient;

private string $baseUri;

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

private function sendRequest(): ResponseInterface
{
return $this->httpClient->get("{$this->baseUri}/generators", [
'headers' => ['Accept' => 'application/json'],
'json' => ['id' => 112],
'http_errors' => false,
]);
}
}
103 changes: 103 additions & 0 deletions example/generators/consumer/tests/Service/GeneratorsTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
<?php

namespace GeneratorsConsumer\Tests\Service;

use DateTime;
use GeneratorsConsumer\Service\HttpClientService;
use PhpPact\Consumer\InteractionBuilder;
use PhpPact\Consumer\Matcher\HttpStatus;
use PhpPact\Consumer\Matcher\Matcher;
use PhpPact\Consumer\Model\ConsumerRequest;
use PhpPact\Consumer\Model\ProviderResponse;
use PhpPact\Standalone\MockService\MockServerConfig;
use PHPUnit\Framework\TestCase;

class GeneratorsTest extends TestCase
{
private Matcher $matcher;

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

public function testGetMatchers()
{
$request = new ConsumerRequest();
$request
->setMethod('GET')
->setPath('/generators')
->addHeader('Accept', 'application/json')
->setBody([
'id' => $this->matcher->fromProviderState($this->matcher->integer(111), '${id}')
]);

$response = new ProviderResponse();
$response
->setStatus($this->matcher->statusCode(HttpStatus::CLIENT_ERROR))
->addHeader('Content-Type', 'application/json')
->setBody([
'regex' => $this->matcher->regex(null, $regexNoAnchors = '\d+ (miles|kilometers)'),
'boolean' => $this->matcher->booleanV3(null),
'integer' => $this->matcher->integerV3(null),
'decimal' => $this->matcher->decimalV3(null),
'hexadecimal' => $this->matcher->hexadecimal(null),
'uuid' => $this->matcher->uuid(null),
'date' => $this->matcher->date('yyyy-MM-dd', null),
'time' => $this->matcher->time('HH:mm::ss', null),
'datetime' => $this->matcher->datetime("YYYY-MM-D'T'HH:mm:ss", null),
'string' => $this->matcher->string(null),
'number' => $this->matcher->number(null),
]);

$config = new MockServerConfig();
$config
->setConsumer('generatorsConsumer')
->setProvider('generatorsProvider')
->setPactDir(__DIR__.'/../../../pacts')
->setPactSpecificationVersion('4.0.0');
if ($logLevel = \getenv('PACT_LOGLEVEL')) {
$config->setLogLevel($logLevel);
}
$builder = new InteractionBuilder($config);
$builder
->given('Get Generators')
->uponReceiving('A get request to /generators')
->with($request)
->willRespondWith($response);

$service = new HttpClientService($config->getBaseUri());
$response = $service->sendRequest();
$verifyResult = $builder->verify();

$statusCode = $response->getStatusCode();
$body = \json_decode($response->getBody(), true, 512, JSON_THROW_ON_ERROR);

$this->assertTrue($verifyResult);
$this->assertThat(
$statusCode,
$this->logicalAnd(
$this->greaterThanOrEqual(400),
$this->lessThanOrEqual(499)
)
);
$this->assertMatchesRegularExpression('/^' . $regexNoAnchors . '$/', $body['regex']);
$this->assertIsBool($body['boolean']);
$this->assertIsInt($body['integer']);
$this->assertIsFloat($body['decimal'] + 0);
$this->assertMatchesRegularExpression('/' . Matcher::HEX_FORMAT . '/', $body['hexadecimal']);
$this->assertMatchesRegularExpression('/' . Matcher::UUID_V4_FORMAT . '/', $body['uuid']);
$this->assertTrue($this->validateDateTime($body['date'], 'Y-m-d'));
$this->assertTrue($this->validateDateTime($body['time'], 'H:i::s'));
$this->assertTrue($this->validateDateTime($body['datetime'], "Y-m-z\TH:i:s"));
$this->assertIsString($body['string']);
$this->assertIsNumeric($body['number']);
}

private function validateDateTime(string $datetime, string $format): bool
{
$value = DateTime::createFromFormat($format, $datetime);

return $value && $value->format($format) === $datetime;
}
}
Loading

0 comments on commit ea31ea3

Please sign in to comment.