AbstractRequestRateLimiterTest.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\HttpFoundation\Tests\RateLimiter;
  11. use PHPUnit\Framework\TestCase;
  12. use Symfony\Component\HttpFoundation\Request;
  13. use Symfony\Component\RateLimiter\LimiterInterface;
  14. use Symfony\Component\RateLimiter\RateLimit;
  15. class AbstractRequestRateLimiterTest extends TestCase
  16. {
  17. /**
  18. * @dataProvider provideRateLimits
  19. */
  20. public function testConsume(array $rateLimits, ?RateLimit $expected)
  21. {
  22. $rateLimiter = new MockAbstractRequestRateLimiter(array_map(function (RateLimit $rateLimit) {
  23. $limiter = $this->createStub(LimiterInterface::class);
  24. $limiter->method('consume')->willReturn($rateLimit);
  25. return $limiter;
  26. }, $rateLimits));
  27. $this->assertSame($expected, $rateLimiter->consume(new Request()));
  28. }
  29. public static function provideRateLimits()
  30. {
  31. $now = new \DateTimeImmutable();
  32. yield 'Both accepted with different count of remaining tokens' => [
  33. [
  34. $expected = new RateLimit(0, $now, true, 1), // less remaining tokens
  35. new RateLimit(1, $now, true, 1),
  36. ],
  37. $expected,
  38. ];
  39. yield 'Both accepted with same count of remaining tokens' => [
  40. [
  41. $expected = new RateLimit(0, $now->add(new \DateInterval('P1D')), true, 1), // longest wait time
  42. new RateLimit(0, $now, true, 1),
  43. ],
  44. $expected,
  45. ];
  46. yield 'Accepted and denied' => [
  47. [
  48. new RateLimit(0, $now, true, 1),
  49. $expected = new RateLimit(0, $now, false, 1), // denied
  50. ],
  51. $expected,
  52. ];
  53. }
  54. }