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