You are here

public function CaptchaCacheTest::testCacheTags in CAPTCHA 8

Test the cache tags.

File

tests/src/Functional/CaptchaCacheTest.php, line 37

Class

CaptchaCacheTest
Tests CAPTCHA caching on various pages.

Namespace

Drupal\Tests\captcha\Functional

Code

public function testCacheTags() {
  global $base_path;

  // Check caching without captcha as anonymous user.
  $this
    ->drupalGet('');
  $this
    ->assertEquals($this
    ->getSession()
    ->getResponseHeader('x-drupal-cache'), 'MISS');
  $this
    ->drupalGet('');
  $this
    ->assertEquals($this
    ->getSession()
    ->getResponseHeader('x-drupal-cache'), 'HIT');

  // Enable captcha on login block and test caching.
  captcha_set_form_id_setting('user_login_form', 'captcha/Math');
  $this
    ->drupalGet('');
  $sid = $this
    ->getCaptchaSidFromForm();
  $this
    ->assertNull($this
    ->getSession()
    ->getResponseHeader('x-drupal-cache'), 'Cache is disabled');
  $this
    ->drupalGet('');
  $this
    ->assertNotEquals($sid, $this
    ->getCaptchaSidFromForm());

  // Switch challenge to captcha/Test, check the captcha isn't cached.
  captcha_set_form_id_setting('user_login_form', 'captcha/Test');
  $this
    ->drupalGet('');
  $sid = $this
    ->getCaptchaSidFromForm();
  $this
    ->assertNull($this
    ->getSession()
    ->getResponseHeader('x-drupal-cache'), 'Cache is disabled');
  $this
    ->drupalGet('');
  $this
    ->assertNotEquals($sid, $this
    ->getCaptchaSidFromForm());

  // Switch challenge to image_captcha/Image, check the captcha isn't cached.
  captcha_set_form_id_setting('user_login_form', 'image_captcha/Image');
  $this
    ->drupalGet('');
  $image_path = $this
    ->getSession()
    ->getPage()
    ->find('css', '.captcha img')
    ->getAttribute('src');
  $this
    ->assertNull($this
    ->getSession()
    ->getResponseHeader('x-drupal-cache'), 'Cache disabled');

  // Check that we get a new image when vising the page again.
  $this
    ->drupalGet('');
  $this
    ->assertNotEquals($image_path, $this
    ->getSession()
    ->getPage()
    ->find('css', '.captcha img')
    ->getAttribute('src'));

  // Check image caching, remove the base path since drupalGet() expects the
  // internal path.
  $this
    ->drupalGet(substr($image_path, strlen($base_path)));
  $this
    ->assertSession()
    ->statusCodeEquals(200);

  // Request image twice to make sure no errors happen (due to page caching).
  $this
    ->drupalGet(substr($image_path, strlen($base_path)));
  $this
    ->assertSession()
    ->statusCodeEquals(200);
}