CacheTest.php 2.23 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
<?php
namespace yiiunit\framework\caching;
use yiiunit\TestCase;
use yii\caching\Cache;

/**
 * Base class for testing cache backends
 */
abstract class CacheTest extends TestCase
{
	/**
	 * @return Cache
	 */
	abstract protected function getCacheInstance();

16 17 18 19 20 21
	protected function setUp()
	{
		parent::setUp();
		$this->requireApp();
	}
	
22 23 24
	public function testSet()
	{
		$cache = $this->getCacheInstance();
25 26 27
		$this->assertTrue($cache->set('string_test', 'string_test'));
		$this->assertTrue($cache->set('number_test', 42));
		$this->assertTrue($cache->set('array_test', array('array_test' => 'array_test')));
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
		$cache['arrayaccess_test'] = new \stdClass();
	}

	public function testGet()
	{
		$cache = $this->getCacheInstance();
		$this->assertEquals('string_test', $cache->get('string_test'));

		$this->assertEquals(42, $cache->get('number_test'));

		$array = $cache->get('array_test');
		$this->assertArrayHasKey('array_test', $array);
		$this->assertEquals('array_test', $array['array_test']);

		$this->assertInstanceOf('stdClass', $cache['arrayaccess_test']);
	}

	public function testMget()
	{
		$cache = $this->getCacheInstance();
		$this->assertEquals(array('string_test' => 'string_test', 'number_test' => 42), $cache->mget(array('string_test', 'number_test')));
	}

	public function testExpire()
	{
		$cache = $this->getCacheInstance();
54
		$this->assertTrue($cache->set('expire_test', 'expire_test', 2));
55 56 57 58 59 60 61 62 63 64 65
		sleep(1);
		$this->assertEquals('expire_test', $cache->get('expire_test'));
		sleep(2);
		$this->assertEquals(false, $cache->get('expire_test'));
	}

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

		// should not change existing keys
66
		$this->assertFalse($cache->add('number_test', 13));
67 68 69
		$this->assertEquals(42, $cache->get('number_test'));

		// should store data is it's not there yet
70
		$this->assertTrue($cache->add('add_test', 13));
71 72 73 74 75 76 77
		$this->assertEquals(13, $cache->get('add_test'));
	}

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

78
		$this->assertTrue($cache->delete('number_test'));
79 80 81 82 83 84
		$this->assertEquals(null, $cache->get('number_test'));
	}

	public function testFlush()
	{
		$cache = $this->getCacheInstance();
85
		$this->assertTrue($cache->flush());
86 87 88
		$this->assertEquals(null, $cache->get('add_test'));
	}
}