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

Initial commit from drush-created site
author Chris Cannam
date Thu, 05 Jul 2018 14:24:15 +0000
parents
children a9cd425dd02b
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 * Tests extending this base class should only translate text when testing
Chris@0 39 * translation functionality. For example, avoid wrapping test text with t()
Chris@0 40 * or TranslatableMarkup().
Chris@0 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@0 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 $this->initFrontPage();
Chris@0 325
Chris@0 326 return $session;
Chris@0 327 }
Chris@0 328
Chris@0 329 /**
Chris@0 330 * Visits the front page when initializing Mink.
Chris@0 331 *
Chris@0 332 * According to the W3C WebDriver specification a cookie can only be set if
Chris@0 333 * the cookie domain is equal to the domain of the active document. When the
Chris@0 334 * browser starts up the active document is not our domain but 'about:blank'
Chris@0 335 * or similar. To be able to set our User-Agent and Xdebug cookies at the
Chris@0 336 * start of the test we now do a request to the front page so the active
Chris@0 337 * document matches the domain.
Chris@0 338 *
Chris@0 339 * @see https://w3c.github.io/webdriver/webdriver-spec.html#add-cookie
Chris@0 340 * @see https://www.w3.org/Bugs/Public/show_bug.cgi?id=20975
Chris@0 341 */
Chris@0 342 protected function initFrontPage() {
Chris@0 343 $session = $this->getSession();
Chris@0 344 $session->visit($this->baseUrl);
Chris@0 345 }
Chris@0 346
Chris@0 347 /**
Chris@0 348 * Gets an instance of the default Mink driver.
Chris@0 349 *
Chris@0 350 * @return Behat\Mink\Driver\DriverInterface
Chris@0 351 * Instance of default Mink driver.
Chris@0 352 *
Chris@0 353 * @throws \InvalidArgumentException
Chris@0 354 * When provided default Mink driver class can't be instantiated.
Chris@0 355 */
Chris@0 356 protected function getDefaultDriverInstance() {
Chris@0 357 // Get default driver params from environment if available.
Chris@0 358 if ($arg_json = $this->getMinkDriverArgs()) {
Chris@0 359 $this->minkDefaultDriverArgs = json_decode($arg_json, TRUE);
Chris@0 360 }
Chris@0 361
Chris@0 362 // Get and check default driver class from environment if available.
Chris@0 363 if ($minkDriverClass = getenv('MINK_DRIVER_CLASS')) {
Chris@0 364 if (class_exists($minkDriverClass)) {
Chris@0 365 $this->minkDefaultDriverClass = $minkDriverClass;
Chris@0 366 }
Chris@0 367 else {
Chris@0 368 throw new \InvalidArgumentException("Can't instantiate provided $minkDriverClass class by environment as default driver class.");
Chris@0 369 }
Chris@0 370 }
Chris@0 371
Chris@0 372 if (is_array($this->minkDefaultDriverArgs)) {
Chris@0 373 // Use ReflectionClass to instantiate class with received params.
Chris@0 374 $reflector = new \ReflectionClass($this->minkDefaultDriverClass);
Chris@0 375 $driver = $reflector->newInstanceArgs($this->minkDefaultDriverArgs);
Chris@0 376 }
Chris@0 377 else {
Chris@0 378 $driver = new $this->minkDefaultDriverClass();
Chris@0 379 }
Chris@0 380 return $driver;
Chris@0 381 }
Chris@0 382
Chris@0 383 /**
Chris@0 384 * Creates the directory to store browser output.
Chris@0 385 *
Chris@0 386 * Creates the directory to store browser output in if a file to write
Chris@0 387 * URLs to has been created by \Drupal\Tests\Listeners\HtmlOutputPrinter.
Chris@0 388 */
Chris@0 389 protected function initBrowserOutputFile() {
Chris@0 390 $browser_output_file = getenv('BROWSERTEST_OUTPUT_FILE');
Chris@0 391 $this->htmlOutputEnabled = is_file($browser_output_file);
Chris@0 392 if ($this->htmlOutputEnabled) {
Chris@0 393 $this->htmlOutputFile = $browser_output_file;
Chris@0 394 $this->htmlOutputClassName = str_replace("\\", "_", get_called_class());
Chris@0 395 $this->htmlOutputDirectory = DRUPAL_ROOT . '/sites/simpletest/browser_output';
Chris@0 396 if (file_prepare_directory($this->htmlOutputDirectory, FILE_CREATE_DIRECTORY) && !file_exists($this->htmlOutputDirectory . '/.htaccess')) {
Chris@0 397 file_put_contents($this->htmlOutputDirectory . '/.htaccess', "<IfModule mod_expires.c>\nExpiresActive Off\n</IfModule>\n");
Chris@0 398 }
Chris@0 399 $this->htmlOutputCounterStorage = $this->htmlOutputDirectory . '/' . $this->htmlOutputClassName . '.counter';
Chris@0 400 $this->htmlOutputTestId = str_replace('sites/simpletest/', '', $this->siteDirectory);
Chris@0 401 if (is_file($this->htmlOutputCounterStorage)) {
Chris@0 402 $this->htmlOutputCounter = max(1, (int) file_get_contents($this->htmlOutputCounterStorage)) + 1;
Chris@0 403 }
Chris@0 404 }
Chris@0 405 }
Chris@0 406
Chris@0 407 /**
Chris@0 408 * Get the Mink driver args from an environment variable, if it is set. Can
Chris@0 409 * be overridden in a derived class so it is possible to use a different
Chris@0 410 * value for a subset of tests, e.g. the JavaScript tests.
Chris@0 411 *
Chris@0 412 * @return string|false
Chris@0 413 * The JSON-encoded argument string. False if it is not set.
Chris@0 414 */
Chris@0 415 protected function getMinkDriverArgs() {
Chris@0 416 return getenv('MINK_DRIVER_ARGS');
Chris@0 417 }
Chris@0 418
Chris@0 419 /**
Chris@0 420 * Provides a Guzzle middleware handler to log every response received.
Chris@0 421 *
Chris@0 422 * @return callable
Chris@0 423 * The callable handler that will do the logging.
Chris@0 424 */
Chris@0 425 protected function getResponseLogHandler() {
Chris@0 426 return function (callable $handler) {
Chris@0 427 return function (RequestInterface $request, array $options) use ($handler) {
Chris@0 428 return $handler($request, $options)
Chris@0 429 ->then(function (ResponseInterface $response) use ($request) {
Chris@0 430 if ($this->htmlOutputEnabled) {
Chris@0 431
Chris@0 432 $caller = $this->getTestMethodCaller();
Chris@0 433 $html_output = 'Called from ' . $caller['function'] . ' line ' . $caller['line'];
Chris@0 434 $html_output .= '<hr />' . $request->getMethod() . ' request to: ' . $request->getUri();
Chris@0 435
Chris@0 436 // On redirect responses (status code starting with '3') we need
Chris@0 437 // to remove the meta tag that would do a browser refresh. We
Chris@0 438 // don't want to redirect developers away when they look at the
Chris@0 439 // debug output file in their browser.
Chris@0 440 $body = $response->getBody();
Chris@0 441 $status_code = (string) $response->getStatusCode();
Chris@0 442 if ($status_code[0] === '3') {
Chris@0 443 $body = preg_replace('#<meta http-equiv="refresh" content=.+/>#', '', $body, 1);
Chris@0 444 }
Chris@0 445 $html_output .= '<hr />' . $body;
Chris@0 446 $html_output .= $this->formatHtmlOutputHeaders($response->getHeaders());
Chris@0 447
Chris@0 448 $this->htmlOutput($html_output);
Chris@0 449 }
Chris@0 450 return $response;
Chris@0 451 });
Chris@0 452 };
Chris@0 453 };
Chris@0 454 }
Chris@0 455
Chris@0 456 /**
Chris@0 457 * Registers additional Mink sessions.
Chris@0 458 *
Chris@0 459 * Tests wishing to use a different driver or change the default driver should
Chris@0 460 * override this method.
Chris@0 461 *
Chris@0 462 * @code
Chris@0 463 * // Register a new session that uses the MinkPonyDriver.
Chris@0 464 * $pony = new MinkPonyDriver();
Chris@0 465 * $session = new Session($pony);
Chris@0 466 * $this->mink->registerSession('pony', $session);
Chris@0 467 * @endcode
Chris@0 468 */
Chris@0 469 protected function registerSessions() {}
Chris@0 470
Chris@0 471 /**
Chris@0 472 * {@inheritdoc}
Chris@0 473 */
Chris@0 474 protected function setUp() {
Chris@0 475 // Installing Drupal creates 1000s of objects. Garbage collection of these
Chris@0 476 // objects is expensive. This appears to be causing random segmentation
Chris@0 477 // faults in PHP 5.x due to https://bugs.php.net/bug.php?id=72286. Once
Chris@0 478 // Drupal is installed is rebuilt, garbage collection is re-enabled.
Chris@0 479 $disable_gc = version_compare(PHP_VERSION, '7', '<') && gc_enabled();
Chris@0 480 if ($disable_gc) {
Chris@0 481 gc_collect_cycles();
Chris@0 482 gc_disable();
Chris@0 483 }
Chris@0 484 parent::setUp();
Chris@0 485
Chris@0 486 $this->setupBaseUrl();
Chris@0 487
Chris@0 488 // Install Drupal test site.
Chris@0 489 $this->prepareEnvironment();
Chris@0 490 $this->installDrupal();
Chris@0 491
Chris@0 492 // Setup Mink.
Chris@0 493 $session = $this->initMink();
Chris@0 494
Chris@0 495 $cookies = $this->extractCookiesFromRequest(\Drupal::request());
Chris@0 496 foreach ($cookies as $cookie_name => $values) {
Chris@0 497 foreach ($values as $value) {
Chris@0 498 $session->setCookie($cookie_name, $value);
Chris@0 499 }
Chris@0 500 }
Chris@0 501
Chris@0 502 // Set up the browser test output file.
Chris@0 503 $this->initBrowserOutputFile();
Chris@0 504 // If garbage collection was disabled prior to rebuilding container,
Chris@0 505 // re-enable it.
Chris@0 506 if ($disable_gc) {
Chris@0 507 gc_enable();
Chris@0 508 }
Chris@0 509
Chris@0 510 // Ensure that the test is not marked as risky because of no assertions. In
Chris@0 511 // PHPUnit 6 tests that only make assertions using $this->assertSession()
Chris@0 512 // can be marked as risky.
Chris@0 513 $this->addToAssertionCount(1);
Chris@0 514 }
Chris@0 515
Chris@0 516 /**
Chris@0 517 * Ensures test files are deletable within file_unmanaged_delete_recursive().
Chris@0 518 *
Chris@0 519 * Some tests chmod generated files to be read only. During
Chris@0 520 * BrowserTestBase::cleanupEnvironment() and other cleanup operations,
Chris@0 521 * these files need to get deleted too.
Chris@0 522 *
Chris@0 523 * @param string $path
Chris@0 524 * The file path.
Chris@0 525 */
Chris@0 526 public static function filePreDeleteCallback($path) {
Chris@0 527 // When the webserver runs with the same system user as phpunit, we can
Chris@0 528 // make read-only files writable again. If not, chmod will fail while the
Chris@0 529 // file deletion still works if file permissions have been configured
Chris@0 530 // correctly. Thus, we ignore any problems while running chmod.
Chris@0 531 @chmod($path, 0700);
Chris@0 532 }
Chris@0 533
Chris@0 534 /**
Chris@0 535 * Clean up the Simpletest environment.
Chris@0 536 */
Chris@0 537 protected function cleanupEnvironment() {
Chris@0 538 // Remove all prefixed tables.
Chris@0 539 $original_connection_info = Database::getConnectionInfo('simpletest_original_default');
Chris@0 540 $original_prefix = $original_connection_info['default']['prefix']['default'];
Chris@0 541 $test_connection_info = Database::getConnectionInfo('default');
Chris@0 542 $test_prefix = $test_connection_info['default']['prefix']['default'];
Chris@0 543 if ($original_prefix != $test_prefix) {
Chris@0 544 $tables = Database::getConnection()->schema()->findTables('%');
Chris@0 545 foreach ($tables as $table) {
Chris@0 546 if (Database::getConnection()->schema()->dropTable($table)) {
Chris@0 547 unset($tables[$table]);
Chris@0 548 }
Chris@0 549 }
Chris@0 550 }
Chris@0 551
Chris@0 552 // Delete test site directory.
Chris@0 553 file_unmanaged_delete_recursive($this->siteDirectory, [$this, 'filePreDeleteCallback']);
Chris@0 554 }
Chris@0 555
Chris@0 556 /**
Chris@0 557 * {@inheritdoc}
Chris@0 558 */
Chris@0 559 protected function tearDown() {
Chris@0 560 parent::tearDown();
Chris@0 561
Chris@0 562 // Destroy the testing kernel.
Chris@0 563 if (isset($this->kernel)) {
Chris@0 564 $this->cleanupEnvironment();
Chris@0 565 $this->kernel->shutdown();
Chris@0 566 }
Chris@0 567
Chris@0 568 // Ensure that internal logged in variable is reset.
Chris@0 569 $this->loggedInUser = FALSE;
Chris@0 570
Chris@0 571 if ($this->mink) {
Chris@0 572 $this->mink->stopSessions();
Chris@0 573 }
Chris@0 574
Chris@0 575 // Restore original shutdown callbacks.
Chris@0 576 if (function_exists('drupal_register_shutdown_function')) {
Chris@0 577 $callbacks = &drupal_register_shutdown_function();
Chris@0 578 $callbacks = $this->originalShutdownCallbacks;
Chris@0 579 }
Chris@0 580 }
Chris@0 581
Chris@0 582 /**
Chris@0 583 * Returns Mink session.
Chris@0 584 *
Chris@0 585 * @param string $name
Chris@0 586 * (optional) Name of the session. Defaults to the active session.
Chris@0 587 *
Chris@0 588 * @return \Behat\Mink\Session
Chris@0 589 * The active Mink session object.
Chris@0 590 */
Chris@0 591 public function getSession($name = NULL) {
Chris@0 592 return $this->mink->getSession($name);
Chris@0 593 }
Chris@0 594
Chris@0 595 /**
Chris@0 596 * Obtain the HTTP client for the system under test.
Chris@0 597 *
Chris@0 598 * Use this method for arbitrary HTTP requests to the site under test. For
Chris@0 599 * most tests, you should not get the HTTP client and instead use navigation
Chris@0 600 * methods such as drupalGet() and clickLink() in order to benefit from
Chris@0 601 * assertions.
Chris@0 602 *
Chris@0 603 * Subclasses which substitute a different Mink driver should override this
Chris@0 604 * method and provide a Guzzle client if the Mink driver provides one.
Chris@0 605 *
Chris@0 606 * @return \GuzzleHttp\ClientInterface
Chris@0 607 * The client with BrowserTestBase configuration.
Chris@0 608 *
Chris@0 609 * @throws \RuntimeException
Chris@0 610 * If the Mink driver does not support a Guzzle HTTP client, throw an
Chris@0 611 * exception.
Chris@0 612 */
Chris@0 613 protected function getHttpClient() {
Chris@0 614 /* @var $mink_driver \Behat\Mink\Driver\DriverInterface */
Chris@0 615 $mink_driver = $this->getSession()->getDriver();
Chris@0 616 if ($mink_driver instanceof GoutteDriver) {
Chris@0 617 return $mink_driver->getClient()->getClient();
Chris@0 618 }
Chris@0 619 throw new \RuntimeException('The Mink client type ' . get_class($mink_driver) . ' does not support getHttpClient().');
Chris@0 620 }
Chris@0 621
Chris@0 622 /**
Chris@0 623 * Returns WebAssert object.
Chris@0 624 *
Chris@0 625 * @param string $name
Chris@0 626 * (optional) Name of the session. Defaults to the active session.
Chris@0 627 *
Chris@0 628 * @return \Drupal\Tests\WebAssert
Chris@0 629 * A new web-assert option for asserting the presence of elements with.
Chris@0 630 */
Chris@0 631 public function assertSession($name = NULL) {
Chris@0 632 $this->addToAssertionCount(1);
Chris@0 633 return new WebAssert($this->getSession($name), $this->baseUrl);
Chris@0 634 }
Chris@0 635
Chris@0 636 /**
Chris@0 637 * Prepare for a request to testing site.
Chris@0 638 *
Chris@0 639 * The testing site is protected via a SIMPLETEST_USER_AGENT cookie that is
Chris@0 640 * checked by drupal_valid_test_ua().
Chris@0 641 *
Chris@0 642 * @see drupal_valid_test_ua()
Chris@0 643 */
Chris@0 644 protected function prepareRequest() {
Chris@0 645 $session = $this->getSession();
Chris@0 646 $session->setCookie('SIMPLETEST_USER_AGENT', drupal_generate_test_ua($this->databasePrefix));
Chris@0 647 }
Chris@0 648
Chris@0 649 /**
Chris@0 650 * Builds an a absolute URL from a system path or a URL object.
Chris@0 651 *
Chris@0 652 * @param string|\Drupal\Core\Url $path
Chris@0 653 * A system path or a URL.
Chris@0 654 * @param array $options
Chris@0 655 * Options to be passed to Url::fromUri().
Chris@0 656 *
Chris@0 657 * @return string
Chris@0 658 * An absolute URL stsring.
Chris@0 659 */
Chris@0 660 protected function buildUrl($path, array $options = []) {
Chris@0 661 if ($path instanceof Url) {
Chris@0 662 $url_options = $path->getOptions();
Chris@0 663 $options = $url_options + $options;
Chris@0 664 $path->setOptions($options);
Chris@0 665 return $path->setAbsolute()->toString();
Chris@0 666 }
Chris@0 667 // The URL generator service is not necessarily available yet; e.g., in
Chris@0 668 // interactive installer tests.
Chris@0 669 elseif ($this->container->has('url_generator')) {
Chris@0 670 $force_internal = isset($options['external']) && $options['external'] == FALSE;
Chris@0 671 if (!$force_internal && UrlHelper::isExternal($path)) {
Chris@0 672 return Url::fromUri($path, $options)->toString();
Chris@0 673 }
Chris@0 674 else {
Chris@0 675 $uri = $path === '<front>' ? 'base:/' : 'base:/' . $path;
Chris@0 676 // Path processing is needed for language prefixing. Skip it when a
Chris@0 677 // path that may look like an external URL is being used as internal.
Chris@0 678 $options['path_processing'] = !$force_internal;
Chris@0 679 return Url::fromUri($uri, $options)
Chris@0 680 ->setAbsolute()
Chris@0 681 ->toString();
Chris@0 682 }
Chris@0 683 }
Chris@0 684 else {
Chris@0 685 return $this->getAbsoluteUrl($path);
Chris@0 686 }
Chris@0 687 }
Chris@0 688
Chris@0 689 /**
Chris@0 690 * Retrieves a Drupal path or an absolute path.
Chris@0 691 *
Chris@0 692 * @param string|\Drupal\Core\Url $path
Chris@0 693 * Drupal path or URL to load into Mink controlled browser.
Chris@0 694 * @param array $options
Chris@0 695 * (optional) Options to be forwarded to the url generator.
Chris@0 696 * @param string[] $headers
Chris@0 697 * An array containing additional HTTP request headers, the array keys are
Chris@0 698 * the header names and the array values the header values. This is useful
Chris@0 699 * to set for example the "Accept-Language" header for requesting the page
Chris@0 700 * in a different language. Note that not all headers are supported, for
Chris@0 701 * example the "Accept" header is always overridden by the browser. For
Chris@0 702 * testing REST APIs it is recommended to obtain a separate HTTP client
Chris@0 703 * using getHttpClient() and performing requests that way.
Chris@0 704 *
Chris@0 705 * @return string
Chris@0 706 * The retrieved HTML string, also available as $this->getRawContent()
Chris@0 707 *
Chris@0 708 * @see \Drupal\Tests\BrowserTestBase::getHttpClient()
Chris@0 709 */
Chris@0 710 protected function drupalGet($path, array $options = [], array $headers = []) {
Chris@0 711 $options['absolute'] = TRUE;
Chris@0 712 $url = $this->buildUrl($path, $options);
Chris@0 713
Chris@0 714 $session = $this->getSession();
Chris@0 715
Chris@0 716 $this->prepareRequest();
Chris@0 717 foreach ($headers as $header_name => $header_value) {
Chris@0 718 $session->setRequestHeader($header_name, $header_value);
Chris@0 719 }
Chris@0 720
Chris@0 721 $session->visit($url);
Chris@0 722 $out = $session->getPage()->getContent();
Chris@0 723
Chris@0 724 // Ensure that any changes to variables in the other thread are picked up.
Chris@0 725 $this->refreshVariables();
Chris@0 726
Chris@0 727 // Replace original page output with new output from redirected page(s).
Chris@0 728 if ($new = $this->checkForMetaRefresh()) {
Chris@0 729 $out = $new;
Chris@0 730 // We are finished with all meta refresh redirects, so reset the counter.
Chris@0 731 $this->metaRefreshCount = 0;
Chris@0 732 }
Chris@0 733
Chris@0 734 // Log only for JavascriptTestBase tests because for Goutte we log with
Chris@0 735 // ::getResponseLogHandler.
Chris@0 736 if ($this->htmlOutputEnabled && !($this->getSession()->getDriver() instanceof GoutteDriver)) {
Chris@0 737 $html_output = 'GET request to: ' . $url .
Chris@0 738 '<hr />Ending URL: ' . $this->getSession()->getCurrentUrl();
Chris@0 739 $html_output .= '<hr />' . $out;
Chris@0 740 $html_output .= $this->getHtmlOutputHeaders();
Chris@0 741 $this->htmlOutput($html_output);
Chris@0 742 }
Chris@0 743
Chris@0 744 return $out;
Chris@0 745 }
Chris@0 746
Chris@0 747 /**
Chris@0 748 * Takes a path and returns an absolute path.
Chris@0 749 *
Chris@0 750 * @param string $path
Chris@0 751 * A path from the Mink controlled browser content.
Chris@0 752 *
Chris@0 753 * @return string
Chris@0 754 * The $path with $base_url prepended, if necessary.
Chris@0 755 */
Chris@0 756 protected function getAbsoluteUrl($path) {
Chris@0 757 global $base_url, $base_path;
Chris@0 758
Chris@0 759 $parts = parse_url($path);
Chris@0 760 if (empty($parts['host'])) {
Chris@0 761 // Ensure that we have a string (and no xpath object).
Chris@0 762 $path = (string) $path;
Chris@0 763 // Strip $base_path, if existent.
Chris@0 764 $length = strlen($base_path);
Chris@0 765 if (substr($path, 0, $length) === $base_path) {
Chris@0 766 $path = substr($path, $length);
Chris@0 767 }
Chris@0 768 // Ensure that we have an absolute path.
Chris@0 769 if (empty($path) || $path[0] !== '/') {
Chris@0 770 $path = '/' . $path;
Chris@0 771 }
Chris@0 772 // Finally, prepend the $base_url.
Chris@0 773 $path = $base_url . $path;
Chris@0 774 }
Chris@0 775 return $path;
Chris@0 776 }
Chris@0 777
Chris@0 778 /**
Chris@0 779 * Logs in a user using the Mink controlled browser.
Chris@0 780 *
Chris@0 781 * If a user is already logged in, then the current user is logged out before
Chris@0 782 * logging in the specified user.
Chris@0 783 *
Chris@0 784 * Please note that neither the current user nor the passed-in user object is
Chris@0 785 * populated with data of the logged in user. If you need full access to the
Chris@0 786 * user object after logging in, it must be updated manually. If you also need
Chris@0 787 * access to the plain-text password of the user (set by drupalCreateUser()),
Chris@0 788 * e.g. to log in the same user again, then it must be re-assigned manually.
Chris@0 789 * For example:
Chris@0 790 * @code
Chris@0 791 * // Create a user.
Chris@0 792 * $account = $this->drupalCreateUser(array());
Chris@0 793 * $this->drupalLogin($account);
Chris@0 794 * // Load real user object.
Chris@0 795 * $pass_raw = $account->passRaw;
Chris@0 796 * $account = User::load($account->id());
Chris@0 797 * $account->passRaw = $pass_raw;
Chris@0 798 * @endcode
Chris@0 799 *
Chris@0 800 * @param \Drupal\Core\Session\AccountInterface $account
Chris@0 801 * User object representing the user to log in.
Chris@0 802 *
Chris@0 803 * @see drupalCreateUser()
Chris@0 804 */
Chris@0 805 protected function drupalLogin(AccountInterface $account) {
Chris@0 806 if ($this->loggedInUser) {
Chris@0 807 $this->drupalLogout();
Chris@0 808 }
Chris@0 809
Chris@0 810 $this->drupalGet('user/login');
Chris@0 811 $this->submitForm([
Chris@0 812 'name' => $account->getUsername(),
Chris@0 813 'pass' => $account->passRaw,
Chris@0 814 ], t('Log in'));
Chris@0 815
Chris@0 816 // @see BrowserTestBase::drupalUserIsLoggedIn()
Chris@0 817 $account->sessionId = $this->getSession()->getCookie($this->getSessionName());
Chris@0 818 $this->assertTrue($this->drupalUserIsLoggedIn($account), new FormattableMarkup('User %name successfully logged in.', ['%name' => $account->getAccountName()]));
Chris@0 819
Chris@0 820 $this->loggedInUser = $account;
Chris@0 821 $this->container->get('current_user')->setAccount($account);
Chris@0 822 }
Chris@0 823
Chris@0 824 /**
Chris@0 825 * Logs a user out of the Mink controlled browser and confirms.
Chris@0 826 *
Chris@0 827 * Confirms logout by checking the login page.
Chris@0 828 */
Chris@0 829 protected function drupalLogout() {
Chris@0 830 // Make a request to the logout page, and redirect to the user page, the
Chris@0 831 // idea being if you were properly logged out you should be seeing a login
Chris@0 832 // screen.
Chris@0 833 $assert_session = $this->assertSession();
Chris@0 834 $this->drupalGet('user/logout', ['query' => ['destination' => 'user']]);
Chris@0 835 $assert_session->fieldExists('name');
Chris@0 836 $assert_session->fieldExists('pass');
Chris@0 837
Chris@0 838 // @see BrowserTestBase::drupalUserIsLoggedIn()
Chris@0 839 unset($this->loggedInUser->sessionId);
Chris@0 840 $this->loggedInUser = FALSE;
Chris@0 841 $this->container->get('current_user')->setAccount(new AnonymousUserSession());
Chris@0 842 }
Chris@0 843
Chris@0 844 /**
Chris@0 845 * Fills and submits a form.
Chris@0 846 *
Chris@0 847 * @param array $edit
Chris@0 848 * Field data in an associative array. Changes the current input fields
Chris@0 849 * (where possible) to the values indicated.
Chris@0 850 *
Chris@0 851 * A checkbox can be set to TRUE to be checked and should be set to FALSE to
Chris@0 852 * be unchecked.
Chris@0 853 * @param string $submit
Chris@0 854 * Value of the submit button whose click is to be emulated. For example,
Chris@0 855 * 'Save'. The processing of the request depends on this value. For example,
Chris@0 856 * a form may have one button with the value 'Save' and another button with
Chris@0 857 * the value 'Delete', and execute different code depending on which one is
Chris@0 858 * clicked.
Chris@0 859 * @param string $form_html_id
Chris@0 860 * (optional) HTML ID of the form to be submitted. On some pages
Chris@0 861 * there are many identical forms, so just using the value of the submit
Chris@0 862 * button is not enough. For example: 'trigger-node-presave-assign-form'.
Chris@0 863 * Note that this is not the Drupal $form_id, but rather the HTML ID of the
Chris@0 864 * form, which is typically the same thing but with hyphens replacing the
Chris@0 865 * underscores.
Chris@0 866 */
Chris@0 867 protected function submitForm(array $edit, $submit, $form_html_id = NULL) {
Chris@0 868 $assert_session = $this->assertSession();
Chris@0 869
Chris@0 870 // Get the form.
Chris@0 871 if (isset($form_html_id)) {
Chris@0 872 $form = $assert_session->elementExists('xpath', "//form[@id='$form_html_id']");
Chris@0 873 $submit_button = $assert_session->buttonExists($submit, $form);
Chris@0 874 $action = $form->getAttribute('action');
Chris@0 875 }
Chris@0 876 else {
Chris@0 877 $submit_button = $assert_session->buttonExists($submit);
Chris@0 878 $form = $assert_session->elementExists('xpath', './ancestor::form', $submit_button);
Chris@0 879 $action = $form->getAttribute('action');
Chris@0 880 }
Chris@0 881
Chris@0 882 // Edit the form values.
Chris@0 883 foreach ($edit as $name => $value) {
Chris@0 884 $field = $assert_session->fieldExists($name, $form);
Chris@0 885
Chris@0 886 // Provide support for the values '1' and '0' for checkboxes instead of
Chris@0 887 // TRUE and FALSE.
Chris@0 888 // @todo Get rid of supporting 1/0 by converting all tests cases using
Chris@0 889 // this to boolean values.
Chris@0 890 $field_type = $field->getAttribute('type');
Chris@0 891 if ($field_type === 'checkbox') {
Chris@0 892 $value = (bool) $value;
Chris@0 893 }
Chris@0 894
Chris@0 895 $field->setValue($value);
Chris@0 896 }
Chris@0 897
Chris@0 898 // Submit form.
Chris@0 899 $this->prepareRequest();
Chris@0 900 $submit_button->press();
Chris@0 901
Chris@0 902 // Ensure that any changes to variables in the other thread are picked up.
Chris@0 903 $this->refreshVariables();
Chris@0 904
Chris@0 905 // Check if there are any meta refresh redirects (like Batch API pages).
Chris@0 906 if ($this->checkForMetaRefresh()) {
Chris@0 907 // We are finished with all meta refresh redirects, so reset the counter.
Chris@0 908 $this->metaRefreshCount = 0;
Chris@0 909 }
Chris@0 910
Chris@0 911 // Log only for JavascriptTestBase tests because for Goutte we log with
Chris@0 912 // ::getResponseLogHandler.
Chris@0 913 if ($this->htmlOutputEnabled && !($this->getSession()->getDriver() instanceof GoutteDriver)) {
Chris@0 914 $out = $this->getSession()->getPage()->getContent();
Chris@0 915 $html_output = 'POST request to: ' . $action .
Chris@0 916 '<hr />Ending URL: ' . $this->getSession()->getCurrentUrl();
Chris@0 917 $html_output .= '<hr />' . $out;
Chris@0 918 $html_output .= $this->getHtmlOutputHeaders();
Chris@0 919 $this->htmlOutput($html_output);
Chris@0 920 }
Chris@0 921
Chris@0 922 }
Chris@0 923
Chris@0 924 /**
Chris@0 925 * Executes a form submission.
Chris@0 926 *
Chris@0 927 * It will be done as usual POST request with Mink.
Chris@0 928 *
Chris@0 929 * @param \Drupal\Core\Url|string $path
Chris@0 930 * Location of the post form. Either a Drupal path or an absolute path or
Chris@0 931 * NULL to post to the current page. For multi-stage forms you can set the
Chris@0 932 * path to NULL and have it post to the last received page. Example:
Chris@0 933 *
Chris@0 934 * @code
Chris@0 935 * // First step in form.
Chris@0 936 * $edit = array(...);
Chris@0 937 * $this->drupalPostForm('some_url', $edit, 'Save');
Chris@0 938 *
Chris@0 939 * // Second step in form.
Chris@0 940 * $edit = array(...);
Chris@0 941 * $this->drupalPostForm(NULL, $edit, 'Save');
Chris@0 942 * @endcode
Chris@0 943 * @param array $edit
Chris@0 944 * Field data in an associative array. Changes the current input fields
Chris@0 945 * (where possible) to the values indicated.
Chris@0 946 *
Chris@0 947 * When working with form tests, the keys for an $edit element should match
Chris@0 948 * the 'name' parameter of the HTML of the form. For example, the 'body'
Chris@0 949 * field for a node has the following HTML:
Chris@0 950 * @code
Chris@0 951 * <textarea id="edit-body-und-0-value" class="text-full form-textarea
Chris@0 952 * resize-vertical" placeholder="" cols="60" rows="9"
Chris@0 953 * name="body[0][value]"></textarea>
Chris@0 954 * @endcode
Chris@0 955 * When testing this field using an $edit parameter, the code becomes:
Chris@0 956 * @code
Chris@0 957 * $edit["body[0][value]"] = 'My test value';
Chris@0 958 * @endcode
Chris@0 959 *
Chris@0 960 * A checkbox can be set to TRUE to be checked and should be set to FALSE to
Chris@0 961 * be unchecked. Multiple select fields can be tested using 'name[]' and
Chris@0 962 * setting each of the desired values in an array:
Chris@0 963 * @code
Chris@0 964 * $edit = array();
Chris@0 965 * $edit['name[]'] = array('value1', 'value2');
Chris@0 966 * @endcode
Chris@0 967 * @todo change $edit to disallow NULL as a value for Drupal 9.
Chris@0 968 * https://www.drupal.org/node/2802401
Chris@0 969 * @param string $submit
Chris@0 970 * Value of the submit button whose click is to be emulated. For example,
Chris@0 971 * 'Save'. The processing of the request depends on this value. For example,
Chris@0 972 * a form may have one button with the value 'Save' and another button with
Chris@0 973 * the value 'Delete', and execute different code depending on which one is
Chris@0 974 * clicked.
Chris@0 975 *
Chris@0 976 * This function can also be called to emulate an Ajax submission. In this
Chris@0 977 * case, this value needs to be an array with the following keys:
Chris@0 978 * - path: A path to submit the form values to for Ajax-specific processing.
Chris@0 979 * - triggering_element: If the value for the 'path' key is a generic Ajax
Chris@0 980 * processing path, this needs to be set to the name of the element. If
Chris@0 981 * the name doesn't identify the element uniquely, then this should
Chris@0 982 * instead be an array with a single key/value pair, corresponding to the
Chris@0 983 * element name and value. The \Drupal\Core\Form\FormAjaxResponseBuilder
Chris@0 984 * uses this to find the #ajax information for the element, including
Chris@0 985 * which specific callback to use for processing the request.
Chris@0 986 *
Chris@0 987 * This can also be set to NULL in order to emulate an Internet Explorer
Chris@0 988 * submission of a form with a single text field, and pressing ENTER in that
Chris@0 989 * textfield: under these conditions, no button information is added to the
Chris@0 990 * POST data.
Chris@0 991 * @param array $options
Chris@0 992 * Options to be forwarded to the url generator.
Chris@0 993 *
Chris@0 994 * @return string
Chris@0 995 * (deprecated) The response content after submit form. It is necessary for
Chris@0 996 * backwards compatibility and will be removed before Drupal 9.0. You should
Chris@0 997 * just use the webAssert object for your assertions.
Chris@0 998 */
Chris@0 999 protected function drupalPostForm($path, $edit, $submit, array $options = []) {
Chris@0 1000 if (is_object($submit)) {
Chris@0 1001 // Cast MarkupInterface objects to string.
Chris@0 1002 $submit = (string) $submit;
Chris@0 1003 }
Chris@0 1004 if ($edit === NULL) {
Chris@0 1005 $edit = [];
Chris@0 1006 }
Chris@0 1007 if (is_array($edit)) {
Chris@0 1008 $edit = $this->castSafeStrings($edit);
Chris@0 1009 }
Chris@0 1010
Chris@0 1011 if (isset($path)) {
Chris@0 1012 $this->drupalGet($path, $options);
Chris@0 1013 }
Chris@0 1014
Chris@0 1015 $this->submitForm($edit, $submit);
Chris@0 1016
Chris@0 1017 return $this->getSession()->getPage()->getContent();
Chris@0 1018 }
Chris@0 1019
Chris@0 1020 /**
Chris@0 1021 * Helper function to get the options of select field.
Chris@0 1022 *
Chris@0 1023 * @param \Behat\Mink\Element\NodeElement|string $select
Chris@0 1024 * Name, ID, or Label of select field to assert.
Chris@0 1025 * @param \Behat\Mink\Element\Element $container
Chris@0 1026 * (optional) Container element to check against. Defaults to current page.
Chris@0 1027 *
Chris@0 1028 * @return array
Chris@0 1029 * Associative array of option keys and values.
Chris@0 1030 */
Chris@0 1031 protected function getOptions($select, Element $container = NULL) {
Chris@0 1032 if (is_string($select)) {
Chris@0 1033 $select = $this->assertSession()->selectExists($select, $container);
Chris@0 1034 }
Chris@0 1035 $options = [];
Chris@0 1036 /* @var \Behat\Mink\Element\NodeElement $option */
Chris@0 1037 foreach ($select->findAll('xpath', '//option') as $option) {
Chris@0 1038 $label = $option->getText();
Chris@0 1039 $value = $option->getAttribute('value') ?: $label;
Chris@0 1040 $options[$value] = $label;
Chris@0 1041 }
Chris@0 1042 return $options;
Chris@0 1043 }
Chris@0 1044
Chris@0 1045 /**
Chris@0 1046 * Installs Drupal into the Simpletest site.
Chris@0 1047 */
Chris@0 1048 public function installDrupal() {
Chris@0 1049 $this->initUserSession();
Chris@0 1050 $this->prepareSettings();
Chris@0 1051 $this->doInstall();
Chris@0 1052 $this->initSettings();
Chris@0 1053 $container = $this->initKernel(\Drupal::request());
Chris@0 1054 $this->initConfig($container);
Chris@0 1055 $this->installModulesFromClassProperty($container);
Chris@0 1056 $this->rebuildAll();
Chris@0 1057 }
Chris@0 1058
Chris@0 1059 /**
Chris@0 1060 * Returns whether a given user account is logged in.
Chris@0 1061 *
Chris@0 1062 * @param \Drupal\Core\Session\AccountInterface $account
Chris@0 1063 * The user account object to check.
Chris@0 1064 *
Chris@0 1065 * @return bool
Chris@0 1066 * Return TRUE if the user is logged in, FALSE otherwise.
Chris@0 1067 */
Chris@0 1068 protected function drupalUserIsLoggedIn(AccountInterface $account) {
Chris@0 1069 $logged_in = FALSE;
Chris@0 1070
Chris@0 1071 if (isset($account->sessionId)) {
Chris@0 1072 $session_handler = $this->container->get('session_handler.storage');
Chris@0 1073 $logged_in = (bool) $session_handler->read($account->sessionId);
Chris@0 1074 }
Chris@0 1075
Chris@0 1076 return $logged_in;
Chris@0 1077 }
Chris@0 1078
Chris@0 1079 /**
Chris@0 1080 * Clicks the element with the given CSS selector.
Chris@0 1081 *
Chris@0 1082 * @param string $css_selector
Chris@0 1083 * The CSS selector identifying the element to click.
Chris@0 1084 */
Chris@0 1085 protected function click($css_selector) {
Chris@0 1086 $this->getSession()->getDriver()->click($this->cssSelectToXpath($css_selector));
Chris@0 1087 }
Chris@0 1088
Chris@0 1089 /**
Chris@0 1090 * Prevents serializing any properties.
Chris@0 1091 *
Chris@0 1092 * Browser tests are run in a separate process. To do this PHPUnit creates a
Chris@0 1093 * script to run the test. If it fails, the test result object will contain a
Chris@0 1094 * stack trace which includes the test object. It will attempt to serialize
Chris@0 1095 * it. Returning an empty array prevents it from serializing anything it
Chris@0 1096 * should not.
Chris@0 1097 *
Chris@0 1098 * @return array
Chris@0 1099 * An empty array.
Chris@0 1100 *
Chris@0 1101 * @see vendor/phpunit/phpunit/src/Util/PHP/Template/TestCaseMethod.tpl.dist
Chris@0 1102 */
Chris@0 1103 public function __sleep() {
Chris@0 1104 return [];
Chris@0 1105 }
Chris@0 1106
Chris@0 1107 /**
Chris@0 1108 * Logs a HTML output message in a text file.
Chris@0 1109 *
Chris@0 1110 * The link to the HTML output message will be printed by the results printer.
Chris@0 1111 *
Chris@0 1112 * @param string $message
Chris@0 1113 * The HTML output message to be stored.
Chris@0 1114 *
Chris@0 1115 * @see \Drupal\Tests\Listeners\VerbosePrinter::printResult()
Chris@0 1116 */
Chris@0 1117 protected function htmlOutput($message) {
Chris@0 1118 if (!$this->htmlOutputEnabled) {
Chris@0 1119 return;
Chris@0 1120 }
Chris@0 1121 $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 1122 $html_output_filename = $this->htmlOutputClassName . '-' . $this->htmlOutputCounter . '-' . $this->htmlOutputTestId . '.html';
Chris@0 1123 file_put_contents($this->htmlOutputDirectory . '/' . $html_output_filename, $message);
Chris@0 1124 file_put_contents($this->htmlOutputCounterStorage, $this->htmlOutputCounter++);
Chris@0 1125 file_put_contents($this->htmlOutputFile, file_create_url('sites/simpletest/browser_output/' . $html_output_filename) . "\n", FILE_APPEND);
Chris@0 1126 }
Chris@0 1127
Chris@0 1128 /**
Chris@0 1129 * Returns headers in HTML output format.
Chris@0 1130 *
Chris@0 1131 * @return string
Chris@0 1132 * HTML output headers.
Chris@0 1133 */
Chris@0 1134 protected function getHtmlOutputHeaders() {
Chris@0 1135 return $this->formatHtmlOutputHeaders($this->getSession()->getResponseHeaders());
Chris@0 1136 }
Chris@0 1137
Chris@0 1138 /**
Chris@0 1139 * Formats HTTP headers as string for HTML output logging.
Chris@0 1140 *
Chris@0 1141 * @param array[] $headers
Chris@0 1142 * Headers that should be formatted.
Chris@0 1143 *
Chris@0 1144 * @return string
Chris@0 1145 * The formatted HTML string.
Chris@0 1146 */
Chris@0 1147 protected function formatHtmlOutputHeaders(array $headers) {
Chris@0 1148 $flattened_headers = array_map(function ($header) {
Chris@0 1149 if (is_array($header)) {
Chris@0 1150 return implode(';', array_map('trim', $header));
Chris@0 1151 }
Chris@0 1152 else {
Chris@0 1153 return $header;
Chris@0 1154 }
Chris@0 1155 }, $headers);
Chris@0 1156 return '<hr />Headers: <pre>' . Html::escape(var_export($flattened_headers, TRUE)) . '</pre>';
Chris@0 1157 }
Chris@0 1158
Chris@0 1159 /**
Chris@0 1160 * Translates a CSS expression to its XPath equivalent.
Chris@0 1161 *
Chris@0 1162 * The search is relative to the root element (HTML tag normally) of the page.
Chris@0 1163 *
Chris@0 1164 * @param string $selector
Chris@0 1165 * CSS selector to use in the search.
Chris@0 1166 * @param bool $html
Chris@0 1167 * (optional) Enables HTML support. Disable it for XML documents.
Chris@0 1168 * @param string $prefix
Chris@0 1169 * (optional) The prefix for the XPath expression.
Chris@0 1170 *
Chris@0 1171 * @return string
Chris@0 1172 * The equivalent XPath of a CSS expression.
Chris@0 1173 */
Chris@0 1174 protected function cssSelectToXpath($selector, $html = TRUE, $prefix = 'descendant-or-self::') {
Chris@0 1175 return (new CssSelectorConverter($html))->toXPath($selector, $prefix);
Chris@0 1176 }
Chris@0 1177
Chris@0 1178 /**
Chris@0 1179 * Searches elements using a CSS selector in the raw content.
Chris@0 1180 *
Chris@0 1181 * The search is relative to the root element (HTML tag normally) of the page.
Chris@0 1182 *
Chris@0 1183 * @param string $selector
Chris@0 1184 * CSS selector to use in the search.
Chris@0 1185 *
Chris@0 1186 * @return \Behat\Mink\Element\NodeElement[]
Chris@0 1187 * The list of elements on the page that match the selector.
Chris@0 1188 */
Chris@0 1189 protected function cssSelect($selector) {
Chris@0 1190 return $this->getSession()->getPage()->findAll('css', $selector);
Chris@0 1191 }
Chris@0 1192
Chris@0 1193 /**
Chris@0 1194 * Follows a link by complete name.
Chris@0 1195 *
Chris@0 1196 * Will click the first link found with this link text.
Chris@0 1197 *
Chris@0 1198 * If the link is discovered and clicked, the test passes. Fail otherwise.
Chris@0 1199 *
Chris@0 1200 * @param string|\Drupal\Component\Render\MarkupInterface $label
Chris@0 1201 * Text between the anchor tags.
Chris@0 1202 * @param int $index
Chris@0 1203 * (optional) The index number for cases where multiple links have the same
Chris@0 1204 * text. Defaults to 0.
Chris@0 1205 */
Chris@0 1206 protected function clickLink($label, $index = 0) {
Chris@0 1207 $label = (string) $label;
Chris@0 1208 $links = $this->getSession()->getPage()->findAll('named', ['link', $label]);
Chris@0 1209 $this->assertArrayHasKey($index, $links, 'The link ' . $label . ' was not found on the page.');
Chris@0 1210 $links[$index]->click();
Chris@0 1211 }
Chris@0 1212
Chris@0 1213 /**
Chris@0 1214 * Retrieves the plain-text content from the current page.
Chris@0 1215 */
Chris@0 1216 protected function getTextContent() {
Chris@0 1217 return $this->getSession()->getPage()->getText();
Chris@0 1218 }
Chris@0 1219
Chris@0 1220 /**
Chris@0 1221 * Performs an xpath search on the contents of the internal browser.
Chris@0 1222 *
Chris@0 1223 * The search is relative to the root element (HTML tag normally) of the page.
Chris@0 1224 *
Chris@0 1225 * @param string $xpath
Chris@0 1226 * The xpath string to use in the search.
Chris@0 1227 * @param array $arguments
Chris@0 1228 * An array of arguments with keys in the form ':name' matching the
Chris@0 1229 * placeholders in the query. The values may be either strings or numeric
Chris@0 1230 * values.
Chris@0 1231 *
Chris@0 1232 * @return \Behat\Mink\Element\NodeElement[]
Chris@0 1233 * The list of elements matching the xpath expression.
Chris@0 1234 */
Chris@0 1235 protected function xpath($xpath, array $arguments = []) {
Chris@0 1236 $xpath = $this->assertSession()->buildXPathQuery($xpath, $arguments);
Chris@0 1237 return $this->getSession()->getPage()->findAll('xpath', $xpath);
Chris@0 1238 }
Chris@0 1239
Chris@0 1240 /**
Chris@0 1241 * Configuration accessor for tests. Returns non-overridden configuration.
Chris@0 1242 *
Chris@0 1243 * @param string $name
Chris@0 1244 * Configuration name.
Chris@0 1245 *
Chris@0 1246 * @return \Drupal\Core\Config\Config
Chris@0 1247 * The configuration object with original configuration data.
Chris@0 1248 */
Chris@0 1249 protected function config($name) {
Chris@0 1250 return $this->container->get('config.factory')->getEditable($name);
Chris@0 1251 }
Chris@0 1252
Chris@0 1253 /**
Chris@0 1254 * Returns all response headers.
Chris@0 1255 *
Chris@0 1256 * @return array
Chris@0 1257 * The HTTP headers values.
Chris@0 1258 *
Chris@0 1259 * @deprecated Scheduled for removal in Drupal 9.0.0.
Chris@0 1260 * Use $this->getSession()->getResponseHeaders() instead.
Chris@0 1261 */
Chris@0 1262 protected function drupalGetHeaders() {
Chris@0 1263 return $this->getSession()->getResponseHeaders();
Chris@0 1264 }
Chris@0 1265
Chris@0 1266 /**
Chris@0 1267 * Gets the value of an HTTP response header.
Chris@0 1268 *
Chris@0 1269 * If multiple requests were required to retrieve the page, only the headers
Chris@0 1270 * from the last request will be checked by default.
Chris@0 1271 *
Chris@0 1272 * @param string $name
Chris@0 1273 * The name of the header to retrieve. Names are case-insensitive (see RFC
Chris@0 1274 * 2616 section 4.2).
Chris@0 1275 *
Chris@0 1276 * @return string|null
Chris@0 1277 * The HTTP header value or NULL if not found.
Chris@0 1278 */
Chris@0 1279 protected function drupalGetHeader($name) {
Chris@0 1280 return $this->getSession()->getResponseHeader($name);
Chris@0 1281 }
Chris@0 1282
Chris@0 1283 /**
Chris@0 1284 * Get the current URL from the browser.
Chris@0 1285 *
Chris@0 1286 * @return string
Chris@0 1287 * The current URL.
Chris@0 1288 */
Chris@0 1289 protected function getUrl() {
Chris@0 1290 return $this->getSession()->getCurrentUrl();
Chris@0 1291 }
Chris@0 1292
Chris@0 1293 /**
Chris@0 1294 * Gets the JavaScript drupalSettings variable for the currently-loaded page.
Chris@0 1295 *
Chris@0 1296 * @return array
Chris@0 1297 * The JSON decoded drupalSettings value from the current page.
Chris@0 1298 */
Chris@0 1299 protected function getDrupalSettings() {
Chris@0 1300 $html = $this->getSession()->getPage()->getHtml();
Chris@0 1301 if (preg_match('@<script type="application/json" data-drupal-selector="drupal-settings-json">([^<]*)</script>@', $html, $matches)) {
Chris@0 1302 return Json::decode($matches[1]);
Chris@0 1303 }
Chris@0 1304 return [];
Chris@0 1305 }
Chris@0 1306
Chris@0 1307 /**
Chris@0 1308 * {@inheritdoc}
Chris@0 1309 */
Chris@0 1310 public static function assertEquals($expected, $actual, $message = '', $delta = 0.0, $maxDepth = 10, $canonicalize = FALSE, $ignoreCase = FALSE) {
Chris@0 1311 // Cast objects implementing MarkupInterface to string instead of
Chris@0 1312 // relying on PHP casting them to string depending on what they are being
Chris@0 1313 // comparing with.
Chris@0 1314 $expected = static::castSafeStrings($expected);
Chris@0 1315 $actual = static::castSafeStrings($actual);
Chris@0 1316 parent::assertEquals($expected, $actual, $message, $delta, $maxDepth, $canonicalize, $ignoreCase);
Chris@0 1317 }
Chris@0 1318
Chris@0 1319 /**
Chris@0 1320 * Retrieves the current calling line in the class under test.
Chris@0 1321 *
Chris@0 1322 * @return array
Chris@0 1323 * An associative array with keys 'file', 'line' and 'function'.
Chris@0 1324 */
Chris@0 1325 protected function getTestMethodCaller() {
Chris@0 1326 $backtrace = debug_backtrace();
Chris@0 1327 // Find the test class that has the test method.
Chris@0 1328 while ($caller = Error::getLastCaller($backtrace)) {
Chris@0 1329 if (isset($caller['class']) && $caller['class'] === get_class($this)) {
Chris@0 1330 break;
Chris@0 1331 }
Chris@0 1332 // If the test method is implemented by a test class's parent then the
Chris@0 1333 // class name of $this will not be part of the backtrace.
Chris@0 1334 // In that case we process the backtrace until the caller is not a
Chris@0 1335 // subclass of $this and return the previous caller.
Chris@0 1336 if (isset($last_caller) && (!isset($caller['class']) || !is_subclass_of($this, $caller['class']))) {
Chris@0 1337 // Return the last caller since that has to be the test class.
Chris@0 1338 $caller = $last_caller;
Chris@0 1339 break;
Chris@0 1340 }
Chris@0 1341 // Otherwise we have not reached our test class yet: save the last caller
Chris@0 1342 // and remove an element from to backtrace to process the next call.
Chris@0 1343 $last_caller = $caller;
Chris@0 1344 array_shift($backtrace);
Chris@0 1345 }
Chris@0 1346
Chris@0 1347 return $caller;
Chris@0 1348 }
Chris@0 1349
Chris@0 1350 /**
Chris@0 1351 * Transforms a nested array into a flat array suitable for drupalPostForm().
Chris@0 1352 *
Chris@0 1353 * @param array $values
Chris@0 1354 * A multi-dimensional form values array to convert.
Chris@0 1355 *
Chris@0 1356 * @return array
Chris@0 1357 * The flattened $edit array suitable for BrowserTestBase::drupalPostForm().
Chris@0 1358 */
Chris@0 1359 protected function translatePostValues(array $values) {
Chris@0 1360 $edit = [];
Chris@0 1361 // The easiest and most straightforward way to translate values suitable for
Chris@0 1362 // BrowserTestBase::drupalPostForm() is to actually build the POST data
Chris@0 1363 // string and convert the resulting key/value pairs back into a flat array.
Chris@0 1364 $query = http_build_query($values);
Chris@0 1365 foreach (explode('&', $query) as $item) {
Chris@0 1366 list($key, $value) = explode('=', $item);
Chris@0 1367 $edit[urldecode($key)] = urldecode($value);
Chris@0 1368 }
Chris@0 1369 return $edit;
Chris@0 1370 }
Chris@0 1371
Chris@0 1372 /**
Chris@0 1373 * Checks for meta refresh tag and if found call drupalGet() recursively.
Chris@0 1374 *
Chris@0 1375 * This function looks for the http-equiv attribute to be set to "Refresh" and
Chris@0 1376 * is case-insensitive.
Chris@0 1377 *
Chris@0 1378 * @return string|false
Chris@0 1379 * Either the new page content or FALSE.
Chris@0 1380 */
Chris@0 1381 protected function checkForMetaRefresh() {
Chris@0 1382 $refresh = $this->cssSelect('meta[http-equiv="Refresh"], meta[http-equiv="refresh"]');
Chris@0 1383 if (!empty($refresh) && (!isset($this->maximumMetaRefreshCount) || $this->metaRefreshCount < $this->maximumMetaRefreshCount)) {
Chris@0 1384 // Parse the content attribute of the meta tag for the format:
Chris@0 1385 // "[delay]: URL=[page_to_redirect_to]".
Chris@0 1386 if (preg_match('/\d+;\s*URL=(?<url>.*)/i', $refresh[0]->getAttribute('content'), $match)) {
Chris@0 1387 $this->metaRefreshCount++;
Chris@0 1388 return $this->drupalGet($this->getAbsoluteUrl(Html::decodeEntities($match['url'])));
Chris@0 1389 }
Chris@0 1390 }
Chris@0 1391 return FALSE;
Chris@0 1392 }
Chris@0 1393
Chris@0 1394 }