annotate core/modules/simpletest/src/WebTestBase.php @ 16:c2387f117808

Routine composer update
author Chris Cannam
date Tue, 10 Jul 2018 15:07:59 +0100
parents 1fec387a4317
children 129ea1e6d783
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@0 10 use Drupal\Component\Utility\SafeMarkup;
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@0 288 'name' => $account->getUsername(),
Chris@0 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@0 297 $pass = $this->assert($this->drupalUserIsLoggedIn($account), format_string('User %name successfully logged in.', ['%name' => $account->getUsername()]), '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@0 663 '@length' => format_size(strlen($this->getRawContent()))
Chris@0 664 ];
Chris@0 665 $message = SafeMarkup::format('@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@14 701 if (!in_array($message, DeprecationListenerTrait::getSkippedDeprecations())) {
Chris@14 702 call_user_func_array([&$this, 'error'], $parameters);
Chris@14 703 }
Chris@14 704 }
Chris@14 705 }
Chris@14 706 else {
Chris@14 707 // Call \Drupal\simpletest\WebTestBase::error() with the parameters from
Chris@14 708 // the header.
Chris@14 709 call_user_func_array([&$this, 'error'], $parameters);
Chris@14 710 }
Chris@0 711 }
Chris@0 712
Chris@0 713 // Save cookies.
Chris@0 714 if (preg_match('/^Set-Cookie: ([^=]+)=(.+)/', $header, $matches)) {
Chris@0 715 $name = $matches[1];
Chris@0 716 $parts = array_map('trim', explode(';', $matches[2]));
Chris@0 717 $value = array_shift($parts);
Chris@0 718 $this->cookies[$name] = ['value' => $value, 'secure' => in_array('secure', $parts)];
Chris@0 719 if ($name === $this->getSessionName()) {
Chris@0 720 if ($value != 'deleted') {
Chris@0 721 $this->sessionId = $value;
Chris@0 722 }
Chris@0 723 else {
Chris@0 724 $this->sessionId = NULL;
Chris@0 725 }
Chris@0 726 }
Chris@0 727 }
Chris@0 728
Chris@0 729 // This is required by cURL.
Chris@0 730 return strlen($header);
Chris@0 731 }
Chris@0 732
Chris@0 733 /**
Chris@0 734 * Close the cURL handler and unset the handler.
Chris@0 735 */
Chris@0 736 protected function curlClose() {
Chris@0 737 if (isset($this->curlHandle)) {
Chris@0 738 curl_close($this->curlHandle);
Chris@0 739 unset($this->curlHandle);
Chris@0 740 }
Chris@0 741 }
Chris@0 742
Chris@0 743 /**
Chris@0 744 * Returns whether the test is being executed from within a test site.
Chris@0 745 *
Chris@0 746 * Mainly used by recursive tests (i.e. to test the testing framework).
Chris@0 747 *
Chris@0 748 * @return bool
Chris@0 749 * TRUE if this test was instantiated in a request within the test site,
Chris@0 750 * FALSE otherwise.
Chris@0 751 *
Chris@0 752 * @see \Drupal\Core\DrupalKernel::bootConfiguration()
Chris@0 753 */
Chris@0 754 protected function isInChildSite() {
Chris@0 755 return DRUPAL_TEST_IN_CHILD_SITE;
Chris@0 756 }
Chris@0 757
Chris@0 758 /**
Chris@0 759 * Retrieves a Drupal path or an absolute path.
Chris@0 760 *
Chris@0 761 * @param \Drupal\Core\Url|string $path
Chris@0 762 * Drupal path or URL to load into internal browser
Chris@0 763 * @param $options
Chris@0 764 * Options to be forwarded to the url generator.
Chris@0 765 * @param $headers
Chris@0 766 * An array containing additional HTTP request headers, each formatted as
Chris@0 767 * "name: value".
Chris@0 768 *
Chris@0 769 * @return string
Chris@0 770 * The retrieved HTML string, also available as $this->getRawContent()
Chris@0 771 */
Chris@0 772 protected function drupalGet($path, array $options = [], array $headers = []) {
Chris@0 773 // We re-using a CURL connection here. If that connection still has certain
Chris@0 774 // options set, it might change the GET into a POST. Make sure we clear out
Chris@0 775 // previous options.
Chris@0 776 $out = $this->curlExec([CURLOPT_HTTPGET => TRUE, CURLOPT_URL => $this->buildUrl($path, $options), CURLOPT_NOBODY => FALSE, CURLOPT_HTTPHEADER => $headers]);
Chris@0 777 // Ensure that any changes to variables in the other thread are picked up.
Chris@0 778 $this->refreshVariables();
Chris@0 779
Chris@0 780 // Replace original page output with new output from redirected page(s).
Chris@0 781 if ($new = $this->checkForMetaRefresh()) {
Chris@0 782 $out = $new;
Chris@0 783 // We are finished with all meta refresh redirects, so reset the counter.
Chris@0 784 $this->metaRefreshCount = 0;
Chris@0 785 }
Chris@0 786
Chris@0 787 if ($path instanceof Url) {
Chris@0 788 $path = $path->setAbsolute()->toString(TRUE)->getGeneratedUrl();
Chris@0 789 }
Chris@0 790
Chris@0 791 $verbose = 'GET request to: ' . $path .
Chris@0 792 '<hr />Ending URL: ' . $this->getUrl();
Chris@0 793 if ($this->dumpHeaders) {
Chris@0 794 $verbose .= '<hr />Headers: <pre>' . Html::escape(var_export(array_map('trim', $this->headers), TRUE)) . '</pre>';
Chris@0 795 }
Chris@0 796 $verbose .= '<hr />' . $out;
Chris@0 797
Chris@0 798 $this->verbose($verbose);
Chris@0 799 return $out;
Chris@0 800 }
Chris@0 801
Chris@0 802 /**
Chris@0 803 * Retrieves a Drupal path or an absolute path and JSON decodes the result.
Chris@0 804 *
Chris@0 805 * @param \Drupal\Core\Url|string $path
Chris@0 806 * Drupal path or URL to request AJAX from.
Chris@0 807 * @param array $options
Chris@0 808 * Array of URL options.
Chris@0 809 * @param array $headers
Chris@0 810 * Array of headers. Eg array('Accept: application/vnd.drupal-ajax').
Chris@0 811 *
Chris@0 812 * @return array
Chris@0 813 * Decoded json.
Chris@0 814 */
Chris@0 815 protected function drupalGetJSON($path, array $options = [], array $headers = []) {
Chris@0 816 return Json::decode($this->drupalGetWithFormat($path, 'json', $options, $headers));
Chris@0 817 }
Chris@0 818
Chris@0 819 /**
Chris@0 820 * Retrieves a Drupal path or an absolute path for a given format.
Chris@0 821 *
Chris@0 822 * @param \Drupal\Core\Url|string $path
Chris@0 823 * Drupal path or URL to request given format from.
Chris@0 824 * @param string $format
Chris@0 825 * The wanted request format.
Chris@0 826 * @param array $options
Chris@0 827 * Array of URL options.
Chris@0 828 * @param array $headers
Chris@0 829 * Array of headers.
Chris@0 830 *
Chris@0 831 * @return mixed
Chris@0 832 * The result of the request.
Chris@0 833 */
Chris@0 834 protected function drupalGetWithFormat($path, $format, array $options = [], array $headers = []) {
Chris@14 835 $options = array_merge_recursive(['query' => ['_format' => $format]], $options);
Chris@0 836 return $this->drupalGet($path, $options, $headers);
Chris@0 837 }
Chris@0 838
Chris@0 839 /**
Chris@0 840 * Requests a path or URL in drupal_ajax format and JSON-decodes the response.
Chris@0 841 *
Chris@0 842 * @param \Drupal\Core\Url|string $path
Chris@0 843 * Drupal path or URL to request from.
Chris@0 844 * @param array $options
Chris@0 845 * Array of URL options.
Chris@0 846 * @param array $headers
Chris@0 847 * Array of headers.
Chris@0 848 *
Chris@0 849 * @return array
Chris@0 850 * Decoded JSON.
Chris@0 851 */
Chris@0 852 protected function drupalGetAjax($path, array $options = [], array $headers = []) {
Chris@0 853 if (!isset($options['query'][MainContentViewSubscriber::WRAPPER_FORMAT])) {
Chris@0 854 $options['query'][MainContentViewSubscriber::WRAPPER_FORMAT] = 'drupal_ajax';
Chris@0 855 }
Chris@0 856 return Json::decode($this->drupalGetXHR($path, $options, $headers));
Chris@0 857 }
Chris@0 858
Chris@0 859 /**
Chris@0 860 * Requests a Drupal path or an absolute path as if it is a XMLHttpRequest.
Chris@0 861 *
Chris@0 862 * @param \Drupal\Core\Url|string $path
Chris@0 863 * Drupal path or URL to request from.
Chris@0 864 * @param array $options
Chris@0 865 * Array of URL options.
Chris@0 866 * @param array $headers
Chris@0 867 * Array of headers.
Chris@0 868 *
Chris@0 869 * @return string
Chris@0 870 * The retrieved content.
Chris@0 871 */
Chris@0 872 protected function drupalGetXHR($path, array $options = [], array $headers = []) {
Chris@0 873 $headers[] = 'X-Requested-With: XMLHttpRequest';
Chris@0 874 return $this->drupalGet($path, $options, $headers);
Chris@0 875 }
Chris@0 876
Chris@0 877 /**
Chris@0 878 * Executes a form submission.
Chris@0 879 *
Chris@0 880 * It will be done as usual POST request with SimpleBrowser.
Chris@0 881 *
Chris@0 882 * @param \Drupal\Core\Url|string $path
Chris@0 883 * Location of the post form. Either a Drupal path or an absolute path or
Chris@0 884 * NULL to post to the current page. For multi-stage forms you can set the
Chris@0 885 * path to NULL and have it post to the last received page. Example:
Chris@0 886 *
Chris@0 887 * @code
Chris@0 888 * // First step in form.
Chris@0 889 * $edit = array(...);
Chris@0 890 * $this->drupalPostForm('some_url', $edit, t('Save'));
Chris@0 891 *
Chris@0 892 * // Second step in form.
Chris@0 893 * $edit = array(...);
Chris@0 894 * $this->drupalPostForm(NULL, $edit, t('Save'));
Chris@0 895 * @endcode
Chris@0 896 * @param $edit
Chris@0 897 * Field data in an associative array. Changes the current input fields
Chris@0 898 * (where possible) to the values indicated.
Chris@0 899 *
Chris@0 900 * When working with form tests, the keys for an $edit element should match
Chris@0 901 * the 'name' parameter of the HTML of the form. For example, the 'body'
Chris@0 902 * field for a node has the following HTML:
Chris@0 903 * @code
Chris@0 904 * <textarea id="edit-body-und-0-value" class="text-full form-textarea
Chris@0 905 * resize-vertical" placeholder="" cols="60" rows="9"
Chris@0 906 * name="body[0][value]"></textarea>
Chris@0 907 * @endcode
Chris@0 908 * When testing this field using an $edit parameter, the code becomes:
Chris@0 909 * @code
Chris@0 910 * $edit["body[0][value]"] = 'My test value';
Chris@0 911 * @endcode
Chris@0 912 *
Chris@0 913 * A checkbox can be set to TRUE to be checked and should be set to FALSE to
Chris@0 914 * be unchecked. Multiple select fields can be tested using 'name[]' and
Chris@0 915 * setting each of the desired values in an array:
Chris@0 916 * @code
Chris@0 917 * $edit = array();
Chris@0 918 * $edit['name[]'] = array('value1', 'value2');
Chris@0 919 * @endcode
Chris@0 920 * @param $submit
Chris@0 921 * Value of the submit button whose click is to be emulated. For example,
Chris@0 922 * t('Save'). The processing of the request depends on this value. For
Chris@0 923 * example, a form may have one button with the value t('Save') and another
Chris@0 924 * button with the value t('Delete'), and execute different code depending
Chris@0 925 * on which one is clicked.
Chris@0 926 *
Chris@0 927 * This function can also be called to emulate an Ajax submission. In this
Chris@0 928 * case, this value needs to be an array with the following keys:
Chris@0 929 * - path: A path to submit the form values to for Ajax-specific processing.
Chris@0 930 * - triggering_element: If the value for the 'path' key is a generic Ajax
Chris@0 931 * processing path, this needs to be set to the name of the element. If
Chris@0 932 * the name doesn't identify the element uniquely, then this should
Chris@0 933 * instead be an array with a single key/value pair, corresponding to the
Chris@0 934 * element name and value. The \Drupal\Core\Form\FormAjaxResponseBuilder
Chris@0 935 * uses this to find the #ajax information for the element, including
Chris@0 936 * which specific callback to use for processing the request.
Chris@0 937 *
Chris@0 938 * This can also be set to NULL in order to emulate an Internet Explorer
Chris@0 939 * submission of a form with a single text field, and pressing ENTER in that
Chris@0 940 * textfield: under these conditions, no button information is added to the
Chris@0 941 * POST data.
Chris@0 942 * @param $options
Chris@0 943 * Options to be forwarded to the url generator.
Chris@0 944 * @param $headers
Chris@0 945 * An array containing additional HTTP request headers, each formatted as
Chris@0 946 * "name: value".
Chris@0 947 * @param $form_html_id
Chris@0 948 * (optional) HTML ID of the form to be submitted. On some pages
Chris@0 949 * there are many identical forms, so just using the value of the submit
Chris@0 950 * button is not enough. For example: 'trigger-node-presave-assign-form'.
Chris@0 951 * Note that this is not the Drupal $form_id, but rather the HTML ID of the
Chris@0 952 * form, which is typically the same thing but with hyphens replacing the
Chris@0 953 * underscores.
Chris@0 954 * @param $extra_post
Chris@0 955 * (optional) A string of additional data to append to the POST submission.
Chris@0 956 * This can be used to add POST data for which there are no HTML fields, as
Chris@0 957 * is done by drupalPostAjaxForm(). This string is literally appended to the
Chris@0 958 * POST data, so it must already be urlencoded and contain a leading "&"
Chris@0 959 * (e.g., "&extra_var1=hello+world&extra_var2=you%26me").
Chris@0 960 */
Chris@0 961 protected function drupalPostForm($path, $edit, $submit, array $options = [], array $headers = [], $form_html_id = NULL, $extra_post = NULL) {
Chris@0 962 if (is_object($submit)) {
Chris@0 963 // Cast MarkupInterface objects to string.
Chris@0 964 $submit = (string) $submit;
Chris@0 965 }
Chris@0 966 if (is_array($edit)) {
Chris@0 967 $edit = $this->castSafeStrings($edit);
Chris@0 968 }
Chris@0 969
Chris@0 970 $submit_matches = FALSE;
Chris@0 971 $ajax = is_array($submit);
Chris@0 972 if (isset($path)) {
Chris@0 973 $this->drupalGet($path, $options);
Chris@0 974 }
Chris@0 975
Chris@0 976 if ($this->parse()) {
Chris@0 977 $edit_save = $edit;
Chris@0 978 // Let's iterate over all the forms.
Chris@0 979 $xpath = "//form";
Chris@0 980 if (!empty($form_html_id)) {
Chris@0 981 $xpath .= "[@id='" . $form_html_id . "']";
Chris@0 982 }
Chris@0 983 $forms = $this->xpath($xpath);
Chris@0 984 foreach ($forms as $form) {
Chris@0 985 // We try to set the fields of this form as specified in $edit.
Chris@0 986 $edit = $edit_save;
Chris@0 987 $post = [];
Chris@0 988 $upload = [];
Chris@0 989 $submit_matches = $this->handleForm($post, $edit, $upload, $ajax ? NULL : $submit, $form);
Chris@0 990 $action = isset($form['action']) ? $this->getAbsoluteUrl((string) $form['action']) : $this->getUrl();
Chris@0 991 if ($ajax) {
Chris@0 992 if (empty($submit['path'])) {
Chris@0 993 throw new \Exception('No #ajax path specified.');
Chris@0 994 }
Chris@0 995 $action = $this->getAbsoluteUrl($submit['path']);
Chris@0 996 // Ajax callbacks verify the triggering element if necessary, so while
Chris@0 997 // we may eventually want extra code that verifies it in the
Chris@0 998 // handleForm() function, it's not currently a requirement.
Chris@0 999 $submit_matches = TRUE;
Chris@0 1000 }
Chris@0 1001 // We post only if we managed to handle every field in edit and the
Chris@0 1002 // submit button matches.
Chris@0 1003 if (!$edit && ($submit_matches || !isset($submit))) {
Chris@0 1004 $post_array = $post;
Chris@0 1005 if ($upload) {
Chris@0 1006 foreach ($upload as $key => $file) {
Chris@0 1007 if (is_array($file) && count($file)) {
Chris@0 1008 // There seems to be no way via php's API to cURL to upload
Chris@0 1009 // several files with the same post field name. However, Drupal
Chris@0 1010 // still sees array-index syntax in a similar way.
Chris@0 1011 for ($i = 0; $i < count($file); $i++) {
Chris@0 1012 $postfield = str_replace('[]', '', $key) . '[' . $i . ']';
Chris@0 1013 $file_path = $this->container->get('file_system')->realpath($file[$i]);
Chris@0 1014 $post[$postfield] = curl_file_create($file_path);
Chris@0 1015 }
Chris@0 1016 }
Chris@0 1017 else {
Chris@0 1018 $file = $this->container->get('file_system')->realpath($file);
Chris@0 1019 if ($file && is_file($file)) {
Chris@0 1020 $post[$key] = curl_file_create($file);
Chris@0 1021 }
Chris@0 1022 }
Chris@0 1023 }
Chris@0 1024 }
Chris@0 1025 else {
Chris@0 1026 $post = $this->serializePostValues($post) . $extra_post;
Chris@0 1027 }
Chris@0 1028 $out = $this->curlExec([CURLOPT_URL => $action, CURLOPT_POST => TRUE, CURLOPT_POSTFIELDS => $post, CURLOPT_HTTPHEADER => $headers]);
Chris@0 1029 // Ensure that any changes to variables in the other thread are picked
Chris@0 1030 // up.
Chris@0 1031 $this->refreshVariables();
Chris@0 1032
Chris@0 1033 // Replace original page output with new output from redirected
Chris@0 1034 // page(s).
Chris@0 1035 if ($new = $this->checkForMetaRefresh()) {
Chris@0 1036 $out = $new;
Chris@0 1037 }
Chris@0 1038
Chris@0 1039 if ($path instanceof Url) {
Chris@0 1040 $path = $path->toString();
Chris@0 1041 }
Chris@0 1042 $verbose = 'POST request to: ' . $path;
Chris@0 1043 $verbose .= '<hr />Ending URL: ' . $this->getUrl();
Chris@0 1044 if ($this->dumpHeaders) {
Chris@0 1045 $verbose .= '<hr />Headers: <pre>' . Html::escape(var_export(array_map('trim', $this->headers), TRUE)) . '</pre>';
Chris@0 1046 }
Chris@0 1047 $verbose .= '<hr />Fields: ' . highlight_string('<?php ' . var_export($post_array, TRUE), TRUE);
Chris@0 1048 $verbose .= '<hr />' . $out;
Chris@0 1049
Chris@0 1050 $this->verbose($verbose);
Chris@0 1051 return $out;
Chris@0 1052 }
Chris@0 1053 }
Chris@0 1054 // We have not found a form which contained all fields of $edit.
Chris@0 1055 foreach ($edit as $name => $value) {
Chris@0 1056 $this->fail(SafeMarkup::format('Failed to set field @name to @value', ['@name' => $name, '@value' => $value]));
Chris@0 1057 }
Chris@0 1058 if (!$ajax && isset($submit)) {
Chris@0 1059 $this->assertTrue($submit_matches, format_string('Found the @submit button', ['@submit' => $submit]));
Chris@0 1060 }
Chris@0 1061 $this->fail(format_string('Found the requested form fields at @path', ['@path' => ($path instanceof Url) ? $path->toString() : $path]));
Chris@0 1062 }
Chris@0 1063 }
Chris@0 1064
Chris@0 1065 /**
Chris@0 1066 * Executes an Ajax form submission.
Chris@0 1067 *
Chris@0 1068 * This executes a POST as ajax.js does. The returned JSON data is used to
Chris@0 1069 * update $this->content via drupalProcessAjaxResponse(). It also returns
Chris@0 1070 * the array of AJAX commands received.
Chris@0 1071 *
Chris@0 1072 * @param \Drupal\Core\Url|string $path
Chris@0 1073 * Location of the form containing the Ajax enabled element to test. Can be
Chris@0 1074 * either a Drupal path or an absolute path or NULL to use the current page.
Chris@0 1075 * @param $edit
Chris@0 1076 * Field data in an associative array. Changes the current input fields
Chris@0 1077 * (where possible) to the values indicated.
Chris@0 1078 * @param $triggering_element
Chris@0 1079 * The name of the form element that is responsible for triggering the Ajax
Chris@0 1080 * functionality to test. May be a string or, if the triggering element is
Chris@0 1081 * a button, an associative array where the key is the name of the button
Chris@0 1082 * and the value is the button label. i.e.) array('op' => t('Refresh')).
Chris@0 1083 * @param $ajax_path
Chris@0 1084 * (optional) Override the path set by the Ajax settings of the triggering
Chris@0 1085 * element.
Chris@0 1086 * @param $options
Chris@0 1087 * (optional) Options to be forwarded to the url generator.
Chris@0 1088 * @param $headers
Chris@0 1089 * (optional) An array containing additional HTTP request headers, each
Chris@0 1090 * formatted as "name: value". Forwarded to drupalPostForm().
Chris@0 1091 * @param $form_html_id
Chris@0 1092 * (optional) HTML ID of the form to be submitted, use when there is more
Chris@0 1093 * than one identical form on the same page and the value of the triggering
Chris@0 1094 * element is not enough to identify the form. Note this is not the Drupal
Chris@0 1095 * ID of the form but rather the HTML ID of the form.
Chris@0 1096 * @param $ajax_settings
Chris@0 1097 * (optional) An array of Ajax settings which if specified will be used in
Chris@0 1098 * place of the Ajax settings of the triggering element.
Chris@0 1099 *
Chris@0 1100 * @return
Chris@0 1101 * An array of Ajax commands.
Chris@0 1102 *
Chris@0 1103 * @see drupalPostForm()
Chris@0 1104 * @see drupalProcessAjaxResponse()
Chris@0 1105 * @see ajax.js
Chris@0 1106 */
Chris@0 1107 protected function drupalPostAjaxForm($path, $edit, $triggering_element, $ajax_path = NULL, array $options = [], array $headers = [], $form_html_id = NULL, $ajax_settings = NULL) {
Chris@0 1108
Chris@0 1109 // Get the content of the initial page prior to calling drupalPostForm(),
Chris@0 1110 // since drupalPostForm() replaces $this->content.
Chris@0 1111 if (isset($path)) {
Chris@0 1112 // Avoid sending the wrapper query argument to drupalGet so we can fetch
Chris@0 1113 // the form and populate the internal WebTest values.
Chris@0 1114 $get_options = $options;
Chris@0 1115 unset($get_options['query'][MainContentViewSubscriber::WRAPPER_FORMAT]);
Chris@0 1116 $this->drupalGet($path, $get_options);
Chris@0 1117 }
Chris@0 1118 $content = $this->content;
Chris@0 1119 $drupal_settings = $this->drupalSettings;
Chris@0 1120
Chris@0 1121 // Provide a default value for the wrapper envelope.
Chris@0 1122 $options['query'][MainContentViewSubscriber::WRAPPER_FORMAT] =
Chris@0 1123 isset($options['query'][MainContentViewSubscriber::WRAPPER_FORMAT]) ?
Chris@0 1124 $options['query'][MainContentViewSubscriber::WRAPPER_FORMAT] :
Chris@0 1125 'drupal_ajax';
Chris@0 1126
Chris@0 1127 // Get the Ajax settings bound to the triggering element.
Chris@0 1128 if (!isset($ajax_settings)) {
Chris@0 1129 if (is_array($triggering_element)) {
Chris@0 1130 $xpath = '//*[@name="' . key($triggering_element) . '" and @value="' . current($triggering_element) . '"]';
Chris@0 1131 }
Chris@0 1132 else {
Chris@0 1133 $xpath = '//*[@name="' . $triggering_element . '"]';
Chris@0 1134 }
Chris@0 1135 if (isset($form_html_id)) {
Chris@0 1136 $xpath = '//form[@id="' . $form_html_id . '"]' . $xpath;
Chris@0 1137 }
Chris@0 1138 $element = $this->xpath($xpath);
Chris@0 1139 $element_id = (string) $element[0]['id'];
Chris@0 1140 $ajax_settings = $drupal_settings['ajax'][$element_id];
Chris@0 1141 }
Chris@0 1142
Chris@0 1143 // Add extra information to the POST data as ajax.js does.
Chris@0 1144 $extra_post = [];
Chris@0 1145 if (isset($ajax_settings['submit'])) {
Chris@0 1146 foreach ($ajax_settings['submit'] as $key => $value) {
Chris@0 1147 $extra_post[$key] = $value;
Chris@0 1148 }
Chris@0 1149 }
Chris@0 1150 $extra_post[AjaxResponseSubscriber::AJAX_REQUEST_PARAMETER] = 1;
Chris@0 1151 $extra_post += $this->getAjaxPageStatePostData();
Chris@0 1152 // Now serialize all the $extra_post values, and prepend it with an '&'.
Chris@0 1153 $extra_post = '&' . $this->serializePostValues($extra_post);
Chris@0 1154
Chris@0 1155 // Unless a particular path is specified, use the one specified by the
Chris@0 1156 // Ajax settings.
Chris@0 1157 if (!isset($ajax_path)) {
Chris@0 1158 if (isset($ajax_settings['url'])) {
Chris@0 1159 // In order to allow to set for example the wrapper envelope query
Chris@0 1160 // parameter we need to get the system path again.
Chris@0 1161 $parsed_url = UrlHelper::parse($ajax_settings['url']);
Chris@0 1162 $options['query'] = $parsed_url['query'] + $options['query'];
Chris@0 1163 $options += ['fragment' => $parsed_url['fragment']];
Chris@0 1164
Chris@0 1165 // We know that $parsed_url['path'] is already with the base path
Chris@0 1166 // attached.
Chris@0 1167 $ajax_path = preg_replace(
Chris@0 1168 '/^' . preg_quote(base_path(), '/') . '/',
Chris@0 1169 '',
Chris@0 1170 $parsed_url['path']
Chris@0 1171 );
Chris@0 1172 }
Chris@0 1173 }
Chris@0 1174
Chris@0 1175 if (empty($ajax_path)) {
Chris@0 1176 throw new \Exception('No #ajax path specified.');
Chris@0 1177 }
Chris@0 1178
Chris@0 1179 $ajax_path = $this->container->get('unrouted_url_assembler')->assemble('base://' . $ajax_path, $options);
Chris@0 1180
Chris@0 1181 // Submit the POST request.
Chris@0 1182 $return = Json::decode($this->drupalPostForm(NULL, $edit, ['path' => $ajax_path, 'triggering_element' => $triggering_element], $options, $headers, $form_html_id, $extra_post));
Chris@0 1183 if ($this->assertAjaxHeader) {
Chris@0 1184 $this->assertIdentical($this->drupalGetHeader('X-Drupal-Ajax-Token'), '1', 'Ajax response header found.');
Chris@0 1185 }
Chris@0 1186
Chris@0 1187 // Change the page content by applying the returned commands.
Chris@0 1188 if (!empty($ajax_settings) && !empty($return)) {
Chris@0 1189 $this->drupalProcessAjaxResponse($content, $return, $ajax_settings, $drupal_settings);
Chris@0 1190 }
Chris@0 1191
Chris@0 1192 $verbose = 'AJAX POST request to: ' . $path;
Chris@0 1193 $verbose .= '<br />AJAX controller path: ' . $ajax_path;
Chris@0 1194 $verbose .= '<hr />Ending URL: ' . $this->getUrl();
Chris@0 1195 $verbose .= '<hr />' . $this->content;
Chris@0 1196
Chris@0 1197 $this->verbose($verbose);
Chris@0 1198
Chris@0 1199 return $return;
Chris@0 1200 }
Chris@0 1201
Chris@0 1202 /**
Chris@0 1203 * Processes an AJAX response into current content.
Chris@0 1204 *
Chris@0 1205 * This processes the AJAX response as ajax.js does. It uses the response's
Chris@0 1206 * JSON data, an array of commands, to update $this->content using equivalent
Chris@0 1207 * DOM manipulation as is used by ajax.js.
Chris@0 1208 * It does not apply custom AJAX commands though, because emulation is only
Chris@0 1209 * implemented for the AJAX commands that ship with Drupal core.
Chris@0 1210 *
Chris@0 1211 * @param string $content
Chris@0 1212 * The current HTML content.
Chris@0 1213 * @param array $ajax_response
Chris@0 1214 * An array of AJAX commands.
Chris@0 1215 * @param array $ajax_settings
Chris@0 1216 * An array of AJAX settings which will be used to process the response.
Chris@0 1217 * @param array $drupal_settings
Chris@0 1218 * An array of settings to update the value of drupalSettings for the
Chris@0 1219 * currently-loaded page.
Chris@0 1220 *
Chris@0 1221 * @see drupalPostAjaxForm()
Chris@0 1222 * @see ajax.js
Chris@0 1223 */
Chris@0 1224 protected function drupalProcessAjaxResponse($content, array $ajax_response, array $ajax_settings, array $drupal_settings) {
Chris@0 1225
Chris@0 1226 // ajax.js applies some defaults to the settings object, so do the same
Chris@0 1227 // for what's used by this function.
Chris@0 1228 $ajax_settings += [
Chris@0 1229 'method' => 'replaceWith',
Chris@0 1230 ];
Chris@0 1231 // DOM can load HTML soup. But, HTML soup can throw warnings, suppress
Chris@0 1232 // them.
Chris@0 1233 $dom = new \DOMDocument();
Chris@0 1234 @$dom->loadHTML($content);
Chris@0 1235 // XPath allows for finding wrapper nodes better than DOM does.
Chris@0 1236 $xpath = new \DOMXPath($dom);
Chris@0 1237 foreach ($ajax_response as $command) {
Chris@0 1238 // Error messages might be not commands.
Chris@0 1239 if (!is_array($command)) {
Chris@0 1240 continue;
Chris@0 1241 }
Chris@0 1242 switch ($command['command']) {
Chris@0 1243 case 'settings':
Chris@0 1244 $drupal_settings = NestedArray::mergeDeepArray([$drupal_settings, $command['settings']], TRUE);
Chris@0 1245 break;
Chris@0 1246
Chris@0 1247 case 'insert':
Chris@0 1248 $wrapperNode = NULL;
Chris@0 1249 // When a command doesn't specify a selector, use the
Chris@0 1250 // #ajax['wrapper'] which is always an HTML ID.
Chris@0 1251 if (!isset($command['selector'])) {
Chris@0 1252 $wrapperNode = $xpath->query('//*[@id="' . $ajax_settings['wrapper'] . '"]')->item(0);
Chris@0 1253 }
Chris@0 1254 // @todo Ajax commands can target any jQuery selector, but these are
Chris@0 1255 // hard to fully emulate with XPath. For now, just handle 'head'
Chris@0 1256 // and 'body', since these are used by the Ajax renderer.
Chris@0 1257 elseif (in_array($command['selector'], ['head', 'body'])) {
Chris@0 1258 $wrapperNode = $xpath->query('//' . $command['selector'])->item(0);
Chris@0 1259 }
Chris@0 1260 if ($wrapperNode) {
Chris@0 1261 // ajax.js adds an enclosing DIV to work around a Safari bug.
Chris@0 1262 $newDom = new \DOMDocument();
Chris@0 1263 // DOM can load HTML soup. But, HTML soup can throw warnings,
Chris@0 1264 // suppress them.
Chris@0 1265 @$newDom->loadHTML('<div>' . $command['data'] . '</div>');
Chris@0 1266 // Suppress warnings thrown when duplicate HTML IDs are encountered.
Chris@0 1267 // This probably means we are replacing an element with the same ID.
Chris@0 1268 $newNode = @$dom->importNode($newDom->documentElement->firstChild->firstChild, TRUE);
Chris@0 1269 $method = isset($command['method']) ? $command['method'] : $ajax_settings['method'];
Chris@0 1270 // The "method" is a jQuery DOM manipulation function. Emulate
Chris@0 1271 // each one using PHP's DOMNode API.
Chris@0 1272 switch ($method) {
Chris@0 1273 case 'replaceWith':
Chris@0 1274 $wrapperNode->parentNode->replaceChild($newNode, $wrapperNode);
Chris@0 1275 break;
Chris@0 1276 case 'append':
Chris@0 1277 $wrapperNode->appendChild($newNode);
Chris@0 1278 break;
Chris@0 1279 case 'prepend':
Chris@0 1280 // If no firstChild, insertBefore() falls back to
Chris@0 1281 // appendChild().
Chris@0 1282 $wrapperNode->insertBefore($newNode, $wrapperNode->firstChild);
Chris@0 1283 break;
Chris@0 1284 case 'before':
Chris@0 1285 $wrapperNode->parentNode->insertBefore($newNode, $wrapperNode);
Chris@0 1286 break;
Chris@0 1287 case 'after':
Chris@0 1288 // If no nextSibling, insertBefore() falls back to
Chris@0 1289 // appendChild().
Chris@0 1290 $wrapperNode->parentNode->insertBefore($newNode, $wrapperNode->nextSibling);
Chris@0 1291 break;
Chris@0 1292 case 'html':
Chris@0 1293 foreach ($wrapperNode->childNodes as $childNode) {
Chris@0 1294 $wrapperNode->removeChild($childNode);
Chris@0 1295 }
Chris@0 1296 $wrapperNode->appendChild($newNode);
Chris@0 1297 break;
Chris@0 1298 }
Chris@0 1299 }
Chris@0 1300 break;
Chris@0 1301
Chris@0 1302 // @todo Add suitable implementations for these commands in order to
Chris@0 1303 // have full test coverage of what ajax.js can do.
Chris@0 1304 case 'remove':
Chris@0 1305 break;
Chris@0 1306 case 'changed':
Chris@0 1307 break;
Chris@0 1308 case 'css':
Chris@0 1309 break;
Chris@0 1310 case 'data':
Chris@0 1311 break;
Chris@0 1312 case 'restripe':
Chris@0 1313 break;
Chris@0 1314 case 'add_css':
Chris@0 1315 break;
Chris@0 1316 case 'update_build_id':
Chris@0 1317 $buildId = $xpath->query('//input[@name="form_build_id" and @value="' . $command['old'] . '"]')->item(0);
Chris@0 1318 if ($buildId) {
Chris@0 1319 $buildId->setAttribute('value', $command['new']);
Chris@0 1320 }
Chris@0 1321 break;
Chris@0 1322 }
Chris@0 1323 }
Chris@0 1324 $content = $dom->saveHTML();
Chris@0 1325 $this->setRawContent($content);
Chris@0 1326 $this->setDrupalSettings($drupal_settings);
Chris@0 1327 }
Chris@0 1328
Chris@0 1329 /**
Chris@0 1330 * Perform a POST HTTP request.
Chris@0 1331 *
Chris@0 1332 * @param string|\Drupal\Core\Url $path
Chris@0 1333 * Drupal path or absolute path where the request should be POSTed.
Chris@0 1334 * @param string $accept
Chris@0 1335 * The value for the "Accept" header. Usually either 'application/json' or
Chris@0 1336 * 'application/vnd.drupal-ajax'.
Chris@0 1337 * @param array $post
Chris@0 1338 * The POST data. When making a 'application/vnd.drupal-ajax' request, the
Chris@0 1339 * Ajax page state data should be included. Use getAjaxPageStatePostData()
Chris@0 1340 * for that.
Chris@0 1341 * @param array $options
Chris@0 1342 * (optional) Options to be forwarded to the url generator. The 'absolute'
Chris@0 1343 * option will automatically be enabled.
Chris@0 1344 *
Chris@0 1345 * @return
Chris@0 1346 * The content returned from the call to curl_exec().
Chris@0 1347 *
Chris@0 1348 * @see WebTestBase::getAjaxPageStatePostData()
Chris@0 1349 * @see WebTestBase::curlExec()
Chris@0 1350 */
Chris@0 1351 protected function drupalPost($path, $accept, array $post, $options = []) {
Chris@0 1352 return $this->curlExec([
Chris@0 1353 CURLOPT_URL => $this->buildUrl($path, $options),
Chris@0 1354 CURLOPT_POST => TRUE,
Chris@0 1355 CURLOPT_POSTFIELDS => $this->serializePostValues($post),
Chris@0 1356 CURLOPT_HTTPHEADER => [
Chris@0 1357 'Accept: ' . $accept,
Chris@0 1358 'Content-Type: application/x-www-form-urlencoded',
Chris@0 1359 ],
Chris@0 1360 ]);
Chris@0 1361 }
Chris@0 1362
Chris@0 1363 /**
Chris@0 1364 * Performs a POST HTTP request with a specific format.
Chris@0 1365 *
Chris@0 1366 * @param string|\Drupal\Core\Url $path
Chris@0 1367 * Drupal path or absolute path where the request should be POSTed.
Chris@0 1368 * @param string $format
Chris@0 1369 * The request format.
Chris@0 1370 * @param array $post
Chris@0 1371 * The POST data. When making a 'application/vnd.drupal-ajax' request, the
Chris@0 1372 * Ajax page state data should be included. Use getAjaxPageStatePostData()
Chris@0 1373 * for that.
Chris@0 1374 * @param array $options
Chris@0 1375 * (optional) Options to be forwarded to the url generator. The 'absolute'
Chris@0 1376 * option will automatically be enabled.
Chris@0 1377 *
Chris@0 1378 * @return string
Chris@0 1379 * The content returned from the call to curl_exec().
Chris@0 1380 *
Chris@0 1381 * @see WebTestBase::drupalPost
Chris@0 1382 * @see WebTestBase::getAjaxPageStatePostData()
Chris@0 1383 * @see WebTestBase::curlExec()
Chris@0 1384 */
Chris@0 1385 protected function drupalPostWithFormat($path, $format, array $post, $options = []) {
Chris@0 1386 $options['query']['_format'] = $format;
Chris@0 1387 return $this->drupalPost($path, '', $post, $options);
Chris@0 1388 }
Chris@0 1389
Chris@0 1390 /**
Chris@0 1391 * Get the Ajax page state from drupalSettings and prepare it for POSTing.
Chris@0 1392 *
Chris@0 1393 * @return array
Chris@0 1394 * The Ajax page state POST data.
Chris@0 1395 */
Chris@0 1396 protected function getAjaxPageStatePostData() {
Chris@0 1397 $post = [];
Chris@0 1398 $drupal_settings = $this->drupalSettings;
Chris@0 1399 if (isset($drupal_settings['ajaxPageState']['theme'])) {
Chris@0 1400 $post['ajax_page_state[theme]'] = $drupal_settings['ajaxPageState']['theme'];
Chris@0 1401 }
Chris@0 1402 if (isset($drupal_settings['ajaxPageState']['theme_token'])) {
Chris@0 1403 $post['ajax_page_state[theme_token]'] = $drupal_settings['ajaxPageState']['theme_token'];
Chris@0 1404 }
Chris@0 1405 if (isset($drupal_settings['ajaxPageState']['libraries'])) {
Chris@0 1406 $post['ajax_page_state[libraries]'] = $drupal_settings['ajaxPageState']['libraries'];
Chris@0 1407 }
Chris@0 1408 return $post;
Chris@0 1409 }
Chris@0 1410
Chris@0 1411 /**
Chris@0 1412 * Serialize POST HTTP request values.
Chris@0 1413 *
Chris@0 1414 * Encode according to application/x-www-form-urlencoded. Both names and
Chris@0 1415 * values needs to be urlencoded, according to
Chris@0 1416 * http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.1
Chris@0 1417 *
Chris@0 1418 * @param array $post
Chris@0 1419 * The array of values to be POSTed.
Chris@0 1420 *
Chris@0 1421 * @return string
Chris@0 1422 * The serialized result.
Chris@0 1423 */
Chris@0 1424 protected function serializePostValues($post = []) {
Chris@0 1425 foreach ($post as $key => $value) {
Chris@0 1426 $post[$key] = urlencode($key) . '=' . urlencode($value);
Chris@0 1427 }
Chris@0 1428 return implode('&', $post);
Chris@0 1429 }
Chris@0 1430
Chris@0 1431 /**
Chris@0 1432 * Transforms a nested array into a flat array suitable for WebTestBase::drupalPostForm().
Chris@0 1433 *
Chris@0 1434 * @param array $values
Chris@0 1435 * A multi-dimensional form values array to convert.
Chris@0 1436 *
Chris@0 1437 * @return array
Chris@0 1438 * The flattened $edit array suitable for WebTestBase::drupalPostForm().
Chris@0 1439 */
Chris@0 1440 protected function translatePostValues(array $values) {
Chris@0 1441 $edit = [];
Chris@0 1442 // The easiest and most straightforward way to translate values suitable for
Chris@0 1443 // WebTestBase::drupalPostForm() is to actually build the POST data string
Chris@0 1444 // and convert the resulting key/value pairs back into a flat array.
Chris@0 1445 $query = http_build_query($values);
Chris@0 1446 foreach (explode('&', $query) as $item) {
Chris@0 1447 list($key, $value) = explode('=', $item);
Chris@0 1448 $edit[urldecode($key)] = urldecode($value);
Chris@0 1449 }
Chris@0 1450 return $edit;
Chris@0 1451 }
Chris@0 1452
Chris@0 1453 /**
Chris@0 1454 * Checks for meta refresh tag and if found call drupalGet() recursively.
Chris@0 1455 *
Chris@0 1456 * This function looks for the http-equiv attribute to be set to "Refresh" and
Chris@0 1457 * is case-sensitive.
Chris@0 1458 *
Chris@0 1459 * @return
Chris@0 1460 * Either the new page content or FALSE.
Chris@0 1461 */
Chris@0 1462 protected function checkForMetaRefresh() {
Chris@0 1463 if (strpos($this->getRawContent(), '<meta ') && $this->parse() && (!isset($this->maximumMetaRefreshCount) || $this->metaRefreshCount < $this->maximumMetaRefreshCount)) {
Chris@0 1464 $refresh = $this->xpath('//meta[@http-equiv="Refresh"]');
Chris@0 1465 if (!empty($refresh)) {
Chris@0 1466 // Parse the content attribute of the meta tag for the format:
Chris@0 1467 // "[delay]: URL=[page_to_redirect_to]".
Chris@0 1468 if (preg_match('/\d+;\s*URL=(?<url>.*)/i', $refresh[0]['content'], $match)) {
Chris@0 1469 $this->metaRefreshCount++;
Chris@0 1470 return $this->drupalGet($this->getAbsoluteUrl(Html::decodeEntities($match['url'])));
Chris@0 1471 }
Chris@0 1472 }
Chris@0 1473 }
Chris@0 1474 return FALSE;
Chris@0 1475 }
Chris@0 1476
Chris@0 1477 /**
Chris@0 1478 * Retrieves only the headers for a Drupal path or an absolute path.
Chris@0 1479 *
Chris@0 1480 * @param $path
Chris@0 1481 * Drupal path or URL to load into internal browser
Chris@0 1482 * @param $options
Chris@0 1483 * Options to be forwarded to the url generator.
Chris@0 1484 * @param $headers
Chris@0 1485 * An array containing additional HTTP request headers, each formatted as
Chris@0 1486 * "name: value".
Chris@0 1487 *
Chris@0 1488 * @return
Chris@0 1489 * The retrieved headers, also available as $this->getRawContent()
Chris@0 1490 */
Chris@0 1491 protected function drupalHead($path, array $options = [], array $headers = []) {
Chris@0 1492 $options['absolute'] = TRUE;
Chris@0 1493 $url = $this->buildUrl($path, $options);
Chris@0 1494 $out = $this->curlExec([CURLOPT_NOBODY => TRUE, CURLOPT_URL => $url, CURLOPT_HTTPHEADER => $headers]);
Chris@0 1495 // Ensure that any changes to variables in the other thread are picked up.
Chris@0 1496 $this->refreshVariables();
Chris@0 1497
Chris@0 1498 if ($this->dumpHeaders) {
Chris@0 1499 $this->verbose('GET request to: ' . $path .
Chris@0 1500 '<hr />Ending URL: ' . $this->getUrl() .
Chris@0 1501 '<hr />Headers: <pre>' . Html::escape(var_export(array_map('trim', $this->headers), TRUE)) . '</pre>');
Chris@0 1502 }
Chris@0 1503
Chris@0 1504 return $out;
Chris@0 1505 }
Chris@0 1506
Chris@0 1507 /**
Chris@0 1508 * Handles form input related to drupalPostForm().
Chris@0 1509 *
Chris@0 1510 * Ensure that the specified fields exist and attempt to create POST data in
Chris@0 1511 * the correct manner for the particular field type.
Chris@0 1512 *
Chris@0 1513 * @param $post
Chris@0 1514 * Reference to array of post values.
Chris@0 1515 * @param $edit
Chris@0 1516 * Reference to array of edit values to be checked against the form.
Chris@0 1517 * @param $submit
Chris@0 1518 * Form submit button value.
Chris@0 1519 * @param $form
Chris@0 1520 * Array of form elements.
Chris@0 1521 *
Chris@0 1522 * @return
Chris@0 1523 * Submit value matches a valid submit input in the form.
Chris@0 1524 */
Chris@0 1525 protected function handleForm(&$post, &$edit, &$upload, $submit, $form) {
Chris@0 1526 // Retrieve the form elements.
Chris@0 1527 $elements = $form->xpath('.//input[not(@disabled)]|.//textarea[not(@disabled)]|.//select[not(@disabled)]');
Chris@0 1528 $submit_matches = FALSE;
Chris@0 1529 foreach ($elements as $element) {
Chris@0 1530 // SimpleXML objects need string casting all the time.
Chris@0 1531 $name = (string) $element['name'];
Chris@0 1532 // This can either be the type of <input> or the name of the tag itself
Chris@0 1533 // for <select> or <textarea>.
Chris@0 1534 $type = isset($element['type']) ? (string) $element['type'] : $element->getName();
Chris@0 1535 $value = isset($element['value']) ? (string) $element['value'] : '';
Chris@0 1536 $done = FALSE;
Chris@0 1537 if (isset($edit[$name])) {
Chris@0 1538 switch ($type) {
Chris@0 1539 case 'text':
Chris@0 1540 case 'tel':
Chris@0 1541 case 'textarea':
Chris@0 1542 case 'url':
Chris@0 1543 case 'number':
Chris@0 1544 case 'range':
Chris@0 1545 case 'color':
Chris@0 1546 case 'hidden':
Chris@0 1547 case 'password':
Chris@0 1548 case 'email':
Chris@0 1549 case 'search':
Chris@0 1550 case 'date':
Chris@0 1551 case 'time':
Chris@0 1552 case 'datetime':
Chris@0 1553 case 'datetime-local';
Chris@0 1554 $post[$name] = $edit[$name];
Chris@0 1555 unset($edit[$name]);
Chris@0 1556 break;
Chris@0 1557 case 'radio':
Chris@0 1558 if ($edit[$name] == $value) {
Chris@0 1559 $post[$name] = $edit[$name];
Chris@0 1560 unset($edit[$name]);
Chris@0 1561 }
Chris@0 1562 break;
Chris@0 1563 case 'checkbox':
Chris@0 1564 // To prevent checkbox from being checked.pass in a FALSE,
Chris@0 1565 // otherwise the checkbox will be set to its value regardless
Chris@0 1566 // of $edit.
Chris@0 1567 if ($edit[$name] === FALSE) {
Chris@0 1568 unset($edit[$name]);
Chris@0 1569 continue 2;
Chris@0 1570 }
Chris@0 1571 else {
Chris@0 1572 unset($edit[$name]);
Chris@0 1573 $post[$name] = $value;
Chris@0 1574 }
Chris@0 1575 break;
Chris@0 1576 case 'select':
Chris@0 1577 $new_value = $edit[$name];
Chris@0 1578 $options = $this->getAllOptions($element);
Chris@0 1579 if (is_array($new_value)) {
Chris@0 1580 // Multiple select box.
Chris@0 1581 if (!empty($new_value)) {
Chris@0 1582 $index = 0;
Chris@0 1583 $key = preg_replace('/\[\]$/', '', $name);
Chris@0 1584 foreach ($options as $option) {
Chris@0 1585 $option_value = (string) $option['value'];
Chris@0 1586 if (in_array($option_value, $new_value)) {
Chris@0 1587 $post[$key . '[' . $index++ . ']'] = $option_value;
Chris@0 1588 $done = TRUE;
Chris@0 1589 unset($edit[$name]);
Chris@0 1590 }
Chris@0 1591 }
Chris@0 1592 }
Chris@0 1593 else {
Chris@0 1594 // No options selected: do not include any POST data for the
Chris@0 1595 // element.
Chris@0 1596 $done = TRUE;
Chris@0 1597 unset($edit[$name]);
Chris@0 1598 }
Chris@0 1599 }
Chris@0 1600 else {
Chris@0 1601 // Single select box.
Chris@0 1602 foreach ($options as $option) {
Chris@0 1603 if ($new_value == $option['value']) {
Chris@0 1604 $post[$name] = $new_value;
Chris@0 1605 unset($edit[$name]);
Chris@0 1606 $done = TRUE;
Chris@0 1607 break;
Chris@0 1608 }
Chris@0 1609 }
Chris@0 1610 }
Chris@0 1611 break;
Chris@0 1612 case 'file':
Chris@0 1613 $upload[$name] = $edit[$name];
Chris@0 1614 unset($edit[$name]);
Chris@0 1615 break;
Chris@0 1616 }
Chris@0 1617 }
Chris@0 1618 if (!isset($post[$name]) && !$done) {
Chris@0 1619 switch ($type) {
Chris@0 1620 case 'textarea':
Chris@0 1621 $post[$name] = (string) $element;
Chris@0 1622 break;
Chris@0 1623 case 'select':
Chris@0 1624 $single = empty($element['multiple']);
Chris@0 1625 $first = TRUE;
Chris@0 1626 $index = 0;
Chris@0 1627 $key = preg_replace('/\[\]$/', '', $name);
Chris@0 1628 $options = $this->getAllOptions($element);
Chris@0 1629 foreach ($options as $option) {
Chris@0 1630 // For single select, we load the first option, if there is a
Chris@0 1631 // selected option that will overwrite it later.
Chris@0 1632 if ($option['selected'] || ($first && $single)) {
Chris@0 1633 $first = FALSE;
Chris@0 1634 if ($single) {
Chris@0 1635 $post[$name] = (string) $option['value'];
Chris@0 1636 }
Chris@0 1637 else {
Chris@0 1638 $post[$key . '[' . $index++ . ']'] = (string) $option['value'];
Chris@0 1639 }
Chris@0 1640 }
Chris@0 1641 }
Chris@0 1642 break;
Chris@0 1643 case 'file':
Chris@0 1644 break;
Chris@0 1645 case 'submit':
Chris@0 1646 case 'image':
Chris@0 1647 if (isset($submit) && $submit == $value) {
Chris@0 1648 $post[$name] = $value;
Chris@0 1649 $submit_matches = TRUE;
Chris@0 1650 }
Chris@0 1651 break;
Chris@0 1652 case 'radio':
Chris@0 1653 case 'checkbox':
Chris@0 1654 if (!isset($element['checked'])) {
Chris@0 1655 break;
Chris@0 1656 }
Chris@0 1657 // Deliberate no break.
Chris@0 1658 default:
Chris@0 1659 $post[$name] = $value;
Chris@0 1660 }
Chris@0 1661 }
Chris@0 1662 }
Chris@0 1663 // An empty name means the value is not sent.
Chris@0 1664 unset($post['']);
Chris@0 1665 return $submit_matches;
Chris@0 1666 }
Chris@0 1667
Chris@0 1668 /**
Chris@0 1669 * Follows a link by complete name.
Chris@0 1670 *
Chris@0 1671 * Will click the first link found with this link text by default, or a later
Chris@0 1672 * one if an index is given. Match is case sensitive with normalized space.
Chris@0 1673 * The label is translated label.
Chris@0 1674 *
Chris@0 1675 * If the link is discovered and clicked, the test passes. Fail otherwise.
Chris@0 1676 *
Chris@0 1677 * @param string|\Drupal\Component\Render\MarkupInterface $label
Chris@0 1678 * Text between the anchor tags.
Chris@0 1679 * @param int $index
Chris@0 1680 * Link position counting from zero.
Chris@0 1681 *
Chris@0 1682 * @return string|bool
Chris@0 1683 * Page contents on success, or FALSE on failure.
Chris@0 1684 */
Chris@0 1685 protected function clickLink($label, $index = 0) {
Chris@0 1686 return $this->clickLinkHelper($label, $index, '//a[normalize-space()=:label]');
Chris@0 1687 }
Chris@0 1688
Chris@0 1689 /**
Chris@0 1690 * Follows a link by partial name.
Chris@0 1691 *
Chris@0 1692 * If the link is discovered and clicked, the test passes. Fail otherwise.
Chris@0 1693 *
Chris@0 1694 * @param string|\Drupal\Component\Render\MarkupInterface $label
Chris@0 1695 * Text between the anchor tags, uses starts-with().
Chris@0 1696 * @param int $index
Chris@0 1697 * Link position counting from zero.
Chris@0 1698 *
Chris@0 1699 * @return string|bool
Chris@0 1700 * Page contents on success, or FALSE on failure.
Chris@0 1701 *
Chris@0 1702 * @see ::clickLink()
Chris@0 1703 */
Chris@0 1704 protected function clickLinkPartialName($label, $index = 0) {
Chris@0 1705 return $this->clickLinkHelper($label, $index, '//a[starts-with(normalize-space(), :label)]');
Chris@0 1706 }
Chris@0 1707
Chris@0 1708 /**
Chris@0 1709 * Provides a helper for ::clickLink() and ::clickLinkPartialName().
Chris@0 1710 *
Chris@0 1711 * @param string|\Drupal\Component\Render\MarkupInterface $label
Chris@0 1712 * Text between the anchor tags, uses starts-with().
Chris@0 1713 * @param int $index
Chris@0 1714 * Link position counting from zero.
Chris@0 1715 * @param string $pattern
Chris@0 1716 * A pattern to use for the XPath.
Chris@0 1717 *
Chris@0 1718 * @return bool|string
Chris@0 1719 * Page contents on success, or FALSE on failure.
Chris@0 1720 */
Chris@0 1721 protected function clickLinkHelper($label, $index, $pattern) {
Chris@0 1722 // Cast MarkupInterface objects to string.
Chris@0 1723 $label = (string) $label;
Chris@0 1724 $url_before = $this->getUrl();
Chris@0 1725 $urls = $this->xpath($pattern, [':label' => $label]);
Chris@0 1726 if (isset($urls[$index])) {
Chris@0 1727 $url_target = $this->getAbsoluteUrl($urls[$index]['href']);
Chris@0 1728 $this->pass(SafeMarkup::format('Clicked link %label (@url_target) from @url_before', ['%label' => $label, '@url_target' => $url_target, '@url_before' => $url_before]), 'Browser');
Chris@0 1729 return $this->drupalGet($url_target);
Chris@0 1730 }
Chris@0 1731 $this->fail(SafeMarkup::format('Link %label does not exist on @url_before', ['%label' => $label, '@url_before' => $url_before]), 'Browser');
Chris@0 1732 return FALSE;
Chris@0 1733 }
Chris@0 1734
Chris@0 1735 /**
Chris@0 1736 * Takes a path and returns an absolute path.
Chris@0 1737 *
Chris@0 1738 * This method is implemented in the way that browsers work, see
Chris@0 1739 * https://url.spec.whatwg.org/#relative-state for more information about the
Chris@0 1740 * possible cases.
Chris@0 1741 *
Chris@0 1742 * @param string $path
Chris@0 1743 * A path from the internal browser content.
Chris@0 1744 *
Chris@0 1745 * @return string
Chris@0 1746 * The $path with $base_url prepended, if necessary.
Chris@0 1747 */
Chris@0 1748 protected function getAbsoluteUrl($path) {
Chris@0 1749 global $base_url, $base_path;
Chris@0 1750
Chris@0 1751 $parts = parse_url($path);
Chris@0 1752
Chris@0 1753 // In case the $path has a host, it is already an absolute URL and we are
Chris@0 1754 // done.
Chris@0 1755 if (!empty($parts['host'])) {
Chris@0 1756 return $path;
Chris@0 1757 }
Chris@0 1758
Chris@0 1759 // In case the $path contains just a query, we turn it into an absolute URL
Chris@0 1760 // with the same scheme, host and path, see
Chris@0 1761 // https://url.spec.whatwg.org/#relative-state.
Chris@0 1762 if (array_keys($parts) === ['query']) {
Chris@0 1763 $current_uri = new Uri($this->getUrl());
Chris@0 1764 return (string) $current_uri->withQuery($parts['query']);
Chris@0 1765 }
Chris@0 1766
Chris@0 1767 if (empty($parts['host'])) {
Chris@0 1768 // Ensure that we have a string (and no xpath object).
Chris@0 1769 $path = (string) $path;
Chris@0 1770 // Strip $base_path, if existent.
Chris@0 1771 $length = strlen($base_path);
Chris@0 1772 if (substr($path, 0, $length) === $base_path) {
Chris@0 1773 $path = substr($path, $length);
Chris@0 1774 }
Chris@0 1775 // Ensure that we have an absolute path.
Chris@0 1776 if (empty($path) || $path[0] !== '/') {
Chris@0 1777 $path = '/' . $path;
Chris@0 1778 }
Chris@0 1779 // Finally, prepend the $base_url.
Chris@0 1780 $path = $base_url . $path;
Chris@0 1781 }
Chris@0 1782 return $path;
Chris@0 1783 }
Chris@0 1784
Chris@0 1785 /**
Chris@0 1786 * Gets the HTTP response headers of the requested page.
Chris@0 1787 *
Chris@0 1788 * Normally we are only interested in the headers returned by the last
Chris@0 1789 * request. However, if a page is redirected or HTTP authentication is in use,
Chris@0 1790 * multiple requests will be required to retrieve the page. Headers from all
Chris@0 1791 * requests may be requested by passing TRUE to this function.
Chris@0 1792 *
Chris@0 1793 * @param $all_requests
Chris@0 1794 * Boolean value specifying whether to return headers from all requests
Chris@0 1795 * instead of just the last request. Defaults to FALSE.
Chris@0 1796 *
Chris@0 1797 * @return
Chris@0 1798 * A name/value array if headers from only the last request are requested.
Chris@0 1799 * If headers from all requests are requested, an array of name/value
Chris@0 1800 * arrays, one for each request.
Chris@0 1801 *
Chris@0 1802 * The pseudonym ":status" is used for the HTTP status line.
Chris@0 1803 *
Chris@0 1804 * Values for duplicate headers are stored as a single comma-separated list.
Chris@0 1805 */
Chris@0 1806 protected function drupalGetHeaders($all_requests = FALSE) {
Chris@0 1807 $request = 0;
Chris@0 1808 $headers = [$request => []];
Chris@0 1809 foreach ($this->headers as $header) {
Chris@0 1810 $header = trim($header);
Chris@0 1811 if ($header === '') {
Chris@0 1812 $request++;
Chris@0 1813 }
Chris@0 1814 else {
Chris@0 1815 if (strpos($header, 'HTTP/') === 0) {
Chris@0 1816 $name = ':status';
Chris@0 1817 $value = $header;
Chris@0 1818 }
Chris@0 1819 else {
Chris@0 1820 list($name, $value) = explode(':', $header, 2);
Chris@0 1821 $name = strtolower($name);
Chris@0 1822 }
Chris@0 1823 if (isset($headers[$request][$name])) {
Chris@0 1824 $headers[$request][$name] .= ',' . trim($value);
Chris@0 1825 }
Chris@0 1826 else {
Chris@0 1827 $headers[$request][$name] = trim($value);
Chris@0 1828 }
Chris@0 1829 }
Chris@0 1830 }
Chris@0 1831 if (!$all_requests) {
Chris@0 1832 $headers = array_pop($headers);
Chris@0 1833 }
Chris@0 1834 return $headers;
Chris@0 1835 }
Chris@0 1836
Chris@0 1837 /**
Chris@0 1838 * Gets the value of an HTTP response header.
Chris@0 1839 *
Chris@0 1840 * If multiple requests were required to retrieve the page, only the headers
Chris@0 1841 * from the last request will be checked by default. However, if TRUE is
Chris@0 1842 * passed as the second argument, all requests will be processed from last to
Chris@0 1843 * first until the header is found.
Chris@0 1844 *
Chris@0 1845 * @param $name
Chris@0 1846 * The name of the header to retrieve. Names are case-insensitive (see RFC
Chris@0 1847 * 2616 section 4.2).
Chris@0 1848 * @param $all_requests
Chris@0 1849 * Boolean value specifying whether to check all requests if the header is
Chris@0 1850 * not found in the last request. Defaults to FALSE.
Chris@0 1851 *
Chris@0 1852 * @return
Chris@0 1853 * The HTTP header value or FALSE if not found.
Chris@0 1854 */
Chris@0 1855 protected function drupalGetHeader($name, $all_requests = FALSE) {
Chris@0 1856 $name = strtolower($name);
Chris@0 1857 $header = FALSE;
Chris@0 1858 if ($all_requests) {
Chris@0 1859 foreach (array_reverse($this->drupalGetHeaders(TRUE)) as $headers) {
Chris@0 1860 if (isset($headers[$name])) {
Chris@0 1861 $header = $headers[$name];
Chris@0 1862 break;
Chris@0 1863 }
Chris@0 1864 }
Chris@0 1865 }
Chris@0 1866 else {
Chris@0 1867 $headers = $this->drupalGetHeaders();
Chris@0 1868 if (isset($headers[$name])) {
Chris@0 1869 $header = $headers[$name];
Chris@0 1870 }
Chris@0 1871 }
Chris@0 1872 return $header;
Chris@0 1873 }
Chris@0 1874
Chris@0 1875 /**
Chris@0 1876 * Check if a HTTP response header exists and has the expected value.
Chris@0 1877 *
Chris@0 1878 * @param string $header
Chris@0 1879 * The header key, example: Content-Type
Chris@0 1880 * @param string $value
Chris@0 1881 * The header value.
Chris@0 1882 * @param string $message
Chris@0 1883 * (optional) A message to display with the assertion.
Chris@0 1884 * @param string $group
Chris@0 1885 * (optional) The group this message is in, which is displayed in a column
Chris@0 1886 * in test output. Use 'Debug' to indicate this is debugging output. Do not
Chris@0 1887 * translate this string. Defaults to 'Other'; most tests do not override
Chris@0 1888 * this default.
Chris@0 1889 *
Chris@0 1890 * @return bool
Chris@0 1891 * TRUE if the assertion succeeded, FALSE otherwise.
Chris@0 1892 */
Chris@0 1893 protected function assertHeader($header, $value, $message = '', $group = 'Browser') {
Chris@0 1894 $header_value = $this->drupalGetHeader($header);
Chris@0 1895 return $this->assertTrue($header_value == $value, $message ? $message : 'HTTP response header ' . $header . ' with value ' . $value . ' found, actual value: ' . $header_value, $group);
Chris@0 1896 }
Chris@0 1897
Chris@0 1898 /**
Chris@0 1899 * Passes if the internal browser's URL matches the given path.
Chris@0 1900 *
Chris@0 1901 * @param \Drupal\Core\Url|string $path
Chris@0 1902 * The expected system path or URL.
Chris@0 1903 * @param $options
Chris@0 1904 * (optional) Any additional options to pass for $path to the url generator.
Chris@0 1905 * @param $message
Chris@0 1906 * (optional) A message to display with the assertion. Do not translate
Chris@0 1907 * messages: use \Drupal\Component\Utility\SafeMarkup::format() to embed
Chris@0 1908 * variables in the message text, not t(). If left blank, a default message
Chris@0 1909 * will be displayed.
Chris@0 1910 * @param $group
Chris@0 1911 * (optional) The group this message is in, which is displayed in a column
Chris@0 1912 * in test output. Use 'Debug' to indicate this is debugging output. Do not
Chris@0 1913 * translate this string. Defaults to 'Other'; most tests do not override
Chris@0 1914 * this default.
Chris@0 1915 *
Chris@0 1916 * @return
Chris@0 1917 * TRUE on pass, FALSE on fail.
Chris@0 1918 */
Chris@0 1919 protected function assertUrl($path, array $options = [], $message = '', $group = 'Other') {
Chris@0 1920 if ($path instanceof Url) {
Chris@0 1921 $url_obj = $path;
Chris@0 1922 }
Chris@0 1923 elseif (UrlHelper::isExternal($path)) {
Chris@0 1924 $url_obj = Url::fromUri($path, $options);
Chris@0 1925 }
Chris@0 1926 else {
Chris@0 1927 $uri = $path === '<front>' ? 'base:/' : 'base:/' . $path;
Chris@0 1928 // This is needed for language prefixing.
Chris@0 1929 $options['path_processing'] = TRUE;
Chris@0 1930 $url_obj = Url::fromUri($uri, $options);
Chris@0 1931 }
Chris@0 1932 $url = $url_obj->setAbsolute()->toString();
Chris@0 1933 if (!$message) {
Chris@0 1934 $message = SafeMarkup::format('Expected @url matches current URL (@current_url).', [
Chris@0 1935 '@url' => var_export($url, TRUE),
Chris@0 1936 '@current_url' => $this->getUrl(),
Chris@0 1937 ]);
Chris@0 1938 }
Chris@0 1939 // Paths in query strings can be encoded or decoded with no functional
Chris@0 1940 // difference, decode them for comparison purposes.
Chris@0 1941 $actual_url = urldecode($this->getUrl());
Chris@0 1942 $expected_url = urldecode($url);
Chris@0 1943 return $this->assertEqual($actual_url, $expected_url, $message, $group);
Chris@0 1944 }
Chris@0 1945
Chris@0 1946 /**
Chris@0 1947 * Asserts the page responds with the specified response code.
Chris@0 1948 *
Chris@0 1949 * @param $code
Chris@0 1950 * Response code. For example 200 is a successful page request. For a list
Chris@0 1951 * of all codes see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html.
Chris@0 1952 * @param $message
Chris@0 1953 * (optional) A message to display with the assertion. Do not translate
Chris@0 1954 * messages: use \Drupal\Component\Utility\SafeMarkup::format() to embed
Chris@0 1955 * variables in the message text, not t(). If left blank, a default message
Chris@0 1956 * will be displayed.
Chris@0 1957 * @param $group
Chris@0 1958 * (optional) The group this message is in, which is displayed in a column
Chris@0 1959 * in test output. Use 'Debug' to indicate this is debugging output. Do not
Chris@0 1960 * translate this string. Defaults to 'Browser'; most tests do not override
Chris@0 1961 * this default.
Chris@0 1962 *
Chris@0 1963 * @return
Chris@0 1964 * Assertion result.
Chris@0 1965 */
Chris@0 1966 protected function assertResponse($code, $message = '', $group = 'Browser') {
Chris@0 1967 $curl_code = curl_getinfo($this->curlHandle, CURLINFO_HTTP_CODE);
Chris@0 1968 $match = is_array($code) ? in_array($curl_code, $code) : $curl_code == $code;
Chris@0 1969 return $this->assertTrue($match, $message ? $message : SafeMarkup::format('HTTP response expected @code, actual @curl_code', ['@code' => $code, '@curl_code' => $curl_code]), $group);
Chris@0 1970 }
Chris@0 1971
Chris@0 1972 /**
Chris@0 1973 * Asserts the page did not return the specified response code.
Chris@0 1974 *
Chris@0 1975 * @param $code
Chris@0 1976 * Response code. For example 200 is a successful page request. For a list
Chris@0 1977 * of all codes see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html.
Chris@0 1978 * @param $message
Chris@0 1979 * (optional) A message to display with the assertion. Do not translate
Chris@0 1980 * messages: use \Drupal\Component\Utility\SafeMarkup::format() to embed
Chris@0 1981 * variables in the message text, not t(). If left blank, a default message
Chris@0 1982 * will be displayed.
Chris@0 1983 * @param $group
Chris@0 1984 * (optional) The group this message is in, which is displayed in a column
Chris@0 1985 * in test output. Use 'Debug' to indicate this is debugging output. Do not
Chris@0 1986 * translate this string. Defaults to 'Browser'; most tests do not override
Chris@0 1987 * this default.
Chris@0 1988 *
Chris@0 1989 * @return
Chris@0 1990 * Assertion result.
Chris@0 1991 */
Chris@0 1992 protected function assertNoResponse($code, $message = '', $group = 'Browser') {
Chris@0 1993 $curl_code = curl_getinfo($this->curlHandle, CURLINFO_HTTP_CODE);
Chris@0 1994 $match = is_array($code) ? in_array($curl_code, $code) : $curl_code == $code;
Chris@0 1995 return $this->assertFalse($match, $message ? $message : SafeMarkup::format('HTTP response not expected @code, actual @curl_code', ['@code' => $code, '@curl_code' => $curl_code]), $group);
Chris@0 1996 }
Chris@0 1997
Chris@0 1998 /**
Chris@0 1999 * Builds an a absolute URL from a system path or a URL object.
Chris@0 2000 *
Chris@0 2001 * @param string|\Drupal\Core\Url $path
Chris@0 2002 * A system path or a URL.
Chris@0 2003 * @param array $options
Chris@0 2004 * Options to be passed to Url::fromUri().
Chris@0 2005 *
Chris@0 2006 * @return string
Chris@0 2007 * An absolute URL string.
Chris@0 2008 */
Chris@0 2009 protected function buildUrl($path, array $options = []) {
Chris@0 2010 if ($path instanceof Url) {
Chris@0 2011 $url_options = $path->getOptions();
Chris@0 2012 $options = $url_options + $options;
Chris@0 2013 $path->setOptions($options);
Chris@0 2014 return $path->setAbsolute()->toString(TRUE)->getGeneratedUrl();
Chris@0 2015 }
Chris@0 2016 // The URL generator service is not necessarily available yet; e.g., in
Chris@0 2017 // interactive installer tests.
Chris@0 2018 elseif ($this->container->has('url_generator')) {
Chris@0 2019 $force_internal = isset($options['external']) && $options['external'] == FALSE;
Chris@0 2020 if (!$force_internal && UrlHelper::isExternal($path)) {
Chris@0 2021 return Url::fromUri($path, $options)->toString();
Chris@0 2022 }
Chris@0 2023 else {
Chris@0 2024 $uri = $path === '<front>' ? 'base:/' : 'base:/' . $path;
Chris@0 2025 // Path processing is needed for language prefixing. Skip it when a
Chris@0 2026 // path that may look like an external URL is being used as internal.
Chris@0 2027 $options['path_processing'] = !$force_internal;
Chris@0 2028 return Url::fromUri($uri, $options)
Chris@0 2029 ->setAbsolute()
Chris@0 2030 ->toString();
Chris@0 2031 }
Chris@0 2032 }
Chris@0 2033 else {
Chris@0 2034 return $this->getAbsoluteUrl($path);
Chris@0 2035 }
Chris@0 2036 }
Chris@0 2037
Chris@0 2038 /**
Chris@0 2039 * Asserts whether an expected cache tag was present in the last response.
Chris@0 2040 *
Chris@0 2041 * @param string $expected_cache_tag
Chris@0 2042 * The expected cache tag.
Chris@0 2043 */
Chris@0 2044 protected function assertCacheTag($expected_cache_tag) {
Chris@0 2045 $cache_tags = explode(' ', $this->drupalGetHeader('X-Drupal-Cache-Tags'));
Chris@0 2046 $this->assertTrue(in_array($expected_cache_tag, $cache_tags), "'" . $expected_cache_tag . "' is present in the X-Drupal-Cache-Tags header.");
Chris@0 2047 }
Chris@0 2048
Chris@0 2049 /**
Chris@0 2050 * Asserts whether an expected cache tag was absent in the last response.
Chris@0 2051 *
Chris@0 2052 * @param string $cache_tag
Chris@0 2053 * The cache tag to check.
Chris@0 2054 */
Chris@0 2055 protected function assertNoCacheTag($cache_tag) {
Chris@0 2056 $cache_tags = explode(' ', $this->drupalGetHeader('X-Drupal-Cache-Tags'));
Chris@0 2057 $this->assertFalse(in_array($cache_tag, $cache_tags), "'" . $cache_tag . "' is absent in the X-Drupal-Cache-Tags header.");
Chris@0 2058 }
Chris@0 2059
Chris@0 2060 /**
Chris@0 2061 * Enables/disables the cacheability headers.
Chris@0 2062 *
Chris@0 2063 * Sets the http.response.debug_cacheability_headers container parameter.
Chris@0 2064 *
Chris@0 2065 * @param bool $value
Chris@0 2066 * (optional) Whether the debugging cacheability headers should be sent.
Chris@0 2067 */
Chris@0 2068 protected function setHttpResponseDebugCacheabilityHeaders($value = TRUE) {
Chris@0 2069 $this->setContainerParameter('http.response.debug_cacheability_headers', $value);
Chris@0 2070 $this->rebuildContainer();
Chris@0 2071 $this->resetAll();
Chris@0 2072 }
Chris@0 2073
Chris@0 2074 }