Laravel version update

Laravel version update
This commit is contained in:
Manish Verma
2018-08-06 18:48:58 +05:30
parent d143048413
commit 126fbb0255
13678 changed files with 1031482 additions and 778530 deletions

View File

@@ -11,12 +11,15 @@
namespace Symfony\Component\HttpKernel\Tests\Bundle;
use Symfony\Component\HttpKernel\Tests\Fixtures\ExtensionNotValidBundle\ExtensionNotValidBundle;
use Symfony\Component\HttpKernel\Tests\Fixtures\ExtensionPresentBundle\ExtensionPresentBundle;
use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;
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 \PHPUnit_Framework_TestCase
class BundleTest extends TestCase
{
public function testGetContainerExtension()
{
@@ -28,10 +31,14 @@ class BundleTest extends \PHPUnit_Framework_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();
$app = $this->getMock('Symfony\Component\Console\Application');
$app = $this->getMockBuilder('Symfony\Component\Console\Application')->getMock();
$app->expects($this->once())->method('add')->with($this->equalTo($cmd));
$bundle = new ExtensionPresentBundle();
@@ -51,4 +58,47 @@ class BundleTest extends \PHPUnit_Framework_TestCase
$bundle = new ExtensionNotValidBundle();
$bundle->getContainerExtension();
}
public function testHttpKernelRegisterCommandsIgnoresCommandsThatAreRegisteredAsServices()
{
$container = new ContainerBuilder();
$container->register('console.command.symfony_component_httpkernel_tests_fixtures_extensionpresentbundle_command_foocommand', 'Symfony\Component\HttpKernel\Tests\Fixtures\ExtensionPresentBundle\Command\FooCommand');
$application = $this->getMockBuilder('Symfony\Component\Console\Application')->getMock();
// add() is never called when the found command classes are already registered as services
$application->expects($this->never())->method('add');
$bundle = new ExtensionPresentBundle();
$bundle->setContainer($container);
$bundle->registerCommands($application);
}
public function testBundleNameIsGuessedFromClass()
{
$bundle = new GuessedNameBundle();
$this->assertSame('Symfony\Component\HttpKernel\Tests\Bundle', $bundle->getNamespace());
$this->assertSame('GuessedNameBundle', $bundle->getName());
}
public function testBundleNameCanBeExplicitlyProvided()
{
$bundle = new NamedBundle();
$this->assertSame('ExplicitlyNamedBundle', $bundle->getName());
$this->assertSame('Symfony\Component\HttpKernel\Tests\Bundle', $bundle->getNamespace());
$this->assertSame('ExplicitlyNamedBundle', $bundle->getName());
}
}
class NamedBundle extends Bundle
{
public function __construct()
{
$this->name = 'ExplicitlyNamedBundle';
}
}
class GuessedNameBundle extends Bundle
{
}

View File

@@ -11,9 +11,10 @@
namespace Symfony\Component\HttpKernel\Tests\CacheClearer;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\CacheClearer\ChainCacheClearer;
class ChainCacheClearerTest extends \PHPUnit_Framework_TestCase
class ChainCacheClearerTest extends TestCase
{
protected static $cacheDir;
@@ -38,6 +39,9 @@ class ChainCacheClearerTest extends \PHPUnit_Framework_TestCase
$chainClearer->clear(self::$cacheDir);
}
/**
* @group legacy
*/
public function testInjectClearerUsingAdd()
{
$clearer = $this->getMockClearer();
@@ -52,6 +56,6 @@ class ChainCacheClearerTest extends \PHPUnit_Framework_TestCase
protected function getMockClearer()
{
return $this->getMock('Symfony\Component\HttpKernel\CacheClearer\CacheClearerInterface');
return $this->getMockBuilder('Symfony\Component\HttpKernel\CacheClearer\CacheClearerInterface')->getMock();
}
}

View File

@@ -0,0 +1,69 @@
<?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\CacheClearer;
use PHPUnit\Framework\TestCase;
use Psr\Cache\CacheItemPoolInterface;
use Symfony\Component\HttpKernel\CacheClearer\Psr6CacheClearer;
class Psr6CacheClearerTest extends TestCase
{
public function testClearPoolsInjectedInConstructor()
{
$pool = $this->getMockBuilder(CacheItemPoolInterface::class)->getMock();
$pool
->expects($this->once())
->method('clear');
(new Psr6CacheClearer(array('pool' => $pool)))->clear('');
}
public function testClearPool()
{
$pool = $this->getMockBuilder(CacheItemPoolInterface::class)->getMock();
$pool
->expects($this->once())
->method('clear');
(new Psr6CacheClearer(array('pool' => $pool)))->clearPool('pool');
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage Cache pool not found: unknown
*/
public function testClearPoolThrowsExceptionOnUnreferencedPool()
{
(new Psr6CacheClearer())->clearPool('unknown');
}
/**
* @group legacy
* @expectedDeprecation The Symfony\Component\HttpKernel\CacheClearer\Psr6CacheClearer::addPool() method is deprecated since Symfony 3.3 and will be removed in 4.0. Pass an array of pools indexed by name to the constructor instead.
*/
public function testClearPoolsInjectedByAdder()
{
$pool1 = $this->getMockBuilder(CacheItemPoolInterface::class)->getMock();
$pool1
->expects($this->once())
->method('clear');
$pool2 = $this->getMockBuilder(CacheItemPoolInterface::class)->getMock();
$pool2
->expects($this->once())
->method('clear');
$clearer = new Psr6CacheClearer(array('pool1' => $pool1));
$clearer->addPool($pool2);
$clearer->clear('');
}
}

View File

@@ -11,9 +11,10 @@
namespace Symfony\Component\HttpKernel\Tests\CacheWarmer;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerAggregate;
class CacheWarmerAggregateTest extends \PHPUnit_Framework_TestCase
class CacheWarmerAggregateTest extends TestCase
{
protected static $cacheDir;
@@ -37,6 +38,9 @@ class CacheWarmerAggregateTest extends \PHPUnit_Framework_TestCase
$aggregate->warmUp(self::$cacheDir);
}
/**
* @group legacy
*/
public function testInjectWarmersUsingAdd()
{
$warmer = $this->getCacheWarmerMock();
@@ -48,6 +52,9 @@ class CacheWarmerAggregateTest extends \PHPUnit_Framework_TestCase
$aggregate->warmUp(self::$cacheDir);
}
/**
* @group legacy
*/
public function testInjectWarmersUsingSetWarmers()
{
$warmer = $this->getCacheWarmerMock();

View File

@@ -11,9 +11,10 @@
namespace Symfony\Component\HttpKernel\Tests\CacheWarmer;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmer;
class CacheWarmerTest extends \PHPUnit_Framework_TestCase
class CacheWarmerTest extends TestCase
{
protected static $cacheFile;
@@ -30,7 +31,7 @@ class CacheWarmerTest extends \PHPUnit_Framework_TestCase
public function testWriteCacheFileCreatesTheFile()
{
$warmer = new TestCacheWarmer(self::$cacheFile);
$warmer->warmUp(dirname(self::$cacheFile));
$warmer->warmUp(\dirname(self::$cacheFile));
$this->assertFileExists(self::$cacheFile);
}
@@ -42,7 +43,7 @@ class CacheWarmerTest extends \PHPUnit_Framework_TestCase
{
$nonWritableFile = '/this/file/is/very/probably/not/writable';
$warmer = new TestCacheWarmer($nonWritableFile);
$warmer->warmUp(dirname($nonWritableFile));
$warmer->warmUp(\dirname($nonWritableFile));
}
}

View File

@@ -11,14 +11,18 @@
namespace Symfony\Component\HttpKernel\Tests;
use Symfony\Component\HttpKernel\Client;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\StreamedResponse;
use PHPUnit\Framework\TestCase;
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;
class ClientTest extends \PHPUnit_Framework_TestCase
/**
* @group time-sensitive
*/
class ClientTest extends TestCase
{
public function testDoRequest()
{
@@ -56,22 +60,17 @@ class ClientTest extends \PHPUnit_Framework_TestCase
$m = $r->getMethod('filterResponse');
$m->setAccessible(true);
$expected = 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',
);
$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);
$this->assertEquals($expected[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);
$this->assertEquals($expected[0], $domResponse->getHeader('Set-Cookie'));
$this->assertEquals($expected, $domResponse->getHeader('Set-Cookie', false));
$this->assertSame((string) $cookie1, $domResponse->getHeader('Set-Cookie'));
$this->assertSame(array((string) $cookie1, (string) $cookie2), $domResponse->getHeader('Set-Cookie', false));
}
public function testFilterResponseSupportsStreamedResponses()
@@ -93,6 +92,7 @@ class ClientTest extends \PHPUnit_Framework_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);
@@ -100,8 +100,8 @@ class ClientTest extends \PHPUnit_Framework_TestCase
$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),
array('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;
@@ -116,11 +116,11 @@ class ClientTest extends \PHPUnit_Framework_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);

View File

@@ -11,9 +11,13 @@
namespace Symfony\Component\HttpKernel\Tests\Config;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\Config\EnvParametersResource;
class EnvParametersResourceTest extends \PHPUnit_Framework_TestCase
/**
* @group legacy
*/
class EnvParametersResourceTest extends TestCase
{
protected $prefix = '__DUMMY_';
protected $initialEnv;

View File

@@ -11,13 +11,14 @@
namespace Symfony\Component\HttpKernel\Tests\Config;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\Config\FileLocator;
class FileLocatorTest extends \PHPUnit_Framework_TestCase
class FileLocatorTest extends TestCase
{
public function testLocate()
{
$kernel = $this->getMock('Symfony\Component\HttpKernel\KernelInterface');
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\KernelInterface')->getMock();
$kernel
->expects($this->atLeastOnce())
->method('locateResource')
@@ -29,13 +30,13 @@ class FileLocatorTest extends \PHPUnit_Framework_TestCase
$kernel
->expects($this->never())
->method('locateResource');
$this->setExpectedException('LogicException');
$this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}('LogicException');
$locator->locate('/some/path');
}
public function testLocateWithGlobalResourcePath()
{
$kernel = $this->getMock('Symfony\Component\HttpKernel\KernelInterface');
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\KernelInterface')->getMock();
$kernel
->expects($this->atLeastOnce())
->method('locateResource')

View File

@@ -0,0 +1,112 @@
<?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\Controller\ArgumentResolver;
use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\ServiceLocator;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Controller\ArgumentResolver\ServiceValueResolver;
use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata;
class ServiceValueResolverTest extends TestCase
{
public function testDoNotSupportWhenControllerDoNotExists()
{
$resolver = new ServiceValueResolver(new ServiceLocator(array()));
$argument = new ArgumentMetadata('dummy', DummyService::class, false, false, null);
$request = $this->requestWithAttributes(array('_controller' => 'my_controller'));
$this->assertFalse($resolver->supports($request, $argument));
}
public function testExistingController()
{
$resolver = new ServiceValueResolver(new ServiceLocator(array(
'App\\Controller\\Mine::method' => function () {
return new ServiceLocator(array(
'dummy' => function () {
return new DummyService();
},
));
},
)));
$request = $this->requestWithAttributes(array('_controller' => 'App\\Controller\\Mine::method'));
$argument = new ArgumentMetadata('dummy', DummyService::class, false, false, null);
$this->assertTrue($resolver->supports($request, $argument));
$this->assertYieldEquals(array(new DummyService()), $resolver->resolve($request, $argument));
}
public function testExistingControllerWithATrailingBackSlash()
{
$resolver = new ServiceValueResolver(new ServiceLocator(array(
'App\\Controller\\Mine::method' => function () {
return new ServiceLocator(array(
'dummy' => function () {
return new DummyService();
},
));
},
)));
$request = $this->requestWithAttributes(array('_controller' => '\\App\\Controller\\Mine::method'));
$argument = new ArgumentMetadata('dummy', DummyService::class, false, false, null);
$this->assertTrue($resolver->supports($request, $argument));
$this->assertYieldEquals(array(new DummyService()), $resolver->resolve($request, $argument));
}
public function testControllerNameIsAnArray()
{
$resolver = new ServiceValueResolver(new ServiceLocator(array(
'App\\Controller\\Mine::method' => function () {
return new ServiceLocator(array(
'dummy' => function () {
return new DummyService();
},
));
},
)));
$request = $this->requestWithAttributes(array('_controller' => array('App\\Controller\\Mine', 'method')));
$argument = new ArgumentMetadata('dummy', DummyService::class, false, false, null);
$this->assertTrue($resolver->supports($request, $argument));
$this->assertYieldEquals(array(new DummyService()), $resolver->resolve($request, $argument));
}
private function requestWithAttributes(array $attributes)
{
$request = Request::create('/');
foreach ($attributes as $name => $value) {
$request->attributes->set($name, $value);
}
return $request;
}
private function assertYieldEquals(array $expected, \Generator $generator)
{
$args = array();
foreach ($generator as $arg) {
$args[] = $arg;
}
$this->assertEquals($expected, $args);
}
}
class DummyService
{
}

View File

@@ -0,0 +1,349 @@
<?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\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\RequestAttributeValueResolver;
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;
class ArgumentResolverTest extends TestCase
{
/** @var ArgumentResolver */
private static $resolver;
public static function setUpBeforeClass()
{
$factory = new ArgumentMetadataFactory();
self::$resolver = new ArgumentResolver($factory);
}
public function testDefaultState()
{
$this->assertEquals(self::$resolver, new ArgumentResolver());
$this->assertNotEquals(self::$resolver, new ArgumentResolver(null, array(new RequestAttributeValueResolver())));
}
public function testGetArguments()
{
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$controller = array(new self(), 'controllerWithFoo');
$this->assertEquals(array('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');
$this->assertEquals(array(), 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');
$this->assertEquals(array('foo', null), self::$resolver->getArguments($request, $controller), '->getArguments() uses default values if present');
}
public function testGetArgumentsOverrideDefaultValueByRequestAttribute()
{
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$request->attributes->set('bar', 'bar');
$controller = array(new self(), 'controllerWithFooAndDefaultBar');
$this->assertEquals(array('foo', 'bar'), self::$resolver->getArguments($request, $controller), '->getArguments() overrides default values if provided in the request attributes');
}
public function testGetArgumentsFromClosure()
{
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$controller = function ($foo) {};
$this->assertEquals(array('foo'), self::$resolver->getArguments($request, $controller));
}
public function testGetArgumentsUsesDefaultValueFromClosure()
{
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$controller = function ($foo, $bar = 'bar') {};
$this->assertEquals(array('foo', 'bar'), self::$resolver->getArguments($request, $controller));
}
public function testGetArgumentsFromInvokableObject()
{
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$controller = new self();
$this->assertEquals(array('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));
}
public function testGetArgumentsFromFunctionName()
{
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$request->attributes->set('foobar', 'foobar');
$controller = __NAMESPACE__.'\controller_function';
$this->assertEquals(array('foo', 'foobar'), self::$resolver->getArguments($request, $controller));
}
public function testGetArgumentsFailsOnUnresolvedValue()
{
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$request->attributes->set('foobar', 'foobar');
$controller = array(new self(), 'controllerWithFooBarFoobar');
try {
self::$resolver->getArguments($request, $controller);
$this->fail('->getArguments() throws a \RuntimeException exception if it cannot determine the argument value');
} catch (\Exception $e) {
$this->assertInstanceOf('\RuntimeException', $e, '->getArguments() throws a \RuntimeException exception if it cannot determine the argument value');
}
}
public function testGetArgumentsInjectsRequest()
{
$request = Request::create('/');
$controller = array(new self(), 'controllerWithRequest');
$this->assertEquals(array($request), self::$resolver->getArguments($request, $controller), '->getArguments() injects the request');
}
public function testGetArgumentsInjectsExtendingRequest()
{
$request = ExtendingRequest::create('/');
$controller = array(new self(), 'controllerWithExtendingRequest');
$this->assertEquals(array($request), self::$resolver->getArguments($request, $controller), '->getArguments() injects the request when extended');
}
/**
* @requires PHP 5.6
*/
public function testGetVariadicArguments()
{
$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'), self::$resolver->getArguments($request, $controller));
}
/**
* @requires PHP 5.6
* @expectedException \InvalidArgumentException
*/
public function testGetVariadicArgumentsWithoutArrayInRequest()
{
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$request->attributes->set('bar', 'foo');
$controller = array(new VariadicController(), 'action');
self::$resolver->getArguments($request, $controller);
}
/**
* @requires PHP 5.6
* @expectedException \InvalidArgumentException
*/
public function testGetArgumentWithoutArray()
{
$factory = new ArgumentMetadataFactory();
$valueResolver = $this->getMockBuilder(ArgumentValueResolverInterface::class)->getMock();
$resolver = new ArgumentResolver($factory, array($valueResolver));
$valueResolver->expects($this->any())->method('supports')->willReturn(true);
$valueResolver->expects($this->any())->method('resolve')->willReturn('foo');
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$request->attributes->set('bar', 'foo');
$controller = array($this, 'controllerWithFooAndDefaultBar');
$resolver->getArguments($request, $controller);
}
/**
* @expectedException \RuntimeException
*/
public function testIfExceptionIsThrownWhenMissingAnArgument()
{
$request = Request::create('/');
$controller = array($this, 'controllerWithFoo');
self::$resolver->getArguments($request, $controller);
}
/**
* @requires PHP 7.1
*/
public function testGetNullableArguments()
{
$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'), self::$resolver->getArguments($request, $controller));
}
/**
* @requires PHP 7.1
*/
public function testGetNullableArgumentsWithDefaults()
{
$request = Request::create('/');
$request->attributes->set('mandatory', 'mandatory');
$controller = array(new NullableController(), 'action');
$this->assertEquals(array(null, null, 'value', 'mandatory'), self::$resolver->getArguments($request, $controller));
}
public function testGetSessionArguments()
{
$session = new Session(new MockArraySessionStorage());
$request = Request::create('/');
$request->setSession($session);
$controller = array($this, 'controllerWithSession');
$this->assertEquals(array($session), self::$resolver->getArguments($request, $controller));
}
public function testGetSessionArgumentsWithExtendedSession()
{
$session = new ExtendingSession(new MockArraySessionStorage());
$request = Request::create('/');
$request->setSession($session);
$controller = array($this, 'controllerWithExtendingSession');
$this->assertEquals(array($session), self::$resolver->getArguments($request, $controller));
}
public function testGetSessionArgumentsWithInterface()
{
$session = $this->getMockBuilder(SessionInterface::class)->getMock();
$request = Request::create('/');
$request->setSession($session);
$controller = array($this, 'controllerWithSessionInterface');
$this->assertEquals(array($session), self::$resolver->getArguments($request, $controller));
}
/**
* @expectedException \RuntimeException
*/
public function testGetSessionMissMatchWithInterface()
{
$session = $this->getMockBuilder(SessionInterface::class)->getMock();
$request = Request::create('/');
$request->setSession($session);
$controller = array($this, 'controllerWithExtendingSession');
self::$resolver->getArguments($request, $controller);
}
/**
* @expectedException \RuntimeException
*/
public function testGetSessionMissMatchWithImplementation()
{
$session = new Session(new MockArraySessionStorage());
$request = Request::create('/');
$request->setSession($session);
$controller = array($this, 'controllerWithExtendingSession');
self::$resolver->getArguments($request, $controller);
}
/**
* @expectedException \RuntimeException
*/
public function testGetSessionMissMatchOnNull()
{
$request = Request::create('/');
$controller = array($this, 'controllerWithExtendingSession');
self::$resolver->getArguments($request, $controller);
}
public function __invoke($foo, $bar = null)
{
}
public function controllerWithFoo($foo)
{
}
public function controllerWithoutArguments()
{
}
protected function controllerWithFooAndDefaultBar($foo, $bar = null)
{
}
protected function controllerWithFooBarFoobar($foo, $bar, $foobar)
{
}
protected function controllerWithRequest(Request $request)
{
}
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)
{
}

View File

@@ -0,0 +1,308 @@
<?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\Controller;
use Psr\Container\ContainerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\Debug\ErrorHandler;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Controller\ContainerControllerResolver;
class ContainerControllerResolverTest extends ControllerResolverTest
{
public function testGetControllerService()
{
$container = $this->createMockContainer();
$container->expects($this->once())
->method('has')
->with('foo')
->will($this->returnValue(true));
$container->expects($this->once())
->method('get')
->with('foo')
->will($this->returnValue($this))
;
$resolver = $this->createControllerResolver(null, $container);
$request = Request::create('/');
$request->attributes->set('_controller', 'foo:controllerMethod1');
$controller = $resolver->getController($request);
$this->assertInstanceOf(\get_class($this), $controller[0]);
$this->assertSame('controllerMethod1', $controller[1]);
}
public function testGetControllerInvokableService()
{
$invokableController = new InvokableController('bar');
$container = $this->createMockContainer();
$container->expects($this->once())
->method('has')
->with('foo')
->will($this->returnValue(true))
;
$container->expects($this->once())
->method('get')
->with('foo')
->will($this->returnValue($invokableController))
;
$resolver = $this->createControllerResolver(null, $container);
$request = Request::create('/');
$request->attributes->set('_controller', 'foo');
$controller = $resolver->getController($request);
$this->assertEquals($invokableController, $controller);
}
public function testGetControllerInvokableServiceWithClassNameAsName()
{
$invokableController = new InvokableController('bar');
$className = __NAMESPACE__.'\InvokableController';
$container = $this->createMockContainer();
$container->expects($this->once())
->method('has')
->with($className)
->will($this->returnValue(true))
;
$container->expects($this->once())
->method('get')
->with($className)
->will($this->returnValue($invokableController))
;
$resolver = $this->createControllerResolver(null, $container);
$request = Request::create('/');
$request->attributes->set('_controller', $className);
$controller = $resolver->getController($request);
$this->assertEquals($invokableController, $controller);
}
public function testNonInstantiableController()
{
$container = $this->createMockContainer();
$container->expects($this->once())
->method('has')
->with(NonInstantiableController::class)
->will($this->returnValue(false))
;
$resolver = $this->createControllerResolver(null, $container);
$request = Request::create('/');
$request->attributes->set('_controller', array(NonInstantiableController::class, 'action'));
$controller = $resolver->getController($request);
$this->assertSame(array(NonInstantiableController::class, 'action'), $controller);
}
/**
* @expectedException \LogicException
* @expectedExceptionMessage Controller "Symfony\Component\HttpKernel\Tests\Controller\ImpossibleConstructController" cannot be fetched from the container because it is private. Did you forget to tag the service with "controller.service_arguments"?
*/
public function testNonConstructController()
{
$container = $this->getMockBuilder(Container::class)->getMock();
$container->expects($this->at(0))
->method('has')
->with(ImpossibleConstructController::class)
->will($this->returnValue(true))
;
$container->expects($this->at(1))
->method('has')
->with(ImpossibleConstructController::class)
->will($this->returnValue(false))
;
$container->expects($this->atLeastOnce())
->method('getRemovedIds')
->with()
->will($this->returnValue(array(ImpossibleConstructController::class => true)))
;
$resolver = $this->createControllerResolver(null, $container);
$request = Request::create('/');
$request->attributes->set('_controller', array(ImpossibleConstructController::class, 'action'));
if (\PHP_VERSION_ID < 70100) {
ErrorHandler::register();
try {
$resolver->getController($request);
} finally {
restore_error_handler();
restore_exception_handler();
}
} else {
$resolver->getController($request);
}
}
public function testNonInstantiableControllerWithCorrespondingService()
{
$service = new \stdClass();
$container = $this->createMockContainer();
$container->expects($this->atLeastOnce())
->method('has')
->with(NonInstantiableController::class)
->will($this->returnValue(true))
;
$container->expects($this->atLeastOnce())
->method('get')
->with(NonInstantiableController::class)
->will($this->returnValue($service))
;
$resolver = $this->createControllerResolver(null, $container);
$request = Request::create('/');
$request->attributes->set('_controller', array(NonInstantiableController::class, 'action'));
$controller = $resolver->getController($request);
$this->assertSame(array($service, 'action'), $controller);
}
/**
* @expectedException \LogicException
* @expectedExceptionMessage Controller "app.my_controller" cannot be fetched from the container because it is private. Did you forget to tag the service with "controller.service_arguments"?
*/
public function testExceptionWhenUsingRemovedControllerService()
{
$container = $this->getMockBuilder(Container::class)->getMock();
$container->expects($this->at(0))
->method('has')
->with('app.my_controller')
->will($this->returnValue(false))
;
$container->expects($this->atLeastOnce())
->method('getRemovedIds')
->with()
->will($this->returnValue(array('app.my_controller' => true)))
;
$resolver = $this->createControllerResolver(null, $container);
$request = Request::create('/');
$request->attributes->set('_controller', 'app.my_controller');
$resolver->getController($request);
}
/**
* @expectedException \LogicException
* @expectedExceptionMessage Controller "app.my_controller" cannot be called without a method name. Did you forget an "__invoke" method?
*/
public function testExceptionWhenUsingControllerWithoutAnInvokeMethod()
{
$container = $this->getMockBuilder(Container::class)->getMock();
$container->expects($this->once())
->method('has')
->with('app.my_controller')
->will($this->returnValue(true))
;
$container->expects($this->once())
->method('get')
->with('app.my_controller')
->will($this->returnValue(new ImpossibleConstructController('toto', 'controller')))
;
$resolver = $this->createControllerResolver(null, $container);
$request = Request::create('/');
$request->attributes->set('_controller', 'app.my_controller');
$resolver->getController($request);
}
/**
* @dataProvider getUndefinedControllers
*/
public function testGetControllerOnNonUndefinedFunction($controller, $exceptionName = null, $exceptionMessage = null)
{
// All this logic needs to be duplicated, since calling parent::testGetControllerOnNonUndefinedFunction will override the expected excetion and not use the regex
$resolver = $this->createControllerResolver();
if (method_exists($this, 'expectException')) {
$this->expectException($exceptionName);
$this->expectExceptionMessageRegExp($exceptionMessage);
} else {
$this->setExpectedExceptionRegExp($exceptionName, $exceptionMessage);
}
$request = Request::create('/');
$request->attributes->set('_controller', $controller);
$resolver->getController($request);
}
public function getUndefinedControllers()
{
return array(
array('foo', \LogicException::class, '/Controller not found: service "foo" does not exist\./'),
array('oof::bar', \InvalidArgumentException::class, '/Class "oof" does not exist\./'),
array('stdClass', \LogicException::class, '/Controller not found: service "stdClass" does not exist\./'),
array(
'Symfony\Component\HttpKernel\Tests\Controller\ControllerResolverTest::bar',
\InvalidArgumentException::class,
'/.?[cC]ontroller(.*?) for URI "\/" is not callable\.( Expected method(.*) Available methods)?/',
),
);
}
protected function createControllerResolver(LoggerInterface $logger = null, ContainerInterface $container = null)
{
if (!$container) {
$container = $this->createMockContainer();
}
return new ContainerControllerResolver($container, $logger);
}
protected function createMockContainer()
{
return $this->getMockBuilder(ContainerInterface::class)->getMock();
}
}
class InvokableController
{
public function __construct($bar) // mandatory argument to prevent automatic instantiation
{
}
public function __invoke()
{
}
}
abstract class NonInstantiableController
{
public static function action()
{
}
}
class ImpossibleConstructController
{
public function __construct($toto, $controller)
{
}
public function action()
{
}
}

View File

@@ -11,16 +11,18 @@
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\VariadicController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Controller\ControllerResolver;
use Symfony\Component\HttpKernel\Tests\Fixtures\Controller\NullableController;
use Symfony\Component\HttpKernel\Tests\Fixtures\Controller\VariadicController;
class ControllerResolverTest extends \PHPUnit_Framework_TestCase
class ControllerResolverTest extends TestCase
{
public function testGetControllerWithoutControllerParameter()
{
$logger = $this->getMock('Psr\Log\LoggerInterface');
$logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
$logger->expects($this->once())->method('warning')->with('Unable to look for the controller as the "_controller" parameter is missing.');
$resolver = $this->createControllerResolver($logger);
@@ -116,7 +118,12 @@ class ControllerResolverTest extends \PHPUnit_Framework_TestCase
public function testGetControllerOnNonUndefinedFunction($controller, $exceptionName = null, $exceptionMessage = null)
{
$resolver = $this->createControllerResolver();
$this->setExpectedException($exceptionName, $exceptionMessage);
if (method_exists($this, 'expectException')) {
$this->expectException($exceptionName);
$this->expectExceptionMessage($exceptionMessage);
} else {
$this->setExpectedException($exceptionName, $exceptionMessage);
}
$request = Request::create('/');
$request->attributes->set('_controller', $controller);
@@ -137,6 +144,9 @@ class ControllerResolverTest extends \PHPUnit_Framework_TestCase
);
}
/**
* @group legacy
*/
public function testGetArguments()
{
$resolver = $this->createControllerResolver();
@@ -200,6 +210,7 @@ class ControllerResolverTest extends \PHPUnit_Framework_TestCase
/**
* @requires PHP 5.6
* @group legacy
*/
public function testGetVariadicArguments()
{
@@ -214,7 +225,7 @@ class ControllerResolverTest extends \PHPUnit_Framework_TestCase
public function testCreateControllerCanReturnAnyCallable()
{
$mock = $this->getMock('Symfony\Component\HttpKernel\Controller\ControllerResolver', array('createController'));
$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'));
$request = Request::create('/');
@@ -222,6 +233,50 @@ class ControllerResolverTest extends \PHPUnit_Framework_TestCase
$mock->getController($request);
}
/**
* @expectedException \RuntimeException
* @group legacy
*/
public function testIfExceptionIsThrownWhenMissingAnArgument()
{
$resolver = new ControllerResolver();
$request = Request::create('/');
$controller = array($this, 'controllerMethod1');
$resolver->getArguments($request, $controller);
}
/**
* @requires PHP 7.1
* @group legacy
*/
public function testGetNullableArguments()
{
$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));
}
/**
* @requires PHP 7.1
* @group legacy
*/
public function testGetNullableArgumentsWithDefaults()
{
$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));
}
protected function createControllerResolver(LoggerInterface $logger = null)
{
return new ControllerResolver($logger);

View File

@@ -0,0 +1,148 @@
<?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\ControllerMetadata;
use Fake\ImportedAndFake;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata;
use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadataFactory;
use Symfony\Component\HttpKernel\Tests\Fixtures\Controller\BasicTypesController;
use Symfony\Component\HttpKernel\Tests\Fixtures\Controller\NullableController;
use Symfony\Component\HttpKernel\Tests\Fixtures\Controller\VariadicController;
class ArgumentMetadataFactoryTest extends TestCase
{
/**
* @var ArgumentMetadataFactory
*/
private $factory;
protected function setUp()
{
$this->factory = new ArgumentMetadataFactory();
}
public function testSignature1()
{
$arguments = $this->factory->createArgumentMetadata(array($this, 'signature1'));
$this->assertEquals(array(
new ArgumentMetadata('foo', self::class, false, false, null),
new ArgumentMetadata('bar', 'array', false, false, null),
new ArgumentMetadata('baz', 'callable', false, false, null),
), $arguments);
}
public function testSignature2()
{
$arguments = $this->factory->createArgumentMetadata(array($this, 'signature2'));
$this->assertEquals(array(
new ArgumentMetadata('foo', self::class, false, true, null, true),
new ArgumentMetadata('bar', __NAMESPACE__.'\FakeClassThatDoesNotExist', false, true, null, true),
new ArgumentMetadata('baz', 'Fake\ImportedAndFake', false, true, null, true),
), $arguments);
}
public function testSignature3()
{
$arguments = $this->factory->createArgumentMetadata(array($this, 'signature3'));
$this->assertEquals(array(
new ArgumentMetadata('bar', __NAMESPACE__.'\FakeClassThatDoesNotExist', false, false, null),
new ArgumentMetadata('baz', 'Fake\ImportedAndFake', false, false, null),
), $arguments);
}
public function testSignature4()
{
$arguments = $this->factory->createArgumentMetadata(array($this, 'signature4'));
$this->assertEquals(array(
new ArgumentMetadata('foo', null, false, true, 'default'),
new ArgumentMetadata('bar', null, false, true, 500),
new ArgumentMetadata('baz', null, false, true, array()),
), $arguments);
}
public function testSignature5()
{
$arguments = $this->factory->createArgumentMetadata(array($this, 'signature5'));
$this->assertEquals(array(
new ArgumentMetadata('foo', 'array', false, true, null, true),
new ArgumentMetadata('bar', null, false, false, null),
), $arguments);
}
/**
* @requires PHP 5.6
*/
public function testVariadicSignature()
{
$arguments = $this->factory->createArgumentMetadata(array(new VariadicController(), 'action'));
$this->assertEquals(array(
new ArgumentMetadata('foo', null, false, false, null),
new ArgumentMetadata('bar', null, true, false, null),
), $arguments);
}
/**
* @requires PHP 7.0
*/
public function testBasicTypesSignature()
{
$arguments = $this->factory->createArgumentMetadata(array(new BasicTypesController(), 'action'));
$this->assertEquals(array(
new ArgumentMetadata('foo', 'string', false, false, null),
new ArgumentMetadata('bar', 'int', false, false, null),
new ArgumentMetadata('baz', 'float', false, false, null),
), $arguments);
}
/**
* @requires PHP 7.1
*/
public function testNullableTypesSignature()
{
$arguments = $this->factory->createArgumentMetadata(array(new NullableController(), 'action'));
$this->assertEquals(array(
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);
}
private function signature1(self $foo, array $bar, callable $baz)
{
}
private function signature2(self $foo = null, FakeClassThatDoesNotExist $bar = null, ImportedAndFake $baz = null)
{
}
private function signature3(FakeClassThatDoesNotExist $bar, ImportedAndFake $baz)
{
}
private function signature4($foo = 'default', $bar = 500, $baz = array())
{
}
private function signature5(array $foo = null, $bar)
{
}
}

View File

@@ -0,0 +1,46 @@
<?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\ControllerMetadata;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata;
class ArgumentMetadataTest extends TestCase
{
public function testWithBcLayerWithDefault()
{
$argument = new ArgumentMetadata('foo', 'string', false, true, 'default value');
$this->assertFalse($argument->isNullable());
}
public function testDefaultValueAvailable()
{
$argument = new ArgumentMetadata('foo', 'string', false, true, 'default value', true);
$this->assertTrue($argument->isNullable());
$this->assertTrue($argument->hasDefaultValue());
$this->assertSame('default value', $argument->getDefaultValue());
}
/**
* @expectedException \LogicException
*/
public function testDefaultValueUnavailable()
{
$argument = new ArgumentMetadata('foo', 'string', false, false, null, false);
$this->assertFalse($argument->isNullable());
$this->assertFalse($argument->hasDefaultValue());
$argument->getDefaultValue();
}
}

View File

@@ -0,0 +1,4 @@
Symfony\Component\DependencyInjection\Compiler\RemovePrivateAliasesPass: Removed service "Psr\Container\ContainerInterface"; reason: private alias.
Symfony\Component\DependencyInjection\Compiler\RemovePrivateAliasesPass: Removed service "Symfony\Component\DependencyInjection\ContainerInterface"; reason: private alias.
Some custom logging message
With ending :

View File

@@ -11,19 +11,19 @@
namespace Symfony\Component\HttpKernel\Tests\DataCollector;
use Symfony\Component\HttpKernel\DataCollector\ConfigDataCollector;
use Symfony\Component\HttpKernel\Kernel;
use PHPUnit\Framework\TestCase;
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 \PHPUnit_Framework_TestCase
class ConfigDataCollectorTest extends TestCase
{
public function testCollect()
{
$kernel = new KernelForTest('test', true);
$c = new ConfigDataCollector();
$c->setCacheVersionInfo(false);
$c->setKernel($kernel);
$c->collect(new Request(), new Response());
@@ -31,31 +31,16 @@ class ConfigDataCollectorTest extends \PHPUnit_Framework_TestCase
$this->assertTrue($c->isDebug());
$this->assertSame('config', $c->getName());
$this->assertSame('testkernel', $c->getAppName());
$this->assertSame(PHP_VERSION, $c->getPhpVersion());
$this->assertRegExp('~^'.preg_quote($c->getPhpVersion(), '~').'~', PHP_VERSION);
$this->assertRegExp('~'.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') && ini_get('opcache.enable'), $c->hasZendOpcache());
$this->assertSame(\extension_loaded('apcu') && ini_get('apc.enabled'), $c->hasApcu());
}
}

View File

@@ -0,0 +1,38 @@
<?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\DataCollector;
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\VarCloner;
class DataCollectorTest extends TestCase
{
public function testCloneVarStringWithScheme()
{
$c = new CloneVarDataCollector('scheme://foo');
$c->collect(new Request(), new Response());
$cloner = new VarCloner();
$this->assertEquals($cloner->cloneVar('scheme://foo'), $c->getData());
}
public function testCloneVarExistingFilePath()
{
$c = new CloneVarDataCollector(array($filePath = tempnam(sys_get_temp_dir(), 'clone_var_data_collector_')));
$c->collect(new Request(), new Response());
$this->assertSame($filePath, $c->getData()[0]);
}
}

View File

@@ -11,15 +11,17 @@
namespace Symfony\Component\HttpKernel\Tests\DataCollector;
use Symfony\Component\HttpKernel\DataCollector\DumpDataCollector;
use PHPUnit\Framework\TestCase;
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>
*/
class DumpDataCollectorTest extends \PHPUnit_Framework_TestCase
class DumpDataCollectorTest extends TestCase
{
public function testDump()
{
@@ -34,7 +36,7 @@ class DumpDataCollectorTest extends \PHPUnit_Framework_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']);
@@ -49,13 +51,9 @@ class DumpDataCollectorTest extends \PHPUnit_Framework_TestCase
);
$this->assertEquals($xDump, $dump);
$this->assertStringMatchesFormat(
'a:1:{i:0;a:5:{s:4:"data";O:39:"Symfony\Component\VarDumper\Cloner\Data":4:{s:45:"Symfony\Component\VarDumper\Cloner\Datadata";a:1:{i:0;a:1:{i:0;i:123;}}s:49:"Symfony\Component\VarDumper\Cloner\DatamaxDepth";i:%i;s:57:"Symfony\Component\VarDumper\Cloner\DatamaxItemsPerDepth";i:%i;s:54:"Symfony\Component\VarDumper\Cloner\DatauseRefHandles";i:%i;}s:4:"name";s:25:"DumpDataCollectorTest.php";s:4:"file";s:%a',
str_replace("\0", '', $collector->serialize())
);
$this->assertStringMatchesFormat('a:3:{i:0;a:5:{s:4:"data";%c:39:"Symfony\Component\VarDumper\Cloner\Data":%a', $collector->serialize());
$this->assertSame(0, $collector->getDumpsCount());
$this->assertSame('a:0:{}', $collector->serialize());
$this->assertSame('a:2:{i:0;b:0;i:1;s:5:"UTF-8";}', $collector->serialize());
}
public function testCollectDefault()
@@ -69,7 +67,7 @@ class DumpDataCollectorTest extends \PHPUnit_Framework_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());
@@ -86,10 +84,9 @@ class DumpDataCollectorTest extends \PHPUnit_Framework_TestCase
$line = __LINE__ - 1;
$file = __FILE__;
$xOutput = <<<EOTXT
<pre class=sf-dump id=sf-dump data-indent-pad=" "><a href="test://{$file}:{$line}" title="{$file}"><span class=sf-dump-meta>DumpDataCollectorTest.php</span></a> on line <span class=sf-dump-meta>{$line}</span>:
<pre class=sf-dump id=sf-dump data-indent-pad=" "><a href="test://{$file}:{$line}" title="{$file}"><span class=sf-dump-meta>DumpDataCollectorTest.php</span></a> on line <span class=sf-dump-meta>{$line}</span>:
<span class=sf-dump-num>123</span>
</pre>
EOTXT;
ob_start();
@@ -100,7 +97,7 @@ EOTXT;
$output = preg_replace('#<(script|style).*?</\1>#s', '', $output);
$output = preg_replace('/sf-dump-\d+/', 'sf-dump', $output);
$this->assertSame($xOutput, $output);
$this->assertSame($xOutput, trim($output));
$this->assertSame(1, $collector->getDumpsCount());
$collector->serialize();
}
@@ -114,6 +111,28 @@ EOTXT;
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(array(array(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());
if (\PHP_VERSION_ID >= 50400) {
$this->assertSame("DumpDataCollectorTest.php on line {$line}:\n456\n", $output);
} else {
$this->assertSame("\"DumpDataCollectorTest.php on line {$line}:\"\n456\n", $output);
}
ob_start();
$collector->__destruct();
$this->assertEmpty(ob_get_clean());
}
}

View File

@@ -11,12 +11,13 @@
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 \PHPUnit_Framework_TestCase
class ExceptionDataCollectorTest extends TestCase
{
public function testCollect()
{
@@ -36,4 +37,23 @@ class ExceptionDataCollectorTest extends \PHPUnit_Framework_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());
}
}

View File

@@ -11,85 +11,134 @@
namespace Symfony\Component\HttpKernel\Tests\DataCollector;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Debug\Exception\SilencedErrorContext;
use Symfony\Component\HttpKernel\DataCollector\LoggerDataCollector;
class LoggerDataCollectorTest extends \PHPUnit_Framework_TestCase
class LoggerDataCollectorTest extends TestCase
{
public function testCollectWithUnexpectedFormat()
{
$logger = $this
->getMockBuilder('Symfony\Component\HttpKernel\Log\DebugLoggerInterface')
->setMethods(array('countErrors', 'getLogs', 'clear'))
->getMock();
$logger->expects($this->once())->method('countErrors')->will($this->returnValue('foo'));
$logger->expects($this->exactly(2))->method('getLogs')->will($this->returnValue(array()));
$c = new LoggerDataCollector($logger, __DIR__.'/');
$c->lateCollect();
$compilerLogs = $c->getCompilerLogs()->getValue('message');
$this->assertSame(array(
array('message' => 'Removed service "Psr\Container\ContainerInterface"; reason: private alias.'),
array('message' => 'Removed service "Symfony\Component\DependencyInjection\ContainerInterface"; reason: private alias.'),
), $compilerLogs['Symfony\Component\DependencyInjection\Compiler\RemovePrivateAliasesPass']);
$this->assertSame(array(
array('message' => 'Some custom logging message'),
array('message' => 'With ending :'),
), $compilerLogs['Unknown Compiler Pass']);
}
/**
* @dataProvider getCollectTestData
*/
public function testCollect($nb, $logs, $expectedLogs, $expectedDeprecationCount, $expectedScreamCount, $expectedPriorities = null)
{
$logger = $this->getMock('Symfony\Component\HttpKernel\Log\DebugLoggerInterface');
$logger = $this
->getMockBuilder('Symfony\Component\HttpKernel\Log\DebugLoggerInterface')
->setMethods(array('countErrors', 'getLogs', 'clear'))
->getMock();
$logger->expects($this->once())->method('countErrors')->will($this->returnValue($nb));
$logger->expects($this->exactly(2))->method('getLogs')->will($this->returnValue($logs));
$c = new LoggerDataCollector($logger);
$c->lateCollect();
$this->assertSame('logger', $c->getName());
$this->assertSame($nb, $c->countErrors());
$this->assertSame($expectedLogs ?: $logs, $c->getLogs());
$this->assertSame($expectedDeprecationCount, $c->countDeprecations());
$this->assertSame($expectedScreamCount, $c->countScreams());
$this->assertEquals('logger', $c->getName());
$this->assertEquals($nb, $c->countErrors());
$logs = array_map(function ($v) {
if (isset($v['context']['exception'])) {
$e = &$v['context']['exception'];
$e = isset($e["\0*\0message"]) ? array($e["\0*\0message"], $e["\0*\0severity"]) : array($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(array('countErrors', 'getLogs', 'clear'))
->getMock();
$logger->expects($this->once())->method('clear');
$c = new LoggerDataCollector($logger);
$c->reset();
}
public function getCollectTestData()
{
return array(
yield 'simple log' => array(
1,
array(array('message' => 'foo', 'context' => array(), 'priority' => 100, 'priorityName' => 'DEBUG')),
array(array('message' => 'foo', 'context' => array(), 'priority' => 100, 'priorityName' => 'DEBUG')),
0,
0,
);
yield 'log with a context' => array(
1,
array(array('message' => 'foo', 'context' => array('foo' => 'bar'), 'priority' => 100, 'priorityName' => 'DEBUG')),
array(array('message' => 'foo', 'context' => array('foo' => 'bar'), 'priority' => 100, 'priorityName' => 'DEBUG')),
0,
0,
);
if (!class_exists(SilencedErrorContext::class)) {
return;
}
yield 'logs with some deprecations' => array(
1,
array(
1,
array(array('message' => 'foo', 'context' => array(), 'priority' => 100, 'priorityName' => 'DEBUG')),
null,
0,
0,
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(
1,
array(array('message' => 'foo', 'context' => array('foo' => fopen(__FILE__, 'r')), 'priority' => 100, 'priorityName' => 'DEBUG')),
array(array('message' => 'foo', 'context' => array('foo' => 'Resource(stream)'), 'priority' => 100, 'priorityName' => 'DEBUG')),
0,
0,
array('message' => 'foo3', 'context' => array('exception' => array('warning', E_USER_WARNING)), 'priority' => 100, 'priorityName' => 'DEBUG'),
array('message' => 'foo', 'context' => array('exception' => array('deprecated', E_DEPRECATED)), 'priority' => 100, 'priorityName' => 'DEBUG', 'errorCount' => 1, 'scream' => false),
array('message' => 'foo2', 'context' => array('exception' => array('deprecated', E_USER_DEPRECATED)), 'priority' => 100, 'priorityName' => 'DEBUG', 'errorCount' => 1, 'scream' => false),
),
2,
0,
array(100 => array('count' => 3, 'name' => 'DEBUG')),
);
yield 'logs with some silent errors' => array(
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(
1,
array(array('message' => 'foo', 'context' => array('foo' => new \stdClass()), 'priority' => 100, 'priorityName' => 'DEBUG')),
array(array('message' => 'foo', 'context' => array('foo' => 'Object(stdClass)'), 'priority' => 100, 'priorityName' => 'DEBUG')),
0,
0,
),
array(
1,
array(
array('message' => 'foo', 'context' => array('type' => E_DEPRECATED, 'level' => E_ALL), 'priority' => 100, 'priorityName' => 'DEBUG'),
array('message' => 'foo2', 'context' => array('type' => E_USER_DEPRECATED, 'level' => E_ALL), 'priority' => 100, 'priorityName' => 'DEBUG'),
),
null,
2,
0,
array(100 => array('count' => 2, 'name' => 'DEBUG')),
),
array(
1,
array(array('message' => 'foo3', 'context' => array('name' => 'E_USER_WARNING', 'type' => E_USER_WARNING, 'level' => 0, 'file' => __FILE__, 'line' => 123), 'priority' => 100, 'priorityName' => 'DEBUG')),
array(array('message' => 'foo3', 'context' => array('name' => 'E_USER_WARNING', 'type' => E_USER_WARNING, 'level' => 0, 'file' => __FILE__, 'line' => 123, 'scream' => true), 'priority' => 100, 'priorityName' => 'DEBUG')),
0,
1,
),
array(
1,
array(
array('message' => 'foo3', 'context' => array('type' => E_USER_WARNING, 'level' => 0, 'file' => __FILE__, 'line' => 123), 'priority' => 100, 'priorityName' => 'DEBUG'),
array('message' => 'foo3', 'context' => array('type' => E_USER_WARNING, 'level' => -1, 'file' => __FILE__, 'line' => 123), 'priority' => 100, 'priorityName' => 'DEBUG'),
),
array(array('message' => 'foo3', 'context' => array('name' => 'E_USER_WARNING', 'type' => E_USER_WARNING, 'level' => -1, 'file' => __FILE__, 'line' => 123, 'errorCount' => 2), 'priority' => 100, 'priorityName' => 'DEBUG')),
0,
1,
array('message' => 'foo3', 'context' => array('exception' => array('warning', E_USER_WARNING)), 'priority' => 100, 'priorityName' => 'DEBUG'),
array('message' => 'foo3', 'context' => array('exception' => array(E_USER_WARNING)), 'priority' => 100, 'priorityName' => 'DEBUG', 'errorCount' => 1, 'scream' => true),
),
0,
1,
);
}
}

View File

@@ -11,11 +11,12 @@
namespace Symfony\Component\HttpKernel\Tests\DataCollector;
use Symfony\Component\HttpKernel\DataCollector\MemoryDataCollector;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\DataCollector\MemoryDataCollector;
class MemoryDataCollectorTest extends \PHPUnit_Framework_TestCase
class MemoryDataCollectorTest extends TestCase
{
public function testCollect()
{

View File

@@ -11,62 +11,95 @@
namespace Symfony\Component\HttpKernel\Tests\DataCollector;
use Symfony\Component\HttpKernel\HttpKernel;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\DataCollector\RequestDataCollector;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
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\Cookie;
use Symfony\Component\EventDispatcher\EventDispatcher;
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;
class RequestDataCollectorTest extends \PHPUnit_Framework_TestCase
class RequestDataCollectorTest extends TestCase
{
public function testCollect()
{
$c = new RequestDataCollector();
$c->collect($this->createRequest(), $this->createResponse());
$c->collect($request = $this->createRequest(), $this->createResponse());
$c->lateCollect();
$attributes = $c->getRequestAttributes();
$this->assertSame('request', $c->getName());
$this->assertInstanceOf('Symfony\Component\HttpFoundation\HeaderBag', $c->getRequestHeaders());
$this->assertInstanceOf('Symfony\Component\HttpFoundation\ParameterBag', $c->getRequestHeaders());
$this->assertInstanceOf('Symfony\Component\HttpFoundation\ParameterBag', $c->getRequestServer());
$this->assertInstanceOf('Symfony\Component\HttpFoundation\ParameterBag', $c->getRequestCookies());
$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->assertSame('foobar', $c->getRoute());
$this->assertSame(array('name' => 'foo'), $c->getRouteParams());
$this->assertEquals('foobar', $c->getRoute());
$this->assertEquals(array('name' => 'foo'), $c->getRouteParams());
$this->assertSame(array(), $c->getSessionAttributes());
$this->assertSame('en', $c->getLocale());
$this->assertRegExp('/Resource\(stream#\d+\)/', $attributes->get('resource'));
$this->assertSame('Object(stdClass)', $attributes->get('object'));
$this->assertContains(__FILE__, $attributes->get('resource'));
$this->assertSame('stdClass', $attributes->get('object')->getType());
$this->assertInstanceOf('Symfony\Component\HttpFoundation\HeaderBag', $c->getResponseHeaders());
$this->assertInstanceOf('Symfony\Component\HttpFoundation\ParameterBag', $c->getResponseHeaders());
$this->assertSame('OK', $c->getStatusText());
$this->assertSame(200, $c->getStatusCode());
$this->assertSame('application/json', $c->getContentType());
}
public function testCollectWithoutRouteParams()
{
$request = $this->createRequest(array());
$c = new RequestDataCollector();
$c->collect($request, $this->createResponse());
$c->lateCollect();
$this->assertEquals(array(), $c->getRouteParams());
}
/**
* Test various types of controller callables.
* @dataProvider provideControllerCallables
*/
public function testControllerInspection()
public function testControllerInspection($name, $callable, $expected)
{
$c = new RequestDataCollector();
$request = $this->createRequest();
$response = $this->createResponse();
$this->injectController($c, $callable, $request);
$c->collect($request, $response);
$c->lateCollect();
$this->assertSame($expected, $c->getController()->getValue(true), sprintf('Testing: %s', $name));
}
public function provideControllerCallables()
{
// make sure we always match the line number
$r1 = new \ReflectionMethod($this, 'testControllerInspection');
$r2 = new \ReflectionMethod($this, 'staticControllerMethod');
$r3 = new \ReflectionClass($this);
// test name, callable, expected
$controllerTests = array(
return array(
array(
'"Regular" callable',
array($this, 'testControllerInspection'),
array(
'class' => 'Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest',
'class' => __NAMESPACE__.'\RequestDataCollectorTest',
'method' => 'testControllerInspection',
'file' => __FILE__,
'line' => $r1->getStartLine(),
@@ -86,8 +119,13 @@ class RequestDataCollectorTest extends \PHPUnit_Framework_TestCase
array(
'Static callback as string',
'Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest::staticControllerMethod',
'Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest::staticControllerMethod',
__NAMESPACE__.'\RequestDataCollectorTest::staticControllerMethod',
array(
'class' => 'Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest',
'method' => 'staticControllerMethod',
'file' => __FILE__,
'line' => $r2->getStartLine(),
),
),
array(
@@ -145,34 +183,97 @@ class RequestDataCollectorTest extends \PHPUnit_Framework_TestCase
),
),
);
$c = new RequestDataCollector();
$request = $this->createRequest();
$response = $this->createResponse();
foreach ($controllerTests as $controllerTest) {
$this->injectController($c, $controllerTest[1], $request);
$c->collect($request, $response);
$this->assertSame($controllerTest[2], $c->getController(), sprintf('Testing: %s', $controllerTest[0]));
}
}
protected function createRequest()
public function testItIgnoresInvalidCallables()
{
$request = $this->createRequestWithSession();
$response = new RedirectResponse('/');
$c = new RequestDataCollector();
$c->collect($request, $response);
$this->assertSame('n/a', $c->getController());
}
public function testItAddsRedirectedAttributesWhenRequestContainsSpecificCookie()
{
$request = $this->createRequest();
$request->cookies->add(array(
'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(array(
'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 = array('name' => 'foo'))
{
$request = Request::create('http://test.com/foo?bar=baz');
$request->attributes->set('foo', 'bar');
$request->attributes->set('_route', 'foobar');
$request->attributes->set('_route_params', array('name' => 'foo'));
$request->attributes->set('_route_params', $routeParams);
$request->attributes->set('resource', fopen(__FILE__, 'r'));
$request->attributes->set('object', new \stdClass());
return $request;
}
private function createRequestWithSession()
{
$request = $this->createRequest();
$request->attributes->set('_controller', 'Foo::bar');
$request->setSession(new Session(new MockArraySessionStorage()));
$request->getSession()->start();
return $request;
}
protected function createResponse()
{
$response = new Response();
$response->setStatusCode(200);
$response->headers->set('Content-Type', 'application/json');
$response->headers->set('X-Foo-Bar', null);
$response->headers->setCookie(new Cookie('foo', 'bar', 1, '/foo', 'localhost', true, true));
$response->headers->setCookie(new Cookie('bar', 'foo', new \DateTime('@946684800')));
$response->headers->setCookie(new Cookie('bazz', 'foo', '2000-12-12'));
@@ -185,8 +286,8 @@ class RequestDataCollectorTest extends \PHPUnit_Framework_TestCase
*/
protected function injectController($collector, $controller, $request)
{
$resolver = $this->getMock('Symfony\\Component\\HttpKernel\\Controller\\ControllerResolverInterface');
$httpKernel = new HttpKernel(new EventDispatcher(), $resolver);
$resolver = $this->getMockBuilder('Symfony\\Component\\HttpKernel\\Controller\\ControllerResolverInterface')->getMock();
$httpKernel = new HttpKernel(new EventDispatcher(), $resolver, null, $this->getMockBuilder(ArgumentResolverInterface::class)->getMock());
$event = new FilterControllerEvent($httpKernel, $controller, $request, HttpKernelInterface::MASTER_REQUEST);
$collector->onKernelController($event);
}
@@ -219,4 +320,15 @@ class RequestDataCollectorTest extends \PHPUnit_Framework_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));
}
}

View File

@@ -11,14 +11,15 @@
namespace Symfony\Component\HttpKernel\Tests\DataCollector;
use Symfony\Component\HttpKernel\DataCollector\TimeDataCollector;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\DataCollector\TimeDataCollector;
/**
* @group time-sensitive
*/
class TimeDataCollectorTest extends \PHPUnit_Framework_TestCase
class TimeDataCollectorTest extends TestCase
{
public function testCollect()
{
@@ -29,7 +30,7 @@ class TimeDataCollectorTest extends \PHPUnit_Framework_TestCase
$c->collect($request, new Response());
$this->assertEquals(1000, $c->getStartTime());
$this->assertEquals(0, $c->getStartTime());
$request->server->set('REQUEST_TIME_FLOAT', 2);
@@ -41,7 +42,7 @@ class TimeDataCollectorTest extends \PHPUnit_Framework_TestCase
$c->collect($request, new Response());
$this->assertEquals(0, $c->getStartTime());
$kernel = $this->getMock('Symfony\Component\HttpKernel\KernelInterface');
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\KernelInterface')->getMock();
$kernel->expects($this->once())->method('getStartTime')->will($this->returnValue(123456));
$c = new TimeDataCollector($kernel);

View File

@@ -11,9 +11,13 @@
namespace Symfony\Component\HttpKernel\Tests\DataCollector\Util;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\DataCollector\Util\ValueExporter;
class ValueExporterTest extends \PHPUnit_Framework_TestCase
/**
* @group legacy
*/
class ValueExporterTest extends TestCase
{
/**
* @var ValueExporter
@@ -28,13 +32,13 @@ class ValueExporterTest extends \PHPUnit_Framework_TestCase
public function testDateTime()
{
$dateTime = new \DateTime('2014-06-10 07:35:40', new \DateTimeZone('UTC'));
$this->assertSame('Object(DateTime) - 2014-06-10T07:35:40+0000', $this->valueExporter->exportValue($dateTime));
$this->assertSame('Object(DateTime) - 2014-06-10T07:35:40+00:00', $this->valueExporter->exportValue($dateTime));
}
public function testDateTimeImmutable()
{
$dateTime = new \DateTimeImmutable('2014-06-10 07:35:40', new \DateTimeZone('UTC'));
$this->assertSame('Object(DateTimeImmutable) - 2014-06-10T07:35:40+0000', $this->valueExporter->exportValue($dateTime));
$this->assertSame('Object(DateTimeImmutable) - 2014-06-10T07:35:40+00:00', $this->valueExporter->exportValue($dateTime));
}
public function testIncompleteClass()

View File

@@ -0,0 +1,67 @@
<?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\Debug;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\Debug\FileLinkFormatter;
class FileLinkFormatterTest extends TestCase
{
public function testWhenNoFileLinkFormatAndNoRequest()
{
$sut = new FileLinkFormatter();
$this->assertFalse($sut->format('/kernel/root/src/my/very/best/file.php', 3));
}
public function testWhenFileLinkFormatAndNoRequest()
{
$file = __DIR__.\DIRECTORY_SEPARATOR.'file.php';
$sut = new FileLinkFormatter('debug://open?url=file://%f&line=%l', new RequestStack());
$this->assertSame("debug://open?url=file://$file&line=3", $sut->format($file, 3));
}
public function testWhenFileLinkFormatAndRequest()
{
$file = __DIR__.\DIRECTORY_SEPARATOR.'file.php';
$baseDir = __DIR__;
$requestStack = new RequestStack();
$request = new Request();
$requestStack->push($request);
$sut = new FileLinkFormatter('debug://open?url=file://%f&line=%l', $requestStack, __DIR__, '/_profiler/open?file=%f&line=%l#line%l');
$this->assertSame("debug://open?url=file://$file&line=3", $sut->format($file, 3));
}
public function testWhenNoFileLinkFormatAndRequest()
{
$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');
$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));
}
}

View File

@@ -11,14 +11,16 @@
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 \PHPUnit_Framework_TestCase
class TraceableEventDispatcherTest extends TestCase
{
public function testStopwatchSections()
{
@@ -33,6 +35,7 @@ class TraceableEventDispatcherTest extends \PHPUnit_Framework_TestCase
'__section__',
'kernel.request',
'kernel.controller',
'kernel.controller_arguments',
'controller',
'kernel.response',
'kernel.terminate',
@@ -108,10 +111,11 @@ class TraceableEventDispatcherTest extends \PHPUnit_Framework_TestCase
protected function getHttpKernel($dispatcher, $controller)
{
$resolver = $this->getMock('Symfony\Component\HttpKernel\Controller\ControllerResolverInterface');
$resolver->expects($this->once())->method('getController')->will($this->returnValue($controller));
$resolver->expects($this->once())->method('getArguments')->will($this->returnValue(array()));
$controllerResolver = $this->getMockBuilder('Symfony\Component\HttpKernel\Controller\ControllerResolverInterface')->getMock();
$controllerResolver->expects($this->once())->method('getController')->will($this->returnValue($controller));
$argumentResolver = $this->getMockBuilder('Symfony\Component\HttpKernel\Controller\ArgumentResolverInterface')->getMock();
$argumentResolver->expects($this->once())->method('getArguments')->will($this->returnValue(array()));
return new HttpKernel($dispatcher, $resolver);
return new HttpKernel($dispatcher, $controllerResolver, new RequestStack(), $argumentResolver);
}
}

View File

@@ -0,0 +1,99 @@
<?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\AddAnnotatedClassesToCachePass;
class AddAnnotatedClassesToCachePassTest extends TestCase
{
public function testExpandClasses()
{
$r = new \ReflectionClass(AddAnnotatedClassesToCachePass::class);
$pass = $r->newInstanceWithoutConstructor();
$r = new \ReflectionMethod(AddAnnotatedClassesToCachePass::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]);
}
}

View File

@@ -0,0 +1,67 @@
<?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\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\HttpKernel\Controller\ArgumentResolver;
use Symfony\Component\HttpKernel\DependencyInjection\ControllerArgumentValueResolverPass;
class ControllerArgumentValueResolverPassTest extends TestCase
{
public function testServicesAreOrderedAccordingToPriority()
{
$services = array(
'n3' => array(array()),
'n1' => array(array('priority' => 200)),
'n2' => array(array('priority' => 100)),
);
$expected = array(
new Reference('n1'),
new Reference('n2'),
new Reference('n3'),
);
$definition = new Definition(ArgumentResolver::class, array(null, array()));
$container = new ContainerBuilder();
$container->setDefinition('argument_resolver', $definition);
foreach ($services as $id => list($tag)) {
$container->register($id)->addTag('controller.argument_value_resolver', $tag);
}
(new ControllerArgumentValueResolverPass())->process($container);
$this->assertEquals($expected, $definition->getArgument(1)->getValues());
}
public function testReturningEmptyArrayWhenNoService()
{
$definition = new Definition(ArgumentResolver::class, array(null, array()));
$container = new ContainerBuilder();
$container->setDefinition('argument_resolver', $definition);
(new ControllerArgumentValueResolverPass())->process($container);
$this->assertEquals(array(), $definition->getArgument(1)->getValues());
}
public function testNoArgumentResolver()
{
$container = new ContainerBuilder();
(new ControllerArgumentValueResolverPass())->process($container);
$this->assertFalse($container->hasDefinition('argument_resolver'));
}
}

View File

@@ -11,90 +11,50 @@
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;
class FragmentRendererPassTest extends \PHPUnit_Framework_TestCase
class FragmentRendererPassTest extends TestCase
{
/**
* Tests that content rendering not implementing FragmentRendererInterface
* trigger an exception.
* triggers an exception.
*
* @expectedException \InvalidArgumentException
*/
public function testContentRendererWithoutInterface()
{
// one service, not implementing any interface
$services = array(
'my_content_renderer' => array(array('alias' => 'foo')),
);
$definition = $this->getMock('Symfony\Component\DependencyInjection\Definition');
$builder = $this->getMock(
'Symfony\Component\DependencyInjection\ContainerBuilder',
array('hasDefinition', 'findTaggedServiceIds', 'getDefinition')
);
$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));
$builder = new ContainerBuilder();
$fragmentHandlerDefinition = $builder->register('fragment.handler');
$builder->register('my_content_renderer', 'Symfony\Component\DependencyInjection\Definition')
->addTag('kernel.fragment_renderer', array('alias' => 'foo'));
$pass = new FragmentRendererPass();
$pass->process($builder);
$this->assertEquals(array(array('addRendererService', array('foo', 'my_content_renderer'))), $fragmentHandlerDefinition->getMethodCalls());
}
public function testValidContentRenderer()
{
$services = array(
'my_content_renderer' => array(array('alias' => 'foo')),
);
$renderer = $this->getMock('Symfony\Component\DependencyInjection\Definition');
$renderer
->expects($this->once())
->method('addMethodCall')
->with('addRendererService', array('foo', 'my_content_renderer'))
;
$definition = $this->getMock('Symfony\Component\DependencyInjection\Definition');
$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->getMock(
'Symfony\Component\DependencyInjection\ContainerBuilder',
array('hasDefinition', 'findTaggedServiceIds', 'getDefinition')
);
$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', array('alias' => 'foo'));
$pass = new FragmentRendererPass();
$pass->process($builder);
$serviceLocatorDefinition = $builder->getDefinition((string) $fragmentHandlerDefinition->getArgument(0));
$this->assertSame(ServiceLocator::class, $serviceLocatorDefinition->getClass());
$this->assertEquals(array('foo' => new ServiceClosureArgument(new Reference('my_content_renderer'))), $serviceLocatorDefinition->getArgument(0));
}
}

View File

@@ -11,22 +11,27 @@
namespace Symfony\Component\HttpKernel\Tests\DependencyInjection;
use Symfony\Component\HttpKernel\DependencyInjection\LazyLoadingFragmentHandler;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\DependencyInjection\LazyLoadingFragmentHandler;
class LazyLoadingFragmentHandlerTest extends \PHPUnit_Framework_TestCase
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->getMock('Symfony\Component\HttpKernel\Fragment\FragmentRendererInterface');
$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()));
$requestStack = $this->getMock('Symfony\Component\HttpFoundation\RequestStack');
$requestStack = $this->getMockBuilder('Symfony\Component\HttpFoundation\RequestStack')->getMock();
$requestStack->expects($this->any())->method('getCurrentRequest')->will($this->returnValue(Request::create('/')));
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock();
$container->expects($this->once())->method('get')->will($this->returnValue($renderer));
$handler = new LazyLoadingFragmentHandler($container, $requestStack, false);
@@ -37,4 +42,25 @@ class LazyLoadingFragmentHandlerTest extends \PHPUnit_Framework_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')->will($this->returnValue('foo'));
$renderer->expects($this->any())->method('render')->will($this->returnValue(new Response()));
$requestStack = $this->getMockBuilder('Symfony\Component\HttpFoundation\RequestStack')->getMock();
$requestStack->expects($this->any())->method('getCurrentRequest')->will($this->returnValue(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')->will($this->returnValue($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');
}
}

View File

@@ -0,0 +1,56 @@
<?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 Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\DependencyInjection\LoggerPass;
use Symfony\Component\HttpKernel\Log\Logger;
/**
* @author Kévin Dunglas <dunglas@gmail.com>
*/
class LoggerPassTest extends TestCase
{
public function testAlwaysSetAutowiringAlias()
{
$container = new ContainerBuilder();
$container->register('logger', 'Foo');
(new LoggerPass())->process($container);
$this->assertFalse($container->getAlias(LoggerInterface::class)->isPublic());
}
public function testDoNotOverrideExistingLogger()
{
$container = new ContainerBuilder();
$container->register('logger', 'Foo');
(new LoggerPass())->process($container);
$this->assertSame('Foo', $container->getDefinition('logger')->getClass());
}
public function testRegisterLogger()
{
$container = new ContainerBuilder();
$container->setParameter('kernel.debug', false);
(new LoggerPass())->process($container);
$definition = $container->getDefinition('logger');
$this->assertSame(Logger::class, $definition->getClass());
$this->assertFalse($definition->isPublic());
}
}

View File

@@ -11,54 +11,40 @@
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 \PHPUnit_Framework_TestCase
class MergeExtensionConfigurationPassTest extends TestCase
{
public function testAutoloadMainExtension()
{
$container = $this->getMock(
'Symfony\\Component\\DependencyInjection\\ContainerBuilder',
array(
'getExtensionConfig',
'loadFromExtension',
'getParameterBag',
'getDefinitions',
'getAliases',
'getExtensions',
)
);
$params = $this->getMock('Symfony\\Component\\DependencyInjection\\ParameterBag\\ParameterBag');
$container = new ContainerBuilder();
$container->registerExtension(new LoadedExtension());
$container->registerExtension(new NotLoadedExtension());
$container->loadFromExtension('loaded', array());
$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(array('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');
}
}

View File

@@ -0,0 +1,413 @@
<?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\DependencyInjection\Argument\ServiceClosureArgument;
use Symfony\Component\DependencyInjection\ChildDefinition;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerAwareTrait;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\ServiceLocator;
use Symfony\Component\DependencyInjection\TypedReference;
use Symfony\Component\HttpKernel\DependencyInjection\RegisterControllerArgumentLocatorsPass;
class RegisterControllerArgumentLocatorsPassTest extends TestCase
{
/**
* @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
* @expectedExceptionMessage Class "Symfony\Component\HttpKernel\Tests\DependencyInjection\NotFound" used for service "foo" cannot be found.
*/
public function testInvalidClass()
{
$container = new ContainerBuilder();
$container->register('argument_resolver.service')->addArgument(array());
$container->register('foo', NotFound::class)
->addTag('controller.service_arguments')
;
$pass = new RegisterControllerArgumentLocatorsPass();
$pass->process($container);
}
/**
* @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
* @expectedExceptionMessage Missing "action" attribute on tag "controller.service_arguments" {"argument":"bar"} for service "foo".
*/
public function testNoAction()
{
$container = new ContainerBuilder();
$container->register('argument_resolver.service')->addArgument(array());
$container->register('foo', RegisterTestController::class)
->addTag('controller.service_arguments', array('argument' => 'bar'))
;
$pass = new RegisterControllerArgumentLocatorsPass();
$pass->process($container);
}
/**
* @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
* @expectedExceptionMessage Missing "argument" attribute on tag "controller.service_arguments" {"action":"fooAction"} for service "foo".
*/
public function testNoArgument()
{
$container = new ContainerBuilder();
$container->register('argument_resolver.service')->addArgument(array());
$container->register('foo', RegisterTestController::class)
->addTag('controller.service_arguments', array('action' => 'fooAction'))
;
$pass = new RegisterControllerArgumentLocatorsPass();
$pass->process($container);
}
/**
* @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
* @expectedExceptionMessage Missing "id" attribute on tag "controller.service_arguments" {"action":"fooAction","argument":"bar"} for service "foo".
*/
public function testNoService()
{
$container = new ContainerBuilder();
$container->register('argument_resolver.service')->addArgument(array());
$container->register('foo', RegisterTestController::class)
->addTag('controller.service_arguments', array('action' => 'fooAction', 'argument' => 'bar'))
;
$pass = new RegisterControllerArgumentLocatorsPass();
$pass->process($container);
}
/**
* @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
* @expectedExceptionMessage Invalid "action" attribute on tag "controller.service_arguments" for service "foo": no public "barAction()" method found on class "Symfony\Component\HttpKernel\Tests\DependencyInjection\RegisterTestController".
*/
public function testInvalidMethod()
{
$container = new ContainerBuilder();
$container->register('argument_resolver.service')->addArgument(array());
$container->register('foo', RegisterTestController::class)
->addTag('controller.service_arguments', array('action' => 'barAction', 'argument' => 'bar', 'id' => 'bar_service'))
;
$pass = new RegisterControllerArgumentLocatorsPass();
$pass->process($container);
}
/**
* @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
* @expectedExceptionMessage Invalid "controller.service_arguments" tag for service "foo": method "fooAction()" has no "baz" argument on class "Symfony\Component\HttpKernel\Tests\DependencyInjection\RegisterTestController".
*/
public function testInvalidArgument()
{
$container = new ContainerBuilder();
$container->register('argument_resolver.service')->addArgument(array());
$container->register('foo', RegisterTestController::class)
->addTag('controller.service_arguments', array('action' => 'fooAction', 'argument' => 'baz', 'id' => 'bar'))
;
$pass = new RegisterControllerArgumentLocatorsPass();
$pass->process($container);
}
public function testAllActions()
{
$container = new ContainerBuilder();
$resolver = $container->register('argument_resolver.service')->addArgument(array());
$container->register('foo', RegisterTestController::class)
->addTag('controller.service_arguments')
;
$pass = new RegisterControllerArgumentLocatorsPass();
$pass->process($container);
$locator = $container->getDefinition((string) $resolver->getArgument(0))->getArgument(0);
$this->assertEquals(array('foo:fooAction'), array_keys($locator));
$this->assertInstanceof(ServiceClosureArgument::class, $locator['foo:fooAction']);
$locator = $container->getDefinition((string) $locator['foo:fooAction']->getValues()[0]);
$this->assertSame(ServiceLocator::class, $locator->getClass());
$this->assertFalse($locator->isPublic());
$expected = array('bar' => new ServiceClosureArgument(new TypedReference(ControllerDummy::class, ControllerDummy::class, RegisterTestController::class, ContainerInterface::IGNORE_ON_INVALID_REFERENCE)));
$this->assertEquals($expected, $locator->getArgument(0));
}
public function testExplicitArgument()
{
$container = new ContainerBuilder();
$resolver = $container->register('argument_resolver.service')->addArgument(array());
$container->register('foo', RegisterTestController::class)
->addTag('controller.service_arguments', array('action' => 'fooAction', 'argument' => 'bar', 'id' => 'bar'))
->addTag('controller.service_arguments', array('action' => 'fooAction', 'argument' => 'bar', 'id' => 'baz')) // should be ignored, the first wins
;
$pass = new RegisterControllerArgumentLocatorsPass();
$pass->process($container);
$locator = $container->getDefinition((string) $resolver->getArgument(0))->getArgument(0);
$locator = $container->getDefinition((string) $locator['foo:fooAction']->getValues()[0]);
$expected = array('bar' => new ServiceClosureArgument(new TypedReference('bar', ControllerDummy::class, RegisterTestController::class)));
$this->assertEquals($expected, $locator->getArgument(0));
}
public function testOptionalArgument()
{
$container = new ContainerBuilder();
$resolver = $container->register('argument_resolver.service')->addArgument(array());
$container->register('foo', RegisterTestController::class)
->addTag('controller.service_arguments', array('action' => 'fooAction', 'argument' => 'bar', 'id' => '?bar'))
;
$pass = new RegisterControllerArgumentLocatorsPass();
$pass->process($container);
$locator = $container->getDefinition((string) $resolver->getArgument(0))->getArgument(0);
$locator = $container->getDefinition((string) $locator['foo:fooAction']->getValues()[0]);
$expected = array('bar' => new ServiceClosureArgument(new TypedReference('bar', ControllerDummy::class, RegisterTestController::class, ContainerInterface::IGNORE_ON_INVALID_REFERENCE)));
$this->assertEquals($expected, $locator->getArgument(0));
}
public function testSkipSetContainer()
{
$container = new ContainerBuilder();
$resolver = $container->register('argument_resolver.service')->addArgument(array());
$container->register('foo', ContainerAwareRegisterTestController::class)
->addTag('controller.service_arguments');
$pass = new RegisterControllerArgumentLocatorsPass();
$pass->process($container);
$locator = $container->getDefinition((string) $resolver->getArgument(0))->getArgument(0);
$this->assertSame(array('foo:fooAction'), array_keys($locator));
}
/**
* @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
* @expectedExceptionMessage Cannot determine controller argument for "Symfony\Component\HttpKernel\Tests\DependencyInjection\NonExistentClassController::fooAction()": the $nonExistent argument is type-hinted with the non-existent class or interface: "Symfony\Component\HttpKernel\Tests\DependencyInjection\NonExistentClass". Did you forget to add a use statement?
*/
public function testExceptionOnNonExistentTypeHint()
{
$container = new ContainerBuilder();
$container->register('argument_resolver.service')->addArgument(array());
$container->register('foo', NonExistentClassController::class)
->addTag('controller.service_arguments');
$pass = new RegisterControllerArgumentLocatorsPass();
$pass->process($container);
}
/**
* @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
* @expectedExceptionMessage Cannot determine controller argument for "Symfony\Component\HttpKernel\Tests\DependencyInjection\NonExistentClassDifferentNamespaceController::fooAction()": the $nonExistent argument is type-hinted with the non-existent class or interface: "Acme\NonExistentClass".
*/
public function testExceptionOnNonExistentTypeHintDifferentNamespace()
{
$container = new ContainerBuilder();
$container->register('argument_resolver.service')->addArgument(array());
$container->register('foo', NonExistentClassDifferentNamespaceController::class)
->addTag('controller.service_arguments');
$pass = new RegisterControllerArgumentLocatorsPass();
$pass->process($container);
}
public function testNoExceptionOnNonExistentTypeHintOptionalArg()
{
$container = new ContainerBuilder();
$resolver = $container->register('argument_resolver.service')->addArgument(array());
$container->register('foo', NonExistentClassOptionalController::class)
->addTag('controller.service_arguments');
$pass = new RegisterControllerArgumentLocatorsPass();
$pass->process($container);
$locator = $container->getDefinition((string) $resolver->getArgument(0))->getArgument(0);
$this->assertSame(array('foo:barAction', 'foo:fooAction'), array_keys($locator));
}
public function testArgumentWithNoTypeHintIsOk()
{
$container = new ContainerBuilder();
$resolver = $container->register('argument_resolver.service')->addArgument(array());
$container->register('foo', ArgumentWithoutTypeController::class)
->addTag('controller.service_arguments');
$pass = new RegisterControllerArgumentLocatorsPass();
$pass->process($container);
$locator = $container->getDefinition((string) $resolver->getArgument(0))->getArgument(0);
$this->assertEmpty(array_keys($locator));
}
public function testControllersAreMadePublic()
{
$container = new ContainerBuilder();
$resolver = $container->register('argument_resolver.service')->addArgument(array());
$container->register('foo', ArgumentWithoutTypeController::class)
->setPublic(false)
->addTag('controller.service_arguments');
$pass = new RegisterControllerArgumentLocatorsPass();
$pass->process($container);
$this->assertTrue($container->getDefinition('foo')->isPublic());
}
/**
* @dataProvider provideBindings
*/
public function testBindings($bindingName)
{
$container = new ContainerBuilder();
$resolver = $container->register('argument_resolver.service')->addArgument(array());
$container->register('foo', RegisterTestController::class)
->setBindings(array($bindingName => new Reference('foo')))
->addTag('controller.service_arguments');
$pass = new RegisterControllerArgumentLocatorsPass();
$pass->process($container);
$locator = $container->getDefinition((string) $resolver->getArgument(0))->getArgument(0);
$locator = $container->getDefinition((string) $locator['foo:fooAction']->getValues()[0]);
$expected = array('bar' => new ServiceClosureArgument(new Reference('foo')));
$this->assertEquals($expected, $locator->getArgument(0));
}
public function provideBindings()
{
return array(array(ControllerDummy::class), array('$bar'));
}
public function testDoNotBindScalarValueToControllerArgument()
{
$container = new ContainerBuilder();
$resolver = $container->register('argument_resolver.service')->addArgument(array());
$container->register('foo', ArgumentWithoutTypeController::class)
->setBindings(array('$someArg' => '%foo%'))
->addTag('controller.service_arguments');
$pass = new RegisterControllerArgumentLocatorsPass();
$pass->process($container);
$locator = $container->getDefinition((string) $resolver->getArgument(0))->getArgument(0);
$this->assertEmpty($locator);
}
public function testBindingsOnChildDefinitions()
{
$container = new ContainerBuilder();
$resolver = $container->register('argument_resolver.service')->addArgument(array());
$container->register('parent', ArgumentWithoutTypeController::class);
$container->setDefinition('child', (new ChildDefinition('parent'))
->setBindings(array('$someArg' => new Reference('parent')))
->addTag('controller.service_arguments')
);
$pass = new RegisterControllerArgumentLocatorsPass();
$pass->process($container);
$locator = $container->getDefinition((string) $resolver->getArgument(0))->getArgument(0);
$this->assertInstanceOf(ServiceClosureArgument::class, $locator['child:fooAction']);
$locator = $container->getDefinition((string) $locator['child:fooAction']->getValues()[0])->getArgument(0);
$this->assertInstanceOf(ServiceClosureArgument::class, $locator['someArg']);
$this->assertEquals(new Reference('parent'), $locator['someArg']->getValues()[0]);
}
}
class RegisterTestController
{
public function __construct(ControllerDummy $bar)
{
}
public function fooAction(ControllerDummy $bar)
{
}
protected function barAction(ControllerDummy $bar)
{
}
}
class ContainerAwareRegisterTestController implements ContainerAwareInterface
{
use ContainerAwareTrait;
public function fooAction(ControllerDummy $bar)
{
}
}
class ControllerDummy
{
}
class NonExistentClassController
{
public function fooAction(NonExistentClass $nonExistent)
{
}
}
class NonExistentClassDifferentNamespaceController
{
public function fooAction(\Acme\NonExistentClass $nonExistent)
{
}
}
class NonExistentClassOptionalController
{
public function fooAction(NonExistentClass $nonExistent = null)
{
}
public function barAction(NonExistentClass $nonExistent = null, $bar)
{
}
}
class ArgumentWithoutTypeController
{
public function fooAction($someArg)
{
}
}

View File

@@ -0,0 +1,148 @@
<?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\DependencyInjection\Compiler\ResolveInvalidReferencesPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\HttpKernel\DependencyInjection\RegisterControllerArgumentLocatorsPass;
use Symfony\Component\HttpKernel\DependencyInjection\RemoveEmptyControllerArgumentLocatorsPass;
class RemoveEmptyControllerArgumentLocatorsPassTest extends TestCase
{
public function testProcess()
{
$container = new ContainerBuilder();
$resolver = $container->register('argument_resolver.service')->addArgument(array());
$container->register('stdClass', 'stdClass');
$container->register(parent::class, 'stdClass');
$container->register('c1', RemoveTestController1::class)->addTag('controller.service_arguments');
$container->register('c2', RemoveTestController2::class)->addTag('controller.service_arguments')
->addMethodCall('setTestCase', array(new Reference('c1')));
$pass = new RegisterControllerArgumentLocatorsPass();
$pass->process($container);
$controllers = $container->getDefinition((string) $resolver->getArgument(0))->getArgument(0);
$this->assertCount(2, $container->getDefinition((string) $controllers['c1:fooAction']->getValues()[0])->getArgument(0));
$this->assertCount(1, $container->getDefinition((string) $controllers['c2:setTestCase']->getValues()[0])->getArgument(0));
$this->assertCount(1, $container->getDefinition((string) $controllers['c2:fooAction']->getValues()[0])->getArgument(0));
(new ResolveInvalidReferencesPass())->process($container);
$this->assertCount(1, $container->getDefinition((string) $controllers['c2:setTestCase']->getValues()[0])->getArgument(0));
$this->assertSame(array(), $container->getDefinition((string) $controllers['c2:fooAction']->getValues()[0])->getArgument(0));
(new RemoveEmptyControllerArgumentLocatorsPass())->process($container);
$controllers = $container->getDefinition((string) $resolver->getArgument(0))->getArgument(0);
$this->assertSame(array('c1:fooAction'), array_keys($controllers));
$this->assertSame(array('bar'), array_keys($container->getDefinition((string) $controllers['c1:fooAction']->getValues()[0])->getArgument(0)));
$expectedLog = array(
'Symfony\Component\HttpKernel\DependencyInjection\RemoveEmptyControllerArgumentLocatorsPass: Removing service-argument resolver for controller "c2:fooAction": no corresponding services exist for the referenced types.',
'Symfony\Component\HttpKernel\DependencyInjection\RemoveEmptyControllerArgumentLocatorsPass: Removing method "setTestCase" of service "c2" from controller candidates: the method is called at instantiation, thus cannot be an action.',
);
$this->assertSame($expectedLog, $container->getCompiler()->getLog());
}
public function testSameIdClass()
{
$container = new ContainerBuilder();
$resolver = $container->register('argument_resolver.service')->addArgument(array());
$container->register(RegisterTestController::class, RegisterTestController::class)
->addTag('controller.service_arguments')
;
(new RegisterControllerArgumentLocatorsPass())->process($container);
(new RemoveEmptyControllerArgumentLocatorsPass())->process($container);
$expected = array(
RegisterTestController::class.':fooAction',
RegisterTestController::class.'::fooAction',
);
$this->assertEquals($expected, array_keys($container->getDefinition((string) $resolver->getArgument(0))->getArgument(0)));
}
public function testInvoke()
{
$container = new ContainerBuilder();
$resolver = $container->register('argument_resolver.service')->addArgument(array());
$container->register('invokable', InvokableRegisterTestController::class)
->addTag('controller.service_arguments')
;
(new RegisterControllerArgumentLocatorsPass())->process($container);
(new RemoveEmptyControllerArgumentLocatorsPass())->process($container);
$this->assertEquals(
array('invokable:__invoke', 'invokable'),
array_keys($container->getDefinition((string) $resolver->getArgument(0))->getArgument(0))
);
}
public function testInvokeSameIdClass()
{
$container = new ContainerBuilder();
$resolver = $container->register('argument_resolver.service')->addArgument(array());
$container->register(InvokableRegisterTestController::class, InvokableRegisterTestController::class)
->addTag('controller.service_arguments')
;
(new RegisterControllerArgumentLocatorsPass())->process($container);
(new RemoveEmptyControllerArgumentLocatorsPass())->process($container);
$expected = array(
InvokableRegisterTestController::class.':__invoke',
InvokableRegisterTestController::class.'::__invoke',
InvokableRegisterTestController::class,
);
$this->assertEquals($expected, array_keys($container->getDefinition((string) $resolver->getArgument(0))->getArgument(0)));
}
}
class RemoveTestController1
{
public function fooAction(\stdClass $bar, ClassNotInContainer $baz)
{
}
}
class RemoveTestController2
{
public function setTestCase(TestCase $test)
{
}
public function fooAction(ClassNotInContainer $bar)
{
}
}
class InvokableRegisterTestController
{
public function __invoke(\stdClass $bar)
{
}
}
class ClassNotInContainer
{
}

View File

@@ -0,0 +1,78 @@
<?php
namespace Symfony\Component\HttpKernel\Tests\DependencyInjection;
use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\Argument\IteratorArgument;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\HttpKernel\DependencyInjection\ResettableServicePass;
use Symfony\Component\HttpKernel\DependencyInjection\ServicesResetter;
use Symfony\Component\HttpKernel\Tests\Fixtures\ClearableService;
use Symfony\Component\HttpKernel\Tests\Fixtures\ResettableService;
class ResettableServicePassTest extends TestCase
{
public function testCompilerPass()
{
$container = new ContainerBuilder();
$container->register('one', ResettableService::class)
->setPublic(true)
->addTag('kernel.reset', array('method' => 'reset'));
$container->register('two', ClearableService::class)
->setPublic(true)
->addTag('kernel.reset', array('method' => 'clear'));
$container->register('services_resetter', ServicesResetter::class)
->setPublic(true)
->setArguments(array(null, array()));
$container->addCompilerPass(new ResettableServicePass());
$container->compile();
$definition = $container->getDefinition('services_resetter');
$this->assertEquals(
array(
new IteratorArgument(array(
'one' => new Reference('one', ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE),
'two' => new Reference('two', ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE),
)),
array(
'one' => 'reset',
'two' => 'clear',
),
),
$definition->getArguments()
);
}
/**
* @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException
* @expectedExceptionMessage Tag kernel.reset requires the "method" attribute to be set.
*/
public function testMissingMethod()
{
$container = new ContainerBuilder();
$container->register(ResettableService::class)
->addTag('kernel.reset');
$container->register('services_resetter', ServicesResetter::class)
->setArguments(array(null, array()));
$container->addCompilerPass(new ResettableServicePass());
$container->compile();
}
public function testCompilerPassWithoutResetters()
{
$container = new ContainerBuilder();
$container->register('services_resetter', ServicesResetter::class)
->setArguments(array(null, array()));
$container->addCompilerPass(new ResettableServicePass());
$container->compile();
$this->assertFalse($container->has('services_resetter'));
}
}

View File

@@ -0,0 +1,42 @@
<?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\ServicesResetter;
use Symfony\Component\HttpKernel\Tests\Fixtures\ClearableService;
use Symfony\Component\HttpKernel\Tests\Fixtures\ResettableService;
class ServicesResetterTest extends TestCase
{
protected function setUp()
{
ResettableService::$counter = 0;
ClearableService::$counter = 0;
}
public function testResetServices()
{
$resetter = new ServicesResetter(new \ArrayIterator(array(
'id1' => new ResettableService(),
'id2' => new ClearableService(),
)), array(
'id1' => 'reset',
'id2' => 'clear',
));
$resetter->reset();
$this->assertEquals(1, ResettableService::$counter);
$this->assertEquals(1, ClearableService::$counter);
}
}

View File

@@ -0,0 +1,17 @@
<?php
namespace Symfony\Component\HttpKernel\Tests\Event;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\FilterControllerArgumentsEvent;
use Symfony\Component\HttpKernel\Tests\TestHttpKernel;
class FilterControllerArgumentsEventTest extends TestCase
{
public function testFilterControllerArgumentsEvent()
{
$filterController = new FilterControllerArgumentsEvent(new TestHttpKernel(), function () {}, array('test'), new Request(), 1);
$this->assertEquals($filterController->getArguments(), array('test'));
}
}

View File

@@ -0,0 +1,27 @@
<?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\Event;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\Tests\TestHttpKernel;
class GetResponseForExceptionEventTest extends TestCase
{
public function testAllowSuccessfulResponseIsFalseByDefault()
{
$event = new GetResponseForExceptionEvent(new TestHttpKernel(), new Request(), 1, new \Exception());
$this->assertFalse($event->isAllowingCustomResponseCode());
}
}

View File

@@ -11,8 +11,9 @@
namespace Symfony\Component\HttpKernel\Tests\EventListener;
use Symfony\Component\HttpKernel\EventListener\AddRequestFormatsListener;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\EventListener\AddRequestFormatsListener;
use Symfony\Component\HttpKernel\KernelEvents;
/**
@@ -20,7 +21,7 @@ use Symfony\Component\HttpKernel\KernelEvents;
*
* @author Gildas Quemener <gildas.quemener@gmail.com>
*/
class AddRequestFormatsListenerTest extends \PHPUnit_Framework_TestCase
class AddRequestFormatsListenerTest extends TestCase
{
/**
* @var AddRequestFormatsListener
@@ -45,7 +46,7 @@ class AddRequestFormatsListenerTest extends \PHPUnit_Framework_TestCase
public function testRegisteredEvent()
{
$this->assertEquals(
array(KernelEvents::REQUEST => 'onKernelRequest'),
array(KernelEvents::REQUEST => array('onKernelRequest', 1)),
AddRequestFormatsListener::getSubscribedEvents()
);
}
@@ -64,7 +65,7 @@ class AddRequestFormatsListenerTest extends \PHPUnit_Framework_TestCase
protected function getRequestMock()
{
return $this->getMock('Symfony\Component\HttpFoundation\Request');
return $this->getMockBuilder('Symfony\Component\HttpFoundation\Request')->getMock();
}
protected function getGetResponseEventMock(Request $request)

View File

@@ -11,10 +11,11 @@
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;
@@ -28,15 +29,13 @@ use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\KernelEvents;
/**
* DebugHandlersListenerTest.
*
* @author Nicolas Grekas <p@tchwork.com>
*/
class DebugHandlersListenerTest extends \PHPUnit_Framework_TestCase
class DebugHandlersListenerTest extends TestCase
{
public function testConfigure()
{
$logger = $this->getMock('Psr\Log\LoggerInterface');
$logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
$userHandler = function () {};
$listener = new DebugHandlersListener($userHandler, $logger);
$xHandler = new ExceptionHandler();
@@ -70,7 +69,7 @@ class DebugHandlersListenerTest extends \PHPUnit_Framework_TestCase
$listener = new DebugHandlersListener(null);
$eHandler = new ErrorHandler();
$event = new KernelEvent(
$this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface'),
$this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock(),
Request::create('/'),
HttpKernelInterface::MASTER_REQUEST
);
@@ -94,7 +93,7 @@ class DebugHandlersListenerTest extends \PHPUnit_Framework_TestCase
{
$dispatcher = new EventDispatcher();
$listener = new DebugHandlersListener(null);
$app = $this->getMock('Symfony\Component\Console\Application');
$app = $this->getMockBuilder('Symfony\Component\Console\Application')->getMock();
$app->expects($this->once())->method('getHelperSet')->will($this->returnValue(new HelperSet()));
$command = new Command(__FUNCTION__);
$command->setApplication($app);
@@ -131,4 +130,26 @@ class DebugHandlersListenerTest extends \PHPUnit_Framework_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(array($eHandler, 'handleException'));
try {
$listener->configure();
} catch (\Exception $exception) {
}
restore_exception_handler();
if (null !== $exception) {
throw $exception;
}
$this->assertSame($userHandler, $eHandler->setExceptionHandler('var_dump'));
}
}

View File

@@ -11,8 +11,9 @@
namespace Symfony\Component\HttpKernel\Tests\EventListener;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Console\ConsoleEvents;
use Symfony\Component\HttpKernel\EventListener\DumpListener;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\VarDumper\Cloner\ClonerInterface;
use Symfony\Component\VarDumper\Cloner\Data;
use Symfony\Component\VarDumper\Dumper\DataDumperInterface;
@@ -23,12 +24,12 @@ use Symfony\Component\VarDumper\VarDumper;
*
* @author Nicolas Grekas <p@tchwork.com>
*/
class DumpListenerTest extends \PHPUnit_Framework_TestCase
class DumpListenerTest extends TestCase
{
public function testSubscribedEvents()
{
$this->assertSame(
array(KernelEvents::REQUEST => array('configure', 1024)),
array(ConsoleEvents::COMMAND => array('configure', 1024)),
DumpListener::getSubscribedEvents()
);
}
@@ -67,7 +68,7 @@ class MockCloner implements ClonerInterface
{
public function cloneVar($var)
{
return new Data(array($var.'-'));
return new Data(array(array($var.'-')));
}
}
@@ -75,8 +76,6 @@ class MockDumper implements DataDumperInterface
{
public function dump(Data $data)
{
$rawData = $data->getRawData();
echo '+'.$rawData[0];
echo '+'.$data->getValue();
}
}

View File

@@ -11,12 +11,16 @@
namespace Symfony\Component\HttpKernel\Tests\EventListener;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\EventListener\ExceptionListener;
use Symfony\Component\HttpKernel\Log\DebugLoggerInterface;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use PHPUnit\Framework\TestCase;
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;
/**
@@ -26,16 +30,16 @@ use Symfony\Component\HttpKernel\Tests\Logger;
*
* @group time-sensitive
*/
class ExceptionListenerTest extends \PHPUnit_Framework_TestCase
class ExceptionListenerTest extends TestCase
{
public function testConstruct()
{
$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));
@@ -95,8 +99,8 @@ class ExceptionListenerTest extends \PHPUnit_Framework_TestCase
$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),
@@ -105,9 +109,9 @@ class ExceptionListenerTest extends \PHPUnit_Framework_TestCase
public function testSubRequestFormat()
{
$listener = new ExceptionListener('foo', $this->getMock('Psr\Log\LoggerInterface'));
$listener = new ExceptionListener('foo', $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock());
$kernel = $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface');
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock();
$kernel->expects($this->once())->method('handle')->will($this->returnCallback(function (Request $request) {
return new Response($request->getRequestFormat());
}));
@@ -115,19 +119,45 @@ class ExceptionListenerTest extends \PHPUnit_Framework_TestCase
$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')->will($this->returnCallback(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, array('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']);
}
}

View File

@@ -11,13 +11,14 @@
namespace Symfony\Component\HttpKernel\Tests\EventListener;
use Symfony\Component\HttpKernel\EventListener\FragmentListener;
use PHPUnit\Framework\TestCase;
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 \PHPUnit_Framework_TestCase
class FragmentListenerTest extends TestCase
{
public function testOnlyTriggeredOnFragmentRoute()
{
@@ -116,6 +117,6 @@ class FragmentListenerTest extends \PHPUnit_Framework_TestCase
private function createGetResponseEvent(Request $request, $requestType = HttpKernelInterface::MASTER_REQUEST)
{
return new GetResponseEvent($this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface'), $request, $requestType);
return new GetResponseEvent($this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock(), $request, $requestType);
}
}

View File

@@ -11,18 +11,19 @@
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 \PHPUnit_Framework_TestCase
class LocaleListenerTest extends TestCase
{
private $requestStack;
protected function setUp()
{
$this->requestStack = $this->getMock('Symfony\Component\HttpFoundation\RequestStack', array(), array(), '', false);
$this->requestStack = $this->getMockBuilder('Symfony\Component\HttpFoundation\RequestStack')->disableOriginalConstructor()->getMock();
}
public function testDefaultLocaleWithoutSession()
@@ -37,8 +38,7 @@ class LocaleListenerTest extends \PHPUnit_Framework_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');
@@ -51,10 +51,10 @@ class LocaleListenerTest extends \PHPUnit_Framework_TestCase
public function testLocaleSetForRoutingContext()
{
// the request context is updated
$context = $this->getMock('Symfony\Component\Routing\RequestContext');
$context = $this->getMockBuilder('Symfony\Component\Routing\RequestContext')->getMock();
$context->expects($this->once())->method('setParameter')->with('_locale', 'es');
$router = $this->getMock('Symfony\Component\Routing\Router', array('getContext'), array(), '', false);
$router = $this->getMockBuilder('Symfony\Component\Routing\Router')->setMethods(array('getContext'))->disableOriginalConstructor()->getMock();
$router->expects($this->once())->method('getContext')->will($this->returnValue($context));
$request = Request::create('/');
@@ -67,10 +67,10 @@ class LocaleListenerTest extends \PHPUnit_Framework_TestCase
public function testRouterResetWithParentRequestOnKernelFinishRequest()
{
// the request context is updated
$context = $this->getMock('Symfony\Component\Routing\RequestContext');
$context = $this->getMockBuilder('Symfony\Component\Routing\RequestContext')->getMock();
$context->expects($this->once())->method('setParameter')->with('_locale', 'es');
$router = $this->getMock('Symfony\Component\Routing\Router', array('getContext'), array(), '', false);
$router = $this->getMockBuilder('Symfony\Component\Routing\Router')->setMethods(array('getContext'))->disableOriginalConstructor()->getMock();
$router->expects($this->once())->method('getContext')->will($this->returnValue($context));
$parentRequest = Request::create('/');
@@ -78,7 +78,7 @@ class LocaleListenerTest extends \PHPUnit_Framework_TestCase
$this->requestStack->expects($this->once())->method('getParentRequest')->will($this->returnValue($parentRequest));
$event = $this->getMock('Symfony\Component\HttpKernel\Event\FinishRequestEvent', array(), array(), '', false);
$event = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\FinishRequestEvent')->disableOriginalConstructor()->getMock();
$listener = new LocaleListener($this->requestStack, 'fr', $router);
$listener->onKernelFinishRequest($event);
@@ -97,6 +97,6 @@ class LocaleListenerTest extends \PHPUnit_Framework_TestCase
private function getEvent(Request $request)
{
return new GetResponseEvent($this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface'), $request, HttpKernelInterface::MASTER_REQUEST);
return new GetResponseEvent($this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock(), $request, HttpKernelInterface::MASTER_REQUEST);
}
}

View File

@@ -11,15 +11,16 @@
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;
class ProfilerListenerTest extends \PHPUnit_Framework_TestCase
class ProfilerListenerTest extends TestCase
{
/**
* Test a master and sub request with an exception and `onlyException` profiler option enabled.
@@ -38,7 +39,7 @@ class ProfilerListenerTest extends \PHPUnit_Framework_TestCase
->method('collect')
->will($this->returnValue($profile));
$kernel = $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface');
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock();
$masterRequest = $this->getMockBuilder('Symfony\Component\HttpFoundation\Request')
->disableOriginalConstructor()

View File

@@ -11,15 +11,16 @@
namespace Symfony\Component\HttpKernel\Tests\EventListener;
use Symfony\Component\HttpKernel\EventListener\ResponseListener;
use PHPUnit\Framework\TestCase;
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 \PHPUnit_Framework_TestCase
class ResponseListenerTest extends TestCase
{
private $dispatcher;
@@ -31,7 +32,7 @@ class ResponseListenerTest extends \PHPUnit_Framework_TestCase
$listener = new ResponseListener('UTF-8');
$this->dispatcher->addListener(KernelEvents::RESPONSE, array($listener, 'onKernelResponse'));
$this->kernel = $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface');
$this->kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock();
}
protected function tearDown()

View File

@@ -11,19 +11,29 @@
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 \PHPUnit_Framework_TestCase
class RouterListenerTest extends TestCase
{
private $requestStack;
protected function setUp()
{
$this->requestStack = $this->getMock('Symfony\Component\HttpFoundation\RequestStack', array(), array(), '', false);
$this->requestStack = $this->getMockBuilder('Symfony\Component\HttpFoundation\RequestStack')->disableOriginalConstructor()->getMock();
}
/**
@@ -32,14 +42,14 @@ class RouterListenerTest extends \PHPUnit_Framework_TestCase
public function testPort($defaultHttpPort, $defaultHttpsPort, $uri, $expectedHttpPort, $expectedHttpsPort)
{
$urlMatcher = $this->getMockBuilder('Symfony\Component\Routing\Matcher\UrlMatcherInterface')
->disableOriginalConstructor()
->getMock();
->disableOriginalConstructor()
->getMock();
$context = new RequestContext();
$context->setHttpPort($defaultHttpPort);
$context->setHttpsPort($defaultHttpsPort);
$urlMatcher->expects($this->any())
->method('getContext')
->will($this->returnValue($context));
->method('getContext')
->will($this->returnValue($context));
$listener = new RouterListener($urlMatcher, $this->requestStack);
$event = $this->createGetResponseEventForUri($uri);
@@ -67,7 +77,7 @@ class RouterListenerTest extends \PHPUnit_Framework_TestCase
*/
private function createGetResponseEventForUri($uri)
{
$kernel = $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface');
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock();
$request = Request::create($uri);
$request->attributes->set('_controller', null); // Prevents going in to routing process
@@ -84,11 +94,11 @@ class RouterListenerTest extends \PHPUnit_Framework_TestCase
public function testRequestMatcher()
{
$kernel = $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface');
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock();
$request = Request::create('http://localhost/');
$event = new GetResponseEvent($kernel, $request, HttpKernelInterface::MASTER_REQUEST);
$requestMatcher = $this->getMock('Symfony\Component\Routing\Matcher\RequestMatcherInterface');
$requestMatcher = $this->getMockBuilder('Symfony\Component\Routing\Matcher\RequestMatcherInterface')->getMock();
$requestMatcher->expects($this->once())
->method('matchRequest')
->with($this->isInstanceOf('Symfony\Component\HttpFoundation\Request'))
@@ -100,11 +110,11 @@ class RouterListenerTest extends \PHPUnit_Framework_TestCase
public function testSubRequestWithDifferentMethod()
{
$kernel = $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface');
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock();
$request = Request::create('http://localhost/', 'post');
$event = new GetResponseEvent($kernel, $request, HttpKernelInterface::MASTER_REQUEST);
$requestMatcher = $this->getMock('Symfony\Component\Routing\Matcher\RequestMatcherInterface');
$requestMatcher = $this->getMockBuilder('Symfony\Component\Routing\Matcher\RequestMatcherInterface')->getMock();
$requestMatcher->expects($this->any())
->method('matchRequest')
->with($this->isInstanceOf('Symfony\Component\HttpFoundation\Request'))
@@ -116,7 +126,7 @@ class RouterListenerTest extends \PHPUnit_Framework_TestCase
$listener->onKernelRequest($event);
// sub-request with another HTTP method
$kernel = $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface');
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock();
$request = Request::create('http://localhost/', 'get');
$event = new GetResponseEvent($kernel, $request, HttpKernelInterface::SUB_REQUEST);
@@ -128,19 +138,19 @@ class RouterListenerTest extends \PHPUnit_Framework_TestCase
/**
* @dataProvider getLoggingParameterData
*/
public function testLoggingParameter($parameter, $log)
public function testLoggingParameter($parameter, $log, $parameters)
{
$requestMatcher = $this->getMock('Symfony\Component\Routing\Matcher\RequestMatcherInterface');
$requestMatcher = $this->getMockBuilder('Symfony\Component\Routing\Matcher\RequestMatcherInterface')->getMock();
$requestMatcher->expects($this->once())
->method('matchRequest')
->will($this->returnValue($parameter));
->method('matchRequest')
->will($this->returnValue($parameter));
$logger = $this->getMock('Psr\Log\LoggerInterface');
$logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
$logger->expects($this->once())
->method('info')
->with($this->equalTo($log));
->method('info')
->with($this->equalTo($log), $this->equalTo($parameters));
$kernel = $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface');
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock();
$request = Request::create('http://localhost/');
$listener = new RouterListener($requestMatcher, $this->requestStack, new RequestContext(), $logger);
@@ -150,8 +160,67 @@ class RouterListenerTest extends \PHPUnit_Framework_TestCase
public function getLoggingParameterData()
{
return array(
array(array('_route' => 'foo'), 'Matched route "foo".'),
array(array(), 'Matched route "n/a".'),
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')),
);
}
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->assertContains('Welcome', $response->getContent());
}
/**
* @expectedException \Symfony\Component\HttpKernel\Exception\BadRequestHttpException
*/
public function testRequestWithBadHost()
{
$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);
}
}

View File

@@ -0,0 +1,49 @@
<?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\EventListener;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\EventListener\SaveSessionListener;
use Symfony\Component\HttpKernel\HttpKernelInterface;
class SaveSessionListenerTest extends TestCase
{
public function testOnlyTriggeredOnMasterRequest()
{
$listener = new SaveSessionListener();
$event = $this->getMockBuilder(FilterResponseEvent::class)->disableOriginalConstructor()->getMock();
$event->expects($this->once())->method('isMasterRequest')->willReturn(false);
$event->expects($this->never())->method('getRequest');
// sub request
$listener->onKernelResponse($event);
}
public function testSessionSaved()
{
$listener = new SaveSessionListener();
$kernel = $this->getMockBuilder(HttpKernelInterface::class)->disableOriginalConstructor()->getMock();
$session = $this->getMockBuilder(SessionInterface::class)->disableOriginalConstructor()->getMock();
$session->expects($this->once())->method('isStarted')->willReturn(true);
$session->expects($this->once())->method('save');
$request = new Request();
$request->setSession($session);
$response = new Response();
$listener->onKernelResponse(new FilterResponseEvent($kernel, $request, HttpKernelInterface::MASTER_REQUEST, $response));
}
}

View File

@@ -0,0 +1,113 @@
<?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\EventListener;
use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\Event\FinishRequestEvent;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\EventListener\AbstractSessionListener;
use Symfony\Component\HttpKernel\EventListener\SessionListener;
use Symfony\Component\HttpKernel\HttpKernelInterface;
class SessionListenerTest extends TestCase
{
public function testOnlyTriggeredOnMasterRequest()
{
$listener = $this->getMockForAbstractClass(AbstractSessionListener::class);
$event = $this->getMockBuilder(GetResponseEvent::class)->disableOriginalConstructor()->getMock();
$event->expects($this->once())->method('isMasterRequest')->willReturn(false);
$event->expects($this->never())->method('getRequest');
// sub request
$listener->onKernelRequest($event);
}
public function testSessionIsSet()
{
$session = $this->getMockBuilder(Session::class)->disableOriginalConstructor()->getMock();
$container = new Container();
$container->set('session', $session);
$request = new Request();
$listener = new SessionListener($container);
$event = $this->getMockBuilder(GetResponseEvent::class)->disableOriginalConstructor()->getMock();
$event->expects($this->once())->method('isMasterRequest')->willReturn(true);
$event->expects($this->once())->method('getRequest')->willReturn($request);
$listener->onKernelRequest($event);
$this->assertTrue($request->hasSession());
$this->assertSame($session, $request->getSession());
}
public function testResponseIsPrivate()
{
$session = $this->getMockBuilder(Session::class)->disableOriginalConstructor()->getMock();
$session->expects($this->exactly(2))->method('getUsageIndex')->will($this->onConsecutiveCalls(0, 1));
$container = new Container();
$container->set('session', $session);
$listener = new SessionListener($container);
$kernel = $this->getMockBuilder(HttpKernelInterface::class)->disableOriginalConstructor()->getMock();
$request = new Request();
$response = new Response();
$listener->onKernelRequest(new GetResponseEvent($kernel, $request, HttpKernelInterface::MASTER_REQUEST));
$listener->onKernelResponse(new FilterResponseEvent($kernel, $request, HttpKernelInterface::MASTER_REQUEST, $response));
$this->assertTrue($response->headers->hasCacheControlDirective('private'));
$this->assertTrue($response->headers->hasCacheControlDirective('must-revalidate'));
$this->assertSame('0', $response->headers->getCacheControlDirective('max-age'));
}
public function testSurrogateMasterRequestIsPublic()
{
$session = $this->getMockBuilder(Session::class)->disableOriginalConstructor()->getMock();
$session->expects($this->exactly(4))->method('getUsageIndex')->will($this->onConsecutiveCalls(0, 1, 1, 1));
$container = new Container();
$container->set('session', $session);
$listener = new SessionListener($container);
$kernel = $this->getMockBuilder(HttpKernelInterface::class)->disableOriginalConstructor()->getMock();
$request = new Request();
$response = new Response();
$response->setCache(array('public' => true, 'max_age' => '30'));
$listener->onKernelRequest(new GetResponseEvent($kernel, $request, HttpKernelInterface::MASTER_REQUEST));
$this->assertTrue($request->hasSession());
$subRequest = clone $request;
$this->assertSame($request->getSession(), $subRequest->getSession());
$listener->onKernelRequest(new GetResponseEvent($kernel, $subRequest, HttpKernelInterface::MASTER_REQUEST));
$listener->onKernelResponse(new FilterResponseEvent($kernel, $subRequest, HttpKernelInterface::MASTER_REQUEST, $response));
$listener->onFinishRequest(new FinishRequestEvent($kernel, $subRequest, HttpKernelInterface::MASTER_REQUEST));
$this->assertFalse($response->headers->hasCacheControlDirective('private'));
$this->assertFalse($response->headers->hasCacheControlDirective('must-revalidate'));
$this->assertSame('30', $response->headers->getCacheControlDirective('max-age'));
$listener->onKernelResponse(new FilterResponseEvent($kernel, $request, HttpKernelInterface::MASTER_REQUEST, $response));
$this->assertTrue($response->headers->hasCacheControlDirective('private'));
$this->assertTrue($response->headers->hasCacheControlDirective('must-revalidate'));
$this->assertSame('0', $response->headers->getCacheControlDirective('max-age'));
}
}

View File

@@ -11,21 +11,22 @@
namespace Symfony\Component\HttpKernel\Tests\EventListener;
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 PHPUnit\Framework\TestCase;
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 \PHPUnit_Framework_TestCase
class SurrogateListenerTest extends TestCase
{
public function testFilterDoesNothingForSubRequests()
{
$dispatcher = new EventDispatcher();
$kernel = $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface');
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock();
$response = new Response('foo <esi:include src="" />');
$listener = new SurrogateListener(new Esi());
@@ -39,7 +40,7 @@ class SurrogateListenerTest extends \PHPUnit_Framework_TestCase
public function testFilterWhenThereIsSomeEsiIncludes()
{
$dispatcher = new EventDispatcher();
$kernel = $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface');
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock();
$response = new Response('foo <esi:include src="" />');
$listener = new SurrogateListener(new Esi());
@@ -53,7 +54,7 @@ class SurrogateListenerTest extends \PHPUnit_Framework_TestCase
public function testFilterWhenThereIsNoEsiIncludes()
{
$dispatcher = new EventDispatcher();
$kernel = $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface');
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock();
$response = new Response('foo');
$listener = new SurrogateListener(new Esi());

View File

@@ -11,11 +11,16 @@
namespace Symfony\Component\HttpKernel\Tests\EventListener;
use Symfony\Component\HttpFoundation\Response;
use PHPUnit\Framework\TestCase;
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.
@@ -24,7 +29,7 @@ use Symfony\Component\HttpFoundation\Session\SessionInterface;
*
* @author Bulat Shakirzyanov <mallluhuct@gmail.com>
*/
class TestSessionListenerTest extends \PHPUnit_Framework_TestCase
class TestSessionListenerTest extends TestCase
{
/**
* @var TestSessionListener
@@ -38,8 +43,11 @@ class TestSessionListenerTest extends \PHPUnit_Framework_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')
->will($this->returnValue($this->session));
}
public function testShouldSaveMasterRequestSession()
@@ -61,8 +69,7 @@ class TestSessionListenerTest extends \PHPUnit_Framework_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();
@@ -70,6 +77,65 @@ class TestSessionListenerTest extends \PHPUnit_Framework_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(array(), $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', array(), array('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', array(), array('MOCKSESSID' => '123'));
$event = new GetResponseEvent($kernel, $request, HttpKernelInterface::MASTER_REQUEST);
$this->listener->onKernelRequest($event);
$response = new Response('', 200, array('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 array(
'same' => array('MOCKSESSID=789; path=/', array('MOCKSESSID=789; path=/')),
'different domain' => array('MOCKSESSID=789; path=/; domain=example.com', array('MOCKSESSID=789; path=/; domain=example.com', 'MOCKSESSID=456; path=/')),
'different path' => array('MOCKSESSID=789; path=/foo', array('MOCKSESSID=789; path=/foo', 'MOCKSESSID=456; path=/')),
);
}
public function testUnstartedSessionIsNotSave()
{
$this->sessionHasNotBeenStarted();
@@ -78,11 +144,20 @@ class TestSessionListenerTest extends \PHPUnit_Framework_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();
$kernel = $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface');
$response = $response ?: new Response();
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock();
$event = new FilterResponseEvent($kernel, $request, $type, $response);
$this->listener->onKernelResponse($event);
@@ -118,6 +193,20 @@ class TestSessionListenerTest extends \PHPUnit_Framework_TestCase
->will($this->returnValue(false));
}
private function sessionIsEmpty()
{
$this->session->expects($this->once())
->method('isEmpty')
->will($this->returnValue(true));
}
private function fixSessionId($sessionId)
{
$this->session->expects($this->any())
->method('getId')
->will($this->returnValue($sessionId));
}
private function getSession()
{
$mock = $this->getMockBuilder('Symfony\Component\HttpFoundation\Session\Session')

View File

@@ -11,13 +11,14 @@
namespace Symfony\Component\HttpKernel\Tests\EventListener;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\FinishRequestEvent;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\EventListener\TranslatorListener;
use Symfony\Component\HttpKernel\HttpKernelInterface;
class TranslatorListenerTest extends \PHPUnit_Framework_TestCase
class TranslatorListenerTest extends TestCase
{
private $listener;
private $translator;
@@ -25,8 +26,8 @@ class TranslatorListenerTest extends \PHPUnit_Framework_TestCase
protected function setUp()
{
$this->translator = $this->getMock('Symfony\Component\Translation\TranslatorInterface');
$this->requestStack = $this->getMock('Symfony\Component\HttpFoundation\RequestStack');
$this->translator = $this->getMockBuilder('Symfony\Component\Translation\TranslatorInterface')->getMock();
$this->requestStack = $this->getMockBuilder('Symfony\Component\HttpFoundation\RequestStack')->getMock();
$this->listener = new TranslatorListener($this->translator, $this->requestStack);
}
@@ -96,7 +97,7 @@ class TranslatorListenerTest extends \PHPUnit_Framework_TestCase
private function createHttpKernel()
{
return $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface');
return $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock();
}
private function createRequest($locale)

View File

@@ -11,27 +11,33 @@
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 \PHPUnit_Framework_TestCase
class ValidateRequestListenerTest extends TestCase
{
protected function tearDown()
{
Request::setTrustedProxies(array(), -1);
}
/**
* @expectedException Symfony\Component\HttpFoundation\Exception\ConflictingHeadersException
* @expectedException \Symfony\Component\HttpFoundation\Exception\ConflictingHeadersException
*/
public function testListenerThrowsWhenMasterRequestHasInconsistentClientIps()
{
$dispatcher = new EventDispatcher();
$kernel = $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface');
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock();
$request = new Request();
$request->setTrustedProxies(array('1.1.1.1'));
$request->setTrustedProxies(array('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', '2.2.2.2');
$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'));

View File

@@ -0,0 +1,13 @@
<?php
namespace Symfony\Component\HttpKernel\Tests\Exception;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
class AccessDeniedHttpExceptionTest extends HttpExceptionTest
{
protected function createException()
{
return new AccessDeniedHttpException();
}
}

View File

@@ -0,0 +1,13 @@
<?php
namespace Symfony\Component\HttpKernel\Tests\Exception;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
class BadRequestHttpExceptionTest extends HttpExceptionTest
{
protected function createException()
{
return new BadRequestHttpException();
}
}

View File

@@ -0,0 +1,13 @@
<?php
namespace Symfony\Component\HttpKernel\Tests\Exception;
use Symfony\Component\HttpKernel\Exception\ConflictHttpException;
class ConflictHttpExceptionTest extends HttpExceptionTest
{
protected function createException()
{
return new ConflictHttpException();
}
}

View File

@@ -0,0 +1,13 @@
<?php
namespace Symfony\Component\HttpKernel\Tests\Exception;
use Symfony\Component\HttpKernel\Exception\GoneHttpException;
class GoneHttpExceptionTest extends HttpExceptionTest
{
protected function createException()
{
return new GoneHttpException();
}
}

View File

@@ -0,0 +1,53 @@
<?php
namespace Symfony\Component\HttpKernel\Tests\Exception;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\Exception\HttpException;
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'),
),
),
);
}
public function testHeadersDefault()
{
$exception = $this->createException();
$this->assertSame(array(), $exception->getHeaders());
}
/**
* @dataProvider headerDataProvider
*/
public function testHeadersConstructor($headers)
{
$exception = new HttpException(200, null, null, $headers);
$this->assertSame($headers, $exception->getHeaders());
}
/**
* @dataProvider headerDataProvider
*/
public function testHeadersSetter($headers)
{
$exception = $this->createException();
$exception->setHeaders($headers);
$this->assertSame($headers, $exception->getHeaders());
}
protected function createException()
{
return new HttpException(200);
}
}

View File

@@ -0,0 +1,13 @@
<?php
namespace Symfony\Component\HttpKernel\Tests\Exception;
use Symfony\Component\HttpKernel\Exception\LengthRequiredHttpException;
class LengthRequiredHttpExceptionTest extends HttpExceptionTest
{
protected function createException()
{
return new LengthRequiredHttpException();
}
}

View File

@@ -0,0 +1,24 @@
<?php
namespace Symfony\Component\HttpKernel\Tests\Exception;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
class MethodNotAllowedHttpExceptionTest extends HttpExceptionTest
{
public function testHeadersDefault()
{
$exception = new MethodNotAllowedHttpException(array('GET', 'PUT'));
$this->assertSame(array('Allow' => 'GET, PUT'), $exception->getHeaders());
}
/**
* @dataProvider headerDataProvider
*/
public function testHeadersSetter($headers)
{
$exception = new MethodNotAllowedHttpException(array('GET'));
$exception->setHeaders($headers);
$this->assertSame($headers, $exception->getHeaders());
}
}

View File

@@ -0,0 +1,13 @@
<?php
namespace Symfony\Component\HttpKernel\Tests\Exception;
use Symfony\Component\HttpKernel\Exception\NotAcceptableHttpException;
class NotAcceptableHttpExceptionTest extends HttpExceptionTest
{
protected function createException()
{
return new NotAcceptableHttpException();
}
}

View File

@@ -0,0 +1,13 @@
<?php
namespace Symfony\Component\HttpKernel\Tests\Exception;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class NotFoundHttpExceptionTest extends HttpExceptionTest
{
protected function createException()
{
return new NotFoundHttpException();
}
}

View File

@@ -0,0 +1,13 @@
<?php
namespace Symfony\Component\HttpKernel\Tests\Exception;
use Symfony\Component\HttpKernel\Exception\PreconditionFailedHttpException;
class PreconditionFailedHttpExceptionTest extends HttpExceptionTest
{
protected function createException()
{
return new PreconditionFailedHttpException();
}
}

View File

@@ -0,0 +1,13 @@
<?php
namespace Symfony\Component\HttpKernel\Tests\Exception;
use Symfony\Component\HttpKernel\Exception\PreconditionRequiredHttpException;
class PreconditionRequiredHttpExceptionTest extends HttpExceptionTest
{
protected function createException()
{
return new PreconditionRequiredHttpException();
}
}

View File

@@ -0,0 +1,29 @@
<?php
namespace Symfony\Component\HttpKernel\Tests\Exception;
use Symfony\Component\HttpKernel\Exception\ServiceUnavailableHttpException;
class ServiceUnavailableHttpExceptionTest extends HttpExceptionTest
{
public function testHeadersDefaultRetryAfter()
{
$exception = new ServiceUnavailableHttpException(10);
$this->assertSame(array('Retry-After' => 10), $exception->getHeaders());
}
/**
* @dataProvider headerDataProvider
*/
public function testHeadersSetter($headers)
{
$exception = new ServiceUnavailableHttpException(10);
$exception->setHeaders($headers);
$this->assertSame($headers, $exception->getHeaders());
}
protected function createException()
{
return new ServiceUnavailableHttpException();
}
}

View File

@@ -0,0 +1,29 @@
<?php
namespace Symfony\Component\HttpKernel\Tests\Exception;
use Symfony\Component\HttpKernel\Exception\TooManyRequestsHttpException;
class TooManyRequestsHttpExceptionTest extends HttpExceptionTest
{
public function testHeadersDefaultRertyAfter()
{
$exception = new TooManyRequestsHttpException(10);
$this->assertSame(array('Retry-After' => 10), $exception->getHeaders());
}
/**
* @dataProvider headerDataProvider
*/
public function testHeadersSetter($headers)
{
$exception = new TooManyRequestsHttpException(10);
$exception->setHeaders($headers);
$this->assertSame($headers, $exception->getHeaders());
}
protected function createException()
{
return new TooManyRequestsHttpException();
}
}

View File

@@ -0,0 +1,24 @@
<?php
namespace Symfony\Component\HttpKernel\Tests\Exception;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
class UnauthorizedHttpExceptionTest extends HttpExceptionTest
{
public function testHeadersDefault()
{
$exception = new UnauthorizedHttpException('Challenge');
$this->assertSame(array('WWW-Authenticate' => 'Challenge'), $exception->getHeaders());
}
/**
* @dataProvider headerDataProvider
*/
public function testHeadersSetter($headers)
{
$exception = new UnauthorizedHttpException('Challenge');
$exception->setHeaders($headers);
$this->assertSame($headers, $exception->getHeaders());
}
}

View File

@@ -0,0 +1,13 @@
<?php
namespace Symfony\Component\HttpKernel\Tests\Exception;
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
class UnprocessableEntityHttpExceptionTest extends HttpExceptionTest
{
protected function createException()
{
return new UnprocessableEntityHttpException();
}
}

View File

@@ -0,0 +1,13 @@
<?php
namespace Symfony\Component\HttpKernel\Tests\Exception;
use Symfony\Component\HttpKernel\Exception\UnsupportedMediaTypeHttpException;
class UnsupportedMediaTypeHttpExceptionTest extends HttpExceptionTest
{
protected function createException()
{
return new UnsupportedMediaTypeHttpException();
}
}

View File

@@ -0,0 +1,37 @@
<?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\_123;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\HttpKernel\Kernel;
class Kernel123 extends Kernel
{
public function registerBundles()
{
return array();
}
public function registerContainerConfiguration(LoaderInterface $loader)
{
}
public function getCacheDir()
{
return sys_get_temp_dir().'/'.Kernel::VERSION.'/kernel123/cache/'.$this->environment;
}
public function getLogDir()
{
return sys_get_temp_dir().'/'.Kernel::VERSION.'/kernel123/logs';
}
}

View File

@@ -0,0 +1,13 @@
<?php
namespace Symfony\Component\HttpKernel\Tests\Fixtures;
class ClearableService
{
public static $counter = 0;
public function clear()
{
++self::$counter;
}
}

View File

@@ -0,0 +1,19 @@
<?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\Controller;
class BasicTypesController
{
public function action(string $foo, int $bar, float $baz)
{
}
}

View File

@@ -0,0 +1,18 @@
<?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\Controller;
use Symfony\Component\HttpFoundation\Request;
class ExtendingRequest extends Request
{
}

View File

@@ -0,0 +1,18 @@
<?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\Controller;
use Symfony\Component\HttpFoundation\Session\Session;
class ExtendingSession extends Session
{
}

View File

@@ -0,0 +1,19 @@
<?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\Controller;
class NullableController
{
public function action(?string $foo, ?\stdClass $bar, ?string $baz = 'value', $mandatory)
{
}
}

View File

@@ -1,5 +1,14 @@
<?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\Controller;
class VariadicController

View File

@@ -0,0 +1,46 @@
<?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\DataCollector;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\DataCollector\DataCollector;
class CloneVarDataCollector extends DataCollector
{
private $varToClone;
public function __construct($varToClone)
{
$this->varToClone = $varToClone;
}
public function collect(Request $request, Response $response, \Exception $exception = null)
{
$this->data = $this->cloneVar($this->varToClone);
}
public function reset()
{
$this->data = array();
}
public function getData()
{
return $this->data;
}
public function getName()
{
return 'clone_var';
}
}

View File

@@ -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
{

View File

@@ -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
{

View File

@@ -0,0 +1,33 @@
<?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\Config\Loader\LoaderInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Kernel;
class KernelWithoutBundles extends Kernel
{
public function registerBundles()
{
return array();
}
public function registerContainerConfiguration(LoaderInterface $loader)
{
}
protected function build(ContainerBuilder $container)
{
$container->setParameter('test_executed', true);
}
}

View File

@@ -0,0 +1,13 @@
<?php
namespace Symfony\Component\HttpKernel\Tests\Fixtures;
class ResettableService
{
public static $counter = 0;
public function reset()
{
++self::$counter;
}
}

View File

@@ -25,4 +25,8 @@ class TestEventDispatcher extends EventDispatcher implements TraceableEventDispa
{
return array('bar');
}
public function reset()
{
}
}

View File

@@ -11,13 +11,14 @@
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 \PHPUnit_Framework_TestCase
class EsiFragmentRendererTest extends TestCase
{
public function testRenderFallbackToInlineStrategyIfEsiNotSupported()
{
@@ -25,6 +26,26 @@ class EsiFragmentRendererTest extends \PHPUnit_Framework_TestCase
$strategy->render('/', Request::create('/'));
}
/**
* @group legacy
* @expectedDeprecation Passing non-scalar values as part of URI attributes to the ESI and SSI rendering strategies is deprecated %s.
*/
public function testRenderFallbackWithObjectAttributesIsDeprecated()
{
$strategy = new EsiFragmentRenderer(new Esi(), $this->getInlineStrategy(true), new UriSigner('foo'));
$request = Request::create('/');
$reference = new ControllerReference('main_controller', array('foo' => new \stdClass()), array());
$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', array('foo' => array(true)), array());
$strategy->render($reference, $request);
}
public function testRender()
{
$strategy = new EsiFragmentRenderer(new Esi(), $this->getInlineStrategy());

View File

@@ -11,14 +11,15 @@
namespace Symfony\Component\HttpKernel\Tests\Fragment;
use Symfony\Component\HttpKernel\Fragment\FragmentHandler;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Fragment\FragmentHandler;
/**
* @group time-sensitive
*/
class FragmentHandlerTest extends \PHPUnit_Framework_TestCase
class FragmentHandlerTest extends TestCase
{
private $requestStack;
@@ -74,7 +75,7 @@ class FragmentHandlerTest extends \PHPUnit_Framework_TestCase
protected function getHandler($returnValue, $arguments = array())
{
$renderer = $this->getMock('Symfony\Component\HttpKernel\Fragment\FragmentRendererInterface');
$renderer = $this->getMockBuilder('Symfony\Component\HttpKernel\Fragment\FragmentRendererInterface')->getMock();
$renderer
->expects($this->any())
->method('getName')
@@ -87,7 +88,7 @@ class FragmentHandlerTest extends \PHPUnit_Framework_TestCase
;
if ($arguments) {
call_user_func_array(array($e, 'with'), $arguments);
\call_user_func_array(array($e, 'with'), $arguments);
}
$handler = new FragmentHandler($this->requestStack);

View File

@@ -11,12 +11,13 @@
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 \PHPUnit_Framework_TestCase
class HIncludeFragmentRendererTest extends TestCase
{
/**
* @expectedException \LogicException
@@ -75,7 +76,7 @@ class HIncludeFragmentRendererTest extends \PHPUnit_Framework_TestCase
public function testRenderWithDefaultText()
{
$engine = $this->getMock('Symfony\\Component\\Templating\\EngineInterface');
$engine = $this->getMockBuilder('Symfony\\Component\\Templating\\EngineInterface')->getMock();
$engine->expects($this->once())
->method('exists')
->with('default')
@@ -85,4 +86,17 @@ class HIncludeFragmentRendererTest extends \PHPUnit_Framework_TestCase
$strategy = new HIncludeFragmentRenderer($engine);
$this->assertEquals('<hx:include src="/foo">default</hx:include>', $strategy->render('/foo', Request::create('/'), array('default' => 'default'))->getContent());
}
public function testRenderWithEngineAndDefaultText()
{
$engine = $this->getMockBuilder('Symfony\\Component\\Templating\\EngineInterface')->getMock();
$engine->expects($this->once())
->method('exists')
->with('loading...')
->will($this->throwException(new \RuntimeException()));
// only default
$strategy = new HIncludeFragmentRenderer($engine);
$this->assertEquals('<hx:include src="/foo">loading...</hx:include>', $strategy->render('/foo', Request::create('/'), array('default' => 'loading...'))->getContent());
}
}

View File

@@ -11,15 +11,19 @@
namespace Symfony\Component\HttpKernel\Tests\Fragment;
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 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\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 \PHPUnit_Framework_TestCase
class InlineFragmentRendererTest extends TestCase
{
public function testRender()
{
@@ -42,16 +46,19 @@ class InlineFragmentRendererTest extends \PHPUnit_Framework_TestCase
$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->server->set('HTTP_X_FORWARDED_FOR', '127.0.0.1');
$subRequest->headers->set('forwarded', array('for="127.0.0.1";host="localhost";proto=http'));
$strategy = new InlineFragmentRenderer($this->getKernelExpectingRequest($subRequest));
$strategy->render(new ControllerReference('main_controller', array('object' => $object), array()), Request::create('/'));
$this->assertSame('foo', $strategy->render(new ControllerReference('main_controller', array('object' => $object), array()), Request::create('/'))->getContent());
}
public function testRenderWithObjectsAsAttributesPassedAsObjectsInTheController()
/**
* @group legacy
*/
public function testRenderWithObjectsAsAttributesPassedAsObjectsInTheControllerLegacy()
{
$resolver = $this->getMock('Symfony\\Component\\HttpKernel\\Controller\\ControllerResolver', array('getController'));
$resolver = $this->getMockBuilder('Symfony\\Component\\HttpKernel\\Controller\\ControllerResolver')->setMethods(array('getController'))->getMock();
$resolver
->expects($this->once())
->method('getController')
@@ -60,7 +67,28 @@ class InlineFragmentRendererTest extends \PHPUnit_Framework_TestCase
}))
;
$kernel = new HttpKernel(new EventDispatcher(), $resolver);
$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('/'));
$this->assertEquals('bar', $response->getContent());
}
/**
* @group legacy
*/
public function testRenderWithObjectsAsAttributesPassedAsObjectsInTheController()
{
$resolver = $this->getMockBuilder(ControllerResolverInterface::class)->getMock();
$resolver
->expects($this->once())
->method('getController')
->will($this->returnValue(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('/'));
@@ -69,14 +97,15 @@ class InlineFragmentRendererTest extends \PHPUnit_Framework_TestCase
public function testRenderWithTrustedHeaderDisabled()
{
$trustedHeaderName = Request::getTrustedHeaderName(Request::HEADER_CLIENT_IP);
Request::setTrustedProxies(array(), 0);
Request::setTrustedHeaderName(Request::HEADER_CLIENT_IP, '');
$expectedSubRequest = Request::create('/');
$expectedSubRequest->headers->set('x-forwarded-for', array('127.0.0.1'));
$strategy = new InlineFragmentRenderer($this->getKernelExpectingRequest(Request::create('/')));
$strategy->render('/', Request::create('/'));
$strategy = new InlineFragmentRenderer($this->getKernelExpectingRequest($expectedSubRequest));
$this->assertSame('foo', $strategy->render('/', Request::create('/'))->getContent());
Request::setTrustedHeaderName(Request::HEADER_CLIENT_IP, $trustedHeaderName);
Request::setTrustedProxies(array(), -1);
}
/**
@@ -84,7 +113,7 @@ class InlineFragmentRendererTest extends \PHPUnit_Framework_TestCase
*/
public function testRenderExceptionNoIgnoreErrors()
{
$dispatcher = $this->getMock('Symfony\Component\EventDispatcher\EventDispatcherInterface');
$dispatcher = $this->getMockBuilder('Symfony\Component\EventDispatcher\EventDispatcherInterface')->getMock();
$dispatcher->expects($this->never())->method('dispatch');
$strategy = new InlineFragmentRenderer($this->getKernel($this->throwException(new \RuntimeException('foo'))), $dispatcher);
@@ -94,7 +123,7 @@ class InlineFragmentRendererTest extends \PHPUnit_Framework_TestCase
public function testRenderExceptionIgnoreErrors()
{
$dispatcher = $this->getMock('Symfony\Component\EventDispatcher\EventDispatcherInterface');
$dispatcher = $this->getMockBuilder('Symfony\Component\EventDispatcher\EventDispatcherInterface')->getMock();
$dispatcher->expects($this->once())->method('dispatch')->with(KernelEvents::EXCEPTION);
$strategy = new InlineFragmentRenderer($this->getKernel($this->throwException(new \RuntimeException('foo'))), $dispatcher);
@@ -114,7 +143,7 @@ class InlineFragmentRendererTest extends \PHPUnit_Framework_TestCase
private function getKernel($returnValue)
{
$kernel = $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface');
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock();
$kernel
->expects($this->any())
->method('handle')
@@ -124,26 +153,10 @@ class InlineFragmentRendererTest extends \PHPUnit_Framework_TestCase
return $kernel;
}
/**
* Creates a Kernel expecting a request equals to $request
* Allows delta in comparison in case REQUEST_TIME changed by 1 second.
*/
private function getKernelExpectingRequest(Request $request)
{
$kernel = $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface');
$kernel
->expects($this->any())
->method('handle')
->with($this->equalTo($request, 1))
;
return $kernel;
}
public function testExceptionInSubRequestsDoesNotMangleOutputBuffers()
{
$resolver = $this->getMock('Symfony\\Component\\HttpKernel\\Controller\\ControllerResolverInterface');
$resolver
$controllerResolver = $this->getMockBuilder('Symfony\\Component\\HttpKernel\\Controller\\ControllerResolverInterface')->getMock();
$controllerResolver
->expects($this->once())
->method('getController')
->will($this->returnValue(function () {
@@ -152,13 +165,15 @@ class InlineFragmentRendererTest extends \PHPUnit_Framework_TestCase
throw new \RuntimeException();
}))
;
$resolver
$argumentResolver = $this->getMockBuilder('Symfony\\Component\\HttpKernel\\Controller\\ArgumentResolverInterface')->getMock();
$argumentResolver
->expects($this->once())
->method('getArguments')
->will($this->returnValue(array()))
;
$kernel = new HttpKernel(new EventDispatcher(), $resolver);
$kernel = new HttpKernel(new EventDispatcher(), $controllerResolver, new RequestStack(), $argumentResolver);
$renderer = new InlineFragmentRenderer($kernel);
// simulate a main request with output buffering
@@ -176,10 +191,10 @@ class InlineFragmentRendererTest extends \PHPUnit_Framework_TestCase
$expectedSubRequest = Request::create('/');
$expectedSubRequest->headers->set('Surrogate-Capability', 'abc="ESI/1.0"');
if (Request::getTrustedHeaderName(Request::HEADER_CLIENT_IP)) {
if (Request::HEADER_X_FORWARDED_FOR & Request::getTrustedHeaderSet()) {
$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('forwarded', array('for="127.0.0.1";host="localhost";proto=http'));
$strategy = new InlineFragmentRenderer($this->getKernelExpectingRequest($expectedSubRequest));
@@ -190,26 +205,77 @@ class InlineFragmentRendererTest extends \PHPUnit_Framework_TestCase
public function testESIHeaderIsKeptInSubrequestWithTrustedHeaderDisabled()
{
$trustedHeaderName = Request::getTrustedHeaderName(Request::HEADER_CLIENT_IP);
Request::setTrustedHeaderName(Request::HEADER_CLIENT_IP, '');
Request::setTrustedProxies(array(), Request::HEADER_FORWARDED);
$this->testESIHeaderIsKeptInSubrequest();
Request::setTrustedHeaderName(Request::HEADER_CLIENT_IP, $trustedHeaderName);
Request::setTrustedProxies(array(), -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', array('127.0.0.1'));
$expectedSubRequest->headers->set('forwarded', array('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' => '*'));
$strategy->render('/', $request);
}
public function testFirstTrustedProxyIsSetAsRemote()
{
Request::setTrustedProxies(array('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', array('127.0.0.1'));
$expectedSubRequest->headers->set('forwarded', array('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(array(), -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', array('127.0.0.1'));
$expectedSubRequest->headers->set('forwarded', array('for="127.0.0.1";host="localhost";proto=http'));
Request::setTrustedProxies(array('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(array(), -1);
}
/**
* Creates a Kernel expecting a request equals to $request
* Allows delta in comparison in case REQUEST_TIME changed by 1 second.
*/
private function getKernelExpectingRequest(Request $request, $strict = false)
{
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock();
$kernel
->expects($this->once())
->method('handle')
->with($this->equalTo($request, 1))
->willReturn(new Response('foo'));
return $kernel;
}
}
class Bar

View File

@@ -11,10 +11,11 @@
namespace Symfony\Component\HttpKernel\Tests\Fragment;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Controller\ControllerReference;
class RoutableFragmentRendererTest extends \PHPUnit_Framework_TestCase
class RoutableFragmentRendererTest extends TestCase
{
/**
* @dataProvider getGenerateFragmentUriData

View File

@@ -0,0 +1,97 @@
<?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\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\HttpKernel\UriSigner;
class SsiFragmentRendererTest extends TestCase
{
public function testRenderFallbackToInlineStrategyIfSsiNotSupported()
{
$strategy = new SsiFragmentRenderer(new Ssi(), $this->getInlineStrategy(true));
$strategy->render('/', Request::create('/'));
}
public function testRender()
{
$strategy = new SsiFragmentRenderer(new Ssi(), $this->getInlineStrategy());
$request = Request::create('/');
$request->setLocale('fr');
$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');
}
public function testRenderControllerReference()
{
$signer = new UriSigner('foo');
$strategy = new SsiFragmentRenderer(new Ssi(), $this->getInlineStrategy(), $signer);
$request = Request::create('/');
$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());
$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()
);
}
/**
* @expectedException \LogicException
*/
public function testRenderControllerReferenceWithoutSignerThrowsException()
{
$strategy = new SsiFragmentRenderer(new Ssi(), $this->getInlineStrategy());
$request = Request::create('/');
$request->setLocale('fr');
$request->headers->set('Surrogate-Capability', 'SSI/1.0');
$strategy->render(new ControllerReference('main_controller'), $request);
}
/**
* @expectedException \LogicException
*/
public function testRenderAltControllerReferenceWithoutSignerThrowsException()
{
$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')));
}
private function getInlineStrategy($called = false)
{
$inline = $this->getMockBuilder('Symfony\Component\HttpKernel\Fragment\InlineFragmentRenderer')->disableOriginalConstructor()->getMock();
if ($called) {
$inline->expects($this->once())->method('render');
}
return $inline;
}
}

View File

@@ -11,11 +11,12 @@
namespace Symfony\Component\HttpKernel\Tests\HttpCache;
use Symfony\Component\HttpKernel\HttpCache\Esi;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpCache\Esi;
class EsiTest extends \PHPUnit_Framework_TestCase
class EsiTest extends TestCase
{
public function testHasSurrogateEsiCapability()
{
@@ -39,10 +40,10 @@ class EsiTest extends \PHPUnit_Framework_TestCase
$request = Request::create('/');
$esi->addSurrogateCapability($request);
$this->assertEquals('symfony2="ESI/1.0"', $request->headers->get('Surrogate-Capability'));
$this->assertEquals('symfony="ESI/1.0"', $request->headers->get('Surrogate-Capability'));
$esi->addSurrogateCapability($request);
$this->assertEquals('symfony2="ESI/1.0", symfony2="ESI/1.0"', $request->headers->get('Surrogate-Capability'));
$this->assertEquals('symfony="ESI/1.0", symfony="ESI/1.0"', $request->headers->get('Surrogate-Capability'));
}
public function testAddSurrogateControl()
@@ -225,15 +226,15 @@ class EsiTest extends \PHPUnit_Framework_TestCase
protected function getCache($request, $response)
{
$cache = $this->getMock('Symfony\Component\HttpKernel\HttpCache\HttpCache', array('getRequest', 'handle'), array(), '', false);
$cache = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpCache\HttpCache')->setMethods(array('getRequest', 'handle'))->disableOriginalConstructor()->getMock();
$cache->expects($this->any())
->method('getRequest')
->will($this->returnValue($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(array($this, 'onConsecutiveCalls'), $response))
;
} else {
$cache->expects($this->any())

View File

@@ -11,9 +11,11 @@
namespace Symfony\Component\HttpKernel\Tests\HttpCache;
use Symfony\Component\HttpKernel\HttpCache\HttpCache;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpCache\Esi;
use Symfony\Component\HttpKernel\HttpCache\HttpCache;
use Symfony\Component\HttpKernel\HttpCache\Store;
use Symfony\Component\HttpKernel\HttpKernelInterface;
/**
@@ -213,7 +215,7 @@ class HttpCacheTest extends HttpCacheTestCase
if ($request->cookies->has('authenticated')) {
$response->headers->set('Cache-Control', 'private, no-store');
$response->setETag('"private tag"');
if (in_array('"private tag"', $etags)) {
if (\in_array('"private tag"', $etags)) {
$response->setStatusCode(304);
} else {
$response->setStatusCode(200);
@@ -223,7 +225,7 @@ class HttpCacheTest extends HttpCacheTestCase
} else {
$response->headers->set('Cache-Control', 'public');
$response->setETag('"public tag"');
if (in_array('"public tag"', $etags)) {
if (\in_array('"public tag"', $etags)) {
$response->setStatusCode(304);
} else {
$response->setStatusCode(200);
@@ -530,8 +532,8 @@ class HttpCacheTest extends HttpCacheTestCase
$this->request('GET', '/');
$this->assertHttpKernelIsNotCalled();
$this->assertEquals(200, $this->response->getStatusCode());
$this->assertTrue(strtotime($this->responses[0]->headers->get('Date')) - strtotime($this->response->headers->get('Date')) < 2);
$this->assertTrue($this->response->headers->get('Age') > 0);
$this->assertLessThan(2, strtotime($this->responses[0]->headers->get('Date')) - strtotime($this->response->headers->get('Date')));
$this->assertGreaterThan(0, $this->response->headers->get('Age'));
$this->assertNotNull($this->response->headers->get('X-Content-Digest'));
$this->assertTraceContains('fresh');
$this->assertTraceNotContains('store');
@@ -554,14 +556,54 @@ class HttpCacheTest extends HttpCacheTestCase
$this->request('GET', '/');
$this->assertHttpKernelIsNotCalled();
$this->assertEquals(200, $this->response->getStatusCode());
$this->assertTrue(strtotime($this->responses[0]->headers->get('Date')) - strtotime($this->response->headers->get('Date')) < 2);
$this->assertTrue($this->response->headers->get('Age') > 0);
$this->assertLessThan(2, strtotime($this->responses[0]->headers->get('Date')) - strtotime($this->response->headers->get('Date')));
$this->assertGreaterThan(0, $this->response->headers->get('Age'));
$this->assertNotNull($this->response->headers->get('X-Content-Digest'));
$this->assertTraceContains('fresh');
$this->assertTraceNotContains('store');
$this->assertEquals('Hello World', $this->response->getContent());
}
public function testDegradationWhenCacheLocked()
{
if ('\\' === \DIRECTORY_SEPARATOR) {
$this->markTestSkipped('Skips on windows to avoid permissions issues.');
}
$this->cacheConfig['stale_while_revalidate'] = 10;
// The prescence of Last-Modified makes this cacheable (because Response::isValidateable() then).
$this->setNextResponse(200, array('Cache-Control' => 'public, s-maxage=5', 'Last-Modified' => 'some while ago'), 'Old response');
$this->request('GET', '/'); // warm the cache
// Now, lock the cache
$concurrentRequest = Request::create('/', 'GET');
$this->store->lock($concurrentRequest);
/*
* After 10s, the cached response has become stale. Yet, we're still within the "stale_while_revalidate"
* timeout so we may serve the stale response.
*/
sleep(10);
$this->request('GET', '/');
$this->assertHttpKernelIsNotCalled();
$this->assertEquals(200, $this->response->getStatusCode());
$this->assertTraceContains('stale-while-revalidate');
$this->assertEquals('Old response', $this->response->getContent());
/*
* Another 10s later, stale_while_revalidate is over. Resort to serving the old response, but
* do so with a "server unavailable" message.
*/
sleep(10);
$this->request('GET', '/');
$this->assertHttpKernelIsNotCalled();
$this->assertEquals(503, $this->response->getStatusCode());
$this->assertEquals('Old response', $this->response->getContent());
}
public function testHitsCachedResponseWithSMaxAgeDirective()
{
$time = \DateTime::createFromFormat('U', time() - 5);
@@ -578,8 +620,8 @@ class HttpCacheTest extends HttpCacheTestCase
$this->request('GET', '/');
$this->assertHttpKernelIsNotCalled();
$this->assertEquals(200, $this->response->getStatusCode());
$this->assertTrue(strtotime($this->responses[0]->headers->get('Date')) - strtotime($this->response->headers->get('Date')) < 2);
$this->assertTrue($this->response->headers->get('Age') > 0);
$this->assertLessThan(2, strtotime($this->responses[0]->headers->get('Date')) - strtotime($this->response->headers->get('Date')));
$this->assertGreaterThan(0, $this->response->headers->get('Age'));
$this->assertNotNull($this->response->headers->get('X-Content-Digest'));
$this->assertTraceContains('fresh');
$this->assertTraceNotContains('store');
@@ -753,7 +795,7 @@ class HttpCacheTest extends HttpCacheTestCase
$this->request('GET', '/');
$this->assertHttpKernelIsCalled();
$this->assertEquals(200, $this->response->getStatusCode());
$this->assertTrue($this->response->headers->get('Age') <= 1);
$this->assertLessThanOrEqual(1, $this->response->headers->get('Age'));
$this->assertNotNull($this->response->headers->get('X-Content-Digest'));
$this->assertTraceContains('stale');
$this->assertTraceNotContains('fresh');
@@ -791,7 +833,7 @@ class HttpCacheTest extends HttpCacheTestCase
$this->assertEquals(200, $this->response->getStatusCode());
$this->assertNotNull($this->response->headers->get('Last-Modified'));
$this->assertNotNull($this->response->headers->get('X-Content-Digest'));
$this->assertTrue($this->response->headers->get('Age') <= 1);
$this->assertLessThanOrEqual(1, $this->response->headers->get('Age'));
$this->assertEquals('Hello World', $this->response->getContent());
$this->assertTraceContains('stale');
$this->assertTraceContains('valid');
@@ -799,6 +841,21 @@ class HttpCacheTest extends HttpCacheTestCase
$this->assertTraceNotContains('miss');
}
public function testValidatesCachedResponsesUseSameHttpMethod()
{
$test = $this;
$this->setNextResponse(200, array(), 'Hello World', function ($request, $response) use ($test) {
$test->assertSame('OPTIONS', $request->getMethod());
});
// build initial request
$this->request('OPTIONS', '/');
// build subsequent request
$this->request('OPTIONS', '/');
}
public function testValidatesCachedResponsesWithETagAndNoFreshnessInformation()
{
$this->setNextResponse(200, array(), 'Hello World', function ($request, $response) {
@@ -826,7 +883,7 @@ class HttpCacheTest extends HttpCacheTestCase
$this->assertEquals(200, $this->response->getStatusCode());
$this->assertNotNull($this->response->headers->get('ETag'));
$this->assertNotNull($this->response->headers->get('X-Content-Digest'));
$this->assertTrue($this->response->headers->get('Age') <= 1);
$this->assertLessThanOrEqual(1, $this->response->headers->get('Age'));
$this->assertEquals('Hello World', $this->response->getContent());
$this->assertTraceContains('stale');
$this->assertTraceContains('valid');
@@ -834,6 +891,40 @@ class HttpCacheTest extends HttpCacheTestCase
$this->assertTraceNotContains('miss');
}
public function testServesResponseWhileFreshAndRevalidatesWithLastModifiedInformation()
{
$time = \DateTime::createFromFormat('U', time());
$this->setNextResponse(200, array(), 'Hello World', function (Request $request, Response $response) use ($time) {
$response->setSharedMaxAge(10);
$response->headers->set('Last-Modified', $time->format(DATE_RFC2822));
});
// prime the cache
$this->request('GET', '/');
// next request before s-maxage has expired: Serve from cache
// without hitting the backend
$this->request('GET', '/');
$this->assertHttpKernelIsNotCalled();
$this->assertEquals(200, $this->response->getStatusCode());
$this->assertEquals('Hello World', $this->response->getContent());
$this->assertTraceContains('fresh');
sleep(15); // expire the cache
$this->setNextResponse(304, array(), '', function (Request $request, Response $response) use ($time) {
$this->assertEquals($time->format(DATE_RFC2822), $request->headers->get('IF_MODIFIED_SINCE'));
});
$this->request('GET', '/');
$this->assertHttpKernelIsCalled();
$this->assertEquals(200, $this->response->getStatusCode());
$this->assertEquals('Hello World', $this->response->getContent());
$this->assertTraceContains('stale');
$this->assertTraceContains('valid');
}
public function testReplacesCachedResponsesWhenValidationResultsInNon304Response()
{
$time = \DateTime::createFromFormat('U', time());
@@ -903,7 +994,7 @@ class HttpCacheTest extends HttpCacheTestCase
$this->assertHttpKernelIsNotCalled();
$this->assertEquals(200, $this->response->getStatusCode());
$this->assertEquals('', $this->response->getContent());
$this->assertEquals(strlen('Hello World'), $this->response->headers->get('Content-Length'));
$this->assertEquals(\strlen('Hello World'), $this->response->headers->get('Content-Length'));
}
public function testSendsNoContentWhenFresh()
@@ -1079,7 +1170,7 @@ class HttpCacheTest extends HttpCacheTestCase
array(
'status' => 200,
'body' => 'Hello World!',
'headers' => array('Cache-Control' => 's-maxage=300'),
'headers' => array('Cache-Control' => 's-maxage=200'),
),
array(
'status' => 200,
@@ -1093,8 +1184,33 @@ class HttpCacheTest extends HttpCacheTestCase
$this->request('GET', '/', array(), array(), true);
$this->assertEquals('Hello World! My name is Bobby.', $this->response->getContent());
// check for 100 or 99 as the test can be executed after a second change
$this->assertTrue(in_array($this->response->getTtl(), array(99, 100)));
$this->assertEquals(100, $this->response->getTtl());
}
public function testEsiCacheSendsTheLowestTtlForHeadRequests()
{
$responses = array(
array(
'status' => 200,
'body' => 'I am a long-lived master response, but I embed a short-lived resource: <esi:include src="/foo" />',
'headers' => array(
'Cache-Control' => 's-maxage=300',
'Surrogate-Control' => 'content="ESI/1.0"',
),
),
array(
'status' => 200,
'body' => 'I am a short-lived resource',
'headers' => array('Cache-Control' => 's-maxage=100'),
),
);
$this->setNextResponses($responses);
$this->request('HEAD', '/', array(), array(), true);
$this->assertEmpty($this->response->getContent());
$this->assertEquals(100, $this->response->getTtl());
}
public function testEsiCacheForceValidation()
@@ -1130,6 +1246,37 @@ class HttpCacheTest extends HttpCacheTestCase
$this->assertTrue($this->response->headers->hasCacheControlDirective('no-cache'));
}
public function testEsiCacheForceValidationForHeadRequests()
{
$responses = array(
array(
'status' => 200,
'body' => 'I am the master response and use expiration caching, but I embed another resource: <esi:include src="/foo" />',
'headers' => array(
'Cache-Control' => 's-maxage=300',
'Surrogate-Control' => 'content="ESI/1.0"',
),
),
array(
'status' => 200,
'body' => 'I am the embedded resource and use validation caching',
'headers' => array('ETag' => 'foobar'),
),
);
$this->setNextResponses($responses);
$this->request('HEAD', '/', array(), array(), true);
// The response has been assembled from expiration and validation based resources
// This can neither be cached nor revalidated, so it should be private/no cache
$this->assertEmpty($this->response->getContent());
$this->assertNull($this->response->getTtl());
$this->assertTrue($this->response->mustRevalidate());
$this->assertTrue($this->response->headers->hasCacheControlDirective('private'));
$this->assertTrue($this->response->headers->hasCacheControlDirective('no-cache'));
}
public function testEsiRecalculateContentLengthHeader()
{
$responses = array(
@@ -1138,7 +1285,6 @@ class HttpCacheTest extends HttpCacheTestCase
'body' => '<esi:include src="/foo" />',
'headers' => array(
'Content-Length' => 26,
'Cache-Control' => 's-maxage=300',
'Surrogate-Control' => 'content="ESI/1.0"',
),
),
@@ -1156,69 +1302,105 @@ class HttpCacheTest extends HttpCacheTestCase
$this->assertEquals(12, $this->response->headers->get('Content-Length'));
}
public function testEsiRecalculateContentLengthHeaderForHeadRequest()
{
$responses = array(
array(
'status' => 200,
'body' => '<esi:include src="/foo" />',
'headers' => array(
'Content-Length' => 26,
'Surrogate-Control' => 'content="ESI/1.0"',
),
),
array(
'status' => 200,
'body' => 'Hello World!',
'headers' => array(),
),
);
$this->setNextResponses($responses);
$this->request('HEAD', '/', array(), array(), true);
// https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.13
// "The Content-Length entity-header field indicates the size of the entity-body,
// in decimal number of OCTETs, sent to the recipient or, in the case of the HEAD
// method, the size of the entity-body that would have been sent had the request
// been a GET."
$this->assertEmpty($this->response->getContent());
$this->assertEquals(12, $this->response->headers->get('Content-Length'));
}
public function testClientIpIsAlwaysLocalhostForForwardedRequests()
{
$this->setNextResponse();
$this->request('GET', '/', array('REMOTE_ADDR' => '10.0.0.1'));
$this->assertEquals('127.0.0.1', $this->kernel->getBackendRequest()->server->get('REMOTE_ADDR'));
$this->kernel->assert(function ($backendRequest) {
$this->assertSame('127.0.0.1', $backendRequest->server->get('REMOTE_ADDR'));
});
}
/**
* @dataProvider getTrustedProxyData
*/
public function testHttpCacheIsSetAsATrustedProxy(array $existing, array $expected)
public function testHttpCacheIsSetAsATrustedProxy(array $existing)
{
Request::setTrustedProxies($existing);
Request::setTrustedProxies($existing, Request::HEADER_X_FORWARDED_ALL);
$this->setNextResponse();
$this->request('GET', '/', array('REMOTE_ADDR' => '10.0.0.1'));
$this->assertSame($existing, Request::getTrustedProxies());
$this->assertEquals($expected, Request::getTrustedProxies());
$existing = array_unique(array_merge($existing, array('127.0.0.1')));
$this->kernel->assert(function ($backendRequest) use ($existing) {
$this->assertSame($existing, Request::getTrustedProxies());
$this->assertsame('10.0.0.1', $backendRequest->getClientIp());
});
Request::setTrustedProxies(array(), -1);
}
public function getTrustedProxyData()
{
return array(
array(array(), array('127.0.0.1')),
array(array('10.0.0.2'), array('10.0.0.2', '127.0.0.1')),
array(array('10.0.0.2', '127.0.0.1'), array('10.0.0.2', '127.0.0.1')),
array(array()),
array(array('10.0.0.2')),
array(array('10.0.0.2', '127.0.0.1')),
);
}
/**
* @dataProvider getXForwardedForData
* @dataProvider getForwardedData
*/
public function testXForwarderForHeaderForForwardedRequests($xForwardedFor, $expected)
public function testForwarderHeaderForForwardedRequests($forwarded, $expected)
{
$this->setNextResponse();
$server = array('REMOTE_ADDR' => '10.0.0.1');
if (false !== $xForwardedFor) {
$server['HTTP_X_FORWARDED_FOR'] = $xForwardedFor;
if (null !== $forwarded) {
Request::setTrustedProxies($server, -1);
$server['HTTP_FORWARDED'] = $forwarded;
}
$this->request('GET', '/', $server);
$this->assertEquals($expected, $this->kernel->getBackendRequest()->headers->get('X-Forwarded-For'));
$this->kernel->assert(function ($backendRequest) use ($expected) {
$this->assertSame($expected, $backendRequest->headers->get('Forwarded'));
});
Request::setTrustedProxies(array(), -1);
}
public function getXForwardedForData()
public function getForwardedData()
{
return array(
array(false, '10.0.0.1'),
array('10.0.0.2', '10.0.0.2, 10.0.0.1'),
array('10.0.0.2, 10.0.0.3', '10.0.0.2, 10.0.0.3, 10.0.0.1'),
array(null, 'for="10.0.0.1";host="localhost";proto=http'),
array('for=10.0.0.2', 'for="10.0.0.2";host="localhost";proto=http, for="10.0.0.1"'),
array('for=10.0.0.2, for=10.0.0.3', 'for="10.0.0.2";host="localhost";proto=http, for="10.0.0.3", for="10.0.0.1"'),
);
}
public function testXForwarderForHeaderForPassRequests()
{
$this->setNextResponse();
$server = array('REMOTE_ADDR' => '10.0.0.1');
$this->request('POST', '/', $server);
$this->assertEquals('10.0.0.1', $this->kernel->getBackendRequest()->headers->get('X-Forwarded-For'));
}
public function testEsiCacheRemoveValidationHeadersIfEmbeddedResponses()
{
$time = \DateTime::createFromFormat('U', time());
@@ -1246,6 +1428,86 @@ class HttpCacheTest extends HttpCacheTestCase
$this->assertNull($this->response->getETag());
$this->assertNull($this->response->getLastModified());
}
public function testEsiCacheRemoveValidationHeadersIfEmbeddedResponsesAndHeadRequest()
{
$time = \DateTime::createFromFormat('U', time());
$responses = array(
array(
'status' => 200,
'body' => '<esi:include src="/hey" />',
'headers' => array(
'Surrogate-Control' => 'content="ESI/1.0"',
'ETag' => 'hey',
'Last-Modified' => $time->format(DATE_RFC2822),
),
),
array(
'status' => 200,
'body' => 'Hey!',
'headers' => array(),
),
);
$this->setNextResponses($responses);
$this->request('HEAD', '/', array(), array(), true);
$this->assertEmpty($this->response->getContent());
$this->assertNull($this->response->getETag());
$this->assertNull($this->response->getLastModified());
}
public function testDoesNotCacheOptionsRequest()
{
$this->setNextResponse(200, array('Cache-Control' => 'public, s-maxage=60'), 'get');
$this->request('GET', '/');
$this->assertHttpKernelIsCalled();
$this->setNextResponse(200, array('Cache-Control' => 'public, s-maxage=60'), 'options');
$this->request('OPTIONS', '/');
$this->assertHttpKernelIsCalled();
$this->request('GET', '/');
$this->assertHttpKernelIsNotCalled();
$this->assertSame('get', $this->response->getContent());
}
public function testUsesOriginalRequestForSurrogate()
{
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock();
$store = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpCache\StoreInterface')->getMock();
$kernel
->expects($this->exactly(2))
->method('handle')
->willReturnCallback(function (Request $request) {
$this->assertSame('127.0.0.1', $request->server->get('REMOTE_ADDR'));
return new Response();
});
$cache = new HttpCache($kernel,
$store,
new Esi()
);
$request = Request::create('/');
$request->server->set('REMOTE_ADDR', '10.0.0.1');
// Main request
$cache->handle($request, HttpKernelInterface::MASTER_REQUEST);
// Main request was now modified by HttpCache
// The surrogate will ask for the request using $this->cache->getRequest()
// which MUST return the original request so the surrogate
// can actually behave like a reverse proxy like e.g. Varnish would.
$this->assertSame('10.0.0.1', $cache->getRequest()->getClientIp());
$this->assertSame('10.0.0.1', $cache->getRequest()->server->get('REMOTE_ADDR'));
// Surrogate request
$cache->handle($request, HttpKernelInterface::SUB_REQUEST);
}
}
class TestKernel implements HttpKernelInterface

View File

@@ -11,13 +11,14 @@
namespace Symfony\Component\HttpKernel\Tests\HttpCache;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpCache\Esi;
use Symfony\Component\HttpKernel\HttpCache\HttpCache;
use Symfony\Component\HttpKernel\HttpCache\Store;
use Symfony\Component\HttpKernel\HttpKernelInterface;
class HttpCacheTestCase extends \PHPUnit_Framework_TestCase
class HttpCacheTestCase extends TestCase
{
protected $kernel;
protected $cache;
@@ -28,6 +29,10 @@ class HttpCacheTestCase extends \PHPUnit_Framework_TestCase
protected $responses;
protected $catch;
protected $esi;
/**
* @var Store
*/
protected $store;
protected function setUp()
@@ -163,7 +168,7 @@ class HttpCacheTestCase extends \PHPUnit_Framework_TestCase
$fp = opendir($directory);
while (false !== $file = readdir($fp)) {
if (!in_array($file, array('.', '..'))) {
if (!\in_array($file, array('.', '..'))) {
if (is_link($directory.'/'.$file)) {
unlink($directory.'/'.$file);
} elseif (is_dir($directory.'/'.$file)) {

View File

@@ -15,10 +15,11 @@
namespace Symfony\Component\HttpKernel\Tests\HttpCache;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpCache\ResponseCacheStrategy;
class ResponseCacheStrategyTest extends \PHPUnit_Framework_TestCase
class ResponseCacheStrategyTest extends TestCase
{
public function testMinimumSharedMaxAgeWins()
{
@@ -74,4 +75,166 @@ class ResponseCacheStrategyTest extends \PHPUnit_Framework_TestCase
$this->assertFalse($response->headers->hasCacheControlDirective('s-maxage'));
}
public function testMasterResponseNotCacheableWhenEmbeddedResponseRequiresValidation()
{
$cacheStrategy = new ResponseCacheStrategy();
$embeddedResponse = new Response();
$embeddedResponse->setLastModified(new \DateTime());
$cacheStrategy->add($embeddedResponse);
$masterResponse = new Response();
$masterResponse->setSharedMaxAge(3600);
$cacheStrategy->update($masterResponse);
$this->assertTrue($masterResponse->headers->hasCacheControlDirective('no-cache'));
$this->assertTrue($masterResponse->headers->hasCacheControlDirective('must-revalidate'));
$this->assertFalse($masterResponse->isFresh());
}
public function testValidationOnMasterResponseIsNotPossibleWhenItContainsEmbeddedResponses()
{
$cacheStrategy = new ResponseCacheStrategy();
// This master response uses the "validation" model
$masterResponse = new Response();
$masterResponse->setLastModified(new \DateTime());
$masterResponse->setEtag('foo');
// Embedded response uses "expiry" model
$embeddedResponse = new Response();
$masterResponse->setSharedMaxAge(3600);
$cacheStrategy->add($embeddedResponse);
$cacheStrategy->update($masterResponse);
$this->assertFalse($masterResponse->isValidateable());
$this->assertFalse($masterResponse->headers->has('Last-Modified'));
$this->assertFalse($masterResponse->headers->has('ETag'));
$this->assertTrue($masterResponse->headers->hasCacheControlDirective('no-cache'));
$this->assertTrue($masterResponse->headers->hasCacheControlDirective('must-revalidate'));
}
public function testMasterResponseWithValidationIsUnchangedWhenThereIsNoEmbeddedResponse()
{
$cacheStrategy = new ResponseCacheStrategy();
$masterResponse = new Response();
$masterResponse->setLastModified(new \DateTime());
$cacheStrategy->update($masterResponse);
$this->assertTrue($masterResponse->isValidateable());
}
public function testMasterResponseWithExpirationIsUnchangedWhenThereIsNoEmbeddedResponse()
{
$cacheStrategy = new ResponseCacheStrategy();
$masterResponse = new Response();
$masterResponse->setSharedMaxAge(3600);
$cacheStrategy->update($masterResponse);
$this->assertTrue($masterResponse->isFresh());
}
public function testMasterResponseIsNotCacheableWhenEmbeddedResponseIsNotCacheable()
{
$cacheStrategy = new ResponseCacheStrategy();
$masterResponse = new Response();
$masterResponse->setSharedMaxAge(3600); // Public, cacheable
/* This response has no validation or expiration information.
That makes it uncacheable, it is always stale.
(It does *not* make this private, though.) */
$embeddedResponse = new Response();
$this->assertFalse($embeddedResponse->isFresh()); // not fresh, as no lifetime is provided
$cacheStrategy->add($embeddedResponse);
$cacheStrategy->update($masterResponse);
$this->assertTrue($masterResponse->headers->hasCacheControlDirective('no-cache'));
$this->assertTrue($masterResponse->headers->hasCacheControlDirective('must-revalidate'));
$this->assertFalse($masterResponse->isFresh());
}
public function testEmbeddingPrivateResponseMakesMainResponsePrivate()
{
$cacheStrategy = new ResponseCacheStrategy();
$masterResponse = new Response();
$masterResponse->setSharedMaxAge(3600); // public, cacheable
// The embedded response might for example contain per-user data that remains valid for 60 seconds
$embeddedResponse = new Response();
$embeddedResponse->setPrivate();
$embeddedResponse->setMaxAge(60); // this would implicitly set "private" as well, but let's be explicit
$cacheStrategy->add($embeddedResponse);
$cacheStrategy->update($masterResponse);
$this->assertTrue($masterResponse->headers->hasCacheControlDirective('private'));
$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()
{
/* When "expiration wins over validation" (https://symfony.com/doc/current/http_cache/validation.html)
* and both the main and embedded response provide s-maxage, then the more restricting value of both
* should be fine, regardless of whether the embedded response can be validated later on or must be
* completely regenerated.
*/
$cacheStrategy = new ResponseCacheStrategy();
$masterResponse = new Response();
$masterResponse->setSharedMaxAge(3600);
$embeddedResponse = new Response();
$embeddedResponse->setSharedMaxAge(60);
$embeddedResponse->setEtag('foo');
$cacheStrategy->add($embeddedResponse);
$cacheStrategy->update($masterResponse);
$this->assertSame('60', $masterResponse->headers->getCacheControlDirective('s-maxage'));
}
public function testResponseIsExpirableButNotValidateableWhenMasterResponseCombinesExpirationAndValidation()
{
$cacheStrategy = new ResponseCacheStrategy();
$masterResponse = new Response();
$masterResponse->setSharedMaxAge(3600);
$masterResponse->setEtag('foo');
$masterResponse->setLastModified(new \DateTime());
$embeddedResponse = new Response();
$embeddedResponse->setSharedMaxAge(60);
$cacheStrategy->add($embeddedResponse);
$cacheStrategy->update($masterResponse);
$this->assertSame('60', $masterResponse->headers->getCacheControlDirective('s-maxage'));
$this->assertFalse($masterResponse->isValidateable());
}
}

View File

@@ -11,11 +11,12 @@
namespace Symfony\Component\HttpKernel\Tests\HttpCache;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpCache\Ssi;
class SsiTest extends \PHPUnit_Framework_TestCase
class SsiTest extends TestCase
{
public function testHasSurrogateSsiCapability()
{
@@ -39,10 +40,10 @@ class SsiTest extends \PHPUnit_Framework_TestCase
$request = Request::create('/');
$ssi->addSurrogateCapability($request);
$this->assertEquals('symfony2="SSI/1.0"', $request->headers->get('Surrogate-Capability'));
$this->assertEquals('symfony="SSI/1.0"', $request->headers->get('Surrogate-Capability'));
$ssi->addSurrogateCapability($request);
$this->assertEquals('symfony2="SSI/1.0", symfony2="SSI/1.0"', $request->headers->get('Surrogate-Capability'));
$this->assertEquals('symfony="SSI/1.0", symfony="SSI/1.0"', $request->headers->get('Surrogate-Capability'));
}
public function testAddSurrogateControl()
@@ -192,15 +193,15 @@ class SsiTest extends \PHPUnit_Framework_TestCase
protected function getCache($request, $response)
{
$cache = $this->getMock('Symfony\Component\HttpKernel\HttpCache\HttpCache', array('getRequest', 'handle'), array(), '', false);
$cache = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpCache\HttpCache')->setMethods(array('getRequest', 'handle'))->disableOriginalConstructor()->getMock();
$cache->expects($this->any())
->method('getRequest')
->will($this->returnValue($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(array($this, 'onConsecutiveCalls'), $response))
;
} else {
$cache->expects($this->any())

View File

@@ -11,11 +11,12 @@
namespace Symfony\Component\HttpKernel\Tests\HttpCache;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpCache\Store;
class StoreTest extends \PHPUnit_Framework_TestCase
class StoreTest extends TestCase
{
protected $request;
protected $response;
@@ -235,6 +236,33 @@ class StoreTest extends \PHPUnit_Framework_TestCase
$this->assertFalse($this->store->isLocked($req));
}
public function testPurgeHttps()
{
$request = Request::create('https://example.com/foo');
$this->store->write($request, new Response('foo'));
$this->assertNotEmpty($this->getStoreMetadata($request));
$this->assertTrue($this->store->purge('https://example.com/foo'));
$this->assertEmpty($this->getStoreMetadata($request));
}
public function testPurgeHttpAndHttps()
{
$requestHttp = Request::create('https://example.com/foo');
$this->store->write($requestHttp, new Response('foo'));
$requestHttps = Request::create('http://example.com/foo');
$this->store->write($requestHttps, new Response('foo'));
$this->assertNotEmpty($this->getStoreMetadata($requestHttp));
$this->assertNotEmpty($this->getStoreMetadata($requestHttps));
$this->assertTrue($this->store->purge('http://example.com/foo'));
$this->assertEmpty($this->getStoreMetadata($requestHttp));
$this->assertEmpty($this->getStoreMetadata($requestHttps));
}
protected function storeSimpleEntry($path = null, $headers = array())
{
if (null === $path) {

View File

@@ -0,0 +1,153 @@
<?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\HttpCache;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpCache\SubRequestHandler;
use Symfony\Component\HttpKernel\HttpKernelInterface;
class SubRequestHandlerTest extends TestCase
{
private static $globalState;
protected function setUp()
{
self::$globalState = $this->getGlobalState();
}
protected function tearDown()
{
Request::setTrustedProxies(self::$globalState[0], self::$globalState[1]);
}
public function testTrustedHeadersAreKept()
{
Request::setTrustedProxies(array('10.0.0.1'), -1);
$globalState = $this->getGlobalState();
$request = Request::create('/');
$request->server->set('REMOTE_ADDR', '10.0.0.1');
$request->headers->set('X-Forwarded-For', '10.0.0.2');
$request->headers->set('X-Forwarded-Host', 'Good');
$request->headers->set('X-Forwarded-Port', '1234');
$request->headers->set('X-Forwarded-Proto', 'https');
$kernel = new TestSubRequestHandlerKernel(function ($request, $type, $catch) {
$this->assertSame('127.0.0.1', $request->server->get('REMOTE_ADDR'));
$this->assertSame('10.0.0.2', $request->getClientIp());
$this->assertSame('Good', $request->headers->get('X-Forwarded-Host'));
$this->assertSame('1234', $request->headers->get('X-Forwarded-Port'));
$this->assertSame('https', $request->headers->get('X-Forwarded-Proto'));
});
SubRequestHandler::handle($kernel, $request, HttpKernelInterface::MASTER_REQUEST, true);
$this->assertSame($globalState, $this->getGlobalState());
}
public function testUntrustedHeadersAreRemoved()
{
$request = Request::create('/');
$request->server->set('REMOTE_ADDR', '10.0.0.1');
$request->headers->set('X-Forwarded-For', '10.0.0.2');
$request->headers->set('X-Forwarded-Host', 'Evil');
$request->headers->set('X-Forwarded-Port', '1234');
$request->headers->set('X-Forwarded-Proto', 'http');
$request->headers->set('Forwarded', 'Evil2');
$kernel = new TestSubRequestHandlerKernel(function ($request, $type, $catch) {
$this->assertSame('127.0.0.1', $request->server->get('REMOTE_ADDR'));
$this->assertSame('10.0.0.1', $request->getClientIp());
$this->assertFalse($request->headers->has('X-Forwarded-Host'));
$this->assertFalse($request->headers->has('X-Forwarded-Port'));
$this->assertFalse($request->headers->has('X-Forwarded-Proto'));
$this->assertSame('for="10.0.0.1";host="localhost";proto=http', $request->headers->get('Forwarded'));
});
SubRequestHandler::handle($kernel, $request, HttpKernelInterface::MASTER_REQUEST, true);
$this->assertSame(self::$globalState, $this->getGlobalState());
}
public function testTrustedForwardedHeader()
{
Request::setTrustedProxies(array('10.0.0.1'), -1);
$globalState = $this->getGlobalState();
$request = Request::create('/');
$request->server->set('REMOTE_ADDR', '10.0.0.1');
$request->headers->set('Forwarded', 'for="10.0.0.2";host="foo.bar:1234";proto=https');
$kernel = new TestSubRequestHandlerKernel(function ($request, $type, $catch) {
$this->assertSame('127.0.0.1', $request->server->get('REMOTE_ADDR'));
$this->assertSame('10.0.0.2', $request->getClientIp());
$this->assertSame('foo.bar:1234', $request->getHttpHost());
$this->assertSame('https', $request->getScheme());
$this->assertSame(1234, $request->getPort());
});
SubRequestHandler::handle($kernel, $request, HttpKernelInterface::MASTER_REQUEST, true);
$this->assertSame($globalState, $this->getGlobalState());
}
public function testTrustedXForwardedForHeader()
{
Request::setTrustedProxies(array('10.0.0.1'), -1);
$globalState = $this->getGlobalState();
$request = Request::create('/');
$request->server->set('REMOTE_ADDR', '10.0.0.1');
$request->headers->set('X-Forwarded-For', '10.0.0.2');
$request->headers->set('X-Forwarded-Host', 'foo.bar');
$request->headers->set('X-Forwarded-Proto', 'https');
$kernel = new TestSubRequestHandlerKernel(function ($request, $type, $catch) {
$this->assertSame('127.0.0.1', $request->server->get('REMOTE_ADDR'));
$this->assertSame('10.0.0.2', $request->getClientIp());
$this->assertSame('foo.bar', $request->getHttpHost());
$this->assertSame('https', $request->getScheme());
});
SubRequestHandler::handle($kernel, $request, HttpKernelInterface::MASTER_REQUEST, true);
$this->assertSame($globalState, $this->getGlobalState());
}
private function getGlobalState()
{
return array(
Request::getTrustedProxies(),
Request::getTrustedHeaderSet(),
);
}
}
class TestSubRequestHandlerKernel implements HttpKernelInterface
{
private $assertCallback;
public function __construct(\Closure $assertCallback)
{
$this->assertCallback = $assertCallback;
}
public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = true)
{
$assertCallback = $this->assertCallback;
$assertCallback($request, $type, $catch);
return new Response();
}
}

View File

@@ -11,14 +11,15 @@
namespace Symfony\Component\HttpKernel\Tests\HttpCache;
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
class TestHttpKernel extends HttpKernel implements ControllerResolverInterface, ArgumentResolverInterface
{
protected $body;
protected $status;
@@ -35,18 +36,28 @@ class TestHttpKernel extends HttpKernel implements ControllerResolverInterface
$this->headers = $headers;
$this->customizer = $customizer;
parent::__construct(new EventDispatcher(), $this);
parent::__construct(new EventDispatcher(), $this, null, $this);
}
public function getBackendRequest()
public function assert(\Closure $callback)
{
return $this->backendRequest;
$trustedConfig = array(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 = array(Request::getTrustedProxies(), Request::getTrustedHeaderSet(), $request);
return parent::handle($request, $type, $catch);
}

View File

@@ -11,14 +11,15 @@
namespace Symfony\Component\HttpKernel\Tests\HttpCache;
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
class TestMultipleHttpKernel extends HttpKernel implements ControllerResolverInterface, ArgumentResolverInterface
{
protected $bodies = array();
protected $statuses = array();
@@ -34,7 +35,7 @@ class TestMultipleHttpKernel extends HttpKernel implements ControllerResolverInt
$this->headers[] = $response['headers'];
}
parent::__construct(new EventDispatcher(), $this);
parent::__construct(new EventDispatcher(), $this, null, $this);
}
public function getBackendRequest()

View File

@@ -11,24 +11,31 @@
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 \PHPUnit_Framework_TestCase
class HttpKernelTest extends TestCase
{
/**
* @expectedException \RuntimeException
*/
public function testHandleWhenControllerThrowsAnExceptionAndCatchIsTrue()
{
$kernel = new HttpKernel(new EventDispatcher(), $this->getResolver(function () { throw new \RuntimeException(); }));
$kernel = $this->getHttpKernel(new EventDispatcher(), function () { throw new \RuntimeException(); });
$kernel->handle(new Request(), HttpKernelInterface::MASTER_REQUEST, true);
}
@@ -38,7 +45,7 @@ class HttpKernelTest extends \PHPUnit_Framework_TestCase
*/
public function testHandleWhenControllerThrowsAnExceptionAndCatchIsFalseAndNoListenerIsRegistered()
{
$kernel = new HttpKernel(new EventDispatcher(), $this->getResolver(function () { throw new \RuntimeException(); }));
$kernel = $this->getHttpKernel(new EventDispatcher(), function () { throw new \RuntimeException(); });
$kernel->handle(new Request(), HttpKernelInterface::MASTER_REQUEST, false);
}
@@ -50,7 +57,7 @@ class HttpKernelTest extends \PHPUnit_Framework_TestCase
$event->setResponse(new Response($event->getException()->getMessage()));
});
$kernel = new HttpKernel($dispatcher, $this->getResolver(function () { throw new \RuntimeException('foo'); }));
$kernel = $this->getHttpKernel($dispatcher, function () { throw new \RuntimeException('foo'); });
$response = $kernel->handle(new Request(), HttpKernelInterface::MASTER_REQUEST, true);
$this->assertEquals('500', $response->getStatusCode());
@@ -66,7 +73,7 @@ class HttpKernelTest extends \PHPUnit_Framework_TestCase
// should set a response, but does not
});
$kernel = new HttpKernel($dispatcher, $this->getResolver(function () use ($exception) { throw $exception; }));
$kernel = $this->getHttpKernel($dispatcher, function () use ($exception) { throw $exception; });
try {
$kernel->handle(new Request(), HttpKernelInterface::MASTER_REQUEST, true);
@@ -83,7 +90,7 @@ class HttpKernelTest extends \PHPUnit_Framework_TestCase
$event->setResponse(new RedirectResponse('/login', 301));
});
$kernel = new HttpKernel($dispatcher, $this->getResolver(function () { throw new AccessDeniedHttpException(); }));
$kernel = $this->getHttpKernel($dispatcher, function () { throw new AccessDeniedHttpException(); });
$response = $kernel->handle(new Request());
$this->assertEquals('301', $response->getStatusCode());
@@ -97,7 +104,7 @@ class HttpKernelTest extends \PHPUnit_Framework_TestCase
$event->setResponse(new Response($event->getException()->getMessage()));
});
$kernel = new HttpKernel($dispatcher, $this->getResolver(function () { throw new MethodNotAllowedHttpException(array('POST')); }));
$kernel = $this->getHttpKernel($dispatcher, function () { throw new MethodNotAllowedHttpException(array('POST')); });
$response = $kernel->handle(new Request());
$this->assertEquals('405', $response->getStatusCode());
@@ -105,16 +112,17 @@ class HttpKernelTest extends \PHPUnit_Framework_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)));
});
$kernel = new HttpKernel($dispatcher, $this->getResolver(function () { throw new \RuntimeException(); }));
$kernel = $this->getHttpKernel($dispatcher, function () { throw new \RuntimeException(); });
$response = $kernel->handle(new Request());
$this->assertEquals($expectedStatusCode, $response->getStatusCode());
@@ -131,6 +139,32 @@ class HttpKernelTest extends \PHPUnit_Framework_TestCase
);
}
/**
* @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 array(
array(200),
array(302),
array(403),
);
}
public function testHandleWhenAListenerReturnsAResponse()
{
$dispatcher = new EventDispatcher();
@@ -138,7 +172,7 @@ class HttpKernelTest extends \PHPUnit_Framework_TestCase
$event->setResponse(new Response('hello'));
});
$kernel = new HttpKernel($dispatcher, $this->getResolver());
$kernel = $this->getHttpKernel($dispatcher);
$this->assertEquals('hello', $kernel->handle(new Request())->getContent());
}
@@ -149,7 +183,7 @@ class HttpKernelTest extends \PHPUnit_Framework_TestCase
public function testHandleWhenNoControllerIsFound()
{
$dispatcher = new EventDispatcher();
$kernel = new HttpKernel($dispatcher, $this->getResolver(false));
$kernel = $this->getHttpKernel($dispatcher, false);
$kernel->handle(new Request());
}
@@ -158,7 +192,7 @@ class HttpKernelTest extends \PHPUnit_Framework_TestCase
{
$response = new Response('foo');
$dispatcher = new EventDispatcher();
$kernel = new HttpKernel($dispatcher, $this->getResolver(function () use ($response) { return $response; }));
$kernel = $this->getHttpKernel($dispatcher, function () use ($response) { return $response; });
$this->assertSame($response, $kernel->handle(new Request()));
}
@@ -166,7 +200,7 @@ class HttpKernelTest extends \PHPUnit_Framework_TestCase
public function testHandleWhenTheControllerIsAnObjectWithInvoke()
{
$dispatcher = new EventDispatcher();
$kernel = new HttpKernel($dispatcher, $this->getResolver(new Controller()));
$kernel = $this->getHttpKernel($dispatcher, new Controller());
$this->assertResponseEquals(new Response('foo'), $kernel->handle(new Request()));
}
@@ -174,7 +208,7 @@ class HttpKernelTest extends \PHPUnit_Framework_TestCase
public function testHandleWhenTheControllerIsAFunction()
{
$dispatcher = new EventDispatcher();
$kernel = new HttpKernel($dispatcher, $this->getResolver('Symfony\Component\HttpKernel\Tests\controller_func'));
$kernel = $this->getHttpKernel($dispatcher, 'Symfony\Component\HttpKernel\Tests\controller_func');
$this->assertResponseEquals(new Response('foo'), $kernel->handle(new Request()));
}
@@ -182,7 +216,7 @@ class HttpKernelTest extends \PHPUnit_Framework_TestCase
public function testHandleWhenTheControllerIsAnArray()
{
$dispatcher = new EventDispatcher();
$kernel = new HttpKernel($dispatcher, $this->getResolver(array(new Controller(), 'controller')));
$kernel = $this->getHttpKernel($dispatcher, array(new Controller(), 'controller'));
$this->assertResponseEquals(new Response('foo'), $kernel->handle(new Request()));
}
@@ -190,7 +224,7 @@ class HttpKernelTest extends \PHPUnit_Framework_TestCase
public function testHandleWhenTheControllerIsAStaticArray()
{
$dispatcher = new EventDispatcher();
$kernel = new HttpKernel($dispatcher, $this->getResolver(array('Symfony\Component\HttpKernel\Tests\Controller', 'staticcontroller')));
$kernel = $this->getHttpKernel($dispatcher, array('Symfony\Component\HttpKernel\Tests\Controller', 'staticcontroller'));
$this->assertResponseEquals(new Response('foo'), $kernel->handle(new Request()));
}
@@ -201,7 +235,7 @@ class HttpKernelTest extends \PHPUnit_Framework_TestCase
public function testHandleWhenTheControllerDoesNotReturnAResponse()
{
$dispatcher = new EventDispatcher();
$kernel = new HttpKernel($dispatcher, $this->getResolver(function () { return 'foo'; }));
$kernel = $this->getHttpKernel($dispatcher, function () { return 'foo'; });
$kernel->handle(new Request());
}
@@ -212,7 +246,8 @@ class HttpKernelTest extends \PHPUnit_Framework_TestCase
$dispatcher->addListener(KernelEvents::VIEW, function ($event) {
$event->setResponse(new Response($event->getControllerResult()));
});
$kernel = new HttpKernel($dispatcher, $this->getResolver(function () { return 'foo'; }));
$kernel = $this->getHttpKernel($dispatcher, function () { return 'foo'; });
$this->assertEquals('foo', $kernel->handle(new Request())->getContent());
}
@@ -223,15 +258,51 @@ class HttpKernelTest extends \PHPUnit_Framework_TestCase
$dispatcher->addListener(KernelEvents::RESPONSE, function ($event) {
$event->setResponse(new Response('foo'));
});
$kernel = new HttpKernel($dispatcher, $this->getResolver());
$kernel = $this->getHttpKernel($dispatcher);
$this->assertEquals('foo', $kernel->handle(new Request())->getContent());
}
public function testHandleAllowChangingControllerArguments()
{
$dispatcher = new EventDispatcher();
$dispatcher->addListener(KernelEvents::CONTROLLER_ARGUMENTS, function (FilterControllerArgumentsEvent $event) {
$event->setArguments(array('foo'));
});
$kernel = $this->getHttpKernel($dispatcher, function ($content) { return new Response($content); });
$this->assertResponseEquals(new Response('foo'), $kernel->handle(new Request()));
}
public function testHandleAllowChangingControllerAndArguments()
{
$dispatcher = new EventDispatcher();
$dispatcher->addListener(KernelEvents::CONTROLLER_ARGUMENTS, function (FilterControllerArgumentsEvent $event) {
$oldController = $event->getController();
$oldArguments = $event->getArguments();
$newController = function ($id) use ($oldController, $oldArguments) {
$response = \call_user_func_array($oldController, $oldArguments);
$response->headers->set('X-Id', $id);
return $response;
};
$event->setController($newController);
$event->setArguments(array('bar'));
});
$kernel = $this->getHttpKernel($dispatcher, function ($content) { return new Response($content); }, null, array('foo'));
$this->assertResponseEquals(new Response('foo', 200, array('X-Id' => 'bar')), $kernel->handle(new Request()));
}
public function testTerminate()
{
$dispatcher = new EventDispatcher();
$kernel = new HttpKernel($dispatcher, $this->getResolver());
$kernel = $this->getHttpKernel($dispatcher);
$dispatcher->addListener(KernelEvents::TERMINATE, function ($event) use (&$called, &$capturedKernel, &$capturedRequest, &$capturedResponse) {
$called = true;
$capturedKernel = $event->getKernel();
@@ -250,55 +321,60 @@ class HttpKernelTest extends \PHPUnit_Framework_TestCase
{
$request = new Request();
$stack = $this->getMock('Symfony\Component\HttpFoundation\RequestStack', array('push', 'pop'));
$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');
$dispatcher = new EventDispatcher();
$kernel = new HttpKernel($dispatcher, $this->getResolver(), $stack);
$kernel = $this->getHttpKernel($dispatcher, null, $stack);
$kernel->handle($request, HttpKernelInterface::MASTER_REQUEST);
}
/**
* @expectedException Symfony\Component\HttpKernel\Exception\BadRequestHttpException
* @expectedException \Symfony\Component\HttpKernel\Exception\BadRequestHttpException
*/
public function testInconsistentClientIpsOnMasterRequests()
{
$request = new Request();
$request->setTrustedProxies(array('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 = new EventDispatcher();
$dispatcher->addListener(KernelEvents::REQUEST, function ($event) {
$event->getRequest()->getClientIp();
});
$kernel = new HttpKernel($dispatcher, $this->getResolver());
$request = new Request();
$request->setTrustedProxies(array('1.1.1.1'));
$request->server->set('REMOTE_ADDR', '1.1.1.1');
$request->headers->set('FORWARDED', '2.2.2.2');
$request->headers->set('X_FORWARDED_FOR', '3.3.3.3');
$kernel = $this->getHttpKernel($dispatcher);
$kernel->handle($request, $kernel::MASTER_REQUEST, false);
Request::setTrustedProxies(array(), -1);
}
protected function getResolver($controller = null)
private function getHttpKernel(EventDispatcherInterface $eventDispatcher, $controller = null, RequestStack $requestStack = null, array $arguments = array())
{
if (null === $controller) {
$controller = function () { return new Response('Hello'); };
}
$resolver = $this->getMock('Symfony\\Component\\HttpKernel\\Controller\\ControllerResolverInterface');
$resolver->expects($this->any())
$controllerResolver = $this->getMockBuilder(ControllerResolverInterface::class)->getMock();
$controllerResolver
->expects($this->any())
->method('getController')
->will($this->returnValue($controller));
$resolver->expects($this->any())
->method('getArguments')
->will($this->returnValue(array()));
return $resolver;
$argumentResolver = $this->getMockBuilder(ArgumentResolverInterface::class)->getMock();
$argumentResolver
->expects($this->any())
->method('getArguments')
->will($this->returnValue($arguments));
return new HttpKernel($eventDispatcher, $controllerResolver, $requestStack, $argumentResolver);
}
protected function assertResponseEquals(Response $expected, Response $actual)
private function assertResponseEquals(Response $expected, Response $actual)
{
$expected->setDate($actual->getDate());
$this->assertEquals($expected, $actual);

View File

@@ -11,18 +11,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\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 \PHPUnit_Framework_TestCase
class KernelTest extends TestCase
{
public static function tearDownAfterClass()
{
$fs = new Filesystem();
$fs->remove(__DIR__.'/Fixtures/cache');
}
public function testConstructor()
{
$env = 'test_env';
@@ -51,6 +65,31 @@ class KernelTest extends \PHPUnit_Framework_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->assertFileNotExists($containerDir.'.legacy');
$kernel = new CustomProjectDirKernel(function ($container) { $container->register('foo', 'stdClass')->setPublic(true); });
$kernel->boot();
$this->assertFileExists($containerDir);
$this->assertFileExists($containerDir.'.legacy');
$this->assertFileNotExists($legacyContainerDir);
$this->assertFileNotExists($legacyContainerDir.'.legacy');
}
public function testBootInitializesBundlesAndContainer()
{
$kernel = $this->getKernel(array('initializeBundles', 'initializeContainer'));
@@ -64,7 +103,7 @@ class KernelTest extends \PHPUnit_Framework_TestCase
public function testBootSetsTheContainerToTheBundles()
{
$bundle = $this->getMock('Symfony\Component\HttpKernel\Bundle\Bundle');
$bundle = $this->getMockBuilder('Symfony\Component\HttpKernel\Bundle\Bundle')->getMock();
$bundle->expects($this->once())
->method('setContainer');
@@ -85,6 +124,9 @@ class KernelTest extends \PHPUnit_Framework_TestCase
$this->assertTrue($kernel->isBooted());
}
/**
* @group legacy
*/
public function testClassCacheIsLoaded()
{
$kernel = $this->getKernel(array('initializeBundles', 'initializeContainer', 'doLoadClassCache'));
@@ -105,6 +147,9 @@ class KernelTest extends \PHPUnit_Framework_TestCase
$kernel->boot();
}
/**
* @group legacy
*/
public function testClassCacheIsNotLoadedWhenKernelIsNotBooted()
{
$kernel = $this->getKernel(array('initializeBundles', 'initializeContainer', 'doLoadClassCache'));
@@ -133,7 +178,7 @@ class KernelTest extends \PHPUnit_Framework_TestCase
->method('getLogDir')
->will($this->returnValue(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);
@@ -161,7 +206,7 @@ class KernelTest extends \PHPUnit_Framework_TestCase
public function testShutdownCallsShutdownOnAllBundles()
{
$bundle = $this->getMock('Symfony\Component\HttpKernel\Bundle\Bundle');
$bundle = $this->getMockBuilder('Symfony\Component\HttpKernel\Bundle\Bundle')->getMock();
$bundle->expects($this->once())
->method('shutdown');
@@ -173,7 +218,7 @@ class KernelTest extends \PHPUnit_Framework_TestCase
public function testShutdownGivesNullContainerToAllBundles()
{
$bundle = $this->getMock('Symfony\Component\HttpKernel\Bundle\Bundle');
$bundle = $this->getMockBuilder('Symfony\Component\HttpKernel\Bundle\Bundle')->getMock();
$bundle->expects($this->at(3))
->method('setContainer')
->with(null);
@@ -304,7 +349,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);
}
@@ -316,7 +361,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()
@@ -394,6 +439,9 @@ EOF;
$this->assertEquals(__DIR__.'/Fixtures/Bundle1Bundle/foo.txt', $kernel->locateResource('@Bundle1Bundle/foo.txt'));
}
/**
* @group legacy
*/
public function testLocateResourceReturnsTheFirstThatMatchesWithParent()
{
$parent = $this->getBundle(__DIR__.'/Fixtures/Bundle1Bundle');
@@ -410,6 +458,9 @@ EOF;
$this->assertEquals(__DIR__.'/Fixtures/Bundle1Bundle/bar.txt', $kernel->locateResource('@ParentAABundle/bar.txt'));
}
/**
* @group legacy
*/
public function testLocateResourceReturnsAllMatches()
{
$parent = $this->getBundle(__DIR__.'/Fixtures/Bundle1Bundle');
@@ -428,6 +479,9 @@ EOF;
$kernel->locateResource('@Bundle1Bundle/foo.txt', null, false));
}
/**
* @group legacy
*/
public function testLocateResourceReturnsAllMatchesBis()
{
$kernel = $this->getKernel(array('getBundle'));
@@ -476,6 +530,9 @@ EOF;
);
}
/**
* @group legacy
*/
public function testLocateResourceReturnsTheDirOneForResourcesAndBundleOnes()
{
$kernel = $this->getKernel(array('getBundle'));
@@ -492,6 +549,9 @@ EOF;
);
}
/**
* @group legacy
*/
public function testLocateResourceOverrideBundleAndResourcesFolders()
{
$parent = $this->getBundle(__DIR__.'/Fixtures/BaseBundle', null, 'BaseBundle', 'BaseBundle');
@@ -565,6 +625,9 @@ EOF;
);
}
/**
* @group legacy
*/
public function testInitializeBundles()
{
$parent = $this->getBundle(null, null, 'ParentABundle');
@@ -583,6 +646,9 @@ EOF;
$this->assertEquals(array($child, $parent), $map['ParentABundle']);
}
/**
* @group legacy
*/
public function testInitializeBundlesSupportInheritanceCascade()
{
$grandparent = $this->getBundle(null, null, 'GrandParentBBundle');
@@ -605,6 +671,7 @@ EOF;
}
/**
* @group legacy
* @expectedException \LogicException
* @expectedExceptionMessage Bundle "ChildCBundle" extends bundle "FooBar", which is not registered.
*/
@@ -615,6 +682,9 @@ EOF;
$kernel->boot();
}
/**
* @group legacy
*/
public function testInitializeBundlesSupportsArbitraryBundleRegistrationOrder()
{
$grandparent = $this->getBundle(null, null, 'GrandParentCBundle');
@@ -637,6 +707,7 @@ EOF;
}
/**
* @group legacy
* @expectedException \LogicException
* @expectedExceptionMessage Bundle "ParentCBundle" is directly extended by two bundles "ChildC2Bundle" and "ChildC1Bundle".
*/
@@ -651,6 +722,7 @@ EOF;
}
/**
* @group legacy
* @expectedException \LogicException
* @expectedExceptionMessage Trying to register two bundles with the same name "DuplicateName"
*/
@@ -664,6 +736,7 @@ EOF;
}
/**
* @group legacy
* @expectedException \LogicException
* @expectedExceptionMessage Bundle "CircularRefBundle" can not extend itself.
*/
@@ -718,6 +791,131 @@ EOF;
$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';
require_once $dir.'/Kernel123.php';
$kernel = new \Symfony\Component\HttpKernel\Tests\Fixtures\_123\Kernel123('dev', true);
$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', array('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->getKernelForTest(array('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.
*
@@ -740,7 +938,7 @@ EOF;
$bundle
->expects($this->any())
->method('getName')
->will($this->returnValue(null === $bundleName ? get_class($bundle) : $bundleName))
->will($this->returnValue(null === $bundleName ? \get_class($bundle) : $bundleName))
;
$bundle
@@ -787,10 +985,10 @@ EOF;
return $kernel;
}
protected function getKernelForTest(array $methods = array())
protected function getKernelForTest(array $methods = array(), $debug = false)
{
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\Tests\Fixtures\KernelForTest')
->setConstructorArgs(array('test', false))
->setConstructorArgs(array('test', $debug))
->setMethods($methods)
->getMock();
$p = new \ReflectionProperty($kernel, 'rootDir');
@@ -814,3 +1012,64 @@ class TestKernel implements HttpKernelInterface
{
}
}
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 array();
}
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);
}
}

View File

@@ -0,0 +1,212 @@
<?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\Log;
use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;
use Symfony\Component\HttpKernel\Log\Logger;
/**
* @author Kévin Dunglas <dunglas@gmail.com>
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class LoggerTest extends TestCase
{
/**
* @var LoggerInterface
*/
private $logger;
/**
* @var string
*/
private $tmpFile;
protected function setUp()
{
$this->tmpFile = sys_get_temp_dir().\DIRECTORY_SEPARATOR.'log';
$this->logger = new Logger(LogLevel::DEBUG, $this->tmpFile);
}
protected function tearDown()
{
if (!@unlink($this->tmpFile)) {
file_put_contents($this->tmpFile, '');
}
}
public static function assertLogsMatch(array $expected, array $given)
{
foreach ($given as $k => $line) {
self::assertThat(1 === preg_match('/[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}[\+-][0-9]{2}:[0-9]{2} '.preg_quote($expected[$k]).'/', $line), self::isTrue(), "\"$line\" do not match expected pattern \"$expected[$k]\"");
}
}
/**
* Return the log messages in order.
*
* @return string[]
*/
public function getLogs()
{
return file($this->tmpFile, FILE_IGNORE_NEW_LINES);
}
public function testImplements()
{
$this->assertInstanceOf(LoggerInterface::class, $this->logger);
}
/**
* @dataProvider provideLevelsAndMessages
*/
public function testLogsAtAllLevels($level, $message)
{
$this->logger->{$level}($message, array('user' => 'Bob'));
$this->logger->log($level, $message, array('user' => 'Bob'));
$expected = array(
"[$level] message of level $level with context: Bob",
"[$level] message of level $level with context: Bob",
);
$this->assertLogsMatch($expected, $this->getLogs());
}
public function provideLevelsAndMessages()
{
return array(
LogLevel::EMERGENCY => array(LogLevel::EMERGENCY, 'message of level emergency with context: {user}'),
LogLevel::ALERT => array(LogLevel::ALERT, 'message of level alert with context: {user}'),
LogLevel::CRITICAL => array(LogLevel::CRITICAL, 'message of level critical with context: {user}'),
LogLevel::ERROR => array(LogLevel::ERROR, 'message of level error with context: {user}'),
LogLevel::WARNING => array(LogLevel::WARNING, 'message of level warning with context: {user}'),
LogLevel::NOTICE => array(LogLevel::NOTICE, 'message of level notice with context: {user}'),
LogLevel::INFO => array(LogLevel::INFO, 'message of level info with context: {user}'),
LogLevel::DEBUG => array(LogLevel::DEBUG, 'message of level debug with context: {user}'),
);
}
public function testLogLevelDisabled()
{
$this->logger = new Logger(LogLevel::INFO, $this->tmpFile);
$this->logger->debug('test', array('user' => 'Bob'));
$this->logger->log(LogLevel::DEBUG, 'test', array('user' => 'Bob'));
// Will always be true, but asserts than an exception isn't thrown
$this->assertSame(array(), $this->getLogs());
}
/**
* @expectedException \Psr\Log\InvalidArgumentException
*/
public function testThrowsOnInvalidLevel()
{
$this->logger->log('invalid level', 'Foo');
}
/**
* @expectedException \Psr\Log\InvalidArgumentException
*/
public function testThrowsOnInvalidMinLevel()
{
new Logger('invalid');
}
/**
* @expectedException \Psr\Log\InvalidArgumentException
*/
public function testInvalidOutput()
{
new Logger(LogLevel::DEBUG, '/');
}
public function testContextReplacement()
{
$logger = $this->logger;
$logger->info('{Message {nothing} {user} {foo.bar} a}', array('user' => 'Bob', 'foo.bar' => 'Bar'));
$expected = array('[info] {Message {nothing} Bob Bar a}');
$this->assertLogsMatch($expected, $this->getLogs());
}
public function testObjectCastToString()
{
if (method_exists($this, 'createPartialMock')) {
$dummy = $this->createPartialMock(DummyTest::class, array('__toString'));
} else {
$dummy = $this->getMock(DummyTest::class, array('__toString'));
}
$dummy->expects($this->atLeastOnce())
->method('__toString')
->will($this->returnValue('DUMMY'));
$this->logger->warning($dummy);
$expected = array('[warning] DUMMY');
$this->assertLogsMatch($expected, $this->getLogs());
}
public function testContextCanContainAnything()
{
$context = array(
'bool' => true,
'null' => null,
'string' => 'Foo',
'int' => 0,
'float' => 0.5,
'nested' => array('with object' => new DummyTest()),
'object' => new \DateTime(),
'resource' => fopen('php://memory', 'r'),
);
$this->logger->warning('Crazy context data', $context);
$expected = array('[warning] Crazy context data');
$this->assertLogsMatch($expected, $this->getLogs());
}
public function testContextExceptionKeyCanBeExceptionOrOtherValues()
{
$logger = $this->logger;
$logger->warning('Random message', array('exception' => 'oops'));
$logger->critical('Uncaught Exception!', array('exception' => new \LogicException('Fail')));
$expected = array(
'[warning] Random message',
'[critical] Uncaught Exception!',
);
$this->assertLogsMatch($expected, $this->getLogs());
}
public function testFormatter()
{
$this->logger = new Logger(LogLevel::DEBUG, $this->tmpFile, function ($level, $message, $context) {
return json_encode(array('level' => $level, 'message' => $message, 'context' => $context)).\PHP_EOL;
});
$this->logger->error('An error', array('foo' => 'bar'));
$this->logger->warning('A warning', array('baz' => 'bar'));
$this->assertSame(array(
'{"level":"error","message":"An error","context":{"foo":"bar"}}',
'{"level":"warning","message":"A warning","context":{"baz":"bar"}}',
), $this->getLogs());
}
}
class DummyTest
{
public function __toString()
{
}
}

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