Attainly/backend/tests/Feature/Auth/EloquentSessionRepositoryTest.php

85 lines
2.6 KiB
PHP

<?php
namespace Tests\Feature\Auth;
use App\Auth\CreateSessionDto;
use App\Auth\SessionRepository;
use App\Shared\ValueObject\EmailAddress;
use App\User\CreateUserDto;
use App\User\UserRepository;
use DateTimeImmutable;
use DateTimeZone;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class EloquentSessionRepositoryTest extends TestCase
{
use RefreshDatabase;
public function test_it_creates_and_finds_a_session(): void
{
$user = app(UserRepository::class)->create(new CreateUserDto(
email: new EmailAddress('user@example.com'),
));
$createdAt = $this->utc('2026-07-31T12:00:00');
$expiresAt = $this->utc('2026-08-07T12:00:00');
$repository = app(SessionRepository::class);
$session = $repository->create(new CreateSessionDto(
token: 'session-token',
user: $user,
createdAt: $createdAt,
expiresAt: $expiresAt,
));
$this->assertSame('session-token', $session->getToken());
$this->assertSame($user, $session->getUser());
$this->assertDatabaseHas('sessions', [
'token' => 'session-token',
'user_id' => $user->getId(),
]);
$foundSession = $repository->findByToken('session-token');
$this->assertNotNull($foundSession);
$this->assertSame(
$user->getId(),
$foundSession->getUser()->getId(),
);
$this->assertEquals($createdAt, $foundSession->getCreatedAt());
$this->assertEquals($expiresAt, $foundSession->getExpiresAt());
}
public function test_it_returns_null_for_an_unknown_token(): void
{
$repository = app(SessionRepository::class);
$this->assertNull($repository->findByToken('unknown-token'));
}
public function test_it_deletes_a_session_by_token(): void
{
$user = app(UserRepository::class)->create(new CreateUserDto(
email: new EmailAddress('user@example.com'),
));
$repository = app(SessionRepository::class);
$repository->create(new CreateSessionDto(
token: 'session-token',
user: $user,
createdAt: $this->utc('2026-07-31T12:00:00'),
expiresAt: $this->utc('2026-08-07T12:00:00'),
));
$repository->deleteByToken('session-token');
$this->assertNull($repository->findByToken('session-token'));
$this->assertDatabaseMissing('sessions', [
'token' => 'session-token',
]);
}
private function utc(string $time): DateTimeImmutable
{
return new DateTimeImmutable($time, new DateTimeZone('UTC'));
}
}