87 lines
2.4 KiB
PHP
87 lines
2.4 KiB
PHP
|
|
<?php
|
||
|
|
|
||
|
|
declare(strict_types=1);
|
||
|
|
|
||
|
|
use App\Contracts\Action;
|
||
|
|
use App\Contracts\ActionInput;
|
||
|
|
use App\Services\ActionExecutorService;
|
||
|
|
use Psr\Log\AbstractLogger;
|
||
|
|
|
||
|
|
describe('ActionExecutorService', function (): void {
|
||
|
|
it('executes action in transaction and logs success', function (): void {
|
||
|
|
// GIVEN
|
||
|
|
$logger = new class () extends AbstractLogger
|
||
|
|
{
|
||
|
|
/** @var array<int, string> */
|
||
|
|
public array $logs = [];
|
||
|
|
|
||
|
|
#[\Override]
|
||
|
|
public function log($level, string | \Stringable $message, array $context = []): void
|
||
|
|
{
|
||
|
|
$this->logs[] = (string) $message;
|
||
|
|
}
|
||
|
|
};
|
||
|
|
|
||
|
|
$action = new class () implements Action
|
||
|
|
{
|
||
|
|
#[\Override]
|
||
|
|
public function __invoke(ActionInput $input): string
|
||
|
|
{
|
||
|
|
return 'done';
|
||
|
|
}
|
||
|
|
};
|
||
|
|
|
||
|
|
$input = new class () implements ActionInput
|
||
|
|
{
|
||
|
|
};
|
||
|
|
$executor = new ActionExecutorService($logger);
|
||
|
|
|
||
|
|
// WHEN
|
||
|
|
$result = $executor->execute($action, $input);
|
||
|
|
|
||
|
|
// THEN
|
||
|
|
expect($result)->toBe('done')
|
||
|
|
->and($logger->logs)->toHaveCount(2)
|
||
|
|
->and($logger->logs[0])->toContain('Executing')
|
||
|
|
->and($logger->logs[1])->toContain('Succeeded');
|
||
|
|
});
|
||
|
|
|
||
|
|
it('logs error and rethrows when action fails', function (): void {
|
||
|
|
// GIVEN
|
||
|
|
$logger = new class () extends AbstractLogger
|
||
|
|
{
|
||
|
|
/** @var array<int, string> */
|
||
|
|
public array $logs = [];
|
||
|
|
|
||
|
|
#[\Override]
|
||
|
|
public function log($level, string | \Stringable $message, array $context = []): void
|
||
|
|
{
|
||
|
|
$this->logs[] = (string) $message;
|
||
|
|
}
|
||
|
|
};
|
||
|
|
|
||
|
|
$action = new class () implements Action
|
||
|
|
{
|
||
|
|
#[\Override]
|
||
|
|
public function __invoke(ActionInput $input): never
|
||
|
|
{
|
||
|
|
throw new \RuntimeException('Database failure');
|
||
|
|
}
|
||
|
|
};
|
||
|
|
|
||
|
|
$input = new class () implements ActionInput
|
||
|
|
{
|
||
|
|
};
|
||
|
|
$executor = new ActionExecutorService($logger);
|
||
|
|
|
||
|
|
// WHEN
|
||
|
|
expect(fn () => $executor->execute($action, $input))
|
||
|
|
// THEN
|
||
|
|
->toThrow(\RuntimeException::class, 'Database failure');
|
||
|
|
|
||
|
|
expect($logger->logs)->toHaveCount(2)
|
||
|
|
->and($logger->logs[0])->toContain('Executing')
|
||
|
|
->and($logger->logs[1])->toContain('Failed');
|
||
|
|
});
|
||
|
|
});
|