1
0
mirror of https://github.com/guzzle/guzzle.git synced 2025-02-23 09:34:00 +01:00
guzzle/tests/Server.php

175 lines
5.0 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-03-23 00:20:56 -07:00
/** @var Client */
private static $client;
2015-02-24 22:50:52 -08:00
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()
{
2015-03-23 00:16:44 -07:00
return self::getClient()->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)
{
$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[] = [
'status' => (string) $response->getStatusCode(),
'reason' => $response->getReasonPhrase(),
'headers' => $headers,
'body' => base64_encode((string) $response->getBody())
2015-02-24 22:50:52 -08:00
];
}
2015-02-24 22:50:52 -08:00
self::getClient()->request('PUT', 'guzzle-server/responses', [
'json' => $data
2015-03-21 15:33:30 -07:00
]);
}
/**
* Get all of the received requests
*
* @return ResponseInterface[]
2013-09-22 20:55:24 -07:00
* @throws \RuntimeException
*/
public static function received()
{
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');
$data = json_decode($response->getBody(), true);
return array_map(
function ($message) {
$uri = $message['uri'];
if (isset($message['query_string'])) {
$uri .= '?' . $message['query_string'];
}
2015-03-23 00:16:44 -07:00
$response = new Psr7\Request(
$message['http_method'],
$uri,
$message['headers'],
$message['body'],
$message['version']
);
2015-03-23 00:16:44 -07:00
return $response->withUri(
$response->getUri()
->withScheme('http')
2015-04-19 20:39:53 -07:00
->withHost($response->getHeaderLine('host'))
2015-03-23 00:16:44 -07:00
);
},
$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-03-23 00:20:56 -07:00
if (!self::$client) {
self::$client = new Client([
'base_uri' => self::$url,
'sync' => true,
]);
}
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
}