Files
cpo_test/laravel/tests/Feature/AuthControllerTest.php
2026-02-06 23:26:56 +07:00

117 lines
3.1 KiB
PHP

<?php
declare(strict_types=1);
namespace Tests\Feature;
use App\Contracts\AuthServiceContract;
use App\Data\Auth\LoginData;
use App\Data\Auth\LoginResult;
use App\Enums\LoginError;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Laravel\Sanctum\PersonalAccessToken;
use Mockery;
use Tests\TestCase;
class AuthControllerTest extends TestCase
{
private const string LOGIN_URL = '/api/login';
private const string LOGOUT_URL = '/api/logout';
public function test_it_returns_correct_error_for_invalid_credentials(): void
{
User::factory()->create([
'email' => 'test@example.com',
'password' => Hash::make('password123'),
]);
$response = $this->postJson(self::LOGIN_URL, [
'email' => 'test@example.com',
'password' => 'ne_password123',
]);
$response->assertStatus(401)
->assertJson([
'message' => 'Invalid credentials',
]);
}
public function test_it_returns_success_response(): void
{
User::factory()->create([
'email' => 'test@example.com',
'password' => Hash::make('password123'),
]);
$response = $this->postJson(self::LOGIN_URL, [
'email' => 'test@example.com',
'password' => 'password123',
]);
$response->assertStatus(200)
->assertJsonStructure([
'token',
]);
}
public function test_it_handles_server_error_from_service(): void
{
$mock = $this->mock(AuthServiceContract::class);
$mock->shouldReceive('attemptLogin')
->once()
->with(Mockery::type(LoginData::class))
->andReturn(LoginResult::error(LoginError::SERVER_ERROR));
$response = $this->postJson(self::LOGIN_URL, [
'email' => 'test@example.com',
'password' => 'password123',
]);
$response->assertStatus(500)
->assertJson([
'message' => 'Authentication failed',
]);
}
public function test_user_can_logout_successfully(): void
{
User::factory()->create([
'email' => 'test@example.com',
'password' => Hash::make('password123'),
]);
$loginResponse = $this->postJson(self::LOGIN_URL, [
'email' => 'test@example.com',
'password' => 'password123',
]);
$token = $loginResponse->json('token');
$tokenBefore = PersonalAccessToken::findToken($token);
$this->assertNotNull($tokenBefore, 'Token should exist before logout');
$logoutResponse = $this->postJson(self::LOGOUT_URL, [], [
'Authorization' => 'Bearer ' . $token,
]);
$logoutResponse->assertStatus(200)
->assertJson([
'message' => 'Logged out',
]);
$tokenAfter = PersonalAccessToken::findToken($token);
$this->assertNull($tokenAfter);
$this->refreshApplication();
$tasksResponse = $this->getJson('/api/tasks', [
'Authorization' => 'Bearer ' . $token,
]);
$tasksResponse->assertStatus(401);
}
}