Coder Social home page Coder Social logo

pock's Introduction

Build Status Coverage Latest stable PHP from Packagist License

pock

Easy to use HTTP mocking solution, compatible with PSR-18 and HTTPlug.

Project is still in its early development stage. API can change over time, but I'll try to not introduce breaking changes. You can find autogenerated documentation here or look at the examples. API for the mock building can be found here and API for the response building (returned from PockBuilder::reply call) can be found here.

Examples

Mock JSON API route with Basic authorization, reply with JSON.

use Pock\Enum\RequestMethod;
use Pock\Enum\RequestScheme;
use Pock\PockBuilder;

$builder = new PockBuilder();
$builder->matchMethod(RequestMethod::GET)
    ->matchScheme(RequestScheme::HTTPS)
    ->matchHost('example.com')
    ->matchPath('/api/v1/users')
    ->matchHeaders([
        'Content-Type' => 'application/json',
        'Authorization' => 'Basic YWxhZGRpbjpvcGVuc2VzYW1l'
    ])
    ->reply(200)
    ->withHeader('Content-Type', 'application/json')
    ->withJson([
        [
            'name' => 'John Doe',
            'username' => 'john',
            'email' => '[email protected]'
        ],
        [
            'name' => 'Jane Doe',
            'username' => 'jane',
            'email' => '[email protected]'
        ],
    ]);

// Pass PSR-18 compatible client to the API client.
$client = new MysteriousApiClient($builder->getClient());
$client->setCredentials('username', 'password');

// Receive mock response.
$response = $client->getUsers();

Same mock, but with models! Also, the code itself is slightly shorter.

use Pock\Enum\RequestMethod;
use Pock\PockBuilder;

$builder = new PockBuilder();
$builder->matchMethod(RequestMethod::GET)
    ->matchUri('https://example.com/api/v1/users')
    ->matchHeaders([
        'Content-Type' => 'application/json',
        'Authorization' => 'Basic YWxhZGRpbjpvcGVuc2VzYW1l'
    ])
    ->reply(200)
    ->withHeader('Content-Type', 'application/json')
    ->withJson([
        // We're assuming here that MysteriousUser's constructor can receive an initial values.
        new MysteriousUser('John Doe', 'john', '[email protected]'),
        new MysteriousUser('Jane Doe', 'jane', '[email protected]'),
    ]);

// Pass PSR-18 compatible client to the API client.
$client = new MysteriousApiClient($builder->getClient());
$client->setCredentials('username', 'password');

// Receive mock response.
$response = $client->getUsers();

It is possible to mock a response using DTO's because pock can use third-party serializers under the hood.

Serializer support

pock supports JMS serializer and Symfony serializer out of the box. Available serializer will be instantiated automatically. It will be used to serialize requests and responses in mocks which means you actually can pass an entire DTO into the corresponding methods (for example, matchJsonBody as an assertion or withJsonBody to generate a response body).

By default, JMS serializer has more priority than the Symfony serializer. You can use methods below before running tests (bootstrap.php) if you want to override default behavior.

use Pock\Factory\JsonSerializerFactory;
use Pock\Factory\XmlSerializerFactory;
use Pock\Serializer\SymfonySerializerAdapter;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;

$encoders = [new XmlEncoder(), new JsonEncoder()];
$normalizers = [new ObjectNormalizer()];
$serializer = new SymfonySerializerAdapter(new Serializer($normalizers, $encoders));

JsonSerializerFactory::setSerializer($serializer);
XmlSerializerFactory::setSerializer($serializer);

In order to use unsupported serializer you should create an adapter which implements Pock\Serializer\SerializerInterface.

Roadmap to stable

  • at(N) - execute mock only at Nth call.
  • always() - always execute this mock (removes mock expiration).
  • Separate UniversalMockException into several exceptions (PockClientException, PockNetworkException, etc).
  • Add methods for easier throwing of exceptions listed in previous entry.
  • replyWithCallback - reply using specified callback.
  • replyWithFactory - reply using specified response factory (provide corresponding interface).
  • Compare XML bodies using DOMDocument, fallback to text comparison in case of problems.
  • Regexp matchers for body, query, URI and path.
  • Form Data body matcher (partial & exact)
  • Multipart form body matcher (just like callback matcher but parses the body as a multipart form data)
  • BREAKING CHANGE: Rename serializer decorators to serializer adapters.
  • Real network response for mocked requests.
  • symfony/http-client support.
  • Document everything (with examples if it’s feasible).

pock's People

Contributors

neur0toxine avatar

Stargazers

 avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

Forkers

avlima gwinn

pock's Issues

Replying with a custom Response

First of all, this library is exactly what I was looking for, and I have found nothing comparable to it (php-http/mock-client lib is dated and also very barebones in comparison to this one), thank you!

For now the intended way of crafting a response is to use the library's PockResponseBuilder. However, I'd like to just put my own response implementing PSR's ResponseInterface, like that:

$myResponse = new Response(); // assume Response is a class from some PSR-7 implementation.
$builder = new PockBuilder();
$builder->replyWith($myResponse); // replyWith() is just some suggested method name

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.