1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 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 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
|
<?php
declare(strict_types=1);
namespace malkusch\lock\Tests\mutex;
use malkusch\lock\exception\LockAcquireException;
use malkusch\lock\mutex\CASMutex;
use phpmock\environment\SleepEnvironmentBuilder;
use phpmock\MockEnabledException;
use phpmock\phpunit\PHPMock;
use PHPUnit\Framework\TestCase;
class CASMutexTest extends TestCase
{
use PHPMock;
#[\Override]
protected function setUp(): void
{
parent::setUp();
$sleepBuilder = new SleepEnvironmentBuilder();
$sleepBuilder->addNamespace(__NAMESPACE__);
$sleepBuilder->addNamespace('malkusch\lock\mutex');
$sleepBuilder->addNamespace('malkusch\lock\util');
$sleep = $sleepBuilder->build();
try {
$sleep->enable();
$this->registerForTearDown($sleep);
} catch (MockEnabledException $e) {
// workaround for burn testing
\assert($e->getMessage() === 'microtime is already enabled.Call disable() on the existing mock.');
}
}
/**
* Tests exceeding the execution timeout.
*/
public function testExceedTimeout(): void
{
$this->expectException(LockAcquireException::class);
$mutex = new CASMutex(1);
$mutex->synchronized(static function (): void {
sleep(2);
});
}
/**
* Tests that an exception would stop any further iteration.
*/
public function testExceptionStopsIteration(): void
{
$this->expectException(\DomainException::class);
$mutex = new CASMutex();
$mutex->synchronized(static function () {
throw new \DomainException();
});
}
/**
* Tests notify() will stop the iteration and return the result.
*/
public function testNotify(): void
{
$i = 0;
$mutex = new CASMutex();
$mutex->synchronized(static function () use ($mutex, &$i) {
++$i;
$mutex->notify();
});
self::assertSame(1, $i);
}
/**
* Tests that the code is executed more times.
*/
public function testIteration(): void
{
$i = 0;
$mutex = new CASMutex();
$mutex->synchronized(static function () use ($mutex, &$i): void {
++$i;
if ($i > 1) {
$mutex->notify();
}
});
self::assertSame(2, $i);
}
}
|