|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Illuminate\Tests\Integration\Queue; |
| 4 | + |
| 5 | +use Illuminate\Bus\Queueable; |
| 6 | +use Illuminate\Contracts\Queue\ShouldQueue; |
| 7 | +use Illuminate\Foundation\Bus\Dispatchable; |
| 8 | +use Illuminate\Foundation\Testing\RefreshDatabase; |
| 9 | +use Illuminate\Queue\InteractsWithQueue; |
| 10 | +use Illuminate\Queue\Middleware\RetryIf; |
| 11 | +use Illuminate\Support\Facades\Queue; |
| 12 | +use InvalidArgumentException; |
| 13 | +use Orchestra\Testbench\Attributes\WithConfig; |
| 14 | +use PHPUnit\Framework\Attributes\DataProvider; |
| 15 | + |
| 16 | +#[WithConfig('queue.default', 'database')] |
| 17 | +class RetryIfMiddlewareTest extends QueueTestCase |
| 18 | +{ |
| 19 | + use RefreshDatabase; |
| 20 | + |
| 21 | + protected function defineEnvironment($app) |
| 22 | + { |
| 23 | + parent::defineEnvironment($app); |
| 24 | + $this->driver = 'database'; |
| 25 | + } |
| 26 | + |
| 27 | + public static function markFailedForRetryIfDataProvider(): array |
| 28 | + { |
| 29 | + return [ |
| 30 | + 'middleware fails on thrown exception' => [ |
| 31 | + InvalidArgumentException::class, |
| 32 | + 1, |
| 33 | + 1, |
| 34 | + ], |
| 35 | + 'middleware retries if exception does not match' => [ |
| 36 | + \LogicException::class, |
| 37 | + 2, |
| 38 | + 1, |
| 39 | + ], |
| 40 | + ]; |
| 41 | + } |
| 42 | + |
| 43 | + #[DataProvider('markFailedForRetryIfDataProvider')] |
| 44 | + public function test_retry_if_middleware( |
| 45 | + $throws, |
| 46 | + int $expectedExceptions, |
| 47 | + int $expectedFails |
| 48 | + ) { |
| 49 | + RetryIfMiddlewareJob::dispatch($throws)->onQueue('default')->onConnection('database'); |
| 50 | + |
| 51 | + $failsCalled = $exceptionsOccurred = 0; |
| 52 | + Queue::exceptionOccurred(function () use (&$exceptionsOccurred) { |
| 53 | + $exceptionsOccurred++; |
| 54 | + }); |
| 55 | + Queue::failing(function () use (&$failsCalled) { |
| 56 | + $failsCalled++; |
| 57 | + }); |
| 58 | + |
| 59 | + $this->runQueueWorkerCommand(['--stop-when-empty' => true, '--sleep' => 1], 2); |
| 60 | + |
| 61 | + $this->assertEquals($expectedExceptions, $exceptionsOccurred); |
| 62 | + $this->assertEquals($expectedFails, $failsCalled); |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +class RetryIfMiddlewareJob implements ShouldQueue |
| 67 | +{ |
| 68 | + use InteractsWithQueue; |
| 69 | + use Queueable; |
| 70 | + use Dispatchable; |
| 71 | + |
| 72 | + public int $tries = 2; |
| 73 | + |
| 74 | + public function __construct(private $throws) |
| 75 | + { |
| 76 | + } |
| 77 | + |
| 78 | + public function handle() |
| 79 | + { |
| 80 | + if ($this->throws === null) { |
| 81 | + return; // success |
| 82 | + } |
| 83 | + |
| 84 | + throw new ($this->throws); |
| 85 | + } |
| 86 | + |
| 87 | + public function middleware(): array |
| 88 | + { |
| 89 | + return [RetryIf::failForExceptions(InvalidArgumentException::class)]; |
| 90 | + } |
| 91 | +} |
0 commit comments