ÿØÿà JFIF    ÿÛ „ ( %!1!%*+...983,7(-.- Symfony/Component/HttpKernel/Tests/DependencyInjection/RegisterListenersPassTest.php000064400000012136152410105270025132 0ustar00 * * 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\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('isPublic') ->will($this->returnValue(true)); $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('isPublic') ->will($this->returnValue(true)); $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)); $builder->expects($this->atLeastOnce()) ->method('findDefinition') ->will($this->returnValue($definition)); $registerListenersPass = new RegisterListenersPass(); $registerListenersPass->process($builder); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage The service "foo" must be public as event listeners are lazy-loaded. */ public function testPrivateEventListener() { $container = new ContainerBuilder(); $container->register('foo', 'stdClass')->setPublic(false)->addTag('kernel.event_listener', array()); $container->register('event_dispatcher', 'stdClass'); $registerListenersPass = new RegisterListenersPass(); $registerListenersPass->process($container); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage The service "foo" must be public as event subscribers are lazy-loaded. */ public function testPrivateEventSubscriber() { $container = new ContainerBuilder(); $container->register('foo', 'stdClass')->setPublic(false)->addTag('kernel.event_subscriber', array()); $container->register('event_dispatcher', 'stdClass'); $registerListenersPass = new RegisterListenersPass(); $registerListenersPass->process($container); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage The service "foo" must not be abstract as event listeners are lazy-loaded. */ public function testAbstractEventListener() { $container = new ContainerBuilder(); $container->register('foo', 'stdClass')->setAbstract(true)->addTag('kernel.event_listener', array()); $container->register('event_dispatcher', 'stdClass'); $registerListenersPass = new RegisterListenersPass(); $registerListenersPass->process($container); } } class SubscriberService implements \Symfony\Component\EventDispatcher\EventSubscriberInterface { public static function getSubscribedEvents() {} } Symfony/Component/HttpKernel/Tests/DependencyInjection/MergeExtensionConfigurationPassTest.php000064400000003656152410105270027150 0ustar00 * * 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\DependencyInjection\MergeExtensionConfigurationPass; class MergeExtensionConfigurationPassTest extends \PHPUnit_Framework_TestCase { 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); } } Symfony/Component/HttpKernel/Tests/DependencyInjection/ContainerAwareHttpKernelTest.php000064400000012550152410105270025531 0ustar00 * * 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\RequestStack; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\EventDispatcher\EventDispatcher; class ContainerAwareHttpKernelTest extends \PHPUnit_Framework_TestCase { /** * @dataProvider getProviderTypes */ public function testHandle($type) { $request = new Request(); $expected = new Response(); $controller = function () use ($expected) { return $expected; }; $container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface'); $this ->expectsEnterScopeOnce($container) ->expectsLeaveScopeOnce($container) ->expectsSetRequestWithAt($container, $request, 3) ->expectsSetRequestWithAt($container, null, 4) ; $dispatcher = new EventDispatcher(); $resolver = $this->getResolverMockFor($controller, $request); $stack = new RequestStack(); $kernel = new ContainerAwareHttpKernel($dispatcher, $container, $resolver, $stack); $actual = $kernel->handle($request, $type); $this->assertSame($expected, $actual, '->handle() returns the response'); } /** * @dataProvider getProviderTypes */ public function testVerifyRequestStackPushPopDuringHandle($type) { $request = new Request(); $expected = new Response(); $controller = function () use ($expected) { return $expected; }; $stack = $this->getMock('Symfony\Component\HttpFoundation\RequestStack', array('push', 'pop')); $stack->expects($this->at(0))->method('push')->with($this->equalTo($request)); $stack->expects($this->at(1))->method('pop'); $container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface'); $dispatcher = new EventDispatcher(); $resolver = $this->getResolverMockFor($controller, $request); $kernel = new ContainerAwareHttpKernel($dispatcher, $container, $resolver, $stack); $kernel->handle($request, $type); } /** * @dataProvider getProviderTypes */ public function testHandleRestoresThePreviousRequestOnException($type) { $request = new Request(); $expected = new \Exception(); $controller = function () use ($expected) { throw $expected; }; $container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface'); $this ->expectsEnterScopeOnce($container) ->expectsLeaveScopeOnce($container) ->expectsSetRequestWithAt($container, $request, 3) ->expectsSetRequestWithAt($container, null, 4) ; $dispatcher = new EventDispatcher(); $resolver = $this->getMock('Symfony\\Component\\HttpKernel\\Controller\\ControllerResolverInterface'); $resolver = $this->getResolverMockFor($controller, $request); $stack = new RequestStack(); $kernel = new ContainerAwareHttpKernel($dispatcher, $container, $resolver, $stack); 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), ); } private function getResolverMockFor($controller, $request) { $resolver = $this->getMock('Symfony\\Component\\HttpKernel\\Controller\\ControllerResolverInterface'); $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())); return $resolver; } private function expectsSetRequestWithAt($container, $with, $at) { $container ->expects($this->at($at)) ->method('set') ->with($this->equalTo('request'), $this->equalTo($with), $this->equalTo('request')) ; return $this; } private function expectsEnterScopeOnce($container) { $container ->expects($this->once()) ->method('enterScope') ->with($this->equalTo('request')) ; return $this; } private function expectsLeaveScopeOnce($container) { $container ->expects($this->once()) ->method('leaveScope') ->with($this->equalTo('request')) ; return $this; } } Symfony/Component/HttpKernel/Tests/Logger.php000064400000005742152410105270015271 0ustar00 * * 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 critical() which is PSR-3 compatible', E_USER_DEPRECATED); $this->log('critical', $message, $context); } /** * @deprecated */ public function err($message, array $context = array()) { trigger_error('Use error() which is PSR-3 compatible', E_USER_DEPRECATED); $this->log('error', $message, $context); } /** * @deprecated */ public function warn($message, array $context = array()) { trigger_error('Use warning() which is PSR-3 compatible', E_USER_DEPRECATED); $this->log('warning', $message, $context); } } Symfony/Component/HttpKernel/Tests/UriSignerTest.php000064400000002235152410105270016613 0ustar00 * * 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'))); } } Symfony/Component/HttpKernel/Tests/CacheClearer/ChainCacheClearerTest.php000064400000003017152410105270022450 0ustar00 * * 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'); } } Symfony/Component/HttpKernel/Tests/DataCollector/ConfigDataCollectorTest.php000064400000004615152410105270023276 0ustar00 * * 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 { 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) { } } Symfony/Component/HttpKernel/Tests/DataCollector/MemoryDataCollectorTest.php000064400000003536152410105270023342 0ustar00 * * 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 { 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('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' ); } } Symfony/Component/HttpKernel/Tests/DataCollector/ExceptionDataCollectorTest.php000064400000002322152410105270024020 0ustar00 * * 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 { 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()); } } Symfony/Component/HttpKernel/Tests/DataCollector/RequestDataCollectorTest.php000064400000017614152410105270023524 0ustar00 * * 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 { /** * @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->assertSame('html', $c->getFormat()); $this->assertSame('foobar', $c->getRoute()); $this->assertSame(array('name' => 'foo'), $c->getRouteParams()); $this->assertSame(array(), $c->getSessionAttributes()); $this->assertSame('en', $c->getLocale()); $this->assertInstanceOf('Symfony\Component\HttpFoundation\HeaderBag', $c->getResponseHeaders()); $this->assertSame('OK', $c->getStatusText()); $this->assertSame(200, $c->getStatusCode()); $this->assertSame('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->assertSame($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'); $request->attributes->set('_route', 'foobar'); $request->attributes->set('_route_params', array('name' => 'foo')); $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'); } } Symfony/Component/HttpKernel/Tests/DataCollector/TimeDataCollectorTest.php000064400000002753152410105270022770 0ustar00 * * 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 { 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()); } } Symfony/Component/HttpKernel/Tests/DataCollector/LoggerDataCollectorTest.php000064400000004551152410105270023307 0ustar00 * * 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; class LoggerDataCollectorTest extends \PHPUnit_Framework_TestCase { /** * @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->lateCollect(); $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 ), ); } } Symfony/Component/HttpKernel/Tests/CacheWarmer/CacheWarmerAggregateTest.php000064400000005731152410105270023061 0ustar00 * * 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; } } Symfony/Component/HttpKernel/Tests/CacheWarmer/CacheWarmerTest.php000064400000003045152410105270021246 0ustar00 * * 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; } } Symfony/Component/HttpKernel/Tests/Fixtures/Resources/ChildBundle/foo.txt000064400000000000152410105270022603 0ustar00Symfony/Component/HttpKernel/Tests/Fixtures/Resources/Bundle1Bundle/foo.txt000064400000000000152410105270023052 0ustar00Symfony/Component/HttpKernel/Tests/Fixtures/Resources/BaseBundle/hide.txt000064400000000000152410105270022560 0ustar00Symfony/Component/HttpKernel/Tests/Fixtures/Resources/FooBundle/foo.txt000064400000000000152410105270022303 0ustar00Symfony/Component/HttpKernel/Tests/Fixtures/ChildBundle/Resources/hide.txt000064400000000000152410105270022731 0ustar00Symfony/Component/HttpKernel/Tests/Fixtures/ChildBundle/Resources/foo.txt000064400000000000152410105270022603 0ustar00Symfony/Component/HttpKernel/Tests/Fixtures/Bundle2Bundle/foo.txt000064400000000000152410105270021101 0ustar00HttpKernel/Tests/Fixtures/ExtensionLoadedBundle/DependencyInjection/ExtensionLoadedExtension.php000064400000001124152410105270032714 0ustar00Symfony/Component * * 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) { } } Symfony/Component/HttpKernel/Tests/Fixtures/ExtensionLoadedBundle/ExtensionLoadedBundle.php000064400000000634152410105270026314 0ustar00 * * 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 { } Symfony/Component/HttpKernel/Tests/Fixtures/KernelForOverrideName.php000064400000001146152410105270022045 0ustar00 * * 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) { } } Symfony/Component/HttpKernel/Tests/Fixtures/Bundle1Bundle/Resources/foo.txt000064400000000000152410105270023052 0ustar00Symfony/Component/HttpKernel/Tests/Fixtures/Bundle1Bundle/bar.txt000064400000000000152410105270021061 0ustar00Symfony/Component/HttpKernel/Tests/Fixtures/Bundle1Bundle/foo.txt000064400000000000152410105270021100 0ustar00Symfony/Component/HttpKernel/Tests/Fixtures/BaseBundle/Resources/hide.txt000064400000000000152410105270022560 0ustar00Symfony/Component/HttpKernel/Tests/Fixtures/BaseBundle/Resources/foo.txt000064400000000000152410105270022432 0ustar00Symfony/Component/HttpKernel/Tests/Fixtures/TestClient.php000064400000001433152410105270017732 0ustar00 * * 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; } } Symfony/Component/HttpKernel/Tests/Fixtures/ExtensionPresentBundle/ExtensionPresentBundle.php000064400000000636152410105270026776 0ustar00 * * 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 { } HttpKernel/Tests/Fixtures/ExtensionPresentBundle/DependencyInjection/ExtensionPresentExtension.php000064400000001126152410105270033376 0ustar00Symfony/Component * * 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) { } } Symfony/Component/HttpKernel/Tests/Fixtures/ExtensionPresentBundle/Command/FooCommand.php000064400000000773152410105270025731 0ustar00 * * 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'); } } Symfony/Component/HttpKernel/Tests/Fixtures/ExtensionPresentBundle/Command/BarCommand.php000064400000000677152410105270025715 0ustar00 * * 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() { return array(); } public function registerContainerConfiguration(LoaderInterface $loader) { } public function isBooted() { return $this->booted; } } Symfony/Component/HttpKernel/Tests/Fixtures/cache/test/MockObjectTestProjectContainer.php000064400000005140152410105270025747 0ustar00parameters = $this->getDefaultParameters(); $this->services = $this->scopedServices = $this->scopeStacks = array(); $this->set('service_container', $this); $this->scopes = array(); $this->scopeChildren = array(); $this->aliases = array(); } public function getParameter($name) { $name = strtolower($name); if (!(isset($this->parameters[$name]) || array_key_exists($name, $this->parameters))) { throw new InvalidArgumentException(sprintf('The parameter "%s" must be defined.', $name)); } return $this->parameters[$name]; } public function hasParameter($name) { $name = strtolower($name); return isset($this->parameters[$name]) || array_key_exists($name, $this->parameters); } public function setParameter($name, $value) { throw new LogicException('Impossible to call set() on a frozen ParameterBag.'); } public function getParameterBag() { if (null === $this->parameterBag) { $this->parameterBag = new FrozenParameterBag($this->parameters); } return $this->parameterBag; } protected function getDefaultParameters() { return array( 'kernel.root_dir' => '/Users/fabien/Code/github/symfony/symfony/src/Symfony/Component/HttpKernel/Tests/Fixtures', 'kernel.environment' => 'test', 'kernel.debug' => false, 'kernel.name' => 'MockObject', 'kernel.cache_dir' => '/Users/fabien/Code/github/symfony/symfony/src/Symfony/Component/HttpKernel/Tests/Fixtures/cache/test', 'kernel.logs_dir' => '/Users/fabien/Code/github/symfony/symfony/src/Symfony/Component/HttpKernel/Tests/Fixtures/logs', 'kernel.bundles' => array( 'Mock_Bundle_7fc4ae26' => 'Mock_Bundle_7fc4ae26', ), 'kernel.charset' => 'UTF-8', 'kernel.container_class' => 'MockObjectTestProjectContainer', ); } } Symfony/Component/HttpKernel/Tests/Fixtures/cache/test/classes.map000064400000000027152410105270021317 0ustar00 * * 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'); } } Symfony/Component/HttpKernel/Tests/Fixtures/FooBarBundle.php000064400000000714152410105270020157 0ustar00 * * 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 } Symfony/Component/HttpKernel/Tests/Fixtures/ExtensionAbsentBundle/ExtensionAbsentBundle.php000064400000000634152410105270026364 0ustar00 * * 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 { } Symfony/Component/HttpKernel/Tests/Config/FileLocatorTest.php000064400000003016152410105270020312 0ustar00 * * 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); } } Symfony/Component/HttpKernel/Tests/ClientTest.php000064400000015177152410105270016133 0ustar00 * * 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 { 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() { $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), ); $file = null; 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); } } Symfony/Component/HttpKernel/Tests/Fragment/InlineFragmentRendererTest.php000064400000017355152410105270023051 0ustar00 * * 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\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 { 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'); $strategy = new InlineFragmentRenderer($this->getKernelExpectingRequest($subRequest)); $strategy->render(new ControllerReference('main_controller', array('object' => $object), array()), Request::create('/')); } public function testRenderWithObjectsAsAttributesPassedAsObjectsInTheController() { $resolver = $this->getMock('Symfony\\Component\\HttpKernel\\Controller\\ControllerResolver', array('getController')); $resolver ->expects($this->once()) ->method('getController') ->will($this->returnValue(function (\stdClass $object, Bar $object1) { return new Response($object1->getBar()); })) ; $kernel = new HttpKernel(new EventDispatcher(), $resolver); $renderer = new InlineFragmentRenderer($kernel); $response = $renderer->render(new ControllerReference('main_controller', array('object' => new \stdClass(), 'object1' => new Bar()), array()), Request::create('/')); $this->assertEquals('bar', $response->getContent()); } public function testRenderWithTrustedHeaderDisabled() { $trustedHeaderName = Request::getTrustedHeaderName(Request::HEADER_CLIENT_IP); Request::setTrustedHeaderName(Request::HEADER_CLIENT_IP, ''); $strategy = new InlineFragmentRenderer($this->getKernelExpectingRequest(Request::create('/'))); $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; } /** * Creates a Kernel expecting a request equals to $request * Allows delta in comparison in case REQUEST_TIME changed by 1 second */ private function getKernelExpectingRequest(Request $request) { $kernel = $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface'); $kernel ->expects($this->any()) ->method('handle') ->with($this->equalTo($request, 1)) ; return $kernel; } public function testExceptionInSubRequestsDoesNotMangleOutputBuffers() { $resolver = $this->getMock('Symfony\\Component\\HttpKernel\\Controller\\ControllerResolverInterface'); $resolver ->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'); } $strategy = new InlineFragmentRenderer($this->getKernelExpectingRequest($expectedSubRequest)); $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); } } class Bar { public $bar = 'bar'; public function getBar() { return $this->bar; } } Symfony/Component/HttpKernel/Tests/Fragment/FragmentHandlerTest.php000064400000005355152410105270021516 0ustar00 * * 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 { private $requestStack; public function setUp() { $this->requestStack = $this->getMockBuilder('Symfony\\Component\\HttpFoundation\\RequestStack') ->disableOriginalConstructor() ->getMock() ; $this->requestStack ->expects($this->any()) ->method('getCurrentRequest') ->will($this->returnValue(Request::create('/'))) ; } /** * @expectedException \InvalidArgumentException */ public function testRenderWhenRendererDoesNotExist() { $handler = new FragmentHandler(array(), null, $this->requestStack); $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(array(), null, $this->requestStack); $handler->addRenderer($renderer); return $handler; } } Symfony/Component/HttpKernel/Tests/Fragment/RoutableFragmentRendererTest.php000064400000007450152410105270023403 0ustar00 * * 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\HttpFoundation\Request; use Symfony\Component\HttpKernel\Controller\ControllerReference; class RoutableFragmentRendererTest extends \PHPUnit_Framework_TestCase { /** * @dataProvider getGenerateFragmentUriData */ public function testGenerateFragmentUri($uri, $controller) { $this->assertEquals($uri, $this->callGenerateFragmentUriMethod($controller, Request::create('/'))); } /** * @dataProvider getGenerateFragmentUriData */ public function testGenerateAbsoluteFragmentUri($uri, $controller) { $this->assertEquals('http://localhost'.$uri, $this->callGenerateFragmentUriMethod($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'))), array('/_fragment?_path=foo%255B0%255D%3Dfoo%26foo%255B1%255D%3Dbar%26_format%3Dhtml%26_locale%3Den%26_controller%3Dcontroller', new ControllerReference('controller', array('foo' => array('foo', 'bar')), array())), ); } 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->callGenerateFragmentUriMethod($controller, $request)); } /** * @expectedException LogicException * @dataProvider getGenerateFragmentUriDataWithNonScalar */ public function testGenerateFragmentUriWithNonScalar($controller) { $this->callGenerateFragmentUriMethod($controller, Request::create('/')); } public function getGenerateFragmentUriDataWithNonScalar() { return array( array(new ControllerReference('controller', array('foo' => new Foo(), 'bar' => 'bar'), array())), array(new ControllerReference('controller', array('foo' => array('foo' => 'foo'), 'bar' => array('bar' => new Foo())), array())), ); } private function callGenerateFragmentUriMethod(ControllerReference $reference, Request $request, $absolute = false) { $renderer = $this->getMockForAbstractClass('Symfony\Component\HttpKernel\Fragment\RoutableFragmentRenderer'); $r = new \ReflectionObject($renderer); $m = $r->getMethod('generateFragmentUri'); $m->setAccessible(true); return $m->invoke($renderer, $reference, $request, $absolute); } } class Foo { public $foo; public function getFoo() { return $this->foo; } } Symfony/Component/HttpKernel/Tests/Fragment/HIncludeFragmentRendererTest.php000064400000010221152410105270023307 0ustar00 * * 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\Controller\ControllerReference; use Symfony\Component\HttpKernel\Fragment\HIncludeFragmentRenderer; use Symfony\Component\HttpKernel\UriSigner; use Symfony\Component\HttpFoundation\Request; class HIncludeFragmentRendererTest extends \PHPUnit_Framework_TestCase { /** * @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('', $strategy->render(new ControllerReference('main_controller', array(), array()), Request::create('/'))->getContent()); } public function testRenderWithUri() { $strategy = new HIncludeFragmentRenderer(); $this->assertEquals('', $strategy->render('/foo', Request::create('/'))->getContent()); $strategy = new HIncludeFragmentRenderer(null, new UriSigner('foo')); $this->assertEquals('', $strategy->render('/foo', Request::create('/'))->getContent()); } public function testRenderWithDefault() { // only default $strategy = new HIncludeFragmentRenderer(); $this->assertEquals('default', $strategy->render('/foo', Request::create('/'), array('default' => 'default'))->getContent()); // only global default $strategy = new HIncludeFragmentRenderer(null, null, 'global_default'); $this->assertEquals('global_default', $strategy->render('/foo', Request::create('/'), array())->getContent()); // global default and default $strategy = new HIncludeFragmentRenderer(null, null, 'global_default'); $this->assertEquals('default', $strategy->render('/foo', Request::create('/'), array('default' => 'default'))->getContent()); } public function testRenderWithAttributesOptions() { // with id $strategy = new HIncludeFragmentRenderer(); $this->assertEquals('default', $strategy->render('/foo', Request::create('/'), array('default' => 'default', 'id' => 'bar'))->getContent()); // with attributes $strategy = new HIncludeFragmentRenderer(); $this->assertEquals('default', $strategy->render('/foo', Request::create('/'), array('default' => 'default', 'attributes' => array('p1' => 'v1', 'p2' => 'v2')))->getContent()); // with id & attributes $strategy = new HIncludeFragmentRenderer(); $this->assertEquals('default', $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('default', $strategy->render('/foo', Request::create('/'), array('default' => 'default'))->getContent()); } } Symfony/Component/HttpKernel/Tests/Fragment/EsiFragmentRendererTest.php000064400000004661152410105270022347 0ustar00 * * 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\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 { 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('', $strategy->render('/', $request)->getContent()); $this->assertEquals("\n", $strategy->render('/', $request, array('comment' => 'This is a comment'))->getContent()); $this->assertEquals('', $strategy->render('/', $request, array('alt' => 'foo'))->getContent()); $this->assertEquals('', $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; } } Symfony/Component/HttpKernel/Tests/HttpKernelTest.php000064400000025076152410105270016774 0ustar00 * * 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 { /** * @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); } public function testVerifyRequestStackPushPopDuringHandle() { $request = new Request(); $stack = $this->getMock('Symfony\Component\HttpFoundation\RequestStack', array('push', 'pop')); $stack->expects($this->at(0))->method('push')->with($this->equalTo($request)); $stack->expects($this->at(1))->method('pop'); $dispatcher = new EventDispatcher(); $kernel = new HttpKernel($dispatcher, $this->getResolver(), $stack); $kernel->handle($request, HttpKernelInterface::MASTER_REQUEST); } 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'); } Symfony/Component/HttpKernel/Tests/Debug/TraceableEventDispatcherTest.php000064400000022337152410105270022632 0ustar00 * * 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 { 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 testDispatchReusedEventNested() { $nestedCall = false; $dispatcher = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch()); $dispatcher->addListener('foo', function (Event $e) use ($dispatcher) { $dispatcher->dispatch('bar', $e); }); $dispatcher->addListener('bar', function (Event $e) use (&$nestedCall) { $nestedCall = true; }); $this->assertFalse($nestedCall); $dispatcher->dispatch('foo'); $this->assertTrue($nestedCall); } 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'); } } Symfony/Component/HttpKernel/Tests/Profiler/RedisProfilerStorageTest.php000064400000002267152410105270022571 0ustar00 * * 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; } } Symfony/Component/HttpKernel/Tests/Profiler/ProfilerTest.php000064400000003124152410105270020246 0ustar00 * * 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 { 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); } } Symfony/Component/HttpKernel/Tests/Profiler/Mock/MemcacheMock.php000064400000012216152410105270021033 0ustar00 * * 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 */ class MemcacheMock { private $connected = false; private $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; } } Symfony/Component/HttpKernel/Tests/Profiler/Mock/MemcachedMock.php000064400000010252152410105270021175 0ustar00 * * 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 */ class MemcachedMock { private $connected = false; private $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; } } Symfony/Component/HttpKernel/Tests/Profiler/Mock/RedisMock.php000064400000011012152410105270020370 0ustar00 * * 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 */ class RedisMock { private $connected = false; private $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; } } Symfony/Component/HttpKernel/Tests/Profiler/MemcachedProfilerStorageTest.php000064400000002343152410105270023364 0ustar00 * * 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; } } Symfony/Component/HttpKernel/Tests/Profiler/MongoDbProfilerStorageTest.php000064400000011655152410105270023051 0ustar00 * * 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 getDsns() { return array( array('mongodb://localhost/symfony_tests/profiler_data', array( 'mongodb://localhost/symfony_tests', 'symfony_tests', 'profiler_data' )), array('mongodb://user:password@localhost/symfony_tests/profiler_data', array( 'mongodb://user:password@localhost/symfony_tests', 'symfony_tests', 'profiler_data' )), array('mongodb://user:password@localhost/admin/symfony_tests/profiler_data', array( 'mongodb://user:password@localhost/admin', 'symfony_tests', 'profiler_data' )), array('mongodb://user:password@localhost:27009,localhost:27010/?replicaSet=rs-name&authSource=admin/symfony_tests/profiler_data', array( 'mongodb://user:password@localhost:27009,localhost:27010/?replicaSet=rs-name&authSource=admin', 'symfony_tests', 'profiler_data' )) ); } 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(); } /** * @dataProvider getDsns */ public function testDsnParser($dsn, $expected) { $m = new \ReflectionMethod(self::$storage, 'parseDsn'); $m->setAccessible(true); $this->assertEquals($expected, $m->invoke(self::$storage, $dsn)); } 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'); } } } Symfony/Component/HttpKernel/Tests/Profiler/FileProfilerStorageTest.php000064400000005347152410105270022404 0ustar00 * * 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)); } } Symfony/Component/HttpKernel/Tests/Profiler/SqliteProfilerStorageTest.php000064400000002516152410105270022761 0ustar00 * * 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; } } Symfony/Component/HttpKernel/Tests/Profiler/AbstractProfilerStorageTest.php000064400000024736152410105270023273 0ustar00 * * 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(); } Symfony/Component/HttpKernel/Tests/Profiler/MemcacheProfilerStorageTest.php000064400000002331152410105270023215 0ustar00 * * 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; } } Symfony/Component/HttpKernel/Tests/EventListener/TestSessionListenerTest.php000064400000007165152410105270023473 0ustar00 * * 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\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\HttpKernelInterface; use Symfony\Component\HttpKernel\Event\FilterResponseEvent; use Symfony\Component\HttpFoundation\Session\SessionInterface; /** * SessionListenerTest. * * Tests SessionListener. * * @author Bulat Shakirzyanov */ class TestSessionListenerTest extends \PHPUnit_Framework_TestCase { /** * @var TestSessionListener */ private $listener; /** * @var SessionInterface */ private $session; protected function setUp() { $this->listener = $this->getMockForAbstractClass('Symfony\Component\HttpKernel\EventListener\TestSessionListener'); $this->session = $this->getSession(); } public function testShouldSaveMasterRequestSession() { $this->sessionHasBeenStarted(); $this->sessionMustBeSaved(); $this->filterResponse(new Request()); } public function testShouldNotSaveSubRequestSession() { $this->sessionMustNotBeSaved(); $this->filterResponse(new Request(), HttpKernelInterface::SUB_REQUEST); } public function testDoesNotDeleteCookieIfUsingSessionLifetime() { $this->sessionHasBeenStarted(); $params = session_get_cookie_params(); session_set_cookie_params(0, $params['path'], $params['domain'], $params['secure'], $params['httponly']); $response = $this->filterResponse(new Request(), HttpKernelInterface::MASTER_REQUEST); $cookies = $response->headers->getCookies(); $this->assertEquals(0, reset($cookies)->getExpiresTime()); } public function testUnstartedSessionIsNotSave() { $this->sessionHasNotBeenStarted(); $this->sessionMustNotBeSaved(); $this->filterResponse(new Request()); } private function filterResponse(Request $request, $type = HttpKernelInterface::MASTER_REQUEST) { $request->setSession($this->session); $response = new Response(); $kernel = $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface'); $event = new FilterResponseEvent($kernel, $request, $type, $response); $this->listener->onKernelResponse($event); $this->assertSame($response, $event->getResponse()); return $response; } private function sessionMustNotBeSaved() { $this->session->expects($this->never()) ->method('save'); } private function sessionMustBeSaved() { $this->session->expects($this->once()) ->method('save'); } private function sessionHasBeenStarted() { $this->session->expects($this->once()) ->method('isStarted') ->will($this->returnValue(true)); } private function sessionHasNotBeenStarted() { $this->session->expects($this->once()) ->method('isStarted') ->will($this->returnValue(false)); } private function getSession() { $mock = $this->getMockBuilder('Symfony\Component\HttpFoundation\Session\Session') ->disableOriginalConstructor() ->getMock(); // set return value for getName() $mock->expects($this->any())->method('getName')->will($this->returnValue('MOCKSESSID')); return $mock; } } Symfony/Component/HttpKernel/Tests/EventListener/ResponseListenerTest.php000064400000006550152410105270023003 0ustar00 * * 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() { $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()); } } Symfony/Component/HttpKernel/Tests/EventListener/ExceptionListenerTest.php000064400000010564152410105270023143 0ustar00 * * 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 */ class ExceptionListenerTest extends \PHPUnit_Framework_TestCase { 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'); } } Symfony/Component/HttpKernel/Tests/EventListener/RouterListenerTest.php000064400000012066152410105270022464 0ustar00 * * 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\HttpFoundation\RequestStack; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\EventListener\RouterListener; use Symfony\Component\HttpKernel\HttpKernelInterface; use Symfony\Component\HttpKernel\Event\GetResponseEvent; use Symfony\Component\Routing\RequestContext; class RouterListenerTest extends \PHPUnit_Framework_TestCase { private $requestStack; public function setUp() { $this->requestStack = $this->getMock('Symfony\Component\HttpFoundation\RequestStack', array(), array(), '', false); } /** * @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, null, null, $this->requestStack); $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(), null, null, $this->requestStack); } 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(), null, $this->requestStack); $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(), null, $this->requestStack); $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()); } } Symfony/Component/HttpKernel/Tests/EventListener/EsiListenerTest.php000064400000005371152410105270021725 0ustar00 * * 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 { public function testFilterDoesNothingForSubRequests() { $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::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 '); $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')); } } Symfony/Component/HttpKernel/Tests/EventListener/LocaleListenerTest.php000064400000007666152410105270022415 0ustar00 * * 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\HttpFoundation\RequestStack; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\EventListener\LocaleListener; use Symfony\Component\HttpKernel\HttpKernelInterface; use Symfony\Component\HttpKernel\Event\GetResponseEvent; class LocaleListenerTest extends \PHPUnit_Framework_TestCase { private $requestStack; protected function setUp() { $this->requestStack = $this->getMock('Symfony\Component\HttpFoundation\RequestStack', array(), array(), '', false); } public function testDefaultLocaleWithoutSession() { $listener = new LocaleListener('fr', null, $this->requestStack); $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', null, $this->requestStack); $event = $this->getEvent($request); $listener->onKernelRequest($event); $this->assertEquals('es', $request->getLocale()); } public function testLocaleSetForRoutingContext() { // 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, $this->requestStack); $listener->onKernelRequest($this->getEvent($request)); } public function testRouterResetWithParentRequestOnKernelFinishRequest() { 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)); $parentRequest = Request::create('/'); $parentRequest->setLocale('es'); $this->requestStack->expects($this->once())->method('getParentRequest')->will($this->returnValue($parentRequest)); $event = $this->getMock('Symfony\Component\HttpKernel\Event\FinishRequestEvent', array(), array(), '', false); $listener = new LocaleListener('fr', $router, $this->requestStack); $listener->onKernelFinishRequest($event); } public function testRequestLocaleIsNotOverridden() { $request = Request::create('/'); $request->setLocale('de'); $listener = new LocaleListener('fr', null, $this->requestStack); $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); } } Symfony/Component/HttpKernel/Tests/EventListener/ProfilerListenerTest.php000064400000010153152410105270022761 0ustar00 * * 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\ProfilerListener; use Symfony\Component\HttpKernel\Event\FilterResponseEvent; use Symfony\Component\HttpKernel\Event\GetResponseEvent; use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent; use Symfony\Component\HttpKernel\Event\PostResponseEvent; use Symfony\Component\HttpKernel\Exception\HttpException; use Symfony\Component\HttpKernel\Kernel; class ProfilerListenerTest extends \PHPUnit_Framework_TestCase { /** * Test to ensure BC without RequestStack * * @deprecated Deprecated since version 2.4, to be removed in 3.0. */ public function testEventsWithoutRequestStack() { $profile = $this->getMockBuilder('Symfony\Component\HttpKernel\Profiler\Profile') ->disableOriginalConstructor() ->getMock(); $profiler = $this->getMockBuilder('Symfony\Component\HttpKernel\Profiler\Profiler') ->disableOriginalConstructor() ->getMock(); $profiler->expects($this->once()) ->method('collect') ->will($this->returnValue($profile)); $kernel = $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface'); $request = $this->getMockBuilder('Symfony\Component\HttpFoundation\Request') ->disableOriginalConstructor() ->getMock(); $response = $this->getMockBuilder('Symfony\Component\HttpFoundation\Response') ->disableOriginalConstructor() ->getMock(); $listener = new ProfilerListener($profiler); $listener->onKernelRequest(new GetResponseEvent($kernel, $request, Kernel::MASTER_REQUEST)); $listener->onKernelResponse(new FilterResponseEvent($kernel, $request, Kernel::MASTER_REQUEST, $response)); $listener->onKernelTerminate(new PostResponseEvent($kernel, $request, $response)); } /** * Test a master and sub request with an exception and `onlyException` profiler option enabled. */ public function testKernelTerminate() { $profile = $this->getMockBuilder('Symfony\Component\HttpKernel\Profiler\Profile') ->disableOriginalConstructor() ->getMock(); $profiler = $this->getMockBuilder('Symfony\Component\HttpKernel\Profiler\Profiler') ->disableOriginalConstructor() ->getMock(); $profiler->expects($this->once()) ->method('collect') ->will($this->returnValue($profile)); $kernel = $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface'); $masterRequest = $this->getMockBuilder('Symfony\Component\HttpFoundation\Request') ->disableOriginalConstructor() ->getMock(); $subRequest = $this->getMockBuilder('Symfony\Component\HttpFoundation\Request') ->disableOriginalConstructor() ->getMock(); $response = $this->getMockBuilder('Symfony\Component\HttpFoundation\Response') ->disableOriginalConstructor() ->getMock(); $onlyException = true; $listener = new ProfilerListener($profiler, null, $onlyException); // master request $listener->onKernelRequest(new GetResponseEvent($kernel, $masterRequest, Kernel::MASTER_REQUEST)); $listener->onKernelResponse(new FilterResponseEvent($kernel, $masterRequest, Kernel::MASTER_REQUEST, $response)); // sub request $listener->onKernelRequest(new GetResponseEvent($kernel, $subRequest, Kernel::SUB_REQUEST)); $listener->onKernelException(new GetResponseForExceptionEvent($kernel, $subRequest, Kernel::SUB_REQUEST, new HttpException(404))); $listener->onKernelResponse(new FilterResponseEvent($kernel, $subRequest, Kernel::SUB_REQUEST, $response)); $listener->onKernelTerminate(new PostResponseEvent($kernel, $masterRequest, $response)); } } Symfony/Component/HttpKernel/Tests/EventListener/FragmentListenerTest.php000064400000006457152410105270022756 0ustar00 * * 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 { 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); } } Symfony/Component/HttpKernel/Tests/TestHttpKernel.php000064400000002107152410105270016762 0ustar00 * * 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()); } } Symfony/Component/HttpKernel/Tests/Bundle/BundleTest.php000064400000004267152410105270017335 0ustar00 * * 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\Bundle\FrameworkBundle\DependencyInjection\Compiler\AddConsoleCommandPass; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\HttpKernel\Bundle\Bundle; use Symfony\Component\HttpKernel\Tests\Fixtures\ExtensionAbsentBundle\ExtensionAbsentBundle; use Symfony\Component\HttpKernel\Tests\Fixtures\ExtensionPresentBundle\Command\FooCommand; use Symfony\Component\HttpKernel\Tests\Fixtures\ExtensionPresentBundle\ExtensionPresentBundle; class BundleTest extends \PHPUnit_Framework_TestCase { public function testRegisterCommands() { $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)); } public function testRegisterCommandsIngoreCommandAsAService() { $container = new ContainerBuilder(); $container->addCompilerPass(new AddConsoleCommandPass()); $definition = new Definition('Symfony\Component\HttpKernel\Tests\Fixtures\ExtensionPresentBundle\Command\FooCommand'); $definition->addTag('console.command'); $container->setDefinition('my-command', $definition); $container->compile(); $application = $this->getMock('Symfony\Component\Console\Application'); // Never called, because it's the // Symfony\Bundle\FrameworkBundle\Console\Application that register // commands as a service $application->expects($this->never())->method('add'); $bundle = new ExtensionPresentBundle(); $bundle->setContainer($container); $bundle->registerCommands($application); } } Symfony/Component/HttpKernel/Tests/KernelTest.php000064400000063276152410105270016140 0ustar00 * * 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\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 { 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->getKernel(array('initializeBundles', 'initializeContainer')); $kernel->expects($this->once()) ->method('initializeBundles'); $kernel->expects($this->once()) ->method('initializeContainer'); $kernel->boot(); } public function testBootSetsTheContainerToTheBundles() { $bundle = $this->getMock('Symfony\Component\HttpKernel\Bundle\Bundle'); $bundle->expects($this->once()) ->method('setContainer'); $kernel = $this->getKernel(array('initializeBundles', 'initializeContainer', 'getBundles')); $kernel->expects($this->once()) ->method('getBundles') ->will($this->returnValue(array($bundle))); $kernel->boot(); } public function testBootSetsTheBootedFlagToTrue() { // use test kernel to access isBooted() $kernel = $this->getKernelForTest(array('initializeBundles', 'initializeContainer')); $kernel->boot(); $this->assertTrue($kernel->isBooted()); } public function testClassCacheIsLoaded() { $kernel = $this->getKernel(array('initializeBundles', 'initializeContainer', 'doLoadClassCache')); $kernel->loadClassCache('name', '.extension'); $kernel->expects($this->once()) ->method('doLoadClassCache') ->with('name', '.extension'); $kernel->boot(); } public function testClassCacheIsNotLoadedByDefault() { $kernel = $this->getKernel(array('initializeBundles', 'initializeContainer')); $kernel->expects($this->never()) ->method('doLoadClassCache'); $kernel->boot(); } public function testClassCacheIsNotLoadedWhenKernelIsNotBooted() { $kernel = $this->getKernel(array('initializeBundles', 'initializeContainer', 'doLoadClassCache')); $kernel->loadClassCache(); $kernel->expects($this->never()) ->method('doLoadClassCache'); } public function testBootKernelSeveralTimesOnlyInitializesBundlesOnce() { $kernel = $this->getKernel(array('initializeBundles', 'initializeContainer')); $kernel->expects($this->once()) ->method('initializeBundles'); $kernel->boot(); $kernel->boot(); } public function testShutdownCallsShutdownOnAllBundles() { $bundle = $this->getMock('Symfony\Component\HttpKernel\Bundle\Bundle'); $bundle->expects($this->once()) ->method('shutdown'); $kernel = $this->getKernel(array(), array($bundle)); $kernel->boot(); $kernel->shutdown(); } public function testShutdownGivesNullContainerToAllBundles() { $bundle = $this->getMock('Symfony\Component\HttpKernel\Bundle\Bundle'); $bundle->expects($this->at(3)) ->method('setContainer') ->with(null); $kernel = $this->getKernel(array('getBundles')); $kernel->expects($this->any()) ->method('getBundles') ->will($this->returnValue(array($bundle))); $kernel->boot(); $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->getKernel(array('getHttpKernel')); $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->getKernel(array('getHttpKernel', 'boot')); $kernel->expects($this->once()) ->method('getHttpKernel') ->will($this->returnValue($httpKernelMock)); $kernel->expects($this->once()) ->method('boot'); $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' 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->getKernel(array('getBundles')); $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->getKernel()->locateResource('Foo'); } /** * @expectedException \RuntimeException */ public function testLocateResourceThrowsExceptionWhenNameIsUnsafe() { $this->getKernel()->locateResource('@FooBundle/../bar'); } /** * @expectedException \InvalidArgumentException */ public function testLocateResourceThrowsExceptionWhenBundleDoesNotExist() { $this->getKernel()->locateResource('@FooBundle/config/routing.xml'); } /** * @expectedException \InvalidArgumentException */ public function testLocateResourceThrowsExceptionWhenResourceDoesNotExist() { $kernel = $this->getKernel(array('getBundle')); $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(array('getBundle')); $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(array('getBundle')); $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(array('getBundle')); $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(array('getBundle')); $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(array('getBundle')); $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(array('getBundle')); $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(array('getBundle')); $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(array('getBundle')); $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(array('getBundle')); $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(array('getBundle')); $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'); // use test kernel so we can access getBundleMap() $kernel = $this->getKernelForTest(array('registerBundles')); $kernel ->expects($this->once()) ->method('registerBundles') ->will($this->returnValue(array($parent, $child))) ; $kernel->boot(); $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'); // use test kernel so we can access getBundleMap() $kernel = $this->getKernelForTest(array('registerBundles')); $kernel ->expects($this->once()) ->method('registerBundles') ->will($this->returnValue(array($grandparent, $parent, $child))) ; $kernel->boot(); $map = $kernel->getBundleMap(); $this->assertEquals(array($child, $parent, $grandparent), $map['GrandParentBBundle']); $this->assertEquals(array($child, $parent), $map['ParentBBundle']); $this->assertEquals(array($child), $map['ChildBBundle']); } /** * @expectedException \LogicException * @expectedExceptionMessage Bundle "ChildCBundle" extends bundle "FooBar", which is not registered. */ public function testInitializeBundlesThrowsExceptionWhenAParentDoesNotExists() { $child = $this->getBundle(null, 'FooBar', 'ChildCBundle'); $kernel = $this->getKernel(array(), array($child)); $kernel->boot(); } public function testInitializeBundlesSupportsArbitraryBundleRegistrationOrder() { $grandparent = $this->getBundle(null, null, 'GrandParentCBundle'); $parent = $this->getBundle(null, 'GrandParentCBundle', 'ParentCBundle'); $child = $this->getBundle(null, 'ParentCBundle', 'ChildCBundle'); // use test kernel so we can access getBundleMap() $kernel = $this->getKernelForTest(array('registerBundles')); $kernel ->expects($this->once()) ->method('registerBundles') ->will($this->returnValue(array($parent, $grandparent, $child))) ; $kernel->boot(); $map = $kernel->getBundleMap(); $this->assertEquals(array($child, $parent, $grandparent), $map['GrandParentCBundle']); $this->assertEquals(array($child, $parent), $map['ParentCBundle']); $this->assertEquals(array($child), $map['ChildCBundle']); } /** * @expectedException \LogicException * @expectedExceptionMessage Bundle "ParentCBundle" is directly extended by two bundles "ChildC2Bundle" and "ChildC1Bundle". */ public function testInitializeBundlesThrowsExceptionWhenABundleIsDirectlyExtendedByTwoBundles() { $parent = $this->getBundle(null, null, 'ParentCBundle'); $child1 = $this->getBundle(null, 'ParentCBundle', 'ChildC1Bundle'); $child2 = $this->getBundle(null, 'ParentCBundle', 'ChildC2Bundle'); $kernel = $this->getKernel(array(), array($parent, $child1, $child2)); $kernel->boot(); } /** * @expectedException \LogicException * @expectedExceptionMessage Trying to register two bundles with the same name "DuplicateName" */ public function testInitializeBundleThrowsExceptionWhenRegisteringTwoBundlesWithTheSameName() { $fooBundle = $this->getBundle(null, null, 'FooBundle', 'DuplicateName'); $barBundle = $this->getBundle(null, null, 'BarBundle', 'DuplicateName'); $kernel = $this->getKernel(array(), array($fooBundle, $barBundle)); $kernel->boot(); } /** * @expectedException \LogicException * @expectedExceptionMessage Bundle "CircularRefBundle" can not extend itself. */ public function testInitializeBundleThrowsExceptionWhenABundleExtendsItself() { $circularRef = $this->getBundle(null, 'CircularRefBundle', 'CircularRefBundle'); $kernel = $this->getKernel(array(), array($circularRef)); $kernel->boot(); } public function testTerminateReturnsSilentlyIfKernelIsNotBooted() { $kernel = $this->getKernel(array('getHttpKernel')); $kernel->expects($this->never()) ->method('getHttpKernel'); $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->getKernel(array('getHttpKernel')); $kernel->expects($this->once()) ->method('getHttpKernel') ->will($this->returnValue($httpKernelMock)); $kernel->boot(); $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->getKernel(array('getHttpKernel')); $kernel->expects($this->exactly(2)) ->method('getHttpKernel') ->will($this->returnValue($httpKernelMock)); $kernel->boot(); $kernel->terminate(Request::create('/'), new Response()); } /** * Returns a mock for the BundleInterface * * @return BundleInterface */ 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; } /** * Returns a mock for the abstract kernel. * * @param array $methods Additional methods to mock (besides the abstract ones) * @param array $bundles Bundles to register * * @return Kernel */ protected function getKernel(array $methods = array(), array $bundles = array()) { $methods[] = 'registerBundles'; $kernel = $this ->getMockBuilder('Symfony\Component\HttpKernel\Kernel') ->setMethods($methods) ->setConstructorArgs(array('test', false)) ->getMockForAbstractClass() ; $kernel->expects($this->any()) ->method('registerBundles') ->will($this->returnValue($bundles)) ; $p = new \ReflectionProperty($kernel, 'rootDir'); $p->setAccessible(true); $p->setValue($kernel, __DIR__.'/Fixtures'); return $kernel; } protected function getKernelForTest(array $methods = array()) { $kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\Tests\Fixtures\KernelForTest') ->setConstructorArgs(array('test', false)) ->setMethods($methods) ->getMock(); $p = new \ReflectionProperty($kernel, 'rootDir'); $p->setAccessible(true); $p->setValue($kernel, __DIR__.'/Fixtures'); return $kernel; } } Symfony/Component/HttpKernel/Tests/HttpCache/HttpCacheTest.php000064400000136217152410105270020422 0ustar00 * * 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\HttpCache; use Symfony\Component\HttpKernel\HttpCache\StoreInterface; use Symfony\Component\HttpKernel\HttpKernelInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; class HttpCacheTest extends HttpCacheTestCase { public function testTerminateDelegatesTerminationOnlyForTerminableInterface() { $storeMock = $this->getMockBuilder('Symfony\\Component\\HttpKernel\\HttpCache\\StoreInterface') ->disableOriginalConstructor() ->getMock(); // does not implement TerminableInterface $kernelMock = $this->getMockBuilder('Symfony\\Component\\HttpKernel\\HttpKernelInterface') ->disableOriginalConstructor() ->getMock(); $kernelMock->expects($this->never()) ->method('terminate'); $kernel = new HttpCache($kernelMock, $storeMock); $kernel->terminate(Request::create('/'), new Response()); // implements TerminableInterface $kernelMock = $this->getMockBuilder('Symfony\\Component\\HttpKernel\\Kernel') ->disableOriginalConstructor() ->setMethods(array('terminate', 'registerBundles', 'registerContainerConfiguration')) ->getMock(); $kernelMock->expects($this->once()) ->method('terminate'); $kernel = new HttpCache($kernelMock, $storeMock); $kernel->terminate(Request::create('/'), new Response()); } public function testPassesOnNonGetHeadRequests() { $this->setNextResponse(200); $this->request('POST', '/'); $this->assertHttpKernelIsCalled(); $this->assertResponseOk(); $this->assertTraceContains('pass'); $this->assertFalse($this->response->headers->has('Age')); } public function testInvalidatesOnPostPutDeleteRequests() { foreach (array('post', 'put', 'delete') as $method) { $this->setNextResponse(200); $this->request($method, '/'); $this->assertHttpKernelIsCalled(); $this->assertResponseOk(); $this->assertTraceContains('invalidate'); $this->assertTraceContains('pass'); } } public function testDoesNotCacheWithAuthorizationRequestHeaderAndNonPublicResponse() { $this->setNextResponse(200, array('ETag' => '"Foo"')); $this->request('GET', '/', array('HTTP_AUTHORIZATION' => 'basic foobarbaz')); $this->assertHttpKernelIsCalled(); $this->assertResponseOk(); $this->assertEquals('private', $this->response->headers->get('Cache-Control')); $this->assertTraceContains('miss'); $this->assertTraceNotContains('store'); $this->assertFalse($this->response->headers->has('Age')); } public function testDoesCacheWithAuthorizationRequestHeaderAndPublicResponse() { $this->setNextResponse(200, array('Cache-Control' => 'public', 'ETag' => '"Foo"')); $this->request('GET', '/', array('HTTP_AUTHORIZATION' => 'basic foobarbaz')); $this->assertHttpKernelIsCalled(); $this->assertResponseOk(); $this->assertTraceContains('miss'); $this->assertTraceContains('store'); $this->assertTrue($this->response->headers->has('Age')); $this->assertEquals('public', $this->response->headers->get('Cache-Control')); } public function testDoesNotCacheWithCookieHeaderAndNonPublicResponse() { $this->setNextResponse(200, array('ETag' => '"Foo"')); $this->request('GET', '/', array(), array('foo' => 'bar')); $this->assertHttpKernelIsCalled(); $this->assertResponseOk(); $this->assertEquals('private', $this->response->headers->get('Cache-Control')); $this->assertTraceContains('miss'); $this->assertTraceNotContains('store'); $this->assertFalse($this->response->headers->has('Age')); } public function testDoesNotCacheRequestsWithACookieHeader() { $this->setNextResponse(200); $this->request('GET', '/', array(), array('foo' => 'bar')); $this->assertHttpKernelIsCalled(); $this->assertResponseOk(); $this->assertEquals('private', $this->response->headers->get('Cache-Control')); $this->assertTraceContains('miss'); $this->assertTraceNotContains('store'); $this->assertFalse($this->response->headers->has('Age')); } public function testRespondsWith304WhenIfModifiedSinceMatchesLastModified() { $time = new \DateTime(); $this->setNextResponse(200, array('Cache-Control' => 'public', 'Last-Modified' => $time->format(DATE_RFC2822), 'Content-Type' => 'text/plain'), 'Hello World'); $this->request('GET', '/', array('HTTP_IF_MODIFIED_SINCE' => $time->format(DATE_RFC2822))); $this->assertHttpKernelIsCalled(); $this->assertEquals(304, $this->response->getStatusCode()); $this->assertEquals('', $this->response->headers->get('Content-Type')); $this->assertEmpty($this->response->getContent()); $this->assertTraceContains('miss'); $this->assertTraceContains('store'); } public function testRespondsWith304WhenIfNoneMatchMatchesETag() { $this->setNextResponse(200, array('Cache-Control' => 'public', 'ETag' => '12345', 'Content-Type' => 'text/plain'), 'Hello World'); $this->request('GET', '/', array('HTTP_IF_NONE_MATCH' => '12345')); $this->assertHttpKernelIsCalled(); $this->assertEquals(304, $this->response->getStatusCode()); $this->assertEquals('', $this->response->headers->get('Content-Type')); $this->assertTrue($this->response->headers->has('ETag')); $this->assertEmpty($this->response->getContent()); $this->assertTraceContains('miss'); $this->assertTraceContains('store'); } public function testRespondsWith304OnlyIfIfNoneMatchAndIfModifiedSinceBothMatch() { $time = new \DateTime(); $this->setNextResponse(200, array(), '', function ($request, $response) use ($time) { $response->setStatusCode(200); $response->headers->set('ETag', '12345'); $response->headers->set('Last-Modified', $time->format(DATE_RFC2822)); $response->headers->set('Content-Type', 'text/plain'); $response->setContent('Hello World'); }); // only ETag matches $t = \DateTime::createFromFormat('U', time() - 3600); $this->request('GET', '/', array('HTTP_IF_NONE_MATCH' => '12345', 'HTTP_IF_MODIFIED_SINCE' => $t->format(DATE_RFC2822))); $this->assertHttpKernelIsCalled(); $this->assertEquals(200, $this->response->getStatusCode()); // only Last-Modified matches $this->request('GET', '/', array('HTTP_IF_NONE_MATCH' => '1234', 'HTTP_IF_MODIFIED_SINCE' => $time->format(DATE_RFC2822))); $this->assertHttpKernelIsCalled(); $this->assertEquals(200, $this->response->getStatusCode()); // Both matches $this->request('GET', '/', array('HTTP_IF_NONE_MATCH' => '12345', 'HTTP_IF_MODIFIED_SINCE' => $time->format(DATE_RFC2822))); $this->assertHttpKernelIsCalled(); $this->assertEquals(304, $this->response->getStatusCode()); } public function testValidatesPrivateResponsesCachedOnTheClient() { $this->setNextResponse(200, array(), '', function ($request, $response) { $etags = preg_split('/\s*,\s*/', $request->headers->get('IF_NONE_MATCH')); if ($request->cookies->has('authenticated')) { $response->headers->set('Cache-Control', 'private, no-store'); $response->setETag('"private tag"'); if (in_array('"private tag"', $etags)) { $response->setStatusCode(304); } else { $response->setStatusCode(200); $response->headers->set('Content-Type', 'text/plain'); $response->setContent('private data'); } } else { $response->headers->set('Cache-Control', 'public'); $response->setETag('"public tag"'); if (in_array('"public tag"', $etags)) { $response->setStatusCode(304); } else { $response->setStatusCode(200); $response->headers->set('Content-Type', 'text/plain'); $response->setContent('public data'); } } }); $this->request('GET', '/'); $this->assertHttpKernelIsCalled(); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('"public tag"', $this->response->headers->get('ETag')); $this->assertEquals('public data', $this->response->getContent()); $this->assertTraceContains('miss'); $this->assertTraceContains('store'); $this->request('GET', '/', array(), array('authenticated' => '')); $this->assertHttpKernelIsCalled(); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('"private tag"', $this->response->headers->get('ETag')); $this->assertEquals('private data', $this->response->getContent()); $this->assertTraceContains('stale'); $this->assertTraceContains('invalid'); $this->assertTraceNotContains('store'); } public function testStoresResponsesWhenNoCacheRequestDirectivePresent() { $time = \DateTime::createFromFormat('U', time() + 5); $this->setNextResponse(200, array('Cache-Control' => 'public', 'Expires' => $time->format(DATE_RFC2822))); $this->request('GET', '/', array('HTTP_CACHE_CONTROL' => 'no-cache')); $this->assertHttpKernelIsCalled(); $this->assertTraceContains('store'); $this->assertTrue($this->response->headers->has('Age')); } public function testReloadsResponsesWhenCacheHitsButNoCacheRequestDirectivePresentWhenAllowReloadIsSetTrue() { $count = 0; $this->setNextResponse(200, array('Cache-Control' => 'public, max-age=10000'), '', function ($request, $response) use (&$count) { ++$count; $response->setContent(1 == $count ? 'Hello World' : 'Goodbye World'); }); $this->request('GET', '/'); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('Hello World', $this->response->getContent()); $this->assertTraceContains('store'); $this->request('GET', '/'); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('Hello World', $this->response->getContent()); $this->assertTraceContains('fresh'); $this->cacheConfig['allow_reload'] = true; $this->request('GET', '/', array('HTTP_CACHE_CONTROL' => 'no-cache')); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('Goodbye World', $this->response->getContent()); $this->assertTraceContains('reload'); $this->assertTraceContains('store'); } public function testDoesNotReloadResponsesWhenAllowReloadIsSetFalseDefault() { $count = 0; $this->setNextResponse(200, array('Cache-Control' => 'public, max-age=10000'), '', function ($request, $response) use (&$count) { ++$count; $response->setContent(1 == $count ? 'Hello World' : 'Goodbye World'); }); $this->request('GET', '/'); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('Hello World', $this->response->getContent()); $this->assertTraceContains('store'); $this->request('GET', '/'); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('Hello World', $this->response->getContent()); $this->assertTraceContains('fresh'); $this->cacheConfig['allow_reload'] = false; $this->request('GET', '/', array('HTTP_CACHE_CONTROL' => 'no-cache')); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('Hello World', $this->response->getContent()); $this->assertTraceNotContains('reload'); $this->request('GET', '/', array('HTTP_CACHE_CONTROL' => 'no-cache')); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('Hello World', $this->response->getContent()); $this->assertTraceNotContains('reload'); } public function testRevalidatesFreshCacheEntryWhenMaxAgeRequestDirectiveIsExceededWhenAllowRevalidateOptionIsSetTrue() { $count = 0; $this->setNextResponse(200, array(), '', function ($request, $response) use (&$count) { ++$count; $response->headers->set('Cache-Control', 'public, max-age=10000'); $response->setETag($count); $response->setContent(1 == $count ? 'Hello World' : 'Goodbye World'); }); $this->request('GET', '/'); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('Hello World', $this->response->getContent()); $this->assertTraceContains('store'); $this->request('GET', '/'); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('Hello World', $this->response->getContent()); $this->assertTraceContains('fresh'); $this->cacheConfig['allow_revalidate'] = true; $this->request('GET', '/', array('HTTP_CACHE_CONTROL' => 'max-age=0')); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('Goodbye World', $this->response->getContent()); $this->assertTraceContains('stale'); $this->assertTraceContains('invalid'); $this->assertTraceContains('store'); } public function testDoesNotRevalidateFreshCacheEntryWhenEnableRevalidateOptionIsSetFalseDefault() { $count = 0; $this->setNextResponse(200, array(), '', function ($request, $response) use (&$count) { ++$count; $response->headers->set('Cache-Control', 'public, max-age=10000'); $response->setETag($count); $response->setContent(1 == $count ? 'Hello World' : 'Goodbye World'); }); $this->request('GET', '/'); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('Hello World', $this->response->getContent()); $this->assertTraceContains('store'); $this->request('GET', '/'); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('Hello World', $this->response->getContent()); $this->assertTraceContains('fresh'); $this->cacheConfig['allow_revalidate'] = false; $this->request('GET', '/', array('HTTP_CACHE_CONTROL' => 'max-age=0')); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('Hello World', $this->response->getContent()); $this->assertTraceNotContains('stale'); $this->assertTraceNotContains('invalid'); $this->assertTraceContains('fresh'); $this->request('GET', '/', array('HTTP_CACHE_CONTROL' => 'max-age=0')); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('Hello World', $this->response->getContent()); $this->assertTraceNotContains('stale'); $this->assertTraceNotContains('invalid'); $this->assertTraceContains('fresh'); } public function testFetchesResponseFromBackendWhenCacheMisses() { $time = \DateTime::createFromFormat('U', time() + 5); $this->setNextResponse(200, array('Cache-Control' => 'public', 'Expires' => $time->format(DATE_RFC2822))); $this->request('GET', '/'); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertTraceContains('miss'); $this->assertTrue($this->response->headers->has('Age')); } public function testDoesNotCacheSomeStatusCodeResponses() { foreach (array_merge(range(201, 202), range(204, 206), range(303, 305), range(400, 403), range(405, 409), range(411, 417), range(500, 505)) as $code) { $time = \DateTime::createFromFormat('U', time() + 5); $this->setNextResponse($code, array('Expires' => $time->format(DATE_RFC2822))); $this->request('GET', '/'); $this->assertEquals($code, $this->response->getStatusCode()); $this->assertTraceNotContains('store'); $this->assertFalse($this->response->headers->has('Age')); } } public function testDoesNotCacheResponsesWithExplicitNoStoreDirective() { $time = \DateTime::createFromFormat('U', time() + 5); $this->setNextResponse(200, array('Expires' => $time->format(DATE_RFC2822), 'Cache-Control' => 'no-store')); $this->request('GET', '/'); $this->assertTraceNotContains('store'); $this->assertFalse($this->response->headers->has('Age')); } public function testDoesNotCacheResponsesWithoutFreshnessInformationOrAValidator() { $this->setNextResponse(); $this->request('GET', '/'); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertTraceNotContains('store'); } public function testCachesResponsesWithExplicitNoCacheDirective() { $time = \DateTime::createFromFormat('U', time() + 5); $this->setNextResponse(200, array('Expires' => $time->format(DATE_RFC2822), 'Cache-Control' => 'public, no-cache')); $this->request('GET', '/'); $this->assertTraceContains('store'); $this->assertTrue($this->response->headers->has('Age')); } public function testCachesResponsesWithAnExpirationHeader() { $time = \DateTime::createFromFormat('U', time() + 5); $this->setNextResponse(200, array('Cache-Control' => 'public', 'Expires' => $time->format(DATE_RFC2822))); $this->request('GET', '/'); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('Hello World', $this->response->getContent()); $this->assertNotNull($this->response->headers->get('Date')); $this->assertNotNull($this->response->headers->get('X-Content-Digest')); $this->assertTraceContains('miss'); $this->assertTraceContains('store'); $values = $this->getMetaStorageValues(); $this->assertCount(1, $values); } public function testCachesResponsesWithAMaxAgeDirective() { $this->setNextResponse(200, array('Cache-Control' => 'public, max-age=5')); $this->request('GET', '/'); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('Hello World', $this->response->getContent()); $this->assertNotNull($this->response->headers->get('Date')); $this->assertNotNull($this->response->headers->get('X-Content-Digest')); $this->assertTraceContains('miss'); $this->assertTraceContains('store'); $values = $this->getMetaStorageValues(); $this->assertCount(1, $values); } public function testCachesResponsesWithASMaxAgeDirective() { $this->setNextResponse(200, array('Cache-Control' => 's-maxage=5')); $this->request('GET', '/'); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('Hello World', $this->response->getContent()); $this->assertNotNull($this->response->headers->get('Date')); $this->assertNotNull($this->response->headers->get('X-Content-Digest')); $this->assertTraceContains('miss'); $this->assertTraceContains('store'); $values = $this->getMetaStorageValues(); $this->assertCount(1, $values); } public function testCachesResponsesWithALastModifiedValidatorButNoFreshnessInformation() { $time = \DateTime::createFromFormat('U', time()); $this->setNextResponse(200, array('Cache-Control' => 'public', 'Last-Modified' => $time->format(DATE_RFC2822))); $this->request('GET', '/'); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('Hello World', $this->response->getContent()); $this->assertTraceContains('miss'); $this->assertTraceContains('store'); } public function testCachesResponsesWithAnETagValidatorButNoFreshnessInformation() { $this->setNextResponse(200, array('Cache-Control' => 'public', 'ETag' => '"123456"')); $this->request('GET', '/'); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('Hello World', $this->response->getContent()); $this->assertTraceContains('miss'); $this->assertTraceContains('store'); } public function testHitsCachedResponsesWithExpiresHeader() { $time1 = \DateTime::createFromFormat('U', time() - 5); $time2 = \DateTime::createFromFormat('U', time() + 5); $this->setNextResponse(200, array('Cache-Control' => 'public', 'Date' => $time1->format(DATE_RFC2822), 'Expires' => $time2->format(DATE_RFC2822))); $this->request('GET', '/'); $this->assertHttpKernelIsCalled(); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertNotNull($this->response->headers->get('Date')); $this->assertTraceContains('miss'); $this->assertTraceContains('store'); $this->assertEquals('Hello World', $this->response->getContent()); $this->request('GET', '/'); $this->assertHttpKernelIsNotCalled(); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertTrue(strtotime($this->responses[0]->headers->get('Date')) - strtotime($this->response->headers->get('Date')) < 2); $this->assertTrue($this->response->headers->get('Age') > 0); $this->assertNotNull($this->response->headers->get('X-Content-Digest')); $this->assertTraceContains('fresh'); $this->assertTraceNotContains('store'); $this->assertEquals('Hello World', $this->response->getContent()); } public function testHitsCachedResponseWithMaxAgeDirective() { $time = \DateTime::createFromFormat('U', time() - 5); $this->setNextResponse(200, array('Date' => $time->format(DATE_RFC2822), 'Cache-Control' => 'public, max-age=10')); $this->request('GET', '/'); $this->assertHttpKernelIsCalled(); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertNotNull($this->response->headers->get('Date')); $this->assertTraceContains('miss'); $this->assertTraceContains('store'); $this->assertEquals('Hello World', $this->response->getContent()); $this->request('GET', '/'); $this->assertHttpKernelIsNotCalled(); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertTrue(strtotime($this->responses[0]->headers->get('Date')) - strtotime($this->response->headers->get('Date')) < 2); $this->assertTrue($this->response->headers->get('Age') > 0); $this->assertNotNull($this->response->headers->get('X-Content-Digest')); $this->assertTraceContains('fresh'); $this->assertTraceNotContains('store'); $this->assertEquals('Hello World', $this->response->getContent()); } public function testHitsCachedResponseWithSMaxAgeDirective() { $time = \DateTime::createFromFormat('U', time() - 5); $this->setNextResponse(200, array('Date' => $time->format(DATE_RFC2822), 'Cache-Control' => 's-maxage=10, max-age=0')); $this->request('GET', '/'); $this->assertHttpKernelIsCalled(); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertNotNull($this->response->headers->get('Date')); $this->assertTraceContains('miss'); $this->assertTraceContains('store'); $this->assertEquals('Hello World', $this->response->getContent()); $this->request('GET', '/'); $this->assertHttpKernelIsNotCalled(); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertTrue(strtotime($this->responses[0]->headers->get('Date')) - strtotime($this->response->headers->get('Date')) < 2); $this->assertTrue($this->response->headers->get('Age') > 0); $this->assertNotNull($this->response->headers->get('X-Content-Digest')); $this->assertTraceContains('fresh'); $this->assertTraceNotContains('store'); $this->assertEquals('Hello World', $this->response->getContent()); } public function testAssignsDefaultTtlWhenResponseHasNoFreshnessInformation() { $this->setNextResponse(); $this->cacheConfig['default_ttl'] = 10; $this->request('GET', '/'); $this->assertHttpKernelIsCalled(); $this->assertTraceContains('miss'); $this->assertTraceContains('store'); $this->assertEquals('Hello World', $this->response->getContent()); $this->assertRegExp('/s-maxage=10/', $this->response->headers->get('Cache-Control')); $this->cacheConfig['default_ttl'] = 10; $this->request('GET', '/'); $this->assertHttpKernelIsNotCalled(); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertTraceContains('fresh'); $this->assertTraceNotContains('store'); $this->assertEquals('Hello World', $this->response->getContent()); } public function testDoesNotAssignDefaultTtlWhenResponseHasMustRevalidateDirective() { $this->setNextResponse(200, array('Cache-Control' => 'must-revalidate')); $this->cacheConfig['default_ttl'] = 10; $this->request('GET', '/'); $this->assertHttpKernelIsCalled(); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertTraceContains('miss'); $this->assertTraceNotContains('store'); $this->assertNotRegExp('/s-maxage/', $this->response->headers->get('Cache-Control')); $this->assertEquals('Hello World', $this->response->getContent()); } public function testFetchesFullResponseWhenCacheStaleAndNoValidatorsPresent() { $time = \DateTime::createFromFormat('U', time() + 5); $this->setNextResponse(200, array('Cache-Control' => 'public', 'Expires' => $time->format(DATE_RFC2822))); // build initial request $this->request('GET', '/'); $this->assertHttpKernelIsCalled(); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertNotNull($this->response->headers->get('Date')); $this->assertNotNull($this->response->headers->get('X-Content-Digest')); $this->assertNotNull($this->response->headers->get('Age')); $this->assertTraceContains('miss'); $this->assertTraceContains('store'); $this->assertEquals('Hello World', $this->response->getContent()); # go in and play around with the cached metadata directly ... $values = $this->getMetaStorageValues(); $this->assertCount(1, $values); $tmp = unserialize($values[0]); $time = \DateTime::createFromFormat('U', time()); $tmp[0][1]['expires'] = $time->format(DATE_RFC2822); $r = new \ReflectionObject($this->store); $m = $r->getMethod('save'); $m->setAccessible(true); $m->invoke($this->store, 'md'.hash('sha256', 'http://localhost/'), serialize($tmp)); // build subsequent request; should be found but miss due to freshness $this->request('GET', '/'); $this->assertHttpKernelIsCalled(); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertTrue($this->response->headers->get('Age') <= 1); $this->assertNotNull($this->response->headers->get('X-Content-Digest')); $this->assertTraceContains('stale'); $this->assertTraceNotContains('fresh'); $this->assertTraceNotContains('miss'); $this->assertTraceContains('store'); $this->assertEquals('Hello World', $this->response->getContent()); } public function testValidatesCachedResponsesWithLastModifiedAndNoFreshnessInformation() { $time = \DateTime::createFromFormat('U', time()); $this->setNextResponse(200, array(), 'Hello World', function ($request, $response) use ($time) { $response->headers->set('Cache-Control', 'public'); $response->headers->set('Last-Modified', $time->format(DATE_RFC2822)); if ($time->format(DATE_RFC2822) == $request->headers->get('IF_MODIFIED_SINCE')) { $response->setStatusCode(304); $response->setContent(''); } }); // build initial request $this->request('GET', '/'); $this->assertHttpKernelIsCalled(); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertNotNull($this->response->headers->get('Last-Modified')); $this->assertNotNull($this->response->headers->get('X-Content-Digest')); $this->assertEquals('Hello World', $this->response->getContent()); $this->assertTraceContains('miss'); $this->assertTraceContains('store'); $this->assertTraceNotContains('stale'); // build subsequent request; should be found but miss due to freshness $this->request('GET', '/'); $this->assertHttpKernelIsCalled(); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertNotNull($this->response->headers->get('Last-Modified')); $this->assertNotNull($this->response->headers->get('X-Content-Digest')); $this->assertTrue($this->response->headers->get('Age') <= 1); $this->assertEquals('Hello World', $this->response->getContent()); $this->assertTraceContains('stale'); $this->assertTraceContains('valid'); $this->assertTraceContains('store'); $this->assertTraceNotContains('miss'); } public function testValidatesCachedResponsesWithETagAndNoFreshnessInformation() { $this->setNextResponse(200, array(), 'Hello World', function ($request, $response) { $response->headers->set('Cache-Control', 'public'); $response->headers->set('ETag', '"12345"'); if ($response->getETag() == $request->headers->get('IF_NONE_MATCH')) { $response->setStatusCode(304); $response->setContent(''); } }); // build initial request $this->request('GET', '/'); $this->assertHttpKernelIsCalled(); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertNotNull($this->response->headers->get('ETag')); $this->assertNotNull($this->response->headers->get('X-Content-Digest')); $this->assertEquals('Hello World', $this->response->getContent()); $this->assertTraceContains('miss'); $this->assertTraceContains('store'); // build subsequent request; should be found but miss due to freshness $this->request('GET', '/'); $this->assertHttpKernelIsCalled(); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertNotNull($this->response->headers->get('ETag')); $this->assertNotNull($this->response->headers->get('X-Content-Digest')); $this->assertTrue($this->response->headers->get('Age') <= 1); $this->assertEquals('Hello World', $this->response->getContent()); $this->assertTraceContains('stale'); $this->assertTraceContains('valid'); $this->assertTraceContains('store'); $this->assertTraceNotContains('miss'); } public function testReplacesCachedResponsesWhenValidationResultsInNon304Response() { $time = \DateTime::createFromFormat('U', time()); $count = 0; $this->setNextResponse(200, array(), 'Hello World', function ($request, $response) use ($time, &$count) { $response->headers->set('Last-Modified', $time->format(DATE_RFC2822)); $response->headers->set('Cache-Control', 'public'); switch (++$count) { case 1: $response->setContent('first response'); break; case 2: $response->setContent('second response'); break; case 3: $response->setContent(''); $response->setStatusCode(304); break; } }); // first request should fetch from backend and store in cache $this->request('GET', '/'); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('first response', $this->response->getContent()); // second request is validated, is invalid, and replaces cached entry $this->request('GET', '/'); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('second response', $this->response->getContent()); // third response is validated, valid, and returns cached entry $this->request('GET', '/'); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('second response', $this->response->getContent()); $this->assertEquals(3, $count); } public function testPassesHeadRequestsThroughDirectlyOnPass() { $that = $this; $this->setNextResponse(200, array(), 'Hello World', function ($request, $response) use ($that) { $response->setContent(''); $response->setStatusCode(200); $that->assertEquals('HEAD', $request->getMethod()); }); $this->request('HEAD', '/', array('HTTP_EXPECT' => 'something ...')); $this->assertHttpKernelIsCalled(); $this->assertEquals('', $this->response->getContent()); } public function testUsesCacheToRespondToHeadRequestsWhenFresh() { $that = $this; $this->setNextResponse(200, array(), 'Hello World', function ($request, $response) use ($that) { $response->headers->set('Cache-Control', 'public, max-age=10'); $response->setContent('Hello World'); $response->setStatusCode(200); $that->assertNotEquals('HEAD', $request->getMethod()); }); $this->request('GET', '/'); $this->assertHttpKernelIsCalled(); $this->assertEquals('Hello World', $this->response->getContent()); $this->request('HEAD', '/'); $this->assertHttpKernelIsNotCalled(); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('', $this->response->getContent()); $this->assertEquals(strlen('Hello World'), $this->response->headers->get('Content-Length')); } public function testSendsNoContentWhenFresh() { $time = \DateTime::createFromFormat('U', time()); $that = $this; $this->setNextResponse(200, array(), 'Hello World', function ($request, $response) use ($that, $time) { $response->headers->set('Cache-Control', 'public, max-age=10'); $response->headers->set('Last-Modified', $time->format(DATE_RFC2822)); }); $this->request('GET', '/'); $this->assertHttpKernelIsCalled(); $this->assertEquals('Hello World', $this->response->getContent()); $this->request('GET', '/', array('HTTP_IF_MODIFIED_SINCE' => $time->format(DATE_RFC2822))); $this->assertHttpKernelIsNotCalled(); $this->assertEquals(304, $this->response->getStatusCode()); $this->assertEquals('', $this->response->getContent()); } public function testInvalidatesCachedResponsesOnPost() { $this->setNextResponse(200, array(), 'Hello World', function ($request, $response) { if ('GET' == $request->getMethod()) { $response->setStatusCode(200); $response->headers->set('Cache-Control', 'public, max-age=500'); $response->setContent('Hello World'); } elseif ('POST' == $request->getMethod()) { $response->setStatusCode(303); $response->headers->set('Location', '/'); $response->headers->remove('Cache-Control'); $response->setContent(''); } }); // build initial request to enter into the cache $this->request('GET', '/'); $this->assertHttpKernelIsCalled(); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('Hello World', $this->response->getContent()); $this->assertTraceContains('miss'); $this->assertTraceContains('store'); // make sure it is valid $this->request('GET', '/'); $this->assertHttpKernelIsNotCalled(); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('Hello World', $this->response->getContent()); $this->assertTraceContains('fresh'); // now POST to same URL $this->request('POST', '/helloworld'); $this->assertHttpKernelIsCalled(); $this->assertEquals('/', $this->response->headers->get('Location')); $this->assertTraceContains('invalidate'); $this->assertTraceContains('pass'); $this->assertEquals('', $this->response->getContent()); // now make sure it was actually invalidated $this->request('GET', '/'); $this->assertHttpKernelIsCalled(); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('Hello World', $this->response->getContent()); $this->assertTraceContains('stale'); $this->assertTraceContains('invalid'); $this->assertTraceContains('store'); } public function testServesFromCacheWhenHeadersMatch() { $count = 0; $this->setNextResponse(200, array('Cache-Control' => 'max-age=10000'), '', function ($request, $response) use (&$count) { $response->headers->set('Vary', 'Accept User-Agent Foo'); $response->headers->set('Cache-Control', 'public, max-age=10'); $response->headers->set('X-Response-Count', ++$count); $response->setContent($request->headers->get('USER_AGENT')); }); $this->request('GET', '/', array('HTTP_ACCEPT' => 'text/html', 'HTTP_USER_AGENT' => 'Bob/1.0')); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('Bob/1.0', $this->response->getContent()); $this->assertTraceContains('miss'); $this->assertTraceContains('store'); $this->request('GET', '/', array('HTTP_ACCEPT' => 'text/html', 'HTTP_USER_AGENT' => 'Bob/1.0')); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('Bob/1.0', $this->response->getContent()); $this->assertTraceContains('fresh'); $this->assertTraceNotContains('store'); $this->assertNotNull($this->response->headers->get('X-Content-Digest')); } public function testStoresMultipleResponsesWhenHeadersDiffer() { $count = 0; $this->setNextResponse(200, array('Cache-Control' => 'max-age=10000'), '', function ($request, $response) use (&$count) { $response->headers->set('Vary', 'Accept User-Agent Foo'); $response->headers->set('Cache-Control', 'public, max-age=10'); $response->headers->set('X-Response-Count', ++$count); $response->setContent($request->headers->get('USER_AGENT')); }); $this->request('GET', '/', array('HTTP_ACCEPT' => 'text/html', 'HTTP_USER_AGENT' => 'Bob/1.0')); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('Bob/1.0', $this->response->getContent()); $this->assertEquals(1, $this->response->headers->get('X-Response-Count')); $this->request('GET', '/', array('HTTP_ACCEPT' => 'text/html', 'HTTP_USER_AGENT' => 'Bob/2.0')); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertTraceContains('miss'); $this->assertTraceContains('store'); $this->assertEquals('Bob/2.0', $this->response->getContent()); $this->assertEquals(2, $this->response->headers->get('X-Response-Count')); $this->request('GET', '/', array('HTTP_ACCEPT' => 'text/html', 'HTTP_USER_AGENT' => 'Bob/1.0')); $this->assertTraceContains('fresh'); $this->assertEquals('Bob/1.0', $this->response->getContent()); $this->assertEquals(1, $this->response->headers->get('X-Response-Count')); $this->request('GET', '/', array('HTTP_ACCEPT' => 'text/html', 'HTTP_USER_AGENT' => 'Bob/2.0')); $this->assertTraceContains('fresh'); $this->assertEquals('Bob/2.0', $this->response->getContent()); $this->assertEquals(2, $this->response->headers->get('X-Response-Count')); $this->request('GET', '/', array('HTTP_USER_AGENT' => 'Bob/2.0')); $this->assertTraceContains('miss'); $this->assertEquals('Bob/2.0', $this->response->getContent()); $this->assertEquals(3, $this->response->headers->get('X-Response-Count')); } public function testShouldCatchExceptions() { $this->catchExceptions(); $this->setNextResponse(); $this->request('GET', '/'); $this->assertExceptionsAreCaught(); } public function testShouldCatchExceptionsWhenReloadingAndNoCacheRequest() { $this->catchExceptions(); $this->setNextResponse(); $this->cacheConfig['allow_reload'] = true; $this->request('GET', '/', array(), array(), false, array('Pragma' => 'no-cache')); $this->assertExceptionsAreCaught(); } public function testShouldNotCatchExceptions() { $this->catchExceptions(false); $this->setNextResponse(); $this->request('GET', '/'); $this->assertExceptionsAreNotCaught(); } public function testEsiCacheSendsTheLowestTtl() { $responses = array( array( 'status' => 200, 'body' => ' ', 'headers' => array( 'Cache-Control' => 's-maxage=300', 'Surrogate-Control' => 'content="ESI/1.0"', ), ), array( 'status' => 200, 'body' => 'Hello World!', 'headers' => array('Cache-Control' => 's-maxage=300'), ), array( 'status' => 200, 'body' => 'My name is Bobby.', 'headers' => array('Cache-Control' => 's-maxage=100'), ), ); $this->setNextResponses($responses); $this->request('GET', '/', array(), array(), true); $this->assertEquals("Hello World! My name is Bobby.", $this->response->getContent()); // check for 100 or 99 as the test can be executed after a second change $this->assertTrue(in_array($this->response->getTtl(), array(99, 100))); } public function testEsiCacheForceValidation() { $responses = array( array( 'status' => 200, 'body' => ' ', 'headers' => array( 'Cache-Control' => 's-maxage=300', 'Surrogate-Control' => 'content="ESI/1.0"', ), ), array( 'status' => 200, 'body' => 'Hello World!', 'headers' => array('ETag' => 'foobar'), ), array( 'status' => 200, 'body' => 'My name is Bobby.', 'headers' => array('Cache-Control' => 's-maxage=100'), ), ); $this->setNextResponses($responses); $this->request('GET', '/', array(), array(), true); $this->assertEquals('Hello World! My name is Bobby.', $this->response->getContent()); $this->assertNull($this->response->getTtl()); $this->assertTrue($this->response->mustRevalidate()); $this->assertTrue($this->response->headers->hasCacheControlDirective('private')); $this->assertTrue($this->response->headers->hasCacheControlDirective('no-cache')); } public function testEsiRecalculateContentLengthHeader() { $responses = array( array( 'status' => 200, 'body' => '', 'headers' => array( 'Content-Length' => 26, 'Cache-Control' => 's-maxage=300', 'Surrogate-Control' => 'content="ESI/1.0"', ), ), array( 'status' => 200, 'body' => 'Hello World!', 'headers' => array(), ), ); $this->setNextResponses($responses); $this->request('GET', '/', array(), array(), true); $this->assertEquals('Hello World!', $this->response->getContent()); $this->assertEquals(12, $this->response->headers->get('Content-Length')); } public function testClientIpIsAlwaysLocalhostForForwardedRequests() { $this->setNextResponse(); $this->request('GET', '/', array('REMOTE_ADDR' => '10.0.0.1')); $this->assertEquals('127.0.0.1', $this->kernel->getBackendRequest()->server->get('REMOTE_ADDR')); } /** * @dataProvider getXForwardedForData */ public function testXForwarderForHeaderForForwardedRequests($xForwardedFor, $expected) { $this->setNextResponse(); $server = array('REMOTE_ADDR' => '10.0.0.1'); if (false !== $xForwardedFor) { $server['HTTP_X_FORWARDED_FOR'] = $xForwardedFor; } $this->request('GET', '/', $server); $this->assertEquals($expected, $this->kernel->getBackendRequest()->headers->get('X-Forwarded-For')); } public function getXForwardedForData() { return array( array(false, '10.0.0.1'), array('10.0.0.2', '10.0.0.2, 10.0.0.1'), array('10.0.0.2, 10.0.0.3', '10.0.0.2, 10.0.0.3, 10.0.0.1'), ); } public function testXForwarderForHeaderForPassRequests() { $this->setNextResponse(); $server = array('REMOTE_ADDR' => '10.0.0.1'); $this->request('POST', '/', $server); $this->assertEquals('10.0.0.1', $this->kernel->getBackendRequest()->headers->get('X-Forwarded-For')); } public function testEsiCacheRemoveValidationHeadersIfEmbeddedResponses() { $time = new \DateTime; $responses = array( array( 'status' => 200, 'body' => '', 'headers' => array( 'Surrogate-Control' => 'content="ESI/1.0"', 'ETag' => 'hey', 'Last-Modified' => $time->format(DATE_RFC2822), ), ), array( 'status' => 200, 'body' => 'Hey!', 'headers' => array(), ), ); $this->setNextResponses($responses); $this->request('GET', '/', array(), array(), true); $this->assertNull($this->response->getETag()); $this->assertNull($this->response->getLastModified()); } } Symfony/Component/HttpKernel/Tests/HttpCache/StoreTest.php000064400000023132152410105270017642 0ustar00 * * 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() { $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('en9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08', $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'.hash('sha256', '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'.hash('sha256', 'test 3')), $this->store->lookup($req3)->getContent()); $this->assertEquals($this->getStorePath('en'.hash('sha256', 'test 2')), $this->store->lookup($req2)->getContent()); $this->assertEquals($this->getStorePath('en'.hash('sha256', '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'.hash('sha256', 'test 1')), $this->store->lookup($req1)->getContent()); $req2 = Request::create('/test', 'get', array(), array(), array(), array('HTTP_FOO' => 'Bling', 'HTTP_BAR' => 'Bam')); $res2 = new Response('test 2', 200, array('Vary' => 'Foo Bar')); $this->store->write($req2, $res2); $this->assertEquals($this->getStorePath('en'.hash('sha256', 'test 2')), $this->store->lookup($req2)->getContent()); $req3 = Request::create('/test', 'get', array(), array(), array(), array('HTTP_FOO' => 'Foo', 'HTTP_BAR' => 'Bar')); $res3 = new Response('test 3', 200, array('Vary' => 'Foo Bar')); $key = $this->store->write($req3, $res3); $this->assertEquals($this->getStorePath('en'.hash('sha256', '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); } } Symfony/Component/HttpKernel/Tests/HttpCache/HttpCacheTestCase.php000064400000012005152410105270021202 0ustar00 * * 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() { $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, $headers = array()) { 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->request->headers->add($headers); $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); } } Symfony/Component/HttpKernel/Tests/HttpCache/TestMultipleHttpKernel.php000064400000004112152410105270022337 0ustar00 * * 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 = array(); protected $statuses = array(); protected $headers = array(); protected $call = false; protected $backendRequest; public function __construct($responses) { 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; } } Symfony/Component/HttpKernel/Tests/HttpCache/TestHttpKernel.php000064400000004400152410105270020623 0ustar00 * * 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 = false; protected $customizer; protected $catch = false; protected $backendRequest; public function __construct($body, $status, $headers, \Closure $customizer = null) { $this->body = $body; $this->status = $status; $this->headers = $headers; $this->customizer = $customizer; 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; } } Symfony/Component/HttpKernel/Tests/HttpCache/EsiTest.php000064400000017516152410105270017277 0ustar00 * * 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 { 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->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->renderIncludeTag('/', '/alt', true)); $this->assertEquals('', $esi->renderIncludeTag('/', '/alt', false)); $this->assertEquals('', $esi->renderIncludeTag('/')); $this->assertEquals(''."\n".'', $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->process($request, $response); $this->assertEquals('foo esi->handle($this, \'...\', \'alt\', true) ?>'."\n", $response->getContent()); $this->assertEquals('ESI', $response->headers->get('x-body-eval')); $response = new Response('foo '); $esi->process($request, $response); $this->assertEquals('foo esi->handle($this, \'...\', \'\', false) ?>'."\n", $response->getContent()); $response = new Response('foo '); $esi->process($request, $response); $this->assertEquals('foo esi->handle($this, \'...\', \'\', false) ?>'."\n", $response->getContent()); } public function testProcessEscapesPhpTags() { $esi = new Esi(); $request = Request::create('/'); $response = new Response('foo <%= "lala" %>'); $esi->process($request, $response); $this->assertEquals('foo php die("foo"); ?>= "lala" %>', $response->getContent()); } /** * @expectedException \RuntimeException */ public function testProcessWhenNoSrcInAnEsi() { $esi = new Esi(); $request = Request::create('/'); $response = new Response('foo '); $esi->process($request, $response); } public function testProcessRemoveSurrogateControlHeader() { $esi = new Esi(); $request = Request::create('/'); $response = new Response('foo '); $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; } } Symfony/Component/HttpKernel/Tests/Controller/ControllerResolverTest.php000064400000022410152410105270022671 0ustar00 * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\HttpKernel\Tests\Controller; use Symfony\Component\HttpKernel\Controller\ControllerResolver; use Symfony\Component\HttpKernel\Tests\Logger; use Symfony\Component\HttpFoundation\Request; class ControllerResolverTest extends \PHPUnit_Framework_TestCase { public function testGetControllerWithoutControllerParameter() { $logger = $this->getMock('Psr\Log\LoggerInterface'); $logger->expects($this->once())->method('warning')->with('Unable to look for the controller as the "_controller" parameter is missing'); $resolver = new ControllerResolver($logger); $request = Request::create('/'); $this->assertFalse($resolver->getController($request), '->getController() returns false when the request has no _controller attribute'); } public function testGetControllerWithLambda() { $resolver = new ControllerResolver(); $request = Request::create('/'); $request->attributes->set('_controller', $lambda = function () {}); $controller = $resolver->getController($request); $this->assertSame($lambda, $controller); } public function testGetControllerWithObjectAndInvokeMethod() { $resolver = new ControllerResolver(); $request = Request::create('/'); $request->attributes->set('_controller', $this); $controller = $resolver->getController($request); $this->assertSame($this, $controller); } public function testGetControllerWithObjectAndMethod() { $resolver = new ControllerResolver(); $request = Request::create('/'); $request->attributes->set('_controller', array($this, 'controllerMethod1')); $controller = $resolver->getController($request); $this->assertSame(array($this, 'controllerMethod1'), $controller); } public function testGetControllerWithClassAndMethod() { $resolver = new ControllerResolver(); $request = Request::create('/'); $request->attributes->set('_controller', array('Symfony\Component\HttpKernel\Tests\Controller\ControllerResolverTest', 'controllerMethod4')); $controller = $resolver->getController($request); $this->assertSame(array('Symfony\Component\HttpKernel\Tests\Controller\ControllerResolverTest', 'controllerMethod4'), $controller); } public function testGetControllerWithObjectAndMethodAsString() { $resolver = new ControllerResolver(); $request = Request::create('/'); $request->attributes->set('_controller', 'Symfony\Component\HttpKernel\Tests\Controller\ControllerResolverTest::controllerMethod1'); $controller = $resolver->getController($request); $this->assertInstanceOf('Symfony\Component\HttpKernel\Tests\Controller\ControllerResolverTest', $controller[0], '->getController() returns a PHP callable'); } public function testGetControllerWithClassAndInvokeMethod() { $resolver = new ControllerResolver(); $request = Request::create('/'); $request->attributes->set('_controller', 'Symfony\Component\HttpKernel\Tests\Controller\ControllerResolverTest'); $controller = $resolver->getController($request); $this->assertInstanceOf('Symfony\Component\HttpKernel\Tests\Controller\ControllerResolverTest', $controller); } /** * @expectedException \InvalidArgumentException */ public function testGetControllerOnObjectWithoutInvokeMethod() { $resolver = new ControllerResolver(); $request = Request::create('/'); $request->attributes->set('_controller', new \stdClass()); $resolver->getController($request); } public function testGetControllerWithFunction() { $resolver = new ControllerResolver(); $request = Request::create('/'); $request->attributes->set('_controller', 'Symfony\Component\HttpKernel\Tests\Controller\some_controller_function'); $controller = $resolver->getController($request); $this->assertSame('Symfony\Component\HttpKernel\Tests\Controller\some_controller_function', $controller); } /** * @dataProvider getUndefinedControllers * @expectedException \InvalidArgumentException */ public function testGetControllerOnNonUndefinedFunction($controller) { $resolver = new ControllerResolver(); $request = Request::create('/'); $request->attributes->set('_controller', $controller); $resolver->getController($request); } public function getUndefinedControllers() { return array( array('foo'), array('foo::bar'), array('stdClass'), array('Symfony\Component\HttpKernel\Tests\Controller\ControllerResolverTest::bar'), ); } 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\Controller\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\Controller\some_controller_function')); $request = Request::create('/'); $request->attributes->set('_controller', 'foobar'); $mock->getController($request); } public function __invoke($foo, $bar = null) { } public 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) { } Symfony/Component/HttpKernel/phpunit.xml.dist000064400000001471152410105270015405 0ustar00 ./Tests/ ./ ./Tests ./vendor