Search code examples
laravelphpunitlaravel-8laravel-testing

Laravel testing - 429 Too Many Requests


As I move forward in my Laravel project I have several tests for controllers and now I'm facing with this issue.

Some of my tests are failing with this message:

Expected response status code [200] but received 429.
Failed asserting that 200 is identical to 429.

I tried to solve with these methods:

  1. Add withoutMiddleware() to TestCase.php:
public function setUp(): void
{
    parent::setUp();

    $this->withoutMiddleware(
        ThrottleRequests::class
    );
}
  1. Add REQUESTS_PER_MINUTE to phpunit.xml:
<phpunit>
  <php>
    ...
    <server name="REQUESTS_PER_MINUTE" value="500"/>
  </php>
</phpunit>
  1. Change my dockerized nginx config for this:
server {
    location ~ \.php$ {
        limit_req zone=one burst=5;
    }
}
limit_req_zone  $binary_remote_addr  zone=one:10m   rate=100r/s;

Neither solution helped.

I don't want to change the Laravel's throttle settings only because of testing. I think here need to be a valid solution for this without changing the framework's settings.

Any suggestion how can I solve this issue?


Solution

  • Frank's solution works but makes not possible to use named limiters. Code below passes correct arguments list and allow to detect named limiters

    <?php
    
    namespace App\Http\Middleware;
    
    use Closure;
    use Illuminate\Routing\Middleware\ThrottleRequestsWithRedis;
    
    class ThrottleRequests extends ThrottleRequestsWithRedis
    {
        public function handle($request, Closure $next, $maxAttempts = 60, $decayMinutes = 1, $prefix = '')
        {
            if (app()->environment('production')) {
                return parent::handle(...func_get_args());
            }
    
            return $next($request);
        }
    }