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