function BasicAuthTest::testCacheabilityOf401Response

Same name and namespace in other branches
  1. 9 core/modules/basic_auth/tests/src/Functional/BasicAuthTest.php \Drupal\Tests\basic_auth\Functional\BasicAuthTest::testCacheabilityOf401Response()
  2. 8.9.x core/modules/basic_auth/tests/src/Functional/BasicAuthTest.php \Drupal\Tests\basic_auth\Functional\BasicAuthTest::testCacheabilityOf401Response()
  3. 11.x core/modules/basic_auth/tests/src/Functional/BasicAuthTest.php \Drupal\Tests\basic_auth\Functional\BasicAuthTest::testCacheabilityOf401Response()

Tests the cacheability of the Basic Auth 401 response.

See also

\Drupal\basic_auth\Authentication\Provider\BasicAuth::challengeException()

File

core/modules/basic_auth/tests/src/Functional/BasicAuthTest.php, line 212

Class

BasicAuthTest
Tests for BasicAuth authentication provider.

Namespace

Drupal\Tests\basic_auth\Functional

Code

public function testCacheabilityOf401Response() : void {
  $url = Url::fromRoute('router_test.11');
  $assert_response_cacheability = function ($expected_page_cache_header_value, $expected_dynamic_page_cache_header_value) use ($url) {
    $this->drupalGet($url);
    $this->assertSession()
      ->statusCodeEquals(401);
    $this->assertSession()
      ->responseHeaderEquals('X-Drupal-Cache', $expected_page_cache_header_value);
    $this->assertSession()
      ->responseHeaderEquals('X-Drupal-Dynamic-Cache', $expected_dynamic_page_cache_header_value);
  };
  // 1. First request: cold caches, both Page Cache and Dynamic Page Cache are
  // now primed.
  $assert_response_cacheability('MISS', 'MISS');
  // 2. Second request: Page Cache HIT, we don't even hit Dynamic Page Cache.
  // This is going to keep happening.
  $assert_response_cacheability('HIT', 'MISS');
  // 3. Third request: after clearing Page Cache, we now see that Dynamic Page
  // Cache is a HIT too.
  $this->container
    ->get('cache.page')
    ->deleteAll();
  $assert_response_cacheability('MISS', 'HIT');
  // 4. Fourth request: warm caches.
  $assert_response_cacheability('HIT', 'HIT');
  // If the permissions of the 'anonymous' role change, it may no longer be
  // necessary to be authenticated to access this route. Therefore the cached
  // 401 responses should be invalidated.
  $this->grantPermissions(Role::load(Role::ANONYMOUS_ID), [
    'access content',
  ]);
  $assert_response_cacheability('MISS', 'MISS');
  $assert_response_cacheability('HIT', 'MISS');
  // Idem for when the 'system.site' config changes.
  $this->config('system.site')
    ->save();
  $assert_response_cacheability('MISS', 'MISS');
  $assert_response_cacheability('HIT', 'MISS');
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.