3

我是测试新手,在尝试为管理区域(防火墙后面)编写功能测试时遇到了一个主要问题。

在我的第一次迭代中,我使用了http://symfony.com/doc/2.2/cookbook/testing/http_authentication.html中描述的方式并且它有效。但是我遇到了一个问题,即数据库被从测试中插入的东西弄得乱七八糟。

在下一次迭代中,我开始使用 SQLLite ......突然身份验证不再起作用,我被重定向到登录页面。

如何确保数据正确加载到 SQLLite 数据库中?
还有什么可能导致这个问题?

到目前为止我所拥有的:

config_test.yml

imports:
    - { resource: parameters.yml }
    - { resource: config_dev.yml }

framework:
    test: ~
    session:
        storage_id: session.storage.mock_file

web_profiler:
    toolbar: false
    intercept_redirects: false

swiftmailer:
    disable_delivery: true

doctrine:
    dbal:
        driver: pdo_sqlite
        path: %kernel.root_dir%/../data/%kernel.environment%/database.sqlite
    orm:
        auto_generate_proxy_classes: true
        auto_mapping: true

security:
    firewalls:
        admin:
            http_basic:

WebDoctrineTestCase.php

namespace Yanic\EventBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Input\ArrayInput;

require_once dirname(__DIR__).'/../../../../app/AppKernel.php';

class WebDoctrineTestCase extends WebTestCase
{
    protected static $entityManager;
    protected static $client;
    protected static $application;

    protected static $isFirstTest = true;

    public function setUp()
    {
        parent::setUp();

        /*static::$client = static::createClient(
            array(),
            array(
                'PHP_AUTH_USER' => 'myUsername',
                'PHP_AUTH_PW'   => 'myPassword'
            )
        );*/

        static::$kernel = new \AppKernel('test', true);
        static::$kernel->boot();

        if (!$this->useCachedDatabase()) {
            $this->databaseInit();
            $this->loadFixtures(); 
        }
    }

    /**
     * Initialize database
     */
    protected function databaseInit()
    {
        static::$entityManager = static::$kernel
            ->getContainer()
            ->get('doctrine.orm.entity_manager');

        static::$application = new \Symfony\Bundle\FrameworkBundle\Console\Application(static::$kernel);

        static::$application->setAutoExit(false);
        $this->runConsole("doctrine:schema:drop", array("--force" => true));
        $this->runConsole("doctrine:schema:create");
        $this->runConsole("cache:warmup");
    }

    /**
     * Load tests fixtures
     */
    protected function loadFixtures()
    {
        $this->runConsole("doctrine:fixtures:load");
    }

    /**
     * Use cached database for testing or return false if not
     */
    protected function useCachedDatabase()
    {
        $container = static::$kernel->getContainer();
        $registry = $container->get('doctrine');
        $om = $registry->getEntityManager();
        $connection = $om->getConnection();

        if ($connection->getDriver() instanceOf SqliteDriver) {
            $params = $connection->getParams();
            $name = isset($params['path']) ? $params['path'] : $params['dbname'];
            $filename = pathinfo($name, PATHINFO_BASENAME);
            $backup = $container->getParameter('kernel.cache_dir') . '/'.$filename;

            // The first time we won't use the cached version
            if (self::$isFirstTest) {
                self::$isFirstTest = false;
                return false;
            }

            self::$isFirstTest = false;

            // Regenerate not-existing database
            if (!file_exists($name)) {
                @unlink($backup);
                return false;
            }

            $om->flush();
            $om->clear();

            // Copy backup to database
            if (!file_exists($backup)) {
                copy($name, $backup);
            }

            copy($backup, $name);
            return true;
        }

        return false;
    }

    /**
     * Executes a console command
     *
     * @param type $command
     * @param array $options
     * @return type integer
     */
    protected function runConsole($command, Array $options = array())
    {
        $options["--env"] = "test";
        $options["--quiet"] = null;
        $options["--no-interaction"] = null;
        $options = array_merge($options, array('command' => $command));
        return static::$application->run(new \Symfony\Component\Console\Input\ArrayInput($options));
    }
}

VenueControllerTest.php

namespace Yanic\EventBundle\Tests\Controller;

class VenueControllerTest extends WebDoctrineTestCase
{
    public function testNew()
    {
        $crawler = static::$client->request('GET', '/admin/de/venues/new');

        $this->assertTrue(
            static::$client->getResponse()->isSuccessful(),
            "Couldn't load form"
        );

        $this->assertFalse(
            static::$client->getResponse()->isRedirect(),
            'The request should not be redirected'
        );
    }

    public function testCreate()
    {
        static::$client->request('GET', '/admin/de/venues/create');

        $this->assertEquals(
            405,
            static::$client->getResponse()->getStatusCode(),
            'We should get Method not allowed'
        );

        $crawler = static::$client->request('GET', '/admin/de/venues/new');

        $form = $crawler->selectButton('Anlegen')->form();

        $country = $crawler->filter('#venue_Country option')->eq(1)->attr('value');
        $city = $crawler->filter('#venue_City option')->eq(1)->attr('value');

        $form['venue[name]']->setValue('Test venue');
        $form['venue[address]']->setValue('any address');
        $form['venue[zip]']->setValue('12345');
        $form['venue[Country]']->select( $country );
        $form['venue[City]']->select( $city );

        $crawler = static::$client->submit($form);

        $this->assertTrue(
            static::$client->getResponse()->isSuccessful(),
            'Posting form return not successful'
        );

        $this->assertTrue(
            static::$client->getResponse()->isRedirect(),
            'The request should be redirected'
        );
    }
}
4

1 回答 1

0

使用 LiipFunctionalTestBundle :

    $this->loadFixtures($this->getBundleFixtures(), null);

    $client = static::makeClient(false, array(
        'PHP_AUTH_USER' => 'smith',
        'PHP_AUTH_PW' => 'Smith123456',
    ));
于 2015-12-27T19:06:37.303 回答