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\Render\FormattableMarkup;
11 use Drupal\Core\EventSubscriber\AjaxResponseSubscriber;
12 use Drupal\Core\EventSubscriber\MainContentViewSubscriber;
13 use Drupal\Core\Session\AccountInterface;
14 use Drupal\Core\Session\AnonymousUserSession;
15 use Drupal\Core\Test\AssertMailTrait;
16 use Drupal\Core\Test\FunctionalTestSetupTrait;
18 use Drupal\system\Tests\Cache\AssertPageCacheContextsAndTagsTrait;
19 use Drupal\Tests\EntityViewTrait;
20 use Drupal\Tests\block\Traits\BlockCreationTrait as BaseBlockCreationTrait;
21 use Drupal\Tests\Listeners\DeprecationListenerTrait;
22 use Drupal\Tests\node\Traits\ContentTypeCreationTrait as BaseContentTypeCreationTrait;
23 use Drupal\Tests\node\Traits\NodeCreationTrait as BaseNodeCreationTrait;
24 use Drupal\Tests\Traits\Core\CronRunTrait;
25 use Drupal\Tests\TestFileCreationTrait;
26 use Drupal\Tests\user\Traits\UserCreationTrait as BaseUserCreationTrait;
27 use Drupal\Tests\XdebugRequestTrait;
28 use Zend\Diactoros\Uri;
31 * Test case for typical Drupal tests.
35 abstract class WebTestBase extends TestBase {
37 use FunctionalTestSetupTrait;
38 use AssertContentTrait;
39 use TestFileCreationTrait {
40 getTestFiles as drupalGetTestFiles;
41 compareFiles as drupalCompareFiles;
43 use AssertPageCacheContextsAndTagsTrait;
44 use BaseBlockCreationTrait {
45 placeBlock as drupalPlaceBlock;
47 use BaseContentTypeCreationTrait {
48 createContentType as drupalCreateContentType;
52 getMails as drupalGetMails;
54 use BaseNodeCreationTrait {
55 getNodeByTitle as drupalGetNodeByTitle;
56 createNode as drupalCreateNode;
58 use BaseUserCreationTrait {
59 createUser as drupalCreateUser;
60 createRole as drupalCreateRole;
61 createAdminRole as drupalCreateAdminRole;
64 use XdebugRequestTrait;
66 buildEntityView as drupalBuildEntityView;
70 * The profile to install as a basis for testing.
74 protected $profile = 'testing';
77 * The URL currently loaded in the internal browser.
84 * The handle of the current cURL connection.
88 protected $curlHandle;
91 * Whether or not to assert the presence of the X-Drupal-Ajax-Token.
95 protected $assertAjaxHeader = TRUE;
98 * The headers of the page currently loaded in the internal browser.
105 * The cookies of the page currently loaded in the internal browser.
109 protected $cookies = [];
112 * Indicates that headers should be dumped if verbose output is enabled.
114 * Headers are dumped to verbose by drupalGet(), drupalHead(), and
119 protected $dumpHeaders = FALSE;
122 * The current user logged in using the internal browser.
124 * @var \Drupal\Core\Session\AccountInterface|bool
126 protected $loggedInUser = FALSE;
129 * The current cookie file used by cURL.
131 * We do not reuse the cookies in further runs, so we do not need a file
132 * but we still need cookie handling, so we set the jar to NULL.
134 protected $cookieFile = NULL;
137 * Additional cURL options.
139 * \Drupal\simpletest\WebTestBase itself never sets this but always obeys what
142 protected $additionalCurlOptions = [];
145 * The original batch, before it was changed for testing purposes.
149 protected $originalBatch;
152 * The original user, before it was changed to a clean uid = 1 for testing.
156 protected $originalUser = NULL;
159 * The original shutdown handlers array, before it was cleaned for testing.
163 protected $originalShutdownCallbacks = [];
166 * The current session ID, if available.
168 protected $sessionId = NULL;
171 * The maximum number of redirects to follow when handling responses.
175 protected $maximumRedirects = 5;
178 * The number of redirects followed during the handling of a request.
180 protected $redirectCount;
184 * The number of meta refresh redirects to follow, or NULL if unlimited.
188 protected $maximumMetaRefreshCount = NULL;
191 * The number of meta refresh redirects followed during ::drupalGet().
195 protected $metaRefreshCount = 0;
198 * Cookies to set on curl requests.
202 protected $curlCookies = [];
205 * An array of custom translations suitable for drupal_rewrite_settings().
209 protected $customTranslations;
212 * Constructor for \Drupal\simpletest\WebTestBase.
214 public function __construct($test_id = NULL) {
215 parent::__construct($test_id);
216 $this->skipClasses[__CLASS__] = TRUE;
217 $this->classLoader = require DRUPAL_ROOT . '/autoload.php';
221 * Checks to see whether a block appears on the page.
223 * @param \Drupal\block\Entity\Block $block
224 * The block entity to find on the page.
226 protected function assertBlockAppears(Block $block) {
227 $result = $this->findBlockInstance($block);
228 $this->assertTrue(!empty($result), format_string('Ensure the block @id appears on the page', ['@id' => $block->id()]));
232 * Checks to see whether a block does not appears on the page.
234 * @param \Drupal\block\Entity\Block $block
235 * The block entity to find on the page.
237 protected function assertNoBlockAppears(Block $block) {
238 $result = $this->findBlockInstance($block);
239 $this->assertFalse(!empty($result), format_string('Ensure the block @id does not appear on the page', ['@id' => $block->id()]));
243 * Find a block instance on the page.
245 * @param \Drupal\block\Entity\Block $block
246 * The block entity to find on the page.
249 * The result from the xpath query.
251 protected function findBlockInstance(Block $block) {
252 return $this->xpath('//div[@id = :id]', [':id' => 'block-' . $block->id()]);
256 * Log in a user with the internal browser.
258 * If a user is already logged in, then the current user is logged out before
259 * logging in the specified user.
261 * Please note that neither the current user nor the passed-in user object is
262 * populated with data of the logged in user. If you need full access to the
263 * user object after logging in, it must be updated manually. If you also need
264 * access to the plain-text password of the user (set by drupalCreateUser()),
265 * e.g. to log in the same user again, then it must be re-assigned manually.
269 * $account = $this->drupalCreateUser(array());
270 * $this->drupalLogin($account);
271 * // Load real user object.
272 * $pass_raw = $account->pass_raw;
273 * $account = User::load($account->id());
274 * $account->pass_raw = $pass_raw;
277 * @param \Drupal\Core\Session\AccountInterface $account
278 * User object representing the user to log in.
280 * @see drupalCreateUser()
282 protected function drupalLogin(AccountInterface $account) {
283 if ($this->loggedInUser) {
284 $this->drupalLogout();
288 'name' => $account->getUsername(),
289 'pass' => $account->pass_raw,
291 $this->drupalPostForm('user/login', $edit, t('Log in'));
293 // @see WebTestBase::drupalUserIsLoggedIn()
294 if (isset($this->sessionId)) {
295 $account->session_id = $this->sessionId;
297 $pass = $this->assert($this->drupalUserIsLoggedIn($account), format_string('User %name successfully logged in.', ['%name' => $account->getUsername()]), 'User login');
299 $this->loggedInUser = $account;
300 $this->container->get('current_user')->setAccount($account);
305 * Returns whether a given user account is logged in.
307 * @param \Drupal\user\UserInterface $account
308 * The user account object to check.
310 protected function drupalUserIsLoggedIn($account) {
313 if (isset($account->session_id)) {
314 $session_handler = $this->container->get('session_handler.storage');
315 $logged_in = (bool) $session_handler->read($account->session_id);
322 * Logs a user out of the internal browser and confirms.
324 * Confirms logout by checking the login page.
326 protected function drupalLogout() {
327 // Make a request to the logout page, and redirect to the user page, the
328 // idea being if you were properly logged out you should be seeing a login
330 $this->drupalGet('user/logout', ['query' => ['destination' => 'user/login']]);
331 $this->assertResponse(200, 'User was logged out.');
332 $pass = $this->assertField('name', 'Username field found.', 'Logout');
333 $pass = $pass && $this->assertField('pass', 'Password field found.', 'Logout');
336 // @see WebTestBase::drupalUserIsLoggedIn()
337 unset($this->loggedInUser->session_id);
338 $this->loggedInUser = FALSE;
339 $this->container->get('current_user')->setAccount(new AnonymousUserSession());
344 * Sets up a Drupal site for running functional and integration tests.
346 * Installs Drupal with the installation profile specified in
347 * \Drupal\simpletest\WebTestBase::$profile into the prefixed database.
349 * Afterwards, installs any additional modules specified in the static
350 * \Drupal\simpletest\WebTestBase::$modules property of each class in the
353 * After installation all caches are flushed and several configuration values
354 * are reset to the values of the parent site executing the test, since the
355 * default values may be incompatible with the environment in which tests are
358 protected function setUp() {
359 // Set an explicit time zone to not rely on the system one, which may vary
360 // from setup to setup. The Australia/Sydney time zone is chosen so all
361 // tests are run using an edge case scenario (UTC+10 and DST). This choice
362 // is made to prevent time zone related regressions and reduce the
363 // fragility of the testing system in general. This is also set in config in
364 // \Drupal\simpletest\WebTestBase::initConfig().
365 date_default_timezone_set('Australia/Sydney');
367 // Preserve original batch for later restoration.
370 // Initialize user 1 and session name.
371 $this->initUserSession();
373 // Prepare the child site settings.
374 $this->prepareSettings();
376 // Execute the non-interactive installer.
379 // Import new settings.php written by the installer.
380 $this->initSettings();
382 // Initialize the request and container post-install.
383 $container = $this->initKernel(\Drupal::request());
385 // Initialize and override certain configurations.
386 $this->initConfig($container);
388 // Collect modules to install.
389 $this->installModulesFromClassProperty($container);
391 // Restore the original batch.
392 $this->restoreBatch();
394 // Reset/rebuild everything.
399 * Preserve the original batch, and instantiate the test batch.
401 protected function setBatch() {
402 // When running tests through the Simpletest UI (vs. on the command line),
403 // Simpletest's batch conflicts with the installer's batch. Batch API does
404 // not support the concept of nested batches (in which the nested is not
405 // progressive), so we need to temporarily pretend there was no batch.
406 // Backup the currently running Simpletest batch.
407 $this->originalBatch = batch_get();
409 // Reset the static batch to remove Simpletest's batch operations.
410 $batch = &batch_get();
415 * Restore the original batch.
419 protected function restoreBatch() {
420 // Restore the original Simpletest batch.
421 $batch = &batch_get();
422 $batch = $this->originalBatch;
426 * Queues custom translations to be written to settings.php.
428 * Use WebTestBase::writeCustomTranslations() to apply and write the queued
431 * @param string $langcode
432 * The langcode to add translations for.
433 * @param array $values
434 * Array of values containing the untranslated string and its translation.
438 * '' => array('Sunday' => 'domingo'),
439 * 'Long month name' => array('March' => 'marzo'),
442 * Pass an empty array to remove all existing custom translations for the
445 protected function addCustomTranslations($langcode, array $values) {
446 // If $values is empty, then the test expects all custom translations to be
448 if (empty($values)) {
449 $this->customTranslations[$langcode] = [];
451 // Otherwise, $values are expected to be merged into previously passed
452 // values, while retaining keys that are not explicitly set.
454 foreach ($values as $context => $translations) {
455 foreach ($translations as $original => $translation) {
456 $this->customTranslations[$langcode][$context][$original] = $translation;
463 * Writes custom translations to the test site's settings.php.
465 * Use TestBase::addCustomTranslations() to queue custom translations before
466 * calling this method.
468 protected function writeCustomTranslations() {
470 foreach ($this->customTranslations as $langcode => $values) {
471 $settings_key = 'locale_custom_strings_' . $langcode;
473 // Update in-memory settings directly.
474 $this->settingsSet($settings_key, $values);
476 $settings['settings'][$settings_key] = (object) [
481 // Only rewrite settings if there are any translation changes to write.
482 if (!empty($settings)) {
483 $this->writeSettings($settings);
488 * Cleans up after testing.
490 * Deletes created files and temporary files directory, deletes the tables
491 * created by setUp(), and resets the database prefix.
493 protected function tearDown() {
494 // Destroy the testing kernel.
495 if (isset($this->kernel)) {
496 $this->kernel->shutdown();
500 // Ensure that the maximum meta refresh count is reset.
501 $this->maximumMetaRefreshCount = NULL;
503 // Ensure that internal logged in variable and cURL options are reset.
504 $this->loggedInUser = FALSE;
505 $this->additionalCurlOptions = [];
507 // Close the CURL handler and reset the cookies array used for upgrade
508 // testing so test classes containing multiple tests are not polluted.
510 $this->curlCookies = [];
515 * Initializes the cURL connection.
517 * If the simpletest_httpauth_credentials variable is set, this function will
518 * add HTTP authentication headers. This is necessary for testing sites that
519 * are protected by login credentials from public access.
520 * See the description of $curl_options for other options.
522 protected function curlInitialize() {
525 if (!isset($this->curlHandle)) {
526 $this->curlHandle = curl_init();
528 // Some versions/configurations of cURL break on a NULL cookie jar, so
529 // supply a real file.
530 if (empty($this->cookieFile)) {
531 $this->cookieFile = $this->publicFilesDirectory . '/cookie.jar';
535 CURLOPT_COOKIEJAR => $this->cookieFile,
536 CURLOPT_URL => $base_url,
537 CURLOPT_FOLLOWLOCATION => FALSE,
538 CURLOPT_RETURNTRANSFER => TRUE,
539 // Required to make the tests run on HTTPS.
540 CURLOPT_SSL_VERIFYPEER => FALSE,
541 // Required to make the tests run on HTTPS.
542 CURLOPT_SSL_VERIFYHOST => FALSE,
543 CURLOPT_HEADERFUNCTION => [&$this, 'curlHeaderCallback'],
544 CURLOPT_USERAGENT => $this->databasePrefix,
545 // Disable support for the @ prefix for uploading files.
546 CURLOPT_SAFE_UPLOAD => TRUE,
548 if (isset($this->httpAuthCredentials)) {
549 $curl_options[CURLOPT_HTTPAUTH] = $this->httpAuthMethod;
550 $curl_options[CURLOPT_USERPWD] = $this->httpAuthCredentials;
552 // curl_setopt_array() returns FALSE if any of the specified options
553 // cannot be set, and stops processing any further options.
554 $result = curl_setopt_array($this->curlHandle, $this->additionalCurlOptions + $curl_options);
556 throw new \UnexpectedValueException('One or more cURL options could not be set.');
559 // We set the user agent header on each request so as to use the current
560 // time and a new uniqid.
561 curl_setopt($this->curlHandle, CURLOPT_USERAGENT, drupal_generate_test_ua($this->databasePrefix));
565 * Initializes and executes a cURL request.
567 * @param $curl_options
568 * An associative array of cURL options to set, where the keys are constants
569 * defined by the cURL library. For a list of valid options, see
570 * http://php.net/manual/function.curl-setopt.php
572 * FALSE if this is an initial request, TRUE if this request is the result
576 * The content returned from the call to curl_exec().
578 * @see curlInitialize()
580 protected function curlExec($curl_options, $redirect = FALSE) {
581 $this->curlInitialize();
583 if (!empty($curl_options[CURLOPT_URL])) {
584 // cURL incorrectly handles URLs with a fragment by including the
585 // fragment in the request to the server, causing some web servers
586 // to reject the request citing "400 - Bad Request". To prevent
587 // this, we strip the fragment from the request.
588 // TODO: Remove this for Drupal 8, since fixed in curl 7.20.0.
589 if (strpos($curl_options[CURLOPT_URL], '#')) {
590 $original_url = $curl_options[CURLOPT_URL];
591 $curl_options[CURLOPT_URL] = strtok($curl_options[CURLOPT_URL], '#');
595 $url = empty($curl_options[CURLOPT_URL]) ? curl_getinfo($this->curlHandle, CURLINFO_EFFECTIVE_URL) : $curl_options[CURLOPT_URL];
597 if (!empty($curl_options[CURLOPT_POST])) {
598 // This is a fix for the Curl library to prevent Expect: 100-continue
599 // headers in POST requests, that may cause unexpected HTTP response
600 // codes from some webservers (like lighttpd that returns a 417 error
601 // code). It is done by setting an empty "Expect" header field that is
602 // not overwritten by Curl.
603 $curl_options[CURLOPT_HTTPHEADER][] = 'Expect:';
607 if (!empty($this->curlCookies)) {
608 $cookies = $this->curlCookies;
611 foreach ($this->extractCookiesFromRequest(\Drupal::request()) as $cookie_name => $values) {
612 foreach ($values as $value) {
613 $cookies[] = $cookie_name . '=' . $value;
617 // Merge additional cookies in.
618 if (!empty($cookies)) {
620 CURLOPT_COOKIE => '',
622 // Ensure any existing cookie data string ends with the correct separator.
623 if (!empty($curl_options[CURLOPT_COOKIE])) {
624 $curl_options[CURLOPT_COOKIE] = rtrim($curl_options[CURLOPT_COOKIE], '; ') . '; ';
626 $curl_options[CURLOPT_COOKIE] .= implode('; ', $cookies) . ';';
629 curl_setopt_array($this->curlHandle, $this->additionalCurlOptions + $curl_options);
632 // Reset headers, the session ID and the redirect counter.
633 $this->sessionId = NULL;
635 $this->redirectCount = 0;
638 $content = curl_exec($this->curlHandle);
639 $status = curl_getinfo($this->curlHandle, CURLINFO_HTTP_CODE);
641 // cURL incorrectly handles URLs with fragments, so instead of
642 // letting cURL handle redirects we take of them ourselves to
643 // to prevent fragments being sent to the web server as part
645 // TODO: Remove this for Drupal 8, since fixed in curl 7.20.0.
646 if (in_array($status, [300, 301, 302, 303, 305, 307]) && $this->redirectCount < $this->maximumRedirects) {
647 if ($this->drupalGetHeader('location')) {
648 $this->redirectCount++;
650 $curl_options[CURLOPT_URL] = $this->drupalGetHeader('location');
651 $curl_options[CURLOPT_HTTPGET] = TRUE;
652 return $this->curlExec($curl_options, TRUE);
656 $this->setRawContent($content);
657 $this->url = isset($original_url) ? $original_url : curl_getinfo($this->curlHandle, CURLINFO_EFFECTIVE_URL);
660 '@method' => !empty($curl_options[CURLOPT_NOBODY]) ? 'HEAD' : (empty($curl_options[CURLOPT_POSTFIELDS]) ? 'GET' : 'POST'),
661 '@url' => isset($original_url) ? $original_url : $url,
662 '@status' => $status,
663 '@length' => format_size(strlen($this->getRawContent())),
665 $message = new FormattableMarkup('@method @url returned @status (@length).', $message_vars);
666 $this->assertTrue($this->getRawContent() !== FALSE, $message, 'Browser');
667 return $this->getRawContent();
671 * Reads headers and registers errors received from the tested site.
673 * @param $curlHandler
678 * @see _drupal_log_error()
680 protected function curlHeaderCallback($curlHandler, $header) {
681 // Header fields can be extended over multiple lines by preceding each
682 // extra line with at least one SP or HT. They should be joined on receive.
683 // Details are in RFC2616 section 4.
684 if ($header[0] == ' ' || $header[0] == "\t") {
685 // Normalize whitespace between chucks.
686 $this->headers[] = array_pop($this->headers) . ' ' . trim($header);
689 $this->headers[] = $header;
692 // Errors are being sent via X-Drupal-Assertion-* headers,
693 // generated by _drupal_log_error() in the exact form required
694 // by \Drupal\simpletest\WebTestBase::error().
695 if (preg_match('/^X-Drupal-Assertion-[0-9]+: (.*)$/', $header, $matches)) {
696 $parameters = unserialize(urldecode($matches[1]));
697 // Handle deprecation notices triggered by system under test.
698 if ($parameters[1] === 'User deprecated function') {
699 if (getenv('SYMFONY_DEPRECATIONS_HELPER') !== 'disabled') {
700 $message = (string) $parameters[0];
701 $test_info = TestDiscovery::getTestInfo(get_called_class());
702 if ($test_info['group'] !== 'legacy' && !in_array($message, DeprecationListenerTrait::getSkippedDeprecations())) {
703 call_user_func_array([&$this, 'error'], $parameters);
708 // Call \Drupal\simpletest\WebTestBase::error() with the parameters from
710 call_user_func_array([&$this, 'error'], $parameters);
715 if (preg_match('/^Set-Cookie: ([^=]+)=(.+)/', $header, $matches)) {
717 $parts = array_map('trim', explode(';', $matches[2]));
718 $value = array_shift($parts);
719 $this->cookies[$name] = ['value' => $value, 'secure' => in_array('secure', $parts)];
720 if ($name === $this->getSessionName()) {
721 if ($value != 'deleted') {
722 $this->sessionId = $value;
725 $this->sessionId = NULL;
730 // This is required by cURL.
731 return strlen($header);
735 * Close the cURL handler and unset the handler.
737 protected function curlClose() {
738 if (isset($this->curlHandle)) {
739 curl_close($this->curlHandle);
740 unset($this->curlHandle);
745 * Returns whether the test is being executed from within a test site.
747 * Mainly used by recursive tests (i.e. to test the testing framework).
750 * TRUE if this test was instantiated in a request within the test site,
753 * @see \Drupal\Core\DrupalKernel::bootConfiguration()
755 protected function isInChildSite() {
756 return DRUPAL_TEST_IN_CHILD_SITE;
760 * Retrieves a Drupal path or an absolute path.
762 * @param \Drupal\Core\Url|string $path
763 * Drupal path or URL to load into internal browser
765 * Options to be forwarded to the url generator.
767 * An array containing additional HTTP request headers, each formatted as
771 * The retrieved HTML string, also available as $this->getRawContent()
773 protected function drupalGet($path, array $options = [], array $headers = []) {
774 // We re-using a CURL connection here. If that connection still has certain
775 // options set, it might change the GET into a POST. Make sure we clear out
777 $out = $this->curlExec([CURLOPT_HTTPGET => TRUE, CURLOPT_URL => $this->buildUrl($path, $options), CURLOPT_NOBODY => FALSE, CURLOPT_HTTPHEADER => $headers]);
778 // Ensure that any changes to variables in the other thread are picked up.
779 $this->refreshVariables();
781 // Replace original page output with new output from redirected page(s).
782 if ($new = $this->checkForMetaRefresh()) {
784 // We are finished with all meta refresh redirects, so reset the counter.
785 $this->metaRefreshCount = 0;
788 if ($path instanceof Url) {
789 $path = $path->setAbsolute()->toString(TRUE)->getGeneratedUrl();
792 $verbose = 'GET request to: ' . $path .
793 '<hr />Ending URL: ' . $this->getUrl();
794 if ($this->dumpHeaders) {
795 $verbose .= '<hr />Headers: <pre>' . Html::escape(var_export(array_map('trim', $this->headers), TRUE)) . '</pre>';
797 $verbose .= '<hr />' . $out;
799 $this->verbose($verbose);
804 * Retrieves a Drupal path or an absolute path and JSON decodes the result.
806 * @param \Drupal\Core\Url|string $path
807 * Drupal path or URL to request AJAX from.
808 * @param array $options
809 * Array of URL options.
810 * @param array $headers
811 * Array of headers. Eg array('Accept: application/vnd.drupal-ajax').
816 protected function drupalGetJSON($path, array $options = [], array $headers = []) {
817 return Json::decode($this->drupalGetWithFormat($path, 'json', $options, $headers));
821 * Retrieves a Drupal path or an absolute path for a given format.
823 * @param \Drupal\Core\Url|string $path
824 * Drupal path or URL to request given format from.
825 * @param string $format
826 * The wanted request format.
827 * @param array $options
828 * Array of URL options.
829 * @param array $headers
833 * The result of the request.
835 protected function drupalGetWithFormat($path, $format, array $options = [], array $headers = []) {
836 $options = array_merge_recursive(['query' => ['_format' => $format]], $options);
837 return $this->drupalGet($path, $options, $headers);
841 * Requests a path or URL in drupal_ajax format and JSON-decodes the response.
843 * @param \Drupal\Core\Url|string $path
844 * Drupal path or URL to request from.
845 * @param array $options
846 * Array of URL options.
847 * @param array $headers
853 protected function drupalGetAjax($path, array $options = [], array $headers = []) {
854 if (!isset($options['query'][MainContentViewSubscriber::WRAPPER_FORMAT])) {
855 $options['query'][MainContentViewSubscriber::WRAPPER_FORMAT] = 'drupal_ajax';
857 return Json::decode($this->drupalGetXHR($path, $options, $headers));
861 * Requests a Drupal path or an absolute path as if it is a XMLHttpRequest.
863 * @param \Drupal\Core\Url|string $path
864 * Drupal path or URL to request from.
865 * @param array $options
866 * Array of URL options.
867 * @param array $headers
871 * The retrieved content.
873 protected function drupalGetXHR($path, array $options = [], array $headers = []) {
874 $headers[] = 'X-Requested-With: XMLHttpRequest';
875 return $this->drupalGet($path, $options, $headers);
879 * Executes a form submission.
881 * It will be done as usual POST request with SimpleBrowser.
883 * @param \Drupal\Core\Url|string $path
884 * Location of the post form. Either a Drupal path or an absolute path or
885 * NULL to post to the current page. For multi-stage forms you can set the
886 * path to NULL and have it post to the last received page. Example:
889 * // First step in form.
890 * $edit = array(...);
891 * $this->drupalPostForm('some_url', $edit, t('Save'));
893 * // Second step in form.
894 * $edit = array(...);
895 * $this->drupalPostForm(NULL, $edit, t('Save'));
898 * Field data in an associative array. Changes the current input fields
899 * (where possible) to the values indicated.
901 * When working with form tests, the keys for an $edit element should match
902 * the 'name' parameter of the HTML of the form. For example, the 'body'
903 * field for a node has the following HTML:
905 * <textarea id="edit-body-und-0-value" class="text-full form-textarea
906 * resize-vertical" placeholder="" cols="60" rows="9"
907 * name="body[0][value]"></textarea>
909 * When testing this field using an $edit parameter, the code becomes:
911 * $edit["body[0][value]"] = 'My test value';
914 * A checkbox can be set to TRUE to be checked and should be set to FALSE to
915 * be unchecked. Multiple select fields can be tested using 'name[]' and
916 * setting each of the desired values in an array:
919 * $edit['name[]'] = array('value1', 'value2');
922 * Value of the submit button whose click is to be emulated. For example,
923 * t('Save'). The processing of the request depends on this value. For
924 * example, a form may have one button with the value t('Save') and another
925 * button with the value t('Delete'), and execute different code depending
926 * on which one is clicked.
928 * This function can also be called to emulate an Ajax submission. In this
929 * case, this value needs to be an array with the following keys:
930 * - path: A path to submit the form values to for Ajax-specific processing.
931 * - triggering_element: If the value for the 'path' key is a generic Ajax
932 * processing path, this needs to be set to the name of the element. If
933 * the name doesn't identify the element uniquely, then this should
934 * instead be an array with a single key/value pair, corresponding to the
935 * element name and value. The \Drupal\Core\Form\FormAjaxResponseBuilder
936 * uses this to find the #ajax information for the element, including
937 * which specific callback to use for processing the request.
939 * This can also be set to NULL in order to emulate an Internet Explorer
940 * submission of a form with a single text field, and pressing ENTER in that
941 * textfield: under these conditions, no button information is added to the
944 * Options to be forwarded to the url generator.
946 * An array containing additional HTTP request headers, each formatted as
948 * @param $form_html_id
949 * (optional) HTML ID of the form to be submitted. On some pages
950 * there are many identical forms, so just using the value of the submit
951 * button is not enough. For example: 'trigger-node-presave-assign-form'.
952 * Note that this is not the Drupal $form_id, but rather the HTML ID of the
953 * form, which is typically the same thing but with hyphens replacing the
956 * (optional) A string of additional data to append to the POST submission.
957 * This can be used to add POST data for which there are no HTML fields, as
958 * is done by drupalPostAjaxForm(). This string is literally appended to the
959 * POST data, so it must already be urlencoded and contain a leading "&"
960 * (e.g., "&extra_var1=hello+world&extra_var2=you%26me").
962 protected function drupalPostForm($path, $edit, $submit, array $options = [], array $headers = [], $form_html_id = NULL, $extra_post = NULL) {
963 if (is_object($submit)) {
964 // Cast MarkupInterface objects to string.
965 $submit = (string) $submit;
967 if (is_array($edit)) {
968 $edit = $this->castSafeStrings($edit);
971 $submit_matches = FALSE;
972 $ajax = is_array($submit);
974 $this->drupalGet($path, $options);
977 if ($this->parse()) {
979 // Let's iterate over all the forms.
981 if (!empty($form_html_id)) {
982 $xpath .= "[@id='" . $form_html_id . "']";
984 $forms = $this->xpath($xpath);
985 foreach ($forms as $form) {
986 // We try to set the fields of this form as specified in $edit.
990 $submit_matches = $this->handleForm($post, $edit, $upload, $ajax ? NULL : $submit, $form);
991 $action = isset($form['action']) ? $this->getAbsoluteUrl((string) $form['action']) : $this->getUrl();
993 if (empty($submit['path'])) {
994 throw new \Exception('No #ajax path specified.');
996 $action = $this->getAbsoluteUrl($submit['path']);
997 // Ajax callbacks verify the triggering element if necessary, so while
998 // we may eventually want extra code that verifies it in the
999 // handleForm() function, it's not currently a requirement.
1000 $submit_matches = TRUE;
1002 // We post only if we managed to handle every field in edit and the
1003 // submit button matches.
1004 if (!$edit && ($submit_matches || !isset($submit))) {
1005 $post_array = $post;
1007 foreach ($upload as $key => $file) {
1008 if (is_array($file) && count($file)) {
1009 // There seems to be no way via php's API to cURL to upload
1010 // several files with the same post field name. However, Drupal
1011 // still sees array-index syntax in a similar way.
1012 for ($i = 0; $i < count($file); $i++) {
1013 $postfield = str_replace('[]', '', $key) . '[' . $i . ']';
1014 $file_path = $this->container->get('file_system')->realpath($file[$i]);
1015 $post[$postfield] = curl_file_create($file_path);
1019 $file = $this->container->get('file_system')->realpath($file);
1020 if ($file && is_file($file)) {
1021 $post[$key] = curl_file_create($file);
1027 $post = $this->serializePostValues($post) . $extra_post;
1029 $out = $this->curlExec([CURLOPT_URL => $action, CURLOPT_POST => TRUE, CURLOPT_POSTFIELDS => $post, CURLOPT_HTTPHEADER => $headers]);
1030 // Ensure that any changes to variables in the other thread are picked
1032 $this->refreshVariables();
1034 // Replace original page output with new output from redirected
1036 if ($new = $this->checkForMetaRefresh()) {
1040 if ($path instanceof Url) {
1041 $path = $path->toString();
1043 $verbose = 'POST request to: ' . $path;
1044 $verbose .= '<hr />Ending URL: ' . $this->getUrl();
1045 if ($this->dumpHeaders) {
1046 $verbose .= '<hr />Headers: <pre>' . Html::escape(var_export(array_map('trim', $this->headers), TRUE)) . '</pre>';
1048 $verbose .= '<hr />Fields: ' . highlight_string('<?php ' . var_export($post_array, TRUE), TRUE);
1049 $verbose .= '<hr />' . $out;
1051 $this->verbose($verbose);
1055 // We have not found a form which contained all fields of $edit.
1056 foreach ($edit as $name => $value) {
1057 $this->fail(new FormattableMarkup('Failed to set field @name to @value', ['@name' => $name, '@value' => $value]));
1059 if (!$ajax && isset($submit)) {
1060 $this->assertTrue($submit_matches, format_string('Found the @submit button', ['@submit' => $submit]));
1062 $this->fail(format_string('Found the requested form fields at @path', ['@path' => ($path instanceof Url) ? $path->toString() : $path]));
1067 * Executes an Ajax form submission.
1069 * This executes a POST as ajax.js does. The returned JSON data is used to
1070 * update $this->content via drupalProcessAjaxResponse(). It also returns
1071 * the array of AJAX commands received.
1073 * @param \Drupal\Core\Url|string $path
1074 * Location of the form containing the Ajax enabled element to test. Can be
1075 * either a Drupal path or an absolute path or NULL to use the current page.
1077 * Field data in an associative array. Changes the current input fields
1078 * (where possible) to the values indicated.
1079 * @param $triggering_element
1080 * The name of the form element that is responsible for triggering the Ajax
1081 * functionality to test. May be a string or, if the triggering element is
1082 * a button, an associative array where the key is the name of the button
1083 * and the value is the button label. i.e.) array('op' => t('Refresh')).
1085 * (optional) Override the path set by the Ajax settings of the triggering
1088 * (optional) Options to be forwarded to the url generator.
1090 * (optional) An array containing additional HTTP request headers, each
1091 * formatted as "name: value". Forwarded to drupalPostForm().
1092 * @param $form_html_id
1093 * (optional) HTML ID of the form to be submitted, use when there is more
1094 * than one identical form on the same page and the value of the triggering
1095 * element is not enough to identify the form. Note this is not the Drupal
1096 * ID of the form but rather the HTML ID of the form.
1097 * @param $ajax_settings
1098 * (optional) An array of Ajax settings which if specified will be used in
1099 * place of the Ajax settings of the triggering element.
1102 * An array of Ajax commands.
1104 * @see drupalPostForm()
1105 * @see drupalProcessAjaxResponse()
1108 protected function drupalPostAjaxForm($path, $edit, $triggering_element, $ajax_path = NULL, array $options = [], array $headers = [], $form_html_id = NULL, $ajax_settings = NULL) {
1110 // Get the content of the initial page prior to calling drupalPostForm(),
1111 // since drupalPostForm() replaces $this->content.
1113 // Avoid sending the wrapper query argument to drupalGet so we can fetch
1114 // the form and populate the internal WebTest values.
1115 $get_options = $options;
1116 unset($get_options['query'][MainContentViewSubscriber::WRAPPER_FORMAT]);
1117 $this->drupalGet($path, $get_options);
1119 $content = $this->content;
1120 $drupal_settings = $this->drupalSettings;
1122 // Provide a default value for the wrapper envelope.
1123 $options['query'][MainContentViewSubscriber::WRAPPER_FORMAT] =
1124 isset($options['query'][MainContentViewSubscriber::WRAPPER_FORMAT]) ?
1125 $options['query'][MainContentViewSubscriber::WRAPPER_FORMAT] :
1128 // Get the Ajax settings bound to the triggering element.
1129 if (!isset($ajax_settings)) {
1130 if (is_array($triggering_element)) {
1131 $xpath = '//*[@name="' . key($triggering_element) . '" and @value="' . current($triggering_element) . '"]';
1134 $xpath = '//*[@name="' . $triggering_element . '"]';
1136 if (isset($form_html_id)) {
1137 $xpath = '//form[@id="' . $form_html_id . '"]' . $xpath;
1139 $element = $this->xpath($xpath);
1140 $element_id = (string) $element[0]['id'];
1141 $ajax_settings = $drupal_settings['ajax'][$element_id];
1144 // Add extra information to the POST data as ajax.js does.
1146 if (isset($ajax_settings['submit'])) {
1147 foreach ($ajax_settings['submit'] as $key => $value) {
1148 $extra_post[$key] = $value;
1151 $extra_post[AjaxResponseSubscriber::AJAX_REQUEST_PARAMETER] = 1;
1152 $extra_post += $this->getAjaxPageStatePostData();
1153 // Now serialize all the $extra_post values, and prepend it with an '&'.
1154 $extra_post = '&' . $this->serializePostValues($extra_post);
1156 // Unless a particular path is specified, use the one specified by the
1158 if (!isset($ajax_path)) {
1159 if (isset($ajax_settings['url'])) {
1160 // In order to allow to set for example the wrapper envelope query
1161 // parameter we need to get the system path again.
1162 $parsed_url = UrlHelper::parse($ajax_settings['url']);
1163 $options['query'] = $parsed_url['query'] + $options['query'];
1164 $options += ['fragment' => $parsed_url['fragment']];
1166 // We know that $parsed_url['path'] is already with the base path
1168 $ajax_path = preg_replace(
1169 '/^' . preg_quote(base_path(), '/') . '/',
1176 if (empty($ajax_path)) {
1177 throw new \Exception('No #ajax path specified.');
1180 $ajax_path = $this->container->get('unrouted_url_assembler')->assemble('base://' . $ajax_path, $options);
1182 // Submit the POST request.
1183 $return = Json::decode($this->drupalPostForm(NULL, $edit, ['path' => $ajax_path, 'triggering_element' => $triggering_element], $options, $headers, $form_html_id, $extra_post));
1184 if ($this->assertAjaxHeader) {
1185 $this->assertIdentical($this->drupalGetHeader('X-Drupal-Ajax-Token'), '1', 'Ajax response header found.');
1188 // Change the page content by applying the returned commands.
1189 if (!empty($ajax_settings) && !empty($return)) {
1190 $this->drupalProcessAjaxResponse($content, $return, $ajax_settings, $drupal_settings);
1193 $verbose = 'AJAX POST request to: ' . $path;
1194 $verbose .= '<br />AJAX controller path: ' . $ajax_path;
1195 $verbose .= '<hr />Ending URL: ' . $this->getUrl();
1196 $verbose .= '<hr />' . $this->content;
1198 $this->verbose($verbose);
1204 * Processes an AJAX response into current content.
1206 * This processes the AJAX response as ajax.js does. It uses the response's
1207 * JSON data, an array of commands, to update $this->content using equivalent
1208 * DOM manipulation as is used by ajax.js.
1209 * It does not apply custom AJAX commands though, because emulation is only
1210 * implemented for the AJAX commands that ship with Drupal core.
1212 * @param string $content
1213 * The current HTML content.
1214 * @param array $ajax_response
1215 * An array of AJAX commands.
1216 * @param array $ajax_settings
1217 * An array of AJAX settings which will be used to process the response.
1218 * @param array $drupal_settings
1219 * An array of settings to update the value of drupalSettings for the
1220 * currently-loaded page.
1222 * @see drupalPostAjaxForm()
1225 protected function drupalProcessAjaxResponse($content, array $ajax_response, array $ajax_settings, array $drupal_settings) {
1227 // ajax.js applies some defaults to the settings object, so do the same
1228 // for what's used by this function.
1230 'method' => 'replaceWith',
1232 // DOM can load HTML soup. But, HTML soup can throw warnings, suppress
1234 $dom = new \DOMDocument();
1235 @$dom->loadHTML($content);
1236 // XPath allows for finding wrapper nodes better than DOM does.
1237 $xpath = new \DOMXPath($dom);
1238 foreach ($ajax_response as $command) {
1239 // Error messages might be not commands.
1240 if (!is_array($command)) {
1243 switch ($command['command']) {
1245 $drupal_settings = NestedArray::mergeDeepArray([$drupal_settings, $command['settings']], TRUE);
1249 $wrapperNode = NULL;
1250 // When a command doesn't specify a selector, use the
1251 // #ajax['wrapper'] which is always an HTML ID.
1252 if (!isset($command['selector'])) {
1253 $wrapperNode = $xpath->query('//*[@id="' . $ajax_settings['wrapper'] . '"]')->item(0);
1255 // @todo Ajax commands can target any jQuery selector, but these are
1256 // hard to fully emulate with XPath. For now, just handle 'head'
1257 // and 'body', since these are used by the Ajax renderer.
1258 elseif (in_array($command['selector'], ['head', 'body'])) {
1259 $wrapperNode = $xpath->query('//' . $command['selector'])->item(0);
1262 // ajax.js adds an enclosing DIV to work around a Safari bug.
1263 $newDom = new \DOMDocument();
1264 // DOM can load HTML soup. But, HTML soup can throw warnings,
1266 @$newDom->loadHTML('<div>' . $command['data'] . '</div>');
1267 // Suppress warnings thrown when duplicate HTML IDs are encountered.
1268 // This probably means we are replacing an element with the same ID.
1269 $newNode = @$dom->importNode($newDom->documentElement->firstChild->firstChild, TRUE);
1270 $method = isset($command['method']) ? $command['method'] : $ajax_settings['method'];
1271 // The "method" is a jQuery DOM manipulation function. Emulate
1272 // each one using PHP's DOMNode API.
1275 $wrapperNode->parentNode->replaceChild($newNode, $wrapperNode);
1278 $wrapperNode->appendChild($newNode);
1281 // If no firstChild, insertBefore() falls back to
1283 $wrapperNode->insertBefore($newNode, $wrapperNode->firstChild);
1286 $wrapperNode->parentNode->insertBefore($newNode, $wrapperNode);
1289 // If no nextSibling, insertBefore() falls back to
1291 $wrapperNode->parentNode->insertBefore($newNode, $wrapperNode->nextSibling);
1294 foreach ($wrapperNode->childNodes as $childNode) {
1295 $wrapperNode->removeChild($childNode);
1297 $wrapperNode->appendChild($newNode);
1303 // @todo Add suitable implementations for these commands in order to
1304 // have full test coverage of what ajax.js can do.
1317 case 'update_build_id':
1318 $buildId = $xpath->query('//input[@name="form_build_id" and @value="' . $command['old'] . '"]')->item(0);
1320 $buildId->setAttribute('value', $command['new']);
1325 $content = $dom->saveHTML();
1326 $this->setRawContent($content);
1327 $this->setDrupalSettings($drupal_settings);
1331 * Perform a POST HTTP request.
1333 * @param string|\Drupal\Core\Url $path
1334 * Drupal path or absolute path where the request should be POSTed.
1335 * @param string $accept
1336 * The value for the "Accept" header. Usually either 'application/json' or
1337 * 'application/vnd.drupal-ajax'.
1338 * @param array $post
1339 * The POST data. When making a 'application/vnd.drupal-ajax' request, the
1340 * Ajax page state data should be included. Use getAjaxPageStatePostData()
1342 * @param array $options
1343 * (optional) Options to be forwarded to the url generator. The 'absolute'
1344 * option will automatically be enabled.
1347 * The content returned from the call to curl_exec().
1349 * @see WebTestBase::getAjaxPageStatePostData()
1350 * @see WebTestBase::curlExec()
1352 protected function drupalPost($path, $accept, array $post, $options = []) {
1353 return $this->curlExec([
1354 CURLOPT_URL => $this->buildUrl($path, $options),
1355 CURLOPT_POST => TRUE,
1356 CURLOPT_POSTFIELDS => $this->serializePostValues($post),
1357 CURLOPT_HTTPHEADER => [
1358 'Accept: ' . $accept,
1359 'Content-Type: application/x-www-form-urlencoded',
1365 * Performs a POST HTTP request with a specific format.
1367 * @param string|\Drupal\Core\Url $path
1368 * Drupal path or absolute path where the request should be POSTed.
1369 * @param string $format
1370 * The request format.
1371 * @param array $post
1372 * The POST data. When making a 'application/vnd.drupal-ajax' request, the
1373 * Ajax page state data should be included. Use getAjaxPageStatePostData()
1375 * @param array $options
1376 * (optional) Options to be forwarded to the url generator. The 'absolute'
1377 * option will automatically be enabled.
1380 * The content returned from the call to curl_exec().
1382 * @see WebTestBase::drupalPost
1383 * @see WebTestBase::getAjaxPageStatePostData()
1384 * @see WebTestBase::curlExec()
1386 protected function drupalPostWithFormat($path, $format, array $post, $options = []) {
1387 $options['query']['_format'] = $format;
1388 return $this->drupalPost($path, '', $post, $options);
1392 * Get the Ajax page state from drupalSettings and prepare it for POSTing.
1395 * The Ajax page state POST data.
1397 protected function getAjaxPageStatePostData() {
1399 $drupal_settings = $this->drupalSettings;
1400 if (isset($drupal_settings['ajaxPageState']['theme'])) {
1401 $post['ajax_page_state[theme]'] = $drupal_settings['ajaxPageState']['theme'];
1403 if (isset($drupal_settings['ajaxPageState']['theme_token'])) {
1404 $post['ajax_page_state[theme_token]'] = $drupal_settings['ajaxPageState']['theme_token'];
1406 if (isset($drupal_settings['ajaxPageState']['libraries'])) {
1407 $post['ajax_page_state[libraries]'] = $drupal_settings['ajaxPageState']['libraries'];
1413 * Serialize POST HTTP request values.
1415 * Encode according to application/x-www-form-urlencoded. Both names and
1416 * values needs to be urlencoded, according to
1417 * http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.1
1419 * @param array $post
1420 * The array of values to be POSTed.
1423 * The serialized result.
1425 protected function serializePostValues($post = []) {
1426 foreach ($post as $key => $value) {
1427 $post[$key] = urlencode($key) . '=' . urlencode($value);
1429 return implode('&', $post);
1433 * Transforms a nested array into a flat array suitable for WebTestBase::drupalPostForm().
1435 * @param array $values
1436 * A multi-dimensional form values array to convert.
1439 * The flattened $edit array suitable for WebTestBase::drupalPostForm().
1441 protected function translatePostValues(array $values) {
1443 // The easiest and most straightforward way to translate values suitable for
1444 // WebTestBase::drupalPostForm() is to actually build the POST data string
1445 // and convert the resulting key/value pairs back into a flat array.
1446 $query = http_build_query($values);
1447 foreach (explode('&', $query) as $item) {
1448 list($key, $value) = explode('=', $item);
1449 $edit[urldecode($key)] = urldecode($value);
1455 * Checks for meta refresh tag and if found call drupalGet() recursively.
1457 * This function looks for the http-equiv attribute to be set to "Refresh" and
1458 * is case-sensitive.
1461 * Either the new page content or FALSE.
1463 protected function checkForMetaRefresh() {
1464 if (strpos($this->getRawContent(), '<meta ') && $this->parse() && (!isset($this->maximumMetaRefreshCount) || $this->metaRefreshCount < $this->maximumMetaRefreshCount)) {
1465 $refresh = $this->xpath('//meta[@http-equiv="Refresh"]');
1466 if (!empty($refresh)) {
1467 // Parse the content attribute of the meta tag for the format:
1468 // "[delay]: URL=[page_to_redirect_to]".
1469 if (preg_match('/\d+;\s*URL=(?<url>.*)/i', $refresh[0]['content'], $match)) {
1470 $this->metaRefreshCount++;
1471 return $this->drupalGet($this->getAbsoluteUrl(Html::decodeEntities($match['url'])));
1479 * Retrieves only the headers for a Drupal path or an absolute path.
1482 * Drupal path or URL to load into internal browser
1484 * Options to be forwarded to the url generator.
1486 * An array containing additional HTTP request headers, each formatted as
1490 * The retrieved headers, also available as $this->getRawContent()
1492 protected function drupalHead($path, array $options = [], array $headers = []) {
1493 $options['absolute'] = TRUE;
1494 $url = $this->buildUrl($path, $options);
1495 $out = $this->curlExec([CURLOPT_NOBODY => TRUE, CURLOPT_URL => $url, CURLOPT_HTTPHEADER => $headers]);
1496 // Ensure that any changes to variables in the other thread are picked up.
1497 $this->refreshVariables();
1499 if ($this->dumpHeaders) {
1500 $this->verbose('GET request to: ' . $path .
1501 '<hr />Ending URL: ' . $this->getUrl() .
1502 '<hr />Headers: <pre>' . Html::escape(var_export(array_map('trim', $this->headers), TRUE)) . '</pre>');
1509 * Handles form input related to drupalPostForm().
1511 * Ensure that the specified fields exist and attempt to create POST data in
1512 * the correct manner for the particular field type.
1515 * Reference to array of post values.
1517 * Reference to array of edit values to be checked against the form.
1519 * Form submit button value.
1521 * Array of form elements.
1524 * Submit value matches a valid submit input in the form.
1526 protected function handleForm(&$post, &$edit, &$upload, $submit, $form) {
1527 // Retrieve the form elements.
1528 $elements = $form->xpath('.//input[not(@disabled)]|.//textarea[not(@disabled)]|.//select[not(@disabled)]');
1529 $submit_matches = FALSE;
1530 foreach ($elements as $element) {
1531 // SimpleXML objects need string casting all the time.
1532 $name = (string) $element['name'];
1533 // This can either be the type of <input> or the name of the tag itself
1534 // for <select> or <textarea>.
1535 $type = isset($element['type']) ? (string) $element['type'] : $element->getName();
1536 $value = isset($element['value']) ? (string) $element['value'] : '';
1538 if (isset($edit[$name])) {
1554 case 'datetime-local';
1555 $post[$name] = $edit[$name];
1556 unset($edit[$name]);
1559 if ($edit[$name] == $value) {
1560 $post[$name] = $edit[$name];
1561 unset($edit[$name]);
1565 // To prevent checkbox from being checked.pass in a FALSE,
1566 // otherwise the checkbox will be set to its value regardless
1568 if ($edit[$name] === FALSE) {
1569 unset($edit[$name]);
1573 unset($edit[$name]);
1574 $post[$name] = $value;
1578 $new_value = $edit[$name];
1579 $options = $this->getAllOptions($element);
1580 if (is_array($new_value)) {
1581 // Multiple select box.
1582 if (!empty($new_value)) {
1584 $key = preg_replace('/\[\]$/', '', $name);
1585 foreach ($options as $option) {
1586 $option_value = (string) $option['value'];
1587 if (in_array($option_value, $new_value)) {
1588 $post[$key . '[' . $index++ . ']'] = $option_value;
1590 unset($edit[$name]);
1595 // No options selected: do not include any POST data for the
1598 unset($edit[$name]);
1602 // Single select box.
1603 foreach ($options as $option) {
1604 if ($new_value == $option['value']) {
1605 $post[$name] = $new_value;
1606 unset($edit[$name]);
1614 $upload[$name] = $edit[$name];
1615 unset($edit[$name]);
1619 if (!isset($post[$name]) && !$done) {
1622 $post[$name] = (string) $element;
1625 $single = empty($element['multiple']);
1628 $key = preg_replace('/\[\]$/', '', $name);
1629 $options = $this->getAllOptions($element);
1630 foreach ($options as $option) {
1631 // For single select, we load the first option, if there is a
1632 // selected option that will overwrite it later.
1633 if ($option['selected'] || ($first && $single)) {
1636 $post[$name] = (string) $option['value'];
1639 $post[$key . '[' . $index++ . ']'] = (string) $option['value'];
1648 if (isset($submit) && $submit == $value) {
1649 $post[$name] = $value;
1650 $submit_matches = TRUE;
1655 if (!isset($element['checked'])) {
1658 // Deliberate no break.
1660 $post[$name] = $value;
1664 // An empty name means the value is not sent.
1666 return $submit_matches;
1670 * Follows a link by complete name.
1672 * Will click the first link found with this link text by default, or a later
1673 * one if an index is given. Match is case sensitive with normalized space.
1674 * The label is translated label.
1676 * If the link is discovered and clicked, the test passes. Fail otherwise.
1678 * @param string|\Drupal\Component\Render\MarkupInterface $label
1679 * Text between the anchor tags.
1681 * Link position counting from zero.
1683 * @return string|bool
1684 * Page contents on success, or FALSE on failure.
1686 protected function clickLink($label, $index = 0) {
1687 return $this->clickLinkHelper($label, $index, '//a[normalize-space()=:label]');
1691 * Follows a link by partial name.
1693 * If the link is discovered and clicked, the test passes. Fail otherwise.
1695 * @param string|\Drupal\Component\Render\MarkupInterface $label
1696 * Text between the anchor tags, uses starts-with().
1698 * Link position counting from zero.
1700 * @return string|bool
1701 * Page contents on success, or FALSE on failure.
1703 * @see ::clickLink()
1705 protected function clickLinkPartialName($label, $index = 0) {
1706 return $this->clickLinkHelper($label, $index, '//a[starts-with(normalize-space(), :label)]');
1710 * Provides a helper for ::clickLink() and ::clickLinkPartialName().
1712 * @param string|\Drupal\Component\Render\MarkupInterface $label
1713 * Text between the anchor tags, uses starts-with().
1715 * Link position counting from zero.
1716 * @param string $pattern
1717 * A pattern to use for the XPath.
1719 * @return bool|string
1720 * Page contents on success, or FALSE on failure.
1722 protected function clickLinkHelper($label, $index, $pattern) {
1723 // Cast MarkupInterface objects to string.
1724 $label = (string) $label;
1725 $url_before = $this->getUrl();
1726 $urls = $this->xpath($pattern, [':label' => $label]);
1727 if (isset($urls[$index])) {
1728 $url_target = $this->getAbsoluteUrl($urls[$index]['href']);
1729 $this->pass(new FormattableMarkup('Clicked link %label (@url_target) from @url_before', ['%label' => $label, '@url_target' => $url_target, '@url_before' => $url_before]), 'Browser');
1730 return $this->drupalGet($url_target);
1732 $this->fail(new FormattableMarkup('Link %label does not exist on @url_before', ['%label' => $label, '@url_before' => $url_before]), 'Browser');
1737 * Takes a path and returns an absolute path.
1739 * This method is implemented in the way that browsers work, see
1740 * https://url.spec.whatwg.org/#relative-state for more information about the
1743 * @param string $path
1744 * A path from the internal browser content.
1747 * The $path with $base_url prepended, if necessary.
1749 protected function getAbsoluteUrl($path) {
1750 global $base_url, $base_path;
1752 $parts = parse_url($path);
1754 // In case the $path has a host, it is already an absolute URL and we are
1756 if (!empty($parts['host'])) {
1760 // In case the $path contains just a query, we turn it into an absolute URL
1761 // with the same scheme, host and path, see
1762 // https://url.spec.whatwg.org/#relative-state.
1763 if (array_keys($parts) === ['query']) {
1764 $current_uri = new Uri($this->getUrl());
1765 return (string) $current_uri->withQuery($parts['query']);
1768 if (empty($parts['host'])) {
1769 // Ensure that we have a string (and no xpath object).
1770 $path = (string) $path;
1771 // Strip $base_path, if existent.
1772 $length = strlen($base_path);
1773 if (substr($path, 0, $length) === $base_path) {
1774 $path = substr($path, $length);
1776 // Ensure that we have an absolute path.
1777 if (empty($path) || $path[0] !== '/') {
1778 $path = '/' . $path;
1780 // Finally, prepend the $base_url.
1781 $path = $base_url . $path;
1787 * Gets the HTTP response headers of the requested page.
1789 * Normally we are only interested in the headers returned by the last
1790 * request. However, if a page is redirected or HTTP authentication is in use,
1791 * multiple requests will be required to retrieve the page. Headers from all
1792 * requests may be requested by passing TRUE to this function.
1794 * @param $all_requests
1795 * Boolean value specifying whether to return headers from all requests
1796 * instead of just the last request. Defaults to FALSE.
1799 * A name/value array if headers from only the last request are requested.
1800 * If headers from all requests are requested, an array of name/value
1801 * arrays, one for each request.
1803 * The pseudonym ":status" is used for the HTTP status line.
1805 * Values for duplicate headers are stored as a single comma-separated list.
1807 protected function drupalGetHeaders($all_requests = FALSE) {
1809 $headers = [$request => []];
1810 foreach ($this->headers as $header) {
1811 $header = trim($header);
1812 if ($header === '') {
1816 if (strpos($header, 'HTTP/') === 0) {
1821 list($name, $value) = explode(':', $header, 2);
1822 $name = strtolower($name);
1824 if (isset($headers[$request][$name])) {
1825 $headers[$request][$name] .= ',' . trim($value);
1828 $headers[$request][$name] = trim($value);
1832 if (!$all_requests) {
1833 $headers = array_pop($headers);
1839 * Gets the value of an HTTP response header.
1841 * If multiple requests were required to retrieve the page, only the headers
1842 * from the last request will be checked by default. However, if TRUE is
1843 * passed as the second argument, all requests will be processed from last to
1844 * first until the header is found.
1847 * The name of the header to retrieve. Names are case-insensitive (see RFC
1848 * 2616 section 4.2).
1849 * @param $all_requests
1850 * Boolean value specifying whether to check all requests if the header is
1851 * not found in the last request. Defaults to FALSE.
1854 * The HTTP header value or FALSE if not found.
1856 protected function drupalGetHeader($name, $all_requests = FALSE) {
1857 $name = strtolower($name);
1859 if ($all_requests) {
1860 foreach (array_reverse($this->drupalGetHeaders(TRUE)) as $headers) {
1861 if (isset($headers[$name])) {
1862 $header = $headers[$name];
1868 $headers = $this->drupalGetHeaders();
1869 if (isset($headers[$name])) {
1870 $header = $headers[$name];
1877 * Check if a HTTP response header exists and has the expected value.
1879 * @param string $header
1880 * The header key, example: Content-Type
1881 * @param string $value
1883 * @param string $message
1884 * (optional) A message to display with the assertion.
1885 * @param string $group
1886 * (optional) The group this message is in, which is displayed in a column
1887 * in test output. Use 'Debug' to indicate this is debugging output. Do not
1888 * translate this string. Defaults to 'Other'; most tests do not override
1892 * TRUE if the assertion succeeded, FALSE otherwise.
1894 protected function assertHeader($header, $value, $message = '', $group = 'Browser') {
1895 $header_value = $this->drupalGetHeader($header);
1896 return $this->assertTrue($header_value == $value, $message ? $message : 'HTTP response header ' . $header . ' with value ' . $value . ' found, actual value: ' . $header_value, $group);
1900 * Passes if the internal browser's URL matches the given path.
1902 * @param \Drupal\Core\Url|string $path
1903 * The expected system path or URL.
1905 * (optional) Any additional options to pass for $path to the url generator.
1907 * (optional) A message to display with the assertion. Do not translate
1908 * messages: use \Drupal\Component\Render\FormattableMarkup to embed
1909 * variables in the message text, not t(). If left blank, a default message
1910 * will be displayed.
1912 * (optional) The group this message is in, which is displayed in a column
1913 * in test output. Use 'Debug' to indicate this is debugging output. Do not
1914 * translate this string. Defaults to 'Other'; most tests do not override
1918 * TRUE on pass, FALSE on fail.
1920 protected function assertUrl($path, array $options = [], $message = '', $group = 'Other') {
1921 if ($path instanceof Url) {
1924 elseif (UrlHelper::isExternal($path)) {
1925 $url_obj = Url::fromUri($path, $options);
1928 $uri = $path === '<front>' ? 'base:/' : 'base:/' . $path;
1929 // This is needed for language prefixing.
1930 $options['path_processing'] = TRUE;
1931 $url_obj = Url::fromUri($uri, $options);
1933 $url = $url_obj->setAbsolute()->toString();
1935 $message = new FormattableMarkup('Expected @url matches current URL (@current_url).', [
1936 '@url' => var_export($url, TRUE),
1937 '@current_url' => $this->getUrl(),
1940 // Paths in query strings can be encoded or decoded with no functional
1941 // difference, decode them for comparison purposes.
1942 $actual_url = urldecode($this->getUrl());
1943 $expected_url = urldecode($url);
1944 return $this->assertEqual($actual_url, $expected_url, $message, $group);
1948 * Asserts the page responds with the specified response code.
1951 * Response code. For example 200 is a successful page request. For a list
1952 * of all codes see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html.
1954 * (optional) A message to display with the assertion. Do not translate
1955 * messages: use \Drupal\Component\Render\FormattableMarkup to embed
1956 * variables in the message text, not t(). If left blank, a default message
1957 * will be displayed.
1959 * (optional) The group this message is in, which is displayed in a column
1960 * in test output. Use 'Debug' to indicate this is debugging output. Do not
1961 * translate this string. Defaults to 'Browser'; most tests do not override
1967 protected function assertResponse($code, $message = '', $group = 'Browser') {
1968 $curl_code = curl_getinfo($this->curlHandle, CURLINFO_HTTP_CODE);
1969 $match = is_array($code) ? in_array($curl_code, $code) : $curl_code == $code;
1970 return $this->assertTrue($match, $message ? $message : new FormattableMarkup('HTTP response expected @code, actual @curl_code', ['@code' => $code, '@curl_code' => $curl_code]), $group);
1974 * Asserts the page did not return the specified response code.
1977 * Response code. For example 200 is a successful page request. For a list
1978 * of all codes see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html.
1980 * (optional) A message to display with the assertion. Do not translate
1981 * messages: use \Drupal\Component\Render\FormattableMarkup to embed
1982 * variables in the message text, not t(). If left blank, a default message
1983 * will be displayed.
1985 * (optional) The group this message is in, which is displayed in a column
1986 * in test output. Use 'Debug' to indicate this is debugging output. Do not
1987 * translate this string. Defaults to 'Browser'; most tests do not override
1993 protected function assertNoResponse($code, $message = '', $group = 'Browser') {
1994 $curl_code = curl_getinfo($this->curlHandle, CURLINFO_HTTP_CODE);
1995 $match = is_array($code) ? in_array($curl_code, $code) : $curl_code == $code;
1996 return $this->assertFalse($match, $message ? $message : new FormattableMarkup('HTTP response not expected @code, actual @curl_code', ['@code' => $code, '@curl_code' => $curl_code]), $group);
2000 * Builds an a absolute URL from a system path or a URL object.
2002 * @param string|\Drupal\Core\Url $path
2003 * A system path or a URL.
2004 * @param array $options
2005 * Options to be passed to Url::fromUri().
2008 * An absolute URL string.
2010 protected function buildUrl($path, array $options = []) {
2011 if ($path instanceof Url) {
2012 $url_options = $path->getOptions();
2013 $options = $url_options + $options;
2014 $path->setOptions($options);
2015 return $path->setAbsolute()->toString(TRUE)->getGeneratedUrl();
2017 // The URL generator service is not necessarily available yet; e.g., in
2018 // interactive installer tests.
2019 elseif ($this->container->has('url_generator')) {
2020 $force_internal = isset($options['external']) && $options['external'] == FALSE;
2021 if (!$force_internal && UrlHelper::isExternal($path)) {
2022 return Url::fromUri($path, $options)->toString();
2025 $uri = $path === '<front>' ? 'base:/' : 'base:/' . $path;
2026 // Path processing is needed for language prefixing. Skip it when a
2027 // path that may look like an external URL is being used as internal.
2028 $options['path_processing'] = !$force_internal;
2029 return Url::fromUri($uri, $options)
2035 return $this->getAbsoluteUrl($path);
2040 * Asserts whether an expected cache tag was present in the last response.
2042 * @param string $expected_cache_tag
2043 * The expected cache tag.
2045 protected function assertCacheTag($expected_cache_tag) {
2046 $cache_tags = explode(' ', $this->drupalGetHeader('X-Drupal-Cache-Tags'));
2047 $this->assertTrue(in_array($expected_cache_tag, $cache_tags), "'" . $expected_cache_tag . "' is present in the X-Drupal-Cache-Tags header.");
2051 * Asserts whether an expected cache tag was absent in the last response.
2053 * @param string $cache_tag
2054 * The cache tag to check.
2056 protected function assertNoCacheTag($cache_tag) {
2057 $cache_tags = explode(' ', $this->drupalGetHeader('X-Drupal-Cache-Tags'));
2058 $this->assertFalse(in_array($cache_tag, $cache_tags), "'" . $cache_tag . "' is absent in the X-Drupal-Cache-Tags header.");
2062 * Enables/disables the cacheability headers.
2064 * Sets the http.response.debug_cacheability_headers container parameter.
2066 * @param bool $value
2067 * (optional) Whether the debugging cacheability headers should be sent.
2069 protected function setHttpResponseDebugCacheabilityHeaders($value = TRUE) {
2070 $this->setContainerParameter('http.response.debug_cacheability_headers', $value);
2071 $this->rebuildContainer();