3 namespace Drupal\Tests\page_cache\Functional;
5 use Drupal\Component\Datetime\DateTimePlus;
6 use Drupal\Core\Site\Settings;
8 use Drupal\entity_test\Entity\EntityTest;
9 use Drupal\Core\Cache\Cache;
10 use Drupal\Tests\BrowserTestBase;
11 use Drupal\Tests\system\Functional\Cache\AssertPageCacheContextsAndTagsTrait;
12 use Drupal\user\RoleInterface;
15 * Enables the page cache and tests it with various HTTP requests.
19 class PageCacheTest extends BrowserTestBase {
21 use AssertPageCacheContextsAndTagsTrait;
23 protected $dumpHeaders = TRUE;
30 public static $modules = ['test_page_test', 'system_test', 'entity_test'];
35 protected function setUp() {
38 $this->config('system.site')
39 ->set('name', 'Drupal')
40 ->set('page.front', '/test-page')
45 * Test that cache tags are properly persisted.
47 * Since tag based invalidation works, we know that our tag properly
50 public function testPageCacheTags() {
51 $config = $this->config('system.performance');
52 $config->set('cache.page.max_age', 300);
55 $path = 'system-test/cache_tags_page';
56 $tags = ['system_test_cache_tags_page'];
57 $this->drupalGet($path);
58 $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
60 // Verify a cache hit, but also the presence of the correct cache tags.
61 $this->drupalGet($path);
62 $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT');
63 $cid_parts = [\Drupal::url('system_test.cache_tags_page', [], ['absolute' => TRUE]), 'html'];
64 $cid = implode(':', $cid_parts);
65 $cache_entry = \Drupal::cache('page')->get($cid);
66 sort($cache_entry->tags);
68 'config:user.role.anonymous',
72 'system_test_cache_tags_page',
74 $this->assertIdentical($cache_entry->tags, $expected_tags);
76 Cache::invalidateTags($tags);
77 $this->drupalGet($path);
78 $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
82 * Test that the page cache doesn't depend on cacheability headers.
84 public function testPageCacheTagsIndependentFromCacheabilityHeaders() {
85 // Disable the cacheability headers.
86 $this->setContainerParameter('http.response.debug_cacheability_headers', FALSE);
87 $this->rebuildContainer();
90 $path = 'system-test/cache_tags_page';
91 $tags = ['system_test_cache_tags_page'];
92 $this->drupalGet($path);
93 $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
95 // Verify a cache hit, but also the presence of the correct cache tags.
96 $this->drupalGet($path);
97 $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT');
98 $cid_parts = [\Drupal::url('system_test.cache_tags_page', [], ['absolute' => TRUE]), 'html'];
99 $cid = implode(':', $cid_parts);
100 $cache_entry = \Drupal::cache('page')->get($cid);
101 sort($cache_entry->tags);
103 'config:user.role.anonymous',
107 'system_test_cache_tags_page',
109 $this->assertIdentical($cache_entry->tags, $expected_tags);
111 Cache::invalidateTags($tags);
112 $this->drupalGet($path);
113 $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
117 * Tests support for different cache items with different request formats
118 * specified via a query parameter.
120 public function testQueryParameterFormatRequests() {
121 $config = $this->config('system.performance');
122 $config->set('cache.page.max_age', 300);
125 $accept_header_cache_url = Url::fromRoute('system_test.page_cache_accept_header');
126 $accept_header_cache_url_with_json = Url::fromRoute('system_test.page_cache_accept_header', ['_format' => 'json']);
128 $this->drupalGet($accept_header_cache_url);
129 $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS', 'HTML page was not yet cached.');
130 $this->drupalGet($accept_header_cache_url);
131 $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT', 'HTML page was cached.');
132 $this->assertRaw('<p>oh hai this is html.</p>', 'The correct HTML response was returned.');
134 $this->drupalGet($accept_header_cache_url_with_json);
135 $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS', 'Json response was not yet cached.');
136 $this->drupalGet($accept_header_cache_url_with_json);
137 $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT', 'Json response was cached.');
138 $this->assertRaw('{"content":"oh hai this is json"}', 'The correct Json response was returned.');
140 // Enable REST support for nodes and hal+json.
141 \Drupal::service('module_installer')->install(['node', 'rest', 'hal', 'basic_auth']);
142 $this->drupalCreateContentType(['type' => 'article']);
143 $node = $this->drupalCreateNode(['type' => 'article']);
144 $node_uri = $node->urlInfo();
145 $node_url_with_hal_json_format = $node->urlInfo('canonical')->setRouteParameter('_format', 'hal_json');
147 $this->drupalGet($node_uri);
148 $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
149 $this->assertEqual($this->drupalGetHeader('Content-Type'), 'text/html; charset=UTF-8');
150 $this->drupalGet($node_uri);
151 $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT');
152 $this->assertEqual($this->drupalGetHeader('Content-Type'), 'text/html; charset=UTF-8');
154 // Now request a HAL page, we expect that the first request is a cache miss
155 // and it serves HTML.
156 $this->drupalGet($node_url_with_hal_json_format);
157 $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
158 $this->assertEqual($this->drupalGetHeader('Content-Type'), 'application/hal+json');
159 $this->drupalGet($node_url_with_hal_json_format);
160 $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT');
161 $this->assertEqual($this->drupalGetHeader('Content-Type'), 'application/hal+json');
163 // Clear the page cache. After that request a HAL request, followed by an
164 // ordinary HTML one.
165 \Drupal::cache('page')->deleteAll();
166 $this->drupalGet($node_url_with_hal_json_format);
167 $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
168 $this->assertEqual($this->drupalGetHeader('Content-Type'), 'application/hal+json');
169 $this->drupalGet($node_url_with_hal_json_format);
170 $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT');
171 $this->assertEqual($this->drupalGetHeader('Content-Type'), 'application/hal+json');
173 $this->drupalGet($node_uri);
174 $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
175 $this->assertEqual($this->drupalGetHeader('Content-Type'), 'text/html; charset=UTF-8');
176 $this->drupalGet($node_uri);
177 $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT');
178 $this->assertEqual($this->drupalGetHeader('Content-Type'), 'text/html; charset=UTF-8');
182 * Tests support of requests with If-Modified-Since and If-None-Match headers.
184 public function testConditionalRequests() {
185 $config = $this->config('system.performance');
186 $config->set('cache.page.max_age', 300);
190 $this->drupalGet('');
191 // Verify the page is not printed twice when the cache is cold.
192 $this->assertNoPattern('#<html.*<html#');
194 $this->drupalGet('');
195 $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT', 'Page was cached.');
196 $etag = $this->drupalGetHeader('ETag');
197 $last_modified = $this->drupalGetHeader('Last-Modified');
199 $this->drupalGet('', [], ['If-Modified-Since' => $last_modified, 'If-None-Match' => $etag]);
200 $this->assertResponse(304, 'Conditional request returned 304 Not Modified.');
202 $this->drupalGet('', [], [
203 'If-Modified-Since' => gmdate(DATE_RFC822, strtotime($last_modified)),
204 'If-None-Match' => $etag,
206 $this->assertResponse(304, 'Conditional request with obsolete If-Modified-Since date returned 304 Not Modified.');
208 $this->drupalGet('', [], [
209 'If-Modified-Since' => gmdate(DATE_RFC850, strtotime($last_modified)),
210 'If-None-Match' => $etag,
212 $this->assertResponse(304, 'Conditional request with obsolete If-Modified-Since date returned 304 Not Modified.');
214 $this->drupalGet('', [], ['If-Modified-Since' => $last_modified, 'If-None-Match' => NULL]);
215 // Verify the page is not printed twice when the cache is warm.
216 $this->assertNoPattern('#<html.*<html#');
217 $this->assertResponse(200, 'Conditional request without If-None-Match returned 200 OK.');
218 $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT', 'Page was cached.');
220 $this->drupalGet('', [], [
221 'If-Modified-Since' => gmdate(DateTimePlus::RFC7231, strtotime($last_modified) + 1),
222 'If-None-Match' => $etag,
224 $this->assertResponse(200, 'Conditional request with new a If-Modified-Since date newer than Last-Modified returned 200 OK.');
225 $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT', 'Page was cached.');
227 $user = $this->drupalCreateUser();
228 $this->drupalLogin($user);
229 $this->drupalGet('', [], ['If-Modified-Since' => $last_modified, 'If-None-Match' => $etag]);
230 $this->assertResponse(200, 'Conditional request returned 200 OK for authenticated user.');
231 $this->assertFalse($this->drupalGetHeader('X-Drupal-Cache'), 'Absence of Page was not cached.');
235 * Tests cache headers.
237 public function testPageCache() {
238 $config = $this->config('system.performance');
239 $config->set('cache.page.max_age', 300);
243 $this->drupalGet('system-test/set-header', ['query' => ['name' => 'Foo', 'value' => 'bar']]);
244 $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS', 'Page was not cached.');
245 $this->assertEqual(strtolower($this->drupalGetHeader('Vary')), 'cookie,accept-encoding', 'Vary header was sent.');
246 // Symfony's Response logic determines a specific order for the subvalues
247 // of the Cache-Control header, even if they are explicitly passed in to
248 // the response header bag in a different order.
249 $this->assertEqual($this->drupalGetHeader('Cache-Control'), 'max-age=300, public', 'Cache-Control header was sent.');
250 $this->assertEqual($this->drupalGetHeader('Expires'), 'Sun, 19 Nov 1978 05:00:00 GMT', 'Expires header was sent.');
251 $this->assertEqual($this->drupalGetHeader('Foo'), 'bar', 'Custom header was sent.');
254 $this->drupalGet('system-test/set-header', ['query' => ['name' => 'Foo', 'value' => 'bar']]);
255 $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT', 'Page was cached.');
256 $this->assertEqual(strtolower($this->drupalGetHeader('Vary')), 'cookie,accept-encoding', 'Vary: Cookie header was sent.');
257 $this->assertEqual($this->drupalGetHeader('Cache-Control'), 'max-age=300, public', 'Cache-Control header was sent.');
258 $this->assertEqual($this->drupalGetHeader('Expires'), 'Sun, 19 Nov 1978 05:00:00 GMT', 'Expires header was sent.');
259 $this->assertEqual($this->drupalGetHeader('Foo'), 'bar', 'Custom header was sent.');
261 // Check replacing default headers.
262 $this->drupalGet('system-test/set-header', ['query' => ['name' => 'Expires', 'value' => 'Fri, 19 Nov 2008 05:00:00 GMT']]);
263 $this->assertEqual($this->drupalGetHeader('Expires'), 'Fri, 19 Nov 2008 05:00:00 GMT', 'Default header was replaced.');
264 $this->drupalGet('system-test/set-header', ['query' => ['name' => 'Vary', 'value' => 'User-Agent']]);
265 $this->assertEqual(strtolower($this->drupalGetHeader('Vary')), 'user-agent,accept-encoding', 'Default header was replaced.');
267 // Check that authenticated users bypass the cache.
268 $user = $this->drupalCreateUser();
269 $this->drupalLogin($user);
270 $this->drupalGet('system-test/set-header', ['query' => ['name' => 'Foo', 'value' => 'bar']]);
271 $this->assertFalse($this->drupalGetHeader('X-Drupal-Cache'), 'Caching was bypassed.');
272 $this->assertTrue(strpos(strtolower($this->drupalGetHeader('Vary')), 'cookie') === FALSE, 'Vary: Cookie header was not sent.');
273 $this->assertEqual($this->drupalGetHeader('Cache-Control'), 'must-revalidate, no-cache, private', 'Cache-Control header was sent.');
274 $this->assertEqual($this->drupalGetHeader('Expires'), 'Sun, 19 Nov 1978 05:00:00 GMT', 'Expires header was sent.');
275 $this->assertEqual($this->drupalGetHeader('Foo'), 'bar', 'Custom header was sent.');
277 // Until bubbling of max-age up to the response is supported, verify that
278 // a custom #cache max-age set on an element does not affect page max-age.
279 $this->drupalLogout();
280 $this->drupalGet('system-test/cache_maxage_page');
281 $this->assertEqual($this->drupalGetHeader('Cache-Control'), 'max-age=300, public');
285 * Tests the automatic presence of the anonymous role's cache tag.
287 * The 'user.permissions' cache context ensures that if the permissions for a
288 * role are modified, users are not served stale render cache content. But,
289 * when entire responses are cached in reverse proxies, the value for the
290 * cache context is never calculated, causing the stale response to not be
291 * invalidated. Therefore, when varying by permissions and the current user is
292 * the anonymous user, the cache tag for the 'anonymous' role must be added.
294 * This test verifies that, and it verifies that it does not happen for other
297 public function testPageCacheAnonymousRolePermissions() {
298 $config = $this->config('system.performance');
299 $config->set('cache.page.max_age', 300);
302 $content_url = Url::fromRoute('system_test.permission_dependent_content');
303 $route_access_url = Url::fromRoute('system_test.permission_dependent_route_access');
305 // 1. anonymous user, without permission.
306 $this->drupalGet($content_url);
307 $this->assertText('Permission to pet llamas: no!');
308 $this->assertCacheContext('user.permissions');
309 $this->assertCacheTag('config:user.role.anonymous');
310 $this->drupalGet($route_access_url);
311 $this->assertCacheContext('user.permissions');
312 $this->assertCacheTag('config:user.role.anonymous');
314 // 2. anonymous user, with permission.
315 user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, ['pet llamas']);
316 $this->drupalGet($content_url);
317 $this->assertText('Permission to pet llamas: yes!');
318 $this->assertCacheContext('user.permissions');
319 $this->assertCacheTag('config:user.role.anonymous');
320 $this->drupalGet($route_access_url);
321 $this->assertCacheContext('user.permissions');
322 $this->assertCacheTag('config:user.role.anonymous');
324 // 3. authenticated user, without permission.
325 $auth_user = $this->drupalCreateUser();
326 $this->drupalLogin($auth_user);
327 $this->drupalGet($content_url);
328 $this->assertText('Permission to pet llamas: no!');
329 $this->assertCacheContext('user.permissions');
330 $this->assertNoCacheTag('config:user.role.authenticated');
331 $this->drupalGet($route_access_url);
332 $this->assertCacheContext('user.permissions');
333 $this->assertNoCacheTag('config:user.role.authenticated');
335 // 4. authenticated user, with permission.
336 user_role_grant_permissions(RoleInterface::AUTHENTICATED_ID, ['pet llamas']);
337 $this->drupalGet($content_url);
338 $this->assertText('Permission to pet llamas: yes!');
339 $this->assertCacheContext('user.permissions');
340 $this->assertNoCacheTag('config:user.role.authenticated');
341 $this->drupalGet($route_access_url);
342 $this->assertCacheContext('user.permissions');
343 $this->assertNoCacheTag('config:user.role.authenticated');
347 * Tests the 4xx-response cache tag is added and invalidated.
349 public function testPageCacheAnonymous403404() {
350 $admin_url = Url::fromRoute('system.admin');
351 $invalid_url = 'foo/does_not_exist';
356 $cache_ttl_4xx = Settings::get('cache_ttl_4xx', 3600);
357 foreach ($tests as $code => $content_url) {
358 // Anonymous user, without permissions.
359 $this->drupalGet($content_url);
360 $this->assertResponse($code);
361 $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
362 $this->assertCacheTag('4xx-response');
363 $this->drupalGet($content_url);
364 $this->assertResponse($code);
365 $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT');
367 'name' => $this->randomMachineName(),
369 'field_test_text' => [
371 'value' => $this->randomString(),
372 'format' => 'plain_text',
376 $entity = EntityTest::create($entity_values);
378 // Saving an entity clears 4xx cache tag.
379 $this->drupalGet($content_url);
380 $this->assertResponse($code);
381 $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
382 $this->drupalGet($content_url);
383 $this->assertResponse($code);
384 $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT');
385 // Rebuilding the router should invalidate the 4xx cache tag.
386 $this->container->get('router.builder')->rebuild();
387 $this->drupalGet($content_url);
388 $this->assertResponse($code);
389 $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
391 // Ensure the 'expire' field on the cache entry uses cache_ttl_4xx.
392 $cache_item = \Drupal::service('cache.page')->get($this->getUrl() . ':html');
393 $difference = $cache_item->expire - (int) $cache_item->created;
394 // Given that a second might have passed we cannot be sure that
395 // $difference will exactly equal the default cache_ttl_4xx setting.
396 // Account for any timing difference or rounding errors by ensuring the
397 // value is within 10 seconds.
399 $difference > $cache_ttl_4xx - 10 &&
400 $difference < $cache_ttl_4xx + 10,
401 "The cache entry expiry time uses the cache_ttl_4xx setting. Expire: {$cache_item->expire} Created: {$cache_item->created}"
405 // Disable 403 and 404 caching.
406 $settings['settings']['cache_ttl_4xx'] = (object) [
410 $this->writeSettings($settings);
411 \Drupal::service('cache.page')->deleteAll();
413 foreach ($tests as $code => $content_url) {
414 // Getting the 404 page twice should still result in a cache miss.
415 $this->drupalGet($content_url);
416 $this->drupalGet($content_url);
417 $this->assertResponse($code);
418 $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
423 * Tests the omit_vary_cookie setting.
425 public function testPageCacheWithoutVaryCookie() {
426 $config = $this->config('system.performance');
427 $config->set('cache.page.max_age', 300);
430 $settings['settings']['omit_vary_cookie'] = (object) [
434 $this->writeSettings($settings);
437 $this->drupalGet('');
438 $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS', 'Page was not cached.');
439 $this->assertTrue(strpos($this->drupalGetHeader('Vary'), 'Cookie') === FALSE, 'Vary: Cookie header was not sent.');
440 $this->assertEqual($this->drupalGetHeader('Cache-Control'), 'max-age=300, public', 'Cache-Control header was sent.');
443 $this->drupalGet('');
444 $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT', 'Page was cached.');
445 $this->assertTrue(strpos($this->drupalGetHeader('Vary'), 'Cookie') === FALSE, 'Vary: Cookie header was not sent.');
446 $this->assertEqual($this->drupalGetHeader('Cache-Control'), 'max-age=300, public', 'Cache-Control header was sent.');
450 * Test the setting of forms to be immutable.
452 public function testFormImmutability() {
453 // Install the module that provides the test form.
454 $this->container->get('module_installer')
455 ->install(['page_cache_form_test']);
456 // Uninstall the page_cache module to verify that form is immutable
457 // regardless of the internal page cache module.
458 $this->container->get('module_installer')->uninstall(['page_cache']);
459 \Drupal::service('router.builder')->rebuild();
461 $this->drupalGet('page_cache_form_test_immutability');
463 $this->assertText("Immutable: TRUE", "Form is immutable.");
465 // The immutable flag is set unconditionally by system_form_alter(), set
466 // a flag to tell page_cache_form_test_module_implements_alter() to disable
467 // that implementation.
468 \Drupal::state()->set('page_cache_bypass_form_immutability', TRUE);
469 \Drupal::moduleHandler()->resetImplementations();
470 Cache::invalidateTags(['rendered']);
472 $this->drupalGet('page_cache_form_test_immutability');
474 $this->assertText("Immutable: FALSE", "Form is not immutable,");
478 * Tests cacheability of a CacheableResponse.
480 * Tests the difference between having a controller return a plain Symfony
481 * Response object versus returning a Response object that implements the
482 * CacheableResponseInterface.
484 public function testCacheableResponseResponses() {
485 $config = $this->config('system.performance');
486 $config->set('cache.page.max_age', 300);
489 // GET a URL, which would be marked as a cache miss if it were cacheable.
490 $this->drupalGet('/system-test/respond-reponse');
491 $this->assertFalse($this->drupalGetHeader('X-Drupal-Cache'), 'Drupal page cache header not found.');
492 $this->assertEqual($this->drupalGetHeader('Cache-Control'), 'must-revalidate, no-cache, private', 'Cache-Control header was sent');
494 // GET it again, verify it's still not cached.
495 $this->drupalGet('/system-test/respond-reponse');
496 $this->assertFalse($this->drupalGetHeader('X-Drupal-Cache'), 'Drupal page cache header not found.');
497 $this->assertEqual($this->drupalGetHeader('Cache-Control'), 'must-revalidate, no-cache, private', 'Cache-Control header was sent');
499 // GET a URL, which would be marked as a cache miss if it were cacheable.
500 $this->drupalGet('/system-test/respond-public-response');
501 $this->assertFalse($this->drupalGetHeader('X-Drupal-Cache'), 'Drupal page cache header not found.');
502 $this->assertEqual($this->drupalGetHeader('Cache-Control'), 'max-age=60, public', 'Cache-Control header was sent');
504 // GET it again, verify it's still not cached.
505 $this->drupalGet('/system-test/respond-public-response');
506 $this->assertFalse($this->drupalGetHeader('X-Drupal-Cache'), 'Drupal page cache header not found.');
507 $this->assertEqual($this->drupalGetHeader('Cache-Control'), 'max-age=60, public', 'Cache-Control header was sent');
509 // GET a URL, which should be marked as a cache miss.
510 $this->drupalGet('/system-test/respond-cacheable-reponse');
511 $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS', 'Page was not cached.');
512 $this->assertEqual($this->drupalGetHeader('Cache-Control'), 'max-age=300, public', 'Cache-Control header was sent.');
514 // GET it again, it should now be a cache hit.
515 $this->drupalGet('/system-test/respond-cacheable-reponse');
516 $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT', 'Page was cached.');
517 $this->assertEqual($this->drupalGetHeader('Cache-Control'), 'max-age=300, public', 'Cache-Control header was sent.');
519 // Uninstall page cache. This should flush all caches so the next call to a
520 // previously cached page should be a miss now.
521 $this->container->get('module_installer')
522 ->uninstall(['page_cache']);
524 // GET a URL that was cached by Page Cache before, it should not be now.
525 $this->drupalGet('/respond-cacheable-reponse');
526 $this->assertFalse($this->drupalGetHeader('X-Drupal-Cache'), 'Drupal page cache header not found.');
530 * Tests that HEAD requests are treated the same as GET requests.
532 public function testHead() {
533 /** @var \GuzzleHttp\ClientInterface $client */
534 $client = $this->getSession()->getDriver()->getClient()->getClient();
537 $url_a = $this->buildUrl('system-test/set-header', ['query' => ['name' => 'Foo', 'value' => 'bar']]);
538 $response_body = $this->drupalGet($url_a);
539 $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS', 'Page was not cached.');
540 $this->assertEqual($this->drupalGetHeader('Foo'), 'bar', 'Custom header was sent.');
541 $this->assertEqual('The following header was set: <em class="placeholder">Foo</em>: <em class="placeholder">bar</em>', $response_body);
542 $response = $client->request('HEAD', $url_a);
543 $this->assertEqual($response->getHeaderLine('X-Drupal-Cache'), 'HIT', 'Page was cached.');
544 $this->assertEqual($response->getHeaderLine('Foo'), 'bar', 'Custom header was sent.');
545 $this->assertEqual('', $response->getBody()->getContents());
548 $url_b = $this->buildUrl('system-test/set-header', ['query' => ['name' => 'Foo', 'value' => 'baz']]);
549 $response = $client->request('HEAD', $url_b);
550 $this->assertEqual($response->getHeaderLine('X-Drupal-Cache'), 'MISS', 'Page was not cached.');
551 $this->assertEqual($response->getHeaderLine('Foo'), 'baz', 'Custom header was sent.');
552 $this->assertEqual('', $response->getBody()->getContents());
553 $response_body = $this->drupalGet($url_b);
554 $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT', 'Page was cached.');
555 $this->assertEqual($this->drupalGetHeader('Foo'), 'baz', 'Custom header was sent.');
556 $this->assertEqual('The following header was set: <em class="placeholder">Foo</em>: <em class="placeholder">baz</em>', $response_body);
560 * Test a cacheable response with custom cache control.
562 public function testCacheableWithCustomCacheControl() {
563 $config = $this->config('system.performance');
564 $config->set('cache.page.max_age', 300);
567 $this->drupalGet('/system-test/custom-cache-control');
568 $this->assertResponse(200);
569 $this->assertHeader('Cache-Control', 'bar, private');
573 * Test that URLs are cached in a not normalized form.
575 public function testNoUrlNormalization() {
577 // Use absolute URLs to avoid any processing.
578 $url = Url::fromRoute('<front>')->setAbsolute()->toString();
580 // In each test, the first array value is raw URL, the second one is the
581 // possible normalized URL.
597 foreach ($tests as list($url_raw, $url_normalized)) {
598 // Initialize cache on raw URL.
599 $headers = $this->getHeaders($url_raw);
600 $this->assertEquals('MISS', $headers['X-Drupal-Cache']);
602 // Ensure cache was set.
603 $headers = $this->getHeaders($url_raw);
604 $this->assertEquals('HIT', $headers['X-Drupal-Cache'], "Cache was set for {$url_raw} URL.");
606 // Check if the normalized URL is not cached.
607 $headers = $this->getHeaders($url_normalized);
608 $this->assertEquals('MISS', $headers['X-Drupal-Cache'], "Cache is missing for {$url_normalized} URL.");
613 * Retrieves only the headers for an absolute path.
615 * Executes a cURL request without any modifications to the given URL.
616 * Note that Guzzle always normalizes URLs which prevents testing all
617 * possible edge cases.
625 protected function getHeaders($url) {
627 curl_setopt($ch, CURLOPT_URL, $url);
628 curl_setopt($ch, CURLOPT_HEADER, TRUE);
629 curl_setopt($ch, CURLOPT_NOBODY, TRUE);
630 curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
631 curl_setopt($ch, CURLOPT_USERAGENT, drupal_generate_test_ua($this->databasePrefix));
632 $output = curl_exec($ch);
636 foreach (explode("\n", $output) as $header) {
637 if (strpos($header, ':')) {
638 list($key, $value) = explode(':', $header, 2);
639 $headers[trim($key)] = trim($value);