annotate core/modules/simpletest/src/WebTestBase.php @ 19:fa3358dc1485 tip

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