Chris@17: assertSession();
Chris@17:
Chris@17: // Get the form.
Chris@17: if (isset($form_html_id)) {
Chris@17: $form = $assert_session->elementExists('xpath', "//form[@id='$form_html_id']");
Chris@17: $submit_button = $assert_session->buttonExists($submit, $form);
Chris@17: $action = $form->getAttribute('action');
Chris@17: }
Chris@17: else {
Chris@17: $submit_button = $assert_session->buttonExists($submit);
Chris@17: $form = $assert_session->elementExists('xpath', './ancestor::form', $submit_button);
Chris@17: $action = $form->getAttribute('action');
Chris@17: }
Chris@17:
Chris@17: // Edit the form values.
Chris@17: foreach ($edit as $name => $value) {
Chris@17: $field = $assert_session->fieldExists($name, $form);
Chris@17:
Chris@17: // Provide support for the values '1' and '0' for checkboxes instead of
Chris@17: // TRUE and FALSE.
Chris@17: // @todo Get rid of supporting 1/0 by converting all tests cases using
Chris@17: // this to boolean values.
Chris@17: $field_type = $field->getAttribute('type');
Chris@17: if ($field_type === 'checkbox') {
Chris@17: $value = (bool) $value;
Chris@17: }
Chris@17:
Chris@17: $field->setValue($value);
Chris@17: }
Chris@17:
Chris@17: // Submit form.
Chris@17: $this->prepareRequest();
Chris@17: $submit_button->press();
Chris@17:
Chris@17: // Ensure that any changes to variables in the other thread are picked up.
Chris@17: $this->refreshVariables();
Chris@17:
Chris@17: // Check if there are any meta refresh redirects (like Batch API pages).
Chris@17: if ($this->checkForMetaRefresh()) {
Chris@17: // We are finished with all meta refresh redirects, so reset the counter.
Chris@17: $this->metaRefreshCount = 0;
Chris@17: }
Chris@17:
Chris@17: // Log only for JavascriptTestBase tests because for Goutte we log with
Chris@17: // ::getResponseLogHandler.
Chris@17: if ($this->htmlOutputEnabled && !($this->getSession()->getDriver() instanceof GoutteDriver)) {
Chris@17: $out = $this->getSession()->getPage()->getContent();
Chris@17: $html_output = 'POST request to: ' . $action .
Chris@17: '
Ending URL: ' . $this->getSession()->getCurrentUrl();
Chris@17: $html_output .= '
' . $out;
Chris@17: $html_output .= $this->getHtmlOutputHeaders();
Chris@17: $this->htmlOutput($html_output);
Chris@17: }
Chris@17:
Chris@17: }
Chris@17:
Chris@17: /**
Chris@17: * Executes a form submission.
Chris@17: *
Chris@17: * It will be done as usual submit form with Mink.
Chris@17: *
Chris@17: * @param \Drupal\Core\Url|string $path
Chris@17: * Location of the post form. Either a Drupal path or an absolute path or
Chris@17: * NULL to post to the current page. For multi-stage forms you can set the
Chris@17: * path to NULL and have it post to the last received page. Example:
Chris@17: *
Chris@17: * @code
Chris@17: * // First step in form.
Chris@17: * $edit = array(...);
Chris@17: * $this->drupalPostForm('some_url', $edit, 'Save');
Chris@17: *
Chris@17: * // Second step in form.
Chris@17: * $edit = array(...);
Chris@17: * $this->drupalPostForm(NULL, $edit, 'Save');
Chris@17: * @endcode
Chris@17: * @param array $edit
Chris@17: * Field data in an associative array. Changes the current input fields
Chris@17: * (where possible) to the values indicated.
Chris@17: *
Chris@17: * When working with form tests, the keys for an $edit element should match
Chris@17: * the 'name' parameter of the HTML of the form. For example, the 'body'
Chris@17: * field for a node has the following HTML:
Chris@17: * @code
Chris@17: *
Chris@17: * @endcode
Chris@17: * When testing this field using an $edit parameter, the code becomes:
Chris@17: * @code
Chris@17: * $edit["body[0][value]"] = 'My test value';
Chris@17: * @endcode
Chris@17: *
Chris@17: * A checkbox can be set to TRUE to be checked and should be set to FALSE to
Chris@17: * be unchecked. Multiple select fields can be tested using 'name[]' and
Chris@17: * setting each of the desired values in an array:
Chris@17: * @code
Chris@17: * $edit = array();
Chris@17: * $edit['name[]'] = array('value1', 'value2');
Chris@17: * @endcode
Chris@17: * @todo change $edit to disallow NULL as a value for Drupal 9.
Chris@17: * https://www.drupal.org/node/2802401
Chris@17: * @param string $submit
Chris@17: * The id, name, label or value of the submit button which is to be clicked.
Chris@17: * For example, 'Save'. The first element matched by
Chris@17: * \Drupal\Tests\WebAssert::buttonExists() will be used. The processing of
Chris@17: * the request depends on this value. For example, a form may have one
Chris@17: * button with the value 'Save' and another button with the value 'Delete',
Chris@17: * and execute different code depending on which one is clicked.
Chris@17: * @param array $options
Chris@17: * Options to be forwarded to the url generator.
Chris@17: * @param string|null $form_html_id
Chris@17: * (optional) HTML ID of the form to be submitted. On some pages
Chris@17: * there are many identical forms, so just using the value of the submit
Chris@17: * button is not enough. For example: 'trigger-node-presave-assign-form'.
Chris@17: * Note that this is not the Drupal $form_id, but rather the HTML ID of the
Chris@17: * form, which is typically the same thing but with hyphens replacing the
Chris@17: * underscores.
Chris@17: *
Chris@17: * @return string
Chris@17: * (deprecated) The response content after submit form. It is necessary for
Chris@17: * backwards compatibility and will be removed before Drupal 9.0. You should
Chris@17: * just use the webAssert object for your assertions.
Chris@17: *
Chris@17: * @see \Drupal\Tests\WebAssert::buttonExists()
Chris@17: */
Chris@17: protected function drupalPostForm($path, $edit, $submit, array $options = [], $form_html_id = NULL) {
Chris@17: if (is_object($submit)) {
Chris@17: // Cast MarkupInterface objects to string.
Chris@17: $submit = (string) $submit;
Chris@17: }
Chris@17: if ($edit === NULL) {
Chris@17: $edit = [];
Chris@17: }
Chris@17: if (is_array($edit)) {
Chris@17: $edit = $this->castSafeStrings($edit);
Chris@17: }
Chris@17:
Chris@17: if (isset($path)) {
Chris@17: $this->drupalGet($path, $options);
Chris@17: }
Chris@17:
Chris@17: $this->submitForm($edit, $submit, $form_html_id);
Chris@17:
Chris@17: return $this->getSession()->getPage()->getContent();
Chris@17: }
Chris@17:
Chris@17: /**
Chris@17: * Logs in a user using the Mink controlled browser.
Chris@17: *
Chris@17: * If a user is already logged in, then the current user is logged out before
Chris@17: * logging in the specified user.
Chris@17: *
Chris@17: * Please note that neither the current user nor the passed-in user object is
Chris@17: * populated with data of the logged in user. If you need full access to the
Chris@17: * user object after logging in, it must be updated manually. If you also need
Chris@17: * access to the plain-text password of the user (set by drupalCreateUser()),
Chris@17: * e.g. to log in the same user again, then it must be re-assigned manually.
Chris@17: * For example:
Chris@17: * @code
Chris@17: * // Create a user.
Chris@17: * $account = $this->drupalCreateUser(array());
Chris@17: * $this->drupalLogin($account);
Chris@17: * // Load real user object.
Chris@17: * $pass_raw = $account->passRaw;
Chris@17: * $account = User::load($account->id());
Chris@17: * $account->passRaw = $pass_raw;
Chris@17: * @endcode
Chris@17: *
Chris@17: * @param \Drupal\Core\Session\AccountInterface $account
Chris@17: * User object representing the user to log in.
Chris@17: *
Chris@17: * @see drupalCreateUser()
Chris@17: */
Chris@17: protected function drupalLogin(AccountInterface $account) {
Chris@17: if ($this->loggedInUser) {
Chris@17: $this->drupalLogout();
Chris@17: }
Chris@17:
Chris@17: $this->drupalGet('user/login');
Chris@17: $this->submitForm([
Chris@18: 'name' => $account->getAccountName(),
Chris@17: 'pass' => $account->passRaw,
Chris@17: ], t('Log in'));
Chris@17:
Chris@17: // @see ::drupalUserIsLoggedIn()
Chris@17: $account->sessionId = $this->getSession()->getCookie(\Drupal::service('session_configuration')->getOptions(\Drupal::request())['name']);
Chris@17: $this->assertTrue($this->drupalUserIsLoggedIn($account), new FormattableMarkup('User %name successfully logged in.', ['%name' => $account->getAccountName()]));
Chris@17:
Chris@17: $this->loggedInUser = $account;
Chris@17: $this->container->get('current_user')->setAccount($account);
Chris@17: }
Chris@17:
Chris@17: /**
Chris@17: * Logs a user out of the Mink controlled browser and confirms.
Chris@17: *
Chris@17: * Confirms logout by checking the login page.
Chris@17: */
Chris@17: protected function drupalLogout() {
Chris@17: // Make a request to the logout page, and redirect to the user page, the
Chris@17: // idea being if you were properly logged out you should be seeing a login
Chris@17: // screen.
Chris@17: $assert_session = $this->assertSession();
Chris@17: $this->drupalGet('user/logout', ['query' => ['destination' => 'user']]);
Chris@17: $assert_session->fieldExists('name');
Chris@17: $assert_session->fieldExists('pass');
Chris@17:
Chris@17: // @see BrowserTestBase::drupalUserIsLoggedIn()
Chris@17: unset($this->loggedInUser->sessionId);
Chris@17: $this->loggedInUser = FALSE;
Chris@17: \Drupal::currentUser()->setAccount(new AnonymousUserSession());
Chris@17: }
Chris@17:
Chris@17: /**
Chris@17: * Returns WebAssert object.
Chris@17: *
Chris@17: * @param string $name
Chris@17: * (optional) Name of the session. Defaults to the active session.
Chris@17: *
Chris@17: * @return \Drupal\Tests\WebAssert
Chris@17: * A new web-assert option for asserting the presence of elements with.
Chris@17: */
Chris@17: public function assertSession($name = NULL) {
Chris@17: $this->addToAssertionCount(1);
Chris@17: return new WebAssert($this->getSession($name), $this->baseUrl);
Chris@17: }
Chris@17:
Chris@17: /**
Chris@17: * Retrieves a Drupal path or an absolute path.
Chris@17: *
Chris@17: * @param string|\Drupal\Core\Url $path
Chris@17: * Drupal path or URL to load into Mink controlled browser.
Chris@17: * @param array $options
Chris@17: * (optional) Options to be forwarded to the url generator.
Chris@17: * @param string[] $headers
Chris@17: * An array containing additional HTTP request headers, the array keys are
Chris@17: * the header names and the array values the header values. This is useful
Chris@17: * to set for example the "Accept-Language" header for requesting the page
Chris@17: * in a different language. Note that not all headers are supported, for
Chris@17: * example the "Accept" header is always overridden by the browser. For
Chris@17: * testing REST APIs it is recommended to obtain a separate HTTP client
Chris@17: * using getHttpClient() and performing requests that way.
Chris@17: *
Chris@17: * @return string
Chris@17: * The retrieved HTML string, also available as $this->getRawContent()
Chris@17: *
Chris@17: * @see \Drupal\Tests\BrowserTestBase::getHttpClient()
Chris@17: */
Chris@17: protected function drupalGet($path, array $options = [], array $headers = []) {
Chris@17: $options['absolute'] = TRUE;
Chris@17: $url = $this->buildUrl($path, $options);
Chris@17:
Chris@17: $session = $this->getSession();
Chris@17:
Chris@17: $this->prepareRequest();
Chris@17: foreach ($headers as $header_name => $header_value) {
Chris@17: $session->setRequestHeader($header_name, $header_value);
Chris@17: }
Chris@17:
Chris@17: $session->visit($url);
Chris@17: $out = $session->getPage()->getContent();
Chris@17:
Chris@17: // Ensure that any changes to variables in the other thread are picked up.
Chris@17: $this->refreshVariables();
Chris@17:
Chris@17: // Replace original page output with new output from redirected page(s).
Chris@17: if ($new = $this->checkForMetaRefresh()) {
Chris@17: $out = $new;
Chris@17: // We are finished with all meta refresh redirects, so reset the counter.
Chris@17: $this->metaRefreshCount = 0;
Chris@17: }
Chris@17:
Chris@17: // Log only for JavascriptTestBase tests because for Goutte we log with
Chris@17: // ::getResponseLogHandler.
Chris@17: if ($this->htmlOutputEnabled && !($this->getSession()->getDriver() instanceof GoutteDriver)) {
Chris@17: $html_output = 'GET request to: ' . $url .
Chris@17: '
Ending URL: ' . $this->getSession()->getCurrentUrl();
Chris@17: $html_output .= '
' . $out;
Chris@17: $html_output .= $this->getHtmlOutputHeaders();
Chris@17: $this->htmlOutput($html_output);
Chris@17: }
Chris@17:
Chris@17: return $out;
Chris@17: }
Chris@17:
Chris@17: /**
Chris@17: * Builds an a absolute URL from a system path or a URL object.
Chris@17: *
Chris@17: * @param string|\Drupal\Core\Url $path
Chris@17: * A system path or a URL.
Chris@17: * @param array $options
Chris@17: * Options to be passed to Url::fromUri().
Chris@17: *
Chris@17: * @return string
Chris@17: * An absolute URL string.
Chris@17: */
Chris@17: protected function buildUrl($path, array $options = []) {
Chris@17: if ($path instanceof Url) {
Chris@17: $url_options = $path->getOptions();
Chris@17: $options = $url_options + $options;
Chris@17: $path->setOptions($options);
Chris@17: return $path->setAbsolute()->toString();
Chris@17: }
Chris@17: // The URL generator service is not necessarily available yet; e.g., in
Chris@17: // interactive installer tests.
Chris@17: elseif (\Drupal::hasService('url_generator')) {
Chris@17: $force_internal = isset($options['external']) && $options['external'] == FALSE;
Chris@17: if (!$force_internal && UrlHelper::isExternal($path)) {
Chris@17: return Url::fromUri($path, $options)->toString();
Chris@17: }
Chris@17: else {
Chris@17: $uri = $path === '' ? 'base:/' : 'base:/' . $path;
Chris@17: // Path processing is needed for language prefixing. Skip it when a
Chris@17: // path that may look like an external URL is being used as internal.
Chris@17: $options['path_processing'] = !$force_internal;
Chris@17: return Url::fromUri($uri, $options)
Chris@17: ->setAbsolute()
Chris@17: ->toString();
Chris@17: }
Chris@17: }
Chris@17: else {
Chris@17: return $this->getAbsoluteUrl($path);
Chris@17: }
Chris@17: }
Chris@17:
Chris@17: /**
Chris@17: * Takes a path and returns an absolute path.
Chris@17: *
Chris@17: * @param string $path
Chris@17: * A path from the Mink controlled browser content.
Chris@17: *
Chris@17: * @return string
Chris@17: * The $path with $base_url prepended, if necessary.
Chris@17: */
Chris@17: protected function getAbsoluteUrl($path) {
Chris@17: global $base_url, $base_path;
Chris@17:
Chris@17: $parts = parse_url($path);
Chris@17: if (empty($parts['host'])) {
Chris@17: // Ensure that we have a string (and no xpath object).
Chris@17: $path = (string) $path;
Chris@17: // Strip $base_path, if existent.
Chris@17: $length = strlen($base_path);
Chris@17: if (substr($path, 0, $length) === $base_path) {
Chris@17: $path = substr($path, $length);
Chris@17: }
Chris@17: // Ensure that we have an absolute path.
Chris@17: if (empty($path) || $path[0] !== '/') {
Chris@17: $path = '/' . $path;
Chris@17: }
Chris@17: // Finally, prepend the $base_url.
Chris@17: $path = $base_url . $path;
Chris@17: }
Chris@17: return $path;
Chris@17: }
Chris@17:
Chris@17: /**
Chris@17: * Prepare for a request to testing site.
Chris@17: *
Chris@17: * The testing site is protected via a SIMPLETEST_USER_AGENT cookie that is
Chris@17: * checked by drupal_valid_test_ua().
Chris@17: *
Chris@17: * @see drupal_valid_test_ua()
Chris@17: */
Chris@17: protected function prepareRequest() {
Chris@17: $session = $this->getSession();
Chris@17: $session->setCookie('SIMPLETEST_USER_AGENT', drupal_generate_test_ua($this->databasePrefix));
Chris@17: }
Chris@17:
Chris@17: /**
Chris@17: * Returns whether a given user account is logged in.
Chris@17: *
Chris@17: * @param \Drupal\Core\Session\AccountInterface $account
Chris@17: * The user account object to check.
Chris@17: *
Chris@17: * @return bool
Chris@17: * Return TRUE if the user is logged in, FALSE otherwise.
Chris@17: */
Chris@17: protected function drupalUserIsLoggedIn(AccountInterface $account) {
Chris@17: $logged_in = FALSE;
Chris@17:
Chris@17: if (isset($account->sessionId)) {
Chris@17: $session_handler = \Drupal::service('session_handler.storage');
Chris@17: $logged_in = (bool) $session_handler->read($account->sessionId);
Chris@17: }
Chris@17:
Chris@17: return $logged_in;
Chris@17: }
Chris@17:
Chris@17: /**
Chris@17: * Clicks the element with the given CSS selector.
Chris@17: *
Chris@17: * @param string $css_selector
Chris@17: * The CSS selector identifying the element to click.
Chris@17: */
Chris@17: protected function click($css_selector) {
Chris@17: $starting_url = $this->getSession()->getCurrentUrl();
Chris@17: $this->getSession()->getDriver()->click($this->cssSelectToXpath($css_selector));
Chris@17: // Log only for JavascriptTestBase tests because for Goutte we log with
Chris@17: // ::getResponseLogHandler.
Chris@17: if ($this->htmlOutputEnabled && !($this->getSession()->getDriver() instanceof GoutteDriver)) {
Chris@17: $out = $this->getSession()->getPage()->getContent();
Chris@17: $html_output =
Chris@17: 'Clicked element with CSS selector: ' . $css_selector .
Chris@17: '
Starting URL: ' . $starting_url .
Chris@17: '
Ending URL: ' . $this->getSession()->getCurrentUrl();
Chris@17: $html_output .= '
' . $out;
Chris@17: $html_output .= $this->getHtmlOutputHeaders();
Chris@17: $this->htmlOutput($html_output);
Chris@17: }
Chris@17: }
Chris@17:
Chris@17: /**
Chris@17: * Follows a link by complete name.
Chris@17: *
Chris@17: * Will click the first link found with this link text.
Chris@17: *
Chris@17: * If the link is discovered and clicked, the test passes. Fail otherwise.
Chris@17: *
Chris@17: * @param string|\Drupal\Component\Render\MarkupInterface $label
Chris@17: * Text between the anchor tags.
Chris@17: * @param int $index
Chris@17: * (optional) The index number for cases where multiple links have the same
Chris@17: * text. Defaults to 0.
Chris@17: */
Chris@17: protected function clickLink($label, $index = 0) {
Chris@17: $label = (string) $label;
Chris@17: $links = $this->getSession()->getPage()->findAll('named', ['link', $label]);
Chris@17: $this->assertArrayHasKey($index, $links, 'The link ' . $label . ' was not found on the page.');
Chris@17: $links[$index]->click();
Chris@17: }
Chris@17:
Chris@17: /**
Chris@17: * Retrieves the plain-text content from the current page.
Chris@17: */
Chris@17: protected function getTextContent() {
Chris@17: return $this->getSession()->getPage()->getText();
Chris@17: }
Chris@17:
Chris@17: /**
Chris@17: * Get the current URL from the browser.
Chris@17: *
Chris@17: * @return string
Chris@17: * The current URL.
Chris@17: */
Chris@17: protected function getUrl() {
Chris@17: return $this->getSession()->getCurrentUrl();
Chris@17: }
Chris@17:
Chris@17: /**
Chris@17: * Checks for meta refresh tag and if found call drupalGet() recursively.
Chris@17: *
Chris@17: * This function looks for the http-equiv attribute to be set to "Refresh" and
Chris@17: * is case-insensitive.
Chris@17: *
Chris@17: * @return string|false
Chris@17: * Either the new page content or FALSE.
Chris@17: */
Chris@17: protected function checkForMetaRefresh() {
Chris@17: $refresh = $this->cssSelect('meta[http-equiv="Refresh"], meta[http-equiv="refresh"]');
Chris@17: if (!empty($refresh) && (!isset($this->maximumMetaRefreshCount) || $this->metaRefreshCount < $this->maximumMetaRefreshCount)) {
Chris@17: // Parse the content attribute of the meta tag for the format:
Chris@17: // "[delay]: URL=[page_to_redirect_to]".
Chris@17: if (preg_match('/\d+;\s*URL=(?.*)/i', $refresh[0]->getAttribute('content'), $match)) {
Chris@17: $this->metaRefreshCount++;
Chris@17: return $this->drupalGet($this->getAbsoluteUrl(Html::decodeEntities($match['url'])));
Chris@17: }
Chris@17: }
Chris@17: return FALSE;
Chris@17: }
Chris@17:
Chris@17: /**
Chris@17: * Searches elements using a CSS selector in the raw content.
Chris@17: *
Chris@17: * The search is relative to the root element (HTML tag normally) of the page.
Chris@17: *
Chris@17: * @param string $selector
Chris@17: * CSS selector to use in the search.
Chris@17: *
Chris@17: * @return \Behat\Mink\Element\NodeElement[]
Chris@17: * The list of elements on the page that match the selector.
Chris@17: */
Chris@17: protected function cssSelect($selector) {
Chris@17: return $this->getSession()->getPage()->findAll('css', $selector);
Chris@17: }
Chris@17:
Chris@17: }