Symfony 4:在测试+控制器+ Twig扩展中保留SQLite PDO连接

时间:2019-02-05 13:33:07

标签: php sqlite symfony pdo twig

我的情况

我有一个具有以下结构的Symfony 4.2项目:

  • src
    • 控制器
    • 服务
    • Twig扩展
  • 模板
  • 测试

我使用数据库类,该类在内部创建PDO连接。如果我使用PHPUnit运行测试,则数据库类必须从mysql切换到sqlite。这里一切都很好。

我的问题

仅运行一个测试时,我无法保留曾经创建的数据库实例。 Symfony似乎在测试过程中会重新创建它:在使用Twig扩展名的Twig模板中。因为数据库类使用

new \PDO('sqlite::memory:');

它会丢失创建的表,因此测试失败。我知道,每次测试后都会重置数据库实例(带有PDO参考),但是在我的情况下,我只有一个测试。 我如何确保它重新使用数据库实例?

此处是相关代码

InstanceExtension类提供函数标题,该标题在Twig模板中使用,并且必须访问数据库。

<?php

namespace App\TwigExtension;

use App\Service\Database;
use Twig\TwigFunction;
use Twig\Extension\AbstractExtension;

class InstanceExtension extends AbstractExtension
{
    protected $db;

    /**
     * @param Database $db
     */
    public function __construct(Database $db)
    {
        $this->db = $db;
    }

    /**
     * Tries to return the title/name for a given ID.
     *
     * @param string $subject
     * @param string|array $tables
     * @param string $lang         Default is 'de'
     *
     * @return string label or id, if no title/name was found
     */
    public function title(string $subject, $tables, string $lang = 'de'): string
    {    
        return $this->db->get_instance_title($subject, $tables, $lang);
    }
}

在我的 services.yaml 中,Database类设置为public(应该重新使用它,不是吗?):

App\Service\Database:
    public: true

数据库类

这是Database类的一部分,用于初始化PDO连接。生产代码(使用MySQL代替)已删除:

<?php

declare(strict_types=1);

namespace App\Service;

class Database
{
    /**
     * @param Config $app_config
     *
     * @throws \Exception
     */
    public function __construct(Config $app_config)
    {
        global $sqlite_pdo;

        try {
            // non test
            // ..

            // test environment
            } else {
                $this->db_engine = 'sqlite';

                // workaround to ensure we have the same PDO instance everytime we use the Database instance
                // if we dont use it, in Twig extensions a new Database instance is created with a new SQLite
                // database, which is empty.
                if (null == $sqlite_pdo) {
                    $pdo = new \PDO('sqlite::memory:');
                    $sqlite_pdo = $pdo;
                } else {
                    $pdo = $sqlite_pdo;
                }
            }

        } catch (\PDOException $e) {
            if (\strpos((string) $e->getMessage(), 'could not find driver') !== false) {
                throw new \Exception(
                    'Could not create a PDO connection. Is the driver installed/enabled?'
                );
            }

            if (\strpos((string) $e->getMessage(), 'unknown database') !== false) {
                throw new \Exception(
                    'Could not create a PDO connection. Check that your database exists.'
                );
            }

            // Don't leak credentials directly if we can.
            throw new \Exception(
                'Could not create a PDO connection. Please check your username and password.'
            );
        }

        if ('mysql' == $this->db_engine) {
            // ...
        }

        // default fetch mode is associative
        $pdo->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_ASSOC);

        // everything odd will be handled as exception
        $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);

        $this->db = $pdo;
    }

    // ...
}

一个测试看起来像:

<?php 

class SalesChannelControllerTest extends TestCase
{
    public function setUp()
    {
        parent::setUp();

        // init Database class, using SQLite
        $this->init_db();

        // further setup function calls

        // SalesChannelController is a child of
        // Symfony\Bundle\FrameworkBundle\Controller\AbstractController
        $this->fixture = new SalesChannelController(
            $this->db
            // ...
        );
    }

    /**
     * Returns a ready-to-use instance of the database. Default adapter is SQLite.
     *
     * @return Database
     */
    protected function init_db(): Database
    {
        // config parameter just contains DB credentials
        $this->db = new Database($this->config);
    }

    public function test_introduction_action()
    {
         // preparations

         /*
          * run action
          *
          * which renders a Twig template, creates a Response and returns it.
          */
         $response = $this->fixture->introduction_action($this->request, $this->session, 'sales_channel1');

         /*
          * check response
          */
         $this->assertEquals(200, $response->getStatusCode());
    } 
}

我当前的解决方法是将PDO实例存储在全局变量中,并在需要时重新使用它。

<?php 

global $sqlite_pdo;

// ...

// inside Database class, when initializing the PDO connection
if (null == $sqlite_pdo) {
    $pdo = new \PDO('sqlite::memory:');
    $sqlite_pdo = $pdo;
} else {
    $pdo = $sqlite_pdo;
}

如果您需要更多信息,请告诉我。感谢您的时间和提前的帮助!

0 个答案:

没有答案