DatabaseTestCase.php 1.55 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
	protected $database;
	protected $driverName = 'mysql';
11 12 13
	/**
	 * @var Connection
	 */
14
	protected $db;
15

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

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

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

37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
	/**
	 * @param bool $reset whether to clean up the test database
	 * @param bool $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;
		}
		$db = new \yii\db\Connection;
		$db->dsn = $this->database['dsn'];
		if (isset($this->database['username'])) {
			$db->username = $this->database['username'];
			$db->password = $this->database['password'];
		}
53 54 55
		if (isset($this->database['attributes'])) {
			$db->attributes = $this->database['attributes'];
		}
56 57 58 59 60 61 62 63 64 65 66 67
		if ($open) {
			$db->open();
			$lines = explode(';', file_get_contents($this->database['fixture']));
			foreach ($lines as $line) {
				if (trim($line) !== '') {
					$db->pdo->exec($line);
				}
			}
		}
		$this->db = $db;
		return $db;
	}
68
}