Skip to content

Instantly share code, notes, and snippets.

@agm1984
Last active July 10, 2020 03:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save agm1984/c96b4562a489c3a1721273465c42dc0f to your computer and use it in GitHub Desktop.
Save agm1984/c96b4562a489c3a1721273465c42dc0f to your computer and use it in GitHub Desktop.
Demonstration of `resetAuth` function
<?php
namespace Tests\Auth;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Tests\TestCase;
class LoginTest extends TestCase
{
use DatabaseTransactions, ThrottlesLogins;
protected $auth_guard = 'web';
// ...
/** @test */
public function it_should_throw_error_422_with_empty_form()
{
$this->postJson(route('login'), ['email' => '', 'password' => ''])
->assertStatus(422)
->assertJsonStructure(['message', 'errors' => ['email', 'password']]);
$this->assertGuest($this->auth_guard);
$this->resetAuth();
}
/** @test */
public function it_should_throw_error_429_when_login_attempt_is_throttled()
{
$throttledUser = factory(User::class, 1)->create()->first();
// corresponds to `Route::group(['middleware' => ['guest', 'throttle:10,5']], function () {`
// ie: 10 attempts allowed per minute, with 5 minute cooldown
foreach (range(0, 9) as $attempt) {
$this->postJson(route('login'), ['email' => $throttledUser->email, 'password' => "{TestCase::AUTH_PASSWORD}_{$attempt}"]);
}
$this->postJson(route('login'), ['email' => $throttledUser->email, 'password' => TestCase::AUTH_PASSWORD . '6'])
->assertStatus(429)
->assertJson(['message' => 'Too Many Attempts.']);
$this->resetAuth();
}
}
@agm1984
Copy link
Author

agm1984 commented Jul 10, 2020

/**
 * When making multiple requests in one test, the state of the Laravel API would not reset between the requests.
 * The AuthManager is a singleton in the laravel container, and it keeps a local cache of the resolved auth guards.
 * `$this->resetAuth()` is used to reset any session-remnants between unit tests.
 * Theory: https://stackoverflow.com/a/57941133/6141025
 */

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment