1
0
mirror of https://github.com/guzzle/guzzle.git synced 2025-02-25 02:22:57 +01:00
guzzle/tests/Server.php

177 lines
4.9 KiB
PHP
Raw Normal View History

<?php
namespace GuzzleHttp\Tests;
use GuzzleHttp\Message\MessageFactory;
use GuzzleHttp\Message\Response;
use GuzzleHttp\Client;
/**
* 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
{
const REQUEST_DELIMITER = "\n----[request]\n";
/** @var Client */
private static $client;
Guzzle 2.0 Adopting composer for dependency management Updating LICENSE, travis build file, making better use of git ignores, and remove unused build target Removing @author tags. Use the commit history for a changelog. Moving files from build folder to / Adding min build target to product a Guzzle only phar with no autoloader [Common] Accepting ZF1 or ZF2 cache in ZendCacheAdapter [Common] Optimizing Stream wrapper and EntityBody abstractions. [Common] [Http] Migrating from Guzzle event system to the Symfony2 event dispatcher [Common] Moved Inflector and Inspector to Service namespace [Http] Simplifying Guzzle\Guzzle curl detection [Http] Removing Guzzle\Http\Pool and now using Guzzle\Http\Curl\CurlMulti [Http] The helper methods from Guzzle\Http\Message\RequestFactory have been removed to prevent confusion and encourage developers to use Guzzle\Http\Client to create requests. [Http] Clients can now send one or more requests in an array using the send() method, so the batch() method was removed. [Http] Updating curl multi to allow blocking calls while sending other transfers [Http] Making the Request::hasHeader method more intuitive. Guzzle\Http\Message\AbstractMessage::hasHeader() now returns true if the header is found using exact matching. If the header is found using a regex or case-insensitive match, then it will return the name of the found header. [Http] Removing content-type guessing from EntityBody based on file extension and solely using finfo. [Http] Adding basic auth plugin [Http] Cleaning up CookieJar and CurlMulti [Http] Removing custom rawurlencode from QueryString because PHP 5.3 now properly deals with tilde characters. [Http] Minor optimization to parsing messages in RequestFactory [Http] Adding Guzzle\Http\Client for developers that don't need commands or service descriptions [Http] Making it easier to set a global User-Agent header for a Guzzle\Http\Client [Http] Fixing the discrepancies between the ClientInterface and Guzzle\Http\Client [Http] Adding the ability to set and retrieve tokenized headers from Requests and Responses [Service] Ditching NIH filters and using the Symfony2 validator [Service] Moving most service building logic to the ServiceBuilder::factory method so that it is easier to build custom config readers. [Service] Allowing deep nested command inheritance. [Service] Cleaning up Inflector caching. [Service] Getting rid of concept of can_batch because everything is now sent in parallel. [Service] Adding a JSON description builder. [Service] Cleaning up ResourceIteratorApplyBatched. [Service] Removing caching stuff from ServiceBuilder because the data being cached is extremely fast to generate. [Service] Added a method to serialize the ServiceDescription in case a ServiceDescription needs to be cached in an application. [Service] Making description builders use static methods. [Service] Adding support to include other description files for XML and JSON description builders. [Service] Adding support for filters to ApiCommands [Service] Using {{}} instead of $. to reference other services as a dependency for another service
2012-01-14 13:57:05 -06:00
public static $started;
public static $url = 'http://127.0.0.1:8124/';
public static $port = 8124;
/**
* Flush the received requests from the server
2013-09-22 20:55:24 -07:00
* @throws \RuntimeException
*/
public static function flush()
{
self::$started && self::$client->delete('guzzle-server/requests');
}
/**
* 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.
*
2011-03-03 12:24:51 -06:00
* @param array|Response $responses A single or array of Responses to queue
* @throws \Exception
*/
public static function enqueue($responses)
{
static $factory;
if (!$factory) {
$factory = new MessageFactory();
}
self::start();
$data = [];
foreach ((array) $responses as $response) {
// Create the response object from a string
if (is_string($response)) {
$response = $factory->fromMessage($response);
2012-05-11 21:04:42 -07:00
} elseif (!($response instanceof Response)) {
throw new \Exception('Responses must be strings or Responses');
}
$headers = array_map(function ($h) {
return implode(' ,', $h);
}, $response->getHeaders());
$data[] = [
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
'statusCode' => $response->getStatusCode(),
'reasonPhrase' => $response->getReasonPhrase(),
'headers' => $headers,
'body' => (string) $response->getBody()
];
}
self::getClient()->put('guzzle-server/responses', [
'body' => json_encode($data)
]);
}
/**
* 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)
{
if (!self::$started) {
return [];
}
$response = self::getClient()->get('guzzle-server/requests');
2013-09-22 20:55:24 -07:00
$data = array_filter(explode(self::REQUEST_DELIMITER, (string) $response->getBody()));
if ($hydrate) {
$factory = new MessageFactory();
2013-09-22 20:55:24 -07:00
$data = array_map(function($message) use ($factory) {
return $factory->fromMessage($message);
}, $data);
}
return $data;
}
/**
* Stop running the node.js server
*/
public static function stop()
{
if (self::$started) {
self::getClient()->delete('guzzle-server');
}
self::$started = false;
}
2014-03-23 10:53:34 -07:00
public static function wait($maxTries = 3)
{
$tries = 0;
while (!self::isListening() && ++$tries < $maxTries) {
usleep(100000);
}
if (!self::isListening()) {
throw new \RuntimeException('Unable to contact node.js server');
}
}
private static function start()
{
if (self::$started){
return;
}
if (!self::isListening()) {
exec('node ' . __DIR__ . \DIRECTORY_SEPARATOR . 'server.js '
. self::$port . ' >> /tmp/server.log 2>&1 &');
2014-03-23 10:53:34 -07:00
self::wait();
}
self::$started = true;
}
private static function isListening()
{
try {
self::getClient()->get('guzzle-server/perf', [
'connect_timeout' => 5,
'timeout' => 5
]);
return true;
} catch (\Exception $e) {
return false;
}
}
private static function getClient()
{
if (!self::$client) {
self::$client = new Client(['base_url' => 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
}