DbCacheTest.php 1.89 KB
Newer Older
1
<?php
2

3
namespace yiiunit\framework\caching;
4

5 6 7 8
use yii\caching\DbCache;

/**
 * Class for testing file cache backend
9 10
 * @group db
 * @group caching
11
 */
Alexander Makarov committed
12
class DbCacheTest extends CacheTestCase
13 14 15 16
{
	private $_cacheInstance;
	private $_connection;

17
	protected function setUp()
18 19 20 21 22
	{
		if (!extension_loaded('pdo') || !extension_loaded('pdo_mysql')) {
			$this->markTestSkipped('pdo and pdo_mysql extensions are required.');
		}

23 24
		parent::setUp();
		
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
		$this->getConnection()->createCommand("
			CREATE TABLE IF NOT EXISTS tbl_cache (
				id char(128) NOT NULL,
				expire int(11) DEFAULT NULL,
				data LONGBLOB,
				PRIMARY KEY (id),
				KEY expire (expire)
			);
		")->execute();
	}

	/**
	 * @param bool $reset whether to clean up the test database
	 * @return \yii\db\Connection
	 */
Alexander Makarov committed
40
	public function getConnection($reset = true)
41
	{
resurtm committed
42
		if ($this->_connection === null) {
43
			$databases = $this->getParam('databases');
Alexander Makarov committed
44
			$params = $databases['mysql'];
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
			$db = new \yii\db\Connection;
			$db->dsn = $params['dsn'];
			$db->username = $params['username'];
			$db->password = $params['password'];
			if ($reset) {
				$db->open();
				$lines = explode(';', file_get_contents($params['fixture']));
				foreach ($lines as $line) {
					if (trim($line) !== '') {
						$db->pdo->exec($line);
					}
				}
			}
			$this->_connection = $db;
		}
		return $this->_connection;
	}


	/**
	 * @return DbCache
	 */
	protected function getCacheInstance()
	{
resurtm committed
69
		if ($this->_cacheInstance === null) {
70 71 72 73 74 75
			$this->_cacheInstance = new DbCache(array(
				'db' => $this->getConnection(),
			));
		}
		return $this->_cacheInstance;
	}
76 77 78 79 80

	public function testExpire()
	{
		$cache = $this->getCacheInstance();

81
		static::$time = \time();
82
		$this->assertTrue($cache->set('expire_test', 'expire_test', 2));
83
		static::$time++;
84
		$this->assertEquals('expire_test', $cache->get('expire_test'));
85
		static::$time++;
86 87
		$this->assertFalse($cache->get('expire_test'));
	}
Zander Baldwin committed
88
}