From 7ba3435c41160a83a2a19f839c894862e5dd427f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Julien=20Fastr=C3=A9?= Date: Thu, 14 Dec 2023 21:16:47 +0100 Subject: [PATCH] Refactor PrepareClientTrait to use the loginUser method --- .../Test/PrepareClientTrait.php | 37 +++++++++++++++++-- tests/app/config/packages/test/security.yaml | 4 -- 2 files changed, 33 insertions(+), 8 deletions(-) diff --git a/src/Bundle/ChillMainBundle/Test/PrepareClientTrait.php b/src/Bundle/ChillMainBundle/Test/PrepareClientTrait.php index c4080e46f..353653619 100644 --- a/src/Bundle/ChillMainBundle/Test/PrepareClientTrait.php +++ b/src/Bundle/ChillMainBundle/Test/PrepareClientTrait.php @@ -11,6 +11,7 @@ declare(strict_types=1); namespace Chill\MainBundle\Test; +use Chill\MainBundle\Repository\UserRepository; use Symfony\Bundle\FrameworkBundle\KernelBrowser; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; @@ -31,13 +32,41 @@ trait PrepareClientTrait $username = 'center a_social', $password = 'password' ): KernelBrowser { + if ('admin' === $username) { + return $this->getClientAuthenticatedAsAdmin(); + } + if (!$this instanceof WebTestCase) { throw new \LogicException(sprintf('The current class does not implements %s', WebTestCase::class)); } - return static::createClient([], [ - 'PHP_AUTH_USER' => $username, - 'PHP_AUTH_PW' => $password, - ]); + $client = static::createClient(); + + $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; } } diff --git a/tests/app/config/packages/test/security.yaml b/tests/app/config/packages/test/security.yaml index 5aaa34ce0..500f81876 100644 --- a/tests/app/config/packages/test/security.yaml +++ b/tests/app/config/packages/test/security.yaml @@ -1,9 +1,5 @@ --- # config/packages/test/security.yaml security: - firewalls: - default: - entry_point: http_basic - http_basic: ~ role_hierarchy: CHILL_MASTER_ROLE: [ CHILL_INHERITED_ROLE_1 ]