1
0
mirror of https://github.com/guzzle/guzzle.git synced 2025-01-18 05:48:15 +01:00

Handle on_headers option in MockHandler (#1580)

* Handle on_headers option

* Tests for correct handling of on_headers option
This commit is contained in:
Bas van Vliet 2016-10-21 23:23:29 +02:00 committed by Márk Sági-Kazár
parent 9061956e6a
commit 56ed0ef043
2 changed files with 42 additions and 0 deletions

View File

@ -1,6 +1,7 @@
<?php
namespace GuzzleHttp\Handler;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Promise\PromiseInterface;
use GuzzleHttp\Promise\RejectedPromise;
@ -73,6 +74,18 @@ class MockHandler implements \Countable
$this->lastOptions = $options;
$response = array_shift($this->queue);
if (isset($options['on_headers'])) {
if (!is_callable($options['on_headers'])) {
throw new \InvalidArgumentException('on_headers must be callable');
}
try {
$options['on_headers']($response);
} catch (\Exception $e) {
$msg = 'An error was encountered during the on_headers event';
$response = new RequestException($msg, $request, $response, $e);
}
}
if (is_callable($response)) {
$response = call_user_func($response, $request, $options);
}

View File

@ -114,6 +114,35 @@ class MockHandlerTest extends \PHPUnit_Framework_TestCase
$this->assertSame($r, $p->wait());
}
/**
* @expectedException \InvalidArgumentException
*/
public function testEnsuresOnHeadersIsCallable()
{
$res = new Response();
$mock = new MockHandler([$res]);
$request = new Request('GET', 'http://example.com');
$mock($request, ['on_headers' => 'error!']);
}
/**
* @expectedException \GuzzleHttp\Exception\RequestException
* @expectedExceptionMessage An error was encountered during the on_headers event
* @expectedExceptionMessage test
*/
public function testRejectsPromiseWhenOnHeadersFails()
{
$res = new Response();
$mock = new MockHandler([$res]);
$request = new Request('GET', 'http://example.com');
$promise = $mock($request, [
'on_headers' => function () {
throw new \Exception('test');
}
]);
$promise->wait();
}
public function testInvokesOnFulfilled()
{
$res = new Response();