From 217e8a2bc5aa6a827ced97fcb76504029d3115d7 Mon Sep 17 00:00:00 2001 From: Mior Muhammad Zaki Date: Tue, 22 Aug 2023 21:21:11 +0800 Subject: [PATCH] [3.x] Test Improvements (#465) * Test Improvements Signed-off-by: Mior Muhammad Zaki * wip Signed-off-by: Mior Muhammad Zaki * wip Signed-off-by: Mior Muhammad Zaki * Apply fixes from StyleCI * wip Signed-off-by: Mior Muhammad Zaki * wip --------- Signed-off-by: Mior Muhammad Zaki Co-authored-by: StyleCI Bot --- .gitattributes | 1 + composer.json | 4 +- tests/Feature/ActingAsTest.php | 23 +- .../DefaultConfigContainsAppUrlTest.php | 8 +- tests/Feature/GuardTest.php | 223 ++++-------------- tests/Feature/PruneExpiredTest.php | 78 ++---- workbench/app/Models/User.php | 42 ++++ .../factories/PersonalAccessTokenFactory.php | 37 +++ workbench/database/factories/UserFactory.php | 21 ++ 9 files changed, 189 insertions(+), 248 deletions(-) create mode 100644 workbench/app/Models/User.php create mode 100644 workbench/database/factories/PersonalAccessTokenFactory.php create mode 100644 workbench/database/factories/UserFactory.php diff --git a/.gitattributes b/.gitattributes index 6c56d0f..2227e2c 100644 --- a/.gitattributes +++ b/.gitattributes @@ -9,6 +9,7 @@ /.github export-ignore /art export-ignore /tests export-ignore +/workbench export-ignore .editorconfig export-ignore .gitattributes export-ignore .gitignore export-ignore diff --git a/composer.json b/composer.json index a1a2ebc..a117949 100644 --- a/composer.json +++ b/composer.json @@ -34,7 +34,9 @@ }, "autoload-dev": { "psr-4": { - "Laravel\\Sanctum\\Tests\\": "tests/" + "Laravel\\Sanctum\\Tests\\": "tests/", + "Workbench\\App\\": "workbench/app/", + "Workbench\\Database\\Factories\\": "workbench/database/factories/" } }, "extra": { diff --git a/tests/Feature/ActingAsTest.php b/tests/Feature/ActingAsTest.php index 5d4fcf7..9c240b5 100644 --- a/tests/Feature/ActingAsTest.php +++ b/tests/Feature/ActingAsTest.php @@ -2,11 +2,8 @@ namespace Laravel\Sanctum\Tests\Feature; -use Illuminate\Foundation\Auth\User; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Route; -use Laravel\Sanctum\Contracts\HasApiTokens as HasApiTokensContract; -use Laravel\Sanctum\HasApiTokens; use Laravel\Sanctum\Http\Middleware\CheckAbilities; use Laravel\Sanctum\Http\Middleware\CheckForAnyAbility; use Laravel\Sanctum\Http\Middleware\CheckForAnyScope; @@ -14,6 +11,7 @@ use Laravel\Sanctum\Sanctum; use Orchestra\Testbench\Concerns\WithWorkbench; use Orchestra\Testbench\TestCase; +use Workbench\App\Models\User; class ActingAsTest extends TestCase { @@ -32,7 +30,7 @@ public function testActingAsWhenTheRouteIsProtectedByAuthMiddlware() return 'bar'; })->middleware('auth:sanctum'); - Sanctum::actingAs($user = new SanctumUser); + Sanctum::actingAs($user = new User); $user->id = 1; $response = $this->get('/foo'); @@ -49,7 +47,7 @@ public function testActingAsWhenTheRouteIsProtectedByCheckScopesMiddleware() return 'bar'; })->middleware(CheckScopes::class.':admin,footest'); - Sanctum::actingAs(new SanctumUser(), ['admin', 'footest']); + Sanctum::actingAs(new User(), ['admin', 'footest']); $response = $this->get('/foo'); $response->assertSuccessful(); @@ -64,7 +62,7 @@ public function testActingAsWhenTheRouteIsProtectedByCheckForAnyScopeMiddleware( return 'bar'; })->middleware(CheckForAnyScope::class.':admin,footest'); - Sanctum::actingAs(new SanctumUser(), ['footest']); + Sanctum::actingAs(new User(), ['footest']); $response = $this->get('/foo'); $response->assertSuccessful(); @@ -79,7 +77,7 @@ public function testActingAsWhenTheRouteIsProtectedByCheckAbilitiesMiddleware() return 'bar'; })->middleware(CheckAbilities::class.':admin,footest'); - Sanctum::actingAs(new SanctumUser(), ['admin', 'footest']); + Sanctum::actingAs(new User(), ['admin', 'footest']); $response = $this->get('/foo'); $response->assertSuccessful(); @@ -94,7 +92,7 @@ public function testActingAsWhenTheRouteIsProtectedByCheckForAnyAbilityMiddlewar return 'bar'; })->middleware(CheckForAnyAbility::class.':admin,footest'); - Sanctum::actingAs(new SanctumUser(), ['footest']); + Sanctum::actingAs(new User(), ['footest']); $response = $this->get('/foo'); $response->assertSuccessful(); @@ -115,7 +113,7 @@ public function testActingAsWhenTheRouteIsProtectedUsingAbilities() return response(403); })->middleware('auth:sanctum'); - $user = new SanctumUser; + $user = new User; $user->id = 1; Sanctum::actingAs($user, ['baz']); @@ -140,7 +138,7 @@ public function testActingAsWhenKeyHasAnyAbility() return response(403); })->middleware('auth:sanctum'); - $user = new SanctumUser; + $user = new User; $user->id = 1; Sanctum::actingAs($user, ['*']); @@ -151,8 +149,3 @@ public function testActingAsWhenKeyHasAnyAbility() $response->assertSee('bar'); } } - -class SanctumUser extends User implements HasApiTokensContract -{ - use HasApiTokens; -} diff --git a/tests/Feature/DefaultConfigContainsAppUrlTest.php b/tests/Feature/DefaultConfigContainsAppUrlTest.php index 1679373..0bb6f60 100644 --- a/tests/Feature/DefaultConfigContainsAppUrlTest.php +++ b/tests/Feature/DefaultConfigContainsAppUrlTest.php @@ -7,6 +7,8 @@ use Orchestra\Testbench\Concerns\WithWorkbench; use Orchestra\Testbench\TestCase; +use function Orchestra\Testbench\package_path; + class DefaultConfigContainsAppUrlTest extends TestCase { use WithWorkbench; @@ -16,14 +18,14 @@ protected function defineEnvironment($app) putenv('APP_URL=https://www.example.com'); $app['config']->set('app.url', 'https://www.example.com'); - $config = require __DIR__.'/../../config/sanctum.php'; + $config = require package_path('config/sanctum.php'); $app['config']->set('sanctum.stateful', $config['stateful']); } public function test_default_config_contains_app_url() { - $config = require __DIR__.'/../../config/sanctum.php'; + $config = require package_path('config/sanctum.php'); $app_host = parse_url(env('APP_URL'), PHP_URL_HOST); @@ -35,7 +37,7 @@ public function test_app_url_is_not_parsed_when_missing_from_env() putenv('APP_URL'); config(['app.url' => null]); - $config = require __DIR__.'/../../config/sanctum.php'; + $config = require package_path('config/sanctum.php'); $this->assertNull(env('APP_URL')); $this->assertNotContains('', $config['stateful']); diff --git a/tests/Feature/GuardTest.php b/tests/Feature/GuardTest.php index 8b5f41b..ab0102e 100644 --- a/tests/Feature/GuardTest.php +++ b/tests/Feature/GuardTest.php @@ -5,28 +5,32 @@ use DateTimeInterface; use Illuminate\Auth\EloquentUserProvider; use Illuminate\Contracts\Auth\Factory as AuthFactory; -use Illuminate\Database\Eloquent\Model; +use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Http\Request; use Illuminate\Support\Facades\Event; -use Illuminate\Support\Str; -use Laravel\Sanctum\Contracts\HasApiTokens as HasApiTokensContract; use Laravel\Sanctum\Events\TokenAuthenticated; use Laravel\Sanctum\Guard; -use Laravel\Sanctum\HasApiTokens; use Laravel\Sanctum\PersonalAccessToken; use Laravel\Sanctum\Sanctum; use Mockery; use Orchestra\Testbench\Concerns\WithWorkbench; use Orchestra\Testbench\TestCase; use stdClass; +use Workbench\App\Models\User; +use Workbench\Database\Factories\PersonalAccessTokenFactory; +use Workbench\Database\Factories\UserFactory; class GuardTest extends TestCase { - use WithWorkbench; + use RefreshDatabase, WithWorkbench; protected function defineEnvironment($app) { - $app['config']->set('database.default', 'testing'); + $app['config']->set([ + 'auth.guards.sanctum.provider' => 'users', + 'auth.providers.users.model' => User::class, + 'database.default' => 'testing', + ]); } public function test_authentication_is_attempted_with_web_middleware() @@ -51,8 +55,6 @@ public function test_authentication_is_attempted_with_web_middleware() public function test_authentication_is_attempted_with_token_if_no_session_present() { - $this->artisan('migrate', ['--database' => 'testing'])->run(); - $factory = Mockery::mock(AuthFactory::class); $guard = new Guard($factory, null, 'users'); @@ -75,9 +77,6 @@ public function test_authentication_is_attempted_with_token_if_no_session_presen public function test_authentication_with_token_fails_if_expired() { - $this->loadLaravelMigrations(['--database' => 'testing']); - $this->artisan('migrate', ['--database' => 'testing'])->run(); - $factory = Mockery::mock(AuthFactory::class); $guard = new Guard($factory, 1, 'users'); @@ -93,18 +92,10 @@ public function test_authentication_with_token_fails_if_expired() $request = Request::create('/', 'GET'); $request->headers->set('Authorization', 'Bearer test'); - $user = User::forceCreate([ - 'name' => 'Taylor Otwell', - 'email' => 'taylor@laravel.com', - 'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', - 'remember_token' => Str::random(10), - ]); - - $token = PersonalAccessToken::forceCreate([ - 'tokenable_id' => $user->id, - 'tokenable_type' => get_class($user), + PersonalAccessTokenFactory::new()->for( + $user = UserFactory::new()->create(), 'tokenable' + )->create([ 'name' => 'Test', - 'token' => hash('sha256', 'test'), 'created_at' => now()->subMinutes(60), ]); @@ -115,9 +106,6 @@ public function test_authentication_with_token_fails_if_expired() public function test_authentication_with_token_fails_if_expires_at_has_passed() { - $this->loadLaravelMigrations(['--database' => 'testing']); - $this->artisan('migrate', ['--database' => 'testing'])->run(); - $factory = Mockery::mock(AuthFactory::class); $guard = new Guard($factory, null, 'users'); @@ -133,18 +121,10 @@ public function test_authentication_with_token_fails_if_expires_at_has_passed() $request = Request::create('/', 'GET'); $request->headers->set('Authorization', 'Bearer test'); - $user = User::forceCreate([ - 'name' => 'Taylor Otwell', - 'email' => 'taylor@laravel.com', - 'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', - 'remember_token' => Str::random(10), - ]); - - $token = PersonalAccessToken::forceCreate([ - 'tokenable_id' => $user->id, - 'tokenable_type' => get_class($user), + PersonalAccessTokenFactory::new()->for( + $user = UserFactory::new()->create(), 'tokenable' + )->create([ 'name' => 'Test', - 'token' => hash('sha256', 'test'), 'expires_at' => now()->subMinutes(60), ]); @@ -155,9 +135,6 @@ public function test_authentication_with_token_fails_if_expires_at_has_passed() public function test_authentication_with_token_succeeds_if_expires_at_not_passed() { - $this->loadLaravelMigrations(['--database' => 'testing']); - $this->artisan('migrate', ['--database' => 'testing'])->run(); - $factory = Mockery::mock(AuthFactory::class); $guard = new Guard($factory, null, 'users'); @@ -173,31 +150,22 @@ public function test_authentication_with_token_succeeds_if_expires_at_not_passed $request = Request::create('/', 'GET'); $request->headers->set('Authorization', 'Bearer test'); - $user = User::forceCreate([ - 'name' => 'Taylor Otwell', - 'email' => 'taylor@laravel.com', - 'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', - 'remember_token' => Str::random(10), - ]); - - $token = PersonalAccessToken::forceCreate([ - 'tokenable_id' => $user->id, - 'tokenable_type' => get_class($user), + $token = PersonalAccessTokenFactory::new()->for( + $user = UserFactory::new()->create(), 'tokenable' + )->create([ 'name' => 'Test', - 'token' => hash('sha256', 'test'), 'expires_at' => now()->addMinutes(60), ]); - $user = $guard->__invoke($request); + $returnedUser = $guard->__invoke($request); - $this->assertNull($user); + $this->assertEquals($user->id, $returnedUser->id); + $this->assertEquals($token->id, $returnedUser->currentAccessToken()->id); + $this->assertInstanceOf(DateTimeInterface::class, $returnedUser->currentAccessToken()->last_used_at); } public function test_authentication_is_successful_with_token_if_no_session_present() { - $this->loadLaravelMigrations(['--database' => 'testing']); - $this->artisan('migrate', ['--database' => 'testing'])->run(); - $factory = Mockery::mock(AuthFactory::class); $guard = new Guard($factory, null); @@ -213,18 +181,10 @@ public function test_authentication_is_successful_with_token_if_no_session_prese $request = Request::create('/', 'GET'); $request->headers->set('Authorization', 'Bearer test'); - $user = User::forceCreate([ - 'name' => 'Taylor Otwell', - 'email' => 'taylor@laravel.com', - 'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', - 'remember_token' => Str::random(10), - ]); - - $token = PersonalAccessToken::forceCreate([ - 'tokenable_id' => $user->id, - 'tokenable_type' => get_class($user), + $token = PersonalAccessTokenFactory::new()->for( + $user = UserFactory::new()->create(), 'tokenable' + )->create([ 'name' => 'Test', - 'token' => hash('sha256', 'test'), ]); $returnedUser = $guard->__invoke($request); @@ -236,10 +196,6 @@ public function test_authentication_is_successful_with_token_if_no_session_prese public function test_authentication_with_token_fails_if_user_provider_is_invalid() { - $this->loadLaravelMigrations(['--database' => 'testing']); - $this->artisan('migrate', ['--database' => 'testing'])->run(); - - config(['auth.guards.sanctum.provider' => 'users']); config(['auth.providers.users.model' => 'App\Models\User']); $factory = $this->app->make(AuthFactory::class); @@ -252,18 +208,10 @@ public function test_authentication_with_token_fails_if_user_provider_is_invalid $request = Request::create('/', 'GET'); $request->headers->set('Authorization', 'Bearer test'); - $user = User::forceCreate([ - 'name' => 'Taylor Otwell', - 'email' => 'taylor@laravel.com', - 'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', - 'remember_token' => Str::random(10), - ]); - - $token = PersonalAccessToken::forceCreate([ - 'tokenable_id' => $user->id, - 'tokenable_type' => get_class($user), + PersonalAccessTokenFactory::new()->for( + UserFactory::new(), 'tokenable' + )->create([ 'name' => 'Test', - 'token' => hash('sha256', 'test'), ]); $returnedUser = $requestGuard->setRequest($request)->user(); @@ -278,9 +226,6 @@ public function test_authentication_with_token_fails_if_user_provider_is_invalid */ public function test_authentication_with_token_fails_if_token_has_invalid_format($invalidToken) { - $this->loadLaravelMigrations(['--database' => 'testing']); - $this->artisan('migrate', ['--database' => 'testing'])->run(); - $factory = Mockery::mock(AuthFactory::class); $guard = new Guard($factory, null, 'users'); @@ -295,18 +240,10 @@ public function test_authentication_with_token_fails_if_token_has_invalid_format $request = Request::create('/', 'GET'); - $user = User::forceCreate([ - 'name' => 'Taylor Otwell', - 'email' => 'taylor@laravel.com', - 'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', - 'remember_token' => Str::random(10), - ]); - - PersonalAccessToken::forceCreate([ - 'tokenable_id' => $user->id, - 'tokenable_type' => get_class($user), + PersonalAccessTokenFactory::new()->for( + UserFactory::new(), 'tokenable' + )->create([ 'name' => 'Test', - 'token' => hash('sha256', 'test'), 'expires_at' => now()->subMinutes(60), ]); @@ -317,12 +254,6 @@ public function test_authentication_with_token_fails_if_token_has_invalid_format public function test_authentication_is_successful_with_token_if_user_provider_is_valid() { - $this->loadLaravelMigrations(['--database' => 'testing']); - $this->artisan('migrate', ['--database' => 'testing'])->run(); - - config(['auth.guards.sanctum.provider' => 'users']); - config(['auth.providers.users.model' => User::class]); - $factory = $this->app->make(AuthFactory::class); $requestGuard = $factory->guard('sanctum'); @@ -333,18 +264,10 @@ public function test_authentication_is_successful_with_token_if_user_provider_is $request = Request::create('/', 'GET'); $request->headers->set('Authorization', 'Bearer test'); - $user = User::forceCreate([ - 'name' => 'Taylor Otwell', - 'email' => 'taylor@laravel.com', - 'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', - 'remember_token' => Str::random(10), - ]); - - $token = PersonalAccessToken::forceCreate([ - 'tokenable_id' => $user->id, - 'tokenable_type' => get_class($user), + PersonalAccessTokenFactory::new()->for( + $user = UserFactory::new()->create(), 'tokenable' + )->create([ 'name' => 'Test', - 'token' => hash('sha256', 'test'), ]); $returnedUser = $requestGuard->setRequest($request)->user(); @@ -356,30 +279,16 @@ public function test_authentication_is_successful_with_token_if_user_provider_is public function test_authentication_fails_if_callback_returns_false() { - $this->loadLaravelMigrations(['--database' => 'testing']); - $this->artisan('migrate', ['--database' => 'testing'])->run(); - - config(['auth.guards.sanctum.provider' => 'users']); - config(['auth.providers.users.model' => User::class]); - $factory = $this->app->make(AuthFactory::class); $requestGuard = $factory->guard('sanctum'); $request = Request::create('/', 'GET'); $request->headers->set('Authorization', 'Bearer test'); - $user = User::forceCreate([ - 'name' => 'Taylor Otwell', - 'email' => 'taylor@laravel.com', - 'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', - 'remember_token' => Str::random(10), - ]); - - $token = PersonalAccessToken::forceCreate([ - 'tokenable_id' => $user->id, - 'tokenable_type' => get_class($user), + PersonalAccessTokenFactory::new()->for( + $user = UserFactory::new()->create(), 'tokenable' + )->create([ 'name' => 'Test', - 'token' => hash('sha256', 'test'), ]); Sanctum::authenticateAccessTokensUsing(function ($accessToken, bool $isValid) { @@ -397,9 +306,6 @@ public function test_authentication_fails_if_callback_returns_false() public function test_authentication_is_successful_with_token_in_custom_header() { - $this->loadLaravelMigrations(['--database' => 'testing']); - $this->artisan('migrate', ['--database' => 'testing'])->run(); - $factory = Mockery::mock(AuthFactory::class); $guard = new Guard($factory, null); @@ -415,18 +321,10 @@ public function test_authentication_is_successful_with_token_in_custom_header() $request = Request::create('/', 'GET'); $request->headers->set('X-Auth-Token', 'test'); - $user = User::forceCreate([ - 'name' => 'Taylor Otwell', - 'email' => 'taylor@laravel.com', - 'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', - 'remember_token' => Str::random(10), - ]); - - $token = PersonalAccessToken::forceCreate([ - 'tokenable_id' => $user->id, - 'tokenable_type' => get_class($user), + $token = PersonalAccessTokenFactory::new()->for( + $user = UserFactory::new()->create(), 'tokenable' + )->create([ 'name' => 'Test', - 'token' => hash('sha256', 'test'), ]); Sanctum::getAccessTokenFromRequestUsing(function (Request $request) { @@ -444,9 +342,6 @@ public function test_authentication_is_successful_with_token_in_custom_header() public function test_authentication_fails_with_token_in_authorization_header_when_using_custom_header() { - $this->loadLaravelMigrations(['--database' => 'testing']); - $this->artisan('migrate', ['--database' => 'testing'])->run(); - $factory = Mockery::mock(AuthFactory::class); $guard = new Guard($factory, null); @@ -462,18 +357,10 @@ public function test_authentication_fails_with_token_in_authorization_header_whe $request = Request::create('/', 'GET'); $request->headers->set('Authorization', 'Bearer test'); - $user = User::forceCreate([ - 'name' => 'Taylor Otwell', - 'email' => 'taylor@laravel.com', - 'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', - 'remember_token' => Str::random(10), - ]); - - $token = PersonalAccessToken::forceCreate([ - 'tokenable_id' => $user->id, - 'tokenable_type' => get_class($user), + PersonalAccessTokenFactory::new()->for( + UserFactory::new(), 'tokenable' + )->create([ 'name' => 'Test', - 'token' => hash('sha256', 'test'), ]); Sanctum::getAccessTokenFromRequestUsing(function (Request $request) { @@ -489,9 +376,6 @@ public function test_authentication_fails_with_token_in_authorization_header_whe public function test_authentication_fails_with_token_in_custom_header_when_using_default_authorization_header() { - $this->loadLaravelMigrations(['--database' => 'testing']); - $this->artisan('migrate', ['--database' => 'testing'])->run(); - $factory = Mockery::mock(AuthFactory::class); $guard = new Guard($factory, null); @@ -507,18 +391,10 @@ public function test_authentication_fails_with_token_in_custom_header_when_using $request = Request::create('/', 'GET'); $request->headers->set('X-Auth-Token', 'test'); - $user = User::forceCreate([ - 'name' => 'Taylor Otwell', - 'email' => 'taylor@laravel.com', - 'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', - 'remember_token' => Str::random(10), - ]); - - $token = PersonalAccessToken::forceCreate([ - 'tokenable_id' => $user->id, - 'tokenable_type' => get_class($user), + PersonalAccessTokenFactory::new()->for( + UserFactory::new(), 'tokenable' + )->create([ 'name' => 'Test', - 'token' => hash('sha256', 'test'), ]); $returnedUser = $guard->__invoke($request); @@ -544,8 +420,3 @@ public static function invalidTokenDataProvider(): array ]; } } - -class User extends Model implements HasApiTokensContract -{ - use HasApiTokens; -} diff --git a/tests/Feature/PruneExpiredTest.php b/tests/Feature/PruneExpiredTest.php index f9787c3..2c4ac36 100644 --- a/tests/Feature/PruneExpiredTest.php +++ b/tests/Feature/PruneExpiredTest.php @@ -2,13 +2,11 @@ namespace Laravel\Sanctum\Tests\Feature; -use Illuminate\Foundation\Auth\User; use Illuminate\Foundation\Testing\RefreshDatabase; -use Laravel\Sanctum\Contracts\HasApiTokens as HasApiTokensContract; -use Laravel\Sanctum\HasApiTokens; -use Laravel\Sanctum\PersonalAccessToken; use Orchestra\Testbench\Concerns\WithWorkbench; use Orchestra\Testbench\TestCase; +use Workbench\Database\Factories\PersonalAccessTokenFactory; +use Workbench\Database\Factories\UserFactory; class PruneExpiredTest extends TestCase { @@ -19,40 +17,31 @@ protected function defineEnvironment($app) $app['config']->set('database.default', 'testing'); } - protected function defineDatabaseMigrations() - { - $this->loadLaravelMigrations(); - } - public function test_can_delete_expired_tokens_with_integer_expiration() { config(['sanctum.expiration' => 60]); - $user = UserForPruneExpiredTest::forceCreate([ - 'name' => 'Taylor Otwell', - 'email' => 'taylor@laravel.com', - 'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', - ]); + $user = UserFactory::new()->create(); - $token_1 = PersonalAccessToken::forceCreate([ - 'tokenable_id' => $user->id, - 'tokenable_type' => get_class($user), + $token_1 = PersonalAccessTokenFactory::new()->for( + $user, 'tokenable' + )->create([ 'name' => 'Test_1', 'token' => hash('sha256', 'test_1'), 'created_at' => now()->subMinutes(181), ]); - $token_2 = PersonalAccessToken::forceCreate([ - 'tokenable_id' => $user->id, - 'tokenable_type' => get_class($user), + $token_2 = PersonalAccessTokenFactory::new()->for( + $user, 'tokenable' + )->create([ 'name' => 'Test_2', 'token' => hash('sha256', 'test_2'), 'created_at' => now()->subMinutes(179), ]); - $token_3 = PersonalAccessToken::forceCreate([ - 'tokenable_id' => $user->id, - 'tokenable_type' => get_class($user), + $token_3 = PersonalAccessTokenFactory::new()->for( + $user, 'tokenable' + )->create([ 'name' => 'Test_3', 'token' => hash('sha256', 'test_3'), 'created_at' => now()->subMinutes(121), @@ -70,15 +59,9 @@ public function test_cant_delete_expired_tokens_with_null_expiration() { config(['sanctum.expiration' => null]); - $user = UserForPruneExpiredTest::forceCreate([ - 'name' => 'Taylor Otwell', - 'email' => 'taylor@laravel.com', - 'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', - ]); - - $token = PersonalAccessToken::forceCreate([ - 'tokenable_id' => $user->id, - 'tokenable_type' => get_class($user), + $token = PersonalAccessTokenFactory::new()->for( + UserFactory::new(), 'tokenable' + )->create([ 'name' => 'Test', 'token' => hash('sha256', 'test'), 'created_at' => now()->subMinutes(70), @@ -94,31 +77,27 @@ public function test_can_delete_expired_tokens_with_expires_at_expiration() { config(['sanctum.expiration' => 60]); - $user = UserForPruneExpiredTest::forceCreate([ - 'name' => 'Taylor Otwell', - 'email' => 'taylor@laravel.com', - 'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', - ]); + $user = UserFactory::new()->create(); - $token_1 = PersonalAccessToken::forceCreate([ - 'tokenable_id' => $user->id, - 'tokenable_type' => get_class($user), + $token_1 = PersonalAccessTokenFactory::new()->for( + $user, 'tokenable' + )->create([ 'name' => 'Test_1', 'token' => hash('sha256', 'test_1'), 'expires_at' => now()->subMinutes(121), ]); - $token_2 = PersonalAccessToken::forceCreate([ - 'tokenable_id' => $user->id, - 'tokenable_type' => get_class($user), + $token_2 = PersonalAccessTokenFactory::new()->for( + $user, 'tokenable' + )->create([ 'name' => 'Test_2', 'token' => hash('sha256', 'test_2'), 'expires_at' => now()->subMinutes(119), ]); - $token_3 = PersonalAccessToken::forceCreate([ - 'tokenable_id' => $user->id, - 'tokenable_type' => get_class($user), + $token_3 = PersonalAccessTokenFactory::new()->for( + $user, 'tokenable' + )->create([ 'name' => 'Test_3', 'token' => hash('sha256', 'test_3'), 'expires_at' => null, @@ -132,10 +111,3 @@ public function test_can_delete_expired_tokens_with_expires_at_expiration() $this->assertDatabaseHas('personal_access_tokens', ['name' => 'Test_3']); } } - -class UserForPruneExpiredTest extends User implements HasApiTokensContract -{ - use HasApiTokens; - - protected $table = 'users'; -} diff --git a/workbench/app/Models/User.php b/workbench/app/Models/User.php new file mode 100644 index 0000000..c4c84c3 --- /dev/null +++ b/workbench/app/Models/User.php @@ -0,0 +1,42 @@ + + */ + protected $fillable = [ + 'name', + 'email', + 'password', + ]; + + /** + * The attributes that should be hidden for serialization. + * + * @var array + */ + protected $hidden = [ + 'password', + 'remember_token', + ]; + + /** + * The attributes that should be cast. + * + * @var array + */ + protected $casts = [ + 'email_verified_at' => 'datetime', + ]; +} diff --git a/workbench/database/factories/PersonalAccessTokenFactory.php b/workbench/database/factories/PersonalAccessTokenFactory.php new file mode 100644 index 0000000..7ce39b6 --- /dev/null +++ b/workbench/database/factories/PersonalAccessTokenFactory.php @@ -0,0 +1,37 @@ + + */ +class PersonalAccessTokenFactory extends Factory +{ + /** + * The name of the factory's corresponding model. + * + * @var class-string<\Illuminate\Database\Eloquent\Model|TModel> + */ + protected $model = PersonalAccessToken::class; + + /** + * Define the model's default state. + * + * @return array + */ + public function definition(): array + { + return [ + 'name' => fake()->company(), + 'token' => hash('sha256', 'test'), + 'created_at' => Carbon::now(), + 'expires_at' => null, + ]; + } +} diff --git a/workbench/database/factories/UserFactory.php b/workbench/database/factories/UserFactory.php new file mode 100644 index 0000000..af134aa --- /dev/null +++ b/workbench/database/factories/UserFactory.php @@ -0,0 +1,21 @@ + + */ + public function modelName() + { + return User::class; + } +}