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