|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace malkusch\lock\mutex; |
| 4 | + |
| 5 | +use Eloquent\Liberator\Liberator; |
| 6 | + |
| 7 | +/** |
| 8 | + * @author Willem Stuursma-Ruwen <[email protected]> |
| 9 | + * @link bitcoin:1P5FAZ4QhXCuwYPnLZdk3PJsqePbu1UDDA Donations |
| 10 | + * @license WTFPL |
| 11 | + * @see CASMutex |
| 12 | + */ |
| 13 | +class FlockMutexTest extends \PHPUnit_Framework_TestCase |
| 14 | +{ |
| 15 | + /** |
| 16 | + * @var FlockMutex |
| 17 | + */ |
| 18 | + private $mutex; |
| 19 | + |
| 20 | + /** |
| 21 | + * @var resource |
| 22 | + */ |
| 23 | + private $file; |
| 24 | + |
| 25 | + protected function setUp() |
| 26 | + { |
| 27 | + parent::setUp(); |
| 28 | + |
| 29 | + $this->file = tempnam(sys_get_temp_dir(), "flock-"); |
| 30 | + $this->mutex = Liberator::liberate(new FlockMutex(fopen($this->file, "r"), 1)); |
| 31 | + } |
| 32 | + |
| 33 | + protected function tearDown() |
| 34 | + { |
| 35 | + unlink($this->file); |
| 36 | + |
| 37 | + parent::tearDown(); |
| 38 | + } |
| 39 | + |
| 40 | + /** |
| 41 | + * @dataProvider dpTimeoutableStrategies |
| 42 | + */ |
| 43 | + public function testCodeExecutedOutsideLockIsNotThrown($strategy) |
| 44 | + { |
| 45 | + $this->mutex->strategy = $strategy; |
| 46 | + |
| 47 | + $this->assertTrue($this->mutex->synchronized(function () { |
| 48 | + usleep(1.1e6); |
| 49 | + return true; |
| 50 | + })); |
| 51 | + } |
| 52 | + |
| 53 | + /** |
| 54 | + * @expectedException \malkusch\lock\exception\TimeoutException |
| 55 | + * @dataProvider dpTimeoutableStrategies |
| 56 | + */ |
| 57 | + public function testTimeoutOccurs($strategy) |
| 58 | + { |
| 59 | + $another_resource = fopen($this->file, "r"); |
| 60 | + flock($another_resource, LOCK_EX); |
| 61 | + |
| 62 | + $this->mutex->strategy = $strategy; |
| 63 | + |
| 64 | + try { |
| 65 | + $this->mutex->synchronized( |
| 66 | + function () { |
| 67 | + $this->fail("Did not expect code to be executed"); |
| 68 | + } |
| 69 | + ); |
| 70 | + } finally { |
| 71 | + fclose($another_resource); |
| 72 | + } |
| 73 | + } |
| 74 | + |
| 75 | + public function dpTimeoutableStrategies() |
| 76 | + { |
| 77 | + return [ |
| 78 | + [FlockMutex::STRATEGY_PCNTL], |
| 79 | + [FlockMutex::STRATEGY_BUSY], |
| 80 | + ]; |
| 81 | + } |
| 82 | +} |
0 commit comments