testing.rst 6.0 KB

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