annotate core/tests/Drupal/Tests/BrowserTestBase.php @ 0:4c8ae668cc8c

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