Red phase: CreateSessionTest covers token, user, createdAt, 7-day expiry, persistence, and fresh instance.
102 lines
2.8 KiB
PHP
102 lines
2.8 KiB
PHP
<?php
|
|
|
|
namespace Tests\Unit\Auth\UseCases;
|
|
|
|
use App\Auth\UseCases\CreateSession\CreateSession;
|
|
use App\Shared\ValueObject\EmailAddress;
|
|
use App\User\CreateUserDto;
|
|
use App\User\User;
|
|
use DateTimeImmutable;
|
|
use PHPUnit\Framework\TestCase;
|
|
use Tests\Fakes\FakeClock;
|
|
use Tests\Fakes\FakeSessionRepository;
|
|
use Tests\Fakes\FakeTokenGenerator;
|
|
use Tests\Fakes\FakeUserRepository;
|
|
|
|
class CreateSessionTest extends TestCase
|
|
{
|
|
private FakeSessionRepository $sessionRepo;
|
|
private FakeTokenGenerator $tokenGenerator;
|
|
private FakeClock $clock;
|
|
private CreateSession $useCase;
|
|
private User $user;
|
|
|
|
protected function setUp(): void
|
|
{
|
|
$this->sessionRepo = new FakeSessionRepository();
|
|
$this->tokenGenerator = new FakeTokenGenerator([
|
|
'token-1',
|
|
]);
|
|
$this->clock = new FakeClock(
|
|
new DateTimeImmutable('2026-05-16 12:00:00'),
|
|
);
|
|
$this->useCase = new CreateSession(
|
|
$this->sessionRepo,
|
|
$this->tokenGenerator,
|
|
$this->clock,
|
|
);
|
|
|
|
$userRepo = new FakeUserRepository();
|
|
$this->user = $userRepo->create(new CreateUserDto(
|
|
email: new EmailAddress('user@example.com'),
|
|
passwordHash: 'hashed:password',
|
|
));
|
|
}
|
|
|
|
public function testCreatesSessionWithGivenToken(): void
|
|
{
|
|
$session = $this->useCase->execute($this->user);
|
|
|
|
$this->assertSame('token-1', $session->getToken());
|
|
}
|
|
|
|
public function testCreatesSessionWithUser(): void
|
|
{
|
|
$session = $this->useCase->execute($this->user);
|
|
|
|
$this->assertSame(
|
|
$this->user->getId(),
|
|
$session->getUser()->getId(),
|
|
);
|
|
}
|
|
|
|
public function testCreatesSessionWithCreatedAtFromClock(): void
|
|
{
|
|
$session = $this->useCase->execute($this->user);
|
|
|
|
$this->assertEquals(
|
|
new DateTimeImmutable('2026-05-16 12:00:00'),
|
|
$session->getCreatedAt(),
|
|
);
|
|
}
|
|
|
|
public function testCreatesSessionWithExpirySevenDaysLater(): void
|
|
{
|
|
$session = $this->useCase->execute($this->user);
|
|
|
|
$this->assertEquals(
|
|
new DateTimeImmutable('2026-05-23 12:00:00'),
|
|
$session->getExpiresAt(),
|
|
);
|
|
}
|
|
|
|
public function testPersistsSessionInRepository(): void
|
|
{
|
|
$session = $this->useCase->execute($this->user);
|
|
|
|
$found = $this->sessionRepo->findByToken('token-1');
|
|
|
|
$this->assertNotNull($found);
|
|
$this->assertSame($session->getToken(), $found->getToken());
|
|
}
|
|
|
|
public function testFreshInstanceReturnedOnEachCall(): void
|
|
{
|
|
$session = $this->useCase->execute($this->user);
|
|
|
|
$this->assertNotSame(
|
|
$session,
|
|
$this->sessionRepo->findByToken('token-1'),
|
|
);
|
|
}
|
|
}
|