Upgrade 1-11.38

This commit is contained in:
xesmyd
2026-03-30 14:10:30 +02:00
parent f2a7e6d1fc
commit ac648ef29d
24665 changed files with 69682 additions and 2205004 deletions
@@ -57,11 +57,10 @@ class CacheClearCommandTest extends TestCase
// simply check that cache is warmed up
$this->assertGreaterThanOrEqual(1, count($metaFiles));
$configCacheFactory = new ConfigCacheFactory(true);
$that = $this;
foreach ($metaFiles as $file) {
$configCacheFactory->cache(substr($file, 0, -5), function () use ($that, $file) {
$that->fail(sprintf('Meta file "%s" is not fresh', (string) $file));
$configCacheFactory->cache(substr($file, 0, -5), function () use ($file) {
$this->fail(sprintf('Meta file "%s" is not fresh', (string) $file));
});
}
@@ -81,6 +80,6 @@ class CacheClearCommandTest extends TestCase
}
}
$this->assertTrue($found, 'Kernel file should present as resource');
$this->assertRegExp(sprintf('/\'kernel.name\'\s*=>\s*\'%s\'/', $this->kernel->getName()), file_get_contents($containerFile), 'kernel.name is properly set on the dumped container');
$this->assertRegExp(sprintf('/\'kernel.container_class\'\s*=>\s*\'%s\'/', get_class($this->kernel->getContainer())), file_get_contents($containerFile), 'kernel.container_class is properly set on the dumped container');
}
}
@@ -11,13 +11,15 @@
namespace Symfony\Bundle\FrameworkBundle\Tests\Command;
use Symfony\Component\Console\Application;
use PHPUnit\Framework\TestCase;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;
use Symfony\Bundle\FrameworkBundle\Command\RouterDebugCommand;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
class RouterDebugCommandTest extends \PHPUnit_Framework_TestCase
class RouterDebugCommandTest extends TestCase
{
public function testDebugAllRoutes()
{
@@ -50,45 +52,51 @@ class RouterDebugCommandTest extends \PHPUnit_Framework_TestCase
*/
private function createCommandTester()
{
$application = new Application();
$application = new Application($this->getKernel());
$command = new RouterDebugCommand();
$command->setContainer($this->getContainer());
$application->add($command);
return new CommandTester($application->find('debug:router'));
}
private function getContainer()
private function getKernel()
{
$routeCollection = new RouteCollection();
$routeCollection->add('foo', new Route('foo'));
$router = $this->getMock('Symfony\Component\Routing\RouterInterface');
$router = $this->getMockBuilder('Symfony\Component\Routing\RouterInterface')->getMock();
$router
->expects($this->any())
->method('getRouteCollection')
->will($this->returnValue($routeCollection))
;
$loader = $this->getMockBuilder('Symfony\Bundle\FrameworkBundle\Routing\DelegatingLoader')
->disableOriginalConstructor()
->getMock();
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock();
$container
->expects($this->once())
->method('has')
->with('router')
->will($this->returnValue(true))
;
$container
->expects($this->any())
->method('get')
->will($this->returnValueMap(array(
array('router', 1, $router),
array('controller_name_converter', 1, $loader),
)));
->with('router')
->willReturn($router)
;
return $container;
$kernel = $this->getMockBuilder(KernelInterface::class)->getMock();
$kernel
->expects($this->any())
->method('getContainer')
->willReturn($container)
;
$kernel
->expects($this->once())
->method('getBundles')
->willReturn(array())
;
return $kernel;
}
}
@@ -11,15 +11,17 @@
namespace Symfony\Bundle\FrameworkBundle\Tests\Command;
use Symfony\Component\Console\Application;
use PHPUnit\Framework\TestCase;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;
use Symfony\Bundle\FrameworkBundle\Command\RouterMatchCommand;
use Symfony\Bundle\FrameworkBundle\Command\RouterDebugCommand;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\RequestContext;
class RouterMatchCommandTest extends \PHPUnit_Framework_TestCase
class RouterMatchCommandTest extends TestCase
{
public function testWithMatchPath()
{
@@ -44,25 +46,19 @@ class RouterMatchCommandTest extends \PHPUnit_Framework_TestCase
*/
private function createCommandTester()
{
$application = new Application();
$command = new RouterMatchCommand();
$command->setContainer($this->getContainer());
$application->add($command);
$command = new RouterDebugCommand();
$command->setContainer($this->getContainer());
$application->add($command);
$application = new Application($this->getKernel());
$application->add(new RouterMatchCommand());
$application->add(new RouterDebugCommand());
return new CommandTester($application->find('router:match'));
}
private function getContainer()
private function getKernel()
{
$routeCollection = new RouteCollection();
$routeCollection->add('foo', new Route('foo'));
$requestContext = new RequestContext();
$router = $this->getMock('Symfony\Component\Routing\RouterInterface');
$router = $this->getMockBuilder('Symfony\Component\Routing\RouterInterface')->getMock();
$router
->expects($this->any())
->method('getRouteCollection')
@@ -74,23 +70,29 @@ class RouterMatchCommandTest extends \PHPUnit_Framework_TestCase
->will($this->returnValue($requestContext))
;
$loader = $this->getMockBuilder('Symfony\Bundle\FrameworkBundle\Routing\DelegatingLoader')
->disableOriginalConstructor()
->getMock();
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock();
$container
->expects($this->once())
->expects($this->atLeastOnce())
->method('has')
->with('router')
->will($this->returnValue(true));
$container->method('get')
->will($this->returnValueMap(array(
array('router', 1, $router),
array('controller_name_converter', 1, $loader),
$container
->expects($this->any())
->method('get')
->willReturn($router);
)));
$kernel = $this->getMockBuilder(KernelInterface::class)->getMock();
$kernel
->expects($this->any())
->method('getContainer')
->willReturn($container)
;
$kernel
->expects($this->once())
->method('getBundles')
->willReturn(array())
;
return $container;
return $kernel;
}
}
@@ -11,12 +11,13 @@
namespace Symfony\Bundle\FrameworkBundle\Tests\Command;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;
use Symfony\Bundle\FrameworkBundle\Command\TranslationDebugCommand;
use Symfony\Component\Filesystem\Filesystem;
class TranslationDebugCommandTest extends \PHPUnit_Framework_TestCase
class TranslationDebugCommandTest extends TestCase
{
private $fs;
private $translationDir;
@@ -64,7 +65,7 @@ class TranslationDebugCommandTest extends \PHPUnit_Framework_TestCase
public function testDebugCustomDirectory()
{
$kernel = $this->getMock('Symfony\Component\HttpKernel\KernelInterface');
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\KernelInterface')->getMock();
$kernel->expects($this->once())
->method('getBundle')
->with($this->equalTo($this->translationDir))
@@ -82,7 +83,7 @@ class TranslationDebugCommandTest extends \PHPUnit_Framework_TestCase
*/
public function testDebugInvalidDirectory()
{
$kernel = $this->getMock('Symfony\Component\HttpKernel\KernelInterface');
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\KernelInterface')->getMock();
$kernel->expects($this->once())
->method('getBundle')
->with($this->equalTo('dir'))
@@ -130,28 +131,28 @@ class TranslationDebugCommandTest extends \PHPUnit_Framework_TestCase
->method('getFallbackLocales')
->will($this->returnValue(array('en')));
$extractor = $this->getMock('Symfony\Component\Translation\Extractor\ExtractorInterface');
$extractor = $this->getMockBuilder('Symfony\Component\Translation\Extractor\ExtractorInterface')->getMock();
$extractor
->expects($this->any())
->method('extract')
->will(
$this->returnCallback(function ($path, $catalogue) use ($extractedMessages) {
$catalogue->add($extractedMessages);
$catalogue->add($extractedMessages);
})
);
$loader = $this->getMock('Symfony\Bundle\FrameworkBundle\Translation\TranslationLoader');
$loader = $this->getMockBuilder('Symfony\Bundle\FrameworkBundle\Translation\TranslationLoader')->getMock();
$loader
->expects($this->any())
->method('loadMessages')
->will(
$this->returnCallback(function ($path, $catalogue) use ($loadedMessages) {
$catalogue->add($loadedMessages);
$catalogue->add($loadedMessages);
})
);
if (null === $kernel) {
$kernel = $this->getMock('Symfony\Component\HttpKernel\KernelInterface');
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\KernelInterface')->getMock();
$kernel
->expects($this->any())
->method('getBundle')
@@ -166,7 +167,7 @@ class TranslationDebugCommandTest extends \PHPUnit_Framework_TestCase
->method('getRootDir')
->will($this->returnValue($this->translationDir));
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock();
$container
->expects($this->any())
->method('get')
@@ -182,7 +183,7 @@ class TranslationDebugCommandTest extends \PHPUnit_Framework_TestCase
private function getBundle($path)
{
$bundle = $this->getMock('Symfony\Component\HttpKernel\Bundle\BundleInterface');
$bundle = $this->getMockBuilder('Symfony\Component\HttpKernel\Bundle\BundleInterface')->getMock();
$bundle
->expects($this->any())
->method('getPath')
@@ -11,6 +11,7 @@
namespace Symfony\Bundle\FrameworkBundle\Tests\Command;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;
use Symfony\Bundle\FrameworkBundle\Command\TranslationUpdateCommand;
@@ -18,26 +19,50 @@ use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\DependencyInjection;
use Symfony\Component\HttpKernel;
class TranslationUpdateCommandTest extends \PHPUnit_Framework_TestCase
class TranslationUpdateCommandTest extends TestCase
{
private $fs;
private $translationDir;
public function testDumpMessagesAndClean()
{
$tester = $this->createCommandTester($this->getContainer(array('foo' => 'foo')));
$tester = $this->createCommandTester($this->getContainer(array('messages' => array('foo' => 'foo'))));
$tester->execute(array('command' => 'translation:update', 'locale' => 'en', 'bundle' => 'foo', '--dump-messages' => true, '--clean' => true));
$this->assertRegExp('/foo/', $tester->getDisplay());
$this->assertRegExp('/1 message was successfully extracted/', $tester->getDisplay());
}
public function testDumpTwoMessagesAndClean()
{
$tester = $this->createCommandTester($this->getContainer(array('messages' => array('foo' => 'foo', 'bar' => 'bar'))));
$tester->execute(array('command' => 'translation:update', 'locale' => 'en', 'bundle' => 'foo', '--dump-messages' => true, '--clean' => true));
$this->assertRegExp('/foo/', $tester->getDisplay());
$this->assertRegExp('/bar/', $tester->getDisplay());
$this->assertRegExp('/2 messages were successfully extracted/', $tester->getDisplay());
}
public function testDumpMessagesForSpecificDomain()
{
$tester = $this->createCommandTester($this->getContainer(array('messages' => array('foo' => 'foo'), 'mydomain' => array('bar' => 'bar'))));
$tester->execute(array('command' => 'translation:update', 'locale' => 'en', 'bundle' => 'foo', '--dump-messages' => true, '--clean' => true, '--domain' => 'mydomain'));
$this->assertRegExp('/bar/', $tester->getDisplay());
$this->assertRegExp('/1 message was successfully extracted/', $tester->getDisplay());
}
public function testWriteMessages()
{
$tester = $this->createCommandTester($this->getContainer(array('foo' => 'foo')));
$tester = $this->createCommandTester($this->getContainer(array('messages' => array('foo' => 'foo'))));
$tester->execute(array('command' => 'translation:update', 'locale' => 'en', 'bundle' => 'foo', '--force' => true));
$this->assertRegExp('/Translation files were successfully updated./', $tester->getDisplay());
}
public function testWriteMessagesForSpecificDomain()
{
$tester = $this->createCommandTester($this->getContainer(array('messages' => array('foo' => 'foo'), 'mydomain' => array('bar' => 'bar'))));
$tester->execute(array('command' => 'translation:update', 'locale' => 'en', 'bundle' => 'foo', '--force' => true, '--domain' => 'mydomain'));
$this->assertRegExp('/Translation files were successfully updated./', $tester->getDisplay());
}
protected function setUp()
{
$this->fs = new Filesystem();
@@ -76,27 +101,29 @@ class TranslationUpdateCommandTest extends \PHPUnit_Framework_TestCase
->method('getFallbackLocales')
->will($this->returnValue(array('en')));
$extractor = $this->getMock('Symfony\Component\Translation\Extractor\ExtractorInterface');
$extractor = $this->getMockBuilder('Symfony\Component\Translation\Extractor\ExtractorInterface')->getMock();
$extractor
->expects($this->any())
->method('extract')
->will(
$this->returnCallback(function ($path, $catalogue) use ($extractedMessages) {
$catalogue->add($extractedMessages);
foreach ($extractedMessages as $domain => $messages) {
$catalogue->add($messages, $domain);
}
})
);
$loader = $this->getMock('Symfony\Bundle\FrameworkBundle\Translation\TranslationLoader');
$loader = $this->getMockBuilder('Symfony\Bundle\FrameworkBundle\Translation\TranslationLoader')->getMock();
$loader
->expects($this->any())
->method('loadMessages')
->will(
$this->returnCallback(function ($path, $catalogue) use ($loadedMessages) {
$catalogue->add($loadedMessages);
$catalogue->add($loadedMessages);
})
);
$writer = $this->getMock('Symfony\Component\Translation\Writer\TranslationWriter');
$writer = $this->getMockBuilder('Symfony\Component\Translation\Writer\TranslationWriter')->getMock();
$writer
->expects($this->any())
->method('getFormats')
@@ -105,7 +132,7 @@ class TranslationUpdateCommandTest extends \PHPUnit_Framework_TestCase
);
if (null === $kernel) {
$kernel = $this->getMock('Symfony\Component\HttpKernel\KernelInterface');
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\KernelInterface')->getMock();
$kernel
->expects($this->any())
->method('getBundle')
@@ -120,7 +147,7 @@ class TranslationUpdateCommandTest extends \PHPUnit_Framework_TestCase
->method('getRootDir')
->will($this->returnValue($this->translationDir));
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock();
$container
->expects($this->any())
->method('get')
@@ -137,7 +164,7 @@ class TranslationUpdateCommandTest extends \PHPUnit_Framework_TestCase
private function getBundle($path)
{
$bundle = $this->getMock('Symfony\Component\HttpKernel\Bundle\BundleInterface');
$bundle = $this->getMockBuilder('Symfony\Component\HttpKernel\Bundle\BundleInterface')->getMock();
$bundle
->expects($this->any())
->method('getPath')
@@ -22,7 +22,7 @@ class ApplicationTest extends TestCase
{
public function testBundleInterfaceImplementation()
{
$bundle = $this->getMock('Symfony\Component\HttpKernel\Bundle\BundleInterface');
$bundle = $this->getMockBuilder('Symfony\Component\HttpKernel\Bundle\BundleInterface')->getMock();
$kernel = $this->getKernel(array($bundle), true);
@@ -32,8 +32,7 @@ class ApplicationTest extends TestCase
public function testBundleCommandsAreRegistered()
{
$bundle = $this->getMock('Symfony\Component\HttpKernel\Bundle\Bundle');
$bundle->expects($this->once())->method('registerCommands');
$bundle = $this->createBundleMock(array());
$kernel = $this->getKernel(array($bundle), true);
@@ -46,8 +45,7 @@ class ApplicationTest extends TestCase
public function testBundleCommandsAreRetrievable()
{
$bundle = $this->getMock('Symfony\Component\HttpKernel\Bundle\Bundle');
$bundle->expects($this->once())->method('registerCommands');
$bundle = $this->createBundleMock(array());
$kernel = $this->getKernel(array($bundle));
@@ -60,47 +58,41 @@ class ApplicationTest extends TestCase
public function testBundleSingleCommandIsRetrievable()
{
$bundle = $this->getMock('Symfony\Component\HttpKernel\Bundle\Bundle');
$bundle->expects($this->once())->method('registerCommands');
$command = new Command('example');
$bundle = $this->createBundleMock(array($command));
$kernel = $this->getKernel(array($bundle));
$application = new Application($kernel);
$command = new Command('example');
$application->add($command);
$this->assertSame($command, $application->get('example'));
}
public function testBundleCommandCanBeFound()
{
$bundle = $this->getMock('Symfony\Component\HttpKernel\Bundle\Bundle');
$bundle->expects($this->once())->method('registerCommands');
$command = new Command('example');
$bundle = $this->createBundleMock(array($command));
$kernel = $this->getKernel(array($bundle));
$application = new Application($kernel);
$command = new Command('example');
$application->add($command);
$this->assertSame($command, $application->find('example'));
}
public function testBundleCommandCanBeFoundByAlias()
{
$bundle = $this->getMock('Symfony\Component\HttpKernel\Bundle\Bundle');
$bundle->expects($this->once())->method('registerCommands');
$command = new Command('example');
$command->setAliases(array('alias'));
$bundle = $this->createBundleMock(array($command));
$kernel = $this->getKernel(array($bundle));
$application = new Application($kernel);
$command = new Command('example');
$command->setAliases(array('alias'));
$application->add($command);
$this->assertSame($command, $application->find('alias'));
}
@@ -123,12 +115,27 @@ class ApplicationTest extends TestCase
$tester->run(array('command' => 'foo'));
}
public function testBundleCommandCanOverriddeAPreExistingCommandWithTheSameName()
{
$command = new Command('example');
$bundle = $this->createBundleMock(array($command));
$kernel = $this->getKernel(array($bundle));
$application = new Application($kernel);
$newCommand = new Command('example');
$application->add($newCommand);
$this->assertSame($newCommand, $application->get('example'));
}
private function getKernel(array $bundles, $useDispatcher = false)
{
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock();
if ($useDispatcher) {
$dispatcher = $this->getMock('Symfony\Component\EventDispatcher\EventDispatcherInterface');
$dispatcher = $this->getMockBuilder('Symfony\Component\EventDispatcher\EventDispatcherInterface')->getMock();
$dispatcher
->expects($this->atLeastOnce())
->method('dispatch')
@@ -153,7 +160,7 @@ class ApplicationTest extends TestCase
->will($this->returnValue(array()))
;
$kernel = $this->getMock('Symfony\Component\HttpKernel\KernelInterface');
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\KernelInterface')->getMock();
$kernel
->expects($this->any())
->method('getBundles')
@@ -167,4 +174,18 @@ class ApplicationTest extends TestCase
return $kernel;
}
private function createBundleMock(array $commands)
{
$bundle = $this->getMockBuilder('Symfony\Component\HttpKernel\Bundle\Bundle')->getMock();
$bundle
->expects($this->once())
->method('registerCommands')
->will($this->returnCallback(function (Application $application) use ($commands) {
$application->addCommands($commands);
}))
;
return $bundle;
}
}
@@ -11,6 +11,7 @@
namespace Symfony\Bundle\FrameworkBundle\Tests\Console\Descriptor;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\BufferedOutput;
use Symfony\Component\Console\Style\SymfonyStyle;
@@ -22,7 +23,7 @@ use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
abstract class AbstractDescriptorTest extends \PHPUnit_Framework_TestCase
abstract class AbstractDescriptorTest extends TestCase
{
/** @dataProvider getDescribeRouteCollectionTestData */
public function testDescribeRouteCollection(RouteCollection $routes, $expectedDescription)
@@ -129,6 +130,7 @@ abstract class AbstractDescriptorTest extends \PHPUnit_Framework_TestCase
}
abstract protected function getDescriptor();
abstract protected function getFormat();
private function assertDescription($expectedDescription, $describedObject, array $options = array())
@@ -115,6 +115,7 @@ class ObjectsProvider
->addTag('tag1', array('attr1' => 'val1', 'attr2' => 'val2'))
->addTag('tag1', array('attr3' => 'val3'))
->addTag('tag2')
->addMethodCall('setMailer', array(new Reference('mailer')))
->setFactory(array(new Reference('factory.service'), 'get')),
);
}
@@ -157,9 +158,11 @@ class CallableClass
public function __invoke()
{
}
public static function staticMethod()
{
}
public function method()
{
}
@@ -93,7 +93,7 @@ class ControllerNameParserTest extends TestCase
try {
$parser->parse($name);
$this->fail('->parse() throws a \InvalidArgumentException if the string is in the valid format, but not matching class can be found');
$this->fail('->parse() throws a \InvalidArgumentException if the class is found but does not exist');
} catch (\Exception $e) {
$this->assertInstanceOf('\InvalidArgumentException', $e, '->parse() throws a \InvalidArgumentException if the class is found but does not exist');
}
@@ -108,7 +108,6 @@ class ControllerNameParserTest extends TestCase
}
/**
* @expectedException
* @dataProvider getInvalidBundleNameTests
*/
public function testInvalidBundleName($bundleName, $suggestedBundleName)
@@ -117,6 +116,7 @@ class ControllerNameParserTest extends TestCase
try {
$parser->parse($bundleName);
$this->fail('->parse() throws a \InvalidArgumentException if the bundle does not exist');
} catch (\Exception $e) {
$this->assertInstanceOf('\InvalidArgumentException', $e, '->parse() throws a \InvalidArgumentException if the bundle does not exist');
@@ -147,7 +147,7 @@ class ControllerNameParserTest extends TestCase
'FabpotFooBundle' => array($this->getBundle('TestBundle\Fabpot\FooBundle', 'FabpotFooBundle'), $this->getBundle('TestBundle\Sensio\FooBundle', 'SensioFooBundle')),
);
$kernel = $this->getMock('Symfony\Component\HttpKernel\KernelInterface');
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\KernelInterface')->getMock();
$kernel
->expects($this->any())
->method('getBundle')
@@ -178,7 +178,7 @@ class ControllerNameParserTest extends TestCase
private function getBundle($namespace, $name)
{
$bundle = $this->getMock('Symfony\Component\HttpKernel\Bundle\BundleInterface');
$bundle = $this->getMockBuilder('Symfony\Component\HttpKernel\Bundle\BundleInterface')->getMock();
$bundle->expects($this->any())->method('getName')->will($this->returnValue($name));
$bundle->expects($this->any())->method('getNamespace')->will($this->returnValue($namespace));
@@ -143,7 +143,12 @@ class ControllerResolverTest extends BaseControllerResolverTest
{
// All this logic needs to be duplicated, since calling parent::testGetControllerOnNonUndefinedFunction will override the expected excetion and not use the regex
$resolver = $this->createControllerResolver();
$this->setExpectedExceptionRegExp($exceptionName, $exceptionMessage);
if (method_exists($this, 'expectException')) {
$this->expectException($exceptionName);
$this->expectExceptionMessageRegExp($exceptionMessage);
} else {
$this->setExpectedExceptionRegExp($exceptionName, $exceptionMessage);
}
$request = Request::create('/');
$request->attributes->set('_controller', $controller);
@@ -179,12 +184,12 @@ class ControllerResolverTest extends BaseControllerResolverTest
protected function createMockParser()
{
return $this->getMock('Symfony\Bundle\FrameworkBundle\Controller\ControllerNameParser', array(), array(), '', false);
return $this->getMockBuilder('Symfony\Bundle\FrameworkBundle\Controller\ControllerNameParser')->disableOriginalConstructor()->getMock();
}
protected function createMockContainer()
{
return $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
return $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock();
}
}
@@ -14,15 +14,20 @@ namespace Symfony\Bundle\FrameworkBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Tests\TestCase;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\HttpFoundation\Session\Flash\FlashBag;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Serializer\SerializerInterface;
class ControllerTest extends TestCase
{
@@ -35,12 +40,12 @@ class ControllerTest extends TestCase
$requestStack = new RequestStack();
$requestStack->push($request);
$kernel = $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface');
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock();
$kernel->expects($this->once())->method('handle')->will($this->returnCallback(function (Request $request) {
return new Response($request->getRequestFormat().'--'.$request->getLocale());
}));
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock();
$container->expects($this->at(0))->method('get')->will($this->returnValue($requestStack));
$container->expects($this->at(1))->method('get')->will($this->returnValue($kernel));
@@ -86,7 +91,7 @@ class ControllerTest extends TestCase
*/
public function testGetUserWithEmptyContainer()
{
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock();
$container
->expects($this->once())
->method('has')
@@ -106,13 +111,13 @@ class ControllerTest extends TestCase
*/
private function getContainerWithTokenStorage($token = null)
{
$tokenStorage = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage');
$tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage')->getMock();
$tokenStorage
->expects($this->once())
->method('getToken')
->will($this->returnValue($token));
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock();
$container
->expects($this->once())
->method('has')
@@ -128,12 +133,211 @@ class ControllerTest extends TestCase
return $container;
}
public function testJson()
{
$container = $this->getMockBuilder(ContainerInterface::class)->getMock();
$container
->expects($this->once())
->method('has')
->with('serializer')
->will($this->returnValue(false));
$controller = new TestController();
$controller->setContainer($container);
$response = $controller->json(array());
$this->assertInstanceOf(JsonResponse::class, $response);
$this->assertEquals('[]', $response->getContent());
}
public function testJsonWithSerializer()
{
$container = $this->getMockBuilder(ContainerInterface::class)->getMock();
$container
->expects($this->once())
->method('has')
->with('serializer')
->will($this->returnValue(true));
$serializer = $this->getMockBuilder(SerializerInterface::class)->getMock();
$serializer
->expects($this->once())
->method('serialize')
->with(array(), 'json', array('json_encode_options' => JsonResponse::DEFAULT_ENCODING_OPTIONS))
->will($this->returnValue('[]'));
$container
->expects($this->once())
->method('get')
->with('serializer')
->will($this->returnValue($serializer));
$controller = new TestController();
$controller->setContainer($container);
$response = $controller->json(array());
$this->assertInstanceOf(JsonResponse::class, $response);
$this->assertEquals('[]', $response->getContent());
}
public function testJsonWithSerializerContextOverride()
{
$container = $this->getMockBuilder(ContainerInterface::class)->getMock();
$container
->expects($this->once())
->method('has')
->with('serializer')
->will($this->returnValue(true));
$serializer = $this->getMockBuilder(SerializerInterface::class)->getMock();
$serializer
->expects($this->once())
->method('serialize')
->with(array(), 'json', array('json_encode_options' => 0, 'other' => 'context'))
->will($this->returnValue('[]'));
$container
->expects($this->once())
->method('get')
->with('serializer')
->will($this->returnValue($serializer));
$controller = new TestController();
$controller->setContainer($container);
$response = $controller->json(array(), 200, array(), array('json_encode_options' => 0, 'other' => 'context'));
$this->assertInstanceOf(JsonResponse::class, $response);
$this->assertEquals('[]', $response->getContent());
$response->setEncodingOptions(JSON_FORCE_OBJECT);
$this->assertEquals('{}', $response->getContent());
}
public function testFile()
{
/* @var ContainerInterface $container */
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock();
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock();
$container->set('kernel', $kernel);
$controller = new TestController();
$controller->setContainer($container);
/* @var BinaryFileResponse $response */
$response = $controller->file(new File(__FILE__));
$this->assertInstanceOf(BinaryFileResponse::class, $response);
$this->assertSame(200, $response->getStatusCode());
if ($response->headers->get('content-type')) {
$this->assertSame('text/x-php', $response->headers->get('content-type'));
}
$this->assertContains(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $response->headers->get('content-disposition'));
$this->assertContains(basename(__FILE__), $response->headers->get('content-disposition'));
}
public function testFileAsInline()
{
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock();
$controller = new TestController();
$controller->setContainer($container);
/* @var BinaryFileResponse $response */
$response = $controller->file(new File(__FILE__), null, ResponseHeaderBag::DISPOSITION_INLINE);
$this->assertInstanceOf(BinaryFileResponse::class, $response);
$this->assertSame(200, $response->getStatusCode());
if ($response->headers->get('content-type')) {
$this->assertSame('text/x-php', $response->headers->get('content-type'));
}
$this->assertContains(ResponseHeaderBag::DISPOSITION_INLINE, $response->headers->get('content-disposition'));
$this->assertContains(basename(__FILE__), $response->headers->get('content-disposition'));
}
public function testFileWithOwnFileName()
{
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock();
$controller = new TestController();
$controller->setContainer($container);
/* @var BinaryFileResponse $response */
$fileName = 'test.php';
$response = $controller->file(new File(__FILE__), $fileName);
$this->assertInstanceOf(BinaryFileResponse::class, $response);
$this->assertSame(200, $response->getStatusCode());
if ($response->headers->get('content-type')) {
$this->assertSame('text/x-php', $response->headers->get('content-type'));
}
$this->assertContains(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $response->headers->get('content-disposition'));
$this->assertContains($fileName, $response->headers->get('content-disposition'));
}
public function testFileWithOwnFileNameAsInline()
{
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock();
$controller = new TestController();
$controller->setContainer($container);
/* @var BinaryFileResponse $response */
$fileName = 'test.php';
$response = $controller->file(new File(__FILE__), $fileName, ResponseHeaderBag::DISPOSITION_INLINE);
$this->assertInstanceOf(BinaryFileResponse::class, $response);
$this->assertSame(200, $response->getStatusCode());
if ($response->headers->get('content-type')) {
$this->assertSame('text/x-php', $response->headers->get('content-type'));
}
$this->assertContains(ResponseHeaderBag::DISPOSITION_INLINE, $response->headers->get('content-disposition'));
$this->assertContains($fileName, $response->headers->get('content-disposition'));
}
public function testFileFromPath()
{
$controller = new TestController();
/* @var BinaryFileResponse $response */
$response = $controller->file(__FILE__);
$this->assertInstanceOf(BinaryFileResponse::class, $response);
$this->assertSame(200, $response->getStatusCode());
if ($response->headers->get('content-type')) {
$this->assertSame('text/x-php', $response->headers->get('content-type'));
}
$this->assertContains(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $response->headers->get('content-disposition'));
$this->assertContains(basename(__FILE__), $response->headers->get('content-disposition'));
}
public function testFileFromPathWithCustomizedFileName()
{
$controller = new TestController();
/* @var BinaryFileResponse $response */
$response = $controller->file(__FILE__, 'test.php');
$this->assertInstanceOf(BinaryFileResponse::class, $response);
$this->assertSame(200, $response->getStatusCode());
if ($response->headers->get('content-type')) {
$this->assertSame('text/x-php', $response->headers->get('content-type'));
}
$this->assertContains(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $response->headers->get('content-disposition'));
$this->assertContains('test.php', $response->headers->get('content-disposition'));
}
/**
* @expectedException \Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException
*/
public function testFileWhichDoesNotExist()
{
$controller = new TestController();
/* @var BinaryFileResponse $response */
$response = $controller->file('some-file.txt', 'test.php');
}
public function testIsGranted()
{
$authorizationChecker = $this->getMock('Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface');
$authorizationChecker = $this->getMockBuilder('Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface')->getMock();
$authorizationChecker->expects($this->once())->method('isGranted')->willReturn(true);
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock();
$container->expects($this->at(0))->method('has')->will($this->returnValue(true));
$container->expects($this->at(1))->method('get')->will($this->returnValue($authorizationChecker));
@@ -148,10 +352,10 @@ class ControllerTest extends TestCase
*/
public function testdenyAccessUnlessGranted()
{
$authorizationChecker = $this->getMock('Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface');
$authorizationChecker = $this->getMockBuilder('Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface')->getMock();
$authorizationChecker->expects($this->once())->method('isGranted')->willReturn(false);
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock();
$container->expects($this->at(0))->method('has')->will($this->returnValue(true));
$container->expects($this->at(1))->method('get')->will($this->returnValue($authorizationChecker));
@@ -163,10 +367,10 @@ class ControllerTest extends TestCase
public function testRenderViewTwig()
{
$twig = $this->getMockBuilder('\Twig_Environment')->disableOriginalConstructor()->getMock();
$twig = $this->getMockBuilder('Twig\Environment')->disableOriginalConstructor()->getMock();
$twig->expects($this->once())->method('render')->willReturn('bar');
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock();
$container->expects($this->at(0))->method('has')->will($this->returnValue(false));
$container->expects($this->at(1))->method('has')->will($this->returnValue(true));
$container->expects($this->at(2))->method('get')->will($this->returnValue($twig));
@@ -179,10 +383,10 @@ class ControllerTest extends TestCase
public function testRenderTwig()
{
$twig = $this->getMockBuilder('\Twig_Environment')->disableOriginalConstructor()->getMock();
$twig = $this->getMockBuilder('Twig\Environment')->disableOriginalConstructor()->getMock();
$twig->expects($this->once())->method('render')->willReturn('bar');
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock();
$container->expects($this->at(0))->method('has')->will($this->returnValue(false));
$container->expects($this->at(1))->method('has')->will($this->returnValue(true));
$container->expects($this->at(2))->method('get')->will($this->returnValue($twig));
@@ -195,9 +399,9 @@ class ControllerTest extends TestCase
public function testStreamTwig()
{
$twig = $this->getMockBuilder('\Twig_Environment')->disableOriginalConstructor()->getMock();
$twig = $this->getMockBuilder('Twig\Environment')->disableOriginalConstructor()->getMock();
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock();
$container->expects($this->at(0))->method('has')->will($this->returnValue(false));
$container->expects($this->at(1))->method('has')->will($this->returnValue(true));
$container->expects($this->at(2))->method('get')->will($this->returnValue($twig));
@@ -210,10 +414,10 @@ class ControllerTest extends TestCase
public function testRedirectToRoute()
{
$router = $this->getMock('Symfony\Component\Routing\RouterInterface');
$router = $this->getMockBuilder('Symfony\Component\Routing\RouterInterface')->getMock();
$router->expects($this->once())->method('generate')->willReturn('/foo');
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock();
$container->expects($this->at(0))->method('get')->will($this->returnValue($router));
$controller = new TestController();
@@ -228,10 +432,10 @@ class ControllerTest extends TestCase
public function testAddFlash()
{
$flashBag = new FlashBag();
$session = $this->getMock('Symfony\Component\HttpFoundation\Session\Session');
$session = $this->getMockBuilder('Symfony\Component\HttpFoundation\Session\Session')->getMock();
$session->expects($this->once())->method('getFlashBag')->willReturn($flashBag);
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock();
$container->expects($this->at(0))->method('has')->will($this->returnValue(true));
$container->expects($this->at(1))->method('get')->will($this->returnValue($session));
@@ -251,10 +455,10 @@ class ControllerTest extends TestCase
public function testIsCsrfTokenValid()
{
$tokenManager = $this->getMock('Symfony\Component\Security\Csrf\CsrfTokenManagerInterface');
$tokenManager = $this->getMockBuilder('Symfony\Component\Security\Csrf\CsrfTokenManagerInterface')->getMock();
$tokenManager->expects($this->once())->method('isTokenValid')->willReturn(true);
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock();
$container->expects($this->at(0))->method('has')->will($this->returnValue(true));
$container->expects($this->at(1))->method('get')->will($this->returnValue($tokenManager));
@@ -266,10 +470,10 @@ class ControllerTest extends TestCase
public function testGenerateUrl()
{
$router = $this->getMock('Symfony\Component\Routing\RouterInterface');
$router = $this->getMockBuilder('Symfony\Component\Routing\RouterInterface')->getMock();
$router->expects($this->once())->method('generate')->willReturn('/foo');
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock();
$container->expects($this->at(0))->method('get')->will($this->returnValue($router));
$controller = new TestController();
@@ -290,10 +494,10 @@ class ControllerTest extends TestCase
public function testRenderViewTemplating()
{
$templating = $this->getMock('Symfony\Bundle\FrameworkBundle\Templating\EngineInterface');
$templating = $this->getMockBuilder('Symfony\Bundle\FrameworkBundle\Templating\EngineInterface')->getMock();
$templating->expects($this->once())->method('render')->willReturn('bar');
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock();
$container->expects($this->at(0))->method('has')->willReturn(true);
$container->expects($this->at(1))->method('get')->will($this->returnValue($templating));
@@ -305,10 +509,10 @@ class ControllerTest extends TestCase
public function testRenderTemplating()
{
$templating = $this->getMock('Symfony\Bundle\FrameworkBundle\Templating\EngineInterface');
$templating = $this->getMockBuilder('Symfony\Bundle\FrameworkBundle\Templating\EngineInterface')->getMock();
$templating->expects($this->once())->method('renderResponse')->willReturn(new Response('bar'));
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock();
$container->expects($this->at(0))->method('has')->willReturn(true);
$container->expects($this->at(1))->method('get')->will($this->returnValue($templating));
@@ -320,9 +524,9 @@ class ControllerTest extends TestCase
public function testStreamTemplating()
{
$templating = $this->getMock('Symfony\Component\Routing\RouterInterface');
$templating = $this->getMockBuilder('Symfony\Component\Routing\RouterInterface')->getMock();
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock();
$container->expects($this->at(0))->method('has')->willReturn(true);
$container->expects($this->at(1))->method('get')->will($this->returnValue($templating));
@@ -341,12 +545,12 @@ class ControllerTest extends TestCase
public function testCreateForm()
{
$form = $this->getMock('Symfony\Component\Form\FormInterface');
$form = $this->getMockBuilder('Symfony\Component\Form\FormInterface')->getMock();
$formFactory = $this->getMock('Symfony\Component\Form\FormFactoryInterface');
$formFactory = $this->getMockBuilder('Symfony\Component\Form\FormFactoryInterface')->getMock();
$formFactory->expects($this->once())->method('create')->willReturn($form);
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock();
$container->expects($this->at(0))->method('get')->will($this->returnValue($formFactory));
$controller = new TestController();
@@ -357,12 +561,12 @@ class ControllerTest extends TestCase
public function testCreateFormBuilder()
{
$formBuilder = $this->getMock('Symfony\Component\Form\FormBuilderInterface');
$formBuilder = $this->getMockBuilder('Symfony\Component\Form\FormBuilderInterface')->getMock();
$formFactory = $this->getMock('Symfony\Component\Form\FormFactoryInterface');
$formFactory = $this->getMockBuilder('Symfony\Component\Form\FormFactoryInterface')->getMock();
$formFactory->expects($this->once())->method('createBuilder')->willReturn($formBuilder);
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock();
$container->expects($this->at(0))->method('get')->will($this->returnValue($formFactory));
$controller = new TestController();
@@ -373,9 +577,9 @@ class ControllerTest extends TestCase
public function testGetDoctrine()
{
$doctrine = $this->getMock('Doctrine\Common\Persistence\ManagerRegistry');
$doctrine = $this->getMockBuilder('Doctrine\Common\Persistence\ManagerRegistry')->getMock();
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock();
$container->expects($this->at(0))->method('has')->will($this->returnValue(true));
$container->expects($this->at(1))->method('get')->will($this->returnValue($doctrine));
@@ -408,6 +612,16 @@ class TestController extends Controller
return parent::getUser();
}
public function json($data, $status = 200, $headers = array(), $context = array())
{
return parent::json($data, $status, $headers, $context);
}
public function file($file, $fileName = null, $disposition = ResponseHeaderBag::DISPOSITION_ATTACHMENT)
{
return parent::file($file, $fileName, $disposition);
}
public function isGranted($attributes, $object = null)
{
return parent::isGranted($attributes, $object);
@@ -66,14 +66,14 @@ class RedirectControllerTest extends TestCase
$request->attributes = new ParameterBag($attributes);
$router = $this->getMock('Symfony\Component\Routing\RouterInterface');
$router = $this->getMockBuilder('Symfony\Component\Routing\RouterInterface')->getMock();
$router
->expects($this->once())
->method('generate')
->with($this->equalTo($route), $this->equalTo($expectedAttributes))
->will($this->returnValue($url));
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock();
$container
->expects($this->once())
@@ -230,7 +230,7 @@ class RedirectControllerTest extends TestCase
private function createRequestObject($scheme, $host, $port, $baseUrl, $queryString = '')
{
$request = $this->getMock('Symfony\Component\HttpFoundation\Request');
$request = $this->getMockBuilder('Symfony\Component\HttpFoundation\Request')->getMock();
$request
->expects($this->any())
->method('getScheme')
@@ -257,7 +257,7 @@ class RedirectControllerTest extends TestCase
private function createRedirectController($httpPort = null, $httpsPort = null)
{
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock();
if (null !== $httpPort) {
$container
@@ -11,56 +11,37 @@
namespace Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler;
use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\AddCacheWarmerPass;
class AddCacheWarmerPassTest extends \PHPUnit_Framework_TestCase
class AddCacheWarmerPassTest extends TestCase
{
public function testThatCacheWarmersAreProcessedInPriorityOrder()
{
$services = array(
'my_cache_warmer_service1' => array(0 => array('priority' => 100)),
'my_cache_warmer_service2' => array(0 => array('priority' => 200)),
'my_cache_warmer_service3' => array(),
);
$container = new ContainerBuilder();
$definition = $this->getMock('Symfony\Component\DependencyInjection\Definition');
$container = $this->getMock(
'Symfony\Component\DependencyInjection\ContainerBuilder',
array('findTaggedServiceIds', 'getDefinition', 'hasDefinition')
);
$container->expects($this->atLeastOnce())
->method('findTaggedServiceIds')
->will($this->returnValue($services));
$container->expects($this->atLeastOnce())
->method('getDefinition')
->with('cache_warmer')
->will($this->returnValue($definition));
$container->expects($this->atLeastOnce())
->method('hasDefinition')
->with('cache_warmer')
->will($this->returnValue(true));
$definition->expects($this->once())
->method('replaceArgument')
->with(0, array(
new Reference('my_cache_warmer_service2'),
new Reference('my_cache_warmer_service1'),
new Reference('my_cache_warmer_service3'),
));
$definition = $container->register('cache_warmer')->addArgument(null);
$container->register('my_cache_warmer_service1')->addTag('kernel.cache_warmer', array('priority' => 100));
$container->register('my_cache_warmer_service2')->addTag('kernel.cache_warmer', array('priority' => 200));
$container->register('my_cache_warmer_service3')->addTag('kernel.cache_warmer');
$addCacheWarmerPass = new AddCacheWarmerPass();
$addCacheWarmerPass->process($container);
$expected = array(
new Reference('my_cache_warmer_service2'),
new Reference('my_cache_warmer_service1'),
new Reference('my_cache_warmer_service3'),
);
$this->assertEquals($expected, $definition->getArgument(0));
}
public function testThatCompilerPassIsIgnoredIfThereIsNoCacheWarmerDefinition()
{
$definition = $this->getMock('Symfony\Component\DependencyInjection\Definition');
$container = $this->getMock(
'Symfony\Component\DependencyInjection\ContainerBuilder',
array('hasDefinition', 'findTaggedServiceIds', 'getDefinition')
);
$definition = $this->getMockBuilder('Symfony\Component\DependencyInjection\Definition')->getMock();
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerBuilder')->setMethods(array('hasDefinition', 'findTaggedServiceIds', 'getDefinition'))->getMock();
$container->expects($this->never())->method('findTaggedServiceIds');
$container->expects($this->never())->method('getDefinition');
@@ -76,11 +57,8 @@ class AddCacheWarmerPassTest extends \PHPUnit_Framework_TestCase
public function testThatCacheWarmersMightBeNotDefined()
{
$definition = $this->getMock('Symfony\Component\DependencyInjection\Definition');
$container = $this->getMock(
'Symfony\Component\DependencyInjection\ContainerBuilder',
array('hasDefinition', 'findTaggedServiceIds', 'getDefinition')
);
$definition = $this->getMockBuilder('Symfony\Component\DependencyInjection\Definition')->getMock();
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerBuilder')->setMethods(array('hasDefinition', 'findTaggedServiceIds', 'getDefinition'))->getMock();
$container->expects($this->atLeastOnce())
->method('findTaggedServiceIds')
@@ -11,49 +11,52 @@
namespace Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler;
use PHPUnit\Framework\TestCase;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\AddConsoleCommandPass;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class AddConsoleCommandPassTest extends \PHPUnit_Framework_TestCase
class AddConsoleCommandPassTest extends TestCase
{
public function testProcess()
/**
* @dataProvider visibilityProvider
*/
public function testProcess($public)
{
$container = new ContainerBuilder();
$container->addCompilerPass(new AddConsoleCommandPass());
$container->setParameter('my-command.class', 'Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler\MyCommand');
$definition = new Definition('%my-command.class%');
$definition->setPublic($public);
$definition->addTag('console.command');
$container->setDefinition('my-command', $definition);
$container->compile();
$alias = 'console.command.symfony_bundle_frameworkbundle_tests_dependencyinjection_compiler_mycommand';
$this->assertTrue($container->hasAlias($alias));
$this->assertSame('my-command', (string) $container->getAlias($alias));
if ($container->hasAlias($alias)) {
$this->assertSame('my-command', (string) $container->getAlias($alias));
} else {
// The alias is replaced by a Definition by the ReplaceAliasByActualDefinitionPass
// in case the original service is private
$this->assertFalse($container->hasDefinition('my-command'));
$this->assertTrue($container->hasDefinition($alias));
}
$id = $public ? 'my-command' : 'console.command.symfony_bundle_frameworkbundle_tests_dependencyinjection_compiler_mycommand';
$this->assertTrue($container->hasParameter('console.command.ids'));
$this->assertSame(array('my-command'), $container->getParameter('console.command.ids'));
$this->assertSame(array($id), $container->getParameter('console.command.ids'));
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage The service "my-command" tagged "console.command" must be public.
*/
public function testProcessThrowAnExceptionIfTheServiceIsNotPublic()
public function visibilityProvider()
{
$container = new ContainerBuilder();
$container->addCompilerPass(new AddConsoleCommandPass());
$definition = new Definition('Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler\MyCommand');
$definition->addTag('console.command');
$definition->setPublic(false);
$container->setDefinition('my-command', $definition);
$container->compile();
return array(
array(true),
array(false),
);
}
/**
@@ -88,26 +91,6 @@ class AddConsoleCommandPassTest extends \PHPUnit_Framework_TestCase
$container->compile();
}
public function testHttpKernelRegisterCommandsIngoreCommandAsAService()
{
$container = new ContainerBuilder();
$container->addCompilerPass(new AddConsoleCommandPass());
$definition = new Definition('Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler\MyCommand');
$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);
}
}
class MyCommand extends Command
@@ -9,9 +9,12 @@
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler;
use PHPUnit\Framework\TestCase;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\AddConstraintValidatorsPass;
class AddConstraintValidatorsPassTest extends \PHPUnit_Framework_TestCase
class AddConstraintValidatorsPassTest extends TestCase
{
public function testThatConstraintValidatorServicesAreProcessed()
{
@@ -20,14 +23,11 @@ class AddConstraintValidatorsPassTest extends \PHPUnit_Framework_TestCase
'my_constraint_validator_service2' => array(),
);
$validatorFactoryDefinition = $this->getMock('Symfony\Component\DependencyInjection\Definition');
$container = $this->getMock(
'Symfony\Component\DependencyInjection\ContainerBuilder',
array('findTaggedServiceIds', 'getDefinition', 'hasDefinition')
);
$validatorFactoryDefinition = $this->getMockBuilder('Symfony\Component\DependencyInjection\Definition')->getMock();
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerBuilder')->setMethods(array('findTaggedServiceIds', 'getDefinition', 'hasDefinition'))->getMock();
$validatorDefinition1 = $this->getMock('Symfony\Component\DependencyInjection\Definition', array('getClass'));
$validatorDefinition2 = $this->getMock('Symfony\Component\DependencyInjection\Definition', array('getClass'));
$validatorDefinition1 = $this->getMockBuilder('Symfony\Component\DependencyInjection\Definition')->setMethods(array('getClass'))->getMock();
$validatorDefinition2 = $this->getMockBuilder('Symfony\Component\DependencyInjection\Definition')->setMethods(array('getClass'))->getMock();
$validatorDefinition1->expects($this->atLeastOnce())
->method('getClass')
@@ -67,11 +67,8 @@ class AddConstraintValidatorsPassTest extends \PHPUnit_Framework_TestCase
public function testThatCompilerPassIsIgnoredIfThereIsNoConstraintValidatorFactoryDefinition()
{
$definition = $this->getMock('Symfony\Component\DependencyInjection\Definition');
$container = $this->getMock(
'Symfony\Component\DependencyInjection\ContainerBuilder',
array('hasDefinition', 'findTaggedServiceIds', 'getDefinition')
);
$definition = $this->getMockBuilder('Symfony\Component\DependencyInjection\Definition')->getMock();
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerBuilder')->setMethods(array('hasDefinition', 'findTaggedServiceIds', 'getDefinition'))->getMock();
$container->expects($this->never())->method('findTaggedServiceIds');
$container->expects($this->never())->method('getDefinition');
@@ -11,12 +11,13 @@
namespace Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler;
use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\AddExpressionLanguageProvidersPass;
class AddExpressionLanguageProvidersPassTest extends \PHPUnit_Framework_TestCase
class AddExpressionLanguageProvidersPassTest extends TestCase
{
public function testProcessForRouter()
{
@@ -11,52 +11,36 @@
namespace Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler;
use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\ConfigCachePass;
class ConfigCachePassTest extends \PHPUnit_Framework_TestCase
class ConfigCachePassTest extends TestCase
{
public function testThatCheckersAreProcessedInPriorityOrder()
{
$services = array(
'checker_2' => array(0 => array('priority' => 100)),
'checker_1' => array(0 => array('priority' => 200)),
'checker_3' => array(),
);
$container = new ContainerBuilder();
$definition = $this->getMock('Symfony\Component\DependencyInjection\Definition');
$container = $this->getMock(
'Symfony\Component\DependencyInjection\ContainerBuilder',
array('findTaggedServiceIds', 'getDefinition', 'hasDefinition')
);
$container->expects($this->atLeastOnce())
->method('findTaggedServiceIds')
->will($this->returnValue($services));
$container->expects($this->atLeastOnce())
->method('getDefinition')
->with('config_cache_factory')
->will($this->returnValue($definition));
$definition->expects($this->once())
->method('replaceArgument')
->with(0, array(
new Reference('checker_1'),
new Reference('checker_2'),
new Reference('checker_3'),
));
$definition = $container->register('config_cache_factory')->addArgument(null);
$container->register('checker_2')->addTag('config_cache.resource_checker', array('priority' => 100));
$container->register('checker_1')->addTag('config_cache.resource_checker', array('priority' => 200));
$container->register('checker_3')->addTag('config_cache.resource_checker');
$pass = new ConfigCachePass();
$pass->process($container);
$expected = array(
new Reference('checker_1'),
new Reference('checker_2'),
new Reference('checker_3'),
);
$this->assertEquals($expected, $definition->getArgument(0));
}
public function testThatCheckersCanBeMissing()
{
$definition = $this->getMock('Symfony\Component\DependencyInjection\Definition');
$container = $this->getMock(
'Symfony\Component\DependencyInjection\ContainerBuilder',
array('findTaggedServiceIds')
);
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerBuilder')->setMethods(array('findTaggedServiceIds'))->getMock();
$container->expects($this->atLeastOnce())
->method('findTaggedServiceIds')
@@ -11,6 +11,7 @@
namespace Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler;
use PHPUnit\Framework\TestCase;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\FormPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
@@ -20,7 +21,7 @@ use Symfony\Component\Form\AbstractType;
/**
* @author Bernhard Schussek <bschussek@gmail.com>
*/
class FormPassTest extends \PHPUnit_Framework_TestCase
class FormPassTest extends TestCase
{
public function testDoNothingIfFormExtensionNotLoaded()
{
@@ -59,7 +60,10 @@ class FormPassTest extends \PHPUnit_Framework_TestCase
), $extDefinition->getArgument(1));
}
public function testAddTaggedTypeExtensions()
/**
* @dataProvider addTaggedTypeExtensionsDataProvider
*/
public function testAddTaggedTypeExtensions(array $extensions, array $expectedRegisteredExtensions)
{
$container = new ContainerBuilder();
$container->addCompilerPass(new FormPass());
@@ -72,26 +76,49 @@ class FormPassTest extends \PHPUnit_Framework_TestCase
));
$container->setDefinition('form.extension', $extDefinition);
$container->register('my.type_extension1', 'stdClass')
->addTag('form.type_extension', array('extended_type' => 'type1'));
$container->register('my.type_extension2', 'stdClass')
->addTag('form.type_extension', array('extended_type' => 'type1'));
$container->register('my.type_extension3', 'stdClass')
->addTag('form.type_extension', array('extended_type' => 'type2'));
foreach ($extensions as $serviceId => $tag) {
$container->register($serviceId, 'stdClass')->addTag('form.type_extension', $tag);
}
$container->compile();
$extDefinition = $container->getDefinition('form.extension');
$this->assertSame($expectedRegisteredExtensions, $extDefinition->getArgument(2));
}
$this->assertSame(array(
'type1' => array(
'my.type_extension1',
'my.type_extension2',
/**
* @return array
*/
public function addTaggedTypeExtensionsDataProvider()
{
return array(
array(
array(
'my.type_extension1' => array('extended_type' => 'type1'),
'my.type_extension2' => array('extended_type' => 'type1'),
'my.type_extension3' => array('extended_type' => 'type2'),
),
array(
'type1' => array('my.type_extension1', 'my.type_extension2'),
'type2' => array('my.type_extension3'),
),
),
'type2' => array(
'my.type_extension3',
array(
array(
'my.type_extension1' => array('extended_type' => 'type1', 'priority' => 1),
'my.type_extension2' => array('extended_type' => 'type1', 'priority' => 2),
'my.type_extension3' => array('extended_type' => 'type1', 'priority' => -1),
'my.type_extension4' => array('extended_type' => 'type2', 'priority' => 2),
'my.type_extension5' => array('extended_type' => 'type2', 'priority' => 1),
'my.type_extension6' => array('extended_type' => 'type2', 'priority' => 1),
),
array(
'type1' => array('my.type_extension2', 'my.type_extension1', 'my.type_extension3'),
'type2' => array('my.type_extension4', 'my.type_extension5', 'my.type_extension6'),
),
),
), $extDefinition->getArgument(2));
);
}
/**
@@ -168,7 +195,12 @@ class FormPassTest extends \PHPUnit_Framework_TestCase
$container->setDefinition('form.extension', $extDefinition);
$container->register($id, 'stdClass')->setPublic(false)->addTag($tagName);
$this->setExpectedException('\InvalidArgumentException', $expectedExceptionMessage);
if (method_exists($this, 'expectException')) {
$this->expectException('InvalidArgumentException');
$this->expectExceptionMessage($expectedExceptionMessage);
} else {
$this->setExpectedException('InvalidArgumentException', $expectedExceptionMessage);
}
$container->compile();
}
@@ -11,15 +11,16 @@
namespace Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler;
use PHPUnit\Framework\TestCase;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\LoggingTranslatorPass;
class LoggingTranslatorPassTest extends \PHPUnit_Framework_TestCase
class LoggingTranslatorPassTest extends TestCase
{
public function testProcess()
{
$definition = $this->getMock('Symfony\Component\DependencyInjection\Definition');
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerBuilder');
$parameterBag = $this->getMock('Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface');
$definition = $this->getMockBuilder('Symfony\Component\DependencyInjection\Definition')->getMock();
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerBuilder')->getMock();
$parameterBag = $this->getMockBuilder('Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface')->getMock();
$container->expects($this->exactly(2))
->method('hasAlias')
@@ -60,7 +61,7 @@ class LoggingTranslatorPassTest extends \PHPUnit_Framework_TestCase
public function testThatCompilerPassIsIgnoredIfThereIsNotLoggerDefinition()
{
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerBuilder');
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerBuilder')->getMock();
$container->expects($this->once())
->method('hasAlias')
->will($this->returnValue(false));
@@ -71,7 +72,7 @@ class LoggingTranslatorPassTest extends \PHPUnit_Framework_TestCase
public function testThatCompilerPassIsIgnoredIfThereIsNotTranslatorDefinition()
{
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerBuilder');
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerBuilder')->getMock();
$container->expects($this->at(0))
->method('hasAlias')
->will($this->returnValue(true));
@@ -11,10 +11,11 @@
namespace Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler;
use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\ProfilerPass;
class ProfilerPassTest extends \PHPUnit_Framework_TestCase
class ProfilerPassTest extends TestCase
{
private $profilerDefinition;
@@ -40,7 +41,7 @@ class ProfilerPassTest extends \PHPUnit_Framework_TestCase
$builder = $this->createContainerMock($services);
$this->setExpectedException('InvalidArgumentException');
$this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}('InvalidArgumentException');
$profilerPass = new ProfilerPass();
$profilerPass->process($builder);
@@ -75,10 +76,7 @@ class ProfilerPassTest extends \PHPUnit_Framework_TestCase
private function createContainerMock($services)
{
$container = $this->getMock(
'Symfony\Component\DependencyInjection\ContainerBuilder',
array('hasDefinition', 'getDefinition', 'findTaggedServiceIds', 'setParameter')
);
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerBuilder')->setMethods(array('hasDefinition', 'getDefinition', 'findTaggedServiceIds', 'setParameter'))->getMock();
$container->expects($this->any())
->method('hasDefinition')
->with($this->equalTo('profiler'))
@@ -11,51 +11,55 @@
namespace Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler;
use PHPUnit\Framework\TestCase;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\PropertyInfoPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
class PropertyInfoPassTest extends \PHPUnit_Framework_TestCase
class PropertyInfoPassTest extends TestCase
{
public function testServicesAreOrderedAccordingToPriority()
/**
* @dataProvider provideTags
*/
public function testServicesAreOrderedAccordingToPriority($index, $tag)
{
$services = array(
'n3' => array('tag' => array()),
'n1' => array('tag' => array('priority' => 200)),
'n2' => array('tag' => array('priority' => 100)),
);
$container = new ContainerBuilder();
$definition = $container->register('property_info')->setArguments(array(null, null, null, null));
$container->register('n2')->addTag($tag, array('priority' => 100));
$container->register('n1')->addTag($tag, array('priority' => 200));
$container->register('n3')->addTag($tag);
$propertyInfoPass = new PropertyInfoPass();
$propertyInfoPass->process($container);
$expected = array(
new Reference('n1'),
new Reference('n2'),
new Reference('n3'),
);
$this->assertEquals($expected, $definition->getArgument($index));
}
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerBuilder', array('findTaggedServiceIds'));
$container->expects($this->any())
->method('findTaggedServiceIds')
->will($this->returnValue($services));
$propertyInfoPass = new PropertyInfoPass();
$method = new \ReflectionMethod(
'Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\PropertyInfoPass',
'findAndSortTaggedServices'
public function provideTags()
{
return array(
array(0, 'property_info.list_extractor'),
array(1, 'property_info.type_extractor'),
array(2, 'property_info.description_extractor'),
array(3, 'property_info.access_extractor'),
);
$method->setAccessible(true);
$actual = $method->invoke($propertyInfoPass, 'tag', $container);
$this->assertEquals($expected, $actual);
}
public function testReturningEmptyArrayWhenNoService()
{
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerBuilder', array('findTaggedServiceIds'));
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerBuilder')->setMethods(array('findTaggedServiceIds'))->getMock();
$container->expects($this->any())
$container
->expects($this->any())
->method('findTaggedServiceIds')
->will($this->returnValue(array()));
->will($this->returnValue(array()))
;
$propertyInfoPass = new PropertyInfoPass();
@@ -11,6 +11,8 @@
namespace Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler;
use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\SerializerPass;
@@ -19,11 +21,11 @@ use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\SerializerPass;
*
* @author Javier Lopez <f12loalf@gmail.com>
*/
class SerializerPassTest extends \PHPUnit_Framework_TestCase
class SerializerPassTest extends TestCase
{
public function testThrowExceptionWhenNoNormalizers()
{
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerBuilder', array('hasDefinition', 'findTaggedServiceIds'));
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerBuilder')->setMethods(array('hasDefinition', 'findTaggedServiceIds'))->getMock();
$container->expects($this->once())
->method('hasDefinition')
@@ -35,7 +37,7 @@ class SerializerPassTest extends \PHPUnit_Framework_TestCase
->with('serializer.normalizer')
->will($this->returnValue(array()));
$this->setExpectedException('RuntimeException');
$this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}('RuntimeException');
$serializerPass = new SerializerPass();
$serializerPass->process($container);
@@ -43,11 +45,8 @@ class SerializerPassTest extends \PHPUnit_Framework_TestCase
public function testThrowExceptionWhenNoEncoders()
{
$definition = $this->getMock('Symfony\Component\DependencyInjection\Definition');
$container = $this->getMock(
'Symfony\Component\DependencyInjection\ContainerBuilder',
array('hasDefinition', 'findTaggedServiceIds', 'getDefinition')
);
$definition = $this->getMockBuilder('Symfony\Component\DependencyInjection\Definition')->getMock();
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerBuilder')->setMethods(array('hasDefinition', 'findTaggedServiceIds', 'getDefinition'))->getMock();
$container->expects($this->once())
->method('hasDefinition')
@@ -61,11 +60,11 @@ class SerializerPassTest extends \PHPUnit_Framework_TestCase
array()
));
$container->expects($this->once())
$container->expects($this->any())
->method('getDefinition')
->will($this->returnValue($definition));
$this->setExpectedException('RuntimeException');
$this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}('RuntimeException');
$serializerPass = new SerializerPass();
$serializerPass->process($container);
@@ -73,34 +72,22 @@ class SerializerPassTest extends \PHPUnit_Framework_TestCase
public function testServicesAreOrderedAccordingToPriority()
{
$services = array(
'n3' => array('tag' => array()),
'n1' => array('tag' => array('priority' => 200)),
'n2' => array('tag' => array('priority' => 100)),
);
$container = new ContainerBuilder();
$expected = array(
new Reference('n1'),
new Reference('n2'),
new Reference('n3'),
);
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerBuilder', array('findTaggedServiceIds'));
$container->expects($this->any())
->method('findTaggedServiceIds')
->will($this->returnValue($services));
$definition = $container->register('serializer')->setArguments(array(null, null));
$container->register('n2')->addTag('serializer.normalizer', array('priority' => 100))->addTag('serializer.encoder', array('priority' => 100));
$container->register('n1')->addTag('serializer.normalizer', array('priority' => 200))->addTag('serializer.encoder', array('priority' => 200));
$container->register('n3')->addTag('serializer.normalizer')->addTag('serializer.encoder');
$serializerPass = new SerializerPass();
$serializerPass->process($container);
$method = new \ReflectionMethod(
'Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\SerializerPass',
'findAndSortTaggedServices'
$expected = array(
new Reference('n1'),
new Reference('n2'),
new Reference('n3'),
);
$method->setAccessible(true);
$actual = $method->invoke($serializerPass, 'tag', $container);
$this->assertEquals($expected, $actual);
$this->assertEquals($expected, $definition->getArgument(0));
$this->assertEquals($expected, $definition->getArgument(1));
}
}
@@ -11,14 +11,15 @@
namespace Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler;
use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\TranslatorPass;
class TranslatorPassTest extends \PHPUnit_Framework_TestCase
class TranslatorPassTest extends TestCase
{
public function testValidCollector()
{
$definition = $this->getMock('Symfony\Component\DependencyInjection\Definition');
$definition = $this->getMockBuilder('Symfony\Component\DependencyInjection\Definition')->getMock();
$definition->expects($this->at(0))
->method('addMethodCall')
->with('addLoader', array('xliff', new Reference('xliff')));
@@ -26,10 +27,7 @@ class TranslatorPassTest extends \PHPUnit_Framework_TestCase
->method('addMethodCall')
->with('addLoader', array('xlf', new Reference('xliff')));
$container = $this->getMock(
'Symfony\Component\DependencyInjection\ContainerBuilder',
array('hasDefinition', 'getDefinition', 'findTaggedServiceIds', 'findDefinition')
);
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerBuilder')->setMethods(array('hasDefinition', 'getDefinition', 'findTaggedServiceIds', 'findDefinition'))->getMock();
$container->expects($this->any())
->method('hasDefinition')
->will($this->returnValue(true));
@@ -41,7 +39,7 @@ class TranslatorPassTest extends \PHPUnit_Framework_TestCase
->will($this->returnValue(array('xliff' => array(array('alias' => 'xliff', 'legacy-alias' => 'xlf')))));
$container->expects($this->once())
->method('findDefinition')
->will($this->returnValue($this->getMock('Symfony\Component\DependencyInjection\Definition')));
->will($this->returnValue($this->getMockBuilder('Symfony\Component\DependencyInjection\Definition')->getMock()));
$pass = new TranslatorPass();
$pass->process($container);
}
@@ -11,27 +11,26 @@
namespace Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler;
use PHPUnit\Framework\TestCase;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\UnusedTagsPass;
class UnusedTagsPassTest extends \PHPUnit_Framework_TestCase
class UnusedTagsPassTest extends TestCase
{
public function testProcess()
{
$pass = new UnusedTagsPass();
$formatter = $this->getMock('Symfony\Component\DependencyInjection\Compiler\LoggingFormatter');
$formatter = $this->getMockBuilder('Symfony\Component\DependencyInjection\Compiler\LoggingFormatter')->getMock();
$formatter
->expects($this->at(0))
->method('format')
->with($pass, 'Tag "kenrel.event_subscriber" was defined on service(s) "foo", "bar", but was never used. Did you mean "kernel.event_subscriber"?')
;
$compiler = $this->getMock('Symfony\Component\DependencyInjection\Compiler\Compiler');
$compiler = $this->getMockBuilder('Symfony\Component\DependencyInjection\Compiler\Compiler')->getMock();
$compiler->expects($this->once())->method('getLoggingFormatter')->will($this->returnValue($formatter));
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerBuilder',
array('findTaggedServiceIds', 'getCompiler', 'findUnusedTags', 'findTags')
);
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerBuilder')->setMethods(array('findTaggedServiceIds', 'getCompiler', 'findUnusedTags', 'findTags'))->getMock();
$container->expects($this->once())->method('getCompiler')->will($this->returnValue($compiler));
$container->expects($this->once())
->method('findTags')
@@ -11,10 +11,11 @@
namespace Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection;
use PHPUnit\Framework\TestCase;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Configuration;
use Symfony\Component\Config\Definition\Processor;
class ConfigurationTest extends \PHPUnit_Framework_TestCase
class ConfigurationTest extends TestCase
{
public function testDefaultConfig()
{
@@ -92,6 +93,7 @@ class ConfigurationTest extends \PHPUnit_Framework_TestCase
{
$processor = new Processor();
$configuration = new Configuration(true);
$processor->processConfiguration($configuration, array(
array(
'secret' => 's3cr3t',
@@ -107,6 +109,8 @@ class ConfigurationTest extends \PHPUnit_Framework_TestCase
$config = $processor->processConfiguration($configuration, array(array('assets' => null)));
$defaultConfig = array(
'enabled' => true,
'version_strategy' => null,
'version' => null,
'version_format' => '%%s?%%s',
'base_path' => '',
@@ -117,6 +121,51 @@ class ConfigurationTest extends \PHPUnit_Framework_TestCase
$this->assertEquals($defaultConfig, $config['assets']);
}
/**
* @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException
* @expectedExceptionMessage You cannot use both "version_strategy" and "version" at the same time under "assets".
*/
public function testInvalidVersionStrategy()
{
$processor = new Processor();
$configuration = new Configuration(true);
$processor->processConfiguration($configuration, array(
array(
'assets' => array(
'base_urls' => '//example.com',
'version' => 1,
'version_strategy' => 'foo',
),
),
));
}
/**
* @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException
* @expectedExceptionMessage You cannot use both "version_strategy" and "version" at the same time under "assets" packages.
*/
public function testInvalidPackageVersionStrategy()
{
$processor = new Processor();
$configuration = new Configuration(true);
$processor->processConfiguration($configuration, array(
array(
'assets' => array(
'base_urls' => '//example.com',
'version' => 1,
'packages' => array(
'foo' => array(
'base_urls' => '//example.com',
'version' => 1,
'version_strategy' => 'foo',
),
),
),
),
));
}
protected static function getBundleDefaultConfig()
{
return array(
@@ -146,6 +195,10 @@ class ConfigurationTest extends \PHPUnit_Framework_TestCase
'only_master_requests' => false,
'dsn' => 'file:%kernel.cache_dir%/profiler',
'collect' => true,
'matcher' => array(
'enabled' => false,
'ips' => array(),
),
),
'translator' => array(
'enabled' => false,
@@ -161,9 +214,10 @@ class ConfigurationTest extends \PHPUnit_Framework_TestCase
'strict_email' => false,
),
'annotations' => array(
'cache' => 'file',
'cache' => 'php_array',
'file_cache_dir' => '%kernel.cache_dir%/annotations',
'debug' => true,
'enabled' => true,
),
'serializer' => array(
'enabled' => false,
@@ -176,6 +230,55 @@ class ConfigurationTest extends \PHPUnit_Framework_TestCase
'property_info' => array(
'enabled' => false,
),
'router' => array(
'enabled' => false,
'http_port' => 80,
'https_port' => 443,
'strict_requirements' => true,
),
'session' => array(
'enabled' => false,
'storage_id' => 'session.storage.native',
'handler_id' => 'session.handler.native_file',
'cookie_httponly' => true,
'gc_probability' => 1,
'save_path' => '%kernel.cache_dir%/sessions',
'metadata_update_threshold' => '0',
),
'request' => array(
'enabled' => false,
'formats' => array(),
),
'templating' => array(
'enabled' => false,
'hinclude_default_template' => null,
'form' => array(
'resources' => array('FrameworkBundle:Form'),
),
'engines' => array(),
'loaders' => array(),
),
'assets' => array(
'enabled' => false,
'version_strategy' => null,
'version' => null,
'version_format' => '%%s?%%s',
'base_path' => '',
'base_urls' => array(),
'packages' => array(),
),
'cache' => array(
'pools' => array(),
'app' => 'cache.adapter.filesystem',
'system' => 'cache.adapter.system',
'directory' => '%kernel.cache_dir%/pools',
'default_redis_provider' => 'redis://localhost',
),
'workflows' => array(),
'php_errors' => array(
'log' => true,
'throw' => true,
),
);
}
}
@@ -11,6 +11,8 @@
namespace Symfony\Bundle\FrameworkBundle\Tests;
class TestBundle extends \Symfony\Component\HttpKernel\Bundle\Bundle
use Symfony\Component\HttpKernel\Bundle\Bundle;
class TestBundle extends Bundle
{
}
@@ -20,9 +20,9 @@ $container->loadFromExtension('framework', array(
'bar' => array(
'base_urls' => array('https://bar2.example.com'),
),
'bar_null_version' => array(
'version' => null,
'base_urls' => array('https://bar3.example.com'),
'bar_version_strategy' => array(
'base_urls' => array('https://bar2.example.com'),
'version_strategy' => 'assets.custom_version_strategy',
),
),
),
@@ -14,6 +14,9 @@ $container->loadFromExtension('framework', array(
'esi' => array(
'enabled' => true,
),
'ssi' => array(
'enabled' => true,
),
'profiler' => array(
'only_exceptions' => true,
'enabled' => false,
@@ -56,7 +59,6 @@ $container->loadFromExtension('framework', array(
),
'validation' => array(
'enabled' => true,
'cache' => 'validator.mapping.cache.doctrine.apc',
),
'annotations' => array(
'cache' => 'file',
@@ -66,9 +68,9 @@ $container->loadFromExtension('framework', array(
'serializer' => array(
'enabled' => true,
'enable_annotations' => true,
'cache' => 'serializer.mapping.cache.apc',
'name_converter' => 'serializer.name_converter.camel_case_to_snake_case',
),
'property_info' => true,
'ide' => 'file%%link%%format',
'request' => array(
'formats' => array(
@@ -18,8 +18,8 @@
<framework:package name="bar">
<framework:base-url>https://bar2.example.com</framework:base-url>
</framework:package>
<framework:package name="bar_null_version" version="">
<framework:base-url>https://bar3.example.com</framework:base-url>
<framework:package name="bar_version_strategy" version-strategy="assets.custom_version_strategy">
<framework:base-url>https://bar_version_strategy.example.com</framework:base-url>
</framework:package>
</framework:assets>
</framework:config>
@@ -12,6 +12,7 @@
<framework:csrf-protection field-name="_csrf"/>
</framework:form>
<framework:esi enabled="true" />
<framework:ssi enabled="true" />
<framework:profiler only-exceptions="true" enabled="false" />
<framework:router resource="%kernel.root_dir%/config/routing.xml" type="xml" />
<framework:session gc-maxlifetime="90000" gc-probability="1" gc-divisor="108" storage-id="session.storage.native" handler-id="session.handler.native_file" name="_SYMFONY" cookie-lifetime="86400" cookie-path="/" cookie-domain="example.com" cookie-secure="true" cookie-httponly="false" use-cookies="true" save-path="/path/to/sessions" />
@@ -38,8 +39,9 @@
<framework:translator enabled="true" fallback="fr" logging="true">
<framework:path>%kernel.root_dir%/Fixtures/translations</framework:path>
</framework:translator>
<framework:validation enabled="true" cache="validator.mapping.cache.doctrine.apc" />
<framework:validation enabled="true" />
<framework:annotations cache="file" debug="true" file-cache-dir="%kernel.cache_dir%/annotations" />
<framework:serializer enabled="true" enable-annotations="true" cache="serializer.mapping.cache.apc" name-converter="serializer.name_converter.camel_case_to_snake_case" />
<framework:serializer enabled="true" enable-annotations="true" name-converter="serializer.name_converter.camel_case_to_snake_case" />
<framework:property-info />
</framework:config>
</container>
@@ -14,6 +14,6 @@ framework:
version_format: '%%s-%%s'
bar:
base_urls: ["https://bar2.example.com"]
bar_null_version:
version: null
base_urls: "https://bar3.example.com"
bar_version_strategy:
base_urls: ["https://bar_version_strategy.example.com"]
version_strategy: assets.custom_version_strategy
@@ -9,6 +9,8 @@ framework:
trusted_proxies: ['127.0.0.1', '10.0.0.1']
esi:
enabled: true
ssi:
enabled: true
profiler:
only_exceptions: true
enabled: false
@@ -44,7 +46,6 @@ framework:
paths: ['%kernel.root_dir%/Fixtures/translations']
validation:
enabled: true
cache: validator.mapping.cache.doctrine.apc
annotations:
cache: file
debug: true
@@ -52,8 +53,8 @@ framework:
serializer:
enabled: true
enable_annotations: true
cache: serializer.mapping.cache.apc
name_converter: serializer.name_converter.camel_case_to_snake_case
property_info: ~
ide: file%%link%%format
request:
formats:
@@ -12,12 +12,28 @@
namespace Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection;
use Symfony\Bundle\FrameworkBundle\Tests\TestCase;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\AddAnnotationsCachedReaderPass;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\FrameworkExtension;
use Symfony\Component\Cache\Adapter\AdapterInterface;
use Symfony\Component\Cache\Adapter\ApcuAdapter;
use Symfony\Component\Cache\Adapter\ArrayAdapter;
use Symfony\Component\Cache\Adapter\ChainAdapter;
use Symfony\Component\Cache\Adapter\DoctrineAdapter;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
use Symfony\Component\Cache\Adapter\ProxyAdapter;
use Symfony\Component\Cache\Adapter\RedisAdapter;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\DefinitionDecorator;
use Symfony\Component\DependencyInjection\Loader\ClosureLoader;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\PropertyAccess\PropertyAccessor;
use Symfony\Component\Serializer\Mapping\Factory\CacheClassMetadataFactory;
use Symfony\Component\Serializer\Mapping\Loader\XmlFileLoader;
use Symfony\Component\Serializer\Mapping\Loader\YamlFileLoader;
use Symfony\Component\Serializer\Normalizer\DataUriNormalizer;
use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer;
use Symfony\Component\Serializer\Normalizer\JsonSerializableNormalizer;
abstract class FrameworkExtensionTest extends TestCase
{
@@ -54,6 +70,32 @@ abstract class FrameworkExtensionTest extends TestCase
$this->assertTrue($def->getArgument(1));
}
public function testPropertyAccessCache()
{
$container = $this->createContainerFromFile('property_accessor');
if (!method_exists(PropertyAccessor::class, 'createCache')) {
return $this->assertFalse($container->hasDefinition('cache.property_access'));
}
$cache = $container->getDefinition('cache.property_access');
$this->assertSame(array(PropertyAccessor::class, 'createCache'), $cache->getFactory(), 'PropertyAccessor::createCache() should be used in non-debug mode');
$this->assertSame(AdapterInterface::class, $cache->getClass());
}
public function testPropertyAccessCacheWithDebug()
{
$container = $this->createContainerFromFile('property_accessor', array('kernel.debug' => true));
if (!method_exists(PropertyAccessor::class, 'createCache')) {
return $this->assertFalse($container->hasDefinition('cache.property_access'));
}
$cache = $container->getDefinition('cache.property_access');
$this->assertNull($cache->getFactory());
$this->assertSame(ArrayAdapter::class, $cache->getClass(), 'ArrayAdapter should be used in debug mode');
}
/**
* @expectedException \LogicException
* @expectedExceptionMessage CSRF protection needs sessions to be enabled.
@@ -91,6 +133,13 @@ abstract class FrameworkExtensionTest extends TestCase
$this->assertTrue($container->hasDefinition('esi'), '->registerEsiConfiguration() loads esi.xml');
}
public function testSsi()
{
$container = $this->createContainerFromFile('full');
$this->assertTrue($container->hasDefinition('ssi'), '->registerSsiConfiguration() loads ssi.xml');
}
public function testEnabledProfiler()
{
$container = $this->createContainerFromFile('profiler');
@@ -107,6 +156,100 @@ abstract class FrameworkExtensionTest extends TestCase
$this->assertFalse($container->hasDefinition('data_collector.config'), '->registerProfilerConfiguration() does not load collectors.xml');
}
public function testWorkflows()
{
$container = $this->createContainerFromFile('workflows');
$this->assertTrue($container->hasDefinition('workflow.article', 'Workflow is registered as a service'));
$this->assertTrue($container->hasDefinition('workflow.article.definition', 'Workflow definition is registered as a service'));
$workflowDefinition = $container->getDefinition('workflow.article.definition');
$this->assertSame(
array(
'draft',
'wait_for_journalist',
'approved_by_journalist',
'wait_for_spellchecker',
'approved_by_spellchecker',
'published',
),
$workflowDefinition->getArgument(0),
'Places are passed to the workflow definition'
);
$this->assertSame(array('workflow.definition' => array(array('name' => 'article', 'type' => 'workflow', 'marking_store' => 'multiple_state'))), $workflowDefinition->getTags());
$this->assertTrue($container->hasDefinition('state_machine.pull_request', 'State machine is registered as a service'));
$this->assertTrue($container->hasDefinition('state_machine.pull_request.definition', 'State machine definition is registered as a service'));
$this->assertCount(4, $workflowDefinition->getArgument(1));
$this->assertSame('draft', $workflowDefinition->getArgument(2));
$stateMachineDefinition = $container->getDefinition('state_machine.pull_request.definition');
$this->assertSame(
array(
'start',
'coding',
'travis',
'review',
'merged',
'closed',
),
$stateMachineDefinition->getArgument(0),
'Places are passed to the state machine definition'
);
$this->assertSame(array('workflow.definition' => array(array('name' => 'pull_request', 'type' => 'state_machine', 'marking_store' => 'single_state'))), $stateMachineDefinition->getTags());
$this->assertCount(9, $stateMachineDefinition->getArgument(1));
$this->assertSame('start', $stateMachineDefinition->getArgument(2));
$serviceMarkingStoreWorkflowDefinition = $container->getDefinition('workflow.service_marking_store_workflow');
/** @var Reference $markingStoreRef */
$markingStoreRef = $serviceMarkingStoreWorkflowDefinition->getArgument(1);
$this->assertInstanceOf(Reference::class, $markingStoreRef);
$this->assertEquals('workflow_service', (string) $markingStoreRef);
}
/**
* @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException
* @expectedExceptionMessage "type" and "service" cannot be used together.
*/
public function testWorkflowCannotHaveBothTypeAndService()
{
$this->createContainerFromFile('workflow_with_type_and_service');
}
/**
* @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException
* @expectedExceptionMessage "arguments" and "service" cannot be used together.
*/
public function testWorkflowCannotHaveBothArgumentsAndService()
{
$this->createContainerFromFile('workflow_with_arguments_and_service');
}
public function testWorkflowMultipleTransitionsWithSameName()
{
$container = $this->createContainerFromFile('workflow_with_multiple_transitions_with_same_name');
$this->assertTrue($container->hasDefinition('workflow.article', 'Workflow is registered as a service'));
$this->assertTrue($container->hasDefinition('workflow.article.definition', 'Workflow definition is registered as a service'));
$workflowDefinition = $container->getDefinition('workflow.article.definition');
$transitions = $workflowDefinition->getArgument(1);
$this->assertCount(5, $transitions);
$this->assertSame('request_review', $transitions[0]->getArgument(0));
$this->assertSame('journalist_approval', $transitions[1]->getArgument(0));
$this->assertSame('spellchecker_approval', $transitions[2]->getArgument(0));
$this->assertSame('publish', $transitions[3]->getArgument(0));
$this->assertSame('publish', $transitions[4]->getArgument(0));
$this->assertSame(array('approved_by_journalist', 'approved_by_spellchecker'), $transitions[3]->getArgument(1));
$this->assertSame(array('draft'), $transitions[4]->getArgument(1));
}
public function testRouter()
{
$container = $this->createContainerFromFile('full');
@@ -198,30 +341,50 @@ abstract class FrameworkExtensionTest extends TestCase
$this->assertEquals('global_hinclude_template', $container->getParameter('fragment.renderer.hinclude.global_template'), '->registerTemplatingConfiguration() registers the global hinclude.js template');
}
public function testTemplatingCanBeDisabled()
{
$container = $this->createContainerFromFile('templating_disabled');
$this->assertFalse($container->hasParameter('templating.engines'), '"templating.engines" container parameter is not registered when templating is disabled.');
}
public function testAssets()
{
$container = $this->createContainerFromFile('assets');
$packages = $container->getDefinition('assets.packages');
// default package
$defaultPackage = $container->getDefinition($packages->getArgument(0));
$defaultPackage = $container->getDefinition((string) $packages->getArgument(0));
$this->assertUrlPackage($container, $defaultPackage, array('http://cdn.example.com'), 'SomeVersionScheme', '%%s?version=%%s');
// packages
$packages = $packages->getArgument(1);
$this->assertCount(5, $packages);
$package = $container->getDefinition($packages['images_path']);
$package = $container->getDefinition((string) $packages['images_path']);
$this->assertPathPackage($container, $package, '/foo', 'SomeVersionScheme', '%%s?version=%%s');
$package = $container->getDefinition($packages['images']);
$package = $container->getDefinition((string) $packages['images']);
$this->assertUrlPackage($container, $package, array('http://images1.example.com', 'http://images2.example.com'), '1.0.0', '%%s?version=%%s');
$package = $container->getDefinition($packages['foo']);
$package = $container->getDefinition((string) $packages['foo']);
$this->assertPathPackage($container, $package, '', '1.0.0', '%%s-%%s');
$package = $container->getDefinition($packages['bar']);
$package = $container->getDefinition((string) $packages['bar']);
$this->assertUrlPackage($container, $package, array('https://bar2.example.com'), 'SomeVersionScheme', '%%s?version=%%s');
$package = $container->getDefinition((string) $packages['bar_version_strategy']);
$this->assertEquals('assets.custom_version_strategy', (string) $package->getArgument(1));
}
public function testAssetsDefaultVersionStrategyAsService()
{
$container = $this->createContainerFromFile('assets_version_strategy_as_service');
$packages = $container->getDefinition('assets.packages');
// default package
$defaultPackage = $container->getDefinition((string) $packages->getArgument(0));
$this->assertEquals('assets.custom_version_strategy', (string) $defaultPackage->getArgument(1));
}
public function testTranslator()
@@ -231,7 +394,7 @@ abstract class FrameworkExtensionTest extends TestCase
$this->assertEquals('translator.default', (string) $container->getAlias('translator'), '->registerTranslatorConfiguration() redefines translator service from identity to real translator');
$options = $container->getDefinition('translator.default')->getArgument(3);
$files = array_map(function ($resource) { return realpath($resource); }, $options['resource_files']['en']);
$files = array_map('realpath', $options['resource_files']['en']);
$ref = new \ReflectionClass('Symfony\Component\Validator\Validation');
$this->assertContains(
strtr(dirname($ref->getFileName()).'/Resources/translations/validators.en.xlf', '/', DIRECTORY_SEPARATOR),
@@ -299,12 +462,12 @@ abstract class FrameworkExtensionTest extends TestCase
$this->assertSame('addMethodMapping', $calls[4][0]);
$this->assertSame(array('loadValidatorMetadata'), $calls[4][1]);
$this->assertSame('setMetadataCache', $calls[5][0]);
$this->assertEquals(array(new Reference('validator.mapping.cache.doctrine.apc')), $calls[5][1]);
$this->assertEquals(array(new Reference('validator.mapping.cache.symfony')), $calls[5][1]);
}
public function testValidationService()
{
$container = $this->createContainerFromFile('validation_annotations');
$container = $this->createContainerFromFile('validation_annotations', array('kernel.charset' => 'UTF-8'), false);
$this->assertInstanceOf('Symfony\Component\Validator\Validator\ValidatorInterface', $container->get('validator'));
}
@@ -314,15 +477,18 @@ abstract class FrameworkExtensionTest extends TestCase
$container = $this->createContainerFromFile('full');
$this->assertEquals($container->getParameter('kernel.cache_dir').'/annotations', $container->getDefinition('annotations.filesystem_cache')->getArgument(0));
$this->assertSame('annotations.cached_reader', (string) $container->getAlias('annotation_reader'));
$this->assertSame('annotations.filesystem_cache', (string) $container->getDefinition('annotations.cached_reader')->getArgument(1));
}
public function testFileLinkFormat()
{
if (ini_get('xdebug.file_link_format') || get_cfg_var('xdebug.file_link_format')) {
$this->markTestSkipped('A custom file_link_format is defined.');
}
$container = $this->createContainerFromFile('full');
$this->assertEquals('file%link%format', $container->getParameter('templating.helper.code.file_link_format'));
$this->assertEquals('file%link%format', $container->getParameter('debug.file_link_format'));
}
public function testValidationAnnotations()
@@ -331,11 +497,13 @@ abstract class FrameworkExtensionTest extends TestCase
$calls = $container->getDefinition('validator.builder')->getMethodCalls();
$this->assertCount(6, $calls);
$this->assertCount(7, $calls);
$this->assertSame('enableAnnotationMapping', $calls[4][0]);
$this->assertEquals(array(new Reference('annotation_reader')), $calls[4][1]);
$this->assertSame('addMethodMapping', $calls[5][0]);
$this->assertSame(array('loadValidatorMetadata'), $calls[5][1]);
$this->assertSame('setMetadataCache', $calls[6][0]);
$this->assertEquals(array(new Reference('validator.mapping.cache.symfony')), $calls[6][1]);
// no cache this time
}
@@ -344,17 +512,20 @@ abstract class FrameworkExtensionTest extends TestCase
require_once __DIR__.'/Fixtures/TestBundle/TestBundle.php';
$container = $this->createContainerFromFile('validation_annotations', array(
'kernel.bundles' => array('TestBundle' => 'Symfony\Bundle\FrameworkBundle\Tests\TestBundle'),
'kernel.bundles' => array('TestBundle' => 'Symfony\\Bundle\\FrameworkBundle\\Tests\\TestBundle'),
'kernel.bundles_metadata' => array('TestBundle' => array('namespace' => 'Symfony\\Bundle\\FrameworkBundle\\Tests', 'parent' => null, 'path' => __DIR__.'/Fixtures/TestBundle')),
));
$calls = $container->getDefinition('validator.builder')->getMethodCalls();
$this->assertCount(7, $calls);
$this->assertCount(8, $calls);
$this->assertSame('addXmlMappings', $calls[3][0]);
$this->assertSame('addYamlMappings', $calls[4][0]);
$this->assertSame('enableAnnotationMapping', $calls[5][0]);
$this->assertSame('addMethodMapping', $calls[6][0]);
$this->assertSame(array('loadValidatorMetadata'), $calls[6][1]);
$this->assertSame('setMetadataCache', $calls[7][0]);
$this->assertEquals(array(new Reference('validator.mapping.cache.symfony')), $calls[7][1]);
$xmlMappings = $calls[3][1][0];
$this->assertCount(2, $xmlMappings);
@@ -365,11 +536,38 @@ abstract class FrameworkExtensionTest extends TestCase
// Testing symfony/framework-bundle with deps=high
$this->assertStringEndsWith('symfony'.DIRECTORY_SEPARATOR.'form/Resources/config/validation.xml', $xmlMappings[0]);
}
$this->assertStringEndsWith('TestBundle'.DIRECTORY_SEPARATOR.'Resources'.DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'validation.xml', $xmlMappings[1]);
$this->assertStringEndsWith('TestBundle/Resources/config/validation.xml', $xmlMappings[1]);
$yamlMappings = $calls[4][1][0];
$this->assertCount(1, $yamlMappings);
$this->assertStringEndsWith('TestBundle'.DIRECTORY_SEPARATOR.'Resources'.DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'validation.yml', $yamlMappings[0]);
$this->assertStringEndsWith('TestBundle/Resources/config/validation.yml', $yamlMappings[0]);
}
public function testValidationPathsUsingCustomBundlePath()
{
require_once __DIR__.'/Fixtures/CustomPathBundle/src/CustomPathBundle.php';
$container = $this->createContainerFromFile('validation_annotations', array(
'kernel.bundles' => array('CustomPathBundle' => 'Symfony\\Bundle\\FrameworkBundle\\Tests\\CustomPathBundle'),
'kernel.bundles_metadata' => array('TestBundle' => array('namespace' => 'Symfony\\Bundle\\FrameworkBundle\\Tests', 'parent' => null, 'path' => __DIR__.'/Fixtures/CustomPathBundle')),
));
$calls = $container->getDefinition('validator.builder')->getMethodCalls();
$xmlMappings = $calls[3][1][0];
$this->assertCount(2, $xmlMappings);
try {
// Testing symfony/symfony
$this->assertStringEndsWith('Component'.DIRECTORY_SEPARATOR.'Form/Resources/config/validation.xml', $xmlMappings[0]);
} catch (\Exception $e) {
// Testing symfony/framework-bundle with deps=high
$this->assertStringEndsWith('symfony'.DIRECTORY_SEPARATOR.'form/Resources/config/validation.xml', $xmlMappings[0]);
}
$this->assertStringEndsWith('CustomPathBundle/Resources/config/validation.xml', $xmlMappings[1]);
$yamlMappings = $calls[4][1][0];
$this->assertCount(1, $yamlMappings);
$this->assertStringEndsWith('CustomPathBundle/Resources/config/validation.yml', $yamlMappings[0]);
}
public function testValidationNoStaticMethod()
@@ -378,8 +576,10 @@ abstract class FrameworkExtensionTest extends TestCase
$calls = $container->getDefinition('validator.builder')->getMethodCalls();
$this->assertCount(4, $calls);
$this->assertCount(5, $calls);
$this->assertSame('addXmlMappings', $calls[3][0]);
$this->assertSame('setMetadataCache', $calls[4][0]);
$this->assertEquals(array(new Reference('validator.mapping.cache.symfony')), $calls[4][1]);
// no cache, no annotations, no static methods
}
@@ -424,8 +624,66 @@ abstract class FrameworkExtensionTest extends TestCase
$this->assertCount(1, $argument);
$this->assertEquals('Symfony\Component\Serializer\Mapping\Loader\AnnotationLoader', $argument[0]->getClass());
$this->assertEquals(new Reference('serializer.mapping.cache.apc'), $container->getDefinition('serializer.mapping.class_metadata_factory')->getArgument(1));
$this->assertNull($container->getDefinition('serializer.mapping.class_metadata_factory')->getArgument(1));
$this->assertEquals(new Reference('serializer.name_converter.camel_case_to_snake_case'), $container->getDefinition('serializer.normalizer.object')->getArgument(1));
$this->assertEquals(new Reference('property_info', ContainerBuilder::IGNORE_ON_INVALID_REFERENCE), $container->getDefinition('serializer.normalizer.object')->getArgument(3));
}
public function testRegisterSerializerExtractor()
{
$container = $this->createContainerFromFile('full');
$serializerExtractorDefinition = $container->getDefinition('property_info.serializer_extractor');
$this->assertEquals('serializer.mapping.class_metadata_factory', $serializerExtractorDefinition->getArgument(0)->__toString());
$this->assertFalse($serializerExtractorDefinition->isPublic());
$tag = $serializerExtractorDefinition->getTag('property_info.list_extractor');
$this->assertEquals(array('priority' => -999), $tag[0]);
}
public function testDataUriNormalizerRegistered()
{
if (!class_exists('Symfony\Component\Serializer\Normalizer\DataUriNormalizer')) {
$this->markTestSkipped('The DataUriNormalizer has been introduced in the Serializer Component version 3.1.');
}
$container = $this->createContainerFromFile('full');
$definition = $container->getDefinition('serializer.normalizer.data_uri');
$tag = $definition->getTag('serializer.normalizer');
$this->assertEquals(DataUriNormalizer::class, $definition->getClass());
$this->assertEquals(-920, $tag[0]['priority']);
}
public function testDateTimeNormalizerRegistered()
{
if (!class_exists('Symfony\Component\Serializer\Normalizer\DateTimeNormalizer')) {
$this->markTestSkipped('The DateTimeNormalizer has been introduced in the Serializer Component version 3.1.');
}
$container = $this->createContainerFromFile('full');
$definition = $container->getDefinition('serializer.normalizer.datetime');
$tag = $definition->getTag('serializer.normalizer');
$this->assertEquals(DateTimeNormalizer::class, $definition->getClass());
$this->assertEquals(-910, $tag[0]['priority']);
}
public function testJsonSerializableNormalizerRegistered()
{
if (!class_exists('Symfony\Component\Serializer\Normalizer\JsonSerializableNormalizer')) {
$this->markTestSkipped('The JsonSerializableNormalizer has been introduced in the Serializer Component version 3.1.');
}
$container = $this->createContainerFromFile('full');
$definition = $container->getDefinition('serializer.normalizer.json_serializable');
$tag = $definition->getTag('serializer.normalizer');
$this->assertEquals(JsonSerializableNormalizer::class, $definition->getClass());
$this->assertEquals(-900, $tag[0]['priority']);
}
public function testObjectNormalizerRegistered()
@@ -439,6 +697,41 @@ abstract class FrameworkExtensionTest extends TestCase
$this->assertEquals(-1000, $tag[0]['priority']);
}
public function testSerializerCacheActivated()
{
if (!class_exists(CacheClassMetadataFactory::class) || !method_exists(XmlFileLoader::class, 'getMappedClasses') || !method_exists(YamlFileLoader::class, 'getMappedClasses')) {
$this->markTestSkipped('The Serializer default cache warmer has been introduced in the Serializer Component version 3.2.');
}
$container = $this->createContainerFromFile('serializer_enabled');
$this->assertTrue($container->hasDefinition('serializer.mapping.cache_class_metadata_factory'));
$cache = $container->getDefinition('serializer.mapping.cache_class_metadata_factory')->getArgument(1);
$this->assertEquals(new Reference('serializer.mapping.cache.symfony'), $cache);
}
public function testSerializerCacheDisabled()
{
$container = $this->createContainerFromFile('serializer_enabled', array('kernel.debug' => true, 'kernel.container_class' => __CLASS__));
$this->assertFalse($container->hasDefinition('serializer.mapping.cache_class_metadata_factory'));
}
/**
* @group legacy
* @expectedDeprecation The "framework.serializer.cache" option is deprecated %s.
*/
public function testDeprecatedSerializerCacheOption()
{
$container = $this->createContainerFromFile('serializer_legacy_cache', array('kernel.debug' => true, 'kernel.container_class' => __CLASS__));
$this->assertFalse($container->hasDefinition('serializer.mapping.cache_class_metadata_factory'));
$this->assertTrue($container->hasDefinition('serializer.mapping.class_metadata_factory'));
$cache = $container->getDefinition('serializer.mapping.class_metadata_factory')->getArgument(1);
$this->assertEquals(new Reference('foo'), $cache);
}
public function testAssetHelperWhenAssetsAreEnabled()
{
$container = $this->createContainerFromFile('full');
@@ -495,19 +788,60 @@ abstract class FrameworkExtensionTest extends TestCase
$this->assertTrue($container->has('property_info'));
}
public function testCacheDefaultRedisProvider()
{
$container = $this->createContainerFromFile('cache');
$redisUrl = 'redis://localhost';
$providerId = md5($redisUrl);
$this->assertTrue($container->hasDefinition($providerId));
$url = $container->getDefinition($providerId)->getArgument(0);
$this->assertSame($redisUrl, $url);
}
public function testCacheDefaultRedisProviderWithEnvVar()
{
$container = $this->createContainerFromFile('cache_env_var');
$redisUrl = 'redis://paas.com';
$providerId = md5($redisUrl);
$this->assertTrue($container->hasDefinition($providerId));
$url = $container->getDefinition($providerId)->getArgument(0);
$this->assertSame($redisUrl, $url);
}
public function testCachePoolServices()
{
$container = $this->createContainerFromFile('cache');
$this->assertCachePoolServiceDefinitionIsCreated($container, 'cache.foo', 'cache.adapter.apcu', 30);
$this->assertCachePoolServiceDefinitionIsCreated($container, 'cache.bar', 'cache.adapter.doctrine', 5);
$this->assertCachePoolServiceDefinitionIsCreated($container, 'cache.baz', 'cache.adapter.filesystem', 7);
$this->assertCachePoolServiceDefinitionIsCreated($container, 'cache.foobar', 'cache.adapter.psr6', 10);
$this->assertCachePoolServiceDefinitionIsCreated($container, 'cache.def', 'cache.app', 11);
}
protected function createContainer(array $data = array())
{
return new ContainerBuilder(new ParameterBag(array_merge(array(
'kernel.bundles' => array('FrameworkBundle' => 'Symfony\\Bundle\\FrameworkBundle\\FrameworkBundle'),
'kernel.bundles_metadata' => array('FrameworkBundle' => array('namespace' => 'Symfony\\Bundle\\FrameworkBundle', 'path' => __DIR__.'/../..', 'parent' => null)),
'kernel.cache_dir' => __DIR__,
'kernel.debug' => false,
'kernel.environment' => 'test',
'kernel.name' => 'kernel',
'kernel.root_dir' => __DIR__,
'kernel.container_class' => 'testContainer',
), $data)));
}
protected function createContainerFromFile($file, $data = array())
protected function createContainerFromFile($file, $data = array(), $resetCompilerPasses = true)
{
$cacheKey = md5(get_class($this).$file.serialize($data));
if (isset(self::$containerCache[$cacheKey])) {
@@ -517,8 +851,11 @@ abstract class FrameworkExtensionTest extends TestCase
$container->registerExtension(new FrameworkExtension());
$this->loadFromFile($container, $file);
$container->getCompilerPassConfig()->setOptimizationPasses(array());
$container->getCompilerPassConfig()->setRemovingPasses(array());
if ($resetCompilerPasses) {
$container->getCompilerPassConfig()->setOptimizationPasses(array());
$container->getCompilerPassConfig()->setRemovingPasses(array());
}
$container->getCompilerPassConfig()->setBeforeRemovingPasses(array(new AddAnnotationsCachedReaderPass()));
$container->compile();
return self::$containerCache[$cacheKey] = $container;
@@ -554,7 +891,7 @@ abstract class FrameworkExtensionTest extends TestCase
private function assertVersionStrategy(ContainerBuilder $container, Reference $reference, $version, $format)
{
$versionStrategy = $container->getDefinition($reference);
$versionStrategy = $container->getDefinition((string) $reference);
if (null === $version) {
$this->assertEquals('assets.empty_version_strategy', (string) $reference);
} else {
@@ -563,4 +900,50 @@ abstract class FrameworkExtensionTest extends TestCase
$this->assertEquals($format, $versionStrategy->getArgument(1));
}
}
private function assertCachePoolServiceDefinitionIsCreated(ContainerBuilder $container, $id, $adapter, $defaultLifetime)
{
$this->assertTrue($container->has($id), sprintf('Service definition "%s" for cache pool of type "%s" is registered', $id, $adapter));
$poolDefinition = $container->getDefinition($id);
$this->assertInstanceOf(DefinitionDecorator::class, $poolDefinition, sprintf('Cache pool "%s" is based on an abstract cache pool.', $id));
$this->assertTrue($poolDefinition->hasTag('cache.pool'), sprintf('Service definition "%s" is tagged with the "cache.pool" tag.', $id));
$this->assertFalse($poolDefinition->isAbstract(), sprintf('Service definition "%s" is not abstract.', $id));
$tag = $poolDefinition->getTag('cache.pool');
$this->assertTrue(isset($tag[0]['default_lifetime']), 'The default lifetime is stored as an attribute of the "cache.pool" tag.');
$this->assertSame($defaultLifetime, $tag[0]['default_lifetime'], 'The default lifetime is stored as an attribute of the "cache.pool" tag.');
$parentDefinition = $poolDefinition;
do {
$parentId = $parentDefinition->getParent();
$parentDefinition = $container->findDefinition($parentId);
} while ($parentDefinition instanceof DefinitionDecorator);
switch ($adapter) {
case 'cache.adapter.apcu':
$this->assertSame(ApcuAdapter::class, $parentDefinition->getClass());
break;
case 'cache.adapter.doctrine':
$this->assertSame(DoctrineAdapter::class, $parentDefinition->getClass());
break;
case 'cache.app':
if (ChainAdapter::class === $parentDefinition->getClass()) {
break;
}
case 'cache.adapter.filesystem':
$this->assertSame(FilesystemAdapter::class, $parentDefinition->getClass());
break;
case 'cache.adapter.psr6':
$this->assertSame(ProxyAdapter::class, $parentDefinition->getClass());
break;
case 'cache.adapter.redis':
$this->assertSame(RedisAdapter::class, $parentDefinition->getClass());
break;
default:
$this->fail('Unresolved adapter: '.$adapter);
}
}
}
@@ -7,14 +7,12 @@
"lazy": true,
"shared": true,
"abstract": true,
"autowire": false,
"autowiring_types": [],
"file": null,
"factory_class": "Full\\Qualified\\FactoryClass",
"factory_method": "get",
"tags": [
],
"autowire": false,
"autowiring_types": []
"tags": []
}
},
"aliases": {
@@ -4,8 +4,7 @@ Public services
Definitions
-----------
definition_1
~~~~~~~~~~~~
### definition_1
- Class: `Full\Qualified\Class1`
- Public: yes
@@ -21,14 +20,12 @@ definition_1
Aliases
-------
alias_1
~~~~~~~
### alias_1
- Service: `service_1`
- Public: yes
alias_2
~~~~~~~
### alias_2
- Service: `service_2`
- Public: no
@@ -7,14 +7,12 @@
"lazy": true,
"shared": true,
"abstract": true,
"autowire": false,
"autowiring_types": [],
"file": null,
"factory_class": "Full\\Qualified\\FactoryClass",
"factory_method": "get",
"tags": [
],
"autowire": false,
"autowiring_types": []
"tags": []
},
"definition_2": {
"class": "Full\\Qualified\\Class2",
@@ -23,9 +21,14 @@
"lazy": false,
"shared": true,
"abstract": false,
"autowire": false,
"autowiring_types": [],
"file": "\/path\/to\/file",
"factory_service": "factory.service",
"factory_method": "get",
"calls": [
"setMailer"
],
"tags": [
{
"name": "tag1",
@@ -42,13 +45,9 @@
},
{
"name": "tag2",
"parameters": [
]
"parameters": []
}
],
"autowire": false,
"autowiring_types": []
]
}
},
"aliases": {
@@ -4,8 +4,7 @@ Public and private services
Definitions
-----------
definition_1
~~~~~~~~~~~~
### definition_1
- Class: `Full\Qualified\Class1`
- Public: yes
@@ -17,8 +16,7 @@ definition_1
- Factory Class: `Full\Qualified\FactoryClass`
- Factory Method: `get`
definition_2
~~~~~~~~~~~~
### definition_2
- Class: `Full\Qualified\Class2`
- Public: no
@@ -30,6 +28,7 @@ definition_2
- File: `/path/to/file`
- Factory Service: `factory.service`
- Factory Method: `get`
- Call: `setMailer`
- Tag: `tag1`
- Attr1: val1
- Attr2: val2
@@ -41,14 +40,12 @@ definition_2
Aliases
-------
alias_1
~~~~~~~
### alias_1
- Service: `service_1`
- Public: yes
alias_2
~~~~~~~
### alias_2
- Service: `service_2`
- Public: no
@@ -7,6 +7,9 @@
</definition>
<definition id="definition_2" class="Full\Qualified\Class2" public="false" synthetic="true" lazy="false" shared="true" abstract="false" autowired="false" file="/path/to/file">
<factory service="factory.service" method="get"/>
<calls>
<call method="setMailer"/>
</calls>
<tags>
<tag name="tag1">
<parameter name="attr1">val1</parameter>
@@ -7,9 +7,14 @@
"lazy": false,
"shared": true,
"abstract": false,
"autowire": false,
"autowiring_types": [],
"file": "\/path\/to\/file",
"factory_service": "factory.service",
"factory_method": "get",
"calls": [
"setMailer"
],
"tags": [
{
"name": "tag1",
@@ -26,19 +31,11 @@
},
{
"name": "tag2",
"parameters": [
]
"parameters": []
}
],
"autowire": false,
"autowiring_types": []
]
}
},
"aliases": [
],
"services": [
]
"aliases": [],
"services": []
}
@@ -4,8 +4,7 @@ Public and private services with tag `tag1`
Definitions
-----------
definition_2
~~~~~~~~~~~~
### definition_2
- Class: `Full\Qualified\Class2`
- Public: no
@@ -17,6 +16,7 @@ definition_2
- File: `/path/to/file`
- Factory Service: `factory.service`
- Factory Method: `get`
- Call: `setMailer`
- Tag: `tag1`
- Attr1: val1
- Attr2: val2
@@ -2,6 +2,9 @@
<container>
<definition id="definition_2" class="Full\Qualified\Class2" public="false" synthetic="true" lazy="false" shared="true" abstract="false" autowired="false" file="/path/to/file">
<factory service="factory.service" method="get"/>
<calls>
<call method="setMailer"/>
</calls>
<tags>
<tag name="tag1">
<parameter name="attr1">val1</parameter>
@@ -7,11 +7,14 @@
"lazy": false,
"shared": true,
"abstract": false,
"autowire": false,
"autowiring_types": [],
"file": "\/path\/to\/file",
"factory_service": "factory.service",
"factory_method": "get",
"autowire": false,
"autowiring_types": []
"calls": [
"setMailer"
]
}
],
"tag2": [
@@ -22,11 +25,14 @@
"lazy": false,
"shared": true,
"abstract": false,
"autowire": false,
"autowiring_types": [],
"file": "\/path\/to\/file",
"factory_service": "factory.service",
"factory_method": "get",
"autowire": false,
"autowiring_types": []
"calls": [
"setMailer"
]
}
]
}
@@ -4,8 +4,7 @@ Container tags
tag1
----
definition_2
~~~~~~~~~~~~
### definition_2
- Class: `Full\Qualified\Class2`
- Public: no
@@ -17,13 +16,13 @@ definition_2
- File: `/path/to/file`
- Factory Service: `factory.service`
- Factory Method: `get`
- Call: `setMailer`
tag2
----
definition_2
~~~~~~~~~~~~
### definition_2
- Class: `Full\Qualified\Class2`
- Public: no
@@ -35,3 +34,4 @@ definition_2
- File: `/path/to/file`
- Factory Service: `factory.service`
- Factory Method: `get`
- Call: `setMailer`
@@ -3,11 +3,17 @@
<tag name="tag1">
<definition id="definition_2" class="Full\Qualified\Class2" public="false" synthetic="true" lazy="false" shared="true" abstract="false" autowired="false" file="/path/to/file">
<factory service="factory.service" method="get"/>
<calls>
<call method="setMailer"/>
</calls>
</definition>
</tag>
<tag name="tag2">
<definition id="definition_2" class="Full\Qualified\Class2" public="false" synthetic="true" lazy="false" shared="true" abstract="false" autowired="false" file="/path/to/file">
<factory service="factory.service" method="get"/>
<calls>
<call method="setMailer"/>
</calls>
</definition>
</tag>
</container>
@@ -5,12 +5,10 @@
"lazy": true,
"shared": true,
"abstract": true,
"autowire": false,
"autowiring_types": [],
"file": null,
"factory_class": "Full\\Qualified\\FactoryClass",
"factory_method": "get",
"tags": [
],
"autowire": false,
"autowiring_types": []
"tags": []
}
@@ -5,9 +5,14 @@
"lazy": false,
"shared": true,
"abstract": false,
"autowire": false,
"autowiring_types": [],
"file": "\/path\/to\/file",
"factory_service": "factory.service",
"factory_method": "get",
"calls": [
"setMailer"
],
"tags": [
{
"name": "tag1",
@@ -24,11 +29,7 @@
},
{
"name": "tag2",
"parameters": [
]
"parameters": []
}
],
"autowire": false,
"autowiring_types": []
]
}
@@ -8,9 +8,10 @@
- File: `/path/to/file`
- Factory Service: `factory.service`
- Factory Method: `get`
- Call: `setMailer`
- Tag: `tag1`
- Attr1: val1
- Attr2: val2
- Tag: `tag1`
- Attr3: val3
- Tag: `tag2`
- Tag: `tag2`
@@ -4,6 +4,7 @@
Service ID -
Class Full\Qualified\Class2
Tags tag1 (attr1: val1, attr2: val2)tag1 (attr3: val3)tag2
Calls setMailer
Public no
Synthetic yes
Lazy no
@@ -1,6 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<definition class="Full\Qualified\Class2" public="false" synthetic="true" lazy="false" shared="true" abstract="false" autowired="false" file="/path/to/file">
<factory service="factory.service" method="get"/>
<calls>
<call method="setMailer"/>
</calls>
<tags>
<tag name="tag1">
<parameter name="attr1">val1</parameter>
@@ -11,7 +11,7 @@
| Requirements | name: [a-z]+ |
| Class | Symfony\Component\Routing\Route |
| Defaults | name: Joseph |
| Options | compiler_class: Symfony\Component\Routing\RouteCompiler |
| | opt1: val1 |
| | opt2: val2 |
| Options | compiler_class: Symfony\Component\Routing\RouteCompiler |
| | opt1: val1 |
| | opt2: val2 |
+--------------+---------------------------------------------------------+
@@ -6,9 +6,7 @@
"scheme": "http|https",
"method": "PUT|POST",
"class": "Symfony\\Component\\Routing\\Route",
"defaults": [
],
"defaults": [],
"requirements": "NO CUSTOM",
"options": {
"compiler_class": "Symfony\\Component\\Routing\\RouteCompiler",
@@ -11,7 +11,7 @@
| Requirements | NO CUSTOM |
| Class | Symfony\Component\Routing\Route |
| Defaults | NONE |
| Options | compiler_class: Symfony\Component\Routing\RouteCompiler |
| | opt1: val1 |
| | opt2: val2 |
| Options | compiler_class: Symfony\Component\Routing\RouteCompiler |
| | opt1: val1 |
| | opt2: val2 |
+--------------+---------------------------------------------------------+
@@ -27,9 +27,7 @@
"scheme": "http|https",
"method": "PUT|POST",
"class": "Symfony\\Component\\Routing\\Route",
"defaults": [
],
"defaults": [],
"requirements": "NO CUSTOM",
"options": {
"compiler_class": "Symfony\\Component\\Routing\\RouteCompiler",
@@ -1,7 +1,7 @@
This template is used for translation message extraction tests
<?php echo $view['translator']->trans('single-quoted key') ?>
<?php echo $view['translator']->trans('double-quoted key') ?>
<?php echo $view['translator']->trans(<<<EOF
<?php echo $view['translator']->trans(<<<'EOF'
heredoc key
EOF
) ?>
@@ -31,3 +31,19 @@ EOF
10,
array('%count%' => 10)
) ?>
<?php echo $view['translator']->trans('other-domain-test-no-params-short-array', array(), 'not_messages'); ?>
<?php echo $view['translator']->trans('other-domain-test-no-params-long-array', array(), 'not_messages'); ?>
<?php echo $view['translator']->trans('other-domain-test-params-short-array', array('foo' => 'bar'), 'not_messages'); ?>
<?php echo $view['translator']->trans('other-domain-test-params-long-array', array('foo' => 'bar'), 'not_messages'); ?>
<?php echo $view['translator']->transChoice('other-domain-test-trans-choice-short-array-%count%', 10, array('%count%' => 10), 'not_messages'); ?>
<?php echo $view['translator']->transChoice('other-domain-test-trans-choice-long-array-%count%', 10, array('%count%' => 10), 'not_messages'); ?>
<?php echo $view['translator']->trans('typecast', array('a' => (int) '123'), 'not_messages'); ?>
<?php echo $view['translator']->transChoice('msg1', 10 + 1, array(), 'not_messages'); ?>
<?php echo $view['translator']->transChoice('msg2', ceil(4.5), array(), 'not_messages'); ?>
@@ -13,6 +13,7 @@ namespace Symfony\Bundle\FrameworkBundle\Tests\Functional\Bundle\TestBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Bundle\FrameworkBundle\Tests\Functional\Bundle\TestBundle\DependencyInjection\AnnotationReaderPass;
use Symfony\Bundle\FrameworkBundle\Tests\Functional\Bundle\TestBundle\DependencyInjection\Config\CustomConfig;
class TestBundle extends Bundle
@@ -25,5 +26,7 @@ class TestBundle extends Bundle
$extension = $container->getExtension('test');
$extension->setCustomConfig(new CustomConfig());
$container->addCompilerPass(new AnnotationReaderPass());
}
}
@@ -39,6 +39,33 @@ class ConfigDebugCommandTest extends WebTestCase
$this->assertContains('custom: foo', $tester->getDisplay());
}
public function testDumpBundleOption()
{
$tester = $this->createCommandTester();
$ret = $tester->execute(array('name' => 'TestBundle', 'path' => 'custom'));
$this->assertSame(0, $ret, 'Returns 0 in case of success');
$this->assertContains('foo', $tester->getDisplay());
}
public function testParametersValuesAreResolved()
{
$tester = $this->createCommandTester();
$ret = $tester->execute(array('name' => 'framework'));
$this->assertSame(0, $ret, 'Returns 0 in case of success');
$this->assertContains("locale: '%env(LOCALE)%'", $tester->getDisplay());
$this->assertContains('secret: test', $tester->getDisplay());
}
public function testDumpUndefinedBundleOption()
{
$tester = $this->createCommandTester();
$tester->execute(array('name' => 'TestBundle', 'path' => 'foo'));
$this->assertContains('Unable to find configuration for "test.foo"', $tester->getDisplay());
}
/**
* @return CommandTester
*/
@@ -30,7 +30,7 @@ class ProfilerTest extends WebTestCase
$client->enableProfiler();
$crawler = $client->request('GET', '/profiler');
$profile = $client->getProfile();
$this->assertTrue(is_object($profile));
$this->assertInternalType('object', $profile);
$client->request('GET', '/profiler');
$this->assertFalse($client->getProfile());
@@ -134,18 +134,4 @@ class SessionTest extends WebTestCase
array('config.yml', false),
);
}
protected function setUp()
{
parent::setUp();
$this->deleteTmpDir('SessionTest');
}
protected function tearDown()
{
parent::tearDown();
$this->deleteTmpDir('SessionTest');
}
}
@@ -13,7 +13,6 @@ namespace Symfony\Bundle\FrameworkBundle\Tests\Functional;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase as BaseWebTestCase;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpKernel\Kernel;
class WebTestCase extends BaseWebTestCase
{
@@ -23,9 +22,19 @@ class WebTestCase extends BaseWebTestCase
self::assertEquals('http://localhost'.$location, $response->headers->get('Location'));
}
protected function deleteTmpDir($testCase)
public static function setUpBeforeClass()
{
if (!file_exists($dir = sys_get_temp_dir().'/'.Kernel::VERSION.'/'.$testCase)) {
static::deleteTmpDir();
}
public static function tearDownAfterClass()
{
static::deleteTmpDir();
}
protected static function deleteTmpDir()
{
if (!file_exists($dir = sys_get_temp_dir().'/'.static::getVarDir())) {
return;
}
@@ -49,10 +58,16 @@ class WebTestCase extends BaseWebTestCase
}
return new $class(
static::getVarDir(),
$options['test_case'],
isset($options['root_config']) ? $options['root_config'] : 'config.yml',
isset($options['environment']) ? $options['environment'] : 'frameworkbundletest'.strtolower($options['test_case']),
isset($options['environment']) ? $options['environment'] : strtolower(static::getVarDir().$options['test_case']),
isset($options['debug']) ? $options['debug'] : true
);
}
protected static function getVarDir()
{
return substr(strrchr(get_called_class(), '\\'), 1);
}
}
@@ -46,14 +46,16 @@ use Symfony\Component\HttpKernel\Kernel;
*/
class AppKernel extends Kernel
{
private $varDir;
private $testCase;
private $rootConfig;
public function __construct($testCase, $rootConfig, $environment, $debug)
public function __construct($varDir, $testCase, $rootConfig, $environment, $debug)
{
if (!is_dir(__DIR__.'/'.$testCase)) {
throw new \InvalidArgumentException(sprintf('The test case "%s" does not exist.', $testCase));
}
$this->varDir = $varDir;
$this->testCase = $testCase;
$fs = new Filesystem();
@@ -81,12 +83,12 @@ class AppKernel extends Kernel
public function getCacheDir()
{
return sys_get_temp_dir().'/'.Kernel::VERSION.'/'.$this->testCase.'/cache/'.$this->environment;
return sys_get_temp_dir().'/'.$this->varDir.'/'.$this->testCase.'/cache/'.$this->environment;
}
public function getLogDir()
{
return sys_get_temp_dir().'/'.Kernel::VERSION.'/'.$this->testCase.'/logs';
return sys_get_temp_dir().'/'.$this->varDir.'/'.$this->testCase.'/logs';
}
public function registerContainerConfiguration(LoaderInterface $loader)
@@ -96,13 +98,13 @@ class AppKernel extends Kernel
public function serialize()
{
return serialize(array($this->testCase, $this->rootConfig, $this->getEnvironment(), $this->isDebug()));
return serialize(array($this->varDir, $this->testCase, $this->rootConfig, $this->getEnvironment(), $this->isDebug()));
}
public function unserialize($str)
{
$a = unserialize($str);
$this->__construct($a[0], $a[1], $a[2], $a[3]);
$this->__construct($a[0], $a[1], $a[2], $a[3], $a[4]);
}
protected function getKernelParameters()
@@ -1,2 +1,10 @@
imports:
- { resource: ../config/default.yml }
framework:
secret: '%secret%'
default_locale: '%env(LOCALE)%'
parameters:
env(LOCALE): en
secret: test
@@ -11,9 +11,10 @@
namespace Symfony\Bundle\FrameworkBundle\Tests\Kernel;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
class MicroKernelTraitTest extends \PHPUnit_Framework_TestCase
class MicroKernelTraitTest extends TestCase
{
public function test()
{
@@ -2,11 +2,12 @@
namespace Symfony\Bundle\FrameworkBundle\Tests\Routing;
use PHPUnit\Framework\TestCase;
use Symfony\Bundle\FrameworkBundle\Controller\ControllerNameParser;
use Symfony\Bundle\FrameworkBundle\Routing\DelegatingLoader;
use Symfony\Component\Config\Loader\LoaderResolver;
class DelegatingLoaderTest extends \PHPUnit_Framework_TestCase
class DelegatingLoaderTest extends TestCase
{
public function testConstructorApi()
{
@@ -11,12 +11,13 @@
namespace Symfony\Bundle\FrameworkBundle\Tests\Routing;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Bundle\FrameworkBundle\Routing\RedirectableUrlMatcher;
use Symfony\Component\Routing\RequestContext;
class RedirectableUrlMatcherTest extends \PHPUnit_Framework_TestCase
class RedirectableUrlMatcherTest extends TestCase
{
public function testRedirectWhenNoSlash()
{
@@ -24,6 +25,10 @@ class RedirectableUrlMatcherTest extends \PHPUnit_Framework_TestCase
$coll->add('foo', new Route('/foo/'));
$matcher = new RedirectableUrlMatcher($coll, $context = new RequestContext());
$parameters = $matcher->match('/foo');
if ('foo' === $parameters['_route']) {
$parameters['_route'] = null; // FC with behavior on 3.4
}
$this->assertEquals(array(
'_controller' => 'Symfony\Bundle\FrameworkBundle\Controller\RedirectController::urlRedirectAction',
@@ -34,7 +39,7 @@ class RedirectableUrlMatcherTest extends \PHPUnit_Framework_TestCase
'httpsPort' => $context->getHttpsPort(),
'_route' => null,
),
$matcher->match('/foo')
$parameters
);
}
@@ -11,11 +11,12 @@
namespace Symfony\Bundle\FrameworkBundle\Tests\Routing;
use PHPUnit\Framework\TestCase;
use Symfony\Bundle\FrameworkBundle\Routing\Router;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
class RouterTest extends \PHPUnit_Framework_TestCase
class RouterTest extends TestCase
{
public function testGenerateWithServiceParam()
{
@@ -131,6 +132,20 @@ class RouterTest extends \PHPUnit_Framework_TestCase
);
}
/**
* @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException
* @expectedExceptionMessage Using "%env(FOO)%" is not allowed in routing configuration.
*/
public function testEnvPlaceholders()
{
$routes = new RouteCollection();
$routes->add('foo', new Route('/%env(FOO)%'));
$router = new Router($this->getServiceContainer($routes), 'foo');
$router->getRouteCollection();
}
public function testHostPlaceholders()
{
$routes = new RouteCollection();
@@ -214,7 +229,7 @@ class RouterTest extends \PHPUnit_Framework_TestCase
*/
private function getServiceContainer(RouteCollection $routes)
{
$loader = $this->getMock('Symfony\Component\Config\Loader\LoaderInterface');
$loader = $this->getMockBuilder('Symfony\Component\Config\Loader\LoaderInterface')->getMock();
$loader
->expects($this->any())
@@ -222,7 +237,7 @@ class RouterTest extends \PHPUnit_Framework_TestCase
->will($this->returnValue($routes))
;
$sc = $this->getMock('Symfony\\Component\\DependencyInjection\\Container', array('get'));
$sc = $this->getMockBuilder('Symfony\\Component\\DependencyInjection\\Container')->setMethods(array('get'))->getMock();
$sc
->expects($this->once())
@@ -11,9 +11,11 @@
namespace Symfony\Bundle\FrameworkBundle\Tests\Templating;
use PHPUnit\Framework\TestCase;
use Symfony\Bundle\FrameworkBundle\Templating\DelegatingEngine;
use Symfony\Component\HttpFoundation\Response;
class DelegatingEngineTest extends \PHPUnit_Framework_TestCase
class DelegatingEngineTest extends TestCase
{
public function testSupportsRetrievesEngineFromTheContainer()
{
@@ -60,7 +62,7 @@ class DelegatingEngineTest extends \PHPUnit_Framework_TestCase
public function testRenderResponseWithFrameworkEngine()
{
$response = $this->getMock('Symfony\Component\HttpFoundation\Response');
$response = new Response();
$engine = $this->getFrameworkEngineMock('template.php', true);
$engine->expects($this->once())
->method('renderResponse')
@@ -84,7 +86,7 @@ class DelegatingEngineTest extends \PHPUnit_Framework_TestCase
private function getEngineMock($template, $supports)
{
$engine = $this->getMock('Symfony\Component\Templating\EngineInterface');
$engine = $this->getMockBuilder('Symfony\Component\Templating\EngineInterface')->getMock();
$engine->expects($this->once())
->method('supports')
@@ -96,7 +98,7 @@ class DelegatingEngineTest extends \PHPUnit_Framework_TestCase
private function getFrameworkEngineMock($template, $supports)
{
$engine = $this->getMock('Symfony\Bundle\FrameworkBundle\Templating\EngineInterface');
$engine = $this->getMockBuilder('Symfony\Bundle\FrameworkBundle\Templating\EngineInterface')->getMock();
$engine->expects($this->once())
->method('supports')
@@ -108,7 +110,7 @@ class DelegatingEngineTest extends \PHPUnit_Framework_TestCase
private function getContainerMock($services)
{
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock();
$i = 0;
foreach ($services as $id => $service) {
@@ -33,7 +33,7 @@ class GlobalVariablesTest extends TestCase
public function testGetUserNoToken()
{
$tokenStorage = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface');
$tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock();
$this->container->set('security.token_storage', $tokenStorage);
$this->assertNull($this->globals->getUser());
}
@@ -43,8 +43,8 @@ class GlobalVariablesTest extends TestCase
*/
public function testGetUser($user, $expectedUser)
{
$tokenStorage = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface');
$token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
$tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock();
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
$this->container->set('security.token_storage', $tokenStorage);
@@ -63,9 +63,9 @@ class GlobalVariablesTest extends TestCase
public function getUserProvider()
{
$user = $this->getMock('Symfony\Component\Security\Core\User\UserInterface');
$user = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
$std = new \stdClass();
$token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
return array(
array($user, $user),
@@ -11,12 +11,13 @@
namespace Symfony\Bundle\FrameworkBundle\Tests\Templating\Helper;
use PHPUnit\Framework\TestCase;
use Symfony\Bundle\FrameworkBundle\Templating\Helper\AssetsHelper;
use Symfony\Component\Asset\Package;
use Symfony\Component\Asset\Packages;
use Symfony\Component\Asset\VersionStrategy\StaticVersionStrategy;
class AssetsHelperTest extends \PHPUnit_Framework_TestCase
class AssetsHelperTest extends TestCase
{
private $helper;
@@ -11,11 +11,12 @@
namespace Symfony\Bundle\FrameworkBundle\Tests\Templating\Helper;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Bundle\FrameworkBundle\Templating\Helper\RequestHelper;
class RequestHelperTest extends \PHPUnit_Framework_TestCase
class RequestHelperTest extends TestCase
{
protected $requestStack;
@@ -11,13 +11,14 @@
namespace Symfony\Bundle\FrameworkBundle\Tests\Templating\Helper;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage;
use Symfony\Bundle\FrameworkBundle\Templating\Helper\SessionHelper;
class SessionHelperTest extends \PHPUnit_Framework_TestCase
class SessionHelperTest extends TestCase
{
protected $requestStack;
@@ -11,13 +11,14 @@
namespace Symfony\Bundle\FrameworkBundle\Tests\Templating\Helper;
use PHPUnit\Framework\TestCase;
use Symfony\Bundle\FrameworkBundle\Templating\Helper\StopwatchHelper;
class StopwatchHelperTest extends \PHPUnit_Framework_TestCase
class StopwatchHelperTest extends TestCase
{
public function testDevEnvironment()
{
$stopwatch = $this->getMock('Symfony\Component\Stopwatch\Stopwatch');
$stopwatch = $this->getMockBuilder('Symfony\Component\Stopwatch\Stopwatch')->getMock();
$stopwatch->expects($this->once())
->method('start')
->with('foo');
@@ -29,11 +30,10 @@ class StopwatchHelperTest extends \PHPUnit_Framework_TestCase
public function testProdEnvironment()
{
$helper = new StopwatchHelper(null);
$helper->start('foo');
try {
$helper->start('foo');
} catch (\BadMethodCallException $e) {
$this->fail('Assumed stopwatch is not called when not provided');
}
// add a dummy assertion here to satisfy PHPUnit, the only thing we want to test is that the code above
// can be executed without throwing any exceptions
$this->addToAssertionCount(1);
}
}
@@ -33,6 +33,20 @@ class TemplateLocatorTest extends TestCase
$locator = new TemplateLocator($fileLocator);
$this->assertEquals('/path/to/template', $locator->locate($template));
// Assert cache is used as $fileLocator->locate should be called only once
$this->assertEquals('/path/to/template', $locator->locate($template));
}
public function testLocateATemplateFromCacheDir()
{
$template = new TemplateReference('bundle', 'controller', 'name', 'format', 'engine');
$fileLocator = $this->getFileLocator();
$locator = new TemplateLocator($fileLocator, __DIR__.'/../../Fixtures');
$this->assertEquals(realpath(__DIR__.'/../../Fixtures/Resources/views/this.is.a.template.format.engine'), $locator->locate($template));
}
public function testThrowsExceptionWhenTemplateNotFound()
@@ -22,7 +22,7 @@ class TemplateNameParserTest extends TestCase
protected function setUp()
{
$kernel = $this->getMock('Symfony\Component\HttpKernel\KernelInterface');
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\KernelInterface')->getMock();
$kernel
->expects($this->any())
->method('getBundle')
@@ -68,11 +68,6 @@ class TemplateNameParserTest extends TestCase
array('FooBundle:Post:foo.bar.index.html.php', 'FooBundle:Post:foo.bar.index.html.php', '@FooBundle/Resources/views/Post/foo.bar.index.html.php', new TemplateReference('FooBundle', 'Post', 'foo.bar.index', 'html', 'php')),
array('@FooBundle/Resources/views/layout.html.twig', '@FooBundle/Resources/views/layout.html.twig', '@FooBundle/Resources/views/layout.html.twig', new BaseTemplateReference('@FooBundle/Resources/views/layout.html.twig', 'twig')),
array('@FooBundle/Foo/layout.html.twig', '@FooBundle/Foo/layout.html.twig', '@FooBundle/Foo/layout.html.twig', new BaseTemplateReference('@FooBundle/Foo/layout.html.twig', 'twig')),
array('/path/to/section/index.html.php', '/path/to/section/index.html.php', '/path/to/section/index.html.php', new BaseTemplateReference('/path/to/section/index.html.php', 'php')),
array('C:\\path\\to\\section\\name.html.php', 'C:path/to/section/name.html.php', 'C:path/to/section/name.html.php', new BaseTemplateReference('C:path/to/section/name.html.php', 'php')),
array('C:\\path\\to\\section\\name:foo.html.php', 'C:path/to/section/name:foo.html.php', 'C:path/to/section/name:foo.html.php', new BaseTemplateReference('C:path/to/section/name:foo.html.php', 'php')),
array('\\path\\to\\section\\name.html.php', '/path/to/section/name.html.php', '/path/to/section/name.html.php', new BaseTemplateReference('/path/to/section/name.html.php', 'php')),
array('/path/to/section/name.php', '/path/to/section/name.php', '/path/to/section/name.php', new BaseTemplateReference('/path/to/section/name.php', 'php')),
array('name.twig', 'name.twig', 'name.twig', new BaseTemplateReference('name.twig', 'twig')),
array('name', 'name', 'name', new BaseTemplateReference('name')),
array('default/index.html.php', '::default/index.html.php', 'views/default/index.html.php', new TemplateReference(null, null, 'default/index', 'html', 'php')),
@@ -86,4 +81,29 @@ class TemplateNameParserTest extends TestCase
{
$this->parser->parse('BarBundle:Post:index.html.php');
}
/**
* @group legacy
* @dataProvider provideAbsolutePaths
* @expectedDeprecation Absolute template path support is deprecated since Symfony 3.1 and will be removed in 4.0.
*/
public function testAbsolutePathsAreDeprecated($name, $logicalName, $path, $ref)
{
$template = $this->parser->parse($name);
$this->assertSame($ref->getLogicalName(), $template->getLogicalName());
$this->assertSame($logicalName, $template->getLogicalName());
$this->assertSame($path, $template->getPath());
}
public function provideAbsolutePaths()
{
return array(
array('/path/to/section/index.html.php', '/path/to/section/index.html.php', '/path/to/section/index.html.php', new BaseTemplateReference('/path/to/section/index.html.php', 'php')),
array('C:\\path\\to\\section\\name.html.php', 'C:path/to/section/name.html.php', 'C:path/to/section/name.html.php', new BaseTemplateReference('C:path/to/section/name.html.php', 'php')),
array('C:\\path\\to\\section\\name:foo.html.php', 'C:path/to/section/name:foo.html.php', 'C:path/to/section/name:foo.html.php', new BaseTemplateReference('C:path/to/section/name:foo.html.php', 'php')),
array('\\path\\to\\section\\name.html.php', '/path/to/section/name.html.php', '/path/to/section/name.html.php', new BaseTemplateReference('/path/to/section/name.html.php', 'php')),
array('/path/to/section/name.php', '/path/to/section/name.php', '/path/to/section/name.php', new BaseTemplateReference('/path/to/section/name.php', 'php')),
);
}
}
@@ -19,21 +19,9 @@ class TemplateTest extends TestCase
/**
* @dataProvider getTemplateToPathProvider
*/
public function testGetPathForTemplatesInABundle($template, $path)
public function testGetPathForTemplate($template, $path)
{
if ($template->get('bundle')) {
$this->assertEquals($template->getPath(), $path);
}
}
/**
* @dataProvider getTemplateToPathProvider
*/
public function testGetPathForTemplatesOutOfABundle($template, $path)
{
if (!$template->get('bundle')) {
$this->assertEquals($template->getPath(), $path);
}
$this->assertSame($template->getPath(), $path);
}
public function getTemplateToPathProvider()
@@ -44,7 +44,7 @@ class TimedPhpEngineTest extends TestCase
*/
private function getContainer()
{
return $this->getMock('Symfony\Component\DependencyInjection\Container');
return $this->getMockBuilder('Symfony\Component\DependencyInjection\Container')->getMock();
}
/**
@@ -52,8 +52,8 @@ class TimedPhpEngineTest extends TestCase
*/
private function getTemplateNameParser()
{
$templateReference = $this->getMock('Symfony\Component\Templating\TemplateReferenceInterface');
$templateNameParser = $this->getMock('Symfony\Component\Templating\TemplateNameParserInterface');
$templateReference = $this->getMockBuilder('Symfony\Component\Templating\TemplateReferenceInterface')->getMock();
$templateNameParser = $this->getMockBuilder('Symfony\Component\Templating\TemplateNameParserInterface')->getMock();
$templateNameParser->expects($this->any())
->method('parse')
->will($this->returnValue($templateReference));
@@ -111,6 +111,6 @@ class TimedPhpEngineTest extends TestCase
*/
private function getStopwatch()
{
return $this->getMock('Symfony\Component\Stopwatch\Stopwatch');
return $this->getMockBuilder('Symfony\Component\Stopwatch\Stopwatch')->getMock();
}
}
+3 -1
View File
@@ -11,6 +11,8 @@
namespace Symfony\Bundle\FrameworkBundle\Tests;
class TestCase extends \PHPUnit_Framework_TestCase
use PHPUnit\Framework\TestCase as PHPUnitTestCase;
class TestCase extends PHPUnitTestCase
{
}
@@ -39,18 +39,31 @@ EOF;
nowdoc key with whitespace and nonescaped \$\n sequences
EOF;
// Assert
$expectedCatalogue = array('messages' => array(
'single-quoted key' => 'prefixsingle-quoted key',
'double-quoted key' => 'prefixdouble-quoted key',
'heredoc key' => 'prefixheredoc key',
'nowdoc key' => 'prefixnowdoc key',
"double-quoted key with whitespace and escaped \$\n\" sequences" => "prefixdouble-quoted key with whitespace and escaped \$\n\" sequences",
'single-quoted key with whitespace and nonescaped \$\n\' sequences' => 'prefixsingle-quoted key with whitespace and nonescaped \$\n\' sequences',
'single-quoted key with "quote mark at the end"' => 'prefixsingle-quoted key with "quote mark at the end"',
$expectedHeredoc => 'prefix'.$expectedHeredoc,
$expectedNowdoc => 'prefix'.$expectedNowdoc,
'{0} There is no apples|{1} There is one apple|]1,Inf[ There are %count% apples' => 'prefix{0} There is no apples|{1} There is one apple|]1,Inf[ There are %count% apples',
));
$expectedCatalogue = array(
'messages' => array(
'single-quoted key' => 'prefixsingle-quoted key',
'double-quoted key' => 'prefixdouble-quoted key',
'heredoc key' => 'prefixheredoc key',
'nowdoc key' => 'prefixnowdoc key',
"double-quoted key with whitespace and escaped \$\n\" sequences" => "prefixdouble-quoted key with whitespace and escaped \$\n\" sequences",
'single-quoted key with whitespace and nonescaped \$\n\' sequences' => 'prefixsingle-quoted key with whitespace and nonescaped \$\n\' sequences',
'single-quoted key with "quote mark at the end"' => 'prefixsingle-quoted key with "quote mark at the end"',
$expectedHeredoc => 'prefix'.$expectedHeredoc,
$expectedNowdoc => 'prefix'.$expectedNowdoc,
'{0} There is no apples|{1} There is one apple|]1,Inf[ There are %count% apples' => 'prefix{0} There is no apples|{1} There is one apple|]1,Inf[ There are %count% apples',
),
'not_messages' => array(
'other-domain-test-no-params-short-array' => 'prefixother-domain-test-no-params-short-array',
'other-domain-test-no-params-long-array' => 'prefixother-domain-test-no-params-long-array',
'other-domain-test-params-short-array' => 'prefixother-domain-test-params-short-array',
'other-domain-test-params-long-array' => 'prefixother-domain-test-params-long-array',
'other-domain-test-trans-choice-short-array-%count%' => 'prefixother-domain-test-trans-choice-short-array-%count%',
'other-domain-test-trans-choice-long-array-%count%' => 'prefixother-domain-test-trans-choice-long-array-%count%',
'typecast' => 'prefixtypecast',
'msg1' => 'prefixmsg1',
'msg2' => 'prefixmsg2',
),
);
$actualCatalogue = $catalogue->all();
$this->assertEquals($expectedCatalogue, $actualCatalogue);
@@ -11,12 +11,13 @@
namespace Symfony\Bundle\FrameworkBundle\Tests\Translation;
use PHPUnit\Framework\TestCase;
use Symfony\Bundle\FrameworkBundle\Translation\Translator;
use Symfony\Component\Translation\MessageCatalogue;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Translation\MessageSelector;
class TranslatorTest extends \PHPUnit_Framework_TestCase
class TranslatorTest extends TestCase
{
protected $tmpDir;
@@ -76,7 +77,7 @@ class TranslatorTest extends \PHPUnit_Framework_TestCase
$this->assertEquals('foobarbax (sr@latin)', $translator->trans('foobarbax'));
// do it another time as the cache is primed now
$loader = $this->getMock('Symfony\Component\Translation\Loader\LoaderInterface');
$loader = $this->getMockBuilder('Symfony\Component\Translation\Loader\LoaderInterface')->getMock();
$loader->expects($this->never())->method('load');
$translator = $this->getTranslator($loader, array('cache_dir' => $this->tmpDir));
@@ -99,7 +100,7 @@ class TranslatorTest extends \PHPUnit_Framework_TestCase
*/
public function testTransWithCachingWithInvalidLocale()
{
$loader = $this->getMock('Symfony\Component\Translation\Loader\LoaderInterface');
$loader = $this->getMockBuilder('Symfony\Component\Translation\Loader\LoaderInterface')->getMock();
$translator = $this->getTranslator($loader, array('cache_dir' => $this->tmpDir), 'loader', '\Symfony\Bundle\FrameworkBundle\Tests\Translation\TranslatorWithInvalidLocale');
$translator->trans('foo');
@@ -122,7 +123,7 @@ class TranslatorTest extends \PHPUnit_Framework_TestCase
public function testGetDefaultLocale()
{
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock();
$container
->expects($this->once())
->method('getParameter')
@@ -135,6 +136,62 @@ class TranslatorTest extends \PHPUnit_Framework_TestCase
$this->assertSame('en', $translator->getLocale());
}
/**
* @expectedException \Symfony\Component\Translation\Exception\InvalidArgumentException
* @expectedExceptionMessage The Translator does not support the following options: 'foo'
*/
public function testInvalidOptions()
{
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock();
(new Translator($container, new MessageSelector(), [], ['foo' => 'bar']));
}
/** @dataProvider getDebugModeAndCacheDirCombinations */
public function testResourceFilesOptionLoadsBeforeOtherAddedResources($debug, $enableCache)
{
$someCatalogue = $this->getCatalogue('some_locale', array());
$loader = $this->getMockBuilder('Symfony\Component\Translation\Loader\LoaderInterface')->getMock();
$loader->expects($this->at(0))
->method('load')
/* The "messages.some_locale.loader" is passed via the resource_file option and shall be loaded first */
->with('messages.some_locale.loader', 'some_locale', 'messages')
->willReturn($someCatalogue);
$loader->expects($this->at(1))
->method('load')
/* This resource is added by an addResource() call and shall be loaded after the resource_files */
->with('second_resource.some_locale.loader', 'some_locale', 'messages')
->willReturn($someCatalogue);
$options = array(
'resource_files' => array('some_locale' => array('messages.some_locale.loader')),
'debug' => $debug,
);
if ($enableCache) {
$options['cache_dir'] = $this->tmpDir;
}
/** @var Translator $translator */
$translator = $this->createTranslator($loader, $options);
$translator->addResource('loader', 'second_resource.some_locale.loader', 'some_locale', 'messages');
$translator->trans('some_message', array(), null, 'some_locale');
}
public function getDebugModeAndCacheDirCombinations()
{
return array(
array(false, false),
array(true, false),
array(false, true),
array(true, true),
);
}
protected function getCatalogue($locale, $messages, $resources = array())
{
$catalogue = new MessageCatalogue($locale);
@@ -150,7 +207,7 @@ class TranslatorTest extends \PHPUnit_Framework_TestCase
protected function getLoader()
{
$loader = $this->getMock('Symfony\Component\Translation\Loader\LoaderInterface');
$loader = $this->getMockBuilder('Symfony\Component\Translation\Loader\LoaderInterface')->getMock();
$loader
->expects($this->at(0))
->method('load')
@@ -208,7 +265,7 @@ class TranslatorTest extends \PHPUnit_Framework_TestCase
protected function getContainer($loader)
{
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock();
$container
->expects($this->any())
->method('get')
@@ -249,7 +306,7 @@ class TranslatorTest extends \PHPUnit_Framework_TestCase
$translator->setFallbackLocales(array('fr'));
$translator->warmup($this->tmpDir);
$loader = $this->getMock('Symfony\Component\Translation\Loader\LoaderInterface');
$loader = $this->getMockBuilder('Symfony\Component\Translation\Loader\LoaderInterface')->getMock();
$loader
->expects($this->never())
->method('load');
@@ -11,17 +11,18 @@
namespace Symfony\Bundle\FrameworkBundle\Tests\Validator;
use PHPUnit\Framework\TestCase;
use Symfony\Bundle\FrameworkBundle\Validator\ConstraintValidatorFactory;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\Validator\Constraints\Blank as BlankConstraint;
class ConstraintValidatorFactoryTest extends \PHPUnit_Framework_TestCase
class ConstraintValidatorFactoryTest extends TestCase
{
public function testGetInstanceCreatesValidator()
{
$class = get_class($this->getMockForAbstractClass('Symfony\\Component\\Validator\\ConstraintValidator'));
$constraint = $this->getMock('Symfony\\Component\\Validator\\Constraint');
$constraint = $this->getMockBuilder('Symfony\\Component\\Validator\\Constraint')->getMock();
$constraint
->expects($this->once())
->method('validatedBy')
@@ -46,14 +47,14 @@ class ConstraintValidatorFactoryTest extends \PHPUnit_Framework_TestCase
$validator = $this->getMockForAbstractClass('Symfony\\Component\\Validator\\ConstraintValidator');
// mock ContainerBuilder b/c it implements TaggedContainerInterface
$container = $this->getMock('Symfony\\Component\\DependencyInjection\\ContainerBuilder', array('get'));
$container = $this->getMockBuilder('Symfony\\Component\\DependencyInjection\\ContainerBuilder')->setMethods(array('get'))->getMock();
$container
->expects($this->once())
->method('get')
->with($service)
->will($this->returnValue($validator));
$constraint = $this->getMock('Symfony\\Component\\Validator\\Constraint');
$constraint = $this->getMockBuilder('Symfony\\Component\\Validator\\Constraint')->getMock();
$constraint
->expects($this->once())
->method('validatedBy')
@@ -62,4 +63,19 @@ class ConstraintValidatorFactoryTest extends \PHPUnit_Framework_TestCase
$factory = new ConstraintValidatorFactory($container, array('validator_constraint_alias' => 'validator_constraint_service'));
$this->assertSame($validator, $factory->getInstance($constraint));
}
/**
* @expectedException \Symfony\Component\Validator\Exception\ValidatorException
*/
public function testGetInstanceInvalidValidatorClass()
{
$constraint = $this->getMockBuilder('Symfony\\Component\\Validator\\Constraint')->getMock();
$constraint
->expects($this->once())
->method('validatedBy')
->will($this->returnValue('Fully\\Qualified\\ConstraintValidator\\Class\\Name'));
$factory = new ConstraintValidatorFactory(new Container());
$factory->getInstance($constraint);
}
}