efe954b3893b4240a1d7744d9cbed2dd974569ee
[moodle.git] / lib / behat / behat_base.php
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/>.
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  */
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;
35 /**
36  * Steps definitions base class.
37  *
38  * To extend by the steps definitions of the different Moodle components.
39  *
40  * It can not contain steps definitions to avoid duplicates, only utility
41  * methods shared between steps.
42  *
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
47  *
48  * @package   core
49  * @category  test
50  * @copyright 2012 David Monllaó
51  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
52  */
53 class behat_base extends Behat\MinkExtension\Context\RawMinkContext {
55     /**
56      * Small timeout.
57      *
58      * A reduced timeout for cases where self::TIMEOUT is too much
59      * and a simple $this->getSession()->getPage()->find() could not
60      * be enough.
61      */
62     const REDUCED_TIMEOUT = 2;
64     /**
65      * The timeout for each Behat step (load page, wait for an element to load...).
66      */
67     const TIMEOUT = 6;
69     /**
70      * And extended timeout for specific cases.
71      */
72     const EXTENDED_TIMEOUT = 10;
74     /**
75      * The JS code to check that the page is ready.
76      */
77     const PAGE_READY_JS = '(typeof M !== "undefined" && M.util && M.util.pending_js && !Boolean(M.util.pending_js.length)) && (document.readyState === "complete")';
79     /**
80      * Locates url, based on provided path.
81      * Override to provide custom routing mechanism.
82      *
83      * @see Behat\MinkExtension\Context\MinkContext
84      * @param string $path
85      * @return string
86      */
87     protected function locate_path($path) {
88         $starturl = rtrim($this->getMinkParameter('base_url'), '/') . '/';
89         return 0 !== strpos($path, 'http') ? $starturl . ltrim($path, '/') : $path;
90     }
92     /**
93      * Returns the first matching element.
94      *
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
102      */
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;
108     }
110     /**
111      * Returns all matching elements.
112      *
113      * Adapter to Behat\Mink\Element\Element::findAll() using the spin() method.
114      *
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
122      */
123     protected function find_all($selector, $locator, $exception = false, $node = false, $timeout = false) {
125         // Generic info.
126         if (!$exception) {
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);
136                 }
138             } else {
139                 $exceptiontype = $selector;
140                 $exceptionlocator = $locator;
141             }
143             $exception = new ElementNotFoundException($this->getSession(), $exceptiontype, null, $exceptionlocator);
144         }
146         $params = array('selector' => $selector, 'locator' => $locator);
147         // Pushing $node if required.
148         if ($node) {
149             $params['node'] = $node;
150         }
152         // How much we will be waiting for the element to appear.
153         if (!$timeout) {
154             $timeout = self::TIMEOUT;
155             $microsleep = false;
156         } else {
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
159             // as possible.
160             $microsleep = true;
161         }
163         // Waits for the node to appear if it exists, otherwise will timeout and throw the provided exception.
164         return $this->spin(
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']);
170                 }
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;
187                     }
188                     $unions[$key] = $args['node']->getXpath() . $union;
189                 }
191                 // We can not use usual Element::find() as it prefixes with DOM root.
192                 return $context->getSession()->getDriver()->find(implode('|', $unions));
193             },
194             $params,
195             $timeout,
196             $exception,
197             $microsleep
198         );
199     }
201     /**
202      * Finds DOM nodes in the page using named selectors.
203      *
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
208      * ready to be used.
209      *
210      * All steps that requires elements to be available before interact with
211      * them should use one of the find* methods.
212      *
213      * The methods calls requires a {'find_' . $elementtype}($locator)
214      * format, like find_link($locator), find_select($locator),
215      * find_button($locator)...
216      *
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
222      */
223     public function __call($name, $arguments) {
225         if (substr($name, 0, 5) !== 'find_') {
226             throw new coding_exception('The "' . $name . '" method does not exist');
227         }
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');
235         }
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',
240             array(
241                 $cleanname,
242                 $this->getSession()->getSelectorsHandler()->xpathLiteral($arguments[0])
243             )
244         );
245     }
247     /**
248      * Escapes the double quote character.
249      *
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.
254      *
255      * @param string $string
256      * @return string
257      */
258     public function escape($string) {
259         return str_replace('"', '\"', $string);
260     }
262     /**
263      * Executes the passed closure until returns true or time outs.
264      *
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.
271      *
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
275      * returned by spin()
276      *
277      * The arguments of the closure are mixed, use $args depending on your needs.
278      *
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
281      * an exception.
282      *
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
290      */
291     protected function spin($lambda, $args = false, $timeout = false, $exception = false, $microsleep = false) {
293         // Using default timeout which is pretty high.
294         if (!$timeout) {
295             $timeout = self::TIMEOUT;
296         }
297         if ($microsleep) {
298             // Will sleep 1/10th of a second by default for self::TIMEOUT seconds.
299             $loops = $timeout * 10;
300         } else {
301             // Will sleep for self::TIMEOUT seconds.
302             $loops = $timeout;
303         }
305         // DOM will never change on non-javascript case; do not wait or try again.
306         if (!$this->running_javascript()) {
307             $loops = 1;
308         }
310         for ($i = 0; $i < $loops; $i++) {
311             // We catch the exception thrown by the step definition to execute it again.
312             try {
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)) {
317                     return $return;
318                 }
319             } catch (Exception $e) {
320                 // We would use the first closure exception if no exception has been provided.
321                 if (!$exception) {
322                     $exception = $e;
323                 }
324                 // We wait until no exception is thrown or timeout expires.
325                 continue;
326             }
328             if ($this->running_javascript()) {
329                 if ($microsleep) {
330                     usleep(100000);
331                 } else {
332                     sleep(1);
333                 }
334             }
335         }
337         // Using coding_exception as is a development issue if no exception has been provided.
338         if (!$exception) {
339             $exception = new coding_exception('spin method requires an exception if the callback does not throw an exception');
340         }
342         // Throwing exception to the user.
343         throw $exception;
344     }
346     /**
347      * Gets a NodeElement based on the locator and selector type received as argument from steps definitions.
348      *
349      * Use behat_base::get_text_selector_node() for text-based selectors.
350      *
351      * @throws ElementNotFoundException Thrown by behat_base::find
352      * @param string $selectortype
353      * @param string $element
354      * @return NodeElement
355      */
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);
363     }
365     /**
366      * Gets a NodeElement based on the locator and selector type received as argument from steps definitions.
367      *
368      * @throws ElementNotFoundException Thrown by behat_base::find
369      * @param string $selectortype
370      * @param string $element
371      * @return NodeElement
372      */
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);
380     }
382     /**
383      * Gets the requested element inside the specified container.
384      *
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
391      */
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);
405     }
407     /**
408      * Transforms from step definition's argument style to Mink format.
409      *
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.
416      *
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.
421      */
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());
428         }
430         return behat_selectors::get_behat_selector($selectortype, $element, $this->getSession());
431     }
433     /**
434      * Transforms from step definition's argument style to Mink format.
435      *
436      * Delegates all the process to behat_base::transform_selector() checking
437      * the provided $selectortype.
438      *
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.
443      */
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());
449         }
451         return $this->transform_selector($selectortype, $element);
452     }
454     /**
455      * Returns whether the scenario is running in a browser that can run Javascript or not.
456      *
457      * @return boolean
458      */
459     protected function running_javascript() {
460         return get_class($this->getSession()->getDriver()) !== 'Behat\Mink\Driver\GoutteDriver';
461     }
463     /**
464      * Spins around an element until it exists
465      *
466      * @throws ExpectationException
467      * @param string $element
468      * @param string $selectortype
469      * @return void
470      */
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.
481         $this->spin(
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'])) {
485                     return true;
486                 }
487                 return false;
488             },
489             array('selector' => $selector, 'locator' => $locator),
490             self::EXTENDED_TIMEOUT,
491             $exception,
492             true
493         );
495     }
497     /**
498      * Spins until the element does not exist
499      *
500      * @throws ExpectationException
501      * @param string $element
502      * @param string $selectortype
503      * @return void
504      */
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.
515         $this->spin(
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'])) {
519                     return true;
520                 }
521                 return false;
522             },
523             array('selector' => $selector, 'locator' => $locator),
524             self::EXTENDED_TIMEOUT,
525             $exception,
526             true
527         );
528     }
530     /**
531      * Ensures that the provided node is visible and we can interact with it.
532      *
533      * @throws ExpectationException
534      * @param NodeElement $node
535      * @return void Throws an exception if it times out without the element being visible
536      */
537     protected function ensure_node_is_visible($node) {
539         if (!$this->running_javascript()) {
540             return;
541         }
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.
548         $this->spin(
549             function($context, $args) {
550                 if ($args->isVisible()) {
551                     return true;
552                 }
553                 return false;
554             },
555             $node,
556             self::EXTENDED_TIMEOUT,
557             $exception,
558             true
559         );
560     }
562     /**
563      * Ensures that the provided element is visible and we can interact with it.
564      *
565      * Returns the node in case other actions are interested in using it.
566      *
567      * @throws ExpectationException
568      * @param string $element
569      * @param string $selectortype
570      * @return NodeElement Throws an exception if it times out without being visible
571      */
572     protected function ensure_element_is_visible($element, $selectortype) {
574         if (!$this->running_javascript()) {
575             return;
576         }
578         $node = $this->get_selected_node($selectortype, $element);
579         $this->ensure_node_is_visible($node);
581         return $node;
582     }
584     /**
585      * Ensures that all the page's editors are loaded.
586      *
587      * @deprecated since Moodle 2.7 MDL-44084 - please do not use this function any more.
588      * @throws ElementNotFoundException
589      * @throws ExpectationException
590      * @return void
591      */
592     protected function ensure_editors_are_loaded() {
593         global $CFG;
595         if (empty($CFG->behat_usedeprecated)) {
596             debugging('Function behat_base::ensure_editors_are_loaded() is deprecated. It is no longer required.');
597         }
598         return;
599     }
601     /**
602      * Change browser window size.
603      *   - small: 640x480
604      *   - medium: 1024x768
605      *   - large: 2560x1600
606      *
607      * @param string $windowsize size of window.
608      * @throws ExpectationException
609      */
610     protected function resize_window($windowsize) {
611         // Non JS don't support resize window.
612         if (!$this->running_javascript()) {
613             return;
614         }
616         switch ($windowsize) {
617             case "small":
618                 $width = 640;
619                 $height = 480;
620                 break;
621             case "medium":
622                 $width = 1024;
623                 $height = 768;
624                 break;
625             case "large":
626                 $width = 2560;
627                 $height = 1600;
628                 break;
629             default:
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());
633                 }
634                 $size = explode('x', $windowsize);
635                 $width = (int) $size[0];
636                 $height = (int) $size[1];
637         }
638         $this->getSession()->getDriver()->resizeWindow($width, $height);
639     }