UiHelperTrait.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. <?php
  2. namespace Drupal\Tests;
  3. use Behat\Mink\Driver\GoutteDriver;
  4. use Drupal\Component\Render\FormattableMarkup;
  5. use Drupal\Component\Utility\Html;
  6. use Drupal\Component\Utility\UrlHelper;
  7. use Drupal\Core\Session\AccountInterface;
  8. use Drupal\Core\Session\AnonymousUserSession;
  9. use Drupal\Core\Test\RefreshVariablesTrait;
  10. use Drupal\Core\Url;
  11. /**
  12. * Provides UI helper methods.
  13. */
  14. trait UiHelperTrait {
  15. use BrowserHtmlDebugTrait;
  16. use AssertHelperTrait;
  17. use RefreshVariablesTrait;
  18. /**
  19. * The current user logged in using the Mink controlled browser.
  20. *
  21. * @var \Drupal\user\UserInterface
  22. */
  23. protected $loggedInUser = FALSE;
  24. /**
  25. * The number of meta refresh redirects to follow, or NULL if unlimited.
  26. *
  27. * @var null|int
  28. */
  29. protected $maximumMetaRefreshCount = NULL;
  30. /**
  31. * The number of meta refresh redirects followed during ::drupalGet().
  32. *
  33. * @var int
  34. */
  35. protected $metaRefreshCount = 0;
  36. /**
  37. * Fills and submits a form.
  38. *
  39. * @param array $edit
  40. * Field data in an associative array. Changes the current input fields
  41. * (where possible) to the values indicated.
  42. *
  43. * A checkbox can be set to TRUE to be checked and should be set to FALSE to
  44. * be unchecked.
  45. * @param string $submit
  46. * Value of the submit button whose click is to be emulated. For example,
  47. * 'Save'. The processing of the request depends on this value. For example,
  48. * a form may have one button with the value 'Save' and another button with
  49. * the value 'Delete', and execute different code depending on which one is
  50. * clicked.
  51. * @param string $form_html_id
  52. * (optional) HTML ID of the form to be submitted. On some pages
  53. * there are many identical forms, so just using the value of the submit
  54. * button is not enough. For example: 'trigger-node-presave-assign-form'.
  55. * Note that this is not the Drupal $form_id, but rather the HTML ID of the
  56. * form, which is typically the same thing but with hyphens replacing the
  57. * underscores.
  58. */
  59. protected function submitForm(array $edit, $submit, $form_html_id = NULL) {
  60. $assert_session = $this->assertSession();
  61. // Get the form.
  62. if (isset($form_html_id)) {
  63. $form = $assert_session->elementExists('xpath', "//form[@id='$form_html_id']");
  64. $submit_button = $assert_session->buttonExists($submit, $form);
  65. $action = $form->getAttribute('action');
  66. }
  67. else {
  68. $submit_button = $assert_session->buttonExists($submit);
  69. $form = $assert_session->elementExists('xpath', './ancestor::form', $submit_button);
  70. $action = $form->getAttribute('action');
  71. }
  72. // Edit the form values.
  73. foreach ($edit as $name => $value) {
  74. $field = $assert_session->fieldExists($name, $form);
  75. // Provide support for the values '1' and '0' for checkboxes instead of
  76. // TRUE and FALSE.
  77. // @todo Get rid of supporting 1/0 by converting all tests cases using
  78. // this to boolean values.
  79. $field_type = $field->getAttribute('type');
  80. if ($field_type === 'checkbox') {
  81. $value = (bool) $value;
  82. }
  83. $field->setValue($value);
  84. }
  85. // Submit form.
  86. $this->prepareRequest();
  87. $submit_button->press();
  88. // Ensure that any changes to variables in the other thread are picked up.
  89. $this->refreshVariables();
  90. // Check if there are any meta refresh redirects (like Batch API pages).
  91. if ($this->checkForMetaRefresh()) {
  92. // We are finished with all meta refresh redirects, so reset the counter.
  93. $this->metaRefreshCount = 0;
  94. }
  95. // Log only for JavascriptTestBase tests because for Goutte we log with
  96. // ::getResponseLogHandler.
  97. if ($this->htmlOutputEnabled && !($this->getSession()->getDriver() instanceof GoutteDriver)) {
  98. $out = $this->getSession()->getPage()->getContent();
  99. $html_output = 'POST request to: ' . $action .
  100. '<hr />Ending URL: ' . $this->getSession()->getCurrentUrl();
  101. $html_output .= '<hr />' . $out;
  102. $html_output .= $this->getHtmlOutputHeaders();
  103. $this->htmlOutput($html_output);
  104. }
  105. }
  106. /**
  107. * Executes a form submission.
  108. *
  109. * It will be done as usual submit form with Mink.
  110. *
  111. * @param \Drupal\Core\Url|string $path
  112. * Location of the post form. Either a Drupal path or an absolute path or
  113. * NULL to post to the current page. For multi-stage forms you can set the
  114. * path to NULL and have it post to the last received page. Example:
  115. *
  116. * @code
  117. * // First step in form.
  118. * $edit = array(...);
  119. * $this->drupalPostForm('some_url', $edit, 'Save');
  120. *
  121. * // Second step in form.
  122. * $edit = array(...);
  123. * $this->drupalPostForm(NULL, $edit, 'Save');
  124. * @endcode
  125. * @param array $edit
  126. * Field data in an associative array. Changes the current input fields
  127. * (where possible) to the values indicated.
  128. *
  129. * When working with form tests, the keys for an $edit element should match
  130. * the 'name' parameter of the HTML of the form. For example, the 'body'
  131. * field for a node has the following HTML:
  132. * @code
  133. * <textarea id="edit-body-und-0-value" class="text-full form-textarea
  134. * resize-vertical" placeholder="" cols="60" rows="9"
  135. * name="body[0][value]"></textarea>
  136. * @endcode
  137. * When testing this field using an $edit parameter, the code becomes:
  138. * @code
  139. * $edit["body[0][value]"] = 'My test value';
  140. * @endcode
  141. *
  142. * A checkbox can be set to TRUE to be checked and should be set to FALSE to
  143. * be unchecked. Multiple select fields can be tested using 'name[]' and
  144. * setting each of the desired values in an array:
  145. * @code
  146. * $edit = array();
  147. * $edit['name[]'] = array('value1', 'value2');
  148. * @endcode
  149. * @todo change $edit to disallow NULL as a value for Drupal 9.
  150. * https://www.drupal.org/node/2802401
  151. * @param string $submit
  152. * Value of the submit button whose click is to be emulated. For example,
  153. * 'Save'. The processing of the request depends on this value. For example,
  154. * a form may have one button with the value 'Save' and another button with
  155. * the value 'Delete', and execute different code depending on which one is
  156. * clicked.
  157. *
  158. * This function can also be called to emulate an Ajax submission. In this
  159. * case, this value needs to be an array with the following keys:
  160. * - path: A path to submit the form values to for Ajax-specific processing.
  161. * - triggering_element: If the value for the 'path' key is a generic Ajax
  162. * processing path, this needs to be set to the name of the element. If
  163. * the name doesn't identify the element uniquely, then this should
  164. * instead be an array with a single key/value pair, corresponding to the
  165. * element name and value. The \Drupal\Core\Form\FormAjaxResponseBuilder
  166. * uses this to find the #ajax information for the element, including
  167. * which specific callback to use for processing the request.
  168. *
  169. * This can also be set to NULL in order to emulate an Internet Explorer
  170. * submission of a form with a single text field, and pressing ENTER in that
  171. * textfield: under these conditions, no button information is added to the
  172. * POST data.
  173. * @param array $options
  174. * Options to be forwarded to the url generator.
  175. * @param string|null $form_html_id
  176. * (optional) HTML ID of the form to be submitted. On some pages
  177. * there are many identical forms, so just using the value of the submit
  178. * button is not enough. For example: 'trigger-node-presave-assign-form'.
  179. * Note that this is not the Drupal $form_id, but rather the HTML ID of the
  180. * form, which is typically the same thing but with hyphens replacing the
  181. * underscores.
  182. *
  183. * @return string
  184. * (deprecated) The response content after submit form. It is necessary for
  185. * backwards compatibility and will be removed before Drupal 9.0. You should
  186. * just use the webAssert object for your assertions.
  187. */
  188. protected function drupalPostForm($path, $edit, $submit, array $options = [], $form_html_id = NULL) {
  189. if (is_object($submit)) {
  190. // Cast MarkupInterface objects to string.
  191. $submit = (string) $submit;
  192. }
  193. if ($edit === NULL) {
  194. $edit = [];
  195. }
  196. if (is_array($edit)) {
  197. $edit = $this->castSafeStrings($edit);
  198. }
  199. if (isset($path)) {
  200. $this->drupalGet($path, $options);
  201. }
  202. $this->submitForm($edit, $submit, $form_html_id);
  203. return $this->getSession()->getPage()->getContent();
  204. }
  205. /**
  206. * Logs in a user using the Mink controlled browser.
  207. *
  208. * If a user is already logged in, then the current user is logged out before
  209. * logging in the specified user.
  210. *
  211. * Please note that neither the current user nor the passed-in user object is
  212. * populated with data of the logged in user. If you need full access to the
  213. * user object after logging in, it must be updated manually. If you also need
  214. * access to the plain-text password of the user (set by drupalCreateUser()),
  215. * e.g. to log in the same user again, then it must be re-assigned manually.
  216. * For example:
  217. * @code
  218. * // Create a user.
  219. * $account = $this->drupalCreateUser(array());
  220. * $this->drupalLogin($account);
  221. * // Load real user object.
  222. * $pass_raw = $account->passRaw;
  223. * $account = User::load($account->id());
  224. * $account->passRaw = $pass_raw;
  225. * @endcode
  226. *
  227. * @param \Drupal\Core\Session\AccountInterface $account
  228. * User object representing the user to log in.
  229. *
  230. * @see drupalCreateUser()
  231. */
  232. protected function drupalLogin(AccountInterface $account) {
  233. if ($this->loggedInUser) {
  234. $this->drupalLogout();
  235. }
  236. $this->drupalGet('user/login');
  237. $this->submitForm([
  238. 'name' => $account->getUsername(),
  239. 'pass' => $account->passRaw,
  240. ], t('Log in'));
  241. // @see ::drupalUserIsLoggedIn()
  242. $account->sessionId = $this->getSession()->getCookie(\Drupal::service('session_configuration')->getOptions(\Drupal::request())['name']);
  243. $this->assertTrue($this->drupalUserIsLoggedIn($account), new FormattableMarkup('User %name successfully logged in.', ['%name' => $account->getAccountName()]));
  244. $this->loggedInUser = $account;
  245. $this->container->get('current_user')->setAccount($account);
  246. }
  247. /**
  248. * Logs a user out of the Mink controlled browser and confirms.
  249. *
  250. * Confirms logout by checking the login page.
  251. */
  252. protected function drupalLogout() {
  253. // Make a request to the logout page, and redirect to the user page, the
  254. // idea being if you were properly logged out you should be seeing a login
  255. // screen.
  256. $assert_session = $this->assertSession();
  257. $this->drupalGet('user/logout', ['query' => ['destination' => 'user']]);
  258. $assert_session->fieldExists('name');
  259. $assert_session->fieldExists('pass');
  260. // @see BrowserTestBase::drupalUserIsLoggedIn()
  261. unset($this->loggedInUser->sessionId);
  262. $this->loggedInUser = FALSE;
  263. \Drupal::currentUser()->setAccount(new AnonymousUserSession());
  264. }
  265. /**
  266. * Returns WebAssert object.
  267. *
  268. * @param string $name
  269. * (optional) Name of the session. Defaults to the active session.
  270. *
  271. * @return \Drupal\Tests\WebAssert
  272. * A new web-assert option for asserting the presence of elements with.
  273. */
  274. public function assertSession($name = NULL) {
  275. $this->addToAssertionCount(1);
  276. return new WebAssert($this->getSession($name), $this->baseUrl);
  277. }
  278. /**
  279. * Retrieves a Drupal path or an absolute path.
  280. *
  281. * @param string|\Drupal\Core\Url $path
  282. * Drupal path or URL to load into Mink controlled browser.
  283. * @param array $options
  284. * (optional) Options to be forwarded to the url generator.
  285. * @param string[] $headers
  286. * An array containing additional HTTP request headers, the array keys are
  287. * the header names and the array values the header values. This is useful
  288. * to set for example the "Accept-Language" header for requesting the page
  289. * in a different language. Note that not all headers are supported, for
  290. * example the "Accept" header is always overridden by the browser. For
  291. * testing REST APIs it is recommended to obtain a separate HTTP client
  292. * using getHttpClient() and performing requests that way.
  293. *
  294. * @return string
  295. * The retrieved HTML string, also available as $this->getRawContent()
  296. *
  297. * @see \Drupal\Tests\BrowserTestBase::getHttpClient()
  298. */
  299. protected function drupalGet($path, array $options = [], array $headers = []) {
  300. $options['absolute'] = TRUE;
  301. $url = $this->buildUrl($path, $options);
  302. $session = $this->getSession();
  303. $this->prepareRequest();
  304. foreach ($headers as $header_name => $header_value) {
  305. $session->setRequestHeader($header_name, $header_value);
  306. }
  307. $session->visit($url);
  308. $out = $session->getPage()->getContent();
  309. // Ensure that any changes to variables in the other thread are picked up.
  310. $this->refreshVariables();
  311. // Replace original page output with new output from redirected page(s).
  312. if ($new = $this->checkForMetaRefresh()) {
  313. $out = $new;
  314. // We are finished with all meta refresh redirects, so reset the counter.
  315. $this->metaRefreshCount = 0;
  316. }
  317. // Log only for JavascriptTestBase tests because for Goutte we log with
  318. // ::getResponseLogHandler.
  319. if ($this->htmlOutputEnabled && !($this->getSession()->getDriver() instanceof GoutteDriver)) {
  320. $html_output = 'GET request to: ' . $url .
  321. '<hr />Ending URL: ' . $this->getSession()->getCurrentUrl();
  322. $html_output .= '<hr />' . $out;
  323. $html_output .= $this->getHtmlOutputHeaders();
  324. $this->htmlOutput($html_output);
  325. }
  326. return $out;
  327. }
  328. /**
  329. * Builds an a absolute URL from a system path or a URL object.
  330. *
  331. * @param string|\Drupal\Core\Url $path
  332. * A system path or a URL.
  333. * @param array $options
  334. * Options to be passed to Url::fromUri().
  335. *
  336. * @return string
  337. * An absolute URL stsring.
  338. */
  339. protected function buildUrl($path, array $options = []) {
  340. if ($path instanceof Url) {
  341. $url_options = $path->getOptions();
  342. $options = $url_options + $options;
  343. $path->setOptions($options);
  344. return $path->setAbsolute()->toString();
  345. }
  346. // The URL generator service is not necessarily available yet; e.g., in
  347. // interactive installer tests.
  348. elseif (\Drupal::hasService('url_generator')) {
  349. $force_internal = isset($options['external']) && $options['external'] == FALSE;
  350. if (!$force_internal && UrlHelper::isExternal($path)) {
  351. return Url::fromUri($path, $options)->toString();
  352. }
  353. else {
  354. $uri = $path === '<front>' ? 'base:/' : 'base:/' . $path;
  355. // Path processing is needed for language prefixing. Skip it when a
  356. // path that may look like an external URL is being used as internal.
  357. $options['path_processing'] = !$force_internal;
  358. return Url::fromUri($uri, $options)
  359. ->setAbsolute()
  360. ->toString();
  361. }
  362. }
  363. else {
  364. return $this->getAbsoluteUrl($path);
  365. }
  366. }
  367. /**
  368. * Takes a path and returns an absolute path.
  369. *
  370. * @param string $path
  371. * A path from the Mink controlled browser content.
  372. *
  373. * @return string
  374. * The $path with $base_url prepended, if necessary.
  375. */
  376. protected function getAbsoluteUrl($path) {
  377. global $base_url, $base_path;
  378. $parts = parse_url($path);
  379. if (empty($parts['host'])) {
  380. // Ensure that we have a string (and no xpath object).
  381. $path = (string) $path;
  382. // Strip $base_path, if existent.
  383. $length = strlen($base_path);
  384. if (substr($path, 0, $length) === $base_path) {
  385. $path = substr($path, $length);
  386. }
  387. // Ensure that we have an absolute path.
  388. if (empty($path) || $path[0] !== '/') {
  389. $path = '/' . $path;
  390. }
  391. // Finally, prepend the $base_url.
  392. $path = $base_url . $path;
  393. }
  394. return $path;
  395. }
  396. /**
  397. * Prepare for a request to testing site.
  398. *
  399. * The testing site is protected via a SIMPLETEST_USER_AGENT cookie that is
  400. * checked by drupal_valid_test_ua().
  401. *
  402. * @see drupal_valid_test_ua()
  403. */
  404. protected function prepareRequest() {
  405. $session = $this->getSession();
  406. $session->setCookie('SIMPLETEST_USER_AGENT', drupal_generate_test_ua($this->databasePrefix));
  407. }
  408. /**
  409. * Returns whether a given user account is logged in.
  410. *
  411. * @param \Drupal\Core\Session\AccountInterface $account
  412. * The user account object to check.
  413. *
  414. * @return bool
  415. * Return TRUE if the user is logged in, FALSE otherwise.
  416. */
  417. protected function drupalUserIsLoggedIn(AccountInterface $account) {
  418. $logged_in = FALSE;
  419. if (isset($account->sessionId)) {
  420. $session_handler = \Drupal::service('session_handler.storage');
  421. $logged_in = (bool) $session_handler->read($account->sessionId);
  422. }
  423. return $logged_in;
  424. }
  425. /**
  426. * Clicks the element with the given CSS selector.
  427. *
  428. * @param string $css_selector
  429. * The CSS selector identifying the element to click.
  430. */
  431. protected function click($css_selector) {
  432. $starting_url = $this->getSession()->getCurrentUrl();
  433. $this->getSession()->getDriver()->click($this->cssSelectToXpath($css_selector));
  434. // Log only for JavascriptTestBase tests because for Goutte we log with
  435. // ::getResponseLogHandler.
  436. if ($this->htmlOutputEnabled && !($this->getSession()->getDriver() instanceof GoutteDriver)) {
  437. $out = $this->getSession()->getPage()->getContent();
  438. $html_output =
  439. 'Clicked element with CSS selector: ' . $css_selector .
  440. '<hr />Starting URL: ' . $starting_url .
  441. '<hr />Ending URL: ' . $this->getSession()->getCurrentUrl();
  442. $html_output .= '<hr />' . $out;
  443. $html_output .= $this->getHtmlOutputHeaders();
  444. $this->htmlOutput($html_output);
  445. }
  446. }
  447. /**
  448. * Follows a link by complete name.
  449. *
  450. * Will click the first link found with this link text.
  451. *
  452. * If the link is discovered and clicked, the test passes. Fail otherwise.
  453. *
  454. * @param string|\Drupal\Component\Render\MarkupInterface $label
  455. * Text between the anchor tags.
  456. * @param int $index
  457. * (optional) The index number for cases where multiple links have the same
  458. * text. Defaults to 0.
  459. */
  460. protected function clickLink($label, $index = 0) {
  461. $label = (string) $label;
  462. $links = $this->getSession()->getPage()->findAll('named', ['link', $label]);
  463. $this->assertArrayHasKey($index, $links, 'The link ' . $label . ' was not found on the page.');
  464. $links[$index]->click();
  465. }
  466. /**
  467. * Retrieves the plain-text content from the current page.
  468. */
  469. protected function getTextContent() {
  470. return $this->getSession()->getPage()->getText();
  471. }
  472. /**
  473. * Get the current URL from the browser.
  474. *
  475. * @return string
  476. * The current URL.
  477. */
  478. protected function getUrl() {
  479. return $this->getSession()->getCurrentUrl();
  480. }
  481. /**
  482. * Checks for meta refresh tag and if found call drupalGet() recursively.
  483. *
  484. * This function looks for the http-equiv attribute to be set to "Refresh" and
  485. * is case-insensitive.
  486. *
  487. * @return string|false
  488. * Either the new page content or FALSE.
  489. */
  490. protected function checkForMetaRefresh() {
  491. $refresh = $this->cssSelect('meta[http-equiv="Refresh"], meta[http-equiv="refresh"]');
  492. if (!empty($refresh) && (!isset($this->maximumMetaRefreshCount) || $this->metaRefreshCount < $this->maximumMetaRefreshCount)) {
  493. // Parse the content attribute of the meta tag for the format:
  494. // "[delay]: URL=[page_to_redirect_to]".
  495. if (preg_match('/\d+;\s*URL=(?<url>.*)/i', $refresh[0]->getAttribute('content'), $match)) {
  496. $this->metaRefreshCount++;
  497. return $this->drupalGet($this->getAbsoluteUrl(Html::decodeEntities($match['url'])));
  498. }
  499. }
  500. return FALSE;
  501. }
  502. /**
  503. * Searches elements using a CSS selector in the raw content.
  504. *
  505. * The search is relative to the root element (HTML tag normally) of the page.
  506. *
  507. * @param string $selector
  508. * CSS selector to use in the search.
  509. *
  510. * @return \Behat\Mink\Element\NodeElement[]
  511. * The list of elements on the page that match the selector.
  512. */
  513. protected function cssSelect($selector) {
  514. return $this->getSession()->getPage()->findAll('css', $selector);
  515. }
  516. }