MDL-61393 pix: add tag icons
[moodle.git] / lib / behat / behat_base.php
blobe7c631fada5ba4d6b5a1cde008c4435809f991b1
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.
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/>.
17 /**
18 * Base class of all steps definitions.
20 * This script is only called from Behat as part of it's integration
21 * in Moodle.
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
29 // NOTE: no MOODLE_INTERNAL test here, this file may be required by behat before including /config.php.
31 use Behat\Mink\Exception\DriverException,
32 Behat\Mink\Exception\ExpectationException as ExpectationException,
33 Behat\Mink\Exception\ElementNotFoundException as ElementNotFoundException,
34 Behat\Mink\Element\NodeElement as NodeElement;
36 /**
37 * Steps definitions base class.
39 * To extend by the steps definitions of the different Moodle components.
41 * It can not contain steps definitions to avoid duplicates, only utility
42 * methods shared between steps.
44 * @method NodeElement find_field(string $locator) Finds a form element
45 * @method NodeElement find_button(string $locator) Finds a form input submit element or a button
46 * @method NodeElement find_link(string $locator) Finds a link on a page
47 * @method NodeElement find_file(string $locator) Finds a forum input file element
49 * @package core
50 * @category test
51 * @copyright 2012 David MonllaĆ³
52 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
54 class behat_base extends Behat\MinkExtension\Context\RawMinkContext {
56 /**
57 * Small timeout.
59 * A reduced timeout for cases where self::TIMEOUT is too much
60 * and a simple $this->getSession()->getPage()->find() could not
61 * be enough.
63 const REDUCED_TIMEOUT = 2;
65 /**
66 * The timeout for each Behat step (load page, wait for an element to load...).
68 const TIMEOUT = 6;
70 /**
71 * And extended timeout for specific cases.
73 const EXTENDED_TIMEOUT = 10;
75 /**
76 * The JS code to check that the page is ready.
78 const PAGE_READY_JS = '(typeof M !== "undefined" && M.util && M.util.pending_js && !Boolean(M.util.pending_js.length)) && (document.readyState === "complete")';
80 /**
81 * Locates url, based on provided path.
82 * Override to provide custom routing mechanism.
84 * @see Behat\MinkExtension\Context\MinkContext
85 * @param string $path
86 * @return string
88 protected function locate_path($path) {
89 $starturl = rtrim($this->getMinkParameter('base_url'), '/') . '/';
90 return 0 !== strpos($path, 'http') ? $starturl . ltrim($path, '/') : $path;
93 /**
94 * Returns the first matching element.
96 * @link http://mink.behat.org/#traverse-the-page-selectors
97 * @param string $selector The selector type (css, xpath, named...)
98 * @param mixed $locator It depends on the $selector, can be the xpath, a name, a css locator...
99 * @param Exception $exception Otherwise we throw exception with generic info
100 * @param NodeElement $node Spins around certain DOM node instead of the whole page
101 * @param int $timeout Forces a specific time out (in seconds).
102 * @return NodeElement
104 protected function find($selector, $locator, $exception = false, $node = false, $timeout = false) {
106 // Throw exception, so dev knows it is not supported.
107 if ($selector === 'named') {
108 $exception = 'Using the "named" selector is deprecated as of 3.1. '
109 .' Use the "named_partial" or use the "named_exact" selector instead.';
110 throw new ExpectationException($exception, $this->getSession());
113 // Returns the first match.
114 $items = $this->find_all($selector, $locator, $exception, $node, $timeout);
115 return count($items) ? reset($items) : null;
119 * Returns all matching elements.
121 * Adapter to Behat\Mink\Element\Element::findAll() using the spin() method.
123 * @link http://mink.behat.org/#traverse-the-page-selectors
124 * @param string $selector The selector type (css, xpath, named...)
125 * @param mixed $locator It depends on the $selector, can be the xpath, a name, a css locator...
126 * @param Exception $exception Otherwise we throw expcetion with generic info
127 * @param NodeElement $node Spins around certain DOM node instead of the whole page
128 * @param int $timeout Forces a specific time out (in seconds). If 0 is provided the default timeout will be applied.
129 * @return array NodeElements list
131 protected function find_all($selector, $locator, $exception = false, $node = false, $timeout = false) {
133 // Throw exception, so dev knows it is not supported.
134 if ($selector === 'named') {
135 $exception = 'Using the "named" selector is deprecated as of 3.1. '
136 .' Use the "named_partial" or use the "named_exact" selector instead.';
137 throw new ExpectationException($exception, $this->getSession());
140 // Generic info.
141 if (!$exception) {
143 // With named selectors we can be more specific.
144 if (($selector == 'named_exact') || ($selector == 'named_partial')) {
145 $exceptiontype = $locator[0];
146 $exceptionlocator = $locator[1];
148 // If we are in a @javascript session all contents would be displayed as HTML characters.
149 if ($this->running_javascript()) {
150 $locator[1] = html_entity_decode($locator[1], ENT_NOQUOTES);
153 } else {
154 $exceptiontype = $selector;
155 $exceptionlocator = $locator;
158 $exception = new ElementNotFoundException($this->getSession(), $exceptiontype, null, $exceptionlocator);
161 $params = array('selector' => $selector, 'locator' => $locator);
162 // Pushing $node if required.
163 if ($node) {
164 $params['node'] = $node;
167 // How much we will be waiting for the element to appear.
168 if (!$timeout) {
169 $timeout = self::TIMEOUT;
170 $microsleep = false;
171 } else {
172 // Spinning each 0.1 seconds if the timeout was forced as we understand
173 // that is a special case and is good to refine the performance as much
174 // as possible.
175 $microsleep = true;
178 // Waits for the node to appear if it exists, otherwise will timeout and throw the provided exception.
179 return $this->spin(
180 function($context, $args) {
182 // If no DOM node provided look in all the page.
183 if (empty($args['node'])) {
184 return $context->getSession()->getPage()->findAll($args['selector'], $args['locator']);
187 // For nodes contained in other nodes we can not use the basic named selectors
188 // as they include unions and they would look for matches in the DOM root.
189 $elementxpath = $context->getSession()->getSelectorsHandler()->selectorToXpath($args['selector'], $args['locator']);
191 // Split the xpath in unions and prefix them with the container xpath.
192 $unions = explode('|', $elementxpath);
193 foreach ($unions as $key => $union) {
194 $union = trim($union);
196 // We are in the container node.
197 if (strpos($union, '.') === 0) {
198 $union = substr($union, 1);
199 } else if (strpos($union, '/') !== 0) {
200 // Adding the path separator in case it is not there.
201 $union = '/' . $union;
203 $unions[$key] = $args['node']->getXpath() . $union;
206 // We can not use usual Element::find() as it prefixes with DOM root.
207 return $context->getSession()->getDriver()->find(implode('|', $unions));
209 $params,
210 $timeout,
211 $exception,
212 $microsleep
217 * Finds DOM nodes in the page using named selectors.
219 * The point of using this method instead of Mink ones is the spin
220 * method of behat_base::find() that looks for the element until it
221 * is available or it timeouts, this avoids the false failures received
222 * when selenium tries to execute commands on elements that are not
223 * ready to be used.
225 * All steps that requires elements to be available before interact with
226 * them should use one of the find* methods.
228 * The methods calls requires a {'find_' . $elementtype}($locator)
229 * format, like find_link($locator), find_select($locator),
230 * find_button($locator)...
232 * @link http://mink.behat.org/#named-selectors
233 * @throws coding_exception
234 * @param string $name The name of the called method
235 * @param mixed $arguments
236 * @return NodeElement
238 public function __call($name, $arguments) {
240 if (substr($name, 0, 5) !== 'find_') {
241 throw new coding_exception('The "' . $name . '" method does not exist');
244 // Only the named selector identifier.
245 $cleanname = substr($name, 5);
247 // All named selectors shares the interface.
248 if (count($arguments) !== 1) {
249 throw new coding_exception('The "' . $cleanname . '" named selector needs the locator as it\'s single argument');
252 // Redirecting execution to the find method with the specified selector.
253 // It will detect if it's pointing to an unexisting named selector.
254 return $this->find('named_partial',
255 array(
256 $cleanname,
257 behat_context_helper::escape($arguments[0])
263 * Escapes the double quote character.
265 * Double quote is the argument delimiter, it can be escaped
266 * with a backslash, but we auto-remove this backslashes
267 * before the step execution, this method is useful when using
268 * arguments as arguments for other steps.
270 * @param string $string
271 * @return string
273 public function escape($string) {
274 return str_replace('"', '\"', $string);
278 * Executes the passed closure until returns true or time outs.
280 * In most cases the document.readyState === 'complete' will be enough, but sometimes JS
281 * requires more time to be completely loaded or an element to be visible or whatever is required to
282 * perform some action on an element; this method receives a closure which should contain the
283 * required statements to ensure the step definition actions and assertions have all their needs
284 * satisfied and executes it until they are satisfied or it timeouts. Redirects the return of the
285 * closure to the caller.
287 * The closures requirements to work well with this spin method are:
288 * - Must return false, null or '' if something goes wrong
289 * - Must return something != false if finishes as expected, this will be the (mixed) value
290 * returned by spin()
292 * The arguments of the closure are mixed, use $args depending on your needs.
294 * You can provide an exception to give more accurate feedback to tests writers, otherwise the
295 * closure exception will be used, but you must provide an exception if the closure does not throw
296 * an exception.
298 * @throws Exception If it timeouts without receiving something != false from the closure
299 * @param Function|array|string $lambda The function to execute or an array passed to call_user_func (maps to a class method)
300 * @param mixed $args Arguments to pass to the closure
301 * @param int $timeout Timeout in seconds
302 * @param Exception $exception The exception to throw in case it time outs.
303 * @param bool $microsleep If set to true it'll sleep micro seconds rather than seconds.
304 * @return mixed The value returned by the closure
306 protected function spin($lambda, $args = false, $timeout = false, $exception = false, $microsleep = false) {
308 // Using default timeout which is pretty high.
309 if (!$timeout) {
310 $timeout = self::TIMEOUT;
312 if ($microsleep) {
313 // Will sleep 1/10th of a second by default for self::TIMEOUT seconds.
314 $loops = $timeout * 10;
315 } else {
316 // Will sleep for self::TIMEOUT seconds.
317 $loops = $timeout;
320 // DOM will never change on non-javascript case; do not wait or try again.
321 if (!$this->running_javascript()) {
322 $loops = 1;
325 for ($i = 0; $i < $loops; $i++) {
326 // We catch the exception thrown by the step definition to execute it again.
327 try {
328 // We don't check with !== because most of the time closures will return
329 // direct Behat methods returns and we are not sure it will be always (bool)false
330 // if it just runs the behat method without returning anything $return == null.
331 if ($return = call_user_func($lambda, $this, $args)) {
332 return $return;
334 } catch (Exception $e) {
335 // We would use the first closure exception if no exception has been provided.
336 if (!$exception) {
337 $exception = $e;
341 if ($this->running_javascript()) {
342 if ($microsleep) {
343 usleep(100000);
344 } else {
345 sleep(1);
350 // Using coding_exception as is a development issue if no exception has been provided.
351 if (!$exception) {
352 $exception = new coding_exception('spin method requires an exception if the callback does not throw an exception');
355 // Throwing exception to the user.
356 throw $exception;
360 * Gets a NodeElement based on the locator and selector type received as argument from steps definitions.
362 * Use behat_base::get_text_selector_node() for text-based selectors.
364 * @throws ElementNotFoundException Thrown by behat_base::find
365 * @param string $selectortype
366 * @param string $element
367 * @return NodeElement
369 protected function get_selected_node($selectortype, $element) {
371 // Getting Mink selector and locator.
372 list($selector, $locator) = $this->transform_selector($selectortype, $element);
374 // Returns the NodeElement.
375 return $this->find($selector, $locator);
379 * Gets a NodeElement based on the locator and selector type received as argument from steps definitions.
381 * @throws ElementNotFoundException Thrown by behat_base::find
382 * @param string $selectortype
383 * @param string $element
384 * @return NodeElement
386 protected function get_text_selector_node($selectortype, $element) {
388 // Getting Mink selector and locator.
389 list($selector, $locator) = $this->transform_text_selector($selectortype, $element);
391 // Returns the NodeElement.
392 return $this->find($selector, $locator);
396 * Gets the requested element inside the specified container.
398 * @throws ElementNotFoundException Thrown by behat_base::find
399 * @param mixed $selectortype The element selector type.
400 * @param mixed $element The element locator.
401 * @param mixed $containerselectortype The container selector type.
402 * @param mixed $containerelement The container locator.
403 * @return NodeElement
405 protected function get_node_in_container($selectortype, $element, $containerselectortype, $containerelement) {
407 // Gets the container, it will always be text based.
408 $containernode = $this->get_text_selector_node($containerselectortype, $containerelement);
410 list($selector, $locator) = $this->transform_selector($selectortype, $element);
412 // Specific exception giving info about where can't we find the element.
413 $locatorexceptionmsg = $element . '" in the "' . $containerelement. '" "' . $containerselectortype. '"';
414 $exception = new ElementNotFoundException($this->getSession(), $selectortype, null, $locatorexceptionmsg);
416 // Looks for the requested node inside the container node.
417 return $this->find($selector, $locator, $exception, $containernode);
421 * Transforms from step definition's argument style to Mink format.
423 * Mink has 3 different selectors css, xpath and named, where named
424 * selectors includes link, button, field... to simplify and group multiple
425 * steps in one we use the same interface, considering all link, buttons...
426 * at the same level as css selectors and xpath; this method makes the
427 * conversion from the arguments received by the steps to the selectors and locators
428 * required to interact with Mink.
430 * @throws ExpectationException
431 * @param string $selectortype It can be css, xpath or any of the named selectors.
432 * @param string $element The locator (or string) we are looking for.
433 * @return array Contains the selector and the locator expected by Mink.
435 protected function transform_selector($selectortype, $element) {
437 // Here we don't know if an allowed text selector is being used.
438 $selectors = behat_selectors::get_allowed_selectors();
439 if (!isset($selectors[$selectortype])) {
440 throw new ExpectationException('The "' . $selectortype . '" selector type does not exist', $this->getSession());
443 return behat_selectors::get_behat_selector($selectortype, $element, $this->getSession());
447 * Transforms from step definition's argument style to Mink format.
449 * Delegates all the process to behat_base::transform_selector() checking
450 * the provided $selectortype.
452 * @throws ExpectationException
453 * @param string $selectortype It can be css, xpath or any of the named selectors.
454 * @param string $element The locator (or string) we are looking for.
455 * @return array Contains the selector and the locator expected by Mink.
457 protected function transform_text_selector($selectortype, $element) {
459 $selectors = behat_selectors::get_allowed_text_selectors();
460 if (empty($selectors[$selectortype])) {
461 throw new ExpectationException('The "' . $selectortype . '" selector can not be used to select text nodes', $this->getSession());
464 return $this->transform_selector($selectortype, $element);
468 * Returns whether the scenario is running in a browser that can run Javascript or not.
470 * @return boolean
472 protected function running_javascript() {
473 return get_class($this->getSession()->getDriver()) !== 'Behat\Mink\Driver\GoutteDriver';
477 * Spins around an element until it exists
479 * @throws ExpectationException
480 * @param string $element
481 * @param string $selectortype
482 * @return void
484 protected function ensure_element_exists($element, $selectortype) {
486 // Getting the behat selector & locator.
487 list($selector, $locator) = $this->transform_selector($selectortype, $element);
489 // Exception if it timesout and the element is still there.
490 $msg = 'The "' . $element . '" element does not exist and should exist';
491 $exception = new ExpectationException($msg, $this->getSession());
493 // It will stop spinning once the find() method returns true.
494 $this->spin(
495 function($context, $args) {
496 // We don't use behat_base::find as it is already spinning.
497 if ($context->getSession()->getPage()->find($args['selector'], $args['locator'])) {
498 return true;
500 return false;
502 array('selector' => $selector, 'locator' => $locator),
503 self::EXTENDED_TIMEOUT,
504 $exception,
505 true
511 * Spins until the element does not exist
513 * @throws ExpectationException
514 * @param string $element
515 * @param string $selectortype
516 * @return void
518 protected function ensure_element_does_not_exist($element, $selectortype) {
520 // Getting the behat selector & locator.
521 list($selector, $locator) = $this->transform_selector($selectortype, $element);
523 // Exception if it timesout and the element is still there.
524 $msg = 'The "' . $element . '" element exists and should not exist';
525 $exception = new ExpectationException($msg, $this->getSession());
527 // It will stop spinning once the find() method returns false.
528 $this->spin(
529 function($context, $args) {
530 // We don't use behat_base::find() as we are already spinning.
531 if (!$context->getSession()->getPage()->find($args['selector'], $args['locator'])) {
532 return true;
534 return false;
536 array('selector' => $selector, 'locator' => $locator),
537 self::EXTENDED_TIMEOUT,
538 $exception,
539 true
544 * Ensures that the provided node is visible and we can interact with it.
546 * @throws ExpectationException
547 * @param NodeElement $node
548 * @return void Throws an exception if it times out without the element being visible
550 protected function ensure_node_is_visible($node) {
552 if (!$this->running_javascript()) {
553 return;
556 // Exception if it timesout and the element is still there.
557 $msg = 'The "' . $node->getXPath() . '" xpath node is not visible and it should be visible';
558 $exception = new ExpectationException($msg, $this->getSession());
560 // It will stop spinning once the isVisible() method returns true.
561 $this->spin(
562 function($context, $args) {
563 if ($args->isVisible()) {
564 return true;
566 return false;
568 $node,
569 self::EXTENDED_TIMEOUT,
570 $exception,
571 true
576 * Ensures that the provided node has a attribute value set. This step can be used to check if specific
577 * JS has finished modifying the node.
579 * @throws ExpectationException
580 * @param NodeElement $node
581 * @param string $attribute attribute name
582 * @param string $attributevalue attribute value to check.
583 * @return void Throws an exception if it times out without the element being visible
585 protected function ensure_node_attribute_is_set($node, $attribute, $attributevalue) {
587 if (!$this->running_javascript()) {
588 return;
591 // Exception if it timesout and the element is still there.
592 $msg = 'The "' . $node->getXPath() . '" xpath node is not visible and it should be visible';
593 $exception = new ExpectationException($msg, $this->getSession());
595 // It will stop spinning once the $args[1]) == $args[2], and method returns true.
596 $this->spin(
597 function($context, $args) {
598 if ($args[0]->getAttribute($args[1]) == $args[2]) {
599 return true;
601 return false;
603 array($node, $attribute, $attributevalue),
604 self::EXTENDED_TIMEOUT,
605 $exception,
606 true
611 * Ensures that the provided element is visible and we can interact with it.
613 * Returns the node in case other actions are interested in using it.
615 * @throws ExpectationException
616 * @param string $element
617 * @param string $selectortype
618 * @return NodeElement Throws an exception if it times out without being visible
620 protected function ensure_element_is_visible($element, $selectortype) {
622 if (!$this->running_javascript()) {
623 return;
626 $node = $this->get_selected_node($selectortype, $element);
627 $this->ensure_node_is_visible($node);
629 return $node;
633 * Ensures that all the page's editors are loaded.
635 * @deprecated since Moodle 2.7 MDL-44084 - please do not use this function any more.
636 * @throws ElementNotFoundException
637 * @throws ExpectationException
638 * @return void
640 protected function ensure_editors_are_loaded() {
641 global $CFG;
643 if (empty($CFG->behat_usedeprecated)) {
644 debugging('Function behat_base::ensure_editors_are_loaded() is deprecated. It is no longer required.');
646 return;
650 * Change browser window size.
651 * - small: 640x480
652 * - medium: 1024x768
653 * - large: 2560x1600
655 * @param string $windowsize size of window.
656 * @param bool $viewport If true, changes viewport rather than window size
657 * @throws ExpectationException
659 protected function resize_window($windowsize, $viewport = false) {
660 // Non JS don't support resize window.
661 if (!$this->running_javascript()) {
662 return;
665 switch ($windowsize) {
666 case "small":
667 $width = 640;
668 $height = 480;
669 break;
670 case "medium":
671 $width = 1024;
672 $height = 768;
673 break;
674 case "large":
675 $width = 2560;
676 $height = 1600;
677 break;
678 default:
679 preg_match('/^(\d+x\d+)$/', $windowsize, $matches);
680 if (empty($matches) || (count($matches) != 2)) {
681 throw new ExpectationException("Invalid screen size, can't resize", $this->getSession());
683 $size = explode('x', $windowsize);
684 $width = (int) $size[0];
685 $height = (int) $size[1];
687 if ($viewport) {
688 // When setting viewport size, we set it so that the document width will be exactly
689 // as specified, assuming that there is a vertical scrollbar. (In cases where there is
690 // no scrollbar it will be slightly wider. We presume this is rare and predictable.)
691 // The window inner height will be as specified, which means the available viewport will
692 // actually be smaller if there is a horizontal scrollbar. We assume that horizontal
693 // scrollbars are rare so this doesn't matter.
694 $offset = $this->getSession()->getDriver()->evaluateScript(
695 'return (function() { var before = document.body.style.overflowY;' .
696 'document.body.style.overflowY = "scroll";' .
697 'var result = {};' .
698 'result.x = window.outerWidth - document.body.offsetWidth;' .
699 'result.y = window.outerHeight - window.innerHeight;' .
700 'document.body.style.overflowY = before;' .
701 'return result; })();');
702 $width += $offset['x'];
703 $height += $offset['y'];
706 $this->getSession()->getDriver()->resizeWindow($width, $height);
710 * Waits for all the JS to be loaded.
712 * @throws \Exception
713 * @throws NoSuchWindow
714 * @throws UnknownError
715 * @return bool True or false depending whether all the JS is loaded or not.
717 public function wait_for_pending_js() {
718 // Waiting for JS is only valid for JS scenarios.
719 if (!$this->running_javascript()) {
720 return;
723 // We don't use behat_base::spin() here as we don't want to end up with an exception
724 // if the page & JSs don't finish loading properly.
725 for ($i = 0; $i < self::EXTENDED_TIMEOUT * 10; $i++) {
726 $pending = '';
727 try {
728 $jscode = '
729 return (function() {
730 if (typeof M === "undefined") {
731 if (document.readyState === "complete") {
732 return "";
733 } else {
734 return "incomplete";
736 } else if (' . self::PAGE_READY_JS . ') {
737 return "";
738 } else if (typeof M.util !== "undefined") {
739 return M.util.pending_js.join(":");
740 } else {
741 return "incomplete"
743 }());';
744 $pending = $this->getSession()->evaluateScript($jscode);
745 } catch (NoSuchWindow $nsw) {
746 // We catch an exception here, in case we just closed the window we were interacting with.
747 // No javascript is running if there is no window right?
748 $pending = '';
749 } catch (UnknownError $e) {
750 // M is not defined when the window or the frame don't exist anymore.
751 if (strstr($e->getMessage(), 'M is not defined') != false) {
752 $pending = '';
756 // If there are no pending JS we stop waiting.
757 if ($pending === '') {
758 return true;
761 // 0.1 seconds.
762 usleep(100000);
765 // Timeout waiting for JS to complete. It will be catched and forwarded to behat_hooks::i_look_for_exceptions().
766 // It is unlikely that Javascript code of a page or an AJAX request needs more than self::EXTENDED_TIMEOUT seconds
767 // to be loaded, although when pages contains Javascript errors M.util.js_complete() can not be executed, so the
768 // number of JS pending code and JS completed code will not match and we will reach this point.
769 throw new \Exception('Javascript code and/or AJAX requests are not ready after ' . self::EXTENDED_TIMEOUT .
770 ' seconds. There is a Javascript error or the code is extremely slow.');
774 * Internal step definition to find exceptions, debugging() messages and PHP debug messages.
776 * Part of behat_hooks class as is part of the testing framework, is auto-executed
777 * after each step so no features will splicitly use it.
779 * @throws Exception Unknown type, depending on what we caught in the hook or basic \Exception.
780 * @see Moodle\BehatExtension\Tester\MoodleStepTester
782 public function look_for_exceptions() {
783 // Wrap in try in case we were interacting with a closed window.
784 try {
786 // Exceptions.
787 $exceptionsxpath = "//div[@data-rel='fatalerror']";
788 // Debugging messages.
789 $debuggingxpath = "//div[@data-rel='debugging']";
790 // PHP debug messages.
791 $phperrorxpath = "//div[@data-rel='phpdebugmessage']";
792 // Any other backtrace.
793 $othersxpath = "(//*[contains(., ': call to ')])[1]";
795 $xpaths = array($exceptionsxpath, $debuggingxpath, $phperrorxpath, $othersxpath);
796 $joinedxpath = implode(' | ', $xpaths);
798 // Joined xpath expression. Most of the time there will be no exceptions, so this pre-check
799 // is faster than to send the 4 xpath queries for each step.
800 if (!$this->getSession()->getDriver()->find($joinedxpath)) {
801 // Check if we have recorded any errors in driver process.
802 $phperrors = behat_get_shutdown_process_errors();
803 if (!empty($phperrors)) {
804 foreach ($phperrors as $error) {
805 $errnostring = behat_get_error_string($error['type']);
806 $msgs[] = $errnostring . ": " .$error['message'] . " at " . $error['file'] . ": " . $error['line'];
808 $msg = "PHP errors found:\n" . implode("\n", $msgs);
809 throw new \Exception(htmlentities($msg));
812 return;
815 // Exceptions.
816 if ($errormsg = $this->getSession()->getPage()->find('xpath', $exceptionsxpath)) {
818 // Getting the debugging info and the backtrace.
819 $errorinfoboxes = $this->getSession()->getPage()->findAll('css', 'div.alert-error');
820 // If errorinfoboxes is empty, try find alert-danger (bootstrap4) class.
821 if (empty($errorinfoboxes)) {
822 $errorinfoboxes = $this->getSession()->getPage()->findAll('css', 'div.alert-danger');
824 // If errorinfoboxes is empty, try find notifytiny (original) class.
825 if (empty($errorinfoboxes)) {
826 $errorinfoboxes = $this->getSession()->getPage()->findAll('css', 'div.notifytiny');
829 // If errorinfoboxes is empty, try find ajax/JS exception in dialogue.
830 if (empty($errorinfoboxes)) {
831 $errorinfoboxes = $this->getSession()->getPage()->findAll('css', 'div.moodle-exception-message');
833 // If ajax/JS exception.
834 if ($errorinfoboxes) {
835 $errorinfo = $this->get_debug_text($errorinfoboxes[0]->getHtml());
838 } else {
839 $errorinfo = $this->get_debug_text($errorinfoboxes[0]->getHtml()) . "\n" .
840 $this->get_debug_text($errorinfoboxes[1]->getHtml());
843 $msg = "Moodle exception: " . $errormsg->getText() . "\n" . $errorinfo;
844 throw new \Exception(html_entity_decode($msg));
847 // Debugging messages.
848 if ($debuggingmessages = $this->getSession()->getPage()->findAll('xpath', $debuggingxpath)) {
849 $msgs = array();
850 foreach ($debuggingmessages as $debuggingmessage) {
851 $msgs[] = $this->get_debug_text($debuggingmessage->getHtml());
853 $msg = "debugging() message/s found:\n" . implode("\n", $msgs);
854 throw new \Exception(html_entity_decode($msg));
857 // PHP debug messages.
858 if ($phpmessages = $this->getSession()->getPage()->findAll('xpath', $phperrorxpath)) {
860 $msgs = array();
861 foreach ($phpmessages as $phpmessage) {
862 $msgs[] = $this->get_debug_text($phpmessage->getHtml());
864 $msg = "PHP debug message/s found:\n" . implode("\n", $msgs);
865 throw new \Exception(html_entity_decode($msg));
868 // Any other backtrace.
869 // First looking through xpath as it is faster than get and parse the whole page contents,
870 // we get the contents and look for matches once we found something to suspect that there is a backtrace.
871 if ($this->getSession()->getDriver()->find($othersxpath)) {
872 $backtracespattern = '/(line [0-9]* of [^:]*: call to [\->&;:a-zA-Z_\x7f-\xff][\->&;:a-zA-Z0-9_\x7f-\xff]*)/';
873 if (preg_match_all($backtracespattern, $this->getSession()->getPage()->getContent(), $backtraces)) {
874 $msgs = array();
875 foreach ($backtraces[0] as $backtrace) {
876 $msgs[] = $backtrace . '()';
878 $msg = "Other backtraces found:\n" . implode("\n", $msgs);
879 throw new \Exception(htmlentities($msg));
883 } catch (NoSuchWindow $e) {
884 // If we were interacting with a popup window it will not exists after closing it.
885 } catch (DriverException $e) {
886 // Same reason as above.
891 * Converts HTML tags to line breaks to display the info in CLI
893 * @param string $html
894 * @return string
896 protected function get_debug_text($html) {
898 // Replacing HTML tags for new lines and keeping only the text.
899 $notags = preg_replace('/<+\s*\/*\s*([A-Z][A-Z0-9]*)\b[^>]*\/*\s*>*/i', "\n", $html);
900 return preg_replace("/(\n)+/s", "\n", $notags);
904 * Helper function to execute api in a given context.
906 * @param string $contextapi context in which api is defined.
907 * @param array $params list of params to pass.
908 * @throws Exception
910 protected function execute($contextapi, $params = array()) {
911 if (!is_array($params)) {
912 $params = array($params);
915 // Get required context and execute the api.
916 $contextapi = explode("::", $contextapi);
917 $context = behat_context_helper::get($contextapi[0]);
918 call_user_func_array(array($context, $contextapi[1]), $params);
920 // NOTE: Wait for pending js and look for exception are not optional, as this might lead to unexpected results.
921 // Don't make them optional for performance reasons.
923 // Wait for pending js.
924 $this->wait_for_pending_js();
926 // Look for exceptions.
927 $this->look_for_exceptions();
931 * Get the actual user in the behat session (note $USER does not correspond to the behat session's user).
932 * @return mixed
933 * @throws coding_exception
935 protected function get_session_user() {
936 global $DB;
938 $sid = $this->getSession()->getCookie('MoodleSession');
939 if (empty($sid)) {
940 throw new coding_exception('failed to get moodle session');
942 $userid = $DB->get_field('sessions', 'userid', ['sid' => $sid]);
943 if (empty($userid)) {
944 throw new coding_exception('failed to get user from seession id '.$sid);
946 return $DB->get_record('user', ['id' => $userid]);
950 * Trigger click on node via javascript instead of actually clicking on it via pointer.
952 * This function resolves the issue of nested elements with click listeners or links - in these cases clicking via
953 * the pointer may accidentally cause a click on the wrong element.
954 * Example of issue: clicking to expand navigation nodes when the config value linkadmincategories is enabled.
955 * @param NodeElement $node
957 protected function js_trigger_click($node) {
958 if (!$this->running_javascript()) {
959 $node->click();
961 $this->ensure_node_is_visible($node); // Ensures hidden elements can't be clicked.
962 $xpath = $node->getXpath();
963 $driver = $this->getSession()->getDriver();
964 if ($driver instanceof \Moodle\BehatExtension\Driver\MoodleSelenium2Driver) {
965 $script = "Syn.click({{ELEMENT}})";
966 $driver->triggerSynScript($xpath, $script);
967 } else {
968 $driver->click($xpath);