ThrottleRequestsWithRedisTest.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. namespace Illuminate\Tests\Integration\Http;
  3. use Illuminate\Foundation\Testing\Concerns\InteractsWithRedis;
  4. use Illuminate\Routing\Middleware\ThrottleRequestsWithRedis;
  5. use Illuminate\Support\Carbon;
  6. use Illuminate\Support\Facades\Route;
  7. use Orchestra\Testbench\TestCase;
  8. use Throwable;
  9. class ThrottleRequestsWithRedisTest extends TestCase
  10. {
  11. use InteractsWithRedis;
  12. protected function tearDown(): void
  13. {
  14. parent::tearDown();
  15. Carbon::setTestNow(null);
  16. }
  17. public function getEnvironmentSetUp($app)
  18. {
  19. $app['config']->set('hashing', ['driver' => 'bcrypt']);
  20. }
  21. public function testLockOpensImmediatelyAfterDecay()
  22. {
  23. $this->ifRedisAvailable(function () {
  24. $now = Carbon::now();
  25. Carbon::setTestNow($now);
  26. Route::get('/', function () {
  27. return 'yes';
  28. })->middleware(ThrottleRequestsWithRedis::class.':2,1');
  29. $response = $this->withoutExceptionHandling()->get('/');
  30. $this->assertSame('yes', $response->getContent());
  31. $this->assertEquals(2, $response->headers->get('X-RateLimit-Limit'));
  32. $this->assertEquals(1, $response->headers->get('X-RateLimit-Remaining'));
  33. $response = $this->withoutExceptionHandling()->get('/');
  34. $this->assertSame('yes', $response->getContent());
  35. $this->assertEquals(2, $response->headers->get('X-RateLimit-Limit'));
  36. $this->assertEquals(0, $response->headers->get('X-RateLimit-Remaining'));
  37. Carbon::setTestNow($finish = $now->addSeconds(58));
  38. try {
  39. $this->withoutExceptionHandling()->get('/');
  40. } catch (Throwable $e) {
  41. $this->assertEquals(429, $e->getStatusCode());
  42. $this->assertEquals(2, $e->getHeaders()['X-RateLimit-Limit']);
  43. $this->assertEquals(0, $e->getHeaders()['X-RateLimit-Remaining']);
  44. // $this->assertTrue(in_array($e->getHeaders()['Retry-After'], [2, 3]));
  45. // $this->assertTrue(in_array($e->getHeaders()['X-RateLimit-Reset'], [$finish->getTimestamp() + 2, $finish->getTimestamp() + 3]));
  46. }
  47. });
  48. }
  49. }