MDL-66550 behat: Normalise selectors better
[moodle.git] / lib / behat / behat_base.php
CommitLineData
d4322e38
DM
1<?php
2// This file is part of Moodle - http://moodle.org/
3//
4// Moodle is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// Moodle is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
16
17/**
18 * Base class of all steps definitions.
19 *
20 * This script is only called from Behat as part of it's integration
21 * in Moodle.
22 *
23 * @package core
24 * @category test
25 * @copyright 2012 David MonllaĆ³
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 */
28
29// NOTE: no MOODLE_INTERNAL test here, this file may be required by behat before including /config.php.
30
7bfb575f
AN
31use Behat\Mink\Exception\DriverException;
32use Behat\Mink\Exception\ExpectationException;
33use Behat\Mink\Exception\ElementNotFoundException;
34use Behat\Mink\Element\NodeElement;
700682dc 35use Behat\Mink\Element\Element;
7bfb575f 36use Behat\Mink\Session;
ff48a235 37
d4322e38
DM
38/**
39 * Steps definitions base class.
40 *
41 * To extend by the steps definitions of the different Moodle components.
42 *
43 * It can not contain steps definitions to avoid duplicates, only utility
44 * methods shared between steps.
45 *
fcb6ed47
MG
46 * @method NodeElement find_field(string $locator) Finds a form element
47 * @method NodeElement find_button(string $locator) Finds a form input submit element or a button
48 * @method NodeElement find_link(string $locator) Finds a link on a page
49 * @method NodeElement find_file(string $locator) Finds a forum input file element
50 *
d4322e38
DM
51 * @package core
52 * @category test
53 * @copyright 2012 David MonllaĆ³
54 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
55 */
56class behat_base extends Behat\MinkExtension\Context\RawMinkContext {
57
74c78e74
DM
58 /**
59 * Small timeout.
60 *
61 * A reduced timeout for cases where self::TIMEOUT is too much
62 * and a simple $this->getSession()->getPage()->find() could not
63 * be enough.
05a5d547 64 *
65 * @deprecated since Moodle 3.7 MDL-64979 - please use get_reduced_timeout() instead
66 * @todo MDL-64982 This will be deleted in Moodle 4.1
67 * @see behat_base::get_reduced_timeout()
74c78e74
DM
68 */
69 const REDUCED_TIMEOUT = 2;
70
d4322e38
DM
71 /**
72 * The timeout for each Behat step (load page, wait for an element to load...).
05a5d547 73 *
74 * @deprecated since Moodle 3.7 MDL-64979 - please use get_timeout() instead
75 * @todo MDL-64982 This will be deleted in Moodle 4.1
76 * @see behat_base::get_timeout()
d4322e38 77 */
845ceaff 78 const TIMEOUT = 6;
d1e55a47
DM
79
80 /**
81 * And extended timeout for specific cases.
05a5d547 82 *
83 * @deprecated since Moodle 3.7 MDL-64979 - please use get_extended_timeout() instead
84 * @todo MDL-64982 This will be deleted in Moodle 4.1
85 * @see behat_base::get_extended_timeout()
d1e55a47
DM
86 */
87 const EXTENDED_TIMEOUT = 10;
88
d1e55a47
DM
89 /**
90 * The JS code to check that the page is ready.
91 */
41f4dabe 92 const PAGE_READY_JS = '(typeof M !== "undefined" && M.util && M.util.pending_js && !Boolean(M.util.pending_js.length)) && (document.readyState === "complete")';
d4322e38 93
786ea937
DM
94 /**
95 * Locates url, based on provided path.
96 * Override to provide custom routing mechanism.
97 *
98 * @see Behat\MinkExtension\Context\MinkContext
99 * @param string $path
100 * @return string
101 */
40923977 102 protected function locate_path($path) {
46ac40cd
DM
103 $starturl = rtrim($this->getMinkParameter('base_url'), '/') . '/';
104 return 0 !== strpos($path, 'http') ? $starturl . ltrim($path, '/') : $path;
786ea937
DM
105 }
106
ff48a235 107 /**
f8f1bdc3 108 * Returns the first matching element.
ff48a235
DM
109 *
110 * @link http://mink.behat.org/#traverse-the-page-selectors
ff48a235
DM
111 * @param string $selector The selector type (css, xpath, named...)
112 * @param mixed $locator It depends on the $selector, can be the xpath, a name, a css locator...
40923977 113 * @param Exception $exception Otherwise we throw exception with generic info
072f67fc 114 * @param NodeElement $node Spins around certain DOM node instead of the whole page
74c78e74 115 * @param int $timeout Forces a specific time out (in seconds).
ff48a235
DM
116 * @return NodeElement
117 */
74c78e74 118 protected function find($selector, $locator, $exception = false, $node = false, $timeout = false) {
f8f1bdc3 119 // Returns the first match.
74c78e74 120 $items = $this->find_all($selector, $locator, $exception, $node, $timeout);
f8f1bdc3
DM
121 return count($items) ? reset($items) : null;
122 }
123
124 /**
125 * Returns all matching elements.
126 *
127 * Adapter to Behat\Mink\Element\Element::findAll() using the spin() method.
128 *
129 * @link http://mink.behat.org/#traverse-the-page-selectors
130 * @param string $selector The selector type (css, xpath, named...)
131 * @param mixed $locator It depends on the $selector, can be the xpath, a name, a css locator...
132 * @param Exception $exception Otherwise we throw expcetion with generic info
700682dc 133 * @param NodeElement $container Restrict the search to just children of the specified container
74c78e74 134 * @param int $timeout Forces a specific time out (in seconds). If 0 is provided the default timeout will be applied.
f8f1bdc3
DM
135 * @return array NodeElements list
136 */
700682dc 137 protected function find_all($selector, $locator, $exception = false, $container = false, $timeout = false) {
42ad096f
RT
138 // Throw exception, so dev knows it is not supported.
139 if ($selector === 'named') {
140 $exception = 'Using the "named" selector is deprecated as of 3.1. '
141 .' Use the "named_partial" or use the "named_exact" selector instead.';
142 throw new ExpectationException($exception, $this->getSession());
143 }
144
ff48a235
DM
145 // Generic info.
146 if (!$exception) {
ff48a235 147 // With named selectors we can be more specific.
07298309 148 if (($selector == 'named_exact') || ($selector == 'named_partial')) {
ff48a235
DM
149 $exceptiontype = $locator[0];
150 $exceptionlocator = $locator[1];
0a7f6a02
DM
151
152 // If we are in a @javascript session all contents would be displayed as HTML characters.
eff79d53 153 if ($this->running_javascript()) {
0a7f6a02
DM
154 $locator[1] = html_entity_decode($locator[1], ENT_NOQUOTES);
155 }
156
ff48a235
DM
157 } else {
158 $exceptiontype = $selector;
159 $exceptionlocator = $locator;
160 }
161
162 $exception = new ElementNotFoundException($this->getSession(), $exceptiontype, null, $exceptionlocator);
163 }
164
74c78e74
DM
165 // How much we will be waiting for the element to appear.
166 if (!$timeout) {
05a5d547 167 $timeout = self::get_timeout();
74c78e74
DM
168 $microsleep = false;
169 } else {
170 // Spinning each 0.1 seconds if the timeout was forced as we understand
171 // that is a special case and is good to refine the performance as much
172 // as possible.
173 $microsleep = true;
174 }
175
700682dc
AN
176 // Normalise the values in order to perform the search.
177 [
178 'selector' => $selector,
179 'locator' => $locator,
180 'container' => $container,
181 ] = $this->normalise_selector($selector, $locator, $container ?: $this->getSession()->getPage());
182
ff48a235
DM
183 // Waits for the node to appear if it exists, otherwise will timeout and throw the provided exception.
184 return $this->spin(
700682dc
AN
185 function() use ($selector, $locator, $container) {
186 return $container->findAll($selector, $locator);
187 }, [], $timeout, $exception, $microsleep
188 );
189 }
072f67fc 190
700682dc
AN
191 /**
192 * Normalise the locator and selector.
193 *
194 * @param string $selector The type of thing to search
195 * @param mixed $locator The locator value. Can be an array, but is more likely a string.
196 * @param Element $container An optional container to search within
197 * @return array The selector, locator, and container to search within
198 */
199 public function normalise_selector(string $selector, $locator, Element $container): array {
200 // Normalise the css and xpath selector types.
201 if ('css_element' === $selector) {
202 $selector = 'css';
203 } else if ('xpath_element' === $selector) {
204 $selector = 'xpath';
205 }
072f67fc 206
700682dc
AN
207 // Convert to named_partial where the selector type is not named_partial, named_exact, xpath, or css.
208 $converttonamed = !$this->getSession()->getSelectorsHandler()->isSelectorRegistered($selector);
209 $converttonamed = $converttonamed && 'xpath' !== $selector;
210 if ($converttonamed) {
211 $allowedpartialselectors = behat_partial_named_selector::get_allowed_selectors();
212 $allowedexactselectors = behat_exact_named_selector::get_allowed_selectors();
213 if (isset($allowedpartialselectors[$selector])) {
214 $locator = behat_selectors::normalise_named_selector($allowedpartialselectors[$selector], $locator);
215 $selector = 'named_partial';
216 } else if (isset($allowedexactselectors[$selector])) {
217 $locator = behat_selectors::normalise_named_selector($allowedexactselectors[$selector], $locator);
218 $selector = 'named_exact';
219 } else {
220 throw new ExpectationException("The '{$selector}' selector type is not registered.", $this);
221 }
222 }
223
224 return [
225 'selector' => $selector,
226 'locator' => $locator,
227 'container' => $container,
228 ];
ff48a235
DM
229 }
230
231 /**
232 * Finds DOM nodes in the page using named selectors.
233 *
234 * The point of using this method instead of Mink ones is the spin
235 * method of behat_base::find() that looks for the element until it
236 * is available or it timeouts, this avoids the false failures received
237 * when selenium tries to execute commands on elements that are not
238 * ready to be used.
239 *
240 * All steps that requires elements to be available before interact with
241 * them should use one of the find* methods.
242 *
243 * The methods calls requires a {'find_' . $elementtype}($locator)
244 * format, like find_link($locator), find_select($locator),
245 * find_button($locator)...
246 *
247 * @link http://mink.behat.org/#named-selectors
248 * @throws coding_exception
46ac40cd 249 * @param string $name The name of the called method
ff48a235
DM
250 * @param mixed $arguments
251 * @return NodeElement
252 */
253 public function __call($name, $arguments) {
700682dc
AN
254 if (substr($name, 0, 5) === 'find_') {
255 return call_user_func_array([$this, 'find'], array_merge(
256 [substr($name, 5)],
257 $arguments
258 ));
ff48a235
DM
259 }
260
700682dc 261 throw new coding_exception("The '{$name}' method does not exist");
ff48a235
DM
262 }
263
49d91129
DM
264 /**
265 * Escapes the double quote character.
266 *
267 * Double quote is the argument delimiter, it can be escaped
268 * with a backslash, but we auto-remove this backslashes
269 * before the step execution, this method is useful when using
270 * arguments as arguments for other steps.
271 *
272 * @param string $string
273 * @return string
274 */
275 public function escape($string) {
276 return str_replace('"', '\"', $string);
277 }
278
786ea937
DM
279 /**
280 * Executes the passed closure until returns true or time outs.
281 *
282 * In most cases the document.readyState === 'complete' will be enough, but sometimes JS
283 * requires more time to be completely loaded or an element to be visible or whatever is required to
284 * perform some action on an element; this method receives a closure which should contain the
285 * required statements to ensure the step definition actions and assertions have all their needs
286 * satisfied and executes it until they are satisfied or it timeouts. Redirects the return of the
287 * closure to the caller.
288 *
289 * The closures requirements to work well with this spin method are:
290 * - Must return false, null or '' if something goes wrong
291 * - Must return something != false if finishes as expected, this will be the (mixed) value
292 * returned by spin()
293 *
ff48a235 294 * The arguments of the closure are mixed, use $args depending on your needs.
786ea937 295 *
ff48a235 296 * You can provide an exception to give more accurate feedback to tests writers, otherwise the
c51c3b55 297 * closure exception will be used, but you must provide an exception if the closure does not throw
ff48a235
DM
298 * an exception.
299 *
8e5f86bc
SH
300 * @throws Exception If it timeouts without receiving something != false from the closure
301 * @param Function|array|string $lambda The function to execute or an array passed to call_user_func (maps to a class method)
302 * @param mixed $args Arguments to pass to the closure
303 * @param int $timeout Timeout in seconds
304 * @param Exception $exception The exception to throw in case it time outs.
305 * @param bool $microsleep If set to true it'll sleep micro seconds rather than seconds.
786ea937
DM
306 * @return mixed The value returned by the closure
307 */
8e5f86bc 308 protected function spin($lambda, $args = false, $timeout = false, $exception = false, $microsleep = false) {
786ea937
DM
309
310 // Using default timeout which is pretty high.
311 if (!$timeout) {
05a5d547 312 $timeout = self::get_timeout();
786ea937 313 }
8e5f86bc 314 if ($microsleep) {
05a5d547 315 // Will sleep 1/10th of a second by default for self::get_timeout() seconds.
8e5f86bc
SH
316 $loops = $timeout * 10;
317 } else {
05a5d547 318 // Will sleep for self::get_timeout() seconds.
8e5f86bc
SH
319 $loops = $timeout;
320 }
786ea937 321
80ac8522
TL
322 // DOM will never change on non-javascript case; do not wait or try again.
323 if (!$this->running_javascript()) {
324 $loops = 1;
325 }
326
8e5f86bc 327 for ($i = 0; $i < $loops; $i++) {
786ea937
DM
328 // We catch the exception thrown by the step definition to execute it again.
329 try {
786ea937 330 // We don't check with !== because most of the time closures will return
ff48a235
DM
331 // direct Behat methods returns and we are not sure it will be always (bool)false
332 // if it just runs the behat method without returning anything $return == null.
8e5f86bc 333 if ($return = call_user_func($lambda, $this, $args)) {
786ea937
DM
334 return $return;
335 }
46ac40cd 336 } catch (Exception $e) {
ff48a235
DM
337 // We would use the first closure exception if no exception has been provided.
338 if (!$exception) {
339 $exception = $e;
340 }
786ea937
DM
341 }
342
80ac8522
TL
343 if ($this->running_javascript()) {
344 if ($microsleep) {
345 usleep(100000);
346 } else {
347 sleep(1);
348 }
8e5f86bc 349 }
786ea937
DM
350 }
351
ff48a235
DM
352 // Using coding_exception as is a development issue if no exception has been provided.
353 if (!$exception) {
8e5f86bc 354 $exception = new coding_exception('spin method requires an exception if the callback does not throw an exception');
ff48a235
DM
355 }
356
786ea937
DM
357 // Throwing exception to the user.
358 throw $exception;
359 }
360
40923977
DM
361 /**
362 * Gets a NodeElement based on the locator and selector type received as argument from steps definitions.
363 *
072f67fc
DM
364 * Use behat_base::get_text_selector_node() for text-based selectors.
365 *
40923977
DM
366 * @throws ElementNotFoundException Thrown by behat_base::find
367 * @param string $selectortype
368 * @param string $element
369 * @return NodeElement
370 */
371 protected function get_selected_node($selectortype, $element) {
372
373 // Getting Mink selector and locator.
374 list($selector, $locator) = $this->transform_selector($selectortype, $element);
375
376 // Returns the NodeElement.
377 return $this->find($selector, $locator);
378 }
379
072f67fc
DM
380 /**
381 * Gets a NodeElement based on the locator and selector type received as argument from steps definitions.
382 *
383 * @throws ElementNotFoundException Thrown by behat_base::find
384 * @param string $selectortype
385 * @param string $element
386 * @return NodeElement
387 */
388 protected function get_text_selector_node($selectortype, $element) {
389
390 // Getting Mink selector and locator.
391 list($selector, $locator) = $this->transform_text_selector($selectortype, $element);
392
393 // Returns the NodeElement.
394 return $this->find($selector, $locator);
395 }
396
397 /**
398 * Gets the requested element inside the specified container.
399 *
400 * @throws ElementNotFoundException Thrown by behat_base::find
401 * @param mixed $selectortype The element selector type.
402 * @param mixed $element The element locator.
403 * @param mixed $containerselectortype The container selector type.
404 * @param mixed $containerelement The container locator.
405 * @return NodeElement
406 */
407 protected function get_node_in_container($selectortype, $element, $containerselectortype, $containerelement) {
408
409 // Gets the container, it will always be text based.
410 $containernode = $this->get_text_selector_node($containerselectortype, $containerelement);
411
412 list($selector, $locator) = $this->transform_selector($selectortype, $element);
413
414 // Specific exception giving info about where can't we find the element.
415 $locatorexceptionmsg = $element . '" in the "' . $containerelement. '" "' . $containerselectortype. '"';
416 $exception = new ElementNotFoundException($this->getSession(), $selectortype, null, $locatorexceptionmsg);
417
418 // Looks for the requested node inside the container node.
419 return $this->find($selector, $locator, $exception, $containernode);
420 }
421
40923977
DM
422 /**
423 * Transforms from step definition's argument style to Mink format.
424 *
425 * Mink has 3 different selectors css, xpath and named, where named
426 * selectors includes link, button, field... to simplify and group multiple
427 * steps in one we use the same interface, considering all link, buttons...
428 * at the same level as css selectors and xpath; this method makes the
429 * conversion from the arguments received by the steps to the selectors and locators
430 * required to interact with Mink.
431 *
432 * @throws ExpectationException
433 * @param string $selectortype It can be css, xpath or any of the named selectors.
434 * @param string $element The locator (or string) we are looking for.
435 * @return array Contains the selector and the locator expected by Mink.
436 */
437 protected function transform_selector($selectortype, $element) {
438
17344d4c
DM
439 // Here we don't know if an allowed text selector is being used.
440 $selectors = behat_selectors::get_allowed_selectors();
441 if (!isset($selectors[$selectortype])) {
40923977
DM
442 throw new ExpectationException('The "' . $selectortype . '" selector type does not exist', $this->getSession());
443 }
444
700682dc
AN
445 [
446 'selector' => $selector,
447 'locator' => $locator,
448 ] = $this->normalise_selector($selectortype, $element, $this->getSession()->getPage());
449
450 return [$selector, $locator];
40923977
DM
451 }
452
072f67fc
DM
453 /**
454 * Transforms from step definition's argument style to Mink format.
455 *
456 * Delegates all the process to behat_base::transform_selector() checking
457 * the provided $selectortype.
458 *
459 * @throws ExpectationException
460 * @param string $selectortype It can be css, xpath or any of the named selectors.
461 * @param string $element The locator (or string) we are looking for.
462 * @return array Contains the selector and the locator expected by Mink.
463 */
464 protected function transform_text_selector($selectortype, $element) {
465
17344d4c
DM
466 $selectors = behat_selectors::get_allowed_text_selectors();
467 if (empty($selectors[$selectortype])) {
072f67fc
DM
468 throw new ExpectationException('The "' . $selectortype . '" selector can not be used to select text nodes', $this->getSession());
469 }
470
471 return $this->transform_selector($selectortype, $element);
472 }
473
eff79d53
DM
474 /**
475 * Returns whether the scenario is running in a browser that can run Javascript or not.
476 *
477 * @return boolean
478 */
479 protected function running_javascript() {
28abad1a 480 return get_class($this->getSession()->getDriver()) !== 'Behat\Mink\Driver\GoutteDriver';
eff79d53
DM
481 }
482
079eae37 483 /**
484 * Checks if the current page is part of the mobile app.
485 *
486 * @return bool True if it's in the app
487 */
488 protected function is_in_app() : bool {
489 // Cannot be in the app if there's no @app tag on scenario.
490 if (!$this->has_tag('app')) {
491 return false;
492 }
493
494 // Check on page to see if it's an app page. Safest way is to look for added JavaScript.
d178865b 495 return $this->getSession()->evaluateScript('typeof window.behat') === 'object';
079eae37 496 }
497
d1e55a47
DM
498 /**
499 * Spins around an element until it exists
500 *
501 * @throws ExpectationException
502 * @param string $element
503 * @param string $selectortype
504 * @return void
505 */
506 protected function ensure_element_exists($element, $selectortype) {
507
508 // Getting the behat selector & locator.
509 list($selector, $locator) = $this->transform_selector($selectortype, $element);
510
511 // Exception if it timesout and the element is still there.
c1faf86b 512 $msg = 'The "' . $element . '" element does not exist and should exist';
d1e55a47
DM
513 $exception = new ExpectationException($msg, $this->getSession());
514
c1faf86b 515 // It will stop spinning once the find() method returns true.
d1e55a47
DM
516 $this->spin(
517 function($context, $args) {
518 // We don't use behat_base::find as it is already spinning.
519 if ($context->getSession()->getPage()->find($args['selector'], $args['locator'])) {
520 return true;
521 }
c1faf86b 522 return false;
d1e55a47
DM
523 },
524 array('selector' => $selector, 'locator' => $locator),
05a5d547 525 self::get_extended_timeout(),
d1e55a47
DM
526 $exception,
527 true
528 );
529
530 }
531
532 /**
533 * Spins until the element does not exist
534 *
535 * @throws ExpectationException
536 * @param string $element
537 * @param string $selectortype
538 * @return void
539 */
540 protected function ensure_element_does_not_exist($element, $selectortype) {
541
542 // Getting the behat selector & locator.
543 list($selector, $locator) = $this->transform_selector($selectortype, $element);
544
545 // Exception if it timesout and the element is still there.
c1faf86b 546 $msg = 'The "' . $element . '" element exists and should not exist';
d1e55a47
DM
547 $exception = new ExpectationException($msg, $this->getSession());
548
c1faf86b 549 // It will stop spinning once the find() method returns false.
d1e55a47
DM
550 $this->spin(
551 function($context, $args) {
c1faf86b 552 // We don't use behat_base::find() as we are already spinning.
d1e55a47
DM
553 if (!$context->getSession()->getPage()->find($args['selector'], $args['locator'])) {
554 return true;
555 }
c1faf86b 556 return false;
d1e55a47
DM
557 },
558 array('selector' => $selector, 'locator' => $locator),
05a5d547 559 self::get_extended_timeout(),
d1e55a47
DM
560 $exception,
561 true
562 );
563 }
564
565 /**
566 * Ensures that the provided node is visible and we can interact with it.
567 *
568 * @throws ExpectationException
569 * @param NodeElement $node
570 * @return void Throws an exception if it times out without the element being visible
571 */
572 protected function ensure_node_is_visible($node) {
573
574 if (!$this->running_javascript()) {
575 return;
576 }
577
578 // Exception if it timesout and the element is still there.
c1faf86b 579 $msg = 'The "' . $node->getXPath() . '" xpath node is not visible and it should be visible';
d1e55a47
DM
580 $exception = new ExpectationException($msg, $this->getSession());
581
c1faf86b 582 // It will stop spinning once the isVisible() method returns true.
d1e55a47
DM
583 $this->spin(
584 function($context, $args) {
585 if ($args->isVisible()) {
586 return true;
587 }
c1faf86b 588 return false;
d1e55a47
DM
589 },
590 $node,
05a5d547 591 self::get_extended_timeout(),
d1e55a47
DM
592 $exception,
593 true
594 );
595 }
596
3df6e801
RT
597 /**
598 * Ensures that the provided node has a attribute value set. This step can be used to check if specific
599 * JS has finished modifying the node.
600 *
601 * @throws ExpectationException
602 * @param NodeElement $node
603 * @param string $attribute attribute name
604 * @param string $attributevalue attribute value to check.
605 * @return void Throws an exception if it times out without the element being visible
606 */
607 protected function ensure_node_attribute_is_set($node, $attribute, $attributevalue) {
608
609 if (!$this->running_javascript()) {
610 return;
611 }
612
613 // Exception if it timesout and the element is still there.
614 $msg = 'The "' . $node->getXPath() . '" xpath node is not visible and it should be visible';
615 $exception = new ExpectationException($msg, $this->getSession());
616
617 // It will stop spinning once the $args[1]) == $args[2], and method returns true.
618 $this->spin(
619 function($context, $args) {
620 if ($args[0]->getAttribute($args[1]) == $args[2]) {
621 return true;
622 }
623 return false;
624 },
625 array($node, $attribute, $attributevalue),
05a5d547 626 self::get_extended_timeout(),
3df6e801
RT
627 $exception,
628 true
629 );
630 }
631
d1e55a47
DM
632 /**
633 * Ensures that the provided element is visible and we can interact with it.
634 *
635 * Returns the node in case other actions are interested in using it.
636 *
637 * @throws ExpectationException
638 * @param string $element
639 * @param string $selectortype
640 * @return NodeElement Throws an exception if it times out without being visible
641 */
642 protected function ensure_element_is_visible($element, $selectortype) {
643
644 if (!$this->running_javascript()) {
645 return;
646 }
647
648 $node = $this->get_selected_node($selectortype, $element);
649 $this->ensure_node_is_visible($node);
650
651 return $node;
652 }
653
654 /**
655 * Ensures that all the page's editors are loaded.
656 *
9f07f05a 657 * @deprecated since Moodle 2.7 MDL-44084 - please do not use this function any more.
d1e55a47 658 * @throws ElementNotFoundException
c1faf86b 659 * @throws ExpectationException
d1e55a47
DM
660 * @return void
661 */
662 protected function ensure_editors_are_loaded() {
786ced99
DW
663 global $CFG;
664
665 if (empty($CFG->behat_usedeprecated)) {
666 debugging('Function behat_base::ensure_editors_are_loaded() is deprecated. It is no longer required.');
667 }
9f07f05a 668 return;
d1e55a47 669 }
c1faf86b 670
66901a69 671 /**
672 * Checks if the current scenario, or its feature, has a specified tag.
673 *
674 * @param string $tag Tag to check
675 * @return bool True if the tag exists in scenario or feature
676 */
677 public function has_tag(string $tag) : bool {
678 return array_key_exists($tag, behat_hooks::get_tags_for_scenario());
679 }
680
3b0b5e57
RT
681 /**
682 * Change browser window size.
683 * - small: 640x480
684 * - medium: 1024x768
685 * - large: 2560x1600
686 *
687 * @param string $windowsize size of window.
5a14c4d9 688 * @param bool $viewport If true, changes viewport rather than window size
3b0b5e57
RT
689 * @throws ExpectationException
690 */
5a14c4d9 691 protected function resize_window($windowsize, $viewport = false) {
3233f32d
RT
692 // Non JS don't support resize window.
693 if (!$this->running_javascript()) {
694 return;
695 }
696
3b0b5e57
RT
697 switch ($windowsize) {
698 case "small":
3d18e5cf
AN
699 $width = 1024;
700 $height = 768;
3b0b5e57
RT
701 break;
702 case "medium":
3d18e5cf 703 $width = 1366;
3b0b5e57
RT
704 $height = 768;
705 break;
706 case "large":
707 $width = 2560;
708 $height = 1600;
709 break;
710 default:
3233f32d 711 preg_match('/^(\d+x\d+)$/', $windowsize, $matches);
3b0b5e57
RT
712 if (empty($matches) || (count($matches) != 2)) {
713 throw new ExpectationException("Invalid screen size, can't resize", $this->getSession());
714 }
715 $size = explode('x', $windowsize);
716 $width = (int) $size[0];
717 $height = (int) $size[1];
718 }
5a14c4d9 719 if ($viewport) {
720 // When setting viewport size, we set it so that the document width will be exactly
721 // as specified, assuming that there is a vertical scrollbar. (In cases where there is
722 // no scrollbar it will be slightly wider. We presume this is rare and predictable.)
723 // The window inner height will be as specified, which means the available viewport will
724 // actually be smaller if there is a horizontal scrollbar. We assume that horizontal
725 // scrollbars are rare so this doesn't matter.
726 $offset = $this->getSession()->getDriver()->evaluateScript(
727 'return (function() { var before = document.body.style.overflowY;' .
728 'document.body.style.overflowY = "scroll";' .
729 'var result = {};' .
730 'result.x = window.outerWidth - document.body.offsetWidth;' .
731 'result.y = window.outerHeight - window.innerHeight;' .
732 'document.body.style.overflowY = before;' .
733 'return result; })();');
734 $width += $offset['x'];
735 $height += $offset['y'];
736 }
737
3b0b5e57
RT
738 $this->getSession()->getDriver()->resizeWindow($width, $height);
739 }
07298309
RT
740
741 /**
742 * Waits for all the JS to be loaded.
743 *
7bfb575f 744 * @return bool Whether any JS is still pending completion.
07298309
RT
745 */
746 public function wait_for_pending_js() {
07298309 747 if (!$this->running_javascript()) {
7bfb575f
AN
748 // JS is not available therefore there is nothing to wait for.
749 return false;
07298309
RT
750 }
751
7bfb575f
AN
752 return static::wait_for_pending_js_in_session($this->getSession());
753 }
754
755 /**
756 * Waits for all the JS to be loaded.
757 *
758 * @param Session $session The Mink Session where JS can be run
759 * @return bool Whether any JS is still pending completion.
760 */
761 public static function wait_for_pending_js_in_session(Session $session) {
07298309
RT
762 // We don't use behat_base::spin() here as we don't want to end up with an exception
763 // if the page & JSs don't finish loading properly.
05a5d547 764 for ($i = 0; $i < self::get_extended_timeout() * 10; $i++) {
07298309
RT
765 $pending = '';
766 try {
7bfb575f 767 $jscode = trim(preg_replace('/\s+/', ' ', '
5536bf4f 768 return (function() {
07298309
RT
769 if (typeof M === "undefined") {
770 if (document.readyState === "complete") {
771 return "";
772 } else {
773 return "incomplete";
774 }
775 } else if (' . self::PAGE_READY_JS . ') {
776 return "";
eb9ca848 777 } else if (typeof M.util !== "undefined") {
07298309 778 return M.util.pending_js.join(":");
eb9ca848
RT
779 } else {
780 return "incomplete"
07298309 781 }
7bfb575f
AN
782 }());'));
783 $pending = $session->evaluateScript($jscode);
07298309
RT
784 } catch (NoSuchWindow $nsw) {
785 // We catch an exception here, in case we just closed the window we were interacting with.
786 // No javascript is running if there is no window right?
787 $pending = '';
788 } catch (UnknownError $e) {
789 // M is not defined when the window or the frame don't exist anymore.
790 if (strstr($e->getMessage(), 'M is not defined') != false) {
791 $pending = '';
792 }
793 }
794
795 // If there are no pending JS we stop waiting.
796 if ($pending === '') {
797 return true;
798 }
799
800 // 0.1 seconds.
801 usleep(100000);
802 }
803
7bfb575f 804 // Timeout waiting for JS to complete. It will be caught and forwarded to behat_hooks::i_look_for_exceptions().
05a5d547 805 // It is unlikely that Javascript code of a page or an AJAX request needs more than get_extended_timeout() seconds
07298309
RT
806 // to be loaded, although when pages contains Javascript errors M.util.js_complete() can not be executed, so the
807 // number of JS pending code and JS completed code will not match and we will reach this point.
05a5d547 808 throw new \Exception('Javascript code and/or AJAX requests are not ready after ' .
809 self::get_extended_timeout() .
810 ' seconds. There is a Javascript error or the code is extremely slow. ' .
811 'If you are using a slow machine, consider setting $CFG->behat_increasetimeout.');
07298309 812 }
eb9ca848
RT
813
814 /**
815 * Internal step definition to find exceptions, debugging() messages and PHP debug messages.
816 *
817 * Part of behat_hooks class as is part of the testing framework, is auto-executed
818 * after each step so no features will splicitly use it.
819 *
820 * @throws Exception Unknown type, depending on what we caught in the hook or basic \Exception.
821 * @see Moodle\BehatExtension\Tester\MoodleStepTester
822 */
823 public function look_for_exceptions() {
824 // Wrap in try in case we were interacting with a closed window.
825 try {
826
827 // Exceptions.
828 $exceptionsxpath = "//div[@data-rel='fatalerror']";
829 // Debugging messages.
830 $debuggingxpath = "//div[@data-rel='debugging']";
831 // PHP debug messages.
832 $phperrorxpath = "//div[@data-rel='phpdebugmessage']";
833 // Any other backtrace.
834 $othersxpath = "(//*[contains(., ': call to ')])[1]";
835
836 $xpaths = array($exceptionsxpath, $debuggingxpath, $phperrorxpath, $othersxpath);
837 $joinedxpath = implode(' | ', $xpaths);
838
839 // Joined xpath expression. Most of the time there will be no exceptions, so this pre-check
840 // is faster than to send the 4 xpath queries for each step.
841 if (!$this->getSession()->getDriver()->find($joinedxpath)) {
0c1bcb63
RT
842 // Check if we have recorded any errors in driver process.
843 $phperrors = behat_get_shutdown_process_errors();
844 if (!empty($phperrors)) {
845 foreach ($phperrors as $error) {
846 $errnostring = behat_get_error_string($error['type']);
847 $msgs[] = $errnostring . ": " .$error['message'] . " at " . $error['file'] . ": " . $error['line'];
848 }
849 $msg = "PHP errors found:\n" . implode("\n", $msgs);
850 throw new \Exception(htmlentities($msg));
851 }
852
eb9ca848
RT
853 return;
854 }
855
856 // Exceptions.
857 if ($errormsg = $this->getSession()->getPage()->find('xpath', $exceptionsxpath)) {
858
859 // Getting the debugging info and the backtrace.
860 $errorinfoboxes = $this->getSession()->getPage()->findAll('css', 'div.alert-error');
63e4df60
DW
861 // If errorinfoboxes is empty, try find alert-danger (bootstrap4) class.
862 if (empty($errorinfoboxes)) {
863 $errorinfoboxes = $this->getSession()->getPage()->findAll('css', 'div.alert-danger');
864 }
eb9ca848
RT
865 // If errorinfoboxes is empty, try find notifytiny (original) class.
866 if (empty($errorinfoboxes)) {
867 $errorinfoboxes = $this->getSession()->getPage()->findAll('css', 'div.notifytiny');
868 }
0c1bcb63
RT
869
870 // If errorinfoboxes is empty, try find ajax/JS exception in dialogue.
871 if (empty($errorinfoboxes)) {
872 $errorinfoboxes = $this->getSession()->getPage()->findAll('css', 'div.moodle-exception-message');
873
874 // If ajax/JS exception.
875 if ($errorinfoboxes) {
876 $errorinfo = $this->get_debug_text($errorinfoboxes[0]->getHtml());
877 }
878
879 } else {
880 $errorinfo = $this->get_debug_text($errorinfoboxes[0]->getHtml()) . "\n" .
881 $this->get_debug_text($errorinfoboxes[1]->getHtml());
882 }
eb9ca848
RT
883
884 $msg = "Moodle exception: " . $errormsg->getText() . "\n" . $errorinfo;
885 throw new \Exception(html_entity_decode($msg));
886 }
887
888 // Debugging messages.
889 if ($debuggingmessages = $this->getSession()->getPage()->findAll('xpath', $debuggingxpath)) {
890 $msgs = array();
891 foreach ($debuggingmessages as $debuggingmessage) {
892 $msgs[] = $this->get_debug_text($debuggingmessage->getHtml());
893 }
894 $msg = "debugging() message/s found:\n" . implode("\n", $msgs);
895 throw new \Exception(html_entity_decode($msg));
896 }
897
898 // PHP debug messages.
899 if ($phpmessages = $this->getSession()->getPage()->findAll('xpath', $phperrorxpath)) {
900
901 $msgs = array();
902 foreach ($phpmessages as $phpmessage) {
903 $msgs[] = $this->get_debug_text($phpmessage->getHtml());
904 }
905 $msg = "PHP debug message/s found:\n" . implode("\n", $msgs);
906 throw new \Exception(html_entity_decode($msg));
907 }
908
909 // Any other backtrace.
910 // First looking through xpath as it is faster than get and parse the whole page contents,
911 // we get the contents and look for matches once we found something to suspect that there is a backtrace.
912 if ($this->getSession()->getDriver()->find($othersxpath)) {
913 $backtracespattern = '/(line [0-9]* of [^:]*: call to [\->&;:a-zA-Z_\x7f-\xff][\->&;:a-zA-Z0-9_\x7f-\xff]*)/';
914 if (preg_match_all($backtracespattern, $this->getSession()->getPage()->getContent(), $backtraces)) {
915 $msgs = array();
916 foreach ($backtraces[0] as $backtrace) {
917 $msgs[] = $backtrace . '()';
918 }
919 $msg = "Other backtraces found:\n" . implode("\n", $msgs);
920 throw new \Exception(htmlentities($msg));
921 }
922 }
923
924 } catch (NoSuchWindow $e) {
925 // If we were interacting with a popup window it will not exists after closing it.
b095b36c
MN
926 } catch (DriverException $e) {
927 // Same reason as above.
eb9ca848
RT
928 }
929 }
930
8918a811
DM
931 /**
932 * Converts HTML tags to line breaks to display the info in CLI
933 *
934 * @param string $html
935 * @return string
936 */
937 protected function get_debug_text($html) {
938
939 // Replacing HTML tags for new lines and keeping only the text.
940 $notags = preg_replace('/<+\s*\/*\s*([A-Z][A-Z0-9]*)\b[^>]*\/*\s*>*/i', "\n", $html);
941 return preg_replace("/(\n)+/s", "\n", $notags);
942 }
943
eb9ca848
RT
944 /**
945 * Helper function to execute api in a given context.
946 *
947 * @param string $contextapi context in which api is defined.
948 * @param array $params list of params to pass.
949 * @throws Exception
950 */
951 protected function execute($contextapi, $params = array()) {
952 if (!is_array($params)) {
953 $params = array($params);
954 }
955
956 // Get required context and execute the api.
957 $contextapi = explode("::", $contextapi);
958 $context = behat_context_helper::get($contextapi[0]);
959 call_user_func_array(array($context, $contextapi[1]), $params);
960
961 // NOTE: Wait for pending js and look for exception are not optional, as this might lead to unexpected results.
962 // Don't make them optional for performance reasons.
963
964 // Wait for pending js.
965 $this->wait_for_pending_js();
966
967 // Look for exceptions.
968 $this->look_for_exceptions();
969 }
353e7876 970
971 /**
972 * Get the actual user in the behat session (note $USER does not correspond to the behat session's user).
973 * @return mixed
974 * @throws coding_exception
975 */
976 protected function get_session_user() {
977 global $DB;
978
979 $sid = $this->getSession()->getCookie('MoodleSession');
980 if (empty($sid)) {
981 throw new coding_exception('failed to get moodle session');
982 }
983 $userid = $DB->get_field('sessions', 'userid', ['sid' => $sid]);
984 if (empty($userid)) {
985 throw new coding_exception('failed to get user from seession id '.$sid);
986 }
987 return $DB->get_record('user', ['id' => $userid]);
988 }
01f2a530 989
990 /**
a1909105 991 * Set current $USER, reset access cache.
9b1fc262
SL
992 *
993 * In some cases, behat will execute the code as admin but in many cases we need to set an specific user as some
994 * API's might rely on the logged user to take some action.
995 *
a1909105 996 * @param null|int|stdClass $user user record, null or 0 means non-logged-in, positive integer means userid
a1909105
SL
997 */
998 public static function set_user($user = null) {
999 global $DB;
1000
1001 if (is_object($user)) {
1002 $user = clone($user);
1003 } else if (!$user) {
1004 // Assign valid data to admin user (some generator-related code needs a valid user).
1005 $user = $DB->get_record('user', array('username' => 'admin'));
1006 } else {
9b1fc262 1007 $user = $DB->get_record('user', array('id' => $user));
a1909105
SL
1008 }
1009 unset($user->description);
1010 unset($user->access);
1011 unset($user->preference);
1012
9b1fc262 1013 // Ensure session is empty, as it may contain caches and user specific info.
a1909105
SL
1014 \core\session\manager::init_empty_session();
1015
1016 \core\session\manager::set_user($user);
1017 }
1018 /**
01f2a530 1019 * Trigger click on node via javascript instead of actually clicking on it via pointer.
1020 *
1021 * This function resolves the issue of nested elements with click listeners or links - in these cases clicking via
1022 * the pointer may accidentally cause a click on the wrong element.
1023 * Example of issue: clicking to expand navigation nodes when the config value linkadmincategories is enabled.
1024 * @param NodeElement $node
1025 */
1026 protected function js_trigger_click($node) {
1027 if (!$this->running_javascript()) {
1028 $node->click();
1029 }
1030 $this->ensure_node_is_visible($node); // Ensures hidden elements can't be clicked.
1031 $xpath = $node->getXpath();
b5be3875
MN
1032 $driver = $this->getSession()->getDriver();
1033 if ($driver instanceof \Moodle\BehatExtension\Driver\MoodleSelenium2Driver) {
1034 $script = "Syn.click({{ELEMENT}})";
1035 $driver->triggerSynScript($xpath, $script);
1036 } else {
1037 $driver->click($xpath);
1038 }
01f2a530 1039 }
05a5d547 1040
1041 /**
1042 * Gets the required timeout in seconds.
1043 *
1044 * @param int $timeout One of the TIMEOUT constants
1045 * @return int Actual timeout (in seconds)
1046 */
1047 protected static function get_real_timeout(int $timeout) : int {
1048 global $CFG;
1049 if (!empty($CFG->behat_increasetimeout)) {
1050 return $timeout * $CFG->behat_increasetimeout;
1051 } else {
1052 return $timeout;
1053 }
1054 }
1055
1056 /**
1057 * Gets the default timeout.
1058 *
1059 * The timeout for each Behat step (load page, wait for an element to load...).
1060 *
1061 * @return int Timeout in seconds
1062 */
1063 public static function get_timeout() : int {
1064 return self::get_real_timeout(6);
1065 }
1066
1067 /**
1068 * Gets the reduced timeout.
1069 *
1070 * A reduced timeout for cases where self::get_timeout() is too much
1071 * and a simple $this->getSession()->getPage()->find() could not
1072 * be enough.
1073 *
1074 * @return int Timeout in seconds
1075 */
1076 public static function get_reduced_timeout() : int {
1077 return self::get_real_timeout(2);
1078 }
1079
1080 /**
1081 * Gets the extended timeout.
1082 *
1083 * A longer timeout for cases where the normal timeout is not enough.
1084 *
1085 * @return int Timeout in seconds
1086 */
1087 public static function get_extended_timeout() : int {
1088 return self::get_real_timeout(10);
1089 }
d4322e38 1090}