monitoring-8.x-1.x-dev/tests/src/Functional/MonitoringCaptchaTest.php
tests/src/Functional/MonitoringCaptchaTest.php
<?php
namespace Drupal\Tests\monitoring\Functional;
/**
* Tests the captcha failed attempts sensor.
*
* @group monitoring
* @dependencies captcha
*/
class MonitoringCaptchaTest extends MonitoringTestBase {
/**
* Modules to install.
*
* @var array
*/
protected static $modules = ['captcha', 'node'];
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
// Add captcha.inc file.
\Drupal::moduleHandler()->loadInclude('captcha', 'inc');
}
/**
* Tests the captcha failed attempts sensor.
*/
public function testCaptchaSensor() {
// 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.
captcha_set_form_id_setting('user_login_form', 'captcha/Math');
// Assert the number of entries in the captcha_session table is 1.
$this->assertEquals(\Drupal::database()->query('SELECT COUNT (*) FROM {captcha_sessions}')->fetchField(), 0);
// Try to log in, with invalid captcha answer which should fail.
$edit = array(
'name' => $user->getAccountName(),
'pass' => $user->pass_raw,
'captcha_response' => '?',
);
$this->drupalGet('user');
$this->submitForm($edit, 'Log in');
// Assert the total number of entries in captcha_sessions table is now 2.
$this->assertEquals(\Drupal::database()->query('SELECT COUNT (*) FROM {captcha_sessions}')->fetchField(), 1);
// Run sensor and get the message.
$message = $this->runSensor('captcha_failed_count')->getMessage();
// Assert the number of failed attempts.
$this->assertEquals($message, '1 attempt(s)');
}
/**
* Test removing captcha sensor.
*/
public function testRemovingCaptchaSensor() {
// Try resaving first, and assert that the dependency persists.
$dependencies = $this->config('monitoring.sensor_config.captcha_failed_count')->get('dependencies');
$this->assertEquals(['module' => ['captcha']], $dependencies);
$user = $this->drupalCreateUser(['administer monitoring']);
$this->drupalLogin($user);
$this->drupalGet('/admin/config/system/monitoring/sensors/captcha_failed_count');
$this->submitForm([], 'Save');
$dependencies = $this->config('monitoring.sensor_config.captcha_failed_count')->get('dependencies');
$this->assertEquals(['module' => ['captcha']], $dependencies);
// Uninstall captcha and assert that the sensor was removed.
$this->uninstallModules(['captcha']);
$this->drupalGet('/admin/config/system/monitoring/sensors/captcha_failed_count');
$this->assertSession()->statusCodeEquals(404);
}
}
