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