Merge branch 'wip-MDL-32773-master' of git://github.com/marinaglancy/moodle
[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 *
244 * @throws Exception If it timeouts without receiving something != false from the closure
245 * @param Closure $lambda The function to execute.
246 * @param mixed $args Arguments to pass to the closure
247 * @param int $timeout Timeout
248 * @param Exception $exception The exception to throw in case it time outs.
786ea937
DM
249 * @return mixed The value returned by the closure
250 */
ff48a235 251 protected function spin($lambda, $args = false, $timeout = false, $exception = false) {
786ea937
DM
252
253 // Using default timeout which is pretty high.
254 if (!$timeout) {
255 $timeout = self::TIMEOUT;
256 }
257
258 for ($i = 0; $i < $timeout; $i++) {
259
260 // We catch the exception thrown by the step definition to execute it again.
261 try {
262
263 // We don't check with !== because most of the time closures will return
ff48a235
DM
264 // direct Behat methods returns and we are not sure it will be always (bool)false
265 // if it just runs the behat method without returning anything $return == null.
786ea937
DM
266 if ($return = $lambda($this, $args)) {
267 return $return;
268 }
46ac40cd 269 } catch (Exception $e) {
ff48a235
DM
270
271 // We would use the first closure exception if no exception has been provided.
272 if (!$exception) {
273 $exception = $e;
274 }
275
786ea937
DM
276 // We wait until no exception is thrown or timeout expires.
277 continue;
278 }
279
280 sleep(1);
281 }
282
ff48a235
DM
283 // Using coding_exception as is a development issue if no exception has been provided.
284 if (!$exception) {
285 $exception = new coding_exception('spin method requires an exception if the closure doesn\'t throw an exception itself');
286 }
287
786ea937
DM
288 // Throwing exception to the user.
289 throw $exception;
290 }
291
40923977
DM
292 /**
293 * Gets a NodeElement based on the locator and selector type received as argument from steps definitions.
294 *
072f67fc
DM
295 * Use behat_base::get_text_selector_node() for text-based selectors.
296 *
40923977
DM
297 * @throws ElementNotFoundException Thrown by behat_base::find
298 * @param string $selectortype
299 * @param string $element
300 * @return NodeElement
301 */
302 protected function get_selected_node($selectortype, $element) {
303
304 // Getting Mink selector and locator.
305 list($selector, $locator) = $this->transform_selector($selectortype, $element);
306
307 // Returns the NodeElement.
308 return $this->find($selector, $locator);
309 }
310
072f67fc
DM
311 /**
312 * Gets a NodeElement based on the locator and selector type received as argument from steps definitions.
313 *
314 * @throws ElementNotFoundException Thrown by behat_base::find
315 * @param string $selectortype
316 * @param string $element
317 * @return NodeElement
318 */
319 protected function get_text_selector_node($selectortype, $element) {
320
321 // Getting Mink selector and locator.
322 list($selector, $locator) = $this->transform_text_selector($selectortype, $element);
323
324 // Returns the NodeElement.
325 return $this->find($selector, $locator);
326 }
327
328 /**
329 * Gets the requested element inside the specified container.
330 *
331 * @throws ElementNotFoundException Thrown by behat_base::find
332 * @param mixed $selectortype The element selector type.
333 * @param mixed $element The element locator.
334 * @param mixed $containerselectortype The container selector type.
335 * @param mixed $containerelement The container locator.
336 * @return NodeElement
337 */
338 protected function get_node_in_container($selectortype, $element, $containerselectortype, $containerelement) {
339
340 // Gets the container, it will always be text based.
341 $containernode = $this->get_text_selector_node($containerselectortype, $containerelement);
342
343 list($selector, $locator) = $this->transform_selector($selectortype, $element);
344
345 // Specific exception giving info about where can't we find the element.
346 $locatorexceptionmsg = $element . '" in the "' . $containerelement. '" "' . $containerselectortype. '"';
347 $exception = new ElementNotFoundException($this->getSession(), $selectortype, null, $locatorexceptionmsg);
348
349 // Looks for the requested node inside the container node.
350 return $this->find($selector, $locator, $exception, $containernode);
351 }
352
40923977
DM
353 /**
354 * Transforms from step definition's argument style to Mink format.
355 *
356 * Mink has 3 different selectors css, xpath and named, where named
357 * selectors includes link, button, field... to simplify and group multiple
358 * steps in one we use the same interface, considering all link, buttons...
359 * at the same level as css selectors and xpath; this method makes the
360 * conversion from the arguments received by the steps to the selectors and locators
361 * required to interact with Mink.
362 *
363 * @throws ExpectationException
364 * @param string $selectortype It can be css, xpath or any of the named selectors.
365 * @param string $element The locator (or string) we are looking for.
366 * @return array Contains the selector and the locator expected by Mink.
367 */
368 protected function transform_selector($selectortype, $element) {
369
17344d4c
DM
370 // Here we don't know if an allowed text selector is being used.
371 $selectors = behat_selectors::get_allowed_selectors();
372 if (!isset($selectors[$selectortype])) {
40923977
DM
373 throw new ExpectationException('The "' . $selectortype . '" selector type does not exist', $this->getSession());
374 }
375
17344d4c 376 return behat_selectors::get_behat_selector($selectortype, $element, $this->getSession());
40923977
DM
377 }
378
072f67fc
DM
379 /**
380 * Transforms from step definition's argument style to Mink format.
381 *
382 * Delegates all the process to behat_base::transform_selector() checking
383 * the provided $selectortype.
384 *
385 * @throws ExpectationException
386 * @param string $selectortype It can be css, xpath or any of the named selectors.
387 * @param string $element The locator (or string) we are looking for.
388 * @return array Contains the selector and the locator expected by Mink.
389 */
390 protected function transform_text_selector($selectortype, $element) {
391
17344d4c
DM
392 $selectors = behat_selectors::get_allowed_text_selectors();
393 if (empty($selectors[$selectortype])) {
072f67fc
DM
394 throw new ExpectationException('The "' . $selectortype . '" selector can not be used to select text nodes', $this->getSession());
395 }
396
397 return $this->transform_selector($selectortype, $element);
398 }
399
eff79d53
DM
400 /**
401 * Returns whether the scenario is running in a browser that can run Javascript or not.
402 *
403 * @return boolean
404 */
405 protected function running_javascript() {
28abad1a 406 return get_class($this->getSession()->getDriver()) !== 'Behat\Mink\Driver\GoutteDriver';
eff79d53
DM
407 }
408
d4322e38 409}