Upgrade 1-11.38

This commit is contained in:
xesmyd
2026-03-30 14:10:30 +02:00
parent f2a7e6d1fc
commit ac648ef29d
24665 changed files with 69682 additions and 2205004 deletions
+9 -4
View File
@@ -14,10 +14,10 @@ namespace Symfony\Component\HttpKernel\Tests\Bundle;
use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Component\HttpKernel\Tests\Fixtures\ExtensionNotValidBundle\ExtensionNotValidBundle;
use Symfony\Component\HttpKernel\Tests\Fixtures\ExtensionPresentBundle\ExtensionPresentBundle;
use Symfony\Component\HttpKernel\Tests\Fixtures\ExtensionAbsentBundle\ExtensionAbsentBundle;
use Symfony\Component\HttpKernel\Tests\Fixtures\ExtensionNotValidBundle\ExtensionNotValidBundle;
use Symfony\Component\HttpKernel\Tests\Fixtures\ExtensionPresentBundle\Command\FooCommand;
use Symfony\Component\HttpKernel\Tests\Fixtures\ExtensionPresentBundle\ExtensionPresentBundle;
class BundleTest extends TestCase
{
@@ -31,6 +31,10 @@ class BundleTest extends TestCase
);
}
/**
* @group legacy
* @expectedDeprecation Auto-registration of the command "Symfony\Component\HttpKernel\Tests\Fixtures\ExtensionPresentBundle\Command\FooCommand" is deprecated since Symfony 3.4 and won't be supported in 4.0. Use PSR-4 based service discovery instead.
*/
public function testRegisterCommands()
{
$cmd = new FooCommand();
@@ -46,11 +50,12 @@ class BundleTest extends TestCase
}
/**
* @expectedException \LogicException
* @expectedExceptionMessage must implement Symfony\Component\DependencyInjection\Extension\ExtensionInterface
* @group legacy
*/
public function testGetContainerExtensionWithInvalidClass()
{
$this->expectException('LogicException');
$this->expectExceptionMessage('must implement Symfony\Component\DependencyInjection\Extension\ExtensionInterface');
$bundle = new ExtensionNotValidBundle();
$bundle->getContainerExtension();
}
@@ -35,10 +35,13 @@ class ChainCacheClearerTest extends TestCase
->expects($this->once())
->method('clear');
$chainClearer = new ChainCacheClearer(array($clearer));
$chainClearer = new ChainCacheClearer([$clearer]);
$chainClearer->clear(self::$cacheDir);
}
/**
* @group legacy
*/
public function testInjectClearerUsingAdd()
{
$clearer = $this->getMockClearer();
@@ -34,10 +34,13 @@ class CacheWarmerAggregateTest extends TestCase
$warmer
->expects($this->once())
->method('warmUp');
$aggregate = new CacheWarmerAggregate(array($warmer));
$aggregate = new CacheWarmerAggregate([$warmer]);
$aggregate->warmUp(self::$cacheDir);
}
/**
* @group legacy
*/
public function testInjectWarmersUsingAdd()
{
$warmer = $this->getCacheWarmerMock();
@@ -49,6 +52,9 @@ class CacheWarmerAggregateTest extends TestCase
$aggregate->warmUp(self::$cacheDir);
}
/**
* @group legacy
*/
public function testInjectWarmersUsingSetWarmers()
{
$warmer = $this->getCacheWarmerMock();
@@ -56,7 +62,7 @@ class CacheWarmerAggregateTest extends TestCase
->expects($this->once())
->method('warmUp');
$aggregate = new CacheWarmerAggregate();
$aggregate->setWarmers(array($warmer));
$aggregate->setWarmers([$warmer]);
$aggregate->warmUp(self::$cacheDir);
}
@@ -70,7 +76,7 @@ class CacheWarmerAggregateTest extends TestCase
->expects($this->once())
->method('warmUp');
$aggregate = new CacheWarmerAggregate(array($warmer));
$aggregate = new CacheWarmerAggregate([$warmer]);
$aggregate->enableOptionalWarmers();
$aggregate->warmUp(self::$cacheDir);
}
@@ -81,12 +87,12 @@ class CacheWarmerAggregateTest extends TestCase
$warmer
->expects($this->once())
->method('isOptional')
->will($this->returnValue(true));
->willReturn(true);
$warmer
->expects($this->never())
->method('warmUp');
$aggregate = new CacheWarmerAggregate(array($warmer));
$aggregate = new CacheWarmerAggregate([$warmer]);
$aggregate->warmUp(self::$cacheDir);
}
@@ -31,19 +31,17 @@ class CacheWarmerTest extends TestCase
public function testWriteCacheFileCreatesTheFile()
{
$warmer = new TestCacheWarmer(self::$cacheFile);
$warmer->warmUp(dirname(self::$cacheFile));
$warmer->warmUp(\dirname(self::$cacheFile));
$this->assertFileExists(self::$cacheFile);
}
/**
* @expectedException \RuntimeException
*/
public function testWriteNonWritableCacheFileThrowsARuntimeException()
{
$this->expectException('RuntimeException');
$nonWritableFile = '/this/file/is/very/probably/not/writable';
$warmer = new TestCacheWarmer($nonWritableFile);
$warmer->warmUp(dirname($nonWritableFile));
$warmer->warmUp(\dirname($nonWritableFile));
}
}
+28 -54
View File
@@ -12,11 +12,11 @@
namespace Symfony\Component\HttpKernel\Tests;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\Client;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\HttpKernel\Client;
use Symfony\Component\HttpKernel\Tests\Fixtures\TestClient;
/**
@@ -39,8 +39,8 @@ class ClientTest extends TestCase
$this->assertEquals('Request: /', $client->getResponse()->getContent(), '->doRequest() uses the request handler to make the request');
$this->assertEquals('www.example.com', $client->getRequest()->getHost(), '->doRequest() uses the request handler to make the request');
$client->request('GET', 'http://www.example.com/?parameter=http://google.com');
$this->assertEquals('http://www.example.com/?parameter='.urlencode('http://google.com'), $client->getRequest()->getUri(), '->doRequest() uses the request handler to make the request');
$client->request('GET', 'http://www.example.com/?parameter=http://example.com');
$this->assertEquals('http://www.example.com/?parameter='.urlencode('http://example.com'), $client->getRequest()->getUri(), '->doRequest() uses the request handler to make the request');
}
public function testGetScript()
@@ -60,44 +60,17 @@ class ClientTest extends TestCase
$m = $r->getMethod('filterResponse');
$m->setAccessible(true);
$expected31 = array(
'foo=bar; expires=Sun, 15 Feb 2009 20:00:00 GMT; domain=http://example.com; path=/foo; secure; httponly',
'foo1=bar1; expires=Sun, 15 Feb 2009 20:00:00 GMT; domain=http://example.com; path=/foo; secure; httponly',
);
$expected33 = array(
'foo=bar; expires=Sun, 15-Feb-2009 20:00:00 GMT; max-age='.(strtotime('Sun, 15-Feb-2009 20:00:00 GMT') - time()).'; path=/foo; domain=http://example.com; secure; httponly',
'foo1=bar1; expires=Sun, 15-Feb-2009 20:00:00 GMT; max-age='.(strtotime('Sun, 15-Feb-2009 20:00:00 GMT') - time()).'; path=/foo; domain=http://example.com; secure; httponly',
);
$response = new Response();
$response->headers->setCookie($cookie1 = new Cookie('foo', 'bar', \DateTime::createFromFormat('j-M-Y H:i:s T', '15-Feb-2009 20:00:00 GMT')->format('U'), '/foo', 'http://example.com', true, true));
$domResponse = $m->invoke($client, $response);
$this->assertSame((string) $cookie1, $domResponse->getHeader('Set-Cookie'));
$response = new Response();
$response->headers->setCookie(new Cookie('foo', 'bar', \DateTime::createFromFormat('j-M-Y H:i:s T', '15-Feb-2009 20:00:00 GMT')->format('U'), '/foo', 'http://example.com', true, true));
$response->headers->setCookie($cookie1 = new Cookie('foo', 'bar', \DateTime::createFromFormat('j-M-Y H:i:s T', '15-Feb-2009 20:00:00 GMT')->format('U'), '/foo', 'http://example.com', true, true));
$response->headers->setCookie($cookie2 = new Cookie('foo1', 'bar1', \DateTime::createFromFormat('j-M-Y H:i:s T', '15-Feb-2009 20:00:00 GMT')->format('U'), '/foo', 'http://example.com', true, true));
$domResponse = $m->invoke($client, $response);
try {
$this->assertEquals($expected31[0], $domResponse->getHeader('Set-Cookie'));
} catch (\PHPUnit\Framework\ExpectationFailedException $e) {
$this->assertEquals($expected33[0], $domResponse->getHeader('Set-Cookie'));
} catch (\PHPUnit_Framework_ExpectationFailedException $e) {
$this->assertEquals($expected33[0], $domResponse->getHeader('Set-Cookie'));
}
$response = new Response();
$response->headers->setCookie(new Cookie('foo', 'bar', \DateTime::createFromFormat('j-M-Y H:i:s T', '15-Feb-2009 20:00:00 GMT')->format('U'), '/foo', 'http://example.com', true, true));
$response->headers->setCookie(new Cookie('foo1', 'bar1', \DateTime::createFromFormat('j-M-Y H:i:s T', '15-Feb-2009 20:00:00 GMT')->format('U'), '/foo', 'http://example.com', true, true));
$domResponse = $m->invoke($client, $response);
try {
$this->assertEquals($expected31[0], $domResponse->getHeader('Set-Cookie'));
} catch (\PHPUnit\Framework\ExpectationFailedException $e) {
$this->assertEquals($expected33[0], $domResponse->getHeader('Set-Cookie'));
} catch (\PHPUnit_Framework_ExpectationFailedException $e) {
$this->assertEquals($expected33[0], $domResponse->getHeader('Set-Cookie'));
}
try {
$this->assertEquals($expected31, $domResponse->getHeader('Set-Cookie', false));
} catch (\PHPUnit\Framework\ExpectationFailedException $e) {
$this->assertEquals($expected33, $domResponse->getHeader('Set-Cookie', false));
} catch (\PHPUnit_Framework_ExpectationFailedException $e) {
$this->assertEquals($expected33, $domResponse->getHeader('Set-Cookie', false));
}
$this->assertSame((string) $cookie1, $domResponse->getHeader('Set-Cookie'));
$this->assertSame([(string) $cookie1, (string) $cookie2], $domResponse->getHeader('Set-Cookie', false));
}
public function testFilterResponseSupportsStreamedResponses()
@@ -119,20 +92,21 @@ class ClientTest extends TestCase
public function testUploadedFile()
{
$source = tempnam(sys_get_temp_dir(), 'source');
file_put_contents($source, '1');
$target = sys_get_temp_dir().'/sf.moved.file';
@unlink($target);
$kernel = new TestHttpKernel();
$client = new Client($kernel);
$files = array(
array('tmp_name' => $source, 'name' => 'original', 'type' => 'mime/original', 'size' => 123, 'error' => UPLOAD_ERR_OK),
new UploadedFile($source, 'original', 'mime/original', 123, UPLOAD_ERR_OK, true),
);
$files = [
['tmp_name' => $source, 'name' => 'original', 'type' => 'mime/original', 'size' => 1, 'error' => \UPLOAD_ERR_OK],
new UploadedFile($source, 'original', 'mime/original', 1, \UPLOAD_ERR_OK, true),
];
$file = null;
foreach ($files as $file) {
$client->request('POST', '/', array(), array('foo' => $file));
$client->request('POST', '/', [], ['foo' => $file]);
$files = $client->getRequest()->files->all();
@@ -142,11 +116,11 @@ class ClientTest extends TestCase
$this->assertEquals('original', $file->getClientOriginalName());
$this->assertEquals('mime/original', $file->getClientMimeType());
$this->assertEquals('123', $file->getClientSize());
$this->assertSame(1, $file->getClientSize());
$this->assertTrue($file->isValid());
}
$file->move(dirname($target), basename($target));
$file->move(\dirname($target), basename($target));
$this->assertFileExists($target);
unlink($target);
@@ -157,9 +131,9 @@ class ClientTest extends TestCase
$kernel = new TestHttpKernel();
$client = new Client($kernel);
$file = array('tmp_name' => '', 'name' => '', 'type' => '', 'size' => 0, 'error' => UPLOAD_ERR_NO_FILE);
$file = ['tmp_name' => '', 'name' => '', 'type' => '', 'size' => 0, 'error' => \UPLOAD_ERR_NO_FILE];
$client->request('POST', '/', array(), array('foo' => $file));
$client->request('POST', '/', [], ['foo' => $file]);
$files = $client->getRequest()->files->all();
@@ -176,17 +150,17 @@ class ClientTest extends TestCase
$file = $this
->getMockBuilder('Symfony\Component\HttpFoundation\File\UploadedFile')
->setConstructorArgs(array($source, 'original', 'mime/original', 123, UPLOAD_ERR_OK, true))
->setMethods(array('getSize'))
->setConstructorArgs([$source, 'original', 'mime/original', 123, \UPLOAD_ERR_OK, true])
->setMethods(['getSize'])
->getMock()
;
$file->expects($this->once())
->method('getSize')
->will($this->returnValue(INF))
->willReturn(\INF)
;
$client->request('POST', '/', array(), array($file));
$client->request('POST', '/', [], [$file]);
$files = $client->getRequest()->files->all();
@@ -195,7 +169,7 @@ class ClientTest extends TestCase
$file = $files[0];
$this->assertFalse($file->isValid());
$this->assertEquals(UPLOAD_ERR_INI_SIZE, $file->getError());
$this->assertEquals(\UPLOAD_ERR_INI_SIZE, $file->getError());
$this->assertEquals('mime/original', $file->getClientMimeType());
$this->assertEquals('original', $file->getClientOriginalName());
$this->assertEquals(0, $file->getClientSize());
@@ -14,6 +14,9 @@ namespace Symfony\Component\HttpKernel\Tests\Config;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\Config\EnvParametersResource;
/**
* @group legacy
*/
class EnvParametersResourceTest extends TestCase
{
protected $prefix = '__DUMMY_';
@@ -22,10 +25,10 @@ class EnvParametersResourceTest extends TestCase
protected function setUp()
{
$this->initialEnv = array(
$this->initialEnv = [
$this->prefix.'1' => 'foo',
$this->prefix.'2' => 'bar',
);
];
foreach ($this->initialEnv as $key => $value) {
$_SERVER[$key] = $value;
@@ -46,7 +49,7 @@ class EnvParametersResourceTest extends TestCase
public function testGetResource()
{
$this->assertSame(
array('prefix' => $this->prefix, 'variables' => $this->initialEnv),
['prefix' => $this->prefix, 'variables' => $this->initialEnv],
$this->resource->getResource(),
'->getResource() returns the resource'
);
@@ -55,7 +58,7 @@ class EnvParametersResourceTest extends TestCase
public function testToString()
{
$this->assertSame(
serialize(array('prefix' => $this->prefix, 'variables' => $this->initialEnv)),
serialize(['prefix' => $this->prefix, 'variables' => $this->initialEnv]),
(string) $this->resource
);
}
@@ -23,14 +23,14 @@ class FileLocatorTest extends TestCase
->expects($this->atLeastOnce())
->method('locateResource')
->with('@BundleName/some/path', null, true)
->will($this->returnValue('/bundle-name/some/path'));
->willReturn('/bundle-name/some/path');
$locator = new FileLocator($kernel);
$this->assertEquals('/bundle-name/some/path', $locator->locate('@BundleName/some/path'));
$kernel
->expects($this->never())
->method('locateResource');
$this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}('LogicException');
$this->expectException('LogicException');
$locator->locate('/some/path');
}
@@ -12,17 +12,18 @@
namespace Symfony\Component\HttpKernel\Tests\Controller;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage;
use Symfony\Component\HttpKernel\Controller\ArgumentResolver;
use Symfony\Component\HttpKernel\Controller\ArgumentResolver\DefaultValueResolver;
use Symfony\Component\HttpKernel\Controller\ArgumentResolver\RequestAttributeValueResolver;
use Symfony\Component\HttpKernel\Controller\ArgumentResolver\RequestValueResolver;
use Symfony\Component\HttpKernel\Controller\ArgumentResolver\VariadicValueResolver;
use Symfony\Component\HttpKernel\Controller\ArgumentValueResolverInterface;
use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadataFactory;
use Symfony\Component\HttpKernel\Tests\Fixtures\Controller\ExtendingRequest;
use Symfony\Component\HttpKernel\Tests\Fixtures\Controller\ExtendingSession;
use Symfony\Component\HttpKernel\Tests\Fixtures\Controller\NullableController;
use Symfony\Component\HttpKernel\Tests\Fixtures\Controller\VariadicController;
use Symfony\Component\HttpFoundation\Request;
class ArgumentResolverTest extends TestCase
{
@@ -32,46 +33,40 @@ class ArgumentResolverTest extends TestCase
public static function setUpBeforeClass()
{
$factory = new ArgumentMetadataFactory();
$argumentValueResolvers = array(
new RequestAttributeValueResolver(),
new RequestValueResolver(),
new DefaultValueResolver(),
new VariadicValueResolver(),
);
self::$resolver = new ArgumentResolver($factory, $argumentValueResolvers);
self::$resolver = new ArgumentResolver($factory);
}
public function testDefaultState()
{
$this->assertEquals(self::$resolver, new ArgumentResolver());
$this->assertNotEquals(self::$resolver, new ArgumentResolver(null, array(new RequestAttributeValueResolver())));
$this->assertNotEquals(self::$resolver, new ArgumentResolver(null, [new RequestAttributeValueResolver()]));
}
public function testGetArguments()
{
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$controller = array(new self(), 'controllerWithFoo');
$controller = [new self(), 'controllerWithFoo'];
$this->assertEquals(array('foo'), self::$resolver->getArguments($request, $controller), '->getArguments() returns an array of arguments for the controller method');
$this->assertEquals(['foo'], self::$resolver->getArguments($request, $controller), '->getArguments() returns an array of arguments for the controller method');
}
public function testGetArgumentsReturnsEmptyArrayWhenNoArguments()
{
$request = Request::create('/');
$controller = array(new self(), 'controllerWithoutArguments');
$controller = [new self(), 'controllerWithoutArguments'];
$this->assertEquals(array(), self::$resolver->getArguments($request, $controller), '->getArguments() returns an empty array if the method takes no arguments');
$this->assertEquals([], self::$resolver->getArguments($request, $controller), '->getArguments() returns an empty array if the method takes no arguments');
}
public function testGetArgumentsUsesDefaultValue()
{
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$controller = array(new self(), 'controllerWithFooAndDefaultBar');
$controller = [new self(), 'controllerWithFooAndDefaultBar'];
$this->assertEquals(array('foo', null), self::$resolver->getArguments($request, $controller), '->getArguments() uses default values if present');
$this->assertEquals(['foo', null], self::$resolver->getArguments($request, $controller), '->getArguments() uses default values if present');
}
public function testGetArgumentsOverrideDefaultValueByRequestAttribute()
@@ -79,9 +74,9 @@ class ArgumentResolverTest extends TestCase
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$request->attributes->set('bar', 'bar');
$controller = array(new self(), 'controllerWithFooAndDefaultBar');
$controller = [new self(), 'controllerWithFooAndDefaultBar'];
$this->assertEquals(array('foo', 'bar'), self::$resolver->getArguments($request, $controller), '->getArguments() overrides default values if provided in the request attributes');
$this->assertEquals(['foo', 'bar'], self::$resolver->getArguments($request, $controller), '->getArguments() overrides default values if provided in the request attributes');
}
public function testGetArgumentsFromClosure()
@@ -90,7 +85,7 @@ class ArgumentResolverTest extends TestCase
$request->attributes->set('foo', 'foo');
$controller = function ($foo) {};
$this->assertEquals(array('foo'), self::$resolver->getArguments($request, $controller));
$this->assertEquals(['foo'], self::$resolver->getArguments($request, $controller));
}
public function testGetArgumentsUsesDefaultValueFromClosure()
@@ -99,7 +94,7 @@ class ArgumentResolverTest extends TestCase
$request->attributes->set('foo', 'foo');
$controller = function ($foo, $bar = 'bar') {};
$this->assertEquals(array('foo', 'bar'), self::$resolver->getArguments($request, $controller));
$this->assertEquals(['foo', 'bar'], self::$resolver->getArguments($request, $controller));
}
public function testGetArgumentsFromInvokableObject()
@@ -108,12 +103,12 @@ class ArgumentResolverTest extends TestCase
$request->attributes->set('foo', 'foo');
$controller = new self();
$this->assertEquals(array('foo', null), self::$resolver->getArguments($request, $controller));
$this->assertEquals(['foo', null], self::$resolver->getArguments($request, $controller));
// Test default bar overridden by request attribute
$request->attributes->set('bar', 'bar');
$this->assertEquals(array('foo', 'bar'), self::$resolver->getArguments($request, $controller));
$this->assertEquals(['foo', 'bar'], self::$resolver->getArguments($request, $controller));
}
public function testGetArgumentsFromFunctionName()
@@ -123,7 +118,7 @@ class ArgumentResolverTest extends TestCase
$request->attributes->set('foobar', 'foobar');
$controller = __NAMESPACE__.'\controller_function';
$this->assertEquals(array('foo', 'foobar'), self::$resolver->getArguments($request, $controller));
$this->assertEquals(['foo', 'foobar'], self::$resolver->getArguments($request, $controller));
}
public function testGetArgumentsFailsOnUnresolvedValue()
@@ -131,7 +126,7 @@ class ArgumentResolverTest extends TestCase
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$request->attributes->set('foobar', 'foobar');
$controller = array(new self(), 'controllerWithFooBarFoobar');
$controller = [new self(), 'controllerWithFooBarFoobar'];
try {
self::$resolver->getArguments($request, $controller);
@@ -144,17 +139,17 @@ class ArgumentResolverTest extends TestCase
public function testGetArgumentsInjectsRequest()
{
$request = Request::create('/');
$controller = array(new self(), 'controllerWithRequest');
$controller = [new self(), 'controllerWithRequest'];
$this->assertEquals(array($request), self::$resolver->getArguments($request, $controller), '->getArguments() injects the request');
$this->assertEquals([$request], self::$resolver->getArguments($request, $controller), '->getArguments() injects the request');
}
public function testGetArgumentsInjectsExtendingRequest()
{
$request = ExtendingRequest::create('/');
$controller = array(new self(), 'controllerWithExtendingRequest');
$controller = [new self(), 'controllerWithExtendingRequest'];
$this->assertEquals(array($request), self::$resolver->getArguments($request, $controller), '->getArguments() injects the request when extended');
$this->assertEquals([$request], self::$resolver->getArguments($request, $controller), '->getArguments() injects the request when extended');
}
/**
@@ -164,35 +159,35 @@ class ArgumentResolverTest extends TestCase
{
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$request->attributes->set('bar', array('foo', 'bar'));
$controller = array(new VariadicController(), 'action');
$request->attributes->set('bar', ['foo', 'bar']);
$controller = [new VariadicController(), 'action'];
$this->assertEquals(array('foo', 'foo', 'bar'), self::$resolver->getArguments($request, $controller));
$this->assertEquals(['foo', 'foo', 'bar'], self::$resolver->getArguments($request, $controller));
}
/**
* @requires PHP 5.6
* @expectedException \InvalidArgumentException
*/
public function testGetVariadicArgumentsWithoutArrayInRequest()
{
$this->expectException('InvalidArgumentException');
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$request->attributes->set('bar', 'foo');
$controller = array(new VariadicController(), 'action');
$controller = [new VariadicController(), 'action'];
self::$resolver->getArguments($request, $controller);
}
/**
* @requires PHP 5.6
* @expectedException \InvalidArgumentException
*/
public function testGetArgumentWithoutArray()
{
$this->expectException('InvalidArgumentException');
$factory = new ArgumentMetadataFactory();
$valueResolver = $this->getMockBuilder(ArgumentValueResolverInterface::class)->getMock();
$resolver = new ArgumentResolver($factory, array($valueResolver));
$resolver = new ArgumentResolver($factory, [$valueResolver]);
$valueResolver->expects($this->any())->method('supports')->willReturn(true);
$valueResolver->expects($this->any())->method('resolve')->willReturn('foo');
@@ -200,17 +195,15 @@ class ArgumentResolverTest extends TestCase
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$request->attributes->set('bar', 'foo');
$controller = array($this, 'controllerWithFooAndDefaultBar');
$controller = [$this, 'controllerWithFooAndDefaultBar'];
$resolver->getArguments($request, $controller);
}
/**
* @expectedException \RuntimeException
*/
public function testIfExceptionIsThrownWhenMissingAnArgument()
{
$this->expectException('RuntimeException');
$request = Request::create('/');
$controller = array($this, 'controllerWithFoo');
$controller = [$this, 'controllerWithFoo'];
self::$resolver->getArguments($request, $controller);
}
@@ -223,10 +216,10 @@ class ArgumentResolverTest extends TestCase
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$request->attributes->set('bar', new \stdClass());
$request->attributes->set('mandatory', 'mandatory');
$controller = array(new NullableController(), 'action');
$request->attributes->set('last', 'last');
$controller = [new NullableController(), 'action'];
$this->assertEquals(array('foo', new \stdClass(), 'value', 'mandatory'), self::$resolver->getArguments($request, $controller));
$this->assertEquals(['foo', new \stdClass(), 'value', 'last'], self::$resolver->getArguments($request, $controller));
}
/**
@@ -235,10 +228,71 @@ class ArgumentResolverTest extends TestCase
public function testGetNullableArgumentsWithDefaults()
{
$request = Request::create('/');
$request->attributes->set('mandatory', 'mandatory');
$controller = array(new NullableController(), 'action');
$request->attributes->set('last', 'last');
$controller = [new NullableController(), 'action'];
$this->assertEquals(array(null, null, 'value', 'mandatory'), self::$resolver->getArguments($request, $controller));
$this->assertEquals([null, null, 'value', 'last'], self::$resolver->getArguments($request, $controller));
}
public function testGetSessionArguments()
{
$session = new Session(new MockArraySessionStorage());
$request = Request::create('/');
$request->setSession($session);
$controller = [$this, 'controllerWithSession'];
$this->assertEquals([$session], self::$resolver->getArguments($request, $controller));
}
public function testGetSessionArgumentsWithExtendedSession()
{
$session = new ExtendingSession(new MockArraySessionStorage());
$request = Request::create('/');
$request->setSession($session);
$controller = [$this, 'controllerWithExtendingSession'];
$this->assertEquals([$session], self::$resolver->getArguments($request, $controller));
}
public function testGetSessionArgumentsWithInterface()
{
$session = $this->getMockBuilder(SessionInterface::class)->getMock();
$request = Request::create('/');
$request->setSession($session);
$controller = [$this, 'controllerWithSessionInterface'];
$this->assertEquals([$session], self::$resolver->getArguments($request, $controller));
}
public function testGetSessionMissMatchWithInterface()
{
$this->expectException('RuntimeException');
$session = $this->getMockBuilder(SessionInterface::class)->getMock();
$request = Request::create('/');
$request->setSession($session);
$controller = [$this, 'controllerWithExtendingSession'];
self::$resolver->getArguments($request, $controller);
}
public function testGetSessionMissMatchWithImplementation()
{
$this->expectException('RuntimeException');
$session = new Session(new MockArraySessionStorage());
$request = Request::create('/');
$request->setSession($session);
$controller = [$this, 'controllerWithExtendingSession'];
self::$resolver->getArguments($request, $controller);
}
public function testGetSessionMissMatchOnNull()
{
$this->expectException('RuntimeException');
$request = Request::create('/');
$controller = [$this, 'controllerWithExtendingSession'];
self::$resolver->getArguments($request, $controller);
}
public function __invoke($foo, $bar = null)
@@ -268,6 +322,18 @@ class ArgumentResolverTest extends TestCase
protected function controllerWithExtendingRequest(ExtendingRequest $request)
{
}
protected function controllerWithSession(Session $session)
{
}
protected function controllerWithSessionInterface(SessionInterface $session)
{
}
protected function controllerWithExtendingSession(ExtendingSession $session)
{
}
}
function controller_function($foo, $foobar)
@@ -13,10 +13,10 @@ namespace Symfony\Component\HttpKernel\Tests\Controller;
use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpKernel\Controller\ControllerResolver;
use Symfony\Component\HttpKernel\Tests\Fixtures\Controller\NullableController;
use Symfony\Component\HttpKernel\Tests\Fixtures\Controller\VariadicController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Controller\ControllerResolver;
use Symfony\Component\HttpKernel\Tests\Fixtures\Controller\LegacyNullableController;
use Symfony\Component\HttpKernel\Tests\Fixtures\Controller\VariadicController;
class ControllerResolverTest extends TestCase
{
@@ -55,9 +55,9 @@ class ControllerResolverTest extends TestCase
$resolver = $this->createControllerResolver();
$request = Request::create('/');
$request->attributes->set('_controller', array($this, 'controllerMethod1'));
$request->attributes->set('_controller', [$this, 'controllerMethod1']);
$controller = $resolver->getController($request);
$this->assertSame(array($this, 'controllerMethod1'), $controller);
$this->assertSame([$this, 'controllerMethod1'], $controller);
}
public function testGetControllerWithClassAndMethod()
@@ -65,9 +65,9 @@ class ControllerResolverTest extends TestCase
$resolver = $this->createControllerResolver();
$request = Request::create('/');
$request->attributes->set('_controller', array('Symfony\Component\HttpKernel\Tests\Controller\ControllerResolverTest', 'controllerMethod4'));
$request->attributes->set('_controller', ['Symfony\Component\HttpKernel\Tests\Controller\ControllerResolverTest', 'controllerMethod4']);
$controller = $resolver->getController($request);
$this->assertSame(array('Symfony\Component\HttpKernel\Tests\Controller\ControllerResolverTest', 'controllerMethod4'), $controller);
$this->assertSame(['Symfony\Component\HttpKernel\Tests\Controller\ControllerResolverTest', 'controllerMethod4'], $controller);
}
public function testGetControllerWithObjectAndMethodAsString()
@@ -90,11 +90,9 @@ class ControllerResolverTest extends TestCase
$this->assertInstanceOf('Symfony\Component\HttpKernel\Tests\Controller\ControllerResolverTest', $controller);
}
/**
* @expectedException \InvalidArgumentException
*/
public function testGetControllerOnObjectWithoutInvokeMethod()
{
$this->expectException('InvalidArgumentException');
$resolver = $this->createControllerResolver();
$request = Request::create('/');
@@ -118,12 +116,8 @@ class ControllerResolverTest extends TestCase
public function testGetControllerOnNonUndefinedFunction($controller, $exceptionName = null, $exceptionMessage = null)
{
$resolver = $this->createControllerResolver();
if (method_exists($this, 'expectException')) {
$this->expectException($exceptionName);
$this->expectExceptionMessage($exceptionMessage);
} else {
$this->setExpectedException($exceptionName, $exceptionMessage);
}
$this->expectException($exceptionName);
$this->expectExceptionMessage($exceptionMessage);
$request = Request::create('/');
$request->attributes->set('_controller', $controller);
@@ -132,16 +126,16 @@ class ControllerResolverTest extends TestCase
public function getUndefinedControllers()
{
return array(
array(1, 'InvalidArgumentException', 'Unable to find controller "1".'),
array('foo', 'InvalidArgumentException', 'Unable to find controller "foo".'),
array('oof::bar', 'InvalidArgumentException', 'Class "oof" does not exist.'),
array('stdClass', 'InvalidArgumentException', 'Unable to find controller "stdClass".'),
array('Symfony\Component\HttpKernel\Tests\Controller\ControllerTest::staticsAction', 'InvalidArgumentException', 'The controller for URI "/" is not callable. Expected method "staticsAction" on class "Symfony\Component\HttpKernel\Tests\Controller\ControllerTest", did you mean "staticAction"?'),
array('Symfony\Component\HttpKernel\Tests\Controller\ControllerTest::privateAction', 'InvalidArgumentException', 'The controller for URI "/" is not callable. Method "privateAction" on class "Symfony\Component\HttpKernel\Tests\Controller\ControllerTest" should be public and non-abstract'),
array('Symfony\Component\HttpKernel\Tests\Controller\ControllerTest::protectedAction', 'InvalidArgumentException', 'The controller for URI "/" is not callable. Method "protectedAction" on class "Symfony\Component\HttpKernel\Tests\Controller\ControllerTest" should be public and non-abstract'),
array('Symfony\Component\HttpKernel\Tests\Controller\ControllerTest::undefinedAction', 'InvalidArgumentException', 'The controller for URI "/" is not callable. Expected method "undefinedAction" on class "Symfony\Component\HttpKernel\Tests\Controller\ControllerTest". Available methods: "publicAction", "staticAction"'),
);
return [
[1, 'InvalidArgumentException', 'Unable to find controller "1".'],
['foo', 'InvalidArgumentException', 'Unable to find controller "foo".'],
['oof::bar', 'InvalidArgumentException', 'Class "oof" does not exist.'],
['stdClass', 'InvalidArgumentException', 'Unable to find controller "stdClass".'],
['Symfony\Component\HttpKernel\Tests\Controller\ControllerTest::staticsAction', 'InvalidArgumentException', 'The controller for URI "/" is not callable: Expected method "staticsAction" on class "Symfony\Component\HttpKernel\Tests\Controller\ControllerTest", did you mean "staticAction"?'],
['Symfony\Component\HttpKernel\Tests\Controller\ControllerTest::privateAction', 'InvalidArgumentException', 'The controller for URI "/" is not callable: Method "privateAction" on class "Symfony\Component\HttpKernel\Tests\Controller\ControllerTest" should be public and non-abstract'],
['Symfony\Component\HttpKernel\Tests\Controller\ControllerTest::protectedAction', 'InvalidArgumentException', 'The controller for URI "/" is not callable: Method "protectedAction" on class "Symfony\Component\HttpKernel\Tests\Controller\ControllerTest" should be public and non-abstract'],
['Symfony\Component\HttpKernel\Tests\Controller\ControllerTest::undefinedAction', 'InvalidArgumentException', 'The controller for URI "/" is not callable: Expected method "undefinedAction" on class "Symfony\Component\HttpKernel\Tests\Controller\ControllerTest". Available methods: "publicAction", "staticAction"'],
];
}
/**
@@ -152,49 +146,49 @@ class ControllerResolverTest extends TestCase
$resolver = $this->createControllerResolver();
$request = Request::create('/');
$controller = array(new self(), 'testGetArguments');
$this->assertEquals(array(), $resolver->getArguments($request, $controller), '->getArguments() returns an empty array if the method takes no arguments');
$controller = [new self(), 'testGetArguments'];
$this->assertEquals([], $resolver->getArguments($request, $controller), '->getArguments() returns an empty array if the method takes no arguments');
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$controller = array(new self(), 'controllerMethod1');
$this->assertEquals(array('foo'), $resolver->getArguments($request, $controller), '->getArguments() returns an array of arguments for the controller method');
$controller = [new self(), 'controllerMethod1'];
$this->assertEquals(['foo'], $resolver->getArguments($request, $controller), '->getArguments() returns an array of arguments for the controller method');
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$controller = array(new self(), 'controllerMethod2');
$this->assertEquals(array('foo', null), $resolver->getArguments($request, $controller), '->getArguments() uses default values if present');
$controller = [new self(), 'controllerMethod2'];
$this->assertEquals(['foo', null], $resolver->getArguments($request, $controller), '->getArguments() uses default values if present');
$request->attributes->set('bar', 'bar');
$this->assertEquals(array('foo', 'bar'), $resolver->getArguments($request, $controller), '->getArguments() overrides default values if provided in the request attributes');
$this->assertEquals(['foo', 'bar'], $resolver->getArguments($request, $controller), '->getArguments() overrides default values if provided in the request attributes');
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$controller = function ($foo) {};
$this->assertEquals(array('foo'), $resolver->getArguments($request, $controller));
$this->assertEquals(['foo'], $resolver->getArguments($request, $controller));
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$controller = function ($foo, $bar = 'bar') {};
$this->assertEquals(array('foo', 'bar'), $resolver->getArguments($request, $controller));
$this->assertEquals(['foo', 'bar'], $resolver->getArguments($request, $controller));
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$controller = new self();
$this->assertEquals(array('foo', null), $resolver->getArguments($request, $controller));
$this->assertEquals(['foo', null], $resolver->getArguments($request, $controller));
$request->attributes->set('bar', 'bar');
$this->assertEquals(array('foo', 'bar'), $resolver->getArguments($request, $controller));
$this->assertEquals(['foo', 'bar'], $resolver->getArguments($request, $controller));
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$request->attributes->set('foobar', 'foobar');
$controller = 'Symfony\Component\HttpKernel\Tests\Controller\some_controller_function';
$this->assertEquals(array('foo', 'foobar'), $resolver->getArguments($request, $controller));
$this->assertEquals(['foo', 'foobar'], $resolver->getArguments($request, $controller));
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$request->attributes->set('foobar', 'foobar');
$controller = array(new self(), 'controllerMethod3');
$controller = [new self(), 'controllerMethod3'];
try {
$resolver->getArguments($request, $controller);
@@ -204,8 +198,8 @@ class ControllerResolverTest extends TestCase
}
$request = Request::create('/');
$controller = array(new self(), 'controllerMethod5');
$this->assertEquals(array($request), $resolver->getArguments($request, $controller), '->getArguments() injects the request');
$controller = [new self(), 'controllerMethod5'];
$this->assertEquals([$request], $resolver->getArguments($request, $controller), '->getArguments() injects the request');
}
/**
@@ -218,15 +212,15 @@ class ControllerResolverTest extends TestCase
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$request->attributes->set('bar', array('foo', 'bar'));
$controller = array(new VariadicController(), 'action');
$this->assertEquals(array('foo', 'foo', 'bar'), $resolver->getArguments($request, $controller));
$request->attributes->set('bar', ['foo', 'bar']);
$controller = [new VariadicController(), 'action'];
$this->assertEquals(['foo', 'foo', 'bar'], $resolver->getArguments($request, $controller));
}
public function testCreateControllerCanReturnAnyCallable()
{
$mock = $this->getMockBuilder('Symfony\Component\HttpKernel\Controller\ControllerResolver')->setMethods(array('createController'))->getMock();
$mock->expects($this->once())->method('createController')->will($this->returnValue('Symfony\Component\HttpKernel\Tests\Controller\some_controller_function'));
$mock = $this->getMockBuilder('Symfony\Component\HttpKernel\Controller\ControllerResolver')->setMethods(['createController'])->getMock();
$mock->expects($this->once())->method('createController')->willReturn('Symfony\Component\HttpKernel\Tests\Controller\some_controller_function');
$request = Request::create('/');
$request->attributes->set('_controller', 'foobar');
@@ -234,15 +228,15 @@ class ControllerResolverTest extends TestCase
}
/**
* @expectedException \RuntimeException
* @group legacy
*/
public function testIfExceptionIsThrownWhenMissingAnArgument()
{
$this->expectException('RuntimeException');
$resolver = new ControllerResolver();
$request = Request::create('/');
$controller = array($this, 'controllerMethod1');
$controller = [$this, 'controllerMethod1'];
$resolver->getArguments($request, $controller);
}
@@ -253,14 +247,18 @@ class ControllerResolverTest extends TestCase
*/
public function testGetNullableArguments()
{
if (\PHP_VERSION_ID >= 80000) {
$this->markTestSkipped('PHP < 8 required.');
}
$resolver = new ControllerResolver();
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$request->attributes->set('bar', new \stdClass());
$request->attributes->set('mandatory', 'mandatory');
$controller = array(new NullableController(), 'action');
$this->assertEquals(array('foo', new \stdClass(), 'value', 'mandatory'), $resolver->getArguments($request, $controller));
$controller = [new LegacyNullableController(), 'action'];
$this->assertEquals(['foo', new \stdClass(), 'value', 'mandatory'], $resolver->getArguments($request, $controller));
}
/**
@@ -269,12 +267,16 @@ class ControllerResolverTest extends TestCase
*/
public function testGetNullableArgumentsWithDefaults()
{
if (\PHP_VERSION_ID >= 80000) {
$this->markTestSkipped('PHP < 8 required.');
}
$resolver = new ControllerResolver();
$request = Request::create('/');
$request->attributes->set('mandatory', 'mandatory');
$controller = array(new NullableController(), 'action');
$this->assertEquals(array(null, null, 'value', 'mandatory'), $resolver->getArguments($request, $controller));
$controller = [new LegacyNullableController(), 'action'];
$this->assertEquals([null, null, 'value', 'mandatory'], $resolver->getArguments($request, $controller));
}
protected function createControllerResolver(LoggerInterface $logger = null)
@@ -33,55 +33,55 @@ class ArgumentMetadataFactoryTest extends TestCase
public function testSignature1()
{
$arguments = $this->factory->createArgumentMetadata(array($this, 'signature1'));
$arguments = $this->factory->createArgumentMetadata([$this, 'signature1']);
$this->assertEquals(array(
$this->assertEquals([
new ArgumentMetadata('foo', self::class, false, false, null),
new ArgumentMetadata('bar', 'array', false, false, null),
new ArgumentMetadata('baz', 'callable', false, false, null),
), $arguments);
], $arguments);
}
public function testSignature2()
{
$arguments = $this->factory->createArgumentMetadata(array($this, 'signature2'));
$arguments = $this->factory->createArgumentMetadata([$this, 'signature2']);
$this->assertEquals(array(
$this->assertEquals([
new ArgumentMetadata('foo', self::class, false, true, null, true),
new ArgumentMetadata('bar', __NAMESPACE__.'\FakeClassThatDoesNotExist', false, true, null, true),
new ArgumentMetadata('bar', FakeClassThatDoesNotExist::class, false, true, null, true),
new ArgumentMetadata('baz', 'Fake\ImportedAndFake', false, true, null, true),
), $arguments);
], $arguments);
}
public function testSignature3()
{
$arguments = $this->factory->createArgumentMetadata(array($this, 'signature3'));
$arguments = $this->factory->createArgumentMetadata([$this, 'signature3']);
$this->assertEquals(array(
new ArgumentMetadata('bar', __NAMESPACE__.'\FakeClassThatDoesNotExist', false, false, null),
$this->assertEquals([
new ArgumentMetadata('bar', FakeClassThatDoesNotExist::class, false, false, null),
new ArgumentMetadata('baz', 'Fake\ImportedAndFake', false, false, null),
), $arguments);
], $arguments);
}
public function testSignature4()
{
$arguments = $this->factory->createArgumentMetadata(array($this, 'signature4'));
$arguments = $this->factory->createArgumentMetadata([$this, 'signature4']);
$this->assertEquals(array(
$this->assertEquals([
new ArgumentMetadata('foo', null, false, true, 'default'),
new ArgumentMetadata('bar', null, false, true, 500),
new ArgumentMetadata('baz', null, false, true, array()),
), $arguments);
new ArgumentMetadata('baz', null, false, true, []),
], $arguments);
}
public function testSignature5()
{
$arguments = $this->factory->createArgumentMetadata(array($this, 'signature5'));
$arguments = $this->factory->createArgumentMetadata([$this, 'signature5']);
$this->assertEquals(array(
$this->assertEquals([
new ArgumentMetadata('foo', 'array', false, true, null, true),
new ArgumentMetadata('bar', null, false, false, null),
), $arguments);
new ArgumentMetadata('bar', null, false, true, null, true),
], $arguments);
}
/**
@@ -89,12 +89,12 @@ class ArgumentMetadataFactoryTest extends TestCase
*/
public function testVariadicSignature()
{
$arguments = $this->factory->createArgumentMetadata(array(new VariadicController(), 'action'));
$arguments = $this->factory->createArgumentMetadata([new VariadicController(), 'action']);
$this->assertEquals(array(
$this->assertEquals([
new ArgumentMetadata('foo', null, false, false, null),
new ArgumentMetadata('bar', null, true, false, null),
), $arguments);
], $arguments);
}
/**
@@ -102,13 +102,13 @@ class ArgumentMetadataFactoryTest extends TestCase
*/
public function testBasicTypesSignature()
{
$arguments = $this->factory->createArgumentMetadata(array(new BasicTypesController(), 'action'));
$arguments = $this->factory->createArgumentMetadata([new BasicTypesController(), 'action']);
$this->assertEquals(array(
$this->assertEquals([
new ArgumentMetadata('foo', 'string', false, false, null),
new ArgumentMetadata('bar', 'int', false, false, null),
new ArgumentMetadata('baz', 'float', false, false, null),
), $arguments);
], $arguments);
}
/**
@@ -116,21 +116,21 @@ class ArgumentMetadataFactoryTest extends TestCase
*/
public function testNullableTypesSignature()
{
$arguments = $this->factory->createArgumentMetadata(array(new NullableController(), 'action'));
$arguments = $this->factory->createArgumentMetadata([new NullableController(), 'action']);
$this->assertEquals(array(
$this->assertEquals([
new ArgumentMetadata('foo', 'string', false, false, null, true),
new ArgumentMetadata('bar', \stdClass::class, false, false, null, true),
new ArgumentMetadata('baz', 'string', false, true, 'value', true),
new ArgumentMetadata('mandatory', null, false, false, null, true),
), $arguments);
new ArgumentMetadata('last', 'string', false, true, '', false),
], $arguments);
}
private function signature1(ArgumentMetadataFactoryTest $foo, array $bar, callable $baz)
private function signature1(self $foo, array $bar, callable $baz)
{
}
private function signature2(ArgumentMetadataFactoryTest $foo = null, FakeClassThatDoesNotExist $bar = null, ImportedAndFake $baz = null)
private function signature2(self $foo = null, FakeClassThatDoesNotExist $bar = null, ImportedAndFake $baz = null)
{
}
@@ -138,11 +138,11 @@ class ArgumentMetadataFactoryTest extends TestCase
{
}
private function signature4($foo = 'default', $bar = 500, $baz = array())
private function signature4($foo = 'default', $bar = 500, $baz = [])
{
}
private function signature5(array $foo = null, $bar)
private function signature5(array $foo = null, $bar = null)
{
}
}
@@ -32,11 +32,9 @@ class ArgumentMetadataTest extends TestCase
$this->assertSame('default value', $argument->getDefaultValue());
}
/**
* @expectedException \LogicException
*/
public function testDefaultValueUnavailable()
{
$this->expectException('LogicException');
$argument = new ArgumentMetadata('foo', 'string', false, false, null, false);
$this->assertFalse($argument->isNullable());
@@ -12,11 +12,11 @@
namespace Symfony\Component\HttpKernel\Tests\DataCollector;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\DataCollector\ConfigDataCollector;
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\DataCollector\ConfigDataCollector;
use Symfony\Component\HttpKernel\Kernel;
class ConfigDataCollectorTest extends TestCase
{
@@ -31,31 +31,16 @@ class ConfigDataCollectorTest extends TestCase
$this->assertTrue($c->isDebug());
$this->assertSame('config', $c->getName());
$this->assertSame('testkernel', $c->getAppName());
$this->assertSame(PHP_VERSION, $c->getPhpVersion());
$this->assertMatchesRegularExpression('~^'.preg_quote($c->getPhpVersion(), '~').'~', \PHP_VERSION);
$this->assertMatchesRegularExpression('~'.preg_quote((string) $c->getPhpVersionExtra(), '~').'$~', \PHP_VERSION);
$this->assertSame(\PHP_INT_SIZE * 8, $c->getPhpArchitecture());
$this->assertSame(class_exists('Locale', false) && \Locale::getDefault() ? \Locale::getDefault() : 'n/a', $c->getPhpIntlLocale());
$this->assertSame(date_default_timezone_get(), $c->getPhpTimezone());
$this->assertSame(Kernel::VERSION, $c->getSymfonyVersion());
$this->assertNull($c->getToken());
// if else clause because we don't know it
if (extension_loaded('xdebug')) {
$this->assertTrue($c->hasXDebug());
} else {
$this->assertFalse($c->hasXDebug());
}
// if else clause because we don't know it
if (((extension_loaded('eaccelerator') && ini_get('eaccelerator.enable'))
||
(extension_loaded('apc') && ini_get('apc.enabled'))
||
(extension_loaded('Zend OPcache') && ini_get('opcache.enable'))
||
(extension_loaded('xcache') && ini_get('xcache.cacher'))
||
(extension_loaded('wincache') && ini_get('wincache.ocenabled')))) {
$this->assertTrue($c->hasAccelerator());
} else {
$this->assertFalse($c->hasAccelerator());
}
$this->assertSame(\extension_loaded('xdebug'), $c->hasXDebug());
$this->assertSame(\extension_loaded('Zend OPcache') && filter_var(ini_get('opcache.enable'), \FILTER_VALIDATE_BOOLEAN), $c->hasZendOpcache());
$this->assertSame(\extension_loaded('apcu') && filter_var(ini_get('apc.enabled'), \FILTER_VALIDATE_BOOLEAN), $c->hasApcu());
}
}
@@ -72,7 +57,7 @@ class KernelForTest extends Kernel
public function getBundles()
{
return array();
return [];
}
public function registerContainerConfiguration(LoaderInterface $loader)
@@ -15,9 +15,7 @@ use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Tests\Fixtures\DataCollector\CloneVarDataCollector;
use Symfony\Component\VarDumper\Cloner\Stub;
use Symfony\Component\VarDumper\Cloner\VarCloner;
use Symfony\Component\VarDumper\Dumper\CliDumper;
class DataCollectorTest extends TestCase
{
@@ -32,19 +30,9 @@ class DataCollectorTest extends TestCase
public function testCloneVarExistingFilePath()
{
$c = new CloneVarDataCollector($filePath = tempnam(sys_get_temp_dir(), 'clone_var_data_collector_'));
$c = new CloneVarDataCollector([$filePath = tempnam(sys_get_temp_dir(), 'clone_var_data_collector_')]);
$c->collect(new Request(), new Response());
$data = $c->getData();
$this->assertInstanceOf(Stub::class, $data->getRawData()[0][0]);
$this->assertDumpEquals("\"$filePath\"", $data);
}
private function assertDumpEquals($dump, $data, $message = '')
{
$dumper = new CliDumper();
$dumper->setColors(false);
$this->assertSame(rtrim($dump), rtrim($dumper->dump($data, true)), $message);
$this->assertSame($filePath, $c->getData()[0]);
}
}
@@ -12,10 +12,11 @@
namespace Symfony\Component\HttpKernel\Tests\DataCollector;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\DataCollector\DumpDataCollector;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\DataCollector\DumpDataCollector;
use Symfony\Component\VarDumper\Cloner\Data;
use Symfony\Component\VarDumper\Dumper\CliDumper;
/**
* @author Nicolas Grekas <p@tchwork.com>
@@ -24,7 +25,7 @@ class DumpDataCollectorTest extends TestCase
{
public function testDump()
{
$data = new Data(array(array(123)));
$data = new Data([[123]]);
$collector = new DumpDataCollector();
@@ -35,19 +36,19 @@ class DumpDataCollectorTest extends TestCase
$this->assertSame(1, $collector->getDumpsCount());
$dump = $collector->getDumps('html');
$this->assertTrue(isset($dump[0]['data']));
$this->assertArrayHasKey('data', $dump[0]);
$dump[0]['data'] = preg_replace('/^.*?<pre/', '<pre', $dump[0]['data']);
$dump[0]['data'] = preg_replace('/sf-dump-\d+/', 'sf-dump', $dump[0]['data']);
$xDump = array(
array(
$xDump = [
[
'data' => "<pre class=sf-dump id=sf-dump data-indent-pad=\" \"><span class=sf-dump-num>123</span>\n</pre><script>Sfdump(\"sf-dump\")</script>\n",
'name' => 'DumpDataCollectorTest.php',
'file' => __FILE__,
'line' => $line,
'fileExcerpt' => false,
),
);
],
];
$this->assertEquals($xDump, $dump);
$this->assertStringMatchesFormat('a:3:{i:0;a:5:{s:4:"data";%c:39:"Symfony\Component\VarDumper\Cloner\Data":%a', $collector->serialize());
@@ -57,7 +58,7 @@ class DumpDataCollectorTest extends TestCase
public function testCollectDefault()
{
$data = new Data(array(array(123)));
$data = new Data([[123]]);
$collector = new DumpDataCollector();
@@ -66,7 +67,7 @@ class DumpDataCollectorTest extends TestCase
ob_start();
$collector->collect(new Request(), new Response());
$output = ob_get_clean();
$output = preg_replace("/\033\[[^m]*m/", '', ob_get_clean());
$this->assertSame("DumpDataCollectorTest.php on line {$line}:\n123\n", $output);
$this->assertSame(1, $collector->getDumpsCount());
@@ -75,7 +76,7 @@ class DumpDataCollectorTest extends TestCase
public function testCollectHtml()
{
$data = new Data(array(array(123)));
$data = new Data([[123]]);
$collector = new DumpDataCollector(null, 'test://%f:%l');
@@ -103,13 +104,32 @@ EOTXT;
public function testFlush()
{
$data = new Data(array(array(456)));
$data = new Data([[456]]);
$collector = new DumpDataCollector();
$collector->dump($data);
$line = __LINE__ - 1;
ob_start();
$collector->__destruct();
$this->assertSame("DumpDataCollectorTest.php on line {$line}:\n456\n", ob_get_clean());
$output = preg_replace("/\033\[[^m]*m/", '', ob_get_clean());
$this->assertSame("DumpDataCollectorTest.php on line {$line}:\n456\n", $output);
}
public function testFlushNothingWhenDataDumperIsProvided()
{
$data = new Data([[456]]);
$dumper = new CliDumper('php://output');
$collector = new DumpDataCollector(null, null, null, null, $dumper);
ob_start();
$collector->dump($data);
$line = __LINE__ - 1;
$output = preg_replace("/\033\[[^m]*m/", '', ob_get_clean());
$this->assertSame("DumpDataCollectorTest.php on line {$line}:\n456\n", $output);
ob_start();
$collector->__destruct();
$this->assertEmpty(ob_get_clean());
}
}
@@ -13,9 +13,9 @@ namespace Symfony\Component\HttpKernel\Tests\DataCollector;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Debug\Exception\FlattenException;
use Symfony\Component\HttpKernel\DataCollector\ExceptionDataCollector;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\DataCollector\ExceptionDataCollector;
class ExceptionDataCollectorTest extends TestCase
{
@@ -37,4 +37,23 @@ class ExceptionDataCollectorTest extends TestCase
$this->assertSame('exception', $c->getName());
$this->assertSame($trace, $c->getTrace());
}
public function testCollectWithoutException()
{
$c = new ExceptionDataCollector();
$c->collect(new Request(), new Response());
$this->assertFalse($c->hasException());
}
public function testReset()
{
$c = new ExceptionDataCollector();
$c->collect(new Request(), new Response(), new \Exception());
$c->reset();
$c->collect(new Request(), new Response());
$this->assertFalse($c->hasException());
}
}
@@ -14,95 +14,133 @@ namespace Symfony\Component\HttpKernel\Tests\DataCollector;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Debug\Exception\SilencedErrorContext;
use Symfony\Component\HttpKernel\DataCollector\LoggerDataCollector;
use Symfony\Component\VarDumper\Cloner\Data;
class LoggerDataCollectorTest extends TestCase
{
private static $data;
public function testCollectWithUnexpectedFormat()
{
$logger = $this
->getMockBuilder('Symfony\Component\HttpKernel\Log\DebugLoggerInterface')
->setMethods(['countErrors', 'getLogs', 'clear'])
->getMock();
$logger->expects($this->once())->method('countErrors')->willReturn(123);
$logger->expects($this->exactly(2))->method('getLogs')->willReturn([]);
$c = new LoggerDataCollector($logger, __DIR__.'/');
$c->lateCollect();
$compilerLogs = $c->getCompilerLogs()->getValue('message');
$this->assertSame([
['message' => 'Removed service "Psr\Container\ContainerInterface"; reason: private alias.'],
['message' => 'Removed service "Symfony\Component\DependencyInjection\ContainerInterface"; reason: private alias.'],
], $compilerLogs['Symfony\Component\DependencyInjection\Compiler\RemovePrivateAliasesPass']);
$this->assertSame([
['message' => 'Some custom logging message'],
['message' => 'With ending :'],
], $compilerLogs['Unknown Compiler Pass']);
}
/**
* @dataProvider getCollectTestData
*/
public function testCollect($nb, $logs, $expectedLogs, $expectedDeprecationCount, $expectedScreamCount, $expectedPriorities = null)
{
$logger = $this->getMockBuilder('Symfony\Component\HttpKernel\Log\DebugLoggerInterface')->getMock();
$logger->expects($this->once())->method('countErrors')->will($this->returnValue($nb));
$logger->expects($this->exactly(2))->method('getLogs')->will($this->returnValue($logs));
// disable cloning the context, to ease fixtures creation.
$c = $this->getMockBuilder(LoggerDataCollector::class)
->setMethods(array('cloneVar'))
->setConstructorArgs(array($logger))
$logger = $this
->getMockBuilder('Symfony\Component\HttpKernel\Log\DebugLoggerInterface')
->setMethods(['countErrors', 'getLogs', 'clear'])
->getMock();
$c->expects($this->any())->method('cloneVar')->willReturn(self::$data);
$logger->expects($this->once())->method('countErrors')->willReturn($nb);
$logger->expects($this->exactly(2))->method('getLogs')->willReturn($logs);
$c = new LoggerDataCollector($logger);
$c->lateCollect();
$this->assertEquals('logger', $c->getName());
$this->assertEquals($nb, $c->countErrors());
$this->assertEquals($expectedLogs, $c->getLogs());
$logs = array_map(function ($v) {
if (isset($v['context']['exception'])) {
$e = &$v['context']['exception'];
$e = isset($e["\0*\0message"]) ? [$e["\0*\0message"], $e["\0*\0severity"]] : [$e["\0Symfony\Component\Debug\Exception\SilencedErrorContext\0severity"]];
}
return $v;
}, $c->getLogs()->getValue(true));
$this->assertEquals($expectedLogs, $logs);
$this->assertEquals($expectedDeprecationCount, $c->countDeprecations());
$this->assertEquals($expectedScreamCount, $c->countScreams());
if (isset($expectedPriorities)) {
$this->assertSame($expectedPriorities, $c->getPriorities());
$this->assertSame($expectedPriorities, $c->getPriorities()->getValue(true));
}
}
public function testReset()
{
$logger = $this
->getMockBuilder('Symfony\Component\HttpKernel\Log\DebugLoggerInterface')
->setMethods(['countErrors', 'getLogs', 'clear'])
->getMock();
$logger->expects($this->once())->method('clear');
$c = new LoggerDataCollector($logger);
$c->reset();
}
public function getCollectTestData()
{
if (null === self::$data) {
self::$data = new Data(array());
}
yield 'simple log' => array(
yield 'simple log' => [
1,
array(array('message' => 'foo', 'context' => array(), 'priority' => 100, 'priorityName' => 'DEBUG')),
array(array('message' => 'foo', 'context' => array(), 'priority' => 100, 'priorityName' => 'DEBUG')),
[['message' => 'foo', 'context' => [], 'priority' => 100, 'priorityName' => 'DEBUG']],
[['message' => 'foo', 'context' => [], 'priority' => 100, 'priorityName' => 'DEBUG']],
0,
0,
);
];
yield 'log with a context' => array(
yield 'log with a context' => [
1,
array(array('message' => 'foo', 'context' => array('foo' => 'bar'), 'priority' => 100, 'priorityName' => 'DEBUG')),
array(array('message' => 'foo', 'context' => self::$data, 'priority' => 100, 'priorityName' => 'DEBUG')),
[['message' => 'foo', 'context' => ['foo' => 'bar'], 'priority' => 100, 'priorityName' => 'DEBUG']],
[['message' => 'foo', 'context' => ['foo' => 'bar'], 'priority' => 100, 'priorityName' => 'DEBUG']],
0,
0,
);
];
if (!class_exists(SilencedErrorContext::class)) {
return;
}
yield 'logs with some deprecations' => array(
yield 'logs with some deprecations' => [
1,
array(
array('message' => 'foo3', 'context' => array('exception' => new \ErrorException('warning', 0, E_USER_WARNING)), 'priority' => 100, 'priorityName' => 'DEBUG'),
array('message' => 'foo', 'context' => array('exception' => new \ErrorException('deprecated', 0, E_DEPRECATED)), 'priority' => 100, 'priorityName' => 'DEBUG'),
array('message' => 'foo2', 'context' => array('exception' => new \ErrorException('deprecated', 0, E_USER_DEPRECATED)), 'priority' => 100, 'priorityName' => 'DEBUG'),
),
array(
array('message' => 'foo3', 'context' => self::$data, 'priority' => 100, 'priorityName' => 'DEBUG'),
array('message' => 'foo', 'context' => self::$data, 'priority' => 100, 'priorityName' => 'DEBUG', 'errorCount' => 1, 'scream' => false),
array('message' => 'foo2', 'context' => self::$data, 'priority' => 100, 'priorityName' => 'DEBUG', 'errorCount' => 1, 'scream' => false),
),
[
['message' => 'foo3', 'context' => ['exception' => new \ErrorException('warning', 0, \E_USER_WARNING)], 'priority' => 100, 'priorityName' => 'DEBUG'],
['message' => 'foo', 'context' => ['exception' => new \ErrorException('deprecated', 0, \E_DEPRECATED)], 'priority' => 100, 'priorityName' => 'DEBUG'],
['message' => 'foo2', 'context' => ['exception' => new \ErrorException('deprecated', 0, \E_USER_DEPRECATED)], 'priority' => 100, 'priorityName' => 'DEBUG'],
],
[
['message' => 'foo3', 'context' => ['exception' => ['warning', \E_USER_WARNING]], 'priority' => 100, 'priorityName' => 'DEBUG'],
['message' => 'foo', 'context' => ['exception' => ['deprecated', \E_DEPRECATED]], 'priority' => 100, 'priorityName' => 'DEBUG', 'errorCount' => 1, 'scream' => false],
['message' => 'foo2', 'context' => ['exception' => ['deprecated', \E_USER_DEPRECATED]], 'priority' => 100, 'priorityName' => 'DEBUG', 'errorCount' => 1, 'scream' => false],
],
2,
0,
array(100 => array('count' => 3, 'name' => 'DEBUG')),
);
[100 => ['count' => 3, 'name' => 'DEBUG']],
];
yield 'logs with some silent errors' => array(
yield 'logs with some silent errors' => [
1,
array(
array('message' => 'foo3', 'context' => array('exception' => new \ErrorException('warning', 0, E_USER_WARNING)), 'priority' => 100, 'priorityName' => 'DEBUG'),
array('message' => 'foo3', 'context' => array('exception' => new SilencedErrorContext(E_USER_WARNING, __FILE__, __LINE__)), 'priority' => 100, 'priorityName' => 'DEBUG'),
),
array(
array('message' => 'foo3', 'context' => self::$data, 'priority' => 100, 'priorityName' => 'DEBUG'),
array('message' => 'foo3', 'context' => self::$data, 'priority' => 100, 'priorityName' => 'DEBUG', 'errorCount' => 1, 'scream' => true),
),
[
['message' => 'foo3', 'context' => ['exception' => new \ErrorException('warning', 0, \E_USER_WARNING)], 'priority' => 100, 'priorityName' => 'DEBUG'],
['message' => 'foo3', 'context' => ['exception' => new SilencedErrorContext(\E_USER_WARNING, __FILE__, __LINE__)], 'priority' => 100, 'priorityName' => 'DEBUG'],
['message' => '0', 'context' => ['exception' => new SilencedErrorContext(\E_USER_WARNING, __FILE__, __LINE__)], 'priority' => 100, 'priorityName' => 'DEBUG'],
],
[
['message' => 'foo3', 'context' => ['exception' => ['warning', \E_USER_WARNING]], 'priority' => 100, 'priorityName' => 'DEBUG'],
['message' => 'foo3', 'context' => ['exception' => [\E_USER_WARNING]], 'priority' => 100, 'priorityName' => 'DEBUG', 'errorCount' => 1, 'scream' => true],
['message' => '0', 'context' => ['exception' => [\E_USER_WARNING]], 'priority' => 100, 'priorityName' => 'DEBUG', 'errorCount' => 1, 'scream' => true],
],
0,
1,
);
2,
];
}
}
@@ -12,9 +12,9 @@
namespace Symfony\Component\HttpKernel\Tests\DataCollector;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\DataCollector\MemoryDataCollector;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\DataCollector\MemoryDataCollector;
class MemoryDataCollectorTest extends TestCase
{
@@ -23,8 +23,8 @@ class MemoryDataCollectorTest extends TestCase
$collector = new MemoryDataCollector();
$collector->collect(new Request(), new Response());
$this->assertInternalType('integer', $collector->getMemory());
$this->assertInternalType('integer', $collector->getMemoryLimit());
$this->assertIsInt($collector->getMemory());
$this->assertIsInt($collector->getMemoryLimit());
$this->assertSame('memory', $collector->getName());
}
@@ -39,21 +39,21 @@ class MemoryDataCollectorTest extends TestCase
public function getBytesConversionTestData()
{
return array(
array('2k', 2048),
array('2 k', 2048),
array('8m', 8 * 1024 * 1024),
array('+2 k', 2048),
array('+2???k', 2048),
array('0x10', 16),
array('0xf', 15),
array('010', 8),
array('+0x10 k', 16 * 1024),
array('1g', 1024 * 1024 * 1024),
array('1G', 1024 * 1024 * 1024),
array('-1', -1),
array('0', 0),
array('2mk', 2048), // the unit must be the last char, so in this case 'k', not 'm'
);
return [
['2k', 2048],
['2 k', 2048],
['8m', 8 * 1024 * 1024],
['+2 k', 2048],
['+2???k', 2048],
['0x10', 16],
['0xf', 15],
['010', 8],
['+0x10 k', 16 * 1024],
['1g', 1024 * 1024 * 1024],
['1G', 1024 * 1024 * 1024],
['-1', -1],
['0', 0],
['2mk', 2048], // the unit must be the last char, so in this case 'k', not 'm'
];
}
}
@@ -12,21 +12,20 @@
namespace Symfony\Component\HttpKernel\Tests\DataCollector;
use PHPUnit\Framework\TestCase;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\ParameterBag;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage;
use Symfony\Component\HttpKernel\Controller\ArgumentResolverInterface;
use Symfony\Component\HttpKernel\DataCollector\RequestDataCollector;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\HttpKernel;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\DataCollector\RequestDataCollector;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\VarDumper\Cloner\Data;
use Symfony\Component\VarDumper\Cloner\VarCloner;
class RequestDataCollectorTest extends TestCase
{
@@ -35,8 +34,8 @@ class RequestDataCollectorTest extends TestCase
$c = new RequestDataCollector();
$c->collect($request = $this->createRequest(), $this->createResponse());
$c->lateCollect();
$cloner = new VarCloner();
$attributes = $c->getRequestAttributes();
$this->assertSame('request', $c->getName());
@@ -46,13 +45,14 @@ class RequestDataCollectorTest extends TestCase
$this->assertInstanceOf('Symfony\Component\HttpFoundation\ParameterBag', $attributes);
$this->assertInstanceOf('Symfony\Component\HttpFoundation\ParameterBag', $c->getRequestRequest());
$this->assertInstanceOf('Symfony\Component\HttpFoundation\ParameterBag', $c->getRequestQuery());
$this->assertInstanceOf(ParameterBag::class, $c->getResponseCookies());
$this->assertSame('html', $c->getFormat());
$this->assertEquals('foobar', $c->getRoute());
$this->assertEquals(array('name' => $cloner->cloneVar(array('name' => 'foo'))->seek('name')), $c->getRouteParams());
$this->assertSame(array(), $c->getSessionAttributes());
$this->assertEquals(['name' => 'foo'], $c->getRouteParams());
$this->assertSame([], $c->getSessionAttributes());
$this->assertSame('en', $c->getLocale());
$this->assertEquals($cloner->cloneVar($request->attributes->get('resource')), $attributes->get('resource'));
$this->assertEquals($cloner->cloneVar($request->attributes->get('object')), $attributes->get('object'));
$this->assertContainsEquals(__FILE__, $attributes->get('resource'));
$this->assertSame('stdClass', $attributes->get('object')->getType());
$this->assertInstanceOf('Symfony\Component\HttpFoundation\ParameterBag', $c->getResponseHeaders());
$this->assertSame('OK', $c->getStatusText());
@@ -62,26 +62,13 @@ class RequestDataCollectorTest extends TestCase
public function testCollectWithoutRouteParams()
{
$request = $this->createRequest(array());
$request = $this->createRequest([]);
$c = new RequestDataCollector();
$c->collect($request, $this->createResponse());
$c->lateCollect();
$this->assertEquals(array(), $c->getRouteParams());
}
public function testKernelResponseDoesNotStartSession()
{
$kernel = $this->getMockBuilder(HttpKernelInterface::class)->getMock();
$request = new Request();
$session = new Session(new MockArraySessionStorage());
$request->setSession($session);
$response = new Response();
$c = new RequestDataCollector();
$c->onKernelResponse(new FilterResponseEvent($kernel, $request, HttpKernelInterface::MASTER_REQUEST, $response));
$this->assertFalse($session->isStarted());
$this->assertEquals([], $c->getRouteParams());
}
/**
@@ -94,8 +81,9 @@ class RequestDataCollectorTest extends TestCase
$response = $this->createResponse();
$this->injectController($c, $callable, $request);
$c->collect($request, $response);
$c->lateCollect();
$this->assertSame($expected, $c->getController(), sprintf('Testing: %s', $name));
$this->assertSame($expected, $c->getController()->getValue(true), sprintf('Testing: %s', $name));
}
public function provideControllerCallables()
@@ -106,95 +94,95 @@ class RequestDataCollectorTest extends TestCase
$r3 = new \ReflectionClass($this);
// test name, callable, expected
return array(
array(
return [
[
'"Regular" callable',
array($this, 'testControllerInspection'),
array(
'class' => __NAMESPACE__.'\RequestDataCollectorTest',
[$this, 'testControllerInspection'],
[
'class' => self::class,
'method' => 'testControllerInspection',
'file' => __FILE__,
'line' => $r1->getStartLine(),
),
),
],
],
array(
[
'Closure',
function () { return 'foo'; },
array(
[
'class' => __NAMESPACE__.'\{closure}',
'method' => null,
'file' => __FILE__,
'line' => __LINE__ - 5,
),
),
],
],
array(
[
'Static callback as string',
__NAMESPACE__.'\RequestDataCollectorTest::staticControllerMethod',
array(
[
'class' => 'Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest',
'method' => 'staticControllerMethod',
'file' => __FILE__,
'line' => $r2->getStartLine(),
),
),
],
],
array(
[
'Static callable with instance',
array($this, 'staticControllerMethod'),
array(
[$this, 'staticControllerMethod'],
[
'class' => 'Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest',
'method' => 'staticControllerMethod',
'file' => __FILE__,
'line' => $r2->getStartLine(),
),
),
],
],
array(
[
'Static callable with class name',
array('Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest', 'staticControllerMethod'),
array(
['Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest', 'staticControllerMethod'],
[
'class' => 'Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest',
'method' => 'staticControllerMethod',
'file' => __FILE__,
'line' => $r2->getStartLine(),
),
),
],
],
array(
[
'Callable with instance depending on __call()',
array($this, 'magicMethod'),
array(
[$this, 'magicMethod'],
[
'class' => 'Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest',
'method' => 'magicMethod',
'file' => 'n/a',
'line' => 'n/a',
),
),
],
],
array(
[
'Callable with class name depending on __callStatic()',
array('Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest', 'magicMethod'),
array(
['Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest', 'magicMethod'],
[
'class' => 'Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest',
'method' => 'magicMethod',
'file' => 'n/a',
'line' => 'n/a',
),
),
],
],
array(
[
'Invokable controller',
$this,
array(
[
'class' => 'Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest',
'method' => null,
'file' => __FILE__,
'line' => $r3->getStartLine(),
),
),
);
],
],
];
}
public function testItIgnoresInvalidCallables()
@@ -208,7 +196,57 @@ class RequestDataCollectorTest extends TestCase
$this->assertSame('n/a', $c->getController());
}
protected function createRequest($routeParams = array('name' => 'foo'))
public function testItAddsRedirectedAttributesWhenRequestContainsSpecificCookie()
{
$request = $this->createRequest();
$request->cookies->add([
'sf_redirect' => '{}',
]);
$kernel = $this->getMockBuilder(HttpKernelInterface::class)->getMock();
$c = new RequestDataCollector();
$c->onKernelResponse(new FilterResponseEvent($kernel, $request, HttpKernelInterface::MASTER_REQUEST, $this->createResponse()));
$this->assertTrue($request->attributes->get('_redirected'));
}
public function testItSetsARedirectCookieIfTheResponseIsARedirection()
{
$c = new RequestDataCollector();
$response = $this->createResponse();
$response->setStatusCode(302);
$response->headers->set('Location', '/somewhere-else');
$c->collect($request = $this->createRequest(), $response);
$c->lateCollect();
$cookie = $this->getCookieByName($response, 'sf_redirect');
$this->assertNotEmpty($cookie->getValue());
}
public function testItCollectsTheRedirectionAndClearTheCookie()
{
$c = new RequestDataCollector();
$request = $this->createRequest();
$request->attributes->set('_redirected', true);
$request->cookies->add([
'sf_redirect' => '{"method": "POST"}',
]);
$c->collect($request, $response = $this->createResponse());
$c->lateCollect();
$this->assertEquals('POST', $c->getRedirect()['method']);
$cookie = $this->getCookieByName($response, 'sf_redirect');
$this->assertNull($cookie->getValue());
}
protected function createRequest($routeParams = ['name' => 'foo'])
{
$request = Request::create('http://test.com/foo?bar=baz');
$request->attributes->set('foo', 'bar');
@@ -282,4 +320,15 @@ class RequestDataCollectorTest extends TestCase
{
throw new \LogicException('Unexpected method call');
}
private function getCookieByName(Response $response, $name)
{
foreach ($response->headers->getCookies() as $cookie) {
if ($cookie->getName() == $name) {
return $cookie;
}
}
throw new \InvalidArgumentException(sprintf('Cookie named "%s" is not in response', $name));
}
}
@@ -12,9 +12,10 @@
namespace Symfony\Component\HttpKernel\Tests\DataCollector;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\DataCollector\TimeDataCollector;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\DataCollector\TimeDataCollector;
use Symfony\Component\Stopwatch\Stopwatch;
/**
* @group time-sensitive
@@ -30,7 +31,7 @@ class TimeDataCollectorTest extends TestCase
$c->collect($request, new Response());
$this->assertEquals(1000, $c->getStartTime());
$this->assertEquals(0, $c->getStartTime());
$request->server->set('REQUEST_TIME_FLOAT', 2);
@@ -43,7 +44,7 @@ class TimeDataCollectorTest extends TestCase
$this->assertEquals(0, $c->getStartTime());
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\KernelInterface')->getMock();
$kernel->expects($this->once())->method('getStartTime')->will($this->returnValue(123456));
$kernel->expects($this->once())->method('getStartTime')->willReturn(123456.0);
$c = new TimeDataCollector($kernel);
$request = new Request();
@@ -51,5 +52,6 @@ class TimeDataCollectorTest extends TestCase
$c->collect($request, new Response());
$this->assertEquals(123456000, $c->getStartTime());
$this->assertSame(class_exists(Stopwatch::class, false), $c->isStopwatchInstalled());
}
}
@@ -27,7 +27,7 @@ class FileLinkFormatterTest extends TestCase
public function testWhenFileLinkFormatAndNoRequest()
{
$file = __DIR__.DIRECTORY_SEPARATOR.'file.php';
$file = __DIR__.\DIRECTORY_SEPARATOR.'file.php';
$sut = new FileLinkFormatter('debug://open?url=file://%f&line=%l', new RequestStack());
@@ -36,8 +36,7 @@ class FileLinkFormatterTest extends TestCase
public function testWhenFileLinkFormatAndRequest()
{
$file = __DIR__.DIRECTORY_SEPARATOR.'file.php';
$baseDir = __DIR__;
$file = __DIR__.\DIRECTORY_SEPARATOR.'file.php';
$requestStack = new RequestStack();
$request = new Request();
$requestStack->push($request);
@@ -49,19 +48,19 @@ class FileLinkFormatterTest extends TestCase
public function testWhenNoFileLinkFormatAndRequest()
{
$file = __DIR__.DIRECTORY_SEPARATOR.'file.php';
$file = __DIR__.\DIRECTORY_SEPARATOR.'file.php';
$requestStack = new RequestStack();
$request = new Request();
$requestStack->push($request);
$request->server->set('SERVER_NAME', 'www.example.org');
$request->server->set('SERVER_PORT', 80);
$request->server->set('SCRIPT_NAME', '/app.php');
$request->server->set('SCRIPT_FILENAME', '/web/app.php');
$request->server->set('REQUEST_URI', '/app.php/example');
$request->server->set('SCRIPT_NAME', '/index.php');
$request->server->set('SCRIPT_FILENAME', '/public/index.php');
$request->server->set('REQUEST_URI', '/index.php/example');
$sut = new FileLinkFormatter(null, $requestStack, __DIR__, '/_profiler/open?file=%f&line=%l#line%l');
$this->assertSame('http://www.example.org/app.php/_profiler/open?file=file.php&line=3#line3', $sut->format($file, 3));
$this->assertSame('http://www.example.org/_profiler/open?file=file.php&line=3#line3', $sut->format($file, 3));
}
}
@@ -13,11 +13,11 @@ namespace Symfony\Component\HttpKernel\Tests\Debug;
use PHPUnit\Framework\TestCase;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Debug\TraceableEventDispatcher;
use Symfony\Component\HttpKernel\HttpKernel;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Stopwatch\Stopwatch;
class TraceableEventDispatcherTest extends TestCase
@@ -25,13 +25,13 @@ class TraceableEventDispatcherTest extends TestCase
public function testStopwatchSections()
{
$dispatcher = new TraceableEventDispatcher(new EventDispatcher(), $stopwatch = new Stopwatch());
$kernel = $this->getHttpKernel($dispatcher, function () { return new Response(); });
$kernel = $this->getHttpKernel($dispatcher, function () { return new Response('', 200, ['X-Debug-Token' => '292e1e']); });
$request = Request::create('/');
$response = $kernel->handle($request);
$kernel->terminate($request, $response);
$events = $stopwatch->getSectionEvents($response->headers->get('X-Debug-Token'));
$this->assertEquals(array(
$this->assertEquals([
'__section__',
'kernel.request',
'kernel.controller',
@@ -39,17 +39,17 @@ class TraceableEventDispatcherTest extends TestCase
'controller',
'kernel.response',
'kernel.terminate',
), array_keys($events));
], array_keys($events));
}
public function testStopwatchCheckControllerOnRequestEvent()
{
$stopwatch = $this->getMockBuilder('Symfony\Component\Stopwatch\Stopwatch')
->setMethods(array('isStarted'))
->setMethods(['isStarted'])
->getMock();
$stopwatch->expects($this->once())
->method('isStarted')
->will($this->returnValue(false));
->willReturn(false);
$dispatcher = new TraceableEventDispatcher(new EventDispatcher(), $stopwatch);
@@ -61,15 +61,13 @@ class TraceableEventDispatcherTest extends TestCase
public function testStopwatchStopControllerOnRequestEvent()
{
$stopwatch = $this->getMockBuilder('Symfony\Component\Stopwatch\Stopwatch')
->setMethods(array('isStarted', 'stop', 'stopSection'))
->setMethods(['isStarted', 'stop'])
->getMock();
$stopwatch->expects($this->once())
->method('isStarted')
->will($this->returnValue(true));
->willReturn(true);
$stopwatch->expects($this->once())
->method('stop');
$stopwatch->expects($this->once())
->method('stopSection');
$dispatcher = new TraceableEventDispatcher(new EventDispatcher(), $stopwatch);
@@ -112,9 +110,9 @@ class TraceableEventDispatcherTest extends TestCase
protected function getHttpKernel($dispatcher, $controller)
{
$controllerResolver = $this->getMockBuilder('Symfony\Component\HttpKernel\Controller\ControllerResolverInterface')->getMock();
$controllerResolver->expects($this->once())->method('getController')->will($this->returnValue($controller));
$controllerResolver->expects($this->once())->method('getController')->willReturn($controller);
$argumentResolver = $this->getMockBuilder('Symfony\Component\HttpKernel\Controller\ArgumentResolverInterface')->getMock();
$argumentResolver->expects($this->once())->method('getArguments')->will($this->returnValue(array()));
$argumentResolver->expects($this->once())->method('getArguments')->willReturn([]);
return new HttpKernel($dispatcher, $controllerResolver, new RequestStack(), $argumentResolver);
}
@@ -1,99 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Tests\DependencyInjection;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\DependencyInjection\AddClassesToCachePass;
class AddClassesToCachePassTest extends TestCase
{
public function testExpandClasses()
{
$r = new \ReflectionClass(AddClassesToCachePass::class);
$pass = $r->newInstanceWithoutConstructor();
$r = new \ReflectionMethod(AddClassesToCachePass::class, 'expandClasses');
$r->setAccessible(true);
$expand = $r->getClosure($pass);
$this->assertSame('Foo', $expand(array('Foo'), array())[0]);
$this->assertSame('Foo', $expand(array('\\Foo'), array())[0]);
$this->assertSame('Foo', $expand(array('Foo'), array('\\Foo'))[0]);
$this->assertSame('Foo', $expand(array('Foo'), array('Foo'))[0]);
$this->assertSame('Foo', $expand(array('\\Foo'), array('\\Foo\\Bar'))[0]);
$this->assertSame('Foo', $expand(array('Foo'), array('\\Foo\\Bar'))[0]);
$this->assertSame('Foo', $expand(array('\\Foo'), array('\\Foo\\Bar\\Acme'))[0]);
$this->assertSame('Foo\\Bar', $expand(array('Foo\\'), array('\\Foo\\Bar'))[0]);
$this->assertSame('Foo\\Bar\\Acme', $expand(array('Foo\\'), array('\\Foo\\Bar\\Acme'))[0]);
$this->assertEmpty($expand(array('Foo\\'), array('\\Foo')));
$this->assertSame('Acme\\Foo\\Bar', $expand(array('**\\Foo\\'), array('\\Acme\\Foo\\Bar'))[0]);
$this->assertEmpty($expand(array('**\\Foo\\'), array('\\Foo\\Bar')));
$this->assertEmpty($expand(array('**\\Foo\\'), array('\\Acme\\Foo')));
$this->assertEmpty($expand(array('**\\Foo\\'), array('\\Foo')));
$this->assertSame('Acme\\Foo', $expand(array('**\\Foo'), array('\\Acme\\Foo'))[0]);
$this->assertEmpty($expand(array('**\\Foo'), array('\\Acme\\Foo\\AcmeBundle')));
$this->assertEmpty($expand(array('**\\Foo'), array('\\Acme\\FooBar\\AcmeBundle')));
$this->assertSame('Foo\\Acme\\Bar', $expand(array('Foo\\*\\Bar'), array('\\Foo\\Acme\\Bar'))[0]);
$this->assertEmpty($expand(array('Foo\\*\\Bar'), array('\\Foo\\Acme\\Bundle\\Bar')));
$this->assertSame('Foo\\Acme\\Bar', $expand(array('Foo\\**\\Bar'), array('\\Foo\\Acme\\Bar'))[0]);
$this->assertSame('Foo\\Acme\\Bundle\\Bar', $expand(array('Foo\\**\\Bar'), array('\\Foo\\Acme\\Bundle\\Bar'))[0]);
$this->assertSame('Acme\\Bar', $expand(array('*\\Bar'), array('\\Acme\\Bar'))[0]);
$this->assertEmpty($expand(array('*\\Bar'), array('\\Bar')));
$this->assertEmpty($expand(array('*\\Bar'), array('\\Foo\\Acme\\Bar')));
$this->assertSame('Foo\\Acme\\Bar', $expand(array('**\\Bar'), array('\\Foo\\Acme\\Bar'))[0]);
$this->assertSame('Foo\\Acme\\Bundle\\Bar', $expand(array('**\\Bar'), array('\\Foo\\Acme\\Bundle\\Bar'))[0]);
$this->assertEmpty($expand(array('**\\Bar'), array('\\Bar')));
$this->assertSame('Foo\\Bar', $expand(array('Foo\\*'), array('\\Foo\\Bar'))[0]);
$this->assertEmpty($expand(array('Foo\\*'), array('\\Foo\\Acme\\Bar')));
$this->assertSame('Foo\\Bar', $expand(array('Foo\\**'), array('\\Foo\\Bar'))[0]);
$this->assertSame('Foo\\Acme\\Bar', $expand(array('Foo\\**'), array('\\Foo\\Acme\\Bar'))[0]);
$this->assertSame(array('Foo\\Bar'), $expand(array('Foo\\*'), array('Foo\\Bar', 'Foo\\BarTest')));
$this->assertSame(array('Foo\\Bar', 'Foo\\BarTest'), $expand(array('Foo\\*', 'Foo\\*Test'), array('Foo\\Bar', 'Foo\\BarTest')));
$this->assertSame(
'Acme\\FooBundle\\Controller\\DefaultController',
$expand(array('**Bundle\\Controller\\'), array('\\Acme\\FooBundle\\Controller\\DefaultController'))[0]
);
$this->assertSame(
'FooBundle\\Controller\\DefaultController',
$expand(array('**Bundle\\Controller\\'), array('\\FooBundle\\Controller\\DefaultController'))[0]
);
$this->assertSame(
'Acme\\FooBundle\\Controller\\Bar\\DefaultController',
$expand(array('**Bundle\\Controller\\'), array('\\Acme\\FooBundle\\Controller\\Bar\\DefaultController'))[0]
);
$this->assertSame(
'Bundle\\Controller\\Bar\\DefaultController',
$expand(array('**Bundle\\Controller\\'), array('\\Bundle\\Controller\\Bar\\DefaultController'))[0]
);
$this->assertSame(
'Acme\\Bundle\\Controller\\Bar\\DefaultController',
$expand(array('**Bundle\\Controller\\'), array('\\Acme\\Bundle\\Controller\\Bar\\DefaultController'))[0]
);
$this->assertSame('Foo\\Bar', $expand(array('Foo\\Bar'), array())[0]);
$this->assertSame('Foo\\Acme\\Bar', $expand(array('Foo\\**'), array('\\Foo\\Acme\\Bar'))[0]);
}
}
@@ -12,6 +12,10 @@
namespace Symfony\Component\HttpKernel\Tests\DependencyInjection;
use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\ServiceLocator;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\DependencyInjection\FragmentRendererPass;
use Symfony\Component\HttpKernel\Fragment\FragmentRendererInterface;
@@ -20,82 +24,42 @@ class FragmentRendererPassTest extends TestCase
{
/**
* Tests that content rendering not implementing FragmentRendererInterface
* trigger an exception.
*
* @expectedException \InvalidArgumentException
* triggers an exception.
*/
public function testContentRendererWithoutInterface()
{
// one service, not implementing any interface
$services = array(
'my_content_renderer' => array(array('alias' => 'foo')),
);
$definition = $this->getMockBuilder('Symfony\Component\DependencyInjection\Definition')->getMock();
$builder = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerBuilder')->setMethods(array('hasDefinition', 'findTaggedServiceIds', 'getDefinition'))->getMock();
$builder->expects($this->any())
->method('hasDefinition')
->will($this->returnValue(true));
// We don't test kernel.fragment_renderer here
$builder->expects($this->atLeastOnce())
->method('findTaggedServiceIds')
->will($this->returnValue($services));
$builder->expects($this->atLeastOnce())
->method('getDefinition')
->will($this->returnValue($definition));
$this->expectException('InvalidArgumentException');
$builder = new ContainerBuilder();
$fragmentHandlerDefinition = $builder->register('fragment.handler');
$builder->register('my_content_renderer', 'Symfony\Component\DependencyInjection\Definition')
->addTag('kernel.fragment_renderer', ['alias' => 'foo']);
$pass = new FragmentRendererPass();
$pass->process($builder);
$this->assertEquals([['addRendererService', ['foo', 'my_content_renderer']]], $fragmentHandlerDefinition->getMethodCalls());
}
public function testValidContentRenderer()
{
$services = array(
'my_content_renderer' => array(array('alias' => 'foo')),
);
$renderer = $this->getMockBuilder('Symfony\Component\DependencyInjection\Definition')->getMock();
$renderer
->expects($this->once())
->method('addMethodCall')
->with('addRendererService', array('foo', 'my_content_renderer'))
;
$definition = $this->getMockBuilder('Symfony\Component\DependencyInjection\Definition')->getMock();
$definition->expects($this->atLeastOnce())
->method('getClass')
->will($this->returnValue('Symfony\Component\HttpKernel\Tests\DependencyInjection\RendererService'));
$definition
->expects($this->once())
->method('isPublic')
->will($this->returnValue(true))
;
$builder = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerBuilder')->setMethods(array('hasDefinition', 'findTaggedServiceIds', 'getDefinition'))->getMock();
$builder->expects($this->any())
->method('hasDefinition')
->will($this->returnValue(true));
// We don't test kernel.fragment_renderer here
$builder->expects($this->atLeastOnce())
->method('findTaggedServiceIds')
->will($this->returnValue($services));
$builder->expects($this->atLeastOnce())
->method('getDefinition')
->will($this->onConsecutiveCalls($renderer, $definition));
$builder = new ContainerBuilder();
$fragmentHandlerDefinition = $builder->register('fragment.handler')
->addArgument(null);
$builder->register('my_content_renderer', 'Symfony\Component\HttpKernel\Tests\DependencyInjection\RendererService')
->addTag('kernel.fragment_renderer', ['alias' => 'foo']);
$pass = new FragmentRendererPass();
$pass->process($builder);
$serviceLocatorDefinition = $builder->getDefinition((string) $fragmentHandlerDefinition->getArgument(0));
$this->assertSame(ServiceLocator::class, $serviceLocatorDefinition->getClass());
$this->assertEquals(['foo' => new ServiceClosureArgument(new Reference('my_content_renderer'))], $serviceLocatorDefinition->getArgument(0));
}
}
class RendererService implements FragmentRendererInterface
{
public function render($uri, Request $request = null, array $options = array())
public function render($uri, Request $request = null, array $options = [])
{
}
@@ -12,23 +12,27 @@
namespace Symfony\Component\HttpKernel\Tests\DependencyInjection;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\DependencyInjection\LazyLoadingFragmentHandler;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\DependencyInjection\LazyLoadingFragmentHandler;
class LazyLoadingFragmentHandlerTest extends TestCase
{
public function test()
/**
* @group legacy
* @expectedDeprecation The Symfony\Component\HttpKernel\DependencyInjection\LazyLoadingFragmentHandler::addRendererService() method is deprecated since Symfony 3.3 and will be removed in 4.0.
*/
public function testRenderWithLegacyMapping()
{
$renderer = $this->getMockBuilder('Symfony\Component\HttpKernel\Fragment\FragmentRendererInterface')->getMock();
$renderer->expects($this->once())->method('getName')->will($this->returnValue('foo'));
$renderer->expects($this->any())->method('render')->will($this->returnValue(new Response()));
$renderer->expects($this->once())->method('getName')->willReturn('foo');
$renderer->expects($this->any())->method('render')->willReturn(new Response());
$requestStack = $this->getMockBuilder('Symfony\Component\HttpFoundation\RequestStack')->getMock();
$requestStack->expects($this->any())->method('getCurrentRequest')->will($this->returnValue(Request::create('/')));
$requestStack->expects($this->any())->method('getCurrentRequest')->willReturn(Request::create('/'));
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock();
$container->expects($this->once())->method('get')->will($this->returnValue($renderer));
$container->expects($this->once())->method('get')->willReturn($renderer);
$handler = new LazyLoadingFragmentHandler($container, $requestStack, false);
$handler->addRendererService('foo', 'foo');
@@ -38,4 +42,25 @@ class LazyLoadingFragmentHandlerTest extends TestCase
// second call should not lazy-load anymore (see once() above on the get() method)
$handler->render('/foo', 'foo');
}
public function testRender()
{
$renderer = $this->getMockBuilder('Symfony\Component\HttpKernel\Fragment\FragmentRendererInterface')->getMock();
$renderer->expects($this->once())->method('getName')->willReturn('foo');
$renderer->expects($this->any())->method('render')->willReturn(new Response());
$requestStack = $this->getMockBuilder('Symfony\Component\HttpFoundation\RequestStack')->getMock();
$requestStack->expects($this->any())->method('getCurrentRequest')->willReturn(Request::create('/'));
$container = $this->getMockBuilder('Psr\Container\ContainerInterface')->getMock();
$container->expects($this->once())->method('has')->with('foo')->willReturn(true);
$container->expects($this->once())->method('get')->willReturn($renderer);
$handler = new LazyLoadingFragmentHandler($container, $requestStack, false);
$handler->render('/foo', 'foo');
// second call should not lazy-load anymore (see once() above on the get() method)
$handler->render('/foo', 'foo');
}
}
@@ -12,44 +12,39 @@
namespace Symfony\Component\HttpKernel\Tests\DependencyInjection;
use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\HttpKernel\DependencyInjection\MergeExtensionConfigurationPass;
class MergeExtensionConfigurationPassTest extends TestCase
{
public function testAutoloadMainExtension()
{
$container = $this->getMockBuilder('Symfony\\Component\\DependencyInjection\\ContainerBuilder')->setMethods(array('getExtensionConfig', 'loadFromExtension', 'getParameterBag', 'getDefinitions', 'getAliases', 'getExtensions'))->getMock();
$params = $this->getMockBuilder('Symfony\\Component\\DependencyInjection\\ParameterBag\\ParameterBag')->getMock();
$container = new ContainerBuilder();
$container->registerExtension(new LoadedExtension());
$container->registerExtension(new NotLoadedExtension());
$container->loadFromExtension('loaded', []);
$container->expects($this->at(0))
->method('getExtensionConfig')
->with('loaded')
->will($this->returnValue(array(array())));
$container->expects($this->at(1))
->method('getExtensionConfig')
->with('notloaded')
->will($this->returnValue(array()));
$container->expects($this->once())
->method('loadFromExtension')
->with('notloaded', array());
$container->expects($this->any())
->method('getParameterBag')
->will($this->returnValue($params));
$params->expects($this->any())
->method('all')
->will($this->returnValue(array()));
$container->expects($this->any())
->method('getDefinitions')
->will($this->returnValue(array()));
$container->expects($this->any())
->method('getAliases')
->will($this->returnValue(array()));
$container->expects($this->any())
->method('getExtensions')
->will($this->returnValue(array()));
$configPass = new MergeExtensionConfigurationPass(array('loaded', 'notloaded'));
$configPass = new MergeExtensionConfigurationPass(['loaded', 'not_loaded']);
$configPass->process($container);
$this->assertTrue($container->hasDefinition('loaded.foo'));
$this->assertTrue($container->hasDefinition('not_loaded.bar'));
}
}
class LoadedExtension extends Extension
{
public function load(array $configs, ContainerBuilder $container)
{
$container->register('loaded.foo');
}
}
class NotLoadedExtension extends Extension
{
public function load(array $configs, ContainerBuilder $container)
{
$container->register('not_loaded.bar');
}
}
@@ -12,8 +12,8 @@
namespace Symfony\Component\HttpKernel\Tests\EventListener;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\EventListener\AddRequestFormatsListener;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\EventListener\AddRequestFormatsListener;
use Symfony\Component\HttpKernel\KernelEvents;
/**
@@ -30,7 +30,7 @@ class AddRequestFormatsListenerTest extends TestCase
protected function setUp()
{
$this->listener = new AddRequestFormatsListener(array('csv' => array('text/csv', 'text/plain')));
$this->listener = new AddRequestFormatsListener(['csv' => ['text/csv', 'text/plain']]);
}
protected function tearDown()
@@ -46,7 +46,7 @@ class AddRequestFormatsListenerTest extends TestCase
public function testRegisteredEvent()
{
$this->assertEquals(
array(KernelEvents::REQUEST => array('onKernelRequest', 1)),
[KernelEvents::REQUEST => ['onKernelRequest', 1]],
AddRequestFormatsListener::getSubscribedEvents()
);
}
@@ -58,7 +58,7 @@ class AddRequestFormatsListenerTest extends TestCase
$request->expects($this->once())
->method('setFormat')
->with('csv', array('text/csv', 'text/plain'));
->with('csv', ['text/csv', 'text/plain']);
$this->listener->onKernelRequest($event);
}
@@ -77,7 +77,7 @@ class AddRequestFormatsListenerTest extends TestCase
$event->expects($this->any())
->method('getRequest')
->will($this->returnValue($request));
->willReturn($request);
return $event;
}
@@ -13,9 +13,9 @@ namespace Symfony\Component\HttpKernel\Tests\EventListener;
use PHPUnit\Framework\TestCase;
use Psr\Log\LogLevel;
use Symfony\Component\Console\Event\ConsoleEvent;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\ConsoleEvents;
use Symfony\Component\Console\Event\ConsoleEvent;
use Symfony\Component\Console\Helper\HelperSet;
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Output\ConsoleOutput;
@@ -29,8 +29,6 @@ use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\KernelEvents;
/**
* DebugHandlersListenerTest.
*
* @author Nicolas Grekas <p@tchwork.com>
*/
class DebugHandlersListenerTest extends TestCase
@@ -42,11 +40,11 @@ class DebugHandlersListenerTest extends TestCase
$listener = new DebugHandlersListener($userHandler, $logger);
$xHandler = new ExceptionHandler();
$eHandler = new ErrorHandler();
$eHandler->setExceptionHandler(array($xHandler, 'handle'));
$eHandler->setExceptionHandler([$xHandler, 'handle']);
$exception = null;
set_error_handler(array($eHandler, 'handleError'));
set_exception_handler(array($eHandler, 'handleException'));
set_error_handler([$eHandler, 'handleError']);
set_exception_handler([$eHandler, 'handleException']);
try {
$listener->configure();
} catch (\Exception $exception) {
@@ -60,10 +58,10 @@ class DebugHandlersListenerTest extends TestCase
$this->assertSame($userHandler, $xHandler->setHandler('var_dump'));
$loggers = $eHandler->setLoggers(array());
$loggers = $eHandler->setLoggers([]);
$this->assertArrayHasKey(E_DEPRECATED, $loggers);
$this->assertSame(array($logger, LogLevel::INFO), $loggers[E_DEPRECATED]);
$this->assertArrayHasKey(\E_DEPRECATED, $loggers);
$this->assertSame([$logger, LogLevel::INFO], $loggers[\E_DEPRECATED]);
}
public function testConfigureForHttpKernelWithNoTerminateWithException()
@@ -77,7 +75,7 @@ class DebugHandlersListenerTest extends TestCase
);
$exception = null;
$h = set_exception_handler(array($eHandler, 'handleException'));
$h = set_exception_handler([$eHandler, 'handleException']);
try {
$listener->configure($event);
} catch (\Exception $exception) {
@@ -96,23 +94,23 @@ class DebugHandlersListenerTest extends TestCase
$dispatcher = new EventDispatcher();
$listener = new DebugHandlersListener(null);
$app = $this->getMockBuilder('Symfony\Component\Console\Application')->getMock();
$app->expects($this->once())->method('getHelperSet')->will($this->returnValue(new HelperSet()));
$app->expects($this->once())->method('getHelperSet')->willReturn(new HelperSet());
$command = new Command(__FUNCTION__);
$command->setApplication($app);
$event = new ConsoleEvent($command, new ArgvInput(), new ConsoleOutput());
$dispatcher->addSubscriber($listener);
$xListeners = array(
KernelEvents::REQUEST => array(array($listener, 'configure')),
ConsoleEvents::COMMAND => array(array($listener, 'configure')),
);
$xListeners = [
KernelEvents::REQUEST => [[$listener, 'configure']],
ConsoleEvents::COMMAND => [[$listener, 'configure']],
];
$this->assertSame($xListeners, $dispatcher->getListeners());
$exception = null;
$eHandler = new ErrorHandler();
set_error_handler(array($eHandler, 'handleError'));
set_exception_handler(array($eHandler, 'handleException'));
set_error_handler([$eHandler, 'handleError']);
set_exception_handler([$eHandler, 'handleException']);
try {
$dispatcher->dispatch(ConsoleEvents::COMMAND, $event);
} catch (\Exception $exception) {
@@ -132,4 +130,26 @@ class DebugHandlersListenerTest extends TestCase
$xHandler(new \Exception());
}
public function testReplaceExistingExceptionHandler()
{
$userHandler = function () {};
$listener = new DebugHandlersListener($userHandler);
$eHandler = new ErrorHandler();
$eHandler->setExceptionHandler('var_dump');
$exception = null;
set_exception_handler([$eHandler, 'handleException']);
try {
$listener->configure();
} catch (\Exception $exception) {
}
restore_exception_handler();
if (null !== $exception) {
throw $exception;
}
$this->assertSame($userHandler, $eHandler->setExceptionHandler('var_dump'));
}
}
@@ -29,7 +29,7 @@ class DumpListenerTest extends TestCase
public function testSubscribedEvents()
{
$this->assertSame(
array(ConsoleEvents::COMMAND => array('configure', 1024)),
[ConsoleEvents::COMMAND => ['configure', 1024]],
DumpListener::getSubscribedEvents()
);
}
@@ -68,7 +68,7 @@ class MockCloner implements ClonerInterface
{
public function cloneVar($var)
{
return new Data(array($var.'-'));
return new Data([[$var.'-']]);
}
}
@@ -76,8 +76,6 @@ class MockDumper implements DataDumperInterface
{
public function dump(Data $data)
{
$rawData = $data->getRawData();
echo '+'.$rawData[0];
echo '+'.$data->getValue();
}
}
@@ -12,12 +12,15 @@
namespace Symfony\Component\HttpKernel\Tests\EventListener;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\EventListener\ExceptionListener;
use Symfony\Component\HttpKernel\Log\DebugLoggerInterface;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\EventListener\ExceptionListener;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Log\DebugLoggerInterface;
use Symfony\Component\HttpKernel\Tests\Logger;
/**
@@ -34,9 +37,9 @@ class ExceptionListenerTest extends TestCase
$logger = new TestLogger();
$l = new ExceptionListener('foo', $logger);
$_logger = new \ReflectionProperty(get_class($l), 'logger');
$_logger = new \ReflectionProperty(\get_class($l), 'logger');
$_logger->setAccessible(true);
$_controller = new \ReflectionProperty(get_class($l), 'controller');
$_controller = new \ReflectionProperty(\get_class($l), 'controller');
$_controller->setAccessible(true);
$this->assertSame($logger, $_logger->getValue($l));
@@ -91,17 +94,17 @@ class ExceptionListenerTest extends TestCase
public function provider()
{
if (!class_exists('Symfony\Component\HttpFoundation\Request')) {
return array(array(null, null));
return [[null, null]];
}
$request = new Request();
$exception = new \Exception('foo');
$event = new GetResponseForExceptionEvent(new TestKernel(), $request, 'foo', $exception);
$event2 = new GetResponseForExceptionEvent(new TestKernelThatThrowsException(), $request, 'foo', $exception);
$event = new GetResponseForExceptionEvent(new TestKernel(), $request, HttpKernelInterface::MASTER_REQUEST, $exception);
$event2 = new GetResponseForExceptionEvent(new TestKernelThatThrowsException(), $request, HttpKernelInterface::MASTER_REQUEST, $exception);
return array(
array($event, $event2),
);
return [
[$event, $event2],
];
}
public function testSubRequestFormat()
@@ -109,26 +112,52 @@ class ExceptionListenerTest extends TestCase
$listener = new ExceptionListener('foo', $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock());
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock();
$kernel->expects($this->once())->method('handle')->will($this->returnCallback(function (Request $request) {
$kernel->expects($this->once())->method('handle')->willReturnCallback(function (Request $request) {
return new Response($request->getRequestFormat());
}));
});
$request = Request::create('/');
$request->setRequestFormat('xml');
$event = new GetResponseForExceptionEvent($kernel, $request, 'foo', new \Exception('foo'));
$event = new GetResponseForExceptionEvent($kernel, $request, HttpKernelInterface::MASTER_REQUEST, new \Exception('foo'));
$listener->onKernelException($event);
$response = $event->getResponse();
$this->assertEquals('xml', $response->getContent());
}
public function testCSPHeaderIsRemoved()
{
$dispatcher = new EventDispatcher();
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock();
$kernel->expects($this->once())->method('handle')->willReturnCallback(function (Request $request) {
return new Response($request->getRequestFormat());
});
$listener = new ExceptionListener('foo', $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock(), true);
$dispatcher->addSubscriber($listener);
$request = Request::create('/');
$event = new GetResponseForExceptionEvent($kernel, $request, HttpKernelInterface::MASTER_REQUEST, new \Exception('foo'));
$dispatcher->dispatch(KernelEvents::EXCEPTION, $event);
$response = new Response('', 200, ['content-security-policy' => "style-src 'self'"]);
$this->assertTrue($response->headers->has('content-security-policy'));
$event = new FilterResponseEvent($kernel, $request, HttpKernelInterface::MASTER_REQUEST, $response);
$dispatcher->dispatch(KernelEvents::RESPONSE, $event);
$this->assertFalse($response->headers->has('content-security-policy'), 'CSP header has been removed');
$this->assertFalse($dispatcher->hasListeners(KernelEvents::RESPONSE), 'CSP removal listener has been removed');
}
}
class TestLogger extends Logger implements DebugLoggerInterface
{
public function countErrors()
{
return count($this->logs['critical']);
return \count($this->logs['critical']);
}
}
@@ -12,10 +12,10 @@
namespace Symfony\Component\HttpKernel\Tests\EventListener;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\EventListener\FragmentListener;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\EventListener\FragmentListener;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\UriSigner;
class FragmentListenerTest extends TestCase
@@ -50,11 +50,9 @@ class FragmentListenerTest extends TestCase
$this->assertEquals($expected, $request->attributes->all());
}
/**
* @expectedException \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
*/
public function testAccessDeniedWithNonSafeMethods()
{
$this->expectException('Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException');
$request = Request::create('http://example.com/_fragment', 'POST');
$listener = new FragmentListener(new UriSigner('foo'));
@@ -63,12 +61,10 @@ class FragmentListenerTest extends TestCase
$listener->onKernelRequest($event);
}
/**
* @expectedException \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
*/
public function testAccessDeniedWithWrongSignature()
{
$request = Request::create('http://example.com/_fragment', 'GET', array(), array(), array(), array('REMOTE_ADDR' => '10.0.0.1'));
$this->expectException('Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException');
$request = Request::create('http://example.com/_fragment', 'GET', [], [], [], ['REMOTE_ADDR' => '10.0.0.1']);
$listener = new FragmentListener(new UriSigner('foo'));
$event = $this->createGetResponseEvent($request);
@@ -79,14 +75,14 @@ class FragmentListenerTest extends TestCase
public function testWithSignature()
{
$signer = new UriSigner('foo');
$request = Request::create($signer->sign('http://example.com/_fragment?_path=foo%3Dbar%26_controller%3Dfoo'), 'GET', array(), array(), array(), array('REMOTE_ADDR' => '10.0.0.1'));
$request = Request::create($signer->sign('http://example.com/_fragment?_path=foo%3Dbar%26_controller%3Dfoo'), 'GET', [], [], [], ['REMOTE_ADDR' => '10.0.0.1']);
$listener = new FragmentListener($signer);
$event = $this->createGetResponseEvent($request);
$listener->onKernelRequest($event);
$this->assertEquals(array('foo' => 'bar', '_controller' => 'foo'), $request->attributes->get('_route_params'));
$this->assertEquals(['foo' => 'bar', '_controller' => 'foo'], $request->attributes->get('_route_params'));
$this->assertFalse($request->query->has('_path'));
}
@@ -105,7 +101,7 @@ class FragmentListenerTest extends TestCase
public function testRemovesPathWithControllerNotDefined()
{
$signer = new UriSigner('foo');
$request = Request::create($signer->sign('http://example.com/_fragment?_path=foo%3Dbar'), 'GET', array(), array(), array(), array('REMOTE_ADDR' => '10.0.0.1'));
$request = Request::create($signer->sign('http://example.com/_fragment?_path=foo%3Dbar'), 'GET', [], [], [], ['REMOTE_ADDR' => '10.0.0.1']);
$listener = new FragmentListener($signer);
$event = $this->createGetResponseEvent($request);
@@ -13,9 +13,9 @@ namespace Symfony\Component\HttpKernel\Tests\EventListener;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\EventListener\LocaleListener;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
class LocaleListenerTest extends TestCase
{
@@ -38,8 +38,7 @@ class LocaleListenerTest extends TestCase
public function testLocaleFromRequestAttribute()
{
$request = Request::create('/');
session_name('foo');
$request->cookies->set('foo', 'value');
$request->cookies->set(session_name(), 'value');
$request->attributes->set('_locale', 'es');
$listener = new LocaleListener($this->requestStack, 'fr');
@@ -55,8 +54,8 @@ class LocaleListenerTest extends TestCase
$context = $this->getMockBuilder('Symfony\Component\Routing\RequestContext')->getMock();
$context->expects($this->once())->method('setParameter')->with('_locale', 'es');
$router = $this->getMockBuilder('Symfony\Component\Routing\Router')->setMethods(array('getContext'))->disableOriginalConstructor()->getMock();
$router->expects($this->once())->method('getContext')->will($this->returnValue($context));
$router = $this->getMockBuilder('Symfony\Component\Routing\Router')->setMethods(['getContext'])->disableOriginalConstructor()->getMock();
$router->expects($this->once())->method('getContext')->willReturn($context);
$request = Request::create('/');
@@ -71,13 +70,13 @@ class LocaleListenerTest extends TestCase
$context = $this->getMockBuilder('Symfony\Component\Routing\RequestContext')->getMock();
$context->expects($this->once())->method('setParameter')->with('_locale', 'es');
$router = $this->getMockBuilder('Symfony\Component\Routing\Router')->setMethods(array('getContext'))->disableOriginalConstructor()->getMock();
$router->expects($this->once())->method('getContext')->will($this->returnValue($context));
$router = $this->getMockBuilder('Symfony\Component\Routing\Router')->setMethods(['getContext'])->disableOriginalConstructor()->getMock();
$router->expects($this->once())->method('getContext')->willReturn($context);
$parentRequest = Request::create('/');
$parentRequest->setLocale('es');
$this->requestStack->expects($this->once())->method('getParentRequest')->will($this->returnValue($parentRequest));
$this->requestStack->expects($this->once())->method('getParentRequest')->willReturn($parentRequest);
$event = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\FinishRequestEvent')->disableOriginalConstructor()->getMock();
@@ -13,12 +13,13 @@ namespace Symfony\Component\HttpKernel\Tests\EventListener;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\EventListener\ProfilerListener;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\Event\PostResponseEvent;
use Symfony\Component\HttpKernel\EventListener\ProfilerListener;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\HttpKernel\Profiler\Profile;
class ProfilerListenerTest extends TestCase
{
@@ -27,9 +28,7 @@ class ProfilerListenerTest extends TestCase
*/
public function testKernelTerminate()
{
$profile = $this->getMockBuilder('Symfony\Component\HttpKernel\Profiler\Profile')
->disableOriginalConstructor()
->getMock();
$profile = new Profile('token');
$profiler = $this->getMockBuilder('Symfony\Component\HttpKernel\Profiler\Profiler')
->disableOriginalConstructor()
@@ -37,7 +36,7 @@ class ProfilerListenerTest extends TestCase
$profiler->expects($this->once())
->method('collect')
->will($this->returnValue($profile));
->willReturn($profile);
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock();
@@ -12,13 +12,13 @@
namespace Symfony\Component\HttpKernel\Tests\EventListener;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\EventListener\ResponseListener;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\EventListener\ResponseListener;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventDispatcher;
class ResponseListenerTest extends TestCase
{
@@ -30,7 +30,7 @@ class ResponseListenerTest extends TestCase
{
$this->dispatcher = new EventDispatcher();
$listener = new ResponseListener('UTF-8');
$this->dispatcher->addListener(KernelEvents::RESPONSE, array($listener, 'onKernelResponse'));
$this->dispatcher->addListener(KernelEvents::RESPONSE, [$listener, 'onKernelResponse']);
$this->kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock();
}
@@ -54,7 +54,7 @@ class ResponseListenerTest extends TestCase
public function testFilterSetsNonDefaultCharsetIfNotOverridden()
{
$listener = new ResponseListener('ISO-8859-15');
$this->dispatcher->addListener(KernelEvents::RESPONSE, array($listener, 'onKernelResponse'), 1);
$this->dispatcher->addListener(KernelEvents::RESPONSE, [$listener, 'onKernelResponse'], 1);
$response = new Response('foo');
@@ -67,7 +67,7 @@ class ResponseListenerTest extends TestCase
public function testFilterDoesNothingIfCharsetIsOverridden()
{
$listener = new ResponseListener('ISO-8859-15');
$this->dispatcher->addListener(KernelEvents::RESPONSE, array($listener, 'onKernelResponse'), 1);
$this->dispatcher->addListener(KernelEvents::RESPONSE, [$listener, 'onKernelResponse'], 1);
$response = new Response('foo');
$response->setCharset('ISO-8859-1');
@@ -81,7 +81,7 @@ class ResponseListenerTest extends TestCase
public function testFiltersSetsNonDefaultCharsetIfNotOverriddenOnNonTextContentType()
{
$listener = new ResponseListener('ISO-8859-15');
$this->dispatcher->addListener(KernelEvents::RESPONSE, array($listener, 'onKernelResponse'), 1);
$this->dispatcher->addListener(KernelEvents::RESPONSE, [$listener, 'onKernelResponse'], 1);
$response = new Response('foo');
$request = Request::create('/');
@@ -12,10 +12,19 @@
namespace Symfony\Component\HttpKernel\Tests\EventListener;
use PHPUnit\Framework\TestCase;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\EventListener\RouterListener;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Controller\ArgumentResolver;
use Symfony\Component\HttpKernel\Controller\ControllerResolver;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\EventListener\ExceptionListener;
use Symfony\Component\HttpKernel\EventListener\RouterListener;
use Symfony\Component\HttpKernel\EventListener\ValidateRequestListener;
use Symfony\Component\HttpKernel\HttpKernel;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\Routing\Exception\NoConfigurationException;
use Symfony\Component\Routing\RequestContext;
class RouterListenerTest extends TestCase
@@ -40,7 +49,7 @@ class RouterListenerTest extends TestCase
$context->setHttpsPort($defaultHttpsPort);
$urlMatcher->expects($this->any())
->method('getContext')
->will($this->returnValue($context));
->willReturn($context);
$listener = new RouterListener($urlMatcher, $this->requestStack);
$event = $this->createGetResponseEventForUri($uri);
@@ -53,12 +62,12 @@ class RouterListenerTest extends TestCase
public function getPortData()
{
return array(
array(80, 443, 'http://localhost/', 80, 443),
array(80, 443, 'http://localhost:90/', 90, 443),
array(80, 443, 'https://localhost/', 80, 443),
array(80, 443, 'https://localhost:90/', 80, 90),
);
return [
[80, 443, 'http://localhost/', 80, 443],
[80, 443, 'http://localhost:90/', 90, 443],
[80, 443, 'https://localhost/', 80, 443],
[80, 443, 'https://localhost:90/', 80, 90],
];
}
/**
@@ -75,11 +84,9 @@ class RouterListenerTest extends TestCase
return new GetResponseEvent($kernel, $request, HttpKernelInterface::MASTER_REQUEST);
}
/**
* @expectedException \InvalidArgumentException
*/
public function testInvalidMatcher()
{
$this->expectException('InvalidArgumentException');
new RouterListener(new \stdClass(), $this->requestStack);
}
@@ -93,7 +100,7 @@ class RouterListenerTest extends TestCase
$requestMatcher->expects($this->once())
->method('matchRequest')
->with($this->isInstanceOf('Symfony\Component\HttpFoundation\Request'))
->will($this->returnValue(array()));
->willReturn([]);
$listener = new RouterListener($requestMatcher, $this->requestStack, new RequestContext());
$listener->onKernelRequest($event);
@@ -109,7 +116,7 @@ class RouterListenerTest extends TestCase
$requestMatcher->expects($this->any())
->method('matchRequest')
->with($this->isInstanceOf('Symfony\Component\HttpFoundation\Request'))
->will($this->returnValue(array()));
->willReturn([]);
$context = new RequestContext();
@@ -134,7 +141,7 @@ class RouterListenerTest extends TestCase
$requestMatcher = $this->getMockBuilder('Symfony\Component\Routing\Matcher\RequestMatcherInterface')->getMock();
$requestMatcher->expects($this->once())
->method('matchRequest')
->will($this->returnValue($parameter));
->willReturn($parameter);
$logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
$logger->expects($this->once())
@@ -150,9 +157,66 @@ class RouterListenerTest extends TestCase
public function getLoggingParameterData()
{
return array(
array(array('_route' => 'foo'), 'Matched route "{route}".', array('route' => 'foo', 'route_parameters' => array('_route' => 'foo'), 'request_uri' => 'http://localhost/', 'method' => 'GET')),
array(array(), 'Matched route "{route}".', array('route' => 'n/a', 'route_parameters' => array(), 'request_uri' => 'http://localhost/', 'method' => 'GET')),
);
return [
[['_route' => 'foo'], 'Matched route "{route}".', ['route' => 'foo', 'route_parameters' => ['_route' => 'foo'], 'request_uri' => 'http://localhost/', 'method' => 'GET']],
[[], 'Matched route "{route}".', ['route' => 'n/a', 'route_parameters' => [], 'request_uri' => 'http://localhost/', 'method' => 'GET']],
];
}
public function testWithBadRequest()
{
$requestStack = new RequestStack();
$requestMatcher = $this->getMockBuilder('Symfony\Component\Routing\Matcher\RequestMatcherInterface')->getMock();
$requestMatcher->expects($this->never())->method('matchRequest');
$dispatcher = new EventDispatcher();
$dispatcher->addSubscriber(new ValidateRequestListener());
$dispatcher->addSubscriber(new RouterListener($requestMatcher, $requestStack, new RequestContext()));
$dispatcher->addSubscriber(new ExceptionListener(function () {
return new Response('Exception handled', 400);
}));
$kernel = new HttpKernel($dispatcher, new ControllerResolver(), $requestStack, new ArgumentResolver());
$request = Request::create('http://localhost/');
$request->headers->set('host', '###');
$response = $kernel->handle($request);
$this->assertSame(400, $response->getStatusCode());
}
public function testNoRoutingConfigurationResponse()
{
$requestStack = new RequestStack();
$requestMatcher = $this->getMockBuilder('Symfony\Component\Routing\Matcher\RequestMatcherInterface')->getMock();
$requestMatcher
->expects($this->once())
->method('matchRequest')
->willThrowException(new NoConfigurationException())
;
$dispatcher = new EventDispatcher();
$dispatcher->addSubscriber(new RouterListener($requestMatcher, $requestStack, new RequestContext()));
$kernel = new HttpKernel($dispatcher, new ControllerResolver(), $requestStack, new ArgumentResolver());
$request = Request::create('http://localhost/');
$response = $kernel->handle($request);
$this->assertSame(404, $response->getStatusCode());
$this->assertStringContainsString('Welcome', $response->getContent());
}
public function testRequestWithBadHost()
{
$this->expectException('Symfony\Component\HttpKernel\Exception\BadRequestHttpException');
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock();
$request = Request::create('http://bad host %22/');
$event = new GetResponseEvent($kernel, $request, HttpKernelInterface::MASTER_REQUEST);
$requestMatcher = $this->getMockBuilder('Symfony\Component\Routing\Matcher\RequestMatcherInterface')->getMock();
$listener = new RouterListener($requestMatcher, $this->requestStack, new RequestContext());
$listener->onKernelRequest($event);
}
}
@@ -12,14 +12,14 @@
namespace Symfony\Component\HttpKernel\Tests\EventListener;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\HttpCache\Esi;
use Symfony\Component\HttpKernel\EventListener\SurrogateListener;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\EventListener\SurrogateListener;
use Symfony\Component\HttpKernel\HttpCache\Esi;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\KernelEvents;
class SurrogateListenerTest extends TestCase
{
@@ -30,7 +30,7 @@ class SurrogateListenerTest extends TestCase
$response = new Response('foo <esi:include src="" />');
$listener = new SurrogateListener(new Esi());
$dispatcher->addListener(KernelEvents::RESPONSE, array($listener, 'onKernelResponse'));
$dispatcher->addListener(KernelEvents::RESPONSE, [$listener, 'onKernelResponse']);
$event = new FilterResponseEvent($kernel, new Request(), HttpKernelInterface::SUB_REQUEST, $response);
$dispatcher->dispatch(KernelEvents::RESPONSE, $event);
@@ -44,7 +44,7 @@ class SurrogateListenerTest extends TestCase
$response = new Response('foo <esi:include src="" />');
$listener = new SurrogateListener(new Esi());
$dispatcher->addListener(KernelEvents::RESPONSE, array($listener, 'onKernelResponse'));
$dispatcher->addListener(KernelEvents::RESPONSE, [$listener, 'onKernelResponse']);
$event = new FilterResponseEvent($kernel, new Request(), HttpKernelInterface::MASTER_REQUEST, $response);
$dispatcher->dispatch(KernelEvents::RESPONSE, $event);
@@ -58,7 +58,7 @@ class SurrogateListenerTest extends TestCase
$response = new Response('foo');
$listener = new SurrogateListener(new Esi());
$dispatcher->addListener(KernelEvents::RESPONSE, array($listener, 'onKernelResponse'));
$dispatcher->addListener(KernelEvents::RESPONSE, [$listener, 'onKernelResponse']);
$event = new FilterResponseEvent($kernel, new Request(), HttpKernelInterface::MASTER_REQUEST, $response);
$dispatcher->dispatch(KernelEvents::RESPONSE, $event);
@@ -12,11 +12,15 @@
namespace Symfony\Component\HttpKernel\Tests\EventListener;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\DependencyInjection\ServiceSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\EventListener\SessionListener;
use Symfony\Component\HttpKernel\EventListener\TestSessionListener;
use Symfony\Component\HttpKernel\HttpKernelInterface;
/**
* SessionListenerTest.
@@ -39,8 +43,11 @@ class TestSessionListenerTest extends TestCase
protected function setUp()
{
$this->listener = $this->getMockForAbstractClass('Symfony\Component\HttpKernel\EventListener\TestSessionListener');
$this->listener = $this->getMockForAbstractClass('Symfony\Component\HttpKernel\EventListener\AbstractTestSessionListener');
$this->session = $this->getSession();
$this->listener->expects($this->any())
->method('getSession')
->willReturn($this->session);
}
public function testShouldSaveMasterRequestSession()
@@ -62,8 +69,7 @@ class TestSessionListenerTest extends TestCase
{
$this->sessionHasBeenStarted();
$params = session_get_cookie_params();
session_set_cookie_params(0, $params['path'], $params['domain'], $params['secure'], $params['httponly']);
@ini_set('session.cookie_lifetime', 0);
$response = $this->filterResponse(new Request(), HttpKernelInterface::MASTER_REQUEST);
$cookies = $response->headers->getCookies();
@@ -71,6 +77,65 @@ class TestSessionListenerTest extends TestCase
$this->assertEquals(0, reset($cookies)->getExpiresTime());
}
/**
* @requires function \Symfony\Component\HttpFoundation\Session\Session::isEmpty
*/
public function testEmptySessionDoesNotSendCookie()
{
$this->sessionHasBeenStarted();
$this->sessionIsEmpty();
$response = $this->filterResponse(new Request(), HttpKernelInterface::MASTER_REQUEST);
$this->assertSame([], $response->headers->getCookies());
}
public function testEmptySessionWithNewSessionIdDoesSendCookie()
{
$this->sessionHasBeenStarted();
$this->sessionIsEmpty();
$this->fixSessionId('456');
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock();
$request = Request::create('/', 'GET', [], ['MOCKSESSID' => '123']);
$event = new GetResponseEvent($kernel, $request, HttpKernelInterface::MASTER_REQUEST);
$this->listener->onKernelRequest($event);
$response = $this->filterResponse(new Request(), HttpKernelInterface::MASTER_REQUEST);
$this->assertNotEmpty($response->headers->getCookies());
}
/**
* @dataProvider anotherCookieProvider
*/
public function testSessionWithNewSessionIdAndNewCookieDoesNotSendAnotherCookie($existing, array $expected)
{
$this->sessionHasBeenStarted();
$this->sessionIsEmpty();
$this->fixSessionId('456');
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock();
$request = Request::create('/', 'GET', [], ['MOCKSESSID' => '123']);
$event = new GetResponseEvent($kernel, $request, HttpKernelInterface::MASTER_REQUEST);
$this->listener->onKernelRequest($event);
$response = new Response('', 200, ['Set-Cookie' => $existing]);
$response = $this->filterResponse(new Request(), HttpKernelInterface::MASTER_REQUEST, $response);
$this->assertSame($expected, $response->headers->get('Set-Cookie', null, false));
}
public function anotherCookieProvider()
{
return [
'same' => ['MOCKSESSID=789; path=/', ['MOCKSESSID=789; path=/']],
'different domain' => ['MOCKSESSID=789; path=/; domain=example.com', ['MOCKSESSID=789; path=/; domain=example.com', 'MOCKSESSID=456; path=/']],
'different path' => ['MOCKSESSID=789; path=/foo', ['MOCKSESSID=789; path=/foo', 'MOCKSESSID=456; path=/']],
];
}
public function testUnstartedSessionIsNotSave()
{
$this->sessionHasNotBeenStarted();
@@ -79,10 +144,19 @@ class TestSessionListenerTest extends TestCase
$this->filterResponse(new Request());
}
private function filterResponse(Request $request, $type = HttpKernelInterface::MASTER_REQUEST)
public function testDoesNotImplementServiceSubscriberInterface()
{
$this->assertTrue(interface_exists(ServiceSubscriberInterface::class));
$this->assertTrue(class_exists(SessionListener::class));
$this->assertTrue(class_exists(TestSessionListener::class));
$this->assertFalse(is_subclass_of(SessionListener::class, ServiceSubscriberInterface::class), 'Implementing ServiceSubscriberInterface would create a dep on the DI component, which eg Silex cannot afford');
$this->assertFalse(is_subclass_of(TestSessionListener::class, ServiceSubscriberInterface::class, 'Implementing ServiceSubscriberInterface would create a dep on the DI component, which eg Silex cannot afford'));
}
private function filterResponse(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, Response $response = null)
{
$request->setSession($this->session);
$response = new Response();
$response = $response ?: new Response();
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock();
$event = new FilterResponseEvent($kernel, $request, $type, $response);
@@ -109,14 +183,28 @@ class TestSessionListenerTest extends TestCase
{
$this->session->expects($this->once())
->method('isStarted')
->will($this->returnValue(true));
->willReturn(true);
}
private function sessionHasNotBeenStarted()
{
$this->session->expects($this->once())
->method('isStarted')
->will($this->returnValue(false));
->willReturn(false);
}
private function sessionIsEmpty()
{
$this->session->expects($this->once())
->method('isEmpty')
->willReturn(true);
}
private function fixSessionId($sessionId)
{
$this->session->expects($this->any())
->method('getId')
->willReturn($sessionId);
}
private function getSession()
@@ -126,7 +214,7 @@ class TestSessionListenerTest extends TestCase
->getMock();
// set return value for getName()
$mock->expects($this->any())->method('getName')->will($this->returnValue('MOCKSESSID'));
$mock->expects($this->any())->method('getName')->willReturn('MOCKSESSID');
return $mock;
}
@@ -45,13 +45,15 @@ class TranslatorListenerTest extends TestCase
public function testDefaultLocaleIsUsedOnExceptionsInOnKernelRequest()
{
$this->translator
->expects($this->at(0))
->expects($this->exactly(2))
->method('setLocale')
->will($this->throwException(new \InvalidArgumentException()));
$this->translator
->expects($this->at(1))
->method('setLocale')
->with($this->equalTo('en'));
->withConsecutive(
['fr'],
['en']
)
->willReturnOnConsecutiveCalls(
$this->throwException(new \InvalidArgumentException())
);
$event = new GetResponseEvent($this->createHttpKernel(), $this->createRequest('fr'), HttpKernelInterface::MASTER_REQUEST);
$this->listener->onKernelRequest($event);
@@ -82,13 +84,15 @@ class TranslatorListenerTest extends TestCase
public function testDefaultLocaleIsUsedOnExceptionsInOnKernelFinishRequest()
{
$this->translator
->expects($this->at(0))
->expects($this->exactly(2))
->method('setLocale')
->will($this->throwException(new \InvalidArgumentException()));
$this->translator
->expects($this->at(1))
->method('setLocale')
->with($this->equalTo('en'));
->withConsecutive(
['fr'],
['en']
)
->willReturnOnConsecutiveCalls(
$this->throwException(new \InvalidArgumentException())
);
$this->setMasterRequest($this->createRequest('fr'));
$event = new FinishRequestEvent($this->createHttpKernel(), $this->createRequest('de'), HttpKernelInterface::SUB_REQUEST);
@@ -113,6 +117,6 @@ class TranslatorListenerTest extends TestCase
$this->requestStack
->expects($this->any())
->method('getParentRequest')
->will($this->returnValue($request));
->willReturn($request);
}
}
@@ -14,28 +14,31 @@ namespace Symfony\Component\HttpKernel\Tests\EventListener;
use PHPUnit\Framework\TestCase;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\EventListener\ValidateRequestListener;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\EventListener\ValidateRequestListener;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\KernelEvents;
class ValidateRequestListenerTest extends TestCase
{
/**
* @expectedException \Symfony\Component\HttpFoundation\Exception\ConflictingHeadersException
*/
protected function tearDown()
{
Request::setTrustedProxies([], -1);
}
public function testListenerThrowsWhenMasterRequestHasInconsistentClientIps()
{
$this->expectException('Symfony\Component\HttpFoundation\Exception\ConflictingHeadersException');
$dispatcher = new EventDispatcher();
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock();
$request = new Request();
$request->setTrustedProxies(array('1.1.1.1'), -1);
$request->setTrustedProxies(['1.1.1.1'], Request::HEADER_X_FORWARDED_FOR | Request::HEADER_FORWARDED);
$request->server->set('REMOTE_ADDR', '1.1.1.1');
$request->headers->set('FORWARDED', 'for=2.2.2.2');
$request->headers->set('X_FORWARDED_FOR', '3.3.3.3');
$dispatcher->addListener(KernelEvents::REQUEST, array(new ValidateRequestListener(), 'onKernelRequest'));
$dispatcher->addListener(KernelEvents::REQUEST, [new ValidateRequestListener(), 'onKernelRequest']);
$event = new GetResponseEvent($kernel, $request, HttpKernelInterface::MASTER_REQUEST);
$dispatcher->dispatch(KernelEvents::REQUEST, $event);
@@ -9,22 +9,22 @@ class HttpExceptionTest extends TestCase
{
public function headerDataProvider()
{
return array(
array(array('X-Test' => 'Test')),
array(array('X-Test' => 1)),
array(
array(
array('X-Test' => 'Test'),
array('X-Test-2' => 'Test-2'),
),
),
);
return [
[['X-Test' => 'Test']],
[['X-Test' => 1]],
[
[
['X-Test' => 'Test'],
['X-Test-2' => 'Test-2'],
],
],
];
}
public function testHeadersDefault()
{
$exception = $this->createException();
$this->assertSame(array(), $exception->getHeaders());
$this->assertSame([], $exception->getHeaders());
}
/**
@@ -8,8 +8,8 @@ class MethodNotAllowedHttpExceptionTest extends HttpExceptionTest
{
public function testHeadersDefault()
{
$exception = new MethodNotAllowedHttpException(array('GET', 'PUT'));
$this->assertSame(array('Allow' => 'GET, PUT'), $exception->getHeaders());
$exception = new MethodNotAllowedHttpException(['GET', 'PUT']);
$this->assertSame(['Allow' => 'GET, PUT'], $exception->getHeaders());
}
/**
@@ -17,7 +17,7 @@ class MethodNotAllowedHttpExceptionTest extends HttpExceptionTest
*/
public function testHeadersSetter($headers)
{
$exception = new MethodNotAllowedHttpException(array('GET'));
$exception = new MethodNotAllowedHttpException(['GET']);
$exception->setHeaders($headers);
$this->assertSame($headers, $exception->getHeaders());
}
@@ -9,7 +9,7 @@ class ServiceUnavailableHttpExceptionTest extends HttpExceptionTest
public function testHeadersDefaultRetryAfter()
{
$exception = new ServiceUnavailableHttpException(10);
$this->assertSame(array('Retry-After' => 10), $exception->getHeaders());
$this->assertSame(['Retry-After' => 10], $exception->getHeaders());
}
/**
@@ -9,7 +9,7 @@ class TooManyRequestsHttpExceptionTest extends HttpExceptionTest
public function testHeadersDefaultRertyAfter()
{
$exception = new TooManyRequestsHttpException(10);
$this->assertSame(array('Retry-After' => 10), $exception->getHeaders());
$this->assertSame(['Retry-After' => 10], $exception->getHeaders());
}
/**
@@ -9,7 +9,7 @@ class UnauthorizedHttpExceptionTest extends HttpExceptionTest
public function testHeadersDefault()
{
$exception = new UnauthorizedHttpException('Challenge');
$this->assertSame(array('WWW-Authenticate' => 'Challenge'), $exception->getHeaders());
$this->assertSame(['WWW-Authenticate' => 'Challenge'], $exception->getHeaders());
}
/**
@@ -6,21 +6,6 @@ use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
class UnprocessableEntityHttpExceptionTest extends HttpExceptionTest
{
/**
* Test that setting the headers using the setter function
* is working as expected.
*
* @param array $headers The headers to set
*
* @dataProvider headerDataProvider
*/
public function testHeadersSetter($headers)
{
$exception = new UnprocessableEntityHttpException(10);
$exception->setHeaders($headers);
$this->assertSame($headers, $exception->getHeaders());
}
protected function createException()
{
return new UnprocessableEntityHttpException();
@@ -6,17 +6,7 @@ use Symfony\Component\HttpKernel\Exception\UnsupportedMediaTypeHttpException;
class UnsupportedMediaTypeHttpExceptionTest extends HttpExceptionTest
{
/**
* @dataProvider headerDataProvider
*/
public function testHeadersSetter($headers)
{
$exception = new UnsupportedMediaTypeHttpException(10);
$exception->setHeaders($headers);
$this->assertSame($headers, $exception->getHeaders());
}
protected function createException($headers = array())
protected function createException()
{
return new UnsupportedMediaTypeHttpException();
}
@@ -11,14 +11,14 @@
namespace Symfony\Component\HttpKernel\Tests\Fixtures\_123;
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\HttpKernel\Kernel;
class Kernel123 extends Kernel
{
public function registerBundles()
{
return array();
return [];
}
public function registerContainerConfiguration(LoaderInterface $loader)
@@ -13,7 +13,7 @@ namespace Symfony\Component\HttpKernel\Tests\Fixtures\Controller;
class NullableController
{
public function action(?string $foo, ?\stdClass $bar, ?string $baz = 'value', $mandatory)
public function action(?string $foo, ?\stdClass $bar, ?string $baz = 'value', string $last = '')
{
}
}
@@ -29,6 +29,11 @@ class CloneVarDataCollector extends DataCollector
$this->data = $this->cloneVar($this->varToClone);
}
public function reset()
{
$this->data = [];
}
public function getData()
{
return $this->data;
@@ -1,22 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Tests\Fixtures\ExtensionLoadedBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\Extension;
class ExtensionLoadedExtension extends Extension
{
public function load(array $configs, ContainerBuilder $container)
{
}
}
@@ -1,18 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Tests\Fixtures\ExtensionLoadedBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class ExtensionLoadedBundle extends Bundle
{
}
@@ -1,17 +0,0 @@
<?php
namespace Symfony\Component\HttpKernel\Tests\Fixtures\ExtensionPresentBundle\Command;
use Symfony\Component\Console\Command\Command;
/**
* This command has a required parameter on the constructor and will be ignored by the default Bundle implementation.
*
* @see Bundle::registerCommands()
*/
class BarCommand extends Command
{
public function __construct($example, $name = 'bar')
{
}
}
@@ -11,8 +11,8 @@
namespace Symfony\Component\HttpKernel\Tests\Fixtures;
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\HttpKernel\Kernel;
class KernelForOverrideName extends Kernel
{
@@ -11,8 +11,8 @@
namespace Symfony\Component\HttpKernel\Tests\Fixtures;
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\HttpKernel\Kernel;
class KernelForTest extends Kernel
{
@@ -23,7 +23,7 @@ class KernelForTest extends Kernel
public function registerBundles()
{
return array();
return [];
}
public function registerContainerConfiguration(LoaderInterface $loader)
@@ -34,4 +34,9 @@ class KernelForTest extends Kernel
{
return $this->booted;
}
public function getProjectDir()
{
return __DIR__;
}
}
@@ -1,28 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Tests\Fixtures;
use Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcherInterface;
use Symfony\Component\EventDispatcher\EventDispatcher;
class TestEventDispatcher extends EventDispatcher implements TraceableEventDispatcherInterface
{
public function getCalledListeners()
{
return array('foo');
}
public function getNotCalledListeners()
{
return array('bar');
}
}
@@ -12,10 +12,10 @@
namespace Symfony\Component\HttpKernel\Tests\Fragment;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Controller\ControllerReference;
use Symfony\Component\HttpKernel\Fragment\EsiFragmentRenderer;
use Symfony\Component\HttpKernel\HttpCache\Esi;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\UriSigner;
class EsiFragmentRendererTest extends TestCase
@@ -34,7 +34,15 @@ class EsiFragmentRendererTest extends TestCase
{
$strategy = new EsiFragmentRenderer(new Esi(), $this->getInlineStrategy(true), new UriSigner('foo'));
$request = Request::create('/');
$reference = new ControllerReference('main_controller', array('foo' => array('a' => array(), 'b' => new \stdClass())), array());
$reference = new ControllerReference('main_controller', ['foo' => new \stdClass()], []);
$strategy->render($reference, $request);
}
public function testRenderFallbackWithScalarIsNotDeprecated()
{
$strategy = new EsiFragmentRenderer(new Esi(), $this->getInlineStrategy(true), new UriSigner('foo'));
$request = Request::create('/');
$reference = new ControllerReference('main_controller', ['foo' => [true]], []);
$strategy->render($reference, $request);
}
@@ -47,8 +55,8 @@ class EsiFragmentRendererTest extends TestCase
$request->headers->set('Surrogate-Capability', 'ESI/1.0');
$this->assertEquals('<esi:include src="/" />', $strategy->render('/', $request)->getContent());
$this->assertEquals("<esi:comment text=\"This is a comment\" />\n<esi:include src=\"/\" />", $strategy->render('/', $request, array('comment' => 'This is a comment'))->getContent());
$this->assertEquals('<esi:include src="/" alt="foo" />', $strategy->render('/', $request, array('alt' => 'foo'))->getContent());
$this->assertEquals("<esi:comment text=\"This is a comment\" />\n<esi:include src=\"/\" />", $strategy->render('/', $request, ['comment' => 'This is a comment'])->getContent());
$this->assertEquals('<esi:include src="/" alt="foo" />', $strategy->render('/', $request, ['alt' => 'foo'])->getContent());
}
public function testRenderControllerReference()
@@ -60,20 +68,18 @@ class EsiFragmentRendererTest extends TestCase
$request->setLocale('fr');
$request->headers->set('Surrogate-Capability', 'ESI/1.0');
$reference = new ControllerReference('main_controller', array(), array());
$altReference = new ControllerReference('alt_controller', array(), array());
$reference = new ControllerReference('main_controller', [], []);
$altReference = new ControllerReference('alt_controller', [], []);
$this->assertEquals(
'<esi:include src="/_fragment?_path=_format%3Dhtml%26_locale%3Dfr%26_controller%3Dmain_controller&_hash=Jz1P8NErmhKTeI6onI1EdAXTB85359MY3RIk5mSJ60w%3D" alt="/_fragment?_path=_format%3Dhtml%26_locale%3Dfr%26_controller%3Dalt_controller&_hash=iPJEdRoUpGrM1ztqByiorpfMPtiW%2FOWwdH1DBUXHhEc%3D" />',
$strategy->render($reference, $request, array('alt' => $altReference))->getContent()
'<esi:include src="/_fragment?_hash=Jz1P8NErmhKTeI6onI1EdAXTB85359MY3RIk5mSJ60w%3D&_path=_format%3Dhtml%26_locale%3Dfr%26_controller%3Dmain_controller" alt="/_fragment?_hash=iPJEdRoUpGrM1ztqByiorpfMPtiW%2FOWwdH1DBUXHhEc%3D&_path=_format%3Dhtml%26_locale%3Dfr%26_controller%3Dalt_controller" />',
$strategy->render($reference, $request, ['alt' => $altReference])->getContent()
);
}
/**
* @expectedException \LogicException
*/
public function testRenderControllerReferenceWithoutSignerThrowsException()
{
$this->expectException('LogicException');
$strategy = new EsiFragmentRenderer(new Esi(), $this->getInlineStrategy());
$request = Request::create('/');
@@ -83,18 +89,16 @@ class EsiFragmentRendererTest extends TestCase
$strategy->render(new ControllerReference('main_controller'), $request);
}
/**
* @expectedException \LogicException
*/
public function testRenderAltControllerReferenceWithoutSignerThrowsException()
{
$this->expectException('LogicException');
$strategy = new EsiFragmentRenderer(new Esi(), $this->getInlineStrategy());
$request = Request::create('/');
$request->setLocale('fr');
$request->headers->set('Surrogate-Capability', 'ESI/1.0');
$strategy->render('/', $request, array('alt' => new ControllerReference('alt_controller')));
$strategy->render('/', $request, ['alt' => new ControllerReference('alt_controller')]);
}
private function getInlineStrategy($called = false)
@@ -12,9 +12,9 @@
namespace Symfony\Component\HttpKernel\Tests\Fragment;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\Fragment\FragmentHandler;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Fragment\FragmentHandler;
/**
* @group time-sensitive
@@ -32,35 +32,29 @@ class FragmentHandlerTest extends TestCase
$this->requestStack
->expects($this->any())
->method('getCurrentRequest')
->will($this->returnValue(Request::create('/')))
->willReturn(Request::create('/'))
;
}
/**
* @expectedException \InvalidArgumentException
*/
public function testRenderWhenRendererDoesNotExist()
{
$this->expectException('InvalidArgumentException');
$handler = new FragmentHandler($this->requestStack);
$handler->render('/', 'foo');
}
/**
* @expectedException \InvalidArgumentException
*/
public function testRenderWithUnknownRenderer()
{
$this->expectException('InvalidArgumentException');
$handler = $this->getHandler($this->returnValue(new Response('foo')));
$handler->render('/', 'bar');
}
/**
* @expectedException \RuntimeException
* @expectedExceptionMessage Error when rendering "http://localhost/" (Status code is 404).
*/
public function testDeliverWithUnsuccessfulResponse()
{
$this->expectException('RuntimeException');
$this->expectExceptionMessage('Error when rendering "http://localhost/" (Status code is 404).');
$handler = $this->getHandler($this->returnValue(new Response('foo', 404)));
$handler->render('/', 'foo');
@@ -68,18 +62,18 @@ class FragmentHandlerTest extends TestCase
public function testRender()
{
$handler = $this->getHandler($this->returnValue(new Response('foo')), array('/', Request::create('/'), array('foo' => 'foo', 'ignore_errors' => true)));
$handler = $this->getHandler($this->returnValue(new Response('foo')), ['/', Request::create('/'), ['foo' => 'foo', 'ignore_errors' => true]]);
$this->assertEquals('foo', $handler->render('/', 'foo', array('foo' => 'foo')));
$this->assertEquals('foo', $handler->render('/', 'foo', ['foo' => 'foo']));
}
protected function getHandler($returnValue, $arguments = array())
protected function getHandler($returnValue, $arguments = [])
{
$renderer = $this->getMockBuilder('Symfony\Component\HttpKernel\Fragment\FragmentRendererInterface')->getMock();
$renderer
->expects($this->any())
->method('getName')
->will($this->returnValue('foo'))
->willReturn('foo')
;
$e = $renderer
->expects($this->any())
@@ -88,7 +82,7 @@ class FragmentHandlerTest extends TestCase
;
if ($arguments) {
call_user_func_array(array($e, 'with'), $arguments);
\call_user_func_array([$e, 'with'], $arguments);
}
$handler = new FragmentHandler($this->requestStack);
@@ -12,27 +12,25 @@
namespace Symfony\Component\HttpKernel\Tests\Fragment;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Controller\ControllerReference;
use Symfony\Component\HttpKernel\Fragment\HIncludeFragmentRenderer;
use Symfony\Component\HttpKernel\UriSigner;
use Symfony\Component\HttpFoundation\Request;
class HIncludeFragmentRendererTest extends TestCase
{
/**
* @expectedException \LogicException
*/
public function testRenderExceptionWhenControllerAndNoSigner()
{
$this->expectException('LogicException');
$strategy = new HIncludeFragmentRenderer();
$strategy->render(new ControllerReference('main_controller', array(), array()), Request::create('/'));
$strategy->render(new ControllerReference('main_controller', [], []), Request::create('/'));
}
public function testRenderWithControllerAndSigner()
{
$strategy = new HIncludeFragmentRenderer(null, new UriSigner('foo'));
$this->assertEquals('<hx:include src="/_fragment?_path=_format%3Dhtml%26_locale%3Den%26_controller%3Dmain_controller&amp;_hash=BP%2BOzCD5MRUI%2BHJpgPDOmoju00FnzLhP3TGcSHbbBLs%3D"></hx:include>', $strategy->render(new ControllerReference('main_controller', array(), array()), Request::create('/'))->getContent());
$this->assertEquals('<hx:include src="/_fragment?_hash=BP%2BOzCD5MRUI%2BHJpgPDOmoju00FnzLhP3TGcSHbbBLs%3D&amp;_path=_format%3Dhtml%26_locale%3Den%26_controller%3Dmain_controller"></hx:include>', $strategy->render(new ControllerReference('main_controller', [], []), Request::create('/'))->getContent());
}
public function testRenderWithUri()
@@ -48,30 +46,30 @@ class HIncludeFragmentRendererTest extends TestCase
{
// only default
$strategy = new HIncludeFragmentRenderer();
$this->assertEquals('<hx:include src="/foo">default</hx:include>', $strategy->render('/foo', Request::create('/'), array('default' => 'default'))->getContent());
$this->assertEquals('<hx:include src="/foo">default</hx:include>', $strategy->render('/foo', Request::create('/'), ['default' => 'default'])->getContent());
// only global default
$strategy = new HIncludeFragmentRenderer(null, null, 'global_default');
$this->assertEquals('<hx:include src="/foo">global_default</hx:include>', $strategy->render('/foo', Request::create('/'), array())->getContent());
$this->assertEquals('<hx:include src="/foo">global_default</hx:include>', $strategy->render('/foo', Request::create('/'), [])->getContent());
// global default and default
$strategy = new HIncludeFragmentRenderer(null, null, 'global_default');
$this->assertEquals('<hx:include src="/foo">default</hx:include>', $strategy->render('/foo', Request::create('/'), array('default' => 'default'))->getContent());
$this->assertEquals('<hx:include src="/foo">default</hx:include>', $strategy->render('/foo', Request::create('/'), ['default' => 'default'])->getContent());
}
public function testRenderWithAttributesOptions()
{
// with id
$strategy = new HIncludeFragmentRenderer();
$this->assertEquals('<hx:include src="/foo" id="bar">default</hx:include>', $strategy->render('/foo', Request::create('/'), array('default' => 'default', 'id' => 'bar'))->getContent());
$this->assertEquals('<hx:include src="/foo" id="bar">default</hx:include>', $strategy->render('/foo', Request::create('/'), ['default' => 'default', 'id' => 'bar'])->getContent());
// with attributes
$strategy = new HIncludeFragmentRenderer();
$this->assertEquals('<hx:include src="/foo" p1="v1" p2="v2">default</hx:include>', $strategy->render('/foo', Request::create('/'), array('default' => 'default', 'attributes' => array('p1' => 'v1', 'p2' => 'v2')))->getContent());
$this->assertEquals('<hx:include src="/foo" p1="v1" p2="v2">default</hx:include>', $strategy->render('/foo', Request::create('/'), ['default' => 'default', 'attributes' => ['p1' => 'v1', 'p2' => 'v2']])->getContent());
// with id & attributes
$strategy = new HIncludeFragmentRenderer();
$this->assertEquals('<hx:include src="/foo" p1="v1" p2="v2" id="bar">default</hx:include>', $strategy->render('/foo', Request::create('/'), array('default' => 'default', 'id' => 'bar', 'attributes' => array('p1' => 'v1', 'p2' => 'v2')))->getContent());
$this->assertEquals('<hx:include src="/foo" p1="v1" p2="v2" id="bar">default</hx:include>', $strategy->render('/foo', Request::create('/'), ['default' => 'default', 'id' => 'bar', 'attributes' => ['p1' => 'v1', 'p2' => 'v2']])->getContent());
}
public function testRenderWithDefaultText()
@@ -80,10 +78,23 @@ class HIncludeFragmentRendererTest extends TestCase
$engine->expects($this->once())
->method('exists')
->with('default')
->will($this->throwException(new \InvalidArgumentException()));
->willThrowException(new \InvalidArgumentException());
// only default
$strategy = new HIncludeFragmentRenderer($engine);
$this->assertEquals('<hx:include src="/foo">default</hx:include>', $strategy->render('/foo', Request::create('/'), array('default' => 'default'))->getContent());
$this->assertEquals('<hx:include src="/foo">default</hx:include>', $strategy->render('/foo', Request::create('/'), ['default' => 'default'])->getContent());
}
public function testRenderWithEngineAndDefaultText()
{
$engine = $this->getMockBuilder('Symfony\\Component\\Templating\\EngineInterface')->getMock();
$engine->expects($this->once())
->method('exists')
->with('loading...')
->willThrowException(new \RuntimeException());
// only default
$strategy = new HIncludeFragmentRenderer($engine);
$this->assertEquals('<hx:include src="/foo">loading...</hx:include>', $strategy->render('/foo', Request::create('/'), ['default' => 'loading...'])->getContent());
}
}
@@ -12,31 +12,19 @@
namespace Symfony\Component\HttpKernel\Tests\Fragment;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\Controller\ArgumentResolver;
use Symfony\Component\HttpKernel\Controller\ControllerResolverInterface;
use Symfony\Component\HttpKernel\Controller\ControllerReference;
use Symfony\Component\HttpKernel\HttpKernel;
use Symfony\Component\HttpKernel\Fragment\InlineFragmentRenderer;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Controller\ArgumentResolver;
use Symfony\Component\HttpKernel\Controller\ControllerReference;
use Symfony\Component\HttpKernel\Controller\ControllerResolverInterface;
use Symfony\Component\HttpKernel\Fragment\InlineFragmentRenderer;
use Symfony\Component\HttpKernel\HttpKernel;
use Symfony\Component\HttpKernel\KernelEvents;
class InlineFragmentRendererTest extends TestCase
{
private $originalTrustedHeaderName;
protected function setUp()
{
$this->originalTrustedHeaderName = Request::getTrustedHeaderName(Request::HEADER_CLIENT_IP);
}
protected function tearDown()
{
Request::setTrustedHeaderName(Request::HEADER_CLIENT_IP, $this->originalTrustedHeaderName);
}
public function testRender()
{
$strategy = new InlineFragmentRenderer($this->getKernel($this->returnValue(new Response('foo'))));
@@ -48,7 +36,7 @@ class InlineFragmentRendererTest extends TestCase
{
$strategy = new InlineFragmentRenderer($this->getKernel($this->returnValue(new Response('foo'))));
$this->assertEquals('foo', $strategy->render(new ControllerReference('main_controller', array(), array()), Request::create('/'))->getContent());
$this->assertEquals('foo', $strategy->render(new ControllerReference('main_controller', [], []), Request::create('/'))->getContent());
}
public function testRenderWithObjectsAsAttributes()
@@ -56,13 +44,15 @@ class InlineFragmentRendererTest extends TestCase
$object = new \stdClass();
$subRequest = Request::create('/_fragment?_path=_format%3Dhtml%26_locale%3Den%26_controller%3Dmain_controller');
$subRequest->attributes->replace(array('object' => $object, '_format' => 'html', '_controller' => 'main_controller', '_locale' => 'en'));
$subRequest->headers->set('x-forwarded-for', array('127.0.0.1'));
$subRequest->attributes->replace(['object' => $object, '_format' => 'html', '_controller' => 'main_controller', '_locale' => 'en']);
$subRequest->headers->set('x-forwarded-for', ['127.0.0.1']);
$subRequest->headers->set('forwarded', ['for="127.0.0.1";host="localhost";proto=http']);
$subRequest->server->set('HTTP_X_FORWARDED_FOR', '127.0.0.1');
$subRequest->server->set('HTTP_FORWARDED', 'for="127.0.0.1";host="localhost";proto=http');
$strategy = new InlineFragmentRenderer($this->getKernelExpectingRequest($subRequest));
$this->assertSame('foo', $strategy->render(new ControllerReference('main_controller', array('object' => $object), array()), Request::create('/'))->getContent());
$this->assertSame('foo', $strategy->render(new ControllerReference('main_controller', ['object' => $object], []), Request::create('/'))->getContent());
}
/**
@@ -70,19 +60,19 @@ class InlineFragmentRendererTest extends TestCase
*/
public function testRenderWithObjectsAsAttributesPassedAsObjectsInTheControllerLegacy()
{
$resolver = $this->getMockBuilder('Symfony\\Component\\HttpKernel\\Controller\\ControllerResolver')->setMethods(array('getController'))->getMock();
$resolver = $this->getMockBuilder('Symfony\\Component\\HttpKernel\\Controller\\ControllerResolver')->setMethods(['getController'])->getMock();
$resolver
->expects($this->once())
->method('getController')
->will($this->returnValue(function (\stdClass $object, Bar $object1) {
->willReturn(function (\stdClass $object, Bar $object1) {
return new Response($object1->getBar());
}))
})
;
$kernel = new HttpKernel(new EventDispatcher(), $resolver, new RequestStack());
$renderer = new InlineFragmentRenderer($kernel);
$response = $renderer->render(new ControllerReference('main_controller', array('object' => new \stdClass(), 'object1' => new Bar()), array()), Request::create('/'));
$response = $renderer->render(new ControllerReference('main_controller', ['object' => new \stdClass(), 'object1' => new Bar()], []), Request::create('/'));
$this->assertEquals('bar', $response->getContent());
}
@@ -95,31 +85,35 @@ class InlineFragmentRendererTest extends TestCase
$resolver
->expects($this->once())
->method('getController')
->will($this->returnValue(function (\stdClass $object, Bar $object1) {
->willReturn(function (\stdClass $object, Bar $object1) {
return new Response($object1->getBar());
}))
})
;
$kernel = new HttpKernel(new EventDispatcher(), $resolver, new RequestStack(), new ArgumentResolver());
$renderer = new InlineFragmentRenderer($kernel);
$response = $renderer->render(new ControllerReference('main_controller', array('object' => new \stdClass(), 'object1' => new Bar()), array()), Request::create('/'));
$response = $renderer->render(new ControllerReference('main_controller', ['object' => new \stdClass(), 'object1' => new Bar()], []), Request::create('/'));
$this->assertEquals('bar', $response->getContent());
}
public function testRenderWithTrustedHeaderDisabled()
{
Request::setTrustedHeaderName(Request::HEADER_CLIENT_IP, '');
Request::setTrustedProxies([], 0);
$strategy = new InlineFragmentRenderer($this->getKernelExpectingRequest(Request::create('/')));
$expectedSubRequest = Request::create('/');
$expectedSubRequest->headers->set('x-forwarded-for', ['127.0.0.1']);
$expectedSubRequest->server->set('HTTP_X_FORWARDED_FOR', '127.0.0.1');
$strategy = new InlineFragmentRenderer($this->getKernelExpectingRequest($expectedSubRequest));
$this->assertSame('foo', $strategy->render('/', Request::create('/'))->getContent());
Request::setTrustedProxies([], -1);
}
/**
* @expectedException \RuntimeException
*/
public function testRenderExceptionNoIgnoreErrors()
{
$this->expectException('RuntimeException');
$dispatcher = $this->getMockBuilder('Symfony\Component\EventDispatcher\EventDispatcherInterface')->getMock();
$dispatcher->expects($this->never())->method('dispatch');
@@ -135,7 +129,7 @@ class InlineFragmentRendererTest extends TestCase
$strategy = new InlineFragmentRenderer($this->getKernel($this->throwException(new \RuntimeException('foo'))), $dispatcher);
$this->assertEmpty($strategy->render('/', Request::create('/'), array('ignore_errors' => true))->getContent());
$this->assertEmpty($strategy->render('/', Request::create('/'), ['ignore_errors' => true])->getContent());
}
public function testRenderExceptionIgnoreErrorsWithAlt()
@@ -145,7 +139,7 @@ class InlineFragmentRendererTest extends TestCase
$this->returnValue(new Response('bar'))
)));
$this->assertEquals('bar', $strategy->render('/', Request::create('/'), array('ignore_errors' => true, 'alt' => '/foo'))->getContent());
$this->assertEquals('bar', $strategy->render('/', Request::create('/'), ['ignore_errors' => true, 'alt' => '/foo'])->getContent());
}
private function getKernel($returnValue)
@@ -166,18 +160,18 @@ class InlineFragmentRendererTest extends TestCase
$controllerResolver
->expects($this->once())
->method('getController')
->will($this->returnValue(function () {
->willReturn(function () {
ob_start();
echo 'bar';
throw new \RuntimeException();
}))
})
;
$argumentResolver = $this->getMockBuilder('Symfony\\Component\\HttpKernel\\Controller\\ArgumentResolverInterface')->getMock();
$argumentResolver
->expects($this->once())
->method('getArguments')
->will($this->returnValue(array()))
->willReturn([])
;
$kernel = new HttpKernel(new EventDispatcher(), $controllerResolver, new RequestStack(), $argumentResolver);
@@ -188,20 +182,42 @@ class InlineFragmentRendererTest extends TestCase
echo 'Foo';
// simulate a sub-request with output buffering and an exception
$renderer->render('/', Request::create('/'), array('ignore_errors' => true));
$renderer->render('/', Request::create('/'), ['ignore_errors' => true]);
$this->assertEquals('Foo', ob_get_clean());
}
public function testLocaleAndFormatAreIsKeptInSubrequest()
{
$expectedSubRequest = Request::create('/');
$expectedSubRequest->attributes->set('_format', 'foo');
$expectedSubRequest->setLocale('fr');
if (Request::HEADER_X_FORWARDED_FOR & Request::getTrustedHeaderSet()) {
$expectedSubRequest->headers->set('x-forwarded-for', ['127.0.0.1']);
$expectedSubRequest->server->set('HTTP_X_FORWARDED_FOR', '127.0.0.1');
}
$expectedSubRequest->headers->set('forwarded', ['for="127.0.0.1";host="localhost";proto=http']);
$expectedSubRequest->server->set('HTTP_FORWARDED', 'for="127.0.0.1";host="localhost";proto=http');
$strategy = new InlineFragmentRenderer($this->getKernelExpectingRequest($expectedSubRequest));
$request = Request::create('/');
$request->attributes->set('_format', 'foo');
$request->setLocale('fr');
$strategy->render('/', $request);
}
public function testESIHeaderIsKeptInSubrequest()
{
$expectedSubRequest = Request::create('/');
$expectedSubRequest->headers->set('Surrogate-Capability', 'abc="ESI/1.0"');
if (Request::getTrustedHeaderName(Request::HEADER_CLIENT_IP)) {
$expectedSubRequest->headers->set('x-forwarded-for', array('127.0.0.1'));
if (Request::HEADER_X_FORWARDED_FOR & Request::getTrustedHeaderSet()) {
$expectedSubRequest->headers->set('x-forwarded-for', ['127.0.0.1']);
$expectedSubRequest->server->set('HTTP_X_FORWARDED_FOR', '127.0.0.1');
}
$expectedSubRequest->headers->set('forwarded', ['for="127.0.0.1";host="localhost";proto=http']);
$expectedSubRequest->server->set('HTTP_FORWARDED', 'for="127.0.0.1";host="localhost";proto=http');
$strategy = new InlineFragmentRenderer($this->getKernelExpectingRequest($expectedSubRequest));
@@ -212,27 +228,68 @@ class InlineFragmentRendererTest extends TestCase
public function testESIHeaderIsKeptInSubrequestWithTrustedHeaderDisabled()
{
$trustedHeaderName = Request::getTrustedHeaderName(Request::HEADER_CLIENT_IP);
Request::setTrustedHeaderName(Request::HEADER_CLIENT_IP, '');
Request::setTrustedProxies([], Request::HEADER_FORWARDED);
$this->testESIHeaderIsKeptInSubrequest();
Request::setTrustedHeaderName(Request::HEADER_CLIENT_IP, $trustedHeaderName);
Request::setTrustedProxies([], -1);
}
public function testHeadersPossiblyResultingIn304AreNotAssignedToSubrequest()
{
$expectedSubRequest = Request::create('/');
if (Request::getTrustedHeaderName(Request::HEADER_CLIENT_IP)) {
$expectedSubRequest->headers->set('x-forwarded-for', array('127.0.0.1'));
$expectedSubRequest->server->set('HTTP_X_FORWARDED_FOR', '127.0.0.1');
}
$expectedSubRequest->headers->set('x-forwarded-for', ['127.0.0.1']);
$expectedSubRequest->headers->set('forwarded', ['for="127.0.0.1";host="localhost";proto=http']);
$expectedSubRequest->server->set('HTTP_X_FORWARDED_FOR', '127.0.0.1');
$expectedSubRequest->server->set('HTTP_FORWARDED', 'for="127.0.0.1";host="localhost";proto=http');
$strategy = new InlineFragmentRenderer($this->getKernelExpectingRequest($expectedSubRequest));
$request = Request::create('/', 'GET', array(), array(), array(), array('HTTP_IF_MODIFIED_SINCE' => 'Fri, 01 Jan 2016 00:00:00 GMT', 'HTTP_IF_NONE_MATCH' => '*'));
$request = Request::create('/', 'GET', [], [], [], ['HTTP_IF_MODIFIED_SINCE' => 'Fri, 01 Jan 2016 00:00:00 GMT', 'HTTP_IF_NONE_MATCH' => '*']);
$strategy->render('/', $request);
}
public function testFirstTrustedProxyIsSetAsRemote()
{
Request::setTrustedProxies(['1.1.1.1'], -1);
$expectedSubRequest = Request::create('/');
$expectedSubRequest->headers->set('Surrogate-Capability', 'abc="ESI/1.0"');
$expectedSubRequest->server->set('REMOTE_ADDR', '127.0.0.1');
$expectedSubRequest->headers->set('x-forwarded-for', ['127.0.0.1']);
$expectedSubRequest->headers->set('forwarded', ['for="127.0.0.1";host="localhost";proto=http']);
$expectedSubRequest->server->set('HTTP_X_FORWARDED_FOR', '127.0.0.1');
$expectedSubRequest->server->set('HTTP_FORWARDED', 'for="127.0.0.1";host="localhost";proto=http');
$strategy = new InlineFragmentRenderer($this->getKernelExpectingRequest($expectedSubRequest));
$request = Request::create('/');
$request->headers->set('Surrogate-Capability', 'abc="ESI/1.0"');
$strategy->render('/', $request);
Request::setTrustedProxies([], -1);
}
public function testIpAddressOfRangedTrustedProxyIsSetAsRemote()
{
$expectedSubRequest = Request::create('/');
$expectedSubRequest->headers->set('Surrogate-Capability', 'abc="ESI/1.0"');
$expectedSubRequest->server->set('REMOTE_ADDR', '127.0.0.1');
$expectedSubRequest->headers->set('x-forwarded-for', ['127.0.0.1']);
$expectedSubRequest->headers->set('forwarded', ['for="127.0.0.1";host="localhost";proto=http']);
$expectedSubRequest->server->set('HTTP_X_FORWARDED_FOR', '127.0.0.1');
$expectedSubRequest->server->set('HTTP_FORWARDED', 'for="127.0.0.1";host="localhost";proto=http');
Request::setTrustedProxies(['1.1.1.1/24'], -1);
$strategy = new InlineFragmentRenderer($this->getKernelExpectingRequest($expectedSubRequest));
$request = Request::create('/');
$request->headers->set('Surrogate-Capability', 'abc="ESI/1.0"');
$strategy->render('/', $request);
Request::setTrustedProxies([], -1);
}
/**
* Creates a Kernel expecting a request equals to $request
* Allows delta in comparison in case REQUEST_TIME changed by 1 second.
@@ -35,14 +35,14 @@ class RoutableFragmentRendererTest extends TestCase
public function getGenerateFragmentUriData()
{
return array(
array('/_fragment?_path=_format%3Dhtml%26_locale%3Den%26_controller%3Dcontroller', new ControllerReference('controller', array(), array())),
array('/_fragment?_path=_format%3Dxml%26_locale%3Den%26_controller%3Dcontroller', new ControllerReference('controller', array('_format' => 'xml'), array())),
array('/_fragment?_path=foo%3Dfoo%26_format%3Djson%26_locale%3Den%26_controller%3Dcontroller', new ControllerReference('controller', array('foo' => 'foo', '_format' => 'json'), array())),
array('/_fragment?bar=bar&_path=foo%3Dfoo%26_format%3Dhtml%26_locale%3Den%26_controller%3Dcontroller', new ControllerReference('controller', array('foo' => 'foo'), array('bar' => 'bar'))),
array('/_fragment?foo=foo&_path=_format%3Dhtml%26_locale%3Den%26_controller%3Dcontroller', new ControllerReference('controller', array(), array('foo' => 'foo'))),
array('/_fragment?_path=foo%255B0%255D%3Dfoo%26foo%255B1%255D%3Dbar%26_format%3Dhtml%26_locale%3Den%26_controller%3Dcontroller', new ControllerReference('controller', array('foo' => array('foo', 'bar')), array())),
);
return [
['/_fragment?_path=_format%3Dhtml%26_locale%3Den%26_controller%3Dcontroller', new ControllerReference('controller', [], [])],
['/_fragment?_path=_format%3Dxml%26_locale%3Den%26_controller%3Dcontroller', new ControllerReference('controller', ['_format' => 'xml'], [])],
['/_fragment?_path=foo%3Dfoo%26_format%3Djson%26_locale%3Den%26_controller%3Dcontroller', new ControllerReference('controller', ['foo' => 'foo', '_format' => 'json'], [])],
['/_fragment?bar=bar&_path=foo%3Dfoo%26_format%3Dhtml%26_locale%3Den%26_controller%3Dcontroller', new ControllerReference('controller', ['foo' => 'foo'], ['bar' => 'bar'])],
['/_fragment?foo=foo&_path=_format%3Dhtml%26_locale%3Den%26_controller%3Dcontroller', new ControllerReference('controller', [], ['foo' => 'foo'])],
['/_fragment?_path=foo%255B0%255D%3Dfoo%26foo%255B1%255D%3Dbar%26_format%3Dhtml%26_locale%3Den%26_controller%3Dcontroller', new ControllerReference('controller', ['foo' => ['foo', 'bar']], [])],
];
}
public function testGenerateFragmentUriWithARequest()
@@ -50,26 +50,26 @@ class RoutableFragmentRendererTest extends TestCase
$request = Request::create('/');
$request->attributes->set('_format', 'json');
$request->setLocale('fr');
$controller = new ControllerReference('controller', array(), array());
$controller = new ControllerReference('controller', [], []);
$this->assertEquals('/_fragment?_path=_format%3Djson%26_locale%3Dfr%26_controller%3Dcontroller', $this->callGenerateFragmentUriMethod($controller, $request));
}
/**
* @expectedException \LogicException
* @dataProvider getGenerateFragmentUriDataWithNonScalar
* @dataProvider getGenerateFragmentUriDataWithNonScalar
*/
public function testGenerateFragmentUriWithNonScalar($controller)
{
$this->expectException('LogicException');
$this->callGenerateFragmentUriMethod($controller, Request::create('/'));
}
public function getGenerateFragmentUriDataWithNonScalar()
{
return array(
array(new ControllerReference('controller', array('foo' => new Foo(), 'bar' => 'bar'), array())),
array(new ControllerReference('controller', array('foo' => array('foo' => 'foo'), 'bar' => array('bar' => new Foo())), array())),
);
return [
[new ControllerReference('controller', ['foo' => new Foo(), 'bar' => 'bar'], [])],
[new ControllerReference('controller', ['foo' => ['foo' => 'foo'], 'bar' => ['bar' => new Foo()]], [])],
];
}
private function callGenerateFragmentUriMethod(ControllerReference $reference, Request $request, $absolute = false)
@@ -12,10 +12,10 @@
namespace Symfony\Component\HttpKernel\Tests\Fragment;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Controller\ControllerReference;
use Symfony\Component\HttpKernel\Fragment\SsiFragmentRenderer;
use Symfony\Component\HttpKernel\HttpCache\Ssi;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\UriSigner;
class SsiFragmentRendererTest extends TestCase
@@ -35,7 +35,7 @@ class SsiFragmentRendererTest extends TestCase
$request->headers->set('Surrogate-Capability', 'SSI/1.0');
$this->assertEquals('<!--#include virtual="/" -->', $strategy->render('/', $request)->getContent());
$this->assertEquals('<!--#include virtual="/" -->', $strategy->render('/', $request, array('comment' => 'This is a comment'))->getContent(), 'Strategy options should not impact the ssi include tag');
$this->assertEquals('<!--#include virtual="/" -->', $strategy->render('/', $request, ['comment' => 'This is a comment'])->getContent(), 'Strategy options should not impact the ssi include tag');
}
public function testRenderControllerReference()
@@ -47,20 +47,18 @@ class SsiFragmentRendererTest extends TestCase
$request->setLocale('fr');
$request->headers->set('Surrogate-Capability', 'SSI/1.0');
$reference = new ControllerReference('main_controller', array(), array());
$altReference = new ControllerReference('alt_controller', array(), array());
$reference = new ControllerReference('main_controller', [], []);
$altReference = new ControllerReference('alt_controller', [], []);
$this->assertEquals(
'<!--#include virtual="/_fragment?_path=_format%3Dhtml%26_locale%3Dfr%26_controller%3Dmain_controller&_hash=Jz1P8NErmhKTeI6onI1EdAXTB85359MY3RIk5mSJ60w%3D" -->',
$strategy->render($reference, $request, array('alt' => $altReference))->getContent()
'<!--#include virtual="/_fragment?_hash=Jz1P8NErmhKTeI6onI1EdAXTB85359MY3RIk5mSJ60w%3D&_path=_format%3Dhtml%26_locale%3Dfr%26_controller%3Dmain_controller" -->',
$strategy->render($reference, $request, ['alt' => $altReference])->getContent()
);
}
/**
* @expectedException \LogicException
*/
public function testRenderControllerReferenceWithoutSignerThrowsException()
{
$this->expectException('LogicException');
$strategy = new SsiFragmentRenderer(new Ssi(), $this->getInlineStrategy());
$request = Request::create('/');
@@ -70,18 +68,16 @@ class SsiFragmentRendererTest extends TestCase
$strategy->render(new ControllerReference('main_controller'), $request);
}
/**
* @expectedException \LogicException
*/
public function testRenderAltControllerReferenceWithoutSignerThrowsException()
{
$this->expectException('LogicException');
$strategy = new SsiFragmentRenderer(new Ssi(), $this->getInlineStrategy());
$request = Request::create('/');
$request->setLocale('fr');
$request->headers->set('Surrogate-Capability', 'SSI/1.0');
$strategy->render('/', $request, array('alt' => new ControllerReference('alt_controller')));
$strategy->render('/', $request, ['alt' => new ControllerReference('alt_controller')]);
}
private function getInlineStrategy($called = false)
+21 -25
View File
@@ -12,9 +12,9 @@
namespace Symfony\Component\HttpKernel\Tests\HttpCache;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\HttpCache\Esi;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpCache\Esi;
class EsiTest extends TestCase
{
@@ -88,7 +88,7 @@ class EsiTest extends TestCase
$request = Request::create('/');
$response = new Response();
$response->headers->set('Content-Type', 'text/plain');
$esi->process($request, $response);
$this->assertSame($response, $esi->process($request, $response));
$this->assertFalse($response->headers->has('x-body-eval'));
}
@@ -99,7 +99,7 @@ class EsiTest extends TestCase
$request = Request::create('/');
$response = new Response('<esi:remove> <a href="http://www.example.com">www.example.com</a> </esi:remove> Keep this'."<esi:remove>\n <a>www.example.com</a> </esi:remove> And this");
$esi->process($request, $response);
$this->assertSame($response, $esi->process($request, $response));
$this->assertEquals(' Keep this And this', $response->getContent());
}
@@ -110,7 +110,7 @@ class EsiTest extends TestCase
$request = Request::create('/');
$response = new Response('<esi:comment text="some comment &gt;" /> Keep this');
$esi->process($request, $response);
$this->assertSame($response, $esi->process($request, $response));
$this->assertEquals(' Keep this', $response->getContent());
}
@@ -121,23 +121,23 @@ class EsiTest extends TestCase
$request = Request::create('/');
$response = new Response('foo <esi:comment text="some comment" /><esi:include src="..." alt="alt" onerror="continue" />');
$esi->process($request, $response);
$this->assertSame($response, $esi->process($request, $response));
$this->assertEquals('foo <?php echo $this->surrogate->handle($this, \'...\', \'alt\', true) ?>'."\n", $response->getContent());
$this->assertEquals('ESI', $response->headers->get('x-body-eval'));
$response = new Response('foo <esi:comment text="some comment" /><esi:include src="foo\'" alt="bar\'" onerror="continue" />');
$esi->process($request, $response);
$this->assertSame($response, $esi->process($request, $response));
$this->assertEquals('foo <?php echo $this->surrogate->handle($this, \'foo\\\'\', \'bar\\\'\', true) ?>'."\n", $response->getContent());
$response = new Response('foo <esi:include src="..." />');
$esi->process($request, $response);
$this->assertSame($response, $esi->process($request, $response));
$this->assertEquals('foo <?php echo $this->surrogate->handle($this, \'...\', \'\', false) ?>'."\n", $response->getContent());
$response = new Response('foo <esi:include src="..."></esi:include>');
$esi->process($request, $response);
$this->assertSame($response, $esi->process($request, $response));
$this->assertEquals('foo <?php echo $this->surrogate->handle($this, \'...\', \'\', false) ?>'."\n", $response->getContent());
}
@@ -148,21 +148,19 @@ class EsiTest extends TestCase
$request = Request::create('/');
$response = new Response('<?php <? <% <script language=php>');
$esi->process($request, $response);
$this->assertSame($response, $esi->process($request, $response));
$this->assertEquals('<?php echo "<?"; ?>php <?php echo "<?"; ?> <?php echo "<%"; ?> <?php echo "<s"; ?>cript language=php>', $response->getContent());
}
/**
* @expectedException \RuntimeException
*/
public function testProcessWhenNoSrcInAnEsi()
{
$this->expectException('RuntimeException');
$esi = new Esi();
$request = Request::create('/');
$response = new Response('foo <esi:include />');
$esi->process($request, $response);
$this->assertSame($response, $esi->process($request, $response));
}
public function testProcessRemoveSurrogateControlHeader()
@@ -172,16 +170,16 @@ class EsiTest extends TestCase
$request = Request::create('/');
$response = new Response('foo <esi:include src="..." />');
$response->headers->set('Surrogate-Control', 'content="ESI/1.0"');
$esi->process($request, $response);
$this->assertSame($response, $esi->process($request, $response));
$this->assertEquals('ESI', $response->headers->get('x-body-eval'));
$response->headers->set('Surrogate-Control', 'no-store, content="ESI/1.0"');
$esi->process($request, $response);
$this->assertSame($response, $esi->process($request, $response));
$this->assertEquals('ESI', $response->headers->get('x-body-eval'));
$this->assertEquals('no-store', $response->headers->get('surrogate-control'));
$response->headers->set('Surrogate-Control', 'content="ESI/1.0", no-store');
$esi->process($request, $response);
$this->assertSame($response, $esi->process($request, $response));
$this->assertEquals('ESI', $response->headers->get('x-body-eval'));
$this->assertEquals('no-store', $response->headers->get('surrogate-control'));
}
@@ -193,11 +191,9 @@ class EsiTest extends TestCase
$this->assertEquals('foo', $esi->handle($cache, '/', '/alt', true));
}
/**
* @expectedException \RuntimeException
*/
public function testHandleWhenResponseIsNot200()
{
$this->expectException('RuntimeException');
$esi = new Esi();
$response = new Response('foo');
$response->setStatusCode(404);
@@ -220,26 +216,26 @@ class EsiTest extends TestCase
$response1 = new Response('foo');
$response1->setStatusCode(404);
$response2 = new Response('bar');
$cache = $this->getCache(Request::create('/'), array($response1, $response2));
$cache = $this->getCache(Request::create('/'), [$response1, $response2]);
$this->assertEquals('bar', $esi->handle($cache, '/', '/alt', false));
}
protected function getCache($request, $response)
{
$cache = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpCache\HttpCache')->setMethods(array('getRequest', 'handle'))->disableOriginalConstructor()->getMock();
$cache = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpCache\HttpCache')->setMethods(['getRequest', 'handle'])->disableOriginalConstructor()->getMock();
$cache->expects($this->any())
->method('getRequest')
->will($this->returnValue($request))
->willReturn($request)
;
if (is_array($response)) {
if (\is_array($response)) {
$cache->expects($this->any())
->method('handle')
->will(call_user_func_array(array($this, 'onConsecutiveCalls'), $response))
->will(\call_user_func_array([$this, 'onConsecutiveCalls'], $response))
;
} else {
$cache->expects($this->any())
->method('handle')
->will($this->returnValue($response))
->willReturn($response)
;
}
File diff suppressed because it is too large Load Diff
@@ -29,6 +29,10 @@ class HttpCacheTestCase extends TestCase
protected $responses;
protected $catch;
protected $esi;
/**
* @var Store
*/
protected $store;
protected function setUp()
@@ -37,12 +41,12 @@ class HttpCacheTestCase extends TestCase
$this->cache = null;
$this->esi = null;
$this->caches = array();
$this->cacheConfig = array();
$this->caches = [];
$this->cacheConfig = [];
$this->request = null;
$this->response = null;
$this->responses = array();
$this->responses = [];
$this->catch = false;
@@ -87,7 +91,7 @@ class HttpCacheTestCase extends TestCase
$traces = $this->cache->getTraces();
$traces = current($traces);
$this->assertRegExp('/'.$trace.'/', implode(', ', $traces));
$this->assertMatchesRegularExpression('/'.$trace.'/', implode(', ', $traces));
}
public function assertTraceNotContains($trace)
@@ -95,7 +99,7 @@ class HttpCacheTestCase extends TestCase
$traces = $this->cache->getTraces();
$traces = current($traces);
$this->assertNotRegExp('/'.$trace.'/', implode(', ', $traces));
$this->assertDoesNotMatchRegularExpression('/'.$trace.'/', implode(', ', $traces));
}
public function assertExceptionsAreCaught()
@@ -108,7 +112,7 @@ class HttpCacheTestCase extends TestCase
$this->assertFalse($this->kernel->isCatchingExceptions());
}
public function request($method, $uri = '/', $server = array(), $cookies = array(), $esi = false, $headers = array())
public function request($method, $uri = '/', $server = [], $cookies = [], $esi = false, $headers = [])
{
if (null === $this->kernel) {
throw new \LogicException('You must call setNextResponse() before calling request().');
@@ -122,7 +126,7 @@ class HttpCacheTestCase extends TestCase
$this->esi = $esi ? new Esi() : null;
$this->cache = new HttpCache($this->kernel, $this->store, $this->esi, $this->cacheConfig);
$this->request = Request::create($uri, $method, array(), $cookies, array(), $server);
$this->request = Request::create($uri, $method, [], $cookies, [], $server);
$this->request->headers->add($headers);
$this->response = $this->cache->handle($this->request, HttpKernelInterface::MASTER_REQUEST, $this->catch);
@@ -132,7 +136,7 @@ class HttpCacheTestCase extends TestCase
public function getMetaStorageValues()
{
$values = array();
$values = [];
foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator(sys_get_temp_dir().'/http_cache/md', \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::LEAVES_ONLY) as $file) {
$values[] = file_get_contents($file);
}
@@ -141,7 +145,7 @@ class HttpCacheTestCase extends TestCase
}
// A basic response with 200 status code and a tiny body.
public function setNextResponse($statusCode = 200, array $headers = array(), $body = 'Hello World', \Closure $customizer = null)
public function setNextResponse($statusCode = 200, array $headers = [], $body = 'Hello World', \Closure $customizer = null)
{
$this->kernel = new TestHttpKernel($body, $statusCode, $headers, $customizer);
}
@@ -164,7 +168,7 @@ class HttpCacheTestCase extends TestCase
$fp = opendir($directory);
while (false !== $file = readdir($fp)) {
if (!in_array($file, array('.', '..'))) {
if (!\in_array($file, ['.', '..'])) {
if (is_link($directory.'/'.$file)) {
unlink($directory.'/'.$file);
} elseif (is_dir($directory.'/'.$file)) {
@@ -175,8 +175,26 @@ class ResponseCacheStrategyTest extends TestCase
$cacheStrategy->update($masterResponse);
$this->assertTrue($masterResponse->headers->hasCacheControlDirective('private'));
// Not sure if we should pass "max-age: 60" in this case, as long as the response is private and
// that's the more conservative of both the master and embedded response...?
$this->assertFalse($masterResponse->headers->hasCacheControlDirective('public'));
}
public function testEmbeddingPublicResponseDoesNotMakeMainResponsePublic()
{
$cacheStrategy = new ResponseCacheStrategy();
$masterResponse = new Response();
$masterResponse->setPrivate(); // this is the default, but let's be explicit
$masterResponse->setMaxAge(100);
$embeddedResponse = new Response();
$embeddedResponse->setPublic();
$embeddedResponse->setSharedMaxAge(100);
$cacheStrategy->add($embeddedResponse);
$cacheStrategy->update($masterResponse);
$this->assertTrue($masterResponse->headers->hasCacheControlDirective('private'));
$this->assertFalse($masterResponse->headers->hasCacheControlDirective('public'));
}
public function testResponseIsExiprableWhenEmbeddedResponseCombinesExpiryAndValidation()
@@ -198,7 +216,7 @@ class ResponseCacheStrategyTest extends TestCase
$cacheStrategy->add($embeddedResponse);
$cacheStrategy->update($masterResponse);
$this->assertSame('60', $masterResponse->headers->getCacheControlDirective('s-maxage'));
$this->assertEqualsWithDelta(60, (int) $masterResponse->headers->getCacheControlDirective('s-maxage'), 1);
}
public function testResponseIsExpirableButNotValidateableWhenMasterResponseCombinesExpirationAndValidation()
@@ -219,4 +237,233 @@ class ResponseCacheStrategyTest extends TestCase
$this->assertSame('60', $masterResponse->headers->getCacheControlDirective('s-maxage'));
$this->assertFalse($masterResponse->isValidateable());
}
/**
* @dataProvider cacheControlMergingProvider
*/
public function testCacheControlMerging(array $expects, array $master, array $surrogates)
{
$cacheStrategy = new ResponseCacheStrategy();
$buildResponse = function ($config) {
$response = new Response();
foreach ($config as $key => $value) {
switch ($key) {
case 'age':
$response->headers->set('Age', $value);
break;
case 'expires':
$expires = clone $response->getDate();
$expires->modify('+'.$value.' seconds');
$response->setExpires($expires);
break;
case 'max-age':
$response->setMaxAge($value);
break;
case 's-maxage':
$response->setSharedMaxAge($value);
break;
case 'private':
$response->setPrivate();
break;
case 'public':
$response->setPublic();
break;
default:
$response->headers->addCacheControlDirective($key, $value);
}
}
return $response;
};
foreach ($surrogates as $config) {
$cacheStrategy->add($buildResponse($config));
}
$response = $buildResponse($master);
$cacheStrategy->update($response);
foreach ($expects as $key => $value) {
if ('expires' === $key) {
$this->assertSame($value, $response->getExpires()->format('U') - $response->getDate()->format('U'));
} elseif ('age' === $key) {
$this->assertSame($value, $response->getAge());
} elseif (true === $value) {
$this->assertTrue($response->headers->hasCacheControlDirective($key), sprintf('Cache-Control header must have "%s" flag', $key));
} elseif (false === $value) {
$this->assertFalse(
$response->headers->hasCacheControlDirective($key),
sprintf('Cache-Control header must NOT have "%s" flag', $key)
);
} else {
$this->assertSame($value, $response->headers->getCacheControlDirective($key), sprintf('Cache-Control flag "%s" should be "%s"', $key, $value));
}
}
}
public function cacheControlMergingProvider()
{
yield 'result is public if all responses are public' => [
['private' => false, 'public' => true],
['public' => true],
[
['public' => true],
],
];
yield 'result is private by default' => [
['private' => true, 'public' => false],
['public' => true],
[
[],
],
];
yield 'combines public and private responses' => [
['must-revalidate' => false, 'private' => true, 'public' => false],
['public' => true],
[
['private' => true],
],
];
yield 'inherits no-cache from surrogates' => [
['no-cache' => true, 'public' => false],
['public' => true],
[
['no-cache' => true],
],
];
yield 'inherits no-store from surrogate' => [
['no-store' => true, 'public' => false],
['public' => true],
[
['no-store' => true],
],
];
yield 'resolve to lowest possible max-age' => [
['public' => false, 'private' => true, 's-maxage' => false, 'max-age' => '60'],
['public' => true, 'max-age' => 3600],
[
['private' => true, 'max-age' => 60],
],
];
yield 'resolves multiple max-age' => [
['public' => false, 'private' => true, 's-maxage' => false, 'max-age' => '60'],
['private' => true, 'max-age' => 100],
[
['private' => true, 'max-age' => 3600],
['public' => true, 'max-age' => 60, 's-maxage' => 60],
['private' => true, 'max-age' => 60],
],
];
yield 'merge max-age and s-maxage' => [
['public' => true, 's-maxage' => '60', 'max-age' => null],
['public' => true, 's-maxage' => 3600],
[
['public' => true, 'max-age' => 60],
],
];
yield 'result is private when combining private responses' => [
['no-cache' => false, 'must-revalidate' => false, 'private' => true],
['s-maxage' => 60, 'private' => true],
[
['s-maxage' => 60, 'private' => true],
],
];
yield 'result can have s-maxage and max-age' => [
['public' => true, 'private' => false, 's-maxage' => '60', 'max-age' => '30'],
['s-maxage' => 100, 'max-age' => 2000],
[
['s-maxage' => 1000, 'max-age' => 30],
['s-maxage' => 500, 'max-age' => 500],
['s-maxage' => 60, 'max-age' => 1000],
],
];
yield 'does not set headers without value' => [
['max-age' => null, 's-maxage' => null, 'public' => null],
['private' => true],
[
['private' => true],
],
];
yield 'max-age 0 is sent to the client' => [
['private' => true, 'max-age' => '0'],
['max-age' => 0, 'private' => true],
[
['max-age' => 60, 'private' => true],
],
];
yield 'max-age is relative to age' => [
['max-age' => '240', 'age' => 60],
['max-age' => 180],
[
['max-age' => 600, 'age' => 60],
],
];
yield 'retains lowest age of all responses' => [
['max-age' => '160', 'age' => 60],
['max-age' => 600, 'age' => 60],
[
['max-age' => 120, 'age' => 20],
],
];
yield 'max-age can be less than age, essentially expiring the response' => [
['age' => 120, 'max-age' => '90'],
['max-age' => 90, 'age' => 120],
[
['max-age' => 120, 'age' => 60],
],
];
yield 'max-age is 0 regardless of age' => [
['max-age' => '0'],
['max-age' => 60],
[
['max-age' => 0, 'age' => 60],
],
];
yield 'max-age is not negative' => [
['max-age' => '0'],
['max-age' => 0],
[
['max-age' => 0, 'age' => 60],
],
];
yield 'calculates lowest Expires header' => [
['expires' => 60],
['expires' => 60],
[
['expires' => 120],
],
];
yield 'calculates Expires header relative to age' => [
['expires' => 210, 'age' => 120],
['expires' => 90],
[
['expires' => 600, 'age' => '120'],
],
];
}
}
+8 -12
View File
@@ -120,11 +120,9 @@ class SsiTest extends TestCase
$this->assertEquals('<?php echo "<?"; ?>php <?php echo "<?"; ?> <?php echo "<%"; ?> <?php echo "<s"; ?>cript language=php>', $response->getContent());
}
/**
* @expectedException \RuntimeException
*/
public function testProcessWhenNoSrcInAnSsi()
{
$this->expectException('RuntimeException');
$ssi = new Ssi();
$request = Request::create('/');
@@ -160,11 +158,9 @@ class SsiTest extends TestCase
$this->assertEquals('foo', $ssi->handle($cache, '/', '/alt', true));
}
/**
* @expectedException \RuntimeException
*/
public function testHandleWhenResponseIsNot200()
{
$this->expectException('RuntimeException');
$ssi = new Ssi();
$response = new Response('foo');
$response->setStatusCode(404);
@@ -187,26 +183,26 @@ class SsiTest extends TestCase
$response1 = new Response('foo');
$response1->setStatusCode(404);
$response2 = new Response('bar');
$cache = $this->getCache(Request::create('/'), array($response1, $response2));
$cache = $this->getCache(Request::create('/'), [$response1, $response2]);
$this->assertEquals('bar', $ssi->handle($cache, '/', '/alt', false));
}
protected function getCache($request, $response)
{
$cache = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpCache\HttpCache')->setMethods(array('getRequest', 'handle'))->disableOriginalConstructor()->getMock();
$cache = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpCache\HttpCache')->setMethods(['getRequest', 'handle'])->disableOriginalConstructor()->getMock();
$cache->expects($this->any())
->method('getRequest')
->will($this->returnValue($request))
->willReturn($request)
;
if (is_array($response)) {
if (\is_array($response)) {
$cache->expects($this->any())
->method('handle')
->will(call_user_func_array(array($this, 'onConsecutiveCalls'), $response))
->will(\call_user_func_array([$this, 'onConsecutiveCalls'], $response))
;
} else {
$cache->expects($this->any())
->method('handle')
->will($this->returnValue($response))
->willReturn($response)
;
}
+83 -29
View File
@@ -29,7 +29,7 @@ class StoreTest extends TestCase
protected function setUp()
{
$this->request = Request::create('/');
$this->response = new Response('hello world', 200, array());
$this->response = new Response('hello world', 200, []);
HttpCacheTestCase::clearDirectory(sys_get_temp_dir().'/http_cache');
@@ -52,7 +52,7 @@ class StoreTest extends TestCase
public function testUnlockFileThatDoesExist()
{
$cacheKey = $this->storeSimpleEntry();
$this->storeSimpleEntry();
$this->store->lock($this->request);
$this->assertTrue($this->store->unlock($this->request));
@@ -92,11 +92,65 @@ class StoreTest extends TestCase
{
$cacheKey = $this->storeSimpleEntry();
$entries = $this->getStoreMetadata($cacheKey);
list($req, $res) = $entries[0];
list(, $res) = $entries[0];
$this->assertEquals('en9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08', $res['x-content-digest'][0]);
}
public function testDoesNotTrustXContentDigestFromUpstream()
{
$response = new Response('test', 200, ['X-Content-Digest' => 'untrusted-from-elsewhere']);
$cacheKey = $this->store->write($this->request, $response);
$entries = $this->getStoreMetadata($cacheKey);
list(, $res) = $entries[0];
$this->assertEquals('en9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08', $res['x-content-digest'][0]);
$this->assertEquals('en9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08', $response->headers->get('X-Content-Digest'));
}
public function testWritesResponseEvenIfXContentDigestIsPresent()
{
// Prime the store
$this->store->write($this->request, new Response('test', 200, ['X-Content-Digest' => 'untrusted-from-elsewhere']));
$response = $this->store->lookup($this->request);
$this->assertNotNull($response);
}
public function testWritingARestoredResponseDoesNotCorruptCache()
{
/*
* This covers the regression reported in https://github.com/symfony/symfony/issues/37174.
*
* A restored response does *not* load the body, but only keep the file path in a special X-Body-File
* header. For reasons (?), the file path was also used as the restored response body.
* It would be up to others (HttpCache...?) to honor this header and actually load the response content
* from there.
*
* When a restored response was stored again, the Store itself would ignore the header. In the first
* step, this would compute a new Content Digest based on the file path in the restored response body;
* this is covered by "Checkpoint 1" below. But, since the X-Body-File header was left untouched (Checkpoint 2), downstream
* code (HttpCache...) would not immediately notice.
*
* Only upon performing the lookup for a second time, we'd get a Response where the (wrong) Content Digest
* is also reflected in the X-Body-File header, this time also producing wrong content when the downstream
* evaluates it.
*/
$this->store->write($this->request, $this->response);
$digest = $this->response->headers->get('X-Content-Digest');
$path = $this->getStorePath($digest);
$response = $this->store->lookup($this->request);
$this->store->write($this->request, $response);
$this->assertEquals($digest, $response->headers->get('X-Content-Digest')); // Checkpoint 1
$this->assertEquals($path, $response->headers->get('X-Body-File')); // Checkpoint 2
$response = $this->store->lookup($this->request);
$this->assertEquals($digest, $response->headers->get('X-Content-Digest'));
$this->assertEquals($path, $response->headers->get('X-Body-File'));
}
public function testFindsAStoredEntryWithLookup()
{
$this->storeSimpleEntry();
@@ -108,7 +162,7 @@ class StoreTest extends TestCase
public function testDoesNotFindAnEntryWithLookupWhenNoneExists()
{
$request = Request::create('/test', 'get', array(), array(), array(), array('HTTP_FOO' => 'Foo', 'HTTP_BAR' => 'Bar'));
$request = Request::create('/test', 'get', [], [], [], ['HTTP_FOO' => 'Foo', 'HTTP_BAR' => 'Bar']);
$this->assertNull($this->store->lookup($request));
}
@@ -137,7 +191,7 @@ class StoreTest extends TestCase
$this->storeSimpleEntry();
$response = $this->store->lookup($this->request);
$this->assertEquals($response->headers->all(), array_merge(array('content-length' => 4, 'x-body-file' => array($this->getStorePath($response->headers->get('X-Content-Digest')))), $this->response->headers->all()));
$this->assertEquals($response->headers->all(), array_merge(['content-length' => 4, 'x-body-file' => [$this->getStorePath($response->headers->get('X-Content-Digest'))]], $this->response->headers->all()));
}
public function testRestoresResponseContentFromEntityStoreWithLookup()
@@ -165,9 +219,9 @@ class StoreTest extends TestCase
public function testDoesNotReturnEntriesThatVaryWithLookup()
{
$req1 = Request::create('/test', 'get', array(), array(), array(), array('HTTP_FOO' => 'Foo', 'HTTP_BAR' => 'Bar'));
$req2 = Request::create('/test', 'get', array(), array(), array(), array('HTTP_FOO' => 'Bling', 'HTTP_BAR' => 'Bam'));
$res = new Response('test', 200, array('Vary' => 'Foo Bar'));
$req1 = Request::create('/test', 'get', [], [], [], ['HTTP_FOO' => 'Foo', 'HTTP_BAR' => 'Bar']);
$req2 = Request::create('/test', 'get', [], [], [], ['HTTP_FOO' => 'Bling', 'HTTP_BAR' => 'Bam']);
$res = new Response('test', 200, ['Vary' => 'Foo Bar']);
$this->store->write($req1, $res);
$this->assertNull($this->store->lookup($req2));
@@ -175,9 +229,9 @@ class StoreTest extends TestCase
public function testDoesNotReturnEntriesThatSlightlyVaryWithLookup()
{
$req1 = Request::create('/test', 'get', array(), array(), array(), array('HTTP_FOO' => 'Foo', 'HTTP_BAR' => 'Bar'));
$req2 = Request::create('/test', 'get', array(), array(), array(), array('HTTP_FOO' => 'Foo', 'HTTP_BAR' => 'Bam'));
$res = new Response('test', 200, array('Vary' => array('Foo', 'Bar')));
$req1 = Request::create('/test', 'get', [], [], [], ['HTTP_FOO' => 'Foo', 'HTTP_BAR' => 'Bar']);
$req2 = Request::create('/test', 'get', [], [], [], ['HTTP_FOO' => 'Foo', 'HTTP_BAR' => 'Bam']);
$res = new Response('test', 200, ['Vary' => ['Foo', 'Bar']]);
$this->store->write($req1, $res);
$this->assertNull($this->store->lookup($req2));
@@ -185,16 +239,16 @@ class StoreTest extends TestCase
public function testStoresMultipleResponsesForEachVaryCombination()
{
$req1 = Request::create('/test', 'get', array(), array(), array(), array('HTTP_FOO' => 'Foo', 'HTTP_BAR' => 'Bar'));
$res1 = new Response('test 1', 200, array('Vary' => 'Foo Bar'));
$req1 = Request::create('/test', 'get', [], [], [], ['HTTP_FOO' => 'Foo', 'HTTP_BAR' => 'Bar']);
$res1 = new Response('test 1', 200, ['Vary' => 'Foo Bar']);
$key = $this->store->write($req1, $res1);
$req2 = Request::create('/test', 'get', array(), array(), array(), array('HTTP_FOO' => 'Bling', 'HTTP_BAR' => 'Bam'));
$res2 = new Response('test 2', 200, array('Vary' => 'Foo Bar'));
$req2 = Request::create('/test', 'get', [], [], [], ['HTTP_FOO' => 'Bling', 'HTTP_BAR' => 'Bam']);
$res2 = new Response('test 2', 200, ['Vary' => 'Foo Bar']);
$this->store->write($req2, $res2);
$req3 = Request::create('/test', 'get', array(), array(), array(), array('HTTP_FOO' => 'Baz', 'HTTP_BAR' => 'Boom'));
$res3 = new Response('test 3', 200, array('Vary' => 'Foo Bar'));
$req3 = Request::create('/test', 'get', [], [], [], ['HTTP_FOO' => 'Baz', 'HTTP_BAR' => 'Boom']);
$res3 = new Response('test 3', 200, ['Vary' => 'Foo Bar']);
$this->store->write($req3, $res3);
$this->assertEquals($this->getStorePath('en'.hash('sha256', 'test 3')), $this->store->lookup($req3)->getContent());
@@ -206,18 +260,18 @@ class StoreTest extends TestCase
public function testOverwritesNonVaryingResponseWithStore()
{
$req1 = Request::create('/test', 'get', array(), array(), array(), array('HTTP_FOO' => 'Foo', 'HTTP_BAR' => 'Bar'));
$res1 = new Response('test 1', 200, array('Vary' => 'Foo Bar'));
$key = $this->store->write($req1, $res1);
$req1 = Request::create('/test', 'get', [], [], [], ['HTTP_FOO' => 'Foo', 'HTTP_BAR' => 'Bar']);
$res1 = new Response('test 1', 200, ['Vary' => 'Foo Bar']);
$this->store->write($req1, $res1);
$this->assertEquals($this->getStorePath('en'.hash('sha256', 'test 1')), $this->store->lookup($req1)->getContent());
$req2 = Request::create('/test', 'get', array(), array(), array(), array('HTTP_FOO' => 'Bling', 'HTTP_BAR' => 'Bam'));
$res2 = new Response('test 2', 200, array('Vary' => 'Foo Bar'));
$req2 = Request::create('/test', 'get', [], [], [], ['HTTP_FOO' => 'Bling', 'HTTP_BAR' => 'Bam']);
$res2 = new Response('test 2', 200, ['Vary' => 'Foo Bar']);
$this->store->write($req2, $res2);
$this->assertEquals($this->getStorePath('en'.hash('sha256', 'test 2')), $this->store->lookup($req2)->getContent());
$req3 = Request::create('/test', 'get', array(), array(), array(), array('HTTP_FOO' => 'Foo', 'HTTP_BAR' => 'Bar'));
$res3 = new Response('test 3', 200, array('Vary' => 'Foo Bar'));
$req3 = Request::create('/test', 'get', [], [], [], ['HTTP_FOO' => 'Foo', 'HTTP_BAR' => 'Bar']);
$res3 = new Response('test 3', 200, ['Vary' => 'Foo Bar']);
$key = $this->store->write($req3, $res3);
$this->assertEquals($this->getStorePath('en'.hash('sha256', 'test 3')), $this->store->lookup($req3)->getContent());
@@ -226,10 +280,10 @@ class StoreTest extends TestCase
public function testLocking()
{
$req = Request::create('/test', 'get', array(), array(), array(), array('HTTP_FOO' => 'Foo', 'HTTP_BAR' => 'Bar'));
$req = Request::create('/test', 'get', [], [], [], ['HTTP_FOO' => 'Foo', 'HTTP_BAR' => 'Bar']);
$this->assertTrue($this->store->lock($req));
$path = $this->store->lock($req);
$this->store->lock($req);
$this->assertTrue($this->store->isLocked($req));
$this->store->unlock($req);
@@ -263,14 +317,14 @@ class StoreTest extends TestCase
$this->assertEmpty($this->getStoreMetadata($requestHttps));
}
protected function storeSimpleEntry($path = null, $headers = array())
protected function storeSimpleEntry($path = null, $headers = [])
{
if (null === $path) {
$path = '/test';
}
$this->request = Request::create($path, 'get', array(), array(), array(), $headers);
$this->response = new Response('test', 200, array('Cache-Control' => 'max-age=420'));
$this->request = Request::create($path, 'get', [], [], [], $headers);
$this->response = new Response('test', 200, ['Cache-Control' => 'max-age=420']);
return $this->store->write($this->request, $this->response);
}
@@ -11,13 +11,13 @@
namespace Symfony\Component\HttpKernel\Tests\HttpCache;
use Symfony\Component\HttpKernel\Controller\ArgumentResolverInterface;
use Symfony\Component\HttpKernel\HttpKernel;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Controller\ArgumentResolverInterface;
use Symfony\Component\HttpKernel\Controller\ControllerResolverInterface;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\HttpKernel\HttpKernel;
use Symfony\Component\HttpKernel\HttpKernelInterface;
class TestHttpKernel extends HttpKernel implements ControllerResolverInterface, ArgumentResolverInterface
{
@@ -39,15 +39,25 @@ class TestHttpKernel extends HttpKernel implements ControllerResolverInterface,
parent::__construct(new EventDispatcher(), $this, null, $this);
}
public function getBackendRequest()
public function assert(\Closure $callback)
{
return $this->backendRequest;
$trustedConfig = [Request::getTrustedProxies(), Request::getTrustedHeaderSet()];
list($trustedProxies, $trustedHeaderSet, $backendRequest) = $this->backendRequest;
Request::setTrustedProxies($trustedProxies, $trustedHeaderSet);
try {
$callback($backendRequest);
} finally {
list($trustedProxies, $trustedHeaderSet) = $trustedConfig;
Request::setTrustedProxies($trustedProxies, $trustedHeaderSet);
}
}
public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = false)
{
$this->catch = $catch;
$this->backendRequest = $request;
$this->backendRequest = [Request::getTrustedProxies(), Request::getTrustedHeaderSet(), $request];
return parent::handle($request, $type, $catch);
}
@@ -59,12 +69,12 @@ class TestHttpKernel extends HttpKernel implements ControllerResolverInterface,
public function getController(Request $request)
{
return array($this, 'callController');
return [$this, 'callController'];
}
public function getArguments(Request $request, $controller)
{
return array($request);
return [$request];
}
public function callController(Request $request)
@@ -11,19 +11,19 @@
namespace Symfony\Component\HttpKernel\Tests\HttpCache;
use Symfony\Component\HttpKernel\Controller\ArgumentResolverInterface;
use Symfony\Component\HttpKernel\HttpKernel;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Controller\ArgumentResolverInterface;
use Symfony\Component\HttpKernel\Controller\ControllerResolverInterface;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\HttpKernel\HttpKernel;
use Symfony\Component\HttpKernel\HttpKernelInterface;
class TestMultipleHttpKernel extends HttpKernel implements ControllerResolverInterface, ArgumentResolverInterface
{
protected $bodies = array();
protected $statuses = array();
protected $headers = array();
protected $bodies = [];
protected $statuses = [];
protected $headers = [];
protected $called = false;
protected $backendRequest;
@@ -52,12 +52,12 @@ class TestMultipleHttpKernel extends HttpKernel implements ControllerResolverInt
public function getController(Request $request)
{
return array($this, 'callController');
return [$this, 'callController'];
}
public function getArguments(Request $request, $controller)
{
return array($request);
return [$request];
}
public function callController(Request $request)
+66 -46
View File
@@ -12,38 +12,35 @@
namespace Symfony\Component\HttpKernel\Tests;
use PHPUnit\Framework\TestCase;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Controller\ArgumentResolverInterface;
use Symfony\Component\HttpKernel\Controller\ControllerResolverInterface;
use Symfony\Component\HttpKernel\Event\FilterControllerArgumentsEvent;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Symfony\Component\HttpKernel\HttpKernel;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\EventDispatcher\EventDispatcher;
class HttpKernelTest extends TestCase
{
/**
* @expectedException \RuntimeException
*/
public function testHandleWhenControllerThrowsAnExceptionAndCatchIsTrue()
{
$this->expectException('RuntimeException');
$kernel = $this->getHttpKernel(new EventDispatcher(), function () { throw new \RuntimeException(); });
$kernel->handle(new Request(), HttpKernelInterface::MASTER_REQUEST, true);
}
/**
* @expectedException \RuntimeException
*/
public function testHandleWhenControllerThrowsAnExceptionAndCatchIsFalseAndNoListenerIsRegistered()
{
$this->expectException('RuntimeException');
$kernel = $this->getHttpKernel(new EventDispatcher(), function () { throw new \RuntimeException(); });
$kernel->handle(new Request(), HttpKernelInterface::MASTER_REQUEST, false);
@@ -103,7 +100,7 @@ class HttpKernelTest extends TestCase
$event->setResponse(new Response($event->getException()->getMessage()));
});
$kernel = $this->getHttpKernel($dispatcher, function () { throw new MethodNotAllowedHttpException(array('POST')); });
$kernel = $this->getHttpKernel($dispatcher, function () { throw new MethodNotAllowedHttpException(['POST']); });
$response = $kernel->handle(new Request());
$this->assertEquals('405', $response->getStatusCode());
@@ -111,13 +108,14 @@ class HttpKernelTest extends TestCase
}
/**
* @group legacy
* @dataProvider getStatusCodes
*/
public function testHandleWhenAnExceptionIsHandledWithASpecificStatusCode($responseStatusCode, $expectedStatusCode)
public function testLegacyHandleWhenAnExceptionIsHandledWithASpecificStatusCode($responseStatusCode, $expectedStatusCode)
{
$dispatcher = new EventDispatcher();
$dispatcher->addListener(KernelEvents::EXCEPTION, function ($event) use ($responseStatusCode, $expectedStatusCode) {
$event->setResponse(new Response('', $responseStatusCode, array('X-Status-Code' => $expectedStatusCode)));
$event->setResponse(new Response('', $responseStatusCode, ['X-Status-Code' => $expectedStatusCode]));
});
$kernel = $this->getHttpKernel($dispatcher, function () { throw new \RuntimeException(); });
@@ -129,12 +127,38 @@ class HttpKernelTest extends TestCase
public function getStatusCodes()
{
return array(
array(200, 404),
array(404, 200),
array(301, 200),
array(500, 200),
);
return [
[200, 404],
[404, 200],
[301, 200],
[500, 200],
];
}
/**
* @dataProvider getSpecificStatusCodes
*/
public function testHandleWhenAnExceptionIsHandledWithASpecificStatusCode($expectedStatusCode)
{
$dispatcher = new EventDispatcher();
$dispatcher->addListener(KernelEvents::EXCEPTION, function (GetResponseForExceptionEvent $event) use ($expectedStatusCode) {
$event->allowCustomResponseCode();
$event->setResponse(new Response('', $expectedStatusCode));
});
$kernel = $this->getHttpKernel($dispatcher, function () { throw new \RuntimeException(); });
$response = $kernel->handle(new Request());
$this->assertEquals($expectedStatusCode, $response->getStatusCode());
}
public function getSpecificStatusCodes()
{
return [
[200],
[302],
[403],
];
}
public function testHandleWhenAListenerReturnsAResponse()
@@ -149,11 +173,9 @@ class HttpKernelTest extends TestCase
$this->assertEquals('hello', $kernel->handle(new Request())->getContent());
}
/**
* @expectedException \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
*/
public function testHandleWhenNoControllerIsFound()
{
$this->expectException('Symfony\Component\HttpKernel\Exception\NotFoundHttpException');
$dispatcher = new EventDispatcher();
$kernel = $this->getHttpKernel($dispatcher, false);
@@ -172,7 +194,7 @@ class HttpKernelTest extends TestCase
public function testHandleWhenTheControllerIsAnObjectWithInvoke()
{
$dispatcher = new EventDispatcher();
$kernel = $this->getHttpKernel($dispatcher, new Controller());
$kernel = $this->getHttpKernel($dispatcher, new TestController());
$this->assertResponseEquals(new Response('foo'), $kernel->handle(new Request()));
}
@@ -188,7 +210,7 @@ class HttpKernelTest extends TestCase
public function testHandleWhenTheControllerIsAnArray()
{
$dispatcher = new EventDispatcher();
$kernel = $this->getHttpKernel($dispatcher, array(new Controller(), 'controller'));
$kernel = $this->getHttpKernel($dispatcher, [new TestController(), 'controller']);
$this->assertResponseEquals(new Response('foo'), $kernel->handle(new Request()));
}
@@ -196,16 +218,14 @@ class HttpKernelTest extends TestCase
public function testHandleWhenTheControllerIsAStaticArray()
{
$dispatcher = new EventDispatcher();
$kernel = $this->getHttpKernel($dispatcher, array('Symfony\Component\HttpKernel\Tests\Controller', 'staticcontroller'));
$kernel = $this->getHttpKernel($dispatcher, ['Symfony\Component\HttpKernel\Tests\TestController', 'staticcontroller']);
$this->assertResponseEquals(new Response('foo'), $kernel->handle(new Request()));
}
/**
* @expectedException \LogicException
*/
public function testHandleWhenTheControllerDoesNotReturnAResponse()
{
$this->expectException('LogicException');
$dispatcher = new EventDispatcher();
$kernel = $this->getHttpKernel($dispatcher, function () { return 'foo'; });
@@ -239,7 +259,7 @@ class HttpKernelTest extends TestCase
{
$dispatcher = new EventDispatcher();
$dispatcher->addListener(KernelEvents::CONTROLLER_ARGUMENTS, function (FilterControllerArgumentsEvent $event) {
$event->setArguments(array('foo'));
$event->setArguments(['foo']);
});
$kernel = $this->getHttpKernel($dispatcher, function ($content) { return new Response($content); });
@@ -255,7 +275,7 @@ class HttpKernelTest extends TestCase
$oldArguments = $event->getArguments();
$newController = function ($id) use ($oldController, $oldArguments) {
$response = call_user_func_array($oldController, $oldArguments);
$response = \call_user_func_array($oldController, $oldArguments);
$response->headers->set('X-Id', $id);
@@ -263,12 +283,12 @@ class HttpKernelTest extends TestCase
};
$event->setController($newController);
$event->setArguments(array('bar'));
$event->setArguments(['bar']);
});
$kernel = $this->getHttpKernel($dispatcher, function ($content) { return new Response($content); }, null, array('foo'));
$kernel = $this->getHttpKernel($dispatcher, function ($content) { return new Response($content); }, null, ['foo']);
$this->assertResponseEquals(new Response('foo', 200, array('X-Id' => 'bar')), $kernel->handle(new Request()));
$this->assertResponseEquals(new Response('foo', 200, ['X-Id' => 'bar']), $kernel->handle(new Request()));
}
public function testTerminate()
@@ -293,9 +313,9 @@ class HttpKernelTest extends TestCase
{
$request = new Request();
$stack = $this->getMockBuilder('Symfony\Component\HttpFoundation\RequestStack')->setMethods(array('push', 'pop'))->getMock();
$stack->expects($this->at(0))->method('push')->with($this->equalTo($request));
$stack->expects($this->at(1))->method('pop');
$stack = $this->getMockBuilder('Symfony\Component\HttpFoundation\RequestStack')->setMethods(['push', 'pop'])->getMock();
$stack->expects($this->once())->method('push')->with($this->equalTo($request));
$stack->expects($this->once())->method('pop');
$dispatcher = new EventDispatcher();
$kernel = $this->getHttpKernel($dispatcher, null, $stack);
@@ -303,13 +323,11 @@ class HttpKernelTest extends TestCase
$kernel->handle($request, HttpKernelInterface::MASTER_REQUEST);
}
/**
* @expectedException \Symfony\Component\HttpKernel\Exception\BadRequestHttpException
*/
public function testInconsistentClientIpsOnMasterRequests()
{
$this->expectException('Symfony\Component\HttpKernel\Exception\BadRequestHttpException');
$request = new Request();
$request->setTrustedProxies(array('1.1.1.1'), -1);
$request->setTrustedProxies(['1.1.1.1'], Request::HEADER_X_FORWARDED_FOR | Request::HEADER_FORWARDED);
$request->server->set('REMOTE_ADDR', '1.1.1.1');
$request->headers->set('FORWARDED', 'for=2.2.2.2');
$request->headers->set('X_FORWARDED_FOR', '3.3.3.3');
@@ -321,9 +339,11 @@ class HttpKernelTest extends TestCase
$kernel = $this->getHttpKernel($dispatcher);
$kernel->handle($request, $kernel::MASTER_REQUEST, false);
Request::setTrustedProxies([], -1);
}
private function getHttpKernel(EventDispatcherInterface $eventDispatcher, $controller = null, RequestStack $requestStack = null, array $arguments = array())
private function getHttpKernel(EventDispatcherInterface $eventDispatcher, $controller = null, RequestStack $requestStack = null, array $arguments = [])
{
if (null === $controller) {
$controller = function () { return new Response('Hello'); };
@@ -333,13 +353,13 @@ class HttpKernelTest extends TestCase
$controllerResolver
->expects($this->any())
->method('getController')
->will($this->returnValue($controller));
->willReturn($controller);
$argumentResolver = $this->getMockBuilder(ArgumentResolverInterface::class)->getMock();
$argumentResolver
->expects($this->any())
->method('getArguments')
->will($this->returnValue($arguments));
->willReturn($arguments);
return new HttpKernel($eventDispatcher, $controllerResolver, $requestStack, $argumentResolver);
}
@@ -351,7 +371,7 @@ class HttpKernelTest extends TestCase
}
}
class Controller
class TestController
{
public function __invoke()
{
+370 -118
View File
@@ -12,18 +12,32 @@
namespace Symfony\Component\HttpKernel\Tests;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\BundleInterface;
use Symfony\Component\HttpKernel\Config\EnvParametersResource;
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Tests\Fixtures\KernelForTest;
use Symfony\Component\HttpKernel\Bundle\BundleInterface;
use Symfony\Component\HttpKernel\Config\EnvParametersResource;
use Symfony\Component\HttpKernel\DependencyInjection\ResettableServicePass;
use Symfony\Component\HttpKernel\DependencyInjection\ServicesResetter;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\HttpKernel\Tests\Fixtures\KernelForOverrideName;
use Symfony\Component\HttpKernel\Tests\Fixtures\KernelForTest;
use Symfony\Component\HttpKernel\Tests\Fixtures\KernelWithoutBundles;
use Symfony\Component\HttpKernel\Tests\Fixtures\ResettableService;
class KernelTest extends TestCase
{
public static function tearDownAfterClass()
{
$fs = new Filesystem();
$fs->remove(__DIR__.'/Fixtures/cache');
}
public function testConstructor()
{
$env = 'test_env';
@@ -52,9 +66,34 @@ class KernelTest extends TestCase
$this->assertNull($clone->getContainer());
}
public function testInitializeContainerClearsOldContainers()
{
$fs = new Filesystem();
$legacyContainerDir = __DIR__.'/Fixtures/cache/custom/ContainerA123456';
$fs->mkdir($legacyContainerDir);
touch($legacyContainerDir.'.legacy');
$kernel = new CustomProjectDirKernel();
$kernel->boot();
$containerDir = __DIR__.'/Fixtures/cache/custom/'.substr(\get_class($kernel->getContainer()), 0, 16);
$this->assertTrue(unlink(__DIR__.'/Fixtures/cache/custom/FixturesCustomDebugProjectContainer.php.meta'));
$this->assertFileExists($containerDir);
$this->assertFileDoesNotExist($containerDir.'.legacy');
$kernel = new CustomProjectDirKernel(function ($container) { $container->register('foo', 'stdClass')->setPublic(true); });
$kernel->boot();
$this->assertFileExists($containerDir);
$this->assertFileExists($containerDir.'.legacy');
$this->assertFileDoesNotExist($legacyContainerDir);
$this->assertFileDoesNotExist($legacyContainerDir.'.legacy');
}
public function testBootInitializesBundlesAndContainer()
{
$kernel = $this->getKernel(array('initializeBundles', 'initializeContainer'));
$kernel = $this->getKernel(['initializeBundles', 'initializeContainer']);
$kernel->expects($this->once())
->method('initializeBundles');
$kernel->expects($this->once())
@@ -69,10 +108,10 @@ class KernelTest extends TestCase
$bundle->expects($this->once())
->method('setContainer');
$kernel = $this->getKernel(array('initializeBundles', 'initializeContainer', 'getBundles'));
$kernel = $this->getKernel(['initializeBundles', 'initializeContainer', 'getBundles']);
$kernel->expects($this->once())
->method('getBundles')
->will($this->returnValue(array($bundle)));
->willReturn([$bundle]);
$kernel->boot();
}
@@ -80,15 +119,18 @@ class KernelTest extends TestCase
public function testBootSetsTheBootedFlagToTrue()
{
// use test kernel to access isBooted()
$kernel = $this->getKernelForTest(array('initializeBundles', 'initializeContainer'));
$kernel = $this->getKernel(['initializeBundles', 'initializeContainer']);
$kernel->boot();
$this->assertTrue($kernel->isBooted());
}
/**
* @group legacy
*/
public function testClassCacheIsLoaded()
{
$kernel = $this->getKernel(array('initializeBundles', 'initializeContainer', 'doLoadClassCache'));
$kernel = $this->getKernel(['initializeBundles', 'initializeContainer', 'doLoadClassCache']);
$kernel->loadClassCache('name', '.extension');
$kernel->expects($this->once())
->method('doLoadClassCache')
@@ -99,16 +141,19 @@ class KernelTest extends TestCase
public function testClassCacheIsNotLoadedByDefault()
{
$kernel = $this->getKernel(array('initializeBundles', 'initializeContainer', 'doLoadClassCache'));
$kernel = $this->getKernel(['initializeBundles', 'initializeContainer', 'doLoadClassCache']);
$kernel->expects($this->never())
->method('doLoadClassCache');
$kernel->boot();
}
/**
* @group legacy
*/
public function testClassCacheIsNotLoadedWhenKernelIsNotBooted()
{
$kernel = $this->getKernel(array('initializeBundles', 'initializeContainer', 'doLoadClassCache'));
$kernel = $this->getKernel(['initializeBundles', 'initializeContainer', 'doLoadClassCache']);
$kernel->loadClassCache();
$kernel->expects($this->never())
->method('doLoadClassCache');
@@ -119,22 +164,22 @@ class KernelTest extends TestCase
$container = new ContainerBuilder();
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\Tests\Fixtures\KernelForTest')
->disableOriginalConstructor()
->setMethods(array('getContainerBuilder', 'prepareContainer', 'getCacheDir', 'getLogDir'))
->setMethods(['getContainerBuilder', 'prepareContainer', 'getCacheDir', 'getLogDir'])
->getMock();
$kernel->expects($this->any())
->method('getContainerBuilder')
->will($this->returnValue($container));
->willReturn($container);
$kernel->expects($this->any())
->method('prepareContainer')
->will($this->returnValue(null));
->willReturn(null);
$kernel->expects($this->any())
->method('getCacheDir')
->will($this->returnValue(sys_get_temp_dir()));
->willReturn(sys_get_temp_dir());
$kernel->expects($this->any())
->method('getLogDir')
->will($this->returnValue(sys_get_temp_dir()));
->willReturn(sys_get_temp_dir());
$reflection = new \ReflectionClass(get_class($kernel));
$reflection = new \ReflectionClass(\get_class($kernel));
$method = $reflection->getMethod('buildContainer');
$method->setAccessible(true);
$method->invoke($kernel);
@@ -152,7 +197,7 @@ class KernelTest extends TestCase
public function testBootKernelSeveralTimesOnlyInitializesBundlesOnce()
{
$kernel = $this->getKernel(array('initializeBundles', 'initializeContainer'));
$kernel = $this->getKernel(['initializeBundles', 'initializeContainer']);
$kernel->expects($this->once())
->method('initializeBundles');
@@ -166,7 +211,7 @@ class KernelTest extends TestCase
$bundle->expects($this->once())
->method('shutdown');
$kernel = $this->getKernel(array(), array($bundle));
$kernel = $this->getKernel([], [$bundle]);
$kernel->boot();
$kernel->shutdown();
@@ -175,14 +220,17 @@ class KernelTest extends TestCase
public function testShutdownGivesNullContainerToAllBundles()
{
$bundle = $this->getMockBuilder('Symfony\Component\HttpKernel\Bundle\Bundle')->getMock();
$bundle->expects($this->at(3))
$bundle->expects($this->exactly(2))
->method('setContainer')
->with(null);
->withConsecutive(
[$this->isInstanceOf(ContainerInterface::class)],
[null]
);
$kernel = $this->getKernel(array('getBundles'));
$kernel = $this->getKernel(['getBundles']);
$kernel->expects($this->any())
->method('getBundles')
->will($this->returnValue(array($bundle)));
->willReturn([$bundle]);
$kernel->boot();
$kernel->shutdown();
@@ -202,10 +250,10 @@ class KernelTest extends TestCase
->method('handle')
->with($request, $type, $catch);
$kernel = $this->getKernel(array('getHttpKernel'));
$kernel = $this->getKernel(['getHttpKernel']);
$kernel->expects($this->once())
->method('getHttpKernel')
->will($this->returnValue($httpKernelMock));
->willReturn($httpKernelMock);
$kernel->handle($request, $type, $catch);
}
@@ -220,10 +268,10 @@ class KernelTest extends TestCase
->disableOriginalConstructor()
->getMock();
$kernel = $this->getKernel(array('getHttpKernel', 'boot'));
$kernel = $this->getKernel(['getHttpKernel', 'boot']);
$kernel->expects($this->once())
->method('getHttpKernel')
->will($this->returnValue($httpKernelMock));
->willReturn($httpKernelMock);
$kernel->expects($this->once())
->method('boot');
@@ -305,7 +353,7 @@ EOF;
// Heredocs are preserved, making the output mixing Unix and Windows line
// endings, switching to "\n" everywhere on Windows to avoid failure.
if ('\\' === DIRECTORY_SEPARATOR) {
if ('\\' === \DIRECTORY_SEPARATOR) {
$expected = str_replace("\r\n", "\n", $expected);
$output = str_replace("\r\n", "\n", $output);
}
@@ -317,7 +365,7 @@ EOF;
{
$kernel = new KernelForTest('test', true);
$this->assertEquals(__DIR__.DIRECTORY_SEPARATOR.'Fixtures', realpath($kernel->getRootDir()));
$this->assertEquals(__DIR__.\DIRECTORY_SEPARATOR.'Fixtures', realpath($kernel->getRootDir()));
}
public function testGetName()
@@ -340,44 +388,36 @@ EOF;
$debug = true;
$kernel = new KernelForTest($env, $debug);
$expected = serialize(array($env, $debug));
$expected = serialize([$env, $debug]);
$this->assertEquals($expected, $kernel->serialize());
}
/**
* @expectedException \InvalidArgumentException
*/
public function testLocateResourceThrowsExceptionWhenNameIsNotValid()
{
$this->expectException('InvalidArgumentException');
$this->getKernel()->locateResource('Foo');
}
/**
* @expectedException \RuntimeException
*/
public function testLocateResourceThrowsExceptionWhenNameIsUnsafe()
{
$this->expectException('RuntimeException');
$this->getKernel()->locateResource('@FooBundle/../bar');
}
/**
* @expectedException \InvalidArgumentException
*/
public function testLocateResourceThrowsExceptionWhenBundleDoesNotExist()
{
$this->expectException('InvalidArgumentException');
$this->getKernel()->locateResource('@FooBundle/config/routing.xml');
}
/**
* @expectedException \InvalidArgumentException
*/
public function testLocateResourceThrowsExceptionWhenResourceDoesNotExist()
{
$kernel = $this->getKernel(array('getBundle'));
$this->expectException('InvalidArgumentException');
$kernel = $this->getKernel(['getBundle']);
$kernel
->expects($this->once())
->method('getBundle')
->will($this->returnValue(array($this->getBundle(__DIR__.'/Fixtures/Bundle1Bundle'))))
->willReturn([$this->getBundle(__DIR__.'/Fixtures/Bundle1Bundle')])
;
$kernel->locateResource('@Bundle1Bundle/config/routing.xml');
@@ -385,75 +425,84 @@ EOF;
public function testLocateResourceReturnsTheFirstThatMatches()
{
$kernel = $this->getKernel(array('getBundle'));
$kernel = $this->getKernel(['getBundle']);
$kernel
->expects($this->once())
->method('getBundle')
->will($this->returnValue(array($this->getBundle(__DIR__.'/Fixtures/Bundle1Bundle'))))
->willReturn([$this->getBundle(__DIR__.'/Fixtures/Bundle1Bundle')])
;
$this->assertEquals(__DIR__.'/Fixtures/Bundle1Bundle/foo.txt', $kernel->locateResource('@Bundle1Bundle/foo.txt'));
}
/**
* @group legacy
*/
public function testLocateResourceReturnsTheFirstThatMatchesWithParent()
{
$parent = $this->getBundle(__DIR__.'/Fixtures/Bundle1Bundle');
$child = $this->getBundle(__DIR__.'/Fixtures/Bundle2Bundle');
$kernel = $this->getKernel(array('getBundle'));
$kernel = $this->getKernel(['getBundle']);
$kernel
->expects($this->exactly(2))
->method('getBundle')
->will($this->returnValue(array($child, $parent)))
->willReturn([$child, $parent])
;
$this->assertEquals(__DIR__.'/Fixtures/Bundle2Bundle/foo.txt', $kernel->locateResource('@ParentAABundle/foo.txt'));
$this->assertEquals(__DIR__.'/Fixtures/Bundle1Bundle/bar.txt', $kernel->locateResource('@ParentAABundle/bar.txt'));
}
/**
* @group legacy
*/
public function testLocateResourceReturnsAllMatches()
{
$parent = $this->getBundle(__DIR__.'/Fixtures/Bundle1Bundle');
$child = $this->getBundle(__DIR__.'/Fixtures/Bundle2Bundle');
$kernel = $this->getKernel(array('getBundle'));
$kernel = $this->getKernel(['getBundle']);
$kernel
->expects($this->once())
->method('getBundle')
->will($this->returnValue(array($child, $parent)))
->willReturn([$child, $parent])
;
$this->assertEquals(array(
$this->assertEquals([
__DIR__.'/Fixtures/Bundle2Bundle/foo.txt',
__DIR__.'/Fixtures/Bundle1Bundle/foo.txt', ),
__DIR__.'/Fixtures/Bundle1Bundle/foo.txt', ],
$kernel->locateResource('@Bundle1Bundle/foo.txt', null, false));
}
/**
* @group legacy
*/
public function testLocateResourceReturnsAllMatchesBis()
{
$kernel = $this->getKernel(array('getBundle'));
$kernel = $this->getKernel(['getBundle']);
$kernel
->expects($this->once())
->method('getBundle')
->will($this->returnValue(array(
->willReturn([
$this->getBundle(__DIR__.'/Fixtures/Bundle1Bundle'),
$this->getBundle(__DIR__.'/Foobar'),
)))
])
;
$this->assertEquals(
array(__DIR__.'/Fixtures/Bundle1Bundle/foo.txt'),
[__DIR__.'/Fixtures/Bundle1Bundle/foo.txt'],
$kernel->locateResource('@Bundle1Bundle/foo.txt', null, false)
);
}
public function testLocateResourceIgnoresDirOnNonResource()
{
$kernel = $this->getKernel(array('getBundle'));
$kernel = $this->getKernel(['getBundle']);
$kernel
->expects($this->once())
->method('getBundle')
->will($this->returnValue(array($this->getBundle(__DIR__.'/Fixtures/Bundle1Bundle'))))
->willReturn([$this->getBundle(__DIR__.'/Fixtures/Bundle1Bundle')])
;
$this->assertEquals(
@@ -464,11 +513,11 @@ EOF;
public function testLocateResourceReturnsTheDirOneForResources()
{
$kernel = $this->getKernel(array('getBundle'));
$kernel = $this->getKernel(['getBundle']);
$kernel
->expects($this->once())
->method('getBundle')
->will($this->returnValue(array($this->getBundle(__DIR__.'/Fixtures/FooBundle', null, null, 'FooBundle'))))
->willReturn([$this->getBundle(__DIR__.'/Fixtures/FooBundle', null, null, 'FooBundle')])
;
$this->assertEquals(
@@ -477,39 +526,45 @@ EOF;
);
}
/**
* @group legacy
*/
public function testLocateResourceReturnsTheDirOneForResourcesAndBundleOnes()
{
$kernel = $this->getKernel(array('getBundle'));
$kernel = $this->getKernel(['getBundle']);
$kernel
->expects($this->once())
->method('getBundle')
->will($this->returnValue(array($this->getBundle(__DIR__.'/Fixtures/Bundle1Bundle', null, null, 'Bundle1Bundle'))))
->willReturn([$this->getBundle(__DIR__.'/Fixtures/Bundle1Bundle', null, null, 'Bundle1Bundle')])
;
$this->assertEquals(array(
$this->assertEquals([
__DIR__.'/Fixtures/Resources/Bundle1Bundle/foo.txt',
__DIR__.'/Fixtures/Bundle1Bundle/Resources/foo.txt', ),
__DIR__.'/Fixtures/Bundle1Bundle/Resources/foo.txt', ],
$kernel->locateResource('@Bundle1Bundle/Resources/foo.txt', __DIR__.'/Fixtures/Resources', false)
);
}
/**
* @group legacy
*/
public function testLocateResourceOverrideBundleAndResourcesFolders()
{
$parent = $this->getBundle(__DIR__.'/Fixtures/BaseBundle', null, 'BaseBundle', 'BaseBundle');
$child = $this->getBundle(__DIR__.'/Fixtures/ChildBundle', 'ParentBundle', 'ChildBundle', 'ChildBundle');
$kernel = $this->getKernel(array('getBundle'));
$kernel = $this->getKernel(['getBundle']);
$kernel
->expects($this->exactly(4))
->method('getBundle')
->will($this->returnValue(array($child, $parent)))
->willReturn([$child, $parent])
;
$this->assertEquals(array(
$this->assertEquals([
__DIR__.'/Fixtures/Resources/ChildBundle/foo.txt',
__DIR__.'/Fixtures/ChildBundle/Resources/foo.txt',
__DIR__.'/Fixtures/BaseBundle/Resources/foo.txt',
),
],
$kernel->locateResource('@BaseBundle/Resources/foo.txt', __DIR__.'/Fixtures/Resources', false)
);
@@ -533,11 +588,11 @@ EOF;
public function testLocateResourceOnDirectories()
{
$kernel = $this->getKernel(array('getBundle'));
$kernel = $this->getKernel(['getBundle']);
$kernel
->expects($this->exactly(2))
->method('getBundle')
->will($this->returnValue(array($this->getBundle(__DIR__.'/Fixtures/FooBundle', null, null, 'FooBundle'))))
->willReturn([$this->getBundle(__DIR__.'/Fixtures/FooBundle', null, null, 'FooBundle')])
;
$this->assertEquals(
@@ -549,11 +604,11 @@ EOF;
$kernel->locateResource('@FooBundle/Resources', __DIR__.'/Fixtures/Resources')
);
$kernel = $this->getKernel(array('getBundle'));
$kernel = $this->getKernel(['getBundle']);
$kernel
->expects($this->exactly(2))
->method('getBundle')
->will($this->returnValue(array($this->getBundle(__DIR__.'/Fixtures/Bundle1Bundle', null, null, 'Bundle1Bundle'))))
->willReturn([$this->getBundle(__DIR__.'/Fixtures/Bundle1Bundle', null, null, 'Bundle1Bundle')])
;
$this->assertEquals(
@@ -566,24 +621,30 @@ EOF;
);
}
/**
* @group legacy
*/
public function testInitializeBundles()
{
$parent = $this->getBundle(null, null, 'ParentABundle');
$child = $this->getBundle(null, 'ParentABundle', 'ChildABundle');
// use test kernel so we can access getBundleMap()
$kernel = $this->getKernelForTest(array('registerBundles'));
$kernel = $this->getKernelForTest(['registerBundles']);
$kernel
->expects($this->once())
->method('registerBundles')
->will($this->returnValue(array($parent, $child)))
->willReturn([$parent, $child])
;
$kernel->boot();
$map = $kernel->getBundleMap();
$this->assertEquals(array($child, $parent), $map['ParentABundle']);
$this->assertEquals([$child, $parent], $map['ParentABundle']);
}
/**
* @group legacy
*/
public function testInitializeBundlesSupportInheritanceCascade()
{
$grandparent = $this->getBundle(null, null, 'GrandParentBBundle');
@@ -591,31 +652,35 @@ EOF;
$child = $this->getBundle(null, 'ParentBBundle', 'ChildBBundle');
// use test kernel so we can access getBundleMap()
$kernel = $this->getKernelForTest(array('registerBundles'));
$kernel = $this->getKernelForTest(['registerBundles']);
$kernel
->expects($this->once())
->method('registerBundles')
->will($this->returnValue(array($grandparent, $parent, $child)))
->willReturn([$grandparent, $parent, $child])
;
$kernel->boot();
$map = $kernel->getBundleMap();
$this->assertEquals(array($child, $parent, $grandparent), $map['GrandParentBBundle']);
$this->assertEquals(array($child, $parent), $map['ParentBBundle']);
$this->assertEquals(array($child), $map['ChildBBundle']);
$this->assertEquals([$child, $parent, $grandparent], $map['GrandParentBBundle']);
$this->assertEquals([$child, $parent], $map['ParentBBundle']);
$this->assertEquals([$child], $map['ChildBBundle']);
}
/**
* @expectedException \LogicException
* @expectedExceptionMessage Bundle "ChildCBundle" extends bundle "FooBar", which is not registered.
* @group legacy
*/
public function testInitializeBundlesThrowsExceptionWhenAParentDoesNotExists()
{
$this->expectException('LogicException');
$this->expectExceptionMessage('Bundle "ChildCBundle" extends bundle "FooBar", which is not registered.');
$child = $this->getBundle(null, 'FooBar', 'ChildCBundle');
$kernel = $this->getKernel(array(), array($child));
$kernel = $this->getKernel([], [$child]);
$kernel->boot();
}
/**
* @group legacy
*/
public function testInitializeBundlesSupportsArbitraryBundleRegistrationOrder()
{
$grandparent = $this->getBundle(null, null, 'GrandParentCBundle');
@@ -623,62 +688,65 @@ EOF;
$child = $this->getBundle(null, 'ParentCBundle', 'ChildCBundle');
// use test kernel so we can access getBundleMap()
$kernel = $this->getKernelForTest(array('registerBundles'));
$kernel = $this->getKernelForTest(['registerBundles']);
$kernel
->expects($this->once())
->method('registerBundles')
->will($this->returnValue(array($parent, $grandparent, $child)))
->willReturn([$parent, $grandparent, $child])
;
$kernel->boot();
$map = $kernel->getBundleMap();
$this->assertEquals(array($child, $parent, $grandparent), $map['GrandParentCBundle']);
$this->assertEquals(array($child, $parent), $map['ParentCBundle']);
$this->assertEquals(array($child), $map['ChildCBundle']);
$this->assertEquals([$child, $parent, $grandparent], $map['GrandParentCBundle']);
$this->assertEquals([$child, $parent], $map['ParentCBundle']);
$this->assertEquals([$child], $map['ChildCBundle']);
}
/**
* @expectedException \LogicException
* @expectedExceptionMessage Bundle "ParentCBundle" is directly extended by two bundles "ChildC2Bundle" and "ChildC1Bundle".
* @group legacy
*/
public function testInitializeBundlesThrowsExceptionWhenABundleIsDirectlyExtendedByTwoBundles()
{
$this->expectException('LogicException');
$this->expectExceptionMessage('Bundle "ParentCBundle" is directly extended by two bundles "ChildC2Bundle" and "ChildC1Bundle".');
$parent = $this->getBundle(null, null, 'ParentCBundle');
$child1 = $this->getBundle(null, 'ParentCBundle', 'ChildC1Bundle');
$child2 = $this->getBundle(null, 'ParentCBundle', 'ChildC2Bundle');
$kernel = $this->getKernel(array(), array($parent, $child1, $child2));
$kernel = $this->getKernel([], [$parent, $child1, $child2]);
$kernel->boot();
}
/**
* @expectedException \LogicException
* @expectedExceptionMessage Trying to register two bundles with the same name "DuplicateName"
* @group legacy
*/
public function testInitializeBundleThrowsExceptionWhenRegisteringTwoBundlesWithTheSameName()
{
$fooBundle = $this->getBundle(null, null, 'FooBundle', 'DuplicateName');
$barBundle = $this->getBundle(null, null, 'BarBundle', 'DuplicateName');
$this->expectException('LogicException');
$this->expectExceptionMessage('Trying to register two bundles with the same name "DuplicateName"');
$fooBundle = $this->getBundle(__DIR__.'/Fixtures/FooBundle', null, 'FooBundle', 'DuplicateName');
$barBundle = $this->getBundle(__DIR__.'/Fixtures/BarBundle', null, 'BarBundle', 'DuplicateName');
$kernel = $this->getKernel(array(), array($fooBundle, $barBundle));
$kernel = $this->getKernel([], [$fooBundle, $barBundle]);
$kernel->boot();
}
/**
* @expectedException \LogicException
* @expectedExceptionMessage Bundle "CircularRefBundle" can not extend itself.
* @group legacy
*/
public function testInitializeBundleThrowsExceptionWhenABundleExtendsItself()
{
$this->expectException('LogicException');
$this->expectExceptionMessage('Bundle "CircularRefBundle" can not extend itself.');
$circularRef = $this->getBundle(null, 'CircularRefBundle', 'CircularRefBundle');
$kernel = $this->getKernel(array(), array($circularRef));
$kernel = $this->getKernel([], [$circularRef]);
$kernel->boot();
}
public function testTerminateReturnsSilentlyIfKernelIsNotBooted()
{
$kernel = $this->getKernel(array('getHttpKernel'));
$kernel = $this->getKernel(['getHttpKernel']);
$kernel->expects($this->never())
->method('getHttpKernel');
@@ -690,7 +758,7 @@ EOF;
// does not implement TerminableInterface
$httpKernel = new TestKernel();
$kernel = $this->getKernel(array('getHttpKernel'));
$kernel = $this->getKernel(['getHttpKernel']);
$kernel->expects($this->once())
->method('getHttpKernel')
->willReturn($httpKernel);
@@ -703,22 +771,30 @@ EOF;
// implements TerminableInterface
$httpKernelMock = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernel')
->disableOriginalConstructor()
->setMethods(array('terminate'))
->setMethods(['terminate'])
->getMock();
$httpKernelMock
->expects($this->once())
->method('terminate');
$kernel = $this->getKernel(array('getHttpKernel'));
$kernel = $this->getKernel(['getHttpKernel']);
$kernel->expects($this->exactly(2))
->method('getHttpKernel')
->will($this->returnValue($httpKernelMock));
->willReturn($httpKernelMock);
$kernel->boot();
$kernel->terminate(Request::create('/'), new Response());
}
public function testKernelWithoutBundles()
{
$kernel = new KernelWithoutBundles('test', true);
$kernel->boot();
$this->assertTrue($kernel->getContainer()->getParameter('test_executed'));
}
public function testKernelRootDirNameStartingWithANumber()
{
$dir = __DIR__.'/Fixtures/123';
@@ -727,6 +803,115 @@ EOF;
$this->assertEquals('_123', $kernel->getName());
}
/**
* @group legacy
* @expectedDeprecation The "Symfony\Component\HttpKernel\Kernel::getEnvParameters()" method is deprecated as of 3.3 and will be removed in 4.0. Use the %cenv()%c syntax to get the value of any environment variable from configuration files instead.
* @expectedDeprecation The support of special environment variables that start with SYMFONY__ (such as "SYMFONY__FOO__BAR") is deprecated as of 3.3 and will be removed in 4.0. Use the %cenv()%c syntax instead to get the value of environment variables in configuration files.
*/
public function testSymfonyEnvironmentVariables()
{
$_SERVER['SYMFONY__FOO__BAR'] = 'baz';
$kernel = $this->getKernel();
$method = new \ReflectionMethod($kernel, 'getEnvParameters');
$method->setAccessible(true);
$envParameters = $method->invoke($kernel);
$this->assertSame('baz', $envParameters['foo.bar']);
unset($_SERVER['SYMFONY__FOO__BAR']);
}
public function testProjectDirExtension()
{
$kernel = new CustomProjectDirKernel();
$kernel->boot();
$this->assertSame('foo', $kernel->getProjectDir());
$this->assertSame('foo', $kernel->getContainer()->getParameter('kernel.project_dir'));
}
public function testKernelReset()
{
(new Filesystem())->remove(__DIR__.'/Fixtures/cache');
$kernel = new CustomProjectDirKernel();
$kernel->boot();
$containerClass = \get_class($kernel->getContainer());
$containerFile = (new \ReflectionClass($kernel->getContainer()))->getFileName();
unlink(__DIR__.'/Fixtures/cache/custom/FixturesCustomDebugProjectContainer.php.meta');
$kernel = new CustomProjectDirKernel();
$kernel->boot();
$this->assertInstanceOf($containerClass, $kernel->getContainer());
$this->assertFileExists($containerFile);
unlink(__DIR__.'/Fixtures/cache/custom/FixturesCustomDebugProjectContainer.php.meta');
$kernel = new CustomProjectDirKernel(function ($container) { $container->register('foo', 'stdClass')->setPublic(true); });
$kernel->boot();
$this->assertNotInstanceOf($containerClass, $kernel->getContainer());
$this->assertFileExists($containerFile);
$this->assertFileExists(\dirname($containerFile).'.legacy');
}
public function testKernelPass()
{
$kernel = new PassKernel();
$kernel->boot();
$this->assertTrue($kernel->getContainer()->getParameter('test.processed'));
}
public function testServicesResetter()
{
$httpKernelMock = $this->getMockBuilder(HttpKernelInterface::class)
->disableOriginalConstructor()
->getMock();
$httpKernelMock
->expects($this->exactly(2))
->method('handle');
$kernel = new CustomProjectDirKernel(function ($container) {
$container->addCompilerPass(new ResettableServicePass());
$container->register('one', ResettableService::class)
->setPublic(true)
->addTag('kernel.reset', ['method' => 'reset']);
$container->register('services_resetter', ServicesResetter::class)->setPublic(true);
}, $httpKernelMock, 'resetting');
ResettableService::$counter = 0;
$request = new Request();
$kernel->handle($request);
$kernel->getContainer()->get('one');
$this->assertEquals(0, ResettableService::$counter);
$this->assertFalse($kernel->getContainer()->initialized('services_resetter'));
$kernel->handle($request);
$this->assertEquals(1, ResettableService::$counter);
}
/**
* @group time-sensitive
*/
public function testKernelStartTimeIsResetWhileBootingAlreadyBootedKernel()
{
$kernel = $this->getKernel(['initializeBundles'], [], true);
$kernel->boot();
$preReBoot = $kernel->getStartTime();
sleep(3600); //Intentionally large value to detect if ClockMock ever breaks
$kernel->reboot(null);
$this->assertGreaterThan($preReBoot, $kernel->getStartTime());
}
/**
* Returns a mock for the BundleInterface.
*
@@ -736,7 +921,7 @@ EOF;
{
$bundle = $this
->getMockBuilder('Symfony\Component\HttpKernel\Bundle\BundleInterface')
->setMethods(array('getPath', 'getParent', 'getName'))
->setMethods(['getPath', 'getParent', 'getName'])
->disableOriginalConstructor()
;
@@ -749,19 +934,19 @@ EOF;
$bundle
->expects($this->any())
->method('getName')
->will($this->returnValue(null === $bundleName ? get_class($bundle) : $bundleName))
->willReturn(null === $bundleName ? \get_class($bundle) : $bundleName)
;
$bundle
->expects($this->any())
->method('getPath')
->will($this->returnValue($dir))
->willReturn($dir)
;
$bundle
->expects($this->any())
->method('getParent')
->will($this->returnValue($parent))
->willReturn($parent)
;
return $bundle;
@@ -775,19 +960,19 @@ EOF;
*
* @return Kernel
*/
protected function getKernel(array $methods = array(), array $bundles = array())
protected function getKernel(array $methods = [], array $bundles = [], $debug = false)
{
$methods[] = 'registerBundles';
$kernel = $this
->getMockBuilder('Symfony\Component\HttpKernel\Kernel')
->getMockBuilder(KernelForTest::class)
->setMethods($methods)
->setConstructorArgs(array('test', false))
->getMockForAbstractClass()
->setConstructorArgs(['test', $debug])
->getMock()
;
$kernel->expects($this->any())
->method('registerBundles')
->will($this->returnValue($bundles))
->willReturn($bundles)
;
$p = new \ReflectionProperty($kernel, 'rootDir');
$p->setAccessible(true);
@@ -796,12 +981,13 @@ EOF;
return $kernel;
}
protected function getKernelForTest(array $methods = array())
protected function getKernelForTest(array $methods = [], $debug = false)
{
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\Tests\Fixtures\KernelForTest')
->setConstructorArgs(array('test', false))
$kernel = $this->getMockBuilder(KernelForTest::class)
->setConstructorArgs(['test', $debug])
->setMethods($methods)
->getMock();
->getMock()
;
$p = new \ReflectionProperty($kernel, 'rootDir');
$p->setAccessible(true);
$p->setValue($kernel, __DIR__.'/Fixtures');
@@ -822,4 +1008,70 @@ class TestKernel implements HttpKernelInterface
public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = true)
{
}
public function getProjectDir()
{
return __DIR__.'/Fixtures';
}
}
class CustomProjectDirKernel extends Kernel
{
private $baseDir;
private $buildContainer;
private $httpKernel;
public function __construct(\Closure $buildContainer = null, HttpKernelInterface $httpKernel = null, $name = 'custom')
{
parent::__construct($name, true);
$this->baseDir = 'foo';
$this->buildContainer = $buildContainer;
$this->httpKernel = $httpKernel;
}
public function registerBundles()
{
return [];
}
public function registerContainerConfiguration(LoaderInterface $loader)
{
}
public function getProjectDir()
{
return $this->baseDir;
}
public function getRootDir()
{
return __DIR__.'/Fixtures';
}
protected function build(ContainerBuilder $container)
{
if ($build = $this->buildContainer) {
$build($container);
}
}
protected function getHttpKernel()
{
return $this->httpKernel;
}
}
class PassKernel extends CustomProjectDirKernel implements CompilerPassInterface
{
public function __construct()
{
parent::__construct();
Kernel::__construct('pass', true);
}
public function process(ContainerBuilder $container)
{
$container->setParameter('test.processed', true);
}
}
+22 -19
View File
@@ -22,6 +22,9 @@ class Logger implements LoggerInterface
$this->clear();
}
/**
* @return array
*/
public function getLogs($level = false)
{
return false === $level ? $this->logs : $this->logs[$level];
@@ -29,59 +32,59 @@ class Logger implements LoggerInterface
public function clear()
{
$this->logs = array(
'emergency' => array(),
'alert' => array(),
'critical' => array(),
'error' => array(),
'warning' => array(),
'notice' => array(),
'info' => array(),
'debug' => array(),
);
$this->logs = [
'emergency' => [],
'alert' => [],
'critical' => [],
'error' => [],
'warning' => [],
'notice' => [],
'info' => [],
'debug' => [],
];
}
public function log($level, $message, array $context = array())
public function log($level, $message, array $context = [])
{
$this->logs[$level][] = $message;
}
public function emergency($message, array $context = array())
public function emergency($message, array $context = [])
{
$this->log('emergency', $message, $context);
}
public function alert($message, array $context = array())
public function alert($message, array $context = [])
{
$this->log('alert', $message, $context);
}
public function critical($message, array $context = array())
public function critical($message, array $context = [])
{
$this->log('critical', $message, $context);
}
public function error($message, array $context = array())
public function error($message, array $context = [])
{
$this->log('error', $message, $context);
}
public function warning($message, array $context = array())
public function warning($message, array $context = [])
{
$this->log('warning', $message, $context);
}
public function notice($message, array $context = array())
public function notice($message, array $context = [])
{
$this->log('notice', $message, $context);
}
public function info($message, array $context = array())
public function info($message, array $context = [])
{
$this->log('info', $message, $context);
}
public function debug($message, array $context = array())
public function debug($message, array $context = [])
{
$this->log('debug', $message, $context);
}
@@ -83,22 +83,22 @@ class FileProfilerStorageTest extends TestCase
$profile = new Profile('simple_quote');
$profile->setUrl('http://foo.bar/\'');
$this->storage->write($profile);
$this->assertTrue(false !== $this->storage->read('simple_quote'), '->write() accepts single quotes in URL');
$this->assertNotFalse($this->storage->read('simple_quote'), '->write() accepts single quotes in URL');
$profile = new Profile('double_quote');
$profile->setUrl('http://foo.bar/"');
$this->storage->write($profile);
$this->assertTrue(false !== $this->storage->read('double_quote'), '->write() accepts double quotes in URL');
$this->assertNotFalse($this->storage->read('double_quote'), '->write() accepts double quotes in URL');
$profile = new Profile('backslash');
$profile->setUrl('http://foo.bar/\\');
$this->storage->write($profile);
$this->assertTrue(false !== $this->storage->read('backslash'), '->write() accepts backslash in URL');
$this->assertNotFalse($this->storage->read('backslash'), '->write() accepts backslash in URL');
$profile = new Profile('comma');
$profile->setUrl('http://foo.bar/,');
$this->storage->write($profile);
$this->assertTrue(false !== $this->storage->read('comma'), '->write() accepts comma in URL');
$this->assertNotFalse($this->storage->read('comma'), '->write() accepts comma in URL');
}
public function testStoreDuplicateToken()
@@ -205,9 +205,9 @@ class FileProfilerStorageTest extends TestCase
$records = $this->storage->find('', '', 3, 'GET', $start, time() + 3 * 60);
$this->assertCount(3, $records, '->find() returns all previously added records');
$this->assertEquals($records[0]['token'], 'time_2', '->find() returns records ordered by time in descendant order');
$this->assertEquals($records[1]['token'], 'time_1', '->find() returns records ordered by time in descendant order');
$this->assertEquals($records[2]['token'], 'time_0', '->find() returns records ordered by time in descendant order');
$this->assertEquals('time_2', $records[0]['token'], '->find() returns records ordered by time in descendant order');
$this->assertEquals('time_1', $records[1]['token'], '->find() returns records ordered by time in descendant order');
$this->assertEquals('time_0', $records[2]['token'], '->find() returns records ordered by time in descendant order');
$records = $this->storage->find('', '', 3, 'GET', $start, time() + 2 * 60);
$this->assertCount(2, $records, '->find() should return only first two of the previously added records');
@@ -226,7 +226,7 @@ class FileProfilerStorageTest extends TestCase
public function testRetrieveByMethodAndLimit()
{
foreach (array('POST', 'GET') as $method) {
foreach (['POST', 'GET'] as $method) {
for ($i = 0; $i < 5; ++$i) {
$profile = new Profile('token_'.$i.$method);
$profile->setMethod($method);
@@ -247,7 +247,7 @@ class FileProfilerStorageTest extends TestCase
$profile->setMethod('GET');
$this->storage->write($profile);
$this->assertTrue(false !== $this->storage->read('token1'));
$this->assertNotFalse($this->storage->read('token1'));
$this->assertCount(1, $this->storage->find('127.0.0.1', '', 10, 'GET'));
$profile = new Profile('token2');
@@ -256,7 +256,7 @@ class FileProfilerStorageTest extends TestCase
$profile->setMethod('GET');
$this->storage->write($profile);
$this->assertTrue(false !== $this->storage->read('token2'));
$this->assertNotFalse($this->storage->read('token2'));
$this->assertCount(2, $this->storage->find('127.0.0.1', '', 10, 'GET'));
$this->storage->purge();
@@ -293,8 +293,8 @@ class FileProfilerStorageTest extends TestCase
$tokens = $this->storage->find('', '', 10, '');
$this->assertCount(2, $tokens);
$this->assertContains($tokens[0]['status_code'], array(200, 404));
$this->assertContains($tokens[1]['status_code'], array(200, 404));
$this->assertContains((int) $tokens[0]['status_code'], [200, 404]);
$this->assertContains((int) $tokens[1]['status_code'], [200, 404]);
}
public function testMultiRowIndexFile()
@@ -329,7 +329,7 @@ class FileProfilerStorageTest extends TestCase
$h = tmpfile();
fwrite($h, "line1\n\n\nline2\n");
fseek($h, 0, SEEK_END);
fseek($h, 0, \SEEK_END);
$this->assertEquals('line2', $r->invoke($this->storage, $h));
$this->assertEquals('line1', $r->invoke($this->storage, $h));
+18 -4
View File
@@ -12,12 +12,12 @@
namespace Symfony\Component\HttpKernel\Tests\Profiler;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\DataCollector\DataCollectorInterface;
use Symfony\Component\HttpKernel\DataCollector\RequestDataCollector;
use Symfony\Component\HttpKernel\Profiler\FileProfilerStorage;
use Symfony\Component\HttpKernel\Profiler\Profiler;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\VarDumper\Cloner\Data;
class ProfilerTest extends TestCase
{
@@ -34,10 +34,24 @@ class ProfilerTest extends TestCase
$profiler = new Profiler($this->storage);
$profiler->add($collector);
$profile = $profiler->collect($request, $response);
$profiler->saveProfile($profile);
$this->assertSame(204, $profile->getStatusCode());
$this->assertSame('GET', $profile->getMethod());
$this->assertInstanceOf(Data::class, $profiler->get('request')->getRequestQuery()->all()['foo']);
$this->assertSame('bar', $profile->getCollector('request')->getRequestQuery()->all()['foo']->getValue());
}
public function testReset()
{
$collector = $this->getMockBuilder(DataCollectorInterface::class)
->setMethods(['collect', 'getName', 'reset'])
->getMock();
$collector->expects($this->any())->method('getName')->willReturn('mock');
$collector->expects($this->once())->method('reset');
$profiler = new Profiler($this->storage);
$profiler->add($collector);
$profiler->reset();
}
public function testFindWorksWithDates()
+5 -5
View File
@@ -11,12 +11,12 @@
namespace Symfony\Component\HttpKernel\Tests;
use Symfony\Component\HttpKernel\Controller\ArgumentResolverInterface;
use Symfony\Component\HttpKernel\HttpKernel;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Controller\ArgumentResolverInterface;
use Symfony\Component\HttpKernel\Controller\ControllerResolverInterface;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\HttpKernel\HttpKernel;
class TestHttpKernel extends HttpKernel implements ControllerResolverInterface, ArgumentResolverInterface
{
@@ -27,12 +27,12 @@ class TestHttpKernel extends HttpKernel implements ControllerResolverInterface,
public function getController(Request $request)
{
return array($this, 'callController');
return [$this, 'callController'];
}
public function getArguments(Request $request, $controller)
{
return array($request);
return [$request];
}
public function callController(Request $request)
+27 -4
View File
@@ -20,8 +20,9 @@ class UriSignerTest extends TestCase
{
$signer = new UriSigner('foobar');
$this->assertContains('?_hash=', $signer->sign('http://example.com/foo'));
$this->assertContains('&_hash=', $signer->sign('http://example.com/foo?foo=bar'));
$this->assertStringContainsString('?_hash=', $signer->sign('http://example.com/foo'));
$this->assertStringContainsString('?_hash=', $signer->sign('http://example.com/foo?foo=bar'));
$this->assertStringContainsString('&foo=', $signer->sign('http://example.com/foo?foo=bar'));
}
public function testCheck()
@@ -36,7 +37,7 @@ class UriSignerTest extends TestCase
$this->assertTrue($signer->check($signer->sign('http://example.com/foo?foo=bar')));
$this->assertTrue($signer->check($signer->sign('http://example.com/foo?foo=bar&0=integer')));
$this->assertTrue($signer->sign('http://example.com/foo?foo=bar&bar=foo') === $signer->sign('http://example.com/foo?bar=foo&foo=bar'));
$this->assertSame($signer->sign('http://example.com/foo?foo=bar&bar=foo'), $signer->sign('http://example.com/foo?bar=foo&foo=bar'));
}
public function testCheckWithDifferentArgSeparator()
@@ -45,9 +46,31 @@ class UriSignerTest extends TestCase
$signer = new UriSigner('foobar');
$this->assertSame(
'http://example.com/foo?baz=bay&foo=bar&_hash=rIOcC%2FF3DoEGo%2FvnESjSp7uU9zA9S%2F%2BOLhxgMexoPUM%3D',
'http://example.com/foo?_hash=rIOcC%2FF3DoEGo%2FvnESjSp7uU9zA9S%2F%2BOLhxgMexoPUM%3D&baz=bay&foo=bar',
$signer->sign('http://example.com/foo?foo=bar&baz=bay')
);
$this->assertTrue($signer->check($signer->sign('http://example.com/foo?foo=bar&baz=bay')));
}
public function testCheckWithDifferentParameter()
{
$signer = new UriSigner('foobar', 'qux');
$this->assertSame(
'http://example.com/foo?baz=bay&foo=bar&qux=rIOcC%2FF3DoEGo%2FvnESjSp7uU9zA9S%2F%2BOLhxgMexoPUM%3D',
$signer->sign('http://example.com/foo?foo=bar&baz=bay')
);
$this->assertTrue($signer->check($signer->sign('http://example.com/foo?foo=bar&baz=bay')));
}
public function testSignerWorksWithFragments()
{
$signer = new UriSigner('foobar');
$this->assertSame(
'http://example.com/foo?_hash=EhpAUyEobiM3QTrKxoLOtQq5IsWyWedoXDPqIjzNj5o%3D&bar=foo&foo=bar#foobar',
$signer->sign('http://example.com/foo?bar=foo&foo=bar#foobar')
);
$this->assertTrue($signer->check($signer->sign('http://example.com/foo?bar=foo&foo=bar#foobar')));
}
}