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