Skip to content

Instantly share code, notes, and snippets.

@agm1984
Last active Jul 10, 2020
Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

@agm1984 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