1. Go to this page and download the library: Download waylandace/pact-php library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
waylandace / pact-php example snippets
use PhpPact\Standalone\MockService\MockServer;
use PhpPact\Standalone\MockService\MockServerConfig;
// Create your basic configuration. The host and port will need to match
// whatever your Http Service will be using to access the providers data.
$config = new MockServerConfig();
$config->setHost('localhost');
$config->setPort(7200);
$config->setConsumer('someConsumer');
$config->setProvider('someProvider');
$config->setCors(true);
// Instantiate the mock server object with the config. This can be any
// instance of MockServerConfigInterface.
$server = new MockServer($config);
// Create the process.
$server->start();
// Stop the process.
$server->stop();
$request = new ConsumerRequest();
$request
->setMethod('GET')
->setPath('/hello/Bob')
->addHeader('Content-Type', 'application/json');
$matcher = new Matcher();
$response = new ProviderResponse();
$response
->setStatus(200)
->addHeader('Content-Type', 'application/json')
->setBody([
'message' => $matcher->regex('Hello, Bob', '(Hello, )[A-Za-z]')
]);
// Create a configuration that reflects the server that was started. You can
// create a custom MockServerConfigInterface if needed. This configuration
// is the same that is used via the PactTestListener and uses environment variables.
$config = new MockServerEnvConfig();
$builder = new InteractionBuilder($config);
$builder
->given('a person exists')
->uponReceiving('a get request to /hello/{name}')
->with($request)
->willRespondWith($response); // This has to be last. This is what makes an API request to the Mock Server to set the interaction.
$service = new HttpClientService($config->getBaseUri()); // Pass in the URL to the Mock Server.
$result = $service->getHelloString('Bob'); // Make the real API request against the Mock Server.
$builder->verify();
$this->assertEquals('Hello, Bob', $result); // Make your assertions.
$config = new VerifierConfig();
$config
->setProviderName('someProvider') // Providers name to fetch.
->setProviderVersion('1.0.0') // Providers version.
->setProviderBranch('main') // Providers git branch name.
->setProviderBaseUrl(new Uri('http://localhost:58000')) // URL of the Provider.
->setBrokerUri(new Uri('http://localhost')) // URL of the Pact Broker to publish results.
->setPublishResults(true) // Flag the verifier service to publish the results to the Pact Broker.
->setProcessTimeout(60) // Set process timeout (optional) - default 60
->setProcessIdleTimeout(10) // Set process idle timeout (optional) - default 10
->setEnablePending(true) // Flag to enable pending pacts feature (check pact docs for further info)
->setIncludeWipPactSince('2020-01-30') //Start date of WIP Pacts (check pact docs for further info)
->setRequestFilter(
function (RequestInterface $r) {
return $r->withHeader('MY_SPECIAL_HEADER', 'my special value');
}
);
// Verify that the Consumer 'someConsumer' that is tagged with 'master' is valid.
$verifier = new Verifier($config);
$verifier->verify('someConsumer', 'master'); // The tag is option. If no tag is set it will just grab the latest.
// This will not be reached if the PACT verifier throws an error, otherwise it was successful.
$this->assertTrue(true, 'Pact Verification has failed.');
public function testPactVerifyAll()
{
$config = new VerifierConfig();
$config
->setProviderName('someProvider') // Providers name to fetch.
->setProviderVersion('1.0.0') // Providers version.
->setProviderBranch('main') // Providers git branch name.
->setProviderBaseUrl(new Uri('http://localhost:58000')) // URL of the Provider.
->setBrokerUri(new Uri('http://localhost')) // URL of the Pact Broker to publish results.
->setPublishResults(true) // Flag the verifier service to publish the results to the Pact Broker.
->setEnablePending(true) // Flag to enable pending pacts feature (check pact docs for further info)
->setIncludeWipPactSince('2020-01-30') //Start date of WIP Pacts (check pact docs for further info)
// Verify that all consumers of 'someProvider' are valid.
$verifier = new Verifier($config);
$verifier->verifyAll();
// This will not be reached if the PACT verifier throws an error, otherwise it was successful.
$this->assertTrue(true, 'Pact Verification has failed.');
}
public function testPactVerifyAll()
{
$config = new VerifierConfig();
$config
->setProviderName('someProvider') // Providers name to fetch.
->setProviderVersion('1.0.0') // Providers version.
->setProviderBranch('main') // Providers git branch name.
->setProviderBaseUrl(new Uri('http://localhost:58000')) // URL of the Provider.
->setBrokerUri(new Uri('http://localhost')) // URL of the Pact Broker to publish results.
->setPublishResults(true); // Flag the verifier service to publish the results to the Pact Broker.
->setEnablePending(true) // Flag to enable pending pacts feature (check pact docs for further info)
->setIncludeWipPactSince('2020-01-30') //Start date of WIP Pacts (check pact docs for further info)
// Verify that the files in the array are valid.
$verifier = new Verifier($config);
$verifier->verifyFiles(['C:\SomePath\consumer-provider.json']);
// This will not be reached if the PACT verifier throws an error, otherwise it was successful.
$this->assertTrue(true, 'Pact Verification has failed.');
}
$builder = new MessageBuilder(self::$config);
$contents = new \stdClass();
$contents->song = 'And the wind whispers Mary';
$metadata = ['queue'=>'And the clowns have all gone to bed', 'routing_key'=>'And the clowns have all gone to bed'];
$builder
->given('You can hear happiness staggering on down the street')
->expectsToReceive('footprints dressed in red')
->withMetadata($metadata)
->withContent($contents);
// established mechanism to this via callbacks
$consumerMessage = new ExampleMessageConsumer();
$callback = [$consumerMessage, 'ProcessSong'];
$builder->setCallback($callback);
$builder->verify();
$callbacks = array();
// a hello message is a provider state / given() on the consumer side
$callbacks["a hello message"] = function() {
$content = new \stdClass();
$content->text ="Hello Mary";
$metadata = array();
$metadata['queue'] = "myKey";
$provider = (new ExampleMessageProvider())
->setContents($content)
->setMetadata($metadata);
return $provider->Build();
};
$verifier = (new MessageVerifier($config))
->setCallbacks($callbacks)
->verifyFiles([__DIR__ . '/../../output/test_consumer-test_provider.json']);