annotate core/tests/Drupal/Tests/BrowserTestBase.php @ 12:7a779792577d

Update Drupal core to v8.4.5 (via Composer)
author Chris Cannam
date Fri, 23 Feb 2018 15:52:07 +0000
parents 4c8ae668cc8c
children 1fec387a4317
rev   line source
Chris@0 1 <?php
Chris@0 2
Chris@0 3 namespace Drupal\Tests;
Chris@0 4
Chris@0 5 use Behat\Mink\Driver\GoutteDriver;
Chris@0 6 use Behat\Mink\Element\Element;
Chris@0 7 use Behat\Mink\Mink;
Chris@0 8 use Behat\Mink\Selector\SelectorsHandler;
Chris@0 9 use Behat\Mink\Session;
Chris@0 10 use Drupal\Component\Render\FormattableMarkup;
Chris@0 11 use Drupal\Component\Serialization\Json;
Chris@0 12 use Drupal\Component\Utility\Html;
Chris@0 13 use Drupal\Component\Utility\UrlHelper;
Chris@0 14 use Drupal\Core\Database\Database;
Chris@0 15 use Drupal\Core\Session\AccountInterface;
Chris@0 16 use Drupal\Core\Session\AnonymousUserSession;
Chris@0 17 use Drupal\Core\Test\FunctionalTestSetupTrait;
Chris@0 18 use Drupal\Core\Test\TestSetupTrait;
Chris@0 19 use Drupal\Core\Url;
Chris@0 20 use Drupal\Core\Utility\Error;
Chris@0 21 use Drupal\FunctionalTests\AssertLegacyTrait;
Chris@0 22 use Drupal\Tests\block\Traits\BlockCreationTrait;
Chris@0 23 use Drupal\Tests\node\Traits\ContentTypeCreationTrait;
Chris@0 24 use Drupal\Tests\node\Traits\NodeCreationTrait;
Chris@0 25 use Drupal\Tests\user\Traits\UserCreationTrait;
Chris@0 26 use PHPUnit\Framework\TestCase;
Chris@0 27 use Psr\Http\Message\RequestInterface;
Chris@0 28 use Psr\Http\Message\ResponseInterface;
Chris@0 29 use Symfony\Component\CssSelector\CssSelectorConverter;
Chris@0 30
Chris@0 31 /**
Chris@0 32 * Provides a test case for functional Drupal tests.
Chris@0 33 *
Chris@0 34 * Tests extending BrowserTestBase must exist in the
Chris@0 35 * Drupal\Tests\yourmodule\Functional namespace and live in the
Chris@0 36 * modules/yourmodule/tests/src/Functional directory.
Chris@0 37 *
Chris@12 38 * Tests extending this base class should only translate text when testing
Chris@12 39 * translation functionality. For example, avoid wrapping test text with t()
Chris@12 40 * or TranslatableMarkup().
Chris@12 41 *
Chris@0 42 * @ingroup testing
Chris@0 43 */
Chris@0 44 abstract class BrowserTestBase extends TestCase {
Chris@0 45
Chris@0 46 use FunctionalTestSetupTrait;
Chris@0 47 use TestSetupTrait;
Chris@0 48 use AssertHelperTrait;
Chris@0 49 use BlockCreationTrait {
Chris@0 50 placeBlock as drupalPlaceBlock;
Chris@0 51 }
Chris@0 52 use AssertLegacyTrait;
Chris@0 53 use RandomGeneratorTrait;
Chris@0 54 use SessionTestTrait;
Chris@0 55 use NodeCreationTrait {
Chris@0 56 getNodeByTitle as drupalGetNodeByTitle;
Chris@0 57 createNode as drupalCreateNode;
Chris@0 58 }
Chris@0 59 use ContentTypeCreationTrait {
Chris@0 60 createContentType as drupalCreateContentType;
Chris@0 61 }
Chris@0 62 use ConfigTestTrait;
Chris@0 63 use TestRequirementsTrait;
Chris@0 64 use UserCreationTrait {
Chris@0 65 createRole as drupalCreateRole;
Chris@0 66 createUser as drupalCreateUser;
Chris@0 67 }
Chris@0 68 use XdebugRequestTrait;
Chris@12 69 use PhpunitCompatibilityTrait;
Chris@0 70
Chris@0 71 /**
Chris@0 72 * The database prefix of this test run.
Chris@0 73 *
Chris@0 74 * @var string
Chris@0 75 */
Chris@0 76 protected $databasePrefix;
Chris@0 77
Chris@0 78 /**
Chris@0 79 * Time limit in seconds for the test.
Chris@0 80 *
Chris@0 81 * @var int
Chris@0 82 */
Chris@0 83 protected $timeLimit = 500;
Chris@0 84
Chris@0 85 /**
Chris@0 86 * The translation file directory for the test environment.
Chris@0 87 *
Chris@0 88 * This is set in BrowserTestBase::prepareEnvironment().
Chris@0 89 *
Chris@0 90 * @var string
Chris@0 91 */
Chris@0 92 protected $translationFilesDirectory;
Chris@0 93
Chris@0 94 /**
Chris@0 95 * The config importer that can be used in a test.
Chris@0 96 *
Chris@0 97 * @var \Drupal\Core\Config\ConfigImporter
Chris@0 98 */
Chris@0 99 protected $configImporter;
Chris@0 100
Chris@0 101 /**
Chris@0 102 * Modules to enable.
Chris@0 103 *
Chris@0 104 * The test runner will merge the $modules lists from this class, the class
Chris@0 105 * it extends, and so on up the class hierarchy. It is not necessary to
Chris@0 106 * include modules in your list that a parent class has already declared.
Chris@0 107 *
Chris@0 108 * @var string[]
Chris@0 109 *
Chris@0 110 * @see \Drupal\Tests\BrowserTestBase::installDrupal()
Chris@0 111 */
Chris@0 112 protected static $modules = [];
Chris@0 113
Chris@0 114 /**
Chris@0 115 * The profile to install as a basis for testing.
Chris@0 116 *
Chris@0 117 * @var string
Chris@0 118 */
Chris@0 119 protected $profile = 'testing';
Chris@0 120
Chris@0 121 /**
Chris@0 122 * The current user logged in using the Mink controlled browser.
Chris@0 123 *
Chris@0 124 * @var \Drupal\user\UserInterface
Chris@0 125 */
Chris@0 126 protected $loggedInUser = FALSE;
Chris@0 127
Chris@0 128 /**
Chris@0 129 * An array of custom translations suitable for drupal_rewrite_settings().
Chris@0 130 *
Chris@0 131 * @var array
Chris@0 132 */
Chris@0 133 protected $customTranslations;
Chris@0 134
Chris@0 135 /*
Chris@0 136 * Mink class for the default driver to use.
Chris@0 137 *
Chris@0 138 * Shoud be a fully qualified class name that implements
Chris@0 139 * Behat\Mink\Driver\DriverInterface.
Chris@0 140 *
Chris@0 141 * Value can be overridden using the environment variable MINK_DRIVER_CLASS.
Chris@0 142 *
Chris@0 143 * @var string.
Chris@0 144 */
Chris@0 145 protected $minkDefaultDriverClass = GoutteDriver::class;
Chris@0 146
Chris@0 147 /*
Chris@0 148 * Mink default driver params.
Chris@0 149 *
Chris@0 150 * If it's an array its contents are used as constructor params when default
Chris@0 151 * Mink driver class is instantiated.
Chris@0 152 *
Chris@0 153 * Can be overridden using the environment variable MINK_DRIVER_ARGS. In this
Chris@0 154 * case that variable should be a JSON array, for example:
Chris@0 155 * '["firefox", null, "http://localhost:4444/wd/hub"]'.
Chris@0 156 *
Chris@0 157 *
Chris@0 158 * @var array
Chris@0 159 */
Chris@0 160 protected $minkDefaultDriverArgs;
Chris@0 161
Chris@0 162 /**
Chris@0 163 * Mink session manager.
Chris@0 164 *
Chris@0 165 * This will not be initialized if there was an error during the test setup.
Chris@0 166 *
Chris@0 167 * @var \Behat\Mink\Mink|null
Chris@0 168 */
Chris@0 169 protected $mink;
Chris@0 170
Chris@0 171 /**
Chris@0 172 * {@inheritdoc}
Chris@0 173 *
Chris@0 174 * Browser tests are run in separate processes to prevent collisions between
Chris@0 175 * code that may be loaded by tests.
Chris@0 176 */
Chris@0 177 protected $runTestInSeparateProcess = TRUE;
Chris@0 178
Chris@0 179 /**
Chris@0 180 * {@inheritdoc}
Chris@0 181 */
Chris@0 182 protected $preserveGlobalState = FALSE;
Chris@0 183
Chris@0 184 /**
Chris@0 185 * Class name for HTML output logging.
Chris@0 186 *
Chris@0 187 * @var string
Chris@0 188 */
Chris@0 189 protected $htmlOutputClassName;
Chris@0 190
Chris@0 191 /**
Chris@0 192 * Directory name for HTML output logging.
Chris@0 193 *
Chris@0 194 * @var string
Chris@0 195 */
Chris@0 196 protected $htmlOutputDirectory;
Chris@0 197
Chris@0 198 /**
Chris@0 199 * Counter storage for HTML output logging.
Chris@0 200 *
Chris@0 201 * @var string
Chris@0 202 */
Chris@0 203 protected $htmlOutputCounterStorage;
Chris@0 204
Chris@0 205 /**
Chris@0 206 * Counter for HTML output logging.
Chris@0 207 *
Chris@0 208 * @var int
Chris@0 209 */
Chris@0 210 protected $htmlOutputCounter = 1;
Chris@0 211
Chris@0 212 /**
Chris@0 213 * HTML output output enabled.
Chris@0 214 *
Chris@0 215 * @var bool
Chris@0 216 */
Chris@0 217 protected $htmlOutputEnabled = FALSE;
Chris@0 218
Chris@0 219 /**
Chris@0 220 * The file name to write the list of URLs to.
Chris@0 221 *
Chris@0 222 * This file is read by the PHPUnit result printer.
Chris@0 223 *
Chris@0 224 * @var string
Chris@0 225 *
Chris@0 226 * @see \Drupal\Tests\Listeners\HtmlOutputPrinter
Chris@0 227 */
Chris@0 228 protected $htmlOutputFile;
Chris@0 229
Chris@0 230 /**
Chris@0 231 * HTML output test ID.
Chris@0 232 *
Chris@0 233 * @var int
Chris@0 234 */
Chris@0 235 protected $htmlOutputTestId;
Chris@0 236
Chris@0 237 /**
Chris@0 238 * The base URL.
Chris@0 239 *
Chris@0 240 * @var string
Chris@0 241 */
Chris@0 242 protected $baseUrl;
Chris@0 243
Chris@0 244 /**
Chris@0 245 * The original array of shutdown function callbacks.
Chris@0 246 *
Chris@0 247 * @var array
Chris@0 248 */
Chris@0 249 protected $originalShutdownCallbacks = [];
Chris@0 250
Chris@0 251 /**
Chris@0 252 * The number of meta refresh redirects to follow, or NULL if unlimited.
Chris@0 253 *
Chris@0 254 * @var null|int
Chris@0 255 */
Chris@0 256 protected $maximumMetaRefreshCount = NULL;
Chris@0 257
Chris@0 258 /**
Chris@0 259 * The number of meta refresh redirects followed during ::drupalGet().
Chris@0 260 *
Chris@0 261 * @var int
Chris@0 262 */
Chris@0 263 protected $metaRefreshCount = 0;
Chris@0 264
Chris@0 265 /**
Chris@0 266 * The app root.
Chris@0 267 *
Chris@0 268 * @var string
Chris@0 269 */
Chris@0 270 protected $root;
Chris@0 271
Chris@0 272 /**
Chris@0 273 * The original container.
Chris@0 274 *
Chris@0 275 * Move this to \Drupal\Core\Test\FunctionalTestSetupTrait once TestBase no
Chris@0 276 * longer provides the same value.
Chris@0 277 *
Chris@0 278 * @var \Symfony\Component\DependencyInjection\ContainerInterface
Chris@0 279 */
Chris@0 280 protected $originalContainer;
Chris@0 281
Chris@0 282 /**
Chris@0 283 * {@inheritdoc}
Chris@0 284 */
Chris@0 285 public function __construct($name = NULL, array $data = [], $dataName = '') {
Chris@0 286 parent::__construct($name, $data, $dataName);
Chris@0 287
Chris@0 288 $this->root = dirname(dirname(substr(__DIR__, 0, -strlen(__NAMESPACE__))));
Chris@0 289 }
Chris@0 290
Chris@0 291 /**
Chris@0 292 * Initializes Mink sessions.
Chris@0 293 */
Chris@0 294 protected function initMink() {
Chris@0 295 $driver = $this->getDefaultDriverInstance();
Chris@0 296
Chris@0 297 if ($driver instanceof GoutteDriver) {
Chris@0 298 // Turn off curl timeout. Having a timeout is not a problem in a normal
Chris@0 299 // test running, but it is a problem when debugging. Also, disable SSL
Chris@0 300 // peer verification so that testing under HTTPS always works.
Chris@0 301 /** @var \GuzzleHttp\Client $client */
Chris@0 302 $client = $this->container->get('http_client_factory')->fromOptions([
Chris@0 303 'timeout' => NULL,
Chris@0 304 'verify' => FALSE,
Chris@0 305 ]);
Chris@0 306
Chris@0 307 // Inject a Guzzle middleware to generate debug output for every request
Chris@0 308 // performed in the test.
Chris@0 309 $handler_stack = $client->getConfig('handler');
Chris@0 310 $handler_stack->push($this->getResponseLogHandler());
Chris@0 311
Chris@0 312 $driver->getClient()->setClient($client);
Chris@0 313 }
Chris@0 314
Chris@0 315 $selectors_handler = new SelectorsHandler([
Chris@0 316 'hidden_field_selector' => new HiddenFieldSelector()
Chris@0 317 ]);
Chris@0 318 $session = new Session($driver, $selectors_handler);
Chris@0 319 $this->mink = new Mink();
Chris@0 320 $this->mink->registerSession('default', $session);
Chris@0 321 $this->mink->setDefaultSessionName('default');
Chris@0 322 $this->registerSessions();
Chris@0 323
Chris@0 324 // According to the W3C WebDriver specification a cookie can only be set if
Chris@0 325 // the cookie domain is equal to the domain of the active document. When the
Chris@0 326 // browser starts up the active document is not our domain but 'about:blank'
Chris@0 327 // or similar. To be able to set our User-Agent and Xdebug cookies at the
Chris@0 328 // start of the test we now do a request to the front page so the active
Chris@0 329 // document matches the domain.
Chris@0 330 // @see https://w3c.github.io/webdriver/webdriver-spec.html#add-cookie
Chris@0 331 // @see https://www.w3.org/Bugs/Public/show_bug.cgi?id=20975
Chris@0 332 $session = $this->getSession();
Chris@0 333 $session->visit($this->baseUrl);
Chris@0 334
Chris@0 335 return $session;
Chris@0 336 }
Chris@0 337
Chris@0 338 /**
Chris@0 339 * Gets an instance of the default Mink driver.
Chris@0 340 *
Chris@0 341 * @return Behat\Mink\Driver\DriverInterface
Chris@0 342 * Instance of default Mink driver.
Chris@0 343 *
Chris@0 344 * @throws \InvalidArgumentException
Chris@0 345 * When provided default Mink driver class can't be instantiated.
Chris@0 346 */
Chris@0 347 protected function getDefaultDriverInstance() {
Chris@0 348 // Get default driver params from environment if availables.
Chris@0 349 if ($arg_json = getenv('MINK_DRIVER_ARGS')) {
Chris@12 350 $this->minkDefaultDriverArgs = json_decode($arg_json, TRUE);
Chris@0 351 }
Chris@0 352
Chris@0 353 // Get and check default driver class from environment if availables.
Chris@0 354 if ($minkDriverClass = getenv('MINK_DRIVER_CLASS')) {
Chris@0 355 if (class_exists($minkDriverClass)) {
Chris@0 356 $this->minkDefaultDriverClass = $minkDriverClass;
Chris@0 357 }
Chris@0 358 else {
Chris@0 359 throw new \InvalidArgumentException("Can't instantiate provided $minkDriverClass class by environment as default driver class.");
Chris@0 360 }
Chris@0 361 }
Chris@0 362
Chris@0 363 if (is_array($this->minkDefaultDriverArgs)) {
Chris@0 364 // Use ReflectionClass to instantiate class with received params.
Chris@0 365 $reflector = new \ReflectionClass($this->minkDefaultDriverClass);
Chris@0 366 $driver = $reflector->newInstanceArgs($this->minkDefaultDriverArgs);
Chris@0 367 }
Chris@0 368 else {
Chris@0 369 $driver = new $this->minkDefaultDriverClass();
Chris@0 370 }
Chris@0 371 return $driver;
Chris@0 372 }
Chris@0 373
Chris@0 374 /**
Chris@0 375 * Creates the directory to store browser output.
Chris@0 376 *
Chris@0 377 * Creates the directory to store browser output in if a file to write
Chris@0 378 * URLs to has been created by \Drupal\Tests\Listeners\HtmlOutputPrinter.
Chris@0 379 */
Chris@0 380 protected function initBrowserOutputFile() {
Chris@0 381 $browser_output_file = getenv('BROWSERTEST_OUTPUT_FILE');
Chris@0 382 $this->htmlOutputEnabled = is_file($browser_output_file);
Chris@0 383 if ($this->htmlOutputEnabled) {
Chris@0 384 $this->htmlOutputFile = $browser_output_file;
Chris@0 385 $this->htmlOutputClassName = str_replace("\\", "_", get_called_class());
Chris@0 386 $this->htmlOutputDirectory = DRUPAL_ROOT . '/sites/simpletest/browser_output';
Chris@0 387 if (file_prepare_directory($this->htmlOutputDirectory, FILE_CREATE_DIRECTORY) && !file_exists($this->htmlOutputDirectory . '/.htaccess')) {
Chris@0 388 file_put_contents($this->htmlOutputDirectory . '/.htaccess', "<IfModule mod_expires.c>\nExpiresActive Off\n</IfModule>\n");
Chris@0 389 }
Chris@0 390 $this->htmlOutputCounterStorage = $this->htmlOutputDirectory . '/' . $this->htmlOutputClassName . '.counter';
Chris@0 391 $this->htmlOutputTestId = str_replace('sites/simpletest/', '', $this->siteDirectory);
Chris@0 392 if (is_file($this->htmlOutputCounterStorage)) {
Chris@0 393 $this->htmlOutputCounter = max(1, (int) file_get_contents($this->htmlOutputCounterStorage)) + 1;
Chris@0 394 }
Chris@0 395 }
Chris@0 396 }
Chris@0 397
Chris@0 398 /**
Chris@0 399 * Provides a Guzzle middleware handler to log every response received.
Chris@0 400 *
Chris@0 401 * @return callable
Chris@0 402 * The callable handler that will do the logging.
Chris@0 403 */
Chris@0 404 protected function getResponseLogHandler() {
Chris@0 405 return function (callable $handler) {
Chris@0 406 return function (RequestInterface $request, array $options) use ($handler) {
Chris@0 407 return $handler($request, $options)
Chris@0 408 ->then(function (ResponseInterface $response) use ($request) {
Chris@0 409 if ($this->htmlOutputEnabled) {
Chris@0 410
Chris@0 411 $caller = $this->getTestMethodCaller();
Chris@0 412 $html_output = 'Called from ' . $caller['function'] . ' line ' . $caller['line'];
Chris@0 413 $html_output .= '<hr />' . $request->getMethod() . ' request to: ' . $request->getUri();
Chris@0 414
Chris@0 415 // On redirect responses (status code starting with '3') we need
Chris@0 416 // to remove the meta tag that would do a browser refresh. We
Chris@0 417 // don't want to redirect developers away when they look at the
Chris@0 418 // debug output file in their browser.
Chris@0 419 $body = $response->getBody();
Chris@0 420 $status_code = (string) $response->getStatusCode();
Chris@0 421 if ($status_code[0] === '3') {
Chris@0 422 $body = preg_replace('#<meta http-equiv="refresh" content=.+/>#', '', $body, 1);
Chris@0 423 }
Chris@0 424 $html_output .= '<hr />' . $body;
Chris@0 425 $html_output .= $this->formatHtmlOutputHeaders($response->getHeaders());
Chris@0 426
Chris@0 427 $this->htmlOutput($html_output);
Chris@0 428 }
Chris@0 429 return $response;
Chris@0 430 });
Chris@0 431 };
Chris@0 432 };
Chris@0 433 }
Chris@0 434
Chris@0 435 /**
Chris@0 436 * Registers additional Mink sessions.
Chris@0 437 *
Chris@0 438 * Tests wishing to use a different driver or change the default driver should
Chris@0 439 * override this method.
Chris@0 440 *
Chris@0 441 * @code
Chris@0 442 * // Register a new session that uses the MinkPonyDriver.
Chris@0 443 * $pony = new MinkPonyDriver();
Chris@0 444 * $session = new Session($pony);
Chris@0 445 * $this->mink->registerSession('pony', $session);
Chris@0 446 * @endcode
Chris@0 447 */
Chris@0 448 protected function registerSessions() {}
Chris@0 449
Chris@0 450 /**
Chris@0 451 * {@inheritdoc}
Chris@0 452 */
Chris@0 453 protected function setUp() {
Chris@12 454 // Installing Drupal creates 1000s of objects. Garbage collection of these
Chris@12 455 // objects is expensive. This appears to be causing random segmentation
Chris@12 456 // faults in PHP 5.x due to https://bugs.php.net/bug.php?id=72286. Once
Chris@12 457 // Drupal is installed is rebuilt, garbage collection is re-enabled.
Chris@12 458 $disable_gc = version_compare(PHP_VERSION, '7', '<') && gc_enabled();
Chris@12 459 if ($disable_gc) {
Chris@12 460 gc_collect_cycles();
Chris@12 461 gc_disable();
Chris@12 462 }
Chris@0 463 parent::setUp();
Chris@0 464
Chris@0 465 $this->setupBaseUrl();
Chris@0 466
Chris@0 467 // Install Drupal test site.
Chris@0 468 $this->prepareEnvironment();
Chris@0 469 $this->installDrupal();
Chris@0 470
Chris@0 471 // Setup Mink.
Chris@0 472 $session = $this->initMink();
Chris@0 473
Chris@0 474 $cookies = $this->extractCookiesFromRequest(\Drupal::request());
Chris@0 475 foreach ($cookies as $cookie_name => $values) {
Chris@0 476 foreach ($values as $value) {
Chris@0 477 $session->setCookie($cookie_name, $value);
Chris@0 478 }
Chris@0 479 }
Chris@0 480
Chris@0 481 // Set up the browser test output file.
Chris@0 482 $this->initBrowserOutputFile();
Chris@12 483 // If garbage collection was disabled prior to rebuilding container,
Chris@12 484 // re-enable it.
Chris@12 485 if ($disable_gc) {
Chris@12 486 gc_enable();
Chris@12 487 }
Chris@0 488 }
Chris@0 489
Chris@0 490 /**
Chris@0 491 * Ensures test files are deletable within file_unmanaged_delete_recursive().
Chris@0 492 *
Chris@0 493 * Some tests chmod generated files to be read only. During
Chris@0 494 * BrowserTestBase::cleanupEnvironment() and other cleanup operations,
Chris@0 495 * these files need to get deleted too.
Chris@0 496 *
Chris@0 497 * @param string $path
Chris@0 498 * The file path.
Chris@0 499 */
Chris@0 500 public static function filePreDeleteCallback($path) {
Chris@0 501 // When the webserver runs with the same system user as phpunit, we can
Chris@0 502 // make read-only files writable again. If not, chmod will fail while the
Chris@0 503 // file deletion still works if file permissions have been configured
Chris@0 504 // correctly. Thus, we ignore any problems while running chmod.
Chris@0 505 @chmod($path, 0700);
Chris@0 506 }
Chris@0 507
Chris@0 508 /**
Chris@0 509 * Clean up the Simpletest environment.
Chris@0 510 */
Chris@0 511 protected function cleanupEnvironment() {
Chris@0 512 // Remove all prefixed tables.
Chris@0 513 $original_connection_info = Database::getConnectionInfo('simpletest_original_default');
Chris@0 514 $original_prefix = $original_connection_info['default']['prefix']['default'];
Chris@0 515 $test_connection_info = Database::getConnectionInfo('default');
Chris@0 516 $test_prefix = $test_connection_info['default']['prefix']['default'];
Chris@0 517 if ($original_prefix != $test_prefix) {
Chris@0 518 $tables = Database::getConnection()->schema()->findTables('%');
Chris@0 519 foreach ($tables as $table) {
Chris@0 520 if (Database::getConnection()->schema()->dropTable($table)) {
Chris@0 521 unset($tables[$table]);
Chris@0 522 }
Chris@0 523 }
Chris@0 524 }
Chris@0 525
Chris@0 526 // Delete test site directory.
Chris@0 527 file_unmanaged_delete_recursive($this->siteDirectory, [$this, 'filePreDeleteCallback']);
Chris@0 528 }
Chris@0 529
Chris@0 530 /**
Chris@0 531 * {@inheritdoc}
Chris@0 532 */
Chris@0 533 protected function tearDown() {
Chris@0 534 parent::tearDown();
Chris@0 535
Chris@0 536 // Destroy the testing kernel.
Chris@0 537 if (isset($this->kernel)) {
Chris@0 538 $this->cleanupEnvironment();
Chris@0 539 $this->kernel->shutdown();
Chris@0 540 }
Chris@0 541
Chris@0 542 // Ensure that internal logged in variable is reset.
Chris@0 543 $this->loggedInUser = FALSE;
Chris@0 544
Chris@0 545 if ($this->mink) {
Chris@0 546 $this->mink->stopSessions();
Chris@0 547 }
Chris@0 548
Chris@0 549 // Restore original shutdown callbacks.
Chris@0 550 if (function_exists('drupal_register_shutdown_function')) {
Chris@0 551 $callbacks = &drupal_register_shutdown_function();
Chris@0 552 $callbacks = $this->originalShutdownCallbacks;
Chris@0 553 }
Chris@0 554 }
Chris@0 555
Chris@0 556 /**
Chris@0 557 * Returns Mink session.
Chris@0 558 *
Chris@0 559 * @param string $name
Chris@0 560 * (optional) Name of the session. Defaults to the active session.
Chris@0 561 *
Chris@0 562 * @return \Behat\Mink\Session
Chris@0 563 * The active Mink session object.
Chris@0 564 */
Chris@0 565 public function getSession($name = NULL) {
Chris@0 566 return $this->mink->getSession($name);
Chris@0 567 }
Chris@0 568
Chris@0 569 /**
Chris@0 570 * Returns WebAssert object.
Chris@0 571 *
Chris@0 572 * @param string $name
Chris@0 573 * (optional) Name of the session. Defaults to the active session.
Chris@0 574 *
Chris@0 575 * @return \Drupal\Tests\WebAssert
Chris@0 576 * A new web-assert option for asserting the presence of elements with.
Chris@0 577 */
Chris@0 578 public function assertSession($name = NULL) {
Chris@0 579 return new WebAssert($this->getSession($name), $this->baseUrl);
Chris@0 580 }
Chris@0 581
Chris@0 582 /**
Chris@0 583 * Prepare for a request to testing site.
Chris@0 584 *
Chris@0 585 * The testing site is protected via a SIMPLETEST_USER_AGENT cookie that is
Chris@0 586 * checked by drupal_valid_test_ua().
Chris@0 587 *
Chris@0 588 * @see drupal_valid_test_ua()
Chris@0 589 */
Chris@0 590 protected function prepareRequest() {
Chris@0 591 $session = $this->getSession();
Chris@0 592 $session->setCookie('SIMPLETEST_USER_AGENT', drupal_generate_test_ua($this->databasePrefix));
Chris@0 593 }
Chris@0 594
Chris@0 595 /**
Chris@0 596 * Builds an a absolute URL from a system path or a URL object.
Chris@0 597 *
Chris@0 598 * @param string|\Drupal\Core\Url $path
Chris@0 599 * A system path or a URL.
Chris@0 600 * @param array $options
Chris@0 601 * Options to be passed to Url::fromUri().
Chris@0 602 *
Chris@0 603 * @return string
Chris@0 604 * An absolute URL stsring.
Chris@0 605 */
Chris@0 606 protected function buildUrl($path, array $options = []) {
Chris@0 607 if ($path instanceof Url) {
Chris@0 608 $url_options = $path->getOptions();
Chris@0 609 $options = $url_options + $options;
Chris@0 610 $path->setOptions($options);
Chris@0 611 return $path->setAbsolute()->toString();
Chris@0 612 }
Chris@0 613 // The URL generator service is not necessarily available yet; e.g., in
Chris@0 614 // interactive installer tests.
Chris@0 615 elseif ($this->container->has('url_generator')) {
Chris@0 616 $force_internal = isset($options['external']) && $options['external'] == FALSE;
Chris@0 617 if (!$force_internal && UrlHelper::isExternal($path)) {
Chris@0 618 return Url::fromUri($path, $options)->toString();
Chris@0 619 }
Chris@0 620 else {
Chris@0 621 $uri = $path === '<front>' ? 'base:/' : 'base:/' . $path;
Chris@0 622 // Path processing is needed for language prefixing. Skip it when a
Chris@0 623 // path that may look like an external URL is being used as internal.
Chris@0 624 $options['path_processing'] = !$force_internal;
Chris@0 625 return Url::fromUri($uri, $options)
Chris@0 626 ->setAbsolute()
Chris@0 627 ->toString();
Chris@0 628 }
Chris@0 629 }
Chris@0 630 else {
Chris@0 631 return $this->getAbsoluteUrl($path);
Chris@0 632 }
Chris@0 633 }
Chris@0 634
Chris@0 635 /**
Chris@0 636 * Retrieves a Drupal path or an absolute path.
Chris@0 637 *
Chris@0 638 * @param string|\Drupal\Core\Url $path
Chris@0 639 * Drupal path or URL to load into Mink controlled browser.
Chris@0 640 * @param array $options
Chris@0 641 * (optional) Options to be forwarded to the url generator.
Chris@0 642 * @param string[] $headers
Chris@0 643 * An array containing additional HTTP request headers, the array keys are
Chris@0 644 * the header names and the array values the header values. This is useful
Chris@0 645 * to set for example the "Accept-Language" header for requesting the page
Chris@0 646 * in a different language. Note that not all headers are supported, for
Chris@0 647 * example the "Accept" header is always overridden by the browser. For
Chris@0 648 * testing REST APIs it is recommended to directly use an HTTP client such
Chris@0 649 * as Guzzle instead.
Chris@0 650 *
Chris@0 651 * @return string
Chris@0 652 * The retrieved HTML string, also available as $this->getRawContent()
Chris@0 653 */
Chris@0 654 protected function drupalGet($path, array $options = [], array $headers = []) {
Chris@0 655 $options['absolute'] = TRUE;
Chris@0 656 $url = $this->buildUrl($path, $options);
Chris@0 657
Chris@0 658 $session = $this->getSession();
Chris@0 659
Chris@0 660 $this->prepareRequest();
Chris@0 661 foreach ($headers as $header_name => $header_value) {
Chris@0 662 $session->setRequestHeader($header_name, $header_value);
Chris@0 663 }
Chris@0 664
Chris@0 665 $session->visit($url);
Chris@0 666 $out = $session->getPage()->getContent();
Chris@0 667
Chris@0 668 // Ensure that any changes to variables in the other thread are picked up.
Chris@0 669 $this->refreshVariables();
Chris@0 670
Chris@0 671 // Replace original page output with new output from redirected page(s).
Chris@0 672 if ($new = $this->checkForMetaRefresh()) {
Chris@0 673 $out = $new;
Chris@0 674 // We are finished with all meta refresh redirects, so reset the counter.
Chris@0 675 $this->metaRefreshCount = 0;
Chris@0 676 }
Chris@0 677
Chris@0 678 // Log only for JavascriptTestBase tests because for Goutte we log with
Chris@0 679 // ::getResponseLogHandler.
Chris@0 680 if ($this->htmlOutputEnabled && !($this->getSession()->getDriver() instanceof GoutteDriver)) {
Chris@0 681 $html_output = 'GET request to: ' . $url .
Chris@0 682 '<hr />Ending URL: ' . $this->getSession()->getCurrentUrl();
Chris@0 683 $html_output .= '<hr />' . $out;
Chris@0 684 $html_output .= $this->getHtmlOutputHeaders();
Chris@0 685 $this->htmlOutput($html_output);
Chris@0 686 }
Chris@0 687
Chris@0 688 return $out;
Chris@0 689 }
Chris@0 690
Chris@0 691 /**
Chris@0 692 * Takes a path and returns an absolute path.
Chris@0 693 *
Chris@0 694 * @param string $path
Chris@0 695 * A path from the Mink controlled browser content.
Chris@0 696 *
Chris@0 697 * @return string
Chris@0 698 * The $path with $base_url prepended, if necessary.
Chris@0 699 */
Chris@0 700 protected function getAbsoluteUrl($path) {
Chris@0 701 global $base_url, $base_path;
Chris@0 702
Chris@0 703 $parts = parse_url($path);
Chris@0 704 if (empty($parts['host'])) {
Chris@0 705 // Ensure that we have a string (and no xpath object).
Chris@0 706 $path = (string) $path;
Chris@0 707 // Strip $base_path, if existent.
Chris@0 708 $length = strlen($base_path);
Chris@0 709 if (substr($path, 0, $length) === $base_path) {
Chris@0 710 $path = substr($path, $length);
Chris@0 711 }
Chris@0 712 // Ensure that we have an absolute path.
Chris@0 713 if (empty($path) || $path[0] !== '/') {
Chris@0 714 $path = '/' . $path;
Chris@0 715 }
Chris@0 716 // Finally, prepend the $base_url.
Chris@0 717 $path = $base_url . $path;
Chris@0 718 }
Chris@0 719 return $path;
Chris@0 720 }
Chris@0 721
Chris@0 722 /**
Chris@0 723 * Logs in a user using the Mink controlled browser.
Chris@0 724 *
Chris@0 725 * If a user is already logged in, then the current user is logged out before
Chris@0 726 * logging in the specified user.
Chris@0 727 *
Chris@0 728 * Please note that neither the current user nor the passed-in user object is
Chris@0 729 * populated with data of the logged in user. If you need full access to the
Chris@0 730 * user object after logging in, it must be updated manually. If you also need
Chris@0 731 * access to the plain-text password of the user (set by drupalCreateUser()),
Chris@0 732 * e.g. to log in the same user again, then it must be re-assigned manually.
Chris@0 733 * For example:
Chris@0 734 * @code
Chris@0 735 * // Create a user.
Chris@0 736 * $account = $this->drupalCreateUser(array());
Chris@0 737 * $this->drupalLogin($account);
Chris@0 738 * // Load real user object.
Chris@0 739 * $pass_raw = $account->passRaw;
Chris@0 740 * $account = User::load($account->id());
Chris@0 741 * $account->passRaw = $pass_raw;
Chris@0 742 * @endcode
Chris@0 743 *
Chris@0 744 * @param \Drupal\Core\Session\AccountInterface $account
Chris@0 745 * User object representing the user to log in.
Chris@0 746 *
Chris@0 747 * @see drupalCreateUser()
Chris@0 748 */
Chris@0 749 protected function drupalLogin(AccountInterface $account) {
Chris@0 750 if ($this->loggedInUser) {
Chris@0 751 $this->drupalLogout();
Chris@0 752 }
Chris@0 753
Chris@0 754 $this->drupalGet('user/login');
Chris@0 755 $this->submitForm([
Chris@0 756 'name' => $account->getUsername(),
Chris@0 757 'pass' => $account->passRaw,
Chris@0 758 ], t('Log in'));
Chris@0 759
Chris@0 760 // @see BrowserTestBase::drupalUserIsLoggedIn()
Chris@0 761 $account->sessionId = $this->getSession()->getCookie($this->getSessionName());
Chris@0 762 $this->assertTrue($this->drupalUserIsLoggedIn($account), new FormattableMarkup('User %name successfully logged in.', ['%name' => $account->getAccountName()]));
Chris@0 763
Chris@0 764 $this->loggedInUser = $account;
Chris@0 765 $this->container->get('current_user')->setAccount($account);
Chris@0 766 }
Chris@0 767
Chris@0 768 /**
Chris@0 769 * Logs a user out of the Mink controlled browser and confirms.
Chris@0 770 *
Chris@0 771 * Confirms logout by checking the login page.
Chris@0 772 */
Chris@0 773 protected function drupalLogout() {
Chris@0 774 // Make a request to the logout page, and redirect to the user page, the
Chris@0 775 // idea being if you were properly logged out you should be seeing a login
Chris@0 776 // screen.
Chris@0 777 $assert_session = $this->assertSession();
Chris@0 778 $this->drupalGet('user/logout', ['query' => ['destination' => 'user']]);
Chris@0 779 $assert_session->fieldExists('name');
Chris@0 780 $assert_session->fieldExists('pass');
Chris@0 781
Chris@0 782 // @see BrowserTestBase::drupalUserIsLoggedIn()
Chris@0 783 unset($this->loggedInUser->sessionId);
Chris@0 784 $this->loggedInUser = FALSE;
Chris@0 785 $this->container->get('current_user')->setAccount(new AnonymousUserSession());
Chris@0 786 }
Chris@0 787
Chris@0 788 /**
Chris@0 789 * Fills and submits a form.
Chris@0 790 *
Chris@0 791 * @param array $edit
Chris@0 792 * Field data in an associative array. Changes the current input fields
Chris@0 793 * (where possible) to the values indicated.
Chris@0 794 *
Chris@0 795 * A checkbox can be set to TRUE to be checked and should be set to FALSE to
Chris@0 796 * be unchecked.
Chris@0 797 * @param string $submit
Chris@0 798 * Value of the submit button whose click is to be emulated. For example,
Chris@12 799 * 'Save'. The processing of the request depends on this value. For example,
Chris@12 800 * a form may have one button with the value 'Save' and another button with
Chris@12 801 * the value 'Delete', and execute different code depending on which one is
Chris@12 802 * clicked.
Chris@0 803 * @param string $form_html_id
Chris@0 804 * (optional) HTML ID of the form to be submitted. On some pages
Chris@0 805 * there are many identical forms, so just using the value of the submit
Chris@0 806 * button is not enough. For example: 'trigger-node-presave-assign-form'.
Chris@0 807 * Note that this is not the Drupal $form_id, but rather the HTML ID of the
Chris@0 808 * form, which is typically the same thing but with hyphens replacing the
Chris@0 809 * underscores.
Chris@0 810 */
Chris@0 811 protected function submitForm(array $edit, $submit, $form_html_id = NULL) {
Chris@0 812 $assert_session = $this->assertSession();
Chris@0 813
Chris@0 814 // Get the form.
Chris@0 815 if (isset($form_html_id)) {
Chris@0 816 $form = $assert_session->elementExists('xpath', "//form[@id='$form_html_id']");
Chris@0 817 $submit_button = $assert_session->buttonExists($submit, $form);
Chris@0 818 $action = $form->getAttribute('action');
Chris@0 819 }
Chris@0 820 else {
Chris@0 821 $submit_button = $assert_session->buttonExists($submit);
Chris@0 822 $form = $assert_session->elementExists('xpath', './ancestor::form', $submit_button);
Chris@0 823 $action = $form->getAttribute('action');
Chris@0 824 }
Chris@0 825
Chris@0 826 // Edit the form values.
Chris@0 827 foreach ($edit as $name => $value) {
Chris@0 828 $field = $assert_session->fieldExists($name, $form);
Chris@0 829
Chris@0 830 // Provide support for the values '1' and '0' for checkboxes instead of
Chris@0 831 // TRUE and FALSE.
Chris@0 832 // @todo Get rid of supporting 1/0 by converting all tests cases using
Chris@0 833 // this to boolean values.
Chris@0 834 $field_type = $field->getAttribute('type');
Chris@0 835 if ($field_type === 'checkbox') {
Chris@0 836 $value = (bool) $value;
Chris@0 837 }
Chris@0 838
Chris@0 839 $field->setValue($value);
Chris@0 840 }
Chris@0 841
Chris@0 842 // Submit form.
Chris@0 843 $this->prepareRequest();
Chris@0 844 $submit_button->press();
Chris@0 845
Chris@0 846 // Ensure that any changes to variables in the other thread are picked up.
Chris@0 847 $this->refreshVariables();
Chris@0 848
Chris@0 849 // Check if there are any meta refresh redirects (like Batch API pages).
Chris@0 850 if ($this->checkForMetaRefresh()) {
Chris@0 851 // We are finished with all meta refresh redirects, so reset the counter.
Chris@0 852 $this->metaRefreshCount = 0;
Chris@0 853 }
Chris@0 854
Chris@0 855 // Log only for JavascriptTestBase tests because for Goutte we log with
Chris@0 856 // ::getResponseLogHandler.
Chris@0 857 if ($this->htmlOutputEnabled && !($this->getSession()->getDriver() instanceof GoutteDriver)) {
Chris@0 858 $out = $this->getSession()->getPage()->getContent();
Chris@0 859 $html_output = 'POST request to: ' . $action .
Chris@0 860 '<hr />Ending URL: ' . $this->getSession()->getCurrentUrl();
Chris@0 861 $html_output .= '<hr />' . $out;
Chris@0 862 $html_output .= $this->getHtmlOutputHeaders();
Chris@0 863 $this->htmlOutput($html_output);
Chris@0 864 }
Chris@0 865
Chris@0 866 }
Chris@0 867
Chris@0 868 /**
Chris@0 869 * Executes a form submission.
Chris@0 870 *
Chris@0 871 * It will be done as usual POST request with Mink.
Chris@0 872 *
Chris@0 873 * @param \Drupal\Core\Url|string $path
Chris@0 874 * Location of the post form. Either a Drupal path or an absolute path or
Chris@0 875 * NULL to post to the current page. For multi-stage forms you can set the
Chris@0 876 * path to NULL and have it post to the last received page. Example:
Chris@0 877 *
Chris@0 878 * @code
Chris@0 879 * // First step in form.
Chris@0 880 * $edit = array(...);
Chris@12 881 * $this->drupalPostForm('some_url', $edit, 'Save');
Chris@0 882 *
Chris@0 883 * // Second step in form.
Chris@0 884 * $edit = array(...);
Chris@12 885 * $this->drupalPostForm(NULL, $edit, 'Save');
Chris@0 886 * @endcode
Chris@0 887 * @param array $edit
Chris@0 888 * Field data in an associative array. Changes the current input fields
Chris@0 889 * (where possible) to the values indicated.
Chris@0 890 *
Chris@0 891 * When working with form tests, the keys for an $edit element should match
Chris@0 892 * the 'name' parameter of the HTML of the form. For example, the 'body'
Chris@0 893 * field for a node has the following HTML:
Chris@0 894 * @code
Chris@0 895 * <textarea id="edit-body-und-0-value" class="text-full form-textarea
Chris@0 896 * resize-vertical" placeholder="" cols="60" rows="9"
Chris@0 897 * name="body[0][value]"></textarea>
Chris@0 898 * @endcode
Chris@0 899 * When testing this field using an $edit parameter, the code becomes:
Chris@0 900 * @code
Chris@0 901 * $edit["body[0][value]"] = 'My test value';
Chris@0 902 * @endcode
Chris@0 903 *
Chris@0 904 * A checkbox can be set to TRUE to be checked and should be set to FALSE to
Chris@0 905 * be unchecked. Multiple select fields can be tested using 'name[]' and
Chris@0 906 * setting each of the desired values in an array:
Chris@0 907 * @code
Chris@0 908 * $edit = array();
Chris@0 909 * $edit['name[]'] = array('value1', 'value2');
Chris@0 910 * @endcode
Chris@0 911 * @todo change $edit to disallow NULL as a value for Drupal 9.
Chris@0 912 * https://www.drupal.org/node/2802401
Chris@0 913 * @param string $submit
Chris@0 914 * Value of the submit button whose click is to be emulated. For example,
Chris@12 915 * 'Save'. The processing of the request depends on this value. For example,
Chris@12 916 * a form may have one button with the value 'Save' and another button with
Chris@12 917 * the value 'Delete', and execute different code depending on which one is
Chris@12 918 * clicked.
Chris@0 919 *
Chris@0 920 * This function can also be called to emulate an Ajax submission. In this
Chris@0 921 * case, this value needs to be an array with the following keys:
Chris@0 922 * - path: A path to submit the form values to for Ajax-specific processing.
Chris@0 923 * - triggering_element: If the value for the 'path' key is a generic Ajax
Chris@0 924 * processing path, this needs to be set to the name of the element. If
Chris@0 925 * the name doesn't identify the element uniquely, then this should
Chris@0 926 * instead be an array with a single key/value pair, corresponding to the
Chris@0 927 * element name and value. The \Drupal\Core\Form\FormAjaxResponseBuilder
Chris@0 928 * uses this to find the #ajax information for the element, including
Chris@0 929 * which specific callback to use for processing the request.
Chris@0 930 *
Chris@0 931 * This can also be set to NULL in order to emulate an Internet Explorer
Chris@0 932 * submission of a form with a single text field, and pressing ENTER in that
Chris@0 933 * textfield: under these conditions, no button information is added to the
Chris@0 934 * POST data.
Chris@0 935 * @param array $options
Chris@0 936 * Options to be forwarded to the url generator.
Chris@0 937 *
Chris@0 938 * @return string
Chris@0 939 * (deprecated) The response content after submit form. It is necessary for
Chris@0 940 * backwards compatibility and will be removed before Drupal 9.0. You should
Chris@0 941 * just use the webAssert object for your assertions.
Chris@0 942 */
Chris@0 943 protected function drupalPostForm($path, $edit, $submit, array $options = []) {
Chris@0 944 if (is_object($submit)) {
Chris@0 945 // Cast MarkupInterface objects to string.
Chris@0 946 $submit = (string) $submit;
Chris@0 947 }
Chris@0 948 if ($edit === NULL) {
Chris@0 949 $edit = [];
Chris@0 950 }
Chris@0 951 if (is_array($edit)) {
Chris@0 952 $edit = $this->castSafeStrings($edit);
Chris@0 953 }
Chris@0 954
Chris@0 955 if (isset($path)) {
Chris@0 956 $this->drupalGet($path, $options);
Chris@0 957 }
Chris@0 958
Chris@0 959 $this->submitForm($edit, $submit);
Chris@0 960
Chris@0 961 return $this->getSession()->getPage()->getContent();
Chris@0 962 }
Chris@0 963
Chris@0 964 /**
Chris@0 965 * Helper function to get the options of select field.
Chris@0 966 *
Chris@0 967 * @param \Behat\Mink\Element\NodeElement|string $select
Chris@0 968 * Name, ID, or Label of select field to assert.
Chris@0 969 * @param \Behat\Mink\Element\Element $container
Chris@0 970 * (optional) Container element to check against. Defaults to current page.
Chris@0 971 *
Chris@0 972 * @return array
Chris@0 973 * Associative array of option keys and values.
Chris@0 974 */
Chris@0 975 protected function getOptions($select, Element $container = NULL) {
Chris@0 976 if (is_string($select)) {
Chris@0 977 $select = $this->assertSession()->selectExists($select, $container);
Chris@0 978 }
Chris@0 979 $options = [];
Chris@0 980 /* @var \Behat\Mink\Element\NodeElement $option */
Chris@0 981 foreach ($select->findAll('xpath', '//option') as $option) {
Chris@0 982 $label = $option->getText();
Chris@0 983 $value = $option->getAttribute('value') ?: $label;
Chris@0 984 $options[$value] = $label;
Chris@0 985 }
Chris@0 986 return $options;
Chris@0 987 }
Chris@0 988
Chris@0 989 /**
Chris@0 990 * Installs Drupal into the Simpletest site.
Chris@0 991 */
Chris@0 992 public function installDrupal() {
Chris@0 993 $this->initUserSession();
Chris@0 994 $this->prepareSettings();
Chris@0 995 $this->doInstall();
Chris@0 996 $this->initSettings();
Chris@0 997 $container = $this->initKernel(\Drupal::request());
Chris@0 998 $this->initConfig($container);
Chris@0 999 $this->installModulesFromClassProperty($container);
Chris@0 1000 $this->rebuildAll();
Chris@0 1001 }
Chris@0 1002
Chris@0 1003 /**
Chris@0 1004 * Returns whether a given user account is logged in.
Chris@0 1005 *
Chris@0 1006 * @param \Drupal\Core\Session\AccountInterface $account
Chris@0 1007 * The user account object to check.
Chris@0 1008 *
Chris@0 1009 * @return bool
Chris@0 1010 * Return TRUE if the user is logged in, FALSE otherwise.
Chris@0 1011 */
Chris@0 1012 protected function drupalUserIsLoggedIn(AccountInterface $account) {
Chris@0 1013 $logged_in = FALSE;
Chris@0 1014
Chris@0 1015 if (isset($account->sessionId)) {
Chris@0 1016 $session_handler = $this->container->get('session_handler.storage');
Chris@0 1017 $logged_in = (bool) $session_handler->read($account->sessionId);
Chris@0 1018 }
Chris@0 1019
Chris@0 1020 return $logged_in;
Chris@0 1021 }
Chris@0 1022
Chris@0 1023 /**
Chris@0 1024 * Clicks the element with the given CSS selector.
Chris@0 1025 *
Chris@0 1026 * @param string $css_selector
Chris@0 1027 * The CSS selector identifying the element to click.
Chris@0 1028 */
Chris@0 1029 protected function click($css_selector) {
Chris@0 1030 $this->getSession()->getDriver()->click($this->cssSelectToXpath($css_selector));
Chris@0 1031 }
Chris@0 1032
Chris@0 1033 /**
Chris@0 1034 * Prevents serializing any properties.
Chris@0 1035 *
Chris@0 1036 * Browser tests are run in a separate process. To do this PHPUnit creates a
Chris@0 1037 * script to run the test. If it fails, the test result object will contain a
Chris@0 1038 * stack trace which includes the test object. It will attempt to serialize
Chris@0 1039 * it. Returning an empty array prevents it from serializing anything it
Chris@0 1040 * should not.
Chris@0 1041 *
Chris@0 1042 * @return array
Chris@0 1043 * An empty array.
Chris@0 1044 *
Chris@0 1045 * @see vendor/phpunit/phpunit/src/Util/PHP/Template/TestCaseMethod.tpl.dist
Chris@0 1046 */
Chris@0 1047 public function __sleep() {
Chris@0 1048 return [];
Chris@0 1049 }
Chris@0 1050
Chris@0 1051 /**
Chris@0 1052 * Logs a HTML output message in a text file.
Chris@0 1053 *
Chris@0 1054 * The link to the HTML output message will be printed by the results printer.
Chris@0 1055 *
Chris@0 1056 * @param string $message
Chris@0 1057 * The HTML output message to be stored.
Chris@0 1058 *
Chris@0 1059 * @see \Drupal\Tests\Listeners\VerbosePrinter::printResult()
Chris@0 1060 */
Chris@0 1061 protected function htmlOutput($message) {
Chris@0 1062 if (!$this->htmlOutputEnabled) {
Chris@0 1063 return;
Chris@0 1064 }
Chris@0 1065 $message = '<hr />ID #' . $this->htmlOutputCounter . ' (<a href="' . $this->htmlOutputClassName . '-' . ($this->htmlOutputCounter - 1) . '-' . $this->htmlOutputTestId . '.html">Previous</a> | <a href="' . $this->htmlOutputClassName . '-' . ($this->htmlOutputCounter + 1) . '-' . $this->htmlOutputTestId . '.html">Next</a>)<hr />' . $message;
Chris@0 1066 $html_output_filename = $this->htmlOutputClassName . '-' . $this->htmlOutputCounter . '-' . $this->htmlOutputTestId . '.html';
Chris@0 1067 file_put_contents($this->htmlOutputDirectory . '/' . $html_output_filename, $message);
Chris@0 1068 file_put_contents($this->htmlOutputCounterStorage, $this->htmlOutputCounter++);
Chris@0 1069 file_put_contents($this->htmlOutputFile, file_create_url('sites/simpletest/browser_output/' . $html_output_filename) . "\n", FILE_APPEND);
Chris@0 1070 }
Chris@0 1071
Chris@0 1072 /**
Chris@0 1073 * Returns headers in HTML output format.
Chris@0 1074 *
Chris@0 1075 * @return string
Chris@0 1076 * HTML output headers.
Chris@0 1077 */
Chris@0 1078 protected function getHtmlOutputHeaders() {
Chris@0 1079 return $this->formatHtmlOutputHeaders($this->getSession()->getResponseHeaders());
Chris@0 1080 }
Chris@0 1081
Chris@0 1082 /**
Chris@0 1083 * Formats HTTP headers as string for HTML output logging.
Chris@0 1084 *
Chris@0 1085 * @param array[] $headers
Chris@0 1086 * Headers that should be formatted.
Chris@0 1087 *
Chris@0 1088 * @return string
Chris@0 1089 * The formatted HTML string.
Chris@0 1090 */
Chris@0 1091 protected function formatHtmlOutputHeaders(array $headers) {
Chris@0 1092 $flattened_headers = array_map(function ($header) {
Chris@0 1093 if (is_array($header)) {
Chris@0 1094 return implode(';', array_map('trim', $header));
Chris@0 1095 }
Chris@0 1096 else {
Chris@0 1097 return $header;
Chris@0 1098 }
Chris@0 1099 }, $headers);
Chris@0 1100 return '<hr />Headers: <pre>' . Html::escape(var_export($flattened_headers, TRUE)) . '</pre>';
Chris@0 1101 }
Chris@0 1102
Chris@0 1103 /**
Chris@0 1104 * Translates a CSS expression to its XPath equivalent.
Chris@0 1105 *
Chris@0 1106 * The search is relative to the root element (HTML tag normally) of the page.
Chris@0 1107 *
Chris@0 1108 * @param string $selector
Chris@0 1109 * CSS selector to use in the search.
Chris@0 1110 * @param bool $html
Chris@0 1111 * (optional) Enables HTML support. Disable it for XML documents.
Chris@0 1112 * @param string $prefix
Chris@0 1113 * (optional) The prefix for the XPath expression.
Chris@0 1114 *
Chris@0 1115 * @return string
Chris@0 1116 * The equivalent XPath of a CSS expression.
Chris@0 1117 */
Chris@0 1118 protected function cssSelectToXpath($selector, $html = TRUE, $prefix = 'descendant-or-self::') {
Chris@0 1119 return (new CssSelectorConverter($html))->toXPath($selector, $prefix);
Chris@0 1120 }
Chris@0 1121
Chris@0 1122 /**
Chris@0 1123 * Searches elements using a CSS selector in the raw content.
Chris@0 1124 *
Chris@0 1125 * The search is relative to the root element (HTML tag normally) of the page.
Chris@0 1126 *
Chris@0 1127 * @param string $selector
Chris@0 1128 * CSS selector to use in the search.
Chris@0 1129 *
Chris@0 1130 * @return \Behat\Mink\Element\NodeElement[]
Chris@0 1131 * The list of elements on the page that match the selector.
Chris@0 1132 */
Chris@0 1133 protected function cssSelect($selector) {
Chris@0 1134 return $this->getSession()->getPage()->findAll('css', $selector);
Chris@0 1135 }
Chris@0 1136
Chris@0 1137 /**
Chris@0 1138 * Follows a link by complete name.
Chris@0 1139 *
Chris@0 1140 * Will click the first link found with this link text.
Chris@0 1141 *
Chris@0 1142 * If the link is discovered and clicked, the test passes. Fail otherwise.
Chris@0 1143 *
Chris@0 1144 * @param string|\Drupal\Component\Render\MarkupInterface $label
Chris@0 1145 * Text between the anchor tags.
Chris@0 1146 * @param int $index
Chris@0 1147 * (optional) The index number for cases where multiple links have the same
Chris@0 1148 * text. Defaults to 0.
Chris@0 1149 */
Chris@0 1150 protected function clickLink($label, $index = 0) {
Chris@0 1151 $label = (string) $label;
Chris@0 1152 $links = $this->getSession()->getPage()->findAll('named', ['link', $label]);
Chris@0 1153 $links[$index]->click();
Chris@0 1154 }
Chris@0 1155
Chris@0 1156 /**
Chris@0 1157 * Retrieves the plain-text content from the current page.
Chris@0 1158 */
Chris@0 1159 protected function getTextContent() {
Chris@0 1160 return $this->getSession()->getPage()->getText();
Chris@0 1161 }
Chris@0 1162
Chris@0 1163 /**
Chris@0 1164 * Performs an xpath search on the contents of the internal browser.
Chris@0 1165 *
Chris@0 1166 * The search is relative to the root element (HTML tag normally) of the page.
Chris@0 1167 *
Chris@0 1168 * @param string $xpath
Chris@0 1169 * The xpath string to use in the search.
Chris@0 1170 * @param array $arguments
Chris@0 1171 * An array of arguments with keys in the form ':name' matching the
Chris@0 1172 * placeholders in the query. The values may be either strings or numeric
Chris@0 1173 * values.
Chris@0 1174 *
Chris@0 1175 * @return \Behat\Mink\Element\NodeElement[]
Chris@0 1176 * The list of elements matching the xpath expression.
Chris@0 1177 */
Chris@0 1178 protected function xpath($xpath, array $arguments = []) {
Chris@0 1179 $xpath = $this->assertSession()->buildXPathQuery($xpath, $arguments);
Chris@0 1180 return $this->getSession()->getPage()->findAll('xpath', $xpath);
Chris@0 1181 }
Chris@0 1182
Chris@0 1183 /**
Chris@0 1184 * Configuration accessor for tests. Returns non-overridden configuration.
Chris@0 1185 *
Chris@0 1186 * @param string $name
Chris@0 1187 * Configuration name.
Chris@0 1188 *
Chris@0 1189 * @return \Drupal\Core\Config\Config
Chris@0 1190 * The configuration object with original configuration data.
Chris@0 1191 */
Chris@0 1192 protected function config($name) {
Chris@0 1193 return $this->container->get('config.factory')->getEditable($name);
Chris@0 1194 }
Chris@0 1195
Chris@0 1196 /**
Chris@0 1197 * Returns all response headers.
Chris@0 1198 *
Chris@0 1199 * @return array
Chris@0 1200 * The HTTP headers values.
Chris@0 1201 *
Chris@0 1202 * @deprecated Scheduled for removal in Drupal 9.0.0.
Chris@0 1203 * Use $this->getSession()->getResponseHeaders() instead.
Chris@0 1204 */
Chris@0 1205 protected function drupalGetHeaders() {
Chris@0 1206 return $this->getSession()->getResponseHeaders();
Chris@0 1207 }
Chris@0 1208
Chris@0 1209 /**
Chris@0 1210 * Gets the value of an HTTP response header.
Chris@0 1211 *
Chris@0 1212 * If multiple requests were required to retrieve the page, only the headers
Chris@0 1213 * from the last request will be checked by default.
Chris@0 1214 *
Chris@0 1215 * @param string $name
Chris@0 1216 * The name of the header to retrieve. Names are case-insensitive (see RFC
Chris@0 1217 * 2616 section 4.2).
Chris@0 1218 *
Chris@0 1219 * @return string|null
Chris@0 1220 * The HTTP header value or NULL if not found.
Chris@0 1221 */
Chris@0 1222 protected function drupalGetHeader($name) {
Chris@0 1223 return $this->getSession()->getResponseHeader($name);
Chris@0 1224 }
Chris@0 1225
Chris@0 1226 /**
Chris@0 1227 * Get the current URL from the browser.
Chris@0 1228 *
Chris@0 1229 * @return string
Chris@0 1230 * The current URL.
Chris@0 1231 */
Chris@0 1232 protected function getUrl() {
Chris@0 1233 return $this->getSession()->getCurrentUrl();
Chris@0 1234 }
Chris@0 1235
Chris@0 1236 /**
Chris@0 1237 * Gets the JavaScript drupalSettings variable for the currently-loaded page.
Chris@0 1238 *
Chris@0 1239 * @return array
Chris@0 1240 * The JSON decoded drupalSettings value from the current page.
Chris@0 1241 */
Chris@0 1242 protected function getDrupalSettings() {
Chris@0 1243 $html = $this->getSession()->getPage()->getHtml();
Chris@0 1244 if (preg_match('@<script type="application/json" data-drupal-selector="drupal-settings-json">([^<]*)</script>@', $html, $matches)) {
Chris@0 1245 return Json::decode($matches[1]);
Chris@0 1246 }
Chris@0 1247 return [];
Chris@0 1248 }
Chris@0 1249
Chris@0 1250 /**
Chris@0 1251 * {@inheritdoc}
Chris@0 1252 */
Chris@0 1253 public static function assertEquals($expected, $actual, $message = '', $delta = 0.0, $maxDepth = 10, $canonicalize = FALSE, $ignoreCase = FALSE) {
Chris@0 1254 // Cast objects implementing MarkupInterface to string instead of
Chris@0 1255 // relying on PHP casting them to string depending on what they are being
Chris@0 1256 // comparing with.
Chris@0 1257 $expected = static::castSafeStrings($expected);
Chris@0 1258 $actual = static::castSafeStrings($actual);
Chris@0 1259 parent::assertEquals($expected, $actual, $message, $delta, $maxDepth, $canonicalize, $ignoreCase);
Chris@0 1260 }
Chris@0 1261
Chris@0 1262 /**
Chris@0 1263 * Retrieves the current calling line in the class under test.
Chris@0 1264 *
Chris@0 1265 * @return array
Chris@0 1266 * An associative array with keys 'file', 'line' and 'function'.
Chris@0 1267 */
Chris@0 1268 protected function getTestMethodCaller() {
Chris@0 1269 $backtrace = debug_backtrace();
Chris@0 1270 // Find the test class that has the test method.
Chris@0 1271 while ($caller = Error::getLastCaller($backtrace)) {
Chris@0 1272 if (isset($caller['class']) && $caller['class'] === get_class($this)) {
Chris@0 1273 break;
Chris@0 1274 }
Chris@0 1275 // If the test method is implemented by a test class's parent then the
Chris@0 1276 // class name of $this will not be part of the backtrace.
Chris@0 1277 // In that case we process the backtrace until the caller is not a
Chris@0 1278 // subclass of $this and return the previous caller.
Chris@0 1279 if (isset($last_caller) && (!isset($caller['class']) || !is_subclass_of($this, $caller['class']))) {
Chris@0 1280 // Return the last caller since that has to be the test class.
Chris@0 1281 $caller = $last_caller;
Chris@0 1282 break;
Chris@0 1283 }
Chris@0 1284 // Otherwise we have not reached our test class yet: save the last caller
Chris@0 1285 // and remove an element from to backtrace to process the next call.
Chris@0 1286 $last_caller = $caller;
Chris@0 1287 array_shift($backtrace);
Chris@0 1288 }
Chris@0 1289
Chris@0 1290 return $caller;
Chris@0 1291 }
Chris@0 1292
Chris@0 1293 /**
Chris@0 1294 * Checks for meta refresh tag and if found call drupalGet() recursively.
Chris@0 1295 *
Chris@0 1296 * This function looks for the http-equiv attribute to be set to "Refresh" and
Chris@0 1297 * is case-insensitive.
Chris@0 1298 *
Chris@0 1299 * @return string|false
Chris@0 1300 * Either the new page content or FALSE.
Chris@0 1301 */
Chris@0 1302 protected function checkForMetaRefresh() {
Chris@0 1303 $refresh = $this->cssSelect('meta[http-equiv="Refresh"], meta[http-equiv="refresh"]');
Chris@0 1304 if (!empty($refresh) && (!isset($this->maximumMetaRefreshCount) || $this->metaRefreshCount < $this->maximumMetaRefreshCount)) {
Chris@0 1305 // Parse the content attribute of the meta tag for the format:
Chris@0 1306 // "[delay]: URL=[page_to_redirect_to]".
Chris@0 1307 if (preg_match('/\d+;\s*URL=(?<url>.*)/i', $refresh[0]->getAttribute('content'), $match)) {
Chris@0 1308 $this->metaRefreshCount++;
Chris@0 1309 return $this->drupalGet($this->getAbsoluteUrl(Html::decodeEntities($match['url'])));
Chris@0 1310 }
Chris@0 1311 }
Chris@0 1312 return FALSE;
Chris@0 1313 }
Chris@0 1314
Chris@0 1315 }