diff --git a/.gitattributes b/.gitattributes index 1fd8ce1..cc1e786 100644 --- a/.gitattributes +++ b/.gitattributes @@ -3,10 +3,7 @@ /.github/ export-ignore .gitignore export-ignore /.php_cs.dist export-ignore -/phpspec.ci.yml export-ignore -/phpspec.yml.dist export-ignore /phpstan-baseline.neon export-ignore /phpstan.neon.dist export-ignore /phpunit.xml.dist export-ignore -/spec/ export-ignore /tests/ export-ignore diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml index 1979b2e..3e9db95 100644 --- a/.github/workflows/checks.yml +++ b/.github/workflows/checks.yml @@ -13,7 +13,7 @@ jobs: steps: - name: Checkout code - uses: actions/checkout@v4 + uses: actions/checkout@v7 - name: Composer normalize uses: docker://ergebnis/composer-normalize-action diff --git a/.github/workflows/static.yml b/.github/workflows/static.yml index fe574a0..1243c5f 100644 --- a/.github/workflows/static.yml +++ b/.github/workflows/static.yml @@ -13,7 +13,7 @@ jobs: steps: - name: Checkout code - uses: actions/checkout@v4 + uses: actions/checkout@v7 - name: PHPStan uses: docker://oskarstark/phpstan-ga @@ -28,7 +28,7 @@ jobs: steps: - name: Checkout code - uses: actions/checkout@v4 + uses: actions/checkout@v7 - name: PHP-CS-Fixer uses: docker://oskarstark/php-cs-fixer-ga diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index be2c811..9049ac8 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -11,16 +11,13 @@ jobs: name: PHP ${{ matrix.php }} Latest runs-on: ubuntu-latest strategy: + fail-fast: false matrix: - php: ['7.2', '7.3', '7.4', '8.0', '8.1', '8.2', '8.3', '8.4'] + php: ['7.2', '7.3', '7.4', '8.0', '8.1', '8.2', '8.3', '8.4', '8.5', '8.6'] steps: - name: Checkout code - uses: actions/checkout@v4 - - - name: Emulate PHP 8.3 - run: composer config platform.php 8.3.999 - if: matrix.php == '8.4' + uses: actions/checkout@v7 - name: Setup PHP uses: shivammathur/setup-php@v2 @@ -30,6 +27,9 @@ jobs: coverage: none - name: Install dependencies + env: + # laminas/laminas-diactoros only has releases with known advisories for PHP < 8.1 + COMPOSER_NO_SECURITY_BLOCKING: 1 run: composer update --prefer-dist --no-interaction --no-progress - name: Execute tests @@ -41,7 +41,7 @@ jobs: steps: - name: Checkout code - uses: actions/checkout@v4 + uses: actions/checkout@v7 - name: Setup PHP uses: shivammathur/setup-php@v2 @@ -52,7 +52,7 @@ jobs: - name: Install dependencies run: | - rm src/MessageFactory/SlimMessageFactory.php src/StreamFactory/SlimStreamFactory.php src/UriFactory/SlimUriFactory.php spec/MessageFactory/SlimMessageFactorySpec.php spec/StreamFactory/SlimStreamFactorySpec.php spec/UriFactory/SlimUriFactorySpec.php + rm src/MessageFactory/SlimMessageFactory.php src/StreamFactory/SlimStreamFactory.php src/UriFactory/SlimUriFactory.php tests/MessageFactory/SlimMessageFactoryTest.php tests/StreamFactory/SlimStreamFactoryTest.php tests/UriFactory/SlimUriFactoryTest.php composer remove --dev "slim/slim" --no-interaction --no-update composer require "psr/http-message:^2.0" --no-interaction --no-update composer update --prefer-dist --prefer-stable --no-interaction --no-progress @@ -64,12 +64,13 @@ jobs: name: PHP ${{ matrix.php }} Lowest runs-on: ubuntu-latest strategy: + fail-fast: false matrix: php: ['7.2', '7.3', '7.4'] steps: - name: Checkout code - uses: actions/checkout@v4 + uses: actions/checkout@v7 - name: Setup PHP uses: shivammathur/setup-php@v2 @@ -79,9 +80,9 @@ jobs: coverage: none - name: Install dependencies - run: | - composer require "sebastian/comparator:^3.0.2" --no-interaction --no-update - composer update --prefer-dist --prefer-stable --prefer-lowest --no-interaction --no-progress + env: + COMPOSER_NO_SECURITY_BLOCKING: 1 + run: composer update --prefer-dist --prefer-stable --prefer-lowest --no-interaction --no-progress - name: Execute tests run: composer test @@ -92,19 +93,17 @@ jobs: steps: - name: Checkout code - uses: actions/checkout@v4 + uses: actions/checkout@v7 - name: Setup PHP uses: shivammathur/setup-php@v2 with: - php-version: 7.4 + php-version: 8.6 tools: composer - coverage: xdebug + coverage: pcov - name: Install dependencies - run: | - composer require "friends-of-phpspec/phpspec-code-coverage:^4.3.2" --no-interaction --no-update - composer update --prefer-dist --no-interaction --no-progress + run: composer update --prefer-dist --no-interaction --no-progress - name: Execute tests run: composer test-ci diff --git a/.gitignore b/.gitignore index fddbbfb..ee0ca50 100644 --- a/.gitignore +++ b/.gitignore @@ -2,7 +2,8 @@ .php-cs-fixer.cache /build/ /composer.lock -/phpspec.yml +/.phpunit.cache/ +/.phpunit.result.cache /phpstan.neon /phpunit.xml /vendor/ diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php index 55bd8ed..f567bd6 100644 --- a/.php-cs-fixer.dist.php +++ b/.php-cs-fixer.dist.php @@ -2,7 +2,7 @@ $finder = PhpCsFixer\Finder::create() ->in(__DIR__.'/src') - ->in(__DIR__.'/spec') + ->in(__DIR__.'/tests') ->name('*.php') ; diff --git a/CHANGELOG.md b/CHANGELOG.md index e13c12e..d643e87 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,10 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). +## [Unreleased] + +- Migrated the test suite from phpspec to PHPUnit. + ## [1.16.2] - 2024-10-02 - Avoid error when reading 0 bytes from BufferedStream. diff --git a/composer.json b/composer.json index 37a86a7..ec6a455 100644 --- a/composer.json +++ b/composer.json @@ -26,10 +26,10 @@ "ext-zlib": "*", "ergebnis/composer-normalize": "^2.6", "guzzlehttp/psr7": "^1.0 || ^2.0", + "laminas/laminas-diactoros": "^2.0 || ^3.0", "php-http/message-factory": "^1.0.2", - "phpspec/phpspec": "^5.1 || ^6.3 || ^7.1", - "slim/slim": "^3.0", - "laminas/laminas-diactoros": "^2.0 || ^3.0" + "phpunit/phpunit": "^8.5.40 || ^9.6.22 || ^10.5.45 || ^11.5.20 || ^12.4 || ^13.0", + "slim/slim": "^3.0" }, "suggest": { "ext-zlib": "Used with compressor/decompressor streams", @@ -53,11 +53,14 @@ }, "autoload-dev": { "psr-4": { - "spec\\Http\\Message\\": "spec/" - } + "Http\\Message\\Tests\\": "tests/" + }, + "files": [ + "tests/functions.php" + ] }, "scripts": { - "test": "vendor/bin/phpspec run", - "test-ci": "vendor/bin/phpspec run -c phpspec.ci.yml" + "test": "vendor/bin/phpunit", + "test-ci": "vendor/bin/phpunit --coverage-filter src --coverage-text --coverage-clover build/coverage.xml" } } diff --git a/phpspec.ci.yml b/phpspec.ci.yml deleted file mode 100644 index 5f8a626..0000000 --- a/phpspec.ci.yml +++ /dev/null @@ -1,11 +0,0 @@ -suites: - message_suite: - namespace: Http\Message - psr4_prefix: Http\Message -formatter.name: pretty -extensions: - FriendsOfPhpSpec\PhpSpec\CodeCoverage\CodeCoverageExtension: ~ -code_coverage: - format: clover - output: build/coverage.xml -runner.maintainers.errors.level: 16383 diff --git a/phpspec.yml.dist b/phpspec.yml.dist deleted file mode 100644 index 785cf0e..0000000 --- a/phpspec.yml.dist +++ /dev/null @@ -1,6 +0,0 @@ -suites: - message_suite: - namespace: Http\Message - psr4_prefix: Http\Message -formatter.name: pretty -runner.maintainers.errors.level: 16383 diff --git a/phpstan-baseline.neon b/phpstan-baseline.neon index 31bd899..ced0519 100644 --- a/phpstan-baseline.neon +++ b/phpstan-baseline.neon @@ -15,16 +15,6 @@ parameters: count: 1 path: src/Builder/ResponseBuilder.php - - - message: "#^Result of \\|\\| is always true\\.$#" - count: 1 - path: src/Builder/ResponseBuilder.php - - - - message: "#^Else branch is unreachable because ternary operator condition is always true\\.$#" - count: 1 - path: src/Builder/ResponseBuilder.php - - message: "#^Method Http\\\\Message\\\\Cookie\\:\\:createWithoutValidation\\(\\) has no return type specified\\.$#" count: 1 @@ -101,14 +91,14 @@ parameters: path: src/CookieJar.php - - message: "#^Method Http\\\\Message\\\\CookieJar\\:\\:clear\\(\\) has no return type specified\\.$#" - count: 1 + message: "#^Cannot call method .* on mixed\\.$#" + count: 4 path: src/CookieJar.php - - message: "#^Property Http\\\\Message\\\\CookieUtil\\:\\:\\$dateFormats type has no value type specified in iterable type array\\.$#" + message: "#^Method Http\\\\Message\\\\CookieJar\\:\\:clear\\(\\) has no return type specified\\.$#" count: 1 - path: src/CookieUtil.php + path: src/CookieJar.php - message: "#^Method Http\\\\Message\\\\MessageFactory\\\\DiactorosMessageFactory\\:\\:createRequest\\(\\) has parameter \\$headers with no value type specified in iterable type array\\.$#" @@ -181,6 +171,4 @@ parameters: path: src/UriFactory/SlimUriFactory.php - - message: "#^Call to function array_key_exists\\(\\) with 'chunk' and array will always evaluate to false\\.$#" - count: 1 - path: src/filters.php + message: '#Trait .* is used zero times and is not analysed#' diff --git a/phpstan.neon.dist b/phpstan.neon.dist index 6355eac..5192ac3 100644 --- a/phpstan.neon.dist +++ b/phpstan.neon.dist @@ -2,6 +2,7 @@ includes: - phpstan-baseline.neon parameters: + treatPhpDocTypesAsCertain: false level: max paths: - src diff --git a/phpunit.xml.dist b/phpunit.xml.dist new file mode 100644 index 0000000..e89cbf5 --- /dev/null +++ b/phpunit.xml.dist @@ -0,0 +1,19 @@ + + + + + + + + + + tests + + + diff --git a/spec/Authentication/AutoBasicAuthSpec.php b/spec/Authentication/AutoBasicAuthSpec.php deleted file mode 100644 index ba4ea8e..0000000 --- a/spec/Authentication/AutoBasicAuthSpec.php +++ /dev/null @@ -1,83 +0,0 @@ -shouldHaveType('Http\Message\Authentication\AutoBasicAuth'); - } - - public function it_is_an_authentication() - { - $this->shouldImplement('Http\Message\Authentication'); - } - - public function it_authenticates_a_request( - RequestInterface $request, - UriInterface $uri, - UriInterface $uriWithoutUserInfo, - RequestInterface $requestWithoutUserInfo, - RequestInterface $authenticatedRequest - ) { - $request->getUri()->willReturn($uri); - $uri->getUserInfo()->willReturn('username:password'); - $uri->withUserInfo('', null)->willReturn($uriWithoutUserInfo); - $request->withUri($uriWithoutUserInfo)->willReturn($requestWithoutUserInfo); - $requestWithoutUserInfo - ->withHeader('Authorization', 'Basic '.base64_encode('username:password')) - ->willReturn($authenticatedRequest) - ; - - $this->authenticate($request)->shouldReturn($authenticatedRequest); - } - - public function it_authenticates_a_request_without_password( - RequestInterface $request, - UriInterface $uri, - UriInterface $uriWithoutUserInfo, - RequestInterface $requestWithoutUserInfo, - RequestInterface $authenticatedRequest - ) { - $request->getUri()->willReturn($uri); - $uri->getUserInfo()->willReturn('username'); - $uri->withUserInfo('', null)->willReturn($uriWithoutUserInfo); - $request->withUri($uriWithoutUserInfo)->willReturn($requestWithoutUserInfo); - $requestWithoutUserInfo - ->withHeader('Authorization', 'Basic '.base64_encode('username')) - ->willReturn($authenticatedRequest) - ; - - $this->authenticate($request)->shouldReturn($authenticatedRequest); - } - - public function it_does_not_authenticate_a_request(RequestInterface $request, UriInterface $uri) - { - $request->getUri()->willReturn($uri); - $uri->getUserInfo()->willReturn(''); - - $this->authenticate($request)->shouldReturn($request); - } - - public function it_authenticates_a_request_without_user_info_removal( - RequestInterface $request, - UriInterface $uri, - RequestInterface $authenticatedRequest - ) { - $this->beConstructedWith(false); - - $request->getUri()->willReturn($uri); - $uri->getUserInfo()->willReturn('username:password'); - $request - ->withHeader('Authorization', 'Basic '.base64_encode('username:password')) - ->willReturn($authenticatedRequest) - ; - - $this->authenticate($request)->shouldReturn($authenticatedRequest); - } -} diff --git a/spec/Authentication/BasicAuthSpec.php b/spec/Authentication/BasicAuthSpec.php deleted file mode 100644 index c0e2b80..0000000 --- a/spec/Authentication/BasicAuthSpec.php +++ /dev/null @@ -1,31 +0,0 @@ -beConstructedWith('john.doe', 'secret'); - } - - public function it_is_initializable() - { - $this->shouldHaveType('Http\Message\Authentication\BasicAuth'); - } - - public function it_is_an_authentication() - { - $this->shouldImplement('Http\Message\Authentication'); - } - - public function it_authenticates_a_request(RequestInterface $request, RequestInterface $newRequest) - { - $request->withHeader('Authorization', 'Basic '.base64_encode('john.doe:secret'))->willReturn($newRequest); - - $this->authenticate($request)->shouldReturn($newRequest); - } -} diff --git a/spec/Authentication/BearerSpec.php b/spec/Authentication/BearerSpec.php deleted file mode 100644 index a8670ac..0000000 --- a/spec/Authentication/BearerSpec.php +++ /dev/null @@ -1,31 +0,0 @@ -beConstructedWith('token'); - } - - public function it_is_initializable() - { - $this->shouldHaveType('Http\Message\Authentication\Bearer'); - } - - public function it_is_an_authentication() - { - $this->shouldImplement('Http\Message\Authentication'); - } - - public function it_authenticates_a_request(RequestInterface $request, RequestInterface $newRequest) - { - $request->withHeader('Authorization', 'Bearer token')->willReturn($newRequest); - - $this->authenticate($request)->shouldReturn($newRequest); - } -} diff --git a/spec/Authentication/ChainSpec.php b/spec/Authentication/ChainSpec.php deleted file mode 100644 index 55f5d9a..0000000 --- a/spec/Authentication/ChainSpec.php +++ /dev/null @@ -1,50 +0,0 @@ -shouldHaveType('Http\Message\Authentication\Chain'); - } - - public function it_is_an_authentication() - { - $this->shouldImplement('Http\Message\Authentication'); - } - - public function it_throws_an_exception_when_non_authentication_is_passed() - { - $this->beConstructedWith(['authentication']); - - $this->shouldThrow('InvalidArgumentException')->duringInstantiation(); - } - - public function it_authenticates_a_request( - Authentication $auth1, - Authentication $auth2, - RequestInterface $originalRequest, - RequestInterface $request1, - RequestInterface $request2 - ) { - $originalRequest->withHeader('AuthMethod1', 'AuthValue')->willReturn($request1); - $request1->withHeader('AuthMethod2', 'AuthValue')->willReturn($request2); - - $auth1->authenticate($originalRequest)->will(function ($args) { - return $args[0]->withHeader('AuthMethod1', 'AuthValue'); - }); - - $auth2->authenticate($request1)->will(function ($args) { - return $args[0]->withHeader('AuthMethod2', 'AuthValue'); - }); - - $this->beConstructedWith([$auth1, $auth2]); - - $this->authenticate($originalRequest)->shouldReturn($request2); - } -} diff --git a/spec/Authentication/HeaderSpec.php b/spec/Authentication/HeaderSpec.php deleted file mode 100644 index 9558184..0000000 --- a/spec/Authentication/HeaderSpec.php +++ /dev/null @@ -1,31 +0,0 @@ -beConstructedWith('X-AUTH-TOKEN', 'REAL'); - } - - public function it_is_initializable() - { - $this->shouldHaveType('Http\Message\Authentication\Header'); - } - - public function it_is_an_authentication() - { - $this->shouldImplement('Http\Message\Authentication'); - } - - public function it_authenticates_a_request(RequestInterface $request, RequestInterface $newRequest) - { - $request->withHeader('X-AUTH-TOKEN', 'REAL')->willReturn($newRequest); - - $this->authenticate($request)->shouldReturn($newRequest); - } -} diff --git a/spec/Authentication/MatchingSpec.php b/spec/Authentication/MatchingSpec.php deleted file mode 100644 index 23cd1d6..0000000 --- a/spec/Authentication/MatchingSpec.php +++ /dev/null @@ -1,50 +0,0 @@ -beConstructedWith($authentication, $matcher); - } - - public function it_is_initializable() - { - $this->shouldHaveType('Http\Message\Authentication\Matching'); - } - - public function it_is_an_authentication() - { - $this->shouldImplement('Http\Message\Authentication'); - } - - public function it_authenticates_a_request(Authentication $authentication, RequestInterface $request, RequestInterface $newRequest) - { - $authentication->authenticate($request)->willReturn($newRequest); - - $this->authenticate($request)->shouldReturn($newRequest); - } - - public function it_does_not_authenticate_a_request(Authentication $authentication, RequestInterface $request) - { - $matcher = function ($request) { return false; }; - - $this->beConstructedWith($authentication, $matcher); - - $authentication->authenticate($request)->shouldNotBeCalled(); - - $this->authenticate($request)->shouldReturn($request); - } - - public function it_creates_a_matcher_from_url(Authentication $authentication) - { - $this->createUrlMatcher($authentication, 'url')->shouldHaveType('Http\Message\Authentication\Matching'); - } -} diff --git a/spec/Authentication/QueryParamSpec.php b/spec/Authentication/QueryParamSpec.php deleted file mode 100644 index eae560f..0000000 --- a/spec/Authentication/QueryParamSpec.php +++ /dev/null @@ -1,58 +0,0 @@ -beConstructedWith([ - 'username' => 'username', - 'password' => 'password', - ]); - } - - public function it_is_initializable() - { - $this->shouldHaveType('Http\Message\Authentication\QueryParam'); - } - - public function it_is_an_authentication() - { - $this->shouldImplement('Http\Message\Authentication'); - } - - public function it_authenticates_a_request( - RequestInterface $request, - UriInterface $uri, - RequestInterface $newRequest, - UriInterface $newUri - ) { - $request->getUri()->willReturn($uri); - $uri->getQuery()->willReturn('param1=value1¶m2[]=value2'); - $uri->withQuery('param1=value1¶m2%5B0%5D=value2&username=username&password=password')->will( - function ($args) use ($newUri) { - $newUri->getQuery()->willReturn($args[0]); - - return $newUri; - } - ); - - $request->withUri($newUri)->will(function ($args) use ($newRequest) { - $newRequest->getUri()->willReturn($args[0]); - - return $newRequest; - }); - - $authenticatedRequest = $this->authenticate($request); - $authenticatedRequest->shouldBe($newRequest); - - $authenticatedUri = $authenticatedRequest->getUri(); - $authenticatedUri->shouldBe($newUri); - $authenticatedUri->getQuery()->shouldReturn('param1=value1¶m2%5B0%5D=value2&username=username&password=password'); - } -} diff --git a/spec/Authentication/RequestConditionalSpec.php b/spec/Authentication/RequestConditionalSpec.php deleted file mode 100644 index f143f7a..0000000 --- a/spec/Authentication/RequestConditionalSpec.php +++ /dev/null @@ -1,49 +0,0 @@ -beConstructedWith($requestMatcher, $authentication); - } - - public function it_is_initializable() - { - $this->shouldHaveType('Http\Message\Authentication\RequestConditional'); - } - - public function it_is_an_authentication() - { - $this->shouldImplement('Http\Message\Authentication'); - } - - public function it_authenticates_a_request( - Authentication $authentication, - RequestMatcher $requestMatcher, - RequestInterface $request, - RequestInterface $newRequest - ) { - $requestMatcher->matches($request)->willReturn(true); - $authentication->authenticate($request)->willReturn($newRequest); - - $this->authenticate($request)->shouldReturn($newRequest); - } - - public function it_does_not_authenticate_a_request( - Authentication $authentication, - RequestMatcher $requestMatcher, - RequestInterface $request - ) { - $requestMatcher->matches($request)->willReturn(false); - $authentication->authenticate($request)->shouldNotBeCalled(); - - $this->authenticate($request)->shouldReturn($request); - } -} diff --git a/spec/Authentication/WsseSpec.php b/spec/Authentication/WsseSpec.php deleted file mode 100644 index bb48c1f..0000000 --- a/spec/Authentication/WsseSpec.php +++ /dev/null @@ -1,38 +0,0 @@ -beConstructedWith('john.doe', 'secret'); - } - - public function it_is_initializable() - { - $this->shouldHaveType('Http\Message\Authentication\Wsse'); - } - - public function it_is_an_authentication() - { - $this->shouldImplement('Http\Message\Authentication'); - } - - public function it_authenticates_a_request( - RequestInterface $request, - RequestInterface $newRequest, - RequestInterface $newerRequest - ) { - $request->withHeader('Authorization', 'WSSE profile="UsernameToken"')->willReturn($newRequest); - $newRequest->withHeader('X-WSSE', Argument::that(function ($arg) { - return preg_match('/UsernameToken Username=".*", PasswordDigest=".*", Nonce=".*", Created=".*"/', $arg); - }))->willReturn($newerRequest); - - $this->authenticate($request)->shouldReturn($newerRequest); - } -} diff --git a/spec/Builder/ResponseBuilderSpec.php b/spec/Builder/ResponseBuilderSpec.php deleted file mode 100644 index 4dfe977..0000000 --- a/spec/Builder/ResponseBuilderSpec.php +++ /dev/null @@ -1,38 +0,0 @@ -beConstructedWith($response); - $this->shouldHaveType('Http\Message\Builder\ResponseBuilder'); - } - - public function it_reads_headers_from_array(ResponseInterface $response) - { - $response->withStatus(200, 'OK')->willReturn($response); - $response->withProtocolVersion('1.1')->willReturn($response); - $response->hasHeader('Content-type')->willReturn(false); - $response->withHeader('Content-type', 'text/html')->willReturn($response); - $this->beConstructedWith($response); - $this->setHeadersFromArray(['HTTP/1.1 200 OK', 'Content-type: text/html']); - } - - /** - * @see https://github.com/php-http/message/issues/41 - */ - public function it_splits_headers_correctly(ResponseInterface $response) - { - $response->withStatus(200, 'OK')->willReturn($response); - $response->withProtocolVersion('1.1')->willReturn($response); - $response->hasHeader('Content-type')->willReturn(false); - $response->withHeader('Content-type', 'application/xml+atom')->willReturn($response); - $this->beConstructedWith($response); - $this->setHeadersFromString("HTTP/1.1 200 OK\r\nContent-type: application/xml+atom\r\n"); - } -} diff --git a/spec/CookieJarSpec.php b/spec/CookieJarSpec.php deleted file mode 100644 index 9a8acb6..0000000 --- a/spec/CookieJarSpec.php +++ /dev/null @@ -1,178 +0,0 @@ -shouldHaveType('Http\Message\CookieJar'); - } - - public function it_is_an_iterator_aggregate() - { - $this->getIterator()->shouldHaveType('Iterator'); - } - - public function it_has_a_cookie() - { - $cookie = new Cookie('name', 'value'); - - $this->addCookie($cookie); - - $this->hasCookie($cookie)->shouldReturn(true); - $this->hasCookies()->shouldReturn(true); - } - - public function it_accepts_a_cookie() - { - $cookie = new Cookie('name', 'value'); - $cookie2 = new Cookie('name', 'value2'); - - $this->addCookie($cookie); - $this->addCookie($cookie2); - - $this->hasCookie($cookie)->shouldReturn(false); - $this->hasCookie($cookie2)->shouldReturn(true); - } - - public function it_removes_a_cookie_with_an_empty_value() - { - $cookie = new Cookie('name', 'value'); - $cookie2 = new Cookie('name'); - - $this->addCookie($cookie); - $this->addCookie($cookie2); - - $this->hasCookie($cookie)->shouldReturn(false); - $this->hasCookie($cookie2)->shouldReturn(false); - } - - public function it_removes_a_cookie_with_a_lower_expiration_time() - { - $cookie = new Cookie('name', 'value', 100); - $cookie2 = new Cookie('name', 'value', 1000); - - $this->addCookie($cookie); - $this->addCookie($cookie2); - - $this->hasCookie($cookie)->shouldReturn(false); - $this->hasCookie($cookie2)->shouldReturn(true); - } - - public function it_removes_a_cookie() - { - $cookie = new Cookie('name', 'value', 100); - - $this->addCookie($cookie); - $this->removeCookie($cookie); - - $this->hasCookie($cookie)->shouldReturn(false); - } - - public function it_returns_all_cookies() - { - $cookie = new Cookie('name', 'value'); - $cookie2 = new Cookie('name2', 'value'); - - $this->addCookie($cookie); - $this->addCookie($cookie2); - - $this->getCookies()->shouldBeAnArrayOfInstance('Http\Message\Cookie'); - } - - public function it_returns_the_matching_cookies() - { - $cookie = new Cookie('name', 'value'); - $cookie2 = new Cookie('name', 'value2'); - - $this->addCookie($cookie); - - $this->getMatchingCookies($cookie2)->shouldBeAnArrayOfInstance('Http\Message\Cookie'); - } - - public function it_sets_cookies() - { - $cookie = new Cookie('name', 'value'); - - $this->setCookies([$cookie]); - - $this->hasCookie($cookie)->shouldReturn(true); - $this->hasCookies()->shouldReturn(true); - $this->count()->shouldReturn(1); - } - - public function it_accepts_cookies() - { - $cookie = new Cookie('name', 'value'); - $cookie2 = new Cookie('name2', 'value'); - - $this->addCookie($cookie); - $this->addCookies([$cookie2]); - - $this->hasCookie($cookie)->shouldReturn(true); - $this->hasCookie($cookie2)->shouldReturn(true); - $this->hasCookies()->shouldReturn(true); - $this->count()->shouldReturn(2); - } - - public function it_removes_cookies() - { - $cookie = new Cookie('name', 'value'); - $cookie2 = new Cookie('name2', 'value'); - - $this->addCookies([$cookie, $cookie2]); - $this->removeCookies([$cookie2]); - - $this->hasCookie($cookie)->shouldReturn(true); - $this->hasCookie($cookie2)->shouldReturn(false); - $this->hasCookies()->shouldReturn(true); - $this->count()->shouldReturn(1); - } - - public function it_removes_matching_cookies() - { - $cookie = new Cookie('name', 'value'); - $cookie2 = new Cookie('name2', 'value', 0, 'php-http.org'); - - $this->addCookies([$cookie, $cookie2]); - - $this->removeMatchingCookies('name2', 'php-http.org', '/'); - - $this->hasCookie($cookie)->shouldReturn(true); - $this->hasCookie($cookie2)->shouldReturn(false); - $this->hasCookies()->shouldReturn(true); - $this->count()->shouldReturn(1); - } - - public function it_clears_cookies() - { - $cookie = new Cookie('name', 'value', 0, 'php-http.org'); - $cookie2 = new Cookie('name2', 'value'); - - $this->addCookies([$cookie, $cookie2]); - - $this->clear(); - - $this->hasCookies()->shouldReturn(false); - $this->count()->shouldReturn(0); - } - - public function getMatchers(): array - { - return [ - 'beAnArrayOfInstance' => function ($subject, $instance) { - foreach ($subject as $element) { - if (!$element instanceof $instance) { - return false; - } - } - - return true; - }, - ]; - } -} diff --git a/spec/CookieSpec.php b/spec/CookieSpec.php deleted file mode 100644 index 5f77e97..0000000 --- a/spec/CookieSpec.php +++ /dev/null @@ -1,284 +0,0 @@ -beConstructedWith('name', 'value'); - } - - public function it_is_initializable() - { - $this->shouldHaveType('Http\Message\Cookie'); - } - - public function it_has_a_name() - { - $this->getName()->shouldReturn('name'); - } - - /** - * @dataProvider invalidCharacterExamples - */ - public function it_throws_an_exception_when_the_name_contains_invalid_character() - { - foreach (self::invalidCharacterExamples() as $example) { - $this->beConstructedWith($example[0]); - - if ($example[1]) { - $expectation = $this->shouldThrow('InvalidArgumentException'); - } else { - $expectation = $this->shouldNotThrow('InvalidArgumentException'); - } - - $expectation->duringInstantiation(); - } - } - - public function it_throws_an_expection_when_name_is_empty() - { - $this->beConstructedWith(''); - - $this->shouldThrow('InvalidArgumentException')->duringInstantiation(); - } - - public function it_has_a_value() - { - $this->getValue()->shouldReturn('value'); - $this->hasValue()->shouldReturn(true); - } - - public function it_throws_an_exception_when_the_value_contains_invalid_character() - { - foreach (self::invalidCharacterExamples() as $example) { - $this->beConstructedWith('name', $example[0]); - - if ($example[1]) { - $expectation = $this->shouldThrow('InvalidArgumentException'); - } else { - $expectation = $this->shouldNotThrow('InvalidArgumentException'); - } - - $expectation->duringInstantiation(); - } - } - - public function it_accepts_a_value() - { - $cookie = $this->withValue('value2'); - - $cookie->shouldHaveType('Http\Message\Cookie'); - $cookie->getValue()->shouldReturn('value2'); - } - - public function it_throws_an_exception_when_the_new_value_contains_invalid_character() - { - foreach (self::invalidCharacterExamples() as $example) { - if ($example[1]) { - $expectation = $this->shouldThrow('InvalidArgumentException'); - } else { - $expectation = $this->shouldNotThrow('InvalidArgumentException'); - } - - $expectation->duringWithValue($example[0]); - } - } - - public function it_has_a_max_age_time() - { - $this->beConstructedWith('name', 'value', 10); - - $this->getMaxAge()->shouldReturn(10); - $this->hasMaxAge()->shouldReturn(true); - } - - public function it_accepts_a_max_age() - { - $cookie = $this->withMaxAge(1); - - $cookie->shouldHaveType('Http\Message\Cookie'); - $cookie->getMaxAge()->shouldReturn(1); - } - - public function it_throws_an_exception_when_max_age_is_invalid() - { - $this->shouldThrow('InvalidArgumentException')->duringWithMaxAge('-1'); - } - - public function it_has_an_expires_attribute() - { - $expires = new \DateTime('+10 seconds'); - - $this->beConstructedWith('name', 'value', null, null, null, false, false, $expires); - - $this->getExpires()->shouldReturn($expires); - $this->hasExpires()->shouldReturn(true); - $this->isExpired()->shouldReturn(false); - } - - public function it_accepts_an_expires_attribute() - { - $expires = new \DateTime('+10 seconds'); - - $cookie = $this->withExpires($expires); - - $cookie->shouldHaveType('Http\Message\Cookie'); - $cookie->getExpires()->shouldReturn($expires); - } - - public function it_is_expired() - { - $this->beConstructedWith('name', 'value', null, null, null, false, false, new \DateTime('-2 minutes')); - - $this->getExpires()->shouldHaveType('DateTime'); - $this->hasExpires()->shouldReturn(true); - $this->isExpired()->shouldReturn(true); - } - - public function it_has_a_domain() - { - $this->getDomain()->shouldReturn(null); - $this->hasDomain()->shouldReturn(false); - } - - public function it_has_a_valid_domain() - { - $this->beConstructedWith('name', 'value', null, '.PhP-hTtP.oRg'); - - $this->getDomain()->shouldReturn('php-http.org'); - $this->hasDomain()->shouldReturn(true); - } - - public function it_accepts_a_domain() - { - $cookie = $this->withDomain('.PhP-hTtP.oRg'); - - $cookie->shouldHaveType('Http\Message\Cookie'); - $cookie->getDomain()->shouldReturn('php-http.org'); - } - - public function it_matches_a_domain() - { - $this->beConstructedWith('name', 'value', null, 'php-http.org'); - - $this->matchDomain('PhP-hTtP.oRg')->shouldReturn(true); - $this->matchDomain('127.0.0.1')->shouldReturn(false); - $this->matchDomain('wWw.PhP-hTtP.oRg')->shouldReturn(true); - } - - public function it_has_a_path() - { - $this->getPath()->shouldReturn('/'); - } - - public function it_accepts_a_path() - { - $cookie = $this->withPath('/path'); - - $cookie->shouldHaveType('Http\Message\Cookie'); - $cookie->getPath()->shouldReturn('/path'); - } - - public function it_matches_a_path() - { - $this->beConstructedWith('name', 'value', null, null, '/path/to/somewhere'); - - $this->matchPath('/path/to/somewhere')->shouldReturn(true); - $this->matchPath('/path/to/somewhere/else')->shouldReturn(true); - $this->matchPath('/path/to/somewhereelse')->shouldReturn(false); - } - - public function it_matches_the_root_path() - { - $this->beConstructedWith('name', 'value', null, null, '/'); - - $this->matchPath('/')->shouldReturn(true); - $this->matchPath('/cookies')->shouldReturn(true); - $this->matchPath('/cookies/')->shouldReturn(true); - } - - public function it_is_secure() - { - $this->isSecure()->shouldReturn(false); - } - - public function it_accepts_security() - { - $cookie = $this->withSecure(true); - - $cookie->shouldHaveType('Http\Message\Cookie'); - $cookie->isSecure()->shouldReturn(true); - } - - public function it_can_be_http_only() - { - $this->isHttpOnly()->shouldReturn(false); - } - - public function it_accepts_http_only() - { - $cookie = $this->withHttpOnly(true); - - $cookie->shouldHaveType('Http\Message\Cookie'); - $cookie->isHttpOnly()->shouldReturn(true); - } - - public function it_matches_other_cookies() - { - $this->beConstructedWith('name', 'value', null, 'php-http.org'); - - $matches = new Cookie('name', 'value2', null, 'php-http.org'); - $notMatches = new Cookie('anotherName', 'value2', null, 'php-http.org'); - - $this->match($matches)->shouldReturn(true); - $this->match($notMatches)->shouldReturn(false); - } - - public function it_validates_itself() - { - $this->isValid()->shouldReturn(true); - } - - public function it_can_be_constructed_without_name_validation() - { - $this->beConstructedThrough('createWithoutValidation', ["\x20"]); - - $this->isValid()->shouldReturn(false); - } - - public function it_can_be_constructed_without_value_validation() - { - $this->beConstructedThrough('createWithoutValidation', ['name', "\x20"]); - - $this->isValid()->shouldReturn(false); - } - - public function it_can_be_constructed_without_max_age_validation() - { - $this->beConstructedThrough('createWithoutValidation', ['name', 'value', '-1']); - - $this->isValid()->shouldReturn(false); - } - - /** - * Provides examples for invalid characers in names and values. - * - * @return array - */ - private static function invalidCharacterExamples() - { - return [ - ['a', false], - ["\x00", true], - ['z', false], - ["\x20", true], - ['0', false], - ["\x7F", true], - ]; - } -} diff --git a/spec/CookieUtilSpec.php b/spec/CookieUtilSpec.php deleted file mode 100644 index 3777b0a..0000000 --- a/spec/CookieUtilSpec.php +++ /dev/null @@ -1,156 +0,0 @@ -testCookieParse('Friday, 31 Jul 20 08:49:37 GMT', 'Friday, 31-Jul-2020 08:49:37 +0000'); - } - - public function it_parses_cookie_date_string_2() - { - $this->testCookieParse('Friday, 31-Jul-20 08:49:37 GMT', 'Friday, 31-Jul-2020 08:49:37 +0000'); - } - - public function it_parses_cookie_date_string_3() - { - $this->testCookieParse('Fri, 31-Jul-2020 08:49:37 GMT', 'Friday, 31-Jul-2020 08:49:37 +0000'); - } - - public function it_parses_cookie_date_string_4() - { - $this->testCookieParse('Fri, 31 Jul 2020 08:49:37 GMT', 'Friday, 31-Jul-2020 08:49:37 +0000'); - } - - public function it_parses_cookie_date_string_5() - { - $this->testCookieParse('Fri, 31-07-2020 08:49:37 GMT', 'Friday, 31-Jul-2020 08:49:37 +0000'); - } - - public function it_parses_cookie_date_string_6() - { - $this->testCookieParse('Fri, 31-07-20 08:49:37 GMT', 'Friday, 31-Jul-2020 08:49:37 +0000'); - } - - public function it_parses_cookie_date_string_7() - { - $this->testCookieParse('Friday, 31-Jul-20 08:49:37 GMT', 'Friday, 31-Jul-2020 08:49:37 +0000'); - } - - public function it_parses_cookie_date_string_8() - { - $this->testCookieParse('Fri Jul 31 08:49:37 2020', 'Friday, 31-Jul-2020 08:49:37 +0000'); - } - - public function it_parses_cookie_date_string_9() - { - $this->testCookieParse('Friday July 31st 2020, 08:49:37 GMT', 'Friday, 31-Jul-2020 08:49:37 +0000'); - } - - public function it_parses_cookie_date_string_10() - { - // https://github.com/salesforce/tough-cookie/blob/master/test/date_test.js#L52 - $this->testCookieParse('Wed, 09 Jun 2021 10:18:14 GMT', 'Wednesday, 09-Jun-2021 10:18:14 +0000'); - } - - public function it_parses_cookie_date_string_11() - { - // https://github.com/salesforce/tough-cookie/blob/master/test/date_test.js#L52 - $this->testCookieParse('Wed, 09 Jun 2021 22:18:14 GMT', 'Wednesday, 09-Jun-2021 22:18:14 +0000'); - } - - public function it_parses_cookie_date_string_12() - { - // https://github.com/salesforce/tough-cookie/blob/master/test/date_test.js#L52 - $this->testCookieParse('Tue, 18 Oct 2011 07:42:42.123 GMT', 'Tuesday, 18-Oct-2011 07:42:42 +0000'); - } - - public function it_parses_cookie_date_string_13() - { - // https://github.com/salesforce/tough-cookie/blob/master/test/date_test.js#L52 - $this->testCookieParse('18 Oct 2011 07:42:42 GMT', 'Tuesday, 18-Oct-2011 07:42:42 +0000'); - } - - public function it_parses_cookie_date_string_14() - { - // https://github.com/salesforce/tough-cookie/blob/master/test/date_test.js#L52 - $this->testCookieParse('8 Oct 2011 7:42:42 GMT', 'Saturday, 08-Oct-2011 07:42:42 +0000'); - } - - public function it_parses_cookie_date_string_15() - { - // https://github.com/salesforce/tough-cookie/blob/master/test/date_test.js#L52 - $this->testCookieParse('8 Oct 2011 7:2:42 GMT', 'Saturday, 08-Oct-2011 07:02:42 +0000'); - } - - public function it_parses_cookie_date_string_16() - { - // https://github.com/salesforce/tough-cookie/blob/master/test/date_test.js#L52 - $this->testCookieParse('Oct 18 2011 07:42:42 GMT', 'Tuesday, 18-Oct-2011 07:42:42 +0000'); - } - - public function it_parses_cookie_date_string_17() - { - // https://github.com/salesforce/tough-cookie/blob/master/test/date_test.js#L52 - $this->testCookieParse('Tue Oct 18 2011 07:05:03 GMT+0000 (GMT)', 'Tuesday, 18-Oct-2011 07:05:03 +0000'); - } - - public function it_parses_cookie_date_string_18() - { - // https://github.com/salesforce/tough-cookie/blob/master/test/date_test.js#L52 - $this->testCookieParse('09 Jun 2021 10:18:14 GMT', 'Wednesday, 09-Jun-2021 10:18:14 +0000'); - } - - public function it_parses_cookie_date_string_19() - { - // https://github.com/salesforce/tough-cookie/blob/master/test/date_test.js#L52 - $this->testCookieParse('01 Jan 1970 00:00:00 GMT', 'Thursday, 01-Jan-1970 00:00:00 +0000'); - } - - public function it_parses_cookie_date_string_20() - { - // https://github.com/salesforce/tough-cookie/blob/master/test/date_test.js#L52 - $this->testCookieParse('01 Jan 1601 00:00:00 GMT', 'Monday, 01-Jan-1601 00:00:00 +0000'); - } - - public function it_parses_cookie_date_string_21() - { - // implicit year - $this->testCookieParse('10 Feb 81 13:00:00 GMT', 'Tuesday, 10-Feb-1981 13:00:00 +0000'); - } - - public function it_parses_cookie_date_string_22() - { - // dashes - $this->testCookieParse('Thu, 17-Apr-2014 02:12:29 GMT', 'Thursday, 17-Apr-2014 02:12:29 +0000'); - } - - public function it_parses_cookie_date_string_23() - { - // dashes and UTC - $this->testCookieParse('Thu, 17-Apr-2014 02:12:29 UTC', 'Thursday, 17-Apr-2014 02:12:29 +0000'); - } - - public function it_throws_an_exception_if_cookie_date_string_is_unparseable_1() - { - $this->beConstructedThrough('parseDate', ['Flursday July 31st 2020, 08:49:37 GMT']); - $this->shouldThrow('Http\Message\Exception\UnexpectedValueException'); - } - - public function it_throws_an_exception_if_cookie_date_string_is_unparseable_2() - { - $this->beConstructedThrough('parseDate', ['99 Jix 3038 48:86:72 ZMT']); - $this->shouldThrow('Http\Message\Exception\UnexpectedValueException'); - } - - private function testCookieParse(string $input, string $output) - { - $this->beConstructedThrough('parseDate', [$input]); - $this->shouldHaveType('\DateTime'); - $this->format('l, d-M-Y H:i:s O')->shouldReturn($output); - } -} diff --git a/spec/Decorator/MessageDecoratorSpec.php b/spec/Decorator/MessageDecoratorSpec.php deleted file mode 100644 index 8c8bd33..0000000 --- a/spec/Decorator/MessageDecoratorSpec.php +++ /dev/null @@ -1,141 +0,0 @@ -beAnInstanceOf('spec\Http\Message\Decorator\MessageDecoratorStub', [$message]); - } - - public function it_is_initializable() - { - $this->shouldHaveType('spec\Http\Message\Decorator\MessageDecoratorStub'); - } - - public function it_is_a_message() - { - $this->shouldImplement('Psr\Http\Message\MessageInterface'); - } - - public function it_is_a_message_decorator() - { - $this->shouldUseTrait('Http\Message\Decorator\MessageDecorator'); - } - - public function it_has_a_message() - { - $this->getMessage()->shouldImplement('Psr\Http\Message\MessageInterface'); - } - - public function it_has_a_protocol_version(MessageInterface $message) - { - $message->getProtocolVersion()->willReturn('1.1'); - - $this->getProtocolVersion()->shouldReturn('1.1'); - } - - public function it_accepts_a_protocol_version(MessageInterface $message, MessageInterface $newMessage) - { - $message->withProtocolVersion('1.1')->willReturn($newMessage); - - $new = $this->withProtocolVersion('1.1'); - $new->getMessage()->shouldReturn($newMessage); - } - - public function it_has_headers(MessageInterface $message) - { - $headers = [ - 'Content-Type' => 'application/xml', - ]; - - $message->getHeaders()->willReturn($headers); - - $this->getHeaders()->shouldReturn($headers); - } - - public function it_can_check_a_header(MessageInterface $message) - { - $message->hasHeader('Content-Type')->willReturn(true); - - $this->hasHeader('Content-Type')->shouldReturn(true); - } - - public function it_has_a_header(MessageInterface $message) - { - $message->getHeader('Content-Type')->willReturn(['application/xml']); - - $this->getHeader('Content-Type')->shouldReturn(['application/xml']); - } - - public function it_has_a_header_line(MessageInterface $message) - { - $message->getHeaderLine('Accept-Encoding')->willReturn('gzip, deflate'); - - $this->getHeaderLine('Accept-Encoding')->shouldReturn('gzip, deflate'); - } - - public function it_accepts_a_header(MessageInterface $message, MessageInterface $newMessage) - { - $message->withHeader('Content-Type', 'application/xml')->willReturn($newMessage); - - $new = $this->withHeader('Content-Type', 'application/xml'); - $new->getMessage()->shouldReturn($newMessage); - } - - public function it_accepts_added_headers(MessageInterface $message, MessageInterface $newMessage) - { - $message->withAddedHeader('Content-Type', 'application/xml')->willReturn($newMessage); - - $new = $this->withAddedHeader('Content-Type', 'application/xml'); - $new->getMessage()->shouldReturn($newMessage); - } - - public function it_removes_a_header(MessageInterface $message, MessageInterface $newMessage) - { - $message->withoutHeader('Content-Type')->willReturn($newMessage); - - $new = $this->withoutHeader('Content-Type'); - $new->getMessage()->shouldReturn($newMessage); - } - - public function it_has_a_body(MessageInterface $message, StreamInterface $body) - { - $message->getBody()->willReturn($body); - - $this->getBody()->shouldReturn($body); - } - - public function it_accepts_a_body(MessageInterface $message, MessageInterface $newMessage, StreamInterface $body) - { - $message->withBody($body)->willReturn($newMessage); - - $new = $this->withBody($body); - $new->getMessage()->shouldReturn($newMessage); - } - - public function getMatchers(): array - { - return [ - 'useTrait' => function ($subject, $trait) { - return class_uses($subject, $trait); - }, - ]; - } -} - -class MessageDecoratorStub implements MessageInterface -{ - use MessageDecorator; - - public function __construct(MessageInterface $message) - { - $this->message = $message; - } -} diff --git a/spec/Decorator/RequestDecoratorSpec.php b/spec/Decorator/RequestDecoratorSpec.php deleted file mode 100644 index b1e200c..0000000 --- a/spec/Decorator/RequestDecoratorSpec.php +++ /dev/null @@ -1,107 +0,0 @@ -beAnInstanceOf('spec\Http\Message\Decorator\RequestDecoratorStub', [$request]); - } - - public function it_is_initializable() - { - $this->shouldHaveType('spec\Http\Message\Decorator\RequestDecoratorStub'); - } - - public function it_is_a_request() - { - $this->shouldImplement('Psr\Http\Message\RequestInterface'); - } - - public function it_is_a_request_decorator() - { - $this->shouldUseTrait('Http\Message\Decorator\RequestDecorator'); - } - - public function it_has_a_request() - { - $this->getRequest()->shouldImplement('Psr\Http\Message\RequestInterface'); - } - - public function it_accepts_a_request(RequestInterface $request) - { - $new = $this->withRequest($request); - - $new->getRequest()->shouldReturn($request); - } - - public function it_has_a_request_target(RequestInterface $request) - { - $request->getRequestTarget()->willReturn('/'); - - $this->getRequestTarget()->shouldReturn('/'); - } - - public function it_accepts_a_request_target(RequestInterface $request, RequestInterface $newRequest) - { - $request->withRequestTarget('/')->willReturn($newRequest); - - $new = $this->withRequestTarget('/'); - $new->getMessage()->shouldReturn($newRequest); - } - - public function it_has_a_method(RequestInterface $request) - { - $request->getMethod()->willReturn('GET'); - - $this->getMethod()->shouldReturn('GET'); - } - - public function it_accepts_a_method(RequestInterface $request, RequestInterface $newRequest) - { - $request->withMethod('GET')->willReturn($newRequest); - - $new = $this->withMethod('GET'); - $new->getMessage()->shouldReturn($newRequest); - } - - public function it_has_an_uri(RequestInterface $request, UriInterface $uri) - { - $request->getUri()->willReturn($uri); - - $this->getUri()->shouldReturn($uri); - } - - public function it_accepts_an_uri(RequestInterface $request, RequestInterface $newRequest, UriInterface $uri) - { - $request->withUri($uri, false)->willReturn($newRequest); - - $new = $this->withUri($uri); - $new->getMessage()->shouldReturn($newRequest); - } - - public function getMatchers(): array - { - return [ - 'useTrait' => function ($subject, $trait) { - return class_uses($subject, $trait); - }, - ]; - } -} - -class RequestDecoratorStub implements RequestInterface -{ - use RequestDecorator; - - public function __construct(RequestInterface $request) - { - $this->message = $request; - } -} diff --git a/spec/Decorator/ResponseDecoratorSpec.php b/spec/Decorator/ResponseDecoratorSpec.php deleted file mode 100644 index 3c7798b..0000000 --- a/spec/Decorator/ResponseDecoratorSpec.php +++ /dev/null @@ -1,83 +0,0 @@ -beAnInstanceOf('spec\Http\Message\Decorator\ResponseDecoratorStub', [$response]); - } - - public function it_is_initializable() - { - $this->shouldHaveType('spec\Http\Message\Decorator\ResponseDecoratorStub'); - } - - public function it_is_a_response() - { - $this->shouldImplement('Psr\Http\Message\ResponseInterface'); - } - - public function it_is_a_response_decorator() - { - $this->shouldUseTrait('Http\Message\Decorator\ResponseDecorator'); - } - - public function it_has_a_response() - { - $this->getResponse()->shouldImplement('Psr\Http\Message\ResponseInterface'); - } - - public function it_accepts_a_response(ResponseInterface $response) - { - $new = $this->withResponse($response); - - $new->getResponse()->shouldReturn($response); - } - - public function it_has_a_status_code(ResponseInterface $response) - { - $response->getStatusCode()->willReturn(200); - - $this->getStatusCode()->shouldReturn(200); - } - - public function it_accepts_a_status(ResponseInterface $response, ResponseInterface $newResponse) - { - $response->withStatus(200, 'OK')->willReturn($newResponse); - - $new = $this->withStatus(200, 'OK'); - $new->getMessage()->shouldReturn($newResponse); - } - - public function it_has_a_reason_phrase(ResponseInterface $response) - { - $response->getReasonPhrase()->willReturn('OK'); - - $this->getReasonPhrase()->shouldReturn('OK'); - } - - public function getMatchers(): array - { - return [ - 'useTrait' => function ($subject, $trait) { - return class_uses($subject, $trait); - }, - ]; - } -} - -class ResponseDecoratorStub implements ResponseInterface -{ - use ResponseDecorator; - - public function __construct(ResponseInterface $response) - { - $this->message = $response; - } -} diff --git a/spec/Decorator/StreamDecoratorSpec.php b/spec/Decorator/StreamDecoratorSpec.php deleted file mode 100644 index 1315579..0000000 --- a/spec/Decorator/StreamDecoratorSpec.php +++ /dev/null @@ -1,153 +0,0 @@ -beAnInstanceOf('spec\Http\Message\Decorator\StreamDecoratorStub', [$stream]); - } - - public function it_is_initializable() - { - $this->shouldHaveType('spec\Http\Message\Decorator\StreamDecoratorStub'); - } - - public function it_is_a_stream_decorator() - { - $this->shouldUseTrait('Http\Message\Decorator\StreamDecorator'); - } - - public function it_casts_the_stream_to_string(StreamInterface $stream) - { - $stream->__toString()->willReturn('body'); - - $this->__toString()->shouldReturn('body'); - } - - public function it_closes_the_stream(StreamInterface $stream) - { - $stream->close()->shouldBeCalled(); - - $this->close(); - } - - public function it_detaches_the_stream(StreamInterface $stream) - { - $stream->detach()->willReturn('detached'); - - $this->detach()->shouldReturn('detached'); - } - - public function it_returns_the_size_of_the_stream(StreamInterface $stream) - { - $stream->getSize()->willReturn(1234); - - $this->getSize()->shouldReturn(1234); - } - - public function it_returns_the_current_position_of_the_stream(StreamInterface $stream) - { - $stream->tell()->willReturn(0); - - $this->tell()->shouldReturn(0); - } - - public function it_checks_whether_the_stream_is_eof(StreamInterface $stream) - { - $stream->eof()->willReturn(false); - - $this->eof()->shouldReturn(false); - } - - public function it_checks_whether_the_stream_is_seekable(StreamInterface $stream) - { - $stream->isSeekable()->willReturn(true); - - $this->isSeekable()->shouldReturn(true); - } - - public function it_seeks_the_current_position_of_the_stream(StreamInterface $stream) - { - $stream->seek(0, SEEK_SET)->shouldBeCalled(); - - $this->seek(0); - } - - public function it_rewinds_to_the_beginning_of_the_stream(StreamInterface $stream) - { - $stream->rewind()->shouldBeCalled(); - - $this->rewind(); - } - - public function it_checks_whether_the_stream_is_writable(StreamInterface $stream) - { - $stream->isWritable()->willReturn(true); - - $this->isWritable()->shouldReturn(true); - } - - public function it_writes_to_the_stream(StreamInterface $stream) - { - $stream->write('body')->shouldBeCalled()->willReturn(4); - - $this->write('body'); - } - - public function it_checks_whether_the_stream_is_readable(StreamInterface $stream) - { - $stream->isReadable()->willReturn(true); - - $this->isReadable()->shouldReturn(true); - } - - public function it_reads_from_the_stream(StreamInterface $stream) - { - $stream->read(4)->willReturn('body'); - - $this->read(4)->shouldReturn('body'); - } - - public function it_returns_the_contents_of_the_stream(StreamInterface $stream) - { - $stream->getContents()->willReturn('body'); - - $this->getContents()->shouldReturn('body'); - } - - public function it_returns_metadata_of_the_stream(StreamInterface $stream) - { - $stream->getMetadata(null)->willReturn(['key' => 'value']); - $stream->getMetadata('key')->willReturn('value'); - $stream->getMetadata('key2')->willReturn(null); - - $this->getMetadata()->shouldReturn(['key' => 'value']); - $this->getMetadata('key')->shouldReturn('value'); - $this->getMetadata('key2')->shouldReturn(null); - } - - public function getMatchers(): array - { - return [ - 'useTrait' => function ($subject, $trait) { - return class_uses($subject, $trait); - }, - ]; - } -} - -class StreamDecoratorStub implements StreamInterface -{ - use StreamDecorator; - - public function __construct(StreamInterface $stream) - { - $this->stream = $stream; - } -} diff --git a/spec/Encoding/ChunkStreamSpec.php b/spec/Encoding/ChunkStreamSpec.php deleted file mode 100644 index b008112..0000000 --- a/spec/Encoding/ChunkStreamSpec.php +++ /dev/null @@ -1,45 +0,0 @@ -beConstructedWith($stream); - } - - public function it_is_initializable() - { - $this->shouldHaveType('Http\Message\Encoding\ChunkStream'); - } - - public function it_chunks_content() - { - $stream = new MemoryStream('This is a stream'); - $this->beConstructedWith($stream, 6); - - $this->getContents()->shouldReturn("10\r\nThis is a stream\r\n0\r\n\r\n"); - } - - public function it_chunks_in_multiple() - { - $stream = new MemoryStream('This is a stream', 6); - $this->beConstructedWith($stream, 6); - - $this->getContents()->shouldReturn("6\r\nThis i\r\n6\r\ns a st\r\n4\r\nream\r\n0\r\n\r\n"); - } - - public function it_does_not_know_the_content_size() - { - $stream = new MemoryStream('This is a stream'); - $this->beConstructedWith($stream, 6); - - $this->getSize()->shouldReturn(null); - } -} diff --git a/spec/Encoding/CompressStreamSpec.php b/spec/Encoding/CompressStreamSpec.php deleted file mode 100644 index 79ac873..0000000 --- a/spec/Encoding/CompressStreamSpec.php +++ /dev/null @@ -1,49 +0,0 @@ -beConstructedWith($stream); - } - - public function it_is_initializable() - { - $this->shouldHaveType('Http\Message\Encoding\CompressStream'); - } - - public function it_reads() - { - $stream = new MemoryStream('This is a test stream'); - $this->beConstructedWith($stream); - - $stream->rewind(); - $this->read(4)->shouldReturn(substr(gzcompress('This is a test stream'), 0, 4)); - } - - public function it_gets_content() - { - $stream = new MemoryStream('This is a test stream'); - $this->beConstructedWith($stream); - - $stream->rewind(); - $this->getContents()->shouldReturn(gzcompress('This is a test stream')); - } - - public function it_does_not_know_the_content_size() - { - $stream = new MemoryStream('This is a test stream'); - $this->beConstructedWith($stream); - - $stream->rewind(); - $this->getSize()->shouldReturn(null); - } -} diff --git a/spec/Encoding/DechunkStreamSpec.php b/spec/Encoding/DechunkStreamSpec.php deleted file mode 100644 index 5a57fe0..0000000 --- a/spec/Encoding/DechunkStreamSpec.php +++ /dev/null @@ -1,46 +0,0 @@ -beConstructedWith($stream); - } - - public function it_is_initializable() - { - $this->shouldHaveType('Http\Message\Encoding\DechunkStream'); - } - - public function it_reads() - { - $stream = new MemoryStream("4\r\ntest\r\n4\r\ntest\r\n0\r\n\r\n\0"); - $this->beConstructedWith($stream); - - $this->read(6)->shouldReturn('testte'); - $this->read(6)->shouldReturn('st'); - } - - public function it_gets_content() - { - $stream = new MemoryStream("4\r\ntest\r\n0\r\n\r\n\0"); - $this->beConstructedWith($stream); - - $this->getContents()->shouldReturn('test'); - } - - public function it_does_not_know_the_content_size() - { - $stream = new MemoryStream("4\r\ntest\r\n4\r\ntest\r\n0\r\n\r\n\0"); - $this->beConstructedWith($stream); - - $this->getSize()->shouldReturn(null); - } -} diff --git a/spec/Encoding/DecompressStreamSpec.php b/spec/Encoding/DecompressStreamSpec.php deleted file mode 100644 index cee6c9a..0000000 --- a/spec/Encoding/DecompressStreamSpec.php +++ /dev/null @@ -1,48 +0,0 @@ -beConstructedWith($stream); - } - - public function it_is_initializable() - { - $this->shouldHaveType('Http\Message\Encoding\DecompressStream'); - } - - public function it_reads() - { - // "This is a test stream" | deflate - $stream = new MemoryStream(gzcompress('This is a test stream')); - $this->beConstructedWith($stream); - - $this->read(4)->shouldReturn('This'); - } - - public function it_gets_content() - { - // "This is a test stream" | deflate - $stream = new MemoryStream(gzcompress('This is a test stream')); - $this->beConstructedWith($stream); - - $this->getContents()->shouldReturn('This is a test stream'); - } - - public function it_does_not_know_the_content_size() - { - $stream = new MemoryStream(gzcompress('This is a test stream')); - $this->beConstructedWith($stream); - - $this->getSize()->shouldReturn(null); - } -} diff --git a/spec/Encoding/DeflateStreamSpec.php b/spec/Encoding/DeflateStreamSpec.php deleted file mode 100644 index 008c58d..0000000 --- a/spec/Encoding/DeflateStreamSpec.php +++ /dev/null @@ -1,47 +0,0 @@ -beConstructedWith($stream); - } - - public function it_is_initializable() - { - $this->shouldHaveType('Http\Message\Encoding\DeflateStream'); - } - - public function it_reads() - { - $stream = new MemoryStream('This is a test stream'); - $this->beConstructedWith($stream); - - $stream->rewind(); - $this->read(4)->shouldReturn(substr(gzdeflate('This is a test stream'), 0, 4)); - } - - public function it_gets_content() - { - $stream = new MemoryStream('This is a test stream'); - $this->beConstructedWith($stream); - - $stream->rewind(); - $this->getContents()->shouldReturn(gzdeflate('This is a test stream')); - } - - public function it_does_not_know_the_content_size() - { - $stream = new MemoryStream('This stream is a test stream'); - $this->beConstructedWith($stream); - - $this->getSize()->shouldReturn(null); - } -} diff --git a/spec/Encoding/FilteredStreamStubSpec.php b/spec/Encoding/FilteredStreamStubSpec.php deleted file mode 100644 index fbaf68c..0000000 --- a/spec/Encoding/FilteredStreamStubSpec.php +++ /dev/null @@ -1,69 +0,0 @@ -beAnInstanceOf('spec\Http\Message\Encoding\FilteredStreamStub'); - $this->beConstructedWith($stream, 'foo'); - $this->shouldThrow('RuntimeException')->duringInstantiation(); - } - - public function it_throws_during_instantiation_with_invalid_write_filter_options(StreamInterface $stream) - { - $this->beAnInstanceOf('spec\Http\Message\Encoding\FilteredStreamStub'); - $this->beConstructedWith($stream, null, 'foo'); - $this->shouldThrow('RuntimeException')->duringInstantiation(); - } - - public function let(StreamInterface $stream) - { - $this->beAnInstanceOf('spec\Http\Message\Encoding\FilteredStreamStub'); - $this->beConstructedWith($stream); - } - - public function it_reads() - { - // "This is a test stream" | base64_encode - $stream = new MemoryStream('This is a test stream'); - $this->beConstructedWith($stream); - - $this->read(4)->shouldReturn('VGhp'); - } - - public function it_gets_content() - { - // "This is a test stream" | base64_encode - $stream = new MemoryStream('This is a test stream'); - $this->beConstructedWith($stream); - - $this->getContents()->shouldReturn('VGhpcyBpcyBhIHRlc3Qgc3RyZWFt'); - } - - public function it_does_not_know_the_content_size() - { - $stream = new MemoryStream(gzencode('This is a test stream')); - $this->beConstructedWith($stream); - - $this->getSize()->shouldBeNull(); - } -} - -class FilteredStreamStub extends FilteredStream -{ - protected function readFilter(): string - { - return 'convert.base64-encode'; - } - - protected function writeFilter(): string - { - return 'convert.base64-encode'; - } -} diff --git a/spec/Encoding/GzipDecodeStreamSpec.php b/spec/Encoding/GzipDecodeStreamSpec.php deleted file mode 100644 index 32ea393..0000000 --- a/spec/Encoding/GzipDecodeStreamSpec.php +++ /dev/null @@ -1,48 +0,0 @@ -beConstructedWith($stream); - } - - public function it_is_initializable() - { - $this->shouldHaveType('Http\Message\Encoding\GzipDecodeStream'); - } - - public function it_reads() - { - // "This is a test stream" | deflate - $stream = new MemoryStream(gzencode('This is a test stream')); - $this->beConstructedWith($stream); - - $this->read(4)->shouldReturn('This'); - } - - public function it_gets_content() - { - // "This is a test stream" | deflate - $stream = new MemoryStream(gzencode('This is a test stream')); - $this->beConstructedWith($stream); - - $this->getContents()->shouldReturn('This is a test stream'); - } - - public function it_does_not_know_the_content_size() - { - $stream = new MemoryStream(gzencode('This is a test stream')); - $this->beConstructedWith($stream); - - $this->getSize()->shouldReturn(null); - } -} diff --git a/spec/Encoding/GzipEncodeStreamSpec.php b/spec/Encoding/GzipEncodeStreamSpec.php deleted file mode 100644 index bcce227..0000000 --- a/spec/Encoding/GzipEncodeStreamSpec.php +++ /dev/null @@ -1,49 +0,0 @@ -beConstructedWith($stream); - } - - public function it_is_initializable() - { - $this->shouldHaveType('Http\Message\Encoding\GzipEncodeStream'); - } - - public function it_reads() - { - $stream = new MemoryStream('This is a test stream'); - $this->beConstructedWith($stream); - - $stream->rewind(); - $this->read(4)->shouldReturn(substr(gzencode('This is a test stream'), 0, 4)); - } - - public function it_gets_content() - { - $stream = new MemoryStream('This is a test stream'); - $this->beConstructedWith($stream); - - $stream->rewind(); - $this->getContents()->shouldReturn(gzencode('This is a test stream')); - } - - public function it_does_not_know_the_content_size() - { - $stream = new MemoryStream('This is a test stream'); - $this->beConstructedWith($stream); - - $stream->rewind(); - $this->getSize()->shouldReturn(null); - } -} diff --git a/spec/Encoding/InflateStreamSpec.php b/spec/Encoding/InflateStreamSpec.php deleted file mode 100644 index f61ff84..0000000 --- a/spec/Encoding/InflateStreamSpec.php +++ /dev/null @@ -1,48 +0,0 @@ -beConstructedWith($stream); - } - - public function it_is_initializable() - { - $this->shouldHaveType('Http\Message\Encoding\InflateStream'); - } - - public function it_reads() - { - // "This is a test stream" | deflate - $stream = new MemoryStream(gzdeflate('This is a test stream')); - $this->beConstructedWith($stream); - - $this->read(4)->shouldReturn('This'); - } - - public function it_gets_content() - { - // "This is a test stream" | deflate - $stream = new MemoryStream(gzdeflate('This is a test stream')); - $this->beConstructedWith($stream); - - $this->getContents()->shouldReturn('This is a test stream'); - } - - public function it_does_not_know_the_content_size() - { - $stream = new MemoryStream(gzdeflate('This stream is a test stream')); - $this->beConstructedWith($stream); - - $this->getSize()->shouldReturn(null); - } -} diff --git a/spec/Encoding/StreamBehavior.php b/spec/Encoding/StreamBehavior.php deleted file mode 100644 index 5834a03..0000000 --- a/spec/Encoding/StreamBehavior.php +++ /dev/null @@ -1,11 +0,0 @@ -shouldImplement('Psr\Http\Message\StreamInterface'); - } -} diff --git a/spec/Encoding/ZlibStreamBehavior.php b/spec/Encoding/ZlibStreamBehavior.php deleted file mode 100644 index 39dce20..0000000 --- a/spec/Encoding/ZlibStreamBehavior.php +++ /dev/null @@ -1,46 +0,0 @@ -shouldThrow('RuntimeException')->duringInstantiation(); - - ZlibExtensionLoadedMock::$enabled = false; - } - } - - class ZlibExtensionLoadedMock - { - /** - * If enabled, the mocked method is used. - * - * @var bool - */ - public static $enabled = false; - - /** - * extension_loaded function mock. - */ - public static function extensionLoaded() - { - if (static::$enabled) { - return false; - } else { - return call_user_func_array('\extension_loaded', func_get_args()); - } - } - } -} - -namespace Http\Message\Encoding { - use spec\Http\Message\Encoding\ZlibExtensionLoadedMock; - - function extension_loaded($extension) - { - return ZlibExtensionLoadedMock::extensionLoaded($extension); - } -} diff --git a/spec/Formatter/CurlCommandFormatterSpec.php b/spec/Formatter/CurlCommandFormatterSpec.php deleted file mode 100644 index e6ed104..0000000 --- a/spec/Formatter/CurlCommandFormatterSpec.php +++ /dev/null @@ -1,154 +0,0 @@ -shouldHaveType('Http\Message\Formatter\CurlCommandFormatter'); - } - - public function it_is_a_formatter() - { - $this->shouldImplement('Http\Message\Formatter'); - } - - public function it_formats_the_request(RequestInterface $request, UriInterface $uri, StreamInterface $body) - { - $request->getUri()->willReturn($uri); - $request->getBody()->willReturn($body); - - $uri->withFragment('')->shouldBeCalled()->willReturn($uri); - $uri->__toString()->shouldBeCalled()->willReturn('http://foo.com/bar'); - $request->getMethod()->willReturn('GET'); - $request->getProtocolVersion()->willReturn('1.1'); - - $request->getHeaders()->willReturn(['foo' => ['bar', 'baz']]); - $request->getHeaderLine('foo')->willReturn('bar, baz'); - - $this->formatRequest($request)->shouldReturn('curl \'http://foo.com/bar\' -H \'foo: bar, baz\''); - } - - public function it_formats_post_request(RequestInterface $request, UriInterface $uri, StreamInterface $body) - { - $request->getUri()->willReturn($uri); - $request->getBody()->willReturn($body); - - $body->__toString()->willReturn('body " data'." test' bar"); - $body->getSize()->willReturn(1); - $body->isSeekable()->willReturn(true); - $body->rewind()->shouldBeCalled(); - - $uri->withFragment('')->shouldBeCalled()->willReturn($uri); - $uri->__toString()->shouldBeCalled()->willReturn('http://foo.com/bar'); - $request->getMethod()->willReturn('POST'); - $request->getProtocolVersion()->willReturn('2.0'); - - $request->getHeaders()->willReturn([]); - - $this->formatRequest($request)->shouldReturn("curl 'http://foo.com/bar' --http2 --request POST --data 'body \" data test'\'' bar'"); - } - - public function it_does_nothing_for_response(ResponseInterface $response, RequestInterface $request) - { - $this->formatResponse($response)->shouldReturn(''); - $this->formatResponseForRequest($response, $request)->shouldReturn(''); - } - - public function it_formats_the_request_with_user_agent(RequestInterface $request, UriInterface $uri, StreamInterface $body) - { - $request->getUri()->willReturn($uri); - $request->getBody()->willReturn($body); - - $uri->withFragment('')->shouldBeCalled()->willReturn($uri); - $uri->__toString()->shouldBeCalled()->willReturn('http://foo.com/bar'); - $request->getMethod()->willReturn('GET'); - $request->getProtocolVersion()->willReturn('1.1'); - $request->getHeaders()->willReturn(['user-agent' => ['foobar-browser']]); - - $this->formatRequest($request)->shouldReturn("curl 'http://foo.com/bar' -A 'foobar-browser'"); - } - - public function it_formats_requests_with_null_bytes(RequestInterface $request, UriInterface $uri, StreamInterface $body) - { - $request->getUri()->willReturn($uri); - $request->getBody()->willReturn($body); - - $body->__toString()->willReturn("\0"); - $body->getSize()->willReturn(1); - $body->isSeekable()->willReturn(true); - $body->rewind()->shouldBeCalled(); - - $uri->withFragment('')->shouldBeCalled()->willReturn($uri); - $uri->__toString()->shouldBeCalled()->willReturn('http://foo.com/bar'); - $request->getMethod()->willReturn('POST'); - $request->getProtocolVersion()->willReturn('1.1'); - $request->getHeaders()->willReturn([]); - - $this->formatRequest($request)->shouldReturn("curl 'http://foo.com/bar' --request POST --data '[binary stream omitted]'"); - } - - public function it_formats_requests_with_line_break(RequestInterface $request, UriInterface $uri, StreamInterface $body) - { - $request->getUri()->willReturn($uri); - $request->getBody()->willReturn($body); - - $body->__toString()->willReturn("foo\nbar"); - $body->getSize()->willReturn(1); - $body->isSeekable()->willReturn(true); - $body->rewind()->shouldBeCalled(); - - $uri->withFragment('')->shouldBeCalled()->willReturn($uri); - $uri->__toString()->shouldBeCalled()->willReturn('http://foo.com/bar'); - $request->getMethod()->willReturn('POST'); - $request->getProtocolVersion()->willReturn('1.1'); - $request->getHeaders()->willReturn([]); - - $this->formatRequest($request)->shouldReturn("curl 'http://foo.com/bar' --request POST --data 'foo\nbar'"); - } - - public function it_formats_requests_with_nonseekable_body(RequestInterface $request, UriInterface $uri, StreamInterface $body) - { - $request->getUri()->willReturn($uri); - $request->getBody()->willReturn($body); - - $body->getSize()->willReturn(1); - $body->isSeekable()->willReturn(false); - $body->__toString()->shouldNotBeCalled(); - $body->rewind()->shouldNotBeCalled(); - - $uri->withFragment('')->shouldBeCalled()->willReturn($uri); - $uri->__toString()->shouldBeCalled()->willReturn('http://foo.com/bar'); - $request->getMethod()->willReturn('POST'); - $request->getProtocolVersion()->willReturn('1.1'); - $request->getHeaders()->willReturn([]); - - $this->formatRequest($request)->shouldReturn("curl 'http://foo.com/bar' --request POST --data '[non-seekable stream omitted]'"); - } - - public function it_formats_requests_with_long_body(RequestInterface $request, UriInterface $uri, StreamInterface $body) - { - $request->getUri()->willReturn($uri); - $request->getBody()->willReturn($body); - - $body->__toString()->shouldNotBeCalled(); - $body->getSize()->willReturn(2097153); - $body->isSeekable()->willReturn(true); - $body->rewind()->shouldNotBeCalled(); - - $uri->withFragment('')->shouldBeCalled()->willReturn($uri); - $uri->__toString()->shouldBeCalled()->willReturn('http://foo.com/bar'); - $request->getMethod()->willReturn('POST'); - $request->getProtocolVersion()->willReturn('1.1'); - $request->getHeaders()->willReturn([]); - - $this->formatRequest($request)->shouldReturn("curl 'http://foo.com/bar' --request POST --data '[too long stream omitted]'"); - } -} diff --git a/spec/Formatter/FullHttpMessageFormatterSpec.php b/spec/Formatter/FullHttpMessageFormatterSpec.php deleted file mode 100644 index e5fa362..0000000 --- a/spec/Formatter/FullHttpMessageFormatterSpec.php +++ /dev/null @@ -1,295 +0,0 @@ -beConstructedWith($maxBodyLength); - } - - public function it_is_initializable() - { - $this->shouldHaveType('Http\Message\Formatter\FullHttpMessageFormatter'); - } - - public function it_is_a_formatter() - { - $this->shouldImplement('Http\Message\Formatter'); - } - - public function it_formats_the_request_with_size_limit(RequestInterface $request, StreamInterface $stream) - { - $this->beConstructedWith(18); - - $stream->isSeekable()->willReturn(true); - $stream->rewind()->shouldBeCalled(); - $stream->__toString()->willReturn('This is an HTML stream request content.'); - $request->getBody()->willReturn($stream); - $request->getMethod()->willReturn('GET'); - $request->getRequestTarget()->willReturn('/foo'); - $request->getProtocolVersion()->willReturn('1.1'); - $request->getHeaders()->willReturn([ - 'X-Param-Foo' => ['foo'], - 'X-Param-Bar' => ['bar'], - ]); - - $expectedMessage = <<formatRequest($request)->shouldReturn($expectedMessage); - } - - public function it_formats_the_request_without_size_limit(RequestInterface $request, StreamInterface $stream) - { - $this->beConstructedWith(null); - - $stream->isSeekable()->willReturn(true); - $stream->rewind()->shouldBeCalled(); - $stream->__toString()->willReturn('This is an HTML stream request content.'); - $request->getBody()->willReturn($stream); - $request->getMethod()->willReturn('GET'); - $request->getRequestTarget()->willReturn('/foo'); - $request->getProtocolVersion()->willReturn('1.1'); - $request->getHeaders()->willReturn([ - 'X-Param-Foo' => ['foo'], - 'X-Param-Bar' => ['bar'], - ]); - - $expectedMessage = <<formatRequest($request)->shouldReturn($expectedMessage); - } - - public function it_does_not_format_the_request(RequestInterface $request, StreamInterface $stream) - { - $this->beConstructedWith(0); - - $stream->isSeekable()->willReturn(true); - $stream->__toString()->willReturn('This is an HTML stream request content.'); - $request->getBody()->willReturn($stream); - $request->getMethod()->willReturn('GET'); - $request->getRequestTarget()->willReturn('/foo'); - $request->getProtocolVersion()->willReturn('1.1'); - $request->getHeaders()->willReturn([ - 'X-Param-Foo' => ['foo'], - 'X-Param-Bar' => ['bar'], - ]); - - $expectedMessage = <<formatRequest($request)->shouldReturn($expectedMessage); - } - - public function it_does_not_format_no_seekable_request(RequestInterface $request, StreamInterface $stream) - { - $this->beConstructedWith(1000); - - $stream->isSeekable()->willReturn(false); - $stream->__toString()->willReturn('This is an HTML stream request content.'); - $request->getBody()->willReturn($stream); - $request->getMethod()->willReturn('GET'); - $request->getRequestTarget()->willReturn('/foo'); - $request->getProtocolVersion()->willReturn('1.1'); - $request->getHeaders()->willReturn([ - 'X-Param-Foo' => ['foo'], - 'X-Param-Bar' => ['bar'], - ]); - - $expectedMessage = <<formatRequest($request)->shouldReturn($expectedMessage); - } - - public function it_formats_the_response_with_size_limit(ResponseInterface $response, StreamInterface $stream, RequestInterface $request) - { - $this->beConstructedWith(18); - - $stream->isSeekable()->willReturn(true); - $stream->rewind()->shouldBeCalled(); - $stream->__toString()->willReturn('This is an HTML stream response content.'); - $response->getBody()->willReturn($stream); - $response->getProtocolVersion()->willReturn('1.1'); - $response->getStatusCode()->willReturn(200); - $response->getReasonPhrase()->willReturn('OK'); - $response->getHeaders()->willReturn([ - 'X-Param-Foo' => ['foo'], - 'X-Param-Bar' => ['bar'], - ]); - - $expectedMessage = <<formatResponse($response)->shouldReturn($expectedMessage); - $this->formatResponseForRequest($response, $request)->shouldReturn($expectedMessage); - } - - public function it_formats_the_response_without_size_limit(ResponseInterface $response, StreamInterface $stream) - { - $this->beConstructedWith(null); - - $stream->isSeekable()->willReturn(true); - $stream->rewind()->shouldBeCalled(); - $stream->__toString()->willReturn('This is an HTML stream response content.'); - $response->getBody()->willReturn($stream); - $response->getProtocolVersion()->willReturn('1.1'); - $response->getStatusCode()->willReturn(200); - $response->getReasonPhrase()->willReturn('OK'); - $response->getHeaders()->willReturn([ - 'X-Param-Foo' => ['foo'], - 'X-Param-Bar' => ['bar'], - ]); - - $expectedMessage = <<formatResponse($response)->shouldReturn($expectedMessage); - } - - public function it_does_not_format_the_response(ResponseInterface $response, StreamInterface $stream) - { - $this->beConstructedWith(0); - - $stream->isSeekable()->willReturn(true); - $stream->__toString()->willReturn('This is an HTML stream response content.'); - $response->getBody()->willReturn($stream); - $response->getProtocolVersion()->willReturn('1.1'); - $response->getStatusCode()->willReturn(200); - $response->getReasonPhrase()->willReturn('OK'); - $response->getHeaders()->willReturn([ - 'X-Param-Foo' => ['foo'], - 'X-Param-Bar' => ['bar'], - ]); - - $expectedMessage = <<formatResponse($response)->shouldReturn($expectedMessage); - } - - public function it_does_not_format_no_seekable_response(ResponseInterface $response, StreamInterface $stream) - { - $this->beConstructedWith(1000); - - $stream->isSeekable()->willReturn(false); - $stream->__toString()->willReturn('This is an HTML stream response content.'); - $response->getBody()->willReturn($stream); - $response->getProtocolVersion()->willReturn('1.1'); - $response->getStatusCode()->willReturn(200); - $response->getReasonPhrase()->willReturn('OK'); - $response->getHeaders()->willReturn([ - 'X-Param-Foo' => ['foo'], - 'X-Param-Bar' => ['bar'], - ]); - - $expectedMessage = <<formatResponse($response)->shouldReturn($expectedMessage); - } - - public function it_omits_body_with_null_bytes(RequestInterface $request, StreamInterface $stream) - { - $this->beConstructedWith(1); - - $stream->isSeekable()->willReturn(true); - $stream->rewind()->shouldBeCalled(); - $stream->__toString()->willReturn("\0"); - $request->getBody()->willReturn($stream); - $request->getMethod()->willReturn('GET'); - $request->getRequestTarget()->willReturn('/foo'); - $request->getProtocolVersion()->willReturn('1.1'); - $request->getHeaders()->willReturn([]); - - $expectedMessage = <<formatRequest($request)->shouldReturn($expectedMessage); - } - - public function it_allows_to_change_binary_detection(RequestInterface $request, StreamInterface $stream) - { - $this->beConstructedWith(1, '/\x01/'); - - $stream->isSeekable()->willReturn(true); - $stream->rewind()->shouldBeCalled(); - $stream->__toString()->willReturn("\0"); - $request->getBody()->willReturn($stream); - $request->getMethod()->willReturn('GET'); - $request->getRequestTarget()->willReturn('/foo'); - $request->getProtocolVersion()->willReturn('1.1'); - $request->getHeaders()->willReturn([]); - - $expectedMessage = <<formatRequest($request)->shouldReturn($expectedMessage); - } - - public function it_omits_body_with_line_break(RequestInterface $request, StreamInterface $stream) - { - $this->beConstructedWith(7); - - $stream->isSeekable()->willReturn(true); - $stream->rewind()->shouldBeCalled(); - $stream->__toString()->willReturn("foo\nbar"); - $request->getBody()->willReturn($stream); - $request->getMethod()->willReturn('GET'); - $request->getRequestTarget()->willReturn('/foo'); - $request->getProtocolVersion()->willReturn('1.1'); - $request->getHeaders()->willReturn([]); - - $expectedMessage = <<formatRequest($request)->shouldReturn($expectedMessage); - } -} diff --git a/spec/Formatter/SimpleFormatterSpec.php b/spec/Formatter/SimpleFormatterSpec.php deleted file mode 100644 index c8fc5cf..0000000 --- a/spec/Formatter/SimpleFormatterSpec.php +++ /dev/null @@ -1,41 +0,0 @@ -shouldHaveType('Http\Message\Formatter\SimpleFormatter'); - } - - public function it_is_a_formatter() - { - $this->shouldImplement('Http\Message\Formatter'); - } - - public function it_formats_the_request(RequestInterface $request, UriInterface $uri) - { - $uri->__toString()->willReturn('http://foo.com/bar'); - $request->getMethod()->willReturn('GET'); - $request->getUri()->willReturn($uri); - $request->getProtocolVersion()->willReturn('1.1'); - - $this->formatRequest($request)->shouldReturn('GET http://foo.com/bar 1.1'); - } - - public function it_formats_the_response(ResponseInterface $response, RequestInterface $request) - { - $response->getReasonPhrase()->willReturn('OK'); - $response->getProtocolVersion()->willReturn('1.1'); - $response->getStatusCode()->willReturn('200'); - - $this->formatResponse($response)->shouldReturn('200 OK 1.1'); - $this->formatResponseForRequest($response, $request)->shouldReturn('200 OK 1.1'); - } -} diff --git a/spec/MessageFactory/DiactorosMessageFactorySpec.php b/spec/MessageFactory/DiactorosMessageFactorySpec.php deleted file mode 100644 index 89cffb3..0000000 --- a/spec/MessageFactory/DiactorosMessageFactorySpec.php +++ /dev/null @@ -1,15 +0,0 @@ -shouldHaveType('Http\Message\MessageFactory\DiactorosMessageFactory'); - } -} diff --git a/spec/MessageFactory/GuzzleMessageFactorySpec.php b/spec/MessageFactory/GuzzleMessageFactorySpec.php deleted file mode 100644 index be7de66..0000000 --- a/spec/MessageFactory/GuzzleMessageFactorySpec.php +++ /dev/null @@ -1,15 +0,0 @@ -shouldHaveType('Http\Message\MessageFactory\GuzzleMessageFactory'); - } -} diff --git a/spec/MessageFactory/MessageFactoryBehavior.php b/spec/MessageFactory/MessageFactoryBehavior.php deleted file mode 100644 index 42c51ae..0000000 --- a/spec/MessageFactory/MessageFactoryBehavior.php +++ /dev/null @@ -1,29 +0,0 @@ -shouldImplement('Http\Message\MessageFactory'); - } - - public function it_creates_a_request() - { - $request = $this->createRequest('GET', '/', ['X-hello' => 'world'], 'lorem'); - - $request->shouldHaveType('Psr\Http\Message\RequestInterface'); - $request->getMethod()->shouldReturn('GET'); - $request->getRequestTarget()->shouldReturn('/'); - $request->getBody()->__toString()->shouldReturn('lorem'); - $request->getHeaderLine('X-hello')->shouldReturn('world'); - } - - public function it_creates_a_response() - { - $response = $this->createResponse(); - - $response->shouldHaveType('Psr\Http\Message\ResponseInterface'); - } -} diff --git a/spec/MessageFactory/SlimMessageFactorySpec.php b/spec/MessageFactory/SlimMessageFactorySpec.php deleted file mode 100644 index b549a55..0000000 --- a/spec/MessageFactory/SlimMessageFactorySpec.php +++ /dev/null @@ -1,18 +0,0 @@ -shouldHaveType('Http\Message\MessageFactory\SlimMessageFactory'); - } -} diff --git a/spec/RequestMatcher/CallbackRequestMatcherSpec.php b/spec/RequestMatcher/CallbackRequestMatcherSpec.php deleted file mode 100644 index fbf12a5..0000000 --- a/spec/RequestMatcher/CallbackRequestMatcherSpec.php +++ /dev/null @@ -1,42 +0,0 @@ -beConstructedWith(function () {}); - } - - public function it_is_initializable() - { - $this->shouldHaveType('Http\Message\RequestMatcher\CallbackRequestMatcher'); - } - - public function it_is_a_request_matcher() - { - $this->shouldImplement('Http\Message\RequestMatcher'); - } - - public function it_matches_a_request(RequestInterface $request) - { - $callback = function () { return true; }; - - $this->beConstructedWith($callback); - - $this->matches($request)->shouldReturn(true); - } - - public function it_does_not_match_a_request(RequestInterface $request) - { - $callback = function () { return false; }; - - $this->beConstructedWith($callback); - - $this->matches($request)->shouldReturn(false); - } -} diff --git a/spec/RequestMatcher/RegexRequestMatcherSpec.php b/spec/RequestMatcher/RegexRequestMatcherSpec.php deleted file mode 100644 index 9f1dc7a..0000000 --- a/spec/RequestMatcher/RegexRequestMatcherSpec.php +++ /dev/null @@ -1,45 +0,0 @@ -beConstructedWith($regex); - } - - public function it_is_initializable() - { - $this->shouldHaveType('Http\Message\RequestMatcher\RegexRequestMatcher'); - } - - public function it_is_a_request_matcher() - { - $this->shouldImplement('Http\Message\RequestMatcher'); - } - - public function it_matches_a_request(RequestInterface $request, UriInterface $uri) - { - $this->beConstructedWith('/test/'); - - $request->getUri()->willReturn($uri); - $uri->__toString()->willReturn('/test'); - - $this->matches($request)->shouldReturn(true); - } - - public function it_does_not_match_a_request(RequestInterface $request, UriInterface $uri) - { - $this->beConstructedWith('/test/'); - - $request->getUri()->willReturn($uri); - $uri->__toString()->willReturn('/ttttt'); - - $this->matches($request)->shouldReturn(false); - } -} diff --git a/spec/RequestMatcher/RequestMatcherSpec.php b/spec/RequestMatcher/RequestMatcherSpec.php deleted file mode 100644 index 0a000f1..0000000 --- a/spec/RequestMatcher/RequestMatcherSpec.php +++ /dev/null @@ -1,98 +0,0 @@ -shouldHaveType('Http\Message\RequestMatcher\RequestMatcher'); - } - - public function it_is_a_request_matcher() - { - $this->shouldImplement('Http\Message\RequestMatcher'); - } - - public function it_matches_a_path(RequestInterface $request, UriInterface $uri) - { - $this->beConstructedWith('^/tes?'); - - $request->getUri()->willReturn($uri); - $uri->getPath()->willReturn('/test/foo'); - - $this->matches($request)->shouldReturn(true); - } - - public function it_does_not_match_a_path(RequestInterface $request, UriInterface $uri) - { - $this->beConstructedWith('#^/tes?#'); - - $request->getUri()->willReturn($uri); - $uri->getPath()->willReturn('/ttttt'); - - $this->matches($request)->shouldReturn(false); - } - - public function it_matches_a_host(RequestInterface $request, UriInterface $uri) - { - $this->beConstructedWith(null, 'php-htt?'); - - $request->getUri()->willReturn($uri); - $uri->getHost()->willReturn('php-http.org'); - - $this->matches($request)->shouldReturn(true); - } - - public function it_does_not_match_a_host(RequestInterface $request, UriInterface $uri) - { - $this->beConstructedWith(null, 'php-htt?'); - - $request->getUri()->willReturn($uri); - $uri->getHost()->willReturn('httplug.io'); - - $this->matches($request)->shouldReturn(false); - } - - public function it_matches_a_method(RequestInterface $request) - { - $this->beConstructedWith(null, null, 'get'); - - $request->getMethod()->willReturn('GET'); - - $this->matches($request)->shouldReturn(true); - } - - public function it_does_not_match_a_method(RequestInterface $request) - { - $this->beConstructedWith(null, null, 'get'); - - $request->getMethod()->willReturn('post'); - - $this->matches($request)->shouldReturn(false); - } - - public function it_matches_a_scheme(RequestInterface $request, UriInterface $uri) - { - $this->beConstructedWith(null, null, null, 'http'); - - $request->getUri()->willReturn($uri); - $uri->getScheme()->willReturn('http'); - - $this->matches($request)->shouldReturn(true); - } - - public function it_does_not_match_a_scheme(RequestInterface $request, UriInterface $uri) - { - $this->beConstructedWith(null, null, null, 'http'); - - $request->getUri()->willReturn($uri); - $uri->getScheme()->willReturn('https'); - - $this->matches($request)->shouldReturn(false); - } -} diff --git a/spec/Stream/BufferedStreamSpec.php b/spec/Stream/BufferedStreamSpec.php deleted file mode 100644 index f80fa69..0000000 --- a/spec/Stream/BufferedStreamSpec.php +++ /dev/null @@ -1,184 +0,0 @@ -beConstructedWith($stream); - - $stream->getSize()->willReturn(null); - } - - public function it_is_castable_to_string(StreamInterface $stream) - { - $eofCounter = 0; - $stream->eof()->will(function () use (&$eofCounter) { - return ++$eofCounter > 1; - }); - - $stream->read(8192)->willReturn('foo'); - - $this->__toString()->shouldReturn('foo'); - } - - public function it_detachs(StreamInterface $stream) - { - $stream->eof()->willReturn(true); - $stream->read(8192)->willReturn(''); - $stream->close()->shouldBeCalled(); - - $this->detach()->shouldBeResource(); - $this->detach()->shouldBeNull(); - } - - public function it_gets_size(StreamInterface $stream) - { - $stream->eof()->willReturn(false); - $this->getSize()->shouldReturn(null); - - $eofCounter = 0; - $stream->eof()->will(function () use (&$eofCounter) { - return ++$eofCounter > 1; - }); - - $stream->read(8192)->willReturn('foo'); - - $this->getContents()->shouldReturn('foo'); - $this->getSize()->shouldReturn(3); - } - - public function it_tells(StreamInterface $stream) - { - $this->tell()->shouldReturn(0); - - $eofCounter = 0; - $stream->eof()->will(function () use (&$eofCounter) { - return ++$eofCounter > 1; - }); - - $stream->read(8192)->willReturn('foo'); - $this->getContents()->shouldReturn('foo'); - $this->tell()->shouldReturn(3); - } - - public function it_eof(StreamInterface $stream) - { - // Case when underlying is false - $stream->eof()->willReturn(false); - $this->eof()->shouldReturn(false); - - // Case when sync and underlying is true - $stream->eof()->willReturn(true); - $this->eof()->shouldReturn(true); - - // Case not sync but underlying is true - $eofCounter = 0; - $stream->eof()->will(function () use (&$eofCounter) { - return ++$eofCounter > 1; - }); - - $stream->read(8192)->willReturn('foo'); - - $this->getContents()->shouldReturn('foo'); - $this->seek(0); - - $stream->eof()->willReturn(true); - $this->eof()->shouldReturn(false); - } - - public function it_is_seekable(StreamInterface $stream) - { - $this->isSeekable()->shouldReturn(true); - } - - public function it_seeks(StreamInterface $stream) - { - $this->seek(0); - $this->tell()->shouldReturn(0); - - $eofCounter = 0; - $stream->eof()->will(function () use (&$eofCounter) { - return ++$eofCounter > 1; - }); - - $stream->read(8192)->willReturn('foo'); - - $this->getContents()->shouldReturn('foo'); - $this->seek(2); - $this->tell()->shouldReturn(2); - } - - public function it_rewinds(StreamInterface $stream) - { - $this->rewind(); - $this->tell()->shouldReturn(0); - - $eofCounter = 0; - $stream->eof()->will(function () use (&$eofCounter) { - return ++$eofCounter > 1; - }); - - $stream->read(8192)->willReturn('foo'); - - $this->getContents()->shouldReturn('foo'); - $this->tell()->shouldReturn(3); - $this->rewind(); - $this->tell()->shouldReturn(0); - } - - public function it_is_not_writable(StreamInterface $stream) - { - $this->isWritable()->shouldReturn(false); - $this->shouldThrow('\RuntimeException')->duringWrite('foo'); - } - - public function it_is_readable(StreamInterface $stream) - { - $this->isReadable()->shouldReturn(true); - } - - public function it_reads(StreamInterface $stream) - { - $eofCounter = 0; - $stream->eof()->will(function () use (&$eofCounter) { - return ++$eofCounter > 1; - }); - - $stream->read(3)->willReturn('foo'); - $this->read(3)->shouldReturn('foo'); - - $stream->read(3)->willReturn('bar'); - $this->read(3)->shouldReturn('bar'); - - $this->rewind(); - $this->read(4)->shouldReturn('foob'); - - $stream->read(3)->willReturn('baz'); - $this->read(5)->shouldReturn('arbaz'); - } - - public function it_get_contents(StreamInterface $stream) - { - $eofCounter = 0; - $stream->eof()->will(function () use (&$eofCounter) { - return ++$eofCounter > 1; - }); - - $stream->read(8192)->willReturn('foo'); - - $this->getContents()->shouldReturn('foo'); - $this->eof()->shouldReturn(true); - } - - public function it_get_metadatas(StreamInterface $stream) - { - $this->getMetadata()->shouldBeArray(); - $this->getMetadata('unexistant')->shouldBeNull(); - $this->getMetadata('stream_type')->shouldReturn('TEMP'); - } -} diff --git a/spec/StreamFactory/DiactorosStreamFactorySpec.php b/spec/StreamFactory/DiactorosStreamFactorySpec.php deleted file mode 100644 index f7da767..0000000 --- a/spec/StreamFactory/DiactorosStreamFactorySpec.php +++ /dev/null @@ -1,22 +0,0 @@ -shouldHaveType('Http\Message\StreamFactory\DiactorosStreamFactory'); - } - - public function it_creates_a_stream_from_stream() - { - $this->createStream(new Stream('php://memory')) - ->shouldHaveType('Psr\Http\Message\StreamInterface'); - } -} diff --git a/spec/StreamFactory/GuzzleStreamFactorySpec.php b/spec/StreamFactory/GuzzleStreamFactorySpec.php deleted file mode 100644 index 799a01d..0000000 --- a/spec/StreamFactory/GuzzleStreamFactorySpec.php +++ /dev/null @@ -1,22 +0,0 @@ -shouldHaveType('Http\Message\StreamFactory\GuzzleStreamFactory'); - } - - public function it_creates_a_stream_from_stream() - { - $this->createStream(new Stream(fopen('php://memory', 'rw'))) - ->shouldHaveType('Psr\Http\Message\StreamInterface'); - } -} diff --git a/spec/StreamFactory/SlimStreamFactorySpec.php b/spec/StreamFactory/SlimStreamFactorySpec.php deleted file mode 100644 index 308f739..0000000 --- a/spec/StreamFactory/SlimStreamFactorySpec.php +++ /dev/null @@ -1,26 +0,0 @@ -shouldHaveType('Http\Message\StreamFactory\SlimStreamFactory'); - } - - public function it_creates_a_stream_from_stream() - { - $resource = fopen('php://memory', 'rw'); - $this->createStream(new Stream($resource)) - ->shouldHaveType('Psr\Http\Message\StreamInterface'); - } -} diff --git a/spec/StreamFactory/StreamFactoryBehavior.php b/spec/StreamFactory/StreamFactoryBehavior.php deleted file mode 100644 index 5a4953c..0000000 --- a/spec/StreamFactory/StreamFactoryBehavior.php +++ /dev/null @@ -1,67 +0,0 @@ -shouldImplement('Http\Message\StreamFactory'); - } - - public function it_creates_a_stream_from_string() - { - $this->createStream('foo')->shouldHaveType('Psr\Http\Message\StreamInterface'); - } - - public function it_creates_a_stream_from_resource() - { - $this->createStream(fopen('php://memory', 'rw')) - ->shouldHaveType('Psr\Http\Message\StreamInterface'); - } - - public function it_creates_a_stream_from_null() - { - $this->createStream(null)->shouldHaveType('Psr\Http\Message\StreamInterface'); - } - - public function it_creates_a_stream_from_non_seekable_resource() - { - $url = 'https://raw.githubusercontent.com/php-http/multipart-stream-builder/master/tests/Resources/httplug.png'; - $resource = fopen($url, 'r'); - $this->createStream($resource) - ->shouldHaveType('Psr\Http\Message\StreamInterface'); - } - - public function it_does_not_rewind_existing_stream() - { - $stream = new Stream(fopen('php://memory', 'rw')); - $stream->write('abcdef'); - $stream->seek(3); - - $this->createStream($stream) - ->shouldHaveContent('def'); - } - - public function it_does_not_rewind_existing_resource() - { - $resource = fopen('php://memory', 'rw'); - fwrite($resource, 'abcdef'); - fseek($resource, 3); - - $this->createStream($resource) - ->shouldHaveContent('def'); - } - - public function getMatchers(): array - { - return [ - 'haveContent' => function (StreamInterface $subject, $key) { - return $subject->getContents() === $key; - }, - ]; - } -} diff --git a/spec/UriFactory/DiactorosUriFactorySpec.php b/spec/UriFactory/DiactorosUriFactorySpec.php deleted file mode 100644 index d362dcd..0000000 --- a/spec/UriFactory/DiactorosUriFactorySpec.php +++ /dev/null @@ -1,24 +0,0 @@ -shouldHaveType('Http\Message\UriFactory\DiactorosUriFactory'); - } - - /** - * TODO: Remove this when https://github.com/phpspec/phpspec/issues/825 is resolved. - */ - public function it_creates_a_uri_from_uri(UriInterface $uri) - { - $this->createUri($uri)->shouldReturn($uri); - } -} diff --git a/spec/UriFactory/GuzzleUriFactorySpec.php b/spec/UriFactory/GuzzleUriFactorySpec.php deleted file mode 100644 index a9b5510..0000000 --- a/spec/UriFactory/GuzzleUriFactorySpec.php +++ /dev/null @@ -1,24 +0,0 @@ -shouldHaveType('Http\Message\UriFactory\GuzzleUriFactory'); - } - - /** - * TODO: Remove this when https://github.com/phpspec/phpspec/issues/825 is resolved. - */ - public function it_creates_a_uri_from_uri(UriInterface $uri) - { - $this->createUri($uri)->shouldReturn($uri); - } -} diff --git a/spec/UriFactory/SlimUriFactorySpec.php b/spec/UriFactory/SlimUriFactorySpec.php deleted file mode 100644 index a486625..0000000 --- a/spec/UriFactory/SlimUriFactorySpec.php +++ /dev/null @@ -1,27 +0,0 @@ -shouldHaveType('Http\Message\UriFactory\SlimUriFactory'); - } - - /** - * TODO: Remove this when https://github.com/phpspec/phpspec/issues/825 is resolved. - */ - public function it_creates_a_uri_from_uri(UriInterface $uri) - { - $this->createUri($uri)->shouldReturn($uri); - } -} diff --git a/spec/UriFactory/UriFactoryBehavior.php b/spec/UriFactory/UriFactoryBehavior.php deleted file mode 100644 index f7116bc..0000000 --- a/spec/UriFactory/UriFactoryBehavior.php +++ /dev/null @@ -1,28 +0,0 @@ -shouldImplement('Http\Message\UriFactory'); - } - - public function it_creates_a_uri_from_string() - { - $this->createUri('http://php-http.org')->shouldHaveType('Psr\Http\Message\UriInterface'); - } - - public function it_creates_a_uri_from_uri(UriInterface $uri) - { - $this->createUri($uri)->shouldReturn($uri); - } - - public function it_throws_an_exception_when_uri_is_invalid() - { - $this->shouldThrow('InvalidArgumentException')->duringCreateUri(null); - } -} diff --git a/src/Builder/ResponseBuilder.php b/src/Builder/ResponseBuilder.php index 4c3ecfc..ee9630e 100644 --- a/src/Builder/ResponseBuilder.php +++ b/src/Builder/ResponseBuilder.php @@ -64,7 +64,7 @@ public function setHeadersFromArray(array $headers) /** * Add headers represented by a single string. * - * @param string $headers response headers as single string + * @param string|\Stringable $headers response headers as single string * * @return $this * @@ -80,16 +80,24 @@ public function setHeadersFromString($headers) sprintf( '%s expects parameter 1 to be a string, %s given', __METHOD__, - is_object($headers) ? get_class($headers) : gettype($headers) + self::describeType($headers) ) ); } - $this->setHeadersFromArray(explode("\r\n", $headers)); + $this->setHeadersFromArray(explode("\r\n", (string) $headers)); return $this; } + /** + * @param mixed $value value whose type is described in error messages + */ + private static function describeType($value): string + { + return is_object($value) ? get_class($value) : gettype($value); + } + /** * Set response status from a status string. * diff --git a/src/CookieUtil.php b/src/CookieUtil.php index 44c5314..0177a8c 100644 --- a/src/CookieUtil.php +++ b/src/CookieUtil.php @@ -10,7 +10,7 @@ final class CookieUtil * Handles dates as defined by RFC 2616 section 3.3.1, and also some other * non-standard, but common formats. * - * @var array + * @var string[] */ private static $dateFormats = [ 'D, d M y H:i:s T', @@ -34,6 +34,9 @@ final class CookieUtil */ public static function parseDate($dateValue) { + if (!is_string($dateValue)) { + throw new \InvalidArgumentException('Date must be of type string, given '.gettype($dateValue)); + } foreach (self::$dateFormats as $dateFormat) { if (false !== $date = \DateTime::createFromFormat($dateFormat, $dateValue, new \DateTimeZone('GMT'))) { return $date; diff --git a/src/Encoding/Filter/Chunk.php b/src/Encoding/Filter/Chunk.php index 7a9e18f..8002e35 100644 --- a/src/Encoding/Filter/Chunk.php +++ b/src/Encoding/Filter/Chunk.php @@ -12,12 +12,14 @@ class Chunk extends \php_user_filter public function filter($in, $out, &$consumed, $closing): int { while ($bucket = stream_bucket_make_writeable($in)) { + /* @phpstan-ignore argument.type */ $lenbucket = stream_bucket_new($this->stream, dechex($bucket->datalen)."\r\n"); stream_bucket_append($out, $lenbucket); $consumed += $bucket->datalen; stream_bucket_append($out, $bucket); + /* @phpstan-ignore argument.type */ $lenbucket = stream_bucket_new($this->stream, "\r\n"); stream_bucket_append($out, $lenbucket); } diff --git a/src/Encoding/FilteredStream.php b/src/Encoding/FilteredStream.php index 4bc44a6..6a92d41 100644 --- a/src/Encoding/FilteredStream.php +++ b/src/Encoding/FilteredStream.php @@ -113,9 +113,11 @@ public function eof(): bool protected function fill(): void { $readFilterCallback = $this->readFilterCallback; + /* @phpstan-ignore assignOp.invalid */ $this->buffer .= $readFilterCallback($this->stream->read(self::BUFFER_SIZE)); if ($this->stream->eof()) { + /* @phpstan-ignore assignOp.invalid */ $this->buffer .= $readFilterCallback(); } } diff --git a/tests/Authentication/AutoBasicAuthTest.php b/tests/Authentication/AutoBasicAuthTest.php new file mode 100644 index 0000000..bbf4cdb --- /dev/null +++ b/tests/Authentication/AutoBasicAuthTest.php @@ -0,0 +1,95 @@ +createStub(RequestInterface::class); + $uriWithoutUserInfo = $this->createStub(UriInterface::class); + + $requestWithoutUserInfo = $this->createMock(RequestInterface::class); + $requestWithoutUserInfo->expects($this->once()) + ->method('withHeader') + ->with('Authorization', 'Basic '.base64_encode('username:password')) + ->willReturn($authenticatedRequest); + + $uri = $this->createMock(UriInterface::class); + $uri->method('getUserInfo')->willReturn('username:password'); + $uri->expects($this->once())->method('withUserInfo')->with('')->willReturn($uriWithoutUserInfo); + + $request = $this->createMock(RequestInterface::class); + $request->method('getUri')->willReturn($uri); + $request->expects($this->once())->method('withUri')->with($uriWithoutUserInfo)->willReturn($requestWithoutUserInfo); + + self::assertSame($authenticatedRequest, (new AutoBasicAuth())->authenticate($request)); + } + + public function testAuthenticatesRequestWithoutPassword(): void + { + $authenticatedRequest = $this->createStub(RequestInterface::class); + $uriWithoutUserInfo = $this->createStub(UriInterface::class); + + $requestWithoutUserInfo = $this->createMock(RequestInterface::class); + $requestWithoutUserInfo->expects($this->once()) + ->method('withHeader') + ->with('Authorization', 'Basic '.base64_encode('username')) + ->willReturn($authenticatedRequest); + + $uri = $this->createMock(UriInterface::class); + $uri->method('getUserInfo')->willReturn('username'); + $uri->expects($this->once())->method('withUserInfo')->with('')->willReturn($uriWithoutUserInfo); + + $request = $this->createMock(RequestInterface::class); + $request->method('getUri')->willReturn($uri); + $request->expects($this->once())->method('withUri')->with($uriWithoutUserInfo)->willReturn($requestWithoutUserInfo); + + self::assertSame($authenticatedRequest, (new AutoBasicAuth())->authenticate($request)); + } + + public function testDoesNotAuthenticateRequestWithoutUserInfo(): void + { + $uri = $this->createStub(UriInterface::class); + $uri->method('getUserInfo')->willReturn(''); + + $request = $this->createMock(RequestInterface::class); + $request->method('getUri')->willReturn($uri); + $request->expects($this->never())->method('withHeader'); + $request->expects($this->never())->method('withUri'); + + self::assertSame($request, (new AutoBasicAuth())->authenticate($request)); + } + + public function testAuthenticatesRequestWithoutRemovingUserInfo(): void + { + $authenticatedRequest = $this->createStub(RequestInterface::class); + + $uri = $this->createMock(UriInterface::class); + $uri->method('getUserInfo')->willReturn('username:password'); + $uri->expects($this->never())->method('withUserInfo'); + + $request = $this->createMock(RequestInterface::class); + $request->method('getUri')->willReturn($uri); + $request->expects($this->never())->method('withUri'); + $request->expects($this->once()) + ->method('withHeader') + ->with('Authorization', 'Basic '.base64_encode('username:password')) + ->willReturn($authenticatedRequest); + + self::assertSame($authenticatedRequest, (new AutoBasicAuth(false))->authenticate($request)); + } +} diff --git a/tests/Authentication/BasicAuthTest.php b/tests/Authentication/BasicAuthTest.php new file mode 100644 index 0000000..82610b0 --- /dev/null +++ b/tests/Authentication/BasicAuthTest.php @@ -0,0 +1,31 @@ +createStub(RequestInterface::class); + + $request = $this->createMock(RequestInterface::class); + $request->expects($this->once()) + ->method('withHeader') + ->with('Authorization', 'Basic '.base64_encode('john.doe:secret')) + ->willReturn($newRequest); + + self::assertSame($newRequest, (new BasicAuth('john.doe', 'secret'))->authenticate($request)); + } +} diff --git a/tests/Authentication/BearerTest.php b/tests/Authentication/BearerTest.php new file mode 100644 index 0000000..e72094c --- /dev/null +++ b/tests/Authentication/BearerTest.php @@ -0,0 +1,31 @@ +createStub(RequestInterface::class); + + $request = $this->createMock(RequestInterface::class); + $request->expects($this->once()) + ->method('withHeader') + ->with('Authorization', 'Bearer token') + ->willReturn($newRequest); + + self::assertSame($newRequest, (new Bearer('token'))->authenticate($request)); + } +} diff --git a/tests/Authentication/ChainTest.php b/tests/Authentication/ChainTest.php new file mode 100644 index 0000000..1e1e598 --- /dev/null +++ b/tests/Authentication/ChainTest.php @@ -0,0 +1,47 @@ +expectException(\InvalidArgumentException::class); + + new Chain(['authentication']); + } + + public function testReturnsRequestUnchangedWhenChainIsEmpty(): void + { + $request = $this->createStub(RequestInterface::class); + + self::assertSame($request, (new Chain())->authenticate($request)); + } + + public function testAuthenticatesRequestThroughAllMembersInOrder(): void + { + $originalRequest = $this->createStub(RequestInterface::class); + $request1 = $this->createStub(RequestInterface::class); + $request2 = $this->createStub(RequestInterface::class); + + $auth1 = $this->createMock(Authentication::class); + $auth1->expects($this->once())->method('authenticate')->with($originalRequest)->willReturn($request1); + + $auth2 = $this->createMock(Authentication::class); + $auth2->expects($this->once())->method('authenticate')->with($request1)->willReturn($request2); + + self::assertSame($request2, (new Chain([$auth1, $auth2]))->authenticate($originalRequest)); + } +} diff --git a/tests/Authentication/HeaderTest.php b/tests/Authentication/HeaderTest.php new file mode 100644 index 0000000..78fcfee --- /dev/null +++ b/tests/Authentication/HeaderTest.php @@ -0,0 +1,31 @@ +createStub(RequestInterface::class); + + $request = $this->createMock(RequestInterface::class); + $request->expects($this->once()) + ->method('withHeader') + ->with('X-AUTH-TOKEN', 'REAL') + ->willReturn($newRequest); + + self::assertSame($newRequest, (new Header('X-AUTH-TOKEN', 'REAL'))->authenticate($request)); + } +} diff --git a/tests/Authentication/MatchingTest.php b/tests/Authentication/MatchingTest.php new file mode 100644 index 0000000..ef54364 --- /dev/null +++ b/tests/Authentication/MatchingTest.php @@ -0,0 +1,64 @@ +createStub(Authentication::class))); + } + + public function testAuthenticatesMatchingRequest(): void + { + $request = $this->createStub(RequestInterface::class); + $newRequest = $this->createStub(RequestInterface::class); + + $authentication = $this->createMock(Authentication::class); + $authentication->expects($this->once())->method('authenticate')->with($request)->willReturn($newRequest); + + $matching = new Matching($authentication, function () { + return true; + }); + + self::assertSame($newRequest, $matching->authenticate($request)); + } + + public function testDoesNotAuthenticateNonMatchingRequest(): void + { + $request = $this->createStub(RequestInterface::class); + + $authentication = $this->createMock(Authentication::class); + $authentication->expects($this->never())->method('authenticate'); + + $matching = new Matching($authentication, function () { + return false; + }); + + self::assertSame($request, $matching->authenticate($request)); + } + + public function testCreatesUrlMatcher(): void + { + $matchingRequest = $this->createStub(RequestInterface::class); + $matchingRequest->method('getRequestTarget')->willReturn('/api/users'); + $otherRequest = $this->createStub(RequestInterface::class); + $otherRequest->method('getRequestTarget')->willReturn('/public'); + $authenticatedRequest = $this->createStub(RequestInterface::class); + + $authentication = $this->createMock(Authentication::class); + $authentication->expects($this->once())->method('authenticate')->with($matchingRequest)->willReturn($authenticatedRequest); + + $matching = Matching::createUrlMatcher($authentication, '#^/api#'); + + self::assertSame($authenticatedRequest, $matching->authenticate($matchingRequest)); + self::assertSame($otherRequest, $matching->authenticate($otherRequest)); + } +} diff --git a/tests/Authentication/QueryParamTest.php b/tests/Authentication/QueryParamTest.php new file mode 100644 index 0000000..faf4188 --- /dev/null +++ b/tests/Authentication/QueryParamTest.php @@ -0,0 +1,43 @@ +createStub(UriInterface::class); + $newRequest = $this->createStub(RequestInterface::class); + + $uri = $this->createMock(UriInterface::class); + $uri->method('getQuery')->willReturn('param1=value1¶m2[]=value2'); + $uri->expects($this->once()) + ->method('withQuery') + ->with('param1=value1¶m2%5B0%5D=value2&username=username&password=password') + ->willReturn($newUri); + + $request = $this->createMock(RequestInterface::class); + $request->method('getUri')->willReturn($uri); + $request->expects($this->once())->method('withUri')->with($newUri)->willReturn($newRequest); + + $authentication = new QueryParam([ + 'username' => 'username', + 'password' => 'password', + ]); + + self::assertSame($newRequest, $authentication->authenticate($request)); + } +} diff --git a/tests/Authentication/RequestConditionalTest.php b/tests/Authentication/RequestConditionalTest.php new file mode 100644 index 0000000..d6268f4 --- /dev/null +++ b/tests/Authentication/RequestConditionalTest.php @@ -0,0 +1,51 @@ +createStub(RequestMatcher::class), + $this->createStub(Authentication::class) + ); + + self::assertInstanceOf(Authentication::class, $authentication); + } + + public function testAuthenticatesMatchingRequest(): void + { + $request = $this->createStub(RequestInterface::class); + $newRequest = $this->createStub(RequestInterface::class); + + $requestMatcher = $this->createMock(RequestMatcher::class); + $requestMatcher->expects($this->once())->method('matches')->with($request)->willReturn(true); + + $authentication = $this->createMock(Authentication::class); + $authentication->expects($this->once())->method('authenticate')->with($request)->willReturn($newRequest); + + self::assertSame($newRequest, (new RequestConditional($requestMatcher, $authentication))->authenticate($request)); + } + + public function testDoesNotAuthenticateNonMatchingRequest(): void + { + $request = $this->createStub(RequestInterface::class); + + $requestMatcher = $this->createMock(RequestMatcher::class); + $requestMatcher->expects($this->once())->method('matches')->with($request)->willReturn(false); + + $authentication = $this->createMock(Authentication::class); + $authentication->expects($this->never())->method('authenticate'); + + self::assertSame($request, (new RequestConditional($requestMatcher, $authentication))->authenticate($request)); + } +} diff --git a/tests/Authentication/WsseTest.php b/tests/Authentication/WsseTest.php new file mode 100644 index 0000000..21259fd --- /dev/null +++ b/tests/Authentication/WsseTest.php @@ -0,0 +1,51 @@ +[^"]*)", PasswordDigest="(?[^"]*)", Nonce="(?[^"]*)", Created="(?[^"]*)"$/'; + + public function testIsAnAuthentication(): void + { + self::assertInstanceOf(Authentication::class, new Wsse('john.doe', 'secret')); + } + + public function testThrowsExceptionForUnknownHashAlgorithm(): void + { + $this->expectException(\InvalidArgumentException::class); + + new Wsse('john.doe', 'secret', 'not-an-algorithm'); + } + + public function testAuthenticatesRequest(): void + { + $request = (new Wsse('john.doe', 'secret'))->authenticate(new Request('GET', '/')); + + self::assertSame('WSSE profile="UsernameToken"', $request->getHeaderLine('Authorization')); + $this->assertValidWsseHeader($request->getHeaderLine('X-WSSE'), 'john.doe', 'secret', 'sha1'); + } + + public function testAuthenticatesRequestWithCustomHashAlgorithm(): void + { + $request = (new Wsse('john.doe', 'secret', 'sha512'))->authenticate(new Request('GET', '/')); + + $this->assertValidWsseHeader($request->getHeaderLine('X-WSSE'), 'john.doe', 'secret', 'sha512'); + } + + private function assertValidWsseHeader(string $header, string $username, string $password, string $algorithm): void + { + self::assertSame(1, preg_match(self::HEADER_PATTERN, $header, $matches), sprintf('Malformed X-WSSE header "%s".', $header)); + self::assertSame($username, $matches['username']); + + $expectedDigest = base64_encode(hash($algorithm, base64_decode($matches['nonce']).$matches['created'].$password, true)); + self::assertSame($expectedDigest, $matches['digest']); + } +} diff --git a/tests/Builder/ResponseBuilderTest.php b/tests/Builder/ResponseBuilderTest.php new file mode 100644 index 0000000..43ac7e9 --- /dev/null +++ b/tests/Builder/ResponseBuilderTest.php @@ -0,0 +1,80 @@ +createStub(ResponseInterface::class); + + self::assertSame($response, (new ResponseBuilder($response))->getResponse()); + } + + public function testReadsHeadersFromArray(): void + { + $response = $this->createMock(ResponseInterface::class); + $response->expects($this->once())->method('withStatus')->with(200, 'OK')->willReturnSelf(); + $response->expects($this->once())->method('withProtocolVersion')->with('1.1')->willReturnSelf(); + $response->expects($this->once())->method('hasHeader')->with('Content-type')->willReturn(false); + $response->expects($this->once())->method('withHeader')->with('Content-type', 'text/html')->willReturnSelf(); + + $builder = new ResponseBuilder($response); + + self::assertSame($builder, $builder->setHeadersFromArray(['HTTP/1.1 200 OK', 'Content-type: text/html'])); + } + + /** + * @see https://github.com/php-http/message/issues/41 + */ + public function testSplitsHeadersCorrectly(): void + { + $response = $this->createMock(ResponseInterface::class); + $response->expects($this->once())->method('withStatus')->with(200, 'OK')->willReturnSelf(); + $response->expects($this->once())->method('withProtocolVersion')->with('1.1')->willReturnSelf(); + $response->expects($this->once())->method('hasHeader')->with('Content-type')->willReturn(false); + $response->expects($this->once())->method('withHeader')->with('Content-type', 'application/xml+atom')->willReturnSelf(); + + (new ResponseBuilder($response))->setHeadersFromString("HTTP/1.1 200 OK\r\nContent-type: application/xml+atom\r\n"); + } + + public function testAddsRepeatedHeaders(): void + { + $builder = new ResponseBuilder(new Response()); + $builder->setHeadersFromString("HTTP/2 404 Not Found\r\nSet-Cookie: a=1\r\nSet-Cookie: b=2\r\n"); + + $response = $builder->getResponse(); + self::assertSame(404, $response->getStatusCode()); + self::assertSame('Not Found', $response->getReasonPhrase()); + self::assertSame('2', $response->getProtocolVersion()); + self::assertSame(['a=1', 'b=2'], $response->getHeader('Set-Cookie')); + } + + public function testThrowsExceptionForInvalidStatusLine(): void + { + $this->expectException(\InvalidArgumentException::class); + + (new ResponseBuilder(new Response()))->setStatus('FOO 200'); + } + + public function testThrowsExceptionForInvalidHeaderLine(): void + { + $this->expectException(\InvalidArgumentException::class); + + (new ResponseBuilder(new Response()))->addHeader('no colon here'); + } + + public function testThrowsExceptionForNonStringHeaders(): void + { + $this->expectException(\InvalidArgumentException::class); + + (new ResponseBuilder(new Response()))->setHeadersFromString(['HTTP/1.1 200 OK']); + } +} diff --git a/tests/CookieJarTest.php b/tests/CookieJarTest.php new file mode 100644 index 0000000..29d1037 --- /dev/null +++ b/tests/CookieJarTest.php @@ -0,0 +1,179 @@ +getIterator()); + self::assertCount(0, $jar); + } + + public function testIteratesOverCookies(): void + { + $cookie = new Cookie('name', 'value'); + $jar = new CookieJar(); + $jar->addCookie($cookie); + + self::assertSame([$cookie], iterator_to_array($jar->getIterator(), false)); + } + + public function testHasCookie(): void + { + $cookie = new Cookie('name', 'value'); + $jar = new CookieJar(); + + $jar->addCookie($cookie); + + self::assertTrue($jar->hasCookie($cookie)); + self::assertTrue($jar->hasCookies()); + } + + public function testReplacesCookieWithDifferentValue(): void + { + $cookie = new Cookie('name', 'value'); + $cookie2 = new Cookie('name', 'value2'); + $jar = new CookieJar(); + + $jar->addCookie($cookie); + $jar->addCookie($cookie2); + + self::assertFalse($jar->hasCookie($cookie)); + self::assertTrue($jar->hasCookie($cookie2)); + } + + public function testRemovesCookieWhenNewCookieHasEmptyValue(): void + { + $cookie = new Cookie('name', 'value'); + $cookie2 = new Cookie('name'); + $jar = new CookieJar(); + + $jar->addCookie($cookie); + $jar->addCookie($cookie2); + + self::assertFalse($jar->hasCookie($cookie)); + self::assertFalse($jar->hasCookie($cookie2)); + } + + public function testReplacesCookieWithLowerMaxAge(): void + { + $cookie = new Cookie('name', 'value', 100); + $cookie2 = new Cookie('name', 'value', 1000); + $jar = new CookieJar(); + + $jar->addCookie($cookie); + $jar->addCookie($cookie2); + + self::assertFalse($jar->hasCookie($cookie)); + self::assertTrue($jar->hasCookie($cookie2)); + } + + public function testRemovesCookie(): void + { + $cookie = new Cookie('name', 'value', 100); + $jar = new CookieJar(); + + $jar->addCookie($cookie); + $jar->removeCookie($cookie); + + self::assertFalse($jar->hasCookie($cookie)); + } + + public function testReturnsAllCookies(): void + { + $cookie = new Cookie('name', 'value'); + $cookie2 = new Cookie('name2', 'value'); + $jar = new CookieJar(); + + $jar->addCookie($cookie); + $jar->addCookie($cookie2); + + self::assertSame([$cookie, $cookie2], $jar->getCookies()); + } + + public function testReturnsMatchingCookies(): void + { + $cookie = new Cookie('name', 'value'); + $other = new Cookie('other', 'value'); + $jar = new CookieJar(); + + $jar->addCookies([$cookie, $other]); + + self::assertSame([$cookie], $jar->getMatchingCookies(new Cookie('name', 'value2'))); + } + + public function testSetsCookies(): void + { + $cookie = new Cookie('name', 'value'); + $jar = new CookieJar(); + $jar->addCookie(new Cookie('previous', 'value')); + + $jar->setCookies([$cookie]); + + self::assertTrue($jar->hasCookie($cookie)); + self::assertCount(1, $jar); + } + + public function testAddsCookies(): void + { + $cookie = new Cookie('name', 'value'); + $cookie2 = new Cookie('name2', 'value'); + $jar = new CookieJar(); + + $jar->addCookie($cookie); + $jar->addCookies([$cookie2]); + + self::assertTrue($jar->hasCookie($cookie)); + self::assertTrue($jar->hasCookie($cookie2)); + self::assertCount(2, $jar); + } + + public function testRemovesCookies(): void + { + $cookie = new Cookie('name', 'value'); + $cookie2 = new Cookie('name2', 'value'); + $jar = new CookieJar(); + + $jar->addCookies([$cookie, $cookie2]); + $jar->removeCookies([$cookie2]); + + self::assertTrue($jar->hasCookie($cookie)); + self::assertFalse($jar->hasCookie($cookie2)); + self::assertCount(1, $jar); + } + + public function testRemovesMatchingCookies(): void + { + $cookie = new Cookie('name', 'value'); + $cookie2 = new Cookie('name2', 'value', 0, 'php-http.org'); + $jar = new CookieJar(); + + $jar->addCookies([$cookie, $cookie2]); + $jar->removeMatchingCookies('name2', 'php-http.org', '/'); + + self::assertTrue($jar->hasCookie($cookie)); + self::assertFalse($jar->hasCookie($cookie2)); + self::assertCount(1, $jar); + } + + public function testClearsCookies(): void + { + $jar = new CookieJar(); + $jar->addCookies([new Cookie('name', 'value', 0, 'php-http.org'), new Cookie('name2', 'value')]); + + $jar->clear(); + + self::assertFalse($jar->hasCookies()); + self::assertCount(0, $jar); + } +} diff --git a/tests/CookieTest.php b/tests/CookieTest.php new file mode 100644 index 0000000..69b5c19 --- /dev/null +++ b/tests/CookieTest.php @@ -0,0 +1,284 @@ +getName()); + } + + public function testThrowsExceptionWhenNameIsEmpty(): void + { + $this->expectException(\InvalidArgumentException::class); + + new Cookie(''); + } + + /** + * @return iterable + */ + public static function validCharacterProvider(): iterable + { + yield 'lowercase a' => ['a']; + yield 'lowercase z' => ['z']; + yield 'digit zero' => ['0']; + } + + /** + * @return iterable + */ + public static function invalidCharacterProvider(): iterable + { + yield 'null byte' => ["\x00"]; + yield 'space' => ["\x20"]; + yield 'delete' => ["\x7F"]; + } + + /** + * @dataProvider validCharacterProvider + */ + #[DataProvider('validCharacterProvider')] + public function testAcceptsValidCharacters(string $value): void + { + $cookie = new Cookie($value, $value); + + self::assertSame($value, $cookie->getName()); + self::assertSame($value, $cookie->getValue()); + self::assertSame($value, $cookie->withValue($value)->getValue()); + } + + /** + * @dataProvider invalidCharacterProvider + */ + #[DataProvider('invalidCharacterProvider')] + public function testThrowsExceptionWhenNameContainsInvalidCharacter(string $name): void + { + $this->expectException(\InvalidArgumentException::class); + + new Cookie($name); + } + + /** + * @dataProvider invalidCharacterProvider + */ + #[DataProvider('invalidCharacterProvider')] + public function testThrowsExceptionWhenValueContainsInvalidCharacter(string $value): void + { + $this->expectException(\InvalidArgumentException::class); + + new Cookie('name', $value); + } + + /** + * @dataProvider invalidCharacterProvider + */ + #[DataProvider('invalidCharacterProvider')] + public function testThrowsExceptionWhenNewValueContainsInvalidCharacter(string $value): void + { + $cookie = new Cookie('name', 'value'); + + $this->expectException(\InvalidArgumentException::class); + + $cookie->withValue($value); + } + + public function testHasValue(): void + { + $cookie = new Cookie('name', 'value'); + + self::assertSame('value', $cookie->getValue()); + self::assertTrue($cookie->hasValue()); + self::assertFalse((new Cookie('name'))->hasValue()); + } + + public function testWithValueIsImmutable(): void + { + $cookie = new Cookie('name', 'value'); + $new = $cookie->withValue('value2'); + + self::assertNotSame($cookie, $new); + self::assertSame('value2', $new->getValue()); + self::assertSame('value', $cookie->getValue()); + } + + public function testHasMaxAge(): void + { + $cookie = new Cookie('name', 'value', 10); + + self::assertSame(10, $cookie->getMaxAge()); + self::assertTrue($cookie->hasMaxAge()); + self::assertFalse((new Cookie('name'))->hasMaxAge()); + } + + public function testWithMaxAge(): void + { + self::assertSame(1, (new Cookie('name', 'value'))->withMaxAge(1)->getMaxAge()); + } + + public function testThrowsExceptionWhenMaxAgeIsInvalid(): void + { + $this->expectException(\InvalidArgumentException::class); + + (new Cookie('name', 'value'))->withMaxAge('-1'); + } + + public function testHasExpires(): void + { + $expires = new \DateTime('+10 seconds'); + $cookie = new Cookie('name', 'value', null, null, null, false, false, $expires); + + self::assertSame($expires, $cookie->getExpires()); + self::assertTrue($cookie->hasExpires()); + self::assertFalse($cookie->isExpired()); + } + + public function testWithExpires(): void + { + $expires = new \DateTime('+10 seconds'); + + self::assertSame($expires, (new Cookie('name', 'value'))->withExpires($expires)->getExpires()); + } + + public function testIsExpired(): void + { + $cookie = new Cookie('name', 'value', null, null, null, false, false, new \DateTime('-2 minutes')); + + self::assertTrue($cookie->hasExpires()); + self::assertTrue($cookie->isExpired()); + } + + public function testHasNoDomainByDefault(): void + { + $cookie = new Cookie('name', 'value'); + + self::assertNull($cookie->getDomain()); + self::assertFalse($cookie->hasDomain()); + } + + public function testNormalizesDomain(): void + { + $cookie = new Cookie('name', 'value', null, '.PhP-hTtP.oRg'); + + self::assertSame('php-http.org', $cookie->getDomain()); + self::assertTrue($cookie->hasDomain()); + } + + public function testWithDomain(): void + { + self::assertSame('php-http.org', (new Cookie('name', 'value'))->withDomain('.PhP-hTtP.oRg')->getDomain()); + } + + /** + * @return iterable + */ + public static function domainProvider(): iterable + { + yield 'same domain, different case' => ['PhP-hTtP.oRg', true]; + yield 'subdomain' => ['wWw.PhP-hTtP.oRg', true]; + yield 'ip address' => ['127.0.0.1', false]; + yield 'other domain' => ['httplug.io', false]; + } + + /** + * @dataProvider domainProvider + */ + #[DataProvider('domainProvider')] + public function testMatchesDomain(string $domain, bool $expected): void + { + self::assertSame($expected, (new Cookie('name', 'value', null, 'php-http.org'))->matchDomain($domain)); + } + + public function testHasRootPathByDefault(): void + { + self::assertSame('/', (new Cookie('name', 'value'))->getPath()); + } + + public function testWithPath(): void + { + self::assertSame('/path', (new Cookie('name', 'value'))->withPath('/path')->getPath()); + } + + /** + * @return iterable + */ + public static function pathProvider(): iterable + { + yield 'identical path' => ['/path/to/somewhere', '/path/to/somewhere', true]; + yield 'sub path' => ['/path/to/somewhere', '/path/to/somewhere/else', true]; + yield 'common prefix only' => ['/path/to/somewhere', '/path/to/somewhereelse', false]; + yield 'root matches root' => ['/', '/', true]; + yield 'root matches sub path' => ['/', '/cookies', true]; + yield 'root matches sub path with trailing slash' => ['/', '/cookies/', true]; + } + + /** + * @dataProvider pathProvider + */ + #[DataProvider('pathProvider')] + public function testMatchesPath(string $cookiePath, string $path, bool $expected): void + { + self::assertSame($expected, (new Cookie('name', 'value', null, null, $cookiePath))->matchPath($path)); + } + + public function testIsNotSecureByDefault(): void + { + self::assertFalse((new Cookie('name', 'value'))->isSecure()); + } + + public function testWithSecure(): void + { + self::assertTrue((new Cookie('name', 'value'))->withSecure(true)->isSecure()); + } + + public function testIsNotHttpOnlyByDefault(): void + { + self::assertFalse((new Cookie('name', 'value'))->isHttpOnly()); + } + + public function testWithHttpOnly(): void + { + self::assertTrue((new Cookie('name', 'value'))->withHttpOnly(true)->isHttpOnly()); + } + + public function testMatchesOtherCookies(): void + { + $cookie = new Cookie('name', 'value', null, 'php-http.org'); + + self::assertTrue($cookie->match(new Cookie('name', 'value2', null, 'php-http.org'))); + self::assertFalse($cookie->match(new Cookie('anotherName', 'value2', null, 'php-http.org'))); + } + + public function testIsValid(): void + { + self::assertTrue((new Cookie('name', 'value'))->isValid()); + } + + /** + * @return iterable}> + */ + public static function invalidCookieArgumentsProvider(): iterable + { + yield 'invalid name' => [["\x20"]]; + yield 'invalid value' => [['name', "\x20"]]; + yield 'invalid max age' => [['name', 'value', '-1']]; + } + + /** + * @param list $arguments + * + * @dataProvider invalidCookieArgumentsProvider + */ + #[DataProvider('invalidCookieArgumentsProvider')] + public function testCanBeCreatedWithoutValidation(array $arguments): void + { + self::assertFalse(Cookie::createWithoutValidation(...$arguments)->isValid()); + } +} diff --git a/tests/CookieUtilTest.php b/tests/CookieUtilTest.php new file mode 100644 index 0000000..164a44e --- /dev/null +++ b/tests/CookieUtilTest.php @@ -0,0 +1,80 @@ + + */ + public static function dateProvider(): iterable + { + yield 'RFC 850, two digit year' => ['Friday, 31 Jul 20 08:49:37 GMT', 'Friday, 31-Jul-2020 08:49:37 +0000']; + yield 'RFC 850 with dashes' => ['Friday, 31-Jul-20 08:49:37 GMT', 'Friday, 31-Jul-2020 08:49:37 +0000']; + yield 'dashes, four digit year' => ['Fri, 31-Jul-2020 08:49:37 GMT', 'Friday, 31-Jul-2020 08:49:37 +0000']; + yield 'RFC 1123' => ['Fri, 31 Jul 2020 08:49:37 GMT', 'Friday, 31-Jul-2020 08:49:37 +0000']; + yield 'numeric month, four digit year' => ['Fri, 31-07-2020 08:49:37 GMT', 'Friday, 31-Jul-2020 08:49:37 +0000']; + yield 'numeric month, two digit year' => ['Fri, 31-07-20 08:49:37 GMT', 'Friday, 31-Jul-2020 08:49:37 +0000']; + yield 'asctime' => ['Fri Jul 31 08:49:37 2020', 'Friday, 31-Jul-2020 08:49:37 +0000']; + yield 'free form' => ['Friday July 31st 2020, 08:49:37 GMT', 'Friday, 31-Jul-2020 08:49:37 +0000']; + yield 'morning' => ['Wed, 09 Jun 2021 10:18:14 GMT', 'Wednesday, 09-Jun-2021 10:18:14 +0000']; + yield 'evening' => ['Wed, 09 Jun 2021 22:18:14 GMT', 'Wednesday, 09-Jun-2021 22:18:14 +0000']; + yield 'milliseconds' => ['Tue, 18 Oct 2011 07:42:42.123 GMT', 'Tuesday, 18-Oct-2011 07:42:42 +0000']; + yield 'without weekday' => ['18 Oct 2011 07:42:42 GMT', 'Tuesday, 18-Oct-2011 07:42:42 +0000']; + yield 'single digit day and hour' => ['8 Oct 2011 7:42:42 GMT', 'Saturday, 08-Oct-2011 07:42:42 +0000']; + yield 'single digit minute' => ['8 Oct 2011 7:2:42 GMT', 'Saturday, 08-Oct-2011 07:02:42 +0000']; + yield 'month first' => ['Oct 18 2011 07:42:42 GMT', 'Tuesday, 18-Oct-2011 07:42:42 +0000']; + yield 'javascript toString' => ['Tue Oct 18 2011 07:05:03 GMT+0000 (GMT)', 'Tuesday, 18-Oct-2011 07:05:03 +0000']; + yield 'leading zero day without weekday' => ['09 Jun 2021 10:18:14 GMT', 'Wednesday, 09-Jun-2021 10:18:14 +0000']; + yield 'unix epoch' => ['01 Jan 1970 00:00:00 GMT', 'Thursday, 01-Jan-1970 00:00:00 +0000']; + yield 'windows epoch' => ['01 Jan 1601 00:00:00 GMT', 'Monday, 01-Jan-1601 00:00:00 +0000']; + yield 'implicit century' => ['10 Feb 81 13:00:00 GMT', 'Tuesday, 10-Feb-1981 13:00:00 +0000']; + yield 'dashes with GMT' => ['Thu, 17-Apr-2014 02:12:29 GMT', 'Thursday, 17-Apr-2014 02:12:29 +0000']; + yield 'dashes with UTC' => ['Thu, 17-Apr-2014 02:12:29 UTC', 'Thursday, 17-Apr-2014 02:12:29 +0000']; + } + + /** + * @dataProvider dateProvider + */ + #[DataProvider('dateProvider')] + public function testParsesCookieDate(string $input, string $expected): void + { + self::assertSame($expected, CookieUtil::parseDate($input)->format('l, d-M-Y H:i:s O')); + } + + /** + * @return iterable + */ + public static function unparseableDateProvider(): iterable + { + yield 'unknown weekday' => ['Flursday July 31st 2020, 08:49:37 GMT']; + yield 'garbage' => ['99 Jix 3038 48:86:72 ZMT']; + } + + /** + * @dataProvider unparseableDateProvider + */ + #[DataProvider('unparseableDateProvider')] + public function testThrowsExceptionForUnparseableDate(string $input): void + { + $this->expectException(UnexpectedValueException::class); + + CookieUtil::parseDate($input); + } + + public function testThrowsExceptionForNonStringDate(): void + { + $this->expectException(\InvalidArgumentException::class); + + CookieUtil::parseDate(123); + } +} diff --git a/tests/Decorator/MessageDecoratorTest.php b/tests/Decorator/MessageDecoratorTest.php new file mode 100644 index 0000000..6bb8aff --- /dev/null +++ b/tests/Decorator/MessageDecoratorTest.php @@ -0,0 +1,146 @@ +createStub(MessageInterface::class); + + self::assertSame($message, (new MessageDecoratorStub($message))->getMessage()); + } + + public function testDelegatesGetProtocolVersion(): void + { + $message = $this->createStub(MessageInterface::class); + $message->method('getProtocolVersion')->willReturn('1.1'); + + self::assertSame('1.1', (new MessageDecoratorStub($message))->getProtocolVersion()); + } + + public function testDelegatesGetHeaders(): void + { + $headers = ['Content-Type' => ['application/xml']]; + $message = $this->createStub(MessageInterface::class); + $message->method('getHeaders')->willReturn($headers); + + self::assertSame($headers, (new MessageDecoratorStub($message))->getHeaders()); + } + + public function testDelegatesHasHeader(): void + { + $message = $this->createMock(MessageInterface::class); + $message->expects($this->once())->method('hasHeader')->with('Content-Type')->willReturn(true); + + self::assertTrue((new MessageDecoratorStub($message))->hasHeader('Content-Type')); + } + + public function testDelegatesGetHeader(): void + { + $message = $this->createMock(MessageInterface::class); + $message->expects($this->once())->method('getHeader')->with('Content-Type')->willReturn(['application/xml']); + + self::assertSame(['application/xml'], (new MessageDecoratorStub($message))->getHeader('Content-Type')); + } + + public function testDelegatesGetHeaderLine(): void + { + $message = $this->createMock(MessageInterface::class); + $message->expects($this->once())->method('getHeaderLine')->with('Accept-Encoding')->willReturn('gzip, deflate'); + + self::assertSame('gzip, deflate', (new MessageDecoratorStub($message))->getHeaderLine('Accept-Encoding')); + } + + public function testDelegatesGetBody(): void + { + $body = $this->createStub(StreamInterface::class); + $message = $this->createStub(MessageInterface::class); + $message->method('getBody')->willReturn($body); + + self::assertSame($body, (new MessageDecoratorStub($message))->getBody()); + } + + public function testWithProtocolVersionReturnsNewDecorator(): void + { + $newMessage = $this->createStub(MessageInterface::class); + $message = $this->createMock(MessageInterface::class); + $message->expects($this->once())->method('withProtocolVersion')->with('1.1')->willReturn($newMessage); + + $this->assertImmutableDecoration($message, $newMessage, static function (MessageDecoratorStub $decorator): MessageInterface { + return $decorator->withProtocolVersion('1.1'); + }); + } + + public function testWithHeaderReturnsNewDecorator(): void + { + $newMessage = $this->createStub(MessageInterface::class); + $message = $this->createMock(MessageInterface::class); + $message->expects($this->once())->method('withHeader')->with('Content-Type', 'application/xml')->willReturn($newMessage); + + $this->assertImmutableDecoration($message, $newMessage, static function (MessageDecoratorStub $decorator): MessageInterface { + return $decorator->withHeader('Content-Type', 'application/xml'); + }); + } + + public function testWithAddedHeaderReturnsNewDecorator(): void + { + $newMessage = $this->createStub(MessageInterface::class); + $message = $this->createMock(MessageInterface::class); + $message->expects($this->once())->method('withAddedHeader')->with('Content-Type', 'application/xml')->willReturn($newMessage); + + $this->assertImmutableDecoration($message, $newMessage, static function (MessageDecoratorStub $decorator): MessageInterface { + return $decorator->withAddedHeader('Content-Type', 'application/xml'); + }); + } + + public function testWithoutHeaderReturnsNewDecorator(): void + { + $newMessage = $this->createStub(MessageInterface::class); + $message = $this->createMock(MessageInterface::class); + $message->expects($this->once())->method('withoutHeader')->with('Content-Type')->willReturn($newMessage); + + $this->assertImmutableDecoration($message, $newMessage, static function (MessageDecoratorStub $decorator): MessageInterface { + return $decorator->withoutHeader('Content-Type'); + }); + } + + public function testWithBodyReturnsNewDecorator(): void + { + $body = $this->createStub(StreamInterface::class); + $newMessage = $this->createStub(MessageInterface::class); + $message = $this->createMock(MessageInterface::class); + $message->expects($this->once())->method('withBody')->with($body)->willReturn($newMessage); + + $this->assertImmutableDecoration($message, $newMessage, static function (MessageDecoratorStub $decorator) use ($body): MessageInterface { + return $decorator->withBody($body); + }); + } + + /** + * @param callable(MessageDecoratorStub): MessageInterface $mutate + */ + private function assertImmutableDecoration(MessageInterface $message, MessageInterface $newMessage, callable $mutate): void + { + $decorator = new MessageDecoratorStub($message); + $new = $mutate($decorator); + + self::assertInstanceOf(MessageDecoratorStub::class, $new); + self::assertNotSame($decorator, $new); + self::assertSame($newMessage, $new->getMessage()); + self::assertSame($message, $decorator->getMessage()); + } +} diff --git a/tests/Decorator/RequestDecoratorTest.php b/tests/Decorator/RequestDecoratorTest.php new file mode 100644 index 0000000..68cf6fe --- /dev/null +++ b/tests/Decorator/RequestDecoratorTest.php @@ -0,0 +1,111 @@ +createStub(RequestInterface::class); + + self::assertSame($request, (new RequestDecoratorStub($request))->getRequest()); + } + + public function testWithRequestReturnsNewDecorator(): void + { + $request = $this->createStub(RequestInterface::class); + $otherRequest = $this->createStub(RequestInterface::class); + $decorator = new RequestDecoratorStub($request); + + $new = $decorator->withRequest($otherRequest); + + self::assertInstanceOf(RequestDecoratorStub::class, $new); + self::assertSame($otherRequest, $new->getRequest()); + self::assertSame($request, $decorator->getRequest()); + } + + public function testDelegatesGetRequestTarget(): void + { + $request = $this->createStub(RequestInterface::class); + $request->method('getRequestTarget')->willReturn('/'); + + self::assertSame('/', (new RequestDecoratorStub($request))->getRequestTarget()); + } + + public function testDelegatesGetMethod(): void + { + $request = $this->createStub(RequestInterface::class); + $request->method('getMethod')->willReturn('GET'); + + self::assertSame('GET', (new RequestDecoratorStub($request))->getMethod()); + } + + public function testDelegatesGetUri(): void + { + $uri = $this->createStub(UriInterface::class); + $request = $this->createStub(RequestInterface::class); + $request->method('getUri')->willReturn($uri); + + self::assertSame($uri, (new RequestDecoratorStub($request))->getUri()); + } + + public function testWithRequestTargetReturnsNewDecorator(): void + { + $newRequest = $this->createStub(RequestInterface::class); + $request = $this->createMock(RequestInterface::class); + $request->expects($this->once())->method('withRequestTarget')->with('/')->willReturn($newRequest); + + $new = (new RequestDecoratorStub($request))->withRequestTarget('/'); + + self::assertInstanceOf(RequestDecoratorStub::class, $new); + self::assertSame($newRequest, $new->getMessage()); + } + + public function testWithMethodReturnsNewDecorator(): void + { + $newRequest = $this->createStub(RequestInterface::class); + $request = $this->createMock(RequestInterface::class); + $request->expects($this->once())->method('withMethod')->with('GET')->willReturn($newRequest); + + $new = (new RequestDecoratorStub($request))->withMethod('GET'); + + self::assertInstanceOf(RequestDecoratorStub::class, $new); + self::assertSame($newRequest, $new->getMessage()); + } + + public function testWithUriReturnsNewDecorator(): void + { + $uri = $this->createStub(UriInterface::class); + $newRequest = $this->createStub(RequestInterface::class); + $request = $this->createMock(RequestInterface::class); + $request->expects($this->once())->method('withUri')->with($uri, false)->willReturn($newRequest); + + $new = (new RequestDecoratorStub($request))->withUri($uri); + + self::assertInstanceOf(RequestDecoratorStub::class, $new); + self::assertSame($newRequest, $new->getMessage()); + } + + public function testWithUriPassesPreserveHost(): void + { + $uri = $this->createStub(UriInterface::class); + $newRequest = $this->createStub(RequestInterface::class); + $request = $this->createMock(RequestInterface::class); + $request->expects($this->once())->method('withUri')->with($uri, true)->willReturn($newRequest); + + self::assertSame($newRequest, (new RequestDecoratorStub($request))->withUri($uri, true)->getMessage()); + } +} diff --git a/tests/Decorator/ResponseDecoratorTest.php b/tests/Decorator/ResponseDecoratorTest.php new file mode 100644 index 0000000..f304129 --- /dev/null +++ b/tests/Decorator/ResponseDecoratorTest.php @@ -0,0 +1,66 @@ +createStub(ResponseInterface::class); + + self::assertSame($response, (new ResponseDecoratorStub($response))->getResponse()); + } + + public function testWithResponseReturnsNewDecorator(): void + { + $response = $this->createStub(ResponseInterface::class); + $otherResponse = $this->createStub(ResponseInterface::class); + $decorator = new ResponseDecoratorStub($response); + + $new = $decorator->withResponse($otherResponse); + + self::assertInstanceOf(ResponseDecoratorStub::class, $new); + self::assertSame($otherResponse, $new->getResponse()); + self::assertSame($response, $decorator->getResponse()); + } + + public function testDelegatesGetStatusCode(): void + { + $response = $this->createStub(ResponseInterface::class); + $response->method('getStatusCode')->willReturn(200); + + self::assertSame(200, (new ResponseDecoratorStub($response))->getStatusCode()); + } + + public function testDelegatesGetReasonPhrase(): void + { + $response = $this->createStub(ResponseInterface::class); + $response->method('getReasonPhrase')->willReturn('OK'); + + self::assertSame('OK', (new ResponseDecoratorStub($response))->getReasonPhrase()); + } + + public function testWithStatusReturnsNewDecorator(): void + { + $newResponse = $this->createStub(ResponseInterface::class); + $response = $this->createMock(ResponseInterface::class); + $response->expects($this->once())->method('withStatus')->with(200, 'OK')->willReturn($newResponse); + + $new = (new ResponseDecoratorStub($response))->withStatus(200, 'OK'); + + self::assertInstanceOf(ResponseDecoratorStub::class, $new); + self::assertSame($newResponse, $new->getMessage()); + } +} diff --git a/tests/Decorator/StreamDecoratorTest.php b/tests/Decorator/StreamDecoratorTest.php new file mode 100644 index 0000000..9913ec1 --- /dev/null +++ b/tests/Decorator/StreamDecoratorTest.php @@ -0,0 +1,147 @@ +createStub(StreamInterface::class); + $stream->method('__toString')->willReturn('body'); + + self::assertSame('body', (string) new StreamDecoratorStub($stream)); + } + + public function testClosesStream(): void + { + $stream = $this->createMock(StreamInterface::class); + $stream->expects($this->once())->method('close'); + + (new StreamDecoratorStub($stream))->close(); + } + + public function testDetachesStream(): void + { + $resource = fopen('php://memory', 'r'); + $stream = $this->createStub(StreamInterface::class); + $stream->method('detach')->willReturn($resource); + + self::assertSame($resource, (new StreamDecoratorStub($stream))->detach()); + } + + public function testReturnsSize(): void + { + $stream = $this->createStub(StreamInterface::class); + $stream->method('getSize')->willReturn(1234); + + self::assertSame(1234, (new StreamDecoratorStub($stream))->getSize()); + } + + public function testReturnsCurrentPosition(): void + { + $stream = $this->createStub(StreamInterface::class); + $stream->method('tell')->willReturn(0); + + self::assertSame(0, (new StreamDecoratorStub($stream))->tell()); + } + + public function testChecksEof(): void + { + $stream = $this->createStub(StreamInterface::class); + $stream->method('eof')->willReturn(false); + + self::assertFalse((new StreamDecoratorStub($stream))->eof()); + } + + public function testChecksSeekable(): void + { + $stream = $this->createStub(StreamInterface::class); + $stream->method('isSeekable')->willReturn(true); + + self::assertTrue((new StreamDecoratorStub($stream))->isSeekable()); + } + + public function testSeeks(): void + { + $stream = $this->createMock(StreamInterface::class); + $stream->expects($this->once())->method('seek')->with(0, SEEK_SET); + + (new StreamDecoratorStub($stream))->seek(0); + } + + public function testRewinds(): void + { + $stream = $this->createMock(StreamInterface::class); + $stream->expects($this->once())->method('rewind'); + + (new StreamDecoratorStub($stream))->rewind(); + } + + public function testChecksWritable(): void + { + $stream = $this->createStub(StreamInterface::class); + $stream->method('isWritable')->willReturn(true); + + self::assertTrue((new StreamDecoratorStub($stream))->isWritable()); + } + + public function testWrites(): void + { + $stream = $this->createMock(StreamInterface::class); + $stream->expects($this->once())->method('write')->with('body')->willReturn(4); + + self::assertSame(4, (new StreamDecoratorStub($stream))->write('body')); + } + + public function testChecksReadable(): void + { + $stream = $this->createStub(StreamInterface::class); + $stream->method('isReadable')->willReturn(true); + + self::assertTrue((new StreamDecoratorStub($stream))->isReadable()); + } + + public function testReads(): void + { + $stream = $this->createMock(StreamInterface::class); + $stream->expects($this->once())->method('read')->with(4)->willReturn('body'); + + self::assertSame('body', (new StreamDecoratorStub($stream))->read(4)); + } + + public function testReturnsContents(): void + { + $stream = $this->createStub(StreamInterface::class); + $stream->method('getContents')->willReturn('body'); + + self::assertSame('body', (new StreamDecoratorStub($stream))->getContents()); + } + + public function testReturnsMetadata(): void + { + $stream = $this->createStub(StreamInterface::class); + $stream->method('getMetadata')->willReturnMap([ + [null, ['key' => 'value']], + ['key', 'value'], + ['key2', null], + ]); + + $decorator = new StreamDecoratorStub($stream); + + self::assertSame(['key' => 'value'], $decorator->getMetadata()); + self::assertSame('value', $decorator->getMetadata('key')); + self::assertNull($decorator->getMetadata('key2')); + } +} diff --git a/tests/Encoding/ChunkStreamTest.php b/tests/Encoding/ChunkStreamTest.php new file mode 100644 index 0000000..e7444c4 --- /dev/null +++ b/tests/Encoding/ChunkStreamTest.php @@ -0,0 +1,39 @@ +getContents()); + } + + public function testChunksInMultipleParts(): void + { + $stream = new ChunkStream(new MemoryStream('This is a stream', 6)); + + self::assertSame("6\r\nThis i\r\n6\r\ns a st\r\n4\r\nream\r\n0\r\n\r\n", $stream->getContents()); + } + + public function testDoesNotKnowContentSize(): void + { + self::assertNull((new ChunkStream(new MemoryStream('This is a stream')))->getSize()); + } + + public function testRoundTripsWithDechunkStream(): void + { + $chunked = (new ChunkStream(new MemoryStream('This is a stream', 6)))->getContents(); + + self::assertSame('This is a stream', (new DechunkStream(new MemoryStream($chunked)))->getContents()); + } +} diff --git a/tests/Encoding/DechunkStreamTest.php b/tests/Encoding/DechunkStreamTest.php new file mode 100644 index 0000000..4bcfcaa --- /dev/null +++ b/tests/Encoding/DechunkStreamTest.php @@ -0,0 +1,32 @@ +read(6)); + self::assertSame('st', $stream->read(6)); + } + + public function testGetsContent(): void + { + $stream = new DechunkStream(new MemoryStream("4\r\ntest\r\n0\r\n\r\n\0")); + + self::assertSame('test', $stream->getContents()); + } + + public function testDoesNotKnowContentSize(): void + { + self::assertNull((new DechunkStream(new MemoryStream("4\r\ntest\r\n0\r\n\r\n\0")))->getSize()); + } +} diff --git a/tests/Encoding/FilteredStreamTest.php b/tests/Encoding/FilteredStreamTest.php new file mode 100644 index 0000000..efd0f65 --- /dev/null +++ b/tests/Encoding/FilteredStreamTest.php @@ -0,0 +1,57 @@ +expectException(\RuntimeException::class); + + new FilteredStreamStub($this->createStub(StreamInterface::class), 'foo'); + } + + public function testThrowsWithInvalidWriteFilterOptions(): void + { + $this->expectException(\RuntimeException::class); + + // the $writeFilterOptions argument is deprecated and triggers a silenced E_USER_DEPRECATED + new FilteredStreamStub($this->createStub(StreamInterface::class), null, 'foo'); + } + + public function testReads(): void + { + $stream = new FilteredStreamStub(new MemoryStream('This is a test stream')); + + self::assertSame('VGhp', $stream->read(4)); + } + + public function testGetsContent(): void + { + $stream = new FilteredStreamStub(new MemoryStream('This is a test stream')); + + self::assertSame('VGhpcyBpcyBhIHRlc3Qgc3RyZWFt', $stream->getContents()); + } + + public function testDoesNotKnowContentSize(): void + { + self::assertNull((new FilteredStreamStub(new MemoryStream('This is a test stream')))->getSize()); + } + + public function testIsNotSeekable(): void + { + self::assertFalse((new FilteredStreamStub(new MemoryStream('This is a test stream')))->isSeekable()); + } + + public function testCastsToFilteredString(): void + { + self::assertSame('VGhpcyBpcyBhIHRlc3Qgc3RyZWFt', (string) new FilteredStreamStub(new MemoryStream('This is a test stream'))); + } +} diff --git a/tests/Encoding/ZlibStreamTest.php b/tests/Encoding/ZlibStreamTest.php new file mode 100644 index 0000000..78e925b --- /dev/null +++ b/tests/Encoding/ZlibStreamTest.php @@ -0,0 +1,177 @@ +, callable(string): string}> + */ + public static function encoderProvider(): iterable + { + yield 'compress (RFC 1950)' => [CompressStream::class, 'gzcompress']; + yield 'deflate (RFC 1951)' => [DeflateStream::class, 'gzdeflate']; + yield 'gzip encode (RFC 1952)' => [GzipEncodeStream::class, 'gzencode']; + } + + /** + * @return iterable, callable(string): string}> + */ + public static function decoderProvider(): iterable + { + yield 'decompress (RFC 1950)' => [DecompressStream::class, 'gzcompress']; + yield 'inflate (RFC 1951)' => [InflateStream::class, 'gzdeflate']; + yield 'gzip decode (RFC 1952)' => [GzipDecodeStream::class, 'gzencode']; + } + + /** + * @return iterable, class-string}> + */ + public static function roundTripProvider(): iterable + { + yield 'compress / decompress' => [CompressStream::class, DecompressStream::class]; + yield 'deflate / inflate' => [DeflateStream::class, InflateStream::class]; + yield 'gzip encode / gzip decode' => [GzipEncodeStream::class, GzipDecodeStream::class]; + } + + /** + * @return iterable}> + */ + public static function zlibDependentStreamProvider(): iterable + { + yield 'compress' => [CompressStream::class]; + yield 'decompress' => [DecompressStream::class]; + yield 'inflate' => [InflateStream::class]; + yield 'gzip encode' => [GzipEncodeStream::class]; + yield 'gzip decode' => [GzipDecodeStream::class]; + } + + /** + * @param class-string $streamClass + * @param callable(string): string $encode + * + * @dataProvider encoderProvider + */ + #[DataProvider('encoderProvider')] + public function testEncoderReads(string $streamClass, callable $encode): void + { + $stream = new $streamClass(new MemoryStream(self::CONTENT)); + + self::assertSame(substr($encode(self::CONTENT), 0, 4), $stream->read(4)); + } + + /** + * @param class-string $streamClass + * @param callable(string): string $encode + * + * @dataProvider encoderProvider + */ + #[DataProvider('encoderProvider')] + public function testEncoderGetsContent(string $streamClass, callable $encode): void + { + $stream = new $streamClass(new MemoryStream(self::CONTENT)); + + self::assertSame($encode(self::CONTENT), $stream->getContents()); + } + + /** + * @param class-string $streamClass + * @param callable(string): string $encode + * + * @dataProvider decoderProvider + */ + #[DataProvider('decoderProvider')] + public function testDecoderReads(string $streamClass, callable $encode): void + { + $stream = new $streamClass(new MemoryStream($encode(self::CONTENT))); + + self::assertSame('This', $stream->read(4)); + } + + /** + * @param class-string $streamClass + * @param callable(string): string $encode + * + * @dataProvider decoderProvider + */ + #[DataProvider('decoderProvider')] + public function testDecoderGetsContent(string $streamClass, callable $encode): void + { + $stream = new $streamClass(new MemoryStream($encode(self::CONTENT))); + + self::assertSame(self::CONTENT, $stream->getContents()); + } + + /** + * @param class-string $encoderClass + * @param class-string $decoderClass + * + * @dataProvider roundTripProvider + */ + #[DataProvider('roundTripProvider')] + public function testRoundTrip(string $encoderClass, string $decoderClass): void + { + $content = str_repeat(self::CONTENT, 1000); + $encoded = (new $encoderClass(new MemoryStream($content)))->getContents(); + + self::assertSame($content, (new $decoderClass(new MemoryStream($encoded)))->getContents()); + } + + /** + * @param class-string $streamClass + * @param callable(string): string $encode + * + * @dataProvider encoderProvider + * @dataProvider decoderProvider + */ + #[DataProvider('encoderProvider')] + #[DataProvider('decoderProvider')] + public function testDoesNotKnowContentSize(string $streamClass, callable $encode): void + { + $stream = new $streamClass(new MemoryStream($encode(self::CONTENT))); + + self::assertNull($stream->getSize()); + } + + /** + * @param class-string $streamClass + * + * @dataProvider zlibDependentStreamProvider + */ + #[DataProvider('zlibDependentStreamProvider')] + public function testThrowsWhenZlibIsNotLoaded(string $streamClass): void + { + ZlibExtension::disable(); + + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('The zlib extension must be enabled to use this stream'); + + new $streamClass(new MemoryStream()); + } +} diff --git a/tests/Fixtures/FilteredStreamStub.php b/tests/Fixtures/FilteredStreamStub.php new file mode 100644 index 0000000..453d8c3 --- /dev/null +++ b/tests/Fixtures/FilteredStreamStub.php @@ -0,0 +1,20 @@ +size = strlen($body); - $this->resource = fopen('php://memory', 'rw+'); - - if (null !== $chunkSize) { - stream_set_read_buffer($this->resource, $chunkSize); - stream_set_chunk_size($this->resource, $chunkSize); + $resource = fopen('php://memory', 'rw+'); + if (false === $resource) { + throw new \RuntimeException('Unable to open php://memory'); } - fwrite($this->resource, $body); - fseek($this->resource, 0); + stream_set_read_buffer($resource, $chunkSize); + stream_set_chunk_size($resource, $chunkSize); + fwrite($resource, $body); + fseek($resource, 0); + $this->resource = $resource; + $this->size = strlen($body); $this->chunkSize = $chunkSize; } @@ -53,7 +68,7 @@ public function getSize(): int public function tell(): int { - return ftell($this->resource); + return (int) ftell($this->resource); } public function eof(): bool @@ -83,7 +98,7 @@ public function isWritable(): bool public function write(string $string): int { - return fwrite($this->resource, $string); + return (int) fwrite($this->resource, $string); } public function isReadable(): bool @@ -93,7 +108,7 @@ public function isReadable(): bool public function read(int $length): string { - return fread($this->resource, min($this->chunkSize, $length)); + return (string) fread($this->resource, min($this->chunkSize, $length)); } public function getContents(): string @@ -111,6 +126,6 @@ public function getMetadata(?string $key = null) return $metadata; } - return $metadata[$key]; + return $metadata[$key] ?? null; } } diff --git a/tests/Fixtures/MessageDecoratorStub.php b/tests/Fixtures/MessageDecoratorStub.php new file mode 100644 index 0000000..b051fe9 --- /dev/null +++ b/tests/Fixtures/MessageDecoratorStub.php @@ -0,0 +1,18 @@ +message = $message; + } +} diff --git a/tests/Fixtures/RequestDecoratorStub.php b/tests/Fixtures/RequestDecoratorStub.php new file mode 100644 index 0000000..433f297 --- /dev/null +++ b/tests/Fixtures/RequestDecoratorStub.php @@ -0,0 +1,18 @@ +message = $request; + } +} diff --git a/tests/Fixtures/ResponseDecoratorStub.php b/tests/Fixtures/ResponseDecoratorStub.php new file mode 100644 index 0000000..997c0e8 --- /dev/null +++ b/tests/Fixtures/ResponseDecoratorStub.php @@ -0,0 +1,18 @@ +message = $response; + } +} diff --git a/tests/Fixtures/StreamDecoratorStub.php b/tests/Fixtures/StreamDecoratorStub.php new file mode 100644 index 0000000..bcc3e2f --- /dev/null +++ b/tests/Fixtures/StreamDecoratorStub.php @@ -0,0 +1,18 @@ +stream = $stream; + } +} diff --git a/tests/Fixtures/ZlibExtension.php b/tests/Fixtures/ZlibExtension.php new file mode 100644 index 0000000..6001671 --- /dev/null +++ b/tests/Fixtures/ZlibExtension.php @@ -0,0 +1,37 @@ +createRequestStub('GET', '1.1', ['foo' => ['bar', 'baz']], $this->createStub(StreamInterface::class)); + $request->method('getHeaderLine')->willReturnMap([['foo', 'bar, baz']]); + + self::assertSame("curl 'http://foo.com/bar' -H 'foo: bar, baz'", (new CurlCommandFormatter())->formatRequest($request)); + } + + public function testStripsFragmentFromUri(): void + { + $request = new Request('GET', 'http://foo.com/bar#fragment'); + + self::assertSame("curl 'http://foo.com/bar'", (new CurlCommandFormatter())->formatRequest($request)); + } + + public function testFormatsPostRequest(): void + { + $body = $this->createMock(StreamInterface::class); + $body->method('__toString')->willReturn('body " data'." test' bar"); + $body->method('getSize')->willReturn(1); + $body->method('isSeekable')->willReturn(true); + $body->expects($this->once())->method('rewind'); + + $request = $this->createRequestStub('POST', '2.0', [], $body); + + self::assertSame( + "curl 'http://foo.com/bar' --http2 --request POST --data 'body \" data test'\'' bar'", + (new CurlCommandFormatter())->formatRequest($request) + ); + } + + public function testFormatsHeadRequestWithHttp10(): void + { + $request = new Request('HEAD', 'http://foo.com/bar', [], null, '1.0'); + + self::assertSame("curl 'http://foo.com/bar' --http1.0 --head", (new CurlCommandFormatter())->formatRequest($request)); + } + + public function testSkipsHostHeaderMatchingUri(): void + { + $request = new Request('GET', 'http://foo.com/bar', ['Host' => 'foo.com']); + + self::assertSame("curl 'http://foo.com/bar'", (new CurlCommandFormatter())->formatRequest($request)); + } + + public function testFormatsRequestWithUserAgent(): void + { + $request = $this->createRequestStub('GET', '1.1', ['user-agent' => ['foobar-browser']], $this->createStub(StreamInterface::class)); + + self::assertSame("curl 'http://foo.com/bar' -A 'foobar-browser'", (new CurlCommandFormatter())->formatRequest($request)); + } + + public function testOmitsBinaryBody(): void + { + $body = $this->createMock(StreamInterface::class); + $body->method('__toString')->willReturn("\0"); + $body->method('getSize')->willReturn(1); + $body->method('isSeekable')->willReturn(true); + $body->expects($this->once())->method('rewind'); + + $request = $this->createRequestStub('POST', '1.1', [], $body); + + self::assertSame( + "curl 'http://foo.com/bar' --request POST --data '[binary stream omitted]'", + (new CurlCommandFormatter())->formatRequest($request) + ); + } + + public function testKeepsLineBreaksInBody(): void + { + $body = $this->createMock(StreamInterface::class); + $body->method('__toString')->willReturn("foo\nbar"); + $body->method('getSize')->willReturn(1); + $body->method('isSeekable')->willReturn(true); + $body->expects($this->once())->method('rewind'); + + $request = $this->createRequestStub('POST', '1.1', [], $body); + + self::assertSame( + "curl 'http://foo.com/bar' --request POST --data 'foo\nbar'", + (new CurlCommandFormatter())->formatRequest($request) + ); + } + + public function testOmitsNonSeekableBody(): void + { + $body = $this->createMock(StreamInterface::class); + $body->method('getSize')->willReturn(1); + $body->method('isSeekable')->willReturn(false); + $body->expects($this->never())->method('__toString'); + $body->expects($this->never())->method('rewind'); + + $request = $this->createRequestStub('POST', '1.1', [], $body); + + self::assertSame( + "curl 'http://foo.com/bar' --request POST --data '[non-seekable stream omitted]'", + (new CurlCommandFormatter())->formatRequest($request) + ); + } + + public function testOmitsTooLongBody(): void + { + $body = $this->createMock(StreamInterface::class); + $body->method('getSize')->willReturn(2097153); + $body->method('isSeekable')->willReturn(true); + $body->expects($this->never())->method('__toString'); + $body->expects($this->never())->method('rewind'); + + $request = $this->createRequestStub('POST', '1.1', [], $body); + + self::assertSame( + "curl 'http://foo.com/bar' --request POST --data '[too long stream omitted]'", + (new CurlCommandFormatter())->formatRequest($request) + ); + } + + public function testDoesNothingForResponse(): void + { + $response = $this->createStub(ResponseInterface::class); + $formatter = new CurlCommandFormatter(); + + self::assertSame('', $formatter->formatResponse($response)); + self::assertSame('', $formatter->formatResponseForRequest($response, $this->createStub(RequestInterface::class))); + } + + /** + * @param array> $headers + * + * @return RequestInterface&\PHPUnit\Framework\MockObject\Stub + */ + private function createRequestStub(string $method, string $protocolVersion, array $headers, StreamInterface $body): RequestInterface + { + $uri = $this->createStub(UriInterface::class); + $uri->method('withFragment')->willReturnSelf(); + $uri->method('__toString')->willReturn('http://foo.com/bar'); + + $request = $this->createStub(RequestInterface::class); + $request->method('getUri')->willReturn($uri); + $request->method('getBody')->willReturn($body); + $request->method('getMethod')->willReturn($method); + $request->method('getProtocolVersion')->willReturn($protocolVersion); + $request->method('getHeaders')->willReturn($headers); + + return $request; + } +} diff --git a/tests/Formatter/FullHttpMessageFormatterTest.php b/tests/Formatter/FullHttpMessageFormatterTest.php new file mode 100644 index 0000000..4ebf29c --- /dev/null +++ b/tests/Formatter/FullHttpMessageFormatterTest.php @@ -0,0 +1,190 @@ + ['foo'], + 'X-Param-Bar' => ['bar'], + ]; + + public function testIsAFormatter(): void + { + self::assertInstanceOf(Formatter::class, new FullHttpMessageFormatter()); + } + + /** + * @return iterable + */ + public static function bodyLengthProvider(): iterable + { + yield 'with size limit' => [18, 'This is an HTML st']; + yield 'without size limit' => [null, 'This is an HTML stream content.']; + } + + /** + * @dataProvider bodyLengthProvider + */ + #[DataProvider('bodyLengthProvider')] + public function testFormatsRequest(?int $maxBodyLength, string $expectedBody): void + { + $stream = $this->createMock(StreamInterface::class); + $stream->method('isSeekable')->willReturn(true); + $stream->method('__toString')->willReturn('This is an HTML stream content.'); + $stream->expects($this->once())->method('rewind'); + + $expected = "GET /foo HTTP/1.1\nX-Param-Foo: foo\nX-Param-Bar: bar\n\n".$expectedBody; + + self::assertSame($expected, (new FullHttpMessageFormatter($maxBodyLength))->formatRequest($this->createRequestStub($stream, self::HEADERS))); + } + + /** + * @dataProvider bodyLengthProvider + */ + #[DataProvider('bodyLengthProvider')] + public function testFormatsResponse(?int $maxBodyLength, string $expectedBody): void + { + $stream = $this->createMock(StreamInterface::class); + $stream->method('isSeekable')->willReturn(true); + $stream->method('__toString')->willReturn('This is an HTML stream content.'); + $stream->expects($this->exactly(2))->method('rewind'); + + $response = $this->createResponseStub($stream); + $formatter = new FullHttpMessageFormatter($maxBodyLength); + $expected = "HTTP/1.1 200 OK\nX-Param-Foo: foo\nX-Param-Bar: bar\n\n".$expectedBody; + + self::assertSame($expected, $formatter->formatResponse($response)); + self::assertSame($expected, $formatter->formatResponseForRequest($response, $this->createStub(RequestInterface::class))); + } + + /** + * @return iterable + */ + public static function unreadableBodyProvider(): iterable + { + yield 'body length is zero' => [0, true]; + yield 'stream is not seekable' => [1000, false]; + } + + /** + * @dataProvider unreadableBodyProvider + */ + #[DataProvider('unreadableBodyProvider')] + public function testDoesNotReadRequestBody(int $maxBodyLength, bool $seekable): void + { + $stream = $this->createMock(StreamInterface::class); + $stream->method('isSeekable')->willReturn($seekable); + $stream->expects($this->never())->method('__toString'); + $stream->expects($this->never())->method('rewind'); + + self::assertSame( + "GET /foo HTTP/1.1\nX-Param-Foo: foo\nX-Param-Bar: bar\n\n", + (new FullHttpMessageFormatter($maxBodyLength))->formatRequest($this->createRequestStub($stream, self::HEADERS)) + ); + } + + /** + * @dataProvider unreadableBodyProvider + */ + #[DataProvider('unreadableBodyProvider')] + public function testDoesNotReadResponseBody(int $maxBodyLength, bool $seekable): void + { + $stream = $this->createMock(StreamInterface::class); + $stream->method('isSeekable')->willReturn($seekable); + $stream->expects($this->never())->method('__toString'); + $stream->expects($this->never())->method('rewind'); + + self::assertSame( + "HTTP/1.1 200 OK\nX-Param-Foo: foo\nX-Param-Bar: bar\n\n", + (new FullHttpMessageFormatter($maxBodyLength))->formatResponse($this->createResponseStub($stream)) + ); + } + + public function testOmitsBinaryBody(): void + { + $stream = $this->createSeekableStream("\0"); + + self::assertSame( + "GET /foo HTTP/1.1\n\n[binary stream omitted]", + (new FullHttpMessageFormatter(1))->formatRequest($this->createRequestStub($stream, [])) + ); + } + + public function testAllowsCustomBinaryDetection(): void + { + $stream = $this->createSeekableStream("\0"); + + self::assertSame( + "GET /foo HTTP/1.1\n\n\0", + (new FullHttpMessageFormatter(1, '/\x01/'))->formatRequest($this->createRequestStub($stream, [])) + ); + } + + public function testKeepsLineBreaksInBody(): void + { + $stream = $this->createSeekableStream("foo\nbar"); + + self::assertSame( + "GET /foo HTTP/1.1\n\nfoo\nbar", + (new FullHttpMessageFormatter(7))->formatRequest($this->createRequestStub($stream, [])) + ); + } + + public function testTruncatesMultibyteBodyByCharacters(): void + { + $stream = $this->createSeekableStream('Grüße aus Österreich'); + + self::assertSame( + "GET /foo HTTP/1.1\n\nGrüße", + (new FullHttpMessageFormatter(5))->formatRequest($this->createRequestStub($stream, [])) + ); + } + + private function createSeekableStream(string $content): StreamInterface + { + $stream = $this->createMock(StreamInterface::class); + $stream->method('isSeekable')->willReturn(true); + $stream->method('__toString')->willReturn($content); + $stream->expects($this->once())->method('rewind'); + + return $stream; + } + + /** + * @param array> $headers + */ + private function createRequestStub(StreamInterface $body, array $headers): RequestInterface + { + $request = $this->createStub(RequestInterface::class); + $request->method('getBody')->willReturn($body); + $request->method('getMethod')->willReturn('GET'); + $request->method('getRequestTarget')->willReturn('/foo'); + $request->method('getProtocolVersion')->willReturn('1.1'); + $request->method('getHeaders')->willReturn($headers); + + return $request; + } + + private function createResponseStub(StreamInterface $body): ResponseInterface + { + $response = $this->createStub(ResponseInterface::class); + $response->method('getBody')->willReturn($body); + $response->method('getProtocolVersion')->willReturn('1.1'); + $response->method('getStatusCode')->willReturn(200); + $response->method('getReasonPhrase')->willReturn('OK'); + $response->method('getHeaders')->willReturn(self::HEADERS); + + return $response; + } +} diff --git a/tests/Formatter/SimpleFormatterTest.php b/tests/Formatter/SimpleFormatterTest.php new file mode 100644 index 0000000..4d39341 --- /dev/null +++ b/tests/Formatter/SimpleFormatterTest.php @@ -0,0 +1,46 @@ +createStub(UriInterface::class); + $uri->method('__toString')->willReturn('http://foo.com/bar'); + + $request = $this->createStub(RequestInterface::class); + $request->method('getMethod')->willReturn('GET'); + $request->method('getUri')->willReturn($uri); + $request->method('getProtocolVersion')->willReturn('1.1'); + + self::assertSame('GET http://foo.com/bar 1.1', (new SimpleFormatter())->formatRequest($request)); + } + + public function testFormatsResponse(): void + { + $response = $this->createStub(ResponseInterface::class); + $response->method('getReasonPhrase')->willReturn('OK'); + $response->method('getProtocolVersion')->willReturn('1.1'); + $response->method('getStatusCode')->willReturn(200); + + $formatter = new SimpleFormatter(); + + self::assertSame('200 OK 1.1', $formatter->formatResponse($response)); + self::assertSame('200 OK 1.1', $formatter->formatResponseForRequest($response, $this->createStub(RequestInterface::class))); + } +} diff --git a/tests/MessageFactory/DiactorosMessageFactoryTest.php b/tests/MessageFactory/DiactorosMessageFactoryTest.php new file mode 100644 index 0000000..60afd1a --- /dev/null +++ b/tests/MessageFactory/DiactorosMessageFactoryTest.php @@ -0,0 +1,16 @@ +createFactory()->createRequest('GET', '/', ['X-hello' => 'world'], 'lorem'); + + self::assertSame('GET', $request->getMethod()); + self::assertSame('/', $request->getRequestTarget()); + self::assertSame('lorem', (string) $request->getBody()); + self::assertSame('world', $request->getHeaderLine('X-hello')); + self::assertSame('1.1', $request->getProtocolVersion()); + } + + public function testCreatesRequestWithProtocolVersion(): void + { + $request = $this->createFactory()->createRequest('POST', 'http://php-http.org/', [], null, '1.0'); + + self::assertSame('POST', $request->getMethod()); + self::assertSame('1.0', $request->getProtocolVersion()); + } + + public function testCreatesResponse(): void + { + $response = $this->createFactory()->createResponse(); + + self::assertSame(200, $response->getStatusCode()); + } + + public function testCreatesResponseWithArguments(): void + { + $response = $this->createFactory()->createResponse(404, 'Not Found', ['X-hello' => 'world'], 'lorem', '1.0'); + + self::assertSame(404, $response->getStatusCode()); + self::assertSame('Not Found', $response->getReasonPhrase()); + self::assertSame('world', $response->getHeaderLine('X-hello')); + self::assertSame('lorem', (string) $response->getBody()); + self::assertSame('1.0', $response->getProtocolVersion()); + } +} diff --git a/tests/MessageFactory/SlimMessageFactoryTest.php b/tests/MessageFactory/SlimMessageFactoryTest.php new file mode 100644 index 0000000..4657ee9 --- /dev/null +++ b/tests/MessageFactory/SlimMessageFactoryTest.php @@ -0,0 +1,24 @@ +createStub(RequestInterface::class); + $received = null; + + $matcher = new CallbackRequestMatcher(static function (RequestInterface $r) use (&$received): bool { + $received = $r; + + return true; + }); + + self::assertTrue($matcher->matches($request)); + self::assertSame($request, $received); + } + + public function testDoesNotMatchRequest(): void + { + $matcher = new CallbackRequestMatcher(static function (): bool { + return false; + }); + + self::assertFalse($matcher->matches($this->createStub(RequestInterface::class))); + } +} diff --git a/tests/RequestMatcher/RegexRequestMatcherTest.php b/tests/RequestMatcher/RegexRequestMatcherTest.php new file mode 100644 index 0000000..0abb3d5 --- /dev/null +++ b/tests/RequestMatcher/RegexRequestMatcherTest.php @@ -0,0 +1,40 @@ +matches($this->createRequest('/test'))); + } + + public function testDoesNotMatchRequest(): void + { + self::assertFalse((new RegexRequestMatcher('/test/'))->matches($this->createRequest('/ttttt'))); + } + + private function createRequest(string $uri): RequestInterface + { + $uriStub = $this->createStub(UriInterface::class); + $uriStub->method('__toString')->willReturn($uri); + + $request = $this->createStub(RequestInterface::class); + $request->method('getUri')->willReturn($uriStub); + + return $request; + } +} diff --git a/tests/RequestMatcher/RequestMatcherTest.php b/tests/RequestMatcher/RequestMatcherTest.php new file mode 100644 index 0000000..f76e882 --- /dev/null +++ b/tests/RequestMatcher/RequestMatcherTest.php @@ -0,0 +1,53 @@ +matches(new Request('DELETE', 'ftp://example.com/anything'))); + } + + /** + * @return iterable + */ + public static function matchProvider(): iterable + { + yield 'path matches' => [new RequestMatcher('^/tes?'), 'GET', 'http://php-http.org/test/foo', true]; + yield 'path does not match' => [new RequestMatcher('^/tes?'), 'GET', 'http://php-http.org/ttttt', false]; + yield 'path is url decoded' => [new RequestMatcher('^/hello world$'), 'GET', 'http://php-http.org/hello%20world', true]; + yield 'host matches' => [new RequestMatcher(null, 'php-htt?'), 'GET', 'http://php-http.org/', true]; + yield 'host matches case insensitive' => [new RequestMatcher(null, 'PHP-HTTP'), 'GET', 'http://php-http.org/', true]; + yield 'host does not match' => [new RequestMatcher(null, 'php-htt?'), 'GET', 'http://httplug.io/', false]; + yield 'method matches' => [new RequestMatcher(null, null, 'get'), 'GET', 'http://php-http.org/', true]; + yield 'one of many methods matches' => [new RequestMatcher(null, null, ['get', 'post']), 'POST', 'http://php-http.org/', true]; + yield 'method does not match' => [new RequestMatcher(null, null, 'get'), 'POST', 'http://php-http.org/', false]; + yield 'scheme matches' => [new RequestMatcher(null, null, [], 'http'), 'GET', 'http://php-http.org/', true]; + yield 'scheme does not match' => [new RequestMatcher(null, null, [], 'http'), 'GET', 'https://php-http.org/', false]; + yield 'all constraints match' => [new RequestMatcher('^/api', 'example\.com$', 'POST', 'https'), 'POST', 'https://example.com/api/users', true]; + yield 'one constraint fails' => [new RequestMatcher('^/api', 'example\.com$', 'POST', 'https'), 'GET', 'https://example.com/api/users', false]; + } + + /** + * @dataProvider matchProvider + */ + #[DataProvider('matchProvider')] + public function testMatches(RequestMatcher $matcher, string $method, string $uri, bool $expected): void + { + self::assertSame($expected, $matcher->matches(new Request($method, $uri))); + } +} diff --git a/tests/Stream/BufferedStreamTest.php b/tests/Stream/BufferedStreamTest.php new file mode 100644 index 0000000..39b658f --- /dev/null +++ b/tests/Stream/BufferedStreamTest.php @@ -0,0 +1,181 @@ +createNonSeekableStream('foo'))); + } + + public function testDetaches(): void + { + $inner = $this->createMock(StreamInterface::class); + $inner->method('getSize')->willReturn(null); + $inner->method('eof')->willReturn(true); + $inner->expects($this->once())->method('close'); + + $stream = new BufferedStream($inner); + + self::assertIsResource($stream->detach()); + self::assertNull($stream->detach()); + self::assertFalse($stream->isSeekable()); + self::assertFalse($stream->isReadable()); + self::assertNull($stream->getSize()); + self::assertSame([], $stream->getMetadata()); + } + + public function testGetsSizeOnceUnderlyingStreamIsConsumed(): void + { + $stream = new BufferedStream($this->createNonSeekableStream('foo')); + + self::assertNull($stream->getSize()); + self::assertSame('foo', $stream->getContents()); + self::assertSame(3, $stream->getSize()); + } + + public function testUsesKnownSizeOfUnderlyingStream(): void + { + self::assertSame(3, (new BufferedStream(new MemoryStream('foo')))->getSize()); + } + + public function testTells(): void + { + $stream = new BufferedStream($this->createNonSeekableStream('foo')); + + self::assertSame(0, $stream->tell()); + self::assertSame('foo', $stream->getContents()); + self::assertSame(3, $stream->tell()); + } + + public function testEof(): void + { + $stream = new BufferedStream($this->createNonSeekableStream('foo')); + + self::assertFalse($stream->eof()); + self::assertSame('foo', $stream->getContents()); + self::assertTrue($stream->eof()); + + // underlying stream is at eof, but the buffer is not + $stream->seek(0); + self::assertFalse($stream->eof()); + } + + public function testIsSeekable(): void + { + self::assertTrue((new BufferedStream($this->createNonSeekableStream('')))->isSeekable()); + } + + public function testSeeks(): void + { + $stream = new BufferedStream($this->createNonSeekableStream('foo')); + + $stream->seek(0); + self::assertSame(0, $stream->tell()); + + self::assertSame('foo', $stream->getContents()); + $stream->seek(2); + self::assertSame(2, $stream->tell()); + self::assertSame('o', $stream->read(1)); + } + + public function testRewinds(): void + { + $stream = new BufferedStream($this->createNonSeekableStream('foo')); + + $stream->rewind(); + self::assertSame(0, $stream->tell()); + + self::assertSame('foo', $stream->getContents()); + self::assertSame(3, $stream->tell()); + + $stream->rewind(); + self::assertSame(0, $stream->tell()); + self::assertSame('foo', $stream->getContents()); + } + + public function testIsNotWritable(): void + { + $stream = new BufferedStream($this->createNonSeekableStream('')); + + self::assertFalse($stream->isWritable()); + + $this->expectException(\RuntimeException::class); + $stream->write('foo'); + } + + public function testIsReadable(): void + { + self::assertTrue((new BufferedStream($this->createNonSeekableStream('')))->isReadable()); + } + + public function testReadsFromBufferAndUnderlyingStream(): void + { + $stream = new BufferedStream($this->createNonSeekableStream('foobarbaz')); + + self::assertSame('foo', $stream->read(3)); + self::assertSame('bar', $stream->read(3)); + + $stream->rewind(); + self::assertSame('foob', $stream->read(4)); + self::assertSame('arbaz', $stream->read(5)); + } + + public function testReadsZeroBytes(): void + { + self::assertSame('', (new BufferedStream($this->createNonSeekableStream('foo')))->read(0)); + } + + public function testGetsContents(): void + { + $stream = new BufferedStream($this->createNonSeekableStream('foo')); + + self::assertSame('foo', $stream->getContents()); + self::assertTrue($stream->eof()); + } + + public function testGetsMetadata(): void + { + $stream = new BufferedStream($this->createNonSeekableStream('')); + + self::assertIsArray($stream->getMetadata()); + self::assertNull($stream->getMetadata('unexistant')); + self::assertSame('TEMP', $stream->getMetadata('stream_type')); + } + + public function testUsesMemoryBufferWhenFileBufferIsDisabled(): void + { + self::assertSame('MEMORY', (new BufferedStream($this->createNonSeekableStream(''), false))->getMetadata('stream_type')); + } + + /** + * @return StreamInterface a stream of unknown size that can only be read forward + */ + private function createNonSeekableStream(string $content): StreamInterface + { + $position = 0; + + $stream = $this->createStub(StreamInterface::class); + $stream->method('getSize')->willReturn(null); + $stream->method('isSeekable')->willReturn(false); + $stream->method('eof')->willReturnCallback(static function () use (&$position, $content): bool { + return $position >= strlen($content); + }); + $stream->method('read')->willReturnCallback(static function (int $length) use (&$position, $content): string { + $chunk = (string) substr($content, $position, $length); + $position += strlen($chunk); + + return $chunk; + }); + + return $stream; + } +} diff --git a/tests/StreamFactory/DiactorosStreamFactoryTest.php b/tests/StreamFactory/DiactorosStreamFactoryTest.php new file mode 100644 index 0000000..af90f62 --- /dev/null +++ b/tests/StreamFactory/DiactorosStreamFactoryTest.php @@ -0,0 +1,23 @@ +createFactory()->createStream('foo'); + + self::assertSame('foo', (string) $stream); + } + + public function testCreatesStreamFromNull(): void + { + $stream = $this->createFactory()->createStream(null); + + self::assertSame('', (string) $stream); + } + + public function testCreatesStreamFromResource(): void + { + $resource = $this->openMemoryResource('foo'); + + self::assertSame('foo', (string) $this->createFactory()->createStream($resource)); + } + + public function testCreatesStreamFromStream(): void + { + $stream = $this->createNativeStream($this->openMemoryResource('foo')); + + self::assertSame($stream, $this->createFactory()->createStream($stream)); + } + + public function testCreatesStreamFromNonSeekableResource(): void + { + if ('\\' === DIRECTORY_SEPARATOR) { + self::markTestSkipped('Unix domain socket pairs are not available on Windows.'); + } + + $pair = stream_socket_pair(STREAM_PF_UNIX, STREAM_SOCK_STREAM, STREAM_IPPROTO_IP); + self::assertIsArray($pair); + [$reader, $writer] = $pair; + fwrite($writer, 'foo'); + fclose($writer); + + $stream = $this->createFactory()->createStream($reader); + + self::assertFalse($stream->isSeekable()); + self::assertSame('foo', $stream->getContents()); + } + + public function testDoesNotRewindExistingStream(): void + { + $stream = $this->createNativeStream($this->openMemoryResource('abcdef')); + $stream->seek(3); + + self::assertSame('def', $this->createFactory()->createStream($stream)->getContents()); + } + + public function testDoesNotRewindExistingResource(): void + { + $resource = $this->openMemoryResource('abcdef'); + fseek($resource, 3); + + self::assertSame('def', $this->createFactory()->createStream($resource)->getContents()); + } + + /** + * @return resource + */ + private function openMemoryResource(string $content) + { + $resource = fopen('php://memory', 'rw+'); + self::assertIsResource($resource); + fwrite($resource, $content); + rewind($resource); + + return $resource; + } +} diff --git a/tests/UriFactory/DiactorosUriFactoryTest.php b/tests/UriFactory/DiactorosUriFactoryTest.php new file mode 100644 index 0000000..f4489e4 --- /dev/null +++ b/tests/UriFactory/DiactorosUriFactoryTest.php @@ -0,0 +1,16 @@ +createFactory()->createUri('http://php-http.org/path?query#fragment'); + + self::assertSame('http', $uri->getScheme()); + self::assertSame('php-http.org', $uri->getHost()); + self::assertSame('/path', $uri->getPath()); + self::assertSame('query', $uri->getQuery()); + self::assertSame('fragment', $uri->getFragment()); + } + + public function testReturnsGivenUri(): void + { + $uri = $this->createStub(UriInterface::class); + + self::assertSame($uri, $this->createFactory()->createUri($uri)); + } + + public function testThrowsExceptionWhenUriIsInvalid(): void + { + $this->expectException(\InvalidArgumentException::class); + + $this->createFactory()->createUri(null); + } +} diff --git a/tests/functions.php b/tests/functions.php new file mode 100644 index 0000000..1411bcd --- /dev/null +++ b/tests/functions.php @@ -0,0 +1,16 @@ +