MDL-38025 behat: Replacing selector-based steps by human-friendly options
[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 */
62 protected function locatePath($path) {
63 $startUrl = rtrim($this->getMinkParameter('base_url'), '/') . '/';
64 return 0 !== strpos($path, 'http') ? $startUrl . ltrim($path, '/') : $path;
65 }
66
ff48a235
DM
67 /**
68 * Adapter to Behat\Mink\Element\Element::find() using the spin() method.
69 *
70 * @link http://mink.behat.org/#traverse-the-page-selectors
71 * @param Exception $exception Otherwise we throw expcetion with generic info
72 * @param string $selector The selector type (css, xpath, named...)
73 * @param mixed $locator It depends on the $selector, can be the xpath, a name, a css locator...
74 * @return NodeElement
75 */
76 protected function find($selector, $locator, $exception = false) {
77
78 // Generic info.
79 if (!$exception) {
80
81 // With named selectors we can be more specific.
82 if ($selector == 'named') {
83 $exceptiontype = $locator[0];
84 $exceptionlocator = $locator[1];
85 } else {
86 $exceptiontype = $selector;
87 $exceptionlocator = $locator;
88 }
89
90 $exception = new ElementNotFoundException($this->getSession(), $exceptiontype, null, $exceptionlocator);
91 }
92
93 // Waits for the node to appear if it exists, otherwise will timeout and throw the provided exception.
94 return $this->spin(
95 function($context, $args) {
96 return $context->getSession()->getPage()->find($args[0], $args[1]);
97 },
98 array($selector, $locator),
99 self::TIMEOUT,
100 $exception
101 );
102 }
103
104 /**
105 * Finds DOM nodes in the page using named selectors.
106 *
107 * The point of using this method instead of Mink ones is the spin
108 * method of behat_base::find() that looks for the element until it
109 * is available or it timeouts, this avoids the false failures received
110 * when selenium tries to execute commands on elements that are not
111 * ready to be used.
112 *
113 * All steps that requires elements to be available before interact with
114 * them should use one of the find* methods.
115 *
116 * The methods calls requires a {'find_' . $elementtype}($locator)
117 * format, like find_link($locator), find_select($locator),
118 * find_button($locator)...
119 *
120 * @link http://mink.behat.org/#named-selectors
121 * @throws coding_exception
122 * @param string $method The name of the called method
123 * @param mixed $arguments
124 * @return NodeElement
125 */
126 public function __call($name, $arguments) {
127
128 if (substr($name, 0, 5) !== 'find_') {
129 throw new coding_exception('The "' . $name . '" method does not exist');
130 }
131
132 // Only the named selector identifier.
133 $cleanname = substr($name, 5);
134
135 // All named selectors shares the interface.
136 if (count($arguments) !== 1) {
137 throw new coding_exception('The "' . $cleanname . '" named selector needs the locator as it\'s single argument');
138 }
139
140 // Redirecting execution to the find method with the specified selector.
141 // It will detect if it's pointing to an unexisting named selector.
142 return $this->find('named',
143 array(
144 $cleanname,
145 $this->getSession()->getSelectorsHandler()->xpathLiteral($arguments[0])
146 )
147 );
148 }
149
786ea937
DM
150 /**
151 * Executes the passed closure until returns true or time outs.
152 *
153 * In most cases the document.readyState === 'complete' will be enough, but sometimes JS
154 * requires more time to be completely loaded or an element to be visible or whatever is required to
155 * perform some action on an element; this method receives a closure which should contain the
156 * required statements to ensure the step definition actions and assertions have all their needs
157 * satisfied and executes it until they are satisfied or it timeouts. Redirects the return of the
158 * closure to the caller.
159 *
160 * The closures requirements to work well with this spin method are:
161 * - Must return false, null or '' if something goes wrong
162 * - Must return something != false if finishes as expected, this will be the (mixed) value
163 * returned by spin()
164 *
ff48a235 165 * The arguments of the closure are mixed, use $args depending on your needs.
786ea937 166 *
ff48a235
DM
167 * You can provide an exception to give more accurate feedback to tests writers, otherwise the
168 * closure exception will be used, but you must provide an exception if the closure does not throws
169 * an exception.
170 *
171 * @throws Exception If it timeouts without receiving something != false from the closure
172 * @param Closure $lambda The function to execute.
173 * @param mixed $args Arguments to pass to the closure
174 * @param int $timeout Timeout
175 * @param Exception $exception The exception to throw in case it time outs.
786ea937
DM
176 * @return mixed The value returned by the closure
177 */
ff48a235 178 protected function spin($lambda, $args = false, $timeout = false, $exception = false) {
786ea937
DM
179
180 // Using default timeout which is pretty high.
181 if (!$timeout) {
182 $timeout = self::TIMEOUT;
183 }
184
185 for ($i = 0; $i < $timeout; $i++) {
186
187 // We catch the exception thrown by the step definition to execute it again.
188 try {
189
190 // We don't check with !== because most of the time closures will return
ff48a235
DM
191 // direct Behat methods returns and we are not sure it will be always (bool)false
192 // if it just runs the behat method without returning anything $return == null.
786ea937
DM
193 if ($return = $lambda($this, $args)) {
194 return $return;
195 }
196 } catch(Exception $e) {
ff48a235
DM
197
198 // We would use the first closure exception if no exception has been provided.
199 if (!$exception) {
200 $exception = $e;
201 }
202
786ea937
DM
203 // We wait until no exception is thrown or timeout expires.
204 continue;
205 }
206
207 sleep(1);
208 }
209
ff48a235
DM
210 // Using coding_exception as is a development issue if no exception has been provided.
211 if (!$exception) {
212 $exception = new coding_exception('spin method requires an exception if the closure doesn\'t throw an exception itself');
213 }
214
786ea937
DM
215 // Throwing exception to the user.
216 throw $exception;
217 }
218
d4322e38 219}