Re: Mock HTTP servers for unit tests. [message #185696 is a reply to message #185668] |
Thu, 01 May 2014 11:54 |
Thomas 'PointedEars'
Messages: 701 Registered: October 2010
Karma:
|
Senior Member |
|
|
Daniel Pitts wrote:
> I'm developing some code which makes http requests from PHP. I'd like to
> be able to Unit Test my code as smoothly as possible.
> […]
> Things I need:
> * Ability to validate a specific request was made, with a specific
> set of Headers.
> * Ability to provide a "mock" response, and validate my code can
> handle it.
>
> Things I really want:
> * Ability to send parallel requests (think curl_multi), and validate
> the requests are made in parallel.
> * Ability to delay one response for a specific amount of time, but
> have another response return earlier.
PHP 5.4+ and “php -S $TEST_HOST:$PORT your_handler.php”, perhaps with the
“-c” and/or “-d” options, should suffice.
Depending on the header fields you need to read, and the PHP version you
have available, you might need to use a different server.
apache_request_headers() is available in the CLI server since PHP 5.5.7.
I have verified that the CLI server of PHP 5.5.11 can handle several
requests made at approximately the same time (as expected):
,----
| $ echo '<?php echo $_SERVER["REQUEST_URI"] . "\n";' > server.php
| $ php -S localhost:1337 server.php
| Listening on http://localhost:1337
| Document root is /home/****/scripts/php/test
| Press Ctrl-C to quit.
`----
In another terminal:
,----
| $ GET http://localhost:1337/foo & GET http://localhost:1337/bar
| [1] 19301
| /bar
| $ /foo
| [1]+ Done GET http://localhost:1337/foo
`----
[“GET” is symlinked to lwp-request(1p), a Perl-based command-line tool to
make HTTP requests. The “$” in-between is only the client's shell
interfering with the server output; you will not see it if you use a PHP
client like curl_multi(). Note that apparently reading the server script
from a FIFO is not possible; you need to create a real file.]
<http://php.net/manual/en/features.commandline.webserver.php>
<http://php.net/manual/en/reserved.variables.php>
<http://php.net/apache_request_headers>
<http://php.net/sleep>
PointedEars
--
var bugRiddenCrashPronePieceOfJunk = (
navigator.userAgent.indexOf('MSIE 5') != -1
&& navigator.userAgent.indexOf('Mac') != -1
) // Plone, register_function.js:16
|
|
|