UiHelperTrait.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  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. * The id, name, label or value of the submit button which is to be clicked.
  153. * For example, 'Save'. The first element matched by
  154. * \Drupal\Tests\WebAssert::buttonExists() will be used. The processing of
  155. * the request depends on this value. For example, a form may have one
  156. * button with the value 'Save' and another button with the value 'Delete',
  157. * and execute different code depending on which one is clicked.
  158. * @param array $options
  159. * Options to be forwarded to the url generator.
  160. * @param string|null $form_html_id
  161. * (optional) HTML ID of the form to be submitted. On some pages
  162. * there are many identical forms, so just using the value of the submit
  163. * button is not enough. For example: 'trigger-node-presave-assign-form'.
  164. * Note that this is not the Drupal $form_id, but rather the HTML ID of the
  165. * form, which is typically the same thing but with hyphens replacing the
  166. * underscores.
  167. *
  168. * @return string
  169. * (deprecated) The response content after submit form. It is necessary for
  170. * backwards compatibility and will be removed before Drupal 9.0. You should
  171. * just use the webAssert object for your assertions.
  172. *
  173. * @see \Drupal\Tests\WebAssert::buttonExists()
  174. */
  175. protected function drupalPostForm($path, $edit, $submit, array $options = [], $form_html_id = NULL) {
  176. if (is_object($submit)) {
  177. // Cast MarkupInterface objects to string.
  178. $submit = (string) $submit;
  179. }
  180. if ($edit === NULL) {
  181. $edit = [];
  182. }
  183. if (is_array($edit)) {
  184. $edit = $this->castSafeStrings($edit);
  185. }
  186. if (isset($path)) {
  187. $this->drupalGet($path, $options);
  188. }
  189. $this->submitForm($edit, $submit, $form_html_id);
  190. return $this->getSession()->getPage()->getContent();
  191. }
  192. /**
  193. * Logs in a user using the Mink controlled browser.
  194. *
  195. * If a user is already logged in, then the current user is logged out before
  196. * logging in the specified user.
  197. *
  198. * Please note that neither the current user nor the passed-in user object is
  199. * populated with data of the logged in user. If you need full access to the
  200. * user object after logging in, it must be updated manually. If you also need
  201. * access to the plain-text password of the user (set by drupalCreateUser()),
  202. * e.g. to log in the same user again, then it must be re-assigned manually.
  203. * For example:
  204. * @code
  205. * // Create a user.
  206. * $account = $this->drupalCreateUser(array());
  207. * $this->drupalLogin($account);
  208. * // Load real user object.
  209. * $pass_raw = $account->passRaw;
  210. * $account = User::load($account->id());
  211. * $account->passRaw = $pass_raw;
  212. * @endcode
  213. *
  214. * @param \Drupal\Core\Session\AccountInterface $account
  215. * User object representing the user to log in.
  216. *
  217. * @see drupalCreateUser()
  218. */
  219. protected function drupalLogin(AccountInterface $account) {
  220. if ($this->loggedInUser) {
  221. $this->drupalLogout();
  222. }
  223. $this->drupalGet(Url::fromRoute('user.login'));
  224. $this->submitForm([
  225. 'name' => $account->getAccountName(),
  226. 'pass' => $account->passRaw,
  227. ], t('Log in'));
  228. // @see ::drupalUserIsLoggedIn()
  229. $account->sessionId = $this->getSession()->getCookie(\Drupal::service('session_configuration')->getOptions(\Drupal::request())['name']);
  230. $this->assertTrue($this->drupalUserIsLoggedIn($account), new FormattableMarkup('User %name successfully logged in.', ['%name' => $account->getAccountName()]));
  231. $this->loggedInUser = $account;
  232. $this->container->get('current_user')->setAccount($account);
  233. }
  234. /**
  235. * Logs a user out of the Mink controlled browser and confirms.
  236. *
  237. * Confirms logout by checking the login page.
  238. */
  239. protected function drupalLogout() {
  240. // Make a request to the logout page, and redirect to the user page, the
  241. // idea being if you were properly logged out you should be seeing a login
  242. // screen.
  243. $assert_session = $this->assertSession();
  244. $destination = Url::fromRoute('user.page')->toString();
  245. $this->drupalGet(Url::fromRoute('user.logout', [], ['query' => ['destination' => $destination]]));
  246. $assert_session->fieldExists('name');
  247. $assert_session->fieldExists('pass');
  248. // @see BrowserTestBase::drupalUserIsLoggedIn()
  249. unset($this->loggedInUser->sessionId);
  250. $this->loggedInUser = FALSE;
  251. \Drupal::currentUser()->setAccount(new AnonymousUserSession());
  252. }
  253. /**
  254. * Returns WebAssert object.
  255. *
  256. * @param string $name
  257. * (optional) Name of the session. Defaults to the active session.
  258. *
  259. * @return \Drupal\Tests\WebAssert
  260. * A new web-assert option for asserting the presence of elements with.
  261. */
  262. public function assertSession($name = NULL) {
  263. $this->addToAssertionCount(1);
  264. return new WebAssert($this->getSession($name), $this->baseUrl);
  265. }
  266. /**
  267. * Retrieves a Drupal path or an absolute path.
  268. *
  269. * @param string|\Drupal\Core\Url $path
  270. * Drupal path or URL to load into Mink controlled browser.
  271. * @param array $options
  272. * (optional) Options to be forwarded to the url generator.
  273. * @param string[] $headers
  274. * An array containing additional HTTP request headers, the array keys are
  275. * the header names and the array values the header values. This is useful
  276. * to set for example the "Accept-Language" header for requesting the page
  277. * in a different language. Note that not all headers are supported, for
  278. * example the "Accept" header is always overridden by the browser. For
  279. * testing REST APIs it is recommended to obtain a separate HTTP client
  280. * using getHttpClient() and performing requests that way.
  281. *
  282. * @return string
  283. * The retrieved HTML string, also available as $this->getRawContent()
  284. *
  285. * @see \Drupal\Tests\BrowserTestBase::getHttpClient()
  286. */
  287. protected function drupalGet($path, array $options = [], array $headers = []) {
  288. $options['absolute'] = TRUE;
  289. $url = $this->buildUrl($path, $options);
  290. $session = $this->getSession();
  291. $this->prepareRequest();
  292. foreach ($headers as $header_name => $header_value) {
  293. $session->setRequestHeader($header_name, $header_value);
  294. }
  295. $session->visit($url);
  296. $out = $session->getPage()->getContent();
  297. // Ensure that any changes to variables in the other thread are picked up.
  298. $this->refreshVariables();
  299. // Replace original page output with new output from redirected page(s).
  300. if ($new = $this->checkForMetaRefresh()) {
  301. $out = $new;
  302. // We are finished with all meta refresh redirects, so reset the counter.
  303. $this->metaRefreshCount = 0;
  304. }
  305. // Log only for JavascriptTestBase tests because for Goutte we log with
  306. // ::getResponseLogHandler.
  307. if ($this->htmlOutputEnabled && !($this->getSession()->getDriver() instanceof GoutteDriver)) {
  308. $html_output = 'GET request to: ' . $url .
  309. '<hr />Ending URL: ' . $this->getSession()->getCurrentUrl();
  310. $html_output .= '<hr />' . $out;
  311. $html_output .= $this->getHtmlOutputHeaders();
  312. $this->htmlOutput($html_output);
  313. }
  314. return $out;
  315. }
  316. /**
  317. * Builds an a absolute URL from a system path or a URL object.
  318. *
  319. * @param string|\Drupal\Core\Url $path
  320. * A system path or a URL.
  321. * @param array $options
  322. * Options to be passed to Url::fromUri().
  323. *
  324. * @return string
  325. * An absolute URL string.
  326. */
  327. protected function buildUrl($path, array $options = []) {
  328. if ($path instanceof Url) {
  329. $url_options = $path->getOptions();
  330. $options = $url_options + $options;
  331. $path->setOptions($options);
  332. return $path->setAbsolute()->toString();
  333. }
  334. // The URL generator service is not necessarily available yet; e.g., in
  335. // interactive installer tests.
  336. elseif (\Drupal::hasService('url_generator')) {
  337. $force_internal = isset($options['external']) && $options['external'] == FALSE;
  338. if (!$force_internal && UrlHelper::isExternal($path)) {
  339. return Url::fromUri($path, $options)->toString();
  340. }
  341. else {
  342. $uri = $path === '<front>' ? 'base:/' : 'base:/' . $path;
  343. // Path processing is needed for language prefixing. Skip it when a
  344. // path that may look like an external URL is being used as internal.
  345. $options['path_processing'] = !$force_internal;
  346. return Url::fromUri($uri, $options)
  347. ->setAbsolute()
  348. ->toString();
  349. }
  350. }
  351. else {
  352. return $this->getAbsoluteUrl($path);
  353. }
  354. }
  355. /**
  356. * Takes a path and returns an absolute path.
  357. *
  358. * @param string $path
  359. * A path from the Mink controlled browser content.
  360. *
  361. * @return string
  362. * The $path with $base_url prepended, if necessary.
  363. */
  364. protected function getAbsoluteUrl($path) {
  365. global $base_url, $base_path;
  366. $parts = parse_url($path);
  367. if (empty($parts['host'])) {
  368. // Ensure that we have a string (and no xpath object).
  369. $path = (string) $path;
  370. // Strip $base_path, if existent.
  371. $length = strlen($base_path);
  372. if (substr($path, 0, $length) === $base_path) {
  373. $path = substr($path, $length);
  374. }
  375. // Ensure that we have an absolute path.
  376. if (empty($path) || $path[0] !== '/') {
  377. $path = '/' . $path;
  378. }
  379. // Finally, prepend the $base_url.
  380. $path = $base_url . $path;
  381. }
  382. return $path;
  383. }
  384. /**
  385. * Prepare for a request to testing site.
  386. *
  387. * The testing site is protected via a SIMPLETEST_USER_AGENT cookie that is
  388. * checked by drupal_valid_test_ua().
  389. *
  390. * @see drupal_valid_test_ua()
  391. */
  392. protected function prepareRequest() {
  393. $session = $this->getSession();
  394. $session->setCookie('SIMPLETEST_USER_AGENT', drupal_generate_test_ua($this->databasePrefix));
  395. }
  396. /**
  397. * Returns whether a given user account is logged in.
  398. *
  399. * @param \Drupal\Core\Session\AccountInterface $account
  400. * The user account object to check.
  401. *
  402. * @return bool
  403. * Return TRUE if the user is logged in, FALSE otherwise.
  404. */
  405. protected function drupalUserIsLoggedIn(AccountInterface $account) {
  406. $logged_in = FALSE;
  407. if (isset($account->sessionId)) {
  408. $session_handler = \Drupal::service('session_handler.storage');
  409. $logged_in = (bool) $session_handler->read($account->sessionId);
  410. }
  411. return $logged_in;
  412. }
  413. /**
  414. * Clicks the element with the given CSS selector.
  415. *
  416. * @param string $css_selector
  417. * The CSS selector identifying the element to click.
  418. */
  419. protected function click($css_selector) {
  420. $starting_url = $this->getSession()->getCurrentUrl();
  421. $this->getSession()->getDriver()->click($this->cssSelectToXpath($css_selector));
  422. // Log only for JavascriptTestBase tests because for Goutte we log with
  423. // ::getResponseLogHandler.
  424. if ($this->htmlOutputEnabled && !($this->getSession()->getDriver() instanceof GoutteDriver)) {
  425. $out = $this->getSession()->getPage()->getContent();
  426. $html_output =
  427. 'Clicked element with CSS selector: ' . $css_selector .
  428. '<hr />Starting URL: ' . $starting_url .
  429. '<hr />Ending URL: ' . $this->getSession()->getCurrentUrl();
  430. $html_output .= '<hr />' . $out;
  431. $html_output .= $this->getHtmlOutputHeaders();
  432. $this->htmlOutput($html_output);
  433. }
  434. }
  435. /**
  436. * Follows a link by complete name.
  437. *
  438. * Will click the first link found with this link text.
  439. *
  440. * If the link is discovered and clicked, the test passes. Fail otherwise.
  441. *
  442. * @param string|\Drupal\Component\Render\MarkupInterface $label
  443. * Text between the anchor tags.
  444. * @param int $index
  445. * (optional) The index number for cases where multiple links have the same
  446. * text. Defaults to 0.
  447. */
  448. protected function clickLink($label, $index = 0) {
  449. $label = (string) $label;
  450. $links = $this->getSession()->getPage()->findAll('named', ['link', $label]);
  451. $this->assertArrayHasKey($index, $links, 'The link ' . $label . ' was not found on the page.');
  452. $links[$index]->click();
  453. }
  454. /**
  455. * Retrieves the plain-text content from the current page.
  456. */
  457. protected function getTextContent() {
  458. return $this->getSession()->getPage()->getText();
  459. }
  460. /**
  461. * Get the current URL from the browser.
  462. *
  463. * @return string
  464. * The current URL.
  465. */
  466. protected function getUrl() {
  467. return $this->getSession()->getCurrentUrl();
  468. }
  469. /**
  470. * Checks for meta refresh tag and if found call drupalGet() recursively.
  471. *
  472. * This function looks for the http-equiv attribute to be set to "Refresh" and
  473. * is case-insensitive.
  474. *
  475. * @return string|false
  476. * Either the new page content or FALSE.
  477. */
  478. protected function checkForMetaRefresh() {
  479. $refresh = $this->cssSelect('meta[http-equiv="Refresh"], meta[http-equiv="refresh"]');
  480. if (!empty($refresh) && (!isset($this->maximumMetaRefreshCount) || $this->metaRefreshCount < $this->maximumMetaRefreshCount)) {
  481. // Parse the content attribute of the meta tag for the format:
  482. // "[delay]: URL=[page_to_redirect_to]".
  483. if (preg_match('/\d+;\s*URL=\'?(?<url>[^\']*)/i', $refresh[0]->getAttribute('content'), $match)) {
  484. $this->metaRefreshCount++;
  485. return $this->drupalGet($this->getAbsoluteUrl(Html::decodeEntities($match['url'])));
  486. }
  487. }
  488. return FALSE;
  489. }
  490. /**
  491. * Searches elements using a CSS selector in the raw content.
  492. *
  493. * The search is relative to the root element (HTML tag normally) of the page.
  494. *
  495. * @param string $selector
  496. * CSS selector to use in the search.
  497. *
  498. * @return \Behat\Mink\Element\NodeElement[]
  499. * The list of elements on the page that match the selector.
  500. */
  501. protected function cssSelect($selector) {
  502. return $this->getSession()->getPage()->findAll('css', $selector);
  503. }
  504. }