Chris@0: root = dirname(dirname(substr(__DIR__, 0, -strlen(__NAMESPACE__)))); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Initializes Mink sessions. Chris@0: */ Chris@0: protected function initMink() { Chris@0: $driver = $this->getDefaultDriverInstance(); Chris@0: Chris@0: if ($driver instanceof GoutteDriver) { Chris@0: // Turn off curl timeout. Having a timeout is not a problem in a normal Chris@0: // test running, but it is a problem when debugging. Also, disable SSL Chris@0: // peer verification so that testing under HTTPS always works. Chris@0: /** @var \GuzzleHttp\Client $client */ Chris@0: $client = $this->container->get('http_client_factory')->fromOptions([ Chris@0: 'timeout' => NULL, Chris@0: 'verify' => FALSE, Chris@0: ]); Chris@0: Chris@0: // Inject a Guzzle middleware to generate debug output for every request Chris@0: // performed in the test. Chris@0: $handler_stack = $client->getConfig('handler'); Chris@0: $handler_stack->push($this->getResponseLogHandler()); Chris@0: Chris@0: $driver->getClient()->setClient($client); Chris@0: } Chris@0: Chris@0: $selectors_handler = new SelectorsHandler([ Chris@0: 'hidden_field_selector' => new HiddenFieldSelector() Chris@0: ]); Chris@0: $session = new Session($driver, $selectors_handler); Chris@0: $this->mink = new Mink(); Chris@0: $this->mink->registerSession('default', $session); Chris@0: $this->mink->setDefaultSessionName('default'); Chris@0: $this->registerSessions(); Chris@0: Chris@0: $this->initFrontPage(); Chris@0: Chris@0: return $session; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Visits the front page when initializing Mink. Chris@0: * Chris@0: * According to the W3C WebDriver specification a cookie can only be set if Chris@0: * the cookie domain is equal to the domain of the active document. When the Chris@0: * browser starts up the active document is not our domain but 'about:blank' Chris@0: * or similar. To be able to set our User-Agent and Xdebug cookies at the Chris@0: * start of the test we now do a request to the front page so the active Chris@0: * document matches the domain. Chris@0: * Chris@0: * @see https://w3c.github.io/webdriver/webdriver-spec.html#add-cookie Chris@0: * @see https://www.w3.org/Bugs/Public/show_bug.cgi?id=20975 Chris@0: */ Chris@0: protected function initFrontPage() { Chris@0: $session = $this->getSession(); Chris@0: $session->visit($this->baseUrl); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets an instance of the default Mink driver. Chris@0: * Chris@0: * @return Behat\Mink\Driver\DriverInterface Chris@0: * Instance of default Mink driver. Chris@0: * Chris@0: * @throws \InvalidArgumentException Chris@0: * When provided default Mink driver class can't be instantiated. Chris@0: */ Chris@0: protected function getDefaultDriverInstance() { Chris@0: // Get default driver params from environment if available. Chris@0: if ($arg_json = $this->getMinkDriverArgs()) { Chris@0: $this->minkDefaultDriverArgs = json_decode($arg_json, TRUE); Chris@0: } Chris@0: Chris@0: // Get and check default driver class from environment if available. Chris@0: if ($minkDriverClass = getenv('MINK_DRIVER_CLASS')) { Chris@0: if (class_exists($minkDriverClass)) { Chris@0: $this->minkDefaultDriverClass = $minkDriverClass; Chris@0: } Chris@0: else { Chris@0: throw new \InvalidArgumentException("Can't instantiate provided $minkDriverClass class by environment as default driver class."); Chris@0: } Chris@0: } Chris@0: Chris@0: if (is_array($this->minkDefaultDriverArgs)) { Chris@0: // Use ReflectionClass to instantiate class with received params. Chris@0: $reflector = new \ReflectionClass($this->minkDefaultDriverClass); Chris@0: $driver = $reflector->newInstanceArgs($this->minkDefaultDriverArgs); Chris@0: } Chris@0: else { Chris@0: $driver = new $this->minkDefaultDriverClass(); Chris@0: } Chris@0: return $driver; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Creates the directory to store browser output. Chris@0: * Chris@0: * Creates the directory to store browser output in if a file to write Chris@0: * URLs to has been created by \Drupal\Tests\Listeners\HtmlOutputPrinter. Chris@0: */ Chris@0: protected function initBrowserOutputFile() { Chris@0: $browser_output_file = getenv('BROWSERTEST_OUTPUT_FILE'); Chris@0: $this->htmlOutputEnabled = is_file($browser_output_file); Chris@0: if ($this->htmlOutputEnabled) { Chris@0: $this->htmlOutputFile = $browser_output_file; Chris@0: $this->htmlOutputClassName = str_replace("\\", "_", get_called_class()); Chris@0: $this->htmlOutputDirectory = DRUPAL_ROOT . '/sites/simpletest/browser_output'; Chris@0: if (file_prepare_directory($this->htmlOutputDirectory, FILE_CREATE_DIRECTORY) && !file_exists($this->htmlOutputDirectory . '/.htaccess')) { Chris@0: file_put_contents($this->htmlOutputDirectory . '/.htaccess', "\nExpiresActive Off\n\n"); Chris@0: } Chris@0: $this->htmlOutputCounterStorage = $this->htmlOutputDirectory . '/' . $this->htmlOutputClassName . '.counter'; Chris@0: $this->htmlOutputTestId = str_replace('sites/simpletest/', '', $this->siteDirectory); Chris@0: if (is_file($this->htmlOutputCounterStorage)) { Chris@0: $this->htmlOutputCounter = max(1, (int) file_get_contents($this->htmlOutputCounterStorage)) + 1; Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Get the Mink driver args from an environment variable, if it is set. Can Chris@0: * be overridden in a derived class so it is possible to use a different Chris@0: * value for a subset of tests, e.g. the JavaScript tests. Chris@0: * Chris@0: * @return string|false Chris@0: * The JSON-encoded argument string. False if it is not set. Chris@0: */ Chris@0: protected function getMinkDriverArgs() { Chris@0: return getenv('MINK_DRIVER_ARGS'); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Provides a Guzzle middleware handler to log every response received. Chris@0: * Chris@0: * @return callable Chris@0: * The callable handler that will do the logging. Chris@0: */ Chris@0: protected function getResponseLogHandler() { Chris@0: return function (callable $handler) { Chris@0: return function (RequestInterface $request, array $options) use ($handler) { Chris@0: return $handler($request, $options) Chris@0: ->then(function (ResponseInterface $response) use ($request) { Chris@0: if ($this->htmlOutputEnabled) { Chris@0: Chris@0: $caller = $this->getTestMethodCaller(); Chris@0: $html_output = 'Called from ' . $caller['function'] . ' line ' . $caller['line']; Chris@0: $html_output .= '
' . $request->getMethod() . ' request to: ' . $request->getUri(); Chris@0: Chris@0: // On redirect responses (status code starting with '3') we need Chris@0: // to remove the meta tag that would do a browser refresh. We Chris@0: // don't want to redirect developers away when they look at the Chris@0: // debug output file in their browser. Chris@0: $body = $response->getBody(); Chris@0: $status_code = (string) $response->getStatusCode(); Chris@0: if ($status_code[0] === '3') { Chris@0: $body = preg_replace('##', '', $body, 1); Chris@0: } Chris@0: $html_output .= '
' . $body; Chris@0: $html_output .= $this->formatHtmlOutputHeaders($response->getHeaders()); Chris@0: Chris@0: $this->htmlOutput($html_output); Chris@0: } Chris@0: return $response; Chris@0: }); Chris@0: }; Chris@0: }; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Registers additional Mink sessions. Chris@0: * Chris@0: * Tests wishing to use a different driver or change the default driver should Chris@0: * override this method. Chris@0: * Chris@0: * @code Chris@0: * // Register a new session that uses the MinkPonyDriver. Chris@0: * $pony = new MinkPonyDriver(); Chris@0: * $session = new Session($pony); Chris@0: * $this->mink->registerSession('pony', $session); Chris@0: * @endcode Chris@0: */ Chris@0: protected function registerSessions() {} Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: protected function setUp() { Chris@0: // Installing Drupal creates 1000s of objects. Garbage collection of these Chris@0: // objects is expensive. This appears to be causing random segmentation Chris@0: // faults in PHP 5.x due to https://bugs.php.net/bug.php?id=72286. Once Chris@0: // Drupal is installed is rebuilt, garbage collection is re-enabled. Chris@0: $disable_gc = version_compare(PHP_VERSION, '7', '<') && gc_enabled(); Chris@0: if ($disable_gc) { Chris@0: gc_collect_cycles(); Chris@0: gc_disable(); Chris@0: } Chris@0: parent::setUp(); Chris@0: Chris@0: $this->setupBaseUrl(); Chris@0: Chris@0: // Install Drupal test site. Chris@0: $this->prepareEnvironment(); Chris@0: $this->installDrupal(); Chris@0: Chris@0: // Setup Mink. Chris@0: $session = $this->initMink(); Chris@0: Chris@0: $cookies = $this->extractCookiesFromRequest(\Drupal::request()); Chris@0: foreach ($cookies as $cookie_name => $values) { Chris@0: foreach ($values as $value) { Chris@0: $session->setCookie($cookie_name, $value); Chris@0: } Chris@0: } Chris@0: Chris@0: // Set up the browser test output file. Chris@0: $this->initBrowserOutputFile(); Chris@0: // If garbage collection was disabled prior to rebuilding container, Chris@0: // re-enable it. Chris@0: if ($disable_gc) { Chris@0: gc_enable(); Chris@0: } Chris@0: Chris@0: // Ensure that the test is not marked as risky because of no assertions. In Chris@0: // PHPUnit 6 tests that only make assertions using $this->assertSession() Chris@0: // can be marked as risky. Chris@0: $this->addToAssertionCount(1); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Ensures test files are deletable within file_unmanaged_delete_recursive(). Chris@0: * Chris@0: * Some tests chmod generated files to be read only. During Chris@0: * BrowserTestBase::cleanupEnvironment() and other cleanup operations, Chris@0: * these files need to get deleted too. Chris@0: * Chris@0: * @param string $path Chris@0: * The file path. Chris@0: */ Chris@0: public static function filePreDeleteCallback($path) { Chris@0: // When the webserver runs with the same system user as phpunit, we can Chris@0: // make read-only files writable again. If not, chmod will fail while the Chris@0: // file deletion still works if file permissions have been configured Chris@0: // correctly. Thus, we ignore any problems while running chmod. Chris@0: @chmod($path, 0700); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Clean up the Simpletest environment. Chris@0: */ Chris@0: protected function cleanupEnvironment() { Chris@0: // Remove all prefixed tables. Chris@0: $original_connection_info = Database::getConnectionInfo('simpletest_original_default'); Chris@0: $original_prefix = $original_connection_info['default']['prefix']['default']; Chris@0: $test_connection_info = Database::getConnectionInfo('default'); Chris@0: $test_prefix = $test_connection_info['default']['prefix']['default']; Chris@0: if ($original_prefix != $test_prefix) { Chris@0: $tables = Database::getConnection()->schema()->findTables('%'); Chris@0: foreach ($tables as $table) { Chris@0: if (Database::getConnection()->schema()->dropTable($table)) { Chris@0: unset($tables[$table]); Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: // Delete test site directory. Chris@0: file_unmanaged_delete_recursive($this->siteDirectory, [$this, 'filePreDeleteCallback']); Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: protected function tearDown() { Chris@0: parent::tearDown(); Chris@0: Chris@0: // Destroy the testing kernel. Chris@0: if (isset($this->kernel)) { Chris@0: $this->cleanupEnvironment(); Chris@0: $this->kernel->shutdown(); Chris@0: } Chris@0: Chris@0: // Ensure that internal logged in variable is reset. Chris@0: $this->loggedInUser = FALSE; Chris@0: Chris@0: if ($this->mink) { Chris@0: $this->mink->stopSessions(); Chris@0: } Chris@0: Chris@0: // Restore original shutdown callbacks. Chris@0: if (function_exists('drupal_register_shutdown_function')) { Chris@0: $callbacks = &drupal_register_shutdown_function(); Chris@0: $callbacks = $this->originalShutdownCallbacks; Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns Mink session. Chris@0: * Chris@0: * @param string $name Chris@0: * (optional) Name of the session. Defaults to the active session. Chris@0: * Chris@0: * @return \Behat\Mink\Session Chris@0: * The active Mink session object. Chris@0: */ Chris@0: public function getSession($name = NULL) { Chris@0: return $this->mink->getSession($name); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Obtain the HTTP client for the system under test. Chris@0: * Chris@0: * Use this method for arbitrary HTTP requests to the site under test. For Chris@0: * most tests, you should not get the HTTP client and instead use navigation Chris@0: * methods such as drupalGet() and clickLink() in order to benefit from Chris@0: * assertions. Chris@0: * Chris@0: * Subclasses which substitute a different Mink driver should override this Chris@0: * method and provide a Guzzle client if the Mink driver provides one. Chris@0: * Chris@0: * @return \GuzzleHttp\ClientInterface Chris@0: * The client with BrowserTestBase configuration. Chris@0: * Chris@0: * @throws \RuntimeException Chris@0: * If the Mink driver does not support a Guzzle HTTP client, throw an Chris@0: * exception. Chris@0: */ Chris@0: protected function getHttpClient() { Chris@0: /* @var $mink_driver \Behat\Mink\Driver\DriverInterface */ Chris@0: $mink_driver = $this->getSession()->getDriver(); Chris@0: if ($mink_driver instanceof GoutteDriver) { Chris@0: return $mink_driver->getClient()->getClient(); Chris@0: } Chris@0: throw new \RuntimeException('The Mink client type ' . get_class($mink_driver) . ' does not support getHttpClient().'); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns WebAssert object. Chris@0: * Chris@0: * @param string $name Chris@0: * (optional) Name of the session. Defaults to the active session. Chris@0: * Chris@0: * @return \Drupal\Tests\WebAssert Chris@0: * A new web-assert option for asserting the presence of elements with. Chris@0: */ Chris@0: public function assertSession($name = NULL) { Chris@0: $this->addToAssertionCount(1); Chris@0: return new WebAssert($this->getSession($name), $this->baseUrl); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Prepare for a request to testing site. Chris@0: * Chris@0: * The testing site is protected via a SIMPLETEST_USER_AGENT cookie that is Chris@0: * checked by drupal_valid_test_ua(). Chris@0: * Chris@0: * @see drupal_valid_test_ua() Chris@0: */ Chris@0: protected function prepareRequest() { Chris@0: $session = $this->getSession(); Chris@0: $session->setCookie('SIMPLETEST_USER_AGENT', drupal_generate_test_ua($this->databasePrefix)); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Builds an a absolute URL from a system path or a URL object. Chris@0: * Chris@0: * @param string|\Drupal\Core\Url $path Chris@0: * A system path or a URL. Chris@0: * @param array $options Chris@0: * Options to be passed to Url::fromUri(). Chris@0: * Chris@0: * @return string Chris@0: * An absolute URL stsring. Chris@0: */ Chris@0: protected function buildUrl($path, array $options = []) { Chris@0: if ($path instanceof Url) { Chris@0: $url_options = $path->getOptions(); Chris@0: $options = $url_options + $options; Chris@0: $path->setOptions($options); Chris@0: return $path->setAbsolute()->toString(); Chris@0: } Chris@0: // The URL generator service is not necessarily available yet; e.g., in Chris@0: // interactive installer tests. Chris@0: elseif ($this->container->has('url_generator')) { Chris@0: $force_internal = isset($options['external']) && $options['external'] == FALSE; Chris@0: if (!$force_internal && UrlHelper::isExternal($path)) { Chris@0: return Url::fromUri($path, $options)->toString(); Chris@0: } Chris@0: else { Chris@0: $uri = $path === '' ? 'base:/' : 'base:/' . $path; Chris@0: // Path processing is needed for language prefixing. Skip it when a Chris@0: // path that may look like an external URL is being used as internal. Chris@0: $options['path_processing'] = !$force_internal; Chris@0: return Url::fromUri($uri, $options) Chris@0: ->setAbsolute() Chris@0: ->toString(); Chris@0: } Chris@0: } Chris@0: else { Chris@0: return $this->getAbsoluteUrl($path); Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Retrieves a Drupal path or an absolute path. Chris@0: * Chris@0: * @param string|\Drupal\Core\Url $path Chris@0: * Drupal path or URL to load into Mink controlled browser. Chris@0: * @param array $options Chris@0: * (optional) Options to be forwarded to the url generator. Chris@0: * @param string[] $headers Chris@0: * An array containing additional HTTP request headers, the array keys are Chris@0: * the header names and the array values the header values. This is useful Chris@0: * to set for example the "Accept-Language" header for requesting the page Chris@0: * in a different language. Note that not all headers are supported, for Chris@0: * example the "Accept" header is always overridden by the browser. For Chris@0: * testing REST APIs it is recommended to obtain a separate HTTP client Chris@0: * using getHttpClient() and performing requests that way. Chris@0: * Chris@0: * @return string Chris@0: * The retrieved HTML string, also available as $this->getRawContent() Chris@0: * Chris@0: * @see \Drupal\Tests\BrowserTestBase::getHttpClient() Chris@0: */ Chris@0: protected function drupalGet($path, array $options = [], array $headers = []) { Chris@0: $options['absolute'] = TRUE; Chris@0: $url = $this->buildUrl($path, $options); Chris@0: Chris@0: $session = $this->getSession(); Chris@0: Chris@0: $this->prepareRequest(); Chris@0: foreach ($headers as $header_name => $header_value) { Chris@0: $session->setRequestHeader($header_name, $header_value); Chris@0: } Chris@0: Chris@0: $session->visit($url); Chris@0: $out = $session->getPage()->getContent(); Chris@0: Chris@0: // Ensure that any changes to variables in the other thread are picked up. Chris@0: $this->refreshVariables(); Chris@0: Chris@0: // Replace original page output with new output from redirected page(s). Chris@0: if ($new = $this->checkForMetaRefresh()) { Chris@0: $out = $new; Chris@0: // We are finished with all meta refresh redirects, so reset the counter. Chris@0: $this->metaRefreshCount = 0; Chris@0: } Chris@0: Chris@0: // Log only for JavascriptTestBase tests because for Goutte we log with Chris@0: // ::getResponseLogHandler. Chris@0: if ($this->htmlOutputEnabled && !($this->getSession()->getDriver() instanceof GoutteDriver)) { Chris@0: $html_output = 'GET request to: ' . $url . Chris@0: '
Ending URL: ' . $this->getSession()->getCurrentUrl(); Chris@0: $html_output .= '
' . $out; Chris@0: $html_output .= $this->getHtmlOutputHeaders(); Chris@0: $this->htmlOutput($html_output); Chris@0: } Chris@0: Chris@0: return $out; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Takes a path and returns an absolute path. Chris@0: * Chris@0: * @param string $path Chris@0: * A path from the Mink controlled browser content. Chris@0: * Chris@0: * @return string Chris@0: * The $path with $base_url prepended, if necessary. Chris@0: */ Chris@0: protected function getAbsoluteUrl($path) { Chris@0: global $base_url, $base_path; Chris@0: Chris@0: $parts = parse_url($path); Chris@0: if (empty($parts['host'])) { Chris@0: // Ensure that we have a string (and no xpath object). Chris@0: $path = (string) $path; Chris@0: // Strip $base_path, if existent. Chris@0: $length = strlen($base_path); Chris@0: if (substr($path, 0, $length) === $base_path) { Chris@0: $path = substr($path, $length); Chris@0: } Chris@0: // Ensure that we have an absolute path. Chris@0: if (empty($path) || $path[0] !== '/') { Chris@0: $path = '/' . $path; Chris@0: } Chris@0: // Finally, prepend the $base_url. Chris@0: $path = $base_url . $path; Chris@0: } Chris@0: return $path; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Logs in a user using the Mink controlled browser. Chris@0: * Chris@0: * If a user is already logged in, then the current user is logged out before Chris@0: * logging in the specified user. Chris@0: * Chris@0: * Please note that neither the current user nor the passed-in user object is Chris@0: * populated with data of the logged in user. If you need full access to the Chris@0: * user object after logging in, it must be updated manually. If you also need Chris@0: * access to the plain-text password of the user (set by drupalCreateUser()), Chris@0: * e.g. to log in the same user again, then it must be re-assigned manually. Chris@0: * For example: Chris@0: * @code Chris@0: * // Create a user. Chris@0: * $account = $this->drupalCreateUser(array()); Chris@0: * $this->drupalLogin($account); Chris@0: * // Load real user object. Chris@0: * $pass_raw = $account->passRaw; Chris@0: * $account = User::load($account->id()); Chris@0: * $account->passRaw = $pass_raw; Chris@0: * @endcode Chris@0: * Chris@0: * @param \Drupal\Core\Session\AccountInterface $account Chris@0: * User object representing the user to log in. Chris@0: * Chris@0: * @see drupalCreateUser() Chris@0: */ Chris@0: protected function drupalLogin(AccountInterface $account) { Chris@0: if ($this->loggedInUser) { Chris@0: $this->drupalLogout(); Chris@0: } Chris@0: Chris@0: $this->drupalGet('user/login'); Chris@0: $this->submitForm([ Chris@0: 'name' => $account->getUsername(), Chris@0: 'pass' => $account->passRaw, Chris@0: ], t('Log in')); Chris@0: Chris@0: // @see BrowserTestBase::drupalUserIsLoggedIn() Chris@0: $account->sessionId = $this->getSession()->getCookie($this->getSessionName()); Chris@0: $this->assertTrue($this->drupalUserIsLoggedIn($account), new FormattableMarkup('User %name successfully logged in.', ['%name' => $account->getAccountName()])); Chris@0: Chris@0: $this->loggedInUser = $account; Chris@0: $this->container->get('current_user')->setAccount($account); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Logs a user out of the Mink controlled browser and confirms. Chris@0: * Chris@0: * Confirms logout by checking the login page. Chris@0: */ Chris@0: protected function drupalLogout() { Chris@0: // Make a request to the logout page, and redirect to the user page, the Chris@0: // idea being if you were properly logged out you should be seeing a login Chris@0: // screen. Chris@0: $assert_session = $this->assertSession(); Chris@0: $this->drupalGet('user/logout', ['query' => ['destination' => 'user']]); Chris@0: $assert_session->fieldExists('name'); Chris@0: $assert_session->fieldExists('pass'); Chris@0: Chris@0: // @see BrowserTestBase::drupalUserIsLoggedIn() Chris@0: unset($this->loggedInUser->sessionId); Chris@0: $this->loggedInUser = FALSE; Chris@0: $this->container->get('current_user')->setAccount(new AnonymousUserSession()); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Fills and submits a form. Chris@0: * Chris@0: * @param array $edit Chris@0: * Field data in an associative array. Changes the current input fields Chris@0: * (where possible) to the values indicated. Chris@0: * Chris@0: * A checkbox can be set to TRUE to be checked and should be set to FALSE to Chris@0: * be unchecked. Chris@0: * @param string $submit Chris@0: * Value of the submit button whose click is to be emulated. For example, Chris@0: * 'Save'. The processing of the request depends on this value. For example, Chris@0: * a form may have one button with the value 'Save' and another button with Chris@0: * the value 'Delete', and execute different code depending on which one is Chris@0: * clicked. Chris@0: * @param string $form_html_id Chris@0: * (optional) HTML ID of the form to be submitted. On some pages Chris@0: * there are many identical forms, so just using the value of the submit Chris@0: * button is not enough. For example: 'trigger-node-presave-assign-form'. Chris@0: * Note that this is not the Drupal $form_id, but rather the HTML ID of the Chris@0: * form, which is typically the same thing but with hyphens replacing the Chris@0: * underscores. Chris@0: */ Chris@0: protected function submitForm(array $edit, $submit, $form_html_id = NULL) { Chris@0: $assert_session = $this->assertSession(); Chris@0: Chris@0: // Get the form. Chris@0: if (isset($form_html_id)) { Chris@0: $form = $assert_session->elementExists('xpath', "//form[@id='$form_html_id']"); Chris@0: $submit_button = $assert_session->buttonExists($submit, $form); Chris@0: $action = $form->getAttribute('action'); Chris@0: } Chris@0: else { Chris@0: $submit_button = $assert_session->buttonExists($submit); Chris@0: $form = $assert_session->elementExists('xpath', './ancestor::form', $submit_button); Chris@0: $action = $form->getAttribute('action'); Chris@0: } Chris@0: Chris@0: // Edit the form values. Chris@0: foreach ($edit as $name => $value) { Chris@0: $field = $assert_session->fieldExists($name, $form); Chris@0: Chris@0: // Provide support for the values '1' and '0' for checkboxes instead of Chris@0: // TRUE and FALSE. Chris@0: // @todo Get rid of supporting 1/0 by converting all tests cases using Chris@0: // this to boolean values. Chris@0: $field_type = $field->getAttribute('type'); Chris@0: if ($field_type === 'checkbox') { Chris@0: $value = (bool) $value; Chris@0: } Chris@0: Chris@0: $field->setValue($value); Chris@0: } Chris@0: Chris@0: // Submit form. Chris@0: $this->prepareRequest(); Chris@0: $submit_button->press(); Chris@0: Chris@0: // Ensure that any changes to variables in the other thread are picked up. Chris@0: $this->refreshVariables(); Chris@0: Chris@0: // Check if there are any meta refresh redirects (like Batch API pages). Chris@0: if ($this->checkForMetaRefresh()) { Chris@0: // We are finished with all meta refresh redirects, so reset the counter. Chris@0: $this->metaRefreshCount = 0; Chris@0: } Chris@0: Chris@0: // Log only for JavascriptTestBase tests because for Goutte we log with Chris@0: // ::getResponseLogHandler. Chris@0: if ($this->htmlOutputEnabled && !($this->getSession()->getDriver() instanceof GoutteDriver)) { Chris@0: $out = $this->getSession()->getPage()->getContent(); Chris@0: $html_output = 'POST request to: ' . $action . Chris@0: '
Ending URL: ' . $this->getSession()->getCurrentUrl(); Chris@0: $html_output .= '
' . $out; Chris@0: $html_output .= $this->getHtmlOutputHeaders(); Chris@0: $this->htmlOutput($html_output); Chris@0: } Chris@0: Chris@0: } Chris@0: Chris@0: /** Chris@0: * Executes a form submission. Chris@0: * Chris@0: * It will be done as usual POST request with Mink. Chris@0: * Chris@0: * @param \Drupal\Core\Url|string $path Chris@0: * Location of the post form. Either a Drupal path or an absolute path or Chris@0: * NULL to post to the current page. For multi-stage forms you can set the Chris@0: * path to NULL and have it post to the last received page. Example: Chris@0: * Chris@0: * @code Chris@0: * // First step in form. Chris@0: * $edit = array(...); Chris@0: * $this->drupalPostForm('some_url', $edit, 'Save'); Chris@0: * Chris@0: * // Second step in form. Chris@0: * $edit = array(...); Chris@0: * $this->drupalPostForm(NULL, $edit, 'Save'); Chris@0: * @endcode Chris@0: * @param array $edit Chris@0: * Field data in an associative array. Changes the current input fields Chris@0: * (where possible) to the values indicated. Chris@0: * Chris@0: * When working with form tests, the keys for an $edit element should match Chris@0: * the 'name' parameter of the HTML of the form. For example, the 'body' Chris@0: * field for a node has the following HTML: Chris@0: * @code Chris@0: * Chris@0: * @endcode Chris@0: * When testing this field using an $edit parameter, the code becomes: Chris@0: * @code Chris@0: * $edit["body[0][value]"] = 'My test value'; Chris@0: * @endcode Chris@0: * Chris@0: * A checkbox can be set to TRUE to be checked and should be set to FALSE to Chris@0: * be unchecked. Multiple select fields can be tested using 'name[]' and Chris@0: * setting each of the desired values in an array: Chris@0: * @code Chris@0: * $edit = array(); Chris@0: * $edit['name[]'] = array('value1', 'value2'); Chris@0: * @endcode Chris@0: * @todo change $edit to disallow NULL as a value for Drupal 9. Chris@0: * https://www.drupal.org/node/2802401 Chris@0: * @param string $submit Chris@0: * Value of the submit button whose click is to be emulated. For example, Chris@0: * 'Save'. The processing of the request depends on this value. For example, Chris@0: * a form may have one button with the value 'Save' and another button with Chris@0: * the value 'Delete', and execute different code depending on which one is Chris@0: * clicked. Chris@0: * Chris@0: * This function can also be called to emulate an Ajax submission. In this Chris@0: * case, this value needs to be an array with the following keys: Chris@0: * - path: A path to submit the form values to for Ajax-specific processing. Chris@0: * - triggering_element: If the value for the 'path' key is a generic Ajax Chris@0: * processing path, this needs to be set to the name of the element. If Chris@0: * the name doesn't identify the element uniquely, then this should Chris@0: * instead be an array with a single key/value pair, corresponding to the Chris@0: * element name and value. The \Drupal\Core\Form\FormAjaxResponseBuilder Chris@0: * uses this to find the #ajax information for the element, including Chris@0: * which specific callback to use for processing the request. Chris@0: * Chris@0: * This can also be set to NULL in order to emulate an Internet Explorer Chris@0: * submission of a form with a single text field, and pressing ENTER in that Chris@0: * textfield: under these conditions, no button information is added to the Chris@0: * POST data. Chris@0: * @param array $options Chris@0: * Options to be forwarded to the url generator. Chris@0: * Chris@0: * @return string Chris@0: * (deprecated) The response content after submit form. It is necessary for Chris@0: * backwards compatibility and will be removed before Drupal 9.0. You should Chris@0: * just use the webAssert object for your assertions. Chris@0: */ Chris@0: protected function drupalPostForm($path, $edit, $submit, array $options = []) { Chris@0: if (is_object($submit)) { Chris@0: // Cast MarkupInterface objects to string. Chris@0: $submit = (string) $submit; Chris@0: } Chris@0: if ($edit === NULL) { Chris@0: $edit = []; Chris@0: } Chris@0: if (is_array($edit)) { Chris@0: $edit = $this->castSafeStrings($edit); Chris@0: } Chris@0: Chris@0: if (isset($path)) { Chris@0: $this->drupalGet($path, $options); Chris@0: } Chris@0: Chris@0: $this->submitForm($edit, $submit); Chris@0: Chris@0: return $this->getSession()->getPage()->getContent(); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Helper function to get the options of select field. Chris@0: * Chris@0: * @param \Behat\Mink\Element\NodeElement|string $select Chris@0: * Name, ID, or Label of select field to assert. Chris@0: * @param \Behat\Mink\Element\Element $container Chris@0: * (optional) Container element to check against. Defaults to current page. Chris@0: * Chris@0: * @return array Chris@0: * Associative array of option keys and values. Chris@0: */ Chris@0: protected function getOptions($select, Element $container = NULL) { Chris@0: if (is_string($select)) { Chris@0: $select = $this->assertSession()->selectExists($select, $container); Chris@0: } Chris@0: $options = []; Chris@0: /* @var \Behat\Mink\Element\NodeElement $option */ Chris@0: foreach ($select->findAll('xpath', '//option') as $option) { Chris@0: $label = $option->getText(); Chris@0: $value = $option->getAttribute('value') ?: $label; Chris@0: $options[$value] = $label; Chris@0: } Chris@0: return $options; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Installs Drupal into the Simpletest site. Chris@0: */ Chris@0: public function installDrupal() { Chris@0: $this->initUserSession(); Chris@0: $this->prepareSettings(); Chris@0: $this->doInstall(); Chris@0: $this->initSettings(); Chris@0: $container = $this->initKernel(\Drupal::request()); Chris@0: $this->initConfig($container); Chris@0: $this->installModulesFromClassProperty($container); Chris@0: $this->rebuildAll(); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns whether a given user account is logged in. Chris@0: * Chris@0: * @param \Drupal\Core\Session\AccountInterface $account Chris@0: * The user account object to check. Chris@0: * Chris@0: * @return bool Chris@0: * Return TRUE if the user is logged in, FALSE otherwise. Chris@0: */ Chris@0: protected function drupalUserIsLoggedIn(AccountInterface $account) { Chris@0: $logged_in = FALSE; Chris@0: Chris@0: if (isset($account->sessionId)) { Chris@0: $session_handler = $this->container->get('session_handler.storage'); Chris@0: $logged_in = (bool) $session_handler->read($account->sessionId); Chris@0: } Chris@0: Chris@0: return $logged_in; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Clicks the element with the given CSS selector. Chris@0: * Chris@0: * @param string $css_selector Chris@0: * The CSS selector identifying the element to click. Chris@0: */ Chris@0: protected function click($css_selector) { Chris@0: $this->getSession()->getDriver()->click($this->cssSelectToXpath($css_selector)); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Prevents serializing any properties. Chris@0: * Chris@0: * Browser tests are run in a separate process. To do this PHPUnit creates a Chris@0: * script to run the test. If it fails, the test result object will contain a Chris@0: * stack trace which includes the test object. It will attempt to serialize Chris@0: * it. Returning an empty array prevents it from serializing anything it Chris@0: * should not. Chris@0: * Chris@0: * @return array Chris@0: * An empty array. Chris@0: * Chris@0: * @see vendor/phpunit/phpunit/src/Util/PHP/Template/TestCaseMethod.tpl.dist Chris@0: */ Chris@0: public function __sleep() { Chris@0: return []; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Logs a HTML output message in a text file. Chris@0: * Chris@0: * The link to the HTML output message will be printed by the results printer. Chris@0: * Chris@0: * @param string $message Chris@0: * The HTML output message to be stored. Chris@0: * Chris@0: * @see \Drupal\Tests\Listeners\VerbosePrinter::printResult() Chris@0: */ Chris@0: protected function htmlOutput($message) { Chris@0: if (!$this->htmlOutputEnabled) { Chris@0: return; Chris@0: } Chris@0: $message = '
ID #' . $this->htmlOutputCounter . ' (Previous | Next)
' . $message; Chris@0: $html_output_filename = $this->htmlOutputClassName . '-' . $this->htmlOutputCounter . '-' . $this->htmlOutputTestId . '.html'; Chris@0: file_put_contents($this->htmlOutputDirectory . '/' . $html_output_filename, $message); Chris@0: file_put_contents($this->htmlOutputCounterStorage, $this->htmlOutputCounter++); Chris@0: file_put_contents($this->htmlOutputFile, file_create_url('sites/simpletest/browser_output/' . $html_output_filename) . "\n", FILE_APPEND); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns headers in HTML output format. Chris@0: * Chris@0: * @return string Chris@0: * HTML output headers. Chris@0: */ Chris@0: protected function getHtmlOutputHeaders() { Chris@0: return $this->formatHtmlOutputHeaders($this->getSession()->getResponseHeaders()); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Formats HTTP headers as string for HTML output logging. Chris@0: * Chris@0: * @param array[] $headers Chris@0: * Headers that should be formatted. Chris@0: * Chris@0: * @return string Chris@0: * The formatted HTML string. Chris@0: */ Chris@0: protected function formatHtmlOutputHeaders(array $headers) { Chris@0: $flattened_headers = array_map(function ($header) { Chris@0: if (is_array($header)) { Chris@0: return implode(';', array_map('trim', $header)); Chris@0: } Chris@0: else { Chris@0: return $header; Chris@0: } Chris@0: }, $headers); Chris@0: return '
Headers:
' . Html::escape(var_export($flattened_headers, TRUE)) . '
'; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Translates a CSS expression to its XPath equivalent. Chris@0: * Chris@0: * The search is relative to the root element (HTML tag normally) of the page. Chris@0: * Chris@0: * @param string $selector Chris@0: * CSS selector to use in the search. Chris@0: * @param bool $html Chris@0: * (optional) Enables HTML support. Disable it for XML documents. Chris@0: * @param string $prefix Chris@0: * (optional) The prefix for the XPath expression. Chris@0: * Chris@0: * @return string Chris@0: * The equivalent XPath of a CSS expression. Chris@0: */ Chris@0: protected function cssSelectToXpath($selector, $html = TRUE, $prefix = 'descendant-or-self::') { Chris@0: return (new CssSelectorConverter($html))->toXPath($selector, $prefix); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Searches elements using a CSS selector in the raw content. Chris@0: * Chris@0: * The search is relative to the root element (HTML tag normally) of the page. Chris@0: * Chris@0: * @param string $selector Chris@0: * CSS selector to use in the search. Chris@0: * Chris@0: * @return \Behat\Mink\Element\NodeElement[] Chris@0: * The list of elements on the page that match the selector. Chris@0: */ Chris@0: protected function cssSelect($selector) { Chris@0: return $this->getSession()->getPage()->findAll('css', $selector); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Follows a link by complete name. Chris@0: * Chris@0: * Will click the first link found with this link text. Chris@0: * Chris@0: * If the link is discovered and clicked, the test passes. Fail otherwise. Chris@0: * Chris@0: * @param string|\Drupal\Component\Render\MarkupInterface $label Chris@0: * Text between the anchor tags. Chris@0: * @param int $index Chris@0: * (optional) The index number for cases where multiple links have the same Chris@0: * text. Defaults to 0. Chris@0: */ Chris@0: protected function clickLink($label, $index = 0) { Chris@0: $label = (string) $label; Chris@0: $links = $this->getSession()->getPage()->findAll('named', ['link', $label]); Chris@0: $this->assertArrayHasKey($index, $links, 'The link ' . $label . ' was not found on the page.'); Chris@0: $links[$index]->click(); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Retrieves the plain-text content from the current page. Chris@0: */ Chris@0: protected function getTextContent() { Chris@0: return $this->getSession()->getPage()->getText(); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Performs an xpath search on the contents of the internal browser. Chris@0: * Chris@0: * The search is relative to the root element (HTML tag normally) of the page. Chris@0: * Chris@0: * @param string $xpath Chris@0: * The xpath string to use in the search. Chris@0: * @param array $arguments Chris@0: * An array of arguments with keys in the form ':name' matching the Chris@0: * placeholders in the query. The values may be either strings or numeric Chris@0: * values. Chris@0: * Chris@0: * @return \Behat\Mink\Element\NodeElement[] Chris@0: * The list of elements matching the xpath expression. Chris@0: */ Chris@0: protected function xpath($xpath, array $arguments = []) { Chris@0: $xpath = $this->assertSession()->buildXPathQuery($xpath, $arguments); Chris@0: return $this->getSession()->getPage()->findAll('xpath', $xpath); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Configuration accessor for tests. Returns non-overridden configuration. Chris@0: * Chris@0: * @param string $name Chris@0: * Configuration name. Chris@0: * Chris@0: * @return \Drupal\Core\Config\Config Chris@0: * The configuration object with original configuration data. Chris@0: */ Chris@0: protected function config($name) { Chris@0: return $this->container->get('config.factory')->getEditable($name); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns all response headers. Chris@0: * Chris@0: * @return array Chris@0: * The HTTP headers values. Chris@0: * Chris@0: * @deprecated Scheduled for removal in Drupal 9.0.0. Chris@0: * Use $this->getSession()->getResponseHeaders() instead. Chris@0: */ Chris@0: protected function drupalGetHeaders() { Chris@0: return $this->getSession()->getResponseHeaders(); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets the value of an HTTP response header. Chris@0: * Chris@0: * If multiple requests were required to retrieve the page, only the headers Chris@0: * from the last request will be checked by default. Chris@0: * Chris@0: * @param string $name Chris@0: * The name of the header to retrieve. Names are case-insensitive (see RFC Chris@0: * 2616 section 4.2). Chris@0: * Chris@0: * @return string|null Chris@0: * The HTTP header value or NULL if not found. Chris@0: */ Chris@0: protected function drupalGetHeader($name) { Chris@0: return $this->getSession()->getResponseHeader($name); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Get the current URL from the browser. Chris@0: * Chris@0: * @return string Chris@0: * The current URL. Chris@0: */ Chris@0: protected function getUrl() { Chris@0: return $this->getSession()->getCurrentUrl(); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets the JavaScript drupalSettings variable for the currently-loaded page. Chris@0: * Chris@0: * @return array Chris@0: * The JSON decoded drupalSettings value from the current page. Chris@0: */ Chris@0: protected function getDrupalSettings() { Chris@0: $html = $this->getSession()->getPage()->getHtml(); Chris@0: if (preg_match('@@', $html, $matches)) { Chris@0: return Json::decode($matches[1]); Chris@0: } Chris@0: return []; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public static function assertEquals($expected, $actual, $message = '', $delta = 0.0, $maxDepth = 10, $canonicalize = FALSE, $ignoreCase = FALSE) { Chris@0: // Cast objects implementing MarkupInterface to string instead of Chris@0: // relying on PHP casting them to string depending on what they are being Chris@0: // comparing with. Chris@0: $expected = static::castSafeStrings($expected); Chris@0: $actual = static::castSafeStrings($actual); Chris@0: parent::assertEquals($expected, $actual, $message, $delta, $maxDepth, $canonicalize, $ignoreCase); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Retrieves the current calling line in the class under test. Chris@0: * Chris@0: * @return array Chris@0: * An associative array with keys 'file', 'line' and 'function'. Chris@0: */ Chris@0: protected function getTestMethodCaller() { Chris@0: $backtrace = debug_backtrace(); Chris@0: // Find the test class that has the test method. Chris@0: while ($caller = Error::getLastCaller($backtrace)) { Chris@0: if (isset($caller['class']) && $caller['class'] === get_class($this)) { Chris@0: break; Chris@0: } Chris@0: // If the test method is implemented by a test class's parent then the Chris@0: // class name of $this will not be part of the backtrace. Chris@0: // In that case we process the backtrace until the caller is not a Chris@0: // subclass of $this and return the previous caller. Chris@0: if (isset($last_caller) && (!isset($caller['class']) || !is_subclass_of($this, $caller['class']))) { Chris@0: // Return the last caller since that has to be the test class. Chris@0: $caller = $last_caller; Chris@0: break; Chris@0: } Chris@0: // Otherwise we have not reached our test class yet: save the last caller Chris@0: // and remove an element from to backtrace to process the next call. Chris@0: $last_caller = $caller; Chris@0: array_shift($backtrace); Chris@0: } Chris@0: Chris@0: return $caller; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Transforms a nested array into a flat array suitable for drupalPostForm(). Chris@0: * Chris@0: * @param array $values Chris@0: * A multi-dimensional form values array to convert. Chris@0: * Chris@0: * @return array Chris@0: * The flattened $edit array suitable for BrowserTestBase::drupalPostForm(). Chris@0: */ Chris@0: protected function translatePostValues(array $values) { Chris@0: $edit = []; Chris@0: // The easiest and most straightforward way to translate values suitable for Chris@0: // BrowserTestBase::drupalPostForm() is to actually build the POST data Chris@0: // string and convert the resulting key/value pairs back into a flat array. Chris@0: $query = http_build_query($values); Chris@0: foreach (explode('&', $query) as $item) { Chris@0: list($key, $value) = explode('=', $item); Chris@0: $edit[urldecode($key)] = urldecode($value); Chris@0: } Chris@0: return $edit; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Checks for meta refresh tag and if found call drupalGet() recursively. Chris@0: * Chris@0: * This function looks for the http-equiv attribute to be set to "Refresh" and Chris@0: * is case-insensitive. Chris@0: * Chris@0: * @return string|false Chris@0: * Either the new page content or FALSE. Chris@0: */ Chris@0: protected function checkForMetaRefresh() { Chris@0: $refresh = $this->cssSelect('meta[http-equiv="Refresh"], meta[http-equiv="refresh"]'); Chris@0: if (!empty($refresh) && (!isset($this->maximumMetaRefreshCount) || $this->metaRefreshCount < $this->maximumMetaRefreshCount)) { Chris@0: // Parse the content attribute of the meta tag for the format: Chris@0: // "[delay]: URL=[page_to_redirect_to]". Chris@0: if (preg_match('/\d+;\s*URL=(?.*)/i', $refresh[0]->getAttribute('content'), $match)) { Chris@0: $this->metaRefreshCount++; Chris@0: return $this->drupalGet($this->getAbsoluteUrl(Html::decodeEntities($match['url']))); Chris@0: } Chris@0: } Chris@0: return FALSE; Chris@0: } Chris@0: Chris@0: }