diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
index e38d45624..05a0ca204 100644
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -1,49 +1,51 @@
name: Tests
-on: [push, pull_request]
+on:
+ push:
+ branches: [3.x]
+ pull_request:
jobs:
tests:
- name: Tests PHP ${{ matrix.php }}
+ name: PHP ${{ matrix.php }}
runs-on: ubuntu-latest
- continue-on-error: ${{ matrix.experimental }}
strategy:
fail-fast: false
matrix:
- php: [7.3, 7.4, 8.0]
- experimental: [false]
+ php: ['8.1', '8.2', '8.3', '8.4', '8.5']
include:
- - php: 8.0
- analysis: true
- - php: 8.1
- experimental: true
+ - php: '8.5'
+ coverage: 'xdebug'
steps:
- name: Checkout
- uses: actions/checkout@v2
+ uses: actions/checkout@v4
- name: Set up PHP ${{ matrix.php }}
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
- coverage: xdebug
+ coverage: ${{ matrix.coverage || 'none' }}
- name: Install dependencies with Composer
- uses: ramsey/composer-install@v1
+ uses: ramsey/composer-install@v3
- name: Coding standards
- if: matrix.analysis
run: vendor/bin/phpcs
- name: Static analysis
- if: matrix.analysis
- run: vendor/bin/phpstan
+ run: vendor/bin/phpstan analyse --memory-limit=512M
- name: Tests
+ if: ${{ !matrix.coverage }}
+ run: vendor/bin/phpunit
+
+ - name: Tests with coverage
+ if: ${{ matrix.coverage }}
run: vendor/bin/phpunit --coverage-clover clover.xml
- name: Upload coverage results to Coveralls
- if: matrix.analysis
+ if: ${{ matrix.coverage }}
env:
COVERALLS_REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
diff --git a/.gitignore b/.gitignore
index 98775835b..5887e7559 100644
--- a/.gitignore
+++ b/.gitignore
@@ -4,3 +4,4 @@ coverage
vendor
.DS_Store
.idea
+.phpunit.result.cache
diff --git a/.travis.yml b/.travis.yml
deleted file mode 100644
index 18e01111e..000000000
--- a/.travis.yml
+++ /dev/null
@@ -1,30 +0,0 @@
-sudo: false
-
-language: php
-
-dist: trusty
-
-php:
- - 5.5
- - 5.6
- - 7.0
- - 7.1
- - 7.2
- - 7.3
-
-before_script:
- - if [[ "$TRAVIS_PHP_VERSION" == '5.6' ]]; then composer require satooshi/php-coveralls:1.* squizlabs/php_codesniffer:2.* -n ; fi
- - if [[ "$TRAVIS_PHP_VERSION" == '7.1' ]]; then composer require phpstan/phpstan:^0.10.3 -n ; fi
- - if [[ "$TRAVIS_PHP_VERSION" != '5.6' ]]; then composer install -n ; fi
-
-script:
- - if [[ "$TRAVIS_PHP_VERSION" == '5.6' ]]; then vendor/bin/phpunit --coverage-clover clover.xml ; fi
- - if [[ "$TRAVIS_PHP_VERSION" != '5.6' ]]; then vendor/bin/phpunit ; fi
- - if [[ "$TRAVIS_PHP_VERSION" == '5.6' ]]; then vendor/bin/phpcs ; fi
- - if [[ "$TRAVIS_PHP_VERSION" == '7.1' ]]; then vendor/bin/phpstan analyse Slim ; fi
-
-after_script:
- - if [[ "$TRAVIS_PHP_VERSION" == '5.6' ]]; then php vendor/bin/coveralls --coverage_clover=clover.xml -v ; fi
-
-notifications:
- slack: slimphp:0RNzx2JuhkAqIf0MXcUZ0asT
diff --git a/README.md b/README.md
index 292addb86..bcdfc40c9 100644
--- a/README.md
+++ b/README.md
@@ -16,7 +16,12 @@ It's recommended that you use [Composer](https://getcomposer.org/) to install Sl
$ composer require slim/slim "^3.0"
```
-This will install Slim and all required dependencies. Slim requires PHP 5.5.0 or newer.
+This will install Slim and all required dependencies.
+
+## Version compatibility
+
+- Slim version 3.13.0 requires PHP 8.1 or newer.
+- Slim version 3.12.x and below requires PHP 5.5 – PHP 8.1.
## Usage
diff --git a/Slim/App.php b/Slim/App.php
index 67a4d9eec..e73249f88 100644
--- a/Slim/App.php
+++ b/Slim/App.php
@@ -547,7 +547,7 @@ public function subRequest(
array $headers = [],
array $cookies = [],
$bodyContent = '',
- ResponseInterface $response = null
+ ?ResponseInterface $response = null
) {
$env = $this->container->get('environment');
$uri = Uri::createFromEnvironment($env)->withPath($path)->withQuery($query);
@@ -663,7 +663,7 @@ protected function isEmptyResponse(ResponseInterface $response)
*/
protected function isHeadRequest(RequestInterface $request)
{
- return strtoupper($request->getMethod()) === 'HEAD';
+ return strtoupper((string)$request->getMethod()) === 'HEAD';
}
/**
diff --git a/Slim/Collection.php b/Slim/Collection.php
index 2eaec44a3..504699118 100644
--- a/Slim/Collection.php
+++ b/Slim/Collection.php
@@ -16,6 +16,8 @@
* This class provides a common interface used by many other
* classes in a Slim application that manage "collections"
* of data that must be inspected and/or manipulated
+ *
+ * @phpstan-consistent-constructor
*/
class Collection implements CollectionInterface
{
@@ -109,6 +111,7 @@ public function clear()
*
* @return bool
*/
+ #[\ReturnTypeWillChange]
public function offsetExists($key)
{
return $this->has($key);
@@ -121,6 +124,7 @@ public function offsetExists($key)
*
* @return mixed The key's value, or the default value
*/
+ #[\ReturnTypeWillChange]
public function offsetGet($key)
{
return $this->get($key);
@@ -132,6 +136,7 @@ public function offsetGet($key)
* @param string $key The data key
* @param mixed $value The data value
*/
+ #[\ReturnTypeWillChange]
public function offsetSet($key, $value)
{
$this->set($key, $value);
@@ -142,6 +147,7 @@ public function offsetSet($key, $value)
*
* @param string $key The data key
*/
+ #[\ReturnTypeWillChange]
public function offsetUnset($key)
{
$this->remove($key);
@@ -152,6 +158,7 @@ public function offsetUnset($key)
*
* @return int
*/
+ #[\ReturnTypeWillChange]
public function count()
{
return count($this->data);
@@ -162,6 +169,7 @@ public function count()
*
* @return ArrayIterator
*/
+ #[\ReturnTypeWillChange]
public function getIterator()
{
return new ArrayIterator($this->data);
diff --git a/Slim/Container.php b/Slim/Container.php
index 4641f6871..01a592fca 100644
--- a/Slim/Container.php
+++ b/Slim/Container.php
@@ -111,7 +111,7 @@ public function get($id)
if ($this->exceptionThrownByContainer($exception)) {
throw new SlimContainerException(
sprintf('Container error while retrieving "%s"', $id),
- null,
+ 0,
$exception
);
} else {
diff --git a/Slim/DeferredCallable.php b/Slim/DeferredCallable.php
index 5f335841c..5769eca37 100644
--- a/Slim/DeferredCallable.php
+++ b/Slim/DeferredCallable.php
@@ -28,7 +28,7 @@ class DeferredCallable
* @param callable|string $callable
* @param ContainerInterface $container
*/
- public function __construct($callable, ContainerInterface $container = null)
+ public function __construct($callable, ?ContainerInterface $container = null)
{
$this->callable = $callable;
$this->container = $container;
diff --git a/Slim/Handlers/AbstractHandler.php b/Slim/Handlers/AbstractHandler.php
index 5ace9a0fe..4359e24f5 100644
--- a/Slim/Handlers/AbstractHandler.php
+++ b/Slim/Handlers/AbstractHandler.php
@@ -36,7 +36,7 @@ abstract class AbstractHandler
*/
protected function determineContentType(ServerRequestInterface $request)
{
- $acceptHeader = $request->getHeaderLine('Accept');
+ $acceptHeader = (string)$request->getHeaderLine('Accept');
$selectedContentTypes = array_intersect(explode(',', $acceptHeader), $this->knownContentTypes);
if (count($selectedContentTypes)) {
diff --git a/Slim/Http/Request.php b/Slim/Http/Request.php
index 5df7405f5..14569fdfa 100644
--- a/Slim/Http/Request.php
+++ b/Slim/Http/Request.php
@@ -25,6 +25,8 @@
* @link https://github.com/php-fig/http-message/blob/master/src/MessageInterface.php
* @link https://github.com/php-fig/http-message/blob/master/src/RequestInterface.php
* @link https://github.com/php-fig/http-message/blob/master/src/ServerRequestInterface.php
+ *
+ * @phpstan-consistent-constructor
*/
class Request extends Message implements ServerRequestInterface
{
@@ -490,7 +492,7 @@ public function getRequestTarget()
} else {
$basePath = '';
}
- $path = $this->uri->getPath();
+ $path = (string)$this->uri->getPath();
$path = $basePath . '/' . ltrim($path, '/');
$query = $this->uri->getQuery();
@@ -1011,7 +1013,7 @@ public function getParsedBody()
return null;
}
- $mediaType = $this->getMediaType();
+ $mediaType = (string)$this->getMediaType();
// Check if this specific media type has a parser registered first
if (!isset($this->bodyParsers[$mediaType])) {
@@ -1188,7 +1190,7 @@ public function getQueryParam($key, $default = null)
*
* @return mixed[]
*/
- public function getParams(array $only = null)
+ public function getParams(?array $only = null)
{
$params = $this->getQueryParams();
$postParams = $this->getParsedBody();
diff --git a/Slim/Http/Response.php b/Slim/Http/Response.php
index 8ad475d44..f735620ee 100644
--- a/Slim/Http/Response.php
+++ b/Slim/Http/Response.php
@@ -131,8 +131,8 @@ class Response extends Message implements ResponseInterface
*/
public function __construct(
$status = StatusCode::HTTP_OK,
- HeadersInterface $headers = null,
- StreamInterface $body = null
+ ?HeadersInterface $headers = null,
+ ?StreamInterface $body = null
) {
$this->status = $this->filterStatus($status);
$this->headers = $headers ? $headers : new Headers();
@@ -190,7 +190,7 @@ public function withStatus($code, $reasonPhrase = '')
{
$code = $this->filterStatus($code);
- if (!is_string($reasonPhrase) && !method_exists($reasonPhrase, '__toString')) {
+ if (!is_string($reasonPhrase) && !$reasonPhrase instanceof \Stringable) {
throw new InvalidArgumentException('ReasonPhrase must be a string');
}
diff --git a/Slim/Http/UploadedFile.php b/Slim/Http/UploadedFile.php
index 401440dbc..8e056732f 100644
--- a/Slim/Http/UploadedFile.php
+++ b/Slim/Http/UploadedFile.php
@@ -17,6 +17,8 @@
*
* @link https://github.com/php-fig/http-message/blob/master/src/UploadedFileInterface.php
* @link https://github.com/php-fig/http-message/blob/master/src/StreamInterface.php
+ *
+ * @phpstan-consistent-constructor
*/
class UploadedFile implements UploadedFileInterface
{
diff --git a/Slim/Http/Uri.php b/Slim/Http/Uri.php
index 5c67ec8cd..dea767b53 100644
--- a/Slim/Http/Uri.php
+++ b/Slim/Http/Uri.php
@@ -29,6 +29,8 @@
* server parameters.
*
* @link http://tools.ietf.org/html/rfc3986 (the URI specification)
+ *
+ * @phpstan-consistent-constructor
*/
class Uri implements UriInterface
{
@@ -134,7 +136,7 @@ public function __construct(
*/
public static function createFromString($uri)
{
- if (!is_string($uri) && !method_exists($uri, '__toString')) {
+ if (!is_string($uri) && !$uri instanceof \Stringable) {
throw new InvalidArgumentException('Uri must be a string');
}
@@ -170,11 +172,11 @@ public static function createFromEnvironment(Environment $env)
// Authority: Host and Port
if ($env->has('HTTP_HOST')) {
- $host = $env->get('HTTP_HOST');
+ $host = (string)$env->get('HTTP_HOST');
// set a port default
$port = null;
} else {
- $host = $env->get('SERVER_NAME');
+ $host = (string)$env->get('SERVER_NAME');
// set a port default
$port = (int)$env->get('SERVER_PORT', 80);
}
@@ -294,7 +296,7 @@ protected function filterScheme($scheme)
'http' => true,
];
- if (!is_string($scheme) && !method_exists($scheme, '__toString')) {
+ if (!is_string($scheme) && !$scheme instanceof \Stringable) {
throw new InvalidArgumentException('Uri scheme must be a string');
}
@@ -694,7 +696,7 @@ public function getQuery()
*/
public function withQuery($query)
{
- if (!is_string($query) && !method_exists($query, '__toString')) {
+ if (!is_string($query) && !$query instanceof \Stringable) {
throw new InvalidArgumentException('Uri query must be a string');
}
$query = ltrim((string)$query, '?');
@@ -718,7 +720,7 @@ protected function filterQuery($query)
function ($match) {
return rawurlencode($match[0]);
},
- $query
+ (string)$query
);
}
@@ -761,7 +763,7 @@ public function getFragment()
*/
public function withFragment($fragment)
{
- if (!is_string($fragment) && !method_exists($fragment, '__toString')) {
+ if (!is_string($fragment) && !$fragment instanceof \Stringable) {
throw new InvalidArgumentException('Uri fragment must be a string');
}
$fragment = ltrim((string)$fragment, '#');
diff --git a/Slim/MiddlewareAwareTrait.php b/Slim/MiddlewareAwareTrait.php
index 3f3236616..58c1d2e69 100644
--- a/Slim/MiddlewareAwareTrait.php
+++ b/Slim/MiddlewareAwareTrait.php
@@ -87,7 +87,7 @@ protected function addMiddleware(callable $callable)
*
* @throws RuntimeException if the stack is seeded more than once
*/
- protected function seedMiddlewareStack(callable $kernel = null)
+ protected function seedMiddlewareStack(?callable $kernel = null)
{
if (!is_null($this->tip)) {
throw new RuntimeException('MiddlewareStack can only be seeded once.');
diff --git a/Slim/RouteGroup.php b/Slim/RouteGroup.php
index 26fe5c073..32ce6cd9d 100644
--- a/Slim/RouteGroup.php
+++ b/Slim/RouteGroup.php
@@ -15,7 +15,7 @@ class RouteGroup extends Routable implements RouteGroupInterface
/**
* {@inheritdoc}
*/
- public function __invoke(App $app = null)
+ public function __invoke(?App $app = null)
{
$callable = $this->resolveCallable($this->callable);
if ($callable instanceof Closure && $app !== null) {
diff --git a/Slim/Router.php b/Slim/Router.php
index 08a950182..765907177 100644
--- a/Slim/Router.php
+++ b/Slim/Router.php
@@ -83,7 +83,7 @@ class Router implements RouterInterface
/**
* @param RouteParser $parser
*/
- public function __construct(RouteParser $parser = null)
+ public function __construct(?RouteParser $parser = null)
{
$this->routeParser = $parser ?: new StdParser;
}
diff --git a/composer.json b/composer.json
index 0fd93ded9..4cc1b256f 100644
--- a/composer.json
+++ b/composer.json
@@ -28,7 +28,7 @@
}
],
"require": {
- "php": ">=5.5.0",
+ "php": "^8.1",
"ext-json": "*",
"ext-libxml": "*",
"ext-simplexml": "*",
@@ -39,7 +39,8 @@
},
"require-dev": {
"squizlabs/php_codesniffer": "^3.6.0",
- "phpunit/phpunit": "^4.0"
+ "phpunit/phpunit": "^10.5",
+ "phpstan/phpstan": "^2.1"
},
"provide": {
"psr/http-message-implementation": "1.0"
@@ -58,6 +59,12 @@
"test": [
"phpunit",
"phpcs"
+ ],
+ "test:coverage": [
+ "phpunit --coverage-clover clover.xml"
+ ],
+ "analyse": [
+ "phpstan analyse --memory-limit=512M"
]
}
}
diff --git a/phpstan.neon.dist b/phpstan.neon.dist
index 2fc56e798..942bd40b8 100644
--- a/phpstan.neon.dist
+++ b/phpstan.neon.dist
@@ -1,2 +1,5 @@
parameters:
level: 1
+ paths:
+ - Slim
+ - tests
diff --git a/phpunit.xml.dist b/phpunit.xml.dist
index 3fb4fd955..528dbf50d 100644
--- a/phpunit.xml.dist
+++ b/phpunit.xml.dist
@@ -1,16 +1,14 @@
Method not allowed. Must be one of: GET
', (string)$resOut->getBody() ); // now test that exception is raised if the handler isn't registered unset($app->getContainer()['notAllowedHandler']); - $this->setExpectedException('Slim\Exception\MethodNotAllowedException'); + $this->expectException(\Slim\Exception\MethodNotAllowedException::class); $app($req, $res); } @@ -1246,11 +1247,11 @@ public function testInvokeWithoutMatchingRoute() $resOut = $app($req, $res); $this->assertInstanceOf('\Psr\Http\Message\ResponseInterface', $resOut); - $this->assertAttributeEquals(404, 'status', $resOut); + $this->assertSame(404, $resOut->getStatusCode()); // now test that exception is raised if the handler isn't registered unset($app->getContainer()['notFoundHandler']); - $this->setExpectedException('Slim\Exception\NotFoundException'); + $this->expectException(\Slim\Exception\NotFoundException::class); $app($req, $res); } @@ -1270,7 +1271,7 @@ public function testInvokeWithPimpleCallable() $req = new Request('GET', $uri, $headers, $cookies, $serverParams, $body); $res = new Response(); - $mock = $this->getMockBuilder('StdClass')->setMethods(['bar'])->getMock(); + $mock = $this->getMockBuilder('StdClass')->addMethods(['bar'])->getMock(); $app = new App(); $container = $app->getContainer(); @@ -1311,13 +1312,13 @@ public function testInvokeWithPimpleUndefinedCallable() $app = new App(); $container = $app->getContainer(); - $container['foo'] = function () use ($mock, $res) { + $container['foo'] = function () use ($mock) { return $mock; }; $app->get('/foo', 'foo:bar'); - $this->setExpectedException('\RuntimeException'); + $this->expectException(\RuntimeException::class); // Invoke app $app($req, $res); @@ -1343,7 +1344,7 @@ public function testInvokeWithPimpleCallableViaMagicMethod() $app = new App(); $container = $app->getContainer(); - $container['foo'] = function () use ($mock, $res) { + $container['foo'] = function () use ($mock) { return $mock; }; @@ -1360,15 +1361,6 @@ public function testInvokeFunctionName() { $app = new App(); - // @codingStandardsIgnoreStart - function handle($req, $res) - { - $res->write('foo'); - - return $res; - } - // @codingStandardsIgnoreEnd - $app->get('/foo', __NAMESPACE__ . '\handle'); // Prepare request and response objects @@ -1739,7 +1731,7 @@ public function testRespondIndeterminateLength() $body_stream = fopen('php://temp', 'r+'); $response = new Response(); $body = $this->getMockBuilder("\Slim\Http\Body") - ->setMethods(["getSize"]) + ->onlyMethods(["getSize"]) ->setConstructorArgs([$body_stream]) ->getMock(); fwrite($body_stream, "Hello"); @@ -1891,12 +1883,9 @@ public function testExceptionErrorHandlerDoesNotDisplayErrorDetails() $resOut = $app->run(true); $this->assertEquals(500, $resOut->getStatusCode()); - $this->assertNotRegExp('/.*middleware exception.*/', (string)$resOut); + $this->assertDoesNotMatchRegularExpression('/.*middleware exception.*/', (string)$resOut); } - /** - * @requires PHP 7.0 - */ public function testExceptionPhpErrorHandlerDoesNotDisplayErrorDetails() { $app = new App(); @@ -1918,7 +1907,7 @@ public function testExceptionPhpErrorHandlerDoesNotDisplayErrorDetails() $app->getContainer()['response'] = $res; $mw = function ($req, $res, $next) { - dumpFonction(); + call_user_func('dumpFonction'); }; $app->add($mw); @@ -1930,7 +1919,7 @@ public function testExceptionPhpErrorHandlerDoesNotDisplayErrorDetails() $resOut = $app->run(true); $this->assertEquals(500, $resOut->getStatusCode()); - $this->assertNotRegExp('/.*middleware exception.*/', (string)$resOut); + $this->assertDoesNotMatchRegularExpression('/.*middleware exception.*/', (string)$resOut); } /** @@ -1959,11 +1948,9 @@ public function appFactory() return $app; } - /** - * @expectedException Exception - */ public function testRunExceptionNoHandler() { + $this->expectException(\Exception::class); $app = $this->appFactory(); $container = $app->getContainer(); @@ -1995,9 +1982,6 @@ public function testRunSlimException() $this->assertEquals("Failed", $res->getBody()->getContents()); } - /** - * @requires PHP 7.0 - */ public function testRunThrowable() { $app = $this->appFactory(); @@ -2031,11 +2015,9 @@ public function testRunNotFound() $this->assertEquals(404, $res->getStatusCode()); } - /** - * @expectedException \Slim\Exception\NotFoundException - */ public function testRunNotFoundWithoutHandler() { + $this->expectException(\Slim\Exception\NotFoundException::class); $app = $this->appFactory(); $container = $app->getContainer(); unset($container['notFoundHandler']); @@ -2064,11 +2046,9 @@ public function testRunNotAllowed() $this->assertEquals(405, $res->getStatusCode()); } - /** - * @expectedException \Slim\Exception\MethodNotAllowedException - */ public function testRunNotAllowedWithoutHandler() { + $this->expectException(\Slim\Exception\MethodNotAllowedException::class); $app = $this->appFactory(); $container = $app->getContainer(); unset($container['notAllowedHandler']); @@ -2082,6 +2062,51 @@ public function testRunNotAllowedWithoutHandler() $res = $app->run(true); } + public function testRunWithInvalidMethodOverrideReturnsMethodNotAllowed() + { + $app = new App(['settings' => ['determineRouteBeforeAppMiddleware' => true]]); + $app->get('/foo', function ($req, $res) { + return $res; + }); + + $env = Environment::mock([ + 'SCRIPT_NAME' => '/index.php', + 'REQUEST_URI' => '/foo', + 'REQUEST_METHOD' => 'POST', + 'HTTP_X_HTTP_METHOD_OVERRIDE' => 'B@R', + ]); + $uri = Uri::createFromEnvironment($env); + $headers = Headers::createFromEnvironment($env); + $body = new RequestBody(); + $req = new Request('POST', $uri, $headers, [], $env->all(), $body); + $app->getContainer()['request'] = $req; + + $res = $app->run(true); + + $this->assertSame(405, $res->getStatusCode()); + } + + public function testRunWithInvalidMethodOverrideOnUnknownRouteReturnsNotFound() + { + $app = new App(['settings' => ['determineRouteBeforeAppMiddleware' => true]]); + + $env = Environment::mock([ + 'SCRIPT_NAME' => '/index.php', + 'REQUEST_URI' => '/unknown', + 'REQUEST_METHOD' => 'POST', + 'HTTP_X_HTTP_METHOD_OVERRIDE' => 'B@R', + ]); + $uri = Uri::createFromEnvironment($env); + $headers = Headers::createFromEnvironment($env); + $body = new RequestBody(); + $req = new Request('POST', $uri, $headers, [], $env->all(), $body); + $app->getContainer()['request'] = $req; + + $res = $app->run(true); + + $this->assertSame(404, $res->getStatusCode()); + } + public function testAppRunWithDetermineRouteBeforeAppMiddleware() { $app = $this->appFactory(); @@ -2134,13 +2159,12 @@ public function testExceptionErrorHandlerDisplaysErrorDetails() $resOut = $app->run(true); $this->assertEquals(500, $resOut->getStatusCode()); - $this->assertRegExp('/.*middleware exception.*/', (string)$resOut); + $this->assertMatchesRegularExpression('/.*middleware exception.*/', (string)$resOut); } public function testFinalize() { $method = new ReflectionMethod('Slim\App', 'finalize'); - $method->setAccessible(true); $response = new Response(); $response->getBody()->write('foo'); @@ -2154,7 +2178,6 @@ public function testFinalize() public function testFinalizeWithoutBody() { $method = new ReflectionMethod('Slim\App', 'finalize'); - $method->setAccessible(true); $response = $method->invoke(new App(), new Response(304)); @@ -2186,11 +2209,9 @@ public function testCallingAContainerCallable() $this->assertSame(404, $response->getStatusCode()); } - /** - * @expectedException BadMethodCallException - */ public function testCallingFromContainerNotCallable() { + $this->expectException(\BadMethodCallException::class); $settings = [ 'foo' => function ($c) { return null; @@ -2200,20 +2221,16 @@ public function testCallingFromContainerNotCallable() $app->foo('bar'); } - /** - * @expectedException BadMethodCallException - */ public function testCallingAnUnknownContainerCallableThrows() { + $this->expectException(\BadMethodCallException::class); $app = new App(); $app->foo('bar'); } - /** - * @expectedException BadMethodCallException - */ public function testCallingAnUncallableContainerKeyThrows() { + $this->expectException(\BadMethodCallException::class); $app = new App(); $app->getContainer()['bar'] = 'foo'; $app->foo('bar'); @@ -2222,7 +2239,6 @@ public function testCallingAnUncallableContainerKeyThrows() public function testOmittingContentLength() { $method = new ReflectionMethod('Slim\App', 'finalize'); - $method->setAccessible(true); $response = new Response(); $response->getBody()->write('foo'); @@ -2235,16 +2251,13 @@ public function testOmittingContentLength() $this->assertFalse($response->hasHeader('Content-Length')); } - /** - * @expectedException RuntimeException - * @expectedExceptionMessage Unexpected data in output buffer - */ public function testForUnexpectedDataInOutputBuffer() { + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('Unexpected data in output buffer'); $this->expectOutputString('test'); // needed to avoid risky test warning echo "test"; $method = new ReflectionMethod('Slim\App', 'finalize'); - $method->setAccessible(true); $response = new Response(); $response->getBody()->write('foo'); @@ -2302,7 +2315,7 @@ public function testContainerSetToRoute() $app = new App(); $container = $app->getContainer(); - $container['foo'] = function () use ($mock, $res) { + $container['foo'] = function () use ($mock) { return $mock; }; @@ -2321,7 +2334,6 @@ public function testContainerSetToRoute() public function testIsEmptyResponseWithEmptyMethod() { $method = new ReflectionMethod('Slim\App', 'isEmptyResponse'); - $method->setAccessible(true); $response = new Response(); $response = $response->withStatus(204); @@ -2333,7 +2345,6 @@ public function testIsEmptyResponseWithEmptyMethod() public function testIsEmptyResponseWithoutEmptyMethod() { $method = new ReflectionMethod('Slim\App', 'isEmptyResponse'); - $method->setAccessible(true); /** @var Response $response */ $response = $this->getMockBuilder(ResponseInterface::class)->getMock(); @@ -2347,7 +2358,6 @@ public function testIsEmptyResponseWithoutEmptyMethod() public function testIsHeadRequestWithGetRequest() { $method = new ReflectionMethod('Slim\App', 'isHeadRequest'); - $method->setAccessible(true); /** @var Request $request */ $request = $this->getMockBuilder(RequestInterface::class)->getMock(); @@ -2361,7 +2371,6 @@ public function testIsHeadRequestWithGetRequest() public function testIsHeadRequestWithHeadRequest() { $method = new ReflectionMethod('Slim\App', 'isHeadRequest'); - $method->setAccessible(true); /** @var Request $request */ $request = $this->getMockBuilder(RequestInterface::class)->getMock(); @@ -2374,14 +2383,9 @@ public function testIsHeadRequestWithHeadRequest() public function testHandlePhpError() { - $this->skipIfPhp70(); $method = new ReflectionMethod('Slim\App', 'handlePhpError'); - $method->setAccessible(true); - $throwable = $this->getMock( - '\Throwable', - ['getCode', 'getMessage', 'getFile', 'getLine', 'getTraceAsString', 'getPrevious'] - ); + $throwable = new Exception('Oops'); $req = $this->getMockBuilder('Slim\Http\Request')->disableOriginalConstructor()->getMock(); $res = new Response(); @@ -2604,11 +2608,13 @@ public function testInvokeSequentialProccessAfterAddingAnotherRouteArgument() $this->assertInstanceOf('\Psr\Http\Message\ResponseInterface', $resOut2); $this->assertEquals('3', (string)$resOut2->getBody()); } +} - protected function skipIfPhp70() - { - if (version_compare(PHP_VERSION, '7.0', '>=')) { - $this->markTestSkipped(); - } - } +// @codingStandardsIgnoreStart +function handle($req, $res) +{ + $res->write('foo'); + + return $res; } +// @codingStandardsIgnoreEnd diff --git a/tests/CallableResolverTest.php b/tests/CallableResolverTest.php index f3ac94d06..e3096eacc 100644 --- a/tests/CallableResolverTest.php +++ b/tests/CallableResolverTest.php @@ -7,23 +7,23 @@ namespace Slim\Tests; -use PHPUnit_Framework_TestCase; +use PHPUnit\Framework\TestCase; use Slim\CallableResolver; use Slim\Container; -use Slim\Tests\Mocks\CallableTest; -use Slim\Tests\Mocks\InvokableTest; +use Slim\Tests\Mocks\CallableMock; +use Slim\Tests\Mocks\InvokableMock; -class CallableResolverTest extends PHPUnit_Framework_TestCase +class CallableResolverTest extends TestCase { /** * @var Container */ private $container; - public function setUp() + public function setUp(): void { - CallableTest::$CalledCount = 0; - InvokableTest::$CalledCount = 0; + CallableMock::$CalledCount = 0; + InvokableMock::$CalledCount = 0; $this->container = new Container(); } @@ -41,14 +41,6 @@ public function testClosure() public function testFunctionName() { - // @codingStandardsIgnoreStart - function testCallable() - { - static $called_count = 0; - return $called_count++; - }; - // @codingStandardsIgnoreEnd - $resolver = new CallableResolver($this->container); $callable = $resolver->resolve(__NAMESPACE__ . '\testCallable'); $callable(); @@ -57,89 +49,100 @@ function testCallable() public function testObjMethodArray() { - $obj = new CallableTest(); + $obj = new CallableMock(); $resolver = new CallableResolver($this->container); $callable = $resolver->resolve([$obj, 'toCall']); $callable(); - $this->assertEquals(1, CallableTest::$CalledCount); + $this->assertEquals(1, CallableMock::$CalledCount); } public function testSlimCallable() { $resolver = new CallableResolver($this->container); - $callable = $resolver->resolve('Slim\Tests\Mocks\CallableTest:toCall'); + $callable = $resolver->resolve('Slim\Tests\Mocks\CallableMock:toCall'); $callable(); - $this->assertEquals(1, CallableTest::$CalledCount); + $this->assertEquals(1, CallableMock::$CalledCount); } public function testSlimCallableContainer() { $resolver = new CallableResolver($this->container); - $resolver->resolve('Slim\Tests\Mocks\CallableTest:toCall'); - $this->assertEquals($this->container, CallableTest::$CalledContainer); + $resolver->resolve('Slim\Tests\Mocks\CallableMock:toCall'); + $this->assertEquals($this->container, CallableMock::$CalledContainer); } public function testContainer() { - $this->container['callable_service'] = new CallableTest(); + $this->container['callable_service'] = new CallableMock(); $resolver = new CallableResolver($this->container); $callable = $resolver->resolve('callable_service:toCall'); $callable(); - $this->assertEquals(1, CallableTest::$CalledCount); + $this->assertEquals(1, CallableMock::$CalledCount); } public function testResolutionToAnInvokableClassInContainer() { $this->container['an_invokable'] = function ($c) { - return new InvokableTest(); + return new InvokableMock(); }; $resolver = new CallableResolver($this->container); $callable = $resolver->resolve('an_invokable'); $callable(); - $this->assertEquals(1, InvokableTest::$CalledCount); + $this->assertEquals(1, InvokableMock::$CalledCount); } public function testResolutionToAnInvokableClass() { $resolver = new CallableResolver($this->container); - $callable = $resolver->resolve('Slim\Tests\Mocks\InvokableTest'); + $callable = $resolver->resolve('Slim\Tests\Mocks\InvokableMock'); $callable(); - $this->assertEquals(1, InvokableTest::$CalledCount); + $this->assertEquals(1, InvokableMock::$CalledCount); } public function testMethodNotFoundThrowException() { - $this->container['callable_service'] = new CallableTest(); + $this->container['callable_service'] = new CallableMock(); $resolver = new CallableResolver($this->container); - $this->setExpectedException('\RuntimeException'); + $this->expectException('\RuntimeException'); $resolver->resolve('callable_service:noFound'); } public function testFunctionNotFoundThrowException() { $resolver = new CallableResolver($this->container); - $this->setExpectedException('\RuntimeException'); + $this->expectException('\RuntimeException'); $resolver->resolve('noFound'); } public function testClassNotFoundThrowException() { $resolver = new CallableResolver($this->container); - $this->setExpectedException('\RuntimeException', 'Callable Unknown does not exist'); + $this->expectException('\RuntimeException'); + $this->expectExceptionMessage('Callable Unknown does not exist'); $resolver->resolve('Unknown:notFound'); } public function testCallableClassNotFoundThrowException() { $resolver = new CallableResolver($this->container); - $this->setExpectedException('\RuntimeException', 'is not resolvable'); + $this->expectException('\RuntimeException'); + $this->expectExceptionMessage('is not resolvable'); $resolver->resolve(['Unknown', 'notFound']); } public function testCallableInvalidTypeThrowException() { $resolver = new CallableResolver($this->container); - $this->setExpectedException('\RuntimeException', 'is not resolvable'); + $this->expectException('\RuntimeException'); + $this->expectExceptionMessage('is not resolvable'); $resolver->resolve(__LINE__); } } + +// @codingStandardsIgnoreStart +function testCallable() +{ + static $called_count = 0; + return $called_count++; +} +// @codingStandardsIgnoreEnd diff --git a/tests/CollectionTest.php b/tests/CollectionTest.php index 7c21c66af..7588b901e 100644 --- a/tests/CollectionTest.php +++ b/tests/CollectionTest.php @@ -7,11 +7,11 @@ namespace Slim\Tests; -use PHPUnit_Framework_TestCase; +use PHPUnit\Framework\TestCase; use ReflectionProperty; use Slim\Collection; -class CollectionTest extends PHPUnit_Framework_TestCase +class CollectionTest extends TestCase { /** * @var Collection @@ -23,18 +23,16 @@ class CollectionTest extends PHPUnit_Framework_TestCase */ protected $property; - public function setUp() + public function setUp(): void { $this->bag = new Collection(); $this->property = new ReflectionProperty($this->bag, 'data'); - $this->property->setAccessible(true); } public function testInitializeWithData() { $bag = new Collection(['foo' => 'bar']); $bagProperty = new ReflectionProperty($bag, 'data'); - $bagProperty->setAccessible(true); $this->assertEquals(['foo' => 'bar'], $bagProperty->getValue($bag)); } diff --git a/tests/ContainerTest.php b/tests/ContainerTest.php index b989bb2ff..27fbcec51 100644 --- a/tests/ContainerTest.php +++ b/tests/ContainerTest.php @@ -8,18 +8,18 @@ namespace Slim\Tests; use InvalidArgumentException; -use PHPUnit_Framework_TestCase; +use PHPUnit\Framework\TestCase; use Psr\Container\ContainerInterface; use Slim\Container; -class ContainerTest extends PHPUnit_Framework_TestCase +class ContainerTest extends TestCase { /** * @var Container */ protected $container; - public function setUp() + public function setUp(): void { $this->container = new Container; } @@ -29,22 +29,19 @@ public function testGet() $this->assertInstanceOf('\Slim\Http\Environment', $this->container->get('environment')); } - /** - * @expectedException \Slim\Exception\ContainerValueNotFoundException - */ public function testGetWithValueNotFoundError() { + $this->expectException(\Slim\Exception\ContainerValueNotFoundException::class); $this->container->get('foo'); } /** * Test `get()` throws something that is a ContainerException - typically a NotFoundException, when there is a DI * config error - * - * @expectedException \Slim\Exception\ContainerValueNotFoundException */ public function testGetWithDiConfigErrorThrownAsContainerValueNotFoundException() { + $this->expectException(\Slim\Exception\ContainerValueNotFoundException::class); $container = new Container; $container['foo'] = function (ContainerInterface $container) { @@ -57,11 +54,10 @@ function (ContainerInterface $container) { /** * Test `get()` recasts InvalidArgumentException as psr/container exceptions when an error is present * in the DI config - * - * @expectedException \Slim\Exception\ContainerException */ public function testGetWithDiConfigErrorThrownAsInvalidArgumentException() { + $this->expectException(\Slim\Exception\ContainerException::class); $container = new Container; $container['foo'] = function (ContainerInterface $container) { @@ -73,12 +69,11 @@ function (ContainerInterface $container) { /** * Test `get()` does not recast exceptions which are thrown in a factory closure - * - * @expectedException InvalidArgumentException */ public function testGetWithErrorThrownByFactoryClosure() { - $invokable = $this->getMockBuilder('StdClass')->setMethods(['__invoke'])->getMock(); + $this->expectException(\InvalidArgumentException::class); + $invokable = $this->getMockBuilder('StdClass')->addMethods(['__invoke'])->getMock(); /** @var callable $invokable */ $invokable->expects($this->any()) ->method('__invoke') diff --git a/tests/DeferredCallableTest.php b/tests/DeferredCallableTest.php index eb833830d..ea74a4bc5 100644 --- a/tests/DeferredCallableTest.php +++ b/tests/DeferredCallableTest.php @@ -7,27 +7,27 @@ namespace Slim\Tests; -use PHPUnit_Framework_TestCase; +use PHPUnit\Framework\TestCase; use Slim\Container; use Slim\DeferredCallable; -use Slim\Tests\Mocks\CallableTest; +use Slim\Tests\Mocks\CallableMock; -class DeferredCallableTest extends PHPUnit_Framework_TestCase +class DeferredCallableTest extends TestCase { public function testItResolvesCallable() { $container = new Container(); - $container['CallableTest'] = new CallableTest; + $container['CallableTest'] = new CallableMock; $deferred = new DeferredCallable('CallableTest:toCall', $container); $deferred(); - $this->assertEquals(1, CallableTest::$CalledCount); + $this->assertEquals(1, CallableMock::$CalledCount); } public function testItBindsClosuresToContainer() { - $assertCalled = $this->getMockBuilder('StdClass')->setMethods(['foo'])->getMock(); + $assertCalled = $this->getMockBuilder('StdClass')->addMethods(['foo'])->getMock(); $assertCalled ->expects($this->once()) ->method('foo'); diff --git a/tests/Handlers/AbstractHandlerTest.php b/tests/Handlers/AbstractHandlerTest.php index aa7d08ca7..e0c33aa25 100644 --- a/tests/Handlers/AbstractHandlerTest.php +++ b/tests/Handlers/AbstractHandlerTest.php @@ -7,11 +7,11 @@ namespace Slim\Tests\Handlers; -use PHPUnit_Framework_TestCase; +use PHPUnit\Framework\TestCase; use ReflectionClass; use Slim\Handlers\AbstractHandler; -class AbstractHandlerTest extends PHPUnit_Framework_TestCase +class AbstractHandlerTest extends TestCase { public function testHalfValidContentType() { @@ -30,11 +30,9 @@ public function testHalfValidContentType() $class = new ReflectionClass(AbstractHandler::class); $reflectionProperty = $class->getProperty('knownContentTypes'); - $reflectionProperty->setAccessible(true); $reflectionProperty->setValue($abstractHandler, $newTypes); $method = $class->getMethod('determineContentType'); - $method->setAccessible(true); $return = $method->invoke($abstractHandler, $req); @@ -58,7 +56,6 @@ public function testAcceptableMediaTypeIsNotFirstInList() // provide access to the determineContentType() as it's a protected method $class = new ReflectionClass(AbstractHandler::class); $method = $class->getMethod('determineContentType'); - $method->setAccessible(true); // use a mock object here as AbstractHandler cannot be directly instantiated $abstractHandler = $this->getMockForAbstractClass(AbstractHandler::class); diff --git a/tests/Handlers/ErrorTest.php b/tests/Handlers/ErrorTest.php index d82c9a898..eba90a683 100644 --- a/tests/Handlers/ErrorTest.php +++ b/tests/Handlers/ErrorTest.php @@ -8,8 +8,8 @@ namespace Slim\Tests\Handlers; use Exception; -use PHPUnit_Framework_MockObject_MockObject; -use PHPUnit_Framework_TestCase; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; use ReflectionClass; use RuntimeException; use Slim\Handlers\Error; @@ -17,9 +17,9 @@ use Slim\Http\Response; use UnexpectedValueException; -class ErrorTest extends PHPUnit_Framework_TestCase +class ErrorTest extends TestCase { - public function errorProvider() + public static function errorProvider() { return [ ['application/json', 'application/json', '{'], @@ -67,12 +67,10 @@ public function testErrorDisplayDetails($acceptHeader, $contentType, $startOfBod $this->assertEquals(0, strpos((string)$res->getBody(), $startOfBody)); } - /** - * @expectedException UnexpectedValueException - */ public function testNotFoundContentType() { - $errorMock = $this->getMockBuilder(Error::class)->setMethods(['determineContentType'])->getMock(); + $this->expectException(\UnexpectedValueException::class); + $errorMock = $this->getMockBuilder(Error::class)->onlyMethods(['determineContentType'])->getMock(); $errorMock->method('determineContentType') ->will($this->returnValue('unknown/type')); @@ -89,7 +87,7 @@ public function testNotFoundContentType() */ public function testPreviousException() { - $error = $this->getMockBuilder('\Slim\Handlers\Error')->setMethods(['logError'])->getMock(); + $error = $this->getMockBuilder('\Slim\Handlers\Error')->onlyMethods(['logError'])->getMock(); $error->expects($this->once())->method('logError')->with( $this->logicalAnd( $this->stringContains("Type: Exception" . PHP_EOL . "Message: Second Oops"), @@ -111,9 +109,8 @@ public function testRenderHtmlExceptionOrErrorTypeChecksParameter() { $class = new ReflectionClass(Error::class); $renderHtmlExceptionorError = $class->getMethod('renderHtmlExceptionOrError'); - $renderHtmlExceptionorError->setAccessible(true); - $this->setExpectedException(RuntimeException::class); + $this->expectException(RuntimeException::class); $error = new Error(); $renderHtmlExceptionorError->invokeArgs($error, ['foo']); @@ -122,7 +119,7 @@ public function testRenderHtmlExceptionOrErrorTypeChecksParameter() /** * @param string $method * - * @return PHPUnit_Framework_MockObject_MockObject|Request + * @return PHPUnit\Framework\MockObject\MockObject|Request */ protected function getRequest($method, $acceptHeader) { diff --git a/tests/Handlers/NotAllowedTest.php b/tests/Handlers/NotAllowedTest.php index 49935b406..7ec7f35ca 100644 --- a/tests/Handlers/NotAllowedTest.php +++ b/tests/Handlers/NotAllowedTest.php @@ -7,15 +7,15 @@ namespace Slim\Tests\Handlers; -use PHPUnit_Framework_MockObject_MockObject; -use PHPUnit_Framework_TestCase; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; use Slim\Handlers\NotAllowed; use Slim\Http\Request; use Slim\Http\Response; -class NotAllowedTest extends PHPUnit_Framework_TestCase +class NotAllowedTest extends TestCase { - public function invalidMethodProvider() + public static function invalidMethodProvider() { return [ ['application/json', 'application/json', '{'], @@ -60,18 +60,18 @@ public function testOptions() public function testNotFoundContentType() { - $errorMock = $this->getMockBuilder(NotAllowed::class)->setMethods(['determineContentType'])->getMock(); + $errorMock = $this->getMockBuilder(NotAllowed::class)->onlyMethods(['determineContentType'])->getMock(); $errorMock->method('determineContentType') ->will($this->returnValue('unknown/type')); - $this->setExpectedException('\UnexpectedValueException'); + $this->expectException('\UnexpectedValueException'); $errorMock->__invoke($this->getRequest('GET', 'unknown/type'), new Response(), ['POST']); } /** * @param string $method * - * @return PHPUnit_Framework_MockObject_MockObject|Request + * @return PHPUnit\Framework\MockObject\MockObject|Request */ protected function getRequest($method, $contentType = 'text/html') { diff --git a/tests/Handlers/NotFoundTest.php b/tests/Handlers/NotFoundTest.php index 13351b2d8..ccd9f584f 100644 --- a/tests/Handlers/NotFoundTest.php +++ b/tests/Handlers/NotFoundTest.php @@ -7,16 +7,16 @@ namespace Slim\Tests\Handlers; -use PHPUnit_Framework_MockObject_MockObject; -use PHPUnit_Framework_TestCase; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; use Slim\Handlers\NotFound; use Slim\Http\Request; use Slim\Http\Response; use Slim\Http\Uri; -class NotFoundTest extends PHPUnit_Framework_TestCase +class NotFoundTest extends TestCase { - public function notFoundProvider() + public static function notFoundProvider() { return [ ['application/json', 'application/json', '{'], @@ -47,20 +47,35 @@ public function testNotFound($acceptHeader, $contentType, $startOfBody) public function testNotFoundContentType() { - $errorMock = $this->getMockBuilder(NotFound::class)->setMethods(['determineContentType'])->getMock(); + $errorMock = $this->getMockBuilder(NotFound::class)->onlyMethods(['determineContentType'])->getMock(); $errorMock->method('determineContentType') ->will($this->returnValue('unknown/type')); $req = $this->getMockBuilder('Slim\Http\Request')->disableOriginalConstructor()->getMock(); - $this->setExpectedException('\UnexpectedValueException'); + $this->expectException('\UnexpectedValueException'); $errorMock->__invoke($req, new Response(), ['POST']); } + public function testNotFoundForOptionsRequest() + { + $notFound = new NotFound(); + + $req = $this->getMockBuilder(Request::class)->disableOriginalConstructor()->getMock(); + $req->method('getMethod')->willReturn('OPTIONS'); + + /** @var Response $res */ + $res = $notFound->__invoke($req, new Response(), []); + + $this->assertSame(404, $res->getStatusCode()); + $this->assertSame('text/plain', $res->getHeaderLine('Content-Type')); + $this->assertSame('Not found', (string)$res->getBody()); + } + /** * @param string $method * - * @return PHPUnit_Framework_MockObject_MockObject|Request + * @return PHPUnit\Framework\MockObject\MockObject|Request */ protected function getRequest($method, $contentType = 'text/html') { diff --git a/tests/Handlers/PhpErrorTest.php b/tests/Handlers/PhpErrorTest.php index 864495eff..cc58e29f4 100644 --- a/tests/Handlers/PhpErrorTest.php +++ b/tests/Handlers/PhpErrorTest.php @@ -8,17 +8,14 @@ namespace Slim\Tests\Handlers; use Exception; -use PHPUnit_Framework_MockObject_MockObject; -use PHPUnit_Framework_TestCase; +use PHPUnit\Framework\TestCase; use Slim\Handlers\PhpError; use Slim\Http\Request; use Slim\Http\Response; -use Throwable; -use UnexpectedValueException; -class PhpErrorTest extends PHPUnit_Framework_TestCase +class PhpErrorTest extends TestCase { - public function phpErrorProvider() + public static function phpErrorProvider() { return [ ['application/json', 'application/json', '{'], @@ -33,7 +30,6 @@ public function phpErrorProvider() /** * Test invalid method returns the correct code and content type * - * @requires PHP 7.0 * @dataProvider phpErrorProvider */ public function testPhpError($acceptHeader, $contentType, $startOfBody) @@ -51,7 +47,6 @@ public function testPhpError($acceptHeader, $contentType, $startOfBody) /** * Test invalid method returns the correct code and content type * - * @requires PHP 7.0 * @dataProvider phpErrorProvider */ public function testPhpErrorDisplayDetails($acceptHeader, $contentType, $startOfBody) @@ -68,99 +63,22 @@ public function testPhpErrorDisplayDetails($acceptHeader, $contentType, $startOf $this->assertEquals(0, strpos((string)$res->getBody(), $startOfBody)); } - /** - * @requires PHP 7.0 - */ public function testNotFoundContentType() { - $errorMock = $this->getMockBuilder(PhpError::class)->setMethods(['determineContentType'])->getMock(); + $errorMock = $this->getMockBuilder(PhpError::class)->onlyMethods(['determineContentType'])->getMock(); $errorMock->method('determineContentType') ->will($this->returnValue('unknown/type')); $req = $this->getMockBuilder('Slim\Http\Request')->disableOriginalConstructor()->getMock(); - $this->setExpectedException('\UnexpectedValueException'); + $this->expectException('\UnexpectedValueException'); $errorMock->__invoke($req, new Response(), new Exception()); } - /** - * Test invalid method returns the correct code and content type - * - * @requires PHP 5.0 - * @dataProvider phpErrorProvider - */ - public function testPhpError5($acceptHeader, $contentType, $startOfBody) - { - $this->skipIfPhp70(); - $error = new PhpError(); - - /** @var Throwable $throwable */ - $throwable = $this->getMock( - '\Throwable', - ['getCode', 'getMessage', 'getFile', 'getLine', 'getTraceAsString', 'getPrevious'] - ); - - $res = $error->__invoke($this->getRequest('GET', $acceptHeader), new Response(), $throwable); - - $this->assertSame(500, $res->getStatusCode()); - $this->assertSame($contentType, $res->getHeaderLine('Content-Type')); - $this->assertEquals(0, strpos((string)$res->getBody(), $startOfBody)); - } - - /** - * Test invalid method returns the correct code and content type - * - * @dataProvider phpErrorProvider - */ - public function testPhpErrorDisplayDetails5($acceptHeader, $contentType, $startOfBody) - { - $this->skipIfPhp70(); - - $error = new PhpError(true); - - /** @var Throwable $throwable */ - $throwable = $this->getMock( - '\Throwable', - ['getCode', 'getMessage', 'getFile', 'getLine', 'getTraceAsString', 'getPrevious'] - ); - - $throwablePrev = clone $throwable; - - $throwable->method('getCode')->will($this->returnValue(1)); - $throwable->method('getMessage')->will($this->returnValue('Oops')); - $throwable->method('getFile')->will($this->returnValue('test.php')); - $throwable->method('getLine')->will($this->returnValue('1')); - $throwable->method('getTraceAsString')->will($this->returnValue('This is error')); - $throwable->method('getPrevious')->will($this->returnValue($throwablePrev)); - - $res = $error->__invoke($this->getRequest('GET', $acceptHeader), new Response(), $throwable); - - $this->assertSame(500, $res->getStatusCode()); - $this->assertSame($contentType, $res->getHeaderLine('Content-Type')); - $this->assertEquals(0, strpos((string)$res->getBody(), $startOfBody)); - } - - /** - * @requires PHP 5.0 - * @expectedException UnexpectedValueException - */ - public function testNotFoundContentType5() - { - $this->skipIfPhp70(); - $errorMock = $this->getMock(PhpError::class, ['determineContentType']); - $errorMock->method('determineContentType') - ->will($this->returnValue('unknown/type')); - - $throwable = $this->getMockBuilder('Throwable')->getMock(); - $req = $this->getMockBuilder('Slim\Http\Request')->disableOriginalConstructor()->getMock(); - - $errorMock->__invoke($req, new Response(), $throwable); - } - /** * @param string $method * - * @return PHPUnit_Framework_MockObject_MockObject|Request + * @return PHPUnit\Framework\MockObject\MockObject|Request */ protected function getRequest($method, $acceptHeader) { @@ -169,14 +87,4 @@ protected function getRequest($method, $acceptHeader) return $req; } - - /** - * @return mixed - */ - protected function skipIfPhp70() - { - if (version_compare(PHP_VERSION, '7.0', '>=')) { - $this->markTestSkipped(); - } - } } diff --git a/tests/Http/BodyTest.php b/tests/Http/BodyTest.php index d14a6b800..8fecea389 100644 --- a/tests/Http/BodyTest.php +++ b/tests/Http/BodyTest.php @@ -8,11 +8,11 @@ namespace Slim\Tests\Http; use InvalidArgumentException; -use PHPUnit_Framework_TestCase; +use PHPUnit\Framework\TestCase; use ReflectionProperty; use Slim\Http\Body; -class BodyTest extends PHPUnit_Framework_TestCase +class BodyTest extends TestCase { /** * @var string @@ -25,7 +25,7 @@ class BodyTest extends PHPUnit_Framework_TestCase */ protected $stream; - protected function tearDown() + protected function tearDown(): void { if (is_resource($this->stream) === true) { fclose($this->stream); @@ -55,16 +55,13 @@ public function testConstructorAttachesStream() $this->stream = $this->resourceFactory(); $body = new Body($this->stream); $bodyStream = new ReflectionProperty($body, 'stream'); - $bodyStream->setAccessible(true); $this->assertSame($this->stream, $bodyStream->getValue($body)); } - /** - * @expectedException InvalidArgumentException - */ public function testConstructorInvalidStream() { + $this->expectException(\InvalidArgumentException::class); $this->stream = 'foo'; $body = new Body($this->stream); } @@ -74,7 +71,7 @@ public function testGetMetadata() $this->stream = $this->resourceFactory(); $body = new Body($this->stream); - $this->assertInternalType('array', $body->getMetadata()); + $this->assertIsArray($body->getMetadata()); } public function testGetMetadataKey() @@ -99,19 +96,14 @@ public function testDetach() $body = new Body($this->stream); $bodyStream = new ReflectionProperty($body, 'stream'); - $bodyStream->setAccessible(true); $bodyMetadata = new ReflectionProperty($body, 'meta'); - $bodyMetadata->setAccessible(true); $bodyReadable = new ReflectionProperty($body, 'readable'); - $bodyReadable->setAccessible(true); $bodyWritable = new ReflectionProperty($body, 'writable'); - $bodyWritable->setAccessible(true); $bodySeekable = new ReflectionProperty($body, 'seekable'); - $bodySeekable->setAccessible(true); $result = $body->detach(); @@ -146,7 +138,6 @@ public function testToStringDetached() $this->stream = $this->resourceFactory(); $body = new Body($this->stream); $bodyStream = new ReflectionProperty($body, 'stream'); - $bodyStream->setAccessible(true); $bodyStream->setValue($body, null); $this->assertEquals('', (string)$body); @@ -158,8 +149,8 @@ public function testClose() $body = new Body($this->stream); $body->close(); - $this->assertAttributeEquals(null, 'stream', $body); - //$this->assertFalse($body->isAttached()); #1269 + $streamProp = new ReflectionProperty($body, 'stream'); + $this->assertNull($streamProp->getValue($body)); } public function testGetSizeAttached() @@ -175,7 +166,6 @@ public function testGetSizeDetached() $this->stream = $this->resourceFactory(); $body = new Body($this->stream); $bodyStream = new ReflectionProperty($body, 'stream'); - $bodyStream->setAccessible(true); $bodyStream->setValue($body, null); $this->assertNull($body->getSize()); @@ -195,10 +185,9 @@ public function testTellDetachedThrowsRuntimeException() $this->stream = $this->resourceFactory(); $body = new Body($this->stream); $bodyStream = new ReflectionProperty($body, 'stream'); - $bodyStream->setAccessible(true); $bodyStream->setValue($body, null); - $this->setExpectedException('\RuntimeException'); + $this->expectException('\RuntimeException'); $body->tell(); } @@ -227,7 +216,6 @@ public function testEofDetached() $this->stream = $this->resourceFactory(); $body = new Body($this->stream); $bodyStream = new ReflectionProperty($body, 'stream'); - $bodyStream->setAccessible(true); $bodyStream->setValue($body, null); $this->assertTrue($body->eof()); @@ -319,7 +307,7 @@ public function testSeekDetachedThrowsRuntimeException() $body = new Body($this->stream); $body->detach(); - $this->setExpectedException('\RuntimeException'); + $this->expectException('\RuntimeException'); $body->seek(10); } @@ -339,7 +327,7 @@ public function testRewindDetachedThrowsRuntimeException() $body = new Body($this->stream); $body->detach(); - $this->setExpectedException('\RuntimeException'); + $this->expectException('\RuntimeException'); $body->rewind(); } @@ -357,7 +345,7 @@ public function testReadDetachedThrowsRuntimeException() $body = new Body($this->stream); $body->detach(); - $this->setExpectedException('\RuntimeException'); + $this->expectException('\RuntimeException'); $body->read(10); } @@ -379,7 +367,7 @@ public function testWriteDetachedThrowsRuntimeException() $body = new Body($this->stream); $body->detach(); - $this->setExpectedException('\RuntimeException'); + $this->expectException('\RuntimeException'); $body->write('foo'); } @@ -398,7 +386,7 @@ public function testGetContentsDetachedThrowsRuntimeException() $body = new Body($this->stream); $body->detach(); - $this->setExpectedException('\RuntimeException'); + $this->expectException('\RuntimeException'); $body->getContents(); } } diff --git a/tests/Http/CookiesTest.php b/tests/Http/CookiesTest.php index 9370b7325..f57000823 100644 --- a/tests/Http/CookiesTest.php +++ b/tests/Http/CookiesTest.php @@ -8,13 +8,13 @@ namespace Slim\Tests\Http; use InvalidArgumentException; -use PHPUnit_Framework_TestCase; +use PHPUnit\Framework\TestCase; use ReflectionClass; use ReflectionProperty; use Slim\Http\Cookies; use stdClass; -class CookiesTest extends PHPUnit_Framework_TestCase +class CookiesTest extends TestCase { public function testConstructor() { @@ -22,7 +22,6 @@ public function testConstructor() 'test' => 'Works', ]); $prop = new ReflectionProperty($cookies, 'requestCookies'); - $prop->setAccessible(true); $this->assertNotEmpty($prop->getValue($cookies)['test']); $this->assertEquals('Works', $prop->getValue($cookies)['test']); } @@ -43,7 +42,6 @@ public function testSetDefaults() $cookies = new Cookies; $prop = new ReflectionProperty($cookies, 'defaults'); - $prop->setAccessible(true); $origDefaults = $prop->getValue($cookies); @@ -59,7 +57,6 @@ public function testSetCookieValues() $cookies->set('foo', 'bar'); $prop = new ReflectionProperty($cookies, 'responseCookies'); - $prop->setAccessible(true); //we expect all of these values with null/false defaults $expectedValue = [ @@ -96,7 +93,6 @@ public function testSetCookieValuesContainDefaults() $cookies->set('foo', 'bar'); $prop = new ReflectionProperty($cookies, 'responseCookies'); - $prop->setAccessible(true); //we expect to have secure, httponly and samesite from defaults $expectedValue = [ @@ -135,7 +131,6 @@ public function testSetCookieValuesCanOverrideDefaults() $cookies->set('foo', ['value' => 'bar', 'secure' => false, 'samesite' => 'strict']); $prop = new ReflectionProperty($cookies, 'responseCookies'); - $prop->setAccessible(true); $expectedValue = [ 'foo' => [ @@ -170,7 +165,6 @@ public function testSetSameSiteCookieValuesAreCaseInsensitive() $cookies->set('breakfast', ['samesite' => 'StricT']); $prop = new ReflectionProperty($cookies, 'responseCookies'); - $prop->setAccessible(true); $expectedValue = [ 'breakfast' => [ @@ -224,7 +218,6 @@ public function testToHeader() $cookies = new Cookies(); $class = new ReflectionClass($cookies); $method = $class->getMethod('toHeader'); - $method->setAccessible(true); $properties = [ 'name' => 'test', 'properties' => [ @@ -269,7 +262,7 @@ public function testToHeader() public function testParseHeaderException() { - $this->setExpectedException(InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); Cookies::parseHeader(new stdClass); } } diff --git a/tests/Http/EnvironmentTest.php b/tests/Http/EnvironmentTest.php index c0d8a54b2..90683000a 100644 --- a/tests/Http/EnvironmentTest.php +++ b/tests/Http/EnvironmentTest.php @@ -7,16 +7,16 @@ namespace Slim\Tests\Http; -use PHPUnit_Framework_TestCase; +use PHPUnit\Framework\TestCase; use Slim\Http\Environment; -class EnvironmentTest extends PHPUnit_Framework_TestCase +class EnvironmentTest extends TestCase { /** * Server settings for the default HTTP request * used by this script's tests. */ - public function setUp() + public function setUp(): void { $_SERVER['DOCUMENT_ROOT'] = '/var/www'; $_SERVER['SCRIPT_NAME'] = '/foo/index.php'; diff --git a/tests/Http/HeadersTest.php b/tests/Http/HeadersTest.php index c64de5b43..823862990 100644 --- a/tests/Http/HeadersTest.php +++ b/tests/Http/HeadersTest.php @@ -7,12 +7,12 @@ namespace Slim\Tests\Http; -use PHPUnit_Framework_TestCase; +use PHPUnit\Framework\TestCase; use ReflectionProperty; use Slim\Http\Environment; use Slim\Http\Headers; -class HeadersTest extends PHPUnit_Framework_TestCase +class HeadersTest extends TestCase { public function testCreateFromEnvironment() { @@ -21,9 +21,8 @@ public function testCreateFromEnvironment() ]); $h = Headers::createFromEnvironment($e); $prop = new ReflectionProperty($h, 'data'); - $prop->setAccessible(true); - $this->assertInternalType('array', $prop->getValue($h)['accept']); + $this->assertIsArray($prop->getValue($h)['accept']); $this->assertEquals('application/json', $prop->getValue($h)['accept']['value'][0]); } @@ -34,9 +33,8 @@ public function testCreateFromEnvironmentWithSpecialHeaders() ]); $h = Headers::createFromEnvironment($e); $prop = new ReflectionProperty($h, 'data'); - $prop->setAccessible(true); - $this->assertInternalType('array', $prop->getValue($h)['content-type']); + $this->assertIsArray($prop->getValue($h)['content-type']); $this->assertEquals('application/json', $prop->getValue($h)['content-type']['value'][0]); } @@ -48,7 +46,6 @@ public function testCreateFromEnvironmentIgnoresHeaders() ]); $h = Headers::createFromEnvironment($e); $prop = new ReflectionProperty($h, 'data'); - $prop->setAccessible(true); $this->assertNotContains('content-length', $prop->getValue($h)); } @@ -59,9 +56,8 @@ public function testConstructor() 'Content-Length' => 100, ]); $prop = new ReflectionProperty($h, 'data'); - $prop->setAccessible(true); - $this->assertInternalType('array', $prop->getValue($h)['content-length']); + $this->assertIsArray($prop->getValue($h)['content-length']); $this->assertEquals(100, $prop->getValue($h)['content-length']['value'][0]); } @@ -70,9 +66,8 @@ public function testSetSingleValue() $h = new Headers(); $h->set('Content-Length', 100); $prop = new ReflectionProperty($h, 'data'); - $prop->setAccessible(true); - $this->assertInternalType('array', $prop->getValue($h)['content-length']); + $this->assertIsArray($prop->getValue($h)['content-length']); $this->assertEquals(100, $prop->getValue($h)['content-length']['value'][0]); } @@ -81,9 +76,8 @@ public function testSetArrayValue() $h = new Headers(); $h->set('Allow', ['GET', 'POST']); $prop = new ReflectionProperty($h, 'data'); - $prop->setAccessible(true); - $this->assertInternalType('array', $prop->getValue($h)['allow']); + $this->assertIsArray($prop->getValue($h)['allow']); $this->assertEquals(['GET', 'POST'], $prop->getValue($h)['allow']['value']); } @@ -91,7 +85,6 @@ public function testGet() { $h = new Headers(); $prop = new ReflectionProperty($h, 'data'); - $prop->setAccessible(true); $prop->setValue($h, [ 'allow' => [ 'value' => ['GET', 'POST'], @@ -127,9 +120,8 @@ public function testAddNewValue() $h = new Headers(); $h->add('Foo', 'Bar'); $prop = new ReflectionProperty($h, 'data'); - $prop->setAccessible(true); - $this->assertInternalType('array', $prop->getValue($h)['foo']); + $this->assertIsArray($prop->getValue($h)['foo']); $this->assertEquals(['Bar'], $prop->getValue($h)['foo']['value']); } @@ -139,9 +131,8 @@ public function testAddAnotherValue() $h->add('Foo', 'Bar'); $h->add('Foo', 'Xyz'); $prop = new ReflectionProperty($h, 'data'); - $prop->setAccessible(true); - $this->assertInternalType('array', $prop->getValue($h)['foo']); + $this->assertIsArray($prop->getValue($h)['foo']); $this->assertEquals(['Bar', 'Xyz'], $prop->getValue($h)['foo']['value']); } @@ -151,9 +142,8 @@ public function testAddArrayValue() $h->add('Foo', 'Bar'); $h->add('Foo', ['Xyz', '123']); $prop = new ReflectionProperty($h, 'data'); - $prop->setAccessible(true); - $this->assertInternalType('array', $prop->getValue($h)['foo']); + $this->assertIsArray($prop->getValue($h)['foo']); $this->assertEquals(['Bar', 'Xyz', '123'], $prop->getValue($h)['foo']['value']); } @@ -161,7 +151,6 @@ public function testHas() { $h = new Headers(); $prop = new ReflectionProperty($h, 'data'); - $prop->setAccessible(true); $prop->setValue($h, [ 'allow' => [ 'value' => ['GET', 'POST'], @@ -176,7 +165,6 @@ public function testRemove() { $h = new Headers(); $prop = new ReflectionProperty($h, 'data'); - $prop->setAccessible(true); $prop->setValue($h, [ 'Allow' => [ 'value' => ['GET', 'POST'], @@ -192,7 +180,6 @@ public function testOriginalKeys() { $h = new Headers(); $prop = new ReflectionProperty($h, 'data'); - $prop->setAccessible(true); $prop->setValue($h, [ 'Allow' => [ 'value' => ['GET', 'POST'], diff --git a/tests/Http/MessageTest.php b/tests/Http/MessageTest.php index 654fecd2a..e6e1fe4de 100644 --- a/tests/Http/MessageTest.php +++ b/tests/Http/MessageTest.php @@ -8,13 +8,13 @@ namespace Slim\Tests\Http; use InvalidArgumentException; -use PHPUnit_Framework_MockObject_MockObject; -use PHPUnit_Framework_TestCase; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; use Slim\Http\Body; use Slim\Http\Headers; use Slim\Tests\Mocks\MessageStub; -class MessageTest extends PHPUnit_Framework_TestCase +class MessageTest extends TestCase { public function testGetProtocolVersion() { @@ -32,11 +32,9 @@ public function testWithProtocolVersion() $this->assertEquals('1.0', $clone->protocolVersion); } - /** - * @expectedException InvalidArgumentException - */ public function testWithProtocolVersionInvalidThrowsException() { + $this->expectException(\InvalidArgumentException::class); $message = new MessageStub(); $message->withProtocolVersion('3.0'); } @@ -169,7 +167,7 @@ public function testWithBody() } /** - * @return PHPUnit_Framework_MockObject_MockObject|Body + * @return PHPUnit\Framework\MockObject\MockObject|Body */ protected function getBody() { diff --git a/tests/Http/NonBufferedBodyTest.php b/tests/Http/NonBufferedBodyTest.php index 537612ac1..02b51d022 100644 --- a/tests/Http/NonBufferedBodyTest.php +++ b/tests/Http/NonBufferedBodyTest.php @@ -7,19 +7,19 @@ namespace Slim\Tests\Http; -use PHPUnit_Framework_TestCase; +use PHPUnit\Framework\TestCase; use Slim\Http\NonBufferedBody; use Slim\Http\Response; use Slim\Tests\Assets\HeaderStack; -class NonBufferedBodyTest extends PHPUnit_Framework_TestCase +class NonBufferedBodyTest extends TestCase { - protected function setUp() + protected function setUp(): void { HeaderStack::reset(); } - protected function tearDown() + protected function tearDown(): void { HeaderStack::reset(); } diff --git a/tests/Http/RequestBodyTest.php b/tests/Http/RequestBodyTest.php index 07f3b74e8..a68cfa22a 100644 --- a/tests/Http/RequestBodyTest.php +++ b/tests/Http/RequestBodyTest.php @@ -7,11 +7,11 @@ namespace Slim\Tests\Http; -use PHPUnit_Framework_TestCase; +use PHPUnit\Framework\TestCase; use ReflectionProperty; use Slim\Http\RequestBody; -class RequestBodyTest extends PHPUnit_Framework_TestCase +class RequestBodyTest extends TestCase { /** @var string */ // @codingStandardsIgnoreStart @@ -26,14 +26,14 @@ class RequestBodyTest extends PHPUnit_Framework_TestCase * Sets up the fixture, for example, open a network connection. * This method is called before a test is executed. */ - protected function setUp() + protected function setUp(): void { $this->body = new RequestBody(); $this->body->write($this->text); $this->body->rewind(); } - protected function tearDown() + protected function tearDown(): void { if (is_resource($this->stream) === true) { fclose($this->stream); @@ -62,22 +62,20 @@ public function resourceFactory($mode = 'r+') public function testConstructorAttachesStream() { $bodyStream = new ReflectionProperty($this->body, 'stream'); - $bodyStream->setAccessible(true); - $this->assertInternalType('resource', $bodyStream->getValue($this->body)); + $this->assertIsResource($bodyStream->getValue($this->body)); } public function testConstructorSetsMetadata() { $bodyMetadata = new ReflectionProperty($this->body, 'meta'); - $bodyMetadata->setAccessible(true); - $this->assertInternalType('array', $bodyMetadata->getValue($this->body)); + $this->assertIsArray($bodyMetadata->getValue($this->body)); } public function testGetMetadata() { - $this->assertInternalType('array', $this->body->getMetadata()); + $this->assertIsArray($this->body->getMetadata()); } public function testGetMetadataKey() @@ -93,23 +91,18 @@ public function testGetMetadataKeyNotFound() public function testDetach() { $bodyStream = new ReflectionProperty($this->body, 'stream'); - $bodyStream->setAccessible(true); $bodyMetadata = new ReflectionProperty($this->body, 'meta'); - $bodyMetadata->setAccessible(true); $bodyReadable = new ReflectionProperty($this->body, 'readable'); - $bodyReadable->setAccessible(true); $bodyWritable = new ReflectionProperty($this->body, 'writable'); - $bodyWritable->setAccessible(true); $bodySeekable = new ReflectionProperty($this->body, 'seekable'); - $bodySeekable->setAccessible(true); $result = $this->body->detach(); - $this->assertInternalType('resource', $result); + $this->assertIsResource($result); $this->assertNull($bodyStream->getValue($this->body)); $this->assertNull($bodyMetadata->getValue($this->body)); $this->assertNull($bodyReadable->getValue($this->body)); @@ -132,7 +125,6 @@ public function testToStringAttachedRewindsFirst() public function testToStringDetached() { $bodyStream = new ReflectionProperty($this->body, 'stream'); - $bodyStream->setAccessible(true); $bodyStream->setValue($this->body, null); $this->assertEquals('', (string)$this->body); @@ -142,12 +134,11 @@ public function testClose() { $this->body->close(); - $this->assertAttributeEquals(null, 'stream', $this->body); $this->assertFalse($this->body->isReadable()); $this->assertFalse($this->body->isWritable()); $this->assertEquals('', (string)$this->body); - $this->setExpectedException('RuntimeException'); + $this->expectException('RuntimeException'); $this->body->tell(); } @@ -159,7 +150,6 @@ public function testGetSizeAttached() public function testGetSizeDetached() { $bodyStream = new ReflectionProperty($this->body, 'stream'); - $bodyStream->setAccessible(true); $bodyStream->setValue($this->body, null); $this->assertNull($this->body->getSize()); @@ -175,10 +165,9 @@ public function testTellAttached() public function testTellDetachedThrowsRuntimeException() { $bodyStream = new ReflectionProperty($this->body, 'stream'); - $bodyStream->setAccessible(true); $bodyStream->setValue($this->body, null); - $this->setExpectedException('\RuntimeException'); + $this->expectException('\RuntimeException'); $this->body->tell(); } @@ -201,7 +190,6 @@ public function testEofAttachedTrue() public function testEofDetached() { $bodyStream = new ReflectionProperty($this->body, 'stream'); - $bodyStream->setAccessible(true); $bodyStream->setValue($this->body, null); $this->assertTrue($this->body->eof()); @@ -256,7 +244,7 @@ public function testSeekDetachedThrowsRuntimeException() { $this->body->detach(); - $this->setExpectedException('\RuntimeException'); + $this->expectException('\RuntimeException'); $this->body->seek(10); } @@ -272,7 +260,7 @@ public function testRewindDetachedThrowsRuntimeException() { $this->body->detach(); - $this->setExpectedException('\RuntimeException'); + $this->expectException('\RuntimeException'); $this->body->rewind(); } @@ -285,7 +273,7 @@ public function testReadDetachedThrowsRuntimeException() { $this->body->detach(); - $this->setExpectedException('\RuntimeException'); + $this->expectException('\RuntimeException'); $this->body->read(10); } @@ -303,7 +291,7 @@ public function testWriteDetachedThrowsRuntimeException() { $this->body->detach(); - $this->setExpectedException('\RuntimeException'); + $this->expectException('\RuntimeException'); $this->body->write('foo'); } @@ -318,7 +306,7 @@ public function testGetContentsDetachedThrowsRuntimeException() { $this->body->detach(); - $this->setExpectedException('\RuntimeException'); + $this->expectException('\RuntimeException'); $this->body->getContents(); } } diff --git a/tests/Http/RequestTest.php b/tests/Http/RequestTest.php index 2ec742954..b460194f3 100644 --- a/tests/Http/RequestTest.php +++ b/tests/Http/RequestTest.php @@ -8,9 +8,7 @@ namespace Slim\Tests\Http; use InvalidArgumentException; -use PHPUnit_Framework_TestCase; -use Prophecy\Argument; -use Prophecy\Prophecy\MethodProphecy; +use PHPUnit\Framework\TestCase; use Psr\Http\Message\UriInterface; use ReflectionProperty; use RuntimeException; @@ -22,7 +20,7 @@ use Slim\Http\UploadedFile; use Slim\Http\Uri; -class RequestTest extends PHPUnit_Framework_TestCase +class RequestTest extends TestCase { public function requestFactory($envData = []) { @@ -141,23 +139,21 @@ public function testWithMethod() { $request = $this->requestFactory()->withMethod('PUT'); - $this->assertAttributeEquals('PUT', 'method', $request); - $this->assertAttributeEquals('PUT', 'originalMethod', $request); + $this->assertSame('PUT', $request->getMethod()); + $this->assertSame('PUT', $request->getOriginalMethod()); } public function testWithAllAllowedCharactersMethod() { $request = $this->requestFactory()->withMethod("!#$%&'*+.^_`|~09AZ-"); - $this->assertAttributeEquals("!#$%&'*+.^_`|~09AZ-", 'method', $request); - $this->assertAttributeEquals("!#$%&'*+.^_`|~09AZ-", 'originalMethod', $request); + $this->assertSame("!#$%&'*+.^_`|~09AZ-", $request->getMethod()); + $this->assertSame("!#$%&'*+.^_`|~09AZ-", $request->getOriginalMethod()); } - /** - * @expectedException InvalidArgumentException - */ public function testWithMethodInvalid() { + $this->expectException(\InvalidArgumentException::class); $this->requestFactory()->withMethod('B@R'); } @@ -165,7 +161,7 @@ public function testWithMethodNull() { $request = $this->requestFactory()->withMethod(null); - $this->assertAttributeEquals(null, 'originalMethod', $request); + $this->assertNull($request->getOriginalMethod()); } public function testCreateFromEnvironment() @@ -288,11 +284,9 @@ public function testGetMethodOverrideParameterFromBodyArray() $this->assertEquals('PUT', $request->getMethod()); } - /** - * @expectedException InvalidArgumentException - */ public function testCreateRequestWithInvalidMethodString() { + $this->expectException(\InvalidArgumentException::class); $uri = Uri::createFromString('https://example.com:443/foo/bar?abc=123'); $headers = new Headers(); $cookies = []; @@ -301,11 +295,9 @@ public function testCreateRequestWithInvalidMethodString() $request = new Request('B@R', $uri, $headers, $cookies, $serverParams, $body); } - /** - * @expectedException InvalidArgumentException - */ public function testCreateRequestWithInvalidMethodOther() { + $this->expectException(\InvalidArgumentException::class); $uri = Uri::createFromString('https://example.com:443/foo/bar?abc=123'); $headers = new Headers(); $cookies = []; @@ -318,7 +310,6 @@ public function testIsGet() { $request = $this->requestFactory(); $prop = new ReflectionProperty($request, 'originalMethod'); - $prop->setAccessible(true); $prop->setValue($request, 'GET'); $this->assertTrue($request->isGet()); @@ -328,7 +319,6 @@ public function testIsPost() { $request = $this->requestFactory(); $prop = new ReflectionProperty($request, 'originalMethod'); - $prop->setAccessible(true); $prop->setValue($request, 'POST'); $this->assertTrue($request->isPost()); @@ -338,7 +328,6 @@ public function testIsPut() { $request = $this->requestFactory(); $prop = new ReflectionProperty($request, 'originalMethod'); - $prop->setAccessible(true); $prop->setValue($request, 'PUT'); $this->assertTrue($request->isPut()); @@ -348,7 +337,6 @@ public function testIsPatch() { $request = $this->requestFactory(); $prop = new ReflectionProperty($request, 'originalMethod'); - $prop->setAccessible(true); $prop->setValue($request, 'PATCH'); $this->assertTrue($request->isPatch()); @@ -358,7 +346,6 @@ public function testIsDelete() { $request = $this->requestFactory(); $prop = new ReflectionProperty($request, 'originalMethod'); - $prop->setAccessible(true); $prop->setValue($request, 'DELETE'); $this->assertTrue($request->isDelete()); @@ -368,7 +355,6 @@ public function testIsHead() { $request = $this->requestFactory(); $prop = new ReflectionProperty($request, 'originalMethod'); - $prop->setAccessible(true); $prop->setValue($request, 'HEAD'); $this->assertTrue($request->isHead()); @@ -378,7 +364,6 @@ public function testIsOptions() { $request = $this->requestFactory(); $prop = new ReflectionProperty($request, 'originalMethod'); - $prop->setAccessible(true); $prop->setValue($request, 'OPTIONS'); $this->assertTrue($request->isOptions()); @@ -408,7 +393,6 @@ public function testGetRequestTargetAlreadySet() { $request = $this->requestFactory(); $prop = new ReflectionProperty($request, 'requestTarget'); - $prop->setAccessible(true); $prop->setValue($request, '/foo/bar?abc=123'); $this->assertEquals('/foo/bar?abc=123', $request->getRequestTarget()); @@ -418,7 +402,6 @@ public function testGetRequestTargetIfNoUri() { $request = $this->requestFactory(); $prop = new ReflectionProperty($request, 'uri'); - $prop->setAccessible(true); $prop->setValue($request, null); $this->assertEquals('/', $request->getRequestTarget()); @@ -430,18 +413,17 @@ public function testGetRequestTargetWithSlimPsr7Uri() $path = 'foo'; $query = 'bar=1'; - $uriProphecy = $this->prophesize(Uri::class); - $uriGetBasePathProphecy = new MethodProphecy($uriProphecy, 'getBasePath', [Argument::any()]); - $uriGetBasePathProphecy->willReturn($basePath)->shouldBeCalledOnce(); - $uriGetPathProphecy = new MethodProphecy($uriProphecy, 'getPath', [Argument::any()]); - $uriGetPathProphecy->willReturn($path); - $uriGetQueryProphecy = new MethodProphecy($uriProphecy, 'getQuery', [Argument::any()]); - $uriGetQueryProphecy->willReturn($query); + $uri = $this->getMockBuilder(Uri::class) + ->disableOriginalConstructor() + ->onlyMethods(['getBasePath', 'getPath', 'getQuery']) + ->getMock(); + $uri->expects($this->once())->method('getBasePath')->willReturn($basePath); + $uri->method('getPath')->willReturn($path); + $uri->method('getQuery')->willReturn($query); $request = $this->requestFactory(); $prop = new ReflectionProperty($request, 'uri'); - $prop->setAccessible(true); - $prop->setValue($request, $uriProphecy->reveal()); + $prop->setValue($request, $uri); $this->assertEquals($basePath . '/' . $path . '?' . $query, $request->getRequestTarget()); } @@ -449,12 +431,11 @@ public function testGetRequestTargetWithSlimPsr7Uri() public function testGetRequestTargetWithNonSlimPsr7Uri() { // We still pass in a UriInterface, which isn't an instance of Slim URI - $uriProphecy = $this->prophesize(UriInterface::class); + $uri = $this->getMockBuilder(UriInterface::class)->getMock(); $request = $this->requestFactory(); $prop = new ReflectionProperty($request, 'uri'); - $prop->setAccessible(true); - $prop->setValue($request, $uriProphecy->reveal()); + $prop->setValue($request, $uri); $this->assertEquals('/', $request->getRequestTarget()); } @@ -463,14 +444,12 @@ public function testWithRequestTarget() { $clone = $this->requestFactory()->withRequestTarget('/test?user=1'); - $this->assertAttributeEquals('/test?user=1', 'requestTarget', $clone); + $this->assertSame('/test?user=1', $clone->getRequestTarget()); } - /** - * @expectedException InvalidArgumentException - */ public function testWithRequestTargetThatHasSpaces() { + $this->expectException(\InvalidArgumentException::class); $this->requestFactory()->withRequestTarget('/test/m ore/stuff?user=1'); } @@ -500,7 +479,7 @@ public function testWithUri() $request = new Request('GET', $uri1, $headers, $cookies, $serverParams, $body); $clone = $request->withUri($uri2); - $this->assertAttributeSame($uri2, 'uri', $clone); + $this->assertSame($uri2, $clone->getUri()); } public function testWithUriPreservesHost() @@ -546,7 +525,6 @@ public function testGetContentType() ]); $request = $this->requestFactory(); $headersProp = new ReflectionProperty($request, 'headers'); - $headersProp->setAccessible(true); $headersProp->setValue($request, $headers); $this->assertEquals('application/json;charset=utf8', $request->getContentType()); @@ -566,7 +544,6 @@ public function testGetMediaType() ]); $request = $this->requestFactory(); $headersProp = new ReflectionProperty($request, 'headers'); - $headersProp->setAccessible(true); $headersProp->setValue($request, $headers); $this->assertEquals('application/json', $request->getMediaType()); @@ -586,7 +563,6 @@ public function testGetMediaTypeParams() ]); $request = $this->requestFactory(); $headersProp = new ReflectionProperty($request, 'headers'); - $headersProp->setAccessible(true); $headersProp->setValue($request, $headers); $this->assertEquals(['charset' => 'utf8', 'foo' => 'bar'], $request->getMediaTypeParams()); @@ -599,7 +575,6 @@ public function testGetMediaTypeParamsEmpty() ]); $request = $this->requestFactory(); $headersProp = new ReflectionProperty($request, 'headers'); - $headersProp->setAccessible(true); $headersProp->setValue($request, $headers); $this->assertEquals([], $request->getMediaTypeParams()); @@ -619,7 +594,6 @@ public function testGetContentCharset() ]); $request = $this->requestFactory(); $headersProp = new ReflectionProperty($request, 'headers'); - $headersProp->setAccessible(true); $headersProp->setValue($request, $headers); $this->assertEquals('utf8', $request->getContentCharset()); @@ -632,7 +606,6 @@ public function testGetContentCharsetEmpty() ]); $request = $this->requestFactory(); $headersProp = new ReflectionProperty($request, 'headers'); - $headersProp->setAccessible(true); $headersProp->setValue($request, $headers); $this->assertNull($request->getContentCharset()); @@ -652,7 +625,6 @@ public function testGetContentLength() ]); $request = $this->requestFactory(); $headersProp = new ReflectionProperty($request, 'headers'); - $headersProp->setAccessible(true); $headersProp->setValue($request, $headers); $this->assertEquals(150, $request->getContentLength()); @@ -706,7 +678,6 @@ public function testGetQueryParamsAlreadySet() { $request = $this->requestFactory(); $prop = new ReflectionProperty($request, 'queryParams'); - $prop->setAccessible(true); $prop->setValue($request, ['foo' => 'bar']); $this->assertEquals(['foo' => 'bar'], $request->getQueryParams()); @@ -736,7 +707,6 @@ public function testGetQueryParamsWithoutUri() { $request = $this->requestFactory(); $prop = new ReflectionProperty($request, 'uri'); - $prop->setAccessible(true); $prop->setValue($request, null); $this->assertEquals([], $request->getQueryParams()); @@ -795,7 +765,6 @@ public function testGetAttributes() { $request = $this->requestFactory(); $attrProp = new ReflectionProperty($request, 'attributes'); - $attrProp->setAccessible(true); $attrProp->setValue($request, new Collection(['foo' => 'bar'])); $this->assertEquals(['foo' => 'bar'], $request->getAttributes()); @@ -805,7 +774,6 @@ public function testGetAttribute() { $request = $this->requestFactory(); $attrProp = new ReflectionProperty($request, 'attributes'); - $attrProp->setAccessible(true); $attrProp->setValue($request, new Collection(['foo' => 'bar'])); $this->assertEquals('bar', $request->getAttribute('foo')); @@ -817,7 +785,6 @@ public function testWithAttribute() { $request = $this->requestFactory(); $attrProp = new ReflectionProperty($request, 'attributes'); - $attrProp->setAccessible(true); $attrProp->setValue($request, new Collection(['foo' => 'bar'])); $clone = $request->withAttribute('test', '123'); @@ -828,7 +795,6 @@ public function testWithAttributes() { $request = $this->requestFactory(); $attrProp = new ReflectionProperty($request, 'attributes'); - $attrProp->setAccessible(true); $attrProp->setValue($request, new Collection(['foo' => 'bar'])); $clone = $request->withAttributes(['test' => '123']); @@ -840,7 +806,6 @@ public function testWithoutAttribute() { $request = $this->requestFactory(); $attrProp = new ReflectionProperty($request, 'attributes'); - $attrProp->setAccessible(true); $attrProp->setValue($request, new Collection(['foo' => 'bar'])); $clone = $request->withoutAttribute('foo'); @@ -1025,7 +990,6 @@ public function testGetParsedBodyWhenAlreadyParsed() { $request = $this->requestFactory(); $prop = new ReflectionProperty($request, 'bodyParsed'); - $prop->setAccessible(true); $prop->setValue($request, ['foo' => 'bar']); $this->assertEquals(['foo' => 'bar'], $request->getParsedBody()); @@ -1035,7 +999,6 @@ public function testGetParsedBodyWhenBodyDoesNotExist() { $request = $this->requestFactory(); $prop = new ReflectionProperty($request, 'body'); - $prop->setAccessible(true); $prop->setValue($request, null); $this->assertNull($request->getParsedBody()); @@ -1065,11 +1028,9 @@ public function testGetParsedBodyAfterCallReparseBody() $this->assertEquals(['abc' => '123'], $request->getParsedBody()); } - /** - * @expectedException RuntimeException - */ public function testGetParsedBodyAsArray() { + $this->expectException(\RuntimeException::class); $uri = Uri::createFromString('https://example.com:443/foo/bar?abc=123'); $headers = new Headers([ 'Content-Type' => 'application/json;charset=utf8', @@ -1147,19 +1108,15 @@ public function testGetParsedBodyReturnsNullWhenThereIsNoMediaTypeParserRegister $this->assertNull($request->getParsedBody()); } - /** - * @expectedException InvalidArgumentException - */ public function testWithParsedBodyInvalid() { + $this->expectException(\InvalidArgumentException::class); $this->requestFactory()->withParsedBody(2); } - /** - * @expectedException InvalidArgumentException - */ public function testWithParsedBodyInvalidFalseValue() { + $this->expectException(\InvalidArgumentException::class); $this->requestFactory()->withParsedBody(false); } diff --git a/tests/Http/ResponseTest.php b/tests/Http/ResponseTest.php index faaaa3bfe..dae4ac1d4 100755 --- a/tests/Http/ResponseTest.php +++ b/tests/Http/ResponseTest.php @@ -8,22 +8,23 @@ namespace Slim\Tests\Http; use InvalidArgumentException; -use PHPUnit_Framework_TestCase; +use PHPUnit\Framework\TestCase; +use Psr\Http\Message\StreamInterface; use ReflectionProperty; use RuntimeException; use Slim\Http\Body; use Slim\Http\Headers; use Slim\Http\Response; -class ResponseTest extends PHPUnit_Framework_TestCase +class ResponseTest extends TestCase { public function testConstructorWithDefaultArgs() { $response = new Response(); - $this->assertAttributeEquals(200, 'status', $response); - $this->assertAttributeInstanceOf('\Slim\Http\Headers', 'headers', $response); - $this->assertAttributeInstanceOf('\Psr\Http\Message\StreamInterface', 'body', $response); + $this->assertSame(200, $response->getStatusCode()); + $this->assertInstanceOf(Headers::class, $this->readPrivateProperty($response, 'headers')); + $this->assertInstanceOf(StreamInterface::class, $response->getBody()); } public function testConstructorWithCustomArgs() @@ -32,9 +33,9 @@ public function testConstructorWithCustomArgs() $body = new Body(fopen('php://temp', 'r+')); $response = new Response(404, $headers, $body); - $this->assertAttributeEquals(404, 'status', $response); - $this->assertAttributeSame($headers, 'headers', $response); - $this->assertAttributeSame($body, 'body', $response); + $this->assertSame(404, $response->getStatusCode()); + $this->assertSame($headers, $this->readPrivateProperty($response, 'headers')); + $this->assertSame($body, $response->getBody()); } public function testDeepCopyClone() @@ -44,10 +45,16 @@ public function testDeepCopyClone() $response = new Response(404, $headers, $body); $clone = clone $response; - $this->assertAttributeEquals('1.1', 'protocolVersion', $clone); - $this->assertAttributeEquals(404, 'status', $clone); - $this->assertAttributeNotSame($headers, 'headers', $clone); - $this->assertAttributeSame($body, 'body', $clone); + $this->assertSame('1.1', $clone->getProtocolVersion()); + $this->assertSame(404, $clone->getStatusCode()); + $this->assertNotSame($headers, $this->readPrivateProperty($clone, 'headers')); + $this->assertSame($body, $clone->getBody()); + } + + private function readPrivateProperty($object, string $name) + { + $ref = new ReflectionProperty($object, $name); + return $ref->getValue($object); } public function testDisableSetter() @@ -62,7 +69,6 @@ public function testGetStatusCode() { $response = new Response(); $responseStatus = new ReflectionProperty($response, 'status'); - $responseStatus->setAccessible(true); $responseStatus->setValue($response, '404'); $this->assertEquals(404, $response->getStatusCode()); @@ -73,24 +79,20 @@ public function testWithStatus() $response = new Response(); $clone = $response->withStatus(302); - $this->assertAttributeEquals(302, 'status', $clone); + $this->assertSame(302, $clone->getStatusCode()); } - /** - * @expectedException InvalidArgumentException - */ public function testWithStatusInvalidStatusCodeThrowsException() { + $this->expectException(\InvalidArgumentException::class); $response = new Response(); $response->withStatus(800); } - /** - * @expectedException InvalidArgumentException - * @expectedExceptionMessage ReasonPhrase must be a string - */ public function testWithStatusInvalidReasonPhraseThrowsException() { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('ReasonPhrase must be a string'); $response = new Response(); $response->withStatus(200, null); } @@ -109,12 +111,10 @@ public function testGetReasonPhrase() $this->assertEquals('Not Found', $response->getReasonPhrase()); } - /** - * @expectedException InvalidArgumentException - * @expectedExceptionMessage ReasonPhrase must be supplied for this code - */ public function testMustSetReasonPhraseForUnrecognisedCode() { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('ReasonPhrase must be supplied for this code'); $response = new Response(); $response = $response->withStatus(199); } @@ -162,7 +162,6 @@ public function testIsEmpty() { $response = new Response(); $prop = new ReflectionProperty($response, 'status'); - $prop->setAccessible(true); $prop->setValue($response, 204); $this->assertTrue($response->isEmpty()); @@ -172,7 +171,6 @@ public function testIsInformational() { $response = new Response(); $prop = new ReflectionProperty($response, 'status'); - $prop->setAccessible(true); $prop->setValue($response, 100); $this->assertTrue($response->isInformational()); @@ -182,7 +180,6 @@ public function testIsOk() { $response = new Response(); $prop = new ReflectionProperty($response, 'status'); - $prop->setAccessible(true); $prop->setValue($response, 200); $this->assertTrue($response->isOk()); @@ -192,7 +189,6 @@ public function testIsSuccessful() { $response = new Response(); $prop = new ReflectionProperty($response, 'status'); - $prop->setAccessible(true); $prop->setValue($response, 201); $this->assertTrue($response->isSuccessful()); @@ -202,7 +198,6 @@ public function testIsRedirect() { $response = new Response(); $prop = new ReflectionProperty($response, 'status'); - $prop->setAccessible(true); $prop->setValue($response, 302); $this->assertTrue($response->isRedirect()); @@ -212,7 +207,6 @@ public function testIsRedirection() { $response = new Response(); $prop = new ReflectionProperty($response, 'status'); - $prop->setAccessible(true); $prop->setValue($response, 308); $this->assertTrue($response->isRedirection()); @@ -222,7 +216,6 @@ public function testIsForbidden() { $response = new Response(); $prop = new ReflectionProperty($response, 'status'); - $prop->setAccessible(true); $prop->setValue($response, 403); $this->assertTrue($response->isForbidden()); @@ -232,7 +225,6 @@ public function testIsNotFound() { $response = new Response(); $prop = new ReflectionProperty($response, 'status'); - $prop->setAccessible(true); $prop->setValue($response, 404); $this->assertTrue($response->isNotFound()); @@ -242,7 +234,6 @@ public function testIsBadRequest() { $response = new Response(); $prop = new ReflectionProperty($response, 'status'); - $prop->setAccessible(true); $prop->setValue($response, 400); $this->assertTrue($response->isBadRequest()); @@ -252,7 +243,6 @@ public function testIsClientError() { $response = new Response(); $prop = new ReflectionProperty($response, 'status'); - $prop->setAccessible(true); $prop->setValue($response, 400); $this->assertTrue($response->isClientError()); @@ -262,7 +252,6 @@ public function testIsServerError() { $response = new Response(); $prop = new ReflectionProperty($response, 'status'); - $prop->setAccessible(true); $prop->setValue($response, 503); $this->assertTrue($response->isServerError()); @@ -319,11 +308,9 @@ public function testWithJson() $this->assertEquals($response->getStatusCode(), 201); } - /** - * @expectedException RuntimeException - */ public function testWithInvalidJsonThrowsException() { + $this->expectException(\RuntimeException::class); $data = ['foo' => 'bar'.chr(233)]; $this->assertEquals('bar'.chr(233), $data['foo']); diff --git a/tests/Http/StreamTest.php b/tests/Http/StreamTest.php index 1c5bbbe61..3d07884b3 100644 --- a/tests/Http/StreamTest.php +++ b/tests/Http/StreamTest.php @@ -7,11 +7,13 @@ namespace Slim\Tests\Http; -use PHPUnit_Framework_TestCase; +use PHPUnit\Framework\TestCase; +use ReflectionMethod; +use ReflectionProperty; use RuntimeException; use Slim\Http\Stream; -class StreamTest extends PHPUnit_Framework_TestCase +class StreamTest extends TestCase { /** * @var resource pipe stream file handle @@ -23,7 +25,7 @@ class StreamTest extends PHPUnit_Framework_TestCase */ private $pipeStream; - public function tearDown() + public function tearDown(): void { if ($this->pipeFh != null) { stream_get_contents($this->pipeFh); // prevent broken pipe error message @@ -58,31 +60,25 @@ public function testPipeIsNotSeekable() $this->assertFalse($this->pipeStream->isSeekable()); } - /** - * @expectedException RuntimeException - */ public function testCannotSeekPipe() { + $this->expectException(\RuntimeException::class); $this->openPipeStream(); $this->pipeStream->seek(0); } - /** - * @expectedException RuntimeException - */ public function testCannotTellPipe() { + $this->expectException(\RuntimeException::class); $this->openPipeStream(); $this->pipeStream->tell(); } - /** - * @expectedException RuntimeException - */ public function testCannotRewindPipe() { + $this->expectException(\RuntimeException::class); $this->openPipeStream(); $this->pipeStream->rewind(); @@ -121,6 +117,22 @@ public function testPipeGetContents() $this->assertSame('12', $contents); } + public function testAttachDetachesPreviouslyAttachedStream() + { + $firstFh = fopen('php://temp', 'r+'); + $stream = new Stream($firstFh); + + $secondFh = fopen('php://temp', 'r+'); + $attach = new ReflectionMethod(Stream::class, 'attach'); + $attach->invoke($stream, $secondFh); + + $prop = new ReflectionProperty($stream, 'stream'); + $this->assertSame($secondFh, $prop->getValue($stream)); + + fclose($firstFh); + fclose($secondFh); + } + /** * Opens the pipe stream * diff --git a/tests/Http/UploadedFilesTest.php b/tests/Http/UploadedFilesTest.php index 71246d1e7..42db7d21e 100644 --- a/tests/Http/UploadedFilesTest.php +++ b/tests/Http/UploadedFilesTest.php @@ -7,7 +7,7 @@ namespace Slim\Tests\Http; -use PHPUnit_Framework_TestCase; +use PHPUnit\Framework\TestCase; use RuntimeException; use Slim\Http\Environment; use Slim\Http\Headers; @@ -17,20 +17,20 @@ use Slim\Http\UploadedFile; use Slim\Http\Uri; -class UploadedFilesTest extends PHPUnit_Framework_TestCase +class UploadedFilesTest extends TestCase { - static private $filename = './phpUxcOty'; + private static $filename = './phpUxcOty'; - static private $tmpFiles = ['./phpUxcOty']; + private static $tmpFiles = ['./phpUxcOty']; - public static function setUpBeforeClass() + public static function setUpBeforeClass(): void { $fh = fopen(self::$filename, "w"); fwrite($fh, "12345678"); fclose($fh); } - public static function tearDownAfterClass() + public static function tearDownAfterClass(): void { foreach (self::$tmpFiles as $filename) { if (file_exists($filename)) { @@ -147,7 +147,7 @@ public function testMoveToNotWritable(UploadedFile $uploadedFile) { $tempName = uniqid('file-'); $path = 'some_random_dir' . DIRECTORY_SEPARATOR . $tempName; - $this->setExpectedException('\InvalidArgumentException'); + $this->expectException('\InvalidArgumentException'); $uploadedFile->moveTo($path); } @@ -175,18 +175,13 @@ public function testMoveTo(UploadedFile $uploadedFile) * @depends testMoveTo * * @param UploadedFile $uploadedFile - * - * @expectedException RuntimeException */ public function testMoveToCannotBeDoneTwice(UploadedFile $uploadedFile) { + $this->expectException(\RuntimeException::class); $tempName = uniqid('file-'); $path = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $tempName; $uploadedFile->moveTo($path); - $this->assertFileExists($path); - unlink($path); - - $uploadedFile->moveTo($path); } /** @@ -198,7 +193,7 @@ public function testMoveToCannotBeDoneTwice(UploadedFile $uploadedFile) */ public function testMoveToAgain(UploadedFile $uploadedFile) { - $this->setExpectedException('\RuntimeException'); + $this->expectException('\RuntimeException'); $tempName = uniqid('file-'); $path = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $tempName; @@ -214,7 +209,7 @@ public function testMoveToAgain(UploadedFile $uploadedFile) */ public function testMovedStream($uploadedFile) { - $this->setExpectedException('\RuntimeException'); + $this->expectException('\RuntimeException'); $uploadedFile->getStream(); } @@ -229,10 +224,10 @@ public function testMoveToStream() $movedFileContents = ob_get_clean(); $this->assertEquals($contents, $movedFileContents); - $this->assertFileNotExists($uploadedFile->file); + $this->assertFileDoesNotExist($uploadedFile->file); } - public function providerCreateFromEnvironment() + public static function providerCreateFromEnvironment() { return [ // no nest: diff --git a/tests/Http/UriTest.php b/tests/Http/UriTest.php index c8dd09082..0ddf3ffe7 100644 --- a/tests/Http/UriTest.php +++ b/tests/Http/UriTest.php @@ -8,11 +8,11 @@ namespace Slim\Tests\Http; use InvalidArgumentException; -use PHPUnit_Framework_TestCase; +use PHPUnit\Framework\TestCase; use Slim\Http\Environment; use Slim\Http\Uri; -class UriTest extends PHPUnit_Framework_TestCase +class UriTest extends TestCase { protected $uri; @@ -39,38 +39,34 @@ public function testWithScheme() { $uri = $this->uriFactory()->withScheme('http'); - $this->assertAttributeEquals('http', 'scheme', $uri); + $this->assertSame('http', $uri->getScheme()); } public function testWithSchemeRemovesSuffix() { $uri = $this->uriFactory()->withScheme('http://'); - $this->assertAttributeEquals('http', 'scheme', $uri); + $this->assertSame('http', $uri->getScheme()); } public function testWithSchemeEmpty() { $uri = $this->uriFactory()->withScheme(''); - $this->assertAttributeEquals('', 'scheme', $uri); + $this->assertSame('', $uri->getScheme()); } - /** - * @expectedException InvalidArgumentException - * @expectedExceptionMessage Uri scheme must be one of: "", "https", "http" - */ public function testWithSchemeInvalid() { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('Uri scheme must be one of: "", "https", "http"'); $this->uriFactory()->withScheme('ftp'); } - /** - * @expectedException InvalidArgumentException - * @expectedExceptionMessage Uri scheme must be a string - */ public function testWithSchemeInvalidType() { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('Uri scheme must be a string'); $this->uriFactory()->withScheme([]); } @@ -180,24 +176,21 @@ public function testWithUserInfo() { $uri = $this->uriFactory()->withUserInfo('bob', 'pass'); - $this->assertAttributeEquals('bob', 'user', $uri); - $this->assertAttributeEquals('pass', 'password', $uri); + $this->assertSame('bob:pass', $uri->getUserInfo()); } public function testWithUserInfoEncodesCorrectly() { $uri = $this->uriFactory()->withUserInfo('bob@example.com', 'pass:word'); - $this->assertAttributeEquals('bob%40example.com', 'user', $uri); - $this->assertAttributeEquals('pass%3Aword', 'password', $uri); + $this->assertSame('bob%40example.com:pass%3Aword', $uri->getUserInfo()); } public function testWithUserInfoRemovesPassword() { $uri = $this->uriFactory()->withUserInfo('bob'); - $this->assertAttributeEquals('bob', 'user', $uri); - $this->assertAttributeEquals('', 'password', $uri); + $this->assertSame('bob', $uri->getUserInfo()); } public function testWithUserInfoRemovesInfo() @@ -205,8 +198,7 @@ public function testWithUserInfoRemovesInfo() $uri = $this->uriFactory()->withUserInfo('bob', 'password'); $uri = $uri->withUserInfo(''); - $this->assertAttributeEquals('', 'user', $uri); - $this->assertAttributeEquals('', 'password', $uri); + $this->assertSame('', $uri->getUserInfo()); } @@ -219,7 +211,7 @@ public function testWithHost() { $uri = $this->uriFactory()->withHost('slimframework.com'); - $this->assertAttributeEquals('slimframework.com', 'host', $uri); + $this->assertSame('slimframework.com', $uri->getHost()); } public function testGetPortWithSchemeAndNonDefaultPort() @@ -256,29 +248,25 @@ public function testWithPort() { $uri = $this->uriFactory()->withPort(8000); - $this->assertAttributeEquals(8000, 'port', $uri); + $this->assertSame(8000, $uri->getPort()); } public function testWithPortNull() { $uri = $this->uriFactory()->withPort(null); - $this->assertAttributeEquals(null, 'port', $uri); + $this->assertNull($uri->getPort()); } - /** - * @expectedException InvalidArgumentException - */ public function testWithPortInvalidInt() { + $this->expectException(\InvalidArgumentException::class); $this->uriFactory()->withPort(70000); } - /** - * @expectedException InvalidArgumentException - */ public function testWithPortInvalidString() { + $this->expectException(\InvalidArgumentException::class); $this->uriFactory()->withPort('Foo'); } @@ -291,15 +279,13 @@ public function testWithBasePath() { $uri = $this->uriFactory()->withBasePath('/base'); - $this->assertAttributeEquals('/base', 'basePath', $uri); + $this->assertSame('/base', $uri->getBasePath()); } - /** - * @expectedException InvalidArgumentException - * @expectedExceptionMessage Uri path must be a string - */ public function testWithBasePathInvalidType() { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('Uri path must be a string'); $this->uriFactory()->withBasePath(['foo']); } @@ -307,14 +293,14 @@ public function testWithBasePathAddsPrefix() { $uri = $this->uriFactory()->withBasePath('base'); - $this->assertAttributeEquals('/base', 'basePath', $uri); + $this->assertSame('/base', $uri->getBasePath()); } public function testWithBasePathIgnoresSlash() { $uri = $this->uriFactory()->withBasePath('/'); - $this->assertAttributeEquals('', 'basePath', $uri); + $this->assertSame('', $uri->getBasePath()); } public function testGetPath() @@ -326,43 +312,41 @@ public function testWithPath() { $uri = $this->uriFactory()->withPath('/new'); - $this->assertAttributeEquals('/new', 'path', $uri); + $this->assertSame('/new', $uri->getPath()); } public function testWithPathWithoutPrefix() { $uri = $this->uriFactory()->withPath('new'); - $this->assertAttributeEquals('new', 'path', $uri); + $this->assertSame('new', $uri->getPath()); } public function testWithPathEmptyValue() { $uri = $this->uriFactory()->withPath(''); - $this->assertAttributeEquals('', 'path', $uri); + $this->assertSame('', $uri->getPath()); } public function testWithPathUrlEncodesInput() { $uri = $this->uriFactory()->withPath('/includes?/new'); - $this->assertAttributeEquals('/includes%3F/new', 'path', $uri); + $this->assertSame('/includes%3F/new', $uri->getPath()); } public function testWithPathDoesNotDoubleEncodeInput() { $uri = $this->uriFactory()->withPath('/include%25s/new'); - $this->assertAttributeEquals('/include%25s/new', 'path', $uri); + $this->assertSame('/include%25s/new', $uri->getPath()); } - /** - * @expectedException InvalidArgumentException - * @expectedExceptionMessage Uri path must be a string - */ public function testWithPathInvalidType() { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('Uri path must be a string'); $this->uriFactory()->withPath(['foo']); } @@ -375,36 +359,34 @@ public function testWithQuery() { $uri = $this->uriFactory()->withQuery('xyz=123'); - $this->assertAttributeEquals('xyz=123', 'query', $uri); + $this->assertSame('xyz=123', $uri->getQuery()); } public function testWithQueryRemovesPrefix() { $uri = $this->uriFactory()->withQuery('?xyz=123'); - $this->assertAttributeEquals('xyz=123', 'query', $uri); + $this->assertSame('xyz=123', $uri->getQuery()); } public function testWithQueryEmpty() { $uri = $this->uriFactory()->withQuery(''); - $this->assertAttributeEquals('', 'query', $uri); + $this->assertSame('', $uri->getQuery()); } public function testFilterQuery() { $uri = $this->uriFactory()->withQuery('?foobar=%match'); - $this->assertAttributeEquals('foobar=%25match', 'query', $uri); + $this->assertSame('foobar=%25match', $uri->getQuery()); } - /** - * @expectedException InvalidArgumentException - * @expectedExceptionMessage Uri query must be a string - */ public function testWithQueryInvalidType() { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('Uri query must be a string'); $this->uriFactory()->withQuery(['foo']); } @@ -417,29 +399,27 @@ public function testWithFragment() { $uri = $this->uriFactory()->withFragment('other-fragment'); - $this->assertAttributeEquals('other-fragment', 'fragment', $uri); + $this->assertSame('other-fragment', $uri->getFragment()); } public function testWithFragmentRemovesPrefix() { $uri = $this->uriFactory()->withFragment('#other-fragment'); - $this->assertAttributeEquals('other-fragment', 'fragment', $uri); + $this->assertSame('other-fragment', $uri->getFragment()); } public function testWithFragmentEmpty() { $uri = $this->uriFactory()->withFragment(''); - $this->assertAttributeEquals('', 'fragment', $uri); + $this->assertSame('', $uri->getFragment()); } - /** - * @expectedException InvalidArgumentException - * @expectedExceptionMessage Uri fragment must be a string - */ public function testWithFragmentInvalidType() { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('Uri fragment must be a string'); $this->uriFactory()->withFragment(['foo']); } @@ -480,12 +460,10 @@ public function testCreateFromString() $this->assertEquals('abc=123', $uri->getQuery()); } - /** - * @expectedException InvalidArgumentException - * @expectedExceptionMessage Uri must be a string - */ public function testCreateFromStringWithInvalidType() { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('Uri must be a string'); Uri::createFromString(['https://example.com:8080/foo/bar?abc=123']); } diff --git a/tests/MiddlewareAwareTest.php b/tests/MiddlewareAwareTest.php index b206f0fe9..1eff01aec 100644 --- a/tests/MiddlewareAwareTest.php +++ b/tests/MiddlewareAwareTest.php @@ -7,7 +7,7 @@ namespace Slim\Tests; -use PHPUnit_Framework_TestCase; +use PHPUnit\Framework\TestCase; use RuntimeException; use Slim\Http\Body; use Slim\Http\Headers; @@ -16,7 +16,7 @@ use Slim\Http\Uri; use Slim\Tests\Mocks\Stackable; -class MiddlewareAwareTest extends PHPUnit_Framework_TestCase +class MiddlewareAwareTest extends TestCase { public function testSeedsMiddlewareStack() { @@ -101,11 +101,9 @@ public function testMiddlewareStackWithAStatic() $this->assertEquals('In2In1CenterOut1Out2', (string)$res->getBody()); } - /** - * @expectedException RuntimeException - */ public function testMiddlewareBadReturnValue() { + $this->expectException(\RuntimeException::class); // Build middleware stack $stack = new Stackable; $stack->add(function ($req, $res, $next) { @@ -160,7 +158,7 @@ public function testAddMiddlewareWhileStackIsRunningThrowException() }); return $resp; }); - $this->setExpectedException('RuntimeException'); + $this->expectException('RuntimeException'); $stack->callMiddlewareStack( $this->getMockBuilder('Psr\Http\Message\ServerRequestInterface')->disableOriginalConstructor()->getMock(), $this->getMockBuilder('Psr\Http\Message\ResponseInterface')->disableOriginalConstructor()->getMock() @@ -171,7 +169,7 @@ public function testSeedTwiceThrowException() { $stack = new Stackable; $stack->alternativeSeed(); - $this->setExpectedException('RuntimeException'); + $this->expectException('RuntimeException'); $stack->alternativeSeed(); } } diff --git a/tests/Mocks/CallableTest.php b/tests/Mocks/CallableMock.php similarity index 95% rename from tests/Mocks/CallableTest.php rename to tests/Mocks/CallableMock.php index 4c2f94836..f68ca8dc8 100644 --- a/tests/Mocks/CallableTest.php +++ b/tests/Mocks/CallableMock.php @@ -7,7 +7,7 @@ namespace Slim\Tests\Mocks; -class CallableTest +class CallableMock { public static $CalledCount = 0; diff --git a/tests/Mocks/InvocationStrategyTest.php b/tests/Mocks/InvocationStrategyMock.php similarity index 90% rename from tests/Mocks/InvocationStrategyTest.php rename to tests/Mocks/InvocationStrategyMock.php index 8b3949ee2..375704d40 100644 --- a/tests/Mocks/InvocationStrategyTest.php +++ b/tests/Mocks/InvocationStrategyMock.php @@ -11,7 +11,7 @@ use Psr\Http\Message\ServerRequestInterface; use Slim\Interfaces\InvocationStrategyInterface; -class InvocationStrategyTest implements InvocationStrategyInterface +class InvocationStrategyMock implements InvocationStrategyInterface { public static $LastCalledFor = null; diff --git a/tests/Mocks/InvokableTest.php b/tests/Mocks/InvokableMock.php similarity index 93% rename from tests/Mocks/InvokableTest.php rename to tests/Mocks/InvokableMock.php index 3ffc2f502..fa20248e2 100644 --- a/tests/Mocks/InvokableTest.php +++ b/tests/Mocks/InvokableMock.php @@ -7,7 +7,7 @@ namespace Slim\Tests\Mocks; -class InvokableTest +class InvokableMock { public static $CalledCount = 0; diff --git a/tests/RouteTest.php b/tests/RouteTest.php index 5e2527df9..a75eb83fb 100644 --- a/tests/RouteTest.php +++ b/tests/RouteTest.php @@ -8,7 +8,7 @@ namespace Slim\Tests; use Exception; -use PHPUnit_Framework_TestCase; +use PHPUnit\Framework\TestCase; use Slim\Container; use Slim\DeferredCallable; use Slim\Http\Body; @@ -18,11 +18,11 @@ use Slim\Http\Response; use Slim\Http\Uri; use Slim\Route; -use Slim\Tests\Mocks\CallableTest; -use Slim\Tests\Mocks\InvocationStrategyTest; +use Slim\Tests\Mocks\CallableMock; +use Slim\Tests\Mocks\InvocationStrategyMock; use Slim\Tests\Mocks\MiddlewareStub; -class RouteTest extends PHPUnit_Framework_TestCase +class RouteTest extends TestCase { public function routeFactory() { @@ -44,9 +44,9 @@ public function testConstructor() }; $route = new Route($methods, $pattern, $callable); - $this->assertAttributeEquals($methods, 'methods', $route); - $this->assertAttributeEquals($pattern, 'pattern', $route); - $this->assertAttributeEquals($callable, 'callable', $route); + $this->assertEquals($methods, $route->getMethods()); + $this->assertEquals($pattern, $route->getPattern()); + $this->assertEquals($callable, $route->getCallable()); } public function testGetMethodsReturnsArrayWhenContructedWithString() @@ -72,7 +72,7 @@ public function testGetCallable() { $callable = $this->routeFactory()->getCallable(); - $this->assertInternalType('callable', $callable); + $this->assertIsCallable($callable); } public function testArgumentSetting() @@ -176,7 +176,7 @@ public function testSetInvalidName() { $route = $this->routeFactory(); - $this->setExpectedException('InvalidArgumentException'); + $this->expectException('InvalidArgumentException'); $route->setName(false); } @@ -201,7 +201,7 @@ public function testSetInvalidOutputBuffering() { $route = $this->routeFactory(); - $this->setExpectedException('InvalidArgumentException'); + $this->expectException('InvalidArgumentException'); $route->setOutputBuffering('invalid'); } @@ -237,7 +237,7 @@ public function testControllerInContainer() { $container = new Container(); - $container['CallableTest'] = new CallableTest; + $container['CallableTest'] = new CallableMock; $deferred = new DeferredCallable('CallableTest:toCall', $container); @@ -248,12 +248,12 @@ public function testControllerInContainer() $body = new Body(fopen('php://temp', 'r+')); $request = new Request('GET', $uri, new Headers(), [], Environment::mock()->all(), $body); - CallableTest::$CalledCount = 0; + CallableMock::$CalledCount = 0; $result = $route->callMiddlewareStack($request, new Response); $this->assertInstanceOf('Slim\Http\Response', $result); - $this->assertEquals(1, CallableTest::$CalledCount); + $this->assertEquals(1, CallableMock::$CalledCount); } public function testInvokeWhenReturningAResponse() @@ -298,11 +298,9 @@ public function testInvokeWhenReturningAString() $this->assertEquals('foo', (string)$response->getBody()); } - /** - * @expectedException Exception - */ public function testInvokeWithException() { + $this->expectException(\Exception::class); $callable = function ($req, $res, $args) { throw new Exception(); }; @@ -350,9 +348,9 @@ public function testInvokeWhenDisablingOutputBuffer() public function testInvokeDeferredCallable() { $container = new Container(); - $container['CallableTest'] = new CallableTest; + $container['CallableTest'] = new CallableMock; $container['foundHandler'] = function () { - return new InvocationStrategyTest(); + return new InvocationStrategyMock(); }; $route = new Route(['GET'], '/', 'CallableTest:toCall'); @@ -365,7 +363,7 @@ public function testInvokeDeferredCallable() $result = $route->callMiddlewareStack($request, new Response); $this->assertInstanceOf('Slim\Http\Response', $result); - $this->assertEquals([$container['CallableTest'], 'toCall'], InvocationStrategyTest::$LastCalledFor); + $this->assertEquals([$container['CallableTest'], 'toCall'], InvocationStrategyMock::$LastCalledFor); } public function testPatternCanBeChanged() @@ -378,9 +376,9 @@ public function testPatternCanBeChanged() public function testChangingCallable() { $container = new Container(); - $container['CallableTest2'] = new CallableTest; + $container['CallableTest2'] = new CallableMock; $container['foundHandler'] = function () { - return new InvocationStrategyTest(); + return new InvocationStrategyMock(); }; $route = new Route(['GET'], '/', 'CallableTest:toCall'); //Note that this doesn't actually exist @@ -395,6 +393,6 @@ public function testChangingCallable() $result = $route->callMiddlewareStack($request, new Response); $this->assertInstanceOf('Slim\Http\Response', $result); - $this->assertEquals([$container['CallableTest2'], 'toCall'], InvocationStrategyTest::$LastCalledFor); + $this->assertEquals([$container['CallableTest2'], 'toCall'], InvocationStrategyMock::$LastCalledFor); } } diff --git a/tests/RouterTest.php b/tests/RouterTest.php index d825d5cc0..b28f7ebfc 100644 --- a/tests/RouterTest.php +++ b/tests/RouterTest.php @@ -8,13 +8,13 @@ namespace Slim\Tests; use InvalidArgumentException; -use PHPUnit_Framework_TestCase; +use PHPUnit\Framework\TestCase; use ReflectionClass; use RuntimeException; use Slim\Http\Uri; use Slim\Router; -class RouterTest extends PHPUnit_Framework_TestCase +class RouterTest extends TestCase { /** * @var Router @@ -26,14 +26,14 @@ class RouterTest extends PHPUnit_Framework_TestCase */ protected $cacheFile; - public function setUp() + public function setUp(): void { $this->router = new Router; } - public function tearDown() + public function tearDown(): void { - if (file_exists($this->cacheFile)) { + if ($this->cacheFile && file_exists($this->cacheFile)) { unlink($this->cacheFile); } } @@ -48,7 +48,7 @@ public function testMap() $route = $this->router->map($methods, $pattern, $callable); $this->assertInstanceOf('\Slim\Interfaces\RouteInterface', $route); - $this->assertAttributeContains($route, 'routes', $this->router); + $this->assertContains($route, $this->router->getRoutes()); } public function testMapPrependsGroupPattern() @@ -64,15 +64,13 @@ public function testMapPrependsGroupPattern() $route = $this->router->map($methods, $pattern, $callable); $this->router->popGroup(); - $this->assertAttributeEquals('/prefix/hello/{first}/{last}', 'pattern', $route); + $this->assertSame('/prefix/hello/{first}/{last}', $route->getPattern()); } - /** - * @expectedException InvalidArgumentException - * @expectedExceptionMessage Route pattern must be a string - */ public function testMapWithInvalidPatternType() { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('Route pattern must be a string'); $methods = ['GET']; $pattern = ['foo']; $callable = function ($request, $response, $args) { @@ -196,11 +194,9 @@ public function testPathForWithNullQueryParameters() ); } - /** - * @expectedException InvalidArgumentException - */ public function testPathForWithMissingSegmentData() { + $this->expectException(\InvalidArgumentException::class); $methods = ['GET']; $pattern = '/hello/{first}/{last}'; $callable = function ($request, $response, $args) { @@ -212,11 +208,9 @@ public function testPathForWithMissingSegmentData() $this->router->pathFor('foo', ['last' => 'lockhart']); } - /** - * @expectedException RuntimeException - */ public function testPathForRouteNotExists() { + $this->expectException(\RuntimeException::class); $methods = ['GET']; $pattern = '/hello/{first}/{last}'; $callable = function ($request, $response, $args) { @@ -228,11 +222,9 @@ public function testPathForRouteNotExists() $this->router->pathFor('bar', ['first' => 'josh', 'last' => 'lockhart']); } - /** - * @expectedException InvalidArgumentException - */ public function testSettingInvalidBasePath() { + $this->expectException(\InvalidArgumentException::class); $this->router->setBasePath(['invalid']); } @@ -240,7 +232,6 @@ public function testCreateDispatcher() { $class = new ReflectionClass($this->router); $method = $class->getMethod('createDispatcher'); - $method->setAccessible(true); $this->assertInstanceOf('\FastRoute\Dispatcher', $method->invoke($this->router)); } @@ -252,15 +243,12 @@ public function testSetDispatcher() })); $class = new ReflectionClass($this->router); $prop = $class->getProperty('dispatcher'); - $prop->setAccessible(true); $this->assertInstanceOf('\FastRoute\Dispatcher', $prop->getValue($this->router)); } - /** - * @expectedException RuntimeException - */ public function testRemoveRoute() { + $this->expectException(\RuntimeException::class); $methods = ['GET']; $callable = function ($request, $response, $args) { echo sprintf('Hello ignore me'); @@ -312,11 +300,9 @@ public function testRemoveRoute() $this->router->getNamedRoute($routeToRemove->getName()); } - /** - * @expectedException RuntimeException - */ public function testRouteRemovalNotExists() { + $this->expectException(\RuntimeException::class); $this->router->setBasePath('/base/path'); $this->router->removeNamedRoute('non-existing-route-name'); } @@ -347,17 +333,14 @@ public function testSettingCacheFileToFalse() $class = new ReflectionClass($this->router); $property = $class->getProperty('cacheFile'); - $property->setAccessible(true); $this->assertFalse($property->getValue($this->router)); } public function testSettingInvalidCacheFileValue() { - $this->setExpectedException( - '\InvalidArgumentException', - 'Router cache file must be a string' - ); + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('Router cache file must be a string'); $this->router->setCacheFile(['invalid']); } @@ -366,10 +349,8 @@ public function testCacheFileExistsAndIsNotReadable() $this->cacheFile = __DIR__ . '/non-readable.cache'; file_put_contents($this->cacheFile, ''); - $this->setExpectedException( - '\RuntimeException', - sprintf('Router cache file `%s` is not readable', $this->cacheFile) - ); + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage(sprintf('Router cache file `%s` is not readable', $this->cacheFile)); $this->router->setCacheFile($this->cacheFile); } @@ -378,10 +359,8 @@ public function testCacheFileDoesNotExistsAndDirectoryIsNotWritable() { $cacheFile = __DIR__ . '/non-writable-directory/router.cache'; - $this->setExpectedException( - '\RuntimeException', - sprintf('Router cache file directory `%s` is not writable', dirname($cacheFile)) - ); + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage(sprintf('Router cache file directory `%s` is not writable', dirname($cacheFile))); $this->router->setCacheFile($cacheFile); } @@ -399,7 +378,6 @@ public function testRouteCacheFileCanBeDispatched() $this->router->setCacheFile($cacheFile); $class = new ReflectionClass($this->router); $method = $class->getMethod('createDispatcher'); - $method->setAccessible(true); $dispatcher = $method->invoke($this->router); $this->assertInstanceOf('\FastRoute\Dispatcher', $dispatcher); @@ -412,7 +390,6 @@ public function testRouteCacheFileCanBeDispatched() $class = new ReflectionClass($router2); $method = $class->getMethod('createDispatcher'); - $method->setAccessible(true); $dispatcher2 = $method->invoke($this->router); $result = $dispatcher2->dispatch('GET', '/hello/josh/lockhart'); @@ -429,18 +406,15 @@ public function testCreateDispatcherReturnsSameDispatcherASecondTime() { $class = new ReflectionClass($this->router); $method = $class->getMethod('createDispatcher'); - $method->setAccessible(true); $dispatcher = $method->invoke($this->router); $dispatcher2 = $method->invoke($this->router); $this->assertSame($dispatcher2, $dispatcher); } - /** - * @expectedException RuntimeException - */ public function testLookupRouteThrowsExceptionIfRouteNotFound() { + $this->expectException(\RuntimeException::class); $this->router->lookupRoute("thisIsMissing"); }