Bicycle/tests/Unit/FileAuthDriverTest.php
Egor Isaev 9e20ae6c5f dev
2026-08-07 14:01:09 +03:00

115 lines
3.4 KiB
PHP

<?php
namespace Tests\Unit;
use PHPUnit\Framework\TestCase;
use ReflectionClass;
use Services\Auth\FileAuthDriver;
use System\Classes\Session;
class FileAuthDriverTest extends TestCase
{
private string $file;
protected function setUp(): void
{
$this->file = sys_get_temp_dir() . '/bicycle_auth_users_' . uniqid('', true) . '.php';
file_put_contents($this->file, '<?php return ' . var_export([
'bob' => [
'password' => password_hash('secret', PASSWORD_DEFAULT),
'full_name' => 'Bob Smith',
'email' => 'bob@example.com',
'role' => 'manager',
],
], true) . ';');
}
protected function tearDown(): void
{
unlink($this->file);
Session::instance()->destroy();
$ref = new ReflectionClass(Session::class);
$prop = $ref->getProperty('instances');
$prop->setAccessible(true);
$prop->setValue(null, []);
}
public function testLoginWithCorrectCredentialsSucceeds(): void
{
$this->assertTrue((new FileAuthDriver($this->file))->login('bob', 'secret'));
}
public function testLoginWithWrongPasswordFails(): void
{
$this->assertFalse((new FileAuthDriver($this->file))->login('bob', 'wrong'));
}
public function testLoginWithUnknownLoginFails(): void
{
$this->assertFalse((new FileAuthDriver($this->file))->login('nobody', 'secret'));
}
public function testLoggedInIsFalseBeforeLogin(): void
{
$this->assertFalse((new FileAuthDriver($this->file))->loggedIn());
}
public function testLoggedInIsTrueAfterSuccessfulLogin(): void
{
$driver = new FileAuthDriver($this->file);
$driver->login('bob', 'secret');
$this->assertTrue($driver->loggedIn());
}
public function testGetUserReturnsDataWithoutPassword(): void
{
$driver = new FileAuthDriver($this->file);
$driver->login('bob', 'secret');
$user = $driver->getUser();
$this->assertSame('bob', $user['login']);
$this->assertSame('Bob Smith', $user['full_name']);
$this->assertSame('bob@example.com', $user['email']);
$this->assertSame('manager', $user['role']);
$this->assertArrayNotHasKey('password', $user);
}
public function testGetUserIsNullWhenNotAuthorized(): void
{
$this->assertNull((new FileAuthDriver($this->file))->getUser());
}
public function testLogoutClearsAuthorization(): void
{
$driver = new FileAuthDriver($this->file);
$driver->login('bob', 'secret');
$driver->logout();
$this->assertFalse($driver->loggedIn());
}
public function testCheckPasswordAgainstLoggedInUser(): void
{
$driver = new FileAuthDriver($this->file);
$driver->login('bob', 'secret');
$this->assertTrue($driver->checkPassword('secret'));
$this->assertFalse($driver->checkPassword('wrong'));
}
public function testCheckPasswordIsFalseWhenNotAuthorized(): void
{
$this->assertFalse((new FileAuthDriver($this->file))->checkPassword('secret'));
}
public function testMissingUsersFileBehavesAsEmptyList(): void
{
$driver = new FileAuthDriver(sys_get_temp_dir() . '/does_not_exist_' . uniqid('', true) . '.php');
$this->assertFalse($driver->login('bob', 'secret'));
}
}