ARedisMutexTest.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. require_once("common.php");
  3. /**
  4. * Tests for the {@link ARedisMutex} class
  5. * @author Charles Pick
  6. * @package packages.redis.tests
  7. */
  8. class ARedisMutexTest extends CTestCase {
  9. /**
  10. * Holds the redis connection
  11. * @var ARedisConnection
  12. */
  13. protected $_connection;
  14. /**
  15. * Tests the basic functionality
  16. */
  17. public function testBasics() {
  18. $redis = $this->getConnection();
  19. $mutex1 = new ARedisMutex("TestMutex2:".uniqid(),$redis);
  20. $mutex2 = new ARedisMutex($mutex1->name,$redis);
  21. $mutex1->expiresAfter = 2;
  22. $mutex2->expiresAfter = 2;
  23. $this->assertTrue($mutex1->lock());
  24. $this->assertFalse($mutex2->lock());
  25. $this->assertFalse($mutex2->unlock());
  26. $this->assertTrue($mutex1->unlock());
  27. $this->assertTrue($mutex2->lock());
  28. sleep(3);
  29. $this->assertTrue($mutex1->lock());
  30. $this->assertTrue($mutex1->unlock());
  31. }
  32. /**
  33. * Tests the blocking functionality
  34. */
  35. public function testBlock() {
  36. $redis = $this->getConnection();
  37. $mutex1 = new ARedisMutex("TestMutex2:".uniqid(),$redis);
  38. $mutex2 = new ARedisMutex($mutex1->name,$redis);
  39. $mutex1->expiresAfter = 2;
  40. $mutex2->expiresAfter = 2;
  41. $this->assertTrue($mutex1->lock());
  42. $count = 0;
  43. $mutex2->onAfterLock = function(CEvent $event) use (&$count) {
  44. $count++;
  45. $event->sender->unlock();
  46. };
  47. $mutex2->block();
  48. $this->assertEquals(1, $count);
  49. }
  50. /**
  51. * Sets the redis connection to use with this test
  52. * @param ARedisConnection $connection the connection
  53. */
  54. public function setConnection($connection)
  55. {
  56. $this->_connection = $connection;
  57. }
  58. /**
  59. * Gets the redis connection to use with this test
  60. * @return ARedisConnection the redis connection
  61. */
  62. public function getConnection()
  63. {
  64. if ($this->_connection === null) {
  65. $this->_connection = Yii::createComponent(
  66. array(
  67. "class" => "packages.redis.ARedisConnection",
  68. "hostname" => REDIS_HOSTNAME,
  69. "port" => REDIS_PORT,
  70. "database" => REDIS_DATABASE,
  71. "password" => REDIS_PASSWORD
  72. ));
  73. }
  74. return $this->_connection;
  75. }
  76. }