2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
18 * Base class of all steps definitions.
20 * This script is only called from Behat as part of it's integration
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\ExpectationException as ExpectationException,
32 Behat\Mink\Exception\ElementNotFoundException as ElementNotFoundException,
33 Behat\Mink\Element\NodeElement as NodeElement;
36 * Steps definitions base class.
38 * To extend by the steps definitions of the different Moodle components.
40 * It can not contain steps definitions to avoid duplicates, only utility
41 * methods shared between steps.
43 * @method NodeElement find_field(string $locator) Finds a form element
44 * @method NodeElement find_button(string $locator) Finds a form input submit element or a button
45 * @method NodeElement find_link(string $locator) Finds a link on a page
46 * @method NodeElement find_file(string $locator) Finds a forum input file element
50 * @copyright 2012 David Monllaó
51 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
53 class behat_base extends Behat\MinkExtension\Context\RawMinkContext {
58 * A reduced timeout for cases where self::TIMEOUT is too much
59 * and a simple $this->getSession()->getPage()->find() could not
62 const REDUCED_TIMEOUT = 2;
65 * The timeout for each Behat step (load page, wait for an element to load...).
70 * And extended timeout for specific cases.
72 const EXTENDED_TIMEOUT = 10;
75 * The JS code to check that the page is ready.
77 const PAGE_READY_JS = '(typeof M !== "undefined" && M.util && M.util.pending_js && !Boolean(M.util.pending_js.length)) && (document.readyState === "complete")';
80 * Locates url, based on provided path.
81 * Override to provide custom routing mechanism.
83 * @see Behat\MinkExtension\Context\MinkContext
87 protected function locate_path($path) {
88 $starturl = rtrim($this->getMinkParameter('base_url'), '/') . '/';
89 return 0 !== strpos($path, 'http') ? $starturl . ltrim($path, '/') : $path;
93 * Returns the first matching element.
95 * @link http://mink.behat.org/#traverse-the-page-selectors
96 * @param string $selector The selector type (css, xpath, named...)
97 * @param mixed $locator It depends on the $selector, can be the xpath, a name, a css locator...
98 * @param Exception $exception Otherwise we throw exception with generic info
99 * @param NodeElement $node Spins around certain DOM node instead of the whole page
100 * @param int $timeout Forces a specific time out (in seconds).
101 * @return NodeElement
103 protected function find($selector, $locator, $exception = false, $node = false, $timeout = false) {
105 // Returns the first match.
106 $items = $this->find_all($selector, $locator, $exception, $node, $timeout);
107 return count($items) ? reset($items) : null;
111 * Returns all matching elements.
113 * Adapter to Behat\Mink\Element\Element::findAll() using the spin() method.
115 * @link http://mink.behat.org/#traverse-the-page-selectors
116 * @param string $selector The selector type (css, xpath, named...)
117 * @param mixed $locator It depends on the $selector, can be the xpath, a name, a css locator...
118 * @param Exception $exception Otherwise we throw expcetion with generic info
119 * @param NodeElement $node Spins around certain DOM node instead of the whole page
120 * @param int $timeout Forces a specific time out (in seconds). If 0 is provided the default timeout will be applied.
121 * @return array NodeElements list
123 protected function find_all($selector, $locator, $exception = false, $node = false, $timeout = false) {
128 // With named selectors we can be more specific.
129 if ($selector == 'named') {
130 $exceptiontype = $locator[0];
131 $exceptionlocator = $locator[1];
133 // If we are in a @javascript session all contents would be displayed as HTML characters.
134 if ($this->running_javascript()) {
135 $locator[1] = html_entity_decode($locator[1], ENT_NOQUOTES);
139 $exceptiontype = $selector;
140 $exceptionlocator = $locator;
143 $exception = new ElementNotFoundException($this->getSession(), $exceptiontype, null, $exceptionlocator);
146 $params = array('selector' => $selector, 'locator' => $locator);
147 // Pushing $node if required.
149 $params['node'] = $node;
152 // How much we will be waiting for the element to appear.
154 $timeout = self::TIMEOUT;
157 // Spinning each 0.1 seconds if the timeout was forced as we understand
158 // that is a special case and is good to refine the performance as much
163 // Waits for the node to appear if it exists, otherwise will timeout and throw the provided exception.
165 function($context, $args) {
167 // If no DOM node provided look in all the page.
168 if (empty($args['node'])) {
169 return $context->getSession()->getPage()->findAll($args['selector'], $args['locator']);
172 // For nodes contained in other nodes we can not use the basic named selectors
173 // as they include unions and they would look for matches in the DOM root.
174 $elementxpath = $context->getSession()->getSelectorsHandler()->selectorToXpath($args['selector'], $args['locator']);
176 // Split the xpath in unions and prefix them with the container xpath.
177 $unions = explode('|', $elementxpath);
178 foreach ($unions as $key => $union) {
179 $union = trim($union);
181 // We are in the container node.
182 if (strpos($union, '.') === 0) {
183 $union = substr($union, 1);
184 } else if (strpos($union, '/') !== 0) {
185 // Adding the path separator in case it is not there.
186 $union = '/' . $union;
188 $unions[$key] = $args['node']->getXpath() . $union;
191 // We can not use usual Element::find() as it prefixes with DOM root.
192 return $context->getSession()->getDriver()->find(implode('|', $unions));
202 * Finds DOM nodes in the page using named selectors.
204 * The point of using this method instead of Mink ones is the spin
205 * method of behat_base::find() that looks for the element until it
206 * is available or it timeouts, this avoids the false failures received
207 * when selenium tries to execute commands on elements that are not
210 * All steps that requires elements to be available before interact with
211 * them should use one of the find* methods.
213 * The methods calls requires a {'find_' . $elementtype}($locator)
214 * format, like find_link($locator), find_select($locator),
215 * find_button($locator)...
217 * @link http://mink.behat.org/#named-selectors
218 * @throws coding_exception
219 * @param string $name The name of the called method
220 * @param mixed $arguments
221 * @return NodeElement
223 public function __call($name, $arguments) {
225 if (substr($name, 0, 5) !== 'find_') {
226 throw new coding_exception('The "' . $name . '" method does not exist');
229 // Only the named selector identifier.
230 $cleanname = substr($name, 5);
232 // All named selectors shares the interface.
233 if (count($arguments) !== 1) {
234 throw new coding_exception('The "' . $cleanname . '" named selector needs the locator as it\'s single argument');
237 // Redirecting execution to the find method with the specified selector.
238 // It will detect if it's pointing to an unexisting named selector.
239 return $this->find('named',
242 $this->getSession()->getSelectorsHandler()->xpathLiteral($arguments[0])
248 * Escapes the double quote character.
250 * Double quote is the argument delimiter, it can be escaped
251 * with a backslash, but we auto-remove this backslashes
252 * before the step execution, this method is useful when using
253 * arguments as arguments for other steps.
255 * @param string $string
258 public function escape($string) {
259 return str_replace('"', '\"', $string);
263 * Executes the passed closure until returns true or time outs.
265 * In most cases the document.readyState === 'complete' will be enough, but sometimes JS
266 * requires more time to be completely loaded or an element to be visible or whatever is required to
267 * perform some action on an element; this method receives a closure which should contain the
268 * required statements to ensure the step definition actions and assertions have all their needs
269 * satisfied and executes it until they are satisfied or it timeouts. Redirects the return of the
270 * closure to the caller.
272 * The closures requirements to work well with this spin method are:
273 * - Must return false, null or '' if something goes wrong
274 * - Must return something != false if finishes as expected, this will be the (mixed) value
277 * The arguments of the closure are mixed, use $args depending on your needs.
279 * You can provide an exception to give more accurate feedback to tests writers, otherwise the
280 * closure exception will be used, but you must provide an exception if the closure does not throw
283 * @throws Exception If it timeouts without receiving something != false from the closure
284 * @param Function|array|string $lambda The function to execute or an array passed to call_user_func (maps to a class method)
285 * @param mixed $args Arguments to pass to the closure
286 * @param int $timeout Timeout in seconds
287 * @param Exception $exception The exception to throw in case it time outs.
288 * @param bool $microsleep If set to true it'll sleep micro seconds rather than seconds.
289 * @return mixed The value returned by the closure
291 protected function spin($lambda, $args = false, $timeout = false, $exception = false, $microsleep = false) {
293 // Using default timeout which is pretty high.
295 $timeout = self::TIMEOUT;
298 // Will sleep 1/10th of a second by default for self::TIMEOUT seconds.
299 $loops = $timeout * 10;
301 // Will sleep for self::TIMEOUT seconds.
305 // DOM will never change on non-javascript case; do not wait or try again.
306 if (!$this->running_javascript()) {
310 for ($i = 0; $i < $loops; $i++) {
311 // We catch the exception thrown by the step definition to execute it again.
313 // We don't check with !== because most of the time closures will return
314 // direct Behat methods returns and we are not sure it will be always (bool)false
315 // if it just runs the behat method without returning anything $return == null.
316 if ($return = call_user_func($lambda, $this, $args)) {
319 } catch (Exception $e) {
320 // We would use the first closure exception if no exception has been provided.
324 // We wait until no exception is thrown or timeout expires.
328 if ($this->running_javascript()) {
337 // Using coding_exception as is a development issue if no exception has been provided.
339 $exception = new coding_exception('spin method requires an exception if the callback does not throw an exception');
342 // Throwing exception to the user.
347 * Gets a NodeElement based on the locator and selector type received as argument from steps definitions.
349 * Use behat_base::get_text_selector_node() for text-based selectors.
351 * @throws ElementNotFoundException Thrown by behat_base::find
352 * @param string $selectortype
353 * @param string $element
354 * @return NodeElement
356 protected function get_selected_node($selectortype, $element) {
358 // Getting Mink selector and locator.
359 list($selector, $locator) = $this->transform_selector($selectortype, $element);
361 // Returns the NodeElement.
362 return $this->find($selector, $locator);
366 * Gets a NodeElement based on the locator and selector type received as argument from steps definitions.
368 * @throws ElementNotFoundException Thrown by behat_base::find
369 * @param string $selectortype
370 * @param string $element
371 * @return NodeElement
373 protected function get_text_selector_node($selectortype, $element) {
375 // Getting Mink selector and locator.
376 list($selector, $locator) = $this->transform_text_selector($selectortype, $element);
378 // Returns the NodeElement.
379 return $this->find($selector, $locator);
383 * Gets the requested element inside the specified container.
385 * @throws ElementNotFoundException Thrown by behat_base::find
386 * @param mixed $selectortype The element selector type.
387 * @param mixed $element The element locator.
388 * @param mixed $containerselectortype The container selector type.
389 * @param mixed $containerelement The container locator.
390 * @return NodeElement
392 protected function get_node_in_container($selectortype, $element, $containerselectortype, $containerelement) {
394 // Gets the container, it will always be text based.
395 $containernode = $this->get_text_selector_node($containerselectortype, $containerelement);
397 list($selector, $locator) = $this->transform_selector($selectortype, $element);
399 // Specific exception giving info about where can't we find the element.
400 $locatorexceptionmsg = $element . '" in the "' . $containerelement. '" "' . $containerselectortype. '"';
401 $exception = new ElementNotFoundException($this->getSession(), $selectortype, null, $locatorexceptionmsg);
403 // Looks for the requested node inside the container node.
404 return $this->find($selector, $locator, $exception, $containernode);
408 * Transforms from step definition's argument style to Mink format.
410 * Mink has 3 different selectors css, xpath and named, where named
411 * selectors includes link, button, field... to simplify and group multiple
412 * steps in one we use the same interface, considering all link, buttons...
413 * at the same level as css selectors and xpath; this method makes the
414 * conversion from the arguments received by the steps to the selectors and locators
415 * required to interact with Mink.
417 * @throws ExpectationException
418 * @param string $selectortype It can be css, xpath or any of the named selectors.
419 * @param string $element The locator (or string) we are looking for.
420 * @return array Contains the selector and the locator expected by Mink.
422 protected function transform_selector($selectortype, $element) {
424 // Here we don't know if an allowed text selector is being used.
425 $selectors = behat_selectors::get_allowed_selectors();
426 if (!isset($selectors[$selectortype])) {
427 throw new ExpectationException('The "' . $selectortype . '" selector type does not exist', $this->getSession());
430 return behat_selectors::get_behat_selector($selectortype, $element, $this->getSession());
434 * Transforms from step definition's argument style to Mink format.
436 * Delegates all the process to behat_base::transform_selector() checking
437 * the provided $selectortype.
439 * @throws ExpectationException
440 * @param string $selectortype It can be css, xpath or any of the named selectors.
441 * @param string $element The locator (or string) we are looking for.
442 * @return array Contains the selector and the locator expected by Mink.
444 protected function transform_text_selector($selectortype, $element) {
446 $selectors = behat_selectors::get_allowed_text_selectors();
447 if (empty($selectors[$selectortype])) {
448 throw new ExpectationException('The "' . $selectortype . '" selector can not be used to select text nodes', $this->getSession());
451 return $this->transform_selector($selectortype, $element);
455 * Returns whether the scenario is running in a browser that can run Javascript or not.
459 protected function running_javascript() {
460 return get_class($this->getSession()->getDriver()) !== 'Behat\Mink\Driver\GoutteDriver';
464 * Spins around an element until it exists
466 * @throws ExpectationException
467 * @param string $element
468 * @param string $selectortype
471 protected function ensure_element_exists($element, $selectortype) {
473 // Getting the behat selector & locator.
474 list($selector, $locator) = $this->transform_selector($selectortype, $element);
476 // Exception if it timesout and the element is still there.
477 $msg = 'The "' . $element . '" element does not exist and should exist';
478 $exception = new ExpectationException($msg, $this->getSession());
480 // It will stop spinning once the find() method returns true.
482 function($context, $args) {
483 // We don't use behat_base::find as it is already spinning.
484 if ($context->getSession()->getPage()->find($args['selector'], $args['locator'])) {
489 array('selector' => $selector, 'locator' => $locator),
490 self::EXTENDED_TIMEOUT,
498 * Spins until the element does not exist
500 * @throws ExpectationException
501 * @param string $element
502 * @param string $selectortype
505 protected function ensure_element_does_not_exist($element, $selectortype) {
507 // Getting the behat selector & locator.
508 list($selector, $locator) = $this->transform_selector($selectortype, $element);
510 // Exception if it timesout and the element is still there.
511 $msg = 'The "' . $element . '" element exists and should not exist';
512 $exception = new ExpectationException($msg, $this->getSession());
514 // It will stop spinning once the find() method returns false.
516 function($context, $args) {
517 // We don't use behat_base::find() as we are already spinning.
518 if (!$context->getSession()->getPage()->find($args['selector'], $args['locator'])) {
523 array('selector' => $selector, 'locator' => $locator),
524 self::EXTENDED_TIMEOUT,
531 * Ensures that the provided node is visible and we can interact with it.
533 * @throws ExpectationException
534 * @param NodeElement $node
535 * @return void Throws an exception if it times out without the element being visible
537 protected function ensure_node_is_visible($node) {
539 if (!$this->running_javascript()) {
543 // Exception if it timesout and the element is still there.
544 $msg = 'The "' . $node->getXPath() . '" xpath node is not visible and it should be visible';
545 $exception = new ExpectationException($msg, $this->getSession());
547 // It will stop spinning once the isVisible() method returns true.
549 function($context, $args) {
550 if ($args->isVisible()) {
556 self::EXTENDED_TIMEOUT,
563 * Ensures that the provided element is visible and we can interact with it.
565 * Returns the node in case other actions are interested in using it.
567 * @throws ExpectationException
568 * @param string $element
569 * @param string $selectortype
570 * @return NodeElement Throws an exception if it times out without being visible
572 protected function ensure_element_is_visible($element, $selectortype) {
574 if (!$this->running_javascript()) {
578 $node = $this->get_selected_node($selectortype, $element);
579 $this->ensure_node_is_visible($node);
585 * Ensures that all the page's editors are loaded.
587 * @deprecated since Moodle 2.7 MDL-44084 - please do not use this function any more.
588 * @throws ElementNotFoundException
589 * @throws ExpectationException
592 protected function ensure_editors_are_loaded() {
595 if (empty($CFG->behat_usedeprecated)) {
596 debugging('Function behat_base::ensure_editors_are_loaded() is deprecated. It is no longer required.');
602 * Change browser window size.
607 * @param string $windowsize size of window.
608 * @throws ExpectationException
610 protected function resize_window($windowsize) {
611 // Non JS don't support resize window.
612 if (!$this->running_javascript()) {
616 switch ($windowsize) {
630 preg_match('/^(\d+x\d+)$/', $windowsize, $matches);
631 if (empty($matches) || (count($matches) != 2)) {
632 throw new ExpectationException("Invalid screen size, can't resize", $this->getSession());
634 $size = explode('x', $windowsize);
635 $width = (int) $size[0];
636 $height = (int) $size[1];
638 $this->getSession()->getDriver()->resizeWindow($width, $height);