bf4951d9b0397fd3ffc571140d1b2e7a821de276
[yaffs-website] / src / Functional / PageCacheTest.php
1 <?php
2
3 namespace Drupal\Tests\page_cache\Functional;
4
5 use Drupal\Component\Datetime\DateTimePlus;
6 use Drupal\Core\Site\Settings;
7 use Drupal\Core\Url;
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;
13
14 /**
15  * Enables the page cache and tests it with various HTTP requests.
16  *
17  * @group page_cache
18  */
19 class PageCacheTest extends BrowserTestBase {
20
21   use AssertPageCacheContextsAndTagsTrait;
22
23   protected $dumpHeaders = TRUE;
24
25   /**
26    * Modules to enable.
27    *
28    * @var array
29    */
30   public static $modules = ['test_page_test', 'system_test', 'entity_test'];
31
32   /**
33    * {@inheritdoc}
34    */
35   protected function setUp() {
36     parent::setUp();
37
38     $this->config('system.site')
39       ->set('name', 'Drupal')
40       ->set('page.front', '/test-page')
41       ->save();
42   }
43
44   /**
45    * Test that cache tags are properly persisted.
46    *
47    * Since tag based invalidation works, we know that our tag properly
48    * persisted.
49    */
50   public function testPageCacheTags() {
51     $config = $this->config('system.performance');
52     $config->set('cache.page.max_age', 300);
53     $config->save();
54
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');
59
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);
67     $expected_tags = [
68       'config:user.role.anonymous',
69       'http_response',
70       'pre_render',
71       'rendered',
72       'system_test_cache_tags_page',
73     ];
74     $this->assertIdentical($cache_entry->tags, $expected_tags);
75
76     Cache::invalidateTags($tags);
77     $this->drupalGet($path);
78     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
79   }
80
81   /**
82    * Test that the page cache doesn't depend on cacheability headers.
83    */
84   public function testPageCacheTagsIndependentFromCacheabilityHeaders() {
85     // Disable the cacheability headers.
86     $this->setContainerParameter('http.response.debug_cacheability_headers', FALSE);
87     $this->rebuildContainer();
88     $this->resetAll();
89
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');
94
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);
102     $expected_tags = [
103       'config:user.role.anonymous',
104       'http_response',
105       'pre_render',
106       'rendered',
107       'system_test_cache_tags_page',
108     ];
109     $this->assertIdentical($cache_entry->tags, $expected_tags);
110
111     Cache::invalidateTags($tags);
112     $this->drupalGet($path);
113     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
114   }
115
116   /**
117    * Tests support for different cache items with different request formats
118    * specified via a query parameter.
119    */
120   public function testQueryParameterFormatRequests() {
121     $config = $this->config('system.performance');
122     $config->set('cache.page.max_age', 300);
123     $config->save();
124
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']);
127
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.');
133
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.');
139
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');
146
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');
153
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');
162
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');
172
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');
179   }
180
181   /**
182    * Tests support of requests with If-Modified-Since and If-None-Match headers.
183    */
184   public function testConditionalRequests() {
185     $config = $this->config('system.performance');
186     $config->set('cache.page.max_age', 300);
187     $config->save();
188
189     // Fill the cache.
190     $this->drupalGet('');
191     // Verify the page is not printed twice when the cache is cold.
192     $this->assertNoPattern('#<html.*<html#');
193
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');
198
199     $this->drupalGet('', [], ['If-Modified-Since' => $last_modified, 'If-None-Match' => $etag]);
200     $this->assertResponse(304, 'Conditional request returned 304 Not Modified.');
201
202     $this->drupalGet('', [], [
203       'If-Modified-Since' => gmdate(DATE_RFC822, strtotime($last_modified)),
204       'If-None-Match' => $etag,
205     ]);
206     $this->assertResponse(304, 'Conditional request with obsolete If-Modified-Since date returned 304 Not Modified.');
207
208     $this->drupalGet('', [], [
209       'If-Modified-Since' => gmdate(DATE_RFC850, strtotime($last_modified)),
210       'If-None-Match' => $etag,
211     ]);
212     $this->assertResponse(304, 'Conditional request with obsolete If-Modified-Since date returned 304 Not Modified.');
213
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.');
219
220     $this->drupalGet('', [], [
221       'If-Modified-Since' => gmdate(DateTimePlus::RFC7231, strtotime($last_modified) + 1),
222       'If-None-Match' => $etag,
223     ]);
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.');
226
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.');
232   }
233
234   /**
235    * Tests cache headers.
236    */
237   public function testPageCache() {
238     $config = $this->config('system.performance');
239     $config->set('cache.page.max_age', 300);
240     $config->save();
241
242     // Fill the cache.
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.');
252
253     // Check cache.
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.');
260
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.');
266
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.');
276
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');
282   }
283
284   /**
285    * Tests the automatic presence of the anonymous role's cache tag.
286    *
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.
293    *
294    * This test verifies that, and it verifies that it does not happen for other
295    * roles.
296    */
297   public function testPageCacheAnonymousRolePermissions() {
298     $config = $this->config('system.performance');
299     $config->set('cache.page.max_age', 300);
300     $config->save();
301
302     $content_url = Url::fromRoute('system_test.permission_dependent_content');
303     $route_access_url = Url::fromRoute('system_test.permission_dependent_route_access');
304
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');
313
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');
323
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');
334
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');
344   }
345
346   /**
347    * Tests the 4xx-response cache tag is added and invalidated.
348    */
349   public function testPageCacheAnonymous403404() {
350     $admin_url = Url::fromRoute('system.admin');
351     $invalid_url = 'foo/does_not_exist';
352     $tests = [
353       403 => $admin_url,
354       404 => $invalid_url,
355     ];
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');
366       $entity_values = [
367         'name' => $this->randomMachineName(),
368         'user_id' => 1,
369         'field_test_text' => [
370           0 => [
371             'value' => $this->randomString(),
372             'format' => 'plain_text',
373           ]
374         ],
375       ];
376       $entity = EntityTest::create($entity_values);
377       $entity->save();
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');
390
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.
398       $this->assertTrue(
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}"
402       );
403     }
404
405     // Disable 403 and 404 caching.
406     $settings['settings']['cache_ttl_4xx'] = (object) [
407       'value' => 0,
408       'required' => TRUE,
409     ];
410     $this->writeSettings($settings);
411     \Drupal::service('cache.page')->deleteAll();
412
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');
419     }
420   }
421
422   /**
423    * Tests the omit_vary_cookie setting.
424    */
425   public function testPageCacheWithoutVaryCookie() {
426     $config = $this->config('system.performance');
427     $config->set('cache.page.max_age', 300);
428     $config->save();
429
430     $settings['settings']['omit_vary_cookie'] = (object) [
431       'value' => TRUE,
432       'required' => TRUE,
433     ];
434     $this->writeSettings($settings);
435
436     // Fill the cache.
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.');
441
442     // Check cache.
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.');
447   }
448
449   /**
450    * Test the setting of forms to be immutable.
451    */
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();
460
461     $this->drupalGet('page_cache_form_test_immutability');
462
463     $this->assertText("Immutable: TRUE", "Form is immutable.");
464
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']);
471
472     $this->drupalGet('page_cache_form_test_immutability');
473
474     $this->assertText("Immutable: FALSE", "Form is not immutable,");
475   }
476
477   /**
478    * Tests cacheability of a CacheableResponse.
479    *
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.
483    */
484   public function testCacheableResponseResponses() {
485     $config = $this->config('system.performance');
486     $config->set('cache.page.max_age', 300);
487     $config->save();
488
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');
493
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');
498
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');
503
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');
508
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.');
513
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.');
518
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']);
523
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.');
527   }
528
529   /**
530    * Tests that HEAD requests are treated the same as GET requests.
531    */
532   public function testHead() {
533     /** @var \GuzzleHttp\ClientInterface $client */
534     $client = $this->getSession()->getDriver()->getClient()->getClient();
535
536     // GET, then HEAD.
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());
546
547     // HEAD, then GET.
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);
557   }
558
559   /**
560    * Test a cacheable response with custom cache control.
561    */
562   public function testCacheableWithCustomCacheControl() {
563     $config = $this->config('system.performance');
564     $config->set('cache.page.max_age', 300);
565     $config->save();
566
567     $this->drupalGet('/system-test/custom-cache-control');
568     $this->assertResponse(200);
569     $this->assertHeader('Cache-Control', 'bar, private');
570   }
571
572   /**
573    * Test that URLs are cached in a not normalized form.
574    */
575   public function testNoUrlNormalization() {
576
577     // Use absolute URLs to avoid any processing.
578     $url = Url::fromRoute('<front>')->setAbsolute()->toString();
579
580     // In each test, the first array value is raw URL, the second one is the
581     // possible normalized URL.
582     $tests = [
583       [
584         $url . '?z=z&a=a',
585         $url . '?a=a&z=z',
586       ],
587       [
588         $url . '?',
589         $url . '',
590       ],
591       [
592         $url . '?a=b+c',
593         $url . '?a=b%20c',
594       ],
595     ];
596
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']);
601
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.");
605
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.");
609     }
610   }
611
612   /**
613    * Retrieves only the headers for an absolute path.
614    *
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.
618    *
619    * @param string $url
620    *   URL to request.
621    *
622    * @return array
623    *   Array of headers.
624    */
625   protected function getHeaders($url) {
626     $ch = curl_init();
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);
633     curl_close($ch);
634
635     $headers = [];
636     foreach (explode("\n", $output) as $header) {
637       if (strpos($header, ':')) {
638         list($key, $value) = explode(':', $header, 2);
639         $headers[trim($key)] = trim($value);
640       }
641     }
642
643     return $headers;
644   }
645
646 }