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