3 namespace Drupal\Tests;
5 use Behat\Mink\Driver\GoutteDriver;
6 use Behat\Mink\Element\Element;
8 use Behat\Mink\Selector\SelectorsHandler;
9 use Behat\Mink\Session;
10 use Drupal\Component\Serialization\Json;
11 use Drupal\Core\Database\Database;
12 use Drupal\Core\Test\FunctionalTestSetupTrait;
13 use Drupal\Core\Test\TestSetupTrait;
14 use Drupal\Core\Utility\Error;
15 use Drupal\FunctionalTests\AssertLegacyTrait;
16 use Drupal\Tests\block\Traits\BlockCreationTrait;
17 use Drupal\Tests\node\Traits\ContentTypeCreationTrait;
18 use Drupal\Tests\node\Traits\NodeCreationTrait;
19 use Drupal\Tests\user\Traits\UserCreationTrait;
20 use GuzzleHttp\Cookie\CookieJar;
21 use PHPUnit\Framework\TestCase;
22 use Psr\Http\Message\RequestInterface;
23 use Psr\Http\Message\ResponseInterface;
24 use Symfony\Component\CssSelector\CssSelectorConverter;
27 * Provides a test case for functional Drupal tests.
29 * Tests extending BrowserTestBase must exist in the
30 * Drupal\Tests\yourmodule\Functional namespace and live in the
31 * modules/yourmodule/tests/src/Functional directory.
33 * Tests extending this base class should only translate text when testing
34 * translation functionality. For example, avoid wrapping test text with t()
35 * or TranslatableMarkup().
39 abstract class BrowserTestBase extends TestCase {
41 use FunctionalTestSetupTrait;
43 FunctionalTestSetupTrait::refreshVariables insteadof UiHelperTrait;
46 use BlockCreationTrait {
47 placeBlock as drupalPlaceBlock;
49 use AssertLegacyTrait;
50 use RandomGeneratorTrait;
51 use NodeCreationTrait {
52 getNodeByTitle as drupalGetNodeByTitle;
53 createNode as drupalCreateNode;
55 use ContentTypeCreationTrait {
56 createContentType as drupalCreateContentType;
59 use TestRequirementsTrait;
60 use UserCreationTrait {
61 createRole as drupalCreateRole;
62 createUser as drupalCreateUser;
64 use XdebugRequestTrait;
65 use PhpunitCompatibilityTrait;
68 * The database prefix of this test run.
72 protected $databasePrefix;
75 * Time limit in seconds for the test.
79 protected $timeLimit = 500;
82 * The translation file directory for the test environment.
84 * This is set in BrowserTestBase::prepareEnvironment().
88 protected $translationFilesDirectory;
91 * The config importer that can be used in a test.
93 * @var \Drupal\Core\Config\ConfigImporter
95 protected $configImporter;
100 * The test runner will merge the $modules lists from this class, the class
101 * it extends, and so on up the class hierarchy. It is not necessary to
102 * include modules in your list that a parent class has already declared.
106 * @see \Drupal\Tests\BrowserTestBase::installDrupal()
108 protected static $modules = [];
111 * The profile to install as a basis for testing.
115 protected $profile = 'testing';
118 * An array of custom translations suitable for drupal_rewrite_settings().
122 protected $customTranslations;
125 * Mink class for the default driver to use.
127 * Should be a fully-qualified class name that implements
128 * Behat\Mink\Driver\DriverInterface.
130 * Value can be overridden using the environment variable MINK_DRIVER_CLASS.
134 protected $minkDefaultDriverClass = GoutteDriver::class;
137 * Mink default driver params.
139 * If it's an array its contents are used as constructor params when default
140 * Mink driver class is instantiated.
142 * Can be overridden using the environment variable MINK_DRIVER_ARGS. In this
143 * case that variable should be a JSON array, for example:
144 * '["firefox", null, "http://localhost:4444/wd/hub"]'.
149 protected $minkDefaultDriverArgs;
152 * Mink session manager.
154 * This will not be initialized if there was an error during the test setup.
156 * @var \Behat\Mink\Mink|null
163 * Browser tests are run in separate processes to prevent collisions between
164 * code that may be loaded by tests.
166 protected $runTestInSeparateProcess = TRUE;
171 protected $preserveGlobalState = FALSE;
181 * The original array of shutdown function callbacks.
185 protected $originalShutdownCallbacks = [];
195 * The original container.
197 * Move this to \Drupal\Core\Test\FunctionalTestSetupTrait once TestBase no
198 * longer provides the same value.
200 * @var \Symfony\Component\DependencyInjection\ContainerInterface
202 protected $originalContainer;
207 public function __construct($name = NULL, array $data = [], $dataName = '') {
208 parent::__construct($name, $data, $dataName);
210 $this->root = dirname(dirname(substr(__DIR__, 0, -strlen(__NAMESPACE__))));
214 * Initializes Mink sessions.
216 protected function initMink() {
217 $driver = $this->getDefaultDriverInstance();
219 if ($driver instanceof GoutteDriver) {
220 // Turn off curl timeout. Having a timeout is not a problem in a normal
221 // test running, but it is a problem when debugging. Also, disable SSL
222 // peer verification so that testing under HTTPS always works.
223 /** @var \GuzzleHttp\Client $client */
224 $client = $this->container->get('http_client_factory')->fromOptions([
229 // Inject a Guzzle middleware to generate debug output for every request
230 // performed in the test.
231 $handler_stack = $client->getConfig('handler');
232 $handler_stack->push($this->getResponseLogHandler());
234 $driver->getClient()->setClient($client);
237 $selectors_handler = new SelectorsHandler([
238 'hidden_field_selector' => new HiddenFieldSelector(),
240 $session = new Session($driver, $selectors_handler);
241 $cookies = $this->extractCookiesFromRequest(\Drupal::request());
242 foreach ($cookies as $cookie_name => $values) {
243 foreach ($values as $value) {
244 $session->setCookie($cookie_name, $value);
247 $this->mink = new Mink();
248 $this->mink->registerSession('default', $session);
249 $this->mink->setDefaultSessionName('default');
250 $this->registerSessions();
252 $this->initFrontPage();
258 * Visits the front page when initializing Mink.
260 * According to the W3C WebDriver specification a cookie can only be set if
261 * the cookie domain is equal to the domain of the active document. When the
262 * browser starts up the active document is not our domain but 'about:blank'
263 * or similar. To be able to set our User-Agent and Xdebug cookies at the
264 * start of the test we now do a request to the front page so the active
265 * document matches the domain.
267 * @see https://w3c.github.io/webdriver/webdriver-spec.html#add-cookie
268 * @see https://www.w3.org/Bugs/Public/show_bug.cgi?id=20975
270 protected function initFrontPage() {
271 $session = $this->getSession();
272 $session->visit($this->baseUrl);
276 * Gets an instance of the default Mink driver.
278 * @return Behat\Mink\Driver\DriverInterface
279 * Instance of default Mink driver.
281 * @throws \InvalidArgumentException
282 * When provided default Mink driver class can't be instantiated.
284 protected function getDefaultDriverInstance() {
285 // Get default driver params from environment if available.
286 if ($arg_json = $this->getMinkDriverArgs()) {
287 $this->minkDefaultDriverArgs = json_decode($arg_json, TRUE);
290 // Get and check default driver class from environment if available.
291 if ($minkDriverClass = getenv('MINK_DRIVER_CLASS')) {
292 if (class_exists($minkDriverClass)) {
293 $this->minkDefaultDriverClass = $minkDriverClass;
296 throw new \InvalidArgumentException("Can't instantiate provided $minkDriverClass class by environment as default driver class.");
300 if (is_array($this->minkDefaultDriverArgs)) {
301 // Use ReflectionClass to instantiate class with received params.
302 $reflector = new \ReflectionClass($this->minkDefaultDriverClass);
303 $driver = $reflector->newInstanceArgs($this->minkDefaultDriverArgs);
306 $driver = new $this->minkDefaultDriverClass();
312 * Get the Mink driver args from an environment variable, if it is set. Can
313 * be overridden in a derived class so it is possible to use a different
314 * value for a subset of tests, e.g. the JavaScript tests.
316 * @return string|false
317 * The JSON-encoded argument string. False if it is not set.
319 protected function getMinkDriverArgs() {
320 return getenv('MINK_DRIVER_ARGS');
324 * Provides a Guzzle middleware handler to log every response received.
327 * The callable handler that will do the logging.
329 protected function getResponseLogHandler() {
330 return function (callable $handler) {
331 return function (RequestInterface $request, array $options) use ($handler) {
332 return $handler($request, $options)
333 ->then(function (ResponseInterface $response) use ($request) {
334 if ($this->htmlOutputEnabled) {
336 $caller = $this->getTestMethodCaller();
337 $html_output = 'Called from ' . $caller['function'] . ' line ' . $caller['line'];
338 $html_output .= '<hr />' . $request->getMethod() . ' request to: ' . $request->getUri();
340 // On redirect responses (status code starting with '3') we need
341 // to remove the meta tag that would do a browser refresh. We
342 // don't want to redirect developers away when they look at the
343 // debug output file in their browser.
344 $body = $response->getBody();
345 $status_code = (string) $response->getStatusCode();
346 if ($status_code[0] === '3') {
347 $body = preg_replace('#<meta http-equiv="refresh" content=.+/>#', '', $body, 1);
349 $html_output .= '<hr />' . $body;
350 $html_output .= $this->formatHtmlOutputHeaders($response->getHeaders());
352 $this->htmlOutput($html_output);
361 * Registers additional Mink sessions.
363 * Tests wishing to use a different driver or change the default driver should
364 * override this method.
367 * // Register a new session that uses the MinkPonyDriver.
368 * $pony = new MinkPonyDriver();
369 * $session = new Session($pony);
370 * $this->mink->registerSession('pony', $session);
373 protected function registerSessions() {}
378 protected function setUp() {
379 // Installing Drupal creates 1000s of objects. Garbage collection of these
380 // objects is expensive. This appears to be causing random segmentation
381 // faults in PHP 5.x due to https://bugs.php.net/bug.php?id=72286. Once
382 // Drupal is installed is rebuilt, garbage collection is re-enabled.
383 $disable_gc = version_compare(PHP_VERSION, '7', '<') && gc_enabled();
390 $this->setupBaseUrl();
392 // Install Drupal test site.
393 $this->prepareEnvironment();
394 $this->installDrupal();
399 // Set up the browser test output file.
400 $this->initBrowserOutputFile();
401 // If garbage collection was disabled prior to rebuilding container,
407 // Ensure that the test is not marked as risky because of no assertions. In
408 // PHPUnit 6 tests that only make assertions using $this->assertSession()
409 // can be marked as risky.
410 $this->addToAssertionCount(1);
414 * Ensures test files are deletable within file_unmanaged_delete_recursive().
416 * Some tests chmod generated files to be read only. During
417 * BrowserTestBase::cleanupEnvironment() and other cleanup operations,
418 * these files need to get deleted too.
420 * @param string $path
423 public static function filePreDeleteCallback($path) {
424 // When the webserver runs with the same system user as phpunit, we can
425 // make read-only files writable again. If not, chmod will fail while the
426 // file deletion still works if file permissions have been configured
427 // correctly. Thus, we ignore any problems while running chmod.
432 * Clean up the Simpletest environment.
434 protected function cleanupEnvironment() {
435 // Remove all prefixed tables.
436 $original_connection_info = Database::getConnectionInfo('simpletest_original_default');
437 $original_prefix = $original_connection_info['default']['prefix']['default'];
438 $test_connection_info = Database::getConnectionInfo('default');
439 $test_prefix = $test_connection_info['default']['prefix']['default'];
440 if ($original_prefix != $test_prefix) {
441 $tables = Database::getConnection()->schema()->findTables('%');
442 foreach ($tables as $table) {
443 if (Database::getConnection()->schema()->dropTable($table)) {
444 unset($tables[$table]);
449 // Delete test site directory.
450 file_unmanaged_delete_recursive($this->siteDirectory, [$this, 'filePreDeleteCallback']);
456 protected function tearDown() {
459 // Destroy the testing kernel.
460 if (isset($this->kernel)) {
461 $this->cleanupEnvironment();
462 $this->kernel->shutdown();
465 // Ensure that internal logged in variable is reset.
466 $this->loggedInUser = FALSE;
469 $this->mink->stopSessions();
472 // Restore original shutdown callbacks.
473 if (function_exists('drupal_register_shutdown_function')) {
474 $callbacks = &drupal_register_shutdown_function();
475 $callbacks = $this->originalShutdownCallbacks;
480 * Returns Mink session.
482 * @param string $name
483 * (optional) Name of the session. Defaults to the active session.
485 * @return \Behat\Mink\Session
486 * The active Mink session object.
488 public function getSession($name = NULL) {
489 return $this->mink->getSession($name);
493 * Get session cookies from current session.
495 * @return \GuzzleHttp\Cookie\CookieJar
496 * A cookie jar with the current session.
498 protected function getSessionCookies() {
499 $domain = parse_url($this->getUrl(), PHP_URL_HOST);
500 $session_id = $this->getSession()->getCookie($this->getSessionName());
501 $cookies = CookieJar::fromArray([$this->getSessionName() => $session_id], $domain);
507 * Obtain the HTTP client for the system under test.
509 * Use this method for arbitrary HTTP requests to the site under test. For
510 * most tests, you should not get the HTTP client and instead use navigation
511 * methods such as drupalGet() and clickLink() in order to benefit from
514 * Subclasses which substitute a different Mink driver should override this
515 * method and provide a Guzzle client if the Mink driver provides one.
517 * @return \GuzzleHttp\ClientInterface
518 * The client with BrowserTestBase configuration.
520 * @throws \RuntimeException
521 * If the Mink driver does not support a Guzzle HTTP client, throw an
524 protected function getHttpClient() {
525 /* @var $mink_driver \Behat\Mink\Driver\DriverInterface */
526 $mink_driver = $this->getSession()->getDriver();
527 if ($mink_driver instanceof GoutteDriver) {
528 return $mink_driver->getClient()->getClient();
530 throw new \RuntimeException('The Mink client type ' . get_class($mink_driver) . ' does not support getHttpClient().');
534 * Helper function to get the options of select field.
536 * @param \Behat\Mink\Element\NodeElement|string $select
537 * Name, ID, or Label of select field to assert.
538 * @param \Behat\Mink\Element\Element $container
539 * (optional) Container element to check against. Defaults to current page.
542 * Associative array of option keys and values.
544 protected function getOptions($select, Element $container = NULL) {
545 if (is_string($select)) {
546 $select = $this->assertSession()->selectExists($select, $container);
549 /* @var \Behat\Mink\Element\NodeElement $option */
550 foreach ($select->findAll('xpath', '//option') as $option) {
551 $label = $option->getText();
552 $value = $option->getAttribute('value') ?: $label;
553 $options[$value] = $label;
559 * Installs Drupal into the Simpletest site.
561 public function installDrupal() {
562 $this->initUserSession();
563 $this->prepareSettings();
565 $this->initSettings();
566 $container = $this->initKernel(\Drupal::request());
567 $this->initConfig($container);
568 $this->installModulesFromClassProperty($container);
573 * Prevents serializing any properties.
575 * Browser tests are run in a separate process. To do this PHPUnit creates a
576 * script to run the test. If it fails, the test result object will contain a
577 * stack trace which includes the test object. It will attempt to serialize
578 * it. Returning an empty array prevents it from serializing anything it
584 * @see vendor/phpunit/phpunit/src/Util/PHP/Template/TestCaseMethod.tpl.dist
586 public function __sleep() {
591 * Translates a CSS expression to its XPath equivalent.
593 * The search is relative to the root element (HTML tag normally) of the page.
595 * @param string $selector
596 * CSS selector to use in the search.
598 * (optional) Enables HTML support. Disable it for XML documents.
599 * @param string $prefix
600 * (optional) The prefix for the XPath expression.
603 * The equivalent XPath of a CSS expression.
605 protected function cssSelectToXpath($selector, $html = TRUE, $prefix = 'descendant-or-self::') {
606 return (new CssSelectorConverter($html))->toXPath($selector, $prefix);
610 * Performs an xpath search on the contents of the internal browser.
612 * The search is relative to the root element (HTML tag normally) of the page.
614 * @param string $xpath
615 * The xpath string to use in the search.
616 * @param array $arguments
617 * An array of arguments with keys in the form ':name' matching the
618 * placeholders in the query. The values may be either strings or numeric
621 * @return \Behat\Mink\Element\NodeElement[]
622 * The list of elements matching the xpath expression.
624 protected function xpath($xpath, array $arguments = []) {
625 $xpath = $this->assertSession()->buildXPathQuery($xpath, $arguments);
626 return $this->getSession()->getPage()->findAll('xpath', $xpath);
630 * Configuration accessor for tests. Returns non-overridden configuration.
632 * @param string $name
633 * Configuration name.
635 * @return \Drupal\Core\Config\Config
636 * The configuration object with original configuration data.
638 protected function config($name) {
639 return $this->container->get('config.factory')->getEditable($name);
643 * Returns all response headers.
646 * The HTTP headers values.
648 * @deprecated Scheduled for removal in Drupal 9.0.0.
649 * Use $this->getSession()->getResponseHeaders() instead.
651 protected function drupalGetHeaders() {
652 return $this->getSession()->getResponseHeaders();
656 * Gets the value of an HTTP response header.
658 * If multiple requests were required to retrieve the page, only the headers
659 * from the last request will be checked by default.
661 * @param string $name
662 * The name of the header to retrieve. Names are case-insensitive (see RFC
665 * @return string|null
666 * The HTTP header value or NULL if not found.
668 protected function drupalGetHeader($name) {
669 return $this->getSession()->getResponseHeader($name);
673 * Gets the JavaScript drupalSettings variable for the currently-loaded page.
676 * The JSON decoded drupalSettings value from the current page.
678 protected function getDrupalSettings() {
679 $html = $this->getSession()->getPage()->getHtml();
680 if (preg_match('@<script type="application/json" data-drupal-selector="drupal-settings-json">([^<]*)</script>@', $html, $matches)) {
681 return Json::decode($matches[1]);
689 public static function assertEquals($expected, $actual, $message = '', $delta = 0.0, $maxDepth = 10, $canonicalize = FALSE, $ignoreCase = FALSE) {
690 // Cast objects implementing MarkupInterface to string instead of
691 // relying on PHP casting them to string depending on what they are being
693 $expected = static::castSafeStrings($expected);
694 $actual = static::castSafeStrings($actual);
695 parent::assertEquals($expected, $actual, $message, $delta, $maxDepth, $canonicalize, $ignoreCase);
699 * Retrieves the current calling line in the class under test.
702 * An associative array with keys 'file', 'line' and 'function'.
704 protected function getTestMethodCaller() {
705 $backtrace = debug_backtrace();
706 // Find the test class that has the test method.
707 while ($caller = Error::getLastCaller($backtrace)) {
708 if (isset($caller['class']) && $caller['class'] === get_class($this)) {
711 // If the test method is implemented by a test class's parent then the
712 // class name of $this will not be part of the backtrace.
713 // In that case we process the backtrace until the caller is not a
714 // subclass of $this and return the previous caller.
715 if (isset($last_caller) && (!isset($caller['class']) || !is_subclass_of($this, $caller['class']))) {
716 // Return the last caller since that has to be the test class.
717 $caller = $last_caller;
720 // Otherwise we have not reached our test class yet: save the last caller
721 // and remove an element from to backtrace to process the next call.
722 $last_caller = $caller;
723 array_shift($backtrace);
730 * Transforms a nested array into a flat array suitable for drupalPostForm().
732 * @param array $values
733 * A multi-dimensional form values array to convert.
736 * The flattened $edit array suitable for BrowserTestBase::drupalPostForm().
738 protected function translatePostValues(array $values) {
740 // The easiest and most straightforward way to translate values suitable for
741 // BrowserTestBase::drupalPostForm() is to actually build the POST data
742 // string and convert the resulting key/value pairs back into a flat array.
743 $query = http_build_query($values);
744 foreach (explode('&', $query) as $item) {
745 list($key, $value) = explode('=', $item);
746 $edit[urldecode($key)] = urldecode($value);