|
| 1 | +<?php |
| 2 | + |
| 3 | +/* |
| 4 | + * This file is part of the Symfony package. |
| 5 | + * |
| 6 | + * (c) Fabien Potencier <fabien@symfony.com> |
| 7 | + * |
| 8 | + * For the full copyright and license information, please view the LICENSE |
| 9 | + * file that was distributed with this source code. |
| 10 | + */ |
| 11 | + |
| 12 | +namespace Symfony\Component\RateLimiter\Tests; |
| 13 | + |
| 14 | +use PHPUnit\Framework\TestCase; |
| 15 | +use Symfony\Component\OptionsResolver\Exception\MissingOptionsException; |
| 16 | +use Symfony\Component\RateLimiter\FixedWindowLimiter; |
| 17 | +use Symfony\Component\RateLimiter\NoLimiter; |
| 18 | +use Symfony\Component\RateLimiter\RateLimiter; |
| 19 | +use Symfony\Component\RateLimiter\SlidingWindowLimiter; |
| 20 | +use Symfony\Component\RateLimiter\Storage\InMemoryStorage; |
| 21 | +use Symfony\Component\RateLimiter\TokenBucketLimiter; |
| 22 | + |
| 23 | +class RateLimiterTest extends TestCase |
| 24 | +{ |
| 25 | + /** |
| 26 | + * @dataProvider validConfigProvider |
| 27 | + */ |
| 28 | + public function testValidConfig(string $expectedClass, array $config) |
| 29 | + { |
| 30 | + $factory = new RateLimiter($config, new InMemoryStorage()); |
| 31 | + $rateLimiter = $factory->create('key'); |
| 32 | + $this->assertInstanceOf($expectedClass, $rateLimiter); |
| 33 | + } |
| 34 | + |
| 35 | + public function validConfigProvider() |
| 36 | + { |
| 37 | + yield [TokenBucketLimiter::class, [ |
| 38 | + 'strategy' => 'token_bucket', |
| 39 | + 'id' => 'test', |
| 40 | + 'limit' => 5, |
| 41 | + 'rate' => [ |
| 42 | + 'interval' => '5 seconds', |
| 43 | + ], |
| 44 | + ]]; |
| 45 | + yield [FixedWindowLimiter::class, [ |
| 46 | + 'strategy' => 'fixed_window', |
| 47 | + 'id' => 'test', |
| 48 | + 'limit' => 5, |
| 49 | + 'interval' => '5 seconds', |
| 50 | + ]]; |
| 51 | + yield [SlidingWindowLimiter::class, [ |
| 52 | + 'strategy' => 'sliding_window', |
| 53 | + 'id' => 'test', |
| 54 | + 'limit' => 5, |
| 55 | + 'interval' => '5 seconds', |
| 56 | + ]]; |
| 57 | + yield [NoLimiter::class, [ |
| 58 | + 'strategy' => 'no_limit', |
| 59 | + 'id' => 'test', |
| 60 | + ]]; |
| 61 | + } |
| 62 | + |
| 63 | + /** |
| 64 | + * @dataProvider invalidConfigProvider |
| 65 | + */ |
| 66 | + public function testInvalidConfig(string $exceptionClass, array $config) |
| 67 | + { |
| 68 | + $this->expectException($exceptionClass); |
| 69 | + $factory = new RateLimiter($config, new InMemoryStorage()); |
| 70 | + $factory->create('key'); |
| 71 | + } |
| 72 | + |
| 73 | + public function invalidConfigProvider() |
| 74 | + { |
| 75 | + yield [MissingOptionsException::class, [ |
| 76 | + 'strategy' => 'token_bucket', |
| 77 | + ]]; |
| 78 | + } |
| 79 | +} |
0 commit comments