浏览代码

merged branch drak/frameworkbundle_sessiontest (PR #2887)

Commits
-------

ba7d810 [FrameworkBundle] Added functional tests.

Discussion
----------

[FrameworkBundle] Added functional tests

Bug fix: no
Feature addition: no
Backwards compatibility break: no
Symfony2 tests pass: yes
Fixes the following tickets: -
Todo: -

Tests session attributes and flash messages APIs in functional practice. These tests increase coverage of this important area and make any future work on sessions much more reliable.
Fabien Potencier 13 年之前
父节点
当前提交
202cefdb0b

+ 73 - 0
src/Symfony/Bundle/FrameworkBundle/Tests/Functional/Bundle/TestBundle/Controller/SessionController.php

@@ -0,0 +1,73 @@
+<?php
+
+/*
+ * This file is part of the Symfony framework.
+ *
+ * (c) Fabien Potencier <fabien@symfony.com>
+ *
+ * This source file is subject to the MIT license that is bundled
+ * with this source code in the file LICENSE.
+ */
+
+namespace Symfony\Bundle\FrameworkBundle\Tests\Functional\Bundle\TestBundle\Controller;
+
+use Symfony\Component\Security\Core\Exception\AccessDeniedException;
+use Symfony\Component\HttpFoundation\Response;
+use Symfony\Component\HttpFoundation\RedirectResponse;
+use Symfony\Component\Security\Core\SecurityContext;
+use Symfony\Component\DependencyInjection\ContainerAware;
+
+class SessionController extends ContainerAware
+{
+    public function welcomeAction($name=null)
+    {
+        $request = $this->container->get('request');
+        $session = $request->getSession();
+
+        // new session case
+        if (!$session->has('name')) {
+            if (!$name) {
+                return new Response('You are new here and gave no name.');
+            }
+
+            // remember name
+            $session->set('name', $name);
+
+            return new Response(sprintf('Hello %s, nice to meet you.', $name));
+        }
+
+        // existing session
+        $name = $session->get('name');
+
+        return new Response(sprintf('Welcome back %s, nice to meet you.', $name));
+    }
+
+    public function logoutAction()
+    {
+        $request = $this->container->get('request')->getSession('session')->clear();
+        return new Response('Session cleared.');
+    }
+
+    public function setFlashAction($message)
+    {
+        $request = $this->container->get('request');
+        $session = $request->getSession();
+        $session->setFlash('notice', $message);
+
+        return new RedirectResponse($this->container->get('router')->generate('session_showflash'));
+    }
+
+    public function showFlashAction()
+    {
+        $request = $this->container->get('request');
+        $session = $request->getSession();
+
+        if ($session->hasFlash('notice')) {
+            $output = $session->getFlash('notice');
+        } else {
+            $output = 'No flash was set.';
+        }
+
+        return new Response($output);
+    }
+}

+ 20 - 0
src/Symfony/Bundle/FrameworkBundle/Tests/Functional/Bundle/TestBundle/Resources/config/routing.yml

@@ -0,0 +1,20 @@
+session_welcome:
+    pattern: /session
+    defaults: { _controller: TestBundle:Session:welcome }
+
+session_welcome_name:
+    pattern: /session/{name}
+    defaults: { _controller: TestBundle:Session:welcome }
+
+session_logout:
+    pattern: /session_logout
+    defaults: { _controller: TestBundle:Session:logout}
+
+session_setflash:
+    pattern: /session_setflash/{message}
+    defaults: { _controller: TestBundle:Session:setFlash}
+
+session_showflash:
+    pattern: /session_showflash
+    defaults: { _controller: TestBundle:Session:showFlash}
+

+ 18 - 0
src/Symfony/Bundle/FrameworkBundle/Tests/Functional/Bundle/TestBundle/TestBundle.php

@@ -0,0 +1,18 @@
+<?php
+
+/*
+ * This file is part of the Symfony framework.
+ *
+ * (c) Fabien Potencier <fabien@symfony.com>
+ *
+ * This source file is subject to the MIT license that is bundled
+ * with this source code in the file LICENSE.
+ */
+
+namespace Symfony\Bundle\FrameworkBundle\Tests\Functional\Bundle\TestBundle;
+
+use Symfony\Component\HttpKernel\Bundle\Bundle;
+
+class TestBundle extends Bundle
+{
+}

+ 87 - 0
src/Symfony/Bundle/FrameworkBundle/Tests/Functional/SessionTest.php

@@ -0,0 +1,87 @@
+<?php
+
+/*
+ * This file is part of the Symfony framework.
+ *
+ * (c) Fabien Potencier <fabien@symfony.com>
+ *
+ * This source file is subject to the MIT license that is bundled
+ * with this source code in the file LICENSE.
+ */
+
+namespace Symfony\Bundle\FrameworkBundle\Tests\Functional;
+
+/**
+ * @group functional
+ */
+class SessionTest extends WebTestCase
+{
+    /**
+     * @dataProvider getConfigs
+     */
+    public function testWelcome($config)
+    {
+        $client = $this->createClient(array('test_case' => 'Session', 'root_config' => $config));
+        $client->insulate();
+
+        // no session
+        $crawler = $client->request('GET', '/session');
+        $this->assertContains('You are new here and gave no name.', $crawler->text());
+
+        // remember name
+        $crawler = $client->request('GET', '/session/drak');
+        $this->assertContains('Hello drak, nice to meet you.', $crawler->text());
+
+        // prove remembered name
+        $crawler = $client->request('GET', '/session');
+        $this->assertContains('Welcome back drak, nice to meet you.', $crawler->text());
+
+        // clear session
+        $crawler = $client->request('GET', '/session_logout');
+        $this->assertContains('Session cleared.', $crawler->text());
+
+        // prove cleared session
+        $crawler = $client->request('GET', '/session');
+        $this->assertContains('You are new here and gave no name.', $crawler->text());
+    }
+
+    /**
+     * @dataProvider getConfigs
+     */
+    public function testFlash($config)
+    {
+        $client = $this->createClient(array('test_case' => 'Session', 'root_config' => $config));
+        $client->insulate();
+
+        // set flash
+        $crawler = $client->request('GET', '/session_setflash/Hello%20world.');
+
+        // check flash displays on redirect
+        $this->assertContains('Hello world.', $client->followRedirect()->text());
+
+        // check flash is gone
+        $crawler = $client->request('GET', '/session_showflash');
+        $this->assertContains('No flash was set.', $crawler->text());
+    }
+
+    public function getConfigs()
+    {
+        return array(
+            array('config.yml'),
+        );
+    }
+
+    protected function setUp()
+    {
+        parent::setUp();
+
+        $this->deleteTmpDir('SessionTest');
+    }
+
+    protected function tearDown()
+    {
+        parent::tearDown();
+
+        $this->deleteTmpDir('SessionTest');
+    }
+}

+ 66 - 0
src/Symfony/Bundle/FrameworkBundle/Tests/Functional/WebTestCase.php

@@ -0,0 +1,66 @@
+<?php
+
+/*
+ * This file is part of the Symfony framework.
+ *
+ * (c) Fabien Potencier <fabien@symfony.com>
+ *
+ * This source file is subject to the MIT license that is bundled
+ * with this source code in the file LICENSE.
+ */
+
+namespace Symfony\Bundle\FrameworkBundle\Tests\Functional;
+
+use Symfony\Component\HttpKernel\Util\Filesystem;
+use Symfony\Bundle\FrameworkBundle\Test\WebTestCase as BaseWebTestCase;
+
+class WebTestCase extends BaseWebTestCase
+{
+    static public function assertRedirect($response, $location)
+    {
+        self::assertTrue($response->isRedirect(), 'Response is not a redirect, got status code: '.substr($response, 0, 2000));
+        self::assertEquals('http://localhost'.$location, $response->headers->get('Location'));
+    }
+
+    protected function setUp()
+    {
+        if (!class_exists('Twig_Environment')) {
+            $this->markTestSkipped('Twig is not available.');
+        }
+
+        parent::setUp();
+    }
+
+    protected function deleteTmpDir($testCase)
+    {
+        if (!file_exists($dir = sys_get_temp_dir().'/'.$testCase)) {
+            return;
+        }
+
+        $fs = new Filesystem();
+        $fs->remove($dir);
+    }
+
+    static protected function getKernelClass()
+    {
+        require_once __DIR__.'/app/AppKernel.php';
+
+        return 'Symfony\Bundle\FrameworkBundle\Tests\Functional\AppKernel';
+    }
+
+    static protected function createKernel(array $options = array())
+    {
+        $class = self::getKernelClass();
+
+        if (!isset($options['test_case'])) {
+            throw new \InvalidArgumentException('The option "test_case" must be set.');
+        }
+
+        return new $class(
+            $options['test_case'],
+            isset($options['root_config']) ? $options['root_config'] : 'config.yml',
+            isset($options['environment']) ? $options['environment'] : 'frameworkbundletest',
+            isset($options['debug']) ? $options['debug'] : true
+        );
+    }
+}

+ 113 - 0
src/Symfony/Bundle/FrameworkBundle/Tests/Functional/app/AppKernel.php

@@ -0,0 +1,113 @@
+<?php
+
+/*
+ * This file is part of the Symfony framework.
+ *
+ * (c) Fabien Potencier <fabien@symfony.com>
+ *
+ * This source file is subject to the MIT license that is bundled
+ * with this source code in the file LICENSE.
+ */
+
+namespace Symfony\Bundle\FrameworkBundle\Tests\Functional;
+
+// get the autoload file
+$dir = __DIR__;
+$lastDir = null;
+while ($dir !== $lastDir) {
+    $lastDir = $dir;
+
+    if (is_file($dir.'/autoload.php')) {
+        require_once $dir.'/autoload.php';
+        break;
+    }
+
+    if (is_file($dir.'/autoload.php.dist')) {
+        require_once $dir.'/autoload.php.dist';
+        break;
+    }
+
+    $dir = dirname($dir);
+}
+
+use Symfony\Component\HttpKernel\Util\Filesystem;
+use Symfony\Component\Config\Loader\LoaderInterface;
+use Symfony\Component\HttpKernel\Kernel;
+
+/**
+ * App Test Kernel for functional tests.
+ *
+ * @author Johannes M. Schmitt <schmittjoh@gmail.com>
+ */
+class AppKernel extends Kernel
+{
+    private $testCase;
+    private $rootConfig;
+
+    public function __construct($testCase, $rootConfig, $environment, $debug)
+    {
+        if (!is_dir(__DIR__.'/'.$testCase)) {
+            throw new \InvalidArgumentException(sprintf('The test case "%s" does not exist.', $testCase));
+        }
+        $this->testCase = $testCase;
+
+        $fs = new Filesystem();
+        if (!$fs->isAbsolutePath($rootConfig) && !is_file($rootConfig = __DIR__.'/'.$testCase.'/'.$rootConfig)) {
+            throw new \InvalidArgumentException(sprintf('The root config "%s" does not exist.', $rootConfig));
+        }
+        $this->rootConfig = $rootConfig;
+
+        parent::__construct($environment, $debug);
+    }
+
+    public function registerBundles()
+    {
+        if (!is_file($filename = $this->getRootDir().'/'.$this->testCase.'/bundles.php')) {
+            throw new \RuntimeException(sprintf('The bundles file "%s" does not exist.', $filename));
+        }
+
+        return include $filename;
+    }
+
+    public function init()
+    {
+    }
+
+    public function getRootDir()
+    {
+        return __DIR__;
+    }
+
+    public function getCacheDir()
+    {
+        return sys_get_temp_dir().'/'.$this->testCase.'/cache/'.$this->environment;
+    }
+
+    public function getLogDir()
+    {
+        return sys_get_temp_dir().'/'.$this->testCase.'/logs';
+    }
+
+    public function registerContainerConfiguration(LoaderInterface $loader)
+    {
+        $loader->load($this->rootConfig);
+    }
+
+    public function serialize()
+    {
+        return serialize(array($this->testCase, $this->rootConfig, $this->getEnvironment(), $this->isDebug()));
+    }
+
+    public function unserialize($str)
+    {
+        call_user_func_array(array($this, '__construct'), unserialize($str));
+    }
+
+    protected function getKernelParameters()
+    {
+        $parameters = parent::getKernelParameters();
+        $parameters['kernel.test_case'] = $this->testCase;
+
+        return $parameters;
+    }
+}

+ 9 - 0
src/Symfony/Bundle/FrameworkBundle/Tests/Functional/app/Session/bundles.php

@@ -0,0 +1,9 @@
+<?php
+
+use Symfony\Bundle\FrameworkBundle\Tests\Functional\Bundle\TestBundle\TestBundle;
+use Symfony\Bundle\FrameworkBundle\FrameworkBundle;
+
+return array(
+    new FrameworkBundle(),
+    new TestBundle(),
+);

+ 3 - 0
src/Symfony/Bundle/FrameworkBundle/Tests/Functional/app/Session/config.yml

@@ -0,0 +1,3 @@
+imports:
+    - { resource: ./../config/default.yml }
+

+ 2 - 0
src/Symfony/Bundle/FrameworkBundle/Tests/Functional/app/Session/routing.yml

@@ -0,0 +1,2 @@
+_sessiontest_bundle:
+    resource: @TestBundle/Resources/config/routing.yml

+ 2 - 0
src/Symfony/Bundle/FrameworkBundle/Tests/Functional/app/config/default.yml

@@ -0,0 +1,2 @@
+imports:
+    - { resource: framework.yml }

+ 14 - 0
src/Symfony/Bundle/FrameworkBundle/Tests/Functional/app/config/framework.yml

@@ -0,0 +1,14 @@
+framework:
+    charset:       UTF-8
+    secret:        test
+    csrf_protection:
+        enabled: true
+    router:        { resource: "%kernel.root_dir%/%kernel.test_case%/routing.yml" }
+    validation:    { enabled: true, enable_annotations: true }
+    form: ~
+    test: ~
+    session:
+        auto_start:     true
+        storage_id:     session.storage.filesystem
+services:
+    logger: { class: Symfony\Component\HttpKernel\Log\NullLogger }