Updated Drupal to 8.6. This goes with the following updates because it's possible...
[yaffs-website] / web / core / modules / simpletest / src / WebTestBase.php
1 <?php
2
3 namespace Drupal\simpletest;
4
5 use Drupal\block\Entity\Block;
6 use Drupal\Component\Serialization\Json;
7 use Drupal\Component\Utility\Html;
8 use Drupal\Component\Utility\NestedArray;
9 use Drupal\Component\Utility\UrlHelper;
10 use Drupal\Component\Render\FormattableMarkup;
11 use Drupal\Core\EventSubscriber\AjaxResponseSubscriber;
12 use Drupal\Core\EventSubscriber\MainContentViewSubscriber;
13 use Drupal\Core\Session\AccountInterface;
14 use Drupal\Core\Session\AnonymousUserSession;
15 use Drupal\Core\Test\AssertMailTrait;
16 use Drupal\Core\Test\FunctionalTestSetupTrait;
17 use Drupal\Core\Url;
18 use Drupal\system\Tests\Cache\AssertPageCacheContextsAndTagsTrait;
19 use Drupal\Tests\EntityViewTrait;
20 use Drupal\Tests\block\Traits\BlockCreationTrait as BaseBlockCreationTrait;
21 use Drupal\Tests\Listeners\DeprecationListenerTrait;
22 use Drupal\Tests\node\Traits\ContentTypeCreationTrait as BaseContentTypeCreationTrait;
23 use Drupal\Tests\node\Traits\NodeCreationTrait as BaseNodeCreationTrait;
24 use Drupal\Tests\Traits\Core\CronRunTrait;
25 use Drupal\Tests\TestFileCreationTrait;
26 use Drupal\Tests\user\Traits\UserCreationTrait as BaseUserCreationTrait;
27 use Drupal\Tests\XdebugRequestTrait;
28 use Zend\Diactoros\Uri;
29
30 /**
31  * Test case for typical Drupal tests.
32  *
33  * @ingroup testing
34  */
35 abstract class WebTestBase extends TestBase {
36
37   use FunctionalTestSetupTrait;
38   use AssertContentTrait;
39   use TestFileCreationTrait {
40     getTestFiles as drupalGetTestFiles;
41     compareFiles as drupalCompareFiles;
42   }
43   use AssertPageCacheContextsAndTagsTrait;
44   use BaseBlockCreationTrait {
45     placeBlock as drupalPlaceBlock;
46   }
47   use BaseContentTypeCreationTrait {
48     createContentType as drupalCreateContentType;
49   }
50   use CronRunTrait;
51   use AssertMailTrait {
52     getMails as drupalGetMails;
53   }
54   use BaseNodeCreationTrait {
55     getNodeByTitle as drupalGetNodeByTitle;
56     createNode as drupalCreateNode;
57   }
58   use BaseUserCreationTrait {
59     createUser as drupalCreateUser;
60     createRole as drupalCreateRole;
61     createAdminRole as drupalCreateAdminRole;
62   }
63
64   use XdebugRequestTrait;
65   use EntityViewTrait {
66     buildEntityView as drupalBuildEntityView;
67   }
68
69   /**
70    * The profile to install as a basis for testing.
71    *
72    * @var string
73    */
74   protected $profile = 'testing';
75
76   /**
77    * The URL currently loaded in the internal browser.
78    *
79    * @var string
80    */
81   protected $url;
82
83   /**
84    * The handle of the current cURL connection.
85    *
86    * @var resource
87    */
88   protected $curlHandle;
89
90   /**
91    * Whether or not to assert the presence of the X-Drupal-Ajax-Token.
92    *
93    * @var bool
94    */
95   protected $assertAjaxHeader = TRUE;
96
97   /**
98    * The headers of the page currently loaded in the internal browser.
99    *
100    * @var array
101    */
102   protected $headers;
103
104   /**
105    * The cookies of the page currently loaded in the internal browser.
106    *
107    * @var array
108    */
109   protected $cookies = [];
110
111   /**
112    * Indicates that headers should be dumped if verbose output is enabled.
113    *
114    * Headers are dumped to verbose by drupalGet(), drupalHead(), and
115    * drupalPostForm().
116    *
117    * @var bool
118    */
119   protected $dumpHeaders = FALSE;
120
121   /**
122    * The current user logged in using the internal browser.
123    *
124    * @var \Drupal\Core\Session\AccountInterface|bool
125    */
126   protected $loggedInUser = FALSE;
127
128   /**
129    * The current cookie file used by cURL.
130    *
131    * We do not reuse the cookies in further runs, so we do not need a file
132    * but we still need cookie handling, so we set the jar to NULL.
133    */
134   protected $cookieFile = NULL;
135
136   /**
137    * Additional cURL options.
138    *
139    * \Drupal\simpletest\WebTestBase itself never sets this but always obeys what
140    * is set.
141    */
142   protected $additionalCurlOptions = [];
143
144   /**
145    * The original batch, before it was changed for testing purposes.
146    *
147    * @var array
148    */
149   protected $originalBatch;
150
151   /**
152    * The original user, before it was changed to a clean uid = 1 for testing.
153    *
154    * @var object
155    */
156   protected $originalUser = NULL;
157
158   /**
159    * The original shutdown handlers array, before it was cleaned for testing.
160    *
161    * @var array
162    */
163   protected $originalShutdownCallbacks = [];
164
165   /**
166    * The current session ID, if available.
167    */
168   protected $sessionId = NULL;
169
170   /**
171    * The maximum number of redirects to follow when handling responses.
172    *
173    * @var int
174    */
175   protected $maximumRedirects = 5;
176
177   /**
178    * The number of redirects followed during the handling of a request.
179    */
180   protected $redirectCount;
181
182
183   /**
184    * The number of meta refresh redirects to follow, or NULL if unlimited.
185    *
186    * @var null|int
187    */
188   protected $maximumMetaRefreshCount = NULL;
189
190   /**
191    * The number of meta refresh redirects followed during ::drupalGet().
192    *
193    * @var int
194    */
195   protected $metaRefreshCount = 0;
196
197   /**
198    * Cookies to set on curl requests.
199    *
200    * @var array
201    */
202   protected $curlCookies = [];
203
204   /**
205    * An array of custom translations suitable for drupal_rewrite_settings().
206    *
207    * @var array
208    */
209   protected $customTranslations;
210
211   /**
212    * Constructor for \Drupal\simpletest\WebTestBase.
213    */
214   public function __construct($test_id = NULL) {
215     parent::__construct($test_id);
216     $this->skipClasses[__CLASS__] = TRUE;
217     $this->classLoader = require DRUPAL_ROOT . '/autoload.php';
218   }
219
220   /**
221    * Checks to see whether a block appears on the page.
222    *
223    * @param \Drupal\block\Entity\Block $block
224    *   The block entity to find on the page.
225    */
226   protected function assertBlockAppears(Block $block) {
227     $result = $this->findBlockInstance($block);
228     $this->assertTrue(!empty($result), format_string('Ensure the block @id appears on the page', ['@id' => $block->id()]));
229   }
230
231   /**
232    * Checks to see whether a block does not appears on the page.
233    *
234    * @param \Drupal\block\Entity\Block $block
235    *   The block entity to find on the page.
236    */
237   protected function assertNoBlockAppears(Block $block) {
238     $result = $this->findBlockInstance($block);
239     $this->assertFalse(!empty($result), format_string('Ensure the block @id does not appear on the page', ['@id' => $block->id()]));
240   }
241
242   /**
243    * Find a block instance on the page.
244    *
245    * @param \Drupal\block\Entity\Block $block
246    *   The block entity to find on the page.
247    *
248    * @return array
249    *   The result from the xpath query.
250    */
251   protected function findBlockInstance(Block $block) {
252     return $this->xpath('//div[@id = :id]', [':id' => 'block-' . $block->id()]);
253   }
254
255   /**
256    * Log in a user with the internal browser.
257    *
258    * If a user is already logged in, then the current user is logged out before
259    * logging in the specified user.
260    *
261    * Please note that neither the current user nor the passed-in user object is
262    * populated with data of the logged in user. If you need full access to the
263    * user object after logging in, it must be updated manually. If you also need
264    * access to the plain-text password of the user (set by drupalCreateUser()),
265    * e.g. to log in the same user again, then it must be re-assigned manually.
266    * For example:
267    * @code
268    *   // Create a user.
269    *   $account = $this->drupalCreateUser(array());
270    *   $this->drupalLogin($account);
271    *   // Load real user object.
272    *   $pass_raw = $account->pass_raw;
273    *   $account = User::load($account->id());
274    *   $account->pass_raw = $pass_raw;
275    * @endcode
276    *
277    * @param \Drupal\Core\Session\AccountInterface $account
278    *   User object representing the user to log in.
279    *
280    * @see drupalCreateUser()
281    */
282   protected function drupalLogin(AccountInterface $account) {
283     if ($this->loggedInUser) {
284       $this->drupalLogout();
285     }
286
287     $edit = [
288       'name' => $account->getUsername(),
289       'pass' => $account->pass_raw,
290     ];
291     $this->drupalPostForm('user/login', $edit, t('Log in'));
292
293     // @see WebTestBase::drupalUserIsLoggedIn()
294     if (isset($this->sessionId)) {
295       $account->session_id = $this->sessionId;
296     }
297     $pass = $this->assert($this->drupalUserIsLoggedIn($account), format_string('User %name successfully logged in.', ['%name' => $account->getUsername()]), 'User login');
298     if ($pass) {
299       $this->loggedInUser = $account;
300       $this->container->get('current_user')->setAccount($account);
301     }
302   }
303
304   /**
305    * Returns whether a given user account is logged in.
306    *
307    * @param \Drupal\user\UserInterface $account
308    *   The user account object to check.
309    */
310   protected function drupalUserIsLoggedIn($account) {
311     $logged_in = FALSE;
312
313     if (isset($account->session_id)) {
314       $session_handler = $this->container->get('session_handler.storage');
315       $logged_in = (bool) $session_handler->read($account->session_id);
316     }
317
318     return $logged_in;
319   }
320
321   /**
322    * Logs a user out of the internal browser and confirms.
323    *
324    * Confirms logout by checking the login page.
325    */
326   protected function drupalLogout() {
327     // Make a request to the logout page, and redirect to the user page, the
328     // idea being if you were properly logged out you should be seeing a login
329     // screen.
330     $this->drupalGet('user/logout', ['query' => ['destination' => 'user/login']]);
331     $this->assertResponse(200, 'User was logged out.');
332     $pass = $this->assertField('name', 'Username field found.', 'Logout');
333     $pass = $pass && $this->assertField('pass', 'Password field found.', 'Logout');
334
335     if ($pass) {
336       // @see WebTestBase::drupalUserIsLoggedIn()
337       unset($this->loggedInUser->session_id);
338       $this->loggedInUser = FALSE;
339       $this->container->get('current_user')->setAccount(new AnonymousUserSession());
340     }
341   }
342
343   /**
344    * Sets up a Drupal site for running functional and integration tests.
345    *
346    * Installs Drupal with the installation profile specified in
347    * \Drupal\simpletest\WebTestBase::$profile into the prefixed database.
348    *
349    * Afterwards, installs any additional modules specified in the static
350    * \Drupal\simpletest\WebTestBase::$modules property of each class in the
351    * class hierarchy.
352    *
353    * After installation all caches are flushed and several configuration values
354    * are reset to the values of the parent site executing the test, since the
355    * default values may be incompatible with the environment in which tests are
356    * being executed.
357    */
358   protected function setUp() {
359     // Set an explicit time zone to not rely on the system one, which may vary
360     // from setup to setup. The Australia/Sydney time zone is chosen so all
361     // tests are run using an edge case scenario (UTC+10 and DST). This choice
362     // is made to prevent time zone related regressions and reduce the
363     // fragility of the testing system in general. This is also set in config in
364     // \Drupal\simpletest\WebTestBase::initConfig().
365     date_default_timezone_set('Australia/Sydney');
366
367     // Preserve original batch for later restoration.
368     $this->setBatch();
369
370     // Initialize user 1 and session name.
371     $this->initUserSession();
372
373     // Prepare the child site settings.
374     $this->prepareSettings();
375
376     // Execute the non-interactive installer.
377     $this->doInstall();
378
379     // Import new settings.php written by the installer.
380     $this->initSettings();
381
382     // Initialize the request and container post-install.
383     $container = $this->initKernel(\Drupal::request());
384
385     // Initialize and override certain configurations.
386     $this->initConfig($container);
387
388     // Collect modules to install.
389     $this->installModulesFromClassProperty($container);
390
391     // Restore the original batch.
392     $this->restoreBatch();
393
394     // Reset/rebuild everything.
395     $this->rebuildAll();
396   }
397
398   /**
399    * Preserve the original batch, and instantiate the test batch.
400    */
401   protected function setBatch() {
402     // When running tests through the Simpletest UI (vs. on the command line),
403     // Simpletest's batch conflicts with the installer's batch. Batch API does
404     // not support the concept of nested batches (in which the nested is not
405     // progressive), so we need to temporarily pretend there was no batch.
406     // Backup the currently running Simpletest batch.
407     $this->originalBatch = batch_get();
408
409     // Reset the static batch to remove Simpletest's batch operations.
410     $batch = &batch_get();
411     $batch = [];
412   }
413
414   /**
415    * Restore the original batch.
416    *
417    * @see ::setBatch
418    */
419   protected function restoreBatch() {
420     // Restore the original Simpletest batch.
421     $batch = &batch_get();
422     $batch = $this->originalBatch;
423   }
424
425   /**
426    * Queues custom translations to be written to settings.php.
427    *
428    * Use WebTestBase::writeCustomTranslations() to apply and write the queued
429    * translations.
430    *
431    * @param string $langcode
432    *   The langcode to add translations for.
433    * @param array $values
434    *   Array of values containing the untranslated string and its translation.
435    *   For example:
436    *   @code
437    *   array(
438    *     '' => array('Sunday' => 'domingo'),
439    *     'Long month name' => array('March' => 'marzo'),
440    *   );
441    *   @endcode
442    *   Pass an empty array to remove all existing custom translations for the
443    *   given $langcode.
444    */
445   protected function addCustomTranslations($langcode, array $values) {
446     // If $values is empty, then the test expects all custom translations to be
447     // cleared.
448     if (empty($values)) {
449       $this->customTranslations[$langcode] = [];
450     }
451     // Otherwise, $values are expected to be merged into previously passed
452     // values, while retaining keys that are not explicitly set.
453     else {
454       foreach ($values as $context => $translations) {
455         foreach ($translations as $original => $translation) {
456           $this->customTranslations[$langcode][$context][$original] = $translation;
457         }
458       }
459     }
460   }
461
462   /**
463    * Writes custom translations to the test site's settings.php.
464    *
465    * Use TestBase::addCustomTranslations() to queue custom translations before
466    * calling this method.
467    */
468   protected function writeCustomTranslations() {
469     $settings = [];
470     foreach ($this->customTranslations as $langcode => $values) {
471       $settings_key = 'locale_custom_strings_' . $langcode;
472
473       // Update in-memory settings directly.
474       $this->settingsSet($settings_key, $values);
475
476       $settings['settings'][$settings_key] = (object) [
477         'value' => $values,
478         'required' => TRUE,
479       ];
480     }
481     // Only rewrite settings if there are any translation changes to write.
482     if (!empty($settings)) {
483       $this->writeSettings($settings);
484     }
485   }
486
487   /**
488    * Cleans up after testing.
489    *
490    * Deletes created files and temporary files directory, deletes the tables
491    * created by setUp(), and resets the database prefix.
492    */
493   protected function tearDown() {
494     // Destroy the testing kernel.
495     if (isset($this->kernel)) {
496       $this->kernel->shutdown();
497     }
498     parent::tearDown();
499
500     // Ensure that the maximum meta refresh count is reset.
501     $this->maximumMetaRefreshCount = NULL;
502
503     // Ensure that internal logged in variable and cURL options are reset.
504     $this->loggedInUser = FALSE;
505     $this->additionalCurlOptions = [];
506
507     // Close the CURL handler and reset the cookies array used for upgrade
508     // testing so test classes containing multiple tests are not polluted.
509     $this->curlClose();
510     $this->curlCookies = [];
511     $this->cookies = [];
512   }
513
514   /**
515    * Initializes the cURL connection.
516    *
517    * If the simpletest_httpauth_credentials variable is set, this function will
518    * add HTTP authentication headers. This is necessary for testing sites that
519    * are protected by login credentials from public access.
520    * See the description of $curl_options for other options.
521    */
522   protected function curlInitialize() {
523     global $base_url;
524
525     if (!isset($this->curlHandle)) {
526       $this->curlHandle = curl_init();
527
528       // Some versions/configurations of cURL break on a NULL cookie jar, so
529       // supply a real file.
530       if (empty($this->cookieFile)) {
531         $this->cookieFile = $this->publicFilesDirectory . '/cookie.jar';
532       }
533
534       $curl_options = [
535         CURLOPT_COOKIEJAR => $this->cookieFile,
536         CURLOPT_URL => $base_url,
537         CURLOPT_FOLLOWLOCATION => FALSE,
538         CURLOPT_RETURNTRANSFER => TRUE,
539         // Required to make the tests run on HTTPS.
540         CURLOPT_SSL_VERIFYPEER => FALSE,
541         // Required to make the tests run on HTTPS.
542         CURLOPT_SSL_VERIFYHOST => FALSE,
543         CURLOPT_HEADERFUNCTION => [&$this, 'curlHeaderCallback'],
544         CURLOPT_USERAGENT => $this->databasePrefix,
545         // Disable support for the @ prefix for uploading files.
546         CURLOPT_SAFE_UPLOAD => TRUE,
547       ];
548       if (isset($this->httpAuthCredentials)) {
549         $curl_options[CURLOPT_HTTPAUTH] = $this->httpAuthMethod;
550         $curl_options[CURLOPT_USERPWD] = $this->httpAuthCredentials;
551       }
552       // curl_setopt_array() returns FALSE if any of the specified options
553       // cannot be set, and stops processing any further options.
554       $result = curl_setopt_array($this->curlHandle, $this->additionalCurlOptions + $curl_options);
555       if (!$result) {
556         throw new \UnexpectedValueException('One or more cURL options could not be set.');
557       }
558     }
559     // We set the user agent header on each request so as to use the current
560     // time and a new uniqid.
561     curl_setopt($this->curlHandle, CURLOPT_USERAGENT, drupal_generate_test_ua($this->databasePrefix));
562   }
563
564   /**
565    * Initializes and executes a cURL request.
566    *
567    * @param $curl_options
568    *   An associative array of cURL options to set, where the keys are constants
569    *   defined by the cURL library. For a list of valid options, see
570    *   http://php.net/manual/function.curl-setopt.php
571    * @param $redirect
572    *   FALSE if this is an initial request, TRUE if this request is the result
573    *   of a redirect.
574    *
575    * @return
576    *   The content returned from the call to curl_exec().
577    *
578    * @see curlInitialize()
579    */
580   protected function curlExec($curl_options, $redirect = FALSE) {
581     $this->curlInitialize();
582
583     if (!empty($curl_options[CURLOPT_URL])) {
584       // cURL incorrectly handles URLs with a fragment by including the
585       // fragment in the request to the server, causing some web servers
586       // to reject the request citing "400 - Bad Request". To prevent
587       // this, we strip the fragment from the request.
588       // TODO: Remove this for Drupal 8, since fixed in curl 7.20.0.
589       if (strpos($curl_options[CURLOPT_URL], '#')) {
590         $original_url = $curl_options[CURLOPT_URL];
591         $curl_options[CURLOPT_URL] = strtok($curl_options[CURLOPT_URL], '#');
592       }
593     }
594
595     $url = empty($curl_options[CURLOPT_URL]) ? curl_getinfo($this->curlHandle, CURLINFO_EFFECTIVE_URL) : $curl_options[CURLOPT_URL];
596
597     if (!empty($curl_options[CURLOPT_POST])) {
598       // This is a fix for the Curl library to prevent Expect: 100-continue
599       // headers in POST requests, that may cause unexpected HTTP response
600       // codes from some webservers (like lighttpd that returns a 417 error
601       // code). It is done by setting an empty "Expect" header field that is
602       // not overwritten by Curl.
603       $curl_options[CURLOPT_HTTPHEADER][] = 'Expect:';
604     }
605
606     $cookies = [];
607     if (!empty($this->curlCookies)) {
608       $cookies = $this->curlCookies;
609     }
610
611     foreach ($this->extractCookiesFromRequest(\Drupal::request()) as $cookie_name => $values) {
612       foreach ($values as $value) {
613         $cookies[] = $cookie_name . '=' . $value;
614       }
615     }
616
617     // Merge additional cookies in.
618     if (!empty($cookies)) {
619       $curl_options += [
620         CURLOPT_COOKIE => '',
621       ];
622       // Ensure any existing cookie data string ends with the correct separator.
623       if (!empty($curl_options[CURLOPT_COOKIE])) {
624         $curl_options[CURLOPT_COOKIE] = rtrim($curl_options[CURLOPT_COOKIE], '; ') . '; ';
625       }
626       $curl_options[CURLOPT_COOKIE] .= implode('; ', $cookies) . ';';
627     }
628
629     curl_setopt_array($this->curlHandle, $this->additionalCurlOptions + $curl_options);
630
631     if (!$redirect) {
632       // Reset headers, the session ID and the redirect counter.
633       $this->sessionId = NULL;
634       $this->headers = [];
635       $this->redirectCount = 0;
636     }
637
638     $content = curl_exec($this->curlHandle);
639     $status = curl_getinfo($this->curlHandle, CURLINFO_HTTP_CODE);
640
641     // cURL incorrectly handles URLs with fragments, so instead of
642     // letting cURL handle redirects we take of them ourselves to
643     // to prevent fragments being sent to the web server as part
644     // of the request.
645     // TODO: Remove this for Drupal 8, since fixed in curl 7.20.0.
646     if (in_array($status, [300, 301, 302, 303, 305, 307]) && $this->redirectCount < $this->maximumRedirects) {
647       if ($this->drupalGetHeader('location')) {
648         $this->redirectCount++;
649         $curl_options = [];
650         $curl_options[CURLOPT_URL] = $this->drupalGetHeader('location');
651         $curl_options[CURLOPT_HTTPGET] = TRUE;
652         return $this->curlExec($curl_options, TRUE);
653       }
654     }
655
656     $this->setRawContent($content);
657     $this->url = isset($original_url) ? $original_url : curl_getinfo($this->curlHandle, CURLINFO_EFFECTIVE_URL);
658
659     $message_vars = [
660       '@method' => !empty($curl_options[CURLOPT_NOBODY]) ? 'HEAD' : (empty($curl_options[CURLOPT_POSTFIELDS]) ? 'GET' : 'POST'),
661       '@url' => isset($original_url) ? $original_url : $url,
662       '@status' => $status,
663       '@length' => format_size(strlen($this->getRawContent())),
664     ];
665     $message = new FormattableMarkup('@method @url returned @status (@length).', $message_vars);
666     $this->assertTrue($this->getRawContent() !== FALSE, $message, 'Browser');
667     return $this->getRawContent();
668   }
669
670   /**
671    * Reads headers and registers errors received from the tested site.
672    *
673    * @param $curlHandler
674    *   The cURL handler.
675    * @param $header
676    *   An header.
677    *
678    * @see _drupal_log_error()
679    */
680   protected function curlHeaderCallback($curlHandler, $header) {
681     // Header fields can be extended over multiple lines by preceding each
682     // extra line with at least one SP or HT. They should be joined on receive.
683     // Details are in RFC2616 section 4.
684     if ($header[0] == ' ' || $header[0] == "\t") {
685       // Normalize whitespace between chucks.
686       $this->headers[] = array_pop($this->headers) . ' ' . trim($header);
687     }
688     else {
689       $this->headers[] = $header;
690     }
691
692     // Errors are being sent via X-Drupal-Assertion-* headers,
693     // generated by _drupal_log_error() in the exact form required
694     // by \Drupal\simpletest\WebTestBase::error().
695     if (preg_match('/^X-Drupal-Assertion-[0-9]+: (.*)$/', $header, $matches)) {
696       $parameters = unserialize(urldecode($matches[1]));
697       // Handle deprecation notices triggered by system under test.
698       if ($parameters[1] === 'User deprecated function') {
699         if (getenv('SYMFONY_DEPRECATIONS_HELPER') !== 'disabled') {
700           $message = (string) $parameters[0];
701           $test_info = TestDiscovery::getTestInfo(get_called_class());
702           if ($test_info['group'] !== 'legacy' && !in_array($message, DeprecationListenerTrait::getSkippedDeprecations())) {
703             call_user_func_array([&$this, 'error'], $parameters);
704           }
705         }
706       }
707       else {
708         // Call \Drupal\simpletest\WebTestBase::error() with the parameters from
709         // the header.
710         call_user_func_array([&$this, 'error'], $parameters);
711       }
712     }
713
714     // Save cookies.
715     if (preg_match('/^Set-Cookie: ([^=]+)=(.+)/', $header, $matches)) {
716       $name = $matches[1];
717       $parts = array_map('trim', explode(';', $matches[2]));
718       $value = array_shift($parts);
719       $this->cookies[$name] = ['value' => $value, 'secure' => in_array('secure', $parts)];
720       if ($name === $this->getSessionName()) {
721         if ($value != 'deleted') {
722           $this->sessionId = $value;
723         }
724         else {
725           $this->sessionId = NULL;
726         }
727       }
728     }
729
730     // This is required by cURL.
731     return strlen($header);
732   }
733
734   /**
735    * Close the cURL handler and unset the handler.
736    */
737   protected function curlClose() {
738     if (isset($this->curlHandle)) {
739       curl_close($this->curlHandle);
740       unset($this->curlHandle);
741     }
742   }
743
744   /**
745    * Returns whether the test is being executed from within a test site.
746    *
747    * Mainly used by recursive tests (i.e. to test the testing framework).
748    *
749    * @return bool
750    *   TRUE if this test was instantiated in a request within the test site,
751    *   FALSE otherwise.
752    *
753    * @see \Drupal\Core\DrupalKernel::bootConfiguration()
754    */
755   protected function isInChildSite() {
756     return DRUPAL_TEST_IN_CHILD_SITE;
757   }
758
759   /**
760    * Retrieves a Drupal path or an absolute path.
761    *
762    * @param \Drupal\Core\Url|string $path
763    *   Drupal path or URL to load into internal browser
764    * @param $options
765    *   Options to be forwarded to the url generator.
766    * @param $headers
767    *   An array containing additional HTTP request headers, each formatted as
768    *   "name: value".
769    *
770    * @return string
771    *   The retrieved HTML string, also available as $this->getRawContent()
772    */
773   protected function drupalGet($path, array $options = [], array $headers = []) {
774     // We re-using a CURL connection here. If that connection still has certain
775     // options set, it might change the GET into a POST. Make sure we clear out
776     // previous options.
777     $out = $this->curlExec([CURLOPT_HTTPGET => TRUE, CURLOPT_URL => $this->buildUrl($path, $options), CURLOPT_NOBODY => FALSE, CURLOPT_HTTPHEADER => $headers]);
778     // Ensure that any changes to variables in the other thread are picked up.
779     $this->refreshVariables();
780
781     // Replace original page output with new output from redirected page(s).
782     if ($new = $this->checkForMetaRefresh()) {
783       $out = $new;
784       // We are finished with all meta refresh redirects, so reset the counter.
785       $this->metaRefreshCount = 0;
786     }
787
788     if ($path instanceof Url) {
789       $path = $path->setAbsolute()->toString(TRUE)->getGeneratedUrl();
790     }
791
792     $verbose = 'GET request to: ' . $path .
793                '<hr />Ending URL: ' . $this->getUrl();
794     if ($this->dumpHeaders) {
795       $verbose .= '<hr />Headers: <pre>' . Html::escape(var_export(array_map('trim', $this->headers), TRUE)) . '</pre>';
796     }
797     $verbose .= '<hr />' . $out;
798
799     $this->verbose($verbose);
800     return $out;
801   }
802
803   /**
804    * Retrieves a Drupal path or an absolute path and JSON decodes the result.
805    *
806    * @param \Drupal\Core\Url|string $path
807    *   Drupal path or URL to request AJAX from.
808    * @param array $options
809    *   Array of URL options.
810    * @param array $headers
811    *   Array of headers. Eg array('Accept: application/vnd.drupal-ajax').
812    *
813    * @return array
814    *   Decoded json.
815    */
816   protected function drupalGetJSON($path, array $options = [], array $headers = []) {
817     return Json::decode($this->drupalGetWithFormat($path, 'json', $options, $headers));
818   }
819
820   /**
821    * Retrieves a Drupal path or an absolute path for a given format.
822    *
823    * @param \Drupal\Core\Url|string $path
824    *   Drupal path or URL to request given format from.
825    * @param string $format
826    *   The wanted request format.
827    * @param array $options
828    *   Array of URL options.
829    * @param array $headers
830    *   Array of headers.
831    *
832    * @return mixed
833    *   The result of the request.
834    */
835   protected function drupalGetWithFormat($path, $format, array $options = [], array $headers = []) {
836     $options = array_merge_recursive(['query' => ['_format' => $format]], $options);
837     return $this->drupalGet($path, $options, $headers);
838   }
839
840   /**
841    * Requests a path or URL in drupal_ajax format and JSON-decodes the response.
842    *
843    * @param \Drupal\Core\Url|string $path
844    *   Drupal path or URL to request from.
845    * @param array $options
846    *   Array of URL options.
847    * @param array $headers
848    *   Array of headers.
849    *
850    * @return array
851    *   Decoded JSON.
852    */
853   protected function drupalGetAjax($path, array $options = [], array $headers = []) {
854     if (!isset($options['query'][MainContentViewSubscriber::WRAPPER_FORMAT])) {
855       $options['query'][MainContentViewSubscriber::WRAPPER_FORMAT] = 'drupal_ajax';
856     }
857     return Json::decode($this->drupalGetXHR($path, $options, $headers));
858   }
859
860   /**
861    * Requests a Drupal path or an absolute path as if it is a XMLHttpRequest.
862    *
863    * @param \Drupal\Core\Url|string $path
864    *   Drupal path or URL to request from.
865    * @param array $options
866    *   Array of URL options.
867    * @param array $headers
868    *   Array of headers.
869    *
870    * @return string
871    *   The retrieved content.
872    */
873   protected function drupalGetXHR($path, array $options = [], array $headers = []) {
874     $headers[] = 'X-Requested-With: XMLHttpRequest';
875     return $this->drupalGet($path, $options, $headers);
876   }
877
878   /**
879    * Executes a form submission.
880    *
881    * It will be done as usual POST request with SimpleBrowser.
882    *
883    * @param \Drupal\Core\Url|string $path
884    *   Location of the post form. Either a Drupal path or an absolute path or
885    *   NULL to post to the current page. For multi-stage forms you can set the
886    *   path to NULL and have it post to the last received page. Example:
887    *
888    *   @code
889    *   // First step in form.
890    *   $edit = array(...);
891    *   $this->drupalPostForm('some_url', $edit, t('Save'));
892    *
893    *   // Second step in form.
894    *   $edit = array(...);
895    *   $this->drupalPostForm(NULL, $edit, t('Save'));
896    *   @endcode
897    * @param $edit
898    *   Field data in an associative array. Changes the current input fields
899    *   (where possible) to the values indicated.
900    *
901    *   When working with form tests, the keys for an $edit element should match
902    *   the 'name' parameter of the HTML of the form. For example, the 'body'
903    *   field for a node has the following HTML:
904    *   @code
905    *   <textarea id="edit-body-und-0-value" class="text-full form-textarea
906    *    resize-vertical" placeholder="" cols="60" rows="9"
907    *    name="body[0][value]"></textarea>
908    *   @endcode
909    *   When testing this field using an $edit parameter, the code becomes:
910    *   @code
911    *   $edit["body[0][value]"] = 'My test value';
912    *   @endcode
913    *
914    *   A checkbox can be set to TRUE to be checked and should be set to FALSE to
915    *   be unchecked. Multiple select fields can be tested using 'name[]' and
916    *   setting each of the desired values in an array:
917    *   @code
918    *   $edit = array();
919    *   $edit['name[]'] = array('value1', 'value2');
920    *   @endcode
921    * @param $submit
922    *   Value of the submit button whose click is to be emulated. For example,
923    *   t('Save'). The processing of the request depends on this value. For
924    *   example, a form may have one button with the value t('Save') and another
925    *   button with the value t('Delete'), and execute different code depending
926    *   on which one is clicked.
927    *
928    *   This function can also be called to emulate an Ajax submission. In this
929    *   case, this value needs to be an array with the following keys:
930    *   - path: A path to submit the form values to for Ajax-specific processing.
931    *   - triggering_element: If the value for the 'path' key is a generic Ajax
932    *     processing path, this needs to be set to the name of the element. If
933    *     the name doesn't identify the element uniquely, then this should
934    *     instead be an array with a single key/value pair, corresponding to the
935    *     element name and value. The \Drupal\Core\Form\FormAjaxResponseBuilder
936    *     uses this to find the #ajax information for the element, including
937    *     which specific callback to use for processing the request.
938    *
939    *   This can also be set to NULL in order to emulate an Internet Explorer
940    *   submission of a form with a single text field, and pressing ENTER in that
941    *   textfield: under these conditions, no button information is added to the
942    *   POST data.
943    * @param $options
944    *   Options to be forwarded to the url generator.
945    * @param $headers
946    *   An array containing additional HTTP request headers, each formatted as
947    *   "name: value".
948    * @param $form_html_id
949    *   (optional) HTML ID of the form to be submitted. On some pages
950    *   there are many identical forms, so just using the value of the submit
951    *   button is not enough. For example: 'trigger-node-presave-assign-form'.
952    *   Note that this is not the Drupal $form_id, but rather the HTML ID of the
953    *   form, which is typically the same thing but with hyphens replacing the
954    *   underscores.
955    * @param $extra_post
956    *   (optional) A string of additional data to append to the POST submission.
957    *   This can be used to add POST data for which there are no HTML fields, as
958    *   is done by drupalPostAjaxForm(). This string is literally appended to the
959    *   POST data, so it must already be urlencoded and contain a leading "&"
960    *   (e.g., "&extra_var1=hello+world&extra_var2=you%26me").
961    */
962   protected function drupalPostForm($path, $edit, $submit, array $options = [], array $headers = [], $form_html_id = NULL, $extra_post = NULL) {
963     if (is_object($submit)) {
964       // Cast MarkupInterface objects to string.
965       $submit = (string) $submit;
966     }
967     if (is_array($edit)) {
968       $edit = $this->castSafeStrings($edit);
969     }
970
971     $submit_matches = FALSE;
972     $ajax = is_array($submit);
973     if (isset($path)) {
974       $this->drupalGet($path, $options);
975     }
976
977     if ($this->parse()) {
978       $edit_save = $edit;
979       // Let's iterate over all the forms.
980       $xpath = "//form";
981       if (!empty($form_html_id)) {
982         $xpath .= "[@id='" . $form_html_id . "']";
983       }
984       $forms = $this->xpath($xpath);
985       foreach ($forms as $form) {
986         // We try to set the fields of this form as specified in $edit.
987         $edit = $edit_save;
988         $post = [];
989         $upload = [];
990         $submit_matches = $this->handleForm($post, $edit, $upload, $ajax ? NULL : $submit, $form);
991         $action = isset($form['action']) ? $this->getAbsoluteUrl((string) $form['action']) : $this->getUrl();
992         if ($ajax) {
993           if (empty($submit['path'])) {
994             throw new \Exception('No #ajax path specified.');
995           }
996           $action = $this->getAbsoluteUrl($submit['path']);
997           // Ajax callbacks verify the triggering element if necessary, so while
998           // we may eventually want extra code that verifies it in the
999           // handleForm() function, it's not currently a requirement.
1000           $submit_matches = TRUE;
1001         }
1002         // We post only if we managed to handle every field in edit and the
1003         // submit button matches.
1004         if (!$edit && ($submit_matches || !isset($submit))) {
1005           $post_array = $post;
1006           if ($upload) {
1007             foreach ($upload as $key => $file) {
1008               if (is_array($file) && count($file)) {
1009                 // There seems to be no way via php's API to cURL to upload
1010                 // several files with the same post field name. However, Drupal
1011                 // still sees array-index syntax in a similar way.
1012                 for ($i = 0; $i < count($file); $i++) {
1013                   $postfield = str_replace('[]', '', $key) . '[' . $i . ']';
1014                   $file_path = $this->container->get('file_system')->realpath($file[$i]);
1015                   $post[$postfield] = curl_file_create($file_path);
1016                 }
1017               }
1018               else {
1019                 $file = $this->container->get('file_system')->realpath($file);
1020                 if ($file && is_file($file)) {
1021                   $post[$key] = curl_file_create($file);
1022                 }
1023               }
1024             }
1025           }
1026           else {
1027             $post = $this->serializePostValues($post) . $extra_post;
1028           }
1029           $out = $this->curlExec([CURLOPT_URL => $action, CURLOPT_POST => TRUE, CURLOPT_POSTFIELDS => $post, CURLOPT_HTTPHEADER => $headers]);
1030           // Ensure that any changes to variables in the other thread are picked
1031           // up.
1032           $this->refreshVariables();
1033
1034           // Replace original page output with new output from redirected
1035           // page(s).
1036           if ($new = $this->checkForMetaRefresh()) {
1037             $out = $new;
1038           }
1039
1040           if ($path instanceof Url) {
1041             $path = $path->toString();
1042           }
1043           $verbose = 'POST request to: ' . $path;
1044           $verbose .= '<hr />Ending URL: ' . $this->getUrl();
1045           if ($this->dumpHeaders) {
1046             $verbose .= '<hr />Headers: <pre>' . Html::escape(var_export(array_map('trim', $this->headers), TRUE)) . '</pre>';
1047           }
1048           $verbose .= '<hr />Fields: ' . highlight_string('<?php ' . var_export($post_array, TRUE), TRUE);
1049           $verbose .= '<hr />' . $out;
1050
1051           $this->verbose($verbose);
1052           return $out;
1053         }
1054       }
1055       // We have not found a form which contained all fields of $edit.
1056       foreach ($edit as $name => $value) {
1057         $this->fail(new FormattableMarkup('Failed to set field @name to @value', ['@name' => $name, '@value' => $value]));
1058       }
1059       if (!$ajax && isset($submit)) {
1060         $this->assertTrue($submit_matches, format_string('Found the @submit button', ['@submit' => $submit]));
1061       }
1062       $this->fail(format_string('Found the requested form fields at @path', ['@path' => ($path instanceof Url) ? $path->toString() : $path]));
1063     }
1064   }
1065
1066   /**
1067    * Executes an Ajax form submission.
1068    *
1069    * This executes a POST as ajax.js does. The returned JSON data is used to
1070    * update $this->content via drupalProcessAjaxResponse(). It also returns
1071    * the array of AJAX commands received.
1072    *
1073    * @param \Drupal\Core\Url|string $path
1074    *   Location of the form containing the Ajax enabled element to test. Can be
1075    *   either a Drupal path or an absolute path or NULL to use the current page.
1076    * @param $edit
1077    *   Field data in an associative array. Changes the current input fields
1078    *   (where possible) to the values indicated.
1079    * @param $triggering_element
1080    *   The name of the form element that is responsible for triggering the Ajax
1081    *   functionality to test. May be a string or, if the triggering element is
1082    *   a button, an associative array where the key is the name of the button
1083    *   and the value is the button label. i.e.) array('op' => t('Refresh')).
1084    * @param $ajax_path
1085    *   (optional) Override the path set by the Ajax settings of the triggering
1086    *   element.
1087    * @param $options
1088    *   (optional) Options to be forwarded to the url generator.
1089    * @param $headers
1090    *   (optional) An array containing additional HTTP request headers, each
1091    *   formatted as "name: value". Forwarded to drupalPostForm().
1092    * @param $form_html_id
1093    *   (optional) HTML ID of the form to be submitted, use when there is more
1094    *   than one identical form on the same page and the value of the triggering
1095    *   element is not enough to identify the form. Note this is not the Drupal
1096    *   ID of the form but rather the HTML ID of the form.
1097    * @param $ajax_settings
1098    *   (optional) An array of Ajax settings which if specified will be used in
1099    *   place of the Ajax settings of the triggering element.
1100    *
1101    * @return
1102    *   An array of Ajax commands.
1103    *
1104    * @see drupalPostForm()
1105    * @see drupalProcessAjaxResponse()
1106    * @see ajax.js
1107    */
1108   protected function drupalPostAjaxForm($path, $edit, $triggering_element, $ajax_path = NULL, array $options = [], array $headers = [], $form_html_id = NULL, $ajax_settings = NULL) {
1109
1110     // Get the content of the initial page prior to calling drupalPostForm(),
1111     // since drupalPostForm() replaces $this->content.
1112     if (isset($path)) {
1113       // Avoid sending the wrapper query argument to drupalGet so we can fetch
1114       // the form and populate the internal WebTest values.
1115       $get_options = $options;
1116       unset($get_options['query'][MainContentViewSubscriber::WRAPPER_FORMAT]);
1117       $this->drupalGet($path, $get_options);
1118     }
1119     $content = $this->content;
1120     $drupal_settings = $this->drupalSettings;
1121
1122     // Provide a default value for the wrapper envelope.
1123     $options['query'][MainContentViewSubscriber::WRAPPER_FORMAT] =
1124       isset($options['query'][MainContentViewSubscriber::WRAPPER_FORMAT]) ?
1125         $options['query'][MainContentViewSubscriber::WRAPPER_FORMAT] :
1126         'drupal_ajax';
1127
1128     // Get the Ajax settings bound to the triggering element.
1129     if (!isset($ajax_settings)) {
1130       if (is_array($triggering_element)) {
1131         $xpath = '//*[@name="' . key($triggering_element) . '" and @value="' . current($triggering_element) . '"]';
1132       }
1133       else {
1134         $xpath = '//*[@name="' . $triggering_element . '"]';
1135       }
1136       if (isset($form_html_id)) {
1137         $xpath = '//form[@id="' . $form_html_id . '"]' . $xpath;
1138       }
1139       $element = $this->xpath($xpath);
1140       $element_id = (string) $element[0]['id'];
1141       $ajax_settings = $drupal_settings['ajax'][$element_id];
1142     }
1143
1144     // Add extra information to the POST data as ajax.js does.
1145     $extra_post = [];
1146     if (isset($ajax_settings['submit'])) {
1147       foreach ($ajax_settings['submit'] as $key => $value) {
1148         $extra_post[$key] = $value;
1149       }
1150     }
1151     $extra_post[AjaxResponseSubscriber::AJAX_REQUEST_PARAMETER] = 1;
1152     $extra_post += $this->getAjaxPageStatePostData();
1153     // Now serialize all the $extra_post values, and prepend it with an '&'.
1154     $extra_post = '&' . $this->serializePostValues($extra_post);
1155
1156     // Unless a particular path is specified, use the one specified by the
1157     // Ajax settings.
1158     if (!isset($ajax_path)) {
1159       if (isset($ajax_settings['url'])) {
1160         // In order to allow to set for example the wrapper envelope query
1161         // parameter we need to get the system path again.
1162         $parsed_url = UrlHelper::parse($ajax_settings['url']);
1163         $options['query'] = $parsed_url['query'] + $options['query'];
1164         $options += ['fragment' => $parsed_url['fragment']];
1165
1166         // We know that $parsed_url['path'] is already with the base path
1167         // attached.
1168         $ajax_path = preg_replace(
1169           '/^' . preg_quote(base_path(), '/') . '/',
1170           '',
1171           $parsed_url['path']
1172         );
1173       }
1174     }
1175
1176     if (empty($ajax_path)) {
1177       throw new \Exception('No #ajax path specified.');
1178     }
1179
1180     $ajax_path = $this->container->get('unrouted_url_assembler')->assemble('base://' . $ajax_path, $options);
1181
1182     // Submit the POST request.
1183     $return = Json::decode($this->drupalPostForm(NULL, $edit, ['path' => $ajax_path, 'triggering_element' => $triggering_element], $options, $headers, $form_html_id, $extra_post));
1184     if ($this->assertAjaxHeader) {
1185       $this->assertIdentical($this->drupalGetHeader('X-Drupal-Ajax-Token'), '1', 'Ajax response header found.');
1186     }
1187
1188     // Change the page content by applying the returned commands.
1189     if (!empty($ajax_settings) && !empty($return)) {
1190       $this->drupalProcessAjaxResponse($content, $return, $ajax_settings, $drupal_settings);
1191     }
1192
1193     $verbose = 'AJAX POST request to: ' . $path;
1194     $verbose .= '<br />AJAX controller path: ' . $ajax_path;
1195     $verbose .= '<hr />Ending URL: ' . $this->getUrl();
1196     $verbose .= '<hr />' . $this->content;
1197
1198     $this->verbose($verbose);
1199
1200     return $return;
1201   }
1202
1203   /**
1204    * Processes an AJAX response into current content.
1205    *
1206    * This processes the AJAX response as ajax.js does. It uses the response's
1207    * JSON data, an array of commands, to update $this->content using equivalent
1208    * DOM manipulation as is used by ajax.js.
1209    * It does not apply custom AJAX commands though, because emulation is only
1210    * implemented for the AJAX commands that ship with Drupal core.
1211    *
1212    * @param string $content
1213    *   The current HTML content.
1214    * @param array $ajax_response
1215    *   An array of AJAX commands.
1216    * @param array $ajax_settings
1217    *   An array of AJAX settings which will be used to process the response.
1218    * @param array $drupal_settings
1219    *   An array of settings to update the value of drupalSettings for the
1220    *   currently-loaded page.
1221    *
1222    * @see drupalPostAjaxForm()
1223    * @see ajax.js
1224    */
1225   protected function drupalProcessAjaxResponse($content, array $ajax_response, array $ajax_settings, array $drupal_settings) {
1226
1227     // ajax.js applies some defaults to the settings object, so do the same
1228     // for what's used by this function.
1229     $ajax_settings += [
1230       'method' => 'replaceWith',
1231     ];
1232     // DOM can load HTML soup. But, HTML soup can throw warnings, suppress
1233     // them.
1234     $dom = new \DOMDocument();
1235     @$dom->loadHTML($content);
1236     // XPath allows for finding wrapper nodes better than DOM does.
1237     $xpath = new \DOMXPath($dom);
1238     foreach ($ajax_response as $command) {
1239       // Error messages might be not commands.
1240       if (!is_array($command)) {
1241         continue;
1242       }
1243       switch ($command['command']) {
1244         case 'settings':
1245           $drupal_settings = NestedArray::mergeDeepArray([$drupal_settings, $command['settings']], TRUE);
1246           break;
1247
1248         case 'insert':
1249           $wrapperNode = NULL;
1250           // When a command doesn't specify a selector, use the
1251           // #ajax['wrapper'] which is always an HTML ID.
1252           if (!isset($command['selector'])) {
1253             $wrapperNode = $xpath->query('//*[@id="' . $ajax_settings['wrapper'] . '"]')->item(0);
1254           }
1255           // @todo Ajax commands can target any jQuery selector, but these are
1256           //   hard to fully emulate with XPath. For now, just handle 'head'
1257           //   and 'body', since these are used by the Ajax renderer.
1258           elseif (in_array($command['selector'], ['head', 'body'])) {
1259             $wrapperNode = $xpath->query('//' . $command['selector'])->item(0);
1260           }
1261           if ($wrapperNode) {
1262             // ajax.js adds an enclosing DIV to work around a Safari bug.
1263             $newDom = new \DOMDocument();
1264             // DOM can load HTML soup. But, HTML soup can throw warnings,
1265             // suppress them.
1266             @$newDom->loadHTML('<div>' . $command['data'] . '</div>');
1267             // Suppress warnings thrown when duplicate HTML IDs are encountered.
1268             // This probably means we are replacing an element with the same ID.
1269             $newNode = @$dom->importNode($newDom->documentElement->firstChild->firstChild, TRUE);
1270             $method = isset($command['method']) ? $command['method'] : $ajax_settings['method'];
1271             // The "method" is a jQuery DOM manipulation function. Emulate
1272             // each one using PHP's DOMNode API.
1273             switch ($method) {
1274               case 'replaceWith':
1275                 $wrapperNode->parentNode->replaceChild($newNode, $wrapperNode);
1276                 break;
1277               case 'append':
1278                 $wrapperNode->appendChild($newNode);
1279                 break;
1280               case 'prepend':
1281                 // If no firstChild, insertBefore() falls back to
1282                 // appendChild().
1283                 $wrapperNode->insertBefore($newNode, $wrapperNode->firstChild);
1284                 break;
1285               case 'before':
1286                 $wrapperNode->parentNode->insertBefore($newNode, $wrapperNode);
1287                 break;
1288               case 'after':
1289                 // If no nextSibling, insertBefore() falls back to
1290                 // appendChild().
1291                 $wrapperNode->parentNode->insertBefore($newNode, $wrapperNode->nextSibling);
1292                 break;
1293               case 'html':
1294                 foreach ($wrapperNode->childNodes as $childNode) {
1295                   $wrapperNode->removeChild($childNode);
1296                 }
1297                 $wrapperNode->appendChild($newNode);
1298                 break;
1299             }
1300           }
1301           break;
1302
1303         // @todo Add suitable implementations for these commands in order to
1304         //   have full test coverage of what ajax.js can do.
1305         case 'remove':
1306           break;
1307         case 'changed':
1308           break;
1309         case 'css':
1310           break;
1311         case 'data':
1312           break;
1313         case 'restripe':
1314           break;
1315         case 'add_css':
1316           break;
1317         case 'update_build_id':
1318           $buildId = $xpath->query('//input[@name="form_build_id" and @value="' . $command['old'] . '"]')->item(0);
1319           if ($buildId) {
1320             $buildId->setAttribute('value', $command['new']);
1321           }
1322           break;
1323       }
1324     }
1325     $content = $dom->saveHTML();
1326     $this->setRawContent($content);
1327     $this->setDrupalSettings($drupal_settings);
1328   }
1329
1330   /**
1331    * Perform a POST HTTP request.
1332    *
1333    * @param string|\Drupal\Core\Url $path
1334    *   Drupal path or absolute path where the request should be POSTed.
1335    * @param string $accept
1336    *   The value for the "Accept" header. Usually either 'application/json' or
1337    *   'application/vnd.drupal-ajax'.
1338    * @param array $post
1339    *   The POST data. When making a 'application/vnd.drupal-ajax' request, the
1340    *   Ajax page state data should be included. Use getAjaxPageStatePostData()
1341    *   for that.
1342    * @param array $options
1343    *   (optional) Options to be forwarded to the url generator. The 'absolute'
1344    *   option will automatically be enabled.
1345    *
1346    * @return
1347    *   The content returned from the call to curl_exec().
1348    *
1349    * @see WebTestBase::getAjaxPageStatePostData()
1350    * @see WebTestBase::curlExec()
1351    */
1352   protected function drupalPost($path, $accept, array $post, $options = []) {
1353     return $this->curlExec([
1354       CURLOPT_URL => $this->buildUrl($path, $options),
1355       CURLOPT_POST => TRUE,
1356       CURLOPT_POSTFIELDS => $this->serializePostValues($post),
1357       CURLOPT_HTTPHEADER => [
1358         'Accept: ' . $accept,
1359         'Content-Type: application/x-www-form-urlencoded',
1360       ],
1361     ]);
1362   }
1363
1364   /**
1365    * Performs a POST HTTP request with a specific format.
1366    *
1367    * @param string|\Drupal\Core\Url $path
1368    *   Drupal path or absolute path where the request should be POSTed.
1369    * @param string $format
1370    *   The request format.
1371    * @param array $post
1372    *   The POST data. When making a 'application/vnd.drupal-ajax' request, the
1373    *   Ajax page state data should be included. Use getAjaxPageStatePostData()
1374    *   for that.
1375    * @param array $options
1376    *   (optional) Options to be forwarded to the url generator. The 'absolute'
1377    *   option will automatically be enabled.
1378    *
1379    * @return string
1380    *   The content returned from the call to curl_exec().
1381    *
1382    * @see WebTestBase::drupalPost
1383    * @see WebTestBase::getAjaxPageStatePostData()
1384    * @see WebTestBase::curlExec()
1385    */
1386   protected function drupalPostWithFormat($path, $format, array $post, $options = []) {
1387     $options['query']['_format'] = $format;
1388     return $this->drupalPost($path, '', $post, $options);
1389   }
1390
1391   /**
1392    * Get the Ajax page state from drupalSettings and prepare it for POSTing.
1393    *
1394    * @return array
1395    *   The Ajax page state POST data.
1396    */
1397   protected function getAjaxPageStatePostData() {
1398     $post = [];
1399     $drupal_settings = $this->drupalSettings;
1400     if (isset($drupal_settings['ajaxPageState']['theme'])) {
1401       $post['ajax_page_state[theme]'] = $drupal_settings['ajaxPageState']['theme'];
1402     }
1403     if (isset($drupal_settings['ajaxPageState']['theme_token'])) {
1404       $post['ajax_page_state[theme_token]'] = $drupal_settings['ajaxPageState']['theme_token'];
1405     }
1406     if (isset($drupal_settings['ajaxPageState']['libraries'])) {
1407       $post['ajax_page_state[libraries]'] = $drupal_settings['ajaxPageState']['libraries'];
1408     }
1409     return $post;
1410   }
1411
1412   /**
1413    * Serialize POST HTTP request values.
1414    *
1415    * Encode according to application/x-www-form-urlencoded. Both names and
1416    * values needs to be urlencoded, according to
1417    * http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.1
1418    *
1419    * @param array $post
1420    *   The array of values to be POSTed.
1421    *
1422    * @return string
1423    *   The serialized result.
1424    */
1425   protected function serializePostValues($post = []) {
1426     foreach ($post as $key => $value) {
1427       $post[$key] = urlencode($key) . '=' . urlencode($value);
1428     }
1429     return implode('&', $post);
1430   }
1431
1432   /**
1433    * Transforms a nested array into a flat array suitable for WebTestBase::drupalPostForm().
1434    *
1435    * @param array $values
1436    *   A multi-dimensional form values array to convert.
1437    *
1438    * @return array
1439    *   The flattened $edit array suitable for WebTestBase::drupalPostForm().
1440    */
1441   protected function translatePostValues(array $values) {
1442     $edit = [];
1443     // The easiest and most straightforward way to translate values suitable for
1444     // WebTestBase::drupalPostForm() is to actually build the POST data string
1445     // and convert the resulting key/value pairs back into a flat array.
1446     $query = http_build_query($values);
1447     foreach (explode('&', $query) as $item) {
1448       list($key, $value) = explode('=', $item);
1449       $edit[urldecode($key)] = urldecode($value);
1450     }
1451     return $edit;
1452   }
1453
1454   /**
1455    * Checks for meta refresh tag and if found call drupalGet() recursively.
1456    *
1457    * This function looks for the http-equiv attribute to be set to "Refresh" and
1458    * is case-sensitive.
1459    *
1460    * @return
1461    *   Either the new page content or FALSE.
1462    */
1463   protected function checkForMetaRefresh() {
1464     if (strpos($this->getRawContent(), '<meta ') && $this->parse() && (!isset($this->maximumMetaRefreshCount) || $this->metaRefreshCount < $this->maximumMetaRefreshCount)) {
1465       $refresh = $this->xpath('//meta[@http-equiv="Refresh"]');
1466       if (!empty($refresh)) {
1467         // Parse the content attribute of the meta tag for the format:
1468         // "[delay]: URL=[page_to_redirect_to]".
1469         if (preg_match('/\d+;\s*URL=(?<url>.*)/i', $refresh[0]['content'], $match)) {
1470           $this->metaRefreshCount++;
1471           return $this->drupalGet($this->getAbsoluteUrl(Html::decodeEntities($match['url'])));
1472         }
1473       }
1474     }
1475     return FALSE;
1476   }
1477
1478   /**
1479    * Retrieves only the headers for a Drupal path or an absolute path.
1480    *
1481    * @param $path
1482    *   Drupal path or URL to load into internal browser
1483    * @param $options
1484    *   Options to be forwarded to the url generator.
1485    * @param $headers
1486    *   An array containing additional HTTP request headers, each formatted as
1487    *   "name: value".
1488    *
1489    * @return
1490    *   The retrieved headers, also available as $this->getRawContent()
1491    */
1492   protected function drupalHead($path, array $options = [], array $headers = []) {
1493     $options['absolute'] = TRUE;
1494     $url = $this->buildUrl($path, $options);
1495     $out = $this->curlExec([CURLOPT_NOBODY => TRUE, CURLOPT_URL => $url, CURLOPT_HTTPHEADER => $headers]);
1496     // Ensure that any changes to variables in the other thread are picked up.
1497     $this->refreshVariables();
1498
1499     if ($this->dumpHeaders) {
1500       $this->verbose('GET request to: ' . $path .
1501                      '<hr />Ending URL: ' . $this->getUrl() .
1502                      '<hr />Headers: <pre>' . Html::escape(var_export(array_map('trim', $this->headers), TRUE)) . '</pre>');
1503     }
1504
1505     return $out;
1506   }
1507
1508   /**
1509    * Handles form input related to drupalPostForm().
1510    *
1511    * Ensure that the specified fields exist and attempt to create POST data in
1512    * the correct manner for the particular field type.
1513    *
1514    * @param $post
1515    *   Reference to array of post values.
1516    * @param $edit
1517    *   Reference to array of edit values to be checked against the form.
1518    * @param $submit
1519    *   Form submit button value.
1520    * @param $form
1521    *   Array of form elements.
1522    *
1523    * @return
1524    *   Submit value matches a valid submit input in the form.
1525    */
1526   protected function handleForm(&$post, &$edit, &$upload, $submit, $form) {
1527     // Retrieve the form elements.
1528     $elements = $form->xpath('.//input[not(@disabled)]|.//textarea[not(@disabled)]|.//select[not(@disabled)]');
1529     $submit_matches = FALSE;
1530     foreach ($elements as $element) {
1531       // SimpleXML objects need string casting all the time.
1532       $name = (string) $element['name'];
1533       // This can either be the type of <input> or the name of the tag itself
1534       // for <select> or <textarea>.
1535       $type = isset($element['type']) ? (string) $element['type'] : $element->getName();
1536       $value = isset($element['value']) ? (string) $element['value'] : '';
1537       $done = FALSE;
1538       if (isset($edit[$name])) {
1539         switch ($type) {
1540           case 'text':
1541           case 'tel':
1542           case 'textarea':
1543           case 'url':
1544           case 'number':
1545           case 'range':
1546           case 'color':
1547           case 'hidden':
1548           case 'password':
1549           case 'email':
1550           case 'search':
1551           case 'date':
1552           case 'time':
1553           case 'datetime':
1554           case 'datetime-local';
1555             $post[$name] = $edit[$name];
1556             unset($edit[$name]);
1557             break;
1558           case 'radio':
1559             if ($edit[$name] == $value) {
1560               $post[$name] = $edit[$name];
1561               unset($edit[$name]);
1562             }
1563             break;
1564           case 'checkbox':
1565             // To prevent checkbox from being checked.pass in a FALSE,
1566             // otherwise the checkbox will be set to its value regardless
1567             // of $edit.
1568             if ($edit[$name] === FALSE) {
1569               unset($edit[$name]);
1570               continue 2;
1571             }
1572             else {
1573               unset($edit[$name]);
1574               $post[$name] = $value;
1575             }
1576             break;
1577           case 'select':
1578             $new_value = $edit[$name];
1579             $options = $this->getAllOptions($element);
1580             if (is_array($new_value)) {
1581               // Multiple select box.
1582               if (!empty($new_value)) {
1583                 $index = 0;
1584                 $key = preg_replace('/\[\]$/', '', $name);
1585                 foreach ($options as $option) {
1586                   $option_value = (string) $option['value'];
1587                   if (in_array($option_value, $new_value)) {
1588                     $post[$key . '[' . $index++ . ']'] = $option_value;
1589                     $done = TRUE;
1590                     unset($edit[$name]);
1591                   }
1592                 }
1593               }
1594               else {
1595                 // No options selected: do not include any POST data for the
1596                 // element.
1597                 $done = TRUE;
1598                 unset($edit[$name]);
1599               }
1600             }
1601             else {
1602               // Single select box.
1603               foreach ($options as $option) {
1604                 if ($new_value == $option['value']) {
1605                   $post[$name] = $new_value;
1606                   unset($edit[$name]);
1607                   $done = TRUE;
1608                   break;
1609                 }
1610               }
1611             }
1612             break;
1613           case 'file':
1614             $upload[$name] = $edit[$name];
1615             unset($edit[$name]);
1616             break;
1617         }
1618       }
1619       if (!isset($post[$name]) && !$done) {
1620         switch ($type) {
1621           case 'textarea':
1622             $post[$name] = (string) $element;
1623             break;
1624           case 'select':
1625             $single = empty($element['multiple']);
1626             $first = TRUE;
1627             $index = 0;
1628             $key = preg_replace('/\[\]$/', '', $name);
1629             $options = $this->getAllOptions($element);
1630             foreach ($options as $option) {
1631               // For single select, we load the first option, if there is a
1632               // selected option that will overwrite it later.
1633               if ($option['selected'] || ($first && $single)) {
1634                 $first = FALSE;
1635                 if ($single) {
1636                   $post[$name] = (string) $option['value'];
1637                 }
1638                 else {
1639                   $post[$key . '[' . $index++ . ']'] = (string) $option['value'];
1640                 }
1641               }
1642             }
1643             break;
1644           case 'file':
1645             break;
1646           case 'submit':
1647           case 'image':
1648             if (isset($submit) && $submit == $value) {
1649               $post[$name] = $value;
1650               $submit_matches = TRUE;
1651             }
1652             break;
1653           case 'radio':
1654           case 'checkbox':
1655             if (!isset($element['checked'])) {
1656               break;
1657             }
1658             // Deliberate no break.
1659           default:
1660             $post[$name] = $value;
1661         }
1662       }
1663     }
1664     // An empty name means the value is not sent.
1665     unset($post['']);
1666     return $submit_matches;
1667   }
1668
1669   /**
1670    * Follows a link by complete name.
1671    *
1672    * Will click the first link found with this link text by default, or a later
1673    * one if an index is given. Match is case sensitive with normalized space.
1674    * The label is translated label.
1675    *
1676    * If the link is discovered and clicked, the test passes. Fail otherwise.
1677    *
1678    * @param string|\Drupal\Component\Render\MarkupInterface $label
1679    *   Text between the anchor tags.
1680    * @param int $index
1681    *   Link position counting from zero.
1682    *
1683    * @return string|bool
1684    *   Page contents on success, or FALSE on failure.
1685    */
1686   protected function clickLink($label, $index = 0) {
1687     return $this->clickLinkHelper($label, $index, '//a[normalize-space()=:label]');
1688   }
1689
1690   /**
1691    * Follows a link by partial name.
1692    *
1693    * If the link is discovered and clicked, the test passes. Fail otherwise.
1694    *
1695    * @param string|\Drupal\Component\Render\MarkupInterface $label
1696    *   Text between the anchor tags, uses starts-with().
1697    * @param int $index
1698    *   Link position counting from zero.
1699    *
1700    * @return string|bool
1701    *   Page contents on success, or FALSE on failure.
1702    *
1703    * @see ::clickLink()
1704    */
1705   protected function clickLinkPartialName($label, $index = 0) {
1706     return $this->clickLinkHelper($label, $index, '//a[starts-with(normalize-space(), :label)]');
1707   }
1708
1709   /**
1710    * Provides a helper for ::clickLink() and ::clickLinkPartialName().
1711    *
1712    * @param string|\Drupal\Component\Render\MarkupInterface $label
1713    *   Text between the anchor tags, uses starts-with().
1714    * @param int $index
1715    *   Link position counting from zero.
1716    * @param string $pattern
1717    *   A pattern to use for the XPath.
1718    *
1719    * @return bool|string
1720    *   Page contents on success, or FALSE on failure.
1721    */
1722   protected function clickLinkHelper($label, $index, $pattern) {
1723     // Cast MarkupInterface objects to string.
1724     $label = (string) $label;
1725     $url_before = $this->getUrl();
1726     $urls = $this->xpath($pattern, [':label' => $label]);
1727     if (isset($urls[$index])) {
1728       $url_target = $this->getAbsoluteUrl($urls[$index]['href']);
1729       $this->pass(new FormattableMarkup('Clicked link %label (@url_target) from @url_before', ['%label' => $label, '@url_target' => $url_target, '@url_before' => $url_before]), 'Browser');
1730       return $this->drupalGet($url_target);
1731     }
1732     $this->fail(new FormattableMarkup('Link %label does not exist on @url_before', ['%label' => $label, '@url_before' => $url_before]), 'Browser');
1733     return FALSE;
1734   }
1735
1736   /**
1737    * Takes a path and returns an absolute path.
1738    *
1739    * This method is implemented in the way that browsers work, see
1740    * https://url.spec.whatwg.org/#relative-state for more information about the
1741    * possible cases.
1742    *
1743    * @param string $path
1744    *   A path from the internal browser content.
1745    *
1746    * @return string
1747    *   The $path with $base_url prepended, if necessary.
1748    */
1749   protected function getAbsoluteUrl($path) {
1750     global $base_url, $base_path;
1751
1752     $parts = parse_url($path);
1753
1754     // In case the $path has a host, it is already an absolute URL and we are
1755     // done.
1756     if (!empty($parts['host'])) {
1757       return $path;
1758     }
1759
1760     // In case the $path contains just a query, we turn it into an absolute URL
1761     // with the same scheme, host and path, see
1762     // https://url.spec.whatwg.org/#relative-state.
1763     if (array_keys($parts) === ['query']) {
1764       $current_uri = new Uri($this->getUrl());
1765       return (string) $current_uri->withQuery($parts['query']);
1766     }
1767
1768     if (empty($parts['host'])) {
1769       // Ensure that we have a string (and no xpath object).
1770       $path = (string) $path;
1771       // Strip $base_path, if existent.
1772       $length = strlen($base_path);
1773       if (substr($path, 0, $length) === $base_path) {
1774         $path = substr($path, $length);
1775       }
1776       // Ensure that we have an absolute path.
1777       if (empty($path) || $path[0] !== '/') {
1778         $path = '/' . $path;
1779       }
1780       // Finally, prepend the $base_url.
1781       $path = $base_url . $path;
1782     }
1783     return $path;
1784   }
1785
1786   /**
1787    * Gets the HTTP response headers of the requested page.
1788    *
1789    * Normally we are only interested in the headers returned by the last
1790    * request. However, if a page is redirected or HTTP authentication is in use,
1791    * multiple requests will be required to retrieve the page. Headers from all
1792    * requests may be requested by passing TRUE to this function.
1793    *
1794    * @param $all_requests
1795    *   Boolean value specifying whether to return headers from all requests
1796    *   instead of just the last request. Defaults to FALSE.
1797    *
1798    * @return
1799    *   A name/value array if headers from only the last request are requested.
1800    *   If headers from all requests are requested, an array of name/value
1801    *   arrays, one for each request.
1802    *
1803    *   The pseudonym ":status" is used for the HTTP status line.
1804    *
1805    *   Values for duplicate headers are stored as a single comma-separated list.
1806    */
1807   protected function drupalGetHeaders($all_requests = FALSE) {
1808     $request = 0;
1809     $headers = [$request => []];
1810     foreach ($this->headers as $header) {
1811       $header = trim($header);
1812       if ($header === '') {
1813         $request++;
1814       }
1815       else {
1816         if (strpos($header, 'HTTP/') === 0) {
1817           $name = ':status';
1818           $value = $header;
1819         }
1820         else {
1821           list($name, $value) = explode(':', $header, 2);
1822           $name = strtolower($name);
1823         }
1824         if (isset($headers[$request][$name])) {
1825           $headers[$request][$name] .= ',' . trim($value);
1826         }
1827         else {
1828           $headers[$request][$name] = trim($value);
1829         }
1830       }
1831     }
1832     if (!$all_requests) {
1833       $headers = array_pop($headers);
1834     }
1835     return $headers;
1836   }
1837
1838   /**
1839    * Gets the value of an HTTP response header.
1840    *
1841    * If multiple requests were required to retrieve the page, only the headers
1842    * from the last request will be checked by default. However, if TRUE is
1843    * passed as the second argument, all requests will be processed from last to
1844    * first until the header is found.
1845    *
1846    * @param $name
1847    *   The name of the header to retrieve. Names are case-insensitive (see RFC
1848    *   2616 section 4.2).
1849    * @param $all_requests
1850    *   Boolean value specifying whether to check all requests if the header is
1851    *   not found in the last request. Defaults to FALSE.
1852    *
1853    * @return
1854    *   The HTTP header value or FALSE if not found.
1855    */
1856   protected function drupalGetHeader($name, $all_requests = FALSE) {
1857     $name = strtolower($name);
1858     $header = FALSE;
1859     if ($all_requests) {
1860       foreach (array_reverse($this->drupalGetHeaders(TRUE)) as $headers) {
1861         if (isset($headers[$name])) {
1862           $header = $headers[$name];
1863           break;
1864         }
1865       }
1866     }
1867     else {
1868       $headers = $this->drupalGetHeaders();
1869       if (isset($headers[$name])) {
1870         $header = $headers[$name];
1871       }
1872     }
1873     return $header;
1874   }
1875
1876   /**
1877    * Check if a HTTP response header exists and has the expected value.
1878    *
1879    * @param string $header
1880    *   The header key, example: Content-Type
1881    * @param string $value
1882    *   The header value.
1883    * @param string $message
1884    *   (optional) A message to display with the assertion.
1885    * @param string $group
1886    *   (optional) The group this message is in, which is displayed in a column
1887    *   in test output. Use 'Debug' to indicate this is debugging output. Do not
1888    *   translate this string. Defaults to 'Other'; most tests do not override
1889    *   this default.
1890    *
1891    * @return bool
1892    *   TRUE if the assertion succeeded, FALSE otherwise.
1893    */
1894   protected function assertHeader($header, $value, $message = '', $group = 'Browser') {
1895     $header_value = $this->drupalGetHeader($header);
1896     return $this->assertTrue($header_value == $value, $message ? $message : 'HTTP response header ' . $header . ' with value ' . $value . ' found, actual value: ' . $header_value, $group);
1897   }
1898
1899   /**
1900    * Passes if the internal browser's URL matches the given path.
1901    *
1902    * @param \Drupal\Core\Url|string $path
1903    *   The expected system path or URL.
1904    * @param $options
1905    *   (optional) Any additional options to pass for $path to the url generator.
1906    * @param $message
1907    *   (optional) A message to display with the assertion. Do not translate
1908    *   messages: use \Drupal\Component\Render\FormattableMarkup to embed
1909    *   variables in the message text, not t(). If left blank, a default message
1910    *   will be displayed.
1911    * @param $group
1912    *   (optional) The group this message is in, which is displayed in a column
1913    *   in test output. Use 'Debug' to indicate this is debugging output. Do not
1914    *   translate this string. Defaults to 'Other'; most tests do not override
1915    *   this default.
1916    *
1917    * @return
1918    *   TRUE on pass, FALSE on fail.
1919    */
1920   protected function assertUrl($path, array $options = [], $message = '', $group = 'Other') {
1921     if ($path instanceof Url) {
1922       $url_obj = $path;
1923     }
1924     elseif (UrlHelper::isExternal($path)) {
1925       $url_obj = Url::fromUri($path, $options);
1926     }
1927     else {
1928       $uri = $path === '<front>' ? 'base:/' : 'base:/' . $path;
1929       // This is needed for language prefixing.
1930       $options['path_processing'] = TRUE;
1931       $url_obj = Url::fromUri($uri, $options);
1932     }
1933     $url = $url_obj->setAbsolute()->toString();
1934     if (!$message) {
1935       $message = new FormattableMarkup('Expected @url matches current URL (@current_url).', [
1936         '@url' => var_export($url, TRUE),
1937         '@current_url' => $this->getUrl(),
1938       ]);
1939     }
1940     // Paths in query strings can be encoded or decoded with no functional
1941     // difference, decode them for comparison purposes.
1942     $actual_url = urldecode($this->getUrl());
1943     $expected_url = urldecode($url);
1944     return $this->assertEqual($actual_url, $expected_url, $message, $group);
1945   }
1946
1947   /**
1948    * Asserts the page responds with the specified response code.
1949    *
1950    * @param $code
1951    *   Response code. For example 200 is a successful page request. For a list
1952    *   of all codes see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html.
1953    * @param $message
1954    *   (optional) A message to display with the assertion. Do not translate
1955    *   messages: use \Drupal\Component\Render\FormattableMarkup to embed
1956    *   variables in the message text, not t(). If left blank, a default message
1957    *   will be displayed.
1958    * @param $group
1959    *   (optional) The group this message is in, which is displayed in a column
1960    *   in test output. Use 'Debug' to indicate this is debugging output. Do not
1961    *   translate this string. Defaults to 'Browser'; most tests do not override
1962    *   this default.
1963    *
1964    * @return
1965    *   Assertion result.
1966    */
1967   protected function assertResponse($code, $message = '', $group = 'Browser') {
1968     $curl_code = curl_getinfo($this->curlHandle, CURLINFO_HTTP_CODE);
1969     $match = is_array($code) ? in_array($curl_code, $code) : $curl_code == $code;
1970     return $this->assertTrue($match, $message ? $message : new FormattableMarkup('HTTP response expected @code, actual @curl_code', ['@code' => $code, '@curl_code' => $curl_code]), $group);
1971   }
1972
1973   /**
1974    * Asserts the page did not return the specified response code.
1975    *
1976    * @param $code
1977    *   Response code. For example 200 is a successful page request. For a list
1978    *   of all codes see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html.
1979    * @param $message
1980    *   (optional) A message to display with the assertion. Do not translate
1981    *   messages: use \Drupal\Component\Render\FormattableMarkup to embed
1982    *   variables in the message text, not t(). If left blank, a default message
1983    *   will be displayed.
1984    * @param $group
1985    *   (optional) The group this message is in, which is displayed in a column
1986    *   in test output. Use 'Debug' to indicate this is debugging output. Do not
1987    *   translate this string. Defaults to 'Browser'; most tests do not override
1988    *   this default.
1989    *
1990    * @return
1991    *   Assertion result.
1992    */
1993   protected function assertNoResponse($code, $message = '', $group = 'Browser') {
1994     $curl_code = curl_getinfo($this->curlHandle, CURLINFO_HTTP_CODE);
1995     $match = is_array($code) ? in_array($curl_code, $code) : $curl_code == $code;
1996     return $this->assertFalse($match, $message ? $message : new FormattableMarkup('HTTP response not expected @code, actual @curl_code', ['@code' => $code, '@curl_code' => $curl_code]), $group);
1997   }
1998
1999   /**
2000    * Builds an a absolute URL from a system path or a URL object.
2001    *
2002    * @param string|\Drupal\Core\Url $path
2003    *   A system path or a URL.
2004    * @param array $options
2005    *   Options to be passed to Url::fromUri().
2006    *
2007    * @return string
2008    *   An absolute URL string.
2009    */
2010   protected function buildUrl($path, array $options = []) {
2011     if ($path instanceof Url) {
2012       $url_options = $path->getOptions();
2013       $options = $url_options + $options;
2014       $path->setOptions($options);
2015       return $path->setAbsolute()->toString(TRUE)->getGeneratedUrl();
2016     }
2017     // The URL generator service is not necessarily available yet; e.g., in
2018     // interactive installer tests.
2019     elseif ($this->container->has('url_generator')) {
2020       $force_internal = isset($options['external']) && $options['external'] == FALSE;
2021       if (!$force_internal && UrlHelper::isExternal($path)) {
2022         return Url::fromUri($path, $options)->toString();
2023       }
2024       else {
2025         $uri = $path === '<front>' ? 'base:/' : 'base:/' . $path;
2026         // Path processing is needed for language prefixing.  Skip it when a
2027         // path that may look like an external URL is being used as internal.
2028         $options['path_processing'] = !$force_internal;
2029         return Url::fromUri($uri, $options)
2030           ->setAbsolute()
2031           ->toString();
2032       }
2033     }
2034     else {
2035       return $this->getAbsoluteUrl($path);
2036     }
2037   }
2038
2039   /**
2040    * Asserts whether an expected cache tag was present in the last response.
2041    *
2042    * @param string $expected_cache_tag
2043    *   The expected cache tag.
2044    */
2045   protected function assertCacheTag($expected_cache_tag) {
2046     $cache_tags = explode(' ', $this->drupalGetHeader('X-Drupal-Cache-Tags'));
2047     $this->assertTrue(in_array($expected_cache_tag, $cache_tags), "'" . $expected_cache_tag . "' is present in the X-Drupal-Cache-Tags header.");
2048   }
2049
2050   /**
2051    * Asserts whether an expected cache tag was absent in the last response.
2052    *
2053    * @param string $cache_tag
2054    *   The cache tag to check.
2055    */
2056   protected function assertNoCacheTag($cache_tag) {
2057     $cache_tags = explode(' ', $this->drupalGetHeader('X-Drupal-Cache-Tags'));
2058     $this->assertFalse(in_array($cache_tag, $cache_tags), "'" . $cache_tag . "' is absent in the X-Drupal-Cache-Tags header.");
2059   }
2060
2061   /**
2062    * Enables/disables the cacheability headers.
2063    *
2064    * Sets the http.response.debug_cacheability_headers container parameter.
2065    *
2066    * @param bool $value
2067    *   (optional) Whether the debugging cacheability headers should be sent.
2068    */
2069   protected function setHttpResponseDebugCacheabilityHeaders($value = TRUE) {
2070     $this->setContainerParameter('http.response.debug_cacheability_headers', $value);
2071     $this->rebuildContainer();
2072     $this->resetAll();
2073   }
2074
2075 }