updated plugin W3 Total Cache version 2.3.3

This commit is contained in:
2023-06-28 12:45:56 +00:00
committed by Gitium
parent 7d5eef77cf
commit aa3da0eb92
129 changed files with 17998 additions and 186 deletions

View File

@ -0,0 +1,11 @@
# EditorConfig is awesome: http://EditorConfig.org
# top-most EditorConfig file
root = true
# Unix-style newlines with a newline ending for every file
# Indent with 4 spaces
[php]
end_of_line = lf
indent_style = space
indent_size = 4

View File

@ -0,0 +1,11 @@
.editorconfig export-ignore
.gitattributes export-ignore
/.github/ export-ignore
.gitignore export-ignore
/build/ export-ignore
/docs/ export-ignore
/Makefile export-ignore
/phpstan-baseline.neon export-ignore
/phpstan.neon.dist export-ignore
/phpunit.xml.dist export-ignore
/tests/ export-ignore

View File

@ -0,0 +1,3 @@
# Contributing
Please see our [contributing guide](http://docs.guzzlephp.org/en/latest/overview.html#contributing).

View File

@ -0,0 +1 @@
Please consider using one of the issue templates (bug report, feature request).

View File

@ -0,0 +1,18 @@
---
name: 🐛 Bug Report
about: Report errors and problems
---
**Guzzle version(s) affected**: x.y.z
**Description**
<!-- A clear and concise description of the problem. -->
**How to reproduce**
<!-- Code and/or config needed to reproduce the problem. -->
**Possible Solution**
<!--- Optional: only if you have suggestions on a fix/reason for the bug -->
**Additional context**
<!-- Optional: any other context about the problem: log messages, screenshots, etc. -->

View File

@ -0,0 +1,14 @@
---
name: 🚀 Feature Request
about: RFC and ideas for new features and improvements
---
**Description**
<!-- A clear and concise description of the new feature. -->
**Example**
<!-- A simple example of the new feature in action (include PHP code, YAML config, etc.)
If the new feature changes an existing feature, include a simple before/after comparison. -->
**Additional context**
<!-- Add any other context or screenshots about the feature request here. -->

View File

@ -0,0 +1,10 @@
---
name: ⛔ Security Issue
about: See the description to report security-related issues
---
⚠ PLEASE DON'T DISCLOSE SECURITY-RELATED ISSUES PUBLICLY, SEE BELOW.
If you have found a security issue in Guzzle, please send the details to
security [at] guzzlephp.org and don't disclose it publicly until we can provide a
fix for it.

View File

@ -0,0 +1,10 @@
---
name: ⛔ Support Question
about: See https://github.com/guzzle/guzzle/blob/master/.github/SUPPORT.md for questions about using Guzzle and its components
---
We use GitHub issues only to discuss about Guzzle bugs and new features.
For this kind of questions about using Guzzle,
please use any of the support alternatives shown in https://github.com/guzzle/guzzle/blob/master/.github/SUPPORT.md
Thanks!

View File

@ -0,0 +1,18 @@
# Support
If you're looking for support for Guzzle, here are a few options:
- [Documentation](http://guzzlephp.org/)
- [Gitter](https://gitter.im/guzzle/guzzle)
- [#guzzle](https://php-http.slack.com/messages/CE6UAAKL4/) channel in [PHP-HTTP](http://php-http.org) Slack team
Guzzle is a relatively old project, so chances are you will find
much about them on Google or Stack Overflow:
- [guzzle](https://stackoverflow.com/questions/tagged/guzzle) tag on Stack Overflow (recommended)
- [guzzlehttp](https://stackoverflow.com/questions/tagged/guzzlehttp) tag on Stack Overflow
- [guzzle6](https://stackoverflow.com/questions/tagged/guzzle6) tag on Stack Overflow
You can also browse the issue tracker for support requests,
but we encourage everyone to use the channels above instead.

View File

@ -0,0 +1,37 @@
#!/bin/sh -l
#
# This file is a hack to suppress warnings from Roave BC check
#
composer install
# Capture output to variable AND print it
exec 4711>&1
OUTPUT=$(/composer/vendor/bin/roave-backward-compatibility-check 2>&1 | tee /dev/fd/4711)
# Remove rows we want to suppress
OUTPUT=`echo "$OUTPUT" | sed '/GuzzleHttp\\\ClientInterface::VERSION/'d`
OUTPUT=`echo "$OUTPUT" | sed '/Roave\\\BetterReflection\\\Reflection\\\ReflectionClass "Psr\\\Log\\\LogLevel" could not be found in the located source/'d`
# Number of rows we found with "[BC]" in them
BC_BREAKS=`echo "$OUTPUT" | grep -o '\[BC\]' | wc -l | awk '{ print $1 }'`
# The last row of the output is "X backwards-incompatible changes detected". Find X.
STATED_BREAKS=`echo "$OUTPUT" | tail -n 1 | awk -F' ' '{ print $1 }'`
# If
# We found "[BC]" in the command output after we removed suppressed lines
# OR
# We have suppressed X number of BC breaks. If $STATED_BREAKS is larger than X
# THEN
# exit 1
if [ $BC_BREAKS -gt 0 ] || [ $STATED_BREAKS -gt 2 ]; then
echo "EXIT 1"
exit 1
fi
# No BC breaks found
echo "EXIT 0"
exit 0

View File

@ -0,0 +1,21 @@
name: Checks
on:
push:
branches:
- master
pull_request:
jobs:
roave-bc-check:
name: Roave BC Check
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v2
- name: Roave BC Check
uses: docker://nyholm/roave-bc-check-ga
with:
entrypoint: ./.github/workflows/bc.entrypoint

View File

@ -0,0 +1,70 @@
name: CI
on:
push:
branches:
- master
pull_request:
jobs:
build-lowest:
name: Build lowest
runs-on: ubuntu-latest
steps:
- name: Set up PHP
uses: shivammathur/setup-php@v2
with:
php-version: '5.5'
coverage: none
extensions: mbstring, intl
- name: Set up Node
uses: actions/setup-node@v1
with:
node-version: '14.x'
- name: Setup Problem Matchers for PHPUnit
run: echo "::add-matcher::${{ runner.tool_cache }}/phpunit.json"
- name: Checkout code
uses: actions/checkout@v2
- name: Download dependencies
run: composer update --no-interaction --no-progress --prefer-stable --prefer-lowest
- name: Run tests
run: make test
build:
name: Build
runs-on: ubuntu-latest
strategy:
max-parallel: 10
matrix:
php: ['5.5', '5.6', '7.0', '7.1', '7.2', '7.3', '7.4']
steps:
- name: Set up PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
coverage: none
extensions: mbstring, intl
- name: Set up Node
uses: actions/setup-node@v1
with:
node-version: '14.x'
- name: Setup Problem Matchers for PHPUnit
run: echo "::add-matcher::${{ runner.tool_cache }}/phpunit.json"
- name: Checkout code
uses: actions/checkout@v2
- name: Download dependencies
run: composer update --no-interaction --no-progress
- name: Run tests
run: make test

View File

@ -0,0 +1,78 @@
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " start-server to start the test server"
@echo " stop-server to stop the test server"
@echo " test to perform unit tests. Provide TEST to perform a specific test."
@echo " coverage to perform unit tests with code coverage. Provide TEST to perform a specific test."
@echo " coverage-show to show the code coverage report"
@echo " clean to remove build artifacts"
@echo " docs to build the Sphinx docs"
@echo " docs-show to view the Sphinx docs"
@echo " tag to modify the version, update changelog, and chag tag"
@echo " package to build the phar and zip files"
@echo " static to run phpstan and php-cs-fixer on the codebase"
@echo " static-phpstan to run phpstan on the codebase"
@echo " static-phpstan-update-baseline to regenerate the phpstan baseline file"
@echo " static-codestyle-fix to run php-cs-fixer on the codebase, writing the changes"
@echo " static-codestyle-check to run php-cs-fixer on the codebase"
start-server: stop-server
node tests/server.js &> /dev/null &
stop-server:
@PID=$(shell ps axo pid,command \
| grep 'tests/server.js' \
| grep -v grep \
| cut -f 1 -d " "\
) && [ -n "$$PID" ] && kill $$PID || true
test: start-server
vendor/bin/phpunit
$(MAKE) stop-server
coverage: start-server
vendor/bin/phpunit --coverage-html=build/artifacts/coverage
$(MAKE) stop-server
coverage-show: view-coverage
view-coverage:
open build/artifacts/coverage/index.html
clean:
rm -rf artifacts/*
docs:
cd docs && make html && cd ..
docs-show:
open docs/_build/html/index.html
tag:
$(if $(TAG),,$(error TAG is not defined. Pass via "make tag TAG=4.2.1"))
@echo Tagging $(TAG)
chag update $(TAG)
sed -i '' -e "s/VERSION = '.*'/VERSION = '$(TAG)'/" src/ClientInterface.php
php -l src/ClientInterface.php
git add -A
git commit -m '$(TAG) release'
chag tag
package:
php build/packager.php
static: static-phpstan static-codestyle-check
static-phpstan:
docker run --rm -it -e REQUIRE_DEV=true -v ${PWD}:/app -w /app oskarstark/phpstan-ga:0.12.28 analyze $(PHPSTAN_PARAMS)
static-phpstan-update-baseline:
$(MAKE) static-phpstan PHPSTAN_PARAMS="--generate-baseline"
static-codestyle-fix:
docker run --rm -it -v ${PWD}:/app -w /app oskarstark/php-cs-fixer-ga:2.16.3.1 --diff-format udiff $(CS_PARAMS)
static-codestyle-check:
$(MAKE) static-codestyle-fix CS_PARAMS="--dry-run"
.PHONY: docs burgomaster coverage-show view-coverage

View File

@ -0,0 +1,385 @@
<?php
/**
* Packages the zip and phar file using a staging directory.
*
* @license MIT, Michael Dowling https://github.com/mtdowling
* @license https://github.com/mtdowling/Burgomaster/LICENSE
*/
class Burgomaster
{
/** @var string Base staging directory of the project */
public $stageDir;
/** @var string Root directory of the project */
public $projectRoot;
/** @var array stack of sections */
private $sections = array();
/**
* @param string $stageDir Staging base directory where your packaging
* takes place. This folder will be created for
* you if it does not exist. If it exists, it
* will be deleted and recreated to start fresh.
* @param string $projectRoot Root directory of the project.
*
* @throws \InvalidArgumentException
* @throws \RuntimeException
*/
public function __construct($stageDir, $projectRoot = null)
{
$this->startSection('setting_up');
$this->stageDir = $stageDir;
$this->projectRoot = $projectRoot;
if (!$this->stageDir || $this->stageDir == '/') {
throw new \InvalidArgumentException('Invalid base directory');
}
if (is_dir($this->stageDir)) {
$this->debug("Removing existing directory: $this->stageDir");
echo $this->exec("rm -rf $this->stageDir");
}
$this->debug("Creating staging directory: $this->stageDir");
if (!mkdir($this->stageDir, 0777, true)) {
throw new \RuntimeException("Could not create {$this->stageDir}");
}
$this->stageDir = realpath($this->stageDir);
$this->debug("Creating staging directory at: {$this->stageDir}");
if (!is_dir($this->projectRoot)) {
throw new \InvalidArgumentException(
"Project root not found: $this->projectRoot"
);
}
$this->endSection();
$this->startSection('staging');
chdir($this->projectRoot);
}
/**
* Cleanup if the last section was not already closed.
*/
public function __destruct()
{
if ($this->sections) {
$this->endSection();
}
}
/**
* Call this method when starting a specific section of the packager.
*
* This makes the debug messages used in your script more meaningful and
* adds context when things go wrong. Be sure to call endSection() when
* you have finished a section of your packaging script.
*
* @param string $section Part of the packager that is running
*/
public function startSection($section)
{
$this->sections[] = $section;
$this->debug('Starting');
}
/**
* Call this method when leaving the last pushed section of the packager.
*/
public function endSection()
{
if ($this->sections) {
$this->debug('Completed');
array_pop($this->sections);
}
}
/**
* Prints a debug message to STDERR bound to the current section.
*
* @param string $message Message to echo to STDERR
*/
public function debug($message)
{
$prefix = date('c') . ': ';
if ($this->sections) {
$prefix .= '[' . end($this->sections) . '] ';
}
fwrite(STDERR, $prefix . $message . "\n");
}
/**
* Copies a file and creates the destination directory if needed.
*
* @param string $from File to copy
* @param string $to Destination to copy the file to, relative to the
* base staging directory.
* @throws \InvalidArgumentException if the file cannot be found
* @throws \RuntimeException if the directory cannot be created.
* @throws \RuntimeException if the file cannot be copied.
*/
public function deepCopy($from, $to)
{
if (!is_file($from)) {
throw new \InvalidArgumentException("File not found: {$from}");
}
$to = str_replace('//', '/', $this->stageDir . '/' . $to);
$dir = dirname($to);
if (!is_dir($dir)) {
if (!mkdir($dir, 0777, true)) {
throw new \RuntimeException("Unable to create directory: $dir");
}
}
if (!copy($from, $to)) {
throw new \RuntimeException("Unable to copy $from to $to");
}
}
/**
* Recursively copy one folder to another.
*
* Any LICENSE file is automatically copied.
*
* @param string $sourceDir Source directory to copy from
* @param string $destDir Directory to copy the files to that is relative
* to the the stage base directory.
* @param array $extensions File extensions to copy from the $sourceDir.
* Defaults to "php" files only (e.g., ['php']).
* @throws \InvalidArgumentException if the source directory is invalid.
*/
public function recursiveCopy(
$sourceDir,
$destDir,
$extensions = array('php')
) {
if (!realpath($sourceDir)) {
throw new \InvalidArgumentException("$sourceDir not found");
}
if (!$extensions) {
throw new \InvalidArgumentException('$extensions is empty!');
}
$sourceDir = realpath($sourceDir);
$exts = array_fill_keys($extensions, true);
$iter = new \RecursiveDirectoryIterator($sourceDir);
$iter = new \RecursiveIteratorIterator($iter);
$total = 0;
$this->startSection('copy');
$this->debug("Starting to copy files from $sourceDir");
foreach ($iter as $file) {
if (isset($exts[$file->getExtension()])
|| $file->getBaseName() == 'LICENSE'
) {
// Remove the source directory from the destination path
$toPath = str_replace($sourceDir, '', (string) $file);
$toPath = $destDir . '/' . $toPath;
$toPath = str_replace('//', '/', $toPath);
$this->deepCopy((string) $file, $toPath);
$total++;
}
}
$this->debug("Copied $total files from $sourceDir");
$this->endSection();
}
/**
* Execute a command and throw an exception if the return code is not 0.
*
* @param string $command Command to execute
*
* @return string Returns the output of the command as a string
* @throws \RuntimeException on error.
*/
public function exec($command)
{
$this->debug("Executing: $command");
$output = $returnValue = null;
exec($command, $output, $returnValue);
if ($returnValue != 0) {
throw new \RuntimeException('Error executing command: '
. $command . ' : ' . implode("\n", $output));
}
return implode("\n", $output);
}
/**
* Creates a class-map autoloader to the staging directory in a file
* named autoloader.php
*
* @param array $files Files to explicitly require in the autoloader. This
* is similar to Composer's "files" "autoload" section.
* @param string $filename Name of the autoloader file.
* @throws \RuntimeException if the file cannot be written
*/
public function createAutoloader($files = array(), $filename = 'autoloader.php')
{
$sourceDir = realpath($this->stageDir);
$iter = new \RecursiveDirectoryIterator($sourceDir);
$iter = new \RecursiveIteratorIterator($iter);
$this->startSection('autoloader');
$this->debug('Creating classmap autoloader');
$this->debug("Collecting valid PHP files from {$this->stageDir}");
$classMap = array();
foreach ($iter as $file) {
if ($file->getExtension() == 'php') {
$location = str_replace($this->stageDir . '/', '', (string) $file);
$className = str_replace('/', '\\', $location);
$className = substr($className, 0, -4);
// Remove "src\" or "lib\"
if (strpos($className, 'src\\') === 0
|| strpos($className, 'lib\\') === 0
) {
$className = substr($className, 4);
}
$classMap[$className] = "__DIR__ . '/$location'";
$this->debug("Found $className");
}
}
$destFile = $this->stageDir . '/' . $filename;
$this->debug("Writing autoloader to {$destFile}");
if (!($h = fopen($destFile, 'w'))) {
throw new \RuntimeException('Unable to open file for writing');
}
$this->debug('Writing classmap files');
fwrite($h, "<?php\n\n");
fwrite($h, "\$mapping = array(\n");
foreach ($classMap as $c => $f) {
fwrite($h, " '$c' => $f,\n");
}
fwrite($h, ");\n\n");
fwrite($h, <<<EOT
spl_autoload_register(function (\$class) use (\$mapping) {
if (isset(\$mapping[\$class])) {
require \$mapping[\$class];
}
}, true);
EOT
);
fwrite($h, "\n");
$this->debug('Writing automatically included files');
foreach ($files as $file) {
fwrite($h, "require __DIR__ . '/$file';\n");
}
fclose($h);
$this->endSection();
}
/**
* Creates a default stub for the phar that includeds the generated
* autoloader.
*
* This phar also registers a constant that can be used to check if you
* are running the phar. The constant is the basename of the $dest variable
* without the extension, with "_PHAR" appended, then converted to all
* caps (e.g., "/foo/guzzle.phar" gets a contant defined as GUZZLE_PHAR.
*
* @param $dest
* @param string $autoloaderFilename Name of the autoloader file.
*
* @return string
*/
private function createStub($dest, $autoloaderFilename = 'autoloader.php')
{
$this->startSection('stub');
$this->debug("Creating phar stub at $dest");
$alias = basename($dest);
$constName = str_replace('.phar', '', strtoupper($alias)) . '_PHAR';
$stub = "<?php\n";
$stub .= "define('$constName', true);\n";
$stub .= "require 'phar://$alias/{$autoloaderFilename}';\n";
$stub .= "__HALT_COMPILER();\n";
$this->endSection();
return $stub;
}
/**
* Creates a phar that automatically registers an autoloader.
*
* Call this only after your staging directory is built.
*
* @param string $dest Where to save the file. The basename of the file
* is also used as the alias name in the phar
* (e.g., /path/to/guzzle.phar => guzzle.phar).
* @param string|bool|null $stub The path to the phar stub file. Pass or
* leave null to automatically have one created for you. Pass false
* to no use a stub in the generated phar.
* @param string $autoloaderFilename Name of the autolaoder filename.
*/
public function createPhar(
$dest,
$stub = null,
$autoloaderFilename = 'autoloader.php'
) {
$this->startSection('phar');
$this->debug("Creating phar file at $dest");
$this->createDirIfNeeded(dirname($dest));
$phar = new \Phar($dest, 0, basename($dest));
$phar->buildFromDirectory($this->stageDir);
if ($stub !== false) {
if (!$stub) {
$stub = $this->createStub($dest, $autoloaderFilename);
}
$phar->setStub($stub);
}
$this->debug("Created phar at $dest");
$this->endSection();
}
/**
* Creates a zip file containing the staged files of your project.
*
* Call this only after your staging directory is built.
*
* @param string $dest Where to save the zip file
*/
public function createZip($dest)
{
$this->startSection('zip');
$this->debug("Creating a zip file at $dest");
$this->createDirIfNeeded(dirname($dest));
chdir($this->stageDir);
$this->exec("zip -r $dest ./");
$this->debug(" > Created at $dest");
chdir(__DIR__);
$this->endSection();
}
private function createDirIfNeeded($dir)
{
if (!is_dir($dir) && !mkdir($dir, 0755, true)) {
throw new \RuntimeException("Could not create dir: $dir");
}
}
}

View File

@ -0,0 +1,27 @@
<?php
require __DIR__ . '/Burgomaster.php';
$stageDirectory = __DIR__ . '/artifacts/staging';
$projectRoot = __DIR__ . '/../';
$packager = new \Burgomaster($stageDirectory, $projectRoot);
// Copy basic files to the stage directory. Note that we have chdir'd onto
// the $projectRoot directory, so use relative paths.
foreach (['README.md', 'LICENSE'] as $file) {
$packager->deepCopy($file, $file);
}
// Copy each dependency to the staging directory. Copy *.php and *.pem files.
$packager->recursiveCopy('src', 'GuzzleHttp', ['php']);
$packager->recursiveCopy('vendor/guzzlehttp/promises/src', 'GuzzleHttp/Promise');
$packager->recursiveCopy('vendor/guzzlehttp/psr7/src', 'GuzzleHttp/Psr7');
$packager->recursiveCopy('vendor/psr/http-message/src', 'Psr/Http/Message');
$packager->createAutoloader([
'GuzzleHttp/functions_include.php',
'GuzzleHttp/Psr7/functions_include.php',
'GuzzleHttp/Promise/functions_include.php',
]);
$packager->createPhar(__DIR__ . '/artifacts/guzzle.phar');
$packager->createZip(__DIR__ . '/artifacts/guzzle.zip');

View File

@ -0,0 +1,153 @@
# Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = _build
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " texinfo to make Texinfo files"
@echo " info to make Texinfo files and run them through makeinfo"
@echo " gettext to make PO message catalogs"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
clean:
-rm -rf $(BUILDDIR)/*
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/Guzzle.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Guzzle.qhc"
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/Guzzle"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/Guzzle"
@echo "# devhelp"
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
texinfo:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
@echo "Run \`make' in that directory to run these through makeinfo" \
"(use \`make info' here to do that automatically)."
info:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo "Running Texinfo files through makeinfo..."
make -C $(BUILDDIR)/texinfo info
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
gettext:
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
@echo
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."

Binary file not shown.

After

Width:  |  Height:  |  Size: 803 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 242 KiB

View File

@ -0,0 +1,68 @@
import sys, os
from sphinx.highlighting import lexers
from pygments.lexers.web import PhpLexer
lexers['php'] = PhpLexer(startinline=True, linenos=1)
lexers['php-annotations'] = PhpLexer(startinline=True, linenos=1)
primary_domain = 'php'
extensions = []
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'Guzzle'
copyright = u'2015, Michael Dowling'
version = '6'
html_title = "Guzzle Documentation"
html_short_title = "Guzzle 6"
exclude_patterns = ['_build']
html_static_path = ['_static']
##### Guzzle sphinx theme
import guzzle_sphinx_theme
html_translator_class = 'guzzle_sphinx_theme.HTMLTranslator'
html_theme_path = guzzle_sphinx_theme.html_theme_path()
html_theme = 'guzzle_sphinx_theme'
# Custom sidebar templates, maps document names to template names.
html_sidebars = {
'**': ['logo-text.html', 'globaltoc.html', 'searchbox.html']
}
# Register the theme as an extension to generate a sitemap.xml
extensions.append("guzzle_sphinx_theme")
# Guzzle theme options (see theme.conf for more information)
html_theme_options = {
# Set the path to a special layout to include for the homepage
# "index_template": "homepage.html",
# Allow a separate homepage from the master_doc
# homepage = index
# Set the name of the project to appear in the nav menu
# "project_nav_name": "Guzzle",
# Set your Disqus short name to enable comments
# "disqus_comments_shortname": "my_disqus_comments_short_name",
# Set you GA account ID to enable tracking
# "google_analytics_account": "my_ga_account",
# Path to a touch icon
# "touch_icon": "",
# Specify a base_url used to generate sitemap.xml links. If not
# specified, then no sitemap will be built.
"base_url": "http://guzzlephp.org"
# Allow the "Table of Contents" page to be defined separately from "master_doc"
# tocpage = Contents
# Allow the project link to be overriden to a custom URL.
# projectlink = http://myproject.url
}

View File

@ -0,0 +1,193 @@
===
FAQ
===
Does Guzzle require cURL?
=========================
No. Guzzle can use any HTTP handler to send requests. This means that Guzzle
can be used with cURL, PHP's stream wrapper, sockets, and non-blocking libraries
like `React <http://reactphp.org/>`_. You just need to configure an HTTP handler
to use a different method of sending requests.
.. note::
Guzzle has historically only utilized cURL to send HTTP requests. cURL is
an amazing HTTP client (arguably the best), and Guzzle will continue to use
it by default when it is available. It is rare, but some developers don't
have cURL installed on their systems or run into version specific issues.
By allowing swappable HTTP handlers, Guzzle is now much more customizable
and able to adapt to fit the needs of more developers.
Can Guzzle send asynchronous requests?
======================================
Yes. You can use the ``requestAsync``, ``sendAsync``, ``getAsync``,
``headAsync``, ``putAsync``, ``postAsync``, ``deleteAsync``, and ``patchAsync``
methods of a client to send an asynchronous request. The client will return a
``GuzzleHttp\Promise\PromiseInterface`` object. You can chain ``then``
functions off of the promise.
.. code-block:: php
$promise = $client->requestAsync('GET', 'http://httpbin.org/get');
$promise->then(function ($response) {
echo 'Got a response! ' . $response->getStatusCode();
});
You can force an asynchronous response to complete using the ``wait()`` method
of the returned promise.
.. code-block:: php
$promise = $client->requestAsync('GET', 'http://httpbin.org/get');
$response = $promise->wait();
How can I add custom cURL options?
==================================
cURL offers a huge number of `customizable options <http://us1.php.net/curl_setopt>`_.
While Guzzle normalizes many of these options across different handlers, there
are times when you need to set custom cURL options. This can be accomplished
by passing an associative array of cURL settings in the **curl** key of a
request.
For example, let's say you need to customize the outgoing network interface
used with a client.
.. code-block:: php
$client->request('GET', '/', [
'curl' => [
CURLOPT_INTERFACE => 'xxx.xxx.xxx.xxx'
]
]);
If you use asynchronous requests with cURL multi handler and want to tweak it,
additional options can be specified as an associative array in the
**options** key of the ``CurlMultiHandler`` constructor.
.. code-block:: php
use \GuzzleHttp\Client;
use \GuzzleHttp\HandlerStack;
use \GuzzleHttp\Handler\CurlMultiHandler;
$client = new Client(['handler' => HandlerStack::create(new CurlMultiHandler([
'options' => [
CURLMOPT_MAX_TOTAL_CONNECTIONS => 50,
CURLMOPT_MAX_HOST_CONNECTIONS => 5,
]
]))]);
How can I add custom stream context options?
============================================
You can pass custom `stream context options <http://www.php.net/manual/en/context.php>`_
using the **stream_context** key of the request option. The **stream_context**
array is an associative array where each key is a PHP transport, and each value
is an associative array of transport options.
For example, let's say you need to customize the outgoing network interface
used with a client and allow self-signed certificates.
.. code-block:: php
$client->request('GET', '/', [
'stream' => true,
'stream_context' => [
'ssl' => [
'allow_self_signed' => true
],
'socket' => [
'bindto' => 'xxx.xxx.xxx.xxx'
]
]
]);
Why am I getting an SSL verification error?
===========================================
You need to specify the path on disk to the CA bundle used by Guzzle for
verifying the peer certificate. See :ref:`verify-option`.
What is this Maximum function nesting error?
============================================
Maximum function nesting level of '100' reached, aborting
You could run into this error if you have the XDebug extension installed and
you execute a lot of requests in callbacks. This error message comes
specifically from the XDebug extension. PHP itself does not have a function
nesting limit. Change this setting in your php.ini to increase the limit::
xdebug.max_nesting_level = 1000
Why am I getting a 417 error response?
======================================
This can occur for a number of reasons, but if you are sending PUT, POST, or
PATCH requests with an ``Expect: 100-Continue`` header, a server that does not
support this header will return a 417 response. You can work around this by
setting the ``expect`` request option to ``false``:
.. code-block:: php
$client = new GuzzleHttp\Client();
// Disable the expect header on a single request
$response = $client->request('PUT', '/', ['expect' => false]);
// Disable the expect header on all client requests
$client = new GuzzleHttp\Client(['expect' => false]);
How can I track redirected requests?
====================================
You can enable tracking of redirected URIs and status codes via the
`track_redirects` option. Each redirected URI and status code will be stored in the
``X-Guzzle-Redirect-History`` and the ``X-Guzzle-Redirect-Status-History``
header respectively.
The initial request's URI and the final status code will be excluded from the results.
With this in mind you should be able to easily track a request's full redirect path.
For example, let's say you need to track redirects and provide both results
together in a single report:
.. code-block:: php
// First you configure Guzzle with redirect tracking and make a request
$client = new Client([
RequestOptions::ALLOW_REDIRECTS => [
'max' => 10, // allow at most 10 redirects.
'strict' => true, // use "strict" RFC compliant redirects.
'referer' => true, // add a Referer header
'track_redirects' => true,
],
]);
$initialRequest = '/redirect/3'; // Store the request URI for later use
$response = $client->request('GET', $initialRequest); // Make your request
// Retrieve both Redirect History headers
$redirectUriHistory = $response->getHeader('X-Guzzle-Redirect-History')[0]; // retrieve Redirect URI history
$redirectCodeHistory = $response->getHeader('X-Guzzle-Redirect-Status-History')[0]; // retrieve Redirect HTTP Status history
// Add the initial URI requested to the (beginning of) URI history
array_unshift($redirectUriHistory, $initialRequest);
// Add the final HTTP status code to the end of HTTP response history
array_push($redirectCodeHistory, $response->getStatusCode());
// (Optional) Combine the items of each array into a single result set
$fullRedirectReport = [];
foreach ($redirectUriHistory as $key => $value) {
$fullRedirectReport[$key] = ['location' => $value, 'code' => $redirectCodeHistory[$key]];
}
echo json_encode($fullRedirectReport);

View File

@ -0,0 +1,303 @@
=======================
Handlers and Middleware
=======================
Guzzle clients use a handler and middleware system to send HTTP requests.
Handlers
========
A handler function accepts a ``Psr\Http\Message\RequestInterface`` and array of
request options and returns a ``GuzzleHttp\Promise\PromiseInterface`` that is
fulfilled with a ``Psr\Http\Message\ResponseInterface`` or rejected with an
exception.
You can provide a custom handler to a client using the ``handler`` option of
a client constructor. It is important to understand that several request
options used by Guzzle require that specific middlewares wrap the handler used
by the client. You can ensure that the handler you provide to a client uses the
default middlewares by wrapping the handler in the
``GuzzleHttp\HandlerStack::create(callable $handler = null)`` static method.
.. code-block:: php
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Handler\CurlHandler;
$handler = new CurlHandler();
$stack = HandlerStack::create($handler); // Wrap w/ middleware
$client = new Client(['handler' => $stack]);
The ``create`` method adds default handlers to the ``HandlerStack``. When the
``HandlerStack`` is resolved, the handlers will execute in the following order:
1. Sending request:
1. ``http_errors`` - No op when sending a request. The response status code
is checked in the response processing when returning a response promise up
the stack.
2. ``allow_redirects`` - No op when sending a request. Following redirects
occurs when a response promise is being returned up the stack.
3. ``cookies`` - Adds cookies to requests.
4. ``prepare_body`` - The body of an HTTP request will be prepared (e.g.,
add default headers like Content-Length, Content-Type, etc.).
5. <send request with handler>
2. Processing response:
1. ``prepare_body`` - no op on response processing.
2. ``cookies`` - extracts response cookies into the cookie jar.
3. ``allow_redirects`` - Follows redirects.
4. ``http_errors`` - throws exceptions when the response status code ``>=``
400.
When provided no ``$handler`` argument, ``GuzzleHttp\HandlerStack::create()``
will choose the most appropriate handler based on the extensions available on
your system.
.. important::
The handler provided to a client determines how request options are applied
and utilized for each request sent by a client. For example, if you do not
have a cookie middleware associated with a client, then setting the
``cookies`` request option will have no effect on the request.
Middleware
==========
Middleware augments the functionality of handlers by invoking them in the
process of generating responses. Middleware is implemented as a higher order
function that takes the following form.
.. code-block:: php
use Psr\Http\Message\RequestInterface;
function my_middleware()
{
return function (callable $handler) {
return function (RequestInterface $request, array $options) use ($handler) {
return $handler($request, $options);
};
};
}
Middleware functions return a function that accepts the next handler to invoke.
This returned function then returns another function that acts as a composed
handler-- it accepts a request and options, and returns a promise that is
fulfilled with a response. Your composed middleware can modify the request,
add custom request options, and modify the promise returned by the downstream
handler.
Here's an example of adding a header to each request.
.. code-block:: php
use Psr\Http\Message\RequestInterface;
function add_header($header, $value)
{
return function (callable $handler) use ($header, $value) {
return function (
RequestInterface $request,
array $options
) use ($handler, $header, $value) {
$request = $request->withHeader($header, $value);
return $handler($request, $options);
};
};
}
Once a middleware has been created, you can add it to a client by either
wrapping the handler used by the client or by decorating a handler stack.
.. code-block:: php
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Handler\CurlHandler;
use GuzzleHttp\Client;
$stack = new HandlerStack();
$stack->setHandler(new CurlHandler());
$stack->push(add_header('X-Foo', 'bar'));
$client = new Client(['handler' => $stack]);
Now when you send a request, the client will use a handler composed with your
added middleware, adding a header to each request.
Here's an example of creating a middleware that modifies the response of the
downstream handler. This example adds a header to the response.
.. code-block:: php
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Handler\CurlHandler;
use GuzzleHttp\Client;
function add_response_header($header, $value)
{
return function (callable $handler) use ($header, $value) {
return function (
RequestInterface $request,
array $options
) use ($handler, $header, $value) {
$promise = $handler($request, $options);
return $promise->then(
function (ResponseInterface $response) use ($header, $value) {
return $response->withHeader($header, $value);
}
);
};
};
}
$stack = new HandlerStack();
$stack->setHandler(new CurlHandler());
$stack->push(add_response_header('X-Foo', 'bar'));
$client = new Client(['handler' => $stack]);
Creating a middleware that modifies a request is made much simpler using the
``GuzzleHttp\Middleware::mapRequest()`` middleware. This middleware accepts
a function that takes the request argument and returns the request to send.
.. code-block:: php
use Psr\Http\Message\RequestInterface;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Handler\CurlHandler;
use GuzzleHttp\Client;
use GuzzleHttp\Middleware;
$stack = new HandlerStack();
$stack->setHandler(new CurlHandler());
$stack->push(Middleware::mapRequest(function (RequestInterface $request) {
return $request->withHeader('X-Foo', 'bar');
}));
$client = new Client(['handler' => $stack]);
Modifying a response is also much simpler using the
``GuzzleHttp\Middleware::mapResponse()`` middleware.
.. code-block:: php
use Psr\Http\Message\ResponseInterface;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Handler\CurlHandler;
use GuzzleHttp\Client;
use GuzzleHttp\Middleware;
$stack = new HandlerStack();
$stack->setHandler(new CurlHandler());
$stack->push(Middleware::mapResponse(function (ResponseInterface $response) {
return $response->withHeader('X-Foo', 'bar');
}));
$client = new Client(['handler' => $stack]);
HandlerStack
============
A handler stack represents a stack of middleware to apply to a base handler
function. You can push middleware to the stack to add to the top of the stack,
and unshift middleware onto the stack to add to the bottom of the stack. When
the stack is resolved, the handler is pushed onto the stack. Each value is
then popped off of the stack, wrapping the previous value popped off of the
stack.
.. code-block:: php
use Psr\Http\Message\RequestInterface;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use GuzzleHttp\Client;
$stack = new HandlerStack();
$stack->setHandler(\GuzzleHttp\choose_handler());
$stack->push(Middleware::mapRequest(function (RequestInterface $r) {
echo 'A';
return $r;
});
$stack->push(Middleware::mapRequest(function (RequestInterface $r) {
echo 'B';
return $r;
});
$stack->push(Middleware::mapRequest(function (RequestInterface $r) {
echo 'C';
return $r;
});
$client->request('GET', 'http://httpbin.org/');
// echoes 'ABC';
$stack->unshift(Middleware::mapRequest(function (RequestInterface $r) {
echo '0';
return $r;
});
$client = new Client(['handler' => $stack]);
$client->request('GET', 'http://httpbin.org/');
// echoes '0ABC';
You can give middleware a name, which allows you to add middleware before
other named middleware, after other named middleware, or remove middleware
by name.
.. code-block:: php
use Psr\Http\Message\RequestInterface;
use GuzzleHttp\Middleware;
// Add a middleware with a name
$stack->push(Middleware::mapRequest(function (RequestInterface $r) {
return $r->withHeader('X-Foo', 'Bar');
}, 'add_foo');
// Add a middleware before a named middleware (unshift before).
$stack->before('add_foo', Middleware::mapRequest(function (RequestInterface $r) {
return $r->withHeader('X-Baz', 'Qux');
}, 'add_baz');
// Add a middleware after a named middleware (pushed after).
$stack->after('add_baz', Middleware::mapRequest(function (RequestInterface $r) {
return $r->withHeader('X-Lorem', 'Ipsum');
});
// Remove a middleware by name
$stack->remove('add_foo');
Creating a Handler
==================
As stated earlier, a handler is a function accepts a
``Psr\Http\Message\RequestInterface`` and array of request options and returns
a ``GuzzleHttp\Promise\PromiseInterface`` that is fulfilled with a
``Psr\Http\Message\ResponseInterface`` or rejected with an exception.
A handler is responsible for applying the following :doc:`request-options`.
These request options are a subset of request options called
"transfer options".
- :ref:`cert-option`
- :ref:`connect_timeout-option`
- :ref:`debug-option`
- :ref:`delay-option`
- :ref:`decode_content-option`
- :ref:`expect-option`
- :ref:`proxy-option`
- :ref:`sink-option`
- :ref:`timeout-option`
- :ref:`ssl_key-option`
- :ref:`stream-option`
- :ref:`verify-option`

View File

@ -0,0 +1,54 @@
.. title:: Guzzle, PHP HTTP client
====================
Guzzle Documentation
====================
Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and
trivial to integrate with web services.
- Simple interface for building query strings, POST requests, streaming large
uploads, streaming large downloads, using HTTP cookies, uploading JSON data,
etc...
- Can send both synchronous and asynchronous requests using the same interface.
- Uses PSR-7 interfaces for requests, responses, and streams. This allows you
to utilize other PSR-7 compatible libraries with Guzzle.
- Abstracts away the underlying HTTP transport, allowing you to write
environment and transport agnostic code; i.e., no hard dependency on cURL,
PHP streams, sockets, or non-blocking event loops.
- Middleware system allows you to augment and compose client behavior.
.. code-block:: php
$client = new GuzzleHttp\Client();
$res = $client->request('GET', 'https://api.github.com/user', [
'auth' => ['user', 'pass']
]);
echo $res->getStatusCode();
// "200"
echo $res->getHeader('content-type')[0];
// 'application/json; charset=utf8'
echo $res->getBody();
// {"type":"User"...'
// Send an asynchronous request.
$request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org');
$promise = $client->sendAsync($request)->then(function ($response) {
echo 'I completed! ' . $response->getBody();
});
$promise->wait();
User Guide
==========
.. toctree::
:maxdepth: 3
overview
quickstart
request-options
psr7
handlers-and-middleware
testing
faq

View File

@ -0,0 +1,161 @@
========
Overview
========
Requirements
============
#. PHP 5.5.0
#. To use the PHP stream handler, ``allow_url_fopen`` must be enabled in your
system's php.ini.
#. To use the cURL handler, you must have a recent version of cURL >= 7.19.4
compiled with OpenSSL and zlib.
.. note::
Guzzle no longer requires cURL in order to send HTTP requests. Guzzle will
use the PHP stream wrapper to send HTTP requests if cURL is not installed.
Alternatively, you can provide your own HTTP handler used to send requests.
Keep in mind that cURL is still required for sending concurrent requests.
.. _installation:
Installation
============
The recommended way to install Guzzle is with
`Composer <http://getcomposer.org>`_. Composer is a dependency management tool
for PHP that allows you to declare the dependencies your project needs and
installs them into your project.
.. code-block:: bash
# Install Composer
curl -sS https://getcomposer.org/installer | php
You can add Guzzle as a dependency using the composer.phar CLI:
.. code-block:: bash
php composer.phar require guzzlehttp/guzzle:~6.0
Alternatively, you can specify Guzzle as a dependency in your project's
existing composer.json file:
.. code-block:: js
{
"require": {
"guzzlehttp/guzzle": "~6.0"
}
}
After installing, you need to require Composer's autoloader:
.. code-block:: php
require 'vendor/autoload.php';
You can find out more on how to install Composer, configure autoloading, and
other best-practices for defining dependencies at `getcomposer.org <http://getcomposer.org>`_.
Bleeding edge
-------------
During your development, you can keep up with the latest changes on the master
branch by setting the version requirement for Guzzle to ``~6.0@dev``.
.. code-block:: js
{
"require": {
"guzzlehttp/guzzle": "~6.0@dev"
}
}
License
=======
Licensed using the `MIT license <http://opensource.org/licenses/MIT>`_.
Copyright (c) 2015 Michael Dowling <https://github.com/mtdowling>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
Contributing
============
Guidelines
----------
1. Guzzle utilizes PSR-1, PSR-2, PSR-4, and PSR-7.
2. Guzzle is meant to be lean and fast with very few dependencies. This means
that not every feature request will be accepted.
3. Guzzle has a minimum PHP version requirement of PHP 5.5. Pull requests must
not require a PHP version greater than PHP 5.5 unless the feature is only
utilized conditionally.
4. All pull requests must include unit tests to ensure the change works as
expected and to prevent regressions.
Running the tests
-----------------
In order to contribute, you'll need to checkout the source from GitHub and
install Guzzle's dependencies using Composer:
.. code-block:: bash
git clone https://github.com/guzzle/guzzle.git
cd guzzle && curl -s http://getcomposer.org/installer | php && ./composer.phar install --dev
Guzzle is unit tested with PHPUnit. Run the tests using the Makefile:
.. code-block:: bash
make test
.. note::
You'll need to install node.js v0.5.0 or newer in order to perform
integration tests on Guzzle's HTTP handlers.
Reporting a security vulnerability
==================================
We want to ensure that Guzzle is a secure HTTP client library for everyone. If
you've discovered a security vulnerability in Guzzle, we appreciate your help
in disclosing it to us in a `responsible manner <http://en.wikipedia.org/wiki/Responsible_disclosure>`_.
Publicly disclosing a vulnerability can put the entire community at risk. If
you've discovered a security concern, please email us at
security@guzzlephp.org. We'll work with you to make sure that we understand the
scope of the issue, and that we fully address your concern. We consider
correspondence sent to security@guzzlephp.org our highest priority, and work to
address any issues that arise as quickly as possible.
After a security vulnerability has been corrected, a security hotfix release will
be deployed as soon as possible.

View File

@ -0,0 +1,456 @@
================
Guzzle and PSR-7
================
Guzzle utilizes PSR-7 as the HTTP message interface. This allows Guzzle to work
with any other library that utilizes PSR-7 message interfaces.
Guzzle is an HTTP client that sends HTTP requests to a server and receives HTTP
responses. Both requests and responses are referred to as messages.
Guzzle relies on the ``guzzlehttp/psr7`` Composer package for its message
implementation of PSR-7.
You can create a request using the ``GuzzleHttp\Psr7\Request`` class:
.. code-block:: php
use GuzzleHttp\Psr7\Request;
$request = new Request('GET', 'http://httpbin.org/get');
// You can provide other optional constructor arguments.
$headers = ['X-Foo' => 'Bar'];
$body = 'hello!';
$request = new Request('PUT', 'http://httpbin.org/put', $headers, $body);
You can create a response using the ``GuzzleHttp\Psr7\Response`` class:
.. code-block:: php
use GuzzleHttp\Psr7\Response;
// The constructor requires no arguments.
$response = new Response();
echo $response->getStatusCode(); // 200
echo $response->getProtocolVersion(); // 1.1
// You can supply any number of optional arguments.
$status = 200;
$headers = ['X-Foo' => 'Bar'];
$body = 'hello!';
$protocol = '1.1';
$response = new Response($status, $headers, $body, $protocol);
Headers
=======
Both request and response messages contain HTTP headers.
Accessing Headers
-----------------
You can check if a request or response has a specific header using the
``hasHeader()`` method.
.. code-block:: php
use GuzzleHttp\Psr7;
$request = new Psr7\Request('GET', '/', ['X-Foo' => 'bar']);
if ($request->hasHeader('X-Foo')) {
echo 'It is there';
}
You can retrieve all the header values as an array of strings using
``getHeader()``.
.. code-block:: php
$request->getHeader('X-Foo'); // ['bar']
// Retrieving a missing header returns an empty array.
$request->getHeader('X-Bar'); // []
You can iterate over the headers of a message using the ``getHeaders()``
method.
.. code-block:: php
foreach ($request->getHeaders() as $name => $values) {
echo $name . ': ' . implode(', ', $values) . "\r\n";
}
Complex Headers
---------------
Some headers contain additional key value pair information. For example, Link
headers contain a link and several key value pairs:
::
<http://foo.com>; rel="thing"; type="image/jpeg"
Guzzle provides a convenience feature that can be used to parse these types of
headers:
.. code-block:: php
use GuzzleHttp\Psr7;
$request = new Psr7\Request('GET', '/', [
'Link' => '<http:/.../front.jpeg>; rel="front"; type="image/jpeg"'
]);
$parsed = Psr7\parse_header($request->getHeader('Link'));
var_export($parsed);
Will output:
.. code-block:: php
array (
0 =>
array (
0 => '<http:/.../front.jpeg>',
'rel' => 'front',
'type' => 'image/jpeg',
),
)
The result contains a hash of key value pairs. Header values that have no key
(i.e., the link) are indexed numerically while headers parts that form a key
value pair are added as a key value pair.
Body
====
Both request and response messages can contain a body.
You can retrieve the body of a message using the ``getBody()`` method:
.. code-block:: php
$response = GuzzleHttp\get('http://httpbin.org/get');
echo $response->getBody();
// JSON string: { ... }
The body used in request and response objects is a
``Psr\Http\Message\StreamInterface``. This stream is used for both
uploading data and downloading data. Guzzle will, by default, store the body of
a message in a stream that uses PHP temp streams. When the size of the body
exceeds 2 MB, the stream will automatically switch to storing data on disk
rather than in memory (protecting your application from memory exhaustion).
The easiest way to create a body for a message is using the ``stream_for``
function from the ``GuzzleHttp\Psr7`` namespace --
``GuzzleHttp\Psr7\stream_for``. This function accepts strings, resources,
callables, iterators, other streamables, and returns an instance of
``Psr\Http\Message\StreamInterface``.
The body of a request or response can be cast to a string or you can read and
write bytes off of the stream as needed.
.. code-block:: php
use GuzzleHttp\Stream\Stream;
$response = $client->request('GET', 'http://httpbin.org/get');
echo $response->getBody()->read(4);
echo $response->getBody()->read(4);
echo $response->getBody()->read(1024);
var_export($response->eof());
Requests
========
Requests are sent from a client to a server. Requests include the method to
be applied to a resource, the identifier of the resource, and the protocol
version to use.
Request Methods
---------------
When creating a request, you are expected to provide the HTTP method you wish
to perform. You can specify any method you'd like, including a custom method
that might not be part of RFC 7231 (like "MOVE").
.. code-block:: php
// Create a request using a completely custom HTTP method
$request = new \GuzzleHttp\Psr7\Request('MOVE', 'http://httpbin.org/move');
echo $request->getMethod();
// MOVE
You can create and send a request using methods on a client that map to the
HTTP method you wish to use.
:GET: ``$client->get('http://httpbin.org/get', [/** options **/])``
:POST: ``$client->post('http://httpbin.org/post', [/** options **/])``
:HEAD: ``$client->head('http://httpbin.org/get', [/** options **/])``
:PUT: ``$client->put('http://httpbin.org/put', [/** options **/])``
:DELETE: ``$client->delete('http://httpbin.org/delete', [/** options **/])``
:OPTIONS: ``$client->options('http://httpbin.org/get', [/** options **/])``
:PATCH: ``$client->patch('http://httpbin.org/put', [/** options **/])``
For example:
.. code-block:: php
$response = $client->patch('http://httpbin.org/patch', ['body' => 'content']);
Request URI
-----------
The request URI is represented by a ``Psr\Http\Message\UriInterface`` object.
Guzzle provides an implementation of this interface using the
``GuzzleHttp\Psr7\Uri`` class.
When creating a request, you can provide the URI as a string or an instance of
``Psr\Http\Message\UriInterface``.
.. code-block:: php
$response = $client->request('GET', 'http://httpbin.org/get?q=foo');
Scheme
------
The `scheme <http://tools.ietf.org/html/rfc3986#section-3.1>`_ of a request
specifies the protocol to use when sending the request. When using Guzzle, the
scheme can be set to "http" or "https".
.. code-block:: php
$request = new Request('GET', 'http://httpbin.org');
echo $request->getUri()->getScheme(); // http
echo $request->getUri(); // http://httpbin.org
Host
----
The host is accessible using the URI owned by the request or by accessing the
Host header.
.. code-block:: php
$request = new Request('GET', 'http://httpbin.org');
echo $request->getUri()->getHost(); // httpbin.org
echo $request->getHeader('Host'); // httpbin.org
Port
----
No port is necessary when using the "http" or "https" schemes.
.. code-block:: php
$request = new Request('GET', 'http://httpbin.org:8080');
echo $request->getUri()->getPort(); // 8080
echo $request->getUri(); // http://httpbin.org:8080
Path
----
The path of a request is accessible via the URI object.
.. code-block:: php
$request = new Request('GET', 'http://httpbin.org/get');
echo $request->getUri()->getPath(); // /get
The contents of the path will be automatically filtered to ensure that only
allowed characters are present in the path. Any characters that are not allowed
in the path will be percent-encoded according to
`RFC 3986 section 3.3 <https://tools.ietf.org/html/rfc3986#section-3.3>`_
Query string
------------
The query string of a request can be accessed using the ``getQuery()`` of the
URI object owned by the request.
.. code-block:: php
$request = new Request('GET', 'http://httpbin.org/?foo=bar');
echo $request->getUri()->getQuery(); // foo=bar
The contents of the query string will be automatically filtered to ensure that
only allowed characters are present in the query string. Any characters that
are not allowed in the query string will be percent-encoded according to
`RFC 3986 section 3.4 <https://tools.ietf.org/html/rfc3986#section-3.4>`_
Responses
=========
Responses are the HTTP messages a client receives from a server after sending
an HTTP request message.
Start-Line
----------
The start-line of a response contains the protocol and protocol version,
status code, and reason phrase.
.. code-block:: php
$client = new \GuzzleHttp\Client();
$response = $client->request('GET', 'http://httpbin.org/get');
echo $response->getStatusCode(); // 200
echo $response->getReasonPhrase(); // OK
echo $response->getProtocolVersion(); // 1.1
Body
----
As described earlier, you can get the body of a response using the
``getBody()`` method.
.. code-block:: php
$body = $response->getBody();
echo $body;
// Cast to a string: { ... }
$body->seek(0);
// Rewind the body
$body->read(1024);
// Read bytes of the body
Streams
=======
Guzzle uses PSR-7 stream objects to represent request and response message
bodies. These stream objects allow you to work with various types of data all
using a common interface.
HTTP messages consist of a start-line, headers, and a body. The body of an HTTP
message can be very small or extremely large. Attempting to represent the body
of a message as a string can easily consume more memory than intended because
the body must be stored completely in memory. Attempting to store the body of a
request or response in memory would preclude the use of that implementation from
being able to work with large message bodies. The StreamInterface is used in
order to hide the implementation details of where a stream of data is read from
or written to.
The PSR-7 ``Psr\Http\Message\StreamInterface`` exposes several methods
that enable streams to be read from, written to, and traversed effectively.
Streams expose their capabilities using three methods: ``isReadable()``,
``isWritable()``, and ``isSeekable()``. These methods can be used by stream
collaborators to determine if a stream is capable of their requirements.
Each stream instance has various capabilities: they can be read-only,
write-only, read-write, allow arbitrary random access (seeking forwards or
backwards to any location), or only allow sequential access (for example in the
case of a socket or pipe).
Guzzle uses the ``guzzlehttp/psr7`` package to provide stream support. More
information on using streams, creating streams, converting streams to PHP
stream resource, and stream decorators can be found in the
`Guzzle PSR-7 documentation <https://github.com/guzzle/psr7/blob/master/README.md>`_.
Creating Streams
----------------
The best way to create a stream is using the ``GuzzleHttp\Psr7\stream_for``
function. This function accepts strings, resources returned from ``fopen()``,
an object that implements ``__toString()``, iterators, callables, and instances
of ``Psr\Http\Message\StreamInterface``.
.. code-block:: php
use GuzzleHttp\Psr7;
$stream = Psr7\stream_for('string data');
echo $stream;
// string data
echo $stream->read(3);
// str
echo $stream->getContents();
// ing data
var_export($stream->eof());
// true
var_export($stream->tell());
// 11
You can create streams from iterators. The iterator can yield any number of
bytes per iteration. Any excess bytes returned by the iterator that were not
requested by a stream consumer will be buffered until a subsequent read.
.. code-block:: php
use GuzzleHttp\Psr7;
$generator = function ($bytes) {
for ($i = 0; $i < $bytes; $i++) {
yield '.';
}
};
$iter = $generator(1024);
$stream = Psr7\stream_for($iter);
echo $stream->read(3); // ...
Metadata
--------
Streams expose stream metadata through the ``getMetadata()`` method. This
method provides the data you would retrieve when calling PHP's
`stream_get_meta_data() function <http://php.net/manual/en/function.stream-get-meta-data.php>`_,
and can optionally expose other custom data.
.. code-block:: php
use GuzzleHttp\Psr7;
$resource = fopen('/path/to/file', 'r');
$stream = Psr7\stream_for($resource);
echo $stream->getMetadata('uri');
// /path/to/file
var_export($stream->isReadable());
// true
var_export($stream->isWritable());
// false
var_export($stream->isSeekable());
// true
Stream Decorators
-----------------
Adding custom functionality to streams is very simple with stream decorators.
Guzzle provides several built-in decorators that provide additional stream
functionality.
- `AppendStream <https://github.com/guzzle/psr7#appendstream>`_
- `BufferStream <https://github.com/guzzle/psr7#bufferstream>`_
- `CachingStream <https://github.com/guzzle/psr7#cachingstream>`_
- `DroppingStream <https://github.com/guzzle/psr7#droppingstream>`_
- `FnStream <https://github.com/guzzle/psr7#fnstream>`_
- `InflateStream <https://github.com/guzzle/psr7#inflatestream>`_
- `LazyOpenStream <https://github.com/guzzle/psr7#lazyopenstream>`_
- `LimitStream <https://github.com/guzzle/psr7#limitstream>`_
- `MultipartStream <https://github.com/guzzle/psr7#multipartstream>`_
- `NoSeekStream <https://github.com/guzzle/psr7#noseekstream>`_
- `PumpStream <https://github.com/guzzle/psr7#pumpstream>`_

View File

@ -0,0 +1,624 @@
==========
Quickstart
==========
This page provides a quick introduction to Guzzle and introductory examples.
If you have not already installed, Guzzle, head over to the :ref:`installation`
page.
Making a Request
================
You can send requests with Guzzle using a ``GuzzleHttp\ClientInterface``
object.
Creating a Client
-----------------
.. code-block:: php
use GuzzleHttp\Client;
$client = new Client([
// Base URI is used with relative requests
'base_uri' => 'http://httpbin.org',
// You can set any number of default request options.
'timeout' => 2.0,
]);
Clients are immutable in Guzzle 6, which means that you cannot change the defaults used by a client after it's created.
The client constructor accepts an associative array of options:
``base_uri``
(string|UriInterface) Base URI of the client that is merged into relative
URIs. Can be a string or instance of UriInterface. When a relative URI
is provided to a client, the client will combine the base URI with the
relative URI using the rules described in
`RFC 3986, section 2 <http://tools.ietf.org/html/rfc3986#section-5.2>`_.
.. code-block:: php
// Create a client with a base URI
$client = new GuzzleHttp\Client(['base_uri' => 'https://foo.com/api/']);
// Send a request to https://foo.com/api/test
$response = $client->request('GET', 'test');
// Send a request to https://foo.com/root
$response = $client->request('GET', '/root');
Don't feel like reading RFC 3986? Here are some quick examples on how a
``base_uri`` is resolved with another URI.
======================= ================== ===============================
base_uri URI Result
======================= ================== ===============================
``http://foo.com`` ``/bar`` ``http://foo.com/bar``
``http://foo.com/foo`` ``/bar`` ``http://foo.com/bar``
``http://foo.com/foo`` ``bar`` ``http://foo.com/bar``
``http://foo.com/foo/`` ``bar`` ``http://foo.com/foo/bar``
``http://foo.com`` ``http://baz.com`` ``http://baz.com``
``http://foo.com/?bar`` ``bar`` ``http://foo.com/bar``
======================= ================== ===============================
``handler``
(callable) Function that transfers HTTP requests over the wire. The
function is called with a ``Psr7\Http\Message\RequestInterface`` and array
of transfer options, and must return a
``GuzzleHttp\Promise\PromiseInterface`` that is fulfilled with a
``Psr7\Http\Message\ResponseInterface`` on success.
``...``
(mixed) All other options passed to the constructor are used as default
request options with every request created by the client.
Sending Requests
----------------
Magic methods on the client make it easy to send synchronous requests:
.. code-block:: php
$response = $client->get('http://httpbin.org/get');
$response = $client->delete('http://httpbin.org/delete');
$response = $client->head('http://httpbin.org/get');
$response = $client->options('http://httpbin.org/get');
$response = $client->patch('http://httpbin.org/patch');
$response = $client->post('http://httpbin.org/post');
$response = $client->put('http://httpbin.org/put');
You can create a request and then send the request with the client when you're
ready:
.. code-block:: php
use GuzzleHttp\Psr7\Request;
$request = new Request('PUT', 'http://httpbin.org/put');
$response = $client->send($request, ['timeout' => 2]);
Client objects provide a great deal of flexibility in how request are
transferred including default request options, default handler stack middleware
that are used by each request, and a base URI that allows you to send requests
with relative URIs.
You can find out more about client middleware in the
:doc:`handlers-and-middleware` page of the documentation.
Async Requests
--------------
You can send asynchronous requests using the magic methods provided by a client:
.. code-block:: php
$promise = $client->getAsync('http://httpbin.org/get');
$promise = $client->deleteAsync('http://httpbin.org/delete');
$promise = $client->headAsync('http://httpbin.org/get');
$promise = $client->optionsAsync('http://httpbin.org/get');
$promise = $client->patchAsync('http://httpbin.org/patch');
$promise = $client->postAsync('http://httpbin.org/post');
$promise = $client->putAsync('http://httpbin.org/put');
You can also use the `sendAsync()` and `requestAsync()` methods of a client:
.. code-block:: php
use GuzzleHttp\Psr7\Request;
// Create a PSR-7 request object to send
$headers = ['X-Foo' => 'Bar'];
$body = 'Hello!';
$request = new Request('HEAD', 'http://httpbin.org/head', $headers, $body);
$promise = $client->sendAsync($request);
// Or, if you don't need to pass in a request instance:
$promise = $client->requestAsync('GET', 'http://httpbin.org/get');
The promise returned by these methods implements the
`Promises/A+ spec <https://promisesaplus.com/>`_, provided by the
`Guzzle promises library <https://github.com/guzzle/promises>`_. This means
that you can chain ``then()`` calls off of the promise. These then calls are
either fulfilled with a successful ``Psr\Http\Message\ResponseInterface`` or
rejected with an exception.
.. code-block:: php
use Psr\Http\Message\ResponseInterface;
use GuzzleHttp\Exception\RequestException;
$promise = $client->requestAsync('GET', 'http://httpbin.org/get');
$promise->then(
function (ResponseInterface $res) {
echo $res->getStatusCode() . "\n";
},
function (RequestException $e) {
echo $e->getMessage() . "\n";
echo $e->getRequest()->getMethod();
}
);
Concurrent requests
-------------------
You can send multiple requests concurrently using promises and asynchronous
requests.
.. code-block:: php
use GuzzleHttp\Client;
use GuzzleHttp\Promise;
$client = new Client(['base_uri' => 'http://httpbin.org/']);
// Initiate each request but do not block
$promises = [
'image' => $client->getAsync('/image'),
'png' => $client->getAsync('/image/png'),
'jpeg' => $client->getAsync('/image/jpeg'),
'webp' => $client->getAsync('/image/webp')
];
// Wait for the requests to complete; throws a ConnectException
// if any of the requests fail
$responses = Promise\unwrap($promises);
// Wait for the requests to complete, even if some of them fail
$responses = Promise\settle($promises)->wait();
// You can access each response using the key of the promise
echo $responses['image']->getHeader('Content-Length')[0];
echo $responses['png']->getHeader('Content-Length')[0];
You can use the ``GuzzleHttp\Pool`` object when you have an indeterminate
amount of requests you wish to send.
.. code-block:: php
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Pool;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
$client = new Client();
$requests = function ($total) {
$uri = 'http://127.0.0.1:8126/guzzle-server/perf';
for ($i = 0; $i < $total; $i++) {
yield new Request('GET', $uri);
}
};
$pool = new Pool($client, $requests(100), [
'concurrency' => 5,
'fulfilled' => function (Response $response, $index) {
// this is delivered each successful response
},
'rejected' => function (RequestException $reason, $index) {
// this is delivered each failed request
},
]);
// Initiate the transfers and create a promise
$promise = $pool->promise();
// Force the pool of requests to complete.
$promise->wait();
Or using a closure that will return a promise once the pool calls the closure.
.. code-block:: php
$client = new Client();
$requests = function ($total) use ($client) {
$uri = 'http://127.0.0.1:8126/guzzle-server/perf';
for ($i = 0; $i < $total; $i++) {
yield function() use ($client, $uri) {
return $client->getAsync($uri);
};
}
};
$pool = new Pool($client, $requests(100));
Using Responses
===============
In the previous examples, we retrieved a ``$response`` variable or we were
delivered a response from a promise. The response object implements a PSR-7
response, ``Psr\Http\Message\ResponseInterface``, and contains lots of
helpful information.
You can get the status code and reason phrase of the response:
.. code-block:: php
$code = $response->getStatusCode(); // 200
$reason = $response->getReasonPhrase(); // OK
You can retrieve headers from the response:
.. code-block:: php
// Check if a header exists.
if ($response->hasHeader('Content-Length')) {
echo "It exists";
}
// Get a header from the response.
echo $response->getHeader('Content-Length')[0];
// Get all of the response headers.
foreach ($response->getHeaders() as $name => $values) {
echo $name . ': ' . implode(', ', $values) . "\r\n";
}
The body of a response can be retrieved using the ``getBody`` method. The body
can be used as a string, cast to a string, or used as a stream like object.
.. code-block:: php
$body = $response->getBody();
// Implicitly cast the body to a string and echo it
echo $body;
// Explicitly cast the body to a string
$stringBody = (string) $body;
// Read 10 bytes from the body
$tenBytes = $body->read(10);
// Read the remaining contents of the body as a string
$remainingBytes = $body->getContents();
Query String Parameters
=======================
You can provide query string parameters with a request in several ways.
You can set query string parameters in the request's URI:
.. code-block:: php
$response = $client->request('GET', 'http://httpbin.org?foo=bar');
You can specify the query string parameters using the ``query`` request
option as an array.
.. code-block:: php
$client->request('GET', 'http://httpbin.org', [
'query' => ['foo' => 'bar']
]);
Providing the option as an array will use PHP's ``http_build_query`` function
to format the query string.
And finally, you can provide the ``query`` request option as a string.
.. code-block:: php
$client->request('GET', 'http://httpbin.org', ['query' => 'foo=bar']);
Uploading Data
==============
Guzzle provides several methods for uploading data.
You can send requests that contain a stream of data by passing a string,
resource returned from ``fopen``, or an instance of a
``Psr\Http\Message\StreamInterface`` to the ``body`` request option.
.. code-block:: php
// Provide the body as a string.
$r = $client->request('POST', 'http://httpbin.org/post', [
'body' => 'raw data'
]);
// Provide an fopen resource.
$body = fopen('/path/to/file', 'r');
$r = $client->request('POST', 'http://httpbin.org/post', ['body' => $body]);
// Use the stream_for() function to create a PSR-7 stream.
$body = \GuzzleHttp\Psr7\stream_for('hello!');
$r = $client->request('POST', 'http://httpbin.org/post', ['body' => $body]);
An easy way to upload JSON data and set the appropriate header is using the
``json`` request option:
.. code-block:: php
$r = $client->request('PUT', 'http://httpbin.org/put', [
'json' => ['foo' => 'bar']
]);
POST/Form Requests
------------------
In addition to specifying the raw data of a request using the ``body`` request
option, Guzzle provides helpful abstractions over sending POST data.
Sending form fields
~~~~~~~~~~~~~~~~~~~
Sending ``application/x-www-form-urlencoded`` POST requests requires that you
specify the POST fields as an array in the ``form_params`` request options.
.. code-block:: php
$response = $client->request('POST', 'http://httpbin.org/post', [
'form_params' => [
'field_name' => 'abc',
'other_field' => '123',
'nested_field' => [
'nested' => 'hello'
]
]
]);
Sending form files
~~~~~~~~~~~~~~~~~~
You can send files along with a form (``multipart/form-data`` POST requests),
using the ``multipart`` request option. ``multipart`` accepts an array of
associative arrays, where each associative array contains the following keys:
- name: (required, string) key mapping to the form field name.
- contents: (required, mixed) Provide a string to send the contents of the
file as a string, provide an fopen resource to stream the contents from a
PHP stream, or provide a ``Psr\Http\Message\StreamInterface`` to stream
the contents from a PSR-7 stream.
.. code-block:: php
$response = $client->request('POST', 'http://httpbin.org/post', [
'multipart' => [
[
'name' => 'field_name',
'contents' => 'abc'
],
[
'name' => 'file_name',
'contents' => fopen('/path/to/file', 'r')
],
[
'name' => 'other_file',
'contents' => 'hello',
'filename' => 'filename.txt',
'headers' => [
'X-Foo' => 'this is an extra header to include'
]
]
]
]);
Cookies
=======
Guzzle can maintain a cookie session for you if instructed using the
``cookies`` request option. When sending a request, the ``cookies`` option
must be set to an instance of ``GuzzleHttp\Cookie\CookieJarInterface``.
.. code-block:: php
// Use a specific cookie jar
$jar = new \GuzzleHttp\Cookie\CookieJar;
$r = $client->request('GET', 'http://httpbin.org/cookies', [
'cookies' => $jar
]);
You can set ``cookies`` to ``true`` in a client constructor if you would like
to use a shared cookie jar for all requests.
.. code-block:: php
// Use a shared client cookie jar
$client = new \GuzzleHttp\Client(['cookies' => true]);
$r = $client->request('GET', 'http://httpbin.org/cookies');
Different implementations exist for the ``GuzzleHttp\Cookie\CookieJarInterface``
:
- The ``GuzzleHttp\Cookie\CookieJar`` class stores cookies as an array.
- The ``GuzzleHttp\Cookie\FileCookieJar`` class persists non-session cookies
using a JSON formatted file.
- The ``GuzzleHttp\Cookie\SessionCookieJar`` class persists cookies in the
client session.
You can manually set cookies into a cookie jar with the named constructor
``fromArray(array $cookies, $domain)``.
.. code-block:: php
$jar = \GuzzleHttp\Cookie\CookieJar::fromArray(
[
'some_cookie' => 'foo',
'other_cookie' => 'barbaz1234'
],
'example.org'
);
You can get a cookie by its name with the ``getCookieByName($name)`` method
which returns a ``GuzzleHttp\Cookie\SetCookie`` instance.
.. code-block:: php
$cookie = $jar->getCookieByName('some_cookie');
$cookie->getValue(); // 'foo'
$cookie->getDomain(); // 'example.org'
$cookie->getExpires(); // expiration date as a Unix timestamp
The cookies can be also fetched into an array thanks to the `toArray()` method.
The ``GuzzleHttp\Cookie\CookieJarInterface`` interface extends
``Traversable`` so it can be iterated in a foreach loop.
Redirects
=========
Guzzle will automatically follow redirects unless you tell it not to. You can
customize the redirect behavior using the ``allow_redirects`` request option.
- Set to ``true`` to enable normal redirects with a maximum number of 5
redirects. This is the default setting.
- Set to ``false`` to disable redirects.
- Pass an associative array containing the 'max' key to specify the maximum
number of redirects and optionally provide a 'strict' key value to specify
whether or not to use strict RFC compliant redirects (meaning redirect POST
requests with POST requests vs. doing what most browsers do which is
redirect POST requests with GET requests).
.. code-block:: php
$response = $client->request('GET', 'http://github.com');
echo $response->getStatusCode();
// 200
The following example shows that redirects can be disabled.
.. code-block:: php
$response = $client->request('GET', 'http://github.com', [
'allow_redirects' => false
]);
echo $response->getStatusCode();
// 301
Exceptions
==========
**Tree View**
The following tree view describes how the Guzzle Exceptions depend
on each other.
.. code-block:: none
. \RuntimeException
├── SeekException (implements GuzzleException)
└── TransferException (implements GuzzleException)
└── RequestException
├── BadResponseException
│   ├── ServerException
│ └── ClientException
├── ConnectException
└── TooManyRedirectsException
Guzzle throws exceptions for errors that occur during a transfer.
- In the event of a networking error (connection timeout, DNS errors, etc.),
a ``GuzzleHttp\Exception\RequestException`` is thrown. This exception
extends from ``GuzzleHttp\Exception\TransferException``. Catching this
exception will catch any exception that can be thrown while transferring
requests.
.. code-block:: php
use GuzzleHttp\Psr7;
use GuzzleHttp\Exception\RequestException;
try {
$client->request('GET', 'https://github.com/_abc_123_404');
} catch (RequestException $e) {
echo Psr7\str($e->getRequest());
if ($e->hasResponse()) {
echo Psr7\str($e->getResponse());
}
}
- A ``GuzzleHttp\Exception\ConnectException`` exception is thrown in the
event of a networking error. This exception extends from
``GuzzleHttp\Exception\RequestException``.
- A ``GuzzleHttp\Exception\ClientException`` is thrown for 400
level errors if the ``http_errors`` request option is set to true. This
exception extends from ``GuzzleHttp\Exception\BadResponseException`` and
``GuzzleHttp\Exception\BadResponseException`` extends from
``GuzzleHttp\Exception\RequestException``.
.. code-block:: php
use GuzzleHttp\Psr7;
use GuzzleHttp\Exception\ClientException;
try {
$client->request('GET', 'https://github.com/_abc_123_404');
} catch (ClientException $e) {
echo Psr7\str($e->getRequest());
echo Psr7\str($e->getResponse());
}
- A ``GuzzleHttp\Exception\ServerException`` is thrown for 500 level
errors if the ``http_errors`` request option is set to true. This
exception extends from ``GuzzleHttp\Exception\BadResponseException``.
- A ``GuzzleHttp\Exception\TooManyRedirectsException`` is thrown when too
many redirects are followed. This exception extends from ``GuzzleHttp\Exception\RequestException``.
All of the above exceptions extend from
``GuzzleHttp\Exception\TransferException``.
Environment Variables
=====================
Guzzle exposes a few environment variables that can be used to customize the
behavior of the library.
``GUZZLE_CURL_SELECT_TIMEOUT``
Controls the duration in seconds that a curl_multi_* handler will use when
selecting on curl handles using ``curl_multi_select()``. Some systems
have issues with PHP's implementation of ``curl_multi_select()`` where
calling this function always results in waiting for the maximum duration of
the timeout.
``HTTP_PROXY``
Defines the proxy to use when sending requests using the "http" protocol.
Note: because the HTTP_PROXY variable may contain arbitrary user input on some (CGI) environments, the variable is only used on the CLI SAPI. See https://httpoxy.org for more information.
``HTTPS_PROXY``
Defines the proxy to use when sending requests using the "https" protocol.
``NO_PROXY``
Defines URLs for which a proxy should not be used. See :ref:`proxy-option` for usage.
Relevant ini Settings
---------------------
Guzzle can utilize PHP ini settings when configuring clients.
``openssl.cafile``
Specifies the path on disk to a CA file in PEM format to use when sending
requests over "https". See: https://wiki.php.net/rfc/tls-peer-verification#phpini_defaults

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,2 @@
Sphinx>=1.3.0,<1.4.0
guzzle_sphinx_theme>=0.7.0,<0.8.0

View File

@ -0,0 +1,196 @@
======================
Testing Guzzle Clients
======================
Guzzle provides several tools that will enable you to easily mock the HTTP
layer without needing to send requests over the internet.
* Mock handler
* History middleware
* Node.js web server for integration testing
Mock Handler
============
When testing HTTP clients, you often need to simulate specific scenarios like
returning a successful response, returning an error, or returning specific
responses in a certain order. Because unit tests need to be predictable, easy
to bootstrap, and fast, hitting an actual remote API is a test smell.
Guzzle provides a mock handler that can be used to fulfill HTTP requests with
a response or exception by shifting return values off of a queue.
.. code-block:: php
use GuzzleHttp\Client;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Exception\RequestException;
// Create a mock and queue two responses.
$mock = new MockHandler([
new Response(200, ['X-Foo' => 'Bar'], 'Hello, World'),
new Response(202, ['Content-Length' => 0]),
new RequestException('Error Communicating with Server', new Request('GET', 'test'))
]);
$handlerStack = HandlerStack::create($mock);
$client = new Client(['handler' => $handlerStack]);
// The first request is intercepted with the first response.
$response = $client->request('GET', '/');
echo $response->getStatusCode();
//> 200
echo $response->getBody();
//> Hello, World
// The second request is intercepted with the second response.
echo $client->request('GET', '/')->getStatusCode();
//> 202
// Reset the queue and queue up a new response
$mock->reset();
$mock->append(new Response(201));
// As the mock was reset, the new response is the 201 CREATED,
// instead of the previously queued RequestException
echo $client->request('GET', '/')->getStatusCode();
//> 201
When no more responses are in the queue and a request is sent, an
``OutOfBoundsException`` is thrown.
History Middleware
==================
When using things like the ``Mock`` handler, you often need to know if the
requests you expected to send were sent exactly as you intended. While the mock
handler responds with mocked responses, the history middleware maintains a
history of the requests that were sent by a client.
.. code-block:: php
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
$container = [];
$history = Middleware::history($container);
$handlerStack = HandlerStack::create();
// or $handlerStack = HandlerStack::create($mock); if using the Mock handler.
// Add the history middleware to the handler stack.
$handlerStack->push($history);
$client = new Client(['handler' => $handlerStack]);
$client->request('GET', 'http://httpbin.org/get');
$client->request('HEAD', 'http://httpbin.org/get');
// Count the number of transactions
echo count($container);
//> 2
// Iterate over the requests and responses
foreach ($container as $transaction) {
echo $transaction['request']->getMethod();
//> GET, HEAD
if ($transaction['response']) {
echo $transaction['response']->getStatusCode();
//> 200, 200
} elseif ($transaction['error']) {
echo $transaction['error'];
//> exception
}
var_dump($transaction['options']);
//> dumps the request options of the sent request.
}
Test Web Server
===============
Using mock responses is almost always enough when testing a web service client.
When implementing custom :doc:`HTTP handlers <handlers-and-middleware>`, you'll
need to send actual HTTP requests in order to sufficiently test the handler.
However, a best practice is to contact a local web server rather than a server
over the internet.
- Tests are more reliable
- Tests do not require a network connection
- Tests have no external dependencies
Using the test server
---------------------
.. warning::
The following functionality is provided to help developers of Guzzle
develop HTTP handlers. There is no promise of backwards compatibility
when it comes to the node.js test server or the ``GuzzleHttp\Tests\Server``
class. If you are using the test server or ``Server`` class outside of
guzzlehttp/guzzle, then you will need to configure autoloading and
ensure the web server is started manually.
.. hint::
You almost never need to use this test web server. You should only ever
consider using it when developing HTTP handlers. The test web server
is not necessary for mocking requests. For that, please use the
Mock handler and history middleware.
Guzzle ships with a node.js test server that receives requests and returns
responses from a queue. The test server exposes a simple API that is used to
enqueue responses and inspect the requests that it has received.
Any operation on the ``Server`` object will ensure that
the server is running and wait until it is able to receive requests before
returning.
``GuzzleHttp\Tests\Server`` provides a static interface to the test server. You
can queue an HTTP response or an array of responses by calling
``Server::enqueue()``. This method accepts an array of
``Psr\Http\Message\ResponseInterface`` and ``Exception`` objects.
.. code-block:: php
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Tests\Server;
// Start the server and queue a response
Server::enqueue([
new Response(200, ['Content-Length' => 0])
]);
$client = new Client(['base_uri' => Server::$url]);
echo $client->request('GET', '/foo')->getStatusCode();
// 200
When a response is queued on the test server, the test server will remove any
previously queued responses. As the server receives requests, queued responses
are dequeued and returned to the request. When the queue is empty, the server
will return a 500 response.
You can inspect the requests that the server has retrieved by calling
``Server::received()``.
.. code-block:: php
foreach (Server::received() as $response) {
echo $response->getStatusCode();
}
You can clear the list of received requests from the web server using the
``Server::flush()`` method.
.. code-block:: php
Server::flush();
echo count(Server::received());
// 0

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,7 @@
includes:
- phpstan-baseline.neon
parameters:
level: max
paths:
- src

View File

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
bootstrap="./tests/bootstrap.php"
backupGlobals="true"
colors="true"
executionOrder="random"
>
<testsuites>
<testsuite name="Test Suite">
<directory>tests</directory>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory suffix=".php">src</directory>
<exclude>
<directory suffix="Interface.php">src/</directory>
</exclude>
</whitelist>
</filter>
</phpunit>

View File

@ -0,0 +1,811 @@
<?php
namespace GuzzleHttp\Tests;
use GuzzleHttp\Client;
use GuzzleHttp\Cookie\CookieJar;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use GuzzleHttp\Promise\PromiseInterface;
use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Psr7\Uri;
use GuzzleHttp\RequestOptions;
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\ResponseInterface;
class ClientTest extends TestCase
{
public function testUsesDefaultHandler()
{
$client = new Client();
Server::enqueue([new Response(200, ['Content-Length' => 0])]);
$response = $client->get(Server::$url);
self::assertSame(200, $response->getStatusCode());
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage Magic request methods require a URI and optional options array
*/
public function testValidatesArgsForMagicMethods()
{
$client = new Client();
$client->get();
}
public function testCanSendMagicAsyncRequests()
{
$client = new Client();
Server::flush();
Server::enqueue([new Response(200, ['Content-Length' => 2], 'hi')]);
$p = $client->getAsync(Server::$url, ['query' => ['test' => 'foo']]);
self::assertInstanceOf(PromiseInterface::class, $p);
self::assertSame(200, $p->wait()->getStatusCode());
$received = Server::received(true);
self::assertCount(1, $received);
self::assertSame('test=foo', $received[0]->getUri()->getQuery());
}
public function testCanSendSynchronously()
{
$client = new Client(['handler' => new MockHandler([new Response()])]);
$request = new Request('GET', 'http://example.com');
$r = $client->send($request);
self::assertInstanceOf(ResponseInterface::class, $r);
self::assertSame(200, $r->getStatusCode());
}
public function testClientHasOptions()
{
$client = new Client([
'base_uri' => 'http://foo.com',
'timeout' => 2,
'headers' => ['bar' => 'baz'],
'handler' => new MockHandler()
]);
$base = $client->getConfig('base_uri');
self::assertSame('http://foo.com', (string) $base);
self::assertInstanceOf(Uri::class, $base);
self::assertNotNull($client->getConfig('handler'));
self::assertSame(2, $client->getConfig('timeout'));
self::assertArrayHasKey('timeout', $client->getConfig());
self::assertArrayHasKey('headers', $client->getConfig());
}
public function testCanMergeOnBaseUri()
{
$mock = new MockHandler([new Response()]);
$client = new Client([
'base_uri' => 'http://foo.com/bar/',
'handler' => $mock
]);
$client->get('baz');
self::assertSame(
'http://foo.com/bar/baz',
(string)$mock->getLastRequest()->getUri()
);
}
public function testCanMergeOnBaseUriWithRequest()
{
$mock = new MockHandler([new Response(), new Response()]);
$client = new Client([
'handler' => $mock,
'base_uri' => 'http://foo.com/bar/'
]);
$client->request('GET', new Uri('baz'));
self::assertSame(
'http://foo.com/bar/baz',
(string) $mock->getLastRequest()->getUri()
);
$client->request('GET', new Uri('baz'), ['base_uri' => 'http://example.com/foo/']);
self::assertSame(
'http://example.com/foo/baz',
(string) $mock->getLastRequest()->getUri(),
'Can overwrite the base_uri through the request options'
);
}
public function testCanUseRelativeUriWithSend()
{
$mock = new MockHandler([new Response()]);
$client = new Client([
'handler' => $mock,
'base_uri' => 'http://bar.com'
]);
self::assertSame('http://bar.com', (string) $client->getConfig('base_uri'));
$request = new Request('GET', '/baz');
$client->send($request);
self::assertSame(
'http://bar.com/baz',
(string) $mock->getLastRequest()->getUri()
);
}
public function testMergesDefaultOptionsAndDoesNotOverwriteUa()
{
$c = new Client(['headers' => ['User-agent' => 'foo']]);
self::assertSame(['User-agent' => 'foo'], $c->getConfig('headers'));
self::assertInternalType('array', $c->getConfig('allow_redirects'));
self::assertTrue($c->getConfig('http_errors'));
self::assertTrue($c->getConfig('decode_content'));
self::assertTrue($c->getConfig('verify'));
}
public function testDoesNotOverwriteHeaderWithDefault()
{
$mock = new MockHandler([new Response()]);
$c = new Client([
'headers' => ['User-agent' => 'foo'],
'handler' => $mock
]);
$c->get('http://example.com', ['headers' => ['User-Agent' => 'bar']]);
self::assertSame('bar', $mock->getLastRequest()->getHeaderLine('User-Agent'));
}
public function testDoesNotOverwriteHeaderWithDefaultInRequest()
{
$mock = new MockHandler([new Response()]);
$c = new Client([
'headers' => ['User-agent' => 'foo'],
'handler' => $mock
]);
$request = new Request('GET', Server::$url, ['User-Agent' => 'bar']);
$c->send($request);
self::assertSame('bar', $mock->getLastRequest()->getHeaderLine('User-Agent'));
}
public function testDoesOverwriteHeaderWithSetRequestOption()
{
$mock = new MockHandler([new Response()]);
$c = new Client([
'headers' => ['User-agent' => 'foo'],
'handler' => $mock
]);
$request = new Request('GET', Server::$url, ['User-Agent' => 'bar']);
$c->send($request, ['headers' => ['User-Agent' => 'YO']]);
self::assertSame('YO', $mock->getLastRequest()->getHeaderLine('User-Agent'));
}
public function testCanUnsetRequestOptionWithNull()
{
$mock = new MockHandler([new Response()]);
$c = new Client([
'headers' => ['foo' => 'bar'],
'handler' => $mock
]);
$c->get('http://example.com', ['headers' => null]);
self::assertFalse($mock->getLastRequest()->hasHeader('foo'));
}
public function testRewriteExceptionsToHttpErrors()
{
$client = new Client(['handler' => new MockHandler([new Response(404)])]);
$res = $client->get('http://foo.com', ['exceptions' => false]);
self::assertSame(404, $res->getStatusCode());
}
public function testRewriteSaveToToSink()
{
$r = Psr7\stream_for(fopen('php://temp', 'r+'));
$mock = new MockHandler([new Response(200, [], 'foo')]);
$client = new Client(['handler' => $mock]);
$client->get('http://foo.com', ['save_to' => $r]);
self::assertSame($r, $mock->getLastOptions()['sink']);
}
public function testAllowRedirectsCanBeTrue()
{
$mock = new MockHandler([new Response(200, [], 'foo')]);
$handler = HandlerStack::create($mock);
$client = new Client(['handler' => $handler]);
$client->get('http://foo.com', ['allow_redirects' => true]);
self::assertInternalType('array', $mock->getLastOptions()['allow_redirects']);
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage allow_redirects must be true, false, or array
*/
public function testValidatesAllowRedirects()
{
$mock = new MockHandler([new Response(200, [], 'foo')]);
$handler = HandlerStack::create($mock);
$client = new Client(['handler' => $handler]);
$client->get('http://foo.com', ['allow_redirects' => 'foo']);
}
/**
* @expectedException \GuzzleHttp\Exception\ClientException
*/
public function testThrowsHttpErrorsByDefault()
{
$mock = new MockHandler([new Response(404)]);
$handler = HandlerStack::create($mock);
$client = new Client(['handler' => $handler]);
$client->get('http://foo.com');
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage cookies must be an instance of GuzzleHttp\Cookie\CookieJarInterface
*/
public function testValidatesCookies()
{
$mock = new MockHandler([new Response(200, [], 'foo')]);
$handler = HandlerStack::create($mock);
$client = new Client(['handler' => $handler]);
$client->get('http://foo.com', ['cookies' => 'foo']);
}
public function testSetCookieToTrueUsesSharedJar()
{
$mock = new MockHandler([
new Response(200, ['Set-Cookie' => 'foo=bar']),
new Response()
]);
$handler = HandlerStack::create($mock);
$client = new Client(['handler' => $handler, 'cookies' => true]);
$client->get('http://foo.com');
$client->get('http://foo.com');
self::assertSame('foo=bar', $mock->getLastRequest()->getHeaderLine('Cookie'));
}
public function testSetCookieToJar()
{
$mock = new MockHandler([
new Response(200, ['Set-Cookie' => 'foo=bar']),
new Response()
]);
$handler = HandlerStack::create($mock);
$client = new Client(['handler' => $handler]);
$jar = new CookieJar();
$client->get('http://foo.com', ['cookies' => $jar]);
$client->get('http://foo.com', ['cookies' => $jar]);
self::assertSame('foo=bar', $mock->getLastRequest()->getHeaderLine('Cookie'));
}
public function testCanDisableContentDecoding()
{
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$client->get('http://foo.com', ['decode_content' => false]);
$last = $mock->getLastRequest();
self::assertFalse($last->hasHeader('Accept-Encoding'));
self::assertFalse($mock->getLastOptions()['decode_content']);
}
public function testCanSetContentDecodingToValue()
{
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$client->get('http://foo.com', ['decode_content' => 'gzip']);
$last = $mock->getLastRequest();
self::assertSame('gzip', $last->getHeaderLine('Accept-Encoding'));
self::assertSame('gzip', $mock->getLastOptions()['decode_content']);
}
/**
* @expectedException \InvalidArgumentException
*/
public function testValidatesHeaders()
{
$mock = new MockHandler();
$client = new Client(['handler' => $mock]);
$client->get('http://foo.com', ['headers' => 'foo']);
}
public function testAddsBody()
{
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$request = new Request('PUT', 'http://foo.com');
$client->send($request, ['body' => 'foo']);
$last = $mock->getLastRequest();
self::assertSame('foo', (string) $last->getBody());
}
/**
* @expectedException \InvalidArgumentException
*/
public function testValidatesQuery()
{
$mock = new MockHandler();
$client = new Client(['handler' => $mock]);
$request = new Request('PUT', 'http://foo.com');
$client->send($request, ['query' => false]);
}
public function testQueryCanBeString()
{
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$request = new Request('PUT', 'http://foo.com');
$client->send($request, ['query' => 'foo']);
self::assertSame('foo', $mock->getLastRequest()->getUri()->getQuery());
}
public function testQueryCanBeArray()
{
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$request = new Request('PUT', 'http://foo.com');
$client->send($request, ['query' => ['foo' => 'bar baz']]);
self::assertSame('foo=bar%20baz', $mock->getLastRequest()->getUri()->getQuery());
}
public function testCanAddJsonData()
{
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$request = new Request('PUT', 'http://foo.com');
$client->send($request, ['json' => ['foo' => 'bar']]);
$last = $mock->getLastRequest();
self::assertSame('{"foo":"bar"}', (string) $mock->getLastRequest()->getBody());
self::assertSame('application/json', $last->getHeaderLine('Content-Type'));
}
public function testCanAddJsonDataWithoutOverwritingContentType()
{
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$request = new Request('PUT', 'http://foo.com');
$client->send($request, [
'headers' => ['content-type' => 'foo'],
'json' => 'a'
]);
$last = $mock->getLastRequest();
self::assertSame('"a"', (string) $mock->getLastRequest()->getBody());
self::assertSame('foo', $last->getHeaderLine('Content-Type'));
}
public function testCanAddJsonDataWithNullHeader()
{
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$request = new Request('PUT', 'http://foo.com');
$client->send($request, [
'headers' => null,
'json' => 'a'
]);
$last = $mock->getLastRequest();
self::assertSame('"a"', (string) $mock->getLastRequest()->getBody());
self::assertSame('application/json', $last->getHeaderLine('Content-Type'));
}
public function testAuthCanBeTrue()
{
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$client->get('http://foo.com', ['auth' => false]);
$last = $mock->getLastRequest();
self::assertFalse($last->hasHeader('Authorization'));
}
public function testAuthCanBeArrayForBasicAuth()
{
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$client->get('http://foo.com', ['auth' => ['a', 'b']]);
$last = $mock->getLastRequest();
self::assertSame('Basic YTpi', $last->getHeaderLine('Authorization'));
}
public function testAuthCanBeArrayForDigestAuth()
{
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$client->get('http://foo.com', ['auth' => ['a', 'b', 'digest']]);
$last = $mock->getLastOptions();
self::assertSame([
CURLOPT_HTTPAUTH => 2,
CURLOPT_USERPWD => 'a:b'
], $last['curl']);
}
public function testAuthCanBeArrayForNtlmAuth()
{
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$client->get('http://foo.com', ['auth' => ['a', 'b', 'ntlm']]);
$last = $mock->getLastOptions();
self::assertSame([
CURLOPT_HTTPAUTH => 8,
CURLOPT_USERPWD => 'a:b'
], $last['curl']);
}
public function testAuthCanBeCustomType()
{
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$client->get('http://foo.com', ['auth' => 'foo']);
$last = $mock->getLastOptions();
self::assertSame('foo', $last['auth']);
}
public function testCanAddFormParams()
{
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$client->post('http://foo.com', [
'form_params' => [
'foo' => 'bar bam',
'baz' => ['boo' => 'qux']
]
]);
$last = $mock->getLastRequest();
self::assertSame(
'application/x-www-form-urlencoded',
$last->getHeaderLine('Content-Type')
);
self::assertSame(
'foo=bar+bam&baz%5Bboo%5D=qux',
(string) $last->getBody()
);
}
public function testFormParamsEncodedProperly()
{
$separator = ini_get('arg_separator.output');
ini_set('arg_separator.output', '&amp;');
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$client->post('http://foo.com', [
'form_params' => [
'foo' => 'bar bam',
'baz' => ['boo' => 'qux']
]
]);
$last = $mock->getLastRequest();
self::assertSame(
'foo=bar+bam&baz%5Bboo%5D=qux',
(string) $last->getBody()
);
ini_set('arg_separator.output', $separator);
}
/**
* @expectedException \InvalidArgumentException
*/
public function testEnsuresThatFormParamsAndMultipartAreExclusive()
{
$client = new Client(['handler' => function () {
}]);
$client->post('http://foo.com', [
'form_params' => ['foo' => 'bar bam'],
'multipart' => []
]);
}
public function testCanSendMultipart()
{
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$client->post('http://foo.com', [
'multipart' => [
[
'name' => 'foo',
'contents' => 'bar'
],
[
'name' => 'test',
'contents' => fopen(__FILE__, 'r')
]
]
]);
$last = $mock->getLastRequest();
self::assertContains(
'multipart/form-data; boundary=',
$last->getHeaderLine('Content-Type')
);
self::assertContains(
'Content-Disposition: form-data; name="foo"',
(string) $last->getBody()
);
self::assertContains('bar', (string) $last->getBody());
self::assertContains(
'Content-Disposition: form-data; name="foo"' . "\r\n",
(string) $last->getBody()
);
self::assertContains(
'Content-Disposition: form-data; name="test"; filename="ClientTest.php"',
(string) $last->getBody()
);
}
public function testCanSendMultipartWithExplicitBody()
{
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$client->send(
new Request(
'POST',
'http://foo.com',
[],
new Psr7\MultipartStream(
[
[
'name' => 'foo',
'contents' => 'bar',
],
[
'name' => 'test',
'contents' => fopen(__FILE__, 'r'),
],
]
)
)
);
$last = $mock->getLastRequest();
self::assertContains(
'multipart/form-data; boundary=',
$last->getHeaderLine('Content-Type')
);
self::assertContains(
'Content-Disposition: form-data; name="foo"',
(string) $last->getBody()
);
self::assertContains('bar', (string) $last->getBody());
self::assertContains(
'Content-Disposition: form-data; name="foo"' . "\r\n",
(string) $last->getBody()
);
self::assertContains(
'Content-Disposition: form-data; name="test"; filename="ClientTest.php"',
(string) $last->getBody()
);
}
public function testUsesProxyEnvironmentVariables()
{
$http = getenv('HTTP_PROXY');
$https = getenv('HTTPS_PROXY');
$no = getenv('NO_PROXY');
$client = new Client();
self::assertNull($client->getConfig('proxy'));
putenv('HTTP_PROXY=127.0.0.1');
$client = new Client();
self::assertSame(
['http' => '127.0.0.1'],
$client->getConfig('proxy')
);
putenv('HTTPS_PROXY=127.0.0.2');
putenv('NO_PROXY=127.0.0.3, 127.0.0.4');
$client = new Client();
self::assertSame(
['http' => '127.0.0.1', 'https' => '127.0.0.2', 'no' => ['127.0.0.3','127.0.0.4']],
$client->getConfig('proxy')
);
putenv("HTTP_PROXY=$http");
putenv("HTTPS_PROXY=$https");
putenv("NO_PROXY=$no");
}
public function testRequestSendsWithSync()
{
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$client->request('GET', 'http://foo.com');
self::assertTrue($mock->getLastOptions()['synchronous']);
}
public function testSendSendsWithSync()
{
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$client->send(new Request('GET', 'http://foo.com'));
self::assertTrue($mock->getLastOptions()['synchronous']);
}
public function testCanSetCustomHandler()
{
$mock = new MockHandler([new Response(500)]);
$client = new Client(['handler' => $mock]);
$mock2 = new MockHandler([new Response(200)]);
self::assertSame(
200,
$client->send(new Request('GET', 'http://foo.com'), [
'handler' => $mock2
])->getStatusCode()
);
}
public function testProperlyBuildsQuery()
{
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$request = new Request('PUT', 'http://foo.com');
$client->send($request, ['query' => ['foo' => 'bar', 'john' => 'doe']]);
self::assertSame('foo=bar&john=doe', $mock->getLastRequest()->getUri()->getQuery());
}
public function testSendSendsWithIpAddressAndPortAndHostHeaderInRequestTheHostShouldBePreserved()
{
$mockHandler = new MockHandler([new Response()]);
$client = new Client(['base_uri' => 'http://127.0.0.1:8585', 'handler' => $mockHandler]);
$request = new Request('GET', '/test', ['Host'=>'foo.com']);
$client->send($request);
self::assertSame('foo.com', $mockHandler->getLastRequest()->getHeader('Host')[0]);
}
public function testSendSendsWithDomainAndHostHeaderInRequestTheHostShouldBePreserved()
{
$mockHandler = new MockHandler([new Response()]);
$client = new Client(['base_uri' => 'http://foo2.com', 'handler' => $mockHandler]);
$request = new Request('GET', '/test', ['Host'=>'foo.com']);
$client->send($request);
self::assertSame('foo.com', $mockHandler->getLastRequest()->getHeader('Host')[0]);
}
/**
* @expectedException \InvalidArgumentException
*/
public function testValidatesSink()
{
$mockHandler = new MockHandler([new Response()]);
$client = new Client(['handler' => $mockHandler]);
$client->get('http://test.com', ['sink' => true]);
}
public function testHttpDefaultSchemeIfUriHasNone()
{
$mockHandler = new MockHandler([new Response()]);
$client = new Client(['handler' => $mockHandler]);
$client->request('GET', '//example.org/test');
self::assertSame('http://example.org/test', (string) $mockHandler->getLastRequest()->getUri());
}
public function testOnlyAddSchemeWhenHostIsPresent()
{
$mockHandler = new MockHandler([new Response()]);
$client = new Client(['handler' => $mockHandler]);
$client->request('GET', 'baz');
self::assertSame(
'baz',
(string) $mockHandler->getLastRequest()->getUri()
);
}
/**
* @expectedException InvalidArgumentException
*/
public function testHandlerIsCallable()
{
new Client(['handler' => 'not_cllable']);
}
public function testResponseBodyAsString()
{
$responseBody = '{ "package": "guzzle" }';
$mock = new MockHandler([new Response(200, ['Content-Type' => 'application/json'], $responseBody)]);
$client = new Client(['handler' => $mock]);
$request = new Request('GET', 'http://foo.com');
$response = $client->send($request, ['json' => ['a' => 'b']]);
self::assertSame($responseBody, (string) $response->getBody());
}
public function testResponseContent()
{
$responseBody = '{ "package": "guzzle" }';
$mock = new MockHandler([new Response(200, ['Content-Type' => 'application/json'], $responseBody)]);
$client = new Client(['handler' => $mock]);
$request = new Request('POST', 'http://foo.com');
$response = $client->send($request, ['json' => ['a' => 'b']]);
self::assertSame($responseBody, $response->getBody()->getContents());
}
public function testIdnSupportDefaultValue()
{
$mockHandler = new MockHandler([new Response()]);
$client = new Client(['handler' => $mockHandler]);
$config = $client->getConfig();
self::assertTrue($config['idn_conversion']);
}
public function testIdnIsTranslatedToAsciiWhenConversionIsEnabled()
{
$mockHandler = new MockHandler([new Response()]);
$client = new Client(['handler' => $mockHandler]);
$client->request('GET', 'https://яндекс.рф/images', ['idn_conversion' => true]);
$request = $mockHandler->getLastRequest();
self::assertSame('https://xn--d1acpjx3f.xn--p1ai/images', (string) $request->getUri());
self::assertSame('xn--d1acpjx3f.xn--p1ai', (string) $request->getHeaderLine('Host'));
}
public function testIdnStaysTheSameWhenConversionIsDisabled()
{
$mockHandler = new MockHandler([new Response()]);
$client = new Client(['handler' => $mockHandler]);
$client->request('GET', 'https://яндекс.рф/images', ['idn_conversion' => false]);
$request = $mockHandler->getLastRequest();
self::assertSame('https://яндекс.рф/images', (string) $request->getUri());
self::assertSame('яндекс.рф', (string) $request->getHeaderLine('Host'));
}
/**
* @expectedException \GuzzleHttp\Exception\InvalidArgumentException
* @expectedExceptionMessage IDN conversion failed
*/
public function testExceptionOnInvalidIdn()
{
$mockHandler = new MockHandler([new Response()]);
$client = new Client(['handler' => $mockHandler]);
$client->request('GET', 'https://-яндекс.рф/images', ['idn_conversion' => true]);
}
/**
* @depends testCanUseRelativeUriWithSend
* @depends testIdnSupportDefaultValue
*/
public function testIdnBaseUri()
{
$mock = new MockHandler([new Response()]);
$client = new Client([
'handler' => $mock,
'base_uri' => 'http://яндекс.рф',
]);
self::assertSame('http://яндекс.рф', (string) $client->getConfig('base_uri'));
$request = new Request('GET', '/baz');
$client->send($request);
self::assertSame('http://xn--d1acpjx3f.xn--p1ai/baz', (string) $mock->getLastRequest()->getUri());
self::assertSame('xn--d1acpjx3f.xn--p1ai', (string) $mock->getLastRequest()->getHeaderLine('Host'));
}
public function testIdnWithRedirect()
{
$mockHandler = new MockHandler([
new Response(302, ['Location' => 'http://www.tést.com/whatever']),
new Response()
]);
$handler = HandlerStack::create($mockHandler);
$requests = [];
$handler->push(Middleware::history($requests));
$client = new Client(['handler' => $handler]);
$client->request('GET', 'https://яндекс.рф/images', [
RequestOptions::ALLOW_REDIRECTS => [
'referer' => true,
'track_redirects' => true
],
'idn_conversion' => true
]);
$request = $mockHandler->getLastRequest();
self::assertSame('http://www.xn--tst-bma.com/whatever', (string) $request->getUri());
self::assertSame('www.xn--tst-bma.com', (string) $request->getHeaderLine('Host'));
$request = $requests[0]['request'];
self::assertSame('https://xn--d1acpjx3f.xn--p1ai/images', (string) $request->getUri());
self::assertSame('xn--d1acpjx3f.xn--p1ai', (string) $request->getHeaderLine('Host'));
}
}

View File

@ -0,0 +1,449 @@
<?php
namespace GuzzleHttp\Tests\CookieJar;
use DateInterval;
use DateTime;
use DateTimeImmutable;
use GuzzleHttp\Cookie\CookieJar;
use GuzzleHttp\Cookie\SetCookie;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use PHPUnit\Framework\TestCase;
/**
* @covers GuzzleHttp\Cookie\CookieJar
*/
class CookieJarTest extends TestCase
{
/** @var CookieJar */
private $jar;
public function setUp()
{
$this->jar = new CookieJar();
}
protected function getTestCookies()
{
return [
new SetCookie(['Name' => 'foo', 'Value' => 'bar', 'Domain' => 'foo.com', 'Path' => '/', 'Discard' => true]),
new SetCookie(['Name' => 'test', 'Value' => '123', 'Domain' => 'baz.com', 'Path' => '/foo', 'Expires' => 2]),
new SetCookie(['Name' => 'you', 'Value' => '123', 'Domain' => 'bar.com', 'Path' => '/boo', 'Expires' => time() + 1000])
];
}
public function testCreatesFromArray()
{
$jar = CookieJar::fromArray([
'foo' => 'bar',
'baz' => 'bam'
], 'example.com');
self::assertCount(2, $jar);
}
public function testEmptyJarIsCountable()
{
self::assertCount(0, new CookieJar());
}
public function testGetsCookiesByName()
{
$cookies = $this->getTestCookies();
foreach ($this->getTestCookies() as $cookie) {
$this->jar->setCookie($cookie);
}
$testCookie = $cookies[0];
self::assertEquals($testCookie, $this->jar->getCookieByName($testCookie->getName()));
self::assertNull($this->jar->getCookieByName("doesnotexist"));
self::assertNull($this->jar->getCookieByName(""));
}
/**
* Provides test data for cookie cookieJar retrieval
*/
public function getCookiesDataProvider()
{
return [
[['foo', 'baz', 'test', 'muppet', 'googoo'], '', '', '', false],
[['foo', 'baz', 'muppet', 'googoo'], '', '', '', true],
[['googoo'], 'www.example.com', '', '', false],
[['muppet', 'googoo'], 'test.y.example.com', '', '', false],
[['foo', 'baz'], 'example.com', '', '', false],
[['muppet'], 'x.y.example.com', '/acme/', '', false],
[['muppet'], 'x.y.example.com', '/acme/test/', '', false],
[['googoo'], 'x.y.example.com', '/test/acme/test/', '', false],
[['foo', 'baz'], 'example.com', '', '', false],
[['baz'], 'example.com', '', 'baz', false],
];
}
public function testStoresAndRetrievesCookies()
{
$cookies = $this->getTestCookies();
foreach ($cookies as $cookie) {
self::assertTrue($this->jar->setCookie($cookie));
}
self::assertCount(3, $this->jar);
self::assertCount(3, $this->jar->getIterator());
self::assertEquals($cookies, $this->jar->getIterator()->getArrayCopy());
}
public function testRemovesTemporaryCookies()
{
$cookies = $this->getTestCookies();
foreach ($this->getTestCookies() as $cookie) {
$this->jar->setCookie($cookie);
}
$this->jar->clearSessionCookies();
self::assertEquals(
[$cookies[1], $cookies[2]],
$this->jar->getIterator()->getArrayCopy()
);
}
public function testRemovesSelectively()
{
foreach ($this->getTestCookies() as $cookie) {
$this->jar->setCookie($cookie);
}
// Remove foo.com cookies
$this->jar->clear('foo.com');
self::assertCount(2, $this->jar);
// Try again, removing no further cookies
$this->jar->clear('foo.com');
self::assertCount(2, $this->jar);
// Remove bar.com cookies with path of /boo
$this->jar->clear('bar.com', '/boo');
self::assertCount(1, $this->jar);
// Remove cookie by name
$this->jar->clear(null, null, 'test');
self::assertCount(0, $this->jar);
}
public function testDoesNotAddIncompleteCookies()
{
self::assertFalse($this->jar->setCookie(new SetCookie()));
self::assertFalse($this->jar->setCookie(new SetCookie([
'Name' => 'foo'
])));
self::assertFalse($this->jar->setCookie(new SetCookie([
'Name' => false
])));
self::assertFalse($this->jar->setCookie(new SetCookie([
'Name' => true
])));
self::assertFalse($this->jar->setCookie(new SetCookie([
'Name' => 'foo',
'Domain' => 'foo.com'
])));
}
public function testDoesNotAddEmptyCookies()
{
self::assertFalse($this->jar->setCookie(new SetCookie([
'Name' => '',
'Domain' => 'foo.com',
'Value' => 0
])));
}
public function testDoesAddValidCookies()
{
self::assertTrue($this->jar->setCookie(new SetCookie([
'Name' => '0',
'Domain' => 'foo.com',
'Value' => 0
])));
self::assertTrue($this->jar->setCookie(new SetCookie([
'Name' => 'foo',
'Domain' => 'foo.com',
'Value' => 0
])));
self::assertTrue($this->jar->setCookie(new SetCookie([
'Name' => 'foo',
'Domain' => 'foo.com',
'Value' => 0.0
])));
self::assertTrue($this->jar->setCookie(new SetCookie([
'Name' => 'foo',
'Domain' => 'foo.com',
'Value' => '0'
])));
}
public function testOverwritesCookiesThatAreOlderOrDiscardable()
{
$t = time() + 1000;
$data = [
'Name' => 'foo',
'Value' => 'bar',
'Domain' => '.example.com',
'Path' => '/',
'Max-Age' => '86400',
'Secure' => true,
'Discard' => true,
'Expires' => $t
];
// Make sure that the discard cookie is overridden with the non-discard
self::assertTrue($this->jar->setCookie(new SetCookie($data)));
self::assertCount(1, $this->jar);
$data['Discard'] = false;
self::assertTrue($this->jar->setCookie(new SetCookie($data)));
self::assertCount(1, $this->jar);
$c = $this->jar->getIterator()->getArrayCopy();
self::assertFalse($c[0]->getDiscard());
// Make sure it doesn't duplicate the cookie
$this->jar->setCookie(new SetCookie($data));
self::assertCount(1, $this->jar);
// Make sure the more future-ful expiration date supersede the other
$data['Expires'] = time() + 2000;
self::assertTrue($this->jar->setCookie(new SetCookie($data)));
self::assertCount(1, $this->jar);
$c = $this->jar->getIterator()->getArrayCopy();
self::assertNotEquals($t, $c[0]->getExpires());
}
public function testOverwritesCookiesThatHaveChanged()
{
$t = time() + 1000;
$data = [
'Name' => 'foo',
'Value' => 'bar',
'Domain' => '.example.com',
'Path' => '/',
'Max-Age' => '86400',
'Secure' => true,
'Discard' => true,
'Expires' => $t
];
// Make sure that the discard cookie is overridden with the non-discard
self::assertTrue($this->jar->setCookie(new SetCookie($data)));
$data['Value'] = 'boo';
self::assertTrue($this->jar->setCookie(new SetCookie($data)));
self::assertCount(1, $this->jar);
// Changing the value plus a parameter also must overwrite the existing one
$data['Value'] = 'zoo';
$data['Secure'] = false;
self::assertTrue($this->jar->setCookie(new SetCookie($data)));
self::assertCount(1, $this->jar);
$c = $this->jar->getIterator()->getArrayCopy();
self::assertSame('zoo', $c[0]->getValue());
}
public function testAddsCookiesFromResponseWithRequest()
{
$response = new Response(200, [
'Set-Cookie' => "fpc=d=.Hm.yh4.1XmJWjJfs4orLQzKzPImxklQoxXSHOZATHUSEFciRueW_7704iYUtsXNEXq0M92Px2glMdWypmJ7HIQl6XIUvrZimWjQ3vIdeuRbI.FNQMAfcxu_XN1zSx7l.AcPdKL6guHc2V7hIQFhnjRW0rxm2oHY1P4bGQxFNz7f.tHm12ZD3DbdMDiDy7TBXsuP4DM-&v=2; expires=Fri, 02-Mar-2019 02:17:40 GMT;"
]);
$request = new Request('GET', 'http://www.example.com');
$this->jar->extractCookies($request, $response);
self::assertCount(1, $this->jar);
}
public function getMatchingCookiesDataProvider()
{
return [
['https://example.com', 'foo=bar; baz=foobar'],
['http://example.com', ''],
['https://example.com:8912', 'foo=bar; baz=foobar'],
['https://foo.example.com', 'foo=bar; baz=foobar'],
['http://foo.example.com/test/acme/', 'googoo=gaga']
];
}
/**
* @dataProvider getMatchingCookiesDataProvider
*/
public function testReturnsCookiesMatchingRequests($url, $cookies)
{
$bag = [
new SetCookie([
'Name' => 'foo',
'Value' => 'bar',
'Domain' => 'example.com',
'Path' => '/',
'Max-Age' => '86400',
'Secure' => true
]),
new SetCookie([
'Name' => 'baz',
'Value' => 'foobar',
'Domain' => 'example.com',
'Path' => '/',
'Max-Age' => '86400',
'Secure' => true
]),
new SetCookie([
'Name' => 'test',
'Value' => '123',
'Domain' => 'www.foobar.com',
'Path' => '/path/',
'Discard' => true
]),
new SetCookie([
'Name' => 'muppet',
'Value' => 'cookie_monster',
'Domain' => '.y.example.com',
'Path' => '/acme/',
'Expires' => time() + 86400
]),
new SetCookie([
'Name' => 'googoo',
'Value' => 'gaga',
'Domain' => '.example.com',
'Path' => '/test/acme/',
'Max-Age' => 1500
])
];
foreach ($bag as $cookie) {
$this->jar->setCookie($cookie);
}
$request = new Request('GET', $url);
$request = $this->jar->withCookieHeader($request);
self::assertSame($cookies, $request->getHeaderLine('Cookie'));
}
/**
* @expectedException \RuntimeException
* @expectedExceptionMessage Invalid cookie: Cookie name must not contain invalid characters: ASCII Control characters (0-31;127), space, tab and the following characters: ()<>@,;:\"/?={}
*/
public function testThrowsExceptionWithStrictMode()
{
$a = new CookieJar(true);
$a->setCookie(new SetCookie(['Name' => "abc\n", 'Value' => 'foo', 'Domain' => 'bar']));
}
public function testDeletesCookiesByName()
{
$cookies = $this->getTestCookies();
$cookies[] = new SetCookie([
'Name' => 'other',
'Value' => '123',
'Domain' => 'bar.com',
'Path' => '/boo',
'Expires' => time() + 1000
]);
$jar = new CookieJar();
foreach ($cookies as $cookie) {
$jar->setCookie($cookie);
}
self::assertCount(4, $jar);
$jar->clear('bar.com', '/boo', 'other');
self::assertCount(3, $jar);
$names = array_map(function (SetCookie $c) {
return $c->getName();
}, $jar->getIterator()->getArrayCopy());
self::assertSame(['foo', 'test', 'you'], $names);
}
public function testCanConvertToAndLoadFromArray()
{
$jar = new CookieJar(true);
foreach ($this->getTestCookies() as $cookie) {
$jar->setCookie($cookie);
}
self::assertCount(3, $jar);
$arr = $jar->toArray();
self::assertCount(3, $arr);
$newCookieJar = new CookieJar(false, $arr);
self::assertCount(3, $newCookieJar);
self::assertSame($jar->toArray(), $newCookieJar->toArray());
}
public function testAddsCookiesWithEmptyPathFromResponse()
{
$response = new Response(200, [
'Set-Cookie' => "fpc=foobar; expires={$this->futureExpirationDate()}; path=;"
]);
$request = new Request('GET', 'http://www.example.com');
$this->jar->extractCookies($request, $response);
$newRequest = $this->jar->withCookieHeader(new Request('GET', 'http://www.example.com/foo'));
self::assertTrue($newRequest->hasHeader('Cookie'));
}
public function getCookiePathsDataProvider()
{
return [
['', '/'],
['/', '/'],
['/foo', '/'],
['/foo/bar', '/foo'],
['/foo/bar/', '/foo/bar'],
];
}
/**
* @dataProvider getCookiePathsDataProvider
*/
public function testCookiePathWithEmptySetCookiePath($uriPath, $cookiePath)
{
$response = (new Response(200))
->withAddedHeader(
'Set-Cookie',
"foo=bar; expires={$this->futureExpirationDate()}; domain=www.example.com; path=;"
)
->withAddedHeader(
'Set-Cookie',
"bar=foo; expires={$this->futureExpirationDate()}; domain=www.example.com; path=foobar;"
)
;
$request = (new Request('GET', "https://www.example.com{$uriPath}"));
$this->jar->extractCookies($request, $response);
self::assertSame($cookiePath, $this->jar->toArray()[0]['Path']);
self::assertSame($cookiePath, $this->jar->toArray()[1]['Path']);
}
public function getDomainMatchesProvider()
{
return [
['www.example.com', 'www.example.com', true],
['www.example.com', 'www.EXAMPLE.com', true],
['www.example.com', 'www.example.net', false],
['www.example.com', 'ftp.example.com', false],
['www.example.com', 'example.com', true],
['www.example.com', 'EXAMPLE.com', true],
['fra.de.example.com', 'EXAMPLE.com', true],
['www.EXAMPLE.com', 'www.example.com', true],
['www.EXAMPLE.com', 'www.example.COM', true],
];
}
/**
* @dataProvider getDomainMatchesProvider
*/
public function testIgnoresCookiesForMismatchingDomains($requestHost, $domainAttribute, $matches)
{
$response = (new Response(200))
->withAddedHeader(
'Set-Cookie',
"foo=bar; expires={$this->futureExpirationDate()}; domain={$domainAttribute}; path=/;"
)
;
$request = (new Request('GET', "https://{$requestHost}/"));
$this->jar->extractCookies($request, $response);
self::assertCount($matches ? 1 : 0, $this->jar->toArray());
}
private function futureExpirationDate()
{
return (new DateTimeImmutable)->add(new DateInterval('P1D'))->format(DateTime::COOKIE);
}
}

View File

@ -0,0 +1,88 @@
<?php
namespace GuzzleHttp\Tests\CookieJar;
use GuzzleHttp\Cookie\FileCookieJar;
use GuzzleHttp\Cookie\SetCookie;
use PHPUnit\Framework\TestCase;
/**
* @covers GuzzleHttp\Cookie\FileCookieJar
*/
class FileCookieJarTest extends TestCase
{
private $file;
public function setUp()
{
$this->file = tempnam('/tmp', 'file-cookies');
}
/**
* @expectedException \RuntimeException
*/
public function testValidatesCookieFile()
{
file_put_contents($this->file, 'true');
new FileCookieJar($this->file);
}
public function testLoadsFromFile()
{
$jar = new FileCookieJar($this->file);
self::assertSame([], $jar->getIterator()->getArrayCopy());
unlink($this->file);
}
/**
* @dataProvider providerPersistsToFileFileParameters
*/
public function testPersistsToFile($testSaveSessionCookie = false)
{
$jar = new FileCookieJar($this->file, $testSaveSessionCookie);
$jar->setCookie(new SetCookie([
'Name' => 'foo',
'Value' => 'bar',
'Domain' => 'foo.com',
'Expires' => time() + 1000
]));
$jar->setCookie(new SetCookie([
'Name' => 'baz',
'Value' => 'bar',
'Domain' => 'foo.com',
'Expires' => time() + 1000
]));
$jar->setCookie(new SetCookie([
'Name' => 'boo',
'Value' => 'bar',
'Domain' => 'foo.com',
]));
self::assertCount(3, $jar);
unset($jar);
// Make sure it wrote to the file
$contents = file_get_contents($this->file);
self::assertNotEmpty($contents);
// Load the cookieJar from the file
$jar = new FileCookieJar($this->file);
if ($testSaveSessionCookie) {
self::assertCount(3, $jar);
} else {
// Weeds out temporary and session cookies
self::assertCount(2, $jar);
}
unset($jar);
unlink($this->file);
}
public function providerPersistsToFileFileParameters()
{
return [
[false],
[true]
];
}
}

View File

@ -0,0 +1,92 @@
<?php
namespace GuzzleHttp\Tests\CookieJar;
use GuzzleHttp\Cookie\SessionCookieJar;
use GuzzleHttp\Cookie\SetCookie;
use PHPUnit\Framework\TestCase;
/**
* @covers GuzzleHttp\Cookie\SessionCookieJar
*/
class SessionCookieJarTest extends TestCase
{
private $sessionVar;
public function setUp()
{
$this->sessionVar = 'sessionKey';
if (!isset($_SESSION)) {
$_SESSION = [];
}
}
/**
* @expectedException \RuntimeException
*/
public function testValidatesCookieSession()
{
$_SESSION[$this->sessionVar] = 'true';
new SessionCookieJar($this->sessionVar);
}
public function testLoadsFromSession()
{
$jar = new SessionCookieJar($this->sessionVar);
self::assertSame([], $jar->getIterator()->getArrayCopy());
unset($_SESSION[$this->sessionVar]);
}
/**
* @dataProvider providerPersistsToSessionParameters
*/
public function testPersistsToSession($testSaveSessionCookie = false)
{
$jar = new SessionCookieJar($this->sessionVar, $testSaveSessionCookie);
$jar->setCookie(new SetCookie([
'Name' => 'foo',
'Value' => 'bar',
'Domain' => 'foo.com',
'Expires' => time() + 1000
]));
$jar->setCookie(new SetCookie([
'Name' => 'baz',
'Value' => 'bar',
'Domain' => 'foo.com',
'Expires' => time() + 1000
]));
$jar->setCookie(new SetCookie([
'Name' => 'boo',
'Value' => 'bar',
'Domain' => 'foo.com',
]));
self::assertCount(3, $jar);
unset($jar);
// Make sure it wrote to the sessionVar in $_SESSION
$contents = $_SESSION[$this->sessionVar];
self::assertNotEmpty($contents);
// Load the cookieJar from the file
$jar = new SessionCookieJar($this->sessionVar);
if ($testSaveSessionCookie) {
self::assertCount(3, $jar);
} else {
// Weeds out temporary and session cookies
self::assertCount(2, $jar);
}
unset($jar);
unset($_SESSION[$this->sessionVar]);
}
public function providerPersistsToSessionParameters()
{
return [
[false],
[true]
];
}
}

View File

@ -0,0 +1,445 @@
<?php
namespace GuzzleHttp\Tests\CookieJar;
use GuzzleHttp\Cookie\SetCookie;
use PHPUnit\Framework\TestCase;
/**
* @covers GuzzleHttp\Cookie\SetCookie
*/
class SetCookieTest extends TestCase
{
public function testInitializesDefaultValues()
{
$cookie = new SetCookie();
self::assertSame('/', $cookie->getPath());
}
public function testConvertsDateTimeMaxAgeToUnixTimestamp()
{
$cookie = new SetCookie(['Expires' => 'November 20, 1984']);
self::assertInternalType('integer', $cookie->getExpires());
}
public function testAddsExpiresBasedOnMaxAge()
{
$t = time();
$cookie = new SetCookie(['Max-Age' => 100]);
self::assertEquals($t + 100, $cookie->getExpires());
}
public function testHoldsValues()
{
$t = time();
$data = [
'Name' => 'foo',
'Value' => 'baz',
'Path' => '/bar',
'Domain' => 'baz.com',
'Expires' => $t,
'Max-Age' => 100,
'Secure' => true,
'Discard' => true,
'HttpOnly' => true,
'foo' => 'baz',
'bar' => 'bam'
];
$cookie = new SetCookie($data);
self::assertEquals($data, $cookie->toArray());
self::assertSame('foo', $cookie->getName());
self::assertSame('baz', $cookie->getValue());
self::assertSame('baz.com', $cookie->getDomain());
self::assertSame('/bar', $cookie->getPath());
self::assertSame($t, $cookie->getExpires());
self::assertSame(100, $cookie->getMaxAge());
self::assertTrue($cookie->getSecure());
self::assertTrue($cookie->getDiscard());
self::assertTrue($cookie->getHttpOnly());
self::assertSame('baz', $cookie->toArray()['foo']);
self::assertSame('bam', $cookie->toArray()['bar']);
$cookie->setName('a');
$cookie->setValue('b');
$cookie->setPath('c');
$cookie->setDomain('bar.com');
$cookie->setExpires(10);
$cookie->setMaxAge(200);
$cookie->setSecure(false);
$cookie->setHttpOnly(false);
$cookie->setDiscard(false);
self::assertSame('a', $cookie->getName());
self::assertSame('b', $cookie->getValue());
self::assertSame('c', $cookie->getPath());
self::assertSame('bar.com', $cookie->getDomain());
self::assertSame(10, $cookie->getExpires());
self::assertSame(200, $cookie->getMaxAge());
self::assertFalse($cookie->getSecure());
self::assertFalse($cookie->getDiscard());
self::assertFalse($cookie->getHttpOnly());
}
public function testDeterminesIfExpired()
{
$c = new SetCookie();
$c->setExpires(10);
self::assertTrue($c->isExpired());
$c->setExpires(time() + 10000);
self::assertFalse($c->isExpired());
}
public function testMatchesDomain()
{
$cookie = new SetCookie();
self::assertTrue($cookie->matchesDomain('baz.com'));
$cookie->setDomain('baz.com');
self::assertTrue($cookie->matchesDomain('baz.com'));
self::assertFalse($cookie->matchesDomain('bar.com'));
$cookie->setDomain('.baz.com');
self::assertTrue($cookie->matchesDomain('.baz.com'));
self::assertTrue($cookie->matchesDomain('foo.baz.com'));
self::assertFalse($cookie->matchesDomain('baz.bar.com'));
self::assertTrue($cookie->matchesDomain('baz.com'));
$cookie->setDomain('.127.0.0.1');
self::assertTrue($cookie->matchesDomain('127.0.0.1'));
$cookie->setDomain('127.0.0.1');
self::assertTrue($cookie->matchesDomain('127.0.0.1'));
$cookie->setDomain('.com.');
self::assertFalse($cookie->matchesDomain('baz.com'));
$cookie->setDomain('.local');
self::assertTrue($cookie->matchesDomain('example.local'));
$cookie->setDomain('example.com/'); // malformed domain
self::assertFalse($cookie->matchesDomain('example.com'));
}
public function pathMatchProvider()
{
return [
['/foo', '/foo', true],
['/foo', '/Foo', false],
['/foo', '/fo', false],
['/foo', '/foo/bar', true],
['/foo', '/foo/bar/baz', true],
['/foo', '/foo/bar//baz', true],
['/foo', '/foobar', false],
['/foo/bar', '/foo', false],
['/foo/bar', '/foobar', false],
['/foo/bar', '/foo/bar', true],
['/foo/bar', '/foo/bar/', true],
['/foo/bar', '/foo/bar/baz', true],
['/foo/bar/', '/foo/bar', false],
['/foo/bar/', '/foo/bar/', true],
['/foo/bar/', '/foo/bar/baz', true],
];
}
/**
* @dataProvider pathMatchProvider
*/
public function testMatchesPath($cookiePath, $requestPath, $isMatch)
{
$cookie = new SetCookie();
$cookie->setPath($cookiePath);
self::assertSame($isMatch, $cookie->matchesPath($requestPath));
}
public function cookieValidateProvider()
{
return [
['foo', 'baz', 'bar', true],
['0', '0', '0', true],
['foo[bar]', 'baz', 'bar', true],
['', 'baz', 'bar', 'The cookie name must not be empty'],
['foo', '', 'bar', 'The cookie value must not be empty'],
['foo', 'baz', '', 'The cookie domain must not be empty'],
["foo\r", 'baz', '0', 'Cookie name must not contain invalid characters: ASCII Control characters (0-31;127), space, tab and the following characters: ()<>@,;:\"/?={}'],
];
}
/**
* @dataProvider cookieValidateProvider
*/
public function testValidatesCookies($name, $value, $domain, $result)
{
$cookie = new SetCookie([
'Name' => $name,
'Value' => $value,
'Domain' => $domain,
]);
self::assertSame($result, $cookie->validate());
}
public function testDoesNotMatchIp()
{
$cookie = new SetCookie(['Domain' => '192.168.16.']);
self::assertFalse($cookie->matchesDomain('192.168.16.121'));
}
public function testConvertsToString()
{
$t = 1382916008;
$cookie = new SetCookie([
'Name' => 'test',
'Value' => '123',
'Domain' => 'foo.com',
'Expires' => $t,
'Path' => '/abc',
'HttpOnly' => true,
'Secure' => true
]);
self::assertSame(
'test=123; Domain=foo.com; Path=/abc; Expires=Sun, 27 Oct 2013 23:20:08 GMT; Secure; HttpOnly',
(string) $cookie
);
}
/**
* Provides the parsed information from a cookie
*
* @return array
*/
public function cookieParserDataProvider()
{
return [
[
'ASIHTTPRequestTestCookie=This+is+the+value; expires=Sat, 26-Jul-2008 17:00:42 GMT; path=/tests; domain=allseeing-i.com; PHPSESSID=6c951590e7a9359bcedde25cda73e43c; path=/;',
[
'Domain' => 'allseeing-i.com',
'Path' => '/',
'PHPSESSID' => '6c951590e7a9359bcedde25cda73e43c',
'Max-Age' => null,
'Expires' => 'Sat, 26-Jul-2008 17:00:42 GMT',
'Secure' => null,
'Discard' => null,
'Name' => 'ASIHTTPRequestTestCookie',
'Value' => 'This+is+the+value',
'HttpOnly' => false
]
],
['', []],
['foo', []],
['; foo', []],
[
'foo="bar"',
[
'Name' => 'foo',
'Value' => '"bar"',
'Discard' => null,
'Domain' => null,
'Expires' => null,
'Max-Age' => null,
'Path' => '/',
'Secure' => null,
'HttpOnly' => false
]
],
// Test setting a blank value for a cookie
[[
'foo=', 'foo =', 'foo =;', 'foo= ;', 'foo =', 'foo= '],
[
'Name' => 'foo',
'Value' => '',
'Discard' => null,
'Domain' => null,
'Expires' => null,
'Max-Age' => null,
'Path' => '/',
'Secure' => null,
'HttpOnly' => false
]
],
// Test setting a value and removing quotes
[[
'foo=1', 'foo =1', 'foo =1;', 'foo=1 ;', 'foo =1', 'foo= 1', 'foo = 1 ;'],
[
'Name' => 'foo',
'Value' => '1',
'Discard' => null,
'Domain' => null,
'Expires' => null,
'Max-Age' => null,
'Path' => '/',
'Secure' => null,
'HttpOnly' => false
]
],
// Some of the following tests are based on http://framework.zend.com/svn/framework/standard/trunk/tests/Zend/Http/CookieTest.php
[
'justacookie=foo; domain=example.com',
[
'Name' => 'justacookie',
'Value' => 'foo',
'Domain' => 'example.com',
'Discard' => null,
'Expires' => null,
'Max-Age' => null,
'Path' => '/',
'Secure' => null,
'HttpOnly' => false
]
],
[
'expires=tomorrow; secure; path=/Space Out/; expires=Tue, 21-Nov-2006 08:33:44 GMT; domain=.example.com',
[
'Name' => 'expires',
'Value' => 'tomorrow',
'Domain' => '.example.com',
'Path' => '/Space Out/',
'Expires' => 'Tue, 21-Nov-2006 08:33:44 GMT',
'Discard' => null,
'Secure' => true,
'Max-Age' => null,
'HttpOnly' => false
]
],
[
'domain=unittests; expires=Tue, 21-Nov-2006 08:33:44 GMT; domain=example.com; path=/some value/',
[
'Name' => 'domain',
'Value' => 'unittests',
'Domain' => 'example.com',
'Path' => '/some value/',
'Expires' => 'Tue, 21-Nov-2006 08:33:44 GMT',
'Secure' => false,
'Discard' => null,
'Max-Age' => null,
'HttpOnly' => false
]
],
[
'path=indexAction; path=/; domain=.foo.com; expires=Tue, 21-Nov-2006 08:33:44 GMT',
[
'Name' => 'path',
'Value' => 'indexAction',
'Domain' => '.foo.com',
'Path' => '/',
'Expires' => 'Tue, 21-Nov-2006 08:33:44 GMT',
'Secure' => false,
'Discard' => null,
'Max-Age' => null,
'HttpOnly' => false
]
],
[
'secure=sha1; secure; SECURE; domain=some.really.deep.domain.com; version=1; Max-Age=86400',
[
'Name' => 'secure',
'Value' => 'sha1',
'Domain' => 'some.really.deep.domain.com',
'Path' => '/',
'Secure' => true,
'Discard' => null,
'Expires' => time() + 86400,
'Max-Age' => 86400,
'HttpOnly' => false,
'version' => '1'
]
],
[
'PHPSESSID=123456789+abcd%2Cef; secure; discard; domain=.localdomain; path=/foo/baz; expires=Tue, 21-Nov-2006 08:33:44 GMT;',
[
'Name' => 'PHPSESSID',
'Value' => '123456789+abcd%2Cef',
'Domain' => '.localdomain',
'Path' => '/foo/baz',
'Expires' => 'Tue, 21-Nov-2006 08:33:44 GMT',
'Secure' => true,
'Discard' => true,
'Max-Age' => null,
'HttpOnly' => false
]
],
];
}
/**
* @dataProvider cookieParserDataProvider
*/
public function testParseCookie($cookie, $parsed)
{
foreach ((array) $cookie as $v) {
$c = SetCookie::fromString($v);
$p = $c->toArray();
if (isset($p['Expires'])) {
// Remove expires values from the assertion if they are relatively equal
if (abs($p['Expires'] != strtotime($parsed['Expires'])) < 40) {
unset($p['Expires']);
unset($parsed['Expires']);
}
}
if (!empty($parsed)) {
foreach ($parsed as $key => $value) {
self::assertEquals($parsed[$key], $p[$key], 'Comparing ' . $key . ' ' . var_export($value, true) . ' : ' . var_export($parsed, true) . ' | ' . var_export($p, true));
}
foreach ($p as $key => $value) {
self::assertEquals($p[$key], $parsed[$key], 'Comparing ' . $key . ' ' . var_export($value, true) . ' : ' . var_export($parsed, true) . ' | ' . var_export($p, true));
}
} else {
self::assertSame([
'Name' => null,
'Value' => null,
'Domain' => null,
'Path' => '/',
'Max-Age' => null,
'Expires' => null,
'Secure' => false,
'Discard' => false,
'HttpOnly' => false,
], $p);
}
}
}
/**
* Provides the data for testing isExpired
*
* @return array
*/
public function isExpiredProvider()
{
return [
[
'FOO=bar; expires=Thu, 01 Jan 1970 00:00:00 GMT;',
true,
],
[
'FOO=bar; expires=Thu, 01 Jan 1970 00:00:01 GMT;',
true,
],
[
'FOO=bar; expires=' . date(\DateTime::RFC1123, time()+10) . ';',
false,
],
[
'FOO=bar; expires=' . date(\DateTime::RFC1123, time()-10) . ';',
true,
],
[
'FOO=bar;',
false,
],
];
}
/**
* @dataProvider isExpiredProvider
*/
public function testIsExpired($cookie, $expired)
{
self::assertSame(
$expired,
SetCookie::fromString($cookie)->isExpired()
);
}
}

View File

@ -0,0 +1,25 @@
<?php
namespace GuzzleHttp\Tests\Exception;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Psr7\Request;
use PHPUnit\Framework\TestCase;
/**
* @covers \GuzzleHttp\Exception\ConnectException
*/
class ConnectExceptionTest extends TestCase
{
public function testHasNoResponse()
{
$req = new Request('GET', '/');
$prev = new \Exception();
$e = new ConnectException('foo', $req, $prev, ['foo' => 'bar']);
self::assertSame($req, $e->getRequest());
self::assertNull($e->getResponse());
self::assertFalse($e->hasResponse());
self::assertSame('foo', $e->getMessage());
self::assertSame('bar', $e->getHandlerContext()['foo']);
self::assertSame($prev, $e->getPrevious());
}
}

View File

@ -0,0 +1,195 @@
<?php
namespace GuzzleHttp\Tests\Exception;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Psr7\Stream;
use PHPUnit\Framework\TestCase;
/**
* @covers \GuzzleHttp\Exception\RequestException
*/
class RequestExceptionTest extends TestCase
{
public function testHasRequestAndResponse()
{
$req = new Request('GET', '/');
$res = new Response(200);
$e = new RequestException('foo', $req, $res);
self::assertSame($req, $e->getRequest());
self::assertSame($res, $e->getResponse());
self::assertTrue($e->hasResponse());
self::assertSame('foo', $e->getMessage());
}
public function testCreatesGenerateException()
{
$e = RequestException::create(new Request('GET', '/'));
self::assertSame('Error completing request', $e->getMessage());
self::assertInstanceOf('GuzzleHttp\Exception\RequestException', $e);
}
public function testCreatesClientErrorResponseException()
{
$e = RequestException::create(new Request('GET', '/'), new Response(400));
self::assertContains(
'GET /',
$e->getMessage()
);
self::assertContains(
'400 Bad Request',
$e->getMessage()
);
self::assertInstanceOf('GuzzleHttp\Exception\ClientException', $e);
}
public function testCreatesServerErrorResponseException()
{
$e = RequestException::create(new Request('GET', '/'), new Response(500));
self::assertContains(
'GET /',
$e->getMessage()
);
self::assertContains(
'500 Internal Server Error',
$e->getMessage()
);
self::assertInstanceOf('GuzzleHttp\Exception\ServerException', $e);
}
public function testCreatesGenericErrorResponseException()
{
$e = RequestException::create(new Request('GET', '/'), new Response(300));
self::assertContains(
'GET /',
$e->getMessage()
);
self::assertContains(
'300 ',
$e->getMessage()
);
self::assertInstanceOf('GuzzleHttp\Exception\RequestException', $e);
}
/**
* @expectedException InvalidArgumentException
* @expectedExceptionMessage Status code must be an integer value between 1xx and 5xx.
*/
public function testThrowsInvalidArgumentExceptionOnOutOfBoundsResponseCode()
{
throw RequestException::create(new Request('GET', '/'), new Response(600));
}
public function dataPrintableResponses()
{
return [
['You broke the test!'],
['<h1>zlomený zkouška</h1>'],
['{"tester": "Philépe Gonzalez"}'],
["<xml>\n\t<text>Your friendly test</text>\n</xml>"],
['document.body.write("here comes a test");'],
["body:before {\n\tcontent: 'test style';\n}"],
];
}
/**
* @dataProvider dataPrintableResponses
*/
public function testCreatesExceptionWithPrintableBodySummary($content)
{
$response = new Response(
500,
[],
$content
);
$e = RequestException::create(new Request('GET', '/'), $response);
self::assertContains(
$content,
$e->getMessage()
);
self::assertInstanceOf('GuzzleHttp\Exception\RequestException', $e);
}
public function testCreatesExceptionWithTruncatedSummary()
{
$content = str_repeat('+', 121);
$response = new Response(500, [], $content);
$e = RequestException::create(new Request('GET', '/'), $response);
$expected = str_repeat('+', 120) . ' (truncated...)';
self::assertContains($expected, $e->getMessage());
}
public function testExceptionMessageIgnoresEmptyBody()
{
$e = RequestException::create(new Request('GET', '/'), new Response(500));
self::assertStringEndsWith('response', $e->getMessage());
}
public function testHasStatusCodeAsExceptionCode()
{
$e = RequestException::create(new Request('GET', '/'), new Response(442));
self::assertSame(442, $e->getCode());
}
public function testWrapsRequestExceptions()
{
$e = new \Exception('foo');
$r = new Request('GET', 'http://www.oo.com');
$ex = RequestException::wrapException($r, $e);
self::assertInstanceOf('GuzzleHttp\Exception\RequestException', $ex);
self::assertSame($e, $ex->getPrevious());
}
public function testDoesNotWrapExistingRequestExceptions()
{
$r = new Request('GET', 'http://www.oo.com');
$e = new RequestException('foo', $r);
$e2 = RequestException::wrapException($r, $e);
self::assertSame($e, $e2);
}
public function testCanProvideHandlerContext()
{
$r = new Request('GET', 'http://www.oo.com');
$e = new RequestException('foo', $r, null, null, ['bar' => 'baz']);
self::assertSame(['bar' => 'baz'], $e->getHandlerContext());
}
public function testObfuscateUrlWithUsername()
{
$r = new Request('GET', 'http://username@www.oo.com');
$e = RequestException::create($r, new Response(500));
self::assertContains('http://username@www.oo.com', $e->getMessage());
}
public function testObfuscateUrlWithUsernameAndPassword()
{
$r = new Request('GET', 'http://user:password@www.oo.com');
$e = RequestException::create($r, new Response(500));
self::assertContains('http://user:***@www.oo.com', $e->getMessage());
}
public function testGetResponseBodySummaryOfNonReadableStream()
{
self::assertNull(RequestException::getResponseBodySummary(new Response(500, [], new ReadSeekOnlyStream())));
}
}
final class ReadSeekOnlyStream extends Stream
{
public function __construct()
{
parent::__construct(fopen('php://memory', 'wb'));
}
public function isSeekable()
{
return true;
}
public function isReadable()
{
return false;
}
}

View File

@ -0,0 +1,17 @@
<?php
namespace GuzzleHttp\Tests\Exception;
use GuzzleHttp\Exception\SeekException;
use GuzzleHttp\Psr7;
use PHPUnit\Framework\TestCase;
class SeekExceptionTest extends TestCase
{
public function testHasStream()
{
$s = Psr7\stream_for('foo');
$e = new SeekException($s, 10);
self::assertSame($s, $e->getStream());
self::assertContains('10', $e->getMessage());
}
}

View File

@ -0,0 +1,770 @@
<?php
namespace GuzzleHttp\Test\Handler;
use GuzzleHttp\Handler;
use GuzzleHttp\Handler\CurlFactory;
use GuzzleHttp\Handler\EasyHandle;
use GuzzleHttp\Psr7;
use GuzzleHttp\Tests\Server;
use GuzzleHttp\TransferStats;
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\ResponseInterface;
/**
* @covers \GuzzleHttp\Handler\CurlFactory
*/
class CurlFactoryTest extends TestCase
{
public static function setUpBeforeClass()
{
$_SERVER['curl_test'] = true;
unset($_SERVER['_curl']);
}
public static function tearDownAfterClass()
{
unset($_SERVER['_curl'], $_SERVER['curl_test']);
}
public function testCreatesCurlHandle()
{
Server::flush();
Server::enqueue([
new Psr7\Response(200, [
'Foo' => 'Bar',
'Baz' => 'bam',
'Content-Length' => 2,
], 'hi')
]);
$stream = Psr7\stream_for();
$request = new Psr7\Request('PUT', Server::$url, [
'Hi' => ' 123',
'Content-Length' => '7'
], 'testing');
$f = new Handler\CurlFactory(3);
$result = $f->create($request, ['sink' => $stream]);
self::assertInstanceOf(EasyHandle::class, $result);
self::assertInternalType('resource', $result->handle);
self::assertInternalType('array', $result->headers);
self::assertSame($stream, $result->sink);
curl_close($result->handle);
self::assertSame('PUT', $_SERVER['_curl'][CURLOPT_CUSTOMREQUEST]);
self::assertSame(
'http://127.0.0.1:8126/',
$_SERVER['_curl'][CURLOPT_URL]
);
// Sends via post fields when the request is small enough
self::assertSame('testing', $_SERVER['_curl'][CURLOPT_POSTFIELDS]);
self::assertEquals(0, $_SERVER['_curl'][CURLOPT_RETURNTRANSFER]);
self::assertEquals(0, $_SERVER['_curl'][CURLOPT_HEADER]);
self::assertSame(150, $_SERVER['_curl'][CURLOPT_CONNECTTIMEOUT]);
self::assertInstanceOf('Closure', $_SERVER['_curl'][CURLOPT_HEADERFUNCTION]);
if (defined('CURLOPT_PROTOCOLS')) {
self::assertSame(
CURLPROTO_HTTP | CURLPROTO_HTTPS,
$_SERVER['_curl'][CURLOPT_PROTOCOLS]
);
}
self::assertContains('Expect:', $_SERVER['_curl'][CURLOPT_HTTPHEADER]);
self::assertContains('Accept:', $_SERVER['_curl'][CURLOPT_HTTPHEADER]);
self::assertContains('Content-Type:', $_SERVER['_curl'][CURLOPT_HTTPHEADER]);
self::assertContains('Hi: 123', $_SERVER['_curl'][CURLOPT_HTTPHEADER]);
self::assertContains('Host: 127.0.0.1:8126', $_SERVER['_curl'][CURLOPT_HTTPHEADER]);
}
public function testSendsHeadRequests()
{
Server::flush();
Server::enqueue([new Psr7\Response()]);
$a = new Handler\CurlMultiHandler();
$response = $a(new Psr7\Request('HEAD', Server::$url), []);
$response->wait();
self::assertEquals(true, $_SERVER['_curl'][CURLOPT_NOBODY]);
$checks = [CURLOPT_WRITEFUNCTION, CURLOPT_READFUNCTION, CURLOPT_INFILE];
foreach ($checks as $check) {
self::assertArrayNotHasKey($check, $_SERVER['_curl']);
}
self::assertEquals('HEAD', Server::received()[0]->getMethod());
}
public function testCanAddCustomCurlOptions()
{
Server::flush();
Server::enqueue([new Psr7\Response()]);
$a = new Handler\CurlMultiHandler();
$req = new Psr7\Request('GET', Server::$url);
$a($req, ['curl' => [CURLOPT_LOW_SPEED_LIMIT => 10]]);
self::assertEquals(10, $_SERVER['_curl'][CURLOPT_LOW_SPEED_LIMIT]);
}
public function testCanChangeCurlOptions()
{
Server::flush();
Server::enqueue([new Psr7\Response()]);
$a = new Handler\CurlMultiHandler();
$req = new Psr7\Request('GET', Server::$url);
$a($req, ['curl' => [CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_0]]);
self::assertEquals(CURL_HTTP_VERSION_1_0, $_SERVER['_curl'][CURLOPT_HTTP_VERSION]);
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage SSL CA bundle not found: /does/not/exist
*/
public function testValidatesVerify()
{
$f = new Handler\CurlFactory(3);
$f->create(new Psr7\Request('GET', Server::$url), ['verify' => '/does/not/exist']);
}
public function testCanSetVerifyToFile()
{
$f = new Handler\CurlFactory(3);
$f->create(new Psr7\Request('GET', 'http://foo.com'), ['verify' => __FILE__]);
self::assertEquals(__FILE__, $_SERVER['_curl'][CURLOPT_CAINFO]);
self::assertEquals(2, $_SERVER['_curl'][CURLOPT_SSL_VERIFYHOST]);
self::assertEquals(true, $_SERVER['_curl'][CURLOPT_SSL_VERIFYPEER]);
}
public function testCanSetVerifyToDir()
{
$f = new Handler\CurlFactory(3);
$f->create(new Psr7\Request('GET', 'http://foo.com'), ['verify' => __DIR__]);
self::assertEquals(__DIR__, $_SERVER['_curl'][CURLOPT_CAPATH]);
self::assertEquals(2, $_SERVER['_curl'][CURLOPT_SSL_VERIFYHOST]);
self::assertEquals(true, $_SERVER['_curl'][CURLOPT_SSL_VERIFYPEER]);
}
public function testAddsVerifyAsTrue()
{
$f = new Handler\CurlFactory(3);
$f->create(new Psr7\Request('GET', Server::$url), ['verify' => true]);
self::assertEquals(2, $_SERVER['_curl'][CURLOPT_SSL_VERIFYHOST]);
self::assertEquals(true, $_SERVER['_curl'][CURLOPT_SSL_VERIFYPEER]);
self::assertArrayNotHasKey(CURLOPT_CAINFO, $_SERVER['_curl']);
}
public function testCanDisableVerify()
{
$f = new Handler\CurlFactory(3);
$f->create(new Psr7\Request('GET', Server::$url), ['verify' => false]);
self::assertEquals(0, $_SERVER['_curl'][CURLOPT_SSL_VERIFYHOST]);
self::assertEquals(false, $_SERVER['_curl'][CURLOPT_SSL_VERIFYPEER]);
}
public function testAddsProxy()
{
$f = new Handler\CurlFactory(3);
$f->create(new Psr7\Request('GET', Server::$url), ['proxy' => 'http://bar.com']);
self::assertEquals('http://bar.com', $_SERVER['_curl'][CURLOPT_PROXY]);
}
public function testAddsViaScheme()
{
$f = new Handler\CurlFactory(3);
$f->create(new Psr7\Request('GET', Server::$url), [
'proxy' => ['http' => 'http://bar.com', 'https' => 'https://t'],
]);
self::assertEquals('http://bar.com', $_SERVER['_curl'][CURLOPT_PROXY]);
$this->checkNoProxyForHost('http://test.test.com', ['test.test.com'], false);
$this->checkNoProxyForHost('http://test.test.com', ['.test.com'], false);
$this->checkNoProxyForHost('http://test.test.com', ['*.test.com'], true);
$this->checkNoProxyForHost('http://test.test.com', ['*'], false);
$this->checkNoProxyForHost('http://127.0.0.1', ['127.0.0.*'], true);
}
private function checkNoProxyForHost($url, $noProxy, $assertUseProxy)
{
$f = new Handler\CurlFactory(3);
$f->create(new Psr7\Request('GET', $url), [
'proxy' => [
'http' => 'http://bar.com',
'https' => 'https://t',
'no' => $noProxy
],
]);
if ($assertUseProxy) {
self::assertArrayHasKey(CURLOPT_PROXY, $_SERVER['_curl']);
} else {
self::assertArrayNotHasKey(CURLOPT_PROXY, $_SERVER['_curl']);
}
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage SSL private key not found: /does/not/exist
*/
public function testValidatesSslKey()
{
$f = new Handler\CurlFactory(3);
$f->create(new Psr7\Request('GET', Server::$url), ['ssl_key' => '/does/not/exist']);
}
public function testAddsSslKey()
{
$f = new Handler\CurlFactory(3);
$f->create(new Psr7\Request('GET', Server::$url), ['ssl_key' => __FILE__]);
self::assertEquals(__FILE__, $_SERVER['_curl'][CURLOPT_SSLKEY]);
}
public function testAddsSslKeyWithPassword()
{
$f = new Handler\CurlFactory(3);
$f->create(new Psr7\Request('GET', Server::$url), ['ssl_key' => [__FILE__, 'test']]);
self::assertEquals(__FILE__, $_SERVER['_curl'][CURLOPT_SSLKEY]);
self::assertEquals('test', $_SERVER['_curl'][CURLOPT_SSLKEYPASSWD]);
}
public function testAddsSslKeyWhenUsingArraySyntaxButNoPassword()
{
$f = new Handler\CurlFactory(3);
$f->create(new Psr7\Request('GET', Server::$url), ['ssl_key' => [__FILE__]]);
self::assertEquals(__FILE__, $_SERVER['_curl'][CURLOPT_SSLKEY]);
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage SSL certificate not found: /does/not/exist
*/
public function testValidatesCert()
{
$f = new Handler\CurlFactory(3);
$f->create(new Psr7\Request('GET', Server::$url), ['cert' => '/does/not/exist']);
}
public function testAddsCert()
{
$f = new Handler\CurlFactory(3);
$f->create(new Psr7\Request('GET', Server::$url), ['cert' => __FILE__]);
self::assertEquals(__FILE__, $_SERVER['_curl'][CURLOPT_SSLCERT]);
}
public function testAddsCertWithPassword()
{
$f = new Handler\CurlFactory(3);
$f->create(new Psr7\Request('GET', Server::$url), ['cert' => [__FILE__, 'test']]);
self::assertEquals(__FILE__, $_SERVER['_curl'][CURLOPT_SSLCERT]);
self::assertEquals('test', $_SERVER['_curl'][CURLOPT_SSLCERTPASSWD]);
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage progress client option must be callable
*/
public function testValidatesProgress()
{
$f = new Handler\CurlFactory(3);
$f->create(new Psr7\Request('GET', Server::$url), ['progress' => 'foo']);
}
public function testEmitsDebugInfoToStream()
{
$res = fopen('php://memory', 'r+');
Server::flush();
Server::enqueue([new Psr7\Response()]);
$a = new Handler\CurlMultiHandler();
$response = $a(new Psr7\Request('HEAD', Server::$url), ['debug' => $res]);
$response->wait();
rewind($res);
$output = str_replace("\r", '', stream_get_contents($res));
self::assertContains("> HEAD / HTTP/1.1", $output);
self::assertContains("< HTTP/1.1 200", $output);
fclose($res);
}
public function testEmitsProgressToFunction()
{
Server::flush();
Server::enqueue([new Psr7\Response()]);
$a = new Handler\CurlMultiHandler();
$called = [];
$request = new Psr7\Request('HEAD', Server::$url);
$response = $a($request, [
'progress' => function () use (&$called) {
$called[] = func_get_args();
},
]);
$response->wait();
self::assertNotEmpty($called);
foreach ($called as $call) {
self::assertCount(4, $call);
}
}
private function addDecodeResponse($withEncoding = true)
{
$content = gzencode('test');
$headers = ['Content-Length' => strlen($content)];
if ($withEncoding) {
$headers['Content-Encoding'] = 'gzip';
}
$response = new Psr7\Response(200, $headers, $content);
Server::flush();
Server::enqueue([$response]);
return $content;
}
public function testDecodesGzippedResponses()
{
$this->addDecodeResponse();
$handler = new Handler\CurlMultiHandler();
$request = new Psr7\Request('GET', Server::$url);
$response = $handler($request, ['decode_content' => true]);
$response = $response->wait();
self::assertEquals('test', (string) $response->getBody());
self::assertEquals('', $_SERVER['_curl'][CURLOPT_ENCODING]);
$sent = Server::received()[0];
self::assertFalse($sent->hasHeader('Accept-Encoding'));
}
public function testReportsOriginalSizeAndContentEncodingAfterDecoding()
{
$this->addDecodeResponse();
$handler = new Handler\CurlMultiHandler();
$request = new Psr7\Request('GET', Server::$url);
$response = $handler($request, ['decode_content' => true]);
$response = $response->wait();
self::assertSame(
'gzip',
$response->getHeaderLine('x-encoded-content-encoding')
);
self::assertSame(
strlen(gzencode('test')),
(int) $response->getHeaderLine('x-encoded-content-length')
);
}
public function testDecodesGzippedResponsesWithHeader()
{
$this->addDecodeResponse();
$handler = new Handler\CurlMultiHandler();
$request = new Psr7\Request('GET', Server::$url, ['Accept-Encoding' => 'gzip']);
$response = $handler($request, ['decode_content' => true]);
$response = $response->wait();
self::assertEquals('gzip', $_SERVER['_curl'][CURLOPT_ENCODING]);
$sent = Server::received()[0];
self::assertEquals('gzip', $sent->getHeaderLine('Accept-Encoding'));
self::assertEquals('test', (string) $response->getBody());
self::assertFalse($response->hasHeader('content-encoding'));
self::assertTrue(
!$response->hasHeader('content-length') ||
$response->getHeaderLine('content-length') == $response->getBody()->getSize()
);
}
public function testDoesNotForceDecode()
{
$content = $this->addDecodeResponse();
$handler = new Handler\CurlMultiHandler();
$request = new Psr7\Request('GET', Server::$url);
$response = $handler($request, ['decode_content' => false]);
$response = $response->wait();
$sent = Server::received()[0];
self::assertFalse($sent->hasHeader('Accept-Encoding'));
self::assertEquals($content, (string) $response->getBody());
}
public function testProtocolVersion()
{
Server::flush();
Server::enqueue([new Psr7\Response()]);
$a = new Handler\CurlMultiHandler();
$request = new Psr7\Request('GET', Server::$url, [], null, '1.0');
$a($request, []);
self::assertEquals(CURL_HTTP_VERSION_1_0, $_SERVER['_curl'][CURLOPT_HTTP_VERSION]);
}
public function testSavesToStream()
{
$stream = fopen('php://memory', 'r+');
$this->addDecodeResponse();
$handler = new Handler\CurlMultiHandler();
$request = new Psr7\Request('GET', Server::$url);
$response = $handler($request, [
'decode_content' => true,
'sink' => $stream,
]);
$response->wait();
rewind($stream);
self::assertEquals('test', stream_get_contents($stream));
}
public function testSavesToGuzzleStream()
{
$stream = Psr7\stream_for();
$this->addDecodeResponse();
$handler = new Handler\CurlMultiHandler();
$request = new Psr7\Request('GET', Server::$url);
$response = $handler($request, [
'decode_content' => true,
'sink' => $stream,
]);
$response->wait();
self::assertEquals('test', (string) $stream);
}
public function testSavesToFileOnDisk()
{
$tmpfile = tempnam(sys_get_temp_dir(), 'testfile');
$this->addDecodeResponse();
$handler = new Handler\CurlMultiHandler();
$request = new Psr7\Request('GET', Server::$url);
$response = $handler($request, [
'decode_content' => true,
'sink' => $tmpfile,
]);
$response->wait();
self::assertStringEqualsFile($tmpfile, 'test');
unlink($tmpfile);
}
public function testDoesNotAddMultipleContentLengthHeaders()
{
$this->addDecodeResponse();
$handler = new Handler\CurlMultiHandler();
$request = new Psr7\Request('PUT', Server::$url, ['Content-Length' => 3], 'foo');
$response = $handler($request, []);
$response->wait();
$sent = Server::received()[0];
self::assertEquals(3, $sent->getHeaderLine('Content-Length'));
self::assertFalse($sent->hasHeader('Transfer-Encoding'));
self::assertEquals('foo', (string) $sent->getBody());
}
public function testSendsPostWithNoBodyOrDefaultContentType()
{
Server::flush();
Server::enqueue([new Psr7\Response()]);
$handler = new Handler\CurlMultiHandler();
$request = new Psr7\Request('POST', Server::$url);
$response = $handler($request, []);
$response->wait();
$received = Server::received()[0];
self::assertEquals('POST', $received->getMethod());
self::assertFalse($received->hasHeader('content-type'));
self::assertSame('0', $received->getHeaderLine('content-length'));
}
/**
* @expectedException \GuzzleHttp\Exception\RequestException
* @expectedExceptionMessage but attempting to rewind the request body failed
*/
public function testFailsWhenCannotRewindRetryAfterNoResponse()
{
$factory = new Handler\CurlFactory(1);
$stream = Psr7\stream_for('abc');
$stream->read(1);
$stream = new Psr7\NoSeekStream($stream);
$request = new Psr7\Request('PUT', Server::$url, [], $stream);
$fn = function ($request, $options) use (&$fn, $factory) {
$easy = $factory->create($request, $options);
return Handler\CurlFactory::finish($fn, $easy, $factory);
};
$fn($request, [])->wait();
}
public function testRetriesWhenBodyCanBeRewound()
{
$callHandler = $called = false;
$fn = function ($r, $options) use (&$callHandler) {
$callHandler = true;
return \GuzzleHttp\Promise\promise_for(new Psr7\Response());
};
$bd = Psr7\FnStream::decorate(Psr7\stream_for('test'), [
'tell' => function () {
return 1;
},
'rewind' => function () use (&$called) {
$called = true;
}
]);
$factory = new Handler\CurlFactory(1);
$req = new Psr7\Request('PUT', Server::$url, [], $bd);
$easy = $factory->create($req, []);
$res = Handler\CurlFactory::finish($fn, $easy, $factory);
$res = $res->wait();
self::assertTrue($callHandler);
self::assertTrue($called);
self::assertEquals('200', $res->getStatusCode());
}
/**
* @expectedException \GuzzleHttp\Exception\RequestException
* @expectedExceptionMessage The cURL request was retried 3 times
*/
public function testFailsWhenRetryMoreThanThreeTimes()
{
$factory = new Handler\CurlFactory(1);
$call = 0;
$fn = function ($request, $options) use (&$mock, &$call, $factory) {
$call++;
$easy = $factory->create($request, $options);
return Handler\CurlFactory::finish($mock, $easy, $factory);
};
$mock = new Handler\MockHandler([$fn, $fn, $fn]);
$p = $mock(new Psr7\Request('PUT', Server::$url, [], 'test'), []);
$p->wait(false);
self::assertEquals(3, $call);
$p->wait(true);
}
public function testHandles100Continue()
{
Server::flush();
Server::enqueue([
new Psr7\Response(200, ['Test' => 'Hello', 'Content-Length' => 4], 'test'),
]);
$request = new Psr7\Request('PUT', Server::$url, [
'Expect' => '100-Continue'
], 'test');
$handler = new Handler\CurlMultiHandler();
$response = $handler($request, [])->wait();
self::assertSame(200, $response->getStatusCode());
self::assertSame('OK', $response->getReasonPhrase());
self::assertSame('Hello', $response->getHeaderLine('Test'));
self::assertSame('4', $response->getHeaderLine('Content-Length'));
self::assertSame('test', (string) $response->getBody());
}
/**
* @expectedException \GuzzleHttp\Exception\ConnectException
*/
public function testCreatesConnectException()
{
$m = new \ReflectionMethod(CurlFactory::class, 'finishError');
$m->setAccessible(true);
$factory = new Handler\CurlFactory(1);
$easy = $factory->create(new Psr7\Request('GET', Server::$url), []);
$easy->errno = CURLE_COULDNT_CONNECT;
$response = $m->invoke(
null,
function () {
},
$easy,
$factory
);
$response->wait();
}
public function testAddsTimeouts()
{
$f = new Handler\CurlFactory(3);
$f->create(new Psr7\Request('GET', Server::$url), [
'timeout' => 0.1,
'connect_timeout' => 0.2
]);
self::assertEquals(100, $_SERVER['_curl'][CURLOPT_TIMEOUT_MS]);
self::assertEquals(200, $_SERVER['_curl'][CURLOPT_CONNECTTIMEOUT_MS]);
}
public function testAddsStreamingBody()
{
$f = new Handler\CurlFactory(3);
$bd = Psr7\FnStream::decorate(Psr7\stream_for('foo'), [
'getSize' => function () {
return null;
}
]);
$request = new Psr7\Request('PUT', Server::$url, [], $bd);
$f->create($request, []);
self::assertEquals(1, $_SERVER['_curl'][CURLOPT_UPLOAD]);
self::assertInternalType('callable', $_SERVER['_curl'][CURLOPT_READFUNCTION]);
}
/**
* @expectedException \RuntimeException
* @expectedExceptionMessage Directory /does/not/exist/so does not exist for sink value of /does/not/exist/so/error.txt
*/
public function testEnsuresDirExistsBeforeThrowingWarning()
{
$f = new Handler\CurlFactory(3);
$f->create(new Psr7\Request('GET', Server::$url), [
'sink' => '/does/not/exist/so/error.txt'
]);
}
public function testClosesIdleHandles()
{
$f = new Handler\CurlFactory(3);
$req = new Psr7\Request('GET', Server::$url);
$easy = $f->create($req, []);
$h1 = $easy->handle;
$f->release($easy);
self::assertCount(1, self::readAttribute($f, 'handles'));
$easy = $f->create($req, []);
self::assertSame($easy->handle, $h1);
$easy2 = $f->create($req, []);
$easy3 = $f->create($req, []);
$easy4 = $f->create($req, []);
$f->release($easy);
self::assertCount(1, self::readAttribute($f, 'handles'));
$f->release($easy2);
self::assertCount(2, self::readAttribute($f, 'handles'));
$f->release($easy3);
self::assertCount(3, self::readAttribute($f, 'handles'));
$f->release($easy4);
self::assertCount(3, self::readAttribute($f, 'handles'));
}
/**
* @expectedException \InvalidArgumentException
*/
public function testEnsuresOnHeadersIsCallable()
{
$req = new Psr7\Request('GET', Server::$url);
$handler = new Handler\CurlHandler();
$handler($req, ['on_headers' => 'error!']);
}
/**
* @expectedException \GuzzleHttp\Exception\RequestException
* @expectedExceptionMessage An error was encountered during the on_headers event
* @expectedExceptionMessage test
*/
public function testRejectsPromiseWhenOnHeadersFails()
{
Server::flush();
Server::enqueue([
new Psr7\Response(200, ['X-Foo' => 'bar'], 'abc 123')
]);
$req = new Psr7\Request('GET', Server::$url);
$handler = new Handler\CurlHandler();
$promise = $handler($req, [
'on_headers' => function () {
throw new \Exception('test');
}
]);
$promise->wait();
}
public function testSuccessfullyCallsOnHeadersBeforeWritingToSink()
{
Server::flush();
Server::enqueue([
new Psr7\Response(200, ['X-Foo' => 'bar'], 'abc 123')
]);
$req = new Psr7\Request('GET', Server::$url);
$got = null;
$stream = Psr7\stream_for();
$stream = Psr7\FnStream::decorate($stream, [
'write' => function ($data) use ($stream, &$got) {
self::assertNotNull($got);
return $stream->write($data);
}
]);
$handler = new Handler\CurlHandler();
$promise = $handler($req, [
'sink' => $stream,
'on_headers' => function (ResponseInterface $res) use (&$got) {
$got = $res;
self::assertEquals('bar', $res->getHeaderLine('X-Foo'));
}
]);
$response = $promise->wait();
self::assertSame(200, $response->getStatusCode());
self::assertSame('bar', $response->getHeaderLine('X-Foo'));
self::assertSame('abc 123', (string) $response->getBody());
}
public function testInvokesOnStatsOnSuccess()
{
Server::flush();
Server::enqueue([new Psr7\Response(200)]);
$req = new Psr7\Request('GET', Server::$url);
$gotStats = null;
$handler = new Handler\CurlHandler();
$promise = $handler($req, [
'on_stats' => function (TransferStats $stats) use (&$gotStats) {
$gotStats = $stats;
}
]);
$response = $promise->wait();
self::assertSame(200, $response->getStatusCode());
self::assertSame(200, $gotStats->getResponse()->getStatusCode());
self::assertSame(
Server::$url,
(string) $gotStats->getEffectiveUri()
);
self::assertSame(
Server::$url,
(string) $gotStats->getRequest()->getUri()
);
self::assertGreaterThan(0, $gotStats->getTransferTime());
self::assertArrayHasKey('appconnect_time', $gotStats->getHandlerStats());
}
public function testInvokesOnStatsOnError()
{
$req = new Psr7\Request('GET', 'http://127.0.0.1:123');
$gotStats = null;
$handler = new Handler\CurlHandler();
$promise = $handler($req, [
'connect_timeout' => 0.001,
'timeout' => 0.001,
'on_stats' => function (TransferStats $stats) use (&$gotStats) {
$gotStats = $stats;
}
]);
$promise->wait(false);
self::assertFalse($gotStats->hasResponse());
self::assertSame(
'http://127.0.0.1:123',
(string) $gotStats->getEffectiveUri()
);
self::assertSame(
'http://127.0.0.1:123',
(string) $gotStats->getRequest()->getUri()
);
self::assertInternalType('float', $gotStats->getTransferTime());
self::assertInternalType('int', $gotStats->getHandlerErrorData());
self::assertArrayHasKey('appconnect_time', $gotStats->getHandlerStats());
}
public function testRewindsBodyIfPossible()
{
$body = Psr7\stream_for(str_repeat('x', 1024 * 1024 * 2));
$body->seek(1024 * 1024);
self::assertSame(1024 * 1024, $body->tell());
$req = new Psr7\Request('POST', 'https://www.example.com', [
'Content-Length' => 1024 * 1024 * 2,
], $body);
$factory = new CurlFactory(1);
$factory->create($req, []);
self::assertSame(0, $body->tell());
}
public function testDoesNotRewindUnseekableBody()
{
$body = Psr7\stream_for(str_repeat('x', 1024 * 1024 * 2));
$body->seek(1024 * 1024);
$body = new Psr7\NoSeekStream($body);
self::assertSame(1024 * 1024, $body->tell());
$req = new Psr7\Request('POST', 'https://www.example.com', [
'Content-Length' => 1024 * 1024,
], $body);
$factory = new CurlFactory(1);
$factory->create($req, []);
self::assertSame(1024 * 1024, $body->tell());
}
public function testRelease()
{
$factory = new CurlFactory(1);
$easyHandle = new EasyHandle();
$easyHandle->handle = curl_init();
self::assertEmpty($factory->release($easyHandle));
}
}

View File

@ -0,0 +1,87 @@
<?php
namespace GuzzleHttp\Test\Handler;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Handler\CurlHandler;
use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Tests\Server;
use GuzzleHttp\Utils;
use PHPUnit\Framework\TestCase;
/**
* @covers \GuzzleHttp\Handler\CurlHandler
*/
class CurlHandlerTest extends TestCase
{
protected function getHandler($options = [])
{
return new CurlHandler($options);
}
/**
* @expectedException \GuzzleHttp\Exception\ConnectException
* @expectedExceptionMessage cURL
*/
public function testCreatesCurlErrors()
{
$handler = new CurlHandler();
$request = new Request('GET', 'http://localhost:123');
$handler($request, ['timeout' => 0.001, 'connect_timeout' => 0.001])->wait();
}
public function testReusesHandles()
{
Server::flush();
$response = new response(200);
Server::enqueue([$response, $response]);
$a = new CurlHandler();
$request = new Request('GET', Server::$url);
self::assertInstanceOf('GuzzleHttp\Promise\FulfilledPromise', $a($request, []));
self::assertInstanceOf('GuzzleHttp\Promise\FulfilledPromise', $a($request, []));
}
public function testDoesSleep()
{
$response = new response(200);
Server::enqueue([$response]);
$a = new CurlHandler();
$request = new Request('GET', Server::$url);
$s = Utils::currentTime();
$a($request, ['delay' => 0.1])->wait();
self::assertGreaterThan(0.0001, Utils::currentTime() - $s);
}
public function testCreatesCurlErrorsWithContext()
{
$handler = new CurlHandler();
$request = new Request('GET', 'http://localhost:123');
$called = false;
$p = $handler($request, ['timeout' => 0.001, 'connect_timeout' => 0.001])
->otherwise(function (ConnectException $e) use (&$called) {
$called = true;
self::assertArrayHasKey('errno', $e->getHandlerContext());
});
$p->wait();
self::assertTrue($called);
}
public function testUsesContentLengthWhenOverInMemorySize()
{
Server::flush();
Server::enqueue([new Response()]);
$stream = Psr7\stream_for(str_repeat('.', 1000000));
$handler = new CurlHandler();
$request = new Request(
'PUT',
Server::$url,
['Content-Length' => 1000000],
$stream
);
$handler($request, [])->wait();
$received = Server::received()[0];
self::assertEquals(1000000, $received->getHeaderLine('Content-Length'));
self::assertFalse($received->hasHeader('Transfer-Encoding'));
}
}

View File

@ -0,0 +1,123 @@
<?php
namespace GuzzleHttp\Tests\Handler;
use GuzzleHttp\Handler\CurlMultiHandler;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Tests\Server;
use GuzzleHttp\Utils;
use PHPUnit\Framework\TestCase;
class CurlMultiHandlerTest extends TestCase
{
public function setUp()
{
$_SERVER['curl_test'] = true;
unset($_SERVER['_curl_multi']);
}
public function tearDown()
{
unset($_SERVER['_curl_multi'], $_SERVER['curl_test']);
}
public function testCanAddCustomCurlOptions()
{
Server::flush();
Server::enqueue([new Response()]);
$a = new CurlMultiHandler(['options' => [
CURLMOPT_MAXCONNECTS => 5,
]]);
$request = new Request('GET', Server::$url);
$a($request, []);
self::assertEquals(5, $_SERVER['_curl_multi'][CURLMOPT_MAXCONNECTS]);
}
public function testSendsRequest()
{
Server::enqueue([new Response()]);
$a = new CurlMultiHandler();
$request = new Request('GET', Server::$url);
$response = $a($request, [])->wait();
self::assertSame(200, $response->getStatusCode());
}
/**
* @expectedException \GuzzleHttp\Exception\ConnectException
* @expectedExceptionMessage cURL error
*/
public function testCreatesExceptions()
{
$a = new CurlMultiHandler();
$a(new Request('GET', 'http://localhost:123'), [])->wait();
}
public function testCanSetSelectTimeout()
{
$a = new CurlMultiHandler(['select_timeout' => 2]);
self::assertEquals(2, self::readAttribute($a, 'selectTimeout'));
}
public function testCanCancel()
{
Server::flush();
$response = new Response(200);
Server::enqueue(array_fill_keys(range(0, 10), $response));
$a = new CurlMultiHandler();
$responses = [];
for ($i = 0; $i < 10; $i++) {
$response = $a(new Request('GET', Server::$url), []);
$response->cancel();
$responses[] = $response;
}
foreach ($responses as $r) {
self::assertSame('rejected', $response->getState());
}
}
public function testCannotCancelFinished()
{
Server::flush();
Server::enqueue([new Response(200)]);
$a = new CurlMultiHandler();
$response = $a(new Request('GET', Server::$url), []);
$response->wait();
$response->cancel();
self::assertSame('fulfilled', $response->getState());
}
public function testDelaysConcurrently()
{
Server::flush();
Server::enqueue([new Response()]);
$a = new CurlMultiHandler();
$expected = Utils::currentTime() + (100 / 1000);
$response = $a(new Request('GET', Server::$url), ['delay' => 100]);
$response->wait();
self::assertGreaterThanOrEqual($expected, Utils::currentTime());
}
public function testUsesTimeoutEnvironmentVariables()
{
$a = new CurlMultiHandler();
//default if no options are given and no environment variable is set
self::assertEquals(1, self::readAttribute($a, 'selectTimeout'));
putenv("GUZZLE_CURL_SELECT_TIMEOUT=3");
$a = new CurlMultiHandler();
$selectTimeout = getenv('GUZZLE_CURL_SELECT_TIMEOUT');
//Handler reads from the environment if no options are given
self::assertEquals($selectTimeout, self::readAttribute($a, 'selectTimeout'));
}
/**
* @expectedException \BadMethodCallException
*/
public function throwsWhenAccessingInvalidProperty()
{
$h = new CurlMultiHandler();
$h->foo;
}
}

View File

@ -0,0 +1,23 @@
<?php
namespace GuzzleHttp\Test\Handler;
use GuzzleHttp\Handler\EasyHandle;
use GuzzleHttp\Psr7;
use PHPUnit\Framework\TestCase;
/**
* @covers \GuzzleHttp\Handler\EasyHandle
*/
class EasyHandleTest extends TestCase
{
/**
* @expectedException \BadMethodCallException
* @expectedExceptionMessage The EasyHandle has been released
*/
public function testEnsuresHandleExists()
{
$easy = new EasyHandle;
unset($easy->handle);
$easy->handle;
}
}

View File

@ -0,0 +1,261 @@
<?php
namespace GuzzleHttp\Test\Handler;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\Promise\PromiseInterface;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\TransferStats;
use PHPUnit\Framework\TestCase;
/**
* @covers \GuzzleHttp\Handler\MockHandler
*/
class MockHandlerTest extends TestCase
{
public function testReturnsMockResponse()
{
$res = new Response();
$mock = new MockHandler([$res]);
$request = new Request('GET', 'http://example.com');
$p = $mock($request, []);
self::assertSame($res, $p->wait());
}
public function testIsCountable()
{
$res = new Response();
$mock = new MockHandler([$res, $res]);
self::assertCount(2, $mock);
}
public function testEmptyHandlerIsCountable()
{
self::assertCount(0, new MockHandler());
}
/**
* @expectedException \InvalidArgumentException
*/
public function testEnsuresEachAppendIsValid()
{
$mock = new MockHandler(['a']);
$request = new Request('GET', 'http://example.com');
$mock($request, []);
}
public function testCanQueueExceptions()
{
$e = new \Exception('a');
$mock = new MockHandler([$e]);
$request = new Request('GET', 'http://example.com');
$p = $mock($request, []);
try {
$p->wait();
self::fail();
} catch (\Exception $e2) {
self::assertSame($e, $e2);
}
}
public function testCanGetLastRequestAndOptions()
{
$res = new Response();
$mock = new MockHandler([$res]);
$request = new Request('GET', 'http://example.com');
$mock($request, ['foo' => 'bar']);
self::assertSame($request, $mock->getLastRequest());
self::assertSame(['foo' => 'bar'], $mock->getLastOptions());
}
public function testSinkFilename()
{
$filename = sys_get_temp_dir() . '/mock_test_' . uniqid();
$res = new Response(200, [], 'TEST CONTENT');
$mock = new MockHandler([$res]);
$request = new Request('GET', '/');
$p = $mock($request, ['sink' => $filename]);
$p->wait();
self::assertFileExists($filename);
self::assertStringEqualsFile($filename, 'TEST CONTENT');
unlink($filename);
}
public function testSinkResource()
{
$file = tmpfile();
$meta = stream_get_meta_data($file);
$res = new Response(200, [], 'TEST CONTENT');
$mock = new MockHandler([$res]);
$request = new Request('GET', '/');
$p = $mock($request, ['sink' => $file]);
$p->wait();
self::assertFileExists($meta['uri']);
self::assertStringEqualsFile($meta['uri'], 'TEST CONTENT');
}
public function testSinkStream()
{
$stream = new \GuzzleHttp\Psr7\Stream(tmpfile());
$res = new Response(200, [], 'TEST CONTENT');
$mock = new MockHandler([$res]);
$request = new Request('GET', '/');
$p = $mock($request, ['sink' => $stream]);
$p->wait();
self::assertFileExists($stream->getMetadata('uri'));
self::assertStringEqualsFile($stream->getMetadata('uri'), 'TEST CONTENT');
}
public function testCanEnqueueCallables()
{
$r = new Response();
$fn = function ($req, $o) use ($r) {
return $r;
};
$mock = new MockHandler([$fn]);
$request = new Request('GET', 'http://example.com');
$p = $mock($request, ['foo' => 'bar']);
self::assertSame($r, $p->wait());
}
/**
* @expectedException \InvalidArgumentException
*/
public function testEnsuresOnHeadersIsCallable()
{
$res = new Response();
$mock = new MockHandler([$res]);
$request = new Request('GET', 'http://example.com');
$mock($request, ['on_headers' => 'error!']);
}
/**
* @expectedException \GuzzleHttp\Exception\RequestException
* @expectedExceptionMessage An error was encountered during the on_headers event
* @expectedExceptionMessage test
*/
public function testRejectsPromiseWhenOnHeadersFails()
{
$res = new Response();
$mock = new MockHandler([$res]);
$request = new Request('GET', 'http://example.com');
$promise = $mock($request, [
'on_headers' => function () {
throw new \Exception('test');
}
]);
$promise->wait();
}
public function testInvokesOnFulfilled()
{
$res = new Response();
$mock = new MockHandler([$res], function ($v) use (&$c) {
$c = $v;
});
$request = new Request('GET', 'http://example.com');
$mock($request, [])->wait();
self::assertSame($res, $c);
}
public function testInvokesOnRejected()
{
$e = new \Exception('a');
$c = null;
$mock = new MockHandler([$e], null, function ($v) use (&$c) {
$c = $v;
});
$request = new Request('GET', 'http://example.com');
$mock($request, [])->wait(false);
self::assertSame($e, $c);
}
/**
* @expectedException \OutOfBoundsException
*/
public function testThrowsWhenNoMoreResponses()
{
$mock = new MockHandler();
$request = new Request('GET', 'http://example.com');
$mock($request, []);
}
/**
* @expectedException \GuzzleHttp\Exception\BadResponseException
*/
public function testCanCreateWithDefaultMiddleware()
{
$r = new Response(500);
$mock = MockHandler::createWithMiddleware([$r]);
$request = new Request('GET', 'http://example.com');
$mock($request, ['http_errors' => true])->wait();
}
public function testInvokesOnStatsFunctionForResponse()
{
$res = new Response();
$mock = new MockHandler([$res]);
$request = new Request('GET', 'http://example.com');
/** @var TransferStats|null $stats */
$stats = null;
$onStats = function (TransferStats $s) use (&$stats) {
$stats = $s;
};
$p = $mock($request, ['on_stats' => $onStats]);
$p->wait();
self::assertSame($res, $stats->getResponse());
self::assertSame($request, $stats->getRequest());
}
public function testInvokesOnStatsFunctionForError()
{
$e = new \Exception('a');
$c = null;
$mock = new MockHandler([$e], null, function ($v) use (&$c) {
$c = $v;
});
$request = new Request('GET', 'http://example.com');
/** @var TransferStats|null $stats */
$stats = null;
$onStats = function (TransferStats $s) use (&$stats) {
$stats = $s;
};
$mock($request, ['on_stats' => $onStats])->wait(false);
self::assertSame($e, $stats->getHandlerErrorData());
self::assertNull($stats->getResponse());
self::assertSame($request, $stats->getRequest());
}
public function testTransferTime()
{
$e = new \Exception('a');
$c = null;
$mock = new MockHandler([$e], null, function ($v) use (&$c) {
$c = $v;
});
$request = new Request('GET', 'http://example.com');
$stats = null;
$onStats = function (TransferStats $s) use (&$stats) {
$stats = $s;
};
$mock($request, [ 'on_stats' => $onStats, 'transfer_time' => 0.4 ])->wait(false);
self::assertEquals(0.4, $stats->getTransferTime());
}
public function testResetQueue()
{
$mock = new MockHandler([new Response(200), new Response(204)]);
self::assertCount(2, $mock);
$mock->reset();
self::assertEmpty($mock);
$mock->append(new Response(500));
self::assertCount(1, $mock);
}
}

View File

@ -0,0 +1,74 @@
<?php
namespace GuzzleHttp\Test\Handler;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\Handler\Proxy;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\RequestOptions;
use PHPUnit\Framework\TestCase;
/**
* @covers \GuzzleHttp\Handler\Proxy
*/
class ProxyTest extends TestCase
{
public function testSendsToNonSync()
{
$a = $b = null;
$m1 = new MockHandler([function ($v) use (&$a) {
$a = $v;
}]);
$m2 = new MockHandler([function ($v) use (&$b) {
$b = $v;
}]);
$h = Proxy::wrapSync($m1, $m2);
$h(new Request('GET', 'http://foo.com'), []);
self::assertNotNull($a);
self::assertNull($b);
}
public function testSendsToSync()
{
$a = $b = null;
$m1 = new MockHandler([function ($v) use (&$a) {
$a = $v;
}]);
$m2 = new MockHandler([function ($v) use (&$b) {
$b = $v;
}]);
$h = Proxy::wrapSync($m1, $m2);
$h(new Request('GET', 'http://foo.com'), [RequestOptions::SYNCHRONOUS => true]);
self::assertNull($a);
self::assertNotNull($b);
}
public function testSendsToStreaming()
{
$a = $b = null;
$m1 = new MockHandler([function ($v) use (&$a) {
$a = $v;
}]);
$m2 = new MockHandler([function ($v) use (&$b) {
$b = $v;
}]);
$h = Proxy::wrapStreaming($m1, $m2);
$h(new Request('GET', 'http://foo.com'), []);
self::assertNotNull($a);
self::assertNull($b);
}
public function testSendsToNonStreaming()
{
$a = $b = null;
$m1 = new MockHandler([function ($v) use (&$a) {
$a = $v;
}]);
$m2 = new MockHandler([function ($v) use (&$b) {
$b = $v;
}]);
$h = Proxy::wrapStreaming($m1, $m2);
$h(new Request('GET', 'http://foo.com'), ['stream' => true]);
self::assertNull($a);
self::assertNotNull($b);
}
}

View File

@ -0,0 +1,689 @@
<?php
namespace GuzzleHttp\Test\Handler;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Handler\StreamHandler;
use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\FnStream;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\RequestOptions;
use GuzzleHttp\Tests\Server;
use GuzzleHttp\TransferStats;
use GuzzleHttp\Utils;
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\ResponseInterface;
/**
* @covers \GuzzleHttp\Handler\StreamHandler
*/
class StreamHandlerTest extends TestCase
{
private function queueRes()
{
Server::flush();
Server::enqueue([
new Response(200, [
'Foo' => 'Bar',
'Content-Length' => 8,
], 'hi there')
]);
}
public function testReturnsResponseForSuccessfulRequest()
{
$this->queueRes();
$handler = new StreamHandler();
$response = $handler(
new Request('GET', Server::$url, ['Foo' => 'Bar']),
[]
)->wait();
self::assertSame(200, $response->getStatusCode());
self::assertSame('OK', $response->getReasonPhrase());
self::assertSame('Bar', $response->getHeaderLine('Foo'));
self::assertSame('8', $response->getHeaderLine('Content-Length'));
self::assertSame('hi there', (string) $response->getBody());
$sent = Server::received()[0];
self::assertSame('GET', $sent->getMethod());
self::assertSame('/', $sent->getUri()->getPath());
self::assertSame('127.0.0.1:8126', $sent->getHeaderLine('Host'));
self::assertSame('Bar', $sent->getHeaderLine('foo'));
}
/**
* @expectedException \GuzzleHttp\Exception\RequestException
*/
public function testAddsErrorToResponse()
{
$handler = new StreamHandler();
$handler(
new Request('GET', 'http://localhost:123'),
['timeout' => 0.01]
)->wait();
}
public function testStreamAttributeKeepsStreamOpen()
{
$this->queueRes();
$handler = new StreamHandler();
$request = new Request(
'PUT',
Server::$url . 'foo?baz=bar',
['Foo' => 'Bar'],
'test'
);
$response = $handler($request, ['stream' => true])->wait();
self::assertSame(200, $response->getStatusCode());
self::assertSame('OK', $response->getReasonPhrase());
self::assertSame('8', $response->getHeaderLine('Content-Length'));
$body = $response->getBody();
$stream = $body->detach();
self::assertInternalType('resource', $stream);
self::assertSame('http', stream_get_meta_data($stream)['wrapper_type']);
self::assertSame('hi there', stream_get_contents($stream));
fclose($stream);
$sent = Server::received()[0];
self::assertSame('PUT', $sent->getMethod());
self::assertSame('http://127.0.0.1:8126/foo?baz=bar', (string) $sent->getUri());
self::assertSame('Bar', $sent->getHeaderLine('Foo'));
self::assertSame('test', (string) $sent->getBody());
}
public function testDrainsResponseIntoTempStream()
{
$this->queueRes();
$handler = new StreamHandler();
$request = new Request('GET', Server::$url);
$response = $handler($request, [])->wait();
$body = $response->getBody();
$stream = $body->detach();
self::assertSame('php://temp', stream_get_meta_data($stream)['uri']);
self::assertSame('hi', fread($stream, 2));
fclose($stream);
}
public function testDrainsResponseIntoSaveToBody()
{
$r = fopen('php://temp', 'r+');
$this->queueRes();
$handler = new StreamHandler();
$request = new Request('GET', Server::$url);
$response = $handler($request, ['sink' => $r])->wait();
$body = $response->getBody()->detach();
self::assertSame('php://temp', stream_get_meta_data($body)['uri']);
self::assertSame('hi', fread($body, 2));
self::assertSame(' there', stream_get_contents($r));
fclose($r);
}
public function testDrainsResponseIntoSaveToBodyAtPath()
{
$tmpfname = tempnam('/tmp', 'save_to_path');
$this->queueRes();
$handler = new StreamHandler();
$request = new Request('GET', Server::$url);
$response = $handler($request, ['sink' => $tmpfname])->wait();
$body = $response->getBody();
self::assertSame($tmpfname, $body->getMetadata('uri'));
self::assertSame('hi', $body->read(2));
$body->close();
unlink($tmpfname);
}
public function testDrainsResponseIntoSaveToBodyAtNonExistentPath()
{
$tmpfname = tempnam('/tmp', 'save_to_path');
unlink($tmpfname);
$this->queueRes();
$handler = new StreamHandler();
$request = new Request('GET', Server::$url);
$response = $handler($request, ['sink' => $tmpfname])->wait();
$body = $response->getBody();
self::assertSame($tmpfname, $body->getMetadata('uri'));
self::assertSame('hi', $body->read(2));
$body->close();
unlink($tmpfname);
}
public function testDrainsResponseAndReadsOnlyContentLengthBytes()
{
Server::flush();
Server::enqueue([
new Response(200, [
'Foo' => 'Bar',
'Content-Length' => 8,
], 'hi there... This has way too much data!')
]);
$handler = new StreamHandler();
$request = new Request('GET', Server::$url);
$response = $handler($request, [])->wait();
$body = $response->getBody();
$stream = $body->detach();
self::assertSame('hi there', stream_get_contents($stream));
fclose($stream);
}
public function testDoesNotDrainWhenHeadRequest()
{
Server::flush();
// Say the content-length is 8, but return no response.
Server::enqueue([
new Response(200, [
'Foo' => 'Bar',
'Content-Length' => 8,
], '')
]);
$handler = new StreamHandler();
$request = new Request('HEAD', Server::$url);
$response = $handler($request, [])->wait();
$body = $response->getBody();
$stream = $body->detach();
self::assertSame('', stream_get_contents($stream));
fclose($stream);
}
public function testAutomaticallyDecompressGzip()
{
Server::flush();
$content = gzencode('test');
Server::enqueue([
new Response(200, [
'Content-Encoding' => 'gzip',
'Content-Length' => strlen($content),
], $content)
]);
$handler = new StreamHandler();
$request = new Request('GET', Server::$url);
$response = $handler($request, ['decode_content' => true])->wait();
self::assertSame('test', (string) $response->getBody());
self::assertFalse($response->hasHeader('content-encoding'));
self::assertTrue(!$response->hasHeader('content-length') || $response->getHeaderLine('content-length') == $response->getBody()->getSize());
}
public function testReportsOriginalSizeAndContentEncodingAfterDecoding()
{
Server::flush();
$content = gzencode('test');
Server::enqueue([
new Response(200, [
'Content-Encoding' => 'gzip',
'Content-Length' => strlen($content),
], $content)
]);
$handler = new StreamHandler();
$request = new Request('GET', Server::$url);
$response = $handler($request, ['decode_content' => true])->wait();
self::assertSame(
'gzip',
$response->getHeaderLine('x-encoded-content-encoding')
);
self::assertSame(
strlen($content),
(int) $response->getHeaderLine('x-encoded-content-length')
);
}
public function testDoesNotForceGzipDecode()
{
Server::flush();
$content = gzencode('test');
Server::enqueue([
new Response(200, [
'Content-Encoding' => 'gzip',
'Content-Length' => strlen($content),
], $content)
]);
$handler = new StreamHandler();
$request = new Request('GET', Server::$url);
$response = $handler($request, ['decode_content' => false])->wait();
self::assertSame($content, (string) $response->getBody());
self::assertSame('gzip', $response->getHeaderLine('content-encoding'));
self::assertEquals(strlen($content), $response->getHeaderLine('content-length'));
}
public function testProtocolVersion()
{
$this->queueRes();
$handler = new StreamHandler();
$request = new Request('GET', Server::$url, [], null, '1.0');
$handler($request, []);
self::assertSame('1.0', Server::received()[0]->getProtocolVersion());
}
protected function getSendResult(array $opts)
{
$this->queueRes();
$handler = new StreamHandler();
$opts['stream'] = true;
$request = new Request('GET', Server::$url);
return $handler($request, $opts)->wait();
}
/**
* @expectedException \GuzzleHttp\Exception\ConnectException
* @expectedExceptionMessage Connection refused
*/
public function testAddsProxy()
{
$this->getSendResult(['proxy' => '127.0.0.1:8125']);
}
public function testAddsProxyByProtocol()
{
$url = str_replace('http', 'tcp', Server::$url);
// Workaround until #1823 is fixed properly
$url = rtrim($url, '/');
$res = $this->getSendResult(['proxy' => ['http' => $url]]);
$opts = stream_context_get_options($res->getBody()->detach());
self::assertSame($url, $opts['http']['proxy']);
}
public function testAddsProxyButHonorsNoProxy()
{
$url = str_replace('http', 'tcp', Server::$url);
$res = $this->getSendResult(['proxy' => [
'http' => $url,
'no' => ['*']
]]);
$opts = stream_context_get_options($res->getBody()->detach());
self::assertArrayNotHasKey('proxy', $opts['http']);
}
public function testAddsTimeout()
{
$res = $this->getSendResult(['stream' => true, 'timeout' => 200]);
$opts = stream_context_get_options($res->getBody()->detach());
self::assertEquals(200, $opts['http']['timeout']);
}
/**
* @expectedException \GuzzleHttp\Exception\RequestException
* @expectedExceptionMessage SSL CA bundle not found: /does/not/exist
*/
public function testVerifiesVerifyIsValidIfPath()
{
$this->getSendResult(['verify' => '/does/not/exist']);
}
public function testVerifyCanBeDisabled()
{
$handler = $this->getSendResult(['verify' => false]);
self::assertInstanceOf('GuzzleHttp\Psr7\Response', $handler);
}
/**
* @expectedException \GuzzleHttp\Exception\RequestException
* @expectedExceptionMessage SSL certificate not found: /does/not/exist
*/
public function testVerifiesCertIfValidPath()
{
$this->getSendResult(['cert' => '/does/not/exist']);
}
public function testVerifyCanBeSetToPath()
{
$path = $path = \GuzzleHttp\default_ca_bundle();
$res = $this->getSendResult(['verify' => $path]);
$opts = stream_context_get_options($res->getBody()->detach());
self::assertTrue($opts['ssl']['verify_peer']);
self::assertTrue($opts['ssl']['verify_peer_name']);
self::assertSame($path, $opts['ssl']['cafile']);
self::assertFileExists($opts['ssl']['cafile']);
}
public function testUsesSystemDefaultBundle()
{
$path = $path = \GuzzleHttp\default_ca_bundle();
$res = $this->getSendResult(['verify' => true]);
$opts = stream_context_get_options($res->getBody()->detach());
if (PHP_VERSION_ID < 50600) {
self::assertSame($path, $opts['ssl']['cafile']);
} else {
self::assertArrayNotHasKey('cafile', $opts['ssl']);
}
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage Invalid verify request option
*/
public function testEnsuresVerifyOptionIsValid()
{
$this->getSendResult(['verify' => 10]);
}
public function testCanSetPasswordWhenSettingCert()
{
$path = __FILE__;
$res = $this->getSendResult(['cert' => [$path, 'foo']]);
$opts = stream_context_get_options($res->getBody()->detach());
self::assertSame($path, $opts['ssl']['local_cert']);
self::assertSame('foo', $opts['ssl']['passphrase']);
}
public function testDebugAttributeWritesToStream()
{
$this->queueRes();
$f = fopen('php://temp', 'w+');
$this->getSendResult(['debug' => $f]);
fseek($f, 0);
$contents = stream_get_contents($f);
self::assertContains('<GET http://127.0.0.1:8126/> [CONNECT]', $contents);
self::assertContains('<GET http://127.0.0.1:8126/> [FILE_SIZE_IS]', $contents);
self::assertContains('<GET http://127.0.0.1:8126/> [PROGRESS]', $contents);
}
public function testDebugAttributeWritesStreamInfoToBuffer()
{
$called = false;
$this->queueRes();
$buffer = fopen('php://temp', 'r+');
$this->getSendResult([
'progress' => function () use (&$called) {
$called = true;
},
'debug' => $buffer,
]);
fseek($buffer, 0);
$contents = stream_get_contents($buffer);
self::assertContains('<GET http://127.0.0.1:8126/> [CONNECT]', $contents);
self::assertContains('<GET http://127.0.0.1:8126/> [FILE_SIZE_IS] message: "Content-Length: 8"', $contents);
self::assertContains('<GET http://127.0.0.1:8126/> [PROGRESS] bytes_max: "8"', $contents);
self::assertTrue($called);
}
public function testEmitsProgressInformation()
{
$called = [];
$this->queueRes();
$this->getSendResult([
'progress' => function () use (&$called) {
$called[] = func_get_args();
},
]);
self::assertNotEmpty($called);
self::assertEquals(8, $called[0][0]);
self::assertEquals(0, $called[0][1]);
}
public function testEmitsProgressInformationAndDebugInformation()
{
$called = [];
$this->queueRes();
$buffer = fopen('php://memory', 'w+');
$this->getSendResult([
'debug' => $buffer,
'progress' => function () use (&$called) {
$called[] = func_get_args();
},
]);
self::assertNotEmpty($called);
self::assertEquals(8, $called[0][0]);
self::assertEquals(0, $called[0][1]);
rewind($buffer);
self::assertNotEmpty(stream_get_contents($buffer));
fclose($buffer);
}
public function testPerformsShallowMergeOfCustomContextOptions()
{
$res = $this->getSendResult([
'stream_context' => [
'http' => [
'request_fulluri' => true,
'method' => 'HEAD',
],
'socket' => [
'bindto' => '127.0.0.1:0',
],
'ssl' => [
'verify_peer' => false,
],
],
]);
$opts = stream_context_get_options($res->getBody()->detach());
self::assertSame('HEAD', $opts['http']['method']);
self::assertTrue($opts['http']['request_fulluri']);
self::assertSame('127.0.0.1:0', $opts['socket']['bindto']);
self::assertFalse($opts['ssl']['verify_peer']);
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage stream_context must be an array
*/
public function testEnsuresThatStreamContextIsAnArray()
{
$this->getSendResult(['stream_context' => 'foo']);
}
public function testDoesNotAddContentTypeByDefault()
{
$this->queueRes();
$handler = new StreamHandler();
$request = new Request('PUT', Server::$url, ['Content-Length' => 3], 'foo');
$handler($request, []);
$req = Server::received()[0];
self::assertEquals('', $req->getHeaderLine('Content-Type'));
self::assertEquals(3, $req->getHeaderLine('Content-Length'));
}
public function testAddsContentLengthByDefault()
{
$this->queueRes();
$handler = new StreamHandler();
$request = new Request('PUT', Server::$url, [], 'foo');
$handler($request, []);
$req = Server::received()[0];
self::assertEquals(3, $req->getHeaderLine('Content-Length'));
}
public function testAddsContentLengthEvenWhenEmpty()
{
$this->queueRes();
$handler = new StreamHandler();
$request = new Request('PUT', Server::$url, [], '');
$handler($request, []);
$req = Server::received()[0];
self::assertEquals(0, $req->getHeaderLine('Content-Length'));
}
public function testSupports100Continue()
{
Server::flush();
$response = new Response(200, ['Test' => 'Hello', 'Content-Length' => '4'], 'test');
Server::enqueue([$response]);
$request = new Request('PUT', Server::$url, ['Expect' => '100-Continue'], 'test');
$handler = new StreamHandler();
$response = $handler($request, [])->wait();
self::assertSame(200, $response->getStatusCode());
self::assertSame('Hello', $response->getHeaderLine('Test'));
self::assertSame('4', $response->getHeaderLine('Content-Length'));
self::assertSame('test', (string) $response->getBody());
}
public function testDoesSleep()
{
$response = new response(200);
Server::enqueue([$response]);
$a = new StreamHandler();
$request = new Request('GET', Server::$url);
$s = Utils::currentTime();
$a($request, ['delay' => 0.1])->wait();
self::assertGreaterThan(0.0001, Utils::currentTime() - $s);
}
/**
* @expectedException \InvalidArgumentException
*/
public function testEnsuresOnHeadersIsCallable()
{
$req = new Request('GET', Server::$url);
$handler = new StreamHandler();
$handler($req, ['on_headers' => 'error!']);
}
/**
* @expectedException \GuzzleHttp\Exception\RequestException
* @expectedExceptionMessage An error was encountered during the on_headers event
* @expectedExceptionMessage test
*/
public function testRejectsPromiseWhenOnHeadersFails()
{
Server::flush();
Server::enqueue([
new Response(200, ['X-Foo' => 'bar'], 'abc 123')
]);
$req = new Request('GET', Server::$url);
$handler = new StreamHandler();
$promise = $handler($req, [
'on_headers' => function () {
throw new \Exception('test');
}
]);
$promise->wait();
}
public function testSuccessfullyCallsOnHeadersBeforeWritingToSink()
{
Server::flush();
Server::enqueue([
new Response(200, ['X-Foo' => 'bar'], 'abc 123')
]);
$req = new Request('GET', Server::$url);
$got = null;
$stream = Psr7\stream_for();
$stream = FnStream::decorate($stream, [
'write' => function ($data) use ($stream, &$got) {
self::assertNotNull($got);
return $stream->write($data);
}
]);
$handler = new StreamHandler();
$promise = $handler($req, [
'sink' => $stream,
'on_headers' => function (ResponseInterface $res) use (&$got) {
$got = $res;
self::assertSame('bar', $res->getHeaderLine('X-Foo'));
}
]);
$response = $promise->wait();
self::assertSame(200, $response->getStatusCode());
self::assertSame('bar', $response->getHeaderLine('X-Foo'));
self::assertSame('abc 123', (string) $response->getBody());
}
public function testInvokesOnStatsOnSuccess()
{
Server::flush();
Server::enqueue([new Psr7\Response(200)]);
$req = new Psr7\Request('GET', Server::$url);
$gotStats = null;
$handler = new StreamHandler();
$promise = $handler($req, [
'on_stats' => function (TransferStats $stats) use (&$gotStats) {
$gotStats = $stats;
}
]);
$response = $promise->wait();
self::assertSame(200, $response->getStatusCode());
self::assertSame(200, $gotStats->getResponse()->getStatusCode());
self::assertSame(
Server::$url,
(string) $gotStats->getEffectiveUri()
);
self::assertSame(
Server::$url,
(string) $gotStats->getRequest()->getUri()
);
self::assertGreaterThan(0, $gotStats->getTransferTime());
}
public function testInvokesOnStatsOnError()
{
$req = new Psr7\Request('GET', 'http://127.0.0.1:123');
$gotStats = null;
$handler = new StreamHandler();
$promise = $handler($req, [
'connect_timeout' => 0.001,
'timeout' => 0.001,
'on_stats' => function (TransferStats $stats) use (&$gotStats) {
$gotStats = $stats;
}
]);
$promise->wait(false);
self::assertFalse($gotStats->hasResponse());
self::assertSame(
'http://127.0.0.1:123',
(string) $gotStats->getEffectiveUri()
);
self::assertSame(
'http://127.0.0.1:123',
(string) $gotStats->getRequest()->getUri()
);
self::assertInternalType('float', $gotStats->getTransferTime());
self::assertInstanceOf(
ConnectException::class,
$gotStats->getHandlerErrorData()
);
}
public function testStreamIgnoresZeroTimeout()
{
Server::flush();
Server::enqueue([new Psr7\Response(200)]);
$req = new Psr7\Request('GET', Server::$url);
$gotStats = null;
$handler = new StreamHandler();
$promise = $handler($req, [
'connect_timeout' => 10,
'timeout' => 0
]);
$response = $promise->wait();
self::assertSame(200, $response->getStatusCode());
}
public function testDrainsResponseAndReadsAllContentWhenContentLengthIsZero()
{
Server::flush();
Server::enqueue([
new Response(200, [
'Foo' => 'Bar',
'Content-Length' => '0',
], 'hi there... This has a lot of data!')
]);
$handler = new StreamHandler();
$request = new Request('GET', Server::$url);
$response = $handler($request, [])->wait();
$body = $response->getBody();
$stream = $body->detach();
self::assertSame('hi there... This has a lot of data!', stream_get_contents($stream));
fclose($stream);
}
public function testHonorsReadTimeout()
{
Server::flush();
$handler = new StreamHandler();
$response = $handler(
new Request('GET', Server::$url . 'guzzle-server/read-timeout'),
[
RequestOptions::READ_TIMEOUT => 1,
RequestOptions::STREAM => true,
]
)->wait();
self::assertSame(200, $response->getStatusCode());
self::assertSame('OK', $response->getReasonPhrase());
$body = $response->getBody()->detach();
$line = fgets($body);
self::assertSame("sleeping 60 seconds ...\n", $line);
$line = fgets($body);
self::assertFalse($line);
self::assertTrue(stream_get_meta_data($body)['timed_out']);
self::assertFalse(feof($body));
}
}

View File

@ -0,0 +1,214 @@
<?php
namespace GuzzleHttp\Tests;
use GuzzleHttp\Cookie\CookieJar;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use PHPUnit\Framework\TestCase;
class HandlerStackTest extends TestCase
{
public function testSetsHandlerInCtor()
{
$f = function () {
};
$m1 = function () {
};
$h = new HandlerStack($f, [$m1]);
self::assertTrue($h->hasHandler());
}
/**
* @doesNotPerformAssertions
*/
public function testCanSetDifferentHandlerAfterConstruction()
{
$f = function () {
};
$h = new HandlerStack();
$h->setHandler($f);
$h->resolve();
}
/**
* @expectedException \LogicException
*/
public function testEnsuresHandlerIsSet()
{
$h = new HandlerStack();
$h->resolve();
}
public function testPushInOrder()
{
$meths = $this->getFunctions();
$builder = new HandlerStack();
$builder->setHandler($meths[1]);
$builder->push($meths[2]);
$builder->push($meths[3]);
$builder->push($meths[4]);
$composed = $builder->resolve();
self::assertSame('Hello - test123', $composed('test'));
self::assertSame(
[['a', 'test'], ['b', 'test1'], ['c', 'test12']],
$meths[0]
);
}
public function testUnshiftsInReverseOrder()
{
$meths = $this->getFunctions();
$builder = new HandlerStack();
$builder->setHandler($meths[1]);
$builder->unshift($meths[2]);
$builder->unshift($meths[3]);
$builder->unshift($meths[4]);
$composed = $builder->resolve();
self::assertSame('Hello - test321', $composed('test'));
self::assertSame(
[['c', 'test'], ['b', 'test3'], ['a', 'test32']],
$meths[0]
);
}
public function testCanRemoveMiddlewareByInstance()
{
$meths = $this->getFunctions();
$builder = new HandlerStack();
$builder->setHandler($meths[1]);
$builder->push($meths[2]);
$builder->push($meths[2]);
$builder->push($meths[3]);
$builder->push($meths[4]);
$builder->push($meths[2]);
$builder->remove($meths[3]);
$composed = $builder->resolve();
self::assertSame('Hello - test1131', $composed('test'));
}
public function testCanPrintMiddleware()
{
$meths = $this->getFunctions();
$builder = new HandlerStack();
$builder->setHandler($meths[1]);
$builder->push($meths[2], 'a');
$builder->push([__CLASS__, 'foo']);
$builder->push([$this, 'bar']);
$builder->push(__CLASS__ . '::' . 'foo');
$lines = explode("\n", (string) $builder);
self::assertContains("> 4) Name: 'a', Function: callable(", $lines[0]);
self::assertContains("> 3) Name: '', Function: callable(GuzzleHttp\\Tests\\HandlerStackTest::foo)", $lines[1]);
self::assertContains("> 2) Name: '', Function: callable(['GuzzleHttp\\Tests\\HandlerStackTest', 'bar'])", $lines[2]);
self::assertContains("> 1) Name: '', Function: callable(GuzzleHttp\\Tests\\HandlerStackTest::foo)", $lines[3]);
self::assertContains("< 0) Handler: callable(", $lines[4]);
self::assertContains("< 1) Name: '', Function: callable(GuzzleHttp\\Tests\\HandlerStackTest::foo)", $lines[5]);
self::assertContains("< 2) Name: '', Function: callable(['GuzzleHttp\\Tests\\HandlerStackTest', 'bar'])", $lines[6]);
self::assertContains("< 3) Name: '', Function: callable(GuzzleHttp\\Tests\\HandlerStackTest::foo)", $lines[7]);
self::assertContains("< 4) Name: 'a', Function: callable(", $lines[8]);
}
public function testCanAddBeforeByName()
{
$meths = $this->getFunctions();
$builder = new HandlerStack();
$builder->setHandler($meths[1]);
$builder->push($meths[2], 'foo');
$builder->before('foo', $meths[3], 'baz');
$builder->before('baz', $meths[4], 'bar');
$builder->before('baz', $meths[4], 'qux');
$lines = explode("\n", (string) $builder);
self::assertContains('> 4) Name: \'bar\'', $lines[0]);
self::assertContains('> 3) Name: \'qux\'', $lines[1]);
self::assertContains('> 2) Name: \'baz\'', $lines[2]);
self::assertContains('> 1) Name: \'foo\'', $lines[3]);
}
/**
* @expectedException \InvalidArgumentException
*/
public function testEnsuresHandlerExistsByName()
{
$builder = new HandlerStack();
$builder->before('foo', function () {
});
}
public function testCanAddAfterByName()
{
$meths = $this->getFunctions();
$builder = new HandlerStack();
$builder->setHandler($meths[1]);
$builder->push($meths[2], 'a');
$builder->push($meths[3], 'b');
$builder->after('a', $meths[4], 'c');
$builder->after('b', $meths[4], 'd');
$lines = explode("\n", (string) $builder);
self::assertContains('4) Name: \'a\'', $lines[0]);
self::assertContains('3) Name: \'c\'', $lines[1]);
self::assertContains('2) Name: \'b\'', $lines[2]);
self::assertContains('1) Name: \'d\'', $lines[3]);
}
public function testPicksUpCookiesFromRedirects()
{
$mock = new MockHandler([
new Response(301, [
'Location' => 'http://foo.com/baz',
'Set-Cookie' => 'foo=bar; Domain=foo.com'
]),
new Response(200)
]);
$handler = HandlerStack::create($mock);
$request = new Request('GET', 'http://foo.com/bar');
$jar = new CookieJar();
$response = $handler($request, [
'allow_redirects' => true,
'cookies' => $jar
])->wait();
self::assertSame(200, $response->getStatusCode());
$lastRequest = $mock->getLastRequest();
self::assertSame('http://foo.com/baz', (string) $lastRequest->getUri());
self::assertSame('foo=bar', $lastRequest->getHeaderLine('Cookie'));
}
private function getFunctions()
{
$calls = [];
$a = function (callable $next) use (&$calls) {
return function ($v) use ($next, &$calls) {
$calls[] = ['a', $v];
return $next($v . '1');
};
};
$b = function (callable $next) use (&$calls) {
return function ($v) use ($next, &$calls) {
$calls[] = ['b', $v];
return $next($v . '2');
};
};
$c = function (callable $next) use (&$calls) {
return function ($v) use ($next, &$calls) {
$calls[] = ['c', $v];
return $next($v . '3');
};
};
$handler = function ($v) {
return 'Hello - ' . $v;
};
return [&$calls, $handler, $a, $b, $c];
}
public static function foo()
{
}
public function bar()
{
}
}

View File

@ -0,0 +1,21 @@
<?php
namespace GuzzleHttp\Test;
use GuzzleHttp\Psr7;
use GuzzleHttp\Utils;
use PHPUnit\Framework\TestCase;
class InternalUtilsTest extends TestCase
{
public function testCurrentTime()
{
self::assertGreaterThan(0, Utils::currentTime());
}
public function testIdnConvert()
{
$uri = Psr7\uri_for('https://яндекс.рф/images');
$uri = Utils::idnUriConvert($uri);
self::assertSame('xn--d1acpjx3f.xn--p1ai', $uri->getHost());
}
}

View File

@ -0,0 +1,93 @@
<?php
namespace GuzzleHttp\Tests;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\MessageFormatter;
use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use PHPUnit\Framework\TestCase;
/**
* @covers GuzzleHttp\MessageFormatter
*/
class MessageFormatterTest extends TestCase
{
public function testCreatesWithClfByDefault()
{
$f = new MessageFormatter();
self::assertEquals(MessageFormatter::CLF, self::readAttribute($f, 'template'));
$f = new MessageFormatter(null);
self::assertEquals(MessageFormatter::CLF, self::readAttribute($f, 'template'));
}
public function dateProvider()
{
return [
['{ts}', '/^[0-9]{4}\-[0-9]{2}\-[0-9]{2}/'],
['{date_iso_8601}', '/^[0-9]{4}\-[0-9]{2}\-[0-9]{2}/'],
['{date_common_log}', '/^\d\d\/[A-Z][a-z]{2}\/[0-9]{4}/']
];
}
/**
* @dataProvider dateProvider
*/
public function testFormatsTimestamps($format, $pattern)
{
$f = new MessageFormatter($format);
$request = new Request('GET', '/');
$result = $f->format($request);
self::assertRegExp($pattern, $result);
}
public function formatProvider()
{
$request = new Request('PUT', '/', ['x-test' => 'abc'], Psr7\stream_for('foo'));
$response = new Response(200, ['X-Baz' => 'Bar'], Psr7\stream_for('baz'));
$err = new RequestException('Test', $request, $response);
return [
['{request}', [$request], Psr7\str($request)],
['{response}', [$request, $response], Psr7\str($response)],
['{request} {response}', [$request, $response], Psr7\str($request) . ' ' . Psr7\str($response)],
// Empty response yields no value
['{request} {response}', [$request], Psr7\str($request) . ' '],
['{req_headers}', [$request], "PUT / HTTP/1.1\r\nx-test: abc"],
['{res_headers}', [$request, $response], "HTTP/1.1 200 OK\r\nX-Baz: Bar"],
['{res_headers}', [$request], 'NULL'],
['{req_body}', [$request], 'foo'],
['{res_body}', [$request, $response], 'baz'],
['{res_body}', [$request], 'NULL'],
['{method}', [$request], $request->getMethod()],
['{url}', [$request], $request->getUri()],
['{target}', [$request], $request->getRequestTarget()],
['{req_version}', [$request], $request->getProtocolVersion()],
['{res_version}', [$request, $response], $response->getProtocolVersion()],
['{res_version}', [$request], 'NULL'],
['{host}', [$request], $request->getHeaderLine('Host')],
['{hostname}', [$request, $response], gethostname()],
['{hostname}{hostname}', [$request, $response], gethostname() . gethostname()],
['{code}', [$request, $response], $response->getStatusCode()],
['{code}', [$request], 'NULL'],
['{phrase}', [$request, $response], $response->getReasonPhrase()],
['{phrase}', [$request], 'NULL'],
['{error}', [$request, $response, $err], 'Test'],
['{error}', [$request], 'NULL'],
['{req_header_x-test}', [$request], 'abc'],
['{req_header_x-not}', [$request], ''],
['{res_header_X-Baz}', [$request, $response], 'Bar'],
['{res_header_x-not}', [$request, $response], ''],
['{res_header_X-Baz}', [$request], 'NULL'],
];
}
/**
* @dataProvider formatProvider
*/
public function testFormatsMessages($template, $args, $result)
{
$f = new MessageFormatter($template);
self::assertSame((string) $result, call_user_func_array([$f, 'format'], $args));
}
}

View File

@ -0,0 +1,217 @@
<?php
namespace GuzzleHttp\Tests;
use GuzzleHttp\Cookie\CookieJar;
use GuzzleHttp\Cookie\SetCookie;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\MessageFormatter;
use GuzzleHttp\Middleware;
use GuzzleHttp\Promise\PromiseInterface;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Log\Test\TestLogger;
class MiddlewareTest extends TestCase
{
public function testAddsCookiesToRequests()
{
$jar = new CookieJar();
$m = Middleware::cookies($jar);
$h = new MockHandler(
[
function (RequestInterface $request) {
return new Response(200, [
'Set-Cookie' => (string) new SetCookie([
'Name' => 'name',
'Value' => 'value',
'Domain' => 'foo.com'
])
]);
}
]
);
$f = $m($h);
$f(new Request('GET', 'http://foo.com'), ['cookies' => $jar])->wait();
self::assertCount(1, $jar);
}
/**
* @expectedException \GuzzleHttp\Exception\ClientException
*/
public function testThrowsExceptionOnHttpClientError()
{
$m = Middleware::httpErrors();
$h = new MockHandler([new Response(404)]);
$f = $m($h);
$p = $f(new Request('GET', 'http://foo.com'), ['http_errors' => true]);
self::assertSame('pending', $p->getState());
$p->wait();
self::assertSame('rejected', $p->getState());
}
/**
* @expectedException \GuzzleHttp\Exception\ServerException
*/
public function testThrowsExceptionOnHttpServerError()
{
$m = Middleware::httpErrors();
$h = new MockHandler([new Response(500)]);
$f = $m($h);
$p = $f(new Request('GET', 'http://foo.com'), ['http_errors' => true]);
self::assertSame('pending', $p->getState());
$p->wait();
self::assertSame('rejected', $p->getState());
}
/**
* @dataProvider getHistoryUseCases
*/
public function testTracksHistory($container)
{
$m = Middleware::history($container);
$h = new MockHandler([new Response(200), new Response(201)]);
$f = $m($h);
$p1 = $f(new Request('GET', 'http://foo.com'), ['headers' => ['foo' => 'bar']]);
$p2 = $f(new Request('HEAD', 'http://foo.com'), ['headers' => ['foo' => 'baz']]);
$p1->wait();
$p2->wait();
self::assertCount(2, $container);
self::assertSame(200, $container[0]['response']->getStatusCode());
self::assertSame(201, $container[1]['response']->getStatusCode());
self::assertSame('GET', $container[0]['request']->getMethod());
self::assertSame('HEAD', $container[1]['request']->getMethod());
self::assertSame('bar', $container[0]['options']['headers']['foo']);
self::assertSame('baz', $container[1]['options']['headers']['foo']);
}
public function getHistoryUseCases()
{
return [
[[]], // 1. Container is an array
[new \ArrayObject()] // 2. Container is an ArrayObject
];
}
public function testTracksHistoryForFailures()
{
$container = [];
$m = Middleware::history($container);
$request = new Request('GET', 'http://foo.com');
$h = new MockHandler([new RequestException('error', $request)]);
$f = $m($h);
$f($request, [])->wait(false);
self::assertCount(1, $container);
self::assertSame('GET', $container[0]['request']->getMethod());
self::assertInstanceOf(RequestException::class, $container[0]['error']);
}
public function testTapsBeforeAndAfter()
{
$calls = [];
$m = function ($handler) use (&$calls) {
return function ($request, $options) use ($handler, &$calls) {
$calls[] = '2';
return $handler($request, $options);
};
};
$m2 = Middleware::tap(
function (RequestInterface $request, array $options) use (&$calls) {
$calls[] = '1';
},
function (RequestInterface $request, array $options, PromiseInterface $p) use (&$calls) {
$calls[] = '3';
}
);
$h = new MockHandler([new Response()]);
$b = new HandlerStack($h);
$b->push($m2);
$b->push($m);
$comp = $b->resolve();
$p = $comp(new Request('GET', 'http://foo.com'), []);
self::assertSame('123', implode('', $calls));
self::assertInstanceOf(PromiseInterface::class, $p);
self::assertSame(200, $p->wait()->getStatusCode());
}
public function testMapsRequest()
{
$h = new MockHandler([
function (RequestInterface $request, array $options) {
self::assertSame('foo', $request->getHeaderLine('Bar'));
return new Response(200);
}
]);
$stack = new HandlerStack($h);
$stack->push(Middleware::mapRequest(function (RequestInterface $request) {
return $request->withHeader('Bar', 'foo');
}));
$comp = $stack->resolve();
$p = $comp(new Request('PUT', 'http://www.google.com'), []);
self::assertInstanceOf(PromiseInterface::class, $p);
}
public function testMapsResponse()
{
$h = new MockHandler([new Response(200)]);
$stack = new HandlerStack($h);
$stack->push(Middleware::mapResponse(function (ResponseInterface $response) {
return $response->withHeader('Bar', 'foo');
}));
$comp = $stack->resolve();
$p = $comp(new Request('PUT', 'http://www.google.com'), []);
$p->wait();
self::assertSame('foo', $p->wait()->getHeaderLine('Bar'));
}
public function testLogsRequestsAndResponses()
{
$h = new MockHandler([new Response(200)]);
$stack = new HandlerStack($h);
$logger = new TestLogger();
$formatter = new MessageFormatter();
$stack->push(Middleware::log($logger, $formatter));
$comp = $stack->resolve();
$p = $comp(new Request('PUT', 'http://www.google.com'), []);
$p->wait();
self::assertCount(1, $logger->records);
self::assertContains('"PUT / HTTP/1.1" 200', $logger->records[0]['message']);
}
public function testLogsRequestsAndResponsesCustomLevel()
{
$h = new MockHandler([new Response(200)]);
$stack = new HandlerStack($h);
$logger = new TestLogger();
$formatter = new MessageFormatter();
$stack->push(Middleware::log($logger, $formatter, 'debug'));
$comp = $stack->resolve();
$p = $comp(new Request('PUT', 'http://www.google.com'), []);
$p->wait();
self::assertCount(1, $logger->records);
self::assertContains('"PUT / HTTP/1.1" 200', $logger->records[0]['message']);
self::assertSame('debug', $logger->records[0]['level']);
}
public function testLogsRequestsAndErrors()
{
$h = new MockHandler([new Response(404)]);
$stack = new HandlerStack($h);
$logger = new TestLogger();
$formatter = new MessageFormatter('{code} {error}');
$stack->push(Middleware::log($logger, $formatter));
$stack->push(Middleware::httpErrors());
$comp = $stack->resolve();
$p = $comp(new Request('PUT', 'http://www.google.com'), ['http_errors' => true]);
$p->wait(false);
self::assertCount(1, $logger->records);
self::assertContains('PUT http://www.google.com', $logger->records[0]['message']);
self::assertContains('404 Not Found', $logger->records[0]['message']);
}
}

View File

@ -0,0 +1,193 @@
<?php
namespace GuzzleHttp\Tests;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Pool;
use GuzzleHttp\Promise\Promise;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\RequestInterface;
class PoolTest extends TestCase
{
/**
* @expectedException \InvalidArgumentException
*/
public function testValidatesIterable()
{
$p = new Pool(new Client(), 'foo');
$p->promise()->wait();
}
/**
* @expectedException \InvalidArgumentException
*/
public function testValidatesEachElement()
{
$c = new Client();
$requests = ['foo'];
$p = new Pool($c, new \ArrayIterator($requests));
$p->promise()->wait();
}
/**
* @doesNotPerformAssertions
*/
public function testSendsAndRealizesFuture()
{
$c = $this->getClient();
$p = new Pool($c, [new Request('GET', 'http://example.com')]);
$p->promise()->wait();
}
/**
* @doesNotPerformAssertions
*/
public function testExecutesPendingWhenWaiting()
{
$r1 = new Promise(function () use (&$r1) {
$r1->resolve(new Response());
});
$r2 = new Promise(function () use (&$r2) {
$r2->resolve(new Response());
});
$r3 = new Promise(function () use (&$r3) {
$r3->resolve(new Response());
});
$handler = new MockHandler([$r1, $r2, $r3]);
$c = new Client(['handler' => $handler]);
$p = new Pool($c, [
new Request('GET', 'http://example.com'),
new Request('GET', 'http://example.com'),
new Request('GET', 'http://example.com'),
], ['pool_size' => 2]);
$p->promise()->wait();
}
public function testUsesRequestOptions()
{
$h = [];
$handler = new MockHandler([
function (RequestInterface $request) use (&$h) {
$h[] = $request;
return new Response();
}
]);
$c = new Client(['handler' => $handler]);
$opts = ['options' => ['headers' => ['x-foo' => 'bar']]];
$p = new Pool($c, [new Request('GET', 'http://example.com')], $opts);
$p->promise()->wait();
self::assertCount(1, $h);
self::assertTrue($h[0]->hasHeader('x-foo'));
}
public function testCanProvideCallablesThatReturnResponses()
{
$h = [];
$handler = new MockHandler([
function (RequestInterface $request) use (&$h) {
$h[] = $request;
return new Response();
}
]);
$c = new Client(['handler' => $handler]);
$optHistory = [];
$fn = function (array $opts) use (&$optHistory, $c) {
$optHistory = $opts;
return $c->request('GET', 'http://example.com', $opts);
};
$opts = ['options' => ['headers' => ['x-foo' => 'bar']]];
$p = new Pool($c, [$fn], $opts);
$p->promise()->wait();
self::assertCount(1, $h);
self::assertTrue($h[0]->hasHeader('x-foo'));
}
public function testBatchesResults()
{
$requests = [
new Request('GET', 'http://foo.com/200'),
new Request('GET', 'http://foo.com/201'),
new Request('GET', 'http://foo.com/202'),
new Request('GET', 'http://foo.com/404'),
];
$fn = function (RequestInterface $request) {
return new Response(substr($request->getUri()->getPath(), 1));
};
$mock = new MockHandler([$fn, $fn, $fn, $fn]);
$handler = HandlerStack::create($mock);
$client = new Client(['handler' => $handler]);
$results = Pool::batch($client, $requests);
self::assertCount(4, $results);
self::assertSame([0, 1, 2, 3], array_keys($results));
self::assertSame(200, $results[0]->getStatusCode());
self::assertSame(201, $results[1]->getStatusCode());
self::assertSame(202, $results[2]->getStatusCode());
self::assertInstanceOf(ClientException::class, $results[3]);
}
public function testBatchesResultsWithCallbacks()
{
$requests = [
new Request('GET', 'http://foo.com/200'),
new Request('GET', 'http://foo.com/201')
];
$mock = new MockHandler([
function (RequestInterface $request) {
return new Response(substr($request->getUri()->getPath(), 1));
}
]);
$client = new Client(['handler' => $mock]);
$results = Pool::batch($client, $requests, [
'fulfilled' => function ($value) use (&$called) {
$called = true;
}
]);
self::assertCount(2, $results);
self::assertTrue($called);
}
public function testUsesYieldedKeyInFulfilledCallback()
{
$r1 = new Promise(function () use (&$r1) {
$r1->resolve(new Response());
});
$r2 = new Promise(function () use (&$r2) {
$r2->resolve(new Response());
});
$r3 = new Promise(function () use (&$r3) {
$r3->resolve(new Response());
});
$handler = new MockHandler([$r1, $r2, $r3]);
$c = new Client(['handler' => $handler]);
$keys = [];
$requests = [
'request_1' => new Request('GET', 'http://example.com'),
'request_2' => new Request('GET', 'http://example.com'),
'request_3' => new Request('GET', 'http://example.com'),
];
$p = new Pool($c, $requests, [
'pool_size' => 2,
'fulfilled' => function ($res, $index) use (&$keys) {
$keys[] = $index;
}
]);
$p->promise()->wait();
self::assertCount(3, $keys);
self::assertSame($keys, array_keys($requests));
}
private function getClient($total = 1)
{
$queue = [];
for ($i = 0; $i < $total; $i++) {
$queue[] = new Response();
}
$handler = new MockHandler($queue);
return new Client(['handler' => $handler]);
}
}

View File

@ -0,0 +1,155 @@
<?php
namespace GuzzleHttp\Tests;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use GuzzleHttp\Promise\PromiseInterface;
use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\FnStream;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\RequestInterface;
class PrepareBodyMiddlewareTest extends TestCase
{
public function methodProvider()
{
$methods = ['GET', 'PUT', 'POST'];
$bodies = ['Test', ''];
foreach ($methods as $method) {
foreach ($bodies as $body) {
yield [$method, $body];
}
}
}
/**
* @dataProvider methodProvider
*/
public function testAddsContentLengthWhenMissingAndPossible($method, $body)
{
$h = new MockHandler([
function (RequestInterface $request) use ($body) {
$length = strlen($body);
if ($length > 0) {
self::assertEquals($length, $request->getHeaderLine('Content-Length'));
} else {
self::assertFalse($request->hasHeader('Content-Length'));
}
return new Response(200);
}
]);
$m = Middleware::prepareBody();
$stack = new HandlerStack($h);
$stack->push($m);
$comp = $stack->resolve();
$p = $comp(new Request($method, 'http://www.google.com', [], $body), []);
self::assertInstanceOf(PromiseInterface::class, $p);
$response = $p->wait();
self::assertSame(200, $response->getStatusCode());
}
public function testAddsTransferEncodingWhenNoContentLength()
{
$body = FnStream::decorate(Psr7\stream_for('foo'), [
'getSize' => function () {
return null;
}
]);
$h = new MockHandler([
function (RequestInterface $request) {
self::assertFalse($request->hasHeader('Content-Length'));
self::assertSame('chunked', $request->getHeaderLine('Transfer-Encoding'));
return new Response(200);
}
]);
$m = Middleware::prepareBody();
$stack = new HandlerStack($h);
$stack->push($m);
$comp = $stack->resolve();
$p = $comp(new Request('PUT', 'http://www.google.com', [], $body), []);
self::assertInstanceOf(PromiseInterface::class, $p);
$response = $p->wait();
self::assertSame(200, $response->getStatusCode());
}
public function testAddsContentTypeWhenMissingAndPossible()
{
$bd = Psr7\stream_for(fopen(__DIR__ . '/../composer.json', 'r'));
$h = new MockHandler([
function (RequestInterface $request) {
self::assertSame('application/json', $request->getHeaderLine('Content-Type'));
self::assertTrue($request->hasHeader('Content-Length'));
return new Response(200);
}
]);
$m = Middleware::prepareBody();
$stack = new HandlerStack($h);
$stack->push($m);
$comp = $stack->resolve();
$p = $comp(new Request('PUT', 'http://www.google.com', [], $bd), []);
self::assertInstanceOf(PromiseInterface::class, $p);
$response = $p->wait();
self::assertSame(200, $response->getStatusCode());
}
public function expectProvider()
{
return [
[true, ['100-Continue']],
[false, []],
[10, ['100-Continue']],
[500000, []]
];
}
/**
* @dataProvider expectProvider
*/
public function testAddsExpect($value, $result)
{
$bd = Psr7\stream_for(fopen(__DIR__ . '/../composer.json', 'r'));
$h = new MockHandler([
function (RequestInterface $request) use ($result) {
self::assertSame($result, $request->getHeader('Expect'));
return new Response(200);
}
]);
$m = Middleware::prepareBody();
$stack = new HandlerStack($h);
$stack->push($m);
$comp = $stack->resolve();
$p = $comp(new Request('PUT', 'http://www.google.com', [], $bd), [
'expect' => $value
]);
self::assertInstanceOf(PromiseInterface::class, $p);
$response = $p->wait();
self::assertSame(200, $response->getStatusCode());
}
public function testIgnoresIfExpectIsPresent()
{
$bd = Psr7\stream_for(fopen(__DIR__ . '/../composer.json', 'r'));
$h = new MockHandler([
function (RequestInterface $request) {
self::assertSame(['Foo'], $request->getHeader('Expect'));
return new Response(200);
}
]);
$m = Middleware::prepareBody();
$stack = new HandlerStack($h);
$stack->push($m);
$comp = $stack->resolve();
$p = $comp(
new Request('PUT', 'http://www.google.com', ['Expect' => 'Foo'], $bd),
['expect' => true]
);
self::assertInstanceOf(PromiseInterface::class, $p);
$response = $p->wait();
self::assertSame(200, $response->getStatusCode());
}
}

View File

@ -0,0 +1,439 @@
<?php
namespace GuzzleHttp\Tests;
use GuzzleHttp\Client;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\RedirectMiddleware;
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\RequestInterface;
/**
* @covers GuzzleHttp\RedirectMiddleware
*/
class RedirectMiddlewareTest extends TestCase
{
public function testIgnoresNonRedirects()
{
$response = new Response(200);
$stack = new HandlerStack(new MockHandler([$response]));
$stack->push(Middleware::redirect());
$handler = $stack->resolve();
$request = new Request('GET', 'http://example.com');
$promise = $handler($request, []);
$response = $promise->wait();
self::assertSame(200, $response->getStatusCode());
}
public function testIgnoresWhenNoLocation()
{
$response = new Response(304);
$stack = new HandlerStack(new MockHandler([$response]));
$stack->push(Middleware::redirect());
$handler = $stack->resolve();
$request = new Request('GET', 'http://example.com');
$promise = $handler($request, []);
$response = $promise->wait();
self::assertSame(304, $response->getStatusCode());
}
public function testRedirectsWithAbsoluteUri()
{
$mock = new MockHandler([
new Response(302, ['Location' => 'http://test.com']),
new Response(200)
]);
$stack = new HandlerStack($mock);
$stack->push(Middleware::redirect());
$handler = $stack->resolve();
$request = new Request('GET', 'http://example.com?a=b');
$promise = $handler($request, [
'allow_redirects' => ['max' => 2]
]);
$response = $promise->wait();
self::assertSame(200, $response->getStatusCode());
self::assertSame('http://test.com', (string)$mock->getLastRequest()->getUri());
}
public function testRedirectsWithRelativeUri()
{
$mock = new MockHandler([
new Response(302, ['Location' => '/foo']),
new Response(200)
]);
$stack = new HandlerStack($mock);
$stack->push(Middleware::redirect());
$handler = $stack->resolve();
$request = new Request('GET', 'http://example.com?a=b');
$promise = $handler($request, [
'allow_redirects' => ['max' => 2]
]);
$response = $promise->wait();
self::assertSame(200, $response->getStatusCode());
self::assertSame('http://example.com/foo', (string)$mock->getLastRequest()->getUri());
}
/**
* @expectedException \GuzzleHttp\Exception\TooManyRedirectsException
* @expectedExceptionMessage Will not follow more than 3 redirects
*/
public function testLimitsToMaxRedirects()
{
$mock = new MockHandler([
new Response(301, ['Location' => 'http://test.com']),
new Response(302, ['Location' => 'http://test.com']),
new Response(303, ['Location' => 'http://test.com']),
new Response(304, ['Location' => 'http://test.com'])
]);
$stack = new HandlerStack($mock);
$stack->push(Middleware::redirect());
$handler = $stack->resolve();
$request = new Request('GET', 'http://example.com');
$promise = $handler($request, ['allow_redirects' => ['max' => 3]]);
$promise->wait();
}
/**
* @expectedException \GuzzleHttp\Exception\BadResponseException
* @expectedExceptionMessage Redirect URI,
*/
public function testEnsuresProtocolIsValid()
{
$mock = new MockHandler([
new Response(301, ['Location' => 'ftp://test.com'])
]);
$stack = new HandlerStack($mock);
$stack->push(Middleware::redirect());
$handler = $stack->resolve();
$request = new Request('GET', 'http://example.com');
$handler($request, ['allow_redirects' => ['max' => 3]])->wait();
}
public function testAddsRefererHeader()
{
$mock = new MockHandler([
new Response(302, ['Location' => 'http://test.com']),
new Response(200)
]);
$stack = new HandlerStack($mock);
$stack->push(Middleware::redirect());
$handler = $stack->resolve();
$request = new Request('GET', 'http://example.com?a=b');
$promise = $handler($request, [
'allow_redirects' => ['max' => 2, 'referer' => true]
]);
$promise->wait();
self::assertSame(
'http://example.com?a=b',
$mock->getLastRequest()->getHeaderLine('Referer')
);
}
public function testAddsRefererHeaderButClearsUserInfo()
{
$mock = new MockHandler([
new Response(302, ['Location' => 'http://test.com']),
new Response(200)
]);
$stack = new HandlerStack($mock);
$stack->push(Middleware::redirect());
$handler = $stack->resolve();
$request = new Request('GET', 'http://foo:bar@example.com?a=b');
$promise = $handler($request, [
'allow_redirects' => ['max' => 2, 'referer' => true]
]);
$promise->wait();
self::assertSame(
'http://example.com?a=b',
$mock->getLastRequest()->getHeaderLine('Referer')
);
}
public function testAddsGuzzleRedirectHeader()
{
$mock = new MockHandler([
new Response(302, ['Location' => 'http://example.com']),
new Response(302, ['Location' => 'http://example.com/foo']),
new Response(302, ['Location' => 'http://example.com/bar']),
new Response(200)
]);
$stack = new HandlerStack($mock);
$stack->push(Middleware::redirect());
$handler = $stack->resolve();
$request = new Request('GET', 'http://example.com?a=b');
$promise = $handler($request, [
'allow_redirects' => ['track_redirects' => true]
]);
$response = $promise->wait(true);
self::assertSame(
[
'http://example.com',
'http://example.com/foo',
'http://example.com/bar',
],
$response->getHeader(RedirectMiddleware::HISTORY_HEADER)
);
}
public function testAddsGuzzleRedirectStatusHeader()
{
$mock = new MockHandler([
new Response(301, ['Location' => 'http://example.com']),
new Response(302, ['Location' => 'http://example.com/foo']),
new Response(301, ['Location' => 'http://example.com/bar']),
new Response(302, ['Location' => 'http://example.com/baz']),
new Response(200)
]);
$stack = new HandlerStack($mock);
$stack->push(Middleware::redirect());
$handler = $stack->resolve();
$request = new Request('GET', 'http://example.com?a=b');
$promise = $handler($request, [
'allow_redirects' => ['track_redirects' => true]
]);
$response = $promise->wait(true);
self::assertSame(
[
'301',
'302',
'301',
'302',
],
$response->getHeader(RedirectMiddleware::STATUS_HISTORY_HEADER)
);
}
public function testDoesNotAddRefererWhenGoingFromHttpsToHttp()
{
$mock = new MockHandler([
new Response(302, ['Location' => 'http://test.com']),
new Response(200)
]);
$stack = new HandlerStack($mock);
$stack->push(Middleware::redirect());
$handler = $stack->resolve();
$request = new Request('GET', 'https://example.com?a=b');
$promise = $handler($request, [
'allow_redirects' => ['max' => 2, 'referer' => true]
]);
$promise->wait();
self::assertFalse($mock->getLastRequest()->hasHeader('Referer'));
}
public function testInvokesOnRedirectForRedirects()
{
$mock = new MockHandler([
new Response(302, ['Location' => 'http://test.com']),
new Response(200)
]);
$stack = new HandlerStack($mock);
$stack->push(Middleware::redirect());
$handler = $stack->resolve();
$request = new Request('GET', 'http://example.com?a=b');
$call = false;
$promise = $handler($request, [
'allow_redirects' => [
'max' => 2,
'on_redirect' => function ($request, $response, $uri) use (&$call) {
self::assertSame(302, $response->getStatusCode());
self::assertSame('GET', $request->getMethod());
self::assertSame('http://test.com', (string) $uri);
$call = true;
}
]
]);
$promise->wait();
self::assertTrue($call);
}
/**
* @testWith ["digest"]
* ["ntlm"]
*/
public function testRemoveCurlAuthorizationOptionsOnRedirectCrossHost($auth)
{
if (!defined('\CURLOPT_HTTPAUTH')) {
self::markTestSkipped('ext-curl is required for this test');
}
$mock = new MockHandler([
new Response(302, ['Location' => 'http://test.com']),
static function (RequestInterface $request, $options) {
self::assertFalse(
isset($options['curl'][\CURLOPT_HTTPAUTH]),
'curl options still contain CURLOPT_HTTPAUTH entry'
);
self::assertFalse(
isset($options['curl'][\CURLOPT_USERPWD]),
'curl options still contain CURLOPT_USERPWD entry'
);
return new Response(200);
}
]);
$handler = HandlerStack::create($mock);
$client = new Client(['handler' => $handler]);
$client->get('http://example.com?a=b', ['auth' => ['testuser', 'testpass', $auth]]);
}
/**
* @testWith ["digest"]
* ["ntlm"]
*/
public function testRemoveCurlAuthorizationOptionsOnRedirectCrossPort($auth)
{
if (!defined('\CURLOPT_HTTPAUTH')) {
self::markTestSkipped('ext-curl is required for this test');
}
$mock = new MockHandler([
new Response(302, ['Location' => 'http://example.com:81/']),
static function (RequestInterface $request, $options) {
self::assertFalse(
isset($options['curl'][\CURLOPT_HTTPAUTH]),
'curl options still contain CURLOPT_HTTPAUTH entry'
);
self::assertFalse(
isset($options['curl'][\CURLOPT_USERPWD]),
'curl options still contain CURLOPT_USERPWD entry'
);
return new Response(200);
}
]);
$handler = HandlerStack::create($mock);
$client = new Client(['handler' => $handler]);
$client->get('http://example.com?a=b', ['auth' => ['testuser', 'testpass', $auth]]);
}
/**
* @testWith ["digest"]
* ["ntlm"]
*/
public function testRemoveCurlAuthorizationOptionsOnRedirectCrossScheme($auth)
{
if (!defined('\CURLOPT_HTTPAUTH')) {
self::markTestSkipped('ext-curl is required for this test');
}
$mock = new MockHandler([
new Response(302, ['Location' => 'http://example.com?a=b']),
static function (RequestInterface $request, $options) {
self::assertFalse(
isset($options['curl'][\CURLOPT_HTTPAUTH]),
'curl options still contain CURLOPT_HTTPAUTH entry'
);
self::assertFalse(
isset($options['curl'][\CURLOPT_USERPWD]),
'curl options still contain CURLOPT_USERPWD entry'
);
return new Response(200);
}
]);
$handler = HandlerStack::create($mock);
$client = new Client(['handler' => $handler]);
$client->get('https://example.com?a=b', ['auth' => ['testuser', 'testpass', $auth]]);
}
/**
* @testWith ["digest"]
* ["ntlm"]
*/
public function testRemoveCurlAuthorizationOptionsOnRedirectCrossSchemeSamePort($auth)
{
if (!defined('\CURLOPT_HTTPAUTH')) {
self::markTestSkipped('ext-curl is required for this test');
}
$mock = new MockHandler([
new Response(302, ['Location' => 'http://example.com:80?a=b']),
static function (RequestInterface $request, $options) {
self::assertFalse(
isset($options['curl'][\CURLOPT_HTTPAUTH]),
'curl options still contain CURLOPT_HTTPAUTH entry'
);
self::assertFalse(
isset($options['curl'][\CURLOPT_USERPWD]),
'curl options still contain CURLOPT_USERPWD entry'
);
return new Response(200);
}
]);
$handler = HandlerStack::create($mock);
$client = new Client(['handler' => $handler]);
$client->get('https://example.com?a=b', ['auth' => ['testuser', 'testpass', $auth]]);
}
/**
* @testWith ["digest"]
* ["ntlm"]
*/
public function testNotRemoveCurlAuthorizationOptionsOnRedirect($auth)
{
if (!defined('\CURLOPT_HTTPAUTH') || !defined('\CURLOPT_USERPWD')) {
self::markTestSkipped('ext-curl is required for this test');
}
$mock = new MockHandler([
new Response(302, ['Location' => 'http://example.com/2']),
static function (RequestInterface $request, $options) {
self::assertTrue(
isset($options['curl'][\CURLOPT_HTTPAUTH]),
'curl options does not contain expected CURLOPT_HTTPAUTH entry'
);
self::assertTrue(
isset($options['curl'][\CURLOPT_USERPWD]),
'curl options does not contain expected CURLOPT_USERPWD entry'
);
return new Response(200);
}
]);
$handler = HandlerStack::create($mock);
$client = new Client(['handler' => $handler]);
$client->get('http://example.com?a=b', ['auth' => ['testuser', 'testpass', $auth]]);
}
public function crossOriginRedirectProvider()
{
return [
['http://example.com/123', 'http://example.com/', false],
['http://example.com/123', 'http://example.com:80/', false],
['http://example.com:80/123', 'http://example.com/', false],
['http://example.com:80/123', 'http://example.com:80/', false],
['http://example.com/123', 'https://example.com/', true],
['http://example.com/123', 'http://www.example.com/', true],
['http://example.com/123', 'http://example.com:81/', true],
['http://example.com:80/123', 'http://example.com:81/', true],
['https://example.com/123', 'https://example.com/', false],
['https://example.com/123', 'https://example.com:443/', false],
['https://example.com:443/123', 'https://example.com/', false],
['https://example.com:443/123', 'https://example.com:443/', false],
['https://example.com/123', 'http://example.com/', true],
['https://example.com/123', 'https://www.example.com/', true],
['https://example.com/123', 'https://example.com:444/', true],
['https://example.com:443/123', 'https://example.com:444/', true],
];
}
/**
* @dataProvider crossOriginRedirectProvider
*/
public function testHeadersTreatmentOnRedirect($originalUri, $targetUri, $isCrossOrigin)
{
$mock = new MockHandler([
new Response(302, ['Location' => $targetUri]),
function (RequestInterface $request) use ($isCrossOrigin) {
self::assertSame(!$isCrossOrigin, $request->hasHeader('Authorization'));
self::assertSame(!$isCrossOrigin, $request->hasHeader('Cookie'));
return new Response(200);
}
]);
$handler = HandlerStack::create($mock);
$client = new Client(['handler' => $handler]);
$client->get($originalUri, ['auth' => ['testuser', 'testpass'], 'headers' => ['Cookie' => 'foo=bar']]);
}
}

View File

@ -0,0 +1,81 @@
<?php
namespace GuzzleHttp\Tests;
use GuzzleHttp\Client;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\Middleware;
use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\RetryMiddleware;
use PHPUnit\Framework\TestCase;
class RetryMiddlewareTest extends TestCase
{
public function testRetriesWhenDeciderReturnsTrue()
{
$delayCalls = 0;
$calls = [];
$decider = function ($retries, $request, $response, $error) use (&$calls) {
$calls[] = func_get_args();
return count($calls) < 3;
};
$delay = function ($retries, $response) use (&$delayCalls) {
$delayCalls++;
self::assertSame($retries, $delayCalls);
self::assertInstanceOf(Response::class, $response);
return 1;
};
$m = Middleware::retry($decider, $delay);
$h = new MockHandler([new Response(200), new Response(201), new Response(202)]);
$f = $m($h);
$c = new Client(['handler' => $f]);
$p = $c->sendAsync(new Request('GET', 'http://test.com'), []);
$p->wait();
self::assertCount(3, $calls);
self::assertSame(2, $delayCalls);
self::assertSame(202, $p->wait()->getStatusCode());
}
public function testDoesNotRetryWhenDeciderReturnsFalse()
{
$decider = function () {
return false;
};
$m = Middleware::retry($decider);
$h = new MockHandler([new Response(200)]);
$c = new Client(['handler' => $m($h)]);
$p = $c->sendAsync(new Request('GET', 'http://test.com'), []);
self::assertSame(200, $p->wait()->getStatusCode());
}
public function testCanRetryExceptions()
{
$calls = [];
$decider = function ($retries, $request, $response, $error) use (&$calls) {
$calls[] = func_get_args();
return $error instanceof \Exception;
};
$m = Middleware::retry($decider);
$h = new MockHandler([new \Exception(), new Response(201)]);
$c = new Client(['handler' => $m($h)]);
$p = $c->sendAsync(new Request('GET', 'http://test.com'), []);
self::assertSame(201, $p->wait()->getStatusCode());
self::assertCount(2, $calls);
self::assertSame(0, $calls[0][0]);
self::assertNull($calls[0][2]);
self::assertInstanceOf('Exception', $calls[0][3]);
self::assertSame(1, $calls[1][0]);
self::assertInstanceOf(Response::class, $calls[1][2]);
self::assertNull($calls[1][3]);
}
public function testBackoffCalculateDelay()
{
self::assertSame(0, RetryMiddleware::exponentialDelay(0));
self::assertSame(1000, RetryMiddleware::exponentialDelay(1));
self::assertSame(2000, RetryMiddleware::exponentialDelay(2));
self::assertSame(4000, RetryMiddleware::exponentialDelay(3));
self::assertSame(8000, RetryMiddleware::exponentialDelay(4));
}
}

View File

@ -0,0 +1,174 @@
<?php
namespace GuzzleHttp\Tests;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7;
use Psr\Http\Message\ResponseInterface;
/**
* 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
{
/** @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()
{
return self::getClient()->request('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.
*
* @param array|ResponseInterface $responses A single or array of Responses
* to queue.
* @throws \Exception
*/
public static function enqueue($responses)
{
$data = [];
foreach ((array) $responses as $response) {
if (!($response instanceof ResponseInterface)) {
throw new \Exception('Invalid response given.');
}
$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())
];
}
self::getClient()->request('PUT', 'guzzle-server/responses', [
'json' => $data
]);
}
/**
* Get all of the received requests
*
* @return ResponseInterface[]
* @throws \RuntimeException
*/
public static function received()
{
if (!self::$started) {
return [];
}
$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'];
}
$response = new Psr7\Request(
$message['http_method'],
$uri,
$message['headers'],
$message['body'],
$message['version']
);
return $response->withUri(
$response->getUri()
->withScheme('http')
->withHost($response->getHeaderLine('host'))
);
},
$data
);
}
/**
* Stop running the node.js server
*/
public static function stop()
{
if (self::$started) {
self::getClient()->request('DELETE', 'guzzle-server');
}
self::$started = false;
}
public static function wait($maxTries = 5)
{
$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()
{
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
]);
return true;
} catch (\Exception $e) {
return false;
}
}
private static function getClient()
{
if (!self::$client) {
self::$client = new Client([
'base_uri' => self::$url,
'sync' => true,
]);
}
return self::$client;
}
}

View File

@ -0,0 +1,30 @@
<?php
namespace GuzzleHttp\Tests;
use GuzzleHttp\Psr7;
use GuzzleHttp\TransferStats;
use PHPUnit\Framework\TestCase;
class TransferStatsTest extends TestCase
{
public function testHasData()
{
$request = new Psr7\Request('GET', 'http://foo.com');
$response = new Psr7\Response();
$stats = new TransferStats(
$request,
$response,
10.5,
null,
['foo' => 'bar']
);
self::assertSame($request, $stats->getRequest());
self::assertSame($response, $stats->getResponse());
self::assertTrue($stats->hasResponse());
self::assertSame(['foo' => 'bar'], $stats->getHandlerStats());
self::assertSame('bar', $stats->getHandlerStat('foo'));
self::assertSame($request->getUri(), $stats->getEffectiveUri());
self::assertEquals(10.5, $stats->getTransferTime());
self::assertNull($stats->getHandlerErrorData());
}
}

View File

@ -0,0 +1,202 @@
<?php
namespace GuzzleHttp\Tests;
use GuzzleHttp\UriTemplate;
use PHPUnit\Framework\TestCase;
/**
* @covers GuzzleHttp\UriTemplate
*/
class UriTemplateTest extends TestCase
{
/**
* @return array
*/
public function templateProvider()
{
$params = [
'var' => 'value',
'hello' => 'Hello World!',
'empty' => '',
'path' => '/foo/bar',
'x' => '1024',
'y' => '768',
'null' => null,
'list' => ['red', 'green', 'blue'],
'keys' => [
"semi" => ';',
"dot" => '.',
"comma" => ','
],
'empty_keys' => [],
];
return array_map(function ($t) use ($params) {
$t[] = $params;
return $t;
}, [
['foo', 'foo'],
['{var}', 'value'],
['{hello}', 'Hello%20World%21'],
['{+var}', 'value'],
['{+hello}', 'Hello%20World!'],
['{+path}/here', '/foo/bar/here'],
['here?ref={+path}', 'here?ref=/foo/bar'],
['X{#var}', 'X#value'],
['X{#hello}', 'X#Hello%20World!'],
['map?{x,y}', 'map?1024,768'],
['{x,hello,y}', '1024,Hello%20World%21,768'],
['{+x,hello,y}', '1024,Hello%20World!,768'],
['{+path,x}/here', '/foo/bar,1024/here'],
['{#x,hello,y}', '#1024,Hello%20World!,768'],
['{#path,x}/here', '#/foo/bar,1024/here'],
['X{.var}', 'X.value'],
['X{.x,y}', 'X.1024.768'],
['{/var}', '/value'],
['{/var,x}/here', '/value/1024/here'],
['{;x,y}', ';x=1024;y=768'],
['{;x,y,empty}', ';x=1024;y=768;empty'],
['{?x,y}', '?x=1024&y=768'],
['{?x,y,empty}', '?x=1024&y=768&empty='],
['?fixed=yes{&x}', '?fixed=yes&x=1024'],
['{&x,y,empty}', '&x=1024&y=768&empty='],
['{var:3}', 'val'],
['{var:30}', 'value'],
['{list}', 'red,green,blue'],
['{list*}', 'red,green,blue'],
['{keys}', 'semi,%3B,dot,.,comma,%2C'],
['{keys*}', 'semi=%3B,dot=.,comma=%2C'],
['{+path:6}/here', '/foo/b/here'],
['{+list}', 'red,green,blue'],
['{+list*}', 'red,green,blue'],
['{+keys}', 'semi,;,dot,.,comma,,'],
['{+keys*}', 'semi=;,dot=.,comma=,'],
['{#path:6}/here', '#/foo/b/here'],
['{#list}', '#red,green,blue'],
['{#list*}', '#red,green,blue'],
['{#keys}', '#semi,;,dot,.,comma,,'],
['{#keys*}', '#semi=;,dot=.,comma=,'],
['X{.var:3}', 'X.val'],
['X{.list}', 'X.red,green,blue'],
['X{.list*}', 'X.red.green.blue'],
['X{.keys}', 'X.semi,%3B,dot,.,comma,%2C'],
['X{.keys*}', 'X.semi=%3B.dot=..comma=%2C'],
['{/var:1,var}', '/v/value'],
['{/list}', '/red,green,blue'],
['{/list*}', '/red/green/blue'],
['{/list*,path:4}', '/red/green/blue/%2Ffoo'],
['{/keys}', '/semi,%3B,dot,.,comma,%2C'],
['{/keys*}', '/semi=%3B/dot=./comma=%2C'],
['{;hello:5}', ';hello=Hello'],
['{;list}', ';list=red,green,blue'],
['{;list*}', ';list=red;list=green;list=blue'],
['{;keys}', ';keys=semi,%3B,dot,.,comma,%2C'],
['{;keys*}', ';semi=%3B;dot=.;comma=%2C'],
['{?var:3}', '?var=val'],
['{?list}', '?list=red,green,blue'],
['{?list*}', '?list=red&list=green&list=blue'],
['{?keys}', '?keys=semi,%3B,dot,.,comma,%2C'],
['{?keys*}', '?semi=%3B&dot=.&comma=%2C'],
['{&var:3}', '&var=val'],
['{&list}', '&list=red,green,blue'],
['{&list*}', '&list=red&list=green&list=blue'],
['{&keys}', '&keys=semi,%3B,dot,.,comma,%2C'],
['{&keys*}', '&semi=%3B&dot=.&comma=%2C'],
['{.null}', ''],
['{.null,var}', '.value'],
['X{.empty_keys*}', 'X'],
['X{.empty_keys}', 'X'],
// Test that missing expansions are skipped
['test{&missing*}', 'test'],
// Test that multiple expansions can be set
['http://{var}/{var:2}{?keys*}', 'http://value/va?semi=%3B&dot=.&comma=%2C'],
// Test more complex query string stuff
['http://www.test.com{+path}{?var,keys*}', 'http://www.test.com/foo/bar?var=value&semi=%3B&dot=.&comma=%2C']
]);
}
/**
* @dataProvider templateProvider
*/
public function testExpandsUriTemplates($template, $expansion, $params)
{
$uri = new UriTemplate();
self::assertSame($expansion, $uri->expand($template, $params));
}
public function expressionProvider()
{
return [
[
'{+var*}', [
'operator' => '+',
'values' => [
['modifier' => '*', 'value' => 'var']
]
],
],
[
'{?keys,var,val}', [
'operator' => '?',
'values' => [
['value' => 'keys', 'modifier' => ''],
['value' => 'var', 'modifier' => ''],
['value' => 'val', 'modifier' => '']
]
],
],
[
'{+x,hello,y}', [
'operator' => '+',
'values' => [
['value' => 'x', 'modifier' => ''],
['value' => 'hello', 'modifier' => ''],
['value' => 'y', 'modifier' => '']
]
]
]
];
}
/**
* @dataProvider expressionProvider
*/
public function testParsesExpressions($exp, $data)
{
$template = new UriTemplate();
// Access the config object
$class = new \ReflectionClass($template);
$method = $class->getMethod('parseExpression');
$method->setAccessible(true);
$exp = substr($exp, 1, -1);
self::assertSame($data, $method->invokeArgs($template, [$exp]));
}
/**
* @ticket https://github.com/guzzle/guzzle/issues/90
*/
public function testAllowsNestedArrayExpansion()
{
$template = new UriTemplate();
$result = $template->expand('http://example.com{+path}{/segments}{?query,data*,foo*}', [
'path' => '/foo/bar',
'segments' => ['one', 'two'],
'query' => 'test',
'data' => [
'more' => ['fun', 'ice cream']
],
'foo' => [
'baz' => [
'bar' => 'fizz',
'test' => 'buzz'
],
'bam' => 'boo'
]
]);
self::assertSame('http://example.com/foo/bar/one,two?query=test&more%5B0%5D=fun&more%5B1%5D=ice%20cream&baz%5Bbar%5D=fizz&baz%5Btest%5D=buzz&bam=boo', $result);
}
}

View File

@ -0,0 +1,39 @@
<?php
namespace {
setlocale(LC_ALL, 'C');
}
namespace GuzzleHttp\Test {
require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/Server.php';
use GuzzleHttp\Tests\Server;
Server::start();
register_shutdown_function(function () {
Server::stop();
});
}
// Override curl_setopt_array() and curl_multi_setopt() to get the last set curl options
namespace GuzzleHttp\Handler {
function curl_setopt_array($handle, array $options)
{
if (!empty($_SERVER['curl_test'])) {
$_SERVER['_curl'] = $options;
} else {
unset($_SERVER['_curl']);
}
return \curl_setopt_array($handle, $options);
}
function curl_multi_setopt($handle, $option, $value)
{
if (!empty($_SERVER['curl_test'])) {
$_SERVER['_curl_multi'][$option] = $value;
} else {
unset($_SERVER['_curl_multi']);
}
return \curl_multi_setopt($handle, $option, $value);
}
}

View File

@ -0,0 +1,139 @@
<?php
namespace GuzzleHttp\Test;
use GuzzleHttp;
use PHPUnit\Framework\TestCase;
class FunctionsTest extends TestCase
{
public function testExpandsTemplate()
{
self::assertSame(
'foo/123',
GuzzleHttp\uri_template('foo/{bar}', ['bar' => '123'])
);
}
public function noBodyProvider()
{
return [['get'], ['head'], ['delete']];
}
public function testProvidesDefaultUserAgent()
{
$ua = GuzzleHttp\default_user_agent();
self::assertRegExp('#^GuzzleHttp/.+ curl/.+ PHP/.+$#', $ua);
}
public function typeProvider()
{
return [
['foo', 'string(3) "foo"'],
[true, 'bool(true)'],
[false, 'bool(false)'],
[10, 'int(10)'],
[1.0, 'float(1)'],
[new StrClass(), 'object(GuzzleHttp\Test\StrClass)'],
[['foo'], 'array(1)']
];
}
/**
* @dataProvider typeProvider
*/
public function testDescribesType($input, $output)
{
self::assertSame($output, GuzzleHttp\describe_type($input));
}
public function testParsesHeadersFromLines()
{
$lines = ['Foo: bar', 'Foo: baz', 'Abc: 123', 'Def: a, b'];
self::assertSame([
'Foo' => ['bar', 'baz'],
'Abc' => ['123'],
'Def' => ['a, b'],
], GuzzleHttp\headers_from_lines($lines));
}
public function testParsesHeadersFromLinesWithMultipleLines()
{
$lines = ['Foo: bar', 'Foo: baz', 'Foo: 123'];
self::assertSame([
'Foo' => ['bar', 'baz', '123'],
], GuzzleHttp\headers_from_lines($lines));
}
public function testReturnsDebugResource()
{
self::assertInternalType('resource', GuzzleHttp\debug_resource());
}
public function testProvidesDefaultCaBundler()
{
self::assertFileExists(GuzzleHttp\default_ca_bundle());
}
public function noProxyProvider()
{
return [
['mit.edu', ['.mit.edu'], false],
['foo.mit.edu', ['.mit.edu'], true],
['mit.edu', ['mit.edu'], true],
['mit.edu', ['baz', 'mit.edu'], true],
['mit.edu', ['', '', 'mit.edu'], true],
['mit.edu', ['baz', '*'], true],
];
}
/**
* @dataProvider noproxyProvider
*/
public function testChecksNoProxyList($host, $list, $result)
{
self::assertSame(
$result,
\GuzzleHttp\is_host_in_noproxy($host, $list)
);
}
/**
* @expectedException \InvalidArgumentException
*/
public function testEnsuresNoProxyCheckHostIsSet()
{
\GuzzleHttp\is_host_in_noproxy('', []);
}
public function testEncodesJson()
{
self::assertSame('true', \GuzzleHttp\json_encode(true));
}
/**
* @expectedException \InvalidArgumentException
*/
public function testEncodesJsonAndThrowsOnError()
{
\GuzzleHttp\json_encode("\x99");
}
public function testDecodesJson()
{
self::assertTrue(\GuzzleHttp\json_decode('true'));
}
/**
* @expectedException \InvalidArgumentException
*/
public function testDecodesJsonAndThrowsOnError()
{
\GuzzleHttp\json_decode('{{]]');
}
}
final class StrClass
{
public function __toString()
{
return 'foo';
}
}

View File

@ -0,0 +1,250 @@
/**
* Guzzle node.js test server to return queued responses to HTTP requests and
* expose a RESTful API for enqueueing responses and retrieving the requests
* that have been received.
*
* - Delete all requests that have been received:
* > DELETE /guzzle-server/requests
* > Host: 127.0.0.1:8126
*
* - Enqueue responses
* > PUT /guzzle-server/responses
* > Host: 127.0.0.1:8126
* >
* > [{'status': 200, 'reason': 'OK', 'headers': {}, 'body': '' }]
*
* - Get the received requests
* > GET /guzzle-server/requests
* > Host: 127.0.0.1:8126
*
* < HTTP/1.1 200 OK
* <
* < [{'http_method': 'GET', 'uri': '/', 'headers': {}, 'body': 'string'}]
*
* - Attempt access to the secure area
* > GET /secure/by-digest/qop-auth/guzzle-server/requests
* > Host: 127.0.0.1:8126
*
* < HTTP/1.1 401 Unauthorized
* < WWW-Authenticate: Digest realm="Digest Test", qop="auth", nonce="0796e98e1aeef43141fab2a66bf4521a", algorithm="MD5", stale="false"
* <
* < 401 Unauthorized
*
* - Shutdown the server
* > DELETE /guzzle-server
* > Host: 127.0.0.1:8126
*
* @package Guzzle PHP <http://www.guzzlephp.org>
* @license See the LICENSE file that was distributed with this source code.
*/
var http = require('http');
var url = require('url');
/**
* Guzzle node.js server
* @class
*/
var GuzzleServer = function(port, log) {
this.port = port;
this.log = log;
this.responses = [];
this.requests = [];
var that = this;
var md5 = function(input) {
var crypto = require('crypto');
var hasher = crypto.createHash('md5');
hasher.update(input);
return hasher.digest('hex');
};
/**
* Node.js HTTP server authentication module.
*
* It is only initialized on demand (by loadAuthentifier). This avoids
* requiring the dependency to http-auth on standard operations, and the
* performance hit at startup.
*/
var auth;
/**
* Provides authentication handlers (Basic, Digest).
*/
var loadAuthentifier = function(type, options) {
var typeId = type;
if (type == 'digest') {
typeId += '.'+(options && options.qop ? options.qop : 'none');
}
if (!loadAuthentifier[typeId]) {
if (!auth) {
try {
auth = require('http-auth');
} catch (e) {
if (e.code == 'MODULE_NOT_FOUND') {
return;
}
}
}
switch (type) {
case 'digest':
var digestParams = {
realm: 'Digest Test',
login: 'me',
password: 'test'
};
if (options && options.qop) {
digestParams.qop = options.qop;
}
loadAuthentifier[typeId] = auth.digest(digestParams, function(username, callback) {
callback(md5(digestParams.login + ':' + digestParams.realm + ':' + digestParams.password));
});
break
}
}
return loadAuthentifier[typeId];
};
var firewallRequest = function(request, req, res, requestHandlerCallback) {
var securedAreaUriParts = request.uri.match(/^\/secure\/by-(digest)(\/qop-([^\/]*))?(\/.*)$/);
if (securedAreaUriParts) {
var authentifier = loadAuthentifier(securedAreaUriParts[1], { qop: securedAreaUriParts[2] });
if (!authentifier) {
res.writeHead(501, 'HTTP authentication not implemented', { 'Content-Length': 0 });
res.end();
return;
}
authentifier.check(req, res, function(req, res) {
req.url = securedAreaUriParts[4];
requestHandlerCallback(request, req, res);
});
} else {
requestHandlerCallback(request, req, res);
}
};
var controlRequest = function(request, req, res) {
if (req.url == '/guzzle-server/perf') {
res.writeHead(200, 'OK', {'Content-Length': 16});
res.end('Body of response');
} else if (req.method == 'DELETE') {
if (req.url == '/guzzle-server/requests') {
// Clear the received requests
that.requests = [];
res.writeHead(200, 'OK', { 'Content-Length': 0 });
res.end();
if (that.log) {
console.log('Flushing requests');
}
} else if (req.url == '/guzzle-server') {
// Shutdown the server
res.writeHead(200, 'OK', { 'Content-Length': 0, 'Connection': 'close' });
res.end();
if (that.log) {
console.log('Shutting down');
}
that.server.close();
}
} else if (req.method == 'GET') {
if (req.url === '/guzzle-server/requests') {
if (that.log) {
console.log('Sending received requests');
}
// Get received requests
var body = JSON.stringify(that.requests);
res.writeHead(200, 'OK', { 'Content-Length': body.length });
res.end(body);
} else if (req.url == '/guzzle-server/read-timeout') {
if (that.log) {
console.log('Sleeping');
}
res.writeHead(200, 'OK');
res.write("sleeping 60 seconds ...\n");
setTimeout(function () {
res.end("slept 60 seconds\n");
}, 60*1000);
}
} else if (req.method == 'PUT' && req.url == '/guzzle-server/responses') {
if (that.log) {
console.log('Adding responses...');
}
if (!request.body) {
if (that.log) {
console.log('No response data was provided');
}
res.writeHead(400, 'NO RESPONSES IN REQUEST', { 'Content-Length': 0 });
} else {
that.responses = JSON.parse(request.body);
for (var i = 0; i < that.responses.length; i++) {
if (that.responses[i].body) {
that.responses[i].body = Buffer.from(that.responses[i].body, 'base64');
}
}
if (that.log) {
console.log(that.responses);
}
res.writeHead(200, 'OK', { 'Content-Length': 0 });
}
res.end();
}
};
var receivedRequest = function(request, req, res) {
if (req.url.indexOf('/guzzle-server') === 0) {
controlRequest(request, req, res);
} else if (req.url.indexOf('/guzzle-server') == -1 && !that.responses.length) {
res.writeHead(500);
res.end('No responses in queue');
} else {
if (that.log) {
console.log('Returning response from queue and adding request');
}
that.requests.push(request);
var response = that.responses.shift();
res.writeHead(response.status, response.reason, response.headers);
res.end(response.body);
}
};
this.start = function() {
that.server = http.createServer(function(req, res) {
var parts = url.parse(req.url, false);
var request = {
http_method: req.method,
scheme: parts.scheme,
uri: parts.pathname,
query_string: parts.query,
headers: req.headers,
version: req.httpVersion,
body: ''
};
// Receive each chunk of the request body
req.addListener('data', function(chunk) {
request.body += chunk;
});
// Called when the request completes
req.addListener('end', function() {
firewallRequest(request, req, res, receivedRequest);
});
});
that.server.listen(this.port, '127.0.0.1');
if (this.log) {
console.log('Server running at http://127.0.0.1:8126/');
}
};
};
// Get the port from the arguments
port = process.argv.length >= 3 ? process.argv[2] : 8126;
log = process.argv.length >= 4 ? process.argv[3] : false;
// Start the server
server = new GuzzleServer(port, log);
server.start();

View File

@ -1,5 +1,11 @@
# CHANGELOG
## 1.5.3 - 2023-05-21
### Changed
- Removed remaining usage of deprecated functions
## 1.5.2 - 2022-08-07
### Changed

View File

@ -46,11 +46,6 @@
"test": "vendor/bin/simple-phpunit",
"test-ci": "vendor/bin/simple-phpunit --coverage-text"
},
"extra": {
"branch-alias": {
"dev-master": "1.5-dev"
}
},
"config": {
"preferred-install": "dist",
"sort-packages": true

View File

@ -78,7 +78,7 @@ final class Each
$concurrency,
callable $onFulfilled = null
) {
return each_limit(
return self::ofLimit(
$iterable,
$concurrency,
$onFulfilled,

View File

@ -107,7 +107,7 @@ final class Utils
{
$results = [];
foreach ($promises as $key => $promise) {
$results[$key] = inspect($promise);
$results[$key] = self::inspect($promise);
}
return $results;

View File

@ -0,0 +1,9 @@
root = true
[*]
charset = utf-8
end_of_line = lf
indent_size = 4
indent_style = space
insert_final_newline = true
trim_trailing_whitespace = true

View File

@ -0,0 +1,7 @@
/tests export-ignore
.editorconfig export-ignore
.gitattributes export-ignore
.gitignore export-ignore
.travis.yml export-ignore
Makefile export-ignore
phpunit.xml.dist export-ignore

View File

@ -0,0 +1,2 @@
[*.yml]
indent_size = 2

View File

@ -0,0 +1,26 @@
language: php
matrix:
include:
- php: hhvm-3.24
dist: trusty
- php: 5.4
dist: trusty
env: COMPOSER_FLAGS="--prefer-stable --prefer-lowest"
- php: 5.4
dist: trusty
- php: 5.5.9
dist: trusty
env: COMPOSER_FLAGS="--prefer-stable --prefer-lowest"
fast_finish: true
before_install:
- if [[ "$TRAVIS_PHP_VERSION" != "hhvm-3.24" ]]; then echo "xdebug.overload_var_dump = 1" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php.ini; fi
- if [[ "$TRAVIS_PHP_VERSION" == "hhvm-3.24" ]]; then travis_retry composer require "phpunit/phpunit:^5.7.27" --dev --no-update -n; fi
install:
- if [[ "$TRAVIS_PHP_VERSION" != "nightly" ]]; then travis_retry composer update; fi
- if [[ "$TRAVIS_PHP_VERSION" == "nightly" ]]; then travis_retry composer update --ignore-platform-reqs; fi
script:
- make test

View File

@ -0,0 +1,29 @@
all: clean test
test:
vendor/bin/phpunit $(TEST)
coverage:
vendor/bin/phpunit --coverage-html=artifacts/coverage $(TEST)
view-coverage:
open artifacts/coverage/index.html
check-tag:
$(if $(TAG),,$(error TAG is not defined. Pass via "make tag TAG=4.2.1"))
tag: check-tag
@echo Tagging $(TAG)
chag update $(TAG)
git commit -a -m '$(TAG) release'
chag tag
@echo "Release has been created. Push using 'make release'"
@echo "Changes made in the release commit"
git diff HEAD~1 HEAD
release: check-tag
git push origin master
git push origin $(TAG)
clean:
rm -rf artifacts/*

View File

@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit
backupGlobals="true"
colors="true"
beStrictAboutOutputDuringTests="true"
beStrictAboutTestsThatDoNotTestAnything="true"
bootstrap="vendor/autoload.php"
>
<testsuites>
<testsuite name="GuzzleHttp PSR7 Test Suite">
<directory>tests/</directory>
<exclude>tests/Integration</exclude>
</testsuite>
<testsuite name="Integration">
<directory>tests/Integration</directory>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory suffix=".php">src/</directory>
</whitelist>
</filter>
</phpunit>

View File

@ -0,0 +1,213 @@
<?php
namespace GuzzleHttp\Tests\Psr7;
use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\AppendStream;
class AppendStreamTest extends BaseTest
{
public function testValidatesStreamsAreReadable()
{
$a = new AppendStream();
$s = $this->getMockBuilder('Psr\Http\Message\StreamInterface')
->setMethods(['isReadable'])
->getMockForAbstractClass();
$s->expects(self::once())
->method('isReadable')
->will(self::returnValue(false));
$this->expectExceptionGuzzle('InvalidArgumentException', 'Each stream must be readable');
$a->addStream($s);
}
public function testValidatesSeekType()
{
$a = new AppendStream();
$this->expectExceptionGuzzle('RuntimeException', 'The AppendStream can only seek with SEEK_SET');
$a->seek(100, SEEK_CUR);
}
public function testTriesToRewindOnSeek()
{
$a = new AppendStream();
$s = $this->getMockBuilder('Psr\Http\Message\StreamInterface')
->setMethods(['isReadable', 'rewind', 'isSeekable'])
->getMockForAbstractClass();
$s->expects(self::once())
->method('isReadable')
->will(self::returnValue(true));
$s->expects(self::once())
->method('isSeekable')
->will(self::returnValue(true));
$s->expects(self::once())
->method('rewind')
->will(self::throwException(new \RuntimeException()));
$a->addStream($s);
$this->expectExceptionGuzzle('RuntimeException', 'Unable to seek stream 0 of the AppendStream');
$a->seek(10);
}
public function testSeeksToPositionByReading()
{
$a = new AppendStream([
Psr7\Utils::streamFor('foo'),
Psr7\Utils::streamFor('bar'),
Psr7\Utils::streamFor('baz'),
]);
$a->seek(3);
self::assertSame(3, $a->tell());
self::assertSame('bar', $a->read(3));
$a->seek(6);
self::assertSame(6, $a->tell());
self::assertSame('baz', $a->read(3));
}
public function testDetachWithoutStreams()
{
$s = new AppendStream();
$s->detach();
self::assertSame(0, $s->getSize());
self::assertTrue($s->eof());
self::assertTrue($s->isReadable());
self::assertSame('', (string) $s);
self::assertTrue($s->isSeekable());
self::assertFalse($s->isWritable());
}
public function testDetachesEachStream()
{
$handle = fopen('php://temp', 'r');
$s1 = Psr7\Utils::streamFor($handle);
$s2 = Psr7\Utils::streamFor('bar');
$a = new AppendStream([$s1, $s2]);
$a->detach();
self::assertSame(0, $a->getSize());
self::assertTrue($a->eof());
self::assertTrue($a->isReadable());
self::assertSame('', (string) $a);
self::assertTrue($a->isSeekable());
self::assertFalse($a->isWritable());
self::assertNull($s1->detach());
$this->assertInternalTypeGuzzle('resource', $handle, 'resource is not closed when detaching');
fclose($handle);
}
public function testClosesEachStream()
{
$handle = fopen('php://temp', 'r');
$s1 = Psr7\Utils::streamFor($handle);
$s2 = Psr7\Utils::streamFor('bar');
$a = new AppendStream([$s1, $s2]);
$a->close();
self::assertSame(0, $a->getSize());
self::assertTrue($a->eof());
self::assertTrue($a->isReadable());
self::assertSame('', (string) $a);
self::assertTrue($a->isSeekable());
self::assertFalse($a->isWritable());
self::assertFalse(is_resource($handle));
}
public function testIsNotWritable()
{
$a = new AppendStream([Psr7\Utils::streamFor('foo')]);
self::assertFalse($a->isWritable());
self::assertTrue($a->isSeekable());
self::assertTrue($a->isReadable());
$this->expectExceptionGuzzle('RuntimeException', 'Cannot write to an AppendStream');
$a->write('foo');
}
public function testDoesNotNeedStreams()
{
$a = new AppendStream();
self::assertSame('', (string) $a);
}
public function testCanReadFromMultipleStreams()
{
$a = new AppendStream([
Psr7\Utils::streamFor('foo'),
Psr7\Utils::streamFor('bar'),
Psr7\Utils::streamFor('baz'),
]);
self::assertFalse($a->eof());
self::assertSame(0, $a->tell());
self::assertSame('foo', $a->read(3));
self::assertSame('bar', $a->read(3));
self::assertSame('baz', $a->read(3));
self::assertSame('', $a->read(1));
self::assertTrue($a->eof());
self::assertSame(9, $a->tell());
self::assertSame('foobarbaz', (string) $a);
}
public function testCanDetermineSizeFromMultipleStreams()
{
$a = new AppendStream([
Psr7\Utils::streamFor('foo'),
Psr7\Utils::streamFor('bar')
]);
self::assertSame(6, $a->getSize());
$s = $this->getMockBuilder('Psr\Http\Message\StreamInterface')
->setMethods(['isSeekable', 'isReadable'])
->getMockForAbstractClass();
$s->expects(self::once())
->method('isSeekable')
->will(self::returnValue(null));
$s->expects(self::once())
->method('isReadable')
->will(self::returnValue(true));
$a->addStream($s);
self::assertNull($a->getSize());
}
public function testCatchesExceptionsWhenCastingToString()
{
$s = $this->getMockBuilder('Psr\Http\Message\StreamInterface')
->setMethods(['isSeekable', 'read', 'isReadable', 'eof'])
->getMockForAbstractClass();
$s->expects(self::once())
->method('isSeekable')
->will(self::returnValue(true));
$s->expects(self::once())
->method('read')
->will(self::throwException(new \RuntimeException('foo')));
$s->expects(self::once())
->method('isReadable')
->will(self::returnValue(true));
$s->expects(self::any())
->method('eof')
->will(self::returnValue(false));
$a = new AppendStream([$s]);
self::assertFalse($a->eof());
self::assertSame('', (string) $a);
}
public function testReturnsEmptyMetadata()
{
$s = new AppendStream();
self::assertSame([], $s->getMetadata());
self::assertNull($s->getMetadata('foo'));
}
}

View File

@ -0,0 +1,139 @@
<?php
namespace GuzzleHttp\Tests\Psr7;
use PHPUnit\Framework\TestCase;
abstract class BaseTest extends TestCase
{
/**
* @param string $exception
* @param string|null $message
*/
public function expectExceptionGuzzle($exception, $message = null)
{
if (method_exists($this, 'setExpectedException')) {
$this->setExpectedException($exception, $message);
} else {
$this->expectException($exception);
if (null !== $message) {
$this->expectExceptionMessage($message);
}
}
}
public function expectWarningGuzzle()
{
if (method_exists($this, 'expectWarning')) {
$this->expectWarning();
} elseif (class_exists('PHPUnit\Framework\Error\Warning')) {
$this->expectExceptionGuzzle('PHPUnit\Framework\Error\Warning');
} else {
$this->expectExceptionGuzzle('PHPUnit_Framework_Error_Warning');
}
}
/**
* @param string $type
* @param mixed $input
*/
public function assertInternalTypeGuzzle($type, $input)
{
switch ($type) {
case 'array':
if (method_exists($this, 'assertIsArray')) {
self::assertIsArray($input);
} else {
self::assertInternalType('array', $input);
}
break;
case 'bool':
case 'boolean':
if (method_exists($this, 'assertIsBool')) {
self::assertIsBool($input);
} else {
self::assertInternalType('bool', $input);
}
break;
case 'double':
case 'float':
case 'real':
if (method_exists($this, 'assertIsFloat')) {
self::assertIsFloat($input);
} else {
self::assertInternalType('float', $input);
}
break;
case 'int':
case 'integer':
if (method_exists($this, 'assertIsInt')) {
self::assertIsInt($input);
} else {
self::assertInternalType('int', $input);
}
break;
case 'numeric':
if (method_exists($this, 'assertIsNumeric')) {
self::assertIsNumeric($input);
} else {
self::assertInternalType('numeric', $input);
}
break;
case 'object':
if (method_exists($this, 'assertIsObject')) {
self::assertIsObject($input);
} else {
self::assertInternalType('object', $input);
}
break;
case 'resource':
if (method_exists($this, 'assertIsResource')) {
self::assertIsResource($input);
} else {
self::assertInternalType('resource', $input);
}
break;
case 'string':
if (method_exists($this, 'assertIsString')) {
self::assertIsString($input);
} else {
self::assertInternalType('string', $input);
}
break;
case 'scalar':
if (method_exists($this, 'assertIsScalar')) {
self::assertIsScalar($input);
} else {
self::assertInternalType('scalar', $input);
}
break;
case 'callable':
if (method_exists($this, 'assertIsCallable')) {
self::assertIsCallable($input);
} else {
self::assertInternalType('callable', $input);
}
break;
case 'iterable':
if (method_exists($this, 'assertIsIterable')) {
self::assertIsIterable($input);
} else {
self::assertInternalType('iterable', $input);
}
break;
}
}
/**
* @param string $needle
* @param string $haystack
*/
public function assertStringContainsStringGuzzle($needle, $haystack)
{
if (method_exists($this, 'assertStringContainsString')) {
self::assertStringContainsString($needle, $haystack);
} else {
self::assertContains($needle, $haystack);
}
}
}

View File

@ -0,0 +1,63 @@
<?php
namespace GuzzleHttp\Tests\Psr7;
use GuzzleHttp\Psr7\BufferStream;
class BufferStreamTest extends BaseTest
{
public function testHasMetadata()
{
$b = new BufferStream(10);
self::assertTrue($b->isReadable());
self::assertTrue($b->isWritable());
self::assertFalse($b->isSeekable());
self::assertSame(null, $b->getMetadata('foo'));
self::assertSame(10, $b->getMetadata('hwm'));
self::assertSame([], $b->getMetadata());
}
public function testRemovesReadDataFromBuffer()
{
$b = new BufferStream();
self::assertSame(3, $b->write('foo'));
self::assertSame(3, $b->getSize());
self::assertFalse($b->eof());
self::assertSame('foo', $b->read(10));
self::assertTrue($b->eof());
self::assertSame('', $b->read(10));
}
public function testCanCastToStringOrGetContents()
{
$b = new BufferStream();
$b->write('foo');
$b->write('baz');
self::assertSame('foo', $b->read(3));
$b->write('bar');
self::assertSame('bazbar', (string) $b);
$this->expectExceptionGuzzle('RuntimeException', 'Cannot determine the position of a BufferStream');
$b->tell();
}
public function testDetachClearsBuffer()
{
$b = new BufferStream();
$b->write('foo');
$b->detach();
self::assertTrue($b->eof());
self::assertSame(3, $b->write('abc'));
self::assertSame('abc', $b->read(10));
}
public function testExceedingHighwaterMarkReturnsFalseButStillBuffers()
{
$b = new BufferStream(5);
self::assertSame(3, $b->write('hi '));
self::assertFalse($b->write('hello'));
self::assertSame('hi hello', (string) $b);
self::assertSame(4, $b->write('test'));
}
}

View File

@ -0,0 +1,212 @@
<?php
namespace GuzzleHttp\Tests\Psr7;
use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\CachingStream;
use GuzzleHttp\Psr7\Stream;
/**
* @covers GuzzleHttp\Psr7\CachingStream
*/
class CachingStreamTest extends BaseTest
{
/** @var CachingStream */
private $body;
/** @var Stream */
private $decorated;
/**
* @before
*/
public function setUpTest()
{
$this->decorated = Psr7\Utils::streamFor('testing');
$this->body = new CachingStream($this->decorated);
}
/**
* @after
*/
public function tearDownTest()
{
$this->decorated->close();
$this->body->close();
}
public function testUsesRemoteSizeIfAvailable()
{
$body = Psr7\Utils::streamFor('test');
$caching = new CachingStream($body);
self::assertSame(4, $caching->getSize());
}
public function testUsesRemoteSizeIfNotAvailable()
{
$body = new Psr7\PumpStream(function () {
return 'a';
});
$caching = new CachingStream($body);
self::assertNull($caching->getSize());
}
public function testReadsUntilCachedToByte()
{
$this->body->seek(5);
self::assertSame('n', $this->body->read(1));
$this->body->seek(0);
self::assertSame('t', $this->body->read(1));
}
public function testCanSeekNearEndWithSeekEnd()
{
$baseStream = Psr7\Utils::streamFor(implode('', range('a', 'z')));
$cached = new CachingStream($baseStream);
$cached->seek(-1, SEEK_END);
self::assertSame(25, $baseStream->tell());
self::assertSame('z', $cached->read(1));
self::assertSame(26, $cached->getSize());
}
public function testCanSeekToEndWithSeekEnd()
{
$baseStream = Psr7\Utils::streamFor(implode('', range('a', 'z')));
$cached = new CachingStream($baseStream);
$cached->seek(0, SEEK_END);
self::assertSame(26, $baseStream->tell());
self::assertSame('', $cached->read(1));
self::assertSame(26, $cached->getSize());
}
public function testCanUseSeekEndWithUnknownSize()
{
$baseStream = Psr7\Utils::streamFor('testing');
$decorated = Psr7\FnStream::decorate($baseStream, [
'getSize' => function () {
return null;
}
]);
$cached = new CachingStream($decorated);
$cached->seek(-1, SEEK_END);
self::assertSame('g', $cached->read(1));
}
public function testRewindUsesSeek()
{
$a = Psr7\Utils::streamFor('foo');
$d = $this->getMockBuilder('GuzzleHttp\Psr7\CachingStream')
->setMethods(['seek'])
->setConstructorArgs([$a])
->getMock();
$d->expects(self::once())
->method('seek')
->with(0)
->will(self::returnValue(true));
$d->seek(0);
}
public function testCanSeekToReadBytes()
{
self::assertSame('te', $this->body->read(2));
$this->body->seek(0);
self::assertSame('test', $this->body->read(4));
self::assertSame(4, $this->body->tell());
$this->body->seek(2);
self::assertSame(2, $this->body->tell());
$this->body->seek(2, SEEK_CUR);
self::assertSame(4, $this->body->tell());
self::assertSame('ing', $this->body->read(3));
}
public function testCanSeekToReadBytesWithPartialBodyReturned()
{
$stream = fopen('php://temp', 'r+');
fwrite($stream, 'testing');
fseek($stream, 0);
$this->decorated = $this->getMockBuilder('\GuzzleHttp\Psr7\Stream')
->setConstructorArgs([$stream])
->setMethods(['read'])
->getMock();
$this->decorated->expects(self::exactly(2))
->method('read')
->willReturnCallback(function ($length) use ($stream) {
return fread($stream, 2);
});
$this->body = new CachingStream($this->decorated);
self::assertSame(0, $this->body->tell());
$this->body->seek(4, SEEK_SET);
self::assertSame(4, $this->body->tell());
$this->body->seek(0);
self::assertSame('test', $this->body->read(4));
}
public function testWritesToBufferStream()
{
$this->body->read(2);
$this->body->write('hi');
$this->body->seek(0);
self::assertSame('tehiing', (string) $this->body);
}
public function testSkipsOverwrittenBytes()
{
$decorated = Psr7\Utils::streamFor(
implode("\n", array_map(function ($n) {
return str_pad($n, 4, '0', STR_PAD_LEFT);
}, range(0, 25)))
);
$body = new CachingStream($decorated);
self::assertSame("0000\n", Psr7\Utils::readLine($body));
self::assertSame("0001\n", Psr7\Utils::readLine($body));
// Write over part of the body yet to be read, so skip some bytes
self::assertSame(5, $body->write("TEST\n"));
self::assertSame(5, Helpers::readObjectAttribute($body, 'skipReadBytes'));
// Read, which skips bytes, then reads
self::assertSame("0003\n", Psr7\Utils::readLine($body));
self::assertSame(0, Helpers::readObjectAttribute($body, 'skipReadBytes'));
self::assertSame("0004\n", Psr7\Utils::readLine($body));
self::assertSame("0005\n", Psr7\Utils::readLine($body));
// Overwrite part of the cached body (so don't skip any bytes)
$body->seek(5);
self::assertSame(5, $body->write("ABCD\n"));
self::assertSame(0, Helpers::readObjectAttribute($body, 'skipReadBytes'));
self::assertSame("TEST\n", Psr7\Utils::readLine($body));
self::assertSame("0003\n", Psr7\Utils::readLine($body));
self::assertSame("0004\n", Psr7\Utils::readLine($body));
self::assertSame("0005\n", Psr7\Utils::readLine($body));
self::assertSame("0006\n", Psr7\Utils::readLine($body));
self::assertSame(5, $body->write("1234\n"));
self::assertSame(5, Helpers::readObjectAttribute($body, 'skipReadBytes'));
// Seek to 0 and ensure the overwritten bit is replaced
$body->seek(0);
self::assertSame("0000\nABCD\nTEST\n0003\n0004\n0005\n0006\n1234\n0008\n0009\n", $body->read(50));
// Ensure that casting it to a string does not include the bit that was overwritten
$this->assertStringContainsStringGuzzle("0000\nABCD\nTEST\n0003\n0004\n0005\n0006\n1234\n0008\n0009\n", (string) $body);
}
public function testClosesBothStreams()
{
$s = fopen('php://temp', 'r');
$a = Psr7\Utils::streamFor($s);
$d = new CachingStream($a);
$d->close();
self::assertFalse(is_resource($s));
}
public function testEnsuresValidWhence()
{
$this->expectExceptionGuzzle('InvalidArgumentException');
$this->body->seek(10, -123456);
}
}

View File

@ -0,0 +1,27 @@
<?php
namespace GuzzleHttp\Tests\Psr7;
use GuzzleHttp\Psr7\BufferStream;
use GuzzleHttp\Psr7\DroppingStream;
class DroppingStreamTest extends BaseTest
{
public function testBeginsDroppingWhenSizeExceeded()
{
$stream = new BufferStream();
$drop = new DroppingStream($stream, 5);
self::assertSame(3, $drop->write('hel'));
self::assertSame(2, $drop->write('lo'));
self::assertSame(5, $drop->getSize());
self::assertSame('hello', $drop->read(5));
self::assertSame(0, $drop->getSize());
$drop->write('12345678910');
self::assertSame(5, $stream->getSize());
self::assertSame(5, $drop->getSize());
self::assertSame('12345', (string) $drop);
self::assertSame(0, $drop->getSize());
$drop->write('hello');
self::assertSame(0, $drop->write('test'));
}
}

View File

@ -0,0 +1,98 @@
<?php
namespace GuzzleHttp\Tests\Psr7;
use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\FnStream;
/**
* @covers GuzzleHttp\Psr7\FnStream
*/
class FnStreamTest extends BaseTest
{
public function testThrowsWhenNotImplemented()
{
$this->expectExceptionGuzzle('BadMethodCallException', 'seek() is not implemented in the FnStream');
(new FnStream([]))->seek(1);
}
public function testProxiesToFunction()
{
$s = new FnStream([
'read' => function ($len) {
$this->assertSame(3, $len);
return 'foo';
}
]);
self::assertSame('foo', $s->read(3));
}
public function testCanCloseOnDestruct()
{
$called = false;
$s = new FnStream([
'close' => function () use (&$called) {
$called = true;
}
]);
unset($s);
self::assertTrue($called);
}
public function testDoesNotRequireClose()
{
$s = new FnStream([]);
unset($s);
self::assertTrue(true); // strict mode requires an assertion
}
public function testDecoratesStream()
{
$a = Psr7\Utils::streamFor('foo');
$b = FnStream::decorate($a, []);
self::assertSame(3, $b->getSize());
self::assertSame($b->isWritable(), true);
self::assertSame($b->isReadable(), true);
self::assertSame($b->isSeekable(), true);
self::assertSame($b->read(3), 'foo');
self::assertSame($b->tell(), 3);
self::assertSame($a->tell(), 3);
self::assertSame('', $a->read(1));
self::assertSame($b->eof(), true);
self::assertSame($a->eof(), true);
$b->seek(0);
self::assertSame('foo', (string) $b);
$b->seek(0);
self::assertSame('foo', $b->getContents());
self::assertSame($a->getMetadata(), $b->getMetadata());
$b->seek(0, SEEK_END);
$b->write('bar');
self::assertSame('foobar', (string) $b);
$this->assertInternalTypeGuzzle('resource', $b->detach());
$b->close();
}
public function testDecoratesWithCustomizations()
{
$called = false;
$a = Psr7\Utils::streamFor('foo');
$b = FnStream::decorate($a, [
'read' => function ($len) use (&$called, $a) {
$called = true;
return $a->read($len);
}
]);
self::assertSame('foo', $b->read(3));
self::assertTrue($called);
}
public function testDoNotAllowUnserialization()
{
$a = new FnStream([]);
$b = serialize($a);
$this->expectExceptionGuzzle('\LogicException', 'FnStream should never be unserialized');
unserialize($b);
}
}

View File

@ -0,0 +1,11 @@
<?php
namespace GuzzleHttp\Tests\Psr7;
class HasToString
{
public function __toString()
{
return 'foo';
}
}

View File

@ -0,0 +1,68 @@
<?php
namespace GuzzleHttp\Tests\Psr7;
use GuzzleHttp\Psr7;
class HeaderTest extends BaseTest
{
public function parseParamsProvider()
{
$res1 = [
[
'<http:/.../front.jpeg>',
'rel' => 'front',
'type' => 'image/jpeg',
],
[
'<http://.../back.jpeg>',
'rel' => 'back',
'type' => 'image/jpeg',
],
];
return [
[
'<http:/.../front.jpeg>; rel="front"; type="image/jpeg", <http://.../back.jpeg>; rel=back; type="image/jpeg"',
$res1,
],
[
'<http:/.../front.jpeg>; rel="front"; type="image/jpeg",<http://.../back.jpeg>; rel=back; type="image/jpeg"',
$res1,
],
[
'foo="baz"; bar=123, boo, test="123", foobar="foo;bar"',
[
['foo' => 'baz', 'bar' => '123'],
['boo'],
['test' => '123'],
['foobar' => 'foo;bar'],
],
],
[
'<http://.../side.jpeg?test=1>; rel="side"; type="image/jpeg",<http://.../side.jpeg?test=2>; rel=side; type="image/jpeg"',
[
['<http://.../side.jpeg?test=1>', 'rel' => 'side', 'type' => 'image/jpeg'],
['<http://.../side.jpeg?test=2>', 'rel' => 'side', 'type' => 'image/jpeg'],
],
],
[
'',
[],
],
];
}
/**
* @dataProvider parseParamsProvider
*/
public function testParseParams($header, $result)
{
self::assertSame($result, Psr7\Header::parse($header));
}
public function testParsesArrayHeaders()
{
$header = ['a, b', 'c', 'd, e'];
self::assertSame(['a', 'b', 'c', 'd', 'e'], Psr7\Header::normalize($header));
}
}

View File

@ -0,0 +1,35 @@
<?php
namespace GuzzleHttp\Tests\Psr7;
class Helpers
{
/**
* @param object $object
* @param string $attributeName
*/
public static function readObjectAttribute($object, $attributeName)
{
$reflector = new \ReflectionObject($object);
do {
try {
$attribute = $reflector->getProperty($attributeName);
if (!$attribute || $attribute->isPublic()) {
return $object->$attributeName;
}
$attribute->setAccessible(true);
return $attribute->getValue($object);
} catch (\ReflectionException $e) {
// do nothing
}
} while ($reflector = $reflector->getParentClass());
throw new \Exception(
sprintf('Attribute "%s" not found in object.', $attributeName)
);
}
}

View File

@ -0,0 +1,51 @@
<?php
namespace GuzzleHttp\Tests\Psr7;
use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\InflateStream;
use GuzzleHttp\Psr7\NoSeekStream;
class InflateStreamTest extends BaseTest
{
public function testInflatesStreams()
{
$content = gzencode('test');
$a = Psr7\Utils::streamFor($content);
$b = new InflateStream($a);
self::assertSame('test', (string) $b);
}
public function testInflatesStreamsWithFilename()
{
$content = $this->getGzipStringWithFilename('test');
$a = Psr7\Utils::streamFor($content);
$b = new InflateStream($a);
self::assertSame('test', (string) $b);
}
public function testInflatesStreamsPreserveSeekable()
{
$content = $this->getGzipStringWithFilename('test');
$seekable = Psr7\Utils::streamFor($content);
$nonSeekable = new NoSeekStream(Psr7\Utils::streamFor($content));
self::assertTrue((new InflateStream($seekable))->isSeekable());
self::assertFalse((new InflateStream($nonSeekable))->isSeekable());
}
private function getGzipStringWithFilename($original_string)
{
$gzipped = bin2hex(gzencode($original_string));
$header = substr($gzipped, 0, 20);
// set FNAME flag
$header[6]=0;
$header[7]=8;
// make a dummy filename
$filename = '64756d6d7900';
$rest = substr($gzipped, 20);
return hex2bin($header . $filename . $rest);
}
}

View File

@ -0,0 +1,45 @@
<?php
namespace GuzzleHttp\Tests\Psr7\Integration;
use GuzzleHttp\Tests\Psr7\BaseTest;
class ServerRequestFromGlobalsTest extends BaseTest
{
/**
* @before
*/
protected function setUpTest()
{
if (false === $this->getServerUri()) {
self::markTestSkipped();
}
parent::setUp();
}
public function testBodyExists()
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $this->getServerUri());
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, 'foobar');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
curl_close($curl);
self::assertNotFalse($response);
$data = json_decode($response, true);
self::assertIsArray($data);
self::assertArrayHasKey('method', $data);
self::assertArrayHasKey('uri', $data);
self::assertArrayHasKey('body', $data);
self::assertEquals('foobar', $data['body']);
}
private function getServerUri()
{
return isset($_SERVER['TEST_SERVER']) ? $_SERVER['TEST_SERVER'] : false;
}
}

View File

@ -0,0 +1,13 @@
<?php
require dirname(__DIR__, 2) . '/vendor/autoload.php';
$request = \GuzzleHttp\Psr7\ServerRequest::fromGlobals();
$output = [
'method' => $request->getMethod(),
'uri' => $request->getUri()->__toString(),
'body' => $request->getBody()->__toString(),
];
echo json_encode($output);

View File

@ -0,0 +1,71 @@
<?php
namespace GuzzleHttp\Tests\Psr7;
use GuzzleHttp\Psr7\LazyOpenStream;
class LazyOpenStreamTest extends BaseTest
{
private $fname;
/**
* @before
*/
public function setUpTest()
{
$this->fname = tempnam(sys_get_temp_dir(), 'tfile');
if (file_exists($this->fname)) {
unlink($this->fname);
}
}
/**
* @after
*/
public function tearDownTest()
{
if (file_exists($this->fname)) {
unlink($this->fname);
}
}
public function testOpensLazily()
{
$l = new LazyOpenStream($this->fname, 'w+');
$l->write('foo');
$this->assertInternalTypeGuzzle('array', $l->getMetadata());
self::assertFileExists($this->fname);
self::assertSame('foo', file_get_contents($this->fname));
self::assertSame('foo', (string) $l);
}
public function testProxiesToFile()
{
file_put_contents($this->fname, 'foo');
$l = new LazyOpenStream($this->fname, 'r');
self::assertSame('foo', $l->read(4));
self::assertTrue($l->eof());
self::assertSame(3, $l->tell());
self::assertTrue($l->isReadable());
self::assertTrue($l->isSeekable());
self::assertFalse($l->isWritable());
$l->seek(1);
self::assertSame('oo', $l->getContents());
self::assertSame('foo', (string) $l);
self::assertSame(3, $l->getSize());
$this->assertInternalTypeGuzzle('array', $l->getMetadata());
$l->close();
}
public function testDetachesUnderlyingStream()
{
file_put_contents($this->fname, 'foo');
$l = new LazyOpenStream($this->fname, 'r');
$r = $l->detach();
$this->assertInternalTypeGuzzle('resource', $r);
fseek($r, 0);
self::assertSame('foo', stream_get_contents($r));
fclose($r);
}
}

View File

@ -0,0 +1,166 @@
<?php
namespace GuzzleHttp\Tests\Psr7;
use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\FnStream;
use GuzzleHttp\Psr7\LimitStream;
use GuzzleHttp\Psr7\NoSeekStream;
use GuzzleHttp\Psr7\Stream;
/**
* @covers GuzzleHttp\Psr7\LimitStream
*/
class LimitStreamTest extends BaseTest
{
/** @var LimitStream */
private $body;
/** @var Stream */
private $decorated;
/**
* @before
*/
public function setUpTest()
{
$this->decorated = Psr7\Utils::streamFor(fopen(__FILE__, 'r'));
$this->body = new LimitStream($this->decorated, 10, 3);
}
public function testReturnsSubset()
{
$body = new LimitStream(Psr7\Utils::streamFor('foo'), -1, 1);
self::assertSame('oo', (string) $body);
self::assertTrue($body->eof());
$body->seek(0);
self::assertFalse($body->eof());
self::assertSame('oo', $body->read(100));
self::assertSame('', $body->read(1));
self::assertTrue($body->eof());
}
public function testReturnsSubsetWhenCastToString()
{
$body = Psr7\Utils::streamFor('foo_baz_bar');
$limited = new LimitStream($body, 3, 4);
self::assertSame('baz', (string) $limited);
}
public function testReturnsSubsetOfEmptyBodyWhenCastToString()
{
$body = Psr7\Utils::streamFor('01234567891234');
$limited = new LimitStream($body, 0, 10);
self::assertSame('', (string) $limited);
}
public function testReturnsSpecificSubsetOBodyWhenCastToString()
{
$body = Psr7\Utils::streamFor('0123456789abcdef');
$limited = new LimitStream($body, 3, 10);
self::assertSame('abc', (string) $limited);
}
public function testSeeksWhenConstructed()
{
self::assertSame(0, $this->body->tell());
self::assertSame(3, $this->decorated->tell());
}
public function testAllowsBoundedSeek()
{
$this->body->seek(100);
self::assertSame(10, $this->body->tell());
self::assertSame(13, $this->decorated->tell());
$this->body->seek(0);
self::assertSame(0, $this->body->tell());
self::assertSame(3, $this->decorated->tell());
try {
$this->body->seek(-10);
self::fail();
} catch (\RuntimeException $e) {
}
self::assertSame(0, $this->body->tell());
self::assertSame(3, $this->decorated->tell());
$this->body->seek(5);
self::assertSame(5, $this->body->tell());
self::assertSame(8, $this->decorated->tell());
// Fail
try {
$this->body->seek(1000, SEEK_END);
self::fail();
} catch (\RuntimeException $e) {
}
}
public function testReadsOnlySubsetOfData()
{
$data = $this->body->read(100);
self::assertSame(10, strlen($data));
self::assertSame('', $this->body->read(1000));
$this->body->setOffset(10);
$newData = $this->body->read(100);
self::assertSame(10, strlen($newData));
self::assertNotSame($data, $newData);
}
public function testThrowsWhenCurrentGreaterThanOffsetSeek()
{
$a = Psr7\Utils::streamFor('foo_bar');
$b = new NoSeekStream($a);
$c = new LimitStream($b);
$a->getContents();
$this->expectExceptionGuzzle('RuntimeException', 'Could not seek to stream offset 2');
$c->setOffset(2);
}
public function testCanGetContentsWithoutSeeking()
{
$a = Psr7\Utils::streamFor('foo_bar');
$b = new NoSeekStream($a);
$c = new LimitStream($b);
self::assertSame('foo_bar', $c->getContents());
}
public function testClaimsConsumedWhenReadLimitIsReached()
{
self::assertFalse($this->body->eof());
$this->body->read(1000);
self::assertTrue($this->body->eof());
}
public function testContentLengthIsBounded()
{
self::assertSame(10, $this->body->getSize());
}
public function testGetContentsIsBasedOnSubset()
{
$body = new LimitStream(Psr7\Utils::streamFor('foobazbar'), 3, 3);
self::assertSame('baz', $body->getContents());
}
public function testReturnsNullIfSizeCannotBeDetermined()
{
$a = new FnStream([
'getSize' => function () {
return null;
},
'tell' => function () {
return 0;
},
]);
$b = new LimitStream($a);
self::assertNull($b->getSize());
}
public function testLengthLessOffsetWhenNoLimitSize()
{
$a = Psr7\Utils::streamFor('foo_bar');
$b = new LimitStream($a, -1, 4);
self::assertSame(3, $b->getSize());
}
}

View File

@ -0,0 +1,266 @@
<?php
namespace GuzzleHttp\Tests\Psr7;
use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\FnStream;
class MessageTest extends BaseTest
{
public function testConvertsRequestsToStrings()
{
$request = new Psr7\Request('PUT', 'http://foo.com/hi?123', [
'Baz' => 'bar',
'Qux' => 'ipsum',
], 'hello', '1.0');
self::assertSame(
"PUT /hi?123 HTTP/1.0\r\nHost: foo.com\r\nBaz: bar\r\nQux: ipsum\r\n\r\nhello",
Psr7\Message::toString($request)
);
}
public function testConvertsResponsesToStrings()
{
$response = new Psr7\Response(200, [
'Baz' => 'bar',
'Qux' => 'ipsum',
], 'hello', '1.0', 'FOO');
self::assertSame(
"HTTP/1.0 200 FOO\r\nBaz: bar\r\nQux: ipsum\r\n\r\nhello",
Psr7\Message::toString($response)
);
}
public function testCorrectlyRendersSetCookieHeadersToString()
{
$response = new Psr7\Response(200, [
'Set-Cookie' => ['bar','baz','qux']
], 'hello', '1.0', 'FOO');
self::assertSame(
"HTTP/1.0 200 FOO\r\nSet-Cookie: bar\r\nSet-Cookie: baz\r\nSet-Cookie: qux\r\n\r\nhello",
Psr7\Message::toString($response)
);
}
public function testRewindsBody()
{
$body = Psr7\Utils::streamFor('abc');
$res = new Psr7\Response(200, [], $body);
Psr7\Message::rewindBody($res);
self::assertSame(0, $body->tell());
$body->rewind();
Psr7\Message::rewindBody($res);
self::assertSame(0, $body->tell());
}
public function testThrowsWhenBodyCannotBeRewound()
{
$body = Psr7\Utils::streamFor('abc');
$body->read(1);
$body = FnStream::decorate($body, [
'rewind' => function () {
throw new \RuntimeException('a');
},
]);
$res = new Psr7\Response(200, [], $body);
$this->expectExceptionGuzzle('RuntimeException');
Psr7\Message::rewindBody($res);
}
public function testParsesRequestMessages()
{
$req = "GET /abc HTTP/1.0\r\nHost: foo.com\r\nFoo: Bar\r\nBaz: Bam\r\nBaz: Qux\r\n\r\nTest";
$request = Psr7\Message::parseRequest($req);
self::assertSame('GET', $request->getMethod());
self::assertSame('/abc', $request->getRequestTarget());
self::assertSame('1.0', $request->getProtocolVersion());
self::assertSame('foo.com', $request->getHeaderLine('Host'));
self::assertSame('Bar', $request->getHeaderLine('Foo'));
self::assertSame('Bam, Qux', $request->getHeaderLine('Baz'));
self::assertSame('Test', (string)$request->getBody());
self::assertSame('http://foo.com/abc', (string)$request->getUri());
}
public function testParsesRequestMessagesWithHttpsScheme()
{
$req = "PUT /abc?baz=bar HTTP/1.1\r\nHost: foo.com:443\r\n\r\n";
$request = Psr7\Message::parseRequest($req);
self::assertSame('PUT', $request->getMethod());
self::assertSame('/abc?baz=bar', $request->getRequestTarget());
self::assertSame('1.1', $request->getProtocolVersion());
self::assertSame('foo.com:443', $request->getHeaderLine('Host'));
self::assertSame('', (string)$request->getBody());
self::assertSame('https://foo.com/abc?baz=bar', (string)$request->getUri());
}
public function testParsesRequestMessagesWithUriWhenHostIsNotFirst()
{
$req = "PUT / HTTP/1.1\r\nFoo: Bar\r\nHost: foo.com\r\n\r\n";
$request = Psr7\Message::parseRequest($req);
self::assertSame('PUT', $request->getMethod());
self::assertSame('/', $request->getRequestTarget());
self::assertSame('http://foo.com/', (string)$request->getUri());
}
public function testParsesRequestMessagesWithFullUri()
{
$req = "GET https://www.google.com:443/search?q=foobar HTTP/1.1\r\nHost: www.google.com\r\n\r\n";
$request = Psr7\Message::parseRequest($req);
self::assertSame('GET', $request->getMethod());
self::assertSame('https://www.google.com:443/search?q=foobar', $request->getRequestTarget());
self::assertSame('1.1', $request->getProtocolVersion());
self::assertSame('www.google.com', $request->getHeaderLine('Host'));
self::assertSame('', (string)$request->getBody());
self::assertSame('https://www.google.com/search?q=foobar', (string)$request->getUri());
}
public function testParsesRequestMessagesWithCustomMethod()
{
$req = "GET_DATA / HTTP/1.1\r\nFoo: Bar\r\nHost: foo.com\r\n\r\n";
$request = Psr7\Message::parseRequest($req);
self::assertSame('GET_DATA', $request->getMethod());
}
public function testParsesRequestMessagesWithFoldedHeadersOnHttp10()
{
$req = "PUT / HTTP/1.0\r\nFoo: Bar\r\n Bam\r\n\r\n";
$request = Psr7\Message::parseRequest($req);
self::assertSame('PUT', $request->getMethod());
self::assertSame('/', $request->getRequestTarget());
self::assertSame('Bar Bam', $request->getHeaderLine('Foo'));
}
public function testRequestParsingFailsWithFoldedHeadersOnHttp11()
{
$this->expectExceptionGuzzle('InvalidArgumentException', 'Invalid header syntax: Obsolete line folding');
Psr7\Message::parseResponse("GET_DATA / HTTP/1.1\r\nFoo: Bar\r\n Biz: Bam\r\n\r\n");
}
public function testParsesRequestMessagesWhenHeaderDelimiterIsOnlyALineFeed()
{
$req = "PUT / HTTP/1.0\nFoo: Bar\nBaz: Bam\n\n";
$request = Psr7\Message::parseRequest($req);
self::assertSame('PUT', $request->getMethod());
self::assertSame('/', $request->getRequestTarget());
self::assertSame('Bar', $request->getHeaderLine('Foo'));
self::assertSame('Bam', $request->getHeaderLine('Baz'));
}
public function testValidatesRequestMessages()
{
$this->expectExceptionGuzzle('InvalidArgumentException');
Psr7\Message::parseRequest("HTTP/1.1 200 OK\r\n\r\n");
}
public function testParsesResponseMessages()
{
$res = "HTTP/1.0 200 OK\r\nFoo: Bar\r\nBaz: Bam\r\nBaz: Qux\r\n\r\nTest";
$response = Psr7\Message::parseResponse($res);
self::assertSame(200, $response->getStatusCode());
self::assertSame('OK', $response->getReasonPhrase());
self::assertSame('1.0', $response->getProtocolVersion());
self::assertSame('Bar', $response->getHeaderLine('Foo'));
self::assertSame('Bam, Qux', $response->getHeaderLine('Baz'));
self::assertSame('Test', (string)$response->getBody());
}
public function testParsesResponseWithoutReason()
{
$res = "HTTP/1.0 200\r\nFoo: Bar\r\nBaz: Bam\r\nBaz: Qux\r\n\r\nTest";
$response = Psr7\Message::parseResponse($res);
self::assertSame(200, $response->getStatusCode());
self::assertSame('OK', $response->getReasonPhrase());
self::assertSame('1.0', $response->getProtocolVersion());
self::assertSame('Bar', $response->getHeaderLine('Foo'));
self::assertSame('Bam, Qux', $response->getHeaderLine('Baz'));
self::assertSame('Test', (string)$response->getBody());
}
public function testParsesResponseWithLeadingDelimiter()
{
$res = "\r\nHTTP/1.0 200\r\nFoo: Bar\r\n\r\nTest";
$response = Psr7\Message::parseResponse($res);
self::assertSame(200, $response->getStatusCode());
self::assertSame('OK', $response->getReasonPhrase());
self::assertSame('1.0', $response->getProtocolVersion());
self::assertSame('Bar', $response->getHeaderLine('Foo'));
self::assertSame('Test', (string)$response->getBody());
}
public function testParsesResponseWithFoldedHeadersOnHttp10()
{
$res = "HTTP/1.0 200\r\nFoo: Bar\r\n Bam\r\n\r\nTest";
$response = Psr7\Message::parseResponse($res);
self::assertSame(200, $response->getStatusCode());
self::assertSame('OK', $response->getReasonPhrase());
self::assertSame('1.0', $response->getProtocolVersion());
self::assertSame('Bar Bam', $response->getHeaderLine('Foo'));
self::assertSame('Test', (string)$response->getBody());
}
public function testResponseParsingFailsWithFoldedHeadersOnHttp11()
{
$this->expectExceptionGuzzle('InvalidArgumentException', 'Invalid header syntax: Obsolete line folding');
Psr7\Message::parseResponse("HTTP/1.1 200\r\nFoo: Bar\r\n Biz: Bam\r\nBaz: Qux\r\n\r\nTest");
}
public function testParsesResponseWhenHeaderDelimiterIsOnlyALineFeed()
{
$res = "HTTP/1.0 200\nFoo: Bar\nBaz: Bam\n\nTest\n\nOtherTest";
$response = Psr7\Message::parseResponse($res);
self::assertSame(200, $response->getStatusCode());
self::assertSame('OK', $response->getReasonPhrase());
self::assertSame('1.0', $response->getProtocolVersion());
self::assertSame('Bar', $response->getHeaderLine('Foo'));
self::assertSame('Bam', $response->getHeaderLine('Baz'));
self::assertSame("Test\n\nOtherTest", (string)$response->getBody());
}
public function testResponseParsingFailsWithoutHeaderDelimiter()
{
$this->expectExceptionGuzzle('InvalidArgumentException', 'Invalid message: Missing header delimiter');
Psr7\Message::parseResponse("HTTP/1.0 200\r\nFoo: Bar\r\n Baz: Bam\r\nBaz: Qux\r\n");
}
public function testValidatesResponseMessages()
{
$this->expectExceptionGuzzle('InvalidArgumentException');
Psr7\Message::parseResponse("GET / HTTP/1.1\r\n\r\n");
}
public function testMessageBodySummaryWithSmallBody()
{
$message = new Psr7\Response(200, [], 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.');
self::assertSame('Lorem ipsum dolor sit amet, consectetur adipiscing elit.', Psr7\Message::bodySummary($message));
}
public function testMessageBodySummaryWithLargeBody()
{
$message = new Psr7\Response(200, [], 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.');
self::assertSame('Lorem ipsu (truncated...)', Psr7\Message::bodySummary($message, 10));
}
public function testMessageBodySummaryWithSpecialUTF8Characters()
{
$message = new Psr7\Response(200, [], '’é€௵ဪ‱');
self::assertSame('’é€௵ဪ‱', Psr7\Message::bodySummary($message));
}
public function testMessageBodySummaryWithEmptyBody()
{
$message = new Psr7\Response(200, [], '');
self::assertNull(Psr7\Message::bodySummary($message));
}
public function testGetResponseBodySummaryOfNonReadableStream()
{
self::assertNull(Psr7\Message::bodySummary(new Psr7\Response(500, [], new ReadSeekOnlyStream())));
}
}

View File

@ -0,0 +1,22 @@
<?php
namespace GuzzleHttp\Tests\Psr7;
use GuzzleHttp\Psr7;
class MimeTypeTest extends BaseTest
{
public function testDetermineFromExtension()
{
self::assertNull(Psr7\MimeType::fromExtension('not-a-real-extension'));
self::assertSame('application/json', Psr7\MimeType::fromExtension('json'));
}
public function testDetermineFromFilename()
{
self::assertSame(
'image/jpeg',
Psr7\MimeType::fromFilename('/tmp/images/IMG034821.JPEG')
);
}
}

View File

@ -0,0 +1,245 @@
<?php
namespace GuzzleHttp\Tests\Psr7;
use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\MultipartStream;
class MultipartStreamTest extends BaseTest
{
public function testCreatesDefaultBoundary()
{
$b = new MultipartStream();
self::assertNotEmpty($b->getBoundary());
}
public function testCanProvideBoundary()
{
$b = new MultipartStream([], 'foo');
self::assertSame('foo', $b->getBoundary());
}
public function testIsNotWritable()
{
$b = new MultipartStream();
self::assertFalse($b->isWritable());
}
public function testCanCreateEmptyStream()
{
$b = new MultipartStream();
$boundary = $b->getBoundary();
self::assertSame("--{$boundary}--\r\n", $b->getContents());
self::assertSame(strlen($boundary) + 6, $b->getSize());
}
public function testValidatesFilesArrayElement()
{
$this->expectExceptionGuzzle('InvalidArgumentException');
new MultipartStream([['foo' => 'bar']]);
}
public function testEnsuresFileHasName()
{
$this->expectExceptionGuzzle('InvalidArgumentException');
new MultipartStream([['contents' => 'bar']]);
}
public function testSerializesFields()
{
$b = new MultipartStream([
[
'name' => 'foo',
'contents' => 'bar'
],
[
'name' => 'baz',
'contents' => 'bam'
]
], 'boundary');
self::assertSame(
"--boundary\r\nContent-Disposition: form-data; name=\"foo\"\r\nContent-Length: 3\r\n\r\n"
. "bar\r\n--boundary\r\nContent-Disposition: form-data; name=\"baz\"\r\nContent-Length: 3"
. "\r\n\r\nbam\r\n--boundary--\r\n",
(string) $b
);
}
public function testSerializesNonStringFields()
{
$b = new MultipartStream([
[
'name' => 'int',
'contents' => (int) 1
],
[
'name' => 'bool',
'contents' => (boolean) false
],
[
'name' => 'bool2',
'contents' => (boolean) true
],
[
'name' => 'float',
'contents' => (float) 1.1
]
], 'boundary');
self::assertSame(
"--boundary\r\nContent-Disposition: form-data; name=\"int\"\r\nContent-Length: 1\r\n\r\n"
. "1\r\n--boundary\r\nContent-Disposition: form-data; name=\"bool\"\r\n\r\n\r\n--boundary"
. "\r\nContent-Disposition: form-data; name=\"bool2\"\r\nContent-Length: 1\r\n\r\n"
. "1\r\n--boundary\r\nContent-Disposition: form-data; name=\"float\"\r\nContent-Length: 3"
. "\r\n\r\n1.1\r\n--boundary--\r\n",
(string) $b
);
}
public function testSerializesFiles()
{
$f1 = Psr7\FnStream::decorate(Psr7\Utils::streamFor('foo'), [
'getMetadata' => function () {
return '/foo/bar.txt';
}
]);
$f2 = Psr7\FnStream::decorate(Psr7\Utils::streamFor('baz'), [
'getMetadata' => function () {
return '/foo/baz.jpg';
}
]);
$f3 = Psr7\FnStream::decorate(Psr7\Utils::streamFor('bar'), [
'getMetadata' => function () {
return '/foo/bar.gif';
}
]);
$b = new MultipartStream([
[
'name' => 'foo',
'contents' => $f1
],
[
'name' => 'qux',
'contents' => $f2
],
[
'name' => 'qux',
'contents' => $f3
],
], 'boundary');
$expected = <<<EOT
--boundary
Content-Disposition: form-data; name="foo"; filename="bar.txt"
Content-Length: 3
Content-Type: text/plain
foo
--boundary
Content-Disposition: form-data; name="qux"; filename="baz.jpg"
Content-Length: 3
Content-Type: image/jpeg
baz
--boundary
Content-Disposition: form-data; name="qux"; filename="bar.gif"
Content-Length: 3
Content-Type: image/gif
bar
--boundary--
EOT;
self::assertSame($expected, str_replace("\r", '', $b));
}
public function testSerializesFilesWithCustomHeaders()
{
$f1 = Psr7\FnStream::decorate(Psr7\Utils::streamFor('foo'), [
'getMetadata' => function () {
return '/foo/bar.txt';
}
]);
$b = new MultipartStream([
[
'name' => 'foo',
'contents' => $f1,
'headers' => [
'x-foo' => 'bar',
'content-disposition' => 'custom'
]
]
], 'boundary');
$expected = <<<EOT
--boundary
x-foo: bar
content-disposition: custom
Content-Length: 3
Content-Type: text/plain
foo
--boundary--
EOT;
self::assertSame($expected, str_replace("\r", '', $b));
}
public function testSerializesFilesWithCustomHeadersAndMultipleValues()
{
$f1 = Psr7\FnStream::decorate(Psr7\Utils::streamFor('foo'), [
'getMetadata' => function () {
return '/foo/bar.txt';
}
]);
$f2 = Psr7\FnStream::decorate(Psr7\Utils::streamFor('baz'), [
'getMetadata' => function () {
return '/foo/baz.jpg';
}
]);
$b = new MultipartStream([
[
'name' => 'foo',
'contents' => $f1,
'headers' => [
'x-foo' => 'bar',
'content-disposition' => 'custom'
]
],
[
'name' => 'foo',
'contents' => $f2,
'headers' => ['cOntenT-Type' => 'custom'],
]
], 'boundary');
$expected = <<<EOT
--boundary
x-foo: bar
content-disposition: custom
Content-Length: 3
Content-Type: text/plain
foo
--boundary
cOntenT-Type: custom
Content-Disposition: form-data; name="foo"; filename="baz.jpg"
Content-Length: 3
baz
--boundary--
EOT;
self::assertSame($expected, str_replace("\r", '', $b));
}
}

View File

@ -0,0 +1,37 @@
<?php
namespace GuzzleHttp\Tests\Psr7;
use GuzzleHttp\Psr7\NoSeekStream;
/**
* @covers GuzzleHttp\Psr7\NoSeekStream
* @covers GuzzleHttp\Psr7\StreamDecoratorTrait
*/
class NoSeekStreamTest extends BaseTest
{
public function testCannotSeek()
{
$s = $this->getMockBuilder('Psr\Http\Message\StreamInterface')
->setMethods(['isSeekable', 'seek'])
->getMockForAbstractClass();
$s->expects(self::never())->method('seek');
$s->expects(self::never())->method('isSeekable');
$wrapped = new NoSeekStream($s);
self::assertFalse($wrapped->isSeekable());
$this->expectExceptionGuzzle('RuntimeException', 'Cannot seek a NoSeekStream');
$wrapped->seek(2);
}
public function testToStringDoesNotSeek()
{
$s = \GuzzleHttp\Psr7\Utils::streamFor('foo');
$s->seek(1);
$wrapped = new NoSeekStream($s);
self::assertSame('oo', (string) $wrapped);
$wrapped->close();
}
}

View File

@ -0,0 +1,78 @@
<?php
namespace GuzzleHttp\Tests\Psr7;
use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\LimitStream;
use GuzzleHttp\Psr7\PumpStream;
class PumpStreamTest extends BaseTest
{
public function testHasMetadataAndSize()
{
$p = new PumpStream(function () {
}, [
'metadata' => ['foo' => 'bar'],
'size' => 100
]);
self::assertSame('bar', $p->getMetadata('foo'));
self::assertSame(['foo' => 'bar'], $p->getMetadata());
self::assertSame(100, $p->getSize());
}
public function testCanReadFromCallable()
{
$p = Psr7\Utils::streamFor(function ($size) {
return 'a';
});
self::assertSame('a', $p->read(1));
self::assertSame(1, $p->tell());
self::assertSame('aaaaa', $p->read(5));
self::assertSame(6, $p->tell());
}
public function testStoresExcessDataInBuffer()
{
$called = [];
$p = Psr7\Utils::streamFor(function ($size) use (&$called) {
$called[] = $size;
return 'abcdef';
});
self::assertSame('a', $p->read(1));
self::assertSame('b', $p->read(1));
self::assertSame('cdef', $p->read(4));
self::assertSame('abcdefabc', $p->read(9));
self::assertSame([1, 9, 3], $called);
}
public function testInifiniteStreamWrappedInLimitStream()
{
$p = Psr7\Utils::streamFor(function () {
return 'a';
});
$s = new LimitStream($p, 5);
self::assertSame('aaaaa', (string) $s);
}
public function testDescribesCapabilities()
{
$p = Psr7\Utils::streamFor(function () {
});
self::assertTrue($p->isReadable());
self::assertFalse($p->isSeekable());
self::assertFalse($p->isWritable());
self::assertNull($p->getSize());
self::assertSame('', $p->getContents());
self::assertSame('', (string) $p);
$p->close();
self::assertSame('', $p->read(10));
self::assertTrue($p->eof());
try {
self::assertFalse($p->write('aa'));
self::fail();
} catch (\RuntimeException $e) {
}
}
}

View File

@ -0,0 +1,98 @@
<?php
namespace GuzzleHttp\Tests\Psr7;
use GuzzleHttp\Psr7;
class QueryTest extends BaseTest
{
public function parseQueryProvider()
{
return [
// Does not need to parse when the string is empty
['', []],
// Can parse mult-values items
['q=a&q=b', ['q' => ['a', 'b']]],
// Can parse multi-valued items that use numeric indices
['q[0]=a&q[1]=b', ['q[0]' => 'a', 'q[1]' => 'b']],
// Can parse duplicates and does not include numeric indices
['q[]=a&q[]=b', ['q[]' => ['a', 'b']]],
// Ensures that the value of "q" is an array even though one value
['q[]=a', ['q[]' => 'a']],
// Does not modify "." to "_" like PHP's parse_str()
['q.a=a&q.b=b', ['q.a' => 'a', 'q.b' => 'b']],
// Can decode %20 to " "
['q%20a=a%20b', ['q a' => 'a b']],
// Can parse funky strings with no values by assigning each to null
['q&a', ['q' => null, 'a' => null]],
// Does not strip trailing equal signs
['data=abc=', ['data' => 'abc=']],
// Can store duplicates without affecting other values
['foo=a&foo=b&?µ=c', ['foo' => ['a', 'b'], '?µ' => 'c']],
// Sets value to null when no "=" is present
['foo', ['foo' => null]],
// Preserves "0" keys.
['0', ['0' => null]],
// Sets the value to an empty string when "=" is present
['0=', ['0' => '']],
// Preserves falsey keys
['var=0', ['var' => '0']],
['a[b][c]=1&a[b][c]=2', ['a[b][c]' => ['1', '2']]],
['a[b]=c&a[d]=e', ['a[b]' => 'c', 'a[d]' => 'e']],
// Ensure it doesn't leave things behind with repeated values
// Can parse mult-values items
['q=a&q=b&q=c', ['q' => ['a', 'b', 'c']]],
];
}
/**
* @dataProvider parseQueryProvider
*/
public function testParsesQueries($input, $output)
{
$result = Psr7\Query::parse($input);
self::assertSame($output, $result);
}
public function testDoesNotDecode()
{
$str = 'foo%20=bar';
$data = Psr7\Query::parse($str, false);
self::assertSame(['foo%20' => 'bar'], $data);
}
/**
* @dataProvider parseQueryProvider
*/
public function testParsesAndBuildsQueries($input)
{
$result = Psr7\Query::parse($input, false);
self::assertSame($input, Psr7\Query::build($result, false));
}
public function testEncodesWithRfc1738()
{
$str = Psr7\Query::build(['foo bar' => 'baz+'], PHP_QUERY_RFC1738);
self::assertSame('foo+bar=baz%2B', $str);
}
public function testEncodesWithRfc3986()
{
$str = Psr7\Query::build(['foo bar' => 'baz+'], PHP_QUERY_RFC3986);
self::assertSame('foo%20bar=baz%2B', $str);
}
public function testDoesNotEncode()
{
$str = Psr7\Query::build(['foo bar' => 'baz+'], false);
self::assertSame('foo bar=baz+', $str);
}
public function testCanControlDecodingType()
{
$result = Psr7\Query::parse('var=foo+bar', PHP_QUERY_RFC3986);
self::assertSame('foo+bar', $result['var']);
$result = Psr7\Query::parse('var=foo+bar', PHP_QUERY_RFC1738);
self::assertSame('foo bar', $result['var']);
}
}

View File

@ -0,0 +1,23 @@
<?php
namespace GuzzleHttp\Tests\Psr7;
use GuzzleHttp\Psr7\Stream;
final class ReadSeekOnlyStream extends Stream
{
public function __construct()
{
parent::__construct(fopen('php://memory', 'wb'));
}
public function isSeekable()
{
return true;
}
public function isReadable()
{
return false;
}
}

View File

@ -0,0 +1,298 @@
<?php
namespace GuzzleHttp\Tests\Psr7;
use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Uri;
/**
* @covers GuzzleHttp\Psr7\MessageTrait
* @covers GuzzleHttp\Psr7\Request
*/
class RequestTest extends BaseTest
{
public function testRequestUriMayBeString()
{
$r = new Request('GET', '/');
self::assertSame('/', (string) $r->getUri());
}
public function testRequestUriMayBeUri()
{
$uri = new Uri('/');
$r = new Request('GET', $uri);
self::assertSame($uri, $r->getUri());
}
public function testValidateRequestUri()
{
$this->expectExceptionGuzzle('InvalidArgumentException');
new Request('GET', '///');
}
public function testCanConstructWithBody()
{
$r = new Request('GET', '/', [], 'baz');
self::assertInstanceOf('Psr\Http\Message\StreamInterface', $r->getBody());
self::assertSame('baz', (string) $r->getBody());
}
public function testNullBody()
{
$r = new Request('GET', '/', [], null);
self::assertInstanceOf('Psr\Http\Message\StreamInterface', $r->getBody());
self::assertSame('', (string) $r->getBody());
}
public function testFalseyBody()
{
$r = new Request('GET', '/', [], '0');
self::assertInstanceOf('Psr\Http\Message\StreamInterface', $r->getBody());
self::assertSame('0', (string) $r->getBody());
}
public function testConstructorDoesNotReadStreamBody()
{
$streamIsRead = false;
$body = Psr7\FnStream::decorate(Psr7\Utils::streamFor(''), [
'__toString' => function () use (&$streamIsRead) {
$streamIsRead = true;
return '';
}
]);
$r = new Request('GET', '/', [], $body);
self::assertFalse($streamIsRead);
self::assertSame($body, $r->getBody());
}
public function testCapitalizesMethod()
{
$r = new Request('get', '/');
self::assertSame('GET', $r->getMethod());
}
public function testCapitalizesWithMethod()
{
$r = new Request('GET', '/');
self::assertSame('PUT', $r->withMethod('put')->getMethod());
}
public function testWithUri()
{
$r1 = new Request('GET', '/');
$u1 = $r1->getUri();
$u2 = new Uri('http://www.example.com');
$r2 = $r1->withUri($u2);
self::assertNotSame($r1, $r2);
self::assertSame($u2, $r2->getUri());
self::assertSame($u1, $r1->getUri());
}
/**
* @dataProvider invalidMethodsProvider
*/
public function testConstructWithInvalidMethods($method)
{
$this->expectExceptionGuzzle('InvalidArgumentException');
new Request($method, '/');
}
/**
* @dataProvider invalidMethodsProvider
*/
public function testWithInvalidMethods($method)
{
$r = new Request('get', '/');
$this->expectExceptionGuzzle('InvalidArgumentException');
$r->withMethod($method);
}
public function invalidMethodsProvider()
{
return [
[null],
[false],
[['foo']],
[new \stdClass()],
];
}
public function testSameInstanceWhenSameUri()
{
$r1 = new Request('GET', 'http://foo.com');
$r2 = $r1->withUri($r1->getUri());
self::assertSame($r1, $r2);
}
public function testWithRequestTarget()
{
$r1 = new Request('GET', '/');
$r2 = $r1->withRequestTarget('*');
self::assertSame('*', $r2->getRequestTarget());
self::assertSame('/', $r1->getRequestTarget());
}
public function testRequestTargetDoesNotAllowSpaces()
{
$this->expectExceptionGuzzle('InvalidArgumentException');
$r1 = new Request('GET', '/');
$r1->withRequestTarget('/foo bar');
}
public function testRequestTargetDefaultsToSlash()
{
$r1 = new Request('GET', '');
self::assertSame('/', $r1->getRequestTarget());
$r2 = new Request('GET', '*');
self::assertSame('*', $r2->getRequestTarget());
$r3 = new Request('GET', 'http://foo.com/bar baz/');
self::assertSame('/bar%20baz/', $r3->getRequestTarget());
}
public function testBuildsRequestTarget()
{
$r1 = new Request('GET', 'http://foo.com/baz?bar=bam');
self::assertSame('/baz?bar=bam', $r1->getRequestTarget());
}
public function testBuildsRequestTargetWithFalseyQuery()
{
$r1 = new Request('GET', 'http://foo.com/baz?0');
self::assertSame('/baz?0', $r1->getRequestTarget());
}
public function testHostIsAddedFirst()
{
$r = new Request('GET', 'http://foo.com/baz?bar=bam', ['Foo' => 'Bar']);
self::assertSame([
'Host' => ['foo.com'],
'Foo' => ['Bar']
], $r->getHeaders());
}
public function testHeaderValueWithWhitespace()
{
$r = new Request('GET', 'https://example.com/', [
'User-Agent' => 'Linux f0f489981e90 5.10.104-linuxkit 1 SMP Wed Mar 9 19:05:23 UTC 2022 x86_64'
]);
self::assertSame([
'Host' => ['example.com'],
'User-Agent' => ['Linux f0f489981e90 5.10.104-linuxkit 1 SMP Wed Mar 9 19:05:23 UTC 2022 x86_64']
], $r->getHeaders());
}
public function testCanGetHeaderAsCsv()
{
$r = new Request('GET', 'http://foo.com/baz?bar=bam', [
'Foo' => ['a', 'b', 'c']
]);
self::assertSame('a, b, c', $r->getHeaderLine('Foo'));
self::assertSame('', $r->getHeaderLine('Bar'));
}
public function testHostIsNotOverwrittenWhenPreservingHost()
{
$r = new Request('GET', 'http://foo.com/baz?bar=bam', ['Host' => 'a.com']);
self::assertSame(['Host' => ['a.com']], $r->getHeaders());
$r2 = $r->withUri(new Uri('http://www.foo.com/bar'), true);
self::assertSame('a.com', $r2->getHeaderLine('Host'));
}
public function testWithUriSetsHostIfNotSet()
{
$r = (new Request('GET', 'http://foo.com/baz?bar=bam'))->withoutHeader('Host');
self::assertSame([], $r->getHeaders());
$r2 = $r->withUri(new Uri('http://www.baz.com/bar'), true);
self::assertSame('www.baz.com', $r2->getHeaderLine('Host'));
}
public function testOverridesHostWithUri()
{
$r = new Request('GET', 'http://foo.com/baz?bar=bam');
self::assertSame(['Host' => ['foo.com']], $r->getHeaders());
$r2 = $r->withUri(new Uri('http://www.baz.com/bar'));
self::assertSame('www.baz.com', $r2->getHeaderLine('Host'));
}
public function testAggregatesHeaders()
{
$r = new Request('GET', '', [
'ZOO' => 'zoobar',
'zoo' => ['foobar', 'zoobar']
]);
self::assertSame(['ZOO' => ['zoobar', 'foobar', 'zoobar']], $r->getHeaders());
self::assertSame('zoobar, foobar, zoobar', $r->getHeaderLine('zoo'));
}
public function testAddsPortToHeader()
{
$r = new Request('GET', 'http://foo.com:8124/bar');
self::assertSame('foo.com:8124', $r->getHeaderLine('host'));
}
public function testAddsPortToHeaderAndReplacePreviousPort()
{
$r = new Request('GET', 'http://foo.com:8124/bar');
$r = $r->withUri(new Uri('http://foo.com:8125/bar'));
self::assertSame('foo.com:8125', $r->getHeaderLine('host'));
}
/**
* @dataProvider provideHeaderValuesContainingNotAllowedChars
*/
public function testContainsNotAllowedCharsOnHeaderValue($value)
{
$this->expectExceptionGuzzle('InvalidArgumentException', sprintf('"%s" is not valid header value', $value));
$r = new Request(
'GET',
'http://foo.com/baz?bar=bam',
[
'testing' => $value
]
);
}
/**
* @return iterable
*/
public function provideHeaderValuesContainingNotAllowedChars()
{
// Explicit tests for newlines as the most common exploit vector.
$tests = [
["new\nline"],
["new\r\nline"],
["new\rline"],
// Line folding is technically allowed, but deprecated.
// We don't support it.
["new\r\n line"],
["newline\n"],
["\nnewline"],
["newline\r\n"],
["\r\nnewline"],
];
for ($i = 0; $i <= 0xff; $i++) {
if (\chr($i) == "\t") {
continue;
}
if (\chr($i) == " ") {
continue;
}
if ($i >= 0x21 && $i <= 0x7e) {
continue;
}
if ($i >= 0x80) {
continue;
}
$tests[] = ["foo" . \chr($i) . "bar"];
$tests[] = ["foo" . \chr($i)];
}
return $tests;
}
}

View File

@ -0,0 +1,384 @@
<?php
namespace GuzzleHttp\Tests\Psr7;
use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\Response;
/**
* @covers GuzzleHttp\Psr7\MessageTrait
* @covers GuzzleHttp\Psr7\Response
*/
class ResponseTest extends BaseTest
{
public function testDefaultConstructor()
{
$r = new Response();
self::assertSame(200, $r->getStatusCode());
self::assertSame('1.1', $r->getProtocolVersion());
self::assertSame('OK', $r->getReasonPhrase());
self::assertSame([], $r->getHeaders());
self::assertInstanceOf('Psr\Http\Message\StreamInterface', $r->getBody());
self::assertSame('', (string) $r->getBody());
}
public function testCanConstructWithStatusCode()
{
$r = new Response(404);
self::assertSame(404, $r->getStatusCode());
self::assertSame('Not Found', $r->getReasonPhrase());
}
public function testConstructorDoesNotReadStreamBody()
{
$streamIsRead = false;
$body = Psr7\FnStream::decorate(Psr7\Utils::streamFor(''), [
'__toString' => function () use (&$streamIsRead) {
$streamIsRead = true;
return '';
}
]);
$r = new Response(200, [], $body);
self::assertFalse($streamIsRead);
self::assertSame($body, $r->getBody());
}
public function testStatusCanBeNumericString()
{
$r = new Response('404');
$r2 = $r->withStatus('201');
self::assertSame(404, $r->getStatusCode());
self::assertSame('Not Found', $r->getReasonPhrase());
self::assertSame(201, $r2->getStatusCode());
self::assertSame('Created', $r2->getReasonPhrase());
}
public function testCanConstructWithHeaders()
{
$r = new Response(200, ['Foo' => 'Bar']);
self::assertSame(['Foo' => ['Bar']], $r->getHeaders());
self::assertSame('Bar', $r->getHeaderLine('Foo'));
self::assertSame(['Bar'], $r->getHeader('Foo'));
}
public function testCanConstructWithHeadersAsArray()
{
$r = new Response(200, [
'Foo' => ['baz', 'bar']
]);
self::assertSame(['Foo' => ['baz', 'bar']], $r->getHeaders());
self::assertSame('baz, bar', $r->getHeaderLine('Foo'));
self::assertSame(['baz', 'bar'], $r->getHeader('Foo'));
}
public function testCanConstructWithBody()
{
$r = new Response(200, [], 'baz');
self::assertInstanceOf('Psr\Http\Message\StreamInterface', $r->getBody());
self::assertSame('baz', (string) $r->getBody());
}
public function testNullBody()
{
$r = new Response(200, [], null);
self::assertInstanceOf('Psr\Http\Message\StreamInterface', $r->getBody());
self::assertSame('', (string) $r->getBody());
}
public function testFalseyBody()
{
$r = new Response(200, [], '0');
self::assertInstanceOf('Psr\Http\Message\StreamInterface', $r->getBody());
self::assertSame('0', (string) $r->getBody());
}
public function testCanConstructWithReason()
{
$r = new Response(200, [], null, '1.1', 'bar');
self::assertSame('bar', $r->getReasonPhrase());
$r = new Response(200, [], null, '1.1', '0');
self::assertSame('0', $r->getReasonPhrase(), 'Falsey reason works');
}
public function testCanConstructWithProtocolVersion()
{
$r = new Response(200, [], null, '1000');
self::assertSame('1000', $r->getProtocolVersion());
}
public function testWithStatusCodeAndNoReason()
{
$r = (new Response())->withStatus(201);
self::assertSame(201, $r->getStatusCode());
self::assertSame('Created', $r->getReasonPhrase());
}
public function testWithStatusCodeAndReason()
{
$r = (new Response())->withStatus(201, 'Foo');
self::assertSame(201, $r->getStatusCode());
self::assertSame('Foo', $r->getReasonPhrase());
$r = (new Response())->withStatus(201, '0');
self::assertSame(201, $r->getStatusCode());
self::assertSame('0', $r->getReasonPhrase(), 'Falsey reason works');
}
public function testWithProtocolVersion()
{
$r = (new Response())->withProtocolVersion('1000');
self::assertSame('1000', $r->getProtocolVersion());
}
public function testSameInstanceWhenSameProtocol()
{
$r = new Response();
self::assertSame($r, $r->withProtocolVersion('1.1'));
}
public function testWithBody()
{
$b = Psr7\Utils::streamFor('0');
$r = (new Response())->withBody($b);
self::assertInstanceOf('Psr\Http\Message\StreamInterface', $r->getBody());
self::assertSame('0', (string) $r->getBody());
}
public function testSameInstanceWhenSameBody()
{
$r = new Response();
$b = $r->getBody();
self::assertSame($r, $r->withBody($b));
}
public function testWithHeader()
{
$r = new Response(200, ['Foo' => 'Bar']);
$r2 = $r->withHeader('baZ', 'Bam');
self::assertSame(['Foo' => ['Bar']], $r->getHeaders());
self::assertSame(['Foo' => ['Bar'], 'baZ' => ['Bam']], $r2->getHeaders());
self::assertSame('Bam', $r2->getHeaderLine('baz'));
self::assertSame(['Bam'], $r2->getHeader('baz'));
}
public function testNumericHeaderValue()
{
$r = (new Response())->withHeader('Api-Version', 1);
self::assertSame(['Api-Version' => ['1']], $r->getHeaders());
}
public function testWithHeaderAsArray()
{
$r = new Response(200, ['Foo' => 'Bar']);
$r2 = $r->withHeader('baZ', ['Bam', 'Bar']);
self::assertSame(['Foo' => ['Bar']], $r->getHeaders());
self::assertSame(['Foo' => ['Bar'], 'baZ' => ['Bam', 'Bar']], $r2->getHeaders());
self::assertSame('Bam, Bar', $r2->getHeaderLine('baz'));
self::assertSame(['Bam', 'Bar'], $r2->getHeader('baz'));
}
public function testWithHeaderReplacesDifferentCase()
{
$r = new Response(200, ['Foo' => 'Bar']);
$r2 = $r->withHeader('foO', 'Bam');
self::assertSame(['Foo' => ['Bar']], $r->getHeaders());
self::assertSame(['foO' => ['Bam']], $r2->getHeaders());
self::assertSame('Bam', $r2->getHeaderLine('foo'));
self::assertSame(['Bam'], $r2->getHeader('foo'));
}
public function testWithAddedHeader()
{
$r = new Response(200, ['Foo' => 'Bar']);
$r2 = $r->withAddedHeader('foO', 'Baz');
self::assertSame(['Foo' => ['Bar']], $r->getHeaders());
self::assertSame(['Foo' => ['Bar', 'Baz']], $r2->getHeaders());
self::assertSame('Bar, Baz', $r2->getHeaderLine('foo'));
self::assertSame(['Bar', 'Baz'], $r2->getHeader('foo'));
}
public function testWithAddedHeaderAsArray()
{
$r = new Response(200, ['Foo' => 'Bar']);
$r2 = $r->withAddedHeader('foO', ['Baz', 'Bam']);
self::assertSame(['Foo' => ['Bar']], $r->getHeaders());
self::assertSame(['Foo' => ['Bar', 'Baz', 'Bam']], $r2->getHeaders());
self::assertSame('Bar, Baz, Bam', $r2->getHeaderLine('foo'));
self::assertSame(['Bar', 'Baz', 'Bam'], $r2->getHeader('foo'));
}
public function testWithAddedHeaderThatDoesNotExist()
{
$r = new Response(200, ['Foo' => 'Bar']);
$r2 = $r->withAddedHeader('nEw', 'Baz');
self::assertSame(['Foo' => ['Bar']], $r->getHeaders());
self::assertSame(['Foo' => ['Bar'], 'nEw' => ['Baz']], $r2->getHeaders());
self::assertSame('Baz', $r2->getHeaderLine('new'));
self::assertSame(['Baz'], $r2->getHeader('new'));
}
public function testWithoutHeaderThatExists()
{
$r = new Response(200, ['Foo' => 'Bar', 'Baz' => 'Bam']);
$r2 = $r->withoutHeader('foO');
self::assertTrue($r->hasHeader('foo'));
self::assertSame(['Foo' => ['Bar'], 'Baz' => ['Bam']], $r->getHeaders());
self::assertFalse($r2->hasHeader('foo'));
self::assertSame(['Baz' => ['Bam']], $r2->getHeaders());
}
public function testWithoutHeaderThatDoesNotExist()
{
$r = new Response(200, ['Baz' => 'Bam']);
$r2 = $r->withoutHeader('foO');
self::assertSame($r, $r2);
self::assertFalse($r2->hasHeader('foo'));
self::assertSame(['Baz' => ['Bam']], $r2->getHeaders());
}
public function testSameInstanceWhenRemovingMissingHeader()
{
$r = new Response();
self::assertSame($r, $r->withoutHeader('foo'));
}
public function testPassNumericHeaderNameInConstructor()
{
$r = new Response(200, ['Location' => 'foo', '123' => 'bar']);
self::assertSame('bar', $r->getHeaderLine('123'));
}
/**
* @dataProvider invalidHeaderProvider
*/
public function testConstructResponseInvalidHeader($header, $headerValue, $expectedMessage)
{
$this->expectExceptionGuzzle('InvalidArgumentException', $expectedMessage);
new Response(200, [$header => $headerValue]);
}
public function invalidHeaderProvider()
{
return [
['foo', [], 'Header value can not be an empty array.'],
['', '', 'Header name can not be empty.'],
['foo', new \stdClass(), 'Header value must be scalar or null but stdClass provided.'],
];
}
/**
* @dataProvider invalidWithHeaderProvider
*/
public function testWithInvalidHeader($header, $headerValue, $expectedMessage)
{
$r = new Response();
$this->expectExceptionGuzzle('InvalidArgumentException', $expectedMessage);
$r->withHeader($header, $headerValue);
}
public function invalidWithHeaderProvider()
{
return array_merge($this->invalidHeaderProvider(), [
[[], 'foo', 'Header name must be a string but array provided.'],
[false, 'foo', 'Header name must be a string but boolean provided.'],
[new \stdClass(), 'foo', 'Header name must be a string but stdClass provided.'],
["", 'foo', "Header name can not be empty."],
["Content-Type\r\n\r\n", 'foo', "\"Content-Type\r\n\r\n\" is not valid header name."],
["Content-Type\r\n", 'foo', "\"Content-Type\r\n\" is not valid header name."],
["Content-Type\n", 'foo', "\"Content-Type\n\" is not valid header name."],
["\r\nContent-Type", 'foo', "\"\r\nContent-Type\" is not valid header name."],
["\nContent-Type", 'foo', "\"\nContent-Type\" is not valid header name."],
["\n", 'foo', "\"\n\" is not valid header name."],
["\r\n", 'foo', "\"\r\n\" is not valid header name."],
["\t", 'foo', "\"\t\" is not valid header name."],
]);
}
public function testHeaderValuesAreTrimmed()
{
$r1 = new Response(200, ['OWS' => " \t \tFoo\t \t "]);
$r2 = (new Response())->withHeader('OWS', " \t \tFoo\t \t ");
$r3 = (new Response())->withAddedHeader('OWS', " \t \tFoo\t \t ");
foreach ([$r1, $r2, $r3] as $r) {
self::assertSame(['OWS' => ['Foo']], $r->getHeaders());
self::assertSame('Foo', $r->getHeaderLine('OWS'));
self::assertSame(['Foo'], $r->getHeader('OWS'));
}
}
public function testWithAddedHeaderArrayValueAndKeys()
{
$message = (new Response())->withAddedHeader('list', ['foo' => 'one']);
$message = $message->withAddedHeader('list', ['foo' => 'two', 'bar' => 'three']);
$headerLine = $message->getHeaderLine('list');
self::assertSame('one, two, three', $headerLine);
}
/**
* @dataProvider nonIntegerStatusCodeProvider
*
* @param mixed $invalidValues
*/
public function testConstructResponseWithNonIntegerStatusCode($invalidValues)
{
$this->expectExceptionGuzzle('InvalidArgumentException', 'Status code must be an integer value.');
new Response($invalidValues);
}
/**
* @dataProvider nonIntegerStatusCodeProvider
*
* @param mixed $invalidValues
*/
public function testResponseChangeStatusCodeWithNonInteger($invalidValues)
{
$response = new Response();
$this->expectExceptionGuzzle('InvalidArgumentException', 'Status code must be an integer value.');
$response->withStatus($invalidValues);
}
public function nonIntegerStatusCodeProvider()
{
return [
['whatever'],
['1.01'],
[1.01],
[new \stdClass()],
];
}
/**
* @dataProvider invalidStatusCodeRangeProvider
*
* @param mixed $invalidValues
*/
public function testConstructResponseWithInvalidRangeStatusCode($invalidValues)
{
$this->expectExceptionGuzzle('InvalidArgumentException', 'Status code must be an integer value between 1xx and 5xx.');
new Response($invalidValues);
}
/**
* @dataProvider invalidStatusCodeRangeProvider
*
* @param mixed $invalidValues
*/
public function testResponseChangeStatusCodeWithWithInvalidRange($invalidValues)
{
$response = new Response();
$this->expectExceptionGuzzle('InvalidArgumentException', 'Status code must be an integer value between 1xx and 5xx.');
$response->withStatus($invalidValues);
}
public function invalidStatusCodeRangeProvider()
{
return [
[600],
[99],
];
}
}

View File

@ -0,0 +1,544 @@
<?php
namespace GuzzleHttp\Tests\Psr7;
use GuzzleHttp\Psr7\ServerRequest;
use GuzzleHttp\Psr7\UploadedFile;
use GuzzleHttp\Psr7\Uri;
/**
* @covers GuzzleHttp\Psr7\ServerRequest
*/
class ServerRequestTest extends BaseTest
{
public function dataNormalizeFiles()
{
return [
'Single file' => [
[
'file' => [
'name' => 'MyFile.txt',
'type' => 'text/plain',
'tmp_name' => '/tmp/php/php1h4j1o',
'error' => '0',
'size' => '123'
]
],
[
'file' => new UploadedFile(
'/tmp/php/php1h4j1o',
123,
UPLOAD_ERR_OK,
'MyFile.txt',
'text/plain'
)
]
],
'Empty file' => [
[
'image_file' => [
'name' => '',
'type' => '',
'tmp_name' => '',
'error' => '4',
'size' => '0'
]
],
[
'image_file' => new UploadedFile(
'',
0,
UPLOAD_ERR_NO_FILE,
'',
''
)
]
],
'Already Converted' => [
[
'file' => new UploadedFile(
'/tmp/php/php1h4j1o',
123,
UPLOAD_ERR_OK,
'MyFile.txt',
'text/plain'
)
],
[
'file' => new UploadedFile(
'/tmp/php/php1h4j1o',
123,
UPLOAD_ERR_OK,
'MyFile.txt',
'text/plain'
)
]
],
'Already Converted array' => [
[
'file' => [
new UploadedFile(
'/tmp/php/php1h4j1o',
123,
UPLOAD_ERR_OK,
'MyFile.txt',
'text/plain'
),
new UploadedFile(
'',
0,
UPLOAD_ERR_NO_FILE,
'',
''
)
],
],
[
'file' => [
new UploadedFile(
'/tmp/php/php1h4j1o',
123,
UPLOAD_ERR_OK,
'MyFile.txt',
'text/plain'
),
new UploadedFile(
'',
0,
UPLOAD_ERR_NO_FILE,
'',
''
)
],
]
],
'Multiple files' => [
[
'text_file' => [
'name' => 'MyFile.txt',
'type' => 'text/plain',
'tmp_name' => '/tmp/php/php1h4j1o',
'error' => '0',
'size' => '123'
],
'image_file' => [
'name' => '',
'type' => '',
'tmp_name' => '',
'error' => '4',
'size' => '0'
]
],
[
'text_file' => new UploadedFile(
'/tmp/php/php1h4j1o',
123,
UPLOAD_ERR_OK,
'MyFile.txt',
'text/plain'
),
'image_file' => new UploadedFile(
'',
0,
UPLOAD_ERR_NO_FILE,
'',
''
)
]
],
'Nested files' => [
[
'file' => [
'name' => [
0 => 'MyFile.txt',
1 => 'Image.png',
],
'type' => [
0 => 'text/plain',
1 => 'image/png',
],
'tmp_name' => [
0 => '/tmp/php/hp9hskjhf',
1 => '/tmp/php/php1h4j1o',
],
'error' => [
0 => '0',
1 => '0',
],
'size' => [
0 => '123',
1 => '7349',
],
],
'nested' => [
'name' => [
'other' => 'Flag.txt',
'test' => [
0 => 'Stuff.txt',
1 => '',
],
],
'type' => [
'other' => 'text/plain',
'test' => [
0 => 'text/plain',
1 => '',
],
],
'tmp_name' => [
'other' => '/tmp/php/hp9hskjhf',
'test' => [
0 => '/tmp/php/asifu2gp3',
1 => '',
],
],
'error' => [
'other' => '0',
'test' => [
0 => '0',
1 => '4',
],
],
'size' => [
'other' => '421',
'test' => [
0 => '32',
1 => '0',
]
]
],
],
[
'file' => [
0 => new UploadedFile(
'/tmp/php/hp9hskjhf',
123,
UPLOAD_ERR_OK,
'MyFile.txt',
'text/plain'
),
1 => new UploadedFile(
'/tmp/php/php1h4j1o',
7349,
UPLOAD_ERR_OK,
'Image.png',
'image/png'
),
],
'nested' => [
'other' => new UploadedFile(
'/tmp/php/hp9hskjhf',
421,
UPLOAD_ERR_OK,
'Flag.txt',
'text/plain'
),
'test' => [
0 => new UploadedFile(
'/tmp/php/asifu2gp3',
32,
UPLOAD_ERR_OK,
'Stuff.txt',
'text/plain'
),
1 => new UploadedFile(
'',
0,
UPLOAD_ERR_NO_FILE,
'',
''
),
]
]
]
]
];
}
/**
* @dataProvider dataNormalizeFiles
*/
public function testNormalizeFiles($files, $expected)
{
$result = ServerRequest::normalizeFiles($files);
self::assertEquals($expected, $result);
}
public function testNormalizeFilesRaisesException()
{
$this->expectExceptionGuzzle('InvalidArgumentException', 'Invalid value in files specification');
ServerRequest::normalizeFiles(['test' => 'something']);
}
public function dataGetUriFromGlobals()
{
$server = [
'REQUEST_URI' => '/blog/article.php?id=10&user=foo',
'SERVER_PORT' => '443',
'SERVER_ADDR' => '217.112.82.20',
'SERVER_NAME' => 'www.example.org',
'SERVER_PROTOCOL' => 'HTTP/1.1',
'REQUEST_METHOD' => 'POST',
'QUERY_STRING' => 'id=10&user=foo',
'DOCUMENT_ROOT' => '/path/to/your/server/root/',
'HTTP_HOST' => 'www.example.org',
'HTTPS' => 'on',
'REMOTE_ADDR' => '193.60.168.69',
'REMOTE_PORT' => '5390',
'SCRIPT_NAME' => '/blog/article.php',
'SCRIPT_FILENAME' => '/path/to/your/server/root/blog/article.php',
'PHP_SELF' => '/blog/article.php',
];
return [
'HTTPS request' => [
'https://www.example.org/blog/article.php?id=10&user=foo',
$server,
],
'HTTPS request with different on value' => [
'https://www.example.org/blog/article.php?id=10&user=foo',
array_merge($server, ['HTTPS' => '1']),
],
'HTTP request' => [
'http://www.example.org/blog/article.php?id=10&user=foo',
array_merge($server, ['HTTPS' => 'off', 'SERVER_PORT' => '80']),
],
'HTTP_HOST missing -> fallback to SERVER_NAME' => [
'https://www.example.org/blog/article.php?id=10&user=foo',
array_merge($server, ['HTTP_HOST' => null]),
],
'HTTP_HOST and SERVER_NAME missing -> fallback to SERVER_ADDR' => [
'https://217.112.82.20/blog/article.php?id=10&user=foo',
array_merge($server, ['HTTP_HOST' => null, 'SERVER_NAME' => null]),
],
'Query string with ?' => [
'https://www.example.org/path?continue=https://example.com/path?param=1',
array_merge($server, ['REQUEST_URI' => '/path?continue=https://example.com/path?param=1', 'QUERY_STRING' => '']),
],
'No query String' => [
'https://www.example.org/blog/article.php',
array_merge($server, ['REQUEST_URI' => '/blog/article.php', 'QUERY_STRING' => '']),
],
'Host header with port' => [
'https://www.example.org:8324/blog/article.php?id=10&user=foo',
array_merge($server, ['HTTP_HOST' => 'www.example.org:8324']),
],
'IPv6 local loopback address' => [
'https://[::1]:8000/blog/article.php?id=10&user=foo',
array_merge($server, ['HTTP_HOST' => '[::1]:8000']),
],
'Invalid host' => [
'https://localhost/blog/article.php?id=10&user=foo',
array_merge($server, ['HTTP_HOST' => 'a:b']),
],
'Different port with SERVER_PORT' => [
'https://www.example.org:8324/blog/article.php?id=10&user=foo',
array_merge($server, ['SERVER_PORT' => '8324']),
],
'REQUEST_URI missing query string' => [
'https://www.example.org/blog/article.php?id=10&user=foo',
array_merge($server, ['REQUEST_URI' => '/blog/article.php']),
],
'Empty server variable' => [
'http://localhost',
[],
],
];
}
/**
* @dataProvider dataGetUriFromGlobals
*/
public function testGetUriFromGlobals($expected, $serverParams)
{
$_SERVER = $serverParams;
self::assertEquals(new Uri($expected), ServerRequest::getUriFromGlobals());
}
public function testFromGlobals()
{
$_SERVER = [
'REQUEST_URI' => '/blog/article.php?id=10&user=foo',
'SERVER_PORT' => '443',
'SERVER_ADDR' => '217.112.82.20',
'SERVER_NAME' => 'www.example.org',
'SERVER_PROTOCOL' => 'HTTP/1.1',
'REQUEST_METHOD' => 'POST',
'QUERY_STRING' => 'id=10&user=foo',
'DOCUMENT_ROOT' => '/path/to/your/server/root/',
'CONTENT_TYPE' => 'text/plain',
'HTTP_HOST' => 'www.example.org',
'HTTP_ACCEPT' => 'text/html',
'HTTP_REFERRER' => 'https://example.com',
'HTTP_USER_AGENT' => 'My User Agent',
'HTTPS' => 'on',
'REMOTE_ADDR' => '193.60.168.69',
'REMOTE_PORT' => '5390',
'SCRIPT_NAME' => '/blog/article.php',
'SCRIPT_FILENAME' => '/path/to/your/server/root/blog/article.php',
'PHP_SELF' => '/blog/article.php',
];
$_COOKIE = [
'logged-in' => 'yes!'
];
$_POST = [
'name' => 'Pesho',
'email' => 'pesho@example.com',
];
$_GET = [
'id' => 10,
'user' => 'foo',
];
$_FILES = [
'file' => [
'name' => 'MyFile.txt',
'type' => 'text/plain',
'tmp_name' => '/tmp/php/php1h4j1o',
'error' => UPLOAD_ERR_OK,
'size' => 123,
]
];
$server = ServerRequest::fromGlobals();
self::assertSame('POST', $server->getMethod());
self::assertEquals([
'Host' => ['www.example.org'],
'Content-Type' => ['text/plain'],
'Accept' => ['text/html'],
'Referrer' => ['https://example.com'],
'User-Agent' => ['My User Agent'],
], $server->getHeaders());
self::assertSame('', (string) $server->getBody());
self::assertSame('1.1', $server->getProtocolVersion());
self::assertSame($_COOKIE, $server->getCookieParams());
self::assertSame($_POST, $server->getParsedBody());
self::assertSame($_GET, $server->getQueryParams());
self::assertEquals(
new Uri('https://www.example.org/blog/article.php?id=10&user=foo'),
$server->getUri()
);
$expectedFiles = [
'file' => new UploadedFile(
'/tmp/php/php1h4j1o',
123,
UPLOAD_ERR_OK,
'MyFile.txt',
'text/plain'
),
];
self::assertEquals($expectedFiles, $server->getUploadedFiles());
}
public function testUploadedFiles()
{
$request1 = new ServerRequest('GET', '/');
$files = [
'file' => new UploadedFile('test', 123, UPLOAD_ERR_OK)
];
$request2 = $request1->withUploadedFiles($files);
self::assertNotSame($request2, $request1);
self::assertSame([], $request1->getUploadedFiles());
self::assertSame($files, $request2->getUploadedFiles());
}
public function testServerParams()
{
$params = ['name' => 'value'];
$request = new ServerRequest('GET', '/', [], null, '1.1', $params);
self::assertSame($params, $request->getServerParams());
}
public function testCookieParams()
{
$request1 = new ServerRequest('GET', '/');
$params = ['name' => 'value'];
$request2 = $request1->withCookieParams($params);
self::assertNotSame($request2, $request1);
self::assertEmpty($request1->getCookieParams());
self::assertSame($params, $request2->getCookieParams());
}
public function testQueryParams()
{
$request1 = new ServerRequest('GET', '/');
$params = ['name' => 'value'];
$request2 = $request1->withQueryParams($params);
self::assertNotSame($request2, $request1);
self::assertEmpty($request1->getQueryParams());
self::assertSame($params, $request2->getQueryParams());
}
public function testParsedBody()
{
$request1 = new ServerRequest('GET', '/');
$params = ['name' => 'value'];
$request2 = $request1->withParsedBody($params);
self::assertNotSame($request2, $request1);
self::assertEmpty($request1->getParsedBody());
self::assertSame($params, $request2->getParsedBody());
}
public function testAttributes()
{
$request1 = new ServerRequest('GET', '/');
$request2 = $request1->withAttribute('name', 'value');
$request3 = $request2->withAttribute('other', 'otherValue');
$request4 = $request3->withoutAttribute('other');
$request5 = $request3->withoutAttribute('unknown');
self::assertNotSame($request2, $request1);
self::assertNotSame($request3, $request2);
self::assertNotSame($request4, $request3);
self::assertSame($request5, $request3);
self::assertSame([], $request1->getAttributes());
self::assertNull($request1->getAttribute('name'));
self::assertSame(
'something',
$request1->getAttribute('name', 'something'),
'Should return the default value'
);
self::assertSame('value', $request2->getAttribute('name'));
self::assertSame(['name' => 'value'], $request2->getAttributes());
self::assertEquals(['name' => 'value', 'other' => 'otherValue'], $request3->getAttributes());
self::assertSame(['name' => 'value'], $request4->getAttributes());
}
public function testNullAttribute()
{
$request = (new ServerRequest('GET', '/'))->withAttribute('name', null);
self::assertSame(['name' => null], $request->getAttributes());
self::assertNull($request->getAttribute('name', 'different-default'));
$requestWithoutAttribute = $request->withoutAttribute('name');
self::assertSame([], $requestWithoutAttribute->getAttributes());
self::assertSame('different-default', $requestWithoutAttribute->getAttribute('name', 'different-default'));
}
}

View File

@ -0,0 +1,147 @@
<?php
namespace GuzzleHttp\Tests\Psr7;
use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\StreamDecoratorTrait;
use Psr\Http\Message\StreamInterface;
class Str implements StreamInterface
{
use StreamDecoratorTrait;
}
/**
* @covers GuzzleHttp\Psr7\StreamDecoratorTrait
*/
class StreamDecoratorTraitTest extends BaseTest
{
/** @var StreamInterface */
private $a;
/** @var StreamInterface */
private $b;
/** @var resource */
private $c;
/**
* @before
*/
public function setUpTest()
{
$this->c = fopen('php://temp', 'r+');
fwrite($this->c, 'foo');
fseek($this->c, 0);
$this->a = Psr7\Utils::streamFor($this->c);
$this->b = new Str($this->a);
}
public function testCatchesExceptionsWhenCastingToString()
{
$s = $this->getMockBuilder('Psr\Http\Message\StreamInterface')
->setMethods(['read'])
->getMockForAbstractClass();
$s->expects(self::once())
->method('read')
->will(self::throwException(new \Exception('foo')));
$msg = '';
set_error_handler(function ($errNo, $str) use (&$msg) {
$msg = $str;
});
echo new Str($s);
restore_error_handler();
$this->assertStringContainsStringGuzzle('foo', $msg);
}
public function testToString()
{
self::assertSame('foo', (string) $this->b);
}
public function testHasSize()
{
self::assertSame(3, $this->b->getSize());
}
public function testReads()
{
self::assertSame('foo', $this->b->read(10));
}
public function testCheckMethods()
{
self::assertSame($this->a->isReadable(), $this->b->isReadable());
self::assertSame($this->a->isWritable(), $this->b->isWritable());
self::assertSame($this->a->isSeekable(), $this->b->isSeekable());
}
public function testSeeksAndTells()
{
$this->b->seek(1);
self::assertSame(1, $this->a->tell());
self::assertSame(1, $this->b->tell());
$this->b->seek(0);
self::assertSame(0, $this->a->tell());
self::assertSame(0, $this->b->tell());
$this->b->seek(0, SEEK_END);
self::assertSame(3, $this->a->tell());
self::assertSame(3, $this->b->tell());
}
public function testGetsContents()
{
self::assertSame('foo', $this->b->getContents());
self::assertSame('', $this->b->getContents());
$this->b->seek(1);
self::assertSame('oo', $this->b->getContents());
}
public function testCloses()
{
$this->b->close();
self::assertFalse(is_resource($this->c));
}
public function testDetaches()
{
$this->b->detach();
self::assertFalse($this->b->isReadable());
}
public function testWrapsMetadata()
{
self::assertSame($this->b->getMetadata(), $this->a->getMetadata());
self::assertSame($this->b->getMetadata('uri'), $this->a->getMetadata('uri'));
}
public function testWrapsWrites()
{
$this->b->seek(0, SEEK_END);
$this->b->write('foo');
self::assertSame('foofoo', (string) $this->a);
}
public function testThrowsWithInvalidGetter()
{
$this->expectExceptionGuzzle('UnexpectedValueException');
$this->b->foo;
}
public function testThrowsWhenGetterNotImplemented()
{
$s = new BadStream();
$this->expectExceptionGuzzle('BadMethodCallException');
$s->stream;
}
}
class BadStream
{
use StreamDecoratorTrait;
public function __construct()
{
}
}

View File

@ -0,0 +1,403 @@
<?php
namespace GuzzleHttp\Tests\Psr7;
use GuzzleHttp\Psr7\Stream;
/**
* @covers GuzzleHttp\Psr7\Stream
*/
class StreamTest extends BaseTest
{
public static $isFReadError = false;
public function testConstructorThrowsExceptionOnInvalidArgument()
{
$this->expectExceptionGuzzle('InvalidArgumentException');
new Stream(true);
}
public function testConstructorInitializesProperties()
{
$handle = fopen('php://temp', 'r+');
fwrite($handle, 'data');
$stream = new Stream($handle);
self::assertTrue($stream->isReadable());
self::assertTrue($stream->isWritable());
self::assertTrue($stream->isSeekable());
self::assertSame('php://temp', $stream->getMetadata('uri'));
$this->assertInternalTypeGuzzle('array', $stream->getMetadata());
self::assertSame(4, $stream->getSize());
self::assertFalse($stream->eof());
$stream->close();
}
public function testConstructorInitializesPropertiesWithRbPlus()
{
$handle = fopen('php://temp', 'rb+');
fwrite($handle, 'data');
$stream = new Stream($handle);
self::assertTrue($stream->isReadable());
self::assertTrue($stream->isWritable());
self::assertTrue($stream->isSeekable());
self::assertSame('php://temp', $stream->getMetadata('uri'));
$this->assertInternalTypeGuzzle('array', $stream->getMetadata());
self::assertSame(4, $stream->getSize());
self::assertFalse($stream->eof());
$stream->close();
}
public function testStreamClosesHandleOnDestruct()
{
$handle = fopen('php://temp', 'r');
$stream = new Stream($handle);
unset($stream);
self::assertFalse(is_resource($handle));
}
public function testConvertsToString()
{
$handle = fopen('php://temp', 'w+');
fwrite($handle, 'data');
$stream = new Stream($handle);
self::assertSame('data', (string) $stream);
self::assertSame('data', (string) $stream);
$stream->close();
}
public function testConvertsToStringNonSeekableStream()
{
if (defined('HHVM_VERSION')) {
self::markTestSkipped('This does not work on HHVM.');
}
$handle = popen('echo foo', 'r');
$stream = new Stream($handle);
self::assertFalse($stream->isSeekable());
self::assertSame('foo', trim((string) $stream));
}
public function testConvertsToStringNonSeekablePartiallyReadStream()
{
if (defined('HHVM_VERSION')) {
self::markTestSkipped('This does not work on HHVM.');
}
$handle = popen('echo bar', 'r');
$stream = new Stream($handle);
$firstLetter = $stream->read(1);
self::assertFalse($stream->isSeekable());
self::assertSame('b', $firstLetter);
self::assertSame('ar', trim((string) $stream));
}
public function testGetsContents()
{
$handle = fopen('php://temp', 'w+');
fwrite($handle, 'data');
$stream = new Stream($handle);
self::assertSame('', $stream->getContents());
$stream->seek(0);
self::assertSame('data', $stream->getContents());
self::assertSame('', $stream->getContents());
$stream->close();
}
public function testChecksEof()
{
$handle = fopen('php://temp', 'w+');
fwrite($handle, 'data');
$stream = new Stream($handle);
self::assertSame(4, $stream->tell(), 'Stream cursor already at the end');
self::assertFalse($stream->eof(), 'Stream still not eof');
self::assertSame('', $stream->read(1), 'Need to read one more byte to reach eof');
self::assertTrue($stream->eof());
$stream->close();
}
public function testGetSize()
{
$size = filesize(__FILE__);
$handle = fopen(__FILE__, 'r');
$stream = new Stream($handle);
self::assertSame($size, $stream->getSize());
// Load from cache
self::assertSame($size, $stream->getSize());
$stream->close();
}
public function testEnsuresSizeIsConsistent()
{
$h = fopen('php://temp', 'w+');
self::assertSame(3, fwrite($h, 'foo'));
$stream = new Stream($h);
self::assertSame(3, $stream->getSize());
self::assertSame(4, $stream->write('test'));
self::assertSame(7, $stream->getSize());
self::assertSame(7, $stream->getSize());
$stream->close();
}
public function testProvidesStreamPosition()
{
$handle = fopen('php://temp', 'w+');
$stream = new Stream($handle);
self::assertSame(0, $stream->tell());
$stream->write('foo');
self::assertSame(3, $stream->tell());
$stream->seek(1);
self::assertSame(1, $stream->tell());
self::assertSame(ftell($handle), $stream->tell());
$stream->close();
}
public function testDetachStreamAndClearProperties()
{
$handle = fopen('php://temp', 'r');
$stream = new Stream($handle);
self::assertSame($handle, $stream->detach());
$this->assertInternalTypeGuzzle('resource', $handle, 'Stream is not closed');
self::assertNull($stream->detach());
$this->assertStreamStateAfterClosedOrDetached($stream);
$stream->close();
}
public function testCloseResourceAndClearProperties()
{
$handle = fopen('php://temp', 'r');
$stream = new Stream($handle);
$stream->close();
self::assertFalse(is_resource($handle));
$this->assertStreamStateAfterClosedOrDetached($stream);
}
private function assertStreamStateAfterClosedOrDetached(Stream $stream)
{
self::assertFalse($stream->isReadable());
self::assertFalse($stream->isWritable());
self::assertFalse($stream->isSeekable());
self::assertNull($stream->getSize());
self::assertSame([], $stream->getMetadata());
self::assertNull($stream->getMetadata('foo'));
$throws = function (callable $fn) {
try {
$fn();
} catch (\Exception $e) {
$this->assertStringContainsStringGuzzle('Stream is detached', $e->getMessage());
return;
}
$this->fail('Exception should be thrown after the stream is detached.');
};
$throws(function () use ($stream) {
$stream->read(10);
});
$throws(function () use ($stream) {
$stream->write('bar');
});
$throws(function () use ($stream) {
$stream->seek(10);
});
$throws(function () use ($stream) {
$stream->tell();
});
$throws(function () use ($stream) {
$stream->eof();
});
$throws(function () use ($stream) {
$stream->getContents();
});
self::assertSame('', (string) $stream);
}
public function testStreamReadingWithZeroLength()
{
$r = fopen('php://temp', 'r');
$stream = new Stream($r);
self::assertSame('', $stream->read(0));
$stream->close();
}
public function testStreamReadingWithNegativeLength()
{
$r = fopen('php://temp', 'r');
$stream = new Stream($r);
$this->expectExceptionGuzzle('RuntimeException', 'Length parameter cannot be negative');
try {
$stream->read(-1);
} catch (\Exception $e) {
$stream->close();
throw $e;
}
$stream->close();
}
public function testStreamReadingFreadError()
{
self::$isFReadError = true;
$r = fopen('php://temp', 'r');
$stream = new Stream($r);
$this->expectExceptionGuzzle('RuntimeException', 'Unable to read from stream');
try {
$stream->read(1);
} catch (\Exception $e) {
self::$isFReadError = false;
$stream->close();
throw $e;
}
self::$isFReadError = false;
$stream->close();
}
/**
* @dataProvider gzipModeProvider
*
* @param string $mode
* @param bool $readable
* @param bool $writable
*/
public function testGzipStreamModes($mode, $readable, $writable)
{
if (defined('HHVM_VERSION')) {
self::markTestSkipped('This does not work on HHVM.');
}
$r = gzopen('php://temp', $mode);
$stream = new Stream($r);
self::assertSame($readable, $stream->isReadable());
self::assertSame($writable, $stream->isWritable());
$stream->close();
}
public function gzipModeProvider()
{
return [
['mode' => 'rb9', 'readable' => true, 'writable' => false],
['mode' => 'wb2', 'readable' => false, 'writable' => true],
];
}
/**
* @dataProvider readableModeProvider
*
* @param string $mode
*/
public function testReadableStream($mode)
{
$r = fopen('php://temp', $mode);
$stream = new Stream($r);
self::assertTrue($stream->isReadable());
$stream->close();
}
public function readableModeProvider()
{
return [
['r'],
['w+'],
['r+'],
['x+'],
['c+'],
['rb'],
['w+b'],
['r+b'],
['x+b'],
['c+b'],
['rt'],
['w+t'],
['r+t'],
['x+t'],
['c+t'],
['a+'],
['rb+'],
];
}
public function testWriteOnlyStreamIsNotReadable()
{
$r = fopen('php://output', 'w');
$stream = new Stream($r);
self::assertFalse($stream->isReadable());
$stream->close();
}
/**
* @dataProvider writableModeProvider
*
* @param string $mode
*/
public function testWritableStream($mode)
{
$r = fopen('php://temp', $mode);
$stream = new Stream($r);
self::assertTrue($stream->isWritable());
$stream->close();
}
public function writableModeProvider()
{
return [
['w'],
['w+'],
['rw'],
['r+'],
['x+'],
['c+'],
['wb'],
['w+b'],
['r+b'],
['rb+'],
['x+b'],
['c+b'],
['w+t'],
['r+t'],
['x+t'],
['c+t'],
['a'],
['a+'],
];
}
public function testReadOnlyStreamIsNotWritable()
{
$r = fopen('php://input', 'r');
$stream = new Stream($r);
self::assertFalse($stream->isWritable());
$stream->close();
}
}
namespace GuzzleHttp\Psr7;
use GuzzleHttp\Tests\Psr7\StreamTest;
function fread($handle, $length)
{
return StreamTest::$isFReadError ? false : \fread($handle, $length);
}

View File

@ -0,0 +1,200 @@
<?php
namespace GuzzleHttp\Tests\Psr7;
use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\StreamWrapper;
/**
* @covers GuzzleHttp\Psr7\StreamWrapper
*/
class StreamWrapperTest extends BaseTest
{
public function testResource()
{
$stream = Psr7\Utils::streamFor('foo');
$handle = StreamWrapper::getResource($stream);
self::assertSame('foo', fread($handle, 3));
self::assertSame(3, ftell($handle));
self::assertSame(3, fwrite($handle, 'bar'));
self::assertSame(0, fseek($handle, 0));
self::assertSame('foobar', fread($handle, 6));
self::assertSame('', fread($handle, 1));
self::assertTrue(feof($handle));
$stBlksize = defined('PHP_WINDOWS_VERSION_BUILD') ? -1 : 0;
// This fails on HHVM for some reason
if (!defined('HHVM_VERSION')) {
self::assertSame([
0 => 0,
1 => 0,
2 => 33206,
3 => 0,
4 => 0,
5 => 0,
6 => 0,
7 => 6,
8 => 0,
9 => 0,
10 => 0,
11 => $stBlksize,
12 => $stBlksize,
'dev' => 0,
'ino' => 0,
'mode' => 33206,
'nlink' => 0,
'uid' => 0,
'gid' => 0,
'rdev' => 0,
'size' => 6,
'atime' => 0,
'mtime' => 0,
'ctime' => 0,
'blksize' => $stBlksize,
'blocks' => $stBlksize,
], fstat($handle));
}
self::assertTrue(fclose($handle));
self::assertSame('foobar', (string) $stream);
}
public function testStreamContext()
{
$stream = Psr7\Utils::streamFor('foo');
self::assertSame('foo', file_get_contents('guzzle://stream', false, StreamWrapper::createStreamContext($stream)));
}
public function testStreamCast()
{
$streams = [
StreamWrapper::getResource(Psr7\Utils::streamFor('foo')),
StreamWrapper::getResource(Psr7\Utils::streamFor('bar'))
];
$write = null;
$except = null;
$this->assertInternalTypeGuzzle('integer', stream_select($streams, $write, $except, 0));
}
public function testValidatesStream()
{
$stream = $this->getMockBuilder('Psr\Http\Message\StreamInterface')
->setMethods(['isReadable', 'isWritable'])
->getMockForAbstractClass();
$stream->expects(self::once())
->method('isReadable')
->will(self::returnValue(false));
$stream->expects(self::once())
->method('isWritable')
->will(self::returnValue(false));
$this->expectExceptionGuzzle('InvalidArgumentException');
StreamWrapper::getResource($stream);
}
public function testReturnsFalseWhenStreamDoesNotExist()
{
$this->expectWarningGuzzle();
fopen('guzzle://foo', 'r');
}
public function testCanOpenReadonlyStream()
{
$stream = $this->getMockBuilder('Psr\Http\Message\StreamInterface')
->setMethods(['isReadable', 'isWritable'])
->getMockForAbstractClass();
$stream->expects(self::once())
->method('isReadable')
->will(self::returnValue(false));
$stream->expects(self::once())
->method('isWritable')
->will(self::returnValue(true));
$r = StreamWrapper::getResource($stream);
$this->assertInternalTypeGuzzle('resource', $r);
fclose($r);
}
public function testUrlStat()
{
StreamWrapper::register();
$stBlksize = defined('PHP_WINDOWS_VERSION_BUILD') ? -1 : 0;
self::assertSame([
0 => 0,
1 => 0,
2 => 0,
3 => 0,
4 => 0,
5 => 0,
6 => 0,
7 => 0,
8 => 0,
9 => 0,
10 => 0,
11 => $stBlksize,
12 => $stBlksize,
'dev' => 0,
'ino' => 0,
'mode' => 0,
'nlink' => 0,
'uid' => 0,
'gid' => 0,
'rdev' => 0,
'size' => 0,
'atime' => 0,
'mtime' => 0,
'ctime' => 0,
'blksize' => $stBlksize,
'blocks' => $stBlksize,
], stat('guzzle://stream'));
}
public function testXmlReaderWithStream()
{
if (!class_exists('XMLReader')) {
self::markTestSkipped('XML Reader is not available.');
}
if (defined('HHVM_VERSION')) {
self::markTestSkipped('This does not work on HHVM.');
}
$stream = Psr7\Utils::streamFor('<?xml version="1.0" encoding="utf-8"?><foo />');
StreamWrapper::register();
libxml_set_streams_context(StreamWrapper::createStreamContext($stream));
$reader = new \XMLReader();
self::assertTrue($reader->open('guzzle://stream'));
self::assertTrue($reader->read());
self::assertSame('foo', $reader->name);
}
public function testXmlWriterWithStream()
{
if (!class_exists('XMLWriter')) {
self::markTestSkipped('XML Writer is not available.');
}
if (defined('HHVM_VERSION')) {
self::markTestSkipped('This does not work on HHVM.');
}
$stream = Psr7\Utils::streamFor(fopen('php://memory', 'wb'));
StreamWrapper::register();
libxml_set_streams_context(StreamWrapper::createStreamContext($stream));
$writer = new \XMLWriter();
self::assertTrue($writer->openURI('guzzle://stream'));
self::assertTrue($writer->startDocument());
self::assertTrue($writer->writeElement('foo'));
self::assertTrue($writer->endDocument());
$stream->rewind();
self::assertXmlStringEqualsXmlString('<?xml version="1.0"?><foo />', (string) $stream);
}
}

View File

@ -0,0 +1,287 @@
<?php
namespace GuzzleHttp\Tests\Psr7;
use GuzzleHttp\Psr7\Stream;
use GuzzleHttp\Psr7\UploadedFile;
use ReflectionProperty;
/**
* @covers GuzzleHttp\Psr7\UploadedFile
*/
class UploadedFileTest extends BaseTest
{
private $cleanup;
/**
* @before
*/
public function setUpTest()
{
$this->cleanup = [];
}
/**
* @after
*/
public function tearDownTest()
{
foreach ($this->cleanup as $file) {
if (is_scalar($file) && file_exists($file)) {
unlink($file);
}
}
}
public function invalidStreams()
{
return [
'null' => [null],
'true' => [true],
'false' => [false],
'int' => [1],
'float' => [1.1],
'array' => [['filename']],
'object' => [(object) ['filename']],
];
}
/**
* @dataProvider invalidStreams
*/
public function testRaisesExceptionOnInvalidStreamOrFile($streamOrFile)
{
$this->expectExceptionGuzzle('InvalidArgumentException');
new UploadedFile($streamOrFile, 0, UPLOAD_ERR_OK);
}
public function invalidSizes()
{
return [
'null' => [null],
'float' => [1.1],
'array' => [[1]],
'object' => [(object) [1]],
];
}
/**
* @dataProvider invalidSizes
*/
public function testRaisesExceptionOnInvalidSize($size)
{
$this->expectExceptionGuzzle('InvalidArgumentException', 'size');
new UploadedFile(fopen('php://temp', 'wb+'), $size, UPLOAD_ERR_OK);
}
public function invalidErrorStatuses()
{
return [
'null' => [null],
'true' => [true],
'false' => [false],
'float' => [1.1],
'string' => ['1'],
'array' => [[1]],
'object' => [(object) [1]],
'negative' => [-1],
'too-big' => [9],
];
}
/**
* @dataProvider invalidErrorStatuses
*/
public function testRaisesExceptionOnInvalidErrorStatus($status)
{
$this->expectExceptionGuzzle('InvalidArgumentException', 'status');
new UploadedFile(fopen('php://temp', 'wb+'), 0, $status);
}
public function invalidFilenamesAndMediaTypes()
{
return [
'true' => [true],
'false' => [false],
'int' => [1],
'float' => [1.1],
'array' => [['string']],
'object' => [(object) ['string']],
];
}
/**
* @dataProvider invalidFilenamesAndMediaTypes
*/
public function testRaisesExceptionOnInvalidClientFilename($filename)
{
$this->expectExceptionGuzzle('InvalidArgumentException', 'filename');
new UploadedFile(fopen('php://temp', 'wb+'), 0, UPLOAD_ERR_OK, $filename);
}
/**
* @dataProvider invalidFilenamesAndMediaTypes
*/
public function testRaisesExceptionOnInvalidClientMediaType($mediaType)
{
$this->expectExceptionGuzzle('InvalidArgumentException', 'media type');
new UploadedFile(fopen('php://temp', 'wb+'), 0, UPLOAD_ERR_OK, 'foobar.baz', $mediaType);
}
public function testGetStreamReturnsOriginalStreamObject()
{
$stream = new Stream(fopen('php://temp', 'r'));
$upload = new UploadedFile($stream, 0, UPLOAD_ERR_OK);
self::assertSame($stream, $upload->getStream());
}
public function testGetStreamReturnsWrappedPhpStream()
{
$stream = fopen('php://temp', 'wb+');
$upload = new UploadedFile($stream, 0, UPLOAD_ERR_OK);
$uploadStream = $upload->getStream()->detach();
self::assertSame($stream, $uploadStream);
}
public function testGetStreamReturnsStreamForFile()
{
$this->cleanup[] = $stream = tempnam(sys_get_temp_dir(), 'stream_file');
$upload = new UploadedFile($stream, 0, UPLOAD_ERR_OK);
$uploadStream = $upload->getStream();
$r = new ReflectionProperty($uploadStream, 'filename');
$r->setAccessible(true);
self::assertSame($stream, $r->getValue($uploadStream));
}
public function testSuccessful()
{
$stream = \GuzzleHttp\Psr7\Utils::streamFor('Foo bar!');
$upload = new UploadedFile($stream, $stream->getSize(), UPLOAD_ERR_OK, 'filename.txt', 'text/plain');
self::assertSame($stream->getSize(), $upload->getSize());
self::assertSame('filename.txt', $upload->getClientFilename());
self::assertSame('text/plain', $upload->getClientMediaType());
$this->cleanup[] = $to = tempnam(sys_get_temp_dir(), 'successful');
$upload->moveTo($to);
self::assertFileExists($to);
self::assertSame($stream->__toString(), file_get_contents($to));
}
public function invalidMovePaths()
{
return [
'null' => [null],
'true' => [true],
'false' => [false],
'int' => [1],
'float' => [1.1],
'empty' => [''],
'array' => [['filename']],
'object' => [(object) ['filename']],
];
}
/**
* @dataProvider invalidMovePaths
*/
public function testMoveRaisesExceptionForInvalidPath($path)
{
$stream = \GuzzleHttp\Psr7\Utils::streamFor('Foo bar!');
$upload = new UploadedFile($stream, 0, UPLOAD_ERR_OK);
$this->cleanup[] = $path;
$this->expectExceptionGuzzle('InvalidArgumentException', 'path');
$upload->moveTo($path);
}
public function testMoveCannotBeCalledMoreThanOnce()
{
$stream = \GuzzleHttp\Psr7\Utils::streamFor('Foo bar!');
$upload = new UploadedFile($stream, 0, UPLOAD_ERR_OK);
$this->cleanup[] = $to = tempnam(sys_get_temp_dir(), 'diac');
$upload->moveTo($to);
self::assertFileExists($to);
$this->expectExceptionGuzzle('RuntimeException', 'moved');
$upload->moveTo($to);
}
public function testCannotRetrieveStreamAfterMove()
{
$stream = \GuzzleHttp\Psr7\Utils::streamFor('Foo bar!');
$upload = new UploadedFile($stream, 0, UPLOAD_ERR_OK);
$this->cleanup[] = $to = tempnam(sys_get_temp_dir(), 'diac');
$upload->moveTo($to);
self::assertFileExists($to);
$this->expectExceptionGuzzle('RuntimeException', 'moved');
$upload->getStream();
}
public function nonOkErrorStatus()
{
return [
'UPLOAD_ERR_INI_SIZE' => [ UPLOAD_ERR_INI_SIZE ],
'UPLOAD_ERR_FORM_SIZE' => [ UPLOAD_ERR_FORM_SIZE ],
'UPLOAD_ERR_PARTIAL' => [ UPLOAD_ERR_PARTIAL ],
'UPLOAD_ERR_NO_FILE' => [ UPLOAD_ERR_NO_FILE ],
'UPLOAD_ERR_NO_TMP_DIR' => [ UPLOAD_ERR_NO_TMP_DIR ],
'UPLOAD_ERR_CANT_WRITE' => [ UPLOAD_ERR_CANT_WRITE ],
'UPLOAD_ERR_EXTENSION' => [ UPLOAD_ERR_EXTENSION ],
];
}
/**
* @dataProvider nonOkErrorStatus
*/
public function testConstructorDoesNotRaiseExceptionForInvalidStreamWhenErrorStatusPresent($status)
{
$uploadedFile = new UploadedFile('not ok', 0, $status);
self::assertSame($status, $uploadedFile->getError());
}
/**
* @dataProvider nonOkErrorStatus
*/
public function testMoveToRaisesExceptionWhenErrorStatusPresent($status)
{
$uploadedFile = new UploadedFile('not ok', 0, $status);
$this->expectExceptionGuzzle('RuntimeException', 'upload error');
$uploadedFile->moveTo(__DIR__ . '/' . sha1(uniqid('', true)));
}
/**
* @dataProvider nonOkErrorStatus
*/
public function testGetStreamRaisesExceptionWhenErrorStatusPresent($status)
{
$uploadedFile = new UploadedFile('not ok', 0, $status);
$this->expectExceptionGuzzle('RuntimeException', 'upload error');
$uploadedFile->getStream();
}
public function testMoveToCreatesStreamIfOnlyAFilenameWasProvided()
{
$this->cleanup[] = $from = tempnam(sys_get_temp_dir(), 'copy_from');
$this->cleanup[] = $to = tempnam(sys_get_temp_dir(), 'copy_to');
copy(__FILE__, $from);
$uploadedFile = new UploadedFile($from, 100, UPLOAD_ERR_OK, basename($from), 'text/plain');
$uploadedFile->moveTo($to);
self::assertFileEquals(__FILE__, $to);
}
}

View File

@ -0,0 +1,42 @@
<?php
namespace GuzzleHttp\Tests\Psr7;
use GuzzleHttp\Psr7\Uri;
use GuzzleHttp\Psr7\UriComparator;
/**
* @covers GuzzleHttp\Psr7\UriComparator
*/
class UriComparatorTest extends BaseTest
{
/**
* @dataProvider getCrossOriginExamples
*/
public function testIsCrossOrigin($originalUri, $modifiedUri, $expected)
{
self::assertSame($expected, UriComparator::isCrossOrigin(new Uri($originalUri), new Uri($modifiedUri)));
}
public function getCrossOriginExamples()
{
return [
['http://example.com/123', 'http://example.com/', false],
['http://example.com/123', 'http://example.com:80/', false],
['http://example.com:80/123', 'http://example.com/', false],
['http://example.com:80/123', 'http://example.com:80/', false],
['http://example.com/123', 'https://example.com/', true],
['http://example.com/123', 'http://www.example.com/', true],
['http://example.com/123', 'http://example.com:81/', true],
['http://example.com:80/123', 'http://example.com:81/', true],
['https://example.com/123', 'https://example.com/', false],
['https://example.com/123', 'https://example.com:443/', false],
['https://example.com:443/123', 'https://example.com/', false],
['https://example.com:443/123', 'https://example.com:443/', false],
['https://example.com/123', 'http://example.com/', true],
['https://example.com/123', 'https://www.example.com/', true],
['https://example.com/123', 'https://example.com:444/', true],
['https://example.com:443/123', 'https://example.com:444/', true],
];
}
}

View File

@ -0,0 +1,176 @@
<?php
namespace GuzzleHttp\Tests\Psr7;
use GuzzleHttp\Psr7\Uri;
use GuzzleHttp\Psr7\UriNormalizer;
/**
* @covers GuzzleHttp\Psr7\UriNormalizer
*/
class UriNormalizerTest extends BaseTest
{
public function testCapitalizePercentEncoding()
{
$actualEncoding = 'a%c2%7A%5eb%25%fa%fA%Fa';
$expectEncoding = 'a%C2%7A%5Eb%25%FA%FA%FA';
$uri = (new Uri())->withPath("/$actualEncoding")->withQuery($actualEncoding);
self::assertSame("/$actualEncoding?$actualEncoding", (string) $uri, 'Not normalized automatically beforehand');
$normalizedUri = UriNormalizer::normalize($uri, UriNormalizer::CAPITALIZE_PERCENT_ENCODING);
self::assertInstanceOf('Psr\Http\Message\UriInterface', $normalizedUri);
self::assertSame("/$expectEncoding?$expectEncoding", (string) $normalizedUri);
}
/**
* @dataProvider getUnreservedCharacters
*/
public function testDecodeUnreservedCharacters($char)
{
$percentEncoded = '%' . bin2hex($char);
// Add encoded reserved characters to test that those are not decoded and include the percent-encoded
// unreserved character both in lower and upper case to test the decoding is case-insensitive.
$encodedChars = $percentEncoded . '%2F%5B' . strtoupper($percentEncoded);
$uri = (new Uri())->withPath("/$encodedChars")->withQuery($encodedChars);
self::assertSame("/$encodedChars?$encodedChars", (string) $uri, 'Not normalized automatically beforehand');
$normalizedUri = UriNormalizer::normalize($uri, UriNormalizer::DECODE_UNRESERVED_CHARACTERS);
self::assertInstanceOf('Psr\Http\Message\UriInterface', $normalizedUri);
self::assertSame("/$char%2F%5B$char?$char%2F%5B$char", (string) $normalizedUri);
}
public function getUnreservedCharacters()
{
$unreservedChars = array_merge(range('a', 'z'), range('A', 'Z'), range('0', '9'), ['-', '.', '_', '~']);
return array_map(function ($char) {
return [$char];
}, $unreservedChars);
}
/**
* @dataProvider getEmptyPathTestCases
*/
public function testConvertEmptyPath($uri, $expected)
{
$normalizedUri = UriNormalizer::normalize(new Uri($uri), UriNormalizer::CONVERT_EMPTY_PATH);
self::assertInstanceOf('Psr\Http\Message\UriInterface', $normalizedUri);
self::assertSame($expected, (string) $normalizedUri);
}
public function getEmptyPathTestCases()
{
return [
['http://example.org', 'http://example.org/'],
['https://example.org', 'https://example.org/'],
['urn://example.org', 'urn://example.org'],
];
}
public function testRemoveDefaultHost()
{
$uri = new Uri('file://localhost/myfile');
$normalizedUri = UriNormalizer::normalize($uri, UriNormalizer::REMOVE_DEFAULT_HOST);
self::assertInstanceOf('Psr\Http\Message\UriInterface', $normalizedUri);
self::assertSame('file:///myfile', (string) $normalizedUri);
}
public function testRemoveDefaultPort()
{
$uri = $this->getMockBuilder('Psr\Http\Message\UriInterface')->getMock();
$uri->expects(self::any())->method('getScheme')->will(self::returnValue('http'));
$uri->expects(self::any())->method('getPort')->will(self::returnValue(80));
$uri->expects(self::once())->method('withPort')->with(null)->will(self::returnValue(new Uri('http://example.org')));
$normalizedUri = UriNormalizer::normalize($uri, UriNormalizer::REMOVE_DEFAULT_PORT);
self::assertInstanceOf('Psr\Http\Message\UriInterface', $normalizedUri);
self::assertNull($normalizedUri->getPort());
}
public function testRemoveDotSegments()
{
$uri = new Uri('http://example.org/../a/b/../c/./d.html');
$normalizedUri = UriNormalizer::normalize($uri, UriNormalizer::REMOVE_DOT_SEGMENTS);
self::assertInstanceOf('Psr\Http\Message\UriInterface', $normalizedUri);
self::assertSame('http://example.org/a/c/d.html', (string) $normalizedUri);
}
public function testRemoveDotSegmentsOfAbsolutePathReference()
{
$uri = new Uri('/../a/b/../c/./d.html');
$normalizedUri = UriNormalizer::normalize($uri, UriNormalizer::REMOVE_DOT_SEGMENTS);
self::assertInstanceOf('Psr\Http\Message\UriInterface', $normalizedUri);
self::assertSame('/a/c/d.html', (string) $normalizedUri);
}
public function testRemoveDotSegmentsOfRelativePathReference()
{
$uri = new Uri('../c/./d.html');
$normalizedUri = UriNormalizer::normalize($uri, UriNormalizer::REMOVE_DOT_SEGMENTS);
self::assertInstanceOf('Psr\Http\Message\UriInterface', $normalizedUri);
self::assertSame('../c/./d.html', (string) $normalizedUri);
}
public function testRemoveDuplicateSlashes()
{
$uri = new Uri('http://example.org//foo///bar/bam.html');
$normalizedUri = UriNormalizer::normalize($uri, UriNormalizer::REMOVE_DUPLICATE_SLASHES);
self::assertInstanceOf('Psr\Http\Message\UriInterface', $normalizedUri);
self::assertSame('http://example.org/foo/bar/bam.html', (string) $normalizedUri);
}
public function testSortQueryParameters()
{
$uri = new Uri('?lang=en&article=fred');
$normalizedUri = UriNormalizer::normalize($uri, UriNormalizer::SORT_QUERY_PARAMETERS);
self::assertInstanceOf('Psr\Http\Message\UriInterface', $normalizedUri);
self::assertSame('?article=fred&lang=en', (string) $normalizedUri);
}
public function testSortQueryParametersWithSameKeys()
{
$uri = new Uri('?a=b&b=c&a=a&a&b=a&b=b&a=d&a=c');
$normalizedUri = UriNormalizer::normalize($uri, UriNormalizer::SORT_QUERY_PARAMETERS);
self::assertInstanceOf('Psr\Http\Message\UriInterface', $normalizedUri);
self::assertSame('?a&a=a&a=b&a=c&a=d&b=a&b=b&b=c', (string) $normalizedUri);
}
/**
* @dataProvider getEquivalentTestCases
*/
public function testIsEquivalent($uri1, $uri2, $expected)
{
$equivalent = UriNormalizer::isEquivalent(new Uri($uri1), new Uri($uri2));
self::assertSame($expected, $equivalent);
}
public function getEquivalentTestCases()
{
return [
['http://example.org', 'http://example.org', true],
['hTTp://eXaMpLe.org', 'http://example.org', true],
['http://example.org/path?#', 'http://example.org/path', true],
['http://example.org:80', 'http://example.org/', true],
['http://example.org/../a/.././p%61th?%7a=%5e', 'http://example.org/path?z=%5E', true],
['https://example.org/', 'http://example.org/', false],
['https://example.org/', '//example.org/', false],
['//example.org/', '//example.org/', true],
['file:/myfile', 'file:///myfile', true],
['file:///myfile', 'file://localhost/myfile', true],
];
}
}

Some files were not shown because too many files have changed in this diff Show More