Files
myep-team/tests/Security/Voter/UserVoterTest.php
T

83 lines
2.2 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Tests\Security\Voter;
use App\Entity\User;
use App\Security\Voter\UserVoter;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
class UserVoterTest extends TestCase
{
private Security&MockObject $security;
protected function setUp(): void
{
$this->security = $this->createMock(Security::class);
}
public function testSuperAdminMayEditOtherUsers(): void
{
$this->assertSame(
VoterInterface::ACCESS_GRANTED,
$this->vote($this->createUser(true), $this->createUser(false)),
);
}
public function testPlainAdminMayNotEdit(): void
{
$this->assertSame(
VoterInterface::ACCESS_DENIED,
$this->vote($this->createUser(false), $this->createUser(false)),
);
}
public function testSuperAdminMayNotEditThemselves(): void
{
$currentUser = $this->createUser(true);
$this->assertSame(
VoterInterface::ACCESS_DENIED,
$this->vote($currentUser, $currentUser),
);
}
public function testImpersonatorMayNotEdit(): void
{
$this->assertSame(
VoterInterface::ACCESS_DENIED,
$this->vote($this->createUser(true), $this->createUser(false), true),
);
}
private function vote(User $currentUser, User $targetUser, bool $isImpersonator = false): int
{
$this->security
->method('isGranted')
->with('IS_IMPERSONATOR')
->willReturn($isImpersonator);
$token = $this->createMock(TokenInterface::class);
$token
->method('getUser')
->willReturn($currentUser);
$voter = new UserVoter($this->security);
return $voter->vote($token, $targetUser, [UserVoter::EDIT]);
}
private function createUser(bool $superAdmin): User
{
return (new User())
->setRoles(['ROLE_ADMIN'])
->setSuperAdmin($superAdmin)
;
}
}