ldc-cocotte/tests/Unit/Infra/Adapters/Locks/LaravelCacheLockTest.php

101 lines
3.4 KiB
PHP

<?php
declare(strict_types=1);
use Illuminate\Cache\ArrayStore;
use Illuminate\Cache\Repository;
use Illuminate\Contracts\Cache\Lock;
use Illuminate\Contracts\Cache\LockProvider;
use Illuminate\Contracts\Cache\LockTimeoutException as LaravelLockTimeoutException;
use Illuminate\Contracts\Cache\Store;
use Infrastructure\Adapters\Locks\LaravelCacheLock;
use Shared\Concurrency\LockTimeoutException;
describe('LaravelCacheLock', function (): void {
it('executes callback and releases lock afterwards', function (): void {
// GIVEN
$store = new ArrayStore();
$cache = new Repository($store);
$cacheLock = new LaravelCacheLock($cache);
// WHEN
$result = $cacheLock->synchronize('test:lock:success', fn (): string => 'ok');
// THEN
expect($result)->toBe('ok');
// Verify lock was released and can be acquired again immediately
$reacquired = $store->lock('test:lock:success', 10)->get();
expect($reacquired)->toBeTrue();
});
it('releases lock even when callback throws an exception', function (): void {
// GIVEN
$store = new ArrayStore();
$cache = new Repository($store);
$cacheLock = new LaravelCacheLock($cache);
$customException = new \RuntimeException('Callback failure');
// WHEN
$action = fn () => $cacheLock->synchronize('test:lock:exception', function () use ($customException): never {
throw $customException;
});
// THEN
expect($action)->toThrow($customException);
$reacquired = $store->lock('test:lock:exception', 10)->get();
expect($reacquired)->toBeTrue();
});
it('throws LockTimeoutException when lock is already held', function (): void {
// GIVEN
$store = new ArrayStore();
$cache = new Repository($store);
$cacheLock = new LaravelCacheLock($cache);
$heldLock = $store->lock('test:lock:held', 30);
expect($heldLock->get())->toBeTrue();
// WHEN
$action = fn () => $cacheLock->synchronize(
key: 'test:lock:held',
callback: fn (): string => 'never',
ttlSeconds: 30,
waitSeconds: 0,
);
// THEN
expect($action)->toThrow(LockTimeoutException::class);
$heldLock->release();
});
it('wraps Laravel LockTimeoutException with previous exception preserved', function (): void {
// GIVEN
$laravelLock = \Mockery::mock(Lock::class);
$laravelLock->shouldReceive('block')
->once()
->with(5, \Mockery::type(\Closure::class))
->andThrow(new LaravelLockTimeoutException('Timed out'));
$store = \Mockery::mock(Store::class, LockProvider::class);
$store->shouldReceive('lock')
->once()
->with('test:lock:wrapped', 30)
->andReturn($laravelLock);
$cache = new Repository($store);
$cacheLock = new LaravelCacheLock($cache);
// WHEN
try {
$cacheLock->synchronize('test:lock:wrapped', fn (): string => 'never', 30, 5);
$this->fail('Expected LockTimeoutException was not thrown.');
} catch (LockTimeoutException $e) {
// THEN
expect($e->getMessage())->toBe('Timed out')
->and($e->getPrevious())->toBeInstanceOf(LaravelLockTimeoutException::class);
}
});
});