1
0
mirror of https://github.com/guzzle/guzzle.git synced 2025-02-24 18:13:00 +01:00
guzzle/tests/Server.php

170 lines
4.7 KiB
PHP
Raw Normal View History

<?php
namespace GuzzleHttp\Tests;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7;
2015-02-24 22:50:52 -08:00
use Psr\Http\Message\ResponseInterface;
/**
2015-02-24 22:50:52 -08:00
* The Server class is used to control a scripted webserver using node.js that
* will respond to HTTP requests with queued responses.
*
* Queued responses will be served to requests using a FIFO order. All requests
* received by the server are stored on the node.js server and can be retrieved
* by calling {@see Server::received()}.
*
* Mock responses that don't require data to be transmitted over HTTP a great
* for testing. Mock response, however, cannot test the actual sending of an
* HTTP request using cURL. This test server allows the simulation of any
* number of HTTP request response transactions to test the actual sending of
* requests over the wire without having to leave an internal network.
*/
class Server
{
2015-02-24 22:50:52 -08:00
const REQUEST_DELIMITER = "\n----[request]\n";
/** @var Client */
private static $client;
private static $started = false;
public static $url = 'http://127.0.0.1:8126/';
public static $port = 8126;
/**
* Flush the received requests from the server
* @throws \RuntimeException
*/
public static function flush()
{
self::start();
2015-03-21 15:33:30 -07:00
return self::$client->request('DELETE', 'guzzle-server/requests');
2015-02-24 22:50:52 -08:00
}
/**
* Queue an array of responses or a single response on the server.
*
* Any currently queued responses will be overwritten. Subsequent requests
* on the server will return queued responses in FIFO order.
*
2015-02-24 22:50:52 -08:00
* @param array|ResponseInterface $responses A single or array of Responses
* to queue.
* @throws \Exception
*/
2015-02-24 22:50:52 -08:00
public static function enqueue($responses)
{
2015-02-24 22:50:52 -08:00
self::start();
$data = [];
2015-02-24 22:50:52 -08:00
foreach ((array) $responses as $response) {
if (!($response instanceof ResponseInterface)) {
throw new \Exception('Invalid response given.');
}
2015-02-24 22:50:52 -08:00
$headers = array_map(function ($h) {
return implode(' ,', $h);
}, $response->getHeaders());
$data[] = [
'statusCode' => $response->getStatusCode(),
'reasonPhrase' => $response->getReasonPhrase(),
'headers' => $headers,
'body' => base64_encode((string) $response->getBody())
];
}
2015-02-24 22:50:52 -08:00
self::getClient()->request('PUT', 'guzzle-server/responses', [
'json' => json_encode($data)
2015-03-21 15:33:30 -07:00
]);
}
/**
* Get all of the received requests
*
2012-05-16 00:55:45 -07:00
* @param bool $hydrate Set to TRUE to turn the messages into
* actual {@see RequestInterface} objects. If $hydrate is FALSE,
* requests will be returned as strings.
*
* @return array
2013-09-22 20:55:24 -07:00
* @throws \RuntimeException
*/
public static function received($hydrate = false)
{
2015-02-24 22:50:52 -08:00
if (!self::$started) {
return [];
}
2015-03-21 15:33:30 -07:00
$response = self::getClient()->request('GET', 'guzzle-server/requests');
2015-02-24 22:50:52 -08:00
$data = array_filter(explode(self::REQUEST_DELIMITER, (string) $response->getBody()));
if ($hydrate) {
2015-02-24 22:50:52 -08:00
$data = array_map(
function ($message) {
return Psr7\parse_request($message);
2015-02-24 22:50:52 -08:00
},
$data
);
}
2015-02-24 22:50:52 -08:00
return $data;
}
2015-02-24 22:50:52 -08:00
/**
* Stop running the node.js server
*/
public static function stop()
2014-03-23 10:53:34 -07:00
{
2015-02-24 22:50:52 -08:00
if (self::$started) {
2015-03-21 15:33:30 -07:00
self::getClient()->request('DELETE', 'guzzle-server');
2015-02-24 22:50:52 -08:00
}
self::$started = false;
2014-03-23 10:53:34 -07:00
}
public static function wait($maxTries = 5)
{
2015-02-24 22:50:52 -08:00
$tries = 0;
while (!self::isListening() && ++$tries < $maxTries) {
usleep(100000);
}
if (!self::isListening()) {
throw new \RuntimeException('Unable to contact node.js server');
}
}
public static function start()
{
2015-02-24 22:50:52 -08:00
if (self::$started) {
return;
}
if (!self::isListening()) {
exec('node ' . __DIR__ . '/server.js '
. self::$port . ' >> /tmp/server.log 2>&1 &');
self::wait();
}
self::$started = true;
}
private static function isListening()
{
try {
self::getClient()->request('GET', 'guzzle-server/perf', [
'connect_timeout' => 5,
'timeout' => 5
2015-03-21 15:33:30 -07:00
]);
2015-02-24 22:50:52 -08:00
return true;
} catch (\Exception $e) {
return false;
}
}
2015-02-24 22:50:52 -08:00
private static function getClient()
{
2015-02-24 22:50:52 -08:00
if (!self::$client) {
self::$client = new Client(['base_uri' => self::$url]);
}
return self::$client;
}
Breaking / Potentially breaking changes: 1. Adopting a marker interface for Guzzle exceptions. A. All exceptions emitted from Guzzle are now wrapped with a Guzzle namespaced exception. B. Guzzle\Common\GuzzleExceptionInterface was renamed to Guzzle\Common\GuzzleException C. Guzzle\Common\ExceptionCollection was renamed to Guzzle\Common\Exception\ExceptionCollection 2. Using Header objects for Request and Response objects A. When you call $request->getHeader('X'), you will get back a Guzzle\Http\Message\Header object that contains all of the headers that case insensitively match. This object can be cast to a string or iterated like an array. You can pass true in the second argument to retrieve the header as a string. B. Removing the old Guzzle\Common\Collection based searching arguments from most of the request and response header methods. All retrievals are case-insensitive and return Header objects. 3. Changing the two headers added by the cache plugin to just one header with key and ttl. 4. Changing Guzzle\Http\Message\Response::factory() to fromMessage(). 5. Removing the NullObject return value from ServiceDescriptions and instead simply returning null New Features / enhancements: 1. Adding Guzzle\Http\Message\AbstractMessage::addHeaders() 2. Making it simpler to create service descriptions using a unified factory method that delegates to other factories. 3. Better handling of ports and hosts in Guzzle\Http\Url Note: This is a noisy diff because I'm removing trailing whitespace and adding a new line at the end of each source file.
2012-04-21 00:23:07 -07:00
}