testing.rst 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. ======================
  2. Testing Guzzle Clients
  3. ======================
  4. Guzzle provides several tools that will enable you to easily mock the HTTP
  5. layer without needing to send requests over the internet.
  6. * Mock handler
  7. * History middleware
  8. * Node.js web server for integration testing
  9. Mock Handler
  10. ============
  11. When testing HTTP clients, you often need to simulate specific scenarios like
  12. returning a successful response, returning an error, or returning specific
  13. responses in a certain order. Because unit tests need to be predictable, easy
  14. to bootstrap, and fast, hitting an actual remote API is a test smell.
  15. Guzzle provides a mock handler that can be used to fulfill HTTP requests with
  16. a response or exception by shifting return values off of a queue.
  17. .. code-block:: php
  18. use GuzzleHttp\Client;
  19. use GuzzleHttp\Handler\MockHandler;
  20. use GuzzleHttp\HandlerStack;
  21. use GuzzleHttp\Psr7\Response;
  22. use GuzzleHttp\Psr7\Request;
  23. use GuzzleHttp\Exception\RequestException;
  24. // Create a mock and queue two responses.
  25. $mock = new MockHandler([
  26. new Response(200, ['X-Foo' => 'Bar'], 'Hello, World'),
  27. new Response(202, ['Content-Length' => 0]),
  28. new RequestException('Error Communicating with Server', new Request('GET', 'test'))
  29. ]);
  30. $handlerStack = HandlerStack::create($mock);
  31. $client = new Client(['handler' => $handlerStack]);
  32. // The first request is intercepted with the first response.
  33. $response = $client->request('GET', '/');
  34. echo $response->getStatusCode();
  35. //> 200
  36. echo $response->getBody();
  37. //> Hello, World
  38. // The second request is intercepted with the second response.
  39. echo $client->request('GET', '/')->getStatusCode();
  40. //> 202
  41. When no more responses are in the queue and a request is sent, an
  42. ``OutOfBoundsException`` is thrown.
  43. History Middleware
  44. ==================
  45. When using things like the ``Mock`` handler, you often need to know if the
  46. requests you expected to send were sent exactly as you intended. While the mock
  47. handler responds with mocked responses, the history middleware maintains a
  48. history of the requests that were sent by a client.
  49. .. code-block:: php
  50. use GuzzleHttp\Client;
  51. use GuzzleHttp\HandlerStack;
  52. use GuzzleHttp\Middleware;
  53. $container = [];
  54. $history = Middleware::history($container);
  55. $handlerStack = HandlerStack::create();
  56. // or $handlerStack = HandlerStack::create($mock); if using the Mock handler.
  57. // Add the history middleware to the handler stack.
  58. $handlerStack->push($history);
  59. $client = new Client(['handler' => $handlerStack]);
  60. $client->request('GET', 'http://httpbin.org/get');
  61. $client->request('HEAD', 'http://httpbin.org/get');
  62. // Count the number of transactions
  63. echo count($container);
  64. //> 2
  65. // Iterate over the requests and responses
  66. foreach ($container as $transaction) {
  67. echo $transaction['request']->getMethod();
  68. //> GET, HEAD
  69. if ($transaction['response']) {
  70. echo $transaction['response']->getStatusCode();
  71. //> 200, 200
  72. } elseif ($transaction['error']) {
  73. echo $transaction['error'];
  74. //> exception
  75. }
  76. var_dump($transaction['options']);
  77. //> dumps the request options of the sent request.
  78. }
  79. Test Web Server
  80. ===============
  81. Using mock responses is almost always enough when testing a web service client.
  82. When implementing custom :doc:`HTTP handlers <handlers-and-middleware>`, you'll
  83. need to send actual HTTP requests in order to sufficiently test the handler.
  84. However, a best practice is to contact a local web server rather than a server
  85. over the internet.
  86. - Tests are more reliable
  87. - Tests do not require a network connection
  88. - Tests have no external dependencies
  89. Using the test server
  90. ---------------------
  91. .. warning::
  92. The following functionality is provided to help developers of Guzzle
  93. develop HTTP handlers. There is no promise of backwards compatibility
  94. when it comes to the node.js test server or the ``GuzzleHttp\Tests\Server``
  95. class. If you are using the test server or ``Server`` class outside of
  96. guzzlehttp/guzzle, then you will need to configure autoloading and
  97. ensure the web server is started manually.
  98. .. hint::
  99. You almost never need to use this test web server. You should only ever
  100. consider using it when developing HTTP handlers. The test web server
  101. is not necessary for mocking requests. For that, please use the
  102. Mock handler and history middleware.
  103. Guzzle ships with a node.js test server that receives requests and returns
  104. responses from a queue. The test server exposes a simple API that is used to
  105. enqueue responses and inspect the requests that it has received.
  106. Any operation on the ``Server`` object will ensure that
  107. the server is running and wait until it is able to receive requests before
  108. returning.
  109. ``GuzzleHttp\Tests\Server`` provides a static interface to the test server. You
  110. can queue an HTTP response or an array of responses by calling
  111. ``Server::enqueue()``. This method accepts an array of
  112. ``Psr\Http\Message\ResponseInterface`` and ``Exception`` objects.
  113. .. code-block:: php
  114. use GuzzleHttp\Client;
  115. use GuzzleHttp\Psr7\Response;
  116. use GuzzleHttp\Tests\Server;
  117. // Start the server and queue a response
  118. Server::enqueue([
  119. new Response(200, ['Content-Length' => 0])
  120. ]);
  121. $client = new Client(['base_uri' => Server::$url]);
  122. echo $client->request('GET', '/foo')->getStatusCode();
  123. // 200
  124. When a response is queued on the test server, the test server will remove any
  125. previously queued responses. As the server receives requests, queued responses
  126. are dequeued and returned to the request. When the queue is empty, the server
  127. will return a 500 response.
  128. You can inspect the requests that the server has retrieved by calling
  129. ``Server::received()``.
  130. .. code-block:: php
  131. foreach (Server::received() as $response) {
  132. echo $response->getStatusCode();
  133. }
  134. You can clear the list of received requests from the web server using the
  135. ``Server::flush()`` method.
  136. .. code-block:: php
  137. Server::flush();
  138. echo count(Server::received());
  139. // 0