PM_Console/backend/tests/Feature/AuthTest.php

95 خطوط
2.5 KiB
PHP

<?php
namespace Tests\Feature;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Tests\TestCase;
class AuthTest extends TestCase
{
use RefreshDatabase;
public function test_user_can_login_with_valid_credentials(): void
{
$user = User::factory()->create([
'email' => 'admin@pm.com',
'password' => Hash::make('password'),
'status' => 'active',
]);
$response = $this->postJson('/api/login', [
'email' => ' admin@pm.com ',
'password' => 'password',
]);
$response
->assertOk()
->assertJsonPath('success', true)
->assertJsonPath('data.user.id', $user->id)
->assertJsonStructure([
'data' => ['user', 'token', 'permissions'],
]);
}
public function test_login_rejects_invalid_credentials(): void
{
User::factory()->create([
'email' => 'admin@pm.com',
'password' => Hash::make('password'),
'status' => 'active',
]);
$this->postJson('/api/login', [
'email' => 'admin@pm.com',
'password' => 'wrong-password',
])
->assertUnauthorized()
->assertJsonPath('success', false);
}
public function test_inactive_user_cannot_login(): void
{
User::factory()->create([
'email' => 'inactive@pm.com',
'password' => Hash::make('password'),
'status' => 'inactive',
]);
$this->postJson('/api/login', [
'email' => 'inactive@pm.com',
'password' => 'password',
])
->assertForbidden()
->assertJsonPath('success', false);
}
public function test_authenticated_user_can_be_loaded_and_logged_out(): void
{
$user = User::factory()->create([
'password' => Hash::make('password'),
'status' => 'active',
]);
$token = $user->createToken('api-token')->plainTextToken;
$this->withToken($token)
->getJson('/api/user')
->assertOk()
->assertJsonPath('data.id', $user->id);
$this->withToken($token)
->postJson('/api/logout')
->assertOk()
->assertJsonPath('success', true);
Auth::forgetGuards();
$this->withToken($token)
->getJson('/api/user')
->assertUnauthorized();
}
}