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