3 namespace Drupal\simpletest;
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;
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;
30 * Test case for typical Drupal tests.
34 abstract class WebTestBase extends TestBase {
36 use FunctionalTestSetupTrait;
37 use AssertContentTrait;
38 use TestFileCreationTrait {
39 getTestFiles as drupalGetTestFiles;
40 compareFiles as drupalCompareFiles;
42 use AssertPageCacheContextsAndTagsTrait;
43 use BaseBlockCreationTrait {
44 placeBlock as drupalPlaceBlock;
46 use ContentTypeCreationTrait {
47 createContentType as drupalCreateContentType;
51 getMails as drupalGetMails;
53 use NodeCreationTrait {
54 getNodeByTitle as drupalGetNodeByTitle;
55 createNode as drupalCreateNode;
57 use UserCreationTrait {
58 createUser as drupalCreateUser;
59 createRole as drupalCreateRole;
60 createAdminRole as drupalCreateAdminRole;
63 use XdebugRequestTrait;
65 buildEntityView as drupalBuildEntityView;
69 * The profile to install as a basis for testing.
73 protected $profile = 'testing';
76 * The URL currently loaded in the internal browser.
83 * The handle of the current cURL connection.
87 protected $curlHandle;
90 * Whether or not to assert the presence of the X-Drupal-Ajax-Token.
94 protected $assertAjaxHeader = TRUE;
97 * The headers of the page currently loaded in the internal browser.
104 * The cookies of the page currently loaded in the internal browser.
108 protected $cookies = [];
111 * Indicates that headers should be dumped if verbose output is enabled.
113 * Headers are dumped to verbose by drupalGet(), drupalHead(), and
118 protected $dumpHeaders = FALSE;
121 * The current user logged in using the internal browser.
123 * @var \Drupal\Core\Session\AccountInterface|bool
125 protected $loggedInUser = FALSE;
128 * The current cookie file used by cURL.
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.
133 protected $cookieFile = NULL;
136 * Additional cURL options.
138 * \Drupal\simpletest\WebTestBase itself never sets this but always obeys what
141 protected $additionalCurlOptions = [];
144 * The original batch, before it was changed for testing purposes.
148 protected $originalBatch;
151 * The original user, before it was changed to a clean uid = 1 for testing.
155 protected $originalUser = NULL;
158 * The original shutdown handlers array, before it was cleaned for testing.
162 protected $originalShutdownCallbacks = [];
165 * The current session ID, if available.
167 protected $sessionId = NULL;
170 * The maximum number of redirects to follow when handling responses.
174 protected $maximumRedirects = 5;
177 * The number of redirects followed during the handling of a request.
179 protected $redirectCount;
183 * The number of meta refresh redirects to follow, or NULL if unlimited.
187 protected $maximumMetaRefreshCount = NULL;
190 * The number of meta refresh redirects followed during ::drupalGet().
194 protected $metaRefreshCount = 0;
197 * Cookies to set on curl requests.
201 protected $curlCookies = [];
204 * An array of custom translations suitable for drupal_rewrite_settings().
208 protected $customTranslations;
211 * Constructor for \Drupal\simpletest\WebTestBase.
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';
220 * Checks to see whether a block appears on the page.
222 * @param \Drupal\block\Entity\Block $block
223 * The block entity to find on the page.
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()]));
231 * Checks to see whether a block does not appears on the page.
233 * @param \Drupal\block\Entity\Block $block
234 * The block entity to find on the page.
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()]));
242 * Find a block instance on the page.
244 * @param \Drupal\block\Entity\Block $block
245 * The block entity to find on the page.
248 * The result from the xpath query.
250 protected function findBlockInstance(Block $block) {
251 return $this->xpath('//div[@id = :id]', [':id' => 'block-' . $block->id()]);
255 * Log in a user with the internal browser.
257 * If a user is already logged in, then the current user is logged out before
258 * logging in the specified user.
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.
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;
276 * @param \Drupal\Core\Session\AccountInterface $account
277 * User object representing the user to log in.
279 * @see drupalCreateUser()
281 protected function drupalLogin(AccountInterface $account) {
282 if ($this->loggedInUser) {
283 $this->drupalLogout();
287 'name' => $account->getUsername(),
288 'pass' => $account->pass_raw
290 $this->drupalPostForm('user/login', $edit, t('Log in'));
292 // @see WebTestBase::drupalUserIsLoggedIn()
293 if (isset($this->sessionId)) {
294 $account->session_id = $this->sessionId;
296 $pass = $this->assert($this->drupalUserIsLoggedIn($account), format_string('User %name successfully logged in.', ['%name' => $account->getUsername()]), 'User login');
298 $this->loggedInUser = $account;
299 $this->container->get('current_user')->setAccount($account);
304 * Returns whether a given user account is logged in.
306 * @param \Drupal\user\UserInterface $account
307 * The user account object to check.
309 protected function drupalUserIsLoggedIn($account) {
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);
321 * Logs a user out of the internal browser and confirms.
323 * Confirms logout by checking the login page.
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
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');
335 // @see WebTestBase::drupalUserIsLoggedIn()
336 unset($this->loggedInUser->session_id);
337 $this->loggedInUser = FALSE;
338 $this->container->get('current_user')->setAccount(new AnonymousUserSession());
343 * Sets up a Drupal site for running functional and integration tests.
345 * Installs Drupal with the installation profile specified in
346 * \Drupal\simpletest\WebTestBase::$profile into the prefixed database.
348 * Afterwards, installs any additional modules specified in the static
349 * \Drupal\simpletest\WebTestBase::$modules property of each class in the
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
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');
366 // Preserve original batch for later restoration.
369 // Initialize user 1 and session name.
370 $this->initUserSession();
372 // Prepare the child site settings.
373 $this->prepareSettings();
375 // Execute the non-interactive installer.
378 // Import new settings.php written by the installer.
379 $this->initSettings();
381 // Initialize the request and container post-install.
382 $container = $this->initKernel(\Drupal::request());
384 // Initialize and override certain configurations.
385 $this->initConfig($container);
387 // Collect modules to install.
388 $this->installModulesFromClassProperty($container);
390 // Restore the original batch.
391 $this->restoreBatch();
393 // Reset/rebuild everything.
398 * Preserve the original batch, and instantiate the test batch.
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();
408 // Reset the static batch to remove Simpletest's batch operations.
409 $batch = &batch_get();
414 * Restore the original batch.
418 protected function restoreBatch() {
419 // Restore the original Simpletest batch.
420 $batch = &batch_get();
421 $batch = $this->originalBatch;
425 * Queues custom translations to be written to settings.php.
427 * Use WebTestBase::writeCustomTranslations() to apply and write the queued
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.
437 * '' => array('Sunday' => 'domingo'),
438 * 'Long month name' => array('March' => 'marzo'),
441 * Pass an empty array to remove all existing custom translations for the
444 protected function addCustomTranslations($langcode, array $values) {
445 // If $values is empty, then the test expects all custom translations to be
447 if (empty($values)) {
448 $this->customTranslations[$langcode] = [];
450 // Otherwise, $values are expected to be merged into previously passed
451 // values, while retaining keys that are not explicitly set.
453 foreach ($values as $context => $translations) {
454 foreach ($translations as $original => $translation) {
455 $this->customTranslations[$langcode][$context][$original] = $translation;
462 * Writes custom translations to the test site's settings.php.
464 * Use TestBase::addCustomTranslations() to queue custom translations before
465 * calling this method.
467 protected function writeCustomTranslations() {
469 foreach ($this->customTranslations as $langcode => $values) {
470 $settings_key = 'locale_custom_strings_' . $langcode;
472 // Update in-memory settings directly.
473 $this->settingsSet($settings_key, $values);
475 $settings['settings'][$settings_key] = (object) [
480 // Only rewrite settings if there are any translation changes to write.
481 if (!empty($settings)) {
482 $this->writeSettings($settings);
487 * Cleans up after testing.
489 * Deletes created files and temporary files directory, deletes the tables
490 * created by setUp(), and resets the database prefix.
492 protected function tearDown() {
493 // Destroy the testing kernel.
494 if (isset($this->kernel)) {
495 $this->kernel->shutdown();
499 // Ensure that the maximum meta refresh count is reset.
500 $this->maximumMetaRefreshCount = NULL;
502 // Ensure that internal logged in variable and cURL options are reset.
503 $this->loggedInUser = FALSE;
504 $this->additionalCurlOptions = [];
506 // Close the CURL handler and reset the cookies array used for upgrade
507 // testing so test classes containing multiple tests are not polluted.
509 $this->curlCookies = [];
514 * Initializes the cURL connection.
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.
521 protected function curlInitialize() {
524 if (!isset($this->curlHandle)) {
525 $this->curlHandle = curl_init();
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';
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,
547 if (isset($this->httpAuthCredentials)) {
548 $curl_options[CURLOPT_HTTPAUTH] = $this->httpAuthMethod;
549 $curl_options[CURLOPT_USERPWD] = $this->httpAuthCredentials;
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);
555 throw new \UnexpectedValueException('One or more cURL options could not be set.');
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));
564 * Initializes and executes a cURL request.
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
571 * FALSE if this is an initial request, TRUE if this request is the result
575 * The content returned from the call to curl_exec().
577 * @see curlInitialize()
579 protected function curlExec($curl_options, $redirect = FALSE) {
580 $this->curlInitialize();
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], '#');
594 $url = empty($curl_options[CURLOPT_URL]) ? curl_getinfo($this->curlHandle, CURLINFO_EFFECTIVE_URL) : $curl_options[CURLOPT_URL];
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:';
606 if (!empty($this->curlCookies)) {
607 $cookies = $this->curlCookies;
610 foreach ($this->extractCookiesFromRequest(\Drupal::request()) as $cookie_name => $values) {
611 foreach ($values as $value) {
612 $cookies[] = $cookie_name . '=' . $value;
616 // Merge additional cookies in.
617 if (!empty($cookies)) {
619 CURLOPT_COOKIE => '',
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], '; ') . '; ';
625 $curl_options[CURLOPT_COOKIE] .= implode('; ', $cookies) . ';';
628 curl_setopt_array($this->curlHandle, $this->additionalCurlOptions + $curl_options);
631 // Reset headers, the session ID and the redirect counter.
632 $this->sessionId = NULL;
634 $this->redirectCount = 0;
637 $content = curl_exec($this->curlHandle);
638 $status = curl_getinfo($this->curlHandle, CURLINFO_HTTP_CODE);
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
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++;
649 $curl_options[CURLOPT_URL] = $this->drupalGetHeader('location');
650 $curl_options[CURLOPT_HTTPGET] = TRUE;
651 return $this->curlExec($curl_options, TRUE);
655 $this->setRawContent($content);
656 $this->url = isset($original_url) ? $original_url : curl_getinfo($this->curlHandle, CURLINFO_EFFECTIVE_URL);
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()))
664 $message = SafeMarkup::format('@method @url returned @status (@length).', $message_vars);
665 $this->assertTrue($this->getRawContent() !== FALSE, $message, 'Browser');
666 return $this->getRawContent();
670 * Reads headers and registers errors received from the tested site.
672 * @param $curlHandler
677 * @see _drupal_log_error()
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);
688 $this->headers[] = $header;
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
697 call_user_func_array([&$this, 'error'], unserialize(urldecode($matches[1])));
701 if (preg_match('/^Set-Cookie: ([^=]+)=(.+)/', $header, $matches)) {
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;
711 $this->sessionId = NULL;
716 // This is required by cURL.
717 return strlen($header);
721 * Close the cURL handler and unset the handler.
723 protected function curlClose() {
724 if (isset($this->curlHandle)) {
725 curl_close($this->curlHandle);
726 unset($this->curlHandle);
731 * Returns whether the test is being executed from within a test site.
733 * Mainly used by recursive tests (i.e. to test the testing framework).
736 * TRUE if this test was instantiated in a request within the test site,
739 * @see \Drupal\Core\DrupalKernel::bootConfiguration()
741 protected function isInChildSite() {
742 return DRUPAL_TEST_IN_CHILD_SITE;
746 * Retrieves a Drupal path or an absolute path.
748 * @param \Drupal\Core\Url|string $path
749 * Drupal path or URL to load into internal browser
751 * Options to be forwarded to the url generator.
753 * An array containing additional HTTP request headers, each formatted as
757 * The retrieved HTML string, also available as $this->getRawContent()
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
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();
767 // Replace original page output with new output from redirected page(s).
768 if ($new = $this->checkForMetaRefresh()) {
770 // We are finished with all meta refresh redirects, so reset the counter.
771 $this->metaRefreshCount = 0;
774 if ($path instanceof Url) {
775 $path = $path->setAbsolute()->toString(TRUE)->getGeneratedUrl();
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>';
783 $verbose .= '<hr />' . $out;
785 $this->verbose($verbose);
790 * Retrieves a Drupal path or an absolute path and JSON decodes the result.
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').
802 protected function drupalGetJSON($path, array $options = [], array $headers = []) {
803 return Json::decode($this->drupalGetWithFormat($path, 'json', $options, $headers));
807 * Retrieves a Drupal path or an absolute path for a given format.
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
819 * The result of the request.
821 protected function drupalGetWithFormat($path, $format, array $options = [], array $headers = []) {
822 $options += ['query' => ['_format' => $format]];
823 return $this->drupalGet($path, $options, $headers);
827 * Requests a path or URL in drupal_ajax format and JSON-decodes the response.
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
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';
843 return Json::decode($this->drupalGetXHR($path, $options, $headers));
847 * Requests a Drupal path or an absolute path as if it is a XMLHttpRequest.
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
857 * The retrieved content.
859 protected function drupalGetXHR($path, array $options = [], array $headers = []) {
860 $headers[] = 'X-Requested-With: XMLHttpRequest';
861 return $this->drupalGet($path, $options, $headers);
865 * Executes a form submission.
867 * It will be done as usual POST request with SimpleBrowser.
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:
875 * // First step in form.
876 * $edit = array(...);
877 * $this->drupalPostForm('some_url', $edit, t('Save'));
879 * // Second step in form.
880 * $edit = array(...);
881 * $this->drupalPostForm(NULL, $edit, t('Save'));
884 * Field data in an associative array. Changes the current input fields
885 * (where possible) to the values indicated.
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:
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>
895 * When testing this field using an $edit parameter, the code becomes:
897 * $edit["body[0][value]"] = 'My test value';
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:
905 * $edit['name[]'] = array('value1', 'value2');
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.
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.
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
930 * Options to be forwarded to the url generator.
932 * An array containing additional HTTP request headers, each formatted as
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
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").
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;
953 if (is_array($edit)) {
954 $edit = $this->castSafeStrings($edit);
957 $submit_matches = FALSE;
958 $ajax = is_array($submit);
960 $this->drupalGet($path, $options);
963 if ($this->parse()) {
965 // Let's iterate over all the forms.
967 if (!empty($form_html_id)) {
968 $xpath .= "[@id='" . $form_html_id . "']";
970 $forms = $this->xpath($xpath);
971 foreach ($forms as $form) {
972 // We try to set the fields of this form as specified in $edit.
976 $submit_matches = $this->handleForm($post, $edit, $upload, $ajax ? NULL : $submit, $form);
977 $action = isset($form['action']) ? $this->getAbsoluteUrl((string) $form['action']) : $this->getUrl();
979 if (empty($submit['path'])) {
980 throw new \Exception('No #ajax path specified.');
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;
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))) {
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);
1005 $file = $this->container->get('file_system')->realpath($file);
1006 if ($file && is_file($file)) {
1007 $post[$key] = curl_file_create($file);
1013 $post = $this->serializePostValues($post) . $extra_post;
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
1018 $this->refreshVariables();
1020 // Replace original page output with new output from redirected
1022 if ($new = $this->checkForMetaRefresh()) {
1026 if ($path instanceof Url) {
1027 $path = $path->toString();
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>';
1034 $verbose .= '<hr />Fields: ' . highlight_string('<?php ' . var_export($post_array, TRUE), TRUE);
1035 $verbose .= '<hr />' . $out;
1037 $this->verbose($verbose);
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]));
1045 if (!$ajax && isset($submit)) {
1046 $this->assertTrue($submit_matches, format_string('Found the @submit button', ['@submit' => $submit]));
1048 $this->fail(format_string('Found the requested form fields at @path', ['@path' => ($path instanceof Url) ? $path->toString() : $path]));
1053 * Executes an Ajax form submission.
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.
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.
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')).
1071 * (optional) Override the path set by the Ajax settings of the triggering
1074 * (optional) Options to be forwarded to the url generator.
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.
1088 * An array of Ajax commands.
1090 * @see drupalPostForm()
1091 * @see drupalProcessAjaxResponse()
1094 protected function drupalPostAjaxForm($path, $edit, $triggering_element, $ajax_path = NULL, array $options = [], array $headers = [], $form_html_id = NULL, $ajax_settings = NULL) {
1096 // Get the content of the initial page prior to calling drupalPostForm(),
1097 // since drupalPostForm() replaces $this->content.
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);
1105 $content = $this->content;
1106 $drupal_settings = $this->drupalSettings;
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] :
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) . '"]';
1120 $xpath = '//*[@name="' . $triggering_element . '"]';
1122 if (isset($form_html_id)) {
1123 $xpath = '//form[@id="' . $form_html_id . '"]' . $xpath;
1125 $element = $this->xpath($xpath);
1126 $element_id = (string) $element[0]['id'];
1127 $ajax_settings = $drupal_settings['ajax'][$element_id];
1130 // Add extra information to the POST data as ajax.js does.
1132 if (isset($ajax_settings['submit'])) {
1133 foreach ($ajax_settings['submit'] as $key => $value) {
1134 $extra_post[$key] = $value;
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);
1142 // Unless a particular path is specified, use the one specified by the
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']];
1152 // We know that $parsed_url['path'] is already with the base path
1154 $ajax_path = preg_replace(
1155 '/^' . preg_quote(base_path(), '/') . '/',
1162 if (empty($ajax_path)) {
1163 throw new \Exception('No #ajax path specified.');
1166 $ajax_path = $this->container->get('unrouted_url_assembler')->assemble('base://' . $ajax_path, $options);
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.');
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);
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;
1184 $this->verbose($verbose);
1190 * Processes an AJAX response into current content.
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.
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.
1208 * @see drupalPostAjaxForm()
1211 protected function drupalProcessAjaxResponse($content, array $ajax_response, array $ajax_settings, array $drupal_settings) {
1213 // ajax.js applies some defaults to the settings object, so do the same
1214 // for what's used by this function.
1216 'method' => 'replaceWith',
1218 // DOM can load HTML soup. But, HTML soup can throw warnings, suppress
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)) {
1229 switch ($command['command']) {
1231 $drupal_settings = NestedArray::mergeDeepArray([$drupal_settings, $command['settings']], TRUE);
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);
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);
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,
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.
1261 $wrapperNode->parentNode->replaceChild($newNode, $wrapperNode);
1264 $wrapperNode->appendChild($newNode);
1267 // If no firstChild, insertBefore() falls back to
1269 $wrapperNode->insertBefore($newNode, $wrapperNode->firstChild);
1272 $wrapperNode->parentNode->insertBefore($newNode, $wrapperNode);
1275 // If no nextSibling, insertBefore() falls back to
1277 $wrapperNode->parentNode->insertBefore($newNode, $wrapperNode->nextSibling);
1280 foreach ($wrapperNode->childNodes as $childNode) {
1281 $wrapperNode->removeChild($childNode);
1283 $wrapperNode->appendChild($newNode);
1289 // @todo Add suitable implementations for these commands in order to
1290 // have full test coverage of what ajax.js can do.
1303 case 'update_build_id':
1304 $buildId = $xpath->query('//input[@name="form_build_id" and @value="' . $command['old'] . '"]')->item(0);
1306 $buildId->setAttribute('value', $command['new']);
1311 $content = $dom->saveHTML();
1312 $this->setRawContent($content);
1313 $this->setDrupalSettings($drupal_settings);
1317 * Perform a POST HTTP request.
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()
1328 * @param array $options
1329 * (optional) Options to be forwarded to the url generator. The 'absolute'
1330 * option will automatically be enabled.
1333 * The content returned from the call to curl_exec().
1335 * @see WebTestBase::getAjaxPageStatePostData()
1336 * @see WebTestBase::curlExec()
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',
1351 * Performs a POST HTTP request with a specific format.
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()
1361 * @param array $options
1362 * (optional) Options to be forwarded to the url generator. The 'absolute'
1363 * option will automatically be enabled.
1366 * The content returned from the call to curl_exec().
1368 * @see WebTestBase::drupalPost
1369 * @see WebTestBase::getAjaxPageStatePostData()
1370 * @see WebTestBase::curlExec()
1372 protected function drupalPostWithFormat($path, $format, array $post, $options = []) {
1373 $options['query']['_format'] = $format;
1374 return $this->drupalPost($path, '', $post, $options);
1378 * Get the Ajax page state from drupalSettings and prepare it for POSTing.
1381 * The Ajax page state POST data.
1383 protected function getAjaxPageStatePostData() {
1385 $drupal_settings = $this->drupalSettings;
1386 if (isset($drupal_settings['ajaxPageState']['theme'])) {
1387 $post['ajax_page_state[theme]'] = $drupal_settings['ajaxPageState']['theme'];
1389 if (isset($drupal_settings['ajaxPageState']['theme_token'])) {
1390 $post['ajax_page_state[theme_token]'] = $drupal_settings['ajaxPageState']['theme_token'];
1392 if (isset($drupal_settings['ajaxPageState']['libraries'])) {
1393 $post['ajax_page_state[libraries]'] = $drupal_settings['ajaxPageState']['libraries'];
1399 * Serialize POST HTTP request values.
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
1405 * @param array $post
1406 * The array of values to be POSTed.
1409 * The serialized result.
1411 protected function serializePostValues($post = []) {
1412 foreach ($post as $key => $value) {
1413 $post[$key] = urlencode($key) . '=' . urlencode($value);
1415 return implode('&', $post);
1419 * Transforms a nested array into a flat array suitable for WebTestBase::drupalPostForm().
1421 * @param array $values
1422 * A multi-dimensional form values array to convert.
1425 * The flattened $edit array suitable for WebTestBase::drupalPostForm().
1427 protected function translatePostValues(array $values) {
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);
1441 * Checks for meta refresh tag and if found call drupalGet() recursively.
1443 * This function looks for the http-equiv attribute to be set to "Refresh" and
1444 * is case-sensitive.
1447 * Either the new page content or FALSE.
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'])));
1465 * Retrieves only the headers for a Drupal path or an absolute path.
1468 * Drupal path or URL to load into internal browser
1470 * Options to be forwarded to the url generator.
1472 * An array containing additional HTTP request headers, each formatted as
1476 * The retrieved headers, also available as $this->getRawContent()
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();
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>');
1495 * Handles form input related to drupalPostForm().
1497 * Ensure that the specified fields exist and attempt to create POST data in
1498 * the correct manner for the particular field type.
1501 * Reference to array of post values.
1503 * Reference to array of edit values to be checked against the form.
1505 * Form submit button value.
1507 * Array of form elements.
1510 * Submit value matches a valid submit input in the form.
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'] : '';
1524 if (isset($edit[$name])) {
1540 case 'datetime-local';
1541 $post[$name] = $edit[$name];
1542 unset($edit[$name]);
1545 if ($edit[$name] == $value) {
1546 $post[$name] = $edit[$name];
1547 unset($edit[$name]);
1551 // To prevent checkbox from being checked.pass in a FALSE,
1552 // otherwise the checkbox will be set to its value regardless
1554 if ($edit[$name] === FALSE) {
1555 unset($edit[$name]);
1559 unset($edit[$name]);
1560 $post[$name] = $value;
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)) {
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;
1576 unset($edit[$name]);
1581 // No options selected: do not include any POST data for the
1584 unset($edit[$name]);
1588 // Single select box.
1589 foreach ($options as $option) {
1590 if ($new_value == $option['value']) {
1591 $post[$name] = $new_value;
1592 unset($edit[$name]);
1600 $upload[$name] = $edit[$name];
1601 unset($edit[$name]);
1605 if (!isset($post[$name]) && !$done) {
1608 $post[$name] = (string) $element;
1611 $single = empty($element['multiple']);
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)) {
1622 $post[$name] = (string) $option['value'];
1625 $post[$key . '[' . $index++ . ']'] = (string) $option['value'];
1634 if (isset($submit) && $submit == $value) {
1635 $post[$name] = $value;
1636 $submit_matches = TRUE;
1641 if (!isset($element['checked'])) {
1644 // Deliberate no break.
1646 $post[$name] = $value;
1650 // An empty name means the value is not sent.
1652 return $submit_matches;
1656 * Follows a link by complete name.
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.
1662 * If the link is discovered and clicked, the test passes. Fail otherwise.
1664 * @param string|\Drupal\Component\Render\MarkupInterface $label
1665 * Text between the anchor tags.
1667 * Link position counting from zero.
1669 * @return string|bool
1670 * Page contents on success, or FALSE on failure.
1672 protected function clickLink($label, $index = 0) {
1673 return $this->clickLinkHelper($label, $index, '//a[normalize-space()=:label]');
1677 * Follows a link by partial name.
1679 * If the link is discovered and clicked, the test passes. Fail otherwise.
1681 * @param string|\Drupal\Component\Render\MarkupInterface $label
1682 * Text between the anchor tags, uses starts-with().
1684 * Link position counting from zero.
1686 * @return string|bool
1687 * Page contents on success, or FALSE on failure.
1689 * @see ::clickLink()
1691 protected function clickLinkPartialName($label, $index = 0) {
1692 return $this->clickLinkHelper($label, $index, '//a[starts-with(normalize-space(), :label)]');
1696 * Provides a helper for ::clickLink() and ::clickLinkPartialName().
1698 * @param string|\Drupal\Component\Render\MarkupInterface $label
1699 * Text between the anchor tags, uses starts-with().
1701 * Link position counting from zero.
1702 * @param string $pattern
1703 * A pattern to use for the XPath.
1705 * @return bool|string
1706 * Page contents on success, or FALSE on failure.
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);
1718 $this->fail(SafeMarkup::format('Link %label does not exist on @url_before', ['%label' => $label, '@url_before' => $url_before]), 'Browser');
1723 * Takes a path and returns an absolute path.
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
1729 * @param string $path
1730 * A path from the internal browser content.
1733 * The $path with $base_url prepended, if necessary.
1735 protected function getAbsoluteUrl($path) {
1736 global $base_url, $base_path;
1738 $parts = parse_url($path);
1740 // In case the $path has a host, it is already an absolute URL and we are
1742 if (!empty($parts['host'])) {
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']);
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);
1762 // Ensure that we have an absolute path.
1763 if (empty($path) || $path[0] !== '/') {
1764 $path = '/' . $path;
1766 // Finally, prepend the $base_url.
1767 $path = $base_url . $path;
1773 * Gets the HTTP response headers of the requested page.
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.
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.
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.
1789 * The pseudonym ":status" is used for the HTTP status line.
1791 * Values for duplicate headers are stored as a single comma-separated list.
1793 protected function drupalGetHeaders($all_requests = FALSE) {
1795 $headers = [$request => []];
1796 foreach ($this->headers as $header) {
1797 $header = trim($header);
1798 if ($header === '') {
1802 if (strpos($header, 'HTTP/') === 0) {
1807 list($name, $value) = explode(':', $header, 2);
1808 $name = strtolower($name);
1810 if (isset($headers[$request][$name])) {
1811 $headers[$request][$name] .= ',' . trim($value);
1814 $headers[$request][$name] = trim($value);
1818 if (!$all_requests) {
1819 $headers = array_pop($headers);
1825 * Gets the value of an HTTP response header.
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.
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.
1840 * The HTTP header value or FALSE if not found.
1842 protected function drupalGetHeader($name, $all_requests = FALSE) {
1843 $name = strtolower($name);
1845 if ($all_requests) {
1846 foreach (array_reverse($this->drupalGetHeaders(TRUE)) as $headers) {
1847 if (isset($headers[$name])) {
1848 $header = $headers[$name];
1854 $headers = $this->drupalGetHeaders();
1855 if (isset($headers[$name])) {
1856 $header = $headers[$name];
1863 * Check if a HTTP response header exists and has the expected value.
1865 * @param string $header
1866 * The header key, example: Content-Type
1867 * @param string $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
1878 * TRUE if the assertion succeeded, FALSE otherwise.
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);
1886 * Passes if the internal browser's URL matches the given path.
1888 * @param \Drupal\Core\Url|string $path
1889 * The expected system path or URL.
1891 * (optional) Any additional options to pass for $path to the url generator.
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.
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
1904 * TRUE on pass, FALSE on fail.
1906 protected function assertUrl($path, array $options = [], $message = '', $group = 'Other') {
1907 if ($path instanceof Url) {
1910 elseif (UrlHelper::isExternal($path)) {
1911 $url_obj = Url::fromUri($path, $options);
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);
1919 $url = $url_obj->setAbsolute()->toString();
1921 $message = SafeMarkup::format('Expected @url matches current URL (@current_url).', [
1922 '@url' => var_export($url, TRUE),
1923 '@current_url' => $this->getUrl(),
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);
1934 * Asserts the page responds with the specified response 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.
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.
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
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);
1960 * Asserts the page did not return the specified response 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.
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.
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
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);
1986 * Builds an a absolute URL from a system path or a URL object.
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().
1994 * An absolute URL string.
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();
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();
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)
2021 return $this->getAbsoluteUrl($path);
2026 * Asserts whether an expected cache tag was present in the last response.
2028 * @param string $expected_cache_tag
2029 * The expected cache tag.
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.");
2037 * Asserts whether an expected cache tag was absent in the last response.
2039 * @param string $cache_tag
2040 * The cache tag to check.
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.");
2048 * Enables/disables the cacheability headers.
2050 * Sets the http.response.debug_cacheability_headers container parameter.
2052 * @param bool $value
2053 * (optional) Whether the debugging cacheability headers should be sent.
2055 protected function setHttpResponseDebugCacheabilityHeaders($value = TRUE) {
2056 $this->setContainerParameter('http.response.debug_cacheability_headers', $value);
2057 $this->rebuildContainer();