MDL-41988 behat: improvements to spin
[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
ff48a235
DM
31use Behat\Mink\Exception\ExpectationException as ExpectationException,
32 Behat\Mink\Exception\ElementNotFoundException as ElementNotFoundException;
33
d4322e38
DM
34/**
35 * Steps definitions base class.
36 *
37 * To extend by the steps definitions of the different Moodle components.
38 *
39 * It can not contain steps definitions to avoid duplicates, only utility
40 * methods shared between steps.
41 *
42 * @package core
43 * @category test
44 * @copyright 2012 David MonllaĆ³
45 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
46 */
47class behat_base extends Behat\MinkExtension\Context\RawMinkContext {
48
49 /**
50 * The timeout for each Behat step (load page, wait for an element to load...).
51 */
52 const TIMEOUT = 6;
53
786ea937
DM
54 /**
55 * Locates url, based on provided path.
56 * Override to provide custom routing mechanism.
57 *
58 * @see Behat\MinkExtension\Context\MinkContext
59 * @param string $path
60 * @return string
61 */
40923977 62 protected function locate_path($path) {
46ac40cd
DM
63 $starturl = rtrim($this->getMinkParameter('base_url'), '/') . '/';
64 return 0 !== strpos($path, 'http') ? $starturl . ltrim($path, '/') : $path;
786ea937
DM
65 }
66
ff48a235 67 /**
f8f1bdc3 68 * Returns the first matching element.
ff48a235
DM
69 *
70 * @link http://mink.behat.org/#traverse-the-page-selectors
ff48a235
DM
71 * @param string $selector The selector type (css, xpath, named...)
72 * @param mixed $locator It depends on the $selector, can be the xpath, a name, a css locator...
40923977 73 * @param Exception $exception Otherwise we throw exception with generic info
072f67fc 74 * @param NodeElement $node Spins around certain DOM node instead of the whole page
ff48a235
DM
75 * @return NodeElement
76 */
072f67fc 77 protected function find($selector, $locator, $exception = false, $node = false) {
ff48a235 78
f8f1bdc3
DM
79 // Returns the first match.
80 $items = $this->find_all($selector, $locator, $exception, $node);
81 return count($items) ? reset($items) : null;
82 }
83
84 /**
85 * Returns all matching elements.
86 *
87 * Adapter to Behat\Mink\Element\Element::findAll() using the spin() method.
88 *
89 * @link http://mink.behat.org/#traverse-the-page-selectors
90 * @param string $selector The selector type (css, xpath, named...)
91 * @param mixed $locator It depends on the $selector, can be the xpath, a name, a css locator...
92 * @param Exception $exception Otherwise we throw expcetion with generic info
93 * @param NodeElement $node Spins around certain DOM node instead of the whole page
94 * @return array NodeElements list
95 */
96 protected function find_all($selector, $locator, $exception = false, $node = false) {
97
ff48a235
DM
98 // Generic info.
99 if (!$exception) {
100
101 // With named selectors we can be more specific.
102 if ($selector == 'named') {
103 $exceptiontype = $locator[0];
104 $exceptionlocator = $locator[1];
0a7f6a02
DM
105
106 // If we are in a @javascript session all contents would be displayed as HTML characters.
eff79d53 107 if ($this->running_javascript()) {
0a7f6a02
DM
108 $locator[1] = html_entity_decode($locator[1], ENT_NOQUOTES);
109 }
110
ff48a235
DM
111 } else {
112 $exceptiontype = $selector;
113 $exceptionlocator = $locator;
114 }
115
116 $exception = new ElementNotFoundException($this->getSession(), $exceptiontype, null, $exceptionlocator);
117 }
118
072f67fc
DM
119 $params = array('selector' => $selector, 'locator' => $locator);
120 // Pushing $node if required.
121 if ($node) {
122 $params['node'] = $node;
123 }
124
ff48a235
DM
125 // Waits for the node to appear if it exists, otherwise will timeout and throw the provided exception.
126 return $this->spin(
127 function($context, $args) {
072f67fc
DM
128
129 // If no DOM node provided look in all the page.
130 if (empty($args['node'])) {
f8f1bdc3 131 return $context->getSession()->getPage()->findAll($args['selector'], $args['locator']);
072f67fc
DM
132 }
133
134 // For nodes contained in other nodes we can not use the basic named selectors
135 // as they include unions and they would look for matches in the DOM root.
136 $elementxpath = $context->getSession()->getSelectorsHandler()->selectorToXpath($args['selector'], $args['locator']);
137
138 // Split the xpath in unions and prefix them with the container xpath.
139 $unions = explode('|', $elementxpath);
140 foreach ($unions as $key => $union) {
141 $union = trim($union);
142
143 // We are in the container node.
144 if (strpos($union, '.') === 0) {
145 $union = substr($union, 1);
3db1aec5
DM
146 } else if (strpos($union, '/') !== 0) {
147 // Adding the path separator in case it is not there.
148 $union = '/' . $union;
072f67fc
DM
149 }
150 $unions[$key] = $args['node']->getXpath() . $union;
151 }
152
153 // We can not use usual Element::find() as it prefixes with DOM root.
f8f1bdc3 154 return $context->getSession()->getDriver()->find(implode('|', $unions));
ff48a235 155 },
072f67fc 156 $params,
ff48a235
DM
157 self::TIMEOUT,
158 $exception
46ac40cd 159 );
ff48a235
DM
160 }
161
162 /**
163 * Finds DOM nodes in the page using named selectors.
164 *
165 * The point of using this method instead of Mink ones is the spin
166 * method of behat_base::find() that looks for the element until it
167 * is available or it timeouts, this avoids the false failures received
168 * when selenium tries to execute commands on elements that are not
169 * ready to be used.
170 *
171 * All steps that requires elements to be available before interact with
172 * them should use one of the find* methods.
173 *
174 * The methods calls requires a {'find_' . $elementtype}($locator)
175 * format, like find_link($locator), find_select($locator),
176 * find_button($locator)...
177 *
178 * @link http://mink.behat.org/#named-selectors
179 * @throws coding_exception
46ac40cd 180 * @param string $name The name of the called method
ff48a235
DM
181 * @param mixed $arguments
182 * @return NodeElement
183 */
184 public function __call($name, $arguments) {
185
186 if (substr($name, 0, 5) !== 'find_') {
187 throw new coding_exception('The "' . $name . '" method does not exist');
188 }
189
190 // Only the named selector identifier.
191 $cleanname = substr($name, 5);
192
193 // All named selectors shares the interface.
194 if (count($arguments) !== 1) {
195 throw new coding_exception('The "' . $cleanname . '" named selector needs the locator as it\'s single argument');
196 }
197
198 // Redirecting execution to the find method with the specified selector.
199 // It will detect if it's pointing to an unexisting named selector.
200 return $this->find('named',
201 array(
202 $cleanname,
203 $this->getSession()->getSelectorsHandler()->xpathLiteral($arguments[0])
204 )
205 );
206 }
207
49d91129
DM
208 /**
209 * Escapes the double quote character.
210 *
211 * Double quote is the argument delimiter, it can be escaped
212 * with a backslash, but we auto-remove this backslashes
213 * before the step execution, this method is useful when using
214 * arguments as arguments for other steps.
215 *
216 * @param string $string
217 * @return string
218 */
219 public function escape($string) {
220 return str_replace('"', '\"', $string);
221 }
222
786ea937
DM
223 /**
224 * Executes the passed closure until returns true or time outs.
225 *
226 * In most cases the document.readyState === 'complete' will be enough, but sometimes JS
227 * requires more time to be completely loaded or an element to be visible or whatever is required to
228 * perform some action on an element; this method receives a closure which should contain the
229 * required statements to ensure the step definition actions and assertions have all their needs
230 * satisfied and executes it until they are satisfied or it timeouts. Redirects the return of the
231 * closure to the caller.
232 *
233 * The closures requirements to work well with this spin method are:
234 * - Must return false, null or '' if something goes wrong
235 * - Must return something != false if finishes as expected, this will be the (mixed) value
236 * returned by spin()
237 *
ff48a235 238 * The arguments of the closure are mixed, use $args depending on your needs.
786ea937 239 *
ff48a235
DM
240 * You can provide an exception to give more accurate feedback to tests writers, otherwise the
241 * closure exception will be used, but you must provide an exception if the closure does not throws
242 * an exception.
243 *
8e5f86bc
SH
244 * @throws Exception If it timeouts without receiving something != false from the closure
245 * @param Function|array|string $lambda The function to execute or an array passed to call_user_func (maps to a class method)
246 * @param mixed $args Arguments to pass to the closure
247 * @param int $timeout Timeout in seconds
248 * @param Exception $exception The exception to throw in case it time outs.
249 * @param bool $microsleep If set to true it'll sleep micro seconds rather than seconds.
786ea937
DM
250 * @return mixed The value returned by the closure
251 */
8e5f86bc 252 protected function spin($lambda, $args = false, $timeout = false, $exception = false, $microsleep = false) {
786ea937
DM
253
254 // Using default timeout which is pretty high.
255 if (!$timeout) {
256 $timeout = self::TIMEOUT;
257 }
8e5f86bc
SH
258 if ($microsleep) {
259 // Will sleep 1/10th of a second by default for self::TIMEOUT seconds.
260 $loops = $timeout * 10;
261 } else {
262 // Will sleep for self::TIMEOUT seconds.
263 $loops = $timeout;
264 }
786ea937 265
8e5f86bc 266 for ($i = 0; $i < $loops; $i++) {
786ea937
DM
267 // We catch the exception thrown by the step definition to execute it again.
268 try {
786ea937 269 // We don't check with !== because most of the time closures will return
ff48a235
DM
270 // direct Behat methods returns and we are not sure it will be always (bool)false
271 // if it just runs the behat method without returning anything $return == null.
8e5f86bc 272 if ($return = call_user_func($lambda, $this, $args)) {
786ea937
DM
273 return $return;
274 }
46ac40cd 275 } catch (Exception $e) {
ff48a235
DM
276 // We would use the first closure exception if no exception has been provided.
277 if (!$exception) {
278 $exception = $e;
279 }
786ea937
DM
280 // We wait until no exception is thrown or timeout expires.
281 continue;
282 }
283
8e5f86bc
SH
284 if ($microsleep) {
285 usleep(100000);
286 } else {
287 sleep(1);
288 }
786ea937
DM
289 }
290
ff48a235
DM
291 // Using coding_exception as is a development issue if no exception has been provided.
292 if (!$exception) {
8e5f86bc 293 $exception = new coding_exception('spin method requires an exception if the callback does not throw an exception');
ff48a235
DM
294 }
295
786ea937
DM
296 // Throwing exception to the user.
297 throw $exception;
298 }
299
40923977
DM
300 /**
301 * Gets a NodeElement based on the locator and selector type received as argument from steps definitions.
302 *
072f67fc
DM
303 * Use behat_base::get_text_selector_node() for text-based selectors.
304 *
40923977
DM
305 * @throws ElementNotFoundException Thrown by behat_base::find
306 * @param string $selectortype
307 * @param string $element
308 * @return NodeElement
309 */
310 protected function get_selected_node($selectortype, $element) {
311
312 // Getting Mink selector and locator.
313 list($selector, $locator) = $this->transform_selector($selectortype, $element);
314
315 // Returns the NodeElement.
316 return $this->find($selector, $locator);
317 }
318
072f67fc
DM
319 /**
320 * Gets a NodeElement based on the locator and selector type received as argument from steps definitions.
321 *
322 * @throws ElementNotFoundException Thrown by behat_base::find
323 * @param string $selectortype
324 * @param string $element
325 * @return NodeElement
326 */
327 protected function get_text_selector_node($selectortype, $element) {
328
329 // Getting Mink selector and locator.
330 list($selector, $locator) = $this->transform_text_selector($selectortype, $element);
331
332 // Returns the NodeElement.
333 return $this->find($selector, $locator);
334 }
335
336 /**
337 * Gets the requested element inside the specified container.
338 *
339 * @throws ElementNotFoundException Thrown by behat_base::find
340 * @param mixed $selectortype The element selector type.
341 * @param mixed $element The element locator.
342 * @param mixed $containerselectortype The container selector type.
343 * @param mixed $containerelement The container locator.
344 * @return NodeElement
345 */
346 protected function get_node_in_container($selectortype, $element, $containerselectortype, $containerelement) {
347
348 // Gets the container, it will always be text based.
349 $containernode = $this->get_text_selector_node($containerselectortype, $containerelement);
350
351 list($selector, $locator) = $this->transform_selector($selectortype, $element);
352
353 // Specific exception giving info about where can't we find the element.
354 $locatorexceptionmsg = $element . '" in the "' . $containerelement. '" "' . $containerselectortype. '"';
355 $exception = new ElementNotFoundException($this->getSession(), $selectortype, null, $locatorexceptionmsg);
356
357 // Looks for the requested node inside the container node.
358 return $this->find($selector, $locator, $exception, $containernode);
359 }
360
40923977
DM
361 /**
362 * Transforms from step definition's argument style to Mink format.
363 *
364 * Mink has 3 different selectors css, xpath and named, where named
365 * selectors includes link, button, field... to simplify and group multiple
366 * steps in one we use the same interface, considering all link, buttons...
367 * at the same level as css selectors and xpath; this method makes the
368 * conversion from the arguments received by the steps to the selectors and locators
369 * required to interact with Mink.
370 *
371 * @throws ExpectationException
372 * @param string $selectortype It can be css, xpath or any of the named selectors.
373 * @param string $element The locator (or string) we are looking for.
374 * @return array Contains the selector and the locator expected by Mink.
375 */
376 protected function transform_selector($selectortype, $element) {
377
17344d4c
DM
378 // Here we don't know if an allowed text selector is being used.
379 $selectors = behat_selectors::get_allowed_selectors();
380 if (!isset($selectors[$selectortype])) {
40923977
DM
381 throw new ExpectationException('The "' . $selectortype . '" selector type does not exist', $this->getSession());
382 }
383
17344d4c 384 return behat_selectors::get_behat_selector($selectortype, $element, $this->getSession());
40923977
DM
385 }
386
072f67fc
DM
387 /**
388 * Transforms from step definition's argument style to Mink format.
389 *
390 * Delegates all the process to behat_base::transform_selector() checking
391 * the provided $selectortype.
392 *
393 * @throws ExpectationException
394 * @param string $selectortype It can be css, xpath or any of the named selectors.
395 * @param string $element The locator (or string) we are looking for.
396 * @return array Contains the selector and the locator expected by Mink.
397 */
398 protected function transform_text_selector($selectortype, $element) {
399
17344d4c
DM
400 $selectors = behat_selectors::get_allowed_text_selectors();
401 if (empty($selectors[$selectortype])) {
072f67fc
DM
402 throw new ExpectationException('The "' . $selectortype . '" selector can not be used to select text nodes', $this->getSession());
403 }
404
405 return $this->transform_selector($selectortype, $element);
406 }
407
eff79d53
DM
408 /**
409 * Returns whether the scenario is running in a browser that can run Javascript or not.
410 *
411 * @return boolean
412 */
413 protected function running_javascript() {
28abad1a 414 return get_class($this->getSession()->getDriver()) !== 'Behat\Mink\Driver\GoutteDriver';
eff79d53
DM
415 }
416
d4322e38 417}