RedisCacheTest.php 2.02 KB
Newer Older
1 2 3 4 5 6 7
<?php
namespace yiiunit\framework\caching;
use yii\caching\MemCache;
use yii\caching\RedisCache;

/**
 * Class for testing redis cache backend
8 9
 * @group redis
 * @group caching
10 11 12 13 14 15 16 17 18 19
 */
class RedisCacheTest extends CacheTestCase
{
	private $_cacheInstance = null;

	/**
	 * @return MemCache
	 */
	protected function getCacheInstance()
	{
Alexander Makarov committed
20
		$config = [
21 22 23 24
			'hostname' => 'localhost',
			'port' => 6379,
			'database' => 0,
			'dataTimeout' => 0.1,
Alexander Makarov committed
25
		];
26
		$dsn = $config['hostname'] . ':' .$config['port'];
27
		if (!@stream_socket_client($dsn, $errorNumber, $errorDescription, 0.5)) {
28 29 30
			$this->markTestSkipped('No redis server running at ' . $dsn .' : ' . $errorNumber . ' - ' . $errorDescription);
		}

31
		if ($this->_cacheInstance === null) {
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
			$this->_cacheInstance = new RedisCache($config);
		}
		return $this->_cacheInstance;
	}

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

		$this->assertTrue($cache->set('expire_test_ms', 'expire_test_ms', 0.2));
		usleep(100000);
		$this->assertEquals('expire_test_ms', $cache->get('expire_test_ms'));
		usleep(300000);
		$this->assertFalse($cache->get('expire_test_ms'));
	}

	/**
	 * Store a value that is 2 times buffer size big
	 * https://github.com/yiisoft/yii2/issues/743
	 */
	public function testLargeData()
	{
		$cache = $this->getCacheInstance();

		$data=str_repeat('XX',8192); // http://www.php.net/manual/en/function.fread.php
		$key='bigdata1';

		$this->assertFalse($cache->get($key));
		$cache->set($key,$data);
		$this->assertTrue($cache->get($key)===$data);

		// try with multibyte string
		$data=str_repeat('ЖЫ',8192); // http://www.php.net/manual/en/function.fread.php
		$key='bigdata2';

		$this->assertFalse($cache->get($key));
		$cache->set($key,$data);
		$this->assertTrue($cache->get($key)===$data);
	}

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

Alexander Makarov committed
76
		$data=['abc'=>'ежик',2=>'def'];
77 78 79 80 81 82 83 84
		$key='data1';

		$this->assertFalse($cache->get($key));
		$cache->set($key,$data);
		$this->assertTrue($cache->get($key)===$data);
	}

}