1
0
mirror of https://github.com/guzzle/guzzle.git synced 2025-02-11 19:14:38 +01:00

Ensuring the mock adapter reads the request body and emits a headers event

This commit is contained in:
Michael Dowling 2014-03-23 15:52:24 -07:00
parent 9aec0a8723
commit 78bb8c1420
2 changed files with 32 additions and 0 deletions

View File

@ -37,13 +37,21 @@ class MockAdapter implements AdapterInterface
{
RequestEvents::emitBefore($transaction);
if (!$transaction->getResponse()) {
// Read the request body if it is present
if ($transaction->getRequest()->getBody()) {
$transaction->getRequest()->getBody()->__toString();
}
$response = is_callable($this->response)
? call_user_func($this->response, $transaction)
: $this->response;
if (!$response instanceof ResponseInterface) {
throw new \RuntimeException('Invalid mocked response');
}
$transaction->setResponse($response);
RequestEvents::emitHeaders($transaction);
RequestEvents::emitComplete($transaction);
}

View File

@ -11,6 +11,7 @@ use GuzzleHttp\Event\ErrorEvent;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Message\Request;
use GuzzleHttp\Message\Response;
use GuzzleHttp\Stream;
/**
* @covers GuzzleHttp\Adapter\MockAdapter
@ -76,4 +77,27 @@ class MockAdapterTest extends \PHPUnit_Framework_TestCase
});
$m->send(new Transaction(new Client(), $request));
}
public function testReadsRequestBody()
{
$response = new Response(200);
$m = new MockAdapter($response);
$m->setResponse($response);
$body = Stream\create('foo');
$request = new Request('PUT', 'http://httpbin.org/put', [], $body);
$this->assertSame($response, $m->send(new Transaction(new Client(), $request)));
$this->assertEquals(3, $body->tell());
}
public function testEmitsHeadersEvent()
{
$m = new MockAdapter(new Response(404));
$request = new Request('GET', 'http://httbin.org');
$called = false;
$request->getEmitter()->once('headers', function () use (&$called) {
$called = true;
});
$m->send(new Transaction(new Client(), $request));
$this->assertTrue($called);
}
}