|
| 1 | +<?php |
| 2 | + |
| 3 | +use TH\RedisLock\RedisSimpleLock; |
| 4 | + |
| 5 | +class RedisSimpleLockTest extends PHPUnit_Framework_TestCase |
| 6 | +{ |
| 7 | + private $redisClient; |
| 8 | + |
| 9 | + protected function setUp() |
| 10 | + { |
| 11 | + $this->redisClient = new \Predis\Client(getenv("REDIS_URI")); |
| 12 | + $this->redisClient->flushdb(); |
| 13 | + } |
| 14 | + |
| 15 | + public function testLock() |
| 16 | + { |
| 17 | + $lock1 = new RedisSimpleLock("lock identifier", $this->redisClient, 50); |
| 18 | + $lock2 = new RedisSimpleLock("lock identifier", $this->redisClient); |
| 19 | + |
| 20 | + $lock1->acquire(); |
| 21 | + |
| 22 | + // Only the second acquire is supposed to fail |
| 23 | + $this->setExpectedException("Exception"); |
| 24 | + $lock2->acquire(); |
| 25 | + } |
| 26 | + |
| 27 | + public function testLockTtl() |
| 28 | + { |
| 29 | + $lock1 = new RedisSimpleLock("lock identifier", $this->redisClient, 50); |
| 30 | + $lock2 = new RedisSimpleLock("lock identifier", $this->redisClient); |
| 31 | + |
| 32 | + $lock1->acquire(); |
| 33 | + usleep(100000); |
| 34 | + |
| 35 | + // first lock sould have been released |
| 36 | + $lock2->acquire(); |
| 37 | + } |
| 38 | + |
| 39 | + public function testLockSafeRelease() |
| 40 | + { |
| 41 | + $lock1 = new RedisSimpleLock("lock identifier", $this->redisClient, 50); |
| 42 | + $lock2 = new RedisSimpleLock("lock identifier", $this->redisClient); |
| 43 | + |
| 44 | + $lock1->acquire(); |
| 45 | + usleep(100000); |
| 46 | + $lock2->acquire(); |
| 47 | + $lock1->release(); |
| 48 | + |
| 49 | + // lock should still exists |
| 50 | + $this->assertTrue($this->redisClient->exists("lock identifier"), "Lock should not have been released"); |
| 51 | + } |
| 52 | + |
| 53 | + public function testLockRelease() |
| 54 | + { |
| 55 | + $lock1 = new RedisSimpleLock("lock identifier", $this->redisClient, 50); |
| 56 | + $lock2 = new RedisSimpleLock("lock identifier", $this->redisClient); |
| 57 | + |
| 58 | + $lock1->acquire(); |
| 59 | + $lock1->release(); |
| 60 | + |
| 61 | + // first lock sould have been released |
| 62 | + $lock2->acquire(); |
| 63 | + } |
| 64 | + |
| 65 | + public function testLockAutoRelease() |
| 66 | + { |
| 67 | + $lock1 = new RedisSimpleLock("lock identifier", $this->redisClient, 50); |
| 68 | + $lock2 = new RedisSimpleLock("lock identifier", $this->redisClient); |
| 69 | + |
| 70 | + $lock1->acquire(); |
| 71 | + unset($lock1); |
| 72 | + |
| 73 | + // first lock sould have been released |
| 74 | + $lock2->acquire(); |
| 75 | + } |
| 76 | +} |
0 commit comments