testing.rst 5.9 KB

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