63 lines
2.3 KiB
PHP
63 lines
2.3 KiB
PHP
|
|
<?php
|
||
|
|
|
||
|
|
namespace App\Tests\Event\Service;
|
||
|
|
|
||
|
|
use App\Entity\Account;
|
||
|
|
use App\Entity\AccountLoginRegister;
|
||
|
|
use App\Event\Service\LoginStatsSubscriber;
|
||
|
|
use Doctrine\ORM\EntityManagerInterface;
|
||
|
|
use PHPUnit\Framework\Attributes\AllowMockObjectsWithoutExpectations;
|
||
|
|
use PHPUnit\Framework\TestCase;
|
||
|
|
use Symfony\Component\HttpFoundation\Request;
|
||
|
|
use Symfony\Component\Security\Core\User\UserInterface;
|
||
|
|
use Symfony\Component\Security\Http\Event\LoginSuccessEvent;
|
||
|
|
|
||
|
|
#[AllowMockObjectsWithoutExpectations]
|
||
|
|
class LoginStatsSubscriberTest extends TestCase
|
||
|
|
{
|
||
|
|
private $entityManager;
|
||
|
|
private $subscriber;
|
||
|
|
|
||
|
|
protected function setUp(): void
|
||
|
|
{
|
||
|
|
$this->entityManager = $this->createMock(EntityManagerInterface::class);
|
||
|
|
$this->subscriber = new LoginStatsSubscriber($this->entityManager);
|
||
|
|
}
|
||
|
|
|
||
|
|
public function testOnLoginSuccessWithAccount()
|
||
|
|
{
|
||
|
|
$user = $this->createMock(Account::class);
|
||
|
|
$request = new Request([], [], [], [], [], ['REMOTE_ADDR' => '127.0.0.1']);
|
||
|
|
$request->headers->set('User-Agent', 'TestAgent');
|
||
|
|
|
||
|
|
// Manually setting client IP on Request is tricky without relying on 'REMOTE_ADDR' server var or trusted proxies
|
||
|
|
// But getClientIp() defaults to null or 127.0.0.1 depending on setup.
|
||
|
|
// We can just rely on the default behavior for this test or mock the request if it was an interface/mockable.
|
||
|
|
// Since Request is a concrete class, we use it as is.
|
||
|
|
|
||
|
|
$event = $this->createMock(LoginSuccessEvent::class);
|
||
|
|
$event->method('getUser')->willReturn($user);
|
||
|
|
$event->method('getRequest')->willReturn($request);
|
||
|
|
|
||
|
|
$this->entityManager->expects($this->once())
|
||
|
|
->method('persist')
|
||
|
|
->with($this->isInstanceOf(AccountLoginRegister::class));
|
||
|
|
|
||
|
|
$this->entityManager->expects($this->once())->method('flush');
|
||
|
|
|
||
|
|
$this->subscriber->onLoginSuccess($event);
|
||
|
|
}
|
||
|
|
|
||
|
|
public function testOnLoginSuccessWithNonAccountUser()
|
||
|
|
{
|
||
|
|
$user = $this->createMock(UserInterface::class);
|
||
|
|
$event = $this->createMock(LoginSuccessEvent::class);
|
||
|
|
$event->method('getUser')->willReturn($user);
|
||
|
|
|
||
|
|
$this->entityManager->expects($this->never())->method('persist');
|
||
|
|
$this->entityManager->expects($this->never())->method('flush');
|
||
|
|
|
||
|
|
$this->subscriber->onLoginSuccess($event);
|
||
|
|
}
|
||
|
|
}
|