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