the whole shebang

This commit is contained in:
2014-11-25 16:42:40 +01:00
parent 7f74c0613e
commit ab1334c0cf
3686 changed files with 496409 additions and 1 deletions

View File

@@ -0,0 +1,48 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien.potencier@symfony-project.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\Bundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Component\HttpKernel\Tests\Fixtures\ExtensionPresentBundle\ExtensionPresentBundle;
use Symfony\Component\HttpKernel\Tests\Fixtures\ExtensionAbsentBundle\ExtensionAbsentBundle;
use Symfony\Component\HttpKernel\Tests\Fixtures\ExtensionPresentBundle\Command\FooCommand;
class BundleTest extends \PHPUnit_Framework_TestCase
{
public function testRegisterCommands()
{
if (!class_exists('Symfony\Component\Console\Application')) {
$this->markTestSkipped('The "Console" component is not available');
}
if (!interface_exists('Symfony\Component\DependencyInjection\ContainerAwareInterface')) {
$this->markTestSkipped('The "DependencyInjection" component is not available');
}
if (!class_exists('Symfony\Component\Finder\Finder')) {
$this->markTestSkipped('The "Finder" component is not available');
}
$cmd = new FooCommand();
$app = $this->getMock('Symfony\Component\Console\Application');
$app->expects($this->once())->method('add')->with($this->equalTo($cmd));
$bundle = new ExtensionPresentBundle();
$bundle->registerCommands($app);
$bundle2 = new ExtensionAbsentBundle();
$this->assertNull($bundle2->registerCommands($app));
}
}

View File

@@ -0,0 +1,58 @@
<?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 Symfony\Component\HttpKernel\CacheClearer\CacheClearerInterface;
use Symfony\Component\HttpKernel\CacheClearer\ChainCacheClearer;
class ChainCacheClearerTest extends \PHPUnit_Framework_TestCase
{
protected static $cacheDir;
public static function setUpBeforeClass()
{
self::$cacheDir = tempnam(sys_get_temp_dir(), 'sf2_cache_clearer_dir');
}
public static function tearDownAfterClass()
{
@unlink(self::$cacheDir);
}
public function testInjectClearersInConstructor()
{
$clearer = $this->getMockClearer();
$clearer
->expects($this->once())
->method('clear');
$chainClearer = new ChainCacheClearer(array($clearer));
$chainClearer->clear(self::$cacheDir);
}
public function testInjectClearerUsingAdd()
{
$clearer = $this->getMockClearer();
$clearer
->expects($this->once())
->method('clear');
$chainClearer = new ChainCacheClearer();
$chainClearer->add($clearer);
$chainClearer->clear(self::$cacheDir);
}
protected function getMockClearer()
{
return $this->getMock('Symfony\Component\HttpKernel\CacheClearer\CacheClearerInterface');
}
}

View File

@@ -0,0 +1,102 @@
<?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\CacheWarmer;
use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerInterface;
use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerAggregate;
use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmer;
class CacheWarmerAggregateTest extends \PHPUnit_Framework_TestCase
{
protected static $cacheDir;
public static function setUpBeforeClass()
{
self::$cacheDir = tempnam(sys_get_temp_dir(), 'sf2_cache_warmer_dir');
}
public static function tearDownAfterClass()
{
@unlink(self::$cacheDir);
}
public function testInjectWarmersUsingConstructor()
{
$warmer = $this->getCacheWarmerMock();
$warmer
->expects($this->once())
->method('warmUp');
$aggregate = new CacheWarmerAggregate(array($warmer));
$aggregate->warmUp(self::$cacheDir);
}
public function testInjectWarmersUsingAdd()
{
$warmer = $this->getCacheWarmerMock();
$warmer
->expects($this->once())
->method('warmUp');
$aggregate = new CacheWarmerAggregate();
$aggregate->add($warmer);
$aggregate->warmUp(self::$cacheDir);
}
public function testInjectWarmersUsingSetWarmers()
{
$warmer = $this->getCacheWarmerMock();
$warmer
->expects($this->once())
->method('warmUp');
$aggregate = new CacheWarmerAggregate();
$aggregate->setWarmers(array($warmer));
$aggregate->warmUp(self::$cacheDir);
}
public function testWarmupDoesCallWarmupOnOptionalWarmersWhenEnableOptionalWarmersIsEnabled()
{
$warmer = $this->getCacheWarmerMock();
$warmer
->expects($this->never())
->method('isOptional');
$warmer
->expects($this->once())
->method('warmUp');
$aggregate = new CacheWarmerAggregate(array($warmer));
$aggregate->enableOptionalWarmers();
$aggregate->warmUp(self::$cacheDir);
}
public function testWarmupDoesNotCallWarmupOnOptionalWarmersWhenEnableOptionalWarmersIsNotEnabled()
{
$warmer = $this->getCacheWarmerMock();
$warmer
->expects($this->once())
->method('isOptional')
->will($this->returnValue(true));
$warmer
->expects($this->never())
->method('warmUp');
$aggregate = new CacheWarmerAggregate(array($warmer));
$aggregate->warmUp(self::$cacheDir);
}
protected function getCacheWarmerMock()
{
$warmer = $this->getMockBuilder('Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerInterface')
->disableOriginalConstructor()
->getMock();
return $warmer;
}
}

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\CacheWarmer;
use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmer;
class CacheWarmerTest extends \PHPUnit_Framework_TestCase
{
protected static $cacheFile;
public static function setUpBeforeClass()
{
self::$cacheFile = tempnam(sys_get_temp_dir(), 'sf2_cache_warmer_dir');
}
public static function tearDownAfterClass()
{
@unlink(self::$cacheFile);
}
public function testWriteCacheFileCreatesTheFile()
{
$warmer = new TestCacheWarmer(self::$cacheFile);
$warmer->warmUp(dirname(self::$cacheFile));
$this->assertTrue(file_exists(self::$cacheFile));
}
/**
* @expectedException \RuntimeException
*/
public function testWriteNonWritableCacheFileThrowsARuntimeException()
{
$nonWritableFile = '/this/file/is/very/probably/not/writable';
$warmer = new TestCacheWarmer($nonWritableFile);
$warmer->warmUp(dirname($nonWritableFile));
}
}
class TestCacheWarmer extends CacheWarmer
{
protected $file;
public function __construct($file)
{
$this->file = $file;
}
public function warmUp($cacheDir)
{
$this->writeCacheFile($this->file, 'content');
}
public function isOptional()
{
return false;
}
}

View File

@@ -0,0 +1,180 @@
<?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;
use Symfony\Component\HttpKernel\Client;
use Symfony\Component\HttpKernel\HttpKernel;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpKernel\Tests\Fixtures\TestClient;
class ClientTest extends \PHPUnit_Framework_TestCase
{
protected function setUp()
{
if (!class_exists('Symfony\Component\BrowserKit\Client')) {
$this->markTestSkipped('The "BrowserKit" component is not available');
}
}
public function testDoRequest()
{
$client = new Client(new TestHttpKernel());
$client->request('GET', '/');
$this->assertEquals('Request: /', $client->getResponse()->getContent(), '->doRequest() uses the request handler to make the request');
$this->assertInstanceOf('Symfony\Component\BrowserKit\Request', $client->getInternalRequest());
$this->assertInstanceOf('Symfony\Component\HttpFoundation\Request', $client->getRequest());
$this->assertInstanceOf('Symfony\Component\BrowserKit\Response', $client->getInternalResponse());
$this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $client->getResponse());
$client->request('GET', 'http://www.example.com/');
$this->assertEquals('Request: /', $client->getResponse()->getContent(), '->doRequest() uses the request handler to make the request');
$this->assertEquals('www.example.com', $client->getRequest()->getHost(), '->doRequest() uses the request handler to make the request');
$client->request('GET', 'http://www.example.com/?parameter=http://google.com');
$this->assertEquals('http://www.example.com/?parameter='.urlencode('http://google.com'), $client->getRequest()->getUri(), '->doRequest() uses the request handler to make the request');
}
public function testGetScript()
{
if (!class_exists('Symfony\Component\Process\Process')) {
$this->markTestSkipped('The "Process" component is not available');
}
if (!class_exists('Symfony\Component\ClassLoader\ClassLoader')) {
$this->markTestSkipped('The "ClassLoader" component is not available');
}
$client = new TestClient(new TestHttpKernel());
$client->insulate();
$client->request('GET', '/');
$this->assertEquals('Request: /', $client->getResponse()->getContent(), '->getScript() returns a script that uses the request handler to make the request');
}
public function testFilterResponseConvertsCookies()
{
$client = new Client(new TestHttpKernel());
$r = new \ReflectionObject($client);
$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(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->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));
}
public function testFilterResponseSupportsStreamedResponses()
{
$client = new Client(new TestHttpKernel());
$r = new \ReflectionObject($client);
$m = $r->getMethod('filterResponse');
$m->setAccessible(true);
$response = new StreamedResponse(function () {
echo 'foo';
});
$domResponse = $m->invoke($client, $response);
$this->assertEquals('foo', $domResponse->getContent());
}
public function testUploadedFile()
{
$source = tempnam(sys_get_temp_dir(), 'source');
$target = sys_get_temp_dir().'/sf.moved.file';
@unlink($target);
$kernel = new TestHttpKernel();
$client = new Client($kernel);
$files = array(
array('tmp_name' => $source, 'name' => 'original', 'type' => 'mime/original', 'size' => 123, 'error' => UPLOAD_ERR_OK),
new UploadedFile($source, 'original', 'mime/original', 123, UPLOAD_ERR_OK, true),
);
foreach ($files as $file) {
$client->request('POST', '/', array(), array('foo' => $file));
$files = $client->getRequest()->files->all();
$this->assertCount(1, $files);
$file = $files['foo'];
$this->assertEquals('original', $file->getClientOriginalName());
$this->assertEquals('mime/original', $file->getClientMimeType());
$this->assertEquals('123', $file->getClientSize());
$this->assertTrue($file->isValid());
}
$file->move(dirname($target), basename($target));
$this->assertFileExists($target);
unlink($target);
}
public function testUploadedFileWhenSizeExceedsUploadMaxFileSize()
{
$source = tempnam(sys_get_temp_dir(), 'source');
$kernel = new TestHttpKernel();
$client = new Client($kernel);
$file = $this
->getMockBuilder('Symfony\Component\HttpFoundation\File\UploadedFile')
->setConstructorArgs(array($source, 'original', 'mime/original', 123, UPLOAD_ERR_OK, true))
->setMethods(array('getSize'))
->getMock()
;
$file->expects($this->once())
->method('getSize')
->will($this->returnValue(INF))
;
$client->request('POST', '/', array(), array($file));
$files = $client->getRequest()->files->all();
$this->assertCount(1, $files);
$file = $files[0];
$this->assertFalse($file->isValid());
$this->assertEquals(UPLOAD_ERR_INI_SIZE, $file->getError());
$this->assertEquals('mime/original', $file->getClientMimeType());
$this->assertEquals('original', $file->getClientOriginalName());
$this->assertEquals(0, $file->getClientSize());
unlink($source);
}
}

View File

@@ -0,0 +1,47 @@
<?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\Config;
use Symfony\Component\HttpKernel\Config\FileLocator;
class FileLocatorTest extends \PHPUnit_Framework_TestCase
{
public function testLocate()
{
$kernel = $this->getMock('Symfony\Component\HttpKernel\KernelInterface');
$kernel
->expects($this->atLeastOnce())
->method('locateResource')
->with('@BundleName/some/path', null, true)
->will($this->returnValue('/bundle-name/some/path'));
$locator = new FileLocator($kernel);
$this->assertEquals('/bundle-name/some/path', $locator->locate('@BundleName/some/path'));
$kernel
->expects($this->never())
->method('locateResource');
$this->setExpectedException('LogicException');
$locator->locate('/some/path');
}
public function testLocateWithGlobalResourcePath()
{
$kernel = $this->getMock('Symfony\Component\HttpKernel\KernelInterface');
$kernel
->expects($this->atLeastOnce())
->method('locateResource')
->with('@BundleName/some/path', '/global/resource/path', false);
$locator = new FileLocator($kernel, '/global/resource/path');
$locator->locate('@BundleName/some/path', null, false);
}
}

View File

@@ -0,0 +1,190 @@
<?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;
use Symfony\Component\HttpKernel\Controller\ControllerResolver;
use Symfony\Component\HttpFoundation\Request;
class ControllerResolverTest extends \PHPUnit_Framework_TestCase
{
protected function setUp()
{
if (!class_exists('Symfony\Component\HttpFoundation\Request')) {
$this->markTestSkipped('The "HttpFoundation" component is not available');
}
}
public function testGetController()
{
$logger = new Logger();
$resolver = new ControllerResolver($logger);
$request = Request::create('/');
$this->assertFalse($resolver->getController($request), '->getController() returns false when the request has no _controller attribute');
$this->assertEquals(array('Unable to look for the controller as the "_controller" parameter is missing'), $logger->getLogs('warning'));
$request->attributes->set('_controller', 'Symfony\Component\HttpKernel\Tests\ControllerResolverTest::testGetController');
$controller = $resolver->getController($request);
$this->assertInstanceOf('Symfony\Component\HttpKernel\Tests\ControllerResolverTest', $controller[0], '->getController() returns a PHP callable');
$request->attributes->set('_controller', $lambda = function () {});
$controller = $resolver->getController($request);
$this->assertSame($lambda, $controller);
$request->attributes->set('_controller', $this);
$controller = $resolver->getController($request);
$this->assertSame($this, $controller);
$request->attributes->set('_controller', 'Symfony\Component\HttpKernel\Tests\ControllerResolverTest');
$controller = $resolver->getController($request);
$this->assertInstanceOf('Symfony\Component\HttpKernel\Tests\ControllerResolverTest', $controller);
$request->attributes->set('_controller', array($this, 'controllerMethod1'));
$controller = $resolver->getController($request);
$this->assertSame(array($this, 'controllerMethod1'), $controller);
$request->attributes->set('_controller', array('Symfony\Component\HttpKernel\Tests\ControllerResolverTest', 'controllerMethod4'));
$controller = $resolver->getController($request);
$this->assertSame(array('Symfony\Component\HttpKernel\Tests\ControllerResolverTest', 'controllerMethod4'), $controller);
$request->attributes->set('_controller', 'Symfony\Component\HttpKernel\Tests\some_controller_function');
$controller = $resolver->getController($request);
$this->assertSame('Symfony\Component\HttpKernel\Tests\some_controller_function', $controller);
$request->attributes->set('_controller', 'foo');
try {
$resolver->getController($request);
$this->fail('->getController() throws an \InvalidArgumentException if the _controller attribute is not well-formatted');
} catch (\Exception $e) {
$this->assertInstanceOf('\InvalidArgumentException', $e, '->getController() throws an \InvalidArgumentException if the _controller attribute is not well-formatted');
}
$request->attributes->set('_controller', 'foo::bar');
try {
$resolver->getController($request);
$this->fail('->getController() throws an \InvalidArgumentException if the _controller attribute contains a non-existent class');
} catch (\Exception $e) {
$this->assertInstanceOf('\InvalidArgumentException', $e, '->getController() throws an \InvalidArgumentException if the _controller attribute contains a non-existent class');
}
$request->attributes->set('_controller', 'Symfony\Component\HttpKernel\Tests\ControllerResolverTest::bar');
try {
$resolver->getController($request);
$this->fail('->getController() throws an \InvalidArgumentException if the _controller attribute contains a non-existent method');
} catch (\Exception $e) {
$this->assertInstanceOf('\InvalidArgumentException', $e, '->getController() throws an \InvalidArgumentException if the _controller attribute contains a non-existent method');
}
}
public function testGetArguments()
{
$resolver = new ControllerResolver();
$request = Request::create('/');
$controller = array(new self(), 'testGetArguments');
$this->assertEquals(array(), $resolver->getArguments($request, $controller), '->getArguments() returns an empty array if the method takes no arguments');
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$controller = array(new self(), 'controllerMethod1');
$this->assertEquals(array('foo'), $resolver->getArguments($request, $controller), '->getArguments() returns an array of arguments for the controller method');
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$controller = array(new self(), 'controllerMethod2');
$this->assertEquals(array('foo', null), $resolver->getArguments($request, $controller), '->getArguments() uses default values if present');
$request->attributes->set('bar', 'bar');
$this->assertEquals(array('foo', 'bar'), $resolver->getArguments($request, $controller), '->getArguments() overrides default values if provided in the request attributes');
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$controller = function ($foo) {};
$this->assertEquals(array('foo'), $resolver->getArguments($request, $controller));
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$controller = function ($foo, $bar = 'bar') {};
$this->assertEquals(array('foo', 'bar'), $resolver->getArguments($request, $controller));
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$controller = new self();
$this->assertEquals(array('foo', null), $resolver->getArguments($request, $controller));
$request->attributes->set('bar', 'bar');
$this->assertEquals(array('foo', 'bar'), $resolver->getArguments($request, $controller));
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$request->attributes->set('foobar', 'foobar');
$controller = 'Symfony\Component\HttpKernel\Tests\some_controller_function';
$this->assertEquals(array('foo', 'foobar'), $resolver->getArguments($request, $controller));
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$request->attributes->set('foobar', 'foobar');
$controller = array(new self(), 'controllerMethod3');
if (version_compare(PHP_VERSION, '5.3.16', '==')) {
$this->markTestSkipped('PHP 5.3.16 has a major bug in the Reflection sub-system');
} else {
try {
$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');
}
}
$request = Request::create('/');
$controller = array(new self(), 'controllerMethod5');
$this->assertEquals(array($request), $resolver->getArguments($request, $controller), '->getArguments() injects the request');
}
public function testCreateControllerCanReturnAnyCallable()
{
$mock = $this->getMock('Symfony\Component\HttpKernel\Controller\ControllerResolver', array('createController'));
$mock->expects($this->once())->method('createController')->will($this->returnValue('Symfony\Component\HttpKernel\Tests\some_controller_function'));
$request = Request::create('/');
$request->attributes->set('_controller', 'foobar');
$mock->getController($request);
}
public function __invoke($foo, $bar = null)
{
}
protected function controllerMethod1($foo)
{
}
protected function controllerMethod2($foo, $bar = null)
{
}
protected function controllerMethod3($foo, $bar = null, $foobar)
{
}
protected static function controllerMethod4()
{
}
protected function controllerMethod5(Request $request)
{
}
}
function some_controller_function($foo, $foobar)
{
}

View File

@@ -0,0 +1,91 @@
<?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 Symfony\Component\HttpKernel\DataCollector\ConfigDataCollector;
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class ConfigDataCollectorTest extends \PHPUnit_Framework_TestCase
{
protected function setUp()
{
if (!class_exists('Symfony\Component\HttpFoundation\Request')) {
$this->markTestSkipped('The "HttpFoundation" component is not available');
}
}
public function testCollect()
{
$kernel = new KernelForTest('test', true);
$c = new ConfigDataCollector();
$c->setKernel($kernel);
$c->collect(new Request(), new Response());
$this->assertSame('test',$c->getEnv());
$this->assertTrue($c->isDebug());
$this->assertSame('config',$c->getName());
$this->assertSame('testkernel',$c->getAppName());
$this->assertSame(PHP_VERSION,$c->getPhpVersion());
$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());
}
}
}
class KernelForTest extends Kernel
{
public function getName()
{
return 'testkernel';
}
public function registerBundles()
{
}
public function init()
{
}
public function getBundles()
{
return array();
}
public function registerContainerConfiguration(LoaderInterface $loader)
{
}
}

View File

@@ -0,0 +1,47 @@
<?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 Symfony\Component\HttpKernel\DataCollector\ExceptionDataCollector;
use Symfony\Component\HttpKernel\Exception\FlattenException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class ExceptionDataCollectorTest extends \PHPUnit_Framework_TestCase
{
protected function setUp()
{
if (!class_exists('Symfony\Component\HttpFoundation\Request')) {
$this->markTestSkipped('The "HttpFoundation" component is not available');
}
}
public function testCollect()
{
$e = new \Exception('foo',500);
$c = new ExceptionDataCollector();
$flattened = FlattenException::create($e);
$trace = $flattened->getTrace();
$this->assertFalse($c->hasException());
$c->collect(new Request(), new Response(),$e);
$this->assertTrue($c->hasException());
$this->assertEquals($flattened,$c->getException());
$this->assertSame('foo',$c->getMessage());
$this->assertSame(500,$c->getCode());
$this->assertSame('exception',$c->getName());
$this->assertSame($trace,$c->getTrace());
}
}

View File

@@ -0,0 +1,78 @@
<?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 Symfony\Component\HttpKernel\DataCollector\LoggerDataCollector;
use Symfony\Component\HttpKernel\Debug\ErrorHandler;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class LoggerDataCollectorTest extends \PHPUnit_Framework_TestCase
{
protected function setUp()
{
if (!class_exists('Symfony\Component\HttpFoundation\Request')) {
$this->markTestSkipped('The "HttpFoundation" component is not available');
}
}
/**
* @dataProvider getCollectTestData
*/
public function testCollect($nb, $logs, $expectedLogs, $expectedDeprecationCount)
{
$logger = $this->getMock('Symfony\Component\HttpKernel\Log\DebugLoggerInterface');
$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->collect(new Request(), new Response());
$this->assertSame('logger', $c->getName());
$this->assertSame($nb, $c->countErrors());
$this->assertSame($expectedLogs ? $expectedLogs : $logs, $c->getLogs());
$this->assertSame($expectedDeprecationCount, $c->countDeprecations());
}
public function getCollectTestData()
{
return array(
array(
1,
array(array('message' => 'foo', 'context' => array())),
null,
0
),
array(
1,
array(array('message' => 'foo', 'context' => array('foo' => fopen(__FILE__, 'r')))),
array(array('message' => 'foo', 'context' => array('foo' => 'Resource(stream)'))),
0
),
array(
1,
array(array('message' => 'foo', 'context' => array('foo' => new \stdClass()))),
array(array('message' => 'foo', 'context' => array('foo' => 'Object(stdClass)'))),
0
),
array(
1,
array(
array('message' => 'foo', 'context' => array('type' => ErrorHandler::TYPE_DEPRECATION)),
array('message' => 'foo2', 'context' => array('type' => ErrorHandler::TYPE_DEPRECATION))
),
null,
2
),
);
}
}

View File

@@ -0,0 +1,64 @@
<?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 Symfony\Component\HttpKernel\DataCollector\MemoryDataCollector;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class MemoryDataCollectorTest extends \PHPUnit_Framework_TestCase
{
protected function setUp()
{
if (!class_exists('Symfony\Component\HttpFoundation\Request')) {
$this->markTestSkipped('The "HttpFoundation" component is not available');
}
}
public function testCollect()
{
$collector = new MemoryDataCollector();
$collector->collect(new Request(), new Response());
$this->assertInternalType('integer', $collector->getMemory());
$this->assertInternalType('integer', $collector->getMemoryLimit());
$this->assertSame('memory', $collector->getName());
}
/** @dataProvider getBytesConversionTestData */
public function testBytesConversion($limit, $bytes)
{
$collector = new MemoryDataCollector();
$method = new \ReflectionMethod($collector, 'convertToBytes');
$method->setAccessible(true);
$this->assertEquals($bytes, $method->invoke($collector, $limit));
}
public function getBytesConversionTestData()
{
return array(
array('2k', 2048),
array('2 k', 2048),
array('8m', 8 * 1024 * 1024),
array('+2 k', 2048),
array('+2???k', 2048),
array('0x10', 16),
array('0xf', 15),
array('010', 8),
array('+0x10 k', 16 * 1024),
array('1g', 1024 * 1024 * 1024),
array('-1', -1),
array('0', 0),
array('2mk', 2048), // the unit must be the last char, so in this case 'k', not 'm'
);
}
}

View File

@@ -0,0 +1,208 @@
<?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 Symfony\Component\HttpKernel\HttpKernel;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\DataCollector\RequestDataCollector;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\EventDispatcher\EventDispatcher;
class RequestDataCollectorTest extends \PHPUnit_Framework_TestCase
{
protected function setUp()
{
if (!class_exists('Symfony\Component\HttpFoundation\Request')) {
$this->markTestSkipped('The "HttpFoundation" component is not available');
}
}
/**
* @dataProvider provider
*/
public function testCollect(Request $request, Response $response)
{
$c = new RequestDataCollector();
$c->collect($request, $response);
$this->assertSame('request',$c->getName());
$this->assertInstanceOf('Symfony\Component\HttpFoundation\HeaderBag',$c->getRequestHeaders());
$this->assertInstanceOf('Symfony\Component\HttpFoundation\ParameterBag',$c->getRequestServer());
$this->assertInstanceOf('Symfony\Component\HttpFoundation\ParameterBag',$c->getRequestCookies());
$this->assertInstanceOf('Symfony\Component\HttpFoundation\ParameterBag',$c->getRequestAttributes());
$this->assertInstanceOf('Symfony\Component\HttpFoundation\ParameterBag',$c->getRequestRequest());
$this->assertInstanceOf('Symfony\Component\HttpFoundation\ParameterBag',$c->getRequestQuery());
$this->assertEquals('html',$c->getFormat());
$this->assertEquals(array(),$c->getSessionAttributes());
$this->assertEquals('en',$c->getLocale());
$this->assertInstanceOf('Symfony\Component\HttpFoundation\HeaderBag',$c->getResponseHeaders());
$this->assertEquals('OK',$c->getStatusText());
$this->assertEquals(200,$c->getStatusCode());
$this->assertEquals('application/json',$c->getContentType());
}
/**
* Test various types of controller callables.
*
* @dataProvider provider
*/
public function testControllerInspection(Request $request, Response $response)
{
// make sure we always match the line number
$r1 = new \ReflectionMethod($this, 'testControllerInspection');
$r2 = new \ReflectionMethod($this, 'staticControllerMethod');
// test name, callable, expected
$controllerTests = array(
array(
'"Regular" callable',
array($this, 'testControllerInspection'),
array(
'class' => 'Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest',
'method' => 'testControllerInspection',
'file' => __FILE__,
'line' => $r1->getStartLine()
),
),
array(
'Closure',
function() { return 'foo'; },
array(
'class' => __NAMESPACE__.'\{closure}',
'method' => null,
'file' => __FILE__,
'line' => __LINE__ - 5,
),
),
array(
'Static callback as string',
'Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest::staticControllerMethod',
'Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest::staticControllerMethod',
),
array(
'Static callable with instance',
array($this, 'staticControllerMethod'),
array(
'class' => 'Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest',
'method' => 'staticControllerMethod',
'file' => __FILE__,
'line' => $r2->getStartLine()
),
),
array(
'Static callable with class name',
array('Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest', 'staticControllerMethod'),
array(
'class' => 'Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest',
'method' => 'staticControllerMethod',
'file' => __FILE__,
'line' => $r2->getStartLine()
),
),
array(
'Callable with instance depending on __call()',
array($this, 'magicMethod'),
array(
'class' => 'Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest',
'method' => 'magicMethod',
'file' => 'n/a',
'line' => 'n/a'
),
),
array(
'Callable with class name depending on __callStatic()',
array('Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest', 'magicMethod'),
array(
'class' => 'Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest',
'method' => 'magicMethod',
'file' => 'n/a',
'line' => 'n/a'
),
),
);
$c = new RequestDataCollector();
foreach ($controllerTests as $controllerTest) {
$this->injectController($c, $controllerTest[1], $request);
$c->collect($request, $response);
$this->assertEquals($controllerTest[2], $c->getController(), sprintf('Testing: %s', $controllerTest[0]));
}
}
public function provider()
{
if (!class_exists('Symfony\Component\HttpFoundation\Request')) {
return array(array(null, null));
}
$request = Request::create('http://test.com/foo?bar=baz');
$request->attributes->set('foo', 'bar');
$response = new Response();
$response->setStatusCode(200);
$response->headers->set('Content-Type', 'application/json');
$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'));
return array(
array($request, $response)
);
}
/**
* Inject the given controller callable into the data collector.
*/
protected function injectController($collector, $controller, $request)
{
$resolver = $this->getMock('Symfony\\Component\\HttpKernel\\Controller\\ControllerResolverInterface');
$httpKernel = new HttpKernel(new EventDispatcher(), $resolver);
$event = new FilterControllerEvent($httpKernel, $controller, $request, HttpKernelInterface::MASTER_REQUEST);
$collector->onKernelController($event);
}
/**
* Dummy method used as controller callable
*/
public static function staticControllerMethod()
{
throw new \LogicException('Unexpected method call');
}
/**
* Magic method to allow non existing methods to be called and delegated.
*/
public function __call($method, $args)
{
throw new \LogicException('Unexpected method call');
}
/**
* Magic method to allow non existing methods to be called and delegated.
*/
public static function __callStatic($method, $args)
{
throw new \LogicException('Unexpected method call');
}
}

View File

@@ -0,0 +1,58 @@
<?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 Symfony\Component\HttpKernel\DataCollector\TimeDataCollector;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class TimeDataCollectorTest extends \PHPUnit_Framework_TestCase
{
protected function setUp()
{
if (!class_exists('Symfony\Component\HttpFoundation\Request')) {
$this->markTestSkipped('The "HttpFoundation" component is not available');
}
}
public function testCollect()
{
$c = new TimeDataCollector;
$request = new Request();
$request->server->set('REQUEST_TIME', 1);
$c->collect($request, new Response());
$this->assertEquals(1000, $c->getStartTime());
$request->server->set('REQUEST_TIME_FLOAT', 2);
$c->collect($request, new Response());
$this->assertEquals(2000, $c->getStartTime());
$request = new Request();
$c->collect($request, new Response);
$this->assertEquals(0, $c->getStartTime());
$kernel = $this->getMock('Symfony\Component\HttpKernel\KernelInterface');
$kernel->expects($this->once())->method('getStartTime')->will($this->returnValue(123456));
$c = new TimeDataCollector($kernel);
$request = new Request();
$request->server->set('REQUEST_TIME', 1);
$c->collect($request, new Response());
$this->assertEquals(123456000, $c->getStartTime());
}
}

View File

@@ -0,0 +1,237 @@
<?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 Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\EventDispatcher\Event;
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
{
protected function setUp()
{
if (!class_exists('Symfony\Component\EventDispatcher\EventDispatcher')) {
$this->markTestSkipped('The "EventDispatcher" component is not available');
}
if (!class_exists('Symfony\Component\HttpFoundation\Request')) {
$this->markTestSkipped('The "HttpFoundation" component is not available');
}
}
public function testAddRemoveListener()
{
$dispatcher = new EventDispatcher();
$tdispatcher = new TraceableEventDispatcher($dispatcher, new Stopwatch());
$tdispatcher->addListener('foo', $listener = function () { ; });
$listeners = $dispatcher->getListeners('foo');
$this->assertCount(1, $listeners);
$this->assertSame($listener, $listeners[0]);
$tdispatcher->removeListener('foo', $listener);
$this->assertCount(0, $dispatcher->getListeners('foo'));
}
public function testGetListeners()
{
$dispatcher = new EventDispatcher();
$tdispatcher = new TraceableEventDispatcher($dispatcher, new Stopwatch());
$tdispatcher->addListener('foo', $listener = function () { ; });
$this->assertSame($dispatcher->getListeners('foo'), $tdispatcher->getListeners('foo'));
}
public function testHasListeners()
{
$dispatcher = new EventDispatcher();
$tdispatcher = new TraceableEventDispatcher($dispatcher, new Stopwatch());
$this->assertFalse($dispatcher->hasListeners('foo'));
$this->assertFalse($tdispatcher->hasListeners('foo'));
$tdispatcher->addListener('foo', $listener = function () { ; });
$this->assertTrue($dispatcher->hasListeners('foo'));
$this->assertTrue($tdispatcher->hasListeners('foo'));
}
public function testAddRemoveSubscriber()
{
$dispatcher = new EventDispatcher();
$tdispatcher = new TraceableEventDispatcher($dispatcher, new Stopwatch());
$subscriber = new EventSubscriber();
$tdispatcher->addSubscriber($subscriber);
$listeners = $dispatcher->getListeners('foo');
$this->assertCount(1, $listeners);
$this->assertSame(array($subscriber, 'call'), $listeners[0]);
$tdispatcher->removeSubscriber($subscriber);
$this->assertCount(0, $dispatcher->getListeners('foo'));
}
public function testGetCalledListeners()
{
$dispatcher = new EventDispatcher();
$tdispatcher = new TraceableEventDispatcher($dispatcher, new Stopwatch());
$tdispatcher->addListener('foo', $listener = function () { ; });
$this->assertEquals(array(), $tdispatcher->getCalledListeners());
$this->assertEquals(array('foo.closure' => array('event' => 'foo', 'type' => 'Closure', 'pretty' => 'closure')), $tdispatcher->getNotCalledListeners());
$tdispatcher->dispatch('foo');
$this->assertEquals(array('foo.closure' => array('event' => 'foo', 'type' => 'Closure', 'pretty' => 'closure')), $tdispatcher->getCalledListeners());
$this->assertEquals(array(), $tdispatcher->getNotCalledListeners());
}
public function testLogger()
{
$logger = $this->getMock('Psr\Log\LoggerInterface');
$dispatcher = new EventDispatcher();
$tdispatcher = new TraceableEventDispatcher($dispatcher, new Stopwatch(), $logger);
$tdispatcher->addListener('foo', $listener1 = function () { ; });
$tdispatcher->addListener('foo', $listener2 = function () { ; });
$logger->expects($this->at(0))->method('debug')->with("Notified event \"foo\" to listener \"closure\".");
$logger->expects($this->at(1))->method('debug')->with("Notified event \"foo\" to listener \"closure\".");
$tdispatcher->dispatch('foo');
}
public function testLoggerWithStoppedEvent()
{
$logger = $this->getMock('Psr\Log\LoggerInterface');
$dispatcher = new EventDispatcher();
$tdispatcher = new TraceableEventDispatcher($dispatcher, new Stopwatch(), $logger);
$tdispatcher->addListener('foo', $listener1 = function (Event $event) { $event->stopPropagation(); });
$tdispatcher->addListener('foo', $listener2 = function () { ; });
$logger->expects($this->at(0))->method('debug')->with("Notified event \"foo\" to listener \"closure\".");
$logger->expects($this->at(1))->method('debug')->with("Listener \"closure\" stopped propagation of the event \"foo\".");
$logger->expects($this->at(2))->method('debug')->with("Listener \"closure\" was not called for event \"foo\".");
$tdispatcher->dispatch('foo');
}
public function testDispatchCallListeners()
{
$called = array();
$dispatcher = new EventDispatcher();
$tdispatcher = new TraceableEventDispatcher($dispatcher, new Stopwatch());
$tdispatcher->addListener('foo', $listener1 = function () use (&$called) { $called[] = 'foo1'; });
$tdispatcher->addListener('foo', $listener2 = function () use (&$called) { $called[] = 'foo2'; });
$tdispatcher->dispatch('foo');
$this->assertEquals(array('foo1', 'foo2'), $called);
}
public function testDispatchNested()
{
$dispatcher = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch());
$loop = 1;
$dispatcher->addListener('foo', $listener1 = function () use ($dispatcher, &$loop) {
++$loop;
if (2 == $loop) {
$dispatcher->dispatch('foo');
}
});
$dispatcher->dispatch('foo');
}
public function testStopwatchSections()
{
$dispatcher = new TraceableEventDispatcher(new EventDispatcher(), $stopwatch = new Stopwatch());
$kernel = $this->getHttpKernel($dispatcher, function () { return new Response(); });
$request = Request::create('/');
$response = $kernel->handle($request);
$kernel->terminate($request, $response);
$events = $stopwatch->getSectionEvents($response->headers->get('X-Debug-Token'));
$this->assertEquals(array(
'__section__',
'kernel.request',
'kernel.request.loading',
'kernel.controller',
'kernel.controller.loading',
'controller',
'kernel.response',
'kernel.response.loading',
'kernel.terminate',
'kernel.terminate.loading',
), array_keys($events));
}
public function testStopwatchCheckControllerOnRequestEvent()
{
$stopwatch = $this->getMockBuilder('Symfony\Component\Stopwatch\Stopwatch')
->setMethods(array('isStarted'))
->getMock();
$stopwatch->expects($this->once())
->method('isStarted')
->will($this->returnValue(false));
$dispatcher = new TraceableEventDispatcher(new EventDispatcher(), $stopwatch);
$kernel = $this->getHttpKernel($dispatcher, function () { return new Response(); });
$request = Request::create('/');
$kernel->handle($request);
}
public function testStopwatchStopControllerOnRequestEvent()
{
$stopwatch = $this->getMockBuilder('Symfony\Component\Stopwatch\Stopwatch')
->setMethods(array('isStarted', 'stop', 'stopSection'))
->getMock();
$stopwatch->expects($this->once())
->method('isStarted')
->will($this->returnValue(true));
$stopwatch->expects($this->once())
->method('stop');
$stopwatch->expects($this->once())
->method('stopSection');
$dispatcher = new TraceableEventDispatcher(new EventDispatcher(), $stopwatch);
$kernel = $this->getHttpKernel($dispatcher, function () { return new Response(); });
$request = Request::create('/');
$kernel->handle($request);
}
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()));
return new HttpKernel($dispatcher, $resolver);
}
}
class EventSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return array('foo' => 'call');
}
}

View File

@@ -0,0 +1,169 @@
<?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 Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\DependencyInjection\ContainerAwareHttpKernel;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\EventDispatcher\EventDispatcher;
class ContainerAwareHttpKernelTest extends \PHPUnit_Framework_TestCase
{
protected function setUp()
{
if (!class_exists('Symfony\Component\DependencyInjection\Container')) {
$this->markTestSkipped('The "DependencyInjection" component is not available');
}
if (!class_exists('Symfony\Component\EventDispatcher\EventDispatcher')) {
$this->markTestSkipped('The "EventDispatcher" component is not available');
}
if (!class_exists('Symfony\Component\HttpFoundation\Request')) {
$this->markTestSkipped('The "HttpFoundation" component is not available');
}
}
/**
* @dataProvider getProviderTypes
*/
public function testHandle($type)
{
$request = new Request();
$expected = new Response();
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container
->expects($this->once())
->method('enterScope')
->with($this->equalTo('request'))
;
$container
->expects($this->once())
->method('leaveScope')
->with($this->equalTo('request'))
;
$container
->expects($this->at(0))
->method('hasScope')
->with($this->equalTo('request'))
->will($this->returnValue(false));
$container
->expects($this->at(1))
->method('addScope')
->with($this->isInstanceOf('Symfony\Component\DependencyInjection\Scope'));
// enterScope()
$container
->expects($this->at(3))
->method('set')
->with($this->equalTo('request'), $this->equalTo($request), $this->equalTo('request'))
;
$container
->expects($this->at(4))
->method('set')
->with($this->equalTo('request'), $this->equalTo(null), $this->equalTo('request'))
;
$dispatcher = new EventDispatcher();
$resolver = $this->getMock('Symfony\\Component\\HttpKernel\\Controller\\ControllerResolverInterface');
$kernel = new ContainerAwareHttpKernel($dispatcher, $container, $resolver);
$controller = function() use ($expected) {
return $expected;
};
$resolver->expects($this->once())
->method('getController')
->with($request)
->will($this->returnValue($controller));
$resolver->expects($this->once())
->method('getArguments')
->with($request, $controller)
->will($this->returnValue(array()));
$actual = $kernel->handle($request, $type);
$this->assertSame($expected, $actual, '->handle() returns the response');
}
/**
* @dataProvider getProviderTypes
*/
public function testHandleRestoresThePreviousRequestOnException($type)
{
$request = new Request();
$expected = new \Exception();
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container
->expects($this->once())
->method('enterScope')
->with($this->equalTo('request'))
;
$container
->expects($this->once())
->method('leaveScope')
->with($this->equalTo('request'))
;
$container
->expects($this->at(0))
->method('hasScope')
->with($this->equalTo('request'))
->will($this->returnValue(true));
// enterScope()
$container
->expects($this->at(2))
->method('set')
->with($this->equalTo('request'), $this->equalTo($request), $this->equalTo('request'))
;
$container
->expects($this->at(3))
->method('set')
->with($this->equalTo('request'), $this->equalTo(null), $this->equalTo('request'))
;
$dispatcher = new EventDispatcher();
$resolver = $this->getMock('Symfony\\Component\\HttpKernel\\Controller\\ControllerResolverInterface');
$kernel = new ContainerAwareHttpKernel($dispatcher, $container, $resolver);
$controller = function() use ($expected) {
throw $expected;
};
$resolver->expects($this->once())
->method('getController')
->with($request)
->will($this->returnValue($controller));
$resolver->expects($this->once())
->method('getArguments')
->with($request, $controller)
->will($this->returnValue(array()));
try {
$kernel->handle($request, $type);
$this->fail('->handle() suppresses the controller exception');
} catch (\PHPUnit_Framework_Exception $exception) {
throw $exception;
} catch (\Exception $actual) {
$this->assertSame($expected, $actual, '->handle() throws the controller exception');
}
}
public function getProviderTypes()
{
return array(
array(HttpKernelInterface::MASTER_REQUEST),
array(HttpKernelInterface::SUB_REQUEST),
);
}
}

View File

@@ -0,0 +1,65 @@
<?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;
use Symfony\Component\HttpKernel\DependencyInjection\MergeExtensionConfigurationPass;
class MergeExtensionConfigurationPassTest extends \PHPUnit_Framework_TestCase
{
protected function setUp()
{
if (!class_exists('Symfony\Component\DependencyInjection\Container')) {
$this->markTestSkipped('The "DependencyInjection" component is not available');
}
if (!class_exists('Symfony\Component\Config\FileLocator')) {
$this->markTestSkipped('The "Config" component is not available');
}
}
public function testAutoloadMainExtension()
{
$container = $this->getMock('Symfony\\Component\\DependencyInjection\\ContainerBuilder');
$params = $this->getMock('Symfony\\Component\\DependencyInjection\\ParameterBag\\ParameterBag');
$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->process($container);
}
}

View File

@@ -0,0 +1,89 @@
<?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 Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\HttpKernel\DependencyInjection\RegisterListenersPass;
class RegisterListenersPassTest extends \PHPUnit_Framework_TestCase
{
/**
* Tests that event subscribers not implementing EventSubscriberInterface
* trigger an exception.
*
* @expectedException \InvalidArgumentException
*/
public function testEventSubscriberWithoutInterface()
{
// one service, not implementing any interface
$services = array(
'my_event_subscriber' => array(0 => array()),
);
$definition = $this->getMock('Symfony\Component\DependencyInjection\Definition');
$definition->expects($this->atLeastOnce())
->method('getClass')
->will($this->returnValue('stdClass'));
$builder = $this->getMock('Symfony\Component\DependencyInjection\ContainerBuilder');
$builder->expects($this->any())
->method('hasDefinition')
->will($this->returnValue(true));
// We don't test kernel.event_listener here
$builder->expects($this->atLeastOnce())
->method('findTaggedServiceIds')
->will($this->onConsecutiveCalls(array(), $services));
$builder->expects($this->atLeastOnce())
->method('getDefinition')
->will($this->returnValue($definition));
$registerListenersPass = new RegisterListenersPass();
$registerListenersPass->process($builder);
}
public function testValidEventSubscriber()
{
$services = array(
'my_event_subscriber' => array(0 => array()),
);
$definition = $this->getMock('Symfony\Component\DependencyInjection\Definition');
$definition->expects($this->atLeastOnce())
->method('getClass')
->will($this->returnValue('Symfony\Component\HttpKernel\Tests\DependencyInjection\SubscriberService'));
$builder = $this->getMock('Symfony\Component\DependencyInjection\ContainerBuilder');
$builder->expects($this->any())
->method('hasDefinition')
->will($this->returnValue(true));
// We don't test kernel.event_listener here
$builder->expects($this->atLeastOnce())
->method('findTaggedServiceIds')
->will($this->onConsecutiveCalls(array(), $services));
$builder->expects($this->atLeastOnce())
->method('getDefinition')
->will($this->returnValue($definition));
$registerListenersPass = new RegisterListenersPass();
$registerListenersPass->process($builder);
}
}
class SubscriberService implements \Symfony\Component\EventDispatcher\EventSubscriberInterface
{
public static function getSubscribedEvents() {}
}

View File

@@ -0,0 +1,73 @@
<?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 Symfony\Component\HttpKernel\HttpCache\Esi;
use Symfony\Component\HttpKernel\EventListener\EsiListener;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\EventDispatcher\EventDispatcher;
class EsiListenerTest extends \PHPUnit_Framework_TestCase
{
protected function setUp()
{
if (!class_exists('Symfony\Component\EventDispatcher\EventDispatcher')) {
$this->markTestSkipped('The "EventDispatcher" component is not available');
}
}
public function testFilterDoesNothingForSubRequests()
{
$dispatcher = new EventDispatcher();
$kernel = $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface');
$response = new Response('foo <esi:include src="" />');
$listener = new EsiListener(new Esi());
$dispatcher->addListener(KernelEvents::RESPONSE, array($listener, 'onKernelResponse'));
$event = new FilterResponseEvent($kernel, new Request(), HttpKernelInterface::SUB_REQUEST, $response);
$dispatcher->dispatch(KernelEvents::RESPONSE, $event);
$this->assertEquals('', $event->getResponse()->headers->get('Surrogate-Control'));
}
public function testFilterWhenThereIsSomeEsiIncludes()
{
$dispatcher = new EventDispatcher();
$kernel = $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface');
$response = new Response('foo <esi:include src="" />');
$listener = new EsiListener(new Esi());
$dispatcher->addListener(KernelEvents::RESPONSE, array($listener, 'onKernelResponse'));
$event = new FilterResponseEvent($kernel, new Request(), HttpKernelInterface::MASTER_REQUEST, $response);
$dispatcher->dispatch(KernelEvents::RESPONSE, $event);
$this->assertEquals('content="ESI/1.0"', $event->getResponse()->headers->get('Surrogate-Control'));
}
public function testFilterWhenThereIsNoEsiIncludes()
{
$dispatcher = new EventDispatcher();
$kernel = $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface');
$response = new Response('foo');
$listener = new EsiListener(new Esi());
$dispatcher->addListener(KernelEvents::RESPONSE, array($listener, 'onKernelResponse'));
$event = new FilterResponseEvent($kernel, new Request(), HttpKernelInterface::MASTER_REQUEST, $response);
$dispatcher->dispatch(KernelEvents::RESPONSE, $event);
$this->assertEquals('', $event->getResponse()->headers->get('Surrogate-Control'));
}
}

View File

@@ -0,0 +1,157 @@
<?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 Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\EventListener\ExceptionListener;
use Symfony\Component\HttpKernel\Log\DebugLoggerInterface;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Tests\Logger;
/**
* ExceptionListenerTest
*
* @author Robert Schönthal <seroscho@googlemail.com>
*/
class ExceptionListenerTest extends \PHPUnit_Framework_TestCase
{
protected function setUp()
{
if (!class_exists('Symfony\Component\EventDispatcher\EventDispatcher')) {
$this->markTestSkipped('The "EventDispatcher" component is not available');
}
if (!class_exists('Symfony\Component\HttpFoundation\Request')) {
$this->markTestSkipped('The "HttpFoundation" component is not available');
}
}
public function testConstruct()
{
$logger = new TestLogger();
$l = new ExceptionListener('foo', $logger);
$_logger = new \ReflectionProperty(get_class($l), 'logger');
$_logger->setAccessible(true);
$_controller = new \ReflectionProperty(get_class($l), 'controller');
$_controller->setAccessible(true);
$this->assertSame($logger, $_logger->getValue($l));
$this->assertSame('foo', $_controller->getValue($l));
}
/**
* @dataProvider provider
*/
public function testHandleWithoutLogger($event, $event2)
{
// store the current error_log, and disable it temporarily
$errorLog = ini_set('error_log', file_exists('/dev/null') ? '/dev/null' : 'nul');
$l = new ExceptionListener('foo');
$l->onKernelException($event);
$this->assertEquals(new Response('foo'), $event->getResponse());
try {
$l->onKernelException($event2);
} catch (\Exception $e) {
$this->assertSame('foo', $e->getMessage());
}
// restore the old error_log
ini_set('error_log', $errorLog);
}
/**
* @dataProvider provider
*/
public function testHandleWithLogger($event, $event2)
{
$logger = new TestLogger();
$l = new ExceptionListener('foo', $logger);
$l->onKernelException($event);
$this->assertEquals(new Response('foo'), $event->getResponse());
try {
$l->onKernelException($event2);
} catch (\Exception $e) {
$this->assertSame('foo', $e->getMessage());
}
$this->assertEquals(3, $logger->countErrors());
$this->assertCount(3, $logger->getLogs('critical'));
}
public function provider()
{
if (!class_exists('Symfony\Component\HttpFoundation\Request')) {
return array(array(null, null));
}
$request = new Request();
$exception = new \Exception('foo');
$event = new GetResponseForExceptionEvent(new TestKernel(), $request, 'foo', $exception);
$event2 = new GetResponseForExceptionEvent(new TestKernelThatThrowsException(), $request, 'foo', $exception);
return array(
array($event, $event2)
);
}
public function testSubRequestFormat()
{
$listener = new ExceptionListener('foo', $this->getMock('Psr\Log\LoggerInterface'));
$kernel = $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface');
$kernel->expects($this->once())->method('handle')->will($this->returnCallback(function (Request $request) {
return new Response($request->getRequestFormat());
}));
$request = Request::create('/');
$request->setRequestFormat('xml');
$event = new GetResponseForExceptionEvent($kernel, $request, 'foo', new \Exception('foo'));
$listener->onKernelException($event);
$response = $event->getResponse();
$this->assertEquals('xml', $response->getContent());
}
}
class TestLogger extends Logger implements DebugLoggerInterface
{
public function countErrors()
{
return count($this->logs['critical']);
}
}
class TestKernel implements HttpKernelInterface
{
public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = true)
{
return new Response('foo');
}
}
class TestKernelThatThrowsException implements HttpKernelInterface
{
public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = true)
{
throw new \Exception('bar');
}
}

View File

@@ -0,0 +1,101 @@
<?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 Symfony\Component\HttpKernel\EventListener\FragmentListener;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\UriSigner;
class FragmentListenerTest extends \PHPUnit_Framework_TestCase
{
protected function setUp()
{
if (!class_exists('Symfony\Component\EventDispatcher\EventDispatcher')) {
$this->markTestSkipped('The "EventDispatcher" component is not available');
}
}
public function testOnlyTriggeredOnFragmentRoute()
{
$request = Request::create('http://example.com/foo?_path=foo%3Dbar%26_controller%3Dfoo');
$listener = new FragmentListener(new UriSigner('foo'));
$event = $this->createGetResponseEvent($request);
$expected = $request->attributes->all();
$listener->onKernelRequest($event);
$this->assertEquals($expected, $request->attributes->all());
$this->assertTrue($request->query->has('_path'));
}
/**
* @expectedException \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
*/
public function testAccessDeniedWithNonSafeMethods()
{
$request = Request::create('http://example.com/_fragment', 'POST');
$listener = new FragmentListener(new UriSigner('foo'));
$event = $this->createGetResponseEvent($request);
$listener->onKernelRequest($event);
}
/**
* @expectedException \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
*/
public function testAccessDeniedWithNonLocalIps()
{
$request = Request::create('http://example.com/_fragment', 'GET', array(), array(), array(), array('REMOTE_ADDR' => '10.0.0.1'));
$listener = new FragmentListener(new UriSigner('foo'));
$event = $this->createGetResponseEvent($request);
$listener->onKernelRequest($event);
}
/**
* @expectedException \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
*/
public function testAccessDeniedWithWrongSignature()
{
$request = Request::create('http://example.com/_fragment', 'GET', array(), array(), array(), array('REMOTE_ADDR' => '10.0.0.1'));
$listener = new FragmentListener(new UriSigner('foo'));
$event = $this->createGetResponseEvent($request);
$listener->onKernelRequest($event);
}
public function testWithSignature()
{
$signer = new UriSigner('foo');
$request = Request::create($signer->sign('http://example.com/_fragment?_path=foo%3Dbar%26_controller%3Dfoo'), 'GET', array(), array(), array(), array('REMOTE_ADDR' => '10.0.0.1'));
$listener = new FragmentListener($signer);
$event = $this->createGetResponseEvent($request);
$listener->onKernelRequest($event);
$this->assertEquals(array('foo' => 'bar', '_controller' => 'foo'), $request->attributes->get('_route_params'));
$this->assertFalse($request->query->has('_path'));
}
private function createGetResponseEvent(Request $request)
{
return new GetResponseEvent($this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface'), $request, HttpKernelInterface::MASTER_REQUEST);
}
}

View File

@@ -0,0 +1,86 @@
<?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 Symfony\Component\HttpKernel\EventListener\LocaleListener;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
class LocaleListenerTest extends \PHPUnit_Framework_TestCase
{
protected function setUp()
{
if (!class_exists('Symfony\Component\EventDispatcher\EventDispatcher')) {
$this->markTestSkipped('The "EventDispatcher" component is not available');
}
}
public function testDefaultLocaleWithoutSession()
{
$listener = new LocaleListener('fr');
$event = $this->getEvent($request = Request::create('/'));
$listener->onKernelRequest($event);
$this->assertEquals('fr', $request->getLocale());
}
public function testLocaleFromRequestAttribute()
{
$request = Request::create('/');
session_name('foo');
$request->cookies->set('foo', 'value');
$request->attributes->set('_locale', 'es');
$listener = new LocaleListener('fr');
$event = $this->getEvent($request);
$listener->onKernelRequest($event);
$this->assertEquals('es', $request->getLocale());
}
public function testLocaleSetForRoutingContext()
{
if (!class_exists('Symfony\Component\Routing\Router')) {
$this->markTestSkipped('The "Routing" component is not available');
}
// the request context is updated
$context = $this->getMock('Symfony\Component\Routing\RequestContext');
$context->expects($this->once())->method('setParameter')->with('_locale', 'es');
$router = $this->getMock('Symfony\Component\Routing\Router', array('getContext'), array(), '', false);
$router->expects($this->once())->method('getContext')->will($this->returnValue($context));
$request = Request::create('/');
$request->attributes->set('_locale', 'es');
$listener = new LocaleListener('fr', $router);
$listener->onKernelRequest($this->getEvent($request));
}
public function testRequestLocaleIsNotOverridden()
{
$request = Request::create('/');
$request->setLocale('de');
$listener = new LocaleListener('fr');
$event = $this->getEvent($request);
$listener->onKernelRequest($event);
$this->assertEquals('de', $request->getLocale());
}
private function getEvent(Request $request)
{
return new GetResponseEvent($this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface'), $request, HttpKernelInterface::MASTER_REQUEST);
}
}

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\EventListener;
use Symfony\Component\HttpKernel\EventListener\ResponseListener;
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\KernelEvents;
use Symfony\Component\EventDispatcher\EventDispatcher;
class ResponseListenerTest extends \PHPUnit_Framework_TestCase
{
private $dispatcher;
private $kernel;
protected function setUp()
{
if (!class_exists('Symfony\Component\EventDispatcher\EventDispatcher')) {
$this->markTestSkipped('The "EventDispatcher" component is not available');
}
$this->dispatcher = new EventDispatcher();
$listener = new ResponseListener('UTF-8');
$this->dispatcher->addListener(KernelEvents::RESPONSE, array($listener, 'onKernelResponse'));
$this->kernel = $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface');
}
protected function tearDown()
{
$this->dispatcher = null;
$this->kernel = null;
}
public function testFilterDoesNothingForSubRequests()
{
$response = new Response('foo');
$event = new FilterResponseEvent($this->kernel, new Request(), HttpKernelInterface::SUB_REQUEST, $response);
$this->dispatcher->dispatch(KernelEvents::RESPONSE, $event);
$this->assertEquals('', $event->getResponse()->headers->get('content-type'));
}
public function testFilterSetsNonDefaultCharsetIfNotOverridden()
{
$listener = new ResponseListener('ISO-8859-15');
$this->dispatcher->addListener(KernelEvents::RESPONSE, array($listener, 'onKernelResponse'), 1);
$response = new Response('foo');
$event = new FilterResponseEvent($this->kernel, Request::create('/'), HttpKernelInterface::MASTER_REQUEST, $response);
$this->dispatcher->dispatch(KernelEvents::RESPONSE, $event);
$this->assertEquals('ISO-8859-15', $response->getCharset());
}
public function testFilterDoesNothingIfCharsetIsOverridden()
{
$listener = new ResponseListener('ISO-8859-15');
$this->dispatcher->addListener(KernelEvents::RESPONSE, array($listener, 'onKernelResponse'), 1);
$response = new Response('foo');
$response->setCharset('ISO-8859-1');
$event = new FilterResponseEvent($this->kernel, Request::create('/'), HttpKernelInterface::MASTER_REQUEST, $response);
$this->dispatcher->dispatch(KernelEvents::RESPONSE, $event);
$this->assertEquals('ISO-8859-1', $response->getCharset());
}
public function testFiltersSetsNonDefaultCharsetIfNotOverriddenOnNonTextContentType()
{
$listener = new ResponseListener('ISO-8859-15');
$this->dispatcher->addListener(KernelEvents::RESPONSE, array($listener, 'onKernelResponse'), 1);
$response = new Response('foo');
$request = Request::create('/');
$request->setRequestFormat('application/json');
$event = new FilterResponseEvent($this->kernel, $request, HttpKernelInterface::MASTER_REQUEST, $response);
$this->dispatcher->dispatch(KernelEvents::RESPONSE, $event);
$this->assertEquals('ISO-8859-15', $response->getCharset());
}
}

View File

@@ -0,0 +1,134 @@
<?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 Symfony\Component\HttpKernel\EventListener\RouterListener;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\Routing\RequestContext;
class RouterListenerTest extends \PHPUnit_Framework_TestCase
{
protected function setUp()
{
if (!class_exists('Symfony\Component\EventDispatcher\EventDispatcher')) {
$this->markTestSkipped('The "EventDispatcher" component is not available');
}
if (!class_exists('Symfony\Component\Routing\Router')) {
$this->markTestSkipped('The "Routing" component is not available');
}
}
/**
* @dataProvider getPortData
*/
public function testPort($defaultHttpPort, $defaultHttpsPort, $uri, $expectedHttpPort, $expectedHttpsPort)
{
$urlMatcher = $this->getMockBuilder('Symfony\Component\Routing\Matcher\UrlMatcherInterface')
->disableOriginalConstructor()
->getMock();
$context = new RequestContext();
$context->setHttpPort($defaultHttpPort);
$context->setHttpsPort($defaultHttpsPort);
$urlMatcher->expects($this->any())
->method('getContext')
->will($this->returnValue($context));
$listener = new RouterListener($urlMatcher);
$event = $this->createGetResponseEventForUri($uri);
$listener->onKernelRequest($event);
$this->assertEquals($expectedHttpPort, $context->getHttpPort());
$this->assertEquals($expectedHttpsPort, $context->getHttpsPort());
$this->assertEquals(0 === strpos($uri, 'https') ? 'https' : 'http', $context->getScheme());
}
public function getPortData()
{
return array(
array(80, 443, 'http://localhost/', 80, 443),
array(80, 443, 'http://localhost:90/', 90, 443),
array(80, 443, 'https://localhost/', 80, 443),
array(80, 443, 'https://localhost:90/', 80, 90),
);
}
/**
* @param string $uri
*
* @return GetResponseEvent
*/
private function createGetResponseEventForUri($uri)
{
$kernel = $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface');
$request = Request::create($uri);
$request->attributes->set('_controller', null); // Prevents going in to routing process
return new GetResponseEvent($kernel, $request, HttpKernelInterface::MASTER_REQUEST);
}
/**
* @expectedException \InvalidArgumentException
*/
public function testInvalidMatcher()
{
new RouterListener(new \stdClass());
}
public function testRequestMatcher()
{
$kernel = $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface');
$request = Request::create('http://localhost/');
$event = new GetResponseEvent($kernel, $request, HttpKernelInterface::MASTER_REQUEST);
$requestMatcher = $this->getMock('Symfony\Component\Routing\Matcher\RequestMatcherInterface');
$requestMatcher->expects($this->once())
->method('matchRequest')
->with($this->isInstanceOf('Symfony\Component\HttpFoundation\Request'))
->will($this->returnValue(array()));
$listener = new RouterListener($requestMatcher, new RequestContext());
$listener->onKernelRequest($event);
}
public function testSubRequestWithDifferentMethod()
{
$kernel = $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface');
$request = Request::create('http://localhost/', 'post');
$event = new GetResponseEvent($kernel, $request, HttpKernelInterface::MASTER_REQUEST);
$requestMatcher = $this->getMock('Symfony\Component\Routing\Matcher\RequestMatcherInterface');
$requestMatcher->expects($this->any())
->method('matchRequest')
->with($this->isInstanceOf('Symfony\Component\HttpFoundation\Request'))
->will($this->returnValue(array()));
$context = new RequestContext();
$requestMatcher->expects($this->any())
->method('getContext')
->will($this->returnValue($context));
$listener = new RouterListener($requestMatcher, new RequestContext());
$listener->onKernelRequest($event);
// sub-request with another HTTP method
$kernel = $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface');
$request = Request::create('http://localhost/', 'get');
$event = new GetResponseEvent($kernel, $request, HttpKernelInterface::SUB_REQUEST);
$listener->onKernelRequest($event);
$this->assertEquals('GET', $context->getMethod());
}
}

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\ExtensionAbsentBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class ExtensionAbsentBundle extends Bundle
{
}

View File

@@ -0,0 +1,22 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Tests\Fixtures\ExtensionLoadedBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
class ExtensionLoadedExtension extends Extension
{
public function load(array $configs, ContainerBuilder $container)
{
}
}

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\ExtensionLoadedBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class ExtensionLoadedBundle extends Bundle
{
}

View File

@@ -0,0 +1,18 @@
<?php
namespace Symfony\Component\HttpKernel\Tests\Fixtures\ExtensionPresentBundle\Command;
use Symfony\Component\Console\Command\Command;
/**
* This command has a required parameter on the constructor and will be ignored by the default Bundle implementation.
*
* @see Symfony\Component\HttpKernel\Bundle\Bundle::registerCommands
*/
class BarCommand extends Command
{
public function __construct($example, $name = 'bar')
{
}
}

View File

@@ -0,0 +1,23 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien.potencier@symfony-project.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\ExtensionPresentBundle\Command;
use Symfony\Component\Console\Command\Command;
class FooCommand extends Command
{
protected function configure()
{
$this->setName('foo');
}
}

View File

@@ -0,0 +1,22 @@
<?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\ExtensionPresentBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
class ExtensionPresentExtension extends Extension
{
public function load(array $configs, ContainerBuilder $container)
{
}
}

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\ExtensionPresentBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class ExtensionPresentBundle extends Bundle
{
}

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;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class FooBarBundle extends Bundle
{
// We need a full namespaced bundle instance to test isClassInActiveBundle
}

View File

@@ -0,0 +1,30 @@
<?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\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
class KernelForOverrideName extends Kernel
{
protected $name = 'overridden';
public function registerBundles()
{
}
public function registerContainerConfiguration(LoaderInterface $loader)
{
}
}

View File

@@ -0,0 +1,54 @@
<?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\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
class KernelForTest extends Kernel
{
public function getBundleMap()
{
return $this->bundleMap;
}
public function registerBundles()
{
}
public function init()
{
}
public function registerBundleDirs()
{
}
public function registerContainerConfiguration(LoaderInterface $loader)
{
}
public function initializeBundles()
{
parent::initializeBundles();
}
public function isBooted()
{
return $this->booted;
}
public function setIsBooted($value)
{
$this->booted = (Boolean) $value;
}
}

View File

@@ -0,0 +1,31 @@
<?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\HttpKernel\Client;
class TestClient extends Client
{
protected function getScript($request)
{
$script = parent::getScript($request);
$autoload = file_exists(__DIR__.'/../../vendor/autoload.php')
? __DIR__.'/../../vendor/autoload.php'
: __DIR__.'/../../../../../../vendor/autoload.php'
;
$script = preg_replace('/(\->register\(\);)/', "$0\nrequire_once '$autoload';\n", $script);
return $script;
}
}

View File

@@ -0,0 +1,28 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Tests\Fixtures;
use Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcherInterface;
use Symfony\Component\EventDispatcher\EventDispatcher;
class TestEventDispatcher extends EventDispatcher implements TraceableEventDispatcherInterface
{
public function getCalledListeners()
{
return array('foo');
}
public function getNotCalledListeners()
{
return array('bar');
}
}

View File

@@ -0,0 +1,64 @@
<?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\FragmentRenderer;
use Symfony\Component\HttpKernel\Controller\ControllerReference;
use Symfony\Component\HttpKernel\Fragment\EsiFragmentRenderer;
use Symfony\Component\HttpKernel\HttpCache\Esi;
use Symfony\Component\HttpFoundation\Request;
class EsiFragmentRendererTest extends \PHPUnit_Framework_TestCase
{
protected function setUp()
{
if (!class_exists('Symfony\Component\HttpFoundation\Request')) {
$this->markTestSkipped('The "HttpFoundation" component is not available');
}
}
public function testRenderFallbackToInlineStrategyIfNoRequest()
{
$strategy = new EsiFragmentRenderer(new Esi(), $this->getInlineStrategy(true));
$strategy->render('/', Request::create('/'));
}
public function testRenderFallbackToInlineStrategyIfEsiNotSupported()
{
$strategy = new EsiFragmentRenderer(new Esi(), $this->getInlineStrategy(true));
$strategy->render('/', Request::create('/'));
}
public function testRender()
{
$strategy = new EsiFragmentRenderer(new Esi(), $this->getInlineStrategy());
$request = Request::create('/');
$request->setLocale('fr');
$request->headers->set('Surrogate-Capability', 'ESI/1.0');
$this->assertEquals('<esi:include src="/" />', $strategy->render('/', $request)->getContent());
$this->assertEquals("<esi:comment text=\"This is a comment\" />\n<esi:include src=\"/\" />", $strategy->render('/', $request, array('comment' => 'This is a comment'))->getContent());
$this->assertEquals('<esi:include src="/" alt="foo" />', $strategy->render('/', $request, array('alt' => 'foo'))->getContent());
$this->assertEquals('<esi:include src="/_fragment?_path=_format%3Dhtml%26_locale%3Dfr%26_controller%3Dmain_controller" alt="/_fragment?_path=_format%3Dhtml%26_locale%3Dfr%26_controller%3Dalt_controller" />', $strategy->render(new ControllerReference('main_controller', array(), array()), $request, array('alt' => new ControllerReference('alt_controller', array(), array())))->getContent());
}
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

@@ -0,0 +1,81 @@
<?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 Symfony\Component\HttpKernel\Fragment\FragmentHandler;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class FragmentHandlerTest extends \PHPUnit_Framework_TestCase
{
/**
* @expectedException \InvalidArgumentException
*/
public function testRenderWhenRendererDoesNotExist()
{
$handler = new FragmentHandler();
$handler->render('/', 'foo');
}
/**
* @expectedException InvalidArgumentException
*/
public function testRenderWithUnknownRenderer()
{
$handler = $this->getHandler($this->returnValue(new Response('foo')));
$handler->render('/', 'bar');
}
/**
* @expectedException RuntimeException
* @expectedExceptionMessage Error when rendering "http://localhost/" (Status code is 404).
*/
public function testDeliverWithUnsuccessfulResponse()
{
$handler = $this->getHandler($this->returnValue(new Response('foo', 404)));
$handler->render('/', 'foo');
}
public function testRender()
{
$handler = $this->getHandler($this->returnValue(new Response('foo')), array('/', Request::create('/'), array('foo' => 'foo', 'ignore_errors' => true)));
$this->assertEquals('foo', $handler->render('/', 'foo', array('foo' => 'foo')));
}
protected function getHandler($returnValue, $arguments = array())
{
$renderer = $this->getMock('Symfony\Component\HttpKernel\Fragment\FragmentRendererInterface');
$renderer
->expects($this->any())
->method('getName')
->will($this->returnValue('foo'))
;
$e = $renderer
->expects($this->any())
->method('render')
->will($returnValue)
;
if ($arguments) {
call_user_func_array(array($e, 'with'), $arguments);
}
$handler = new FragmentHandler();
$handler->addRenderer($renderer);
$handler->setRequest(Request::create('/'));
return $handler;
}
}

View File

@@ -0,0 +1,95 @@
<?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\Fragment\Tests\FragmentRenderer;
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
{
protected function setUp()
{
if (!class_exists('Symfony\Component\HttpFoundation\Request')) {
$this->markTestSkipped('The "HttpFoundation" component is not available');
}
}
/**
* @expectedException \LogicException
*/
public function testRenderExceptionWhenControllerAndNoSigner()
{
$strategy = new HIncludeFragmentRenderer();
$strategy->render(new ControllerReference('main_controller', array(), array()), Request::create('/'));
}
public function testRenderWithControllerAndSigner()
{
$strategy = new HIncludeFragmentRenderer(null, new UriSigner('foo'));
$this->assertEquals('<hx:include src="/_fragment?_path=_format%3Dhtml%26_locale%3Den%26_controller%3Dmain_controller&amp;_hash=5RZ1IkwF487EaXt6buHka73CCtQ%3D"></hx:include>', $strategy->render(new ControllerReference('main_controller', array(), array()), Request::create('/'))->getContent());
}
public function testRenderWithUri()
{
$strategy = new HIncludeFragmentRenderer();
$this->assertEquals('<hx:include src="/foo"></hx:include>', $strategy->render('/foo', Request::create('/'))->getContent());
$strategy = new HIncludeFragmentRenderer(null, new UriSigner('foo'));
$this->assertEquals('<hx:include src="/foo"></hx:include>', $strategy->render('/foo', Request::create('/'))->getContent());
}
public function testRenderWithDefault()
{
// only default
$strategy = new HIncludeFragmentRenderer();
$this->assertEquals('<hx:include src="/foo">default</hx:include>', $strategy->render('/foo', Request::create('/'), array('default' => 'default'))->getContent());
// only global default
$strategy = new HIncludeFragmentRenderer(null, null, 'global_default');
$this->assertEquals('<hx:include src="/foo">global_default</hx:include>', $strategy->render('/foo', Request::create('/'), array())->getContent());
// global default and default
$strategy = new HIncludeFragmentRenderer(null, null, 'global_default');
$this->assertEquals('<hx:include src="/foo">default</hx:include>', $strategy->render('/foo', Request::create('/'), array('default' => 'default'))->getContent());
}
public function testRenderWithAttributesOptions()
{
// with id
$strategy = new HIncludeFragmentRenderer();
$this->assertEquals('<hx:include src="/foo" id="bar">default</hx:include>', $strategy->render('/foo', Request::create('/'), array('default' => 'default', 'id' => 'bar'))->getContent());
// with attributes
$strategy = new HIncludeFragmentRenderer();
$this->assertEquals('<hx:include src="/foo" p1="v1" p2="v2">default</hx:include>', $strategy->render('/foo', Request::create('/'), array('default' => 'default', 'attributes' => array('p1' => 'v1', 'p2' => 'v2')))->getContent());
// with id & attributes
$strategy = new HIncludeFragmentRenderer();
$this->assertEquals('<hx:include src="/foo" p1="v1" p2="v2" id="bar">default</hx:include>', $strategy->render('/foo', Request::create('/'), array('default' => 'default', 'id' => 'bar', 'attributes' => array('p1' => 'v1', 'p2' => 'v2')))->getContent());
}
public function testRenderWithDefaultText()
{
$engine = $this->getMock('Symfony\\Component\\Templating\\EngineInterface');
$engine->expects($this->once())
->method('exists')
->with('default')
->will($this->throwException(new \InvalidArgumentException()));
// only default
$strategy = new HIncludeFragmentRenderer($engine);
$this->assertEquals('<hx:include src="/foo">default</hx:include>', $strategy->render('/foo', Request::create('/'), array('default' => 'default'))->getContent());
}
}

View File

@@ -0,0 +1,199 @@
<?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\Fragment\Tests\FragmentRenderer;
use Symfony\Component\HttpKernel\Controller\ControllerReference;
use Symfony\Component\HttpKernel\HttpKernel;
use Symfony\Component\HttpKernel\Fragment\InlineFragmentRenderer;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\EventDispatcher\EventDispatcher;
class InlineFragmentRendererTest extends \PHPUnit_Framework_TestCase
{
protected function setUp()
{
if (!class_exists('Symfony\Component\EventDispatcher\EventDispatcher')) {
$this->markTestSkipped('The "EventDispatcher" component is not available');
}
if (!class_exists('Symfony\Component\HttpFoundation\Request')) {
$this->markTestSkipped('The "HttpFoundation" component is not available');
}
}
public function testRender()
{
$strategy = new InlineFragmentRenderer($this->getKernel($this->returnValue(new Response('foo'))));
$this->assertEquals('foo', $strategy->render('/', Request::create('/'))->getContent());
}
public function testRenderWithControllerReference()
{
$strategy = new InlineFragmentRenderer($this->getKernel($this->returnValue(new Response('foo'))));
$this->assertEquals('foo', $strategy->render(new ControllerReference('main_controller', array(), array()), Request::create('/'))->getContent());
}
public function testRenderWithObjectsAsAttributes()
{
$object = new \stdClass();
$subRequest = Request::create('/_fragment?_path=_format%3Dhtml%26_locale%3Den%26_controller%3Dmain_controller');
$subRequest->attributes->replace(array('object' => $object, '_format' => 'html', '_controller' => 'main_controller', '_locale' => 'en'));
$subRequest->headers->set('x-forwarded-for', array('127.0.0.1'));
$subRequest->server->set('HTTP_X_FORWARDED_FOR', '127.0.0.1');
$kernel = $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface');
$kernel
->expects($this->any())
->method('handle')
->with($subRequest)
;
$strategy = new InlineFragmentRenderer($kernel);
$strategy->render(new ControllerReference('main_controller', array('object' => $object), array()), Request::create('/'));
}
public function testRenderWithTrustedHeaderDisabled()
{
$trustedHeaderName = Request::getTrustedHeaderName(Request::HEADER_CLIENT_IP);
Request::setTrustedHeaderName(Request::HEADER_CLIENT_IP, '');
$kernel = $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface');
$kernel
->expects($this->any())
->method('handle')
->with(Request::create('/'))
;
$strategy = new InlineFragmentRenderer($kernel);
$strategy->render('/', Request::create('/'));
Request::setTrustedHeaderName(Request::HEADER_CLIENT_IP, $trustedHeaderName);
}
/**
* @expectedException \RuntimeException
*/
public function testRenderExceptionNoIgnoreErrors()
{
$dispatcher = $this->getMock('Symfony\Component\EventDispatcher\EventDispatcherInterface');
$dispatcher->expects($this->never())->method('dispatch');
$strategy = new InlineFragmentRenderer($this->getKernel($this->throwException(new \RuntimeException('foo'))), $dispatcher);
$this->assertEquals('foo', $strategy->render('/', Request::create('/'))->getContent());
}
public function testRenderExceptionIgnoreErrors()
{
$dispatcher = $this->getMock('Symfony\Component\EventDispatcher\EventDispatcherInterface');
$dispatcher->expects($this->once())->method('dispatch')->with(KernelEvents::EXCEPTION);
$strategy = new InlineFragmentRenderer($this->getKernel($this->throwException(new \RuntimeException('foo'))), $dispatcher);
$this->assertEmpty($strategy->render('/', Request::create('/'), array('ignore_errors' => true))->getContent());
}
public function testRenderExceptionIgnoreErrorsWithAlt()
{
$strategy = new InlineFragmentRenderer($this->getKernel($this->onConsecutiveCalls(
$this->throwException(new \RuntimeException('foo')),
$this->returnValue(new Response('bar'))
)));
$this->assertEquals('bar', $strategy->render('/', Request::create('/'), array('ignore_errors' => true, 'alt' => '/foo'))->getContent());
}
private function getKernel($returnValue)
{
$kernel = $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface');
$kernel
->expects($this->any())
->method('handle')
->will($returnValue)
;
return $kernel;
}
public function testExceptionInSubRequestsDoesNotMangleOutputBuffers()
{
$resolver = $this->getMock('Symfony\\Component\\HttpKernel\\Controller\\ControllerResolverInterface');
$resolver
->expects($this->once())
->method('getController')
->will($this->returnValue(function () {
ob_start();
echo 'bar';
throw new \RuntimeException();
}))
;
$resolver
->expects($this->once())
->method('getArguments')
->will($this->returnValue(array()))
;
$kernel = new HttpKernel(new EventDispatcher(), $resolver);
$renderer = new InlineFragmentRenderer($kernel);
// simulate a main request with output buffering
ob_start();
echo 'Foo';
// simulate a sub-request with output buffering and an exception
$renderer->render('/', Request::create('/'), array('ignore_errors' => true));
$this->assertEquals('Foo', ob_get_clean());
}
public function testESIHeaderIsKeptInSubrequest()
{
$expectedSubRequest = Request::create('/');
$expectedSubRequest->headers->set('Surrogate-Capability', 'abc="ESI/1.0"');
if (Request::getTrustedHeaderName(Request::HEADER_CLIENT_IP)) {
$expectedSubRequest->headers->set('x-forwarded-for', array('127.0.0.1'));
$expectedSubRequest->server->set('HTTP_X_FORWARDED_FOR', '127.0.0.1');
}
$kernel = $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface');
$kernel
->expects($this->any())
->method('handle')
->with($expectedSubRequest)
;
$strategy = new InlineFragmentRenderer($kernel);
$request = Request::create('/');
$request->headers->set('Surrogate-Capability', 'abc="ESI/1.0"');
$strategy->render('/', $request);
}
public function testESIHeaderIsKeptInSubrequestWithTrustedHeaderDisabled()
{
$trustedHeaderName = Request::getTrustedHeaderName(Request::HEADER_CLIENT_IP);
Request::setTrustedHeaderName(Request::HEADER_CLIENT_IP, '');
$this->testESIHeaderIsKeptInSubrequest();
Request::setTrustedHeaderName(Request::HEADER_CLIENT_IP, $trustedHeaderName);
}
}

View File

@@ -0,0 +1,72 @@
<?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\Fragment\Tests\FragmentRenderer;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Controller\ControllerReference;
use Symfony\Component\HttpKernel\Fragment\RoutableFragmentRenderer;
class RoutableFragmentRendererTest extends \PHPUnit_Framework_TestCase
{
/**
* @dataProvider getGenerateFragmentUriData
*/
public function testGenerateFragmentUri($uri, $controller)
{
$this->assertEquals($uri, $this->getRenderer()->doGenerateFragmentUri($controller, Request::create('/')));
}
/**
* @dataProvider getGenerateFragmentUriData
*/
public function testGenerateAbsoluteFragmentUri($uri, $controller)
{
$this->assertEquals('http://localhost'.$uri, $this->getRenderer()->doGenerateFragmentUri($controller, Request::create('/'), true));
}
public function getGenerateFragmentUriData()
{
return array(
array('/_fragment?_path=_format%3Dhtml%26_locale%3Den%26_controller%3Dcontroller', new ControllerReference('controller', array(), array())),
array('/_fragment?_path=_format%3Dxml%26_locale%3Den%26_controller%3Dcontroller', new ControllerReference('controller', array('_format' => 'xml'), array())),
array('/_fragment?_path=foo%3Dfoo%26_format%3Djson%26_locale%3Den%26_controller%3Dcontroller', new ControllerReference('controller', array('foo' => 'foo', '_format' => 'json'), array())),
array('/_fragment?bar=bar&_path=foo%3Dfoo%26_format%3Dhtml%26_locale%3Den%26_controller%3Dcontroller', new ControllerReference('controller', array('foo' => 'foo'), array('bar' => 'bar'))),
array('/_fragment?foo=foo&_path=_format%3Dhtml%26_locale%3Den%26_controller%3Dcontroller', new ControllerReference('controller', array(), array('foo' => 'foo'))),
);
}
public function testGenerateFragmentUriWithARequest()
{
$request = Request::create('/');
$request->attributes->set('_format', 'json');
$request->setLocale('fr');
$controller = new ControllerReference('controller', array(), array());
$this->assertEquals('/_fragment?_path=_format%3Djson%26_locale%3Dfr%26_controller%3Dcontroller', $this->getRenderer()->doGenerateFragmentUri($controller, $request));
}
private function getRenderer()
{
return new Renderer();
}
}
class Renderer extends RoutableFragmentRenderer
{
public function render($uri, Request $request, array $options = array()) {}
public function getName() {}
public function doGenerateFragmentUri(ControllerReference $reference, Request $request, $absolute = false)
{
return parent::generateFragmentUri($reference, $request, $absolute);
}
}

View File

@@ -0,0 +1,227 @@
<?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 Symfony\Component\HttpKernel\HttpCache\Esi;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class EsiTest extends \PHPUnit_Framework_TestCase
{
protected function setUp()
{
if (!class_exists('Symfony\Component\HttpFoundation\Request')) {
$this->markTestSkipped('The "HttpFoundation" component is not available');
}
}
public function testHasSurrogateEsiCapability()
{
$esi = new Esi();
$request = Request::create('/');
$request->headers->set('Surrogate-Capability', 'abc="ESI/1.0"');
$this->assertTrue($esi->hasSurrogateEsiCapability($request));
$request = Request::create('/');
$request->headers->set('Surrogate-Capability', 'foobar');
$this->assertFalse($esi->hasSurrogateEsiCapability($request));
$request = Request::create('/');
$this->assertFalse($esi->hasSurrogateEsiCapability($request));
}
public function testAddSurrogateEsiCapability()
{
$esi = new Esi();
$request = Request::create('/');
$esi->addSurrogateEsiCapability($request);
$this->assertEquals('symfony2="ESI/1.0"', $request->headers->get('Surrogate-Capability'));
$esi->addSurrogateEsiCapability($request);
$this->assertEquals('symfony2="ESI/1.0", symfony2="ESI/1.0"', $request->headers->get('Surrogate-Capability'));
}
public function testAddSurrogateControl()
{
$esi = new Esi();
$response = new Response('foo <esi:include src="" />');
$esi->addSurrogateControl($response);
$this->assertEquals('content="ESI/1.0"', $response->headers->get('Surrogate-Control'));
$response = new Response('foo');
$esi->addSurrogateControl($response);
$this->assertEquals('', $response->headers->get('Surrogate-Control'));
}
public function testNeedsEsiParsing()
{
$esi = new Esi();
$response = new Response();
$response->headers->set('Surrogate-Control', 'content="ESI/1.0"');
$this->assertTrue($esi->needsEsiParsing($response));
$response = new Response();
$this->assertFalse($esi->needsEsiParsing($response));
}
public function testRenderIncludeTag()
{
$esi = new Esi();
$this->assertEquals('<esi:include src="/" onerror="continue" alt="/alt" />', $esi->renderIncludeTag('/', '/alt', true));
$this->assertEquals('<esi:include src="/" alt="/alt" />', $esi->renderIncludeTag('/', '/alt', false));
$this->assertEquals('<esi:include src="/" onerror="continue" />', $esi->renderIncludeTag('/'));
$this->assertEquals('<esi:comment text="some comment" />'."\n".'<esi:include src="/" onerror="continue" alt="/alt" />', $esi->renderIncludeTag('/', '/alt', true, 'some comment'));
}
public function testProcessDoesNothingIfContentTypeIsNotHtml()
{
$esi = new Esi();
$request = Request::create('/');
$response = new Response();
$response->headers->set('Content-Type', 'text/plain');
$esi->process($request, $response);
$this->assertFalse($response->headers->has('x-body-eval'));
}
public function testProcess()
{
$esi = new Esi();
$request = Request::create('/');
$response = new Response('foo <esi:comment text="some comment" /><esi:include src="..." alt="alt" onerror="continue" />');
$esi->process($request, $response);
$this->assertEquals('foo <?php echo $this->esi->handle($this, \'...\', \'alt\', true) ?>'."\n", $response->getContent());
$this->assertEquals('ESI', $response->headers->get('x-body-eval'));
$response = new Response('foo <esi:include src="..." />');
$esi->process($request, $response);
$this->assertEquals('foo <?php echo $this->esi->handle($this, \'...\', \'\', false) ?>'."\n", $response->getContent());
$response = new Response('foo <esi:include src="..."></esi:include>');
$esi->process($request, $response);
$this->assertEquals('foo <?php echo $this->esi->handle($this, \'...\', \'\', false) ?>'."\n", $response->getContent());
}
public function testProcessEscapesPhpTags()
{
$esi = new Esi();
$request = Request::create('/');
$response = new Response('foo <?php die("foo"); ?><%= "lala" %>');
$esi->process($request, $response);
$this->assertEquals('foo <?php echo "<?"; ?>php die("foo"); ?><?php echo "<%"; ?>= "lala" %>', $response->getContent());
}
/**
* @expectedException RuntimeException
*/
public function testProcessWhenNoSrcInAnEsi()
{
$esi = new Esi();
$request = Request::create('/');
$response = new Response('foo <esi:include />');
$esi->process($request, $response);
}
public function testProcessRemoveSurrogateControlHeader()
{
$esi = new Esi();
$request = Request::create('/');
$response = new Response('foo <esi:include src="..." />');
$response->headers->set('Surrogate-Control', 'content="ESI/1.0"');
$esi->process($request, $response);
$this->assertEquals('ESI', $response->headers->get('x-body-eval'));
$response->headers->set('Surrogate-Control', 'no-store, content="ESI/1.0"');
$esi->process($request, $response);
$this->assertEquals('ESI', $response->headers->get('x-body-eval'));
$this->assertEquals('no-store', $response->headers->get('surrogate-control'));
$response->headers->set('Surrogate-Control', 'content="ESI/1.0", no-store');
$esi->process($request, $response);
$this->assertEquals('ESI', $response->headers->get('x-body-eval'));
$this->assertEquals('no-store', $response->headers->get('surrogate-control'));
}
public function testHandle()
{
$esi = new Esi();
$cache = $this->getCache(Request::create('/'), new Response('foo'));
$this->assertEquals('foo', $esi->handle($cache, '/', '/alt', true));
}
/**
* @expectedException RuntimeException
*/
public function testHandleWhenResponseIsNot200()
{
$esi = new Esi();
$response = new Response('foo');
$response->setStatusCode(404);
$cache = $this->getCache(Request::create('/'), $response);
$esi->handle($cache, '/', '/alt', false);
}
public function testHandleWhenResponseIsNot200AndErrorsAreIgnored()
{
$esi = new Esi();
$response = new Response('foo');
$response->setStatusCode(404);
$cache = $this->getCache(Request::create('/'), $response);
$this->assertEquals('', $esi->handle($cache, '/', '/alt', true));
}
public function testHandleWhenResponseIsNot200AndAltIsPresent()
{
$esi = new Esi();
$response1 = new Response('foo');
$response1->setStatusCode(404);
$response2 = new Response('bar');
$cache = $this->getCache(Request::create('/'), array($response1, $response2));
$this->assertEquals('bar', $esi->handle($cache, '/', '/alt', false));
}
protected function getCache($request, $response)
{
$cache = $this->getMock('Symfony\Component\HttpKernel\HttpCache\HttpCache', array('getRequest', 'handle'), array(), '', false);
$cache->expects($this->any())
->method('getRequest')
->will($this->returnValue($request))
;
if (is_array($response)) {
$cache->expects($this->any())
->method('handle')
->will(call_user_func_array(array($this, 'onConsecutiveCalls'), $response))
;
} else {
$cache->expects($this->any())
->method('handle')
->will($this->returnValue($response))
;
}
return $cache;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,179 @@
<?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 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
{
protected $kernel;
protected $cache;
protected $caches;
protected $cacheConfig;
protected $request;
protected $response;
protected $responses;
protected $catch;
protected $esi;
protected function setUp()
{
if (!class_exists('Symfony\Component\HttpFoundation\Request')) {
$this->markTestSkipped('The "HttpFoundation" component is not available');
}
$this->kernel = null;
$this->cache = null;
$this->esi = null;
$this->caches = array();
$this->cacheConfig = array();
$this->request = null;
$this->response = null;
$this->responses = array();
$this->catch = false;
$this->clearDirectory(sys_get_temp_dir().'/http_cache');
}
protected function tearDown()
{
$this->kernel = null;
$this->cache = null;
$this->caches = null;
$this->request = null;
$this->response = null;
$this->responses = null;
$this->cacheConfig = null;
$this->catch = null;
$this->esi = null;
$this->clearDirectory(sys_get_temp_dir().'/http_cache');
}
public function assertHttpKernelIsCalled()
{
$this->assertTrue($this->kernel->hasBeenCalled());
}
public function assertHttpKernelIsNotCalled()
{
$this->assertFalse($this->kernel->hasBeenCalled());
}
public function assertResponseOk()
{
$this->assertEquals(200, $this->response->getStatusCode());
}
public function assertTraceContains($trace)
{
$traces = $this->cache->getTraces();
$traces = current($traces);
$this->assertRegExp('/'.$trace.'/', implode(', ', $traces));
}
public function assertTraceNotContains($trace)
{
$traces = $this->cache->getTraces();
$traces = current($traces);
$this->assertNotRegExp('/'.$trace.'/', implode(', ', $traces));
}
public function assertExceptionsAreCaught()
{
$this->assertTrue($this->kernel->isCatchingExceptions());
}
public function assertExceptionsAreNotCaught()
{
$this->assertFalse($this->kernel->isCatchingExceptions());
}
public function request($method, $uri = '/', $server = array(), $cookies = array(), $esi = false)
{
if (null === $this->kernel) {
throw new \LogicException('You must call setNextResponse() before calling request().');
}
$this->kernel->reset();
$this->store = new Store(sys_get_temp_dir().'/http_cache');
$this->cacheConfig['debug'] = true;
$this->esi = $esi ? new Esi() : null;
$this->cache = new HttpCache($this->kernel, $this->store, $this->esi, $this->cacheConfig);
$this->request = Request::create($uri, $method, array(), $cookies, array(), $server);
$this->response = $this->cache->handle($this->request, HttpKernelInterface::MASTER_REQUEST, $this->catch);
$this->responses[] = $this->response;
}
public function getMetaStorageValues()
{
$values = array();
foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator(sys_get_temp_dir().'/http_cache/md', \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::LEAVES_ONLY) as $file) {
$values[] = file_get_contents($file);
}
return $values;
}
// A basic response with 200 status code and a tiny body.
public function setNextResponse($statusCode = 200, array $headers = array(), $body = 'Hello World', \Closure $customizer = null)
{
$this->kernel = new TestHttpKernel($body, $statusCode, $headers, $customizer);
}
public function setNextResponses($responses)
{
$this->kernel = new TestMultipleHttpKernel($responses);
}
public function catchExceptions($catch = true)
{
$this->catch = $catch;
}
public static function clearDirectory($directory)
{
if (!is_dir($directory)) {
return;
}
$fp = opendir($directory);
while (false !== $file = readdir($fp)) {
if (!in_array($file, array('.', '..'))) {
if (is_link($directory.'/'.$file)) {
unlink($directory.'/'.$file);
} elseif (is_dir($directory.'/'.$file)) {
self::clearDirectory($directory.'/'.$file);
rmdir($directory.'/'.$file);
} else {
unlink($directory.'/'.$file);
}
}
}
closedir($fp);
}
}

View File

@@ -0,0 +1,263 @@
<?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 Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpCache\Store;
class StoreTest extends \PHPUnit_Framework_TestCase
{
protected $request;
protected $response;
protected $store;
protected function setUp()
{
if (!class_exists('Symfony\Component\HttpFoundation\Request')) {
$this->markTestSkipped('The "HttpFoundation" component is not available');
}
$this->request = Request::create('/');
$this->response = new Response('hello world', 200, array());
HttpCacheTestCase::clearDirectory(sys_get_temp_dir().'/http_cache');
$this->store = new Store(sys_get_temp_dir().'/http_cache');
}
protected function tearDown()
{
$this->store = null;
$this->request = null;
$this->response = null;
HttpCacheTestCase::clearDirectory(sys_get_temp_dir().'/http_cache');
}
public function testReadsAnEmptyArrayWithReadWhenNothingCachedAtKey()
{
$this->assertEmpty($this->getStoreMetadata('/nothing'));
}
public function testUnlockFileThatDoesExist()
{
$cacheKey = $this->storeSimpleEntry();
$this->store->lock($this->request);
$this->assertTrue($this->store->unlock($this->request));
}
public function testUnlockFileThatDoesNotExist()
{
$this->assertFalse($this->store->unlock($this->request));
}
public function testRemovesEntriesForKeyWithPurge()
{
$request = Request::create('/foo');
$this->store->write($request, new Response('foo'));
$metadata = $this->getStoreMetadata($request);
$this->assertNotEmpty($metadata);
$this->assertTrue($this->store->purge('/foo'));
$this->assertEmpty($this->getStoreMetadata($request));
// cached content should be kept after purging
$path = $this->store->getPath($metadata[0][1]['x-content-digest'][0]);
$this->assertTrue(is_file($path));
$this->assertFalse($this->store->purge('/bar'));
}
public function testStoresACacheEntry()
{
$cacheKey = $this->storeSimpleEntry();
$this->assertNotEmpty($this->getStoreMetadata($cacheKey));
}
public function testSetsTheXContentDigestResponseHeaderBeforeStoring()
{
$cacheKey = $this->storeSimpleEntry();
$entries = $this->getStoreMetadata($cacheKey);
list ($req, $res) = $entries[0];
$this->assertEquals('ena94a8fe5ccb19ba61c4c0873d391e987982fbbd3', $res['x-content-digest'][0]);
}
public function testFindsAStoredEntryWithLookup()
{
$this->storeSimpleEntry();
$response = $this->store->lookup($this->request);
$this->assertNotNull($response);
$this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $response);
}
public function testDoesNotFindAnEntryWithLookupWhenNoneExists()
{
$request = Request::create('/test', 'get', array(), array(), array(), array('HTTP_FOO' => 'Foo', 'HTTP_BAR' => 'Bar'));
$this->assertNull($this->store->lookup($request));
}
public function testCanonizesUrlsForCacheKeys()
{
$this->storeSimpleEntry($path = '/test?x=y&p=q');
$hitsReq = Request::create($path);
$missReq = Request::create('/test?p=x');
$this->assertNotNull($this->store->lookup($hitsReq));
$this->assertNull($this->store->lookup($missReq));
}
public function testDoesNotFindAnEntryWithLookupWhenTheBodyDoesNotExist()
{
$this->storeSimpleEntry();
$this->assertNotNull($this->response->headers->get('X-Content-Digest'));
$path = $this->getStorePath($this->response->headers->get('X-Content-Digest'));
@unlink($path);
$this->assertNull($this->store->lookup($this->request));
}
public function testRestoresResponseHeadersProperlyWithLookup()
{
$this->storeSimpleEntry();
$response = $this->store->lookup($this->request);
$this->assertEquals($response->headers->all(), array_merge(array('content-length' => 4, 'x-body-file' => array($this->getStorePath($response->headers->get('X-Content-Digest')))), $this->response->headers->all()));
}
public function testRestoresResponseContentFromEntityStoreWithLookup()
{
$this->storeSimpleEntry();
$response = $this->store->lookup($this->request);
$this->assertEquals($this->getStorePath('en'.sha1('test')), $response->getContent());
}
public function testInvalidatesMetaAndEntityStoreEntriesWithInvalidate()
{
$this->storeSimpleEntry();
$this->store->invalidate($this->request);
$response = $this->store->lookup($this->request);
$this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $response);
$this->assertFalse($response->isFresh());
}
public function testSucceedsQuietlyWhenInvalidateCalledWithNoMatchingEntries()
{
$req = Request::create('/test');
$this->store->invalidate($req);
$this->assertNull($this->store->lookup($this->request));
}
public function testDoesNotReturnEntriesThatVaryWithLookup()
{
$req1 = Request::create('/test', 'get', array(), array(), array(), array('HTTP_FOO' => 'Foo', 'HTTP_BAR' => 'Bar'));
$req2 = Request::create('/test', 'get', array(), array(), array(), array('HTTP_FOO' => 'Bling', 'HTTP_BAR' => 'Bam'));
$res = new Response('test', 200, array('Vary' => 'Foo Bar'));
$this->store->write($req1, $res);
$this->assertNull($this->store->lookup($req2));
}
public function testStoresMultipleResponsesForEachVaryCombination()
{
$req1 = Request::create('/test', 'get', array(), array(), array(), array('HTTP_FOO' => 'Foo', 'HTTP_BAR' => 'Bar'));
$res1 = new Response('test 1', 200, array('Vary' => 'Foo Bar'));
$key = $this->store->write($req1, $res1);
$req2 = Request::create('/test', 'get', array(), array(), array(), array('HTTP_FOO' => 'Bling', 'HTTP_BAR' => 'Bam'));
$res2 = new Response('test 2', 200, array('Vary' => 'Foo Bar'));
$this->store->write($req2, $res2);
$req3 = Request::create('/test', 'get', array(), array(), array(), array('HTTP_FOO' => 'Baz', 'HTTP_BAR' => 'Boom'));
$res3 = new Response('test 3', 200, array('Vary' => 'Foo Bar'));
$this->store->write($req3, $res3);
$this->assertEquals($this->getStorePath('en'.sha1('test 3')), $this->store->lookup($req3)->getContent());
$this->assertEquals($this->getStorePath('en'.sha1('test 2')), $this->store->lookup($req2)->getContent());
$this->assertEquals($this->getStorePath('en'.sha1('test 1')), $this->store->lookup($req1)->getContent());
$this->assertCount(3, $this->getStoreMetadata($key));
}
public function testOverwritesNonVaryingResponseWithStore()
{
$req1 = Request::create('/test', 'get', array(), array(), array(), array('HTTP_FOO' => 'Foo', 'HTTP_BAR' => 'Bar'));
$res1 = new Response('test 1', 200, array('Vary' => 'Foo Bar'));
$key = $this->store->write($req1, $res1);
$this->assertEquals($this->getStorePath('en'.sha1('test 1')), $this->store->lookup($req1)->getContent());
$req2 = Request::create('/test', 'get', array(), array(), array(), array('HTTP_FOO' => 'Bling', 'HTTP_BAR' => 'Bam'));
$res2 = new Response('test 2', 200, array('Vary' => 'Foo Bar'));
$this->store->write($req2, $res2);
$this->assertEquals($this->getStorePath('en'.sha1('test 2')), $this->store->lookup($req2)->getContent());
$req3 = Request::create('/test', 'get', array(), array(), array(), array('HTTP_FOO' => 'Foo', 'HTTP_BAR' => 'Bar'));
$res3 = new Response('test 3', 200, array('Vary' => 'Foo Bar'));
$key = $this->store->write($req3, $res3);
$this->assertEquals($this->getStorePath('en'.sha1('test 3')), $this->store->lookup($req3)->getContent());
$this->assertCount(2, $this->getStoreMetadata($key));
}
public function testLocking()
{
$req = Request::create('/test', 'get', array(), array(), array(), array('HTTP_FOO' => 'Foo', 'HTTP_BAR' => 'Bar'));
$this->assertTrue($this->store->lock($req));
$path = $this->store->lock($req);
$this->assertTrue($this->store->isLocked($req));
$this->store->unlock($req);
$this->assertFalse($this->store->isLocked($req));
}
protected function storeSimpleEntry($path = null, $headers = array())
{
if (null === $path) {
$path = '/test';
}
$this->request = Request::create($path, 'get', array(), array(), array(), $headers);
$this->response = new Response('test', 200, array('Cache-Control' => 'max-age=420'));
return $this->store->write($this->request, $this->response);
}
protected function getStoreMetadata($key)
{
$r = new \ReflectionObject($this->store);
$m = $r->getMethod('getMetadata');
$m->setAccessible(true);
if ($key instanceof Request) {
$m1 = $r->getMethod('getCacheKey');
$m1->setAccessible(true);
$key = $m1->invoke($this->store, $key);
}
return $m->invoke($this->store, $key);
}
protected function getStorePath($key)
{
$r = new \ReflectionObject($this->store);
$m = $r->getMethod('getPath');
$m->setAccessible(true);
return $m->invoke($this->store, $key);
}
}

View File

@@ -0,0 +1,93 @@
<?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 Symfony\Component\HttpKernel\HttpKernel;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Controller\ControllerResolverInterface;
use Symfony\Component\EventDispatcher\EventDispatcher;
class TestHttpKernel extends HttpKernel implements ControllerResolverInterface
{
protected $body;
protected $status;
protected $headers;
protected $called;
protected $customizer;
protected $catch;
protected $backendRequest;
public function __construct($body, $status, $headers, \Closure $customizer = null)
{
$this->body = $body;
$this->status = $status;
$this->headers = $headers;
$this->customizer = $customizer;
$this->called = false;
$this->catch = false;
parent::__construct(new EventDispatcher(), $this);
}
public function getBackendRequest()
{
return $this->backendRequest;
}
public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = false)
{
$this->catch = $catch;
$this->backendRequest = $request;
return parent::handle($request, $type, $catch);
}
public function isCatchingExceptions()
{
return $this->catch;
}
public function getController(Request $request)
{
return array($this, 'callController');
}
public function getArguments(Request $request, $controller)
{
return array($request);
}
public function callController(Request $request)
{
$this->called = true;
$response = new Response($this->body, $this->status, $this->headers);
if (null !== $this->customizer) {
call_user_func($this->customizer, $request, $response);
}
return $response;
}
public function hasBeenCalled()
{
return $this->called;
}
public function reset()
{
$this->called = false;
}
}

View File

@@ -0,0 +1,86 @@
<?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 Symfony\Component\HttpKernel\HttpKernel;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Controller\ControllerResolverInterface;
use Symfony\Component\EventDispatcher\EventDispatcher;
class TestMultipleHttpKernel extends HttpKernel implements ControllerResolverInterface
{
protected $bodies;
protected $statuses;
protected $headers;
protected $catch;
protected $call;
protected $backendRequest;
public function __construct($responses)
{
$this->bodies = array();
$this->statuses = array();
$this->headers = array();
$this->call = false;
foreach ($responses as $response) {
$this->bodies[] = $response['body'];
$this->statuses[] = $response['status'];
$this->headers[] = $response['headers'];
}
parent::__construct(new EventDispatcher(), $this);
}
public function getBackendRequest()
{
return $this->backendRequest;
}
public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = false)
{
$this->backendRequest = $request;
return parent::handle($request, $type, $catch);
}
public function getController(Request $request)
{
return array($this, 'callController');
}
public function getArguments(Request $request, $controller)
{
return array($request);
}
public function callController(Request $request)
{
$this->called = true;
$response = new Response(array_shift($this->bodies), array_shift($this->statuses), array_shift($this->headers));
return $response;
}
public function hasBeenCalled()
{
return $this->called;
}
public function reset()
{
$this->call = false;
}
}

View File

@@ -0,0 +1,297 @@
<?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;
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
{
protected function setUp()
{
if (!class_exists('Symfony\Component\EventDispatcher\EventDispatcher')) {
$this->markTestSkipped('The "EventDispatcher" component is not available');
}
if (!class_exists('Symfony\Component\HttpFoundation\Request')) {
$this->markTestSkipped('The "HttpFoundation" component is not available');
}
}
/**
* @expectedException RuntimeException
*/
public function testHandleWhenControllerThrowsAnExceptionAndRawIsTrue()
{
$kernel = new HttpKernel(new EventDispatcher(), $this->getResolver(function () { throw new \RuntimeException(); }));
$kernel->handle(new Request(), HttpKernelInterface::MASTER_REQUEST, true);
}
/**
* @expectedException RuntimeException
*/
public function testHandleWhenControllerThrowsAnExceptionAndRawIsFalseAndNoListenerIsRegistered()
{
$kernel = new HttpKernel(new EventDispatcher(), $this->getResolver(function () { throw new \RuntimeException(); }));
$kernel->handle(new Request(), HttpKernelInterface::MASTER_REQUEST, false);
}
public function testHandleWhenControllerThrowsAnExceptionAndRawIsFalse()
{
$dispatcher = new EventDispatcher();
$dispatcher->addListener(KernelEvents::EXCEPTION, function ($event) {
$event->setResponse(new Response($event->getException()->getMessage()));
});
$kernel = new HttpKernel($dispatcher, $this->getResolver(function () { throw new \RuntimeException('foo'); }));
$response = $kernel->handle(new Request());
$this->assertEquals('500', $response->getStatusCode());
$this->assertEquals('foo', $response->getContent());
}
public function testHandleExceptionWithARedirectionResponse()
{
$dispatcher = new EventDispatcher();
$dispatcher->addListener(KernelEvents::EXCEPTION, function ($event) {
$event->setResponse(new RedirectResponse('/login', 301));
});
$kernel = new HttpKernel($dispatcher, $this->getResolver(function () { throw new AccessDeniedHttpException(); }));
$response = $kernel->handle(new Request());
$this->assertEquals('301', $response->getStatusCode());
$this->assertEquals('/login', $response->headers->get('Location'));
}
public function testHandleHttpException()
{
$dispatcher = new EventDispatcher();
$dispatcher->addListener(KernelEvents::EXCEPTION, function ($event) {
$event->setResponse(new Response($event->getException()->getMessage()));
});
$kernel = new HttpKernel($dispatcher, $this->getResolver(function () { throw new MethodNotAllowedHttpException(array('POST')); }));
$response = $kernel->handle(new Request());
$this->assertEquals('405', $response->getStatusCode());
$this->assertEquals('POST', $response->headers->get('Allow'));
}
/**
* @dataProvider getStatusCodes
*/
public function testHandleWhenAnExceptionIsHandledWithASpecificStatusCode($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(); }));
$response = $kernel->handle(new Request());
$this->assertEquals($expectedStatusCode, $response->getStatusCode());
$this->assertFalse($response->headers->has('X-Status-Code'));
}
public function getStatusCodes()
{
return array(
array(200, 404),
array(404, 200),
array(301, 200),
array(500, 200),
);
}
public function testHandleWhenAListenerReturnsAResponse()
{
$dispatcher = new EventDispatcher();
$dispatcher->addListener(KernelEvents::REQUEST, function ($event) {
$event->setResponse(new Response('hello'));
});
$kernel = new HttpKernel($dispatcher, $this->getResolver());
$this->assertEquals('hello', $kernel->handle(new Request())->getContent());
}
/**
* @expectedException \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
*/
public function testHandleWhenNoControllerIsFound()
{
$dispatcher = new EventDispatcher();
$kernel = new HttpKernel($dispatcher, $this->getResolver(false));
$kernel->handle(new Request());
}
/**
* @expectedException LogicException
*/
public function testHandleWhenTheControllerIsNotACallable()
{
$dispatcher = new EventDispatcher();
$kernel = new HttpKernel($dispatcher, $this->getResolver('foobar'));
$kernel->handle(new Request());
}
public function testHandleWhenTheControllerIsAClosure()
{
$response = new Response('foo');
$dispatcher = new EventDispatcher();
$kernel = new HttpKernel($dispatcher, $this->getResolver(function () use ($response) { return $response; }));
$this->assertSame($response, $kernel->handle(new Request()));
}
public function testHandleWhenTheControllerIsAnObjectWithInvoke()
{
$dispatcher = new EventDispatcher();
$kernel = new HttpKernel($dispatcher, $this->getResolver(new Controller()));
$this->assertResponseEquals(new Response('foo'), $kernel->handle(new Request()));
}
public function testHandleWhenTheControllerIsAFunction()
{
$dispatcher = new EventDispatcher();
$kernel = new HttpKernel($dispatcher, $this->getResolver('Symfony\Component\HttpKernel\Tests\controller_func'));
$this->assertResponseEquals(new Response('foo'), $kernel->handle(new Request()));
}
public function testHandleWhenTheControllerIsAnArray()
{
$dispatcher = new EventDispatcher();
$kernel = new HttpKernel($dispatcher, $this->getResolver(array(new Controller(), 'controller')));
$this->assertResponseEquals(new Response('foo'), $kernel->handle(new Request()));
}
public function testHandleWhenTheControllerIsAStaticArray()
{
$dispatcher = new EventDispatcher();
$kernel = new HttpKernel($dispatcher, $this->getResolver(array('Symfony\Component\HttpKernel\Tests\Controller', 'staticcontroller')));
$this->assertResponseEquals(new Response('foo'), $kernel->handle(new Request()));
}
/**
* @expectedException LogicException
*/
public function testHandleWhenTheControllerDoesNotReturnAResponse()
{
$dispatcher = new EventDispatcher();
$kernel = new HttpKernel($dispatcher, $this->getResolver(function () { return 'foo'; }));
$kernel->handle(new Request());
}
public function testHandleWhenTheControllerDoesNotReturnAResponseButAViewIsRegistered()
{
$dispatcher = new EventDispatcher();
$dispatcher->addListener(KernelEvents::VIEW, function ($event) {
$event->setResponse(new Response($event->getControllerResult()));
});
$kernel = new HttpKernel($dispatcher, $this->getResolver(function () { return 'foo'; }));
$this->assertEquals('foo', $kernel->handle(new Request())->getContent());
}
public function testHandleWithAResponseListener()
{
$dispatcher = new EventDispatcher();
$dispatcher->addListener(KernelEvents::RESPONSE, function ($event) {
$event->setResponse(new Response('foo'));
});
$kernel = new HttpKernel($dispatcher, $this->getResolver());
$this->assertEquals('foo', $kernel->handle(new Request())->getContent());
}
public function testTerminate()
{
$dispatcher = new EventDispatcher();
$kernel = new HttpKernel($dispatcher, $this->getResolver());
$dispatcher->addListener(KernelEvents::TERMINATE, function ($event) use (&$called, &$capturedKernel, &$capturedRequest, &$capturedResponse) {
$called = true;
$capturedKernel = $event->getKernel();
$capturedRequest = $event->getRequest();
$capturedResponse = $event->getResponse();
});
$kernel->terminate($request = Request::create('/'), $response = new Response());
$this->assertTrue($called);
$this->assertEquals($kernel, $capturedKernel);
$this->assertEquals($request, $capturedRequest);
$this->assertEquals($response, $capturedResponse);
}
protected function getResolver($controller = null)
{
if (null === $controller) {
$controller = function() { return new Response('Hello'); };
}
$resolver = $this->getMock('Symfony\\Component\\HttpKernel\\Controller\\ControllerResolverInterface');
$resolver->expects($this->any())
->method('getController')
->will($this->returnValue($controller));
$resolver->expects($this->any())
->method('getArguments')
->will($this->returnValue(array()));
return $resolver;
}
protected function assertResponseEquals(Response $expected, Response $actual)
{
$expected->setDate($actual->getDate());
$this->assertEquals($expected, $actual);
}
}
class Controller
{
public function __invoke()
{
return new Response('foo');
}
public function controller()
{
return new Response('foo');
}
public static function staticController()
{
return new Response('foo');
}
}
function controller_func()
{
return new Response('foo');
}

View File

@@ -0,0 +1,875 @@
<?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;
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Tests\Fixtures\KernelForTest;
use Symfony\Component\HttpKernel\Tests\Fixtures\KernelForOverrideName;
use Symfony\Component\HttpKernel\Tests\Fixtures\FooBarBundle;
class KernelTest extends \PHPUnit_Framework_TestCase
{
protected function setUp()
{
if (!class_exists('Symfony\Component\DependencyInjection\Container')) {
$this->markTestSkipped('The "DependencyInjection" component is not available');
}
}
public function testConstructor()
{
$env = 'test_env';
$debug = true;
$kernel = new KernelForTest($env, $debug);
$this->assertEquals($env, $kernel->getEnvironment());
$this->assertEquals($debug, $kernel->isDebug());
$this->assertFalse($kernel->isBooted());
$this->assertLessThanOrEqual(microtime(true), $kernel->getStartTime());
$this->assertNull($kernel->getContainer());
}
public function testClone()
{
$env = 'test_env';
$debug = true;
$kernel = new KernelForTest($env, $debug);
$clone = clone $kernel;
$this->assertEquals($env, $clone->getEnvironment());
$this->assertEquals($debug, $clone->isDebug());
$this->assertFalse($clone->isBooted());
$this->assertLessThanOrEqual(microtime(true), $clone->getStartTime());
$this->assertNull($clone->getContainer());
}
public function testBootInitializesBundlesAndContainer()
{
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\Tests\Fixtures\KernelForTest')
->disableOriginalConstructor()
->setMethods(array('initializeBundles', 'initializeContainer', 'getBundles'))
->getMock();
$kernel->expects($this->once())
->method('initializeBundles');
$kernel->expects($this->once())
->method('initializeContainer');
$kernel->expects($this->once())
->method('getBundles')
->will($this->returnValue(array()));
$kernel->boot();
}
public function testBootSetsTheContainerToTheBundles()
{
$bundle = $this->getMockBuilder('Symfony\Component\HttpKernel\Bundle\Bundle')
->disableOriginalConstructor()
->getMock();
$bundle->expects($this->once())
->method('setContainer');
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\Tests\Fixtures\KernelForTest')
->disableOriginalConstructor()
->setMethods(array('initializeBundles', 'initializeContainer', 'getBundles'))
->getMock();
$kernel->expects($this->once())
->method('getBundles')
->will($this->returnValue(array($bundle)));
$kernel->boot();
}
public function testBootSetsTheBootedFlagToTrue()
{
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\Tests\Fixtures\KernelForTest')
->disableOriginalConstructor()
->setMethods(array('initializeBundles', 'initializeContainer', 'getBundles'))
->getMock();
$kernel->expects($this->once())
->method('getBundles')
->will($this->returnValue(array()));
$kernel->boot();
$this->assertTrue($kernel->isBooted());
}
public function testClassCacheIsLoaded()
{
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\Tests\Fixtures\KernelForTest')
->disableOriginalConstructor()
->setMethods(array('initializeBundles', 'initializeContainer', 'getBundles', 'doLoadClassCache'))
->getMock();
$kernel->loadClassCache('name', '.extension');
$kernel->expects($this->any())
->method('getBundles')
->will($this->returnValue(array()));
$kernel->expects($this->once())
->method('doLoadClassCache')
->with('name', '.extension');
$kernel->boot();
}
public function testClassCacheIsNotLoadedByDefault()
{
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\Tests\Fixtures\KernelForTest')
->disableOriginalConstructor()
->setMethods(array('initializeBundles', 'initializeContainer', 'getBundles', 'doLoadClassCache'))
->getMock();
$kernel->expects($this->any())
->method('getBundles')
->will($this->returnValue(array()));
$kernel->expects($this->never())
->method('doLoadClassCache');
$kernel->boot();
}
public function testClassCacheIsNotLoadedWhenKernelIsNotBooted()
{
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\Tests\Fixtures\KernelForTest')
->disableOriginalConstructor()
->setMethods(array('initializeBundles', 'initializeContainer', 'getBundles', 'doLoadClassCache'))
->getMock();
$kernel->loadClassCache();
$kernel->expects($this->any())
->method('getBundles')
->will($this->returnValue(array()));
$kernel->expects($this->never())
->method('doLoadClassCache');
}
public function testBootKernelSeveralTimesOnlyInitializesBundlesOnce()
{
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\Tests\Fixtures\KernelForTest')
->disableOriginalConstructor()
->setMethods(array('initializeBundles', 'initializeContainer', 'getBundles'))
->getMock();
$kernel->expects($this->once())
->method('getBundles')
->will($this->returnValue(array()));
$kernel->boot();
$kernel->boot();
}
public function testShutdownCallsShutdownOnAllBundles()
{
$bundle = $this->getMockBuilder('Symfony\Component\HttpKernel\Bundle\Bundle')
->disableOriginalConstructor()
->getMock();
$bundle->expects($this->once())
->method('shutdown');
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\Tests\Fixtures\KernelForTest')
->disableOriginalConstructor()
->setMethods(array('getBundles'))
->getMock();
$kernel->expects($this->once())
->method('getBundles')
->will($this->returnValue(array($bundle)));
$kernel->shutdown();
}
public function testShutdownGivesNullContainerToAllBundles()
{
$bundle = $this->getMockBuilder('Symfony\Component\HttpKernel\Bundle\Bundle')
->disableOriginalConstructor()
->getMock();
$bundle->expects($this->once())
->method('setContainer')
->with(null);
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\Tests\Fixtures\KernelForTest')
->disableOriginalConstructor()
->setMethods(array('getBundles'))
->getMock();
$kernel->expects($this->once())
->method('getBundles')
->will($this->returnValue(array($bundle)));
$kernel->shutdown();
}
public function testHandleCallsHandleOnHttpKernel()
{
$type = HttpKernelInterface::MASTER_REQUEST;
$catch = true;
$request = new Request();
$httpKernelMock = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernel')
->disableOriginalConstructor()
->getMock();
$httpKernelMock
->expects($this->once())
->method('handle')
->with($request, $type, $catch);
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\Tests\Fixtures\KernelForTest')
->disableOriginalConstructor()
->setMethods(array('getHttpKernel'))
->getMock();
$kernel->expects($this->once())
->method('getHttpKernel')
->will($this->returnValue($httpKernelMock));
$kernel->handle($request, $type, $catch);
}
public function testHandleBootsTheKernel()
{
$type = HttpKernelInterface::MASTER_REQUEST;
$catch = true;
$request = new Request();
$httpKernelMock = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernel')
->disableOriginalConstructor()
->getMock();
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\Tests\Fixtures\KernelForTest')
->disableOriginalConstructor()
->setMethods(array('getHttpKernel', 'boot'))
->getMock();
$kernel->expects($this->once())
->method('getHttpKernel')
->will($this->returnValue($httpKernelMock));
$kernel->expects($this->once())
->method('boot');
// required as this value is initialized
// in the kernel constructor, which we don't call
$kernel->setIsBooted(false);
$kernel->handle($request, $type, $catch);
}
public function testStripComments()
{
if (!function_exists('token_get_all')) {
$this->markTestSkipped('The function token_get_all() is not available.');
return;
}
$source = <<<'EOF'
<?php
$string = 'string should not be modified';
$heredoc = <<<HD
Heredoc should not be modified
HD;
$nowdoc = <<<'ND'
Nowdoc should not be modified
ND;
/**
* some class comments to strip
*/
class TestClass
{
/**
* some method comments to strip
*/
public function doStuff()
{
// inline comment
}
}
EOF;
$expected = <<<'EOF'
<?php
$string = 'string should not be modified';
$heredoc =
<<<HD
Heredoc should not be modified
HD;
$nowdoc =
<<<'ND'
Nowdoc should not be modified
ND;
class TestClass
{
public function doStuff()
{
}
}
EOF;
$output = Kernel::stripComments($source);
// Heredocs are preserved, making the output mixing unix and windows line
// endings, switching to "\n" everywhere on windows to avoid failure.
if (defined('PHP_WINDOWS_VERSION_MAJOR')) {
$expected = str_replace("\r\n", "\n", $expected);
$output = str_replace("\r\n", "\n", $output);
}
$this->assertEquals($expected, $output);
}
public function testIsClassInActiveBundleFalse()
{
$kernel = $this->getKernelMockForIsClassInActiveBundleTest();
$this->assertFalse($kernel->isClassInActiveBundle('Not\In\Active\Bundle'));
}
public function testIsClassInActiveBundleFalseNoNamespace()
{
$kernel = $this->getKernelMockForIsClassInActiveBundleTest();
$this->assertFalse($kernel->isClassInActiveBundle('NotNamespacedClass'));
}
public function testIsClassInActiveBundleTrue()
{
$kernel = $this->getKernelMockForIsClassInActiveBundleTest();
$this->assertTrue($kernel->isClassInActiveBundle(__NAMESPACE__.'\Fixtures\FooBarBundle\SomeClass'));
}
protected function getKernelMockForIsClassInActiveBundleTest()
{
$bundle = new FooBarBundle();
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\Tests\Fixtures\KernelForTest')
->disableOriginalConstructor()
->setMethods(array('getBundles'))
->getMock();
$kernel->expects($this->once())
->method('getBundles')
->will($this->returnValue(array($bundle)));
return $kernel;
}
public function testGetRootDir()
{
$kernel = new KernelForTest('test', true);
$this->assertEquals(__DIR__.DIRECTORY_SEPARATOR.'Fixtures', realpath($kernel->getRootDir()));
}
public function testGetName()
{
$kernel = new KernelForTest('test', true);
$this->assertEquals('Fixtures', $kernel->getName());
}
public function testOverrideGetName()
{
$kernel = new KernelForOverrideName('test', true);
$this->assertEquals('overridden', $kernel->getName());
}
public function testSerialize()
{
$env = 'test_env';
$debug = true;
$kernel = new KernelForTest($env, $debug);
$expected = serialize(array($env, $debug));
$this->assertEquals($expected, $kernel->serialize());
}
/**
* @expectedException \InvalidArgumentException
*/
public function testLocateResourceThrowsExceptionWhenNameIsNotValid()
{
$this->getKernelForInvalidLocateResource()->locateResource('Foo');
}
/**
* @expectedException \RuntimeException
*/
public function testLocateResourceThrowsExceptionWhenNameIsUnsafe()
{
$this->getKernelForInvalidLocateResource()->locateResource('@FooBundle/../bar');
}
/**
* @expectedException \InvalidArgumentException
*/
public function testLocateResourceThrowsExceptionWhenBundleDoesNotExist()
{
$this->getKernelForInvalidLocateResource()->locateResource('@FooBundle/config/routing.xml');
}
/**
* @expectedException \InvalidArgumentException
*/
public function testLocateResourceThrowsExceptionWhenResourceDoesNotExist()
{
$kernel = $this->getKernel();
$kernel
->expects($this->once())
->method('getBundle')
->will($this->returnValue(array($this->getBundle(__DIR__.'/Fixtures/Bundle1Bundle'))))
;
$kernel->locateResource('@Bundle1Bundle/config/routing.xml');
}
public function testLocateResourceReturnsTheFirstThatMatches()
{
$kernel = $this->getKernel();
$kernel
->expects($this->once())
->method('getBundle')
->will($this->returnValue(array($this->getBundle(__DIR__.'/Fixtures/Bundle1Bundle'))))
;
$this->assertEquals(__DIR__.'/Fixtures/Bundle1Bundle/foo.txt', $kernel->locateResource('@Bundle1Bundle/foo.txt'));
}
public function testLocateResourceReturnsTheFirstThatMatchesWithParent()
{
$parent = $this->getBundle(__DIR__.'/Fixtures/Bundle1Bundle');
$child = $this->getBundle(__DIR__.'/Fixtures/Bundle2Bundle');
$kernel = $this->getKernel();
$kernel
->expects($this->exactly(2))
->method('getBundle')
->will($this->returnValue(array($child, $parent)))
;
$this->assertEquals(__DIR__.'/Fixtures/Bundle2Bundle/foo.txt', $kernel->locateResource('@ParentAABundle/foo.txt'));
$this->assertEquals(__DIR__.'/Fixtures/Bundle1Bundle/bar.txt', $kernel->locateResource('@ParentAABundle/bar.txt'));
}
public function testLocateResourceReturnsAllMatches()
{
$parent = $this->getBundle(__DIR__.'/Fixtures/Bundle1Bundle');
$child = $this->getBundle(__DIR__.'/Fixtures/Bundle2Bundle');
$kernel = $this->getKernel();
$kernel
->expects($this->once())
->method('getBundle')
->will($this->returnValue(array($child, $parent)))
;
$this->assertEquals(array(
__DIR__.'/Fixtures/Bundle2Bundle/foo.txt',
__DIR__.'/Fixtures/Bundle1Bundle/foo.txt'),
$kernel->locateResource('@Bundle1Bundle/foo.txt', null, false));
}
public function testLocateResourceReturnsAllMatchesBis()
{
$kernel = $this->getKernel();
$kernel
->expects($this->once())
->method('getBundle')
->will($this->returnValue(array(
$this->getBundle(__DIR__.'/Fixtures/Bundle1Bundle'),
$this->getBundle(__DIR__.'/Foobar')
)))
;
$this->assertEquals(
array(__DIR__.'/Fixtures/Bundle1Bundle/foo.txt'),
$kernel->locateResource('@Bundle1Bundle/foo.txt', null, false)
);
}
public function testLocateResourceIgnoresDirOnNonResource()
{
$kernel = $this->getKernel();
$kernel
->expects($this->once())
->method('getBundle')
->will($this->returnValue(array($this->getBundle(__DIR__.'/Fixtures/Bundle1Bundle'))))
;
$this->assertEquals(
__DIR__.'/Fixtures/Bundle1Bundle/foo.txt',
$kernel->locateResource('@Bundle1Bundle/foo.txt', __DIR__.'/Fixtures')
);
}
public function testLocateResourceReturnsTheDirOneForResources()
{
$kernel = $this->getKernel();
$kernel
->expects($this->once())
->method('getBundle')
->will($this->returnValue(array($this->getBundle(__DIR__.'/Fixtures/FooBundle', null, null, 'FooBundle'))))
;
$this->assertEquals(
__DIR__.'/Fixtures/Resources/FooBundle/foo.txt',
$kernel->locateResource('@FooBundle/Resources/foo.txt', __DIR__.'/Fixtures/Resources')
);
}
public function testLocateResourceReturnsTheDirOneForResourcesAndBundleOnes()
{
$kernel = $this->getKernel();
$kernel
->expects($this->once())
->method('getBundle')
->will($this->returnValue(array($this->getBundle(__DIR__.'/Fixtures/Bundle1Bundle', null, null, 'Bundle1Bundle'))))
;
$this->assertEquals(array(
__DIR__.'/Fixtures/Resources/Bundle1Bundle/foo.txt',
__DIR__.'/Fixtures/Bundle1Bundle/Resources/foo.txt'),
$kernel->locateResource('@Bundle1Bundle/Resources/foo.txt', __DIR__.'/Fixtures/Resources', false)
);
}
public function testLocateResourceOverrideBundleAndResourcesFolders()
{
$parent = $this->getBundle(__DIR__.'/Fixtures/BaseBundle', null, 'BaseBundle', 'BaseBundle');
$child = $this->getBundle(__DIR__.'/Fixtures/ChildBundle', 'ParentBundle', 'ChildBundle', 'ChildBundle');
$kernel = $this->getKernel();
$kernel
->expects($this->exactly(4))
->method('getBundle')
->will($this->returnValue(array($child, $parent)))
;
$this->assertEquals(array(
__DIR__.'/Fixtures/Resources/ChildBundle/foo.txt',
__DIR__.'/Fixtures/ChildBundle/Resources/foo.txt',
__DIR__.'/Fixtures/BaseBundle/Resources/foo.txt',
),
$kernel->locateResource('@BaseBundle/Resources/foo.txt', __DIR__.'/Fixtures/Resources', false)
);
$this->assertEquals(
__DIR__.'/Fixtures/Resources/ChildBundle/foo.txt',
$kernel->locateResource('@BaseBundle/Resources/foo.txt', __DIR__.'/Fixtures/Resources')
);
try {
$kernel->locateResource('@BaseBundle/Resources/hide.txt', __DIR__.'/Fixtures/Resources', false);
$this->fail('Hidden resources should raise an exception when returning an array of matching paths');
} catch (\RuntimeException $e) {
}
try {
$kernel->locateResource('@BaseBundle/Resources/hide.txt', __DIR__.'/Fixtures/Resources', true);
$this->fail('Hidden resources should raise an exception when returning the first matching path');
} catch (\RuntimeException $e) {
}
}
public function testLocateResourceOnDirectories()
{
$kernel = $this->getKernel();
$kernel
->expects($this->exactly(2))
->method('getBundle')
->will($this->returnValue(array($this->getBundle(__DIR__.'/Fixtures/FooBundle', null, null, 'FooBundle'))))
;
$this->assertEquals(
__DIR__.'/Fixtures/Resources/FooBundle/',
$kernel->locateResource('@FooBundle/Resources/', __DIR__.'/Fixtures/Resources')
);
$this->assertEquals(
__DIR__.'/Fixtures/Resources/FooBundle',
$kernel->locateResource('@FooBundle/Resources', __DIR__.'/Fixtures/Resources')
);
$kernel = $this->getKernel();
$kernel
->expects($this->exactly(2))
->method('getBundle')
->will($this->returnValue(array($this->getBundle(__DIR__.'/Fixtures/Bundle1Bundle', null, null, 'Bundle1Bundle'))))
;
$this->assertEquals(
__DIR__.'/Fixtures/Bundle1Bundle/Resources/',
$kernel->locateResource('@Bundle1Bundle/Resources/')
);
$this->assertEquals(
__DIR__.'/Fixtures/Bundle1Bundle/Resources',
$kernel->locateResource('@Bundle1Bundle/Resources')
);
}
public function testInitializeBundles()
{
$parent = $this->getBundle(null, null, 'ParentABundle');
$child = $this->getBundle(null, 'ParentABundle', 'ChildABundle');
$kernel = $this->getKernel();
$kernel
->expects($this->once())
->method('registerBundles')
->will($this->returnValue(array($parent, $child)))
;
$kernel->initializeBundles();
$map = $kernel->getBundleMap();
$this->assertEquals(array($child, $parent), $map['ParentABundle']);
}
public function testInitializeBundlesSupportInheritanceCascade()
{
$grandparent = $this->getBundle(null, null, 'GrandParentBBundle');
$parent = $this->getBundle(null, 'GrandParentBBundle', 'ParentBBundle');
$child = $this->getBundle(null, 'ParentBBundle', 'ChildBBundle');
$kernel = $this->getKernel();
$kernel
->expects($this->once())
->method('registerBundles')
->will($this->returnValue(array($grandparent, $parent, $child)))
;
$kernel->initializeBundles();
$map = $kernel->getBundleMap();
$this->assertEquals(array($child, $parent, $grandparent), $map['GrandParentBBundle']);
$this->assertEquals(array($child, $parent), $map['ParentBBundle']);
$this->assertEquals(array($child), $map['ChildBBundle']);
}
/**
* @expectedException \LogicException
*/
public function testInitializeBundlesThrowsExceptionWhenAParentDoesNotExists()
{
$child = $this->getBundle(null, 'FooBar', 'ChildCBundle');
$kernel = $this->getKernel();
$kernel
->expects($this->once())
->method('registerBundles')
->will($this->returnValue(array($child)))
;
$kernel->initializeBundles();
}
public function testInitializeBundlesSupportsArbitraryBundleRegistrationOrder()
{
$grandparent = $this->getBundle(null, null, 'GrandParentCCundle');
$parent = $this->getBundle(null, 'GrandParentCCundle', 'ParentCCundle');
$child = $this->getBundle(null, 'ParentCCundle', 'ChildCCundle');
$kernel = $this->getKernel();
$kernel
->expects($this->once())
->method('registerBundles')
->will($this->returnValue(array($parent, $grandparent, $child)))
;
$kernel->initializeBundles();
$map = $kernel->getBundleMap();
$this->assertEquals(array($child, $parent, $grandparent), $map['GrandParentCCundle']);
$this->assertEquals(array($child, $parent), $map['ParentCCundle']);
$this->assertEquals(array($child), $map['ChildCCundle']);
}
/**
* @expectedException \LogicException
*/
public function testInitializeBundlesThrowsExceptionWhenABundleIsDirectlyExtendedByTwoBundles()
{
$parent = $this->getBundle(null, null, 'ParentCBundle');
$child1 = $this->getBundle(null, 'ParentCBundle', 'ChildC1Bundle');
$child2 = $this->getBundle(null, 'ParentCBundle', 'ChildC2Bundle');
$kernel = $this->getKernel();
$kernel
->expects($this->once())
->method('registerBundles')
->will($this->returnValue(array($parent, $child1, $child2)))
;
$kernel->initializeBundles();
}
/**
* @expectedException \LogicException
*/
public function testInitializeBundleThrowsExceptionWhenRegisteringTwoBundlesWithTheSameName()
{
$fooBundle = $this->getBundle(null, null, 'FooBundle', 'DuplicateName');
$barBundle = $this->getBundle(null, null, 'BarBundle', 'DuplicateName');
$kernel = $this->getKernel();
$kernel
->expects($this->once())
->method('registerBundles')
->will($this->returnValue(array($fooBundle, $barBundle)))
;
$kernel->initializeBundles();
}
/**
* @expectedException \LogicException
*/
public function testInitializeBundleThrowsExceptionWhenABundleExtendsItself()
{
$circularRef = $this->getBundle(null, 'CircularRefBundle', 'CircularRefBundle');
$kernel = $this->getKernel();
$kernel
->expects($this->once())
->method('registerBundles')
->will($this->returnValue(array($circularRef)))
;
$kernel->initializeBundles();
}
public function testTerminateReturnsSilentlyIfKernelIsNotBooted()
{
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\Tests\Fixtures\KernelForTest')
->disableOriginalConstructor()
->setMethods(array('getHttpKernel'))
->getMock();
$kernel->expects($this->never())
->method('getHttpKernel');
$kernel->setIsBooted(false);
$kernel->terminate(Request::create('/'), new Response());
}
public function testTerminateDelegatesTerminationOnlyForTerminableInterface()
{
// does not implement TerminableInterface
$httpKernelMock = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')
->disableOriginalConstructor()
->getMock();
$httpKernelMock
->expects($this->never())
->method('terminate');
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\Tests\Fixtures\KernelForTest')
->disableOriginalConstructor()
->setMethods(array('getHttpKernel'))
->getMock();
$kernel->expects($this->once())
->method('getHttpKernel')
->will($this->returnValue($httpKernelMock));
$kernel->setIsBooted(true);
$kernel->terminate(Request::create('/'), new Response());
// implements TerminableInterface
$httpKernelMock = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernel')
->disableOriginalConstructor()
->setMethods(array('terminate'))
->getMock();
$httpKernelMock
->expects($this->once())
->method('terminate');
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\Tests\Fixtures\KernelForTest')
->disableOriginalConstructor()
->setMethods(array('getHttpKernel'))
->getMock();
$kernel->expects($this->exactly(2))
->method('getHttpKernel')
->will($this->returnValue($httpKernelMock));
$kernel->setIsBooted(true);
$kernel->terminate(Request::create('/'), new Response());
}
protected function getBundle($dir = null, $parent = null, $className = null, $bundleName = null)
{
$bundle = $this
->getMockBuilder('Symfony\Component\HttpKernel\Bundle\BundleInterface')
->setMethods(array('getPath', 'getParent', 'getName'))
->disableOriginalConstructor()
;
if ($className) {
$bundle->setMockClassName($className);
}
$bundle = $bundle->getMockForAbstractClass();
$bundle
->expects($this->any())
->method('getName')
->will($this->returnValue(null === $bundleName ? get_class($bundle) : $bundleName))
;
$bundle
->expects($this->any())
->method('getPath')
->will($this->returnValue($dir))
;
$bundle
->expects($this->any())
->method('getParent')
->will($this->returnValue($parent))
;
return $bundle;
}
protected function getKernel()
{
return $this
->getMockBuilder('Symfony\Component\HttpKernel\Tests\Fixtures\KernelForTest')
->setMethods(array('getBundle', 'registerBundles'))
->disableOriginalConstructor()
->getMock()
;
}
protected function getKernelForInvalidLocateResource()
{
return $this
->getMockBuilder('Symfony\Component\HttpKernel\Kernel')
->disableOriginalConstructor()
->getMockForAbstractClass()
;
}
}

View File

@@ -0,0 +1,128 @@
<?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;
use Psr\Log\LoggerInterface;
class Logger implements LoggerInterface
{
protected $logs;
public function __construct()
{
$this->clear();
}
public function getLogs($level = false)
{
return false === $level ? $this->logs : $this->logs[$level];
}
public function clear()
{
$this->logs = array(
'emergency' => array(),
'alert' => array(),
'critical' => array(),
'error' => array(),
'warning' => array(),
'notice' => array(),
'info' => array(),
'debug' => array(),
);
}
public function log($level, $message, array $context = array())
{
$this->logs[$level][] = $message;
}
public function emergency($message, array $context = array())
{
$this->log('emergency', $message, $context);
}
public function alert($message, array $context = array())
{
$this->log('alert', $message, $context);
}
public function critical($message, array $context = array())
{
$this->log('critical', $message, $context);
}
public function error($message, array $context = array())
{
$this->log('error', $message, $context);
}
public function warning($message, array $context = array())
{
$this->log('warning', $message, $context);
}
public function notice($message, array $context = array())
{
$this->log('notice', $message, $context);
}
public function info($message, array $context = array())
{
$this->log('info', $message, $context);
}
public function debug($message, array $context = array())
{
$this->log('debug', $message, $context);
}
/**
* @deprecated
*/
public function emerg($message, array $context = array())
{
trigger_error('Use emergency() which is PSR-3 compatible', E_USER_DEPRECATED);
$this->log('emergency', $message, $context);
}
/**
* @deprecated
*/
public function crit($message, array $context = array())
{
trigger_error('Use crit() which is PSR-3 compatible', E_USER_DEPRECATED);
$this->log('critical', $message, $context);
}
/**
* @deprecated
*/
public function err($message, array $context = array())
{
trigger_error('Use err() which is PSR-3 compatible', E_USER_DEPRECATED);
$this->log('error', $message, $context);
}
/**
* @deprecated
*/
public function warn($message, array $context = array())
{
trigger_error('Use warn() which is PSR-3 compatible', E_USER_DEPRECATED);
$this->log('warning', $message, $context);
}
}

View File

@@ -0,0 +1,253 @@
<?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\Profiler;
use Symfony\Component\HttpKernel\Profiler\Profile;
abstract class AbstractProfilerStorageTest extends \PHPUnit_Framework_TestCase
{
public function testStore()
{
for ($i = 0; $i < 10; $i ++) {
$profile = new Profile('token_'.$i);
$profile->setIp('127.0.0.1');
$profile->setUrl('http://foo.bar');
$profile->setMethod('GET');
$this->getStorage()->write($profile);
}
$this->assertCount(10, $this->getStorage()->find('127.0.0.1', 'http://foo.bar', 20, 'GET'), '->write() stores data in the storage');
}
public function testChildren()
{
$parentProfile = new Profile('token_parent');
$parentProfile->setIp('127.0.0.1');
$parentProfile->setUrl('http://foo.bar/parent');
$childProfile = new Profile('token_child');
$childProfile->setIp('127.0.0.1');
$childProfile->setUrl('http://foo.bar/child');
$parentProfile->addChild($childProfile);
$this->getStorage()->write($parentProfile);
$this->getStorage()->write($childProfile);
// Load them from storage
$parentProfile = $this->getStorage()->read('token_parent');
$childProfile = $this->getStorage()->read('token_child');
// Check child has link to parent
$this->assertNotNull($childProfile->getParent());
$this->assertEquals($parentProfile->getToken(), $childProfile->getParentToken());
// Check parent has child
$children = $parentProfile->getChildren();
$this->assertCount(1, $children);
$this->assertEquals($childProfile->getToken(), $children[0]->getToken());
}
public function testStoreSpecialCharsInUrl()
{
// The storage accepts special characters in URLs (Even though URLs are not
// supposed to contain them)
$profile = new Profile('simple_quote');
$profile->setUrl('http://foo.bar/\'');
$this->getStorage()->write($profile);
$this->assertTrue(false !== $this->getStorage()->read('simple_quote'), '->write() accepts single quotes in URL');
$profile = new Profile('double_quote');
$profile->setUrl('http://foo.bar/"');
$this->getStorage()->write($profile);
$this->assertTrue(false !== $this->getStorage()->read('double_quote'), '->write() accepts double quotes in URL');
$profile = new Profile('backslash');
$profile->setUrl('http://foo.bar/\\');
$this->getStorage()->write($profile);
$this->assertTrue(false !== $this->getStorage()->read('backslash'), '->write() accepts backslash in URL');
$profile = new Profile('comma');
$profile->setUrl('http://foo.bar/,');
$this->getStorage()->write($profile);
$this->assertTrue(false !== $this->getStorage()->read('comma'), '->write() accepts comma in URL');
}
public function testStoreDuplicateToken()
{
$profile = new Profile('token');
$profile->setUrl('http://example.com/');
$this->assertTrue($this->getStorage()->write($profile), '->write() returns true when the token is unique');
$profile->setUrl('http://example.net/');
$this->assertTrue($this->getStorage()->write($profile), '->write() returns true when the token is already present in the storage');
$this->assertEquals('http://example.net/', $this->getStorage()->read('token')->getUrl(), '->write() overwrites the current profile data');
$this->assertCount(1, $this->getStorage()->find('', '', 1000, ''), '->find() does not return the same profile twice');
}
public function testRetrieveByIp()
{
$profile = new Profile('token');
$profile->setIp('127.0.0.1');
$profile->setMethod('GET');
$this->getStorage()->write($profile);
$this->assertCount(1, $this->getStorage()->find('127.0.0.1', '', 10, 'GET'), '->find() retrieve a record by IP');
$this->assertCount(0, $this->getStorage()->find('127.0.%.1', '', 10, 'GET'), '->find() does not interpret a "%" as a wildcard in the IP');
$this->assertCount(0, $this->getStorage()->find('127.0._.1', '', 10, 'GET'), '->find() does not interpret a "_" as a wildcard in the IP');
}
public function testRetrieveByUrl()
{
$profile = new Profile('simple_quote');
$profile->setIp('127.0.0.1');
$profile->setUrl('http://foo.bar/\'');
$profile->setMethod('GET');
$this->getStorage()->write($profile);
$profile = new Profile('double_quote');
$profile->setIp('127.0.0.1');
$profile->setUrl('http://foo.bar/"');
$profile->setMethod('GET');
$this->getStorage()->write($profile);
$profile = new Profile('backslash');
$profile->setIp('127.0.0.1');
$profile->setUrl('http://foo\\bar/');
$profile->setMethod('GET');
$this->getStorage()->write($profile);
$profile = new Profile('percent');
$profile->setIp('127.0.0.1');
$profile->setUrl('http://foo.bar/%');
$profile->setMethod('GET');
$this->getStorage()->write($profile);
$profile = new Profile('underscore');
$profile->setIp('127.0.0.1');
$profile->setUrl('http://foo.bar/_');
$profile->setMethod('GET');
$this->getStorage()->write($profile);
$profile = new Profile('semicolon');
$profile->setIp('127.0.0.1');
$profile->setUrl('http://foo.bar/;');
$profile->setMethod('GET');
$this->getStorage()->write($profile);
$this->assertCount(1, $this->getStorage()->find('127.0.0.1', 'http://foo.bar/\'', 10, 'GET'), '->find() accepts single quotes in URLs');
$this->assertCount(1, $this->getStorage()->find('127.0.0.1', 'http://foo.bar/"', 10, 'GET'), '->find() accepts double quotes in URLs');
$this->assertCount(1, $this->getStorage()->find('127.0.0.1', 'http://foo\\bar/', 10, 'GET'), '->find() accepts backslash in URLs');
$this->assertCount(1, $this->getStorage()->find('127.0.0.1', 'http://foo.bar/;', 10, 'GET'), '->find() accepts semicolon in URLs');
$this->assertCount(1, $this->getStorage()->find('127.0.0.1', 'http://foo.bar/%', 10, 'GET'), '->find() does not interpret a "%" as a wildcard in the URL');
$this->assertCount(1, $this->getStorage()->find('127.0.0.1', 'http://foo.bar/_', 10, 'GET'), '->find() does not interpret a "_" as a wildcard in the URL');
}
public function testStoreTime()
{
$dt = new \DateTime('now');
$start = $dt->getTimestamp();
for ($i = 0; $i < 3; $i++) {
$dt->modify('+1 minute');
$profile = new Profile('time_'.$i);
$profile->setIp('127.0.0.1');
$profile->setUrl('http://foo.bar');
$profile->setTime($dt->getTimestamp());
$profile->setMethod('GET');
$this->getStorage()->write($profile);
}
$records = $this->getStorage()->find('', '', 3, 'GET', $start, time() + 3 * 60);
$this->assertCount(3, $records, '->find() returns all previously added records');
$this->assertEquals($records[0]['token'], 'time_2', '->find() returns records ordered by time in descendant order');
$this->assertEquals($records[1]['token'], 'time_1', '->find() returns records ordered by time in descendant order');
$this->assertEquals($records[2]['token'], 'time_0', '->find() returns records ordered by time in descendant order');
$records = $this->getStorage()->find('', '', 3, 'GET', $start, time() + 2 * 60);
$this->assertCount(2, $records, '->find() should return only first two of the previously added records');
}
public function testRetrieveByEmptyUrlAndIp()
{
for ($i = 0; $i < 5; $i++) {
$profile = new Profile('token_'.$i);
$profile->setMethod('GET');
$this->getStorage()->write($profile);
}
$this->assertCount(5, $this->getStorage()->find('', '', 10, 'GET'), '->find() returns all previously added records');
$this->getStorage()->purge();
}
public function testRetrieveByMethodAndLimit()
{
foreach (array('POST', 'GET') as $method) {
for ($i = 0; $i < 5; $i++) {
$profile = new Profile('token_'.$i.$method);
$profile->setMethod($method);
$this->getStorage()->write($profile);
}
}
$this->assertCount(5, $this->getStorage()->find('', '', 5, 'POST'));
$this->getStorage()->purge();
}
public function testPurge()
{
$profile = new Profile('token1');
$profile->setIp('127.0.0.1');
$profile->setUrl('http://example.com/');
$profile->setMethod('GET');
$this->getStorage()->write($profile);
$this->assertTrue(false !== $this->getStorage()->read('token1'));
$this->assertCount(1, $this->getStorage()->find('127.0.0.1', '', 10, 'GET'));
$profile = new Profile('token2');
$profile->setIp('127.0.0.1');
$profile->setUrl('http://example.net/');
$profile->setMethod('GET');
$this->getStorage()->write($profile);
$this->assertTrue(false !== $this->getStorage()->read('token2'));
$this->assertCount(2, $this->getStorage()->find('127.0.0.1', '', 10, 'GET'));
$this->getStorage()->purge();
$this->assertEmpty($this->getStorage()->read('token'), '->purge() removes all data stored by profiler');
$this->assertCount(0, $this->getStorage()->find('127.0.0.1', '', 10, 'GET'), '->purge() removes all items from index');
}
public function testDuplicates()
{
for ($i = 1; $i <= 5; $i++) {
$profile = new Profile('foo'.$i);
$profile->setIp('127.0.0.1');
$profile->setUrl('http://example.net/');
$profile->setMethod('GET');
///three duplicates
$this->getStorage()->write($profile);
$this->getStorage()->write($profile);
$this->getStorage()->write($profile);
}
$this->assertCount(3, $this->getStorage()->find('127.0.0.1', 'http://example.net/', 3, 'GET'), '->find() method returns incorrect number of entries');
}
/**
* @return \Symfony\Component\HttpKernel\Profiler\ProfilerStorageInterface
*/
abstract protected function getStorage();
}

View File

@@ -0,0 +1,100 @@
<?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\Profiler;
use Symfony\Component\HttpKernel\Profiler\FileProfilerStorage;
use Symfony\Component\HttpKernel\Profiler\Profile;
class FileProfilerStorageTest extends AbstractProfilerStorageTest
{
protected static $tmpDir;
protected static $storage;
protected static function cleanDir()
{
$flags = \FilesystemIterator::SKIP_DOTS;
$iterator = new \RecursiveDirectoryIterator(self::$tmpDir, $flags);
$iterator = new \RecursiveIteratorIterator($iterator, \RecursiveIteratorIterator::SELF_FIRST);
foreach ($iterator as $file) {
if (is_file($file)) {
unlink($file);
}
}
}
public static function setUpBeforeClass()
{
self::$tmpDir = sys_get_temp_dir().'/sf2_profiler_file_storage';
if (is_dir(self::$tmpDir)) {
self::cleanDir();
}
self::$storage = new FileProfilerStorage('file:'.self::$tmpDir);
}
public static function tearDownAfterClass()
{
self::cleanDir();
}
protected function setUp()
{
self::$storage->purge();
}
/**
* @return \Symfony\Component\HttpKernel\Profiler\ProfilerStorageInterface
*/
protected function getStorage()
{
return self::$storage;
}
public function testMultiRowIndexFile()
{
$iteration = 3;
for ($i = 0; $i < $iteration; $i++) {
$profile = new Profile('token'.$i);
$profile->setIp('127.0.0.'.$i);
$profile->setUrl('http://foo.bar/'.$i);
$storage = $this->getStorage();
$storage->write($profile);
$storage->write($profile);
$storage->write($profile);
}
$handle = fopen(self::$tmpDir.'/index.csv', 'r');
for ($i = 0; $i < $iteration; $i++) {
$row = fgetcsv($handle);
$this->assertEquals('token'.$i, $row[0]);
$this->assertEquals('127.0.0.'.$i, $row[1]);
$this->assertEquals('http://foo.bar/'.$i, $row[3]);
}
$this->assertFalse(fgetcsv($handle));
}
public function testReadLineFromFile()
{
$r = new \ReflectionMethod(self::$storage, 'readLineFromFile');
$r->setAccessible(true);
$h = tmpfile();
fwrite($h, "line1\n\n\nline2\n");
fseek($h, 0, SEEK_END);
$this->assertEquals("line2", $r->invoke(self::$storage, $h));
$this->assertEquals("line1", $r->invoke(self::$storage, $h));
}
}

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\Profiler;
use Symfony\Component\HttpKernel\Profiler\MemcacheProfilerStorage;
use Symfony\Component\HttpKernel\Tests\Profiler\Mock\MemcacheMock;
class MemcacheProfilerStorageTest extends AbstractProfilerStorageTest
{
protected static $storage;
protected function setUp()
{
$memcacheMock = new MemcacheMock();
$memcacheMock->addServer('127.0.0.1', 11211);
self::$storage = new MemcacheProfilerStorage('memcache://127.0.0.1:11211', '', '', 86400);
self::$storage->setMemcache($memcacheMock);
if (self::$storage) {
self::$storage->purge();
}
}
protected function tearDown()
{
if (self::$storage) {
self::$storage->purge();
self::$storage = false;
}
}
/**
* @return \Symfony\Component\HttpKernel\Profiler\ProfilerStorageInterface
*/
protected function getStorage()
{
return self::$storage;
}
}

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\Profiler;
use Symfony\Component\HttpKernel\Profiler\MemcachedProfilerStorage;
use Symfony\Component\HttpKernel\Tests\Profiler\Mock\MemcachedMock;
class MemcachedProfilerStorageTest extends AbstractProfilerStorageTest
{
protected static $storage;
protected function setUp()
{
$memcachedMock = new MemcachedMock();
$memcachedMock->addServer('127.0.0.1', 11211);
self::$storage = new MemcachedProfilerStorage('memcached://127.0.0.1:11211', '', '', 86400);
self::$storage->setMemcached($memcachedMock);
if (self::$storage) {
self::$storage->purge();
}
}
protected function tearDown()
{
if (self::$storage) {
self::$storage->purge();
self::$storage = false;
}
}
/**
* @return \Symfony\Component\HttpKernel\Profiler\ProfilerStorageInterface
*/
protected function getStorage()
{
return self::$storage;
}
}

View File

@@ -0,0 +1,260 @@
<?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\Profiler\Mock;
/**
* MemcacheMock for simulating Memcache extension in tests.
*
* @author Andrej Hudec <pulzarraider@gmail.com>
*/
class MemcacheMock
{
private $connected;
private $storage;
public function __construct()
{
$this->connected = false;
$this->storage = array();
}
/**
* Open memcached server connection
*
* @param string $host
* @param integer $port
* @param integer $timeout
*
* @return boolean
*/
public function connect($host, $port = null, $timeout = null)
{
if ('127.0.0.1' == $host && 11211 == $port) {
$this->connected = true;
return true;
}
return false;
}
/**
* Open memcached server persistent connection
*
* @param string $host
* @param integer $port
* @param integer $timeout
*
* @return boolean
*/
public function pconnect($host, $port = null, $timeout = null)
{
if ('127.0.0.1' == $host && 11211 == $port) {
$this->connected = true;
return true;
}
return false;
}
/**
* Add a memcached server to connection pool
*
* @param string $host
* @param integer $port
* @param boolean $persistent
* @param integer $weight
* @param integer $timeout
* @param integer $retry_interval
* @param boolean $status
* @param callable $failure_callback
* @param integer $timeoutms
*
* @return boolean
*/
public function addServer($host, $port = 11211, $persistent = null, $weight = null, $timeout = null, $retry_interval = null, $status = null, $failure_callback = null, $timeoutms = null)
{
if ('127.0.0.1' == $host && 11211 == $port) {
$this->connected = true;
return true;
}
return false;
}
/**
* Add an item to the server only if such key doesn't exist at the server yet.
*
* @param string $key
* @param mixed $var
* @param integer $flag
* @param integer $expire
*
* @return boolean
*/
public function add($key, $var, $flag = null, $expire = null)
{
if (!$this->connected) {
return false;
}
if (!isset($this->storage[$key])) {
$this->storeData($key, $var);
return true;
}
return false;
}
/**
* Store data at the server.
*
* @param string $key
* @param string $var
* @param integer $flag
* @param integer $expire
*
* @return boolean
*/
public function set($key, $var, $flag = null, $expire = null)
{
if (!$this->connected) {
return false;
}
$this->storeData($key, $var);
return true;
}
/**
* Replace value of the existing item.
*
* @param string $key
* @param mixed $var
* @param integer $flag
* @param integer $expire
*
* @return boolean
*/
public function replace($key, $var, $flag = null, $expire = null)
{
if (!$this->connected) {
return false;
}
if (isset($this->storage[$key])) {
$this->storeData($key, $var);
return true;
}
return false;
}
/**
* Retrieve item from the server.
*
* @param string|array $key
* @param integer|array $flags
*
* @return mixed
*/
public function get($key, &$flags = null)
{
if (!$this->connected) {
return false;
}
if (is_array($key)) {
$result = array();
foreach ($key as $k) {
if (isset($this->storage[$k])) {
$result[] = $this->getData($k);
}
}
return $result;
}
return $this->getData($key);
}
/**
* Delete item from the server
*
* @param string $key
*
* @return boolean
*/
public function delete($key)
{
if (!$this->connected) {
return false;
}
if (isset($this->storage[$key])) {
unset($this->storage[$key]);
return true;
}
return false;
}
/**
* Flush all existing items at the server
*
* @return boolean
*/
public function flush()
{
if (!$this->connected) {
return false;
}
$this->storage = array();
return true;
}
/**
* Close memcached server connection
*
* @return boolean
*/
public function close()
{
$this->connected = false;
return true;
}
private function getData($key)
{
if (isset($this->storage[$key])) {
return unserialize($this->storage[$key]);
}
return false;
}
private function storeData($key, $value)
{
$this->storage[$key] = serialize($value);
return true;
}
}

View File

@@ -0,0 +1,225 @@
<?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\Profiler\Mock;
/**
* MemcachedMock for simulating Memcached extension in tests.
*
* @author Andrej Hudec <pulzarraider@gmail.com>
*/
class MemcachedMock
{
private $connected;
private $storage;
public function __construct()
{
$this->connected = false;
$this->storage = array();
}
/**
* Set a Memcached option
*
* @param integer $option
* @param mixed $value
*
* @return boolean
*/
public function setOption($option, $value)
{
return true;
}
/**
* Add a memcached server to connection pool
*
* @param string $host
* @param integer $port
* @param integer $weight
*
* @return boolean
*/
public function addServer($host, $port = 11211, $weight = 0)
{
if ('127.0.0.1' == $host && 11211 == $port) {
$this->connected = true;
return true;
}
return false;
}
/**
* Add an item to the server only if such key doesn't exist at the server yet.
*
* @param string $key
* @param mixed $value
* @param integer $expiration
*
* @return boolean
*/
public function add($key, $value, $expiration = 0)
{
if (!$this->connected) {
return false;
}
if (!isset($this->storage[$key])) {
$this->storeData($key, $value);
return true;
}
return false;
}
/**
* Store data at the server.
*
* @param string $key
* @param mixed $value
* @param integer $expiration
*
* @return boolean
*/
public function set($key, $value, $expiration = null)
{
if (!$this->connected) {
return false;
}
$this->storeData($key, $value);
return true;
}
/**
* Replace value of the existing item.
*
* @param string $key
* @param mixed $value
* @param integer $expiration
*
* @return boolean
*/
public function replace($key, $value, $expiration = null)
{
if (!$this->connected) {
return false;
}
if (isset($this->storage[$key])) {
$this->storeData($key, $value);
return true;
}
return false;
}
/**
* Retrieve item from the server.
*
* @param string $key
* @param callable $cache_cb
* @param float $cas_token
*
* @return boolean
*/
public function get($key, $cache_cb = null, &$cas_token = null)
{
if (!$this->connected) {
return false;
}
return $this->getData($key);
}
/**
* Append data to an existing item
*
* @param string $key
* @param string $value
*
* @return boolean
*/
public function append($key, $value)
{
if (!$this->connected) {
return false;
}
if (isset($this->storage[$key])) {
$this->storeData($key, $this->getData($key).$value);
return true;
}
return false;
}
/**
* Delete item from the server
*
* @param string $key
*
* @return boolean
*/
public function delete($key)
{
if (!$this->connected) {
return false;
}
if (isset($this->storage[$key])) {
unset($this->storage[$key]);
return true;
}
return false;
}
/**
* Flush all existing items at the server
*
* @return boolean
*/
public function flush()
{
if (!$this->connected) {
return false;
}
$this->storage = array();
return true;
}
private function getData($key)
{
if (isset($this->storage[$key])) {
return unserialize($this->storage[$key]);
}
return false;
}
private function storeData($key, $value)
{
$this->storage[$key] = serialize($value);
return true;
}
}

View File

@@ -0,0 +1,254 @@
<?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\Profiler\Mock;
/**
* RedisMock for simulating Redis extension in tests.
*
* @author Andrej Hudec <pulzarraider@gmail.com>
*/
class RedisMock
{
private $connected;
private $storage;
public function __construct()
{
$this->connected = false;
$this->storage = array();
}
/**
* Add a server to connection pool
*
* @param string $host
* @param integer $port
* @param float $timeout
*
* @return boolean
*/
public function connect($host, $port = 6379, $timeout = 0)
{
if ('127.0.0.1' == $host && 6379 == $port) {
$this->connected = true;
return true;
}
return false;
}
/**
* Set client option.
*
* @param integer $name
* @param integer $value
*
* @return boolean
*/
public function setOption($name, $value)
{
if (!$this->connected) {
return false;
}
return true;
}
/**
* Verify if the specified key exists.
*
* @param string $key
*
* @return boolean
*/
public function exists($key)
{
if (!$this->connected) {
return false;
}
return isset($this->storage[$key]);
}
/**
* Store data at the server with expiration time.
*
* @param string $key
* @param integer $ttl
* @param mixed $value
*
* @return boolean
*/
public function setex($key, $ttl, $value)
{
if (!$this->connected) {
return false;
}
$this->storeData($key, $value);
return true;
}
/**
* Sets an expiration time on an item.
*
* @param string $key
* @param integer $ttl
*
* @return boolean
*/
public function setTimeout($key, $ttl)
{
if (!$this->connected) {
return false;
}
if (isset($this->storage[$key])) {
return true;
}
return false;
}
/**
* Retrieve item from the server.
*
* @param string $key
*
* @return boolean
*/
public function get($key)
{
if (!$this->connected) {
return false;
}
return $this->getData($key);
}
/**
* Append data to an existing item
*
* @param string $key
* @param string $value
*
* @return integer Size of the value after the append.
*/
public function append($key, $value)
{
if (!$this->connected) {
return false;
}
if (isset($this->storage[$key])) {
$this->storeData($key, $this->getData($key).$value);
return strlen($this->storage[$key]);
}
return false;
}
/**
* Remove specified keys.
*
* @param string|array $key
*
* @return integer
*/
public function delete($key)
{
if (!$this->connected) {
return false;
}
if (is_array($key)) {
$result = 0;
foreach ($key as $k) {
if (isset($this->storage[$k])) {
unset($this->storage[$k]);
++$result;
}
}
return $result;
}
if (isset($this->storage[$key])) {
unset($this->storage[$key]);
return 1;
}
return 0;
}
/**
* Flush all existing items from all databases at the server.
*
* @return boolean
*/
public function flushAll()
{
if (!$this->connected) {
return false;
}
$this->storage = array();
return true;
}
/**
* Close Redis server connection
*
* @return boolean
*/
public function close()
{
$this->connected = false;
return true;
}
private function getData($key)
{
if (isset($this->storage[$key])) {
return unserialize($this->storage[$key]);
}
return false;
}
private function storeData($key, $value)
{
$this->storage[$key] = serialize($value);
return true;
}
public function select($dbnum)
{
if (!$this->connected) {
return false;
}
if (0 > $dbnum) {
return false;
}
return true;
}
}

View File

@@ -0,0 +1,128 @@
<?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\Profiler;
use Symfony\Component\HttpKernel\Profiler\MongoDbProfilerStorage;
use Symfony\Component\HttpKernel\Profiler\Profile;
use Symfony\Component\HttpKernel\DataCollector\DataCollector;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class DummyMongoDbProfilerStorage extends MongoDbProfilerStorage
{
public function getMongo()
{
return parent::getMongo();
}
}
class MongoDbProfilerStorageTestDataCollector extends DataCollector
{
public function setData($data)
{
$this->data = $data;
}
public function getData()
{
return $this->data;
}
public function collect(Request $request, Response $response, \Exception $exception = null)
{
}
public function getName()
{
return 'test_data_collector';
}
}
class MongoDbProfilerStorageTest extends AbstractProfilerStorageTest
{
protected static $storage;
public static function setUpBeforeClass()
{
if (extension_loaded('mongo')) {
self::$storage = new DummyMongoDbProfilerStorage('mongodb://localhost/symfony_tests/profiler_data', '', '', 86400);
try {
self::$storage->getMongo();
} catch (\MongoConnectionException $e) {
self::$storage = null;
}
}
}
public static function tearDownAfterClass()
{
if (self::$storage) {
self::$storage->purge();
self::$storage = null;
}
}
public function testCleanup()
{
$dt = new \DateTime('-2 day');
for ($i = 0; $i < 3; $i++) {
$dt->modify('-1 day');
$profile = new Profile('time_'.$i);
$profile->setTime($dt->getTimestamp());
$profile->setMethod('GET');
self::$storage->write($profile);
}
$records = self::$storage->find('', '', 3, 'GET');
$this->assertCount(1, $records, '->find() returns only one record');
$this->assertEquals($records[0]['token'], 'time_2', '->find() returns the latest added record');
self::$storage->purge();
}
public function testUtf8()
{
$profile = new Profile('utf8_test_profile');
$data = 'HЁʃʃϿ, ϢorЃd!';
$nonUtf8Data = mb_convert_encoding($data, 'UCS-2');
$collector = new MongoDbProfilerStorageTestDataCollector();
$collector->setData($nonUtf8Data);
$profile->setCollectors(array($collector));
self::$storage->write($profile);
$readProfile = self::$storage->read('utf8_test_profile');
$collectors = $readProfile->getCollectors();
$this->assertCount(1, $collectors);
$this->assertArrayHasKey('test_data_collector', $collectors);
$this->assertEquals($nonUtf8Data, $collectors['test_data_collector']->getData(), 'Non-UTF8 data is properly encoded/decoded');
}
/**
* @return \Symfony\Component\HttpKernel\Profiler\ProfilerStorageInterface
*/
protected function getStorage()
{
return self::$storage;
}
protected function setUp()
{
if (self::$storage) {
self::$storage->purge();
} else {
$this->markTestSkipped('MongoDbProfilerStorageTest requires the mongo PHP extension and a MongoDB server on localhost');
}
}
}

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\Profiler;
use Symfony\Component\HttpKernel\DataCollector\RequestDataCollector;
use Symfony\Component\HttpKernel\Profiler\SqliteProfilerStorage;
use Symfony\Component\HttpKernel\Profiler\Profiler;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class ProfilerTest extends \PHPUnit_Framework_TestCase
{
protected function setUp()
{
if (!class_exists('Symfony\Component\HttpFoundation\Request')) {
$this->markTestSkipped('The "HttpFoundation" component is not available');
}
}
public function testCollect()
{
if (!class_exists('SQLite3') && (!class_exists('PDO') || !in_array('sqlite', \PDO::getAvailableDrivers()))) {
$this->markTestSkipped('This test requires SQLite support in your environment');
}
$request = new Request();
$request->query->set('foo', 'bar');
$response = new Response();
$collector = new RequestDataCollector();
$tmp = tempnam(sys_get_temp_dir(), 'sf2_profiler');
if (file_exists($tmp)) {
@unlink($tmp);
}
$storage = new SqliteProfilerStorage('sqlite:'.$tmp);
$storage->purge();
$profiler = new Profiler($storage);
$profiler->add($collector);
$profile = $profiler->collect($request, $response);
$profile = $profiler->loadProfile($profile->getToken());
$this->assertEquals(array('foo' => 'bar'), $profiler->get('request')->getRequestQuery()->all());
@unlink($tmp);
}
}

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\Profiler;
use Symfony\Component\HttpKernel\Profiler\RedisProfilerStorage;
use Symfony\Component\HttpKernel\Tests\Profiler\Mock\RedisMock;
class RedisProfilerStorageTest extends AbstractProfilerStorageTest
{
protected static $storage;
protected function setUp()
{
$redisMock = new RedisMock();
$redisMock->connect('127.0.0.1', 6379);
self::$storage = new RedisProfilerStorage('redis://127.0.0.1:6379', '', '', 86400);
self::$storage->setRedis($redisMock);
if (self::$storage) {
self::$storage->purge();
}
}
protected function tearDown()
{
if (self::$storage) {
self::$storage->purge();
self::$storage = false;
}
}
/**
* @return \Symfony\Component\HttpKernel\Profiler\ProfilerStorageInterface
*/
protected function getStorage()
{
return self::$storage;
}
}

View File

@@ -0,0 +1,50 @@
<?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\Profiler;
use Symfony\Component\HttpKernel\Profiler\SqliteProfilerStorage;
class SqliteProfilerStorageTest extends AbstractProfilerStorageTest
{
protected static $dbFile;
protected static $storage;
public static function setUpBeforeClass()
{
self::$dbFile = tempnam(sys_get_temp_dir(), 'sf2_sqlite_storage');
if (file_exists(self::$dbFile)) {
@unlink(self::$dbFile);
}
self::$storage = new SqliteProfilerStorage('sqlite:'.self::$dbFile);
}
public static function tearDownAfterClass()
{
@unlink(self::$dbFile);
}
protected function setUp()
{
if (!class_exists('SQLite3') && (!class_exists('PDO') || !in_array('sqlite', \PDO::getAvailableDrivers()))) {
$this->markTestSkipped('This test requires SQLite support in your environment');
}
self::$storage->purge();
}
/**
* @return \Symfony\Component\HttpKernel\Profiler\ProfilerStorageInterface
*/
protected function getStorage()
{
return self::$storage;
}
}

View File

@@ -0,0 +1,41 @@
<?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;
use Symfony\Component\HttpKernel\HttpKernel;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Controller\ControllerResolverInterface;
use Symfony\Component\EventDispatcher\EventDispatcher;
class TestHttpKernel extends HttpKernel implements ControllerResolverInterface
{
public function __construct()
{
parent::__construct(new EventDispatcher(), $this);
}
public function getController(Request $request)
{
return array($this, 'callController');
}
public function getArguments(Request $request, $controller)
{
return array($request);
}
public function callController(Request $request)
{
return new Response('Request: '.$request->getRequestUri());
}
}

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;
use Symfony\Component\HttpKernel\UriSigner;
class UriSignerTest extends \PHPUnit_Framework_TestCase
{
public function testSign()
{
$signer = new UriSigner('foobar');
$this->assertContains('?_hash=', $signer->sign('http://example.com/foo'));
$this->assertContains('&_hash=', $signer->sign('http://example.com/foo?foo=bar'));
}
public function testCheck()
{
$signer = new UriSigner('foobar');
$this->assertFalse($signer->check('http://example.com/foo?_hash=foo'));
$this->assertFalse($signer->check('http://example.com/foo?foo=bar&_hash=foo'));
$this->assertFalse($signer->check('http://example.com/foo?foo=bar&_hash=foo&bar=foo'));
$this->assertTrue($signer->check($signer->sign('http://example.com/foo')));
$this->assertTrue($signer->check($signer->sign('http://example.com/foo?foo=bar')));
}
}