You are here

public function CaptchaTest::testCaptchaOnLoginForm in CAPTCHA 8

Testing the protection of the user log in form.

File

tests/src/Functional/CaptchaTest.php, line 26

Class

CaptchaTest
Tests CAPTCHA main test case sensitivity.

Namespace

Drupal\Tests\captcha\Functional

Code

public function testCaptchaOnLoginForm() {

  // Create user and test log in without CAPTCHA.
  $user = $this
    ->drupalCreateUser();
  $this
    ->drupalLogin($user);

  // Log out again.
  $this
    ->drupalLogout();

  // Set a CAPTCHA on login form.

  /* @var \Drupal\captcha\Entity\CaptchaPoint $captcha_point */
  $captcha_point = \Drupal::entityTypeManager()
    ->getStorage('captcha_point')
    ->load('user_login_form');
  $captcha_point
    ->setCaptchaType('captcha/Math');
  $captcha_point
    ->enable()
    ->save();

  // Check if there is a CAPTCHA on the login form (look for the title).
  $this
    ->drupalGet('user');
  $this
    ->assertCaptchaPresence(TRUE);

  // Try to log in, which should fail.
  $edit = [
    'name' => $user
      ->getDisplayName(),
    'pass' => $user->pass_raw,
    'captcha_response' => '?',
  ];
  $this
    ->submitForm($edit, $this
    ->t('Log in'), self::LOGIN_HTML_FORM_ID);

  // Check for error message.
  $this
    ->assertSession()
    ->pageTextContains(self::CAPTCHA_WRONG_RESPONSE_ERROR_MESSAGE, 'CAPTCHA should block user login form', 'CAPTCHA');

  // And make sure that user is not logged in:
  // check for name and password fields on ?q=user.
  $this
    ->drupalGet('user');
  $this
    ->assertSession()
    ->fieldExists('name');
  $this
    ->assertSession()
    ->fieldExists('pass');
}