LoginControllerTest.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. namespace App\Tests;
  3. use App\Entity\User;
  4. use Symfony\Bundle\FrameworkBundle\KernelBrowser;
  5. use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
  6. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  7. class LoginControllerTest extends WebTestCase
  8. {
  9. private KernelBrowser $client;
  10. protected function setUp(): void
  11. {
  12. $this->client = static::createClient();
  13. $container = static::getContainer();
  14. $em = $container->get('doctrine.orm.entity_manager');
  15. $userRepository = $em->getRepository(User::class);
  16. // Remove any existing users from the test database
  17. foreach ($userRepository->findAll() as $user) {
  18. $em->remove($user);
  19. }
  20. $em->flush();
  21. // Create a User fixture
  22. /** @var UserPasswordHasherInterface $passwordHasher */
  23. $passwordHasher = $container->get('security.user_password_hasher');
  24. $user = (new User())->setEmail('email@example.com');
  25. $user->setPassword($passwordHasher->hashPassword($user, 'password'));
  26. $em->persist($user);
  27. $em->flush();
  28. }
  29. public function testLogin(): void
  30. {
  31. // Denied - Can't login with invalid email address.
  32. $this->client->request('GET', '/login');
  33. self::assertResponseIsSuccessful();
  34. $this->client->submitForm('Sign in', [
  35. '_username' => 'doesNotExist@example.com',
  36. '_password' => 'password',
  37. ]);
  38. self::assertResponseRedirects('/login');
  39. $this->client->followRedirect();
  40. // Ensure we do not reveal if the user exists or not.
  41. self::assertSelectorTextContains('.alert-danger', 'Invalid credentials.');
  42. // Denied - Can't login with invalid password.
  43. $this->client->request('GET', '/login');
  44. self::assertResponseIsSuccessful();
  45. $this->client->submitForm('Sign in', [
  46. '_username' => 'email@example.com',
  47. '_password' => 'bad-password',
  48. ]);
  49. self::assertResponseRedirects('/login');
  50. $this->client->followRedirect();
  51. // Ensure we do not reveal the user exists but the password is wrong.
  52. self::assertSelectorTextContains('.alert-danger', 'Invalid credentials.');
  53. // Success - Login with valid credentials is allowed.
  54. $this->client->submitForm('Sign in', [
  55. '_username' => 'email@example.com',
  56. '_password' => 'password',
  57. ]);
  58. self::assertResponseRedirects('/');
  59. $this->client->followRedirect();
  60. self::assertSelectorNotExists('.alert-danger');
  61. self::assertResponseIsSuccessful();
  62. }
  63. }