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\Render\FormattableMarkup;
11 use Drupal\Component\Serialization\Json;
12 use Drupal\Component\Utility\Html;
13 use Drupal\Component\Utility\UrlHelper;
14 use Drupal\Core\Database\Database;
15 use Drupal\Core\Session\AccountInterface;
16 use Drupal\Core\Session\AnonymousUserSession;
17 use Drupal\Core\Test\FunctionalTestSetupTrait;
18 use Drupal\Core\Test\TestSetupTrait;
20 use Drupal\Core\Utility\Error;
21 use Drupal\FunctionalTests\AssertLegacyTrait;
22 use Drupal\Tests\block\Traits\BlockCreationTrait;
23 use Drupal\Tests\node\Traits\ContentTypeCreationTrait;
24 use Drupal\Tests\node\Traits\NodeCreationTrait;
25 use Drupal\Tests\user\Traits\UserCreationTrait;
26 use PHPUnit\Framework\TestCase;
27 use Psr\Http\Message\RequestInterface;
28 use Psr\Http\Message\ResponseInterface;
29 use Symfony\Component\CssSelector\CssSelectorConverter;
32 * Provides a test case for functional Drupal tests.
34 * Tests extending BrowserTestBase must exist in the
35 * Drupal\Tests\yourmodule\Functional namespace and live in the
36 * modules/yourmodule/tests/src/Functional directory.
38 * Tests extending this base class should only translate text when testing
39 * translation functionality. For example, avoid wrapping test text with t()
40 * or TranslatableMarkup().
44 abstract class BrowserTestBase extends TestCase {
46 use FunctionalTestSetupTrait;
48 use AssertHelperTrait;
49 use BlockCreationTrait {
50 placeBlock as drupalPlaceBlock;
52 use AssertLegacyTrait;
53 use RandomGeneratorTrait;
55 use NodeCreationTrait {
56 getNodeByTitle as drupalGetNodeByTitle;
57 createNode as drupalCreateNode;
59 use ContentTypeCreationTrait {
60 createContentType as drupalCreateContentType;
63 use TestRequirementsTrait;
64 use UserCreationTrait {
65 createRole as drupalCreateRole;
66 createUser as drupalCreateUser;
68 use XdebugRequestTrait;
69 use PhpunitCompatibilityTrait;
72 * The database prefix of this test run.
76 protected $databasePrefix;
79 * Time limit in seconds for the test.
83 protected $timeLimit = 500;
86 * The translation file directory for the test environment.
88 * This is set in BrowserTestBase::prepareEnvironment().
92 protected $translationFilesDirectory;
95 * The config importer that can be used in a test.
97 * @var \Drupal\Core\Config\ConfigImporter
99 protected $configImporter;
104 * The test runner will merge the $modules lists from this class, the class
105 * it extends, and so on up the class hierarchy. It is not necessary to
106 * include modules in your list that a parent class has already declared.
110 * @see \Drupal\Tests\BrowserTestBase::installDrupal()
112 protected static $modules = [];
115 * The profile to install as a basis for testing.
119 protected $profile = 'testing';
122 * The current user logged in using the Mink controlled browser.
124 * @var \Drupal\user\UserInterface
126 protected $loggedInUser = FALSE;
129 * An array of custom translations suitable for drupal_rewrite_settings().
133 protected $customTranslations;
136 * Mink class for the default driver to use.
138 * Shoud be a fully qualified class name that implements
139 * Behat\Mink\Driver\DriverInterface.
141 * Value can be overridden using the environment variable MINK_DRIVER_CLASS.
145 protected $minkDefaultDriverClass = GoutteDriver::class;
148 * Mink default driver params.
150 * If it's an array its contents are used as constructor params when default
151 * Mink driver class is instantiated.
153 * Can be overridden using the environment variable MINK_DRIVER_ARGS. In this
154 * case that variable should be a JSON array, for example:
155 * '["firefox", null, "http://localhost:4444/wd/hub"]'.
160 protected $minkDefaultDriverArgs;
163 * Mink session manager.
165 * This will not be initialized if there was an error during the test setup.
167 * @var \Behat\Mink\Mink|null
174 * Browser tests are run in separate processes to prevent collisions between
175 * code that may be loaded by tests.
177 protected $runTestInSeparateProcess = TRUE;
182 protected $preserveGlobalState = FALSE;
185 * Class name for HTML output logging.
189 protected $htmlOutputClassName;
192 * Directory name for HTML output logging.
196 protected $htmlOutputDirectory;
199 * Counter storage for HTML output logging.
203 protected $htmlOutputCounterStorage;
206 * Counter for HTML output logging.
210 protected $htmlOutputCounter = 1;
213 * HTML output output enabled.
217 protected $htmlOutputEnabled = FALSE;
220 * The file name to write the list of URLs to.
222 * This file is read by the PHPUnit result printer.
226 * @see \Drupal\Tests\Listeners\HtmlOutputPrinter
228 protected $htmlOutputFile;
231 * HTML output test ID.
235 protected $htmlOutputTestId;
245 * The original array of shutdown function callbacks.
249 protected $originalShutdownCallbacks = [];
252 * The number of meta refresh redirects to follow, or NULL if unlimited.
256 protected $maximumMetaRefreshCount = NULL;
259 * The number of meta refresh redirects followed during ::drupalGet().
263 protected $metaRefreshCount = 0;
273 * The original container.
275 * Move this to \Drupal\Core\Test\FunctionalTestSetupTrait once TestBase no
276 * longer provides the same value.
278 * @var \Symfony\Component\DependencyInjection\ContainerInterface
280 protected $originalContainer;
285 public function __construct($name = NULL, array $data = [], $dataName = '') {
286 parent::__construct($name, $data, $dataName);
288 $this->root = dirname(dirname(substr(__DIR__, 0, -strlen(__NAMESPACE__))));
292 * Initializes Mink sessions.
294 protected function initMink() {
295 $driver = $this->getDefaultDriverInstance();
297 if ($driver instanceof GoutteDriver) {
298 // Turn off curl timeout. Having a timeout is not a problem in a normal
299 // test running, but it is a problem when debugging. Also, disable SSL
300 // peer verification so that testing under HTTPS always works.
301 /** @var \GuzzleHttp\Client $client */
302 $client = $this->container->get('http_client_factory')->fromOptions([
307 // Inject a Guzzle middleware to generate debug output for every request
308 // performed in the test.
309 $handler_stack = $client->getConfig('handler');
310 $handler_stack->push($this->getResponseLogHandler());
312 $driver->getClient()->setClient($client);
315 $selectors_handler = new SelectorsHandler([
316 'hidden_field_selector' => new HiddenFieldSelector()
318 $session = new Session($driver, $selectors_handler);
319 $this->mink = new Mink();
320 $this->mink->registerSession('default', $session);
321 $this->mink->setDefaultSessionName('default');
322 $this->registerSessions();
324 // According to the W3C WebDriver specification a cookie can only be set if
325 // the cookie domain is equal to the domain of the active document. When the
326 // browser starts up the active document is not our domain but 'about:blank'
327 // or similar. To be able to set our User-Agent and Xdebug cookies at the
328 // start of the test we now do a request to the front page so the active
329 // document matches the domain.
330 // @see https://w3c.github.io/webdriver/webdriver-spec.html#add-cookie
331 // @see https://www.w3.org/Bugs/Public/show_bug.cgi?id=20975
332 $session = $this->getSession();
333 $session->visit($this->baseUrl);
339 * Gets an instance of the default Mink driver.
341 * @return Behat\Mink\Driver\DriverInterface
342 * Instance of default Mink driver.
344 * @throws \InvalidArgumentException
345 * When provided default Mink driver class can't be instantiated.
347 protected function getDefaultDriverInstance() {
348 // Get default driver params from environment if available.
349 if ($arg_json = $this->getMinkDriverArgs()) {
350 $this->minkDefaultDriverArgs = json_decode($arg_json, TRUE);
353 // Get and check default driver class from environment if available.
354 if ($minkDriverClass = getenv('MINK_DRIVER_CLASS')) {
355 if (class_exists($minkDriverClass)) {
356 $this->minkDefaultDriverClass = $minkDriverClass;
359 throw new \InvalidArgumentException("Can't instantiate provided $minkDriverClass class by environment as default driver class.");
363 if (is_array($this->minkDefaultDriverArgs)) {
364 // Use ReflectionClass to instantiate class with received params.
365 $reflector = new \ReflectionClass($this->minkDefaultDriverClass);
366 $driver = $reflector->newInstanceArgs($this->minkDefaultDriverArgs);
369 $driver = new $this->minkDefaultDriverClass();
375 * Creates the directory to store browser output.
377 * Creates the directory to store browser output in if a file to write
378 * URLs to has been created by \Drupal\Tests\Listeners\HtmlOutputPrinter.
380 protected function initBrowserOutputFile() {
381 $browser_output_file = getenv('BROWSERTEST_OUTPUT_FILE');
382 $this->htmlOutputEnabled = is_file($browser_output_file);
383 if ($this->htmlOutputEnabled) {
384 $this->htmlOutputFile = $browser_output_file;
385 $this->htmlOutputClassName = str_replace("\\", "_", get_called_class());
386 $this->htmlOutputDirectory = DRUPAL_ROOT . '/sites/simpletest/browser_output';
387 if (file_prepare_directory($this->htmlOutputDirectory, FILE_CREATE_DIRECTORY) && !file_exists($this->htmlOutputDirectory . '/.htaccess')) {
388 file_put_contents($this->htmlOutputDirectory . '/.htaccess', "<IfModule mod_expires.c>\nExpiresActive Off\n</IfModule>\n");
390 $this->htmlOutputCounterStorage = $this->htmlOutputDirectory . '/' . $this->htmlOutputClassName . '.counter';
391 $this->htmlOutputTestId = str_replace('sites/simpletest/', '', $this->siteDirectory);
392 if (is_file($this->htmlOutputCounterStorage)) {
393 $this->htmlOutputCounter = max(1, (int) file_get_contents($this->htmlOutputCounterStorage)) + 1;
399 * Get the Mink driver args from an environment variable, if it is set. Can
400 * be overridden in a derived class so it is possible to use a different
401 * value for a subset of tests, e.g. the JavaScript tests.
403 * @return string|false
404 * The JSON-encoded argument string. False if it is not set.
406 protected function getMinkDriverArgs() {
407 return getenv('MINK_DRIVER_ARGS');
411 * Provides a Guzzle middleware handler to log every response received.
414 * The callable handler that will do the logging.
416 protected function getResponseLogHandler() {
417 return function (callable $handler) {
418 return function (RequestInterface $request, array $options) use ($handler) {
419 return $handler($request, $options)
420 ->then(function (ResponseInterface $response) use ($request) {
421 if ($this->htmlOutputEnabled) {
423 $caller = $this->getTestMethodCaller();
424 $html_output = 'Called from ' . $caller['function'] . ' line ' . $caller['line'];
425 $html_output .= '<hr />' . $request->getMethod() . ' request to: ' . $request->getUri();
427 // On redirect responses (status code starting with '3') we need
428 // to remove the meta tag that would do a browser refresh. We
429 // don't want to redirect developers away when they look at the
430 // debug output file in their browser.
431 $body = $response->getBody();
432 $status_code = (string) $response->getStatusCode();
433 if ($status_code[0] === '3') {
434 $body = preg_replace('#<meta http-equiv="refresh" content=.+/>#', '', $body, 1);
436 $html_output .= '<hr />' . $body;
437 $html_output .= $this->formatHtmlOutputHeaders($response->getHeaders());
439 $this->htmlOutput($html_output);
448 * Registers additional Mink sessions.
450 * Tests wishing to use a different driver or change the default driver should
451 * override this method.
454 * // Register a new session that uses the MinkPonyDriver.
455 * $pony = new MinkPonyDriver();
456 * $session = new Session($pony);
457 * $this->mink->registerSession('pony', $session);
460 protected function registerSessions() {}
465 protected function setUp() {
466 // Installing Drupal creates 1000s of objects. Garbage collection of these
467 // objects is expensive. This appears to be causing random segmentation
468 // faults in PHP 5.x due to https://bugs.php.net/bug.php?id=72286. Once
469 // Drupal is installed is rebuilt, garbage collection is re-enabled.
470 $disable_gc = version_compare(PHP_VERSION, '7', '<') && gc_enabled();
477 $this->setupBaseUrl();
479 // Install Drupal test site.
480 $this->prepareEnvironment();
481 $this->installDrupal();
484 $session = $this->initMink();
486 $cookies = $this->extractCookiesFromRequest(\Drupal::request());
487 foreach ($cookies as $cookie_name => $values) {
488 foreach ($values as $value) {
489 $session->setCookie($cookie_name, $value);
493 // Set up the browser test output file.
494 $this->initBrowserOutputFile();
495 // If garbage collection was disabled prior to rebuilding container,
501 // Ensure that the test is not marked as risky because of no assertions. In
502 // PHPUnit 6 tests that only make assertions using $this->assertSession()
503 // can be marked as risky.
504 $this->addToAssertionCount(1);
508 * Ensures test files are deletable within file_unmanaged_delete_recursive().
510 * Some tests chmod generated files to be read only. During
511 * BrowserTestBase::cleanupEnvironment() and other cleanup operations,
512 * these files need to get deleted too.
514 * @param string $path
517 public static function filePreDeleteCallback($path) {
518 // When the webserver runs with the same system user as phpunit, we can
519 // make read-only files writable again. If not, chmod will fail while the
520 // file deletion still works if file permissions have been configured
521 // correctly. Thus, we ignore any problems while running chmod.
526 * Clean up the Simpletest environment.
528 protected function cleanupEnvironment() {
529 // Remove all prefixed tables.
530 $original_connection_info = Database::getConnectionInfo('simpletest_original_default');
531 $original_prefix = $original_connection_info['default']['prefix']['default'];
532 $test_connection_info = Database::getConnectionInfo('default');
533 $test_prefix = $test_connection_info['default']['prefix']['default'];
534 if ($original_prefix != $test_prefix) {
535 $tables = Database::getConnection()->schema()->findTables('%');
536 foreach ($tables as $table) {
537 if (Database::getConnection()->schema()->dropTable($table)) {
538 unset($tables[$table]);
543 // Delete test site directory.
544 file_unmanaged_delete_recursive($this->siteDirectory, [$this, 'filePreDeleteCallback']);
550 protected function tearDown() {
553 // Destroy the testing kernel.
554 if (isset($this->kernel)) {
555 $this->cleanupEnvironment();
556 $this->kernel->shutdown();
559 // Ensure that internal logged in variable is reset.
560 $this->loggedInUser = FALSE;
563 $this->mink->stopSessions();
566 // Restore original shutdown callbacks.
567 if (function_exists('drupal_register_shutdown_function')) {
568 $callbacks = &drupal_register_shutdown_function();
569 $callbacks = $this->originalShutdownCallbacks;
574 * Returns Mink session.
576 * @param string $name
577 * (optional) Name of the session. Defaults to the active session.
579 * @return \Behat\Mink\Session
580 * The active Mink session object.
582 public function getSession($name = NULL) {
583 return $this->mink->getSession($name);
587 * Returns WebAssert object.
589 * @param string $name
590 * (optional) Name of the session. Defaults to the active session.
592 * @return \Drupal\Tests\WebAssert
593 * A new web-assert option for asserting the presence of elements with.
595 public function assertSession($name = NULL) {
596 return new WebAssert($this->getSession($name), $this->baseUrl);
600 * Prepare for a request to testing site.
602 * The testing site is protected via a SIMPLETEST_USER_AGENT cookie that is
603 * checked by drupal_valid_test_ua().
605 * @see drupal_valid_test_ua()
607 protected function prepareRequest() {
608 $session = $this->getSession();
609 $session->setCookie('SIMPLETEST_USER_AGENT', drupal_generate_test_ua($this->databasePrefix));
613 * Builds an a absolute URL from a system path or a URL object.
615 * @param string|\Drupal\Core\Url $path
616 * A system path or a URL.
617 * @param array $options
618 * Options to be passed to Url::fromUri().
621 * An absolute URL stsring.
623 protected function buildUrl($path, array $options = []) {
624 if ($path instanceof Url) {
625 $url_options = $path->getOptions();
626 $options = $url_options + $options;
627 $path->setOptions($options);
628 return $path->setAbsolute()->toString();
630 // The URL generator service is not necessarily available yet; e.g., in
631 // interactive installer tests.
632 elseif ($this->container->has('url_generator')) {
633 $force_internal = isset($options['external']) && $options['external'] == FALSE;
634 if (!$force_internal && UrlHelper::isExternal($path)) {
635 return Url::fromUri($path, $options)->toString();
638 $uri = $path === '<front>' ? 'base:/' : 'base:/' . $path;
639 // Path processing is needed for language prefixing. Skip it when a
640 // path that may look like an external URL is being used as internal.
641 $options['path_processing'] = !$force_internal;
642 return Url::fromUri($uri, $options)
648 return $this->getAbsoluteUrl($path);
653 * Retrieves a Drupal path or an absolute path.
655 * @param string|\Drupal\Core\Url $path
656 * Drupal path or URL to load into Mink controlled browser.
657 * @param array $options
658 * (optional) Options to be forwarded to the url generator.
659 * @param string[] $headers
660 * An array containing additional HTTP request headers, the array keys are
661 * the header names and the array values the header values. This is useful
662 * to set for example the "Accept-Language" header for requesting the page
663 * in a different language. Note that not all headers are supported, for
664 * example the "Accept" header is always overridden by the browser. For
665 * testing REST APIs it is recommended to directly use an HTTP client such
669 * The retrieved HTML string, also available as $this->getRawContent()
671 protected function drupalGet($path, array $options = [], array $headers = []) {
672 $options['absolute'] = TRUE;
673 $url = $this->buildUrl($path, $options);
675 $session = $this->getSession();
677 $this->prepareRequest();
678 foreach ($headers as $header_name => $header_value) {
679 $session->setRequestHeader($header_name, $header_value);
682 $session->visit($url);
683 $out = $session->getPage()->getContent();
685 // Ensure that any changes to variables in the other thread are picked up.
686 $this->refreshVariables();
688 // Replace original page output with new output from redirected page(s).
689 if ($new = $this->checkForMetaRefresh()) {
691 // We are finished with all meta refresh redirects, so reset the counter.
692 $this->metaRefreshCount = 0;
695 // Log only for JavascriptTestBase tests because for Goutte we log with
696 // ::getResponseLogHandler.
697 if ($this->htmlOutputEnabled && !($this->getSession()->getDriver() instanceof GoutteDriver)) {
698 $html_output = 'GET request to: ' . $url .
699 '<hr />Ending URL: ' . $this->getSession()->getCurrentUrl();
700 $html_output .= '<hr />' . $out;
701 $html_output .= $this->getHtmlOutputHeaders();
702 $this->htmlOutput($html_output);
709 * Takes a path and returns an absolute path.
711 * @param string $path
712 * A path from the Mink controlled browser content.
715 * The $path with $base_url prepended, if necessary.
717 protected function getAbsoluteUrl($path) {
718 global $base_url, $base_path;
720 $parts = parse_url($path);
721 if (empty($parts['host'])) {
722 // Ensure that we have a string (and no xpath object).
723 $path = (string) $path;
724 // Strip $base_path, if existent.
725 $length = strlen($base_path);
726 if (substr($path, 0, $length) === $base_path) {
727 $path = substr($path, $length);
729 // Ensure that we have an absolute path.
730 if (empty($path) || $path[0] !== '/') {
733 // Finally, prepend the $base_url.
734 $path = $base_url . $path;
740 * Logs in a user using the Mink controlled browser.
742 * If a user is already logged in, then the current user is logged out before
743 * logging in the specified user.
745 * Please note that neither the current user nor the passed-in user object is
746 * populated with data of the logged in user. If you need full access to the
747 * user object after logging in, it must be updated manually. If you also need
748 * access to the plain-text password of the user (set by drupalCreateUser()),
749 * e.g. to log in the same user again, then it must be re-assigned manually.
753 * $account = $this->drupalCreateUser(array());
754 * $this->drupalLogin($account);
755 * // Load real user object.
756 * $pass_raw = $account->passRaw;
757 * $account = User::load($account->id());
758 * $account->passRaw = $pass_raw;
761 * @param \Drupal\Core\Session\AccountInterface $account
762 * User object representing the user to log in.
764 * @see drupalCreateUser()
766 protected function drupalLogin(AccountInterface $account) {
767 if ($this->loggedInUser) {
768 $this->drupalLogout();
771 $this->drupalGet('user/login');
773 'name' => $account->getUsername(),
774 'pass' => $account->passRaw,
777 // @see BrowserTestBase::drupalUserIsLoggedIn()
778 $account->sessionId = $this->getSession()->getCookie($this->getSessionName());
779 $this->assertTrue($this->drupalUserIsLoggedIn($account), new FormattableMarkup('User %name successfully logged in.', ['%name' => $account->getAccountName()]));
781 $this->loggedInUser = $account;
782 $this->container->get('current_user')->setAccount($account);
786 * Logs a user out of the Mink controlled browser and confirms.
788 * Confirms logout by checking the login page.
790 protected function drupalLogout() {
791 // Make a request to the logout page, and redirect to the user page, the
792 // idea being if you were properly logged out you should be seeing a login
794 $assert_session = $this->assertSession();
795 $this->drupalGet('user/logout', ['query' => ['destination' => 'user']]);
796 $assert_session->fieldExists('name');
797 $assert_session->fieldExists('pass');
799 // @see BrowserTestBase::drupalUserIsLoggedIn()
800 unset($this->loggedInUser->sessionId);
801 $this->loggedInUser = FALSE;
802 $this->container->get('current_user')->setAccount(new AnonymousUserSession());
806 * Fills and submits a form.
809 * Field data in an associative array. Changes the current input fields
810 * (where possible) to the values indicated.
812 * A checkbox can be set to TRUE to be checked and should be set to FALSE to
814 * @param string $submit
815 * Value of the submit button whose click is to be emulated. For example,
816 * 'Save'. The processing of the request depends on this value. For example,
817 * a form may have one button with the value 'Save' and another button with
818 * the value 'Delete', and execute different code depending on which one is
820 * @param string $form_html_id
821 * (optional) HTML ID of the form to be submitted. On some pages
822 * there are many identical forms, so just using the value of the submit
823 * button is not enough. For example: 'trigger-node-presave-assign-form'.
824 * Note that this is not the Drupal $form_id, but rather the HTML ID of the
825 * form, which is typically the same thing but with hyphens replacing the
828 protected function submitForm(array $edit, $submit, $form_html_id = NULL) {
829 $assert_session = $this->assertSession();
832 if (isset($form_html_id)) {
833 $form = $assert_session->elementExists('xpath', "//form[@id='$form_html_id']");
834 $submit_button = $assert_session->buttonExists($submit, $form);
835 $action = $form->getAttribute('action');
838 $submit_button = $assert_session->buttonExists($submit);
839 $form = $assert_session->elementExists('xpath', './ancestor::form', $submit_button);
840 $action = $form->getAttribute('action');
843 // Edit the form values.
844 foreach ($edit as $name => $value) {
845 $field = $assert_session->fieldExists($name, $form);
847 // Provide support for the values '1' and '0' for checkboxes instead of
849 // @todo Get rid of supporting 1/0 by converting all tests cases using
850 // this to boolean values.
851 $field_type = $field->getAttribute('type');
852 if ($field_type === 'checkbox') {
853 $value = (bool) $value;
856 $field->setValue($value);
860 $this->prepareRequest();
861 $submit_button->press();
863 // Ensure that any changes to variables in the other thread are picked up.
864 $this->refreshVariables();
866 // Check if there are any meta refresh redirects (like Batch API pages).
867 if ($this->checkForMetaRefresh()) {
868 // We are finished with all meta refresh redirects, so reset the counter.
869 $this->metaRefreshCount = 0;
872 // Log only for JavascriptTestBase tests because for Goutte we log with
873 // ::getResponseLogHandler.
874 if ($this->htmlOutputEnabled && !($this->getSession()->getDriver() instanceof GoutteDriver)) {
875 $out = $this->getSession()->getPage()->getContent();
876 $html_output = 'POST request to: ' . $action .
877 '<hr />Ending URL: ' . $this->getSession()->getCurrentUrl();
878 $html_output .= '<hr />' . $out;
879 $html_output .= $this->getHtmlOutputHeaders();
880 $this->htmlOutput($html_output);
886 * Executes a form submission.
888 * It will be done as usual POST request with Mink.
890 * @param \Drupal\Core\Url|string $path
891 * Location of the post form. Either a Drupal path or an absolute path or
892 * NULL to post to the current page. For multi-stage forms you can set the
893 * path to NULL and have it post to the last received page. Example:
896 * // First step in form.
897 * $edit = array(...);
898 * $this->drupalPostForm('some_url', $edit, 'Save');
900 * // Second step in form.
901 * $edit = array(...);
902 * $this->drupalPostForm(NULL, $edit, 'Save');
905 * Field data in an associative array. Changes the current input fields
906 * (where possible) to the values indicated.
908 * When working with form tests, the keys for an $edit element should match
909 * the 'name' parameter of the HTML of the form. For example, the 'body'
910 * field for a node has the following HTML:
912 * <textarea id="edit-body-und-0-value" class="text-full form-textarea
913 * resize-vertical" placeholder="" cols="60" rows="9"
914 * name="body[0][value]"></textarea>
916 * When testing this field using an $edit parameter, the code becomes:
918 * $edit["body[0][value]"] = 'My test value';
921 * A checkbox can be set to TRUE to be checked and should be set to FALSE to
922 * be unchecked. Multiple select fields can be tested using 'name[]' and
923 * setting each of the desired values in an array:
926 * $edit['name[]'] = array('value1', 'value2');
928 * @todo change $edit to disallow NULL as a value for Drupal 9.
929 * https://www.drupal.org/node/2802401
930 * @param string $submit
931 * Value of the submit button whose click is to be emulated. For example,
932 * 'Save'. The processing of the request depends on this value. For example,
933 * a form may have one button with the value 'Save' and another button with
934 * the value 'Delete', and execute different code depending on which one is
937 * This function can also be called to emulate an Ajax submission. In this
938 * case, this value needs to be an array with the following keys:
939 * - path: A path to submit the form values to for Ajax-specific processing.
940 * - triggering_element: If the value for the 'path' key is a generic Ajax
941 * processing path, this needs to be set to the name of the element. If
942 * the name doesn't identify the element uniquely, then this should
943 * instead be an array with a single key/value pair, corresponding to the
944 * element name and value. The \Drupal\Core\Form\FormAjaxResponseBuilder
945 * uses this to find the #ajax information for the element, including
946 * which specific callback to use for processing the request.
948 * This can also be set to NULL in order to emulate an Internet Explorer
949 * submission of a form with a single text field, and pressing ENTER in that
950 * textfield: under these conditions, no button information is added to the
952 * @param array $options
953 * Options to be forwarded to the url generator.
956 * (deprecated) The response content after submit form. It is necessary for
957 * backwards compatibility and will be removed before Drupal 9.0. You should
958 * just use the webAssert object for your assertions.
960 protected function drupalPostForm($path, $edit, $submit, array $options = []) {
961 if (is_object($submit)) {
962 // Cast MarkupInterface objects to string.
963 $submit = (string) $submit;
965 if ($edit === NULL) {
968 if (is_array($edit)) {
969 $edit = $this->castSafeStrings($edit);
973 $this->drupalGet($path, $options);
976 $this->submitForm($edit, $submit);
978 return $this->getSession()->getPage()->getContent();
982 * Helper function to get the options of select field.
984 * @param \Behat\Mink\Element\NodeElement|string $select
985 * Name, ID, or Label of select field to assert.
986 * @param \Behat\Mink\Element\Element $container
987 * (optional) Container element to check against. Defaults to current page.
990 * Associative array of option keys and values.
992 protected function getOptions($select, Element $container = NULL) {
993 if (is_string($select)) {
994 $select = $this->assertSession()->selectExists($select, $container);
997 /* @var \Behat\Mink\Element\NodeElement $option */
998 foreach ($select->findAll('xpath', '//option') as $option) {
999 $label = $option->getText();
1000 $value = $option->getAttribute('value') ?: $label;
1001 $options[$value] = $label;
1007 * Installs Drupal into the Simpletest site.
1009 public function installDrupal() {
1010 $this->initUserSession();
1011 $this->prepareSettings();
1013 $this->initSettings();
1014 $container = $this->initKernel(\Drupal::request());
1015 $this->initConfig($container);
1016 $this->installModulesFromClassProperty($container);
1017 $this->rebuildAll();
1021 * Returns whether a given user account is logged in.
1023 * @param \Drupal\Core\Session\AccountInterface $account
1024 * The user account object to check.
1027 * Return TRUE if the user is logged in, FALSE otherwise.
1029 protected function drupalUserIsLoggedIn(AccountInterface $account) {
1032 if (isset($account->sessionId)) {
1033 $session_handler = $this->container->get('session_handler.storage');
1034 $logged_in = (bool) $session_handler->read($account->sessionId);
1041 * Clicks the element with the given CSS selector.
1043 * @param string $css_selector
1044 * The CSS selector identifying the element to click.
1046 protected function click($css_selector) {
1047 $this->getSession()->getDriver()->click($this->cssSelectToXpath($css_selector));
1051 * Prevents serializing any properties.
1053 * Browser tests are run in a separate process. To do this PHPUnit creates a
1054 * script to run the test. If it fails, the test result object will contain a
1055 * stack trace which includes the test object. It will attempt to serialize
1056 * it. Returning an empty array prevents it from serializing anything it
1062 * @see vendor/phpunit/phpunit/src/Util/PHP/Template/TestCaseMethod.tpl.dist
1064 public function __sleep() {
1069 * Logs a HTML output message in a text file.
1071 * The link to the HTML output message will be printed by the results printer.
1073 * @param string $message
1074 * The HTML output message to be stored.
1076 * @see \Drupal\Tests\Listeners\VerbosePrinter::printResult()
1078 protected function htmlOutput($message) {
1079 if (!$this->htmlOutputEnabled) {
1082 $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;
1083 $html_output_filename = $this->htmlOutputClassName . '-' . $this->htmlOutputCounter . '-' . $this->htmlOutputTestId . '.html';
1084 file_put_contents($this->htmlOutputDirectory . '/' . $html_output_filename, $message);
1085 file_put_contents($this->htmlOutputCounterStorage, $this->htmlOutputCounter++);
1086 file_put_contents($this->htmlOutputFile, file_create_url('sites/simpletest/browser_output/' . $html_output_filename) . "\n", FILE_APPEND);
1090 * Returns headers in HTML output format.
1093 * HTML output headers.
1095 protected function getHtmlOutputHeaders() {
1096 return $this->formatHtmlOutputHeaders($this->getSession()->getResponseHeaders());
1100 * Formats HTTP headers as string for HTML output logging.
1102 * @param array[] $headers
1103 * Headers that should be formatted.
1106 * The formatted HTML string.
1108 protected function formatHtmlOutputHeaders(array $headers) {
1109 $flattened_headers = array_map(function ($header) {
1110 if (is_array($header)) {
1111 return implode(';', array_map('trim', $header));
1117 return '<hr />Headers: <pre>' . Html::escape(var_export($flattened_headers, TRUE)) . '</pre>';
1121 * Translates a CSS expression to its XPath equivalent.
1123 * The search is relative to the root element (HTML tag normally) of the page.
1125 * @param string $selector
1126 * CSS selector to use in the search.
1128 * (optional) Enables HTML support. Disable it for XML documents.
1129 * @param string $prefix
1130 * (optional) The prefix for the XPath expression.
1133 * The equivalent XPath of a CSS expression.
1135 protected function cssSelectToXpath($selector, $html = TRUE, $prefix = 'descendant-or-self::') {
1136 return (new CssSelectorConverter($html))->toXPath($selector, $prefix);
1140 * Searches elements using a CSS selector in the raw content.
1142 * The search is relative to the root element (HTML tag normally) of the page.
1144 * @param string $selector
1145 * CSS selector to use in the search.
1147 * @return \Behat\Mink\Element\NodeElement[]
1148 * The list of elements on the page that match the selector.
1150 protected function cssSelect($selector) {
1151 return $this->getSession()->getPage()->findAll('css', $selector);
1155 * Follows a link by complete name.
1157 * Will click the first link found with this link text.
1159 * If the link is discovered and clicked, the test passes. Fail otherwise.
1161 * @param string|\Drupal\Component\Render\MarkupInterface $label
1162 * Text between the anchor tags.
1164 * (optional) The index number for cases where multiple links have the same
1165 * text. Defaults to 0.
1167 protected function clickLink($label, $index = 0) {
1168 $label = (string) $label;
1169 $links = $this->getSession()->getPage()->findAll('named', ['link', $label]);
1170 $links[$index]->click();
1174 * Retrieves the plain-text content from the current page.
1176 protected function getTextContent() {
1177 return $this->getSession()->getPage()->getText();
1181 * Performs an xpath search on the contents of the internal browser.
1183 * The search is relative to the root element (HTML tag normally) of the page.
1185 * @param string $xpath
1186 * The xpath string to use in the search.
1187 * @param array $arguments
1188 * An array of arguments with keys in the form ':name' matching the
1189 * placeholders in the query. The values may be either strings or numeric
1192 * @return \Behat\Mink\Element\NodeElement[]
1193 * The list of elements matching the xpath expression.
1195 protected function xpath($xpath, array $arguments = []) {
1196 $xpath = $this->assertSession()->buildXPathQuery($xpath, $arguments);
1197 return $this->getSession()->getPage()->findAll('xpath', $xpath);
1201 * Configuration accessor for tests. Returns non-overridden configuration.
1203 * @param string $name
1204 * Configuration name.
1206 * @return \Drupal\Core\Config\Config
1207 * The configuration object with original configuration data.
1209 protected function config($name) {
1210 return $this->container->get('config.factory')->getEditable($name);
1214 * Returns all response headers.
1217 * The HTTP headers values.
1219 * @deprecated Scheduled for removal in Drupal 9.0.0.
1220 * Use $this->getSession()->getResponseHeaders() instead.
1222 protected function drupalGetHeaders() {
1223 return $this->getSession()->getResponseHeaders();
1227 * Gets the value of an HTTP response header.
1229 * If multiple requests were required to retrieve the page, only the headers
1230 * from the last request will be checked by default.
1232 * @param string $name
1233 * The name of the header to retrieve. Names are case-insensitive (see RFC
1234 * 2616 section 4.2).
1236 * @return string|null
1237 * The HTTP header value or NULL if not found.
1239 protected function drupalGetHeader($name) {
1240 return $this->getSession()->getResponseHeader($name);
1244 * Get the current URL from the browser.
1249 protected function getUrl() {
1250 return $this->getSession()->getCurrentUrl();
1254 * Gets the JavaScript drupalSettings variable for the currently-loaded page.
1257 * The JSON decoded drupalSettings value from the current page.
1259 protected function getDrupalSettings() {
1260 $html = $this->getSession()->getPage()->getHtml();
1261 if (preg_match('@<script type="application/json" data-drupal-selector="drupal-settings-json">([^<]*)</script>@', $html, $matches)) {
1262 return Json::decode($matches[1]);
1270 public static function assertEquals($expected, $actual, $message = '', $delta = 0.0, $maxDepth = 10, $canonicalize = FALSE, $ignoreCase = FALSE) {
1271 // Cast objects implementing MarkupInterface to string instead of
1272 // relying on PHP casting them to string depending on what they are being
1274 $expected = static::castSafeStrings($expected);
1275 $actual = static::castSafeStrings($actual);
1276 parent::assertEquals($expected, $actual, $message, $delta, $maxDepth, $canonicalize, $ignoreCase);
1280 * Retrieves the current calling line in the class under test.
1283 * An associative array with keys 'file', 'line' and 'function'.
1285 protected function getTestMethodCaller() {
1286 $backtrace = debug_backtrace();
1287 // Find the test class that has the test method.
1288 while ($caller = Error::getLastCaller($backtrace)) {
1289 if (isset($caller['class']) && $caller['class'] === get_class($this)) {
1292 // If the test method is implemented by a test class's parent then the
1293 // class name of $this will not be part of the backtrace.
1294 // In that case we process the backtrace until the caller is not a
1295 // subclass of $this and return the previous caller.
1296 if (isset($last_caller) && (!isset($caller['class']) || !is_subclass_of($this, $caller['class']))) {
1297 // Return the last caller since that has to be the test class.
1298 $caller = $last_caller;
1301 // Otherwise we have not reached our test class yet: save the last caller
1302 // and remove an element from to backtrace to process the next call.
1303 $last_caller = $caller;
1304 array_shift($backtrace);
1311 * Checks for meta refresh tag and if found call drupalGet() recursively.
1313 * This function looks for the http-equiv attribute to be set to "Refresh" and
1314 * is case-insensitive.
1316 * @return string|false
1317 * Either the new page content or FALSE.
1319 protected function checkForMetaRefresh() {
1320 $refresh = $this->cssSelect('meta[http-equiv="Refresh"], meta[http-equiv="refresh"]');
1321 if (!empty($refresh) && (!isset($this->maximumMetaRefreshCount) || $this->metaRefreshCount < $this->maximumMetaRefreshCount)) {
1322 // Parse the content attribute of the meta tag for the format:
1323 // "[delay]: URL=[page_to_redirect_to]".
1324 if (preg_match('/\d+;\s*URL=(?<url>.*)/i', $refresh[0]->getAttribute('content'), $match)) {
1325 $this->metaRefreshCount++;
1326 return $this->drupalGet($this->getAbsoluteUrl(Html::decodeEntities($match['url'])));