DatabaseTestCase.php 2.09 KB
Newer Older
1
<?php
Alexander Makarov committed
2
namespace yiiunit\framework\db;
3

4
use yii\db\Connection;
Alexander Makarov committed
5
use yiiunit\TestCase as TestCase;
6

Alexander Makarov committed
7
abstract class DatabaseTestCase extends TestCase
8
{
9 10 11 12 13 14
    protected $database;
    protected $driverName = 'mysql';
    /**
     * @var Connection
     */
    protected $db;
15

16 17 18
    protected function setUp()
    {
        parent::setUp();
19
        $databases = self::getParam('databases');
20 21
        $this->database = $databases[$this->driverName];
        $pdo_database = 'pdo_'.$this->driverName;
22

23 24 25 26 27
        if (!extension_loaded('pdo') || !extension_loaded($pdo_database)) {
            $this->markTestSkipped('pdo and '.$pdo_database.' extension are required.');
        }
        $this->mockApplication();
    }
28

29 30 31 32 33 34 35
    protected function tearDown()
    {
        if ($this->db) {
            $this->db->close();
        }
        $this->destroyApplication();
    }
36

37 38 39 40 41 42 43 44 45 46
    /**
     * @param  boolean            $reset whether to clean up the test database
     * @param  boolean            $open  whether to open and populate test database
     * @return \yii\db\Connection
     */
    public function getConnection($reset = true, $open = true)
    {
        if (!$reset && $this->db) {
            return $this->db;
        }
Qiang Xue committed
47 48 49 50 51 52
        $config = $this->database;
        if (isset($config['fixture'])) {
            $fixture = $config['fixture'];
            unset($config['fixture']);
        } else {
            $fixture = null;
53
        }
Qiang Xue committed
54
        return $this->db = $this->prepareDatabase($config, $fixture, $open);
Qiang Xue committed
55 56
    }

Qiang Xue committed
57
    public function prepareDatabase($config, $fixture, $open = true)
Qiang Xue committed
58 59 60
    {
        if (!isset($config['class'])) {
            $config['class'] = 'yii\db\Connection';
61
        }
Qiang Xue committed
62 63
        /* @var $db \yii\db\Connection */
        $db = \Yii::createObject($config);
Qiang Xue committed
64 65 66
        if (!$open) {
            return $db;
        }
Qiang Xue committed
67 68 69
        $db->open();
        if ($fixture !== null) {
            $lines = explode(';', file_get_contents($fixture));
70 71 72 73 74 75 76 77
            foreach ($lines as $line) {
                if (trim($line) !== '') {
                    $db->pdo->exec($line);
                }
            }
        }
        return $db;
    }
78
}