kitetail / zttp

A developer-experience focused HTTP client, optimized for most common use cases.
MIT License
1.68k stars 120 forks source link

Add callback to stub responses #81

Open jasonmccreary opened 4 years ago

jasonmccreary commented 4 years ago

This adds a Zttp::stub method which accepts a callback where you may perform logic to return stubbed responses in your tests. This way your code doesn't actually send a request across the network.

It introduces a new ZttpResponseStub to quickly create responses that will be treated just like a ZttpResponse in your code, while remaining decoupled from the underlying Guzzle classes.

Before, you might have mocked Zttp directly or through a service object wrapper. Now you may simply call:

Zttp::stub(function ($request, $options) {
    if ($request->uri() === 'https://example.com') {
        return new \Zttp\ZttpResponseStub('response body', 200, ['Z-Header' => 'noice']);
    } elseif (isset($options['cookies']['auth'])) {
        return new \Zttp\ZttpResponseStub(/* ... */);
    }
});

This also introduces a Zttp::clearStubs method to remove any previous stubs.

jasonmccreary commented 4 years ago

@adamwathan, I did my best to adhere to the contribution guidelines.

A few areas I think could be touched up:

Otherwise, I think this does well to preserve the encapsulation of Guzzle and doesn't hijack the request lifecycle in any way (runs as the last middleware), while achieving the API you outlined.

cc/ @taylorotwell

buismaarten commented 4 years ago

Need this, it's probably a convenient way to implement a cache system by ourselves.