N°2651 Remove lib test files from index

This commit is contained in:
Pierre Goiffon
2019-12-20 11:55:55 +01:00
parent 4766ca3fd0
commit c75e6960a7
1896 changed files with 5 additions and 134443 deletions

View File

@@ -1,63 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Tests\Controller;
use Psr\Container\ContainerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
class AbstractControllerTest extends ControllerTraitTest
{
protected function createController()
{
return new TestAbstractController();
}
}
class TestAbstractController extends AbstractController
{
use TestControllerTrait;
private $throwOnUnexpectedService;
public function __construct($throwOnUnexpectedService = true)
{
$this->throwOnUnexpectedService = $throwOnUnexpectedService;
}
public function setContainer(ContainerInterface $container)
{
if (!$this->throwOnUnexpectedService) {
return parent::setContainer($container);
}
$expected = self::getSubscribedServices();
foreach ($container->getServiceIds() as $id) {
if ('service_container' === $id) {
continue;
}
if (!isset($expected[$id])) {
throw new \UnexpectedValueException(sprintf('Service "%s" is not expected, as declared by %s::getSubscribedServices()', $id, AbstractController::class));
}
$type = substr($expected[$id], 1);
if (!$container->get($id) instanceof $type) {
throw new \UnexpectedValueException(sprintf('Service "%s" is expected to be an instance of "%s", as declared by %s::getSubscribedServices()', $id, $type, AbstractController::class));
}
}
return parent::setContainer($container);
}
public function fooAction()
{
}
}

View File

@@ -1,192 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Tests\Controller;
use Composer\Autoload\ClassLoader;
use Symfony\Bundle\FrameworkBundle\Controller\ControllerNameParser;
use Symfony\Bundle\FrameworkBundle\Tests\TestCase;
use Symfony\Component\HttpKernel\Kernel;
class ControllerNameParserTest extends TestCase
{
protected $loader;
protected function setUp()
{
$this->loader = new ClassLoader();
$this->loader->add('TestBundle', __DIR__.'/../Fixtures');
$this->loader->add('TestApplication', __DIR__.'/../Fixtures');
$this->loader->register();
}
protected function tearDown()
{
$this->loader->unregister();
$this->loader = null;
}
public function testParse()
{
$parser = $this->createParser();
$this->assertEquals('TestBundle\FooBundle\Controller\DefaultController::indexAction', $parser->parse('FooBundle:Default:index'), '->parse() converts a short a:b:c notation string to a class::method string');
$this->assertEquals('TestBundle\FooBundle\Controller\Sub\DefaultController::indexAction', $parser->parse('FooBundle:Sub\Default:index'), '->parse() converts a short a:b:c notation string to a class::method string');
$this->assertEquals('TestBundle\Fabpot\FooBundle\Controller\DefaultController::indexAction', $parser->parse('SensioFooBundle:Default:index'), '->parse() converts a short a:b:c notation string to a class::method string');
$this->assertEquals('TestBundle\Sensio\Cms\FooBundle\Controller\DefaultController::indexAction', $parser->parse('SensioCmsFooBundle:Default:index'), '->parse() converts a short a:b:c notation string to a class::method string');
$this->assertEquals('TestBundle\FooBundle\Controller\Test\DefaultController::indexAction', $parser->parse('FooBundle:Test\\Default:index'), '->parse() converts a short a:b:c notation string to a class::method string');
$this->assertEquals('TestBundle\FooBundle\Controller\Test\DefaultController::indexAction', $parser->parse('FooBundle:Test/Default:index'), '->parse() converts a short a:b:c notation string to a class::method string');
try {
$parser->parse('foo:');
$this->fail('->parse() throws an \InvalidArgumentException if the controller is not an a:b:c string');
} catch (\Exception $e) {
$this->assertInstanceOf('\InvalidArgumentException', $e, '->parse() throws an \InvalidArgumentException if the controller is not an a:b:c string');
}
}
public function testBuild()
{
$parser = $this->createParser();
$this->assertEquals('FoooooBundle:Default:index', $parser->build('TestBundle\FooBundle\Controller\DefaultController::indexAction'), '->parse() converts a class::method string to a short a:b:c notation string');
$this->assertEquals('FoooooBundle:Sub\Default:index', $parser->build('TestBundle\FooBundle\Controller\Sub\DefaultController::indexAction'), '->parse() converts a class::method string to a short a:b:c notation string');
try {
$parser->build('TestBundle\FooBundle\Controller\DefaultController::index');
$this->fail('->parse() throws an \InvalidArgumentException if the controller is not an aController::cAction string');
} catch (\Exception $e) {
$this->assertInstanceOf('\InvalidArgumentException', $e, '->parse() throws an \InvalidArgumentException if the controller is not an aController::cAction string');
}
try {
$parser->build('TestBundle\FooBundle\Controller\Default::indexAction');
$this->fail('->parse() throws an \InvalidArgumentException if the controller is not an aController::cAction string');
} catch (\Exception $e) {
$this->assertInstanceOf('\InvalidArgumentException', $e, '->parse() throws an \InvalidArgumentException if the controller is not an aController::cAction string');
}
try {
$parser->build('Foo\Controller\DefaultController::indexAction');
$this->fail('->parse() throws an \InvalidArgumentException if the controller is not an aController::cAction string');
} catch (\Exception $e) {
$this->assertInstanceOf('\InvalidArgumentException', $e, '->parse() throws an \InvalidArgumentException if the controller is not an aController::cAction string');
}
}
/**
* @dataProvider getMissingControllersTest
*/
public function testMissingControllers($name)
{
$parser = $this->createParser();
try {
$parser->parse($name);
$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');
}
}
public function getMissingControllersTest()
{
// a normal bundle
$bundles = [
['FooBundle:Fake:index'],
];
// a bundle with children
if (Kernel::VERSION_ID < 40000) {
$bundles[] = ['SensioFooBundle:Fake:index'];
}
return $bundles;
}
/**
* @dataProvider getInvalidBundleNameTests
*/
public function testInvalidBundleName($bundleName, $suggestedBundleName)
{
$parser = $this->createParser();
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');
if (false === $suggestedBundleName) {
// make sure we don't have a suggestion
$this->assertStringNotContainsString('Did you mean', $e->getMessage());
} else {
$this->assertStringContainsString(sprintf('Did you mean "%s"', $suggestedBundleName), $e->getMessage());
}
}
}
public function getInvalidBundleNameTests()
{
return [
'Alternative will be found using levenshtein' => ['FoodBundle:Default:index', 'FooBundle:Default:index'],
'Alternative will be found using partial match' => ['FabpotFooBund:Default:index', 'FabpotFooBundle:Default:index'],
'Bundle does not exist at all' => ['CrazyBundle:Default:index', false],
];
}
private function createParser()
{
$bundles = [
'SensioFooBundle' => [$this->getBundle('TestBundle\Fabpot\FooBundle', 'FabpotFooBundle'), $this->getBundle('TestBundle\Sensio\FooBundle', 'SensioFooBundle')],
'SensioCmsFooBundle' => [$this->getBundle('TestBundle\Sensio\Cms\FooBundle', 'SensioCmsFooBundle')],
'FooBundle' => [$this->getBundle('TestBundle\FooBundle', 'FooBundle')],
'FabpotFooBundle' => [$this->getBundle('TestBundle\Fabpot\FooBundle', 'FabpotFooBundle'), $this->getBundle('TestBundle\Sensio\FooBundle', 'SensioFooBundle')],
];
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\KernelInterface')->getMock();
$kernel
->expects($this->any())
->method('getBundle')
->willReturnCallback(function ($bundle) use ($bundles) {
if (!isset($bundles[$bundle])) {
throw new \InvalidArgumentException(sprintf('Invalid bundle name "%s"', $bundle));
}
return $bundles[$bundle];
})
;
$bundles = [
'SensioFooBundle' => $this->getBundle('TestBundle\Fabpot\FooBundle', 'FabpotFooBundle'),
'SensioCmsFooBundle' => $this->getBundle('TestBundle\Sensio\Cms\FooBundle', 'SensioCmsFooBundle'),
'FoooooBundle' => $this->getBundle('TestBundle\FooBundle', 'FoooooBundle'),
'FooBundle' => $this->getBundle('TestBundle\FooBundle', 'FooBundle'),
'FabpotFooBundle' => $this->getBundle('TestBundle\Fabpot\FooBundle', 'FabpotFooBundle'),
];
$kernel
->expects($this->any())
->method('getBundles')
->willReturn($bundles)
;
return new ControllerNameParser($kernel);
}
private function getBundle($namespace, $name)
{
$bundle = $this->getMockBuilder('Symfony\Component\HttpKernel\Bundle\BundleInterface')->getMock();
$bundle->expects($this->any())->method('getName')->willReturn($name);
$bundle->expects($this->any())->method('getNamespace')->willReturn($namespace);
return $bundle;
}
}

View File

@@ -1,223 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Tests\Controller;
use Psr\Container\ContainerInterface as Psr11ContainerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Bundle\FrameworkBundle\Controller\ControllerNameParser;
use Symfony\Bundle\FrameworkBundle\Controller\ControllerResolver;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Tests\Controller\ContainerControllerResolverTest;
class ControllerResolverTest extends ContainerControllerResolverTest
{
public function testGetControllerOnContainerAware()
{
$resolver = $this->createControllerResolver();
$request = Request::create('/');
$request->attributes->set('_controller', 'Symfony\Bundle\FrameworkBundle\Tests\Controller\ContainerAwareController::testAction');
$controller = $resolver->getController($request);
$this->assertInstanceOf('Symfony\Component\DependencyInjection\ContainerInterface', $controller[0]->getContainer());
$this->assertSame('testAction', $controller[1]);
}
public function testGetControllerOnContainerAwareInvokable()
{
$resolver = $this->createControllerResolver();
$request = Request::create('/');
$request->attributes->set('_controller', 'Symfony\Bundle\FrameworkBundle\Tests\Controller\ContainerAwareController');
$controller = $resolver->getController($request);
$this->assertInstanceOf('Symfony\Bundle\FrameworkBundle\Tests\Controller\ContainerAwareController', $controller);
$this->assertInstanceOf('Symfony\Component\DependencyInjection\ContainerInterface', $controller->getContainer());
}
public function testGetControllerWithBundleNotation()
{
$shortName = 'FooBundle:Default:test';
$parser = $this->createMockParser();
$parser->expects($this->once())
->method('parse')
->with($shortName)
->willReturn('Symfony\Bundle\FrameworkBundle\Tests\Controller\ContainerAwareController::testAction')
;
$resolver = $this->createControllerResolver(null, null, $parser);
$request = Request::create('/');
$request->attributes->set('_controller', $shortName);
$controller = $resolver->getController($request);
$this->assertInstanceOf('Symfony\Bundle\FrameworkBundle\Tests\Controller\ContainerAwareController', $controller[0]);
$this->assertInstanceOf('Symfony\Component\DependencyInjection\ContainerInterface', $controller[0]->getContainer());
$this->assertSame('testAction', $controller[1]);
}
public function testContainerAwareControllerGetsContainerWhenNotSet()
{
class_exists(AbstractControllerTest::class);
$controller = new ContainerAwareController();
$container = new Container();
$container->set(TestAbstractController::class, $controller);
$resolver = $this->createControllerResolver(null, $container);
$request = Request::create('/');
$request->attributes->set('_controller', TestAbstractController::class.':testAction');
$this->assertSame([$controller, 'testAction'], $resolver->getController($request));
$this->assertSame($container, $controller->getContainer());
}
public function testAbstractControllerGetsContainerWhenNotSet()
{
class_exists(AbstractControllerTest::class);
$controller = new TestAbstractController(false);
$container = new Container();
$container->set(TestAbstractController::class, $controller);
$resolver = $this->createControllerResolver(null, $container);
$request = Request::create('/');
$request->attributes->set('_controller', TestAbstractController::class.'::fooAction');
$this->assertSame([$controller, 'fooAction'], $resolver->getController($request));
$this->assertSame($container, $controller->setContainer($container));
}
public function testAbstractControllerServiceWithFcqnIdGetsContainerWhenNotSet()
{
class_exists(AbstractControllerTest::class);
$controller = new DummyController();
$container = new Container();
$container->set(DummyController::class, $controller);
$resolver = $this->createControllerResolver(null, $container);
$request = Request::create('/');
$request->attributes->set('_controller', DummyController::class.':fooAction');
$this->assertSame([$controller, 'fooAction'], $resolver->getController($request));
$this->assertSame($container, $controller->getContainer());
}
public function testAbstractControllerGetsNoContainerWhenSet()
{
class_exists(AbstractControllerTest::class);
$controller = new TestAbstractController(false);
$controllerContainer = new Container();
$controller->setContainer($controllerContainer);
$container = new Container();
$container->set(TestAbstractController::class, $controller);
$resolver = $this->createControllerResolver(null, $container);
$request = Request::create('/');
$request->attributes->set('_controller', TestAbstractController::class.'::fooAction');
$this->assertSame([$controller, 'fooAction'], $resolver->getController($request));
$this->assertSame($controllerContainer, $controller->setContainer($container));
}
public function testAbstractControllerServiceWithFcqnIdGetsNoContainerWhenSet()
{
class_exists(AbstractControllerTest::class);
$controller = new DummyController();
$controllerContainer = new Container();
$controller->setContainer($controllerContainer);
$container = new Container();
$container->set(DummyController::class, $controller);
$resolver = $this->createControllerResolver(null, $container);
$request = Request::create('/');
$request->attributes->set('_controller', DummyController::class.':fooAction');
$this->assertSame([$controller, 'fooAction'], $resolver->getController($request));
$this->assertSame($controllerContainer, $controller->getContainer());
}
protected function createControllerResolver(LoggerInterface $logger = null, Psr11ContainerInterface $container = null, ControllerNameParser $parser = null)
{
if (!$parser) {
$parser = $this->createMockParser();
}
if (!$container) {
$container = $this->createMockContainer();
}
return new ControllerResolver($container, $parser, $logger);
}
protected function createMockParser()
{
return $this->getMockBuilder('Symfony\Bundle\FrameworkBundle\Controller\ControllerNameParser')->disableOriginalConstructor()->getMock();
}
protected function createMockContainer()
{
return $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock();
}
}
class ContainerAwareController implements ContainerAwareInterface
{
private $container;
public function setContainer(ContainerInterface $container = null)
{
$this->container = $container;
}
public function getContainer()
{
return $this->container;
}
public function testAction()
{
}
public function __invoke()
{
}
}
class DummyController extends AbstractController
{
public function getContainer()
{
return $this->container;
}
public function fooAction()
{
}
}

View File

@@ -1,27 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class ControllerTest extends ControllerTraitTest
{
protected function createController()
{
return new TestController();
}
}
class TestController extends Controller
{
use TestControllerTrait;
}

View File

@@ -1,551 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\ControllerTrait;
use Symfony\Bundle\FrameworkBundle\Tests\TestCase;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\Form\Form;
use Symfony\Component\Form\FormConfigInterface;
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\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;
abstract class ControllerTraitTest extends TestCase
{
abstract protected function createController();
public function testForward()
{
$request = Request::create('/');
$request->setLocale('fr');
$request->setRequestFormat('xml');
$requestStack = new RequestStack();
$requestStack->push($request);
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock();
$kernel->expects($this->once())->method('handle')->willReturnCallback(function (Request $request) {
return new Response($request->getRequestFormat().'--'.$request->getLocale());
});
$container = new Container();
$container->set('request_stack', $requestStack);
$container->set('http_kernel', $kernel);
$controller = $this->createController();
$controller->setContainer($container);
$response = $controller->forward('a_controller');
$this->assertEquals('xml--fr', $response->getContent());
}
public function testGetUser()
{
$user = new User('user', 'pass');
$token = new UsernamePasswordToken($user, 'pass', 'default', ['ROLE_USER']);
$controller = $this->createController();
$controller->setContainer($this->getContainerWithTokenStorage($token));
$this->assertSame($controller->getUser(), $user);
}
public function testGetUserAnonymousUserConvertedToNull()
{
$token = new AnonymousToken('default', 'anon.');
$controller = $this->createController();
$controller->setContainer($this->getContainerWithTokenStorage($token));
$this->assertNull($controller->getUser());
}
public function testGetUserWithEmptyTokenStorage()
{
$controller = $this->createController();
$controller->setContainer($this->getContainerWithTokenStorage(null));
$this->assertNull($controller->getUser());
}
public function testGetUserWithEmptyContainer()
{
$this->expectException('LogicException');
$this->expectExceptionMessage('The SecurityBundle is not registered in your application.');
$controller = $this->createController();
$controller->setContainer(new Container());
$controller->getUser();
}
/**
* @param $token
*
* @return Container
*/
private function getContainerWithTokenStorage($token = null)
{
$tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage')->getMock();
$tokenStorage
->expects($this->once())
->method('getToken')
->willReturn($token);
$container = new Container();
$container->set('security.token_storage', $tokenStorage);
return $container;
}
public function testJson()
{
$controller = $this->createController();
$controller->setContainer(new Container());
$response = $controller->json([]);
$this->assertInstanceOf(JsonResponse::class, $response);
$this->assertEquals('[]', $response->getContent());
}
public function testJsonWithSerializer()
{
$container = new Container();
$serializer = $this->getMockBuilder(SerializerInterface::class)->getMock();
$serializer
->expects($this->once())
->method('serialize')
->with([], 'json', ['json_encode_options' => JsonResponse::DEFAULT_ENCODING_OPTIONS])
->willReturn('[]');
$container->set('serializer', $serializer);
$controller = $this->createController();
$controller->setContainer($container);
$response = $controller->json([]);
$this->assertInstanceOf(JsonResponse::class, $response);
$this->assertEquals('[]', $response->getContent());
}
public function testJsonWithSerializerContextOverride()
{
$container = new Container();
$serializer = $this->getMockBuilder(SerializerInterface::class)->getMock();
$serializer
->expects($this->once())
->method('serialize')
->with([], 'json', ['json_encode_options' => 0, 'other' => 'context'])
->willReturn('[]');
$container->set('serializer', $serializer);
$controller = $this->createController();
$controller->setContainer($container);
$response = $controller->json([], 200, [], ['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()
{
$container = new Container();
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock();
$container->set('http_kernel', $kernel);
$controller = $this->createController();
$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->assertStringContainsString(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $response->headers->get('content-disposition'));
$this->assertStringContainsString(basename(__FILE__), $response->headers->get('content-disposition'));
}
public function testFileAsInline()
{
$controller = $this->createController();
/* @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->assertStringContainsString(ResponseHeaderBag::DISPOSITION_INLINE, $response->headers->get('content-disposition'));
$this->assertStringContainsString(basename(__FILE__), $response->headers->get('content-disposition'));
}
public function testFileWithOwnFileName()
{
$controller = $this->createController();
/* @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->assertStringContainsString(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $response->headers->get('content-disposition'));
$this->assertStringContainsString($fileName, $response->headers->get('content-disposition'));
}
public function testFileWithOwnFileNameAsInline()
{
$controller = $this->createController();
/* @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->assertStringContainsString(ResponseHeaderBag::DISPOSITION_INLINE, $response->headers->get('content-disposition'));
$this->assertStringContainsString($fileName, $response->headers->get('content-disposition'));
}
public function testFileFromPath()
{
$controller = $this->createController();
/* @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->assertStringContainsString(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $response->headers->get('content-disposition'));
$this->assertStringContainsString(basename(__FILE__), $response->headers->get('content-disposition'));
}
public function testFileFromPathWithCustomizedFileName()
{
$controller = $this->createController();
/* @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->assertStringContainsString(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $response->headers->get('content-disposition'));
$this->assertStringContainsString('test.php', $response->headers->get('content-disposition'));
}
public function testFileWhichDoesNotExist()
{
$this->expectException('Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException');
$controller = $this->createController();
$controller->file('some-file.txt', 'test.php');
}
public function testIsGranted()
{
$authorizationChecker = $this->getMockBuilder('Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface')->getMock();
$authorizationChecker->expects($this->once())->method('isGranted')->willReturn(true);
$container = new Container();
$container->set('security.authorization_checker', $authorizationChecker);
$controller = $this->createController();
$controller->setContainer($container);
$this->assertTrue($controller->isGranted('foo'));
}
public function testdenyAccessUnlessGranted()
{
$this->expectException('Symfony\Component\Security\Core\Exception\AccessDeniedException');
$authorizationChecker = $this->getMockBuilder('Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface')->getMock();
$authorizationChecker->expects($this->once())->method('isGranted')->willReturn(false);
$container = new Container();
$container->set('security.authorization_checker', $authorizationChecker);
$controller = $this->createController();
$controller->setContainer($container);
$controller->denyAccessUnlessGranted('foo');
}
public function testRenderViewTwig()
{
$twig = $this->getMockBuilder('Twig\Environment')->disableOriginalConstructor()->getMock();
$twig->expects($this->once())->method('render')->willReturn('bar');
$container = new Container();
$container->set('twig', $twig);
$controller = $this->createController();
$controller->setContainer($container);
$this->assertEquals('bar', $controller->renderView('foo'));
}
public function testRenderTwig()
{
$twig = $this->getMockBuilder('Twig\Environment')->disableOriginalConstructor()->getMock();
$twig->expects($this->once())->method('render')->willReturn('bar');
$container = new Container();
$container->set('twig', $twig);
$controller = $this->createController();
$controller->setContainer($container);
$this->assertEquals('bar', $controller->render('foo')->getContent());
}
public function testStreamTwig()
{
$twig = $this->getMockBuilder('Twig\Environment')->disableOriginalConstructor()->getMock();
$container = new Container();
$container->set('twig', $twig);
$controller = $this->createController();
$controller->setContainer($container);
$this->assertInstanceOf('Symfony\Component\HttpFoundation\StreamedResponse', $controller->stream('foo'));
}
public function testRedirectToRoute()
{
$router = $this->getMockBuilder('Symfony\Component\Routing\RouterInterface')->getMock();
$router->expects($this->once())->method('generate')->willReturn('/foo');
$container = new Container();
$container->set('router', $router);
$controller = $this->createController();
$controller->setContainer($container);
$response = $controller->redirectToRoute('foo');
$this->assertInstanceOf('Symfony\Component\HttpFoundation\RedirectResponse', $response);
$this->assertSame('/foo', $response->getTargetUrl());
$this->assertSame(302, $response->getStatusCode());
}
/**
* @runInSeparateProcess
*/
public function testAddFlash()
{
$flashBag = new FlashBag();
$session = $this->getMockBuilder('Symfony\Component\HttpFoundation\Session\Session')->disableOriginalConstructor()->getMock();
$session->expects($this->once())->method('getFlashBag')->willReturn($flashBag);
$container = new Container();
$container->set('session', $session);
$controller = $this->createController();
$controller->setContainer($container);
$controller->addFlash('foo', 'bar');
$this->assertSame(['bar'], $flashBag->get('foo'));
}
public function testCreateAccessDeniedException()
{
$controller = $this->createController();
$this->assertInstanceOf('Symfony\Component\Security\Core\Exception\AccessDeniedException', $controller->createAccessDeniedException());
}
public function testIsCsrfTokenValid()
{
$tokenManager = $this->getMockBuilder('Symfony\Component\Security\Csrf\CsrfTokenManagerInterface')->getMock();
$tokenManager->expects($this->once())->method('isTokenValid')->willReturn(true);
$container = new Container();
$container->set('security.csrf.token_manager', $tokenManager);
$controller = $this->createController();
$controller->setContainer($container);
$this->assertTrue($controller->isCsrfTokenValid('foo', 'bar'));
}
public function testGenerateUrl()
{
$router = $this->getMockBuilder('Symfony\Component\Routing\RouterInterface')->getMock();
$router->expects($this->once())->method('generate')->willReturn('/foo');
$container = new Container();
$container->set('router', $router);
$controller = $this->createController();
$controller->setContainer($container);
$this->assertEquals('/foo', $controller->generateUrl('foo'));
}
public function testRedirect()
{
$controller = $this->createController();
$response = $controller->redirect('https://dunglas.fr', 301);
$this->assertInstanceOf('Symfony\Component\HttpFoundation\RedirectResponse', $response);
$this->assertSame('https://dunglas.fr', $response->getTargetUrl());
$this->assertSame(301, $response->getStatusCode());
}
public function testRenderViewTemplating()
{
$templating = $this->getMockBuilder('Symfony\Bundle\FrameworkBundle\Templating\EngineInterface')->getMock();
$templating->expects($this->once())->method('render')->willReturn('bar');
$container = new Container();
$container->set('templating', $templating);
$controller = $this->createController();
$controller->setContainer($container);
$this->assertEquals('bar', $controller->renderView('foo'));
}
public function testRenderTemplating()
{
$templating = $this->getMockBuilder('Symfony\Bundle\FrameworkBundle\Templating\EngineInterface')->getMock();
$templating->expects($this->once())->method('render')->willReturn('bar');
$container = new Container();
$container->set('templating', $templating);
$controller = $this->createController();
$controller->setContainer($container);
$this->assertEquals('bar', $controller->render('foo')->getContent());
}
public function testStreamTemplating()
{
$templating = $this->getMockBuilder('Symfony\Bundle\FrameworkBundle\Templating\EngineInterface')->getMock();
$container = new Container();
$container->set('templating', $templating);
$controller = $this->createController();
$controller->setContainer($container);
$this->assertInstanceOf('Symfony\Component\HttpFoundation\StreamedResponse', $controller->stream('foo'));
}
public function testCreateNotFoundException()
{
$controller = $this->createController();
$this->assertInstanceOf('Symfony\Component\HttpKernel\Exception\NotFoundHttpException', $controller->createNotFoundException());
}
public function testCreateForm()
{
$form = new Form($this->getMockBuilder(FormConfigInterface::class)->getMock());
$formFactory = $this->getMockBuilder('Symfony\Component\Form\FormFactoryInterface')->getMock();
$formFactory->expects($this->once())->method('create')->willReturn($form);
$container = new Container();
$container->set('form.factory', $formFactory);
$controller = $this->createController();
$controller->setContainer($container);
$this->assertEquals($form, $controller->createForm('foo'));
}
public function testCreateFormBuilder()
{
$formBuilder = $this->getMockBuilder('Symfony\Component\Form\FormBuilderInterface')->getMock();
$formFactory = $this->getMockBuilder('Symfony\Component\Form\FormFactoryInterface')->getMock();
$formFactory->expects($this->once())->method('createBuilder')->willReturn($formBuilder);
$container = new Container();
$container->set('form.factory', $formFactory);
$controller = $this->createController();
$controller->setContainer($container);
$this->assertEquals($formBuilder, $controller->createFormBuilder('foo'));
}
public function testGetDoctrine()
{
$doctrine = $this->getMockBuilder('Doctrine\Common\Persistence\ManagerRegistry')->getMock();
$container = new Container();
$container->set('doctrine', $doctrine);
$controller = $this->createController();
$controller->setContainer($container);
$this->assertEquals($doctrine, $controller->getDoctrine());
}
}
trait TestControllerTrait
{
use ControllerTrait {
generateUrl as public;
redirect as public;
forward as public;
getUser as public;
json as public;
file as public;
isGranted as public;
denyAccessUnlessGranted as public;
redirectToRoute as public;
addFlash as public;
isCsrfTokenValid as public;
renderView as public;
render as public;
stream as public;
createNotFoundException as public;
createAccessDeniedException as public;
createForm as public;
createFormBuilder as public;
getDoctrine as public;
}
}

View File

@@ -1,321 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\RedirectController;
use Symfony\Bundle\FrameworkBundle\Tests\TestCase;
use Symfony\Component\HttpFoundation\ParameterBag;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
/**
* @author Marcin Sikon <marcin.sikon@gmail.com>
*/
class RedirectControllerTest extends TestCase
{
public function testEmptyRoute()
{
$request = new Request();
$controller = new RedirectController();
try {
$controller->redirectAction($request, '', true);
$this->fail('Expected Symfony\Component\HttpKernel\Exception\HttpException to be thrown');
} catch (HttpException $e) {
$this->assertSame(410, $e->getStatusCode());
}
try {
$controller->redirectAction($request, '', false);
$this->fail('Expected Symfony\Component\HttpKernel\Exception\HttpException to be thrown');
} catch (HttpException $e) {
$this->assertSame(404, $e->getStatusCode());
}
}
/**
* @dataProvider provider
*/
public function testRoute($permanent, $ignoreAttributes, $expectedCode, $expectedAttributes)
{
$request = new Request();
$route = 'new-route';
$url = '/redirect-url';
$attributes = [
'route' => $route,
'permanent' => $permanent,
'_route' => 'current-route',
'_route_params' => [
'route' => $route,
'permanent' => $permanent,
'additional-parameter' => 'value',
'ignoreAttributes' => $ignoreAttributes,
],
];
$request->attributes = new ParameterBag($attributes);
$router = $this->getMockBuilder(UrlGeneratorInterface::class)->getMock();
$router
->expects($this->once())
->method('generate')
->with($this->equalTo($route), $this->equalTo($expectedAttributes))
->willReturn($url);
$controller = new RedirectController($router);
$returnResponse = $controller->redirectAction($request, $route, $permanent, $ignoreAttributes);
$this->assertRedirectUrl($returnResponse, $url);
$this->assertEquals($expectedCode, $returnResponse->getStatusCode());
}
public function provider()
{
return [
[true, false, 301, ['additional-parameter' => 'value']],
[false, false, 302, ['additional-parameter' => 'value']],
[false, true, 302, []],
[false, ['additional-parameter'], 302, []],
];
}
public function testEmptyPath()
{
$request = new Request();
$controller = new RedirectController();
try {
$controller->urlRedirectAction($request, '', true);
$this->fail('Expected Symfony\Component\HttpKernel\Exception\HttpException to be thrown');
} catch (HttpException $e) {
$this->assertSame(410, $e->getStatusCode());
}
try {
$controller->urlRedirectAction($request, '', false);
$this->fail('Expected Symfony\Component\HttpKernel\Exception\HttpException to be thrown');
} catch (HttpException $e) {
$this->assertSame(404, $e->getStatusCode());
}
}
public function testFullURL()
{
$request = new Request();
$controller = new RedirectController();
$returnResponse = $controller->urlRedirectAction($request, 'http://foo.bar/');
$this->assertRedirectUrl($returnResponse, 'http://foo.bar/');
$this->assertEquals(302, $returnResponse->getStatusCode());
}
public function testUrlRedirectDefaultPorts()
{
$host = 'www.example.com';
$baseUrl = '/base';
$path = '/redirect-path';
$httpPort = 1080;
$httpsPort = 1443;
$expectedUrl = "https://$host:$httpsPort$baseUrl$path";
$request = $this->createRequestObject('http', $host, $httpPort, $baseUrl);
$controller = $this->createRedirectController(null, $httpsPort);
$returnValue = $controller->urlRedirectAction($request, $path, false, 'https');
$this->assertRedirectUrl($returnValue, $expectedUrl);
$expectedUrl = "http://$host:$httpPort$baseUrl$path";
$request = $this->createRequestObject('https', $host, $httpPort, $baseUrl);
$controller = $this->createRedirectController($httpPort);
$returnValue = $controller->urlRedirectAction($request, $path, false, 'http');
$this->assertRedirectUrl($returnValue, $expectedUrl);
}
/**
* @group legacy
*/
public function testUrlRedirectDefaultPortParameters()
{
$host = 'www.example.com';
$baseUrl = '/base';
$path = '/redirect-path';
$httpPort = 1080;
$httpsPort = 1443;
$expectedUrl = "https://$host:$httpsPort$baseUrl$path";
$request = $this->createRequestObject('http', $host, $httpPort, $baseUrl);
$controller = $this->createLegacyRedirectController(null, $httpsPort);
$returnValue = $controller->urlRedirectAction($request, $path, false, 'https');
$this->assertRedirectUrl($returnValue, $expectedUrl);
$expectedUrl = "http://$host:$httpPort$baseUrl$path";
$request = $this->createRequestObject('https', $host, $httpPort, $baseUrl);
$controller = $this->createLegacyRedirectController($httpPort);
$returnValue = $controller->urlRedirectAction($request, $path, false, 'http');
$this->assertRedirectUrl($returnValue, $expectedUrl);
}
public function urlRedirectProvider()
{
return [
// Standard ports
['http', null, null, 'http', 80, ''],
['http', 80, null, 'http', 80, ''],
['https', null, null, 'http', 80, ''],
['https', 80, null, 'http', 80, ''],
['http', null, null, 'https', 443, ''],
['http', null, 443, 'https', 443, ''],
['https', null, null, 'https', 443, ''],
['https', null, 443, 'https', 443, ''],
// Non-standard ports
['http', null, null, 'http', 8080, ':8080'],
['http', 4080, null, 'http', 8080, ':4080'],
['http', 80, null, 'http', 8080, ''],
['https', null, null, 'http', 8080, ''],
['https', null, 8443, 'http', 8080, ':8443'],
['https', null, 443, 'http', 8080, ''],
['https', null, null, 'https', 8443, ':8443'],
['https', null, 4443, 'https', 8443, ':4443'],
['https', null, 443, 'https', 8443, ''],
['http', null, null, 'https', 8443, ''],
['http', 8080, 4443, 'https', 8443, ':8080'],
['http', 80, 4443, 'https', 8443, ''],
];
}
/**
* @dataProvider urlRedirectProvider
*/
public function testUrlRedirect($scheme, $httpPort, $httpsPort, $requestScheme, $requestPort, $expectedPort)
{
$host = 'www.example.com';
$baseUrl = '/base';
$path = '/redirect-path';
$expectedUrl = "$scheme://$host$expectedPort$baseUrl$path";
$request = $this->createRequestObject($requestScheme, $host, $requestPort, $baseUrl);
$controller = $this->createRedirectController();
$returnValue = $controller->urlRedirectAction($request, $path, false, $scheme, $httpPort, $httpsPort);
$this->assertRedirectUrl($returnValue, $expectedUrl);
}
public function pathQueryParamsProvider()
{
return [
['http://www.example.com/base/redirect-path', '/redirect-path', ''],
['http://www.example.com/base/redirect-path?foo=bar', '/redirect-path?foo=bar', ''],
['http://www.example.com/base/redirect-path?foo=bar', '/redirect-path', 'foo=bar'],
['http://www.example.com/base/redirect-path?foo=bar&abc=example', '/redirect-path?foo=bar', 'abc=example'],
['http://www.example.com/base/redirect-path?foo=bar&abc=example&baz=def', '/redirect-path?foo=bar', 'abc=example&baz=def'],
];
}
/**
* @dataProvider pathQueryParamsProvider
*/
public function testPathQueryParams($expectedUrl, $path, $queryString)
{
$scheme = 'http';
$host = 'www.example.com';
$baseUrl = '/base';
$port = 80;
$request = $this->createRequestObject($scheme, $host, $port, $baseUrl, $queryString);
$controller = $this->createRedirectController();
$returnValue = $controller->urlRedirectAction($request, $path, false, $scheme, $port, null);
$this->assertRedirectUrl($returnValue, $expectedUrl);
}
private function createRequestObject($scheme, $host, $port, $baseUrl, $queryString = '')
{
$request = $this->getMockBuilder('Symfony\Component\HttpFoundation\Request')->getMock();
$request
->expects($this->any())
->method('getScheme')
->willReturn($scheme);
$request
->expects($this->any())
->method('getHost')
->willReturn($host);
$request
->expects($this->any())
->method('getPort')
->willReturn($port);
$request
->expects($this->any())
->method('getBaseUrl')
->willReturn($baseUrl);
$request
->expects($this->any())
->method('getQueryString')
->willReturn($queryString);
return $request;
}
private function createRedirectController($httpPort = null, $httpsPort = null)
{
return new RedirectController(null, $httpPort, $httpsPort);
}
/**
* @deprecated
*/
private function createLegacyRedirectController($httpPort = null, $httpsPort = null)
{
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock();
if (null !== $httpPort) {
$container
->expects($this->once())
->method('hasParameter')
->with($this->equalTo('request_listener.http_port'))
->willReturn(true);
$container
->expects($this->once())
->method('getParameter')
->with($this->equalTo('request_listener.http_port'))
->willReturn($httpPort);
}
if (null !== $httpsPort) {
$container
->expects($this->once())
->method('hasParameter')
->with($this->equalTo('request_listener.https_port'))
->willReturn(true);
$container
->expects($this->once())
->method('getParameter')
->with($this->equalTo('request_listener.https_port'))
->willReturn($httpsPort);
}
$controller = new RedirectController();
$controller->setContainer($container);
return $controller;
}
private function assertRedirectUrl(Response $returnResponse, $expectedUrl)
{
$this->assertTrue($returnResponse->isRedirect($expectedUrl), "Expected: $expectedUrl\nGot: ".$returnResponse->headers->get('Location'));
}
}

View File

@@ -1,88 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\TemplateController;
use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;
use Symfony\Bundle\FrameworkBundle\Tests\TestCase;
/**
* @author Kévin Dunglas <dunglas@gmail.com>
*/
class TemplateControllerTest extends TestCase
{
public function testTwig()
{
$twig = $this->getMockBuilder('Twig\Environment')->disableOriginalConstructor()->getMock();
$twig->expects($this->once())->method('render')->willReturn('bar');
$controller = new TemplateController($twig);
$this->assertEquals('bar', $controller->templateAction('mytemplate')->getContent());
}
public function testTemplating()
{
$templating = $this->getMockBuilder(EngineInterface::class)->getMock();
$templating->expects($this->once())->method('render')->willReturn('bar');
$controller = new TemplateController(null, $templating);
$this->assertEquals('bar', $controller->templateAction('mytemplate')->getContent());
}
/**
* @group legacy
*/
public function testLegacyTwig()
{
$twig = $this->getMockBuilder('Twig\Environment')->disableOriginalConstructor()->getMock();
$twig->expects($this->once())->method('render')->willReturn('bar');
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock();
$container->expects($this->at(0))->method('has')->willReturn(false);
$container->expects($this->at(1))->method('has')->willReturn(true);
$container->expects($this->at(2))->method('get')->willReturn($twig);
$controller = new TemplateController();
$controller->setContainer($container);
$this->assertEquals('bar', $controller->templateAction('mytemplate')->getContent());
}
/**
* @group legacy
*/
public function testLegacyTemplating()
{
$templating = $this->getMockBuilder('Symfony\Bundle\FrameworkBundle\Templating\EngineInterface')->getMock();
$templating->expects($this->once())->method('render')->willReturn('bar');
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock();
$container->expects($this->at(0))->method('has')->willReturn(true);
$container->expects($this->at(1))->method('get')->willReturn($templating);
$controller = new TemplateController();
$controller->setContainer($container);
$this->assertEquals('bar', $controller->templateAction('mytemplate')->getContent());
}
public function testNoTwigNorTemplating()
{
$this->expectException('LogicException');
$this->expectExceptionMessage('You can not use the TemplateController if the Templating Component or the Twig Bundle are not available.');
$controller = new TemplateController();
$controller->templateAction('mytemplate')->getContent();
}
}