|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Tests\Http\Client\Common\Plugin; |
| 6 | + |
| 7 | +use Http\Client\Common\Plugin\ThrottlePlugin; |
| 8 | +use Http\Client\Common\PluginClient; |
| 9 | +use Http\Mock\Client; |
| 10 | +use Nyholm\Psr7\Factory\HttplugFactory; |
| 11 | +use Nyholm\Psr7\Request; |
| 12 | +use PHPUnit\Framework\TestCase; |
| 13 | +use Symfony\Bridge\PhpUnit\ClockMock; |
| 14 | +use Symfony\Component\RateLimiter\RateLimit; |
| 15 | +use Symfony\Component\RateLimiter\RateLimiterFactory; |
| 16 | +use Symfony\Component\RateLimiter\Storage\InMemoryStorage; |
| 17 | + |
| 18 | +/** |
| 19 | + * @group time-sensitive |
| 20 | + */ |
| 21 | +class ThrottlePluginTest extends TestCase |
| 22 | +{ |
| 23 | + private Client $mockClient; |
| 24 | + private PluginClient $client; |
| 25 | + |
| 26 | + protected function setUp(): void |
| 27 | + { |
| 28 | + ClockMock::register(RateLimit::class); |
| 29 | + $this->mockClient = new Client(new HttplugFactory()); |
| 30 | + $this->client = new PluginClient($this->mockClient, [ |
| 31 | + new ThrottlePlugin( |
| 32 | + (new RateLimiterFactory( |
| 33 | + ['id' => 'foo', 'policy' => 'fixed_window', 'limit' => 2, 'interval' => '3 seconds'], |
| 34 | + new InMemoryStorage(), |
| 35 | + ))->create(), |
| 36 | + ), |
| 37 | + ]); |
| 38 | + } |
| 39 | + |
| 40 | + public function testNoThrottle(): void |
| 41 | + { |
| 42 | + $time = time(); |
| 43 | + $this->client->sendRequest(new Request('GET', '')); |
| 44 | + $this->client->sendRequest(new Request('GET', '')); |
| 45 | + $this->assertEqualsWithDelta($time, time(), 1); |
| 46 | + } |
| 47 | + |
| 48 | + public function testThrottle(): void |
| 49 | + { |
| 50 | + $time = time(); |
| 51 | + $this->client->sendRequest(new Request('GET', '')); |
| 52 | + $this->client->sendRequest(new Request('GET', '')); |
| 53 | + $this->client->sendRequest(new Request('GET', '')); |
| 54 | + $this->assertEqualsWithDelta($time, ($timeAfterThrottle = time()) - 3, 1); |
| 55 | + |
| 56 | + $this->client->sendRequest(new Request('GET', '')); |
| 57 | + $this->assertEqualsWithDelta($timeAfterThrottle, time(), 1); |
| 58 | + } |
| 59 | +} |
0 commit comments