|
| 1 | +<?php |
| 2 | + |
| 3 | +use ostark\AsyncQueue\BackgroundProcess; |
| 4 | +use PHPUnit\Framework\TestCase; |
| 5 | +use yii\queue\PushEvent; |
| 6 | + |
| 7 | +/** |
| 8 | + * @covers \ostark\AsyncQueue\RateLimiter |
| 9 | + * @covers \ostark\AsyncQueue\Handlers\BackgroundQueueHandler |
| 10 | + */ |
| 11 | +class RateLimiterTest extends TestCase |
| 12 | +{ |
| 13 | + public $plugin; |
| 14 | + |
| 15 | + public function setUp(): void |
| 16 | + { |
| 17 | + parent::setUp(); |
| 18 | + |
| 19 | + $dummyCommand = new \ostark\AsyncQueue\QueueCommand('craft.php', '--sleep'); |
| 20 | + $this->plugin = new \ostark\AsyncQueue\Plugin('async-queue', null, []); |
| 21 | + $this->plugin->set('async_process', new BackgroundProcess($dummyCommand)); |
| 22 | + } |
| 23 | + |
| 24 | + public function tearDown(): void |
| 25 | + { |
| 26 | + parent::tearDown(); |
| 27 | + @unlink(TEST_FILE); |
| 28 | + } |
| 29 | + |
| 30 | + |
| 31 | + public function test_can_setup_handler_and_invoke_event(): void |
| 32 | + { |
| 33 | + $this->plugin = new \ostark\AsyncQueue\Plugin('async-queue', null, []); |
| 34 | + $handler = new \ostark\AsyncQueue\Handlers\BackgroundQueueHandler($this->plugin); |
| 35 | + |
| 36 | + $handler->__invoke(new PushEvent()); |
| 37 | + |
| 38 | + $this->assertSame(1, $this->plugin->getRateLimiter()->getInternalCount()); |
| 39 | + } |
| 40 | + |
| 41 | + public function test_respect_the_limit_when_adding_multiple_jobs_in_one_request(): void |
| 42 | + { |
| 43 | + $handler = new \ostark\AsyncQueue\Handlers\BackgroundQueueHandler($this->plugin); |
| 44 | + |
| 45 | + $handler->__invoke(new PushEvent()); |
| 46 | + $handler->__invoke(new PushEvent()); |
| 47 | + $handler->__invoke(new PushEvent()); |
| 48 | + $handler->__invoke(new PushEvent()); |
| 49 | + |
| 50 | + $this->assertSame( |
| 51 | + $this->plugin->getRateLimiter()->maxItems, |
| 52 | + $this->plugin->getRateLimiter()->getInternalCount() |
| 53 | + ); |
| 54 | + } |
| 55 | + |
| 56 | + public function test_stop_spawning_processes_when_too_many_jobs_are_reserved(): void |
| 57 | + { |
| 58 | + // Fake the reserved count |
| 59 | + $queue = new class extends \craft\queue\Queue { |
| 60 | + public function getTotalReserved(): int |
| 61 | + { |
| 62 | + return 5; |
| 63 | + } |
| 64 | + }; |
| 65 | + |
| 66 | + $this->plugin->set('async_rate_limiter', new \ostark\AsyncQueue\RateLimiter($queue, $this->plugin->getSettings())); |
| 67 | + $handler = new \ostark\AsyncQueue\Handlers\BackgroundQueueHandler($this->plugin); |
| 68 | + |
| 69 | + $handler->__invoke(new PushEvent()); |
| 70 | + |
| 71 | + $this->assertSame(0, $this->plugin->getRateLimiter()->getInternalCount()); |
| 72 | + } |
| 73 | +} |
0 commit comments