Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

PHP version of Pact. Enables consumer driven contract testing, providing a mock service and DSL for the consumer project, and interaction playback and verification for the service provider project

License

NotificationsYou must be signed in to change notification settings

pact-foundation/pact-php

Repository files navigation

logo

Pact PHP

Code Analysis & TestCoverage StatusCompatibility SuitePackagist

DownloadsDownloads This Month

Fast, easy and reliable testing for your APIs and microservices.


Pact PHP Demo


Pact is the de-facto API contract testing tool. Replace expensive and brittle end-to-end integration tests with fast, reliable and easy to debug unit tests.

  • ⚡ Lightning fast
  • 🎈 Effortless full-stack integration testing - from the front-end to the back-end
  • 🔌 Supports HTTP/REST and event-driven systems
  • 🛠️ Configurable mock server
  • 😌 Powerful matching rules prevents brittle tests
  • 🤝 Integrates with Pact Broker / PactFlow for powerful CI/CD workflows
  • 🔡 Supports 12+ languages

Why use Pact?

Contract testing with Pact lets you:

  • ⚡ Test locally
  • 🚀 Deploy faster
  • ⬇️ Reduce the lead time for change
  • 💰 Reduce the cost of API integration testing
  • 💥 Prevent breaking changes
  • 🔎 Understand your system usage
  • 📃 Document your APIs for free
  • 🗄 Remove the need for complex data fixtures
  • 🤷‍♂️ Reduce the reliance on complex test environments

Watch ourseries on the problems with end-to-end integrated tests, and how contract testing can help.

----------

Documentation

This readme offers a basic introduction to the library. The full documentation for Pact PHP and the rest of the framework is available athttps://docs.pact.io/.

Need Help

Installation

composer require pact-foundation/pact-php --dev# 🚀 now write some tests!

Looking for the previousstable 9.x.x release?

Requirements

PHP 8.1+ as of pact-php v10

Do Not Track

In order to get better statistics as to who is using Pact, we have an anonymous tracking event that triggers when Pact installs for the first time. The only things wetrack are your type of OS, and the version information for the package being installed. No PII data is sent as part of this request. You can disable tracking by setting the environment variablePACT_DO_NOT_TRACK=true:

----------

Usage

Writing a Consumer test

namespaceApp\Tests;useApp\Service\HttpClientService;usePhpPact\Consumer\InteractionBuilder;usePhpPact\Consumer\Matcher\Matcher;usePhpPact\Consumer\Model\ConsumerRequest;usePhpPact\Consumer\Model\ProviderResponse;usePhpPact\Standalone\MockService\MockServerConfig;usePHPUnit\Framework\TestCase;class ConsumerServiceHelloTestextends TestCase{publicfunctiontestGetHelloString():void    {$matcher =newMatcher();// Create your expected request from the consumer.$request =newConsumerRequest();$request            ->setMethod('GET')            ->setPath('/hello/Bob')            ->addHeader('Content-Type','application/json');// Create your expected response from the provider.$response =newProviderResponse();$response            ->setStatus(200)            ->addHeader('Content-Type','application/json')            ->setBody(['message' =>$matcher->term('Hello, Bob','(Hello, )[A-Za-z]+')            ]);// Create a configuration that reflects the server that was started. You can create a custom MockServerConfigInterface if needed.$config =newMockServerConfig();$config            ->setConsumer('jsonConsumer')            ->setProvider('jsonProvider')            ->setPactDir(__DIR__.'/../../../pacts');if ($logLevel =\getenv('PACT_LOGLEVEL')) {$config->setLogLevel($logLevel);        }$builder =newInteractionBuilder($config);$builder            ->uponReceiving('A get request to /hello/{name}')            ->with($request)            ->willRespondWith($response);// This has to be last. This is what makes FFI calls to register the interaction and start the mock server.$service =newHttpClientService($config->getBaseUri());// Pass in the URL to the Mock Server.$helloResult =$service->getHelloString('Bob');// Make the real API request against the Mock Server.$verifyResult =$builder->verify();// This will verify that the interactions took place.$this->assertTrue($verifyResult);// Make your assertions.$this->assertEquals('Hello, Bob',$helloResult);    }}

You can see (and run) the full version of this in./examples/json, as well as other examples in the parent folder.

To run the examples

  1. Clone the repogit@github.com:pact-foundation/pact-php.git
  2. Go to the repocd pact-php
  3. Install all dependenciescomposer install

Run a single example

composer run-example:json

Run all examples

composer run-examples

----------

Verifying a Provider

A provider test takes one or more pact files (contracts) as input, and Pact verifies that your provider adheres to the contract. In the simplest case, you can verify a provider as per below using a local pact file, although in practice you would usually use a Pact Broker to manage your contracts and CI/CD workflow.

namespaceApp\Tests;useGuzzleHttp\Psr7\Uri;usePhpPact\Standalone\ProviderVerifier\Model\VerifierConfig;usePhpPact\Standalone\ProviderVerifier\Verifier;usePhpPactTest\Helper\PhpProcess;usePHPUnit\Framework\TestCase;class PactVerifyTestextends TestCase{privatePhpProcess$process;protectedfunctionsetUp():void    {$this->process =newPhpProcess(__DIR__ .'/path/to/public/');$this->process->start();    }protectedfunctiontearDown():void    {$this->process->stop();    }/**     * This test will run after the web server is started.     */publicfunctiontestPactVerifyConsumer()    {$config =newVerifierConfig();$config->getProviderInfo()            ->setName('jsonProvider')// Providers name to fetch.            ->setHost('localhost')            ->setPort($this->process->getPort());$config->getProviderState()            ->setStateChangeUrl(newUri(sprintf('http://localhost:%d/pact-change-state',$this->process->getPort())))        ;if ($level =\getenv('PACT_LOGLEVEL')) {$config->setLogLevel($level);        }$verifier =newVerifier($config);$verifier->addFile(__DIR__ .'/path/to/pacts/jsonConsumer-jsonProvider.json');$verifyResult =$verifier->verify();$this->assertTrue($verifyResult);    }}

It's best to run Pact verification tests as part of your unit testing suite, so you can readily access stubbing, IaC and other helpful tools.

----------

Compatibility

Versions
VersionStatusSpec CompatibilityPHP CompatibilityInstall
10.xStable1, 1.1, 2, 3, 4^8.1Seeinstallation
9.xStable1, 1.1, 2, 3*^8.09xx
8.xDeprecated1, 1.1, 2, 3*^7.4|^8.0
7.xDeprecated1, 1.1, 2, 3*^7.3
6.xDeprecated1, 1.1, 2, 3*^7.2
5.xDeprecated1, 1.1, 2, 3*^7.1
4.xDeprecated1, 1.1, 2^7.1
3.xDeprecated1, 1.1, 2^7.0
2.xDeprecated1, 1.1, 2>=7
1.xDeprecated1, 1.1>=7

* v3 support is limited to the subset of functionality required to enable language inter-operableMessage support.

Supported Platforms
OSArchitectureSupportedPact-PHP Version
OSXx86_64All
Linuxx86_64All
OSXarm649.x +
Linuxarm649.x +
Windowsx86_64All
Windowsx869.x -
Alpinex86_64All *
Alpinearm64All *

* For 9.x and below, supported with a workaroundRuby Standalone with Alpine.

Roadmap

Theroadmap for Pact and Pact PHP is outlined on our main website.

Contributing

SeeCONTRIBUTING.


About

PHP version of Pact. Enables consumer driven contract testing, providing a mock service and DSL for the consumer project, and interaction playback and verification for the service provider project

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages


[8]ページ先頭

©2009-2025 Movatter.jp