Refactor PrepareClientTrait to use the loginUser method

This commit is contained in:
Julien Fastré 2023-12-14 21:16:47 +01:00
parent 5030b67c5d
commit 7ba3435c41
Signed by: julienfastre
GPG Key ID: BDE2190974723FCB
2 changed files with 33 additions and 8 deletions

View File

@ -11,6 +11,7 @@ declare(strict_types=1);
namespace Chill\MainBundle\Test; namespace Chill\MainBundle\Test;
use Chill\MainBundle\Repository\UserRepository;
use Symfony\Bundle\FrameworkBundle\KernelBrowser; use Symfony\Bundle\FrameworkBundle\KernelBrowser;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
@ -31,13 +32,41 @@ trait PrepareClientTrait
$username = 'center a_social', $username = 'center a_social',
$password = 'password' $password = 'password'
): KernelBrowser { ): KernelBrowser {
if ('admin' === $username) {
return $this->getClientAuthenticatedAsAdmin();
}
if (!$this instanceof WebTestCase) { if (!$this instanceof WebTestCase) {
throw new \LogicException(sprintf('The current class does not implements %s', WebTestCase::class)); throw new \LogicException(sprintf('The current class does not implements %s', WebTestCase::class));
} }
return static::createClient([], [ $client = static::createClient();
'PHP_AUTH_USER' => $username,
'PHP_AUTH_PW' => $password, $userRepository = static::getContainer()->get(UserRepository::class);
]); $user = $userRepository->findOneByUsernameOrEmail($username);
if (null === $user) {
throw new \RuntimeException(sprintf('user with username or email %s not found', $username));
}
$client->loginUser($user);
return $client;
}
public function getClientAuthenticatedAsAdmin(): KernelBrowser
{
if (!$this instanceof WebTestCase) {
throw new \LogicException(sprintf('The current class does not implements %s', WebTestCase::class));
}
$client = static::createClient();
/** @var \Symfony\Component\Security\Core\User\InMemoryUserProvider $userProvider */
$userProvider = static::getContainer()->get('security.user.provider.concrete.in_memory');
$user = $userProvider->loadUserByIdentifier('admin');
$client->loginUser($user);
return $client;
} }
} }

View File

@ -1,9 +1,5 @@
--- ---
# config/packages/test/security.yaml # config/packages/test/security.yaml
security: security:
firewalls:
default:
entry_point: http_basic
http_basic: ~
role_hierarchy: role_hierarchy:
CHILL_MASTER_ROLE: [ CHILL_INHERITED_ROLE_1 ] CHILL_MASTER_ROLE: [ CHILL_INHERITED_ROLE_1 ]