92d1a866da9a2a9f21d20f24b9db423b914b4356
[yaffs-website] / web / core / modules / big_pipe / tests / src / Functional / BigPipeTest.php
1 <?php
2
3 namespace Drupal\Tests\big_pipe\Functional;
4
5 use Behat\Mink\Element\NodeElement;
6 use Drupal\big_pipe\Render\Placeholder\BigPipeStrategy;
7 use Drupal\big_pipe\Render\BigPipe;
8 use Drupal\big_pipe_test\BigPipePlaceholderTestCases;
9 use Drupal\Component\Serialization\Json;
10 use Drupal\Component\Utility\Html;
11 use Drupal\Core\Logger\RfcLogLevel;
12 use Drupal\Core\Url;
13 use Drupal\Tests\BrowserTestBase;
14
15 /**
16  * Tests BigPipe's no-JS detection & response delivery (with and without JS).
17  *
18  * Covers:
19  * - big_pipe_page_attachments()
20  * - \Drupal\big_pipe\Controller\BigPipeController
21  * - \Drupal\big_pipe\EventSubscriber\HtmlResponseBigPipeSubscriber
22  * - \Drupal\big_pipe\Render\BigPipe
23  *
24  * @group big_pipe
25  */
26 class BigPipeTest extends BrowserTestBase {
27
28   /**
29    * Modules to enable.
30    *
31    * @var array
32    */
33   public static $modules = ['big_pipe', 'big_pipe_test', 'dblog'];
34
35   /**
36    * {@inheritdoc}
37    */
38   protected $dumpHeaders = TRUE;
39
40   /**
41    * {@inheritdoc}
42    */
43   protected function setUp() {
44     parent::setUp();
45
46     // Ignore the <meta> refresh that big_pipe.module sets. It causes a redirect
47     // to a page that sets another cookie, which causes WebTestBase to lose the
48     // session cookie. To avoid this problem, tests should first call
49     // drupalGet() and then call checkForMetaRefresh() manually, and then reset
50     // $this->maximumMetaRefreshCount and $this->metaRefreshCount.
51     // @see doMetaRefresh()
52     $this->maximumMetaRefreshCount = 0;
53   }
54
55   /**
56    * Performs a single <meta> refresh explicitly.
57    *
58    * This test disables the automatic <meta> refresh checking, each time it is
59    * desired that this runs, a test case must explicitly call this.
60    *
61    * @see setUp()
62    */
63   protected function performMetaRefresh() {
64     $this->maximumMetaRefreshCount = 1;
65     $this->checkForMetaRefresh();
66     $this->maximumMetaRefreshCount = 0;
67     $this->metaRefreshCount = 0;
68   }
69
70   /**
71    * Tests BigPipe's no-JS detection.
72    *
73    * Covers:
74    * - big_pipe_page_attachments()
75    * - \Drupal\big_pipe\Controller\BigPipeController
76    */
77   public function testNoJsDetection() {
78     $no_js_to_js_markup = '<script>document.cookie = "' . BigPipeStrategy::NOJS_COOKIE . '=1; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT"</script>';
79
80     // 1. No session (anonymous).
81     $this->drupalGet(Url::fromRoute('<front>'));
82     $this->assertSessionCookieExists(FALSE);
83     $this->assertBigPipeNoJsCookieExists(FALSE);
84     $this->assertNoRaw('<noscript><meta http-equiv="Refresh" content="0; URL=');
85     $this->assertNoRaw($no_js_to_js_markup);
86
87     // 2. Session (authenticated).
88     $this->drupalLogin($this->rootUser);
89     $this->assertSessionCookieExists(TRUE);
90     $this->assertBigPipeNoJsCookieExists(FALSE);
91     $this->assertRaw('<noscript><meta http-equiv="Refresh" content="0; URL=' . base_path() . 'big_pipe/no-js?destination=' . base_path() . 'user/1" />' . "\n" . '</noscript>');
92     $this->assertNoRaw($no_js_to_js_markup);
93     $this->assertBigPipeNoJsMetaRefreshRedirect();
94     $this->assertBigPipeNoJsCookieExists(TRUE);
95     $this->assertNoRaw('<noscript><meta http-equiv="Refresh" content="0; URL=');
96     $this->assertRaw($no_js_to_js_markup);
97     $this->drupalLogout();
98
99     // Close the prior connection and remove the collected state.
100     $this->getSession()->reset();
101
102     // 3. Session (anonymous).
103     $this->drupalGet(Url::fromRoute('user.login', [], ['query' => ['trigger_session' => 1]]));
104     $this->drupalGet(Url::fromRoute('user.login'));
105     $this->assertSessionCookieExists(TRUE);
106     $this->assertBigPipeNoJsCookieExists(FALSE);
107     $this->assertRaw('<noscript><meta http-equiv="Refresh" content="0; URL=' . base_path() . 'big_pipe/no-js?destination=' . base_path() . 'user/login" />' . "\n" . '</noscript>');
108     $this->assertNoRaw($no_js_to_js_markup);
109     $this->assertBigPipeNoJsMetaRefreshRedirect();
110     $this->assertBigPipeNoJsCookieExists(TRUE);
111     $this->assertNoRaw('<noscript><meta http-equiv="Refresh" content="0; URL=');
112     $this->assertRaw($no_js_to_js_markup);
113
114     // Close the prior connection and remove the collected state.
115     $this->getSession()->reset();
116
117     // Edge case: route with '_no_big_pipe' option.
118     $this->drupalGet(Url::fromRoute('no_big_pipe'));
119     $this->assertSessionCookieExists(FALSE);
120     $this->assertBigPipeNoJsCookieExists(FALSE);
121     $this->assertNoRaw('<noscript><meta http-equiv="Refresh" content="0; URL=');
122     $this->assertNoRaw($no_js_to_js_markup);
123     $this->drupalLogin($this->rootUser);
124     $this->drupalGet(Url::fromRoute('no_big_pipe'));
125     $this->assertSessionCookieExists(TRUE);
126     $this->assertBigPipeNoJsCookieExists(FALSE);
127     $this->assertNoRaw('<noscript><meta http-equiv="Refresh" content="0; URL=');
128     $this->assertNoRaw($no_js_to_js_markup);
129   }
130
131   /**
132    * Tests BigPipe-delivered HTML responses when JavaScript is enabled.
133    *
134    * Covers:
135    * - \Drupal\big_pipe\EventSubscriber\HtmlResponseBigPipeSubscriber
136    * - \Drupal\big_pipe\Render\BigPipe
137    * - \Drupal\big_pipe\Render\BigPipe::sendPlaceholders()
138    *
139    * @see \Drupal\big_pipe_test\BigPipePlaceholderTestCases
140    */
141   public function testBigPipe() {
142     // Simulate production.
143     $this->config('system.logging')->set('error_level', ERROR_REPORTING_HIDE)->save();
144
145     $this->drupalLogin($this->rootUser);
146     $this->assertSessionCookieExists(TRUE);
147     $this->assertBigPipeNoJsCookieExists(FALSE);
148
149     $log_count = db_query('SELECT COUNT(*) FROM {watchdog}')->fetchField();
150
151     // By not calling performMetaRefresh() here, we simulate JavaScript being
152     // enabled, because as far as the BigPipe module is concerned, JavaScript is
153     // enabled in the browser as long as the BigPipe no-JS cookie is *not* set.
154     // @see setUp()
155     // @see performMetaRefresh()
156
157     $this->drupalGet(Url::fromRoute('big_pipe_test'));
158     $this->assertBigPipeResponseHeadersPresent();
159     $this->assertNoCacheTag('cache_tag_set_in_lazy_builder');
160
161     $this->setCsrfTokenSeedInTestEnvironment();
162     $cases = $this->getTestCases();
163     $this->assertBigPipeNoJsPlaceholders([
164       $cases['edge_case__invalid_html']->bigPipeNoJsPlaceholder     => $cases['edge_case__invalid_html']->embeddedHtmlResponse,
165       $cases['html_attribute_value']->bigPipeNoJsPlaceholder        => $cases['html_attribute_value']->embeddedHtmlResponse,
166       $cases['html_attribute_value_subset']->bigPipeNoJsPlaceholder => $cases['html_attribute_value_subset']->embeddedHtmlResponse,
167     ]);
168     $this->assertBigPipePlaceholders([
169       $cases['html']->bigPipePlaceholderId                             => Json::encode($cases['html']->embeddedAjaxResponseCommands),
170       $cases['edge_case__html_non_lazy_builder']->bigPipePlaceholderId => Json::encode($cases['edge_case__html_non_lazy_builder']->embeddedAjaxResponseCommands),
171       $cases['exception__lazy_builder']->bigPipePlaceholderId          => NULL,
172       $cases['exception__embedded_response']->bigPipePlaceholderId     => NULL,
173     ], [
174       0 => $cases['edge_case__html_non_lazy_builder']->bigPipePlaceholderId,
175       // The 'html' case contains the 'status messages' placeholder, which is
176       // always rendered last.
177       1 => $cases['html']->bigPipePlaceholderId,
178     ]);
179
180     $this->assertRaw('</body>', 'Closing body tag present.');
181
182     $this->pass('Verifying BigPipe assets are present…', 'Debug');
183     $this->assertFalse(empty($this->getDrupalSettings()), 'drupalSettings present.');
184     $this->assertTrue(in_array('big_pipe/big_pipe', explode(',', $this->getDrupalSettings()['ajaxPageState']['libraries'])), 'BigPipe asset library is present.');
185
186     // Verify that the two expected exceptions are logged as errors.
187     $this->assertEqual($log_count + 2, db_query('SELECT COUNT(*) FROM {watchdog}')->fetchField(), 'Two new watchdog entries.');
188     $records = db_query('SELECT * FROM {watchdog} ORDER BY wid DESC LIMIT 2')->fetchAll();
189     $this->assertEqual(RfcLogLevel::ERROR, $records[0]->severity);
190     $this->assertTrue(FALSE !== strpos((string) unserialize($records[0]->variables)['@message'], 'Oh noes!'));
191     $this->assertEqual(RfcLogLevel::ERROR, $records[1]->severity);
192     $this->assertTrue(FALSE !== strpos((string) unserialize($records[1]->variables)['@message'], 'You are not allowed to say llamas are not cool!'));
193
194     // Verify that 4xx responses work fine. (4xx responses are handled by
195     // subrequests to a route pointing to a controller with the desired output.)
196     $this->drupalGet(Url::fromUri('base:non-existing-path'));
197
198     // Simulate development.
199     $this->pass('Verifying BigPipe provides useful error output when an error occurs while rendering a placeholder if verbose error logging is enabled.', 'Debug');
200     $this->config('system.logging')->set('error_level', ERROR_REPORTING_DISPLAY_VERBOSE)->save();
201     $this->drupalGet(Url::fromRoute('big_pipe_test'));
202     // The 'edge_case__html_exception' case throws an exception.
203     $this->assertRaw('The website encountered an unexpected error. Please try again later');
204     $this->assertRaw('You are not allowed to say llamas are not cool!');
205     $this->assertNoRaw(BigPipe::STOP_SIGNAL, 'BigPipe stop signal absent: error occurred before then.');
206     $this->assertNoRaw('</body>', 'Closing body tag absent: error occurred before then.');
207     // The exception is expected. Do not interpret it as a test failure.
208     unlink(\Drupal::root() . '/' . $this->siteDirectory . '/error.log');
209   }
210
211   /**
212    * Tests BigPipe-delivered HTML responses when JavaScript is disabled.
213    *
214    * Covers:
215    * - \Drupal\big_pipe\EventSubscriber\HtmlResponseBigPipeSubscriber
216    * - \Drupal\big_pipe\Render\BigPipe
217    * - \Drupal\big_pipe\Render\BigPipe::sendNoJsPlaceholders()
218    *
219    * @see \Drupal\big_pipe_test\BigPipePlaceholderTestCases
220    */
221   public function testBigPipeNoJs() {
222     // Simulate production.
223     $this->config('system.logging')->set('error_level', ERROR_REPORTING_HIDE)->save();
224
225     $this->drupalLogin($this->rootUser);
226     $this->assertSessionCookieExists(TRUE);
227     $this->assertBigPipeNoJsCookieExists(FALSE);
228
229     // By calling performMetaRefresh() here, we simulate JavaScript being
230     // disabled, because as far as the BigPipe module is concerned, it is
231     // enabled in the browser when the BigPipe no-JS cookie is set.
232     // @see setUp()
233     // @see performMetaRefresh()
234     $this->performMetaRefresh();
235     $this->assertBigPipeNoJsCookieExists(TRUE);
236
237     $this->drupalGet(Url::fromRoute('big_pipe_test'));
238     $this->assertBigPipeResponseHeadersPresent();
239     $this->assertNoCacheTag('cache_tag_set_in_lazy_builder');
240
241     $this->setCsrfTokenSeedInTestEnvironment();
242     $cases = $this->getTestCases();
243     $this->assertBigPipeNoJsPlaceholders([
244       $cases['edge_case__invalid_html']->bigPipeNoJsPlaceholder           => $cases['edge_case__invalid_html']->embeddedHtmlResponse,
245       $cases['html_attribute_value']->bigPipeNoJsPlaceholder              => $cases['html_attribute_value']->embeddedHtmlResponse,
246       $cases['html_attribute_value_subset']->bigPipeNoJsPlaceholder       => $cases['html_attribute_value_subset']->embeddedHtmlResponse,
247       $cases['html']->bigPipeNoJsPlaceholder                              => $cases['html']->embeddedHtmlResponse,
248       $cases['edge_case__html_non_lazy_builder']->bigPipeNoJsPlaceholder  => $cases['edge_case__html_non_lazy_builder']->embeddedHtmlResponse,
249       $cases['exception__lazy_builder']->bigPipePlaceholderId             => NULL,
250       $cases['exception__embedded_response']->bigPipePlaceholderId        => NULL,
251     ]);
252
253     $this->pass('Verifying there are no BigPipe placeholders & replacements…', 'Debug');
254     $this->assertEqual('<none>', $this->drupalGetHeader('BigPipe-Test-Placeholders'));
255     $this->pass('Verifying BigPipe start/stop signals are absent…', 'Debug');
256     $this->assertNoRaw(BigPipe::START_SIGNAL, 'BigPipe start signal absent.');
257     $this->assertNoRaw(BigPipe::STOP_SIGNAL, 'BigPipe stop signal absent.');
258
259     $this->pass('Verifying BigPipe assets are absent…', 'Debug');
260     $this->assertTrue(!isset($this->getDrupalSettings()['bigPipePlaceholderIds']) && empty($this->getDrupalSettings()['ajaxPageState']), 'BigPipe drupalSettings and BigPipe asset library absent.');
261     $this->assertRaw('</body>', 'Closing body tag present.');
262
263     // Verify that 4xx responses work fine. (4xx responses are handled by
264     // subrequests to a route pointing to a controller with the desired output.)
265     $this->drupalGet(Url::fromUri('base:non-existing-path'));
266
267     // Simulate development.
268     $this->pass('Verifying BigPipe provides useful error output when an error occurs while rendering a placeholder if verbose error logging is enabled.', 'Debug');
269     $this->config('system.logging')->set('error_level', ERROR_REPORTING_DISPLAY_VERBOSE)->save();
270     $this->drupalGet(Url::fromRoute('big_pipe_test'));
271     // The 'edge_case__html_exception' case throws an exception.
272     $this->assertRaw('The website encountered an unexpected error. Please try again later');
273     $this->assertRaw('You are not allowed to say llamas are not cool!');
274     $this->assertNoRaw('</body>', 'Closing body tag absent: error occurred before then.');
275     // The exception is expected. Do not interpret it as a test failure.
276     unlink(\Drupal::root() . '/' . $this->siteDirectory . '/error.log');
277   }
278
279   /**
280    * Tests BigPipe with a multi-occurrence placeholder.
281    */
282   public function testBigPipeMultiOccurrencePlaceholders() {
283     $this->drupalLogin($this->rootUser);
284     $this->assertSessionCookieExists(TRUE);
285     $this->assertBigPipeNoJsCookieExists(FALSE);
286
287     // By not calling performMetaRefresh() here, we simulate JavaScript being
288     // enabled, because as far as the BigPipe module is concerned, JavaScript is
289     // enabled in the browser as long as the BigPipe no-JS cookie is *not* set.
290     // @see setUp()
291     // @see performMetaRefresh()
292
293     $this->drupalGet(Url::fromRoute('big_pipe_test_multi_occurrence'));
294     $big_pipe_placeholder_id = 'callback=Drupal%5CCore%5CRender%5CElement%5CStatusMessages%3A%3ArenderMessages&amp;args%5B0%5D&amp;token=_HAdUpwWmet0TOTe2PSiJuMntExoshbm1kh2wQzzzAA';
295     $expected_placeholder_replacement = '<script type="application/vnd.drupal-ajax" data-big-pipe-replacement-for-placeholder-with-id="' . $big_pipe_placeholder_id . '">';
296     $this->assertRaw('The count is 1.');
297     $this->assertNoRaw('The count is 2.');
298     $this->assertNoRaw('The count is 3.');
299     $raw_content = $this->getRawContent();
300     $this->assertTrue(substr_count($raw_content, $expected_placeholder_replacement) == 1, 'Only one placeholder replacement was found for the duplicate #lazy_builder arrays.');
301
302     // By calling performMetaRefresh() here, we simulate JavaScript being
303     // disabled, because as far as the BigPipe module is concerned, it is
304     // enabled in the browser when the BigPipe no-JS cookie is set.
305     // @see setUp()
306     // @see performMetaRefresh()
307     $this->performMetaRefresh();
308     $this->assertBigPipeNoJsCookieExists(TRUE);
309     $this->drupalGet(Url::fromRoute('big_pipe_test_multi_occurrence'));
310     $this->assertRaw('The count is 1.');
311     $this->assertNoRaw('The count is 2.');
312     $this->assertNoRaw('The count is 3.');
313   }
314
315   protected function assertBigPipeResponseHeadersPresent() {
316     $this->pass('Verifying BigPipe response headers…', 'Debug');
317     $this->assertTrue(FALSE !== strpos($this->drupalGetHeader('Cache-Control'), 'private'), 'Cache-Control header set to "private".');
318     $this->assertEqual('no-store, content="BigPipe/1.0"', $this->drupalGetHeader('Surrogate-Control'));
319     $this->assertEqual('no', $this->drupalGetHeader('X-Accel-Buffering'));
320   }
321
322   /**
323    * Asserts expected BigPipe no-JS placeholders are present and replaced.
324    *
325    * @param array $expected_big_pipe_nojs_placeholders
326    *   Keys: BigPipe no-JS placeholder markup. Values: expected replacement
327    *   markup.
328    */
329   protected function assertBigPipeNoJsPlaceholders(array $expected_big_pipe_nojs_placeholders) {
330     $this->pass('Verifying BigPipe no-JS placeholders & replacements…', 'Debug');
331     $this->assertSetsEqual(array_keys($expected_big_pipe_nojs_placeholders), array_map('rawurldecode', explode(' ', $this->drupalGetHeader('BigPipe-Test-No-Js-Placeholders'))));
332     foreach ($expected_big_pipe_nojs_placeholders as $big_pipe_nojs_placeholder => $expected_replacement) {
333       $this->pass('Checking whether the replacement for the BigPipe no-JS placeholder "' . $big_pipe_nojs_placeholder . '" is present:');
334       $this->assertNoRaw($big_pipe_nojs_placeholder);
335       if ($expected_replacement !== NULL) {
336         $this->assertRaw($expected_replacement);
337       }
338     }
339   }
340
341   /**
342    * Asserts expected BigPipe placeholders are present and replaced.
343    *
344    * @param array $expected_big_pipe_placeholders
345    *   Keys: BigPipe placeholder IDs. Values: expected AJAX response.
346    * @param array $expected_big_pipe_placeholder_stream_order
347    *   Keys: BigPipe placeholder IDs. Values: expected AJAX response. Keys are
348    *   defined in the order that they are expected to be rendered & streamed.
349    */
350   protected function assertBigPipePlaceholders(array $expected_big_pipe_placeholders, array $expected_big_pipe_placeholder_stream_order) {
351     $this->pass('Verifying BigPipe placeholders & replacements…', 'Debug');
352     $this->assertSetsEqual(array_keys($expected_big_pipe_placeholders), explode(' ', $this->drupalGetHeader('BigPipe-Test-Placeholders')));
353     $placeholder_positions = [];
354     $placeholder_replacement_positions = [];
355     foreach ($expected_big_pipe_placeholders as $big_pipe_placeholder_id => $expected_ajax_response) {
356       $this->pass('BigPipe placeholder: ' . $big_pipe_placeholder_id, 'Debug');
357       // Verify expected placeholder.
358       $expected_placeholder_html = '<span data-big-pipe-placeholder-id="' . $big_pipe_placeholder_id . '"></span>';
359       $this->assertRaw($expected_placeholder_html, 'BigPipe placeholder for placeholder ID "' . $big_pipe_placeholder_id . '" found.');
360       $pos = strpos($this->getRawContent(), $expected_placeholder_html);
361       $placeholder_positions[$pos] = $big_pipe_placeholder_id;
362       // Verify expected placeholder replacement.
363       $expected_placeholder_replacement = '<script type="application/vnd.drupal-ajax" data-big-pipe-replacement-for-placeholder-with-id="' . $big_pipe_placeholder_id . '">';
364       $result = $this->xpath('//script[@data-big-pipe-replacement-for-placeholder-with-id=:id]', [':id' => Html::decodeEntities($big_pipe_placeholder_id)]);
365       if ($expected_ajax_response === NULL) {
366         $this->assertEqual(0, count($result));
367         $this->assertNoRaw($expected_placeholder_replacement);
368         continue;
369       }
370       $this->assertEqual($expected_ajax_response, trim($result[0]->getText()));
371       $this->assertRaw($expected_placeholder_replacement);
372       $pos = strpos($this->getRawContent(), $expected_placeholder_replacement);
373       $placeholder_replacement_positions[$pos] = $big_pipe_placeholder_id;
374     }
375     ksort($placeholder_positions, SORT_NUMERIC);
376     $this->assertEqual(array_keys($expected_big_pipe_placeholders), array_values($placeholder_positions));
377     $placeholders = array_map(function (NodeElement $element) {
378       return $element->getAttribute('data-big-pipe-placeholder-id');
379     }, $this->cssSelect('[data-big-pipe-placeholder-id]'));
380     $this->assertEqual(count($expected_big_pipe_placeholders), count(array_unique($placeholders)));
381     $expected_big_pipe_placeholders_with_replacements = [];
382     foreach ($expected_big_pipe_placeholder_stream_order as $big_pipe_placeholder_id) {
383       $expected_big_pipe_placeholders_with_replacements[$big_pipe_placeholder_id] = $expected_big_pipe_placeholders[$big_pipe_placeholder_id];
384     }
385     $this->assertEqual($expected_big_pipe_placeholders_with_replacements, array_filter($expected_big_pipe_placeholders));
386     $this->assertSetsEqual(array_keys($expected_big_pipe_placeholders_with_replacements), array_values($placeholder_replacement_positions));
387     $this->assertEqual(count($expected_big_pipe_placeholders_with_replacements), preg_match_all('/' . preg_quote('<script type="application/vnd.drupal-ajax" data-big-pipe-replacement-for-placeholder-with-id="', '/') . '/', $this->getRawContent()));
388
389     $this->pass('Verifying BigPipe start/stop signals…', 'Debug');
390     $this->assertRaw(BigPipe::START_SIGNAL, 'BigPipe start signal present.');
391     $this->assertRaw(BigPipe::STOP_SIGNAL, 'BigPipe stop signal present.');
392     $start_signal_position = strpos($this->getRawContent(), BigPipe::START_SIGNAL);
393     $stop_signal_position = strpos($this->getRawContent(), BigPipe::STOP_SIGNAL);
394     $this->assertTrue($start_signal_position < $stop_signal_position, 'BigPipe start signal appears before stop signal.');
395
396     $this->pass('Verifying BigPipe placeholder replacements and start/stop signals were streamed in the correct order…', 'Debug');
397     $expected_stream_order = array_keys($expected_big_pipe_placeholders_with_replacements);
398     array_unshift($expected_stream_order, BigPipe::START_SIGNAL);
399     array_push($expected_stream_order, BigPipe::STOP_SIGNAL);
400     $actual_stream_order = $placeholder_replacement_positions + [
401         $start_signal_position => BigPipe::START_SIGNAL,
402         $stop_signal_position => BigPipe::STOP_SIGNAL,
403       ];
404     ksort($actual_stream_order, SORT_NUMERIC);
405     $this->assertEqual($expected_stream_order, array_values($actual_stream_order));
406   }
407
408   /**
409    * Ensures CSRF tokens can be generated for the current user's session.
410    */
411   protected function setCsrfTokenSeedInTestEnvironment() {
412     $session_data = $this->container->get('session_handler.write_safe')->read($this->getSession()->getCookie($this->getSessionName()));
413     $csrf_token_seed = unserialize(explode('_sf2_meta|', $session_data)[1])['s'];
414     $this->container->get('session_manager.metadata_bag')->setCsrfTokenSeed($csrf_token_seed);
415   }
416
417   /**
418    * @return \Drupal\big_pipe_test\BigPipePlaceholderTestCase[]
419    */
420   protected function getTestCases($has_session = TRUE) {
421     return BigPipePlaceholderTestCases::cases($this->container, $this->rootUser);
422   }
423
424   /**
425    * Asserts whether arrays A and B are equal, when treated as sets.
426    */
427   protected function assertSetsEqual(array $a, array $b) {
428     return count($a) == count($b) && !array_diff_assoc($a, $b);
429   }
430
431   /**
432    * Asserts whether a BigPipe no-JS cookie exists or not.
433    */
434   protected function assertBigPipeNoJsCookieExists($expected) {
435     $this->assertCookieExists('big_pipe_nojs', $expected, 'BigPipe no-JS');
436   }
437
438   /**
439    * Asserts whether a session cookie exists or not.
440    */
441   protected function assertSessionCookieExists($expected) {
442     $this->assertCookieExists($this->getSessionName(), $expected, 'Session');
443   }
444
445   /**
446    * Asserts whether a cookie exists on the client or not.
447    */
448   protected function assertCookieExists($cookie_name, $expected, $cookie_label) {
449     $this->assertEqual($expected, !empty($this->getSession()->getCookie($cookie_name)), $expected ? "$cookie_label cookie exists." : "$cookie_label cookie does not exist.");
450   }
451
452   /**
453    * Calls ::performMetaRefresh() and asserts the responses.
454    */
455   protected function assertBigPipeNoJsMetaRefreshRedirect() {
456     $original_url = $this->getSession()->getCurrentUrl();
457
458     // Disable automatic following of redirects by the HTTP client, so that this
459     // test can analyze the response headers of each redirect response.
460     $this->getSession()->getDriver()->getClient()->followRedirects(FALSE);
461     $this->performMetaRefresh();
462     $headers[0] = $this->getSession()->getResponseHeaders();
463     $statuses[0] = $this->getSession()->getStatusCode();
464     $this->performMetaRefresh();
465     $headers[1] = $this->getSession()->getResponseHeaders();
466     $statuses[1] = $this->getSession()->getStatusCode();
467     $this->getSession()->getDriver()->getClient()->followRedirects(TRUE);
468
469     $this->assertEqual($original_url, $this->getSession()->getCurrentUrl(), 'Redirected back to the original location.');
470
471     // First response: redirect.
472     $this->assertEqual(302, $statuses[0], 'The first response was a 302 (redirect).');
473     $this->assertIdentical(0, strpos($headers[0]['Set-Cookie'][0], 'big_pipe_nojs=1'), 'The first response sets the big_pipe_nojs cookie.');
474     $this->assertEqual($original_url, $headers[0]['Location'][0], 'The first response redirected back to the original page.');
475     $this->assertTrue(empty(array_diff(['cookies:big_pipe_nojs', 'session.exists'], explode(' ', $headers[0]['X-Drupal-Cache-Contexts'][0]))), 'The first response varies by the "cookies:big_pipe_nojs" and "session.exists" cache contexts.');
476     $this->assertFalse(isset($headers[0]['Surrogate-Control']), 'The first response has no "Surrogate-Control" header.');
477
478     // Second response: redirect followed.
479     $this->assertEqual(200, $statuses[1], 'The second response was a 200.');
480     $this->assertTrue(empty(array_diff(['cookies:big_pipe_nojs', 'session.exists'], explode(' ', $headers[0]['X-Drupal-Cache-Contexts'][0]))), 'The first response varies by the "cookies:big_pipe_nojs" and "session.exists" cache contexts.');
481     $this->assertEqual('no-store, content="BigPipe/1.0"', $headers[1]['Surrogate-Control'][0], 'The second response has a "Surrogate-Control" header.');
482
483     $this->assertNoRaw('<noscript><meta http-equiv="Refresh" content="0; URL=', 'Once the BigPipe no-JS cookie is set, the <meta> refresh is absent: only one redirect ever happens.');
484   }
485
486 }