weekly release 2.7dev
[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 */
845ceaff 58 const TIMEOUT = 6;
d1e55a47
DM
59
60 /**
61 * And extended timeout for specific cases.
62 */
63 const EXTENDED_TIMEOUT = 10;
64
d1e55a47
DM
65 /**
66 * The JS code to check that the page is ready.
67 */
68 const PAGE_READY_JS = '(M && M.util && M.util.pending_js && !Boolean(M.util.pending_js.length)) && (document.readyState === "complete")';
d4322e38 69
786ea937
DM
70 /**
71 * Locates url, based on provided path.
72 * Override to provide custom routing mechanism.
73 *
74 * @see Behat\MinkExtension\Context\MinkContext
75 * @param string $path
76 * @return string
77 */
40923977 78 protected function locate_path($path) {
46ac40cd
DM
79 $starturl = rtrim($this->getMinkParameter('base_url'), '/') . '/';
80 return 0 !== strpos($path, 'http') ? $starturl . ltrim($path, '/') : $path;
786ea937
DM
81 }
82
ff48a235 83 /**
f8f1bdc3 84 * Returns the first matching element.
ff48a235
DM
85 *
86 * @link http://mink.behat.org/#traverse-the-page-selectors
ff48a235
DM
87 * @param string $selector The selector type (css, xpath, named...)
88 * @param mixed $locator It depends on the $selector, can be the xpath, a name, a css locator...
40923977 89 * @param Exception $exception Otherwise we throw exception with generic info
072f67fc 90 * @param NodeElement $node Spins around certain DOM node instead of the whole page
ff48a235
DM
91 * @return NodeElement
92 */
072f67fc 93 protected function find($selector, $locator, $exception = false, $node = false) {
ff48a235 94
f8f1bdc3
DM
95 // Returns the first match.
96 $items = $this->find_all($selector, $locator, $exception, $node);
97 return count($items) ? reset($items) : null;
98 }
99
100 /**
101 * Returns all matching elements.
102 *
103 * Adapter to Behat\Mink\Element\Element::findAll() using the spin() method.
104 *
105 * @link http://mink.behat.org/#traverse-the-page-selectors
106 * @param string $selector The selector type (css, xpath, named...)
107 * @param mixed $locator It depends on the $selector, can be the xpath, a name, a css locator...
108 * @param Exception $exception Otherwise we throw expcetion with generic info
109 * @param NodeElement $node Spins around certain DOM node instead of the whole page
110 * @return array NodeElements list
111 */
112 protected function find_all($selector, $locator, $exception = false, $node = false) {
113
ff48a235
DM
114 // Generic info.
115 if (!$exception) {
116
117 // With named selectors we can be more specific.
118 if ($selector == 'named') {
119 $exceptiontype = $locator[0];
120 $exceptionlocator = $locator[1];
0a7f6a02
DM
121
122 // If we are in a @javascript session all contents would be displayed as HTML characters.
eff79d53 123 if ($this->running_javascript()) {
0a7f6a02
DM
124 $locator[1] = html_entity_decode($locator[1], ENT_NOQUOTES);
125 }
126
ff48a235
DM
127 } else {
128 $exceptiontype = $selector;
129 $exceptionlocator = $locator;
130 }
131
132 $exception = new ElementNotFoundException($this->getSession(), $exceptiontype, null, $exceptionlocator);
133 }
134
072f67fc
DM
135 $params = array('selector' => $selector, 'locator' => $locator);
136 // Pushing $node if required.
137 if ($node) {
138 $params['node'] = $node;
139 }
140
ff48a235
DM
141 // Waits for the node to appear if it exists, otherwise will timeout and throw the provided exception.
142 return $this->spin(
143 function($context, $args) {
072f67fc
DM
144
145 // If no DOM node provided look in all the page.
146 if (empty($args['node'])) {
f8f1bdc3 147 return $context->getSession()->getPage()->findAll($args['selector'], $args['locator']);
072f67fc
DM
148 }
149
150 // For nodes contained in other nodes we can not use the basic named selectors
151 // as they include unions and they would look for matches in the DOM root.
152 $elementxpath = $context->getSession()->getSelectorsHandler()->selectorToXpath($args['selector'], $args['locator']);
153
154 // Split the xpath in unions and prefix them with the container xpath.
155 $unions = explode('|', $elementxpath);
156 foreach ($unions as $key => $union) {
157 $union = trim($union);
158
159 // We are in the container node.
160 if (strpos($union, '.') === 0) {
161 $union = substr($union, 1);
3db1aec5
DM
162 } else if (strpos($union, '/') !== 0) {
163 // Adding the path separator in case it is not there.
164 $union = '/' . $union;
072f67fc
DM
165 }
166 $unions[$key] = $args['node']->getXpath() . $union;
167 }
168
169 // We can not use usual Element::find() as it prefixes with DOM root.
f8f1bdc3 170 return $context->getSession()->getDriver()->find(implode('|', $unions));
ff48a235 171 },
072f67fc 172 $params,
ff48a235
DM
173 self::TIMEOUT,
174 $exception
46ac40cd 175 );
ff48a235
DM
176 }
177
178 /**
179 * Finds DOM nodes in the page using named selectors.
180 *
181 * The point of using this method instead of Mink ones is the spin
182 * method of behat_base::find() that looks for the element until it
183 * is available or it timeouts, this avoids the false failures received
184 * when selenium tries to execute commands on elements that are not
185 * ready to be used.
186 *
187 * All steps that requires elements to be available before interact with
188 * them should use one of the find* methods.
189 *
190 * The methods calls requires a {'find_' . $elementtype}($locator)
191 * format, like find_link($locator), find_select($locator),
192 * find_button($locator)...
193 *
194 * @link http://mink.behat.org/#named-selectors
195 * @throws coding_exception
46ac40cd 196 * @param string $name The name of the called method
ff48a235
DM
197 * @param mixed $arguments
198 * @return NodeElement
199 */
200 public function __call($name, $arguments) {
201
202 if (substr($name, 0, 5) !== 'find_') {
203 throw new coding_exception('The "' . $name . '" method does not exist');
204 }
205
206 // Only the named selector identifier.
207 $cleanname = substr($name, 5);
208
209 // All named selectors shares the interface.
210 if (count($arguments) !== 1) {
211 throw new coding_exception('The "' . $cleanname . '" named selector needs the locator as it\'s single argument');
212 }
213
214 // Redirecting execution to the find method with the specified selector.
215 // It will detect if it's pointing to an unexisting named selector.
216 return $this->find('named',
217 array(
218 $cleanname,
219 $this->getSession()->getSelectorsHandler()->xpathLiteral($arguments[0])
220 )
221 );
222 }
223
49d91129
DM
224 /**
225 * Escapes the double quote character.
226 *
227 * Double quote is the argument delimiter, it can be escaped
228 * with a backslash, but we auto-remove this backslashes
229 * before the step execution, this method is useful when using
230 * arguments as arguments for other steps.
231 *
232 * @param string $string
233 * @return string
234 */
235 public function escape($string) {
236 return str_replace('"', '\"', $string);
237 }
238
786ea937
DM
239 /**
240 * Executes the passed closure until returns true or time outs.
241 *
242 * In most cases the document.readyState === 'complete' will be enough, but sometimes JS
243 * requires more time to be completely loaded or an element to be visible or whatever is required to
244 * perform some action on an element; this method receives a closure which should contain the
245 * required statements to ensure the step definition actions and assertions have all their needs
246 * satisfied and executes it until they are satisfied or it timeouts. Redirects the return of the
247 * closure to the caller.
248 *
249 * The closures requirements to work well with this spin method are:
250 * - Must return false, null or '' if something goes wrong
251 * - Must return something != false if finishes as expected, this will be the (mixed) value
252 * returned by spin()
253 *
ff48a235 254 * The arguments of the closure are mixed, use $args depending on your needs.
786ea937 255 *
ff48a235
DM
256 * You can provide an exception to give more accurate feedback to tests writers, otherwise the
257 * closure exception will be used, but you must provide an exception if the closure does not throws
258 * an exception.
259 *
8e5f86bc
SH
260 * @throws Exception If it timeouts without receiving something != false from the closure
261 * @param Function|array|string $lambda The function to execute or an array passed to call_user_func (maps to a class method)
262 * @param mixed $args Arguments to pass to the closure
263 * @param int $timeout Timeout in seconds
264 * @param Exception $exception The exception to throw in case it time outs.
265 * @param bool $microsleep If set to true it'll sleep micro seconds rather than seconds.
786ea937
DM
266 * @return mixed The value returned by the closure
267 */
8e5f86bc 268 protected function spin($lambda, $args = false, $timeout = false, $exception = false, $microsleep = false) {
786ea937
DM
269
270 // Using default timeout which is pretty high.
271 if (!$timeout) {
272 $timeout = self::TIMEOUT;
273 }
8e5f86bc
SH
274 if ($microsleep) {
275 // Will sleep 1/10th of a second by default for self::TIMEOUT seconds.
276 $loops = $timeout * 10;
277 } else {
278 // Will sleep for self::TIMEOUT seconds.
279 $loops = $timeout;
280 }
786ea937 281
8e5f86bc 282 for ($i = 0; $i < $loops; $i++) {
786ea937
DM
283 // We catch the exception thrown by the step definition to execute it again.
284 try {
786ea937 285 // We don't check with !== because most of the time closures will return
ff48a235
DM
286 // direct Behat methods returns and we are not sure it will be always (bool)false
287 // if it just runs the behat method without returning anything $return == null.
8e5f86bc 288 if ($return = call_user_func($lambda, $this, $args)) {
786ea937
DM
289 return $return;
290 }
46ac40cd 291 } catch (Exception $e) {
ff48a235
DM
292 // We would use the first closure exception if no exception has been provided.
293 if (!$exception) {
294 $exception = $e;
295 }
786ea937
DM
296 // We wait until no exception is thrown or timeout expires.
297 continue;
298 }
299
8e5f86bc
SH
300 if ($microsleep) {
301 usleep(100000);
302 } else {
303 sleep(1);
304 }
786ea937
DM
305 }
306
ff48a235
DM
307 // Using coding_exception as is a development issue if no exception has been provided.
308 if (!$exception) {
8e5f86bc 309 $exception = new coding_exception('spin method requires an exception if the callback does not throw an exception');
ff48a235
DM
310 }
311
786ea937
DM
312 // Throwing exception to the user.
313 throw $exception;
314 }
315
40923977
DM
316 /**
317 * Gets a NodeElement based on the locator and selector type received as argument from steps definitions.
318 *
072f67fc
DM
319 * Use behat_base::get_text_selector_node() for text-based selectors.
320 *
40923977
DM
321 * @throws ElementNotFoundException Thrown by behat_base::find
322 * @param string $selectortype
323 * @param string $element
324 * @return NodeElement
325 */
326 protected function get_selected_node($selectortype, $element) {
327
328 // Getting Mink selector and locator.
329 list($selector, $locator) = $this->transform_selector($selectortype, $element);
330
331 // Returns the NodeElement.
332 return $this->find($selector, $locator);
333 }
334
072f67fc
DM
335 /**
336 * Gets a NodeElement based on the locator and selector type received as argument from steps definitions.
337 *
338 * @throws ElementNotFoundException Thrown by behat_base::find
339 * @param string $selectortype
340 * @param string $element
341 * @return NodeElement
342 */
343 protected function get_text_selector_node($selectortype, $element) {
344
345 // Getting Mink selector and locator.
346 list($selector, $locator) = $this->transform_text_selector($selectortype, $element);
347
348 // Returns the NodeElement.
349 return $this->find($selector, $locator);
350 }
351
352 /**
353 * Gets the requested element inside the specified container.
354 *
355 * @throws ElementNotFoundException Thrown by behat_base::find
356 * @param mixed $selectortype The element selector type.
357 * @param mixed $element The element locator.
358 * @param mixed $containerselectortype The container selector type.
359 * @param mixed $containerelement The container locator.
360 * @return NodeElement
361 */
362 protected function get_node_in_container($selectortype, $element, $containerselectortype, $containerelement) {
363
364 // Gets the container, it will always be text based.
365 $containernode = $this->get_text_selector_node($containerselectortype, $containerelement);
366
367 list($selector, $locator) = $this->transform_selector($selectortype, $element);
368
369 // Specific exception giving info about where can't we find the element.
370 $locatorexceptionmsg = $element . '" in the "' . $containerelement. '" "' . $containerselectortype. '"';
371 $exception = new ElementNotFoundException($this->getSession(), $selectortype, null, $locatorexceptionmsg);
372
373 // Looks for the requested node inside the container node.
374 return $this->find($selector, $locator, $exception, $containernode);
375 }
376
40923977
DM
377 /**
378 * Transforms from step definition's argument style to Mink format.
379 *
380 * Mink has 3 different selectors css, xpath and named, where named
381 * selectors includes link, button, field... to simplify and group multiple
382 * steps in one we use the same interface, considering all link, buttons...
383 * at the same level as css selectors and xpath; this method makes the
384 * conversion from the arguments received by the steps to the selectors and locators
385 * required to interact with Mink.
386 *
387 * @throws ExpectationException
388 * @param string $selectortype It can be css, xpath or any of the named selectors.
389 * @param string $element The locator (or string) we are looking for.
390 * @return array Contains the selector and the locator expected by Mink.
391 */
392 protected function transform_selector($selectortype, $element) {
393
17344d4c
DM
394 // Here we don't know if an allowed text selector is being used.
395 $selectors = behat_selectors::get_allowed_selectors();
396 if (!isset($selectors[$selectortype])) {
40923977
DM
397 throw new ExpectationException('The "' . $selectortype . '" selector type does not exist', $this->getSession());
398 }
399
17344d4c 400 return behat_selectors::get_behat_selector($selectortype, $element, $this->getSession());
40923977
DM
401 }
402
072f67fc
DM
403 /**
404 * Transforms from step definition's argument style to Mink format.
405 *
406 * Delegates all the process to behat_base::transform_selector() checking
407 * the provided $selectortype.
408 *
409 * @throws ExpectationException
410 * @param string $selectortype It can be css, xpath or any of the named selectors.
411 * @param string $element The locator (or string) we are looking for.
412 * @return array Contains the selector and the locator expected by Mink.
413 */
414 protected function transform_text_selector($selectortype, $element) {
415
17344d4c
DM
416 $selectors = behat_selectors::get_allowed_text_selectors();
417 if (empty($selectors[$selectortype])) {
072f67fc
DM
418 throw new ExpectationException('The "' . $selectortype . '" selector can not be used to select text nodes', $this->getSession());
419 }
420
421 return $this->transform_selector($selectortype, $element);
422 }
423
eff79d53
DM
424 /**
425 * Returns whether the scenario is running in a browser that can run Javascript or not.
426 *
427 * @return boolean
428 */
429 protected function running_javascript() {
28abad1a 430 return get_class($this->getSession()->getDriver()) !== 'Behat\Mink\Driver\GoutteDriver';
eff79d53
DM
431 }
432
d1e55a47
DM
433 /**
434 * Spins around an element until it exists
435 *
436 * @throws ExpectationException
437 * @param string $element
438 * @param string $selectortype
439 * @return void
440 */
441 protected function ensure_element_exists($element, $selectortype) {
442
443 // Getting the behat selector & locator.
444 list($selector, $locator) = $this->transform_selector($selectortype, $element);
445
446 // Exception if it timesout and the element is still there.
c1faf86b 447 $msg = 'The "' . $element . '" element does not exist and should exist';
d1e55a47
DM
448 $exception = new ExpectationException($msg, $this->getSession());
449
c1faf86b 450 // It will stop spinning once the find() method returns true.
d1e55a47
DM
451 $this->spin(
452 function($context, $args) {
453 // We don't use behat_base::find as it is already spinning.
454 if ($context->getSession()->getPage()->find($args['selector'], $args['locator'])) {
455 return true;
456 }
c1faf86b 457 return false;
d1e55a47
DM
458 },
459 array('selector' => $selector, 'locator' => $locator),
460 self::EXTENDED_TIMEOUT,
461 $exception,
462 true
463 );
464
465 }
466
467 /**
468 * Spins until the element does not exist
469 *
470 * @throws ExpectationException
471 * @param string $element
472 * @param string $selectortype
473 * @return void
474 */
475 protected function ensure_element_does_not_exist($element, $selectortype) {
476
477 // Getting the behat selector & locator.
478 list($selector, $locator) = $this->transform_selector($selectortype, $element);
479
480 // Exception if it timesout and the element is still there.
c1faf86b 481 $msg = 'The "' . $element . '" element exists and should not exist';
d1e55a47
DM
482 $exception = new ExpectationException($msg, $this->getSession());
483
c1faf86b 484 // It will stop spinning once the find() method returns false.
d1e55a47
DM
485 $this->spin(
486 function($context, $args) {
c1faf86b 487 // We don't use behat_base::find() as we are already spinning.
d1e55a47
DM
488 if (!$context->getSession()->getPage()->find($args['selector'], $args['locator'])) {
489 return true;
490 }
c1faf86b 491 return false;
d1e55a47
DM
492 },
493 array('selector' => $selector, 'locator' => $locator),
494 self::EXTENDED_TIMEOUT,
495 $exception,
496 true
497 );
498 }
499
500 /**
501 * Ensures that the provided node is visible and we can interact with it.
502 *
503 * @throws ExpectationException
504 * @param NodeElement $node
505 * @return void Throws an exception if it times out without the element being visible
506 */
507 protected function ensure_node_is_visible($node) {
508
509 if (!$this->running_javascript()) {
510 return;
511 }
512
513 // Exception if it timesout and the element is still there.
c1faf86b 514 $msg = 'The "' . $node->getXPath() . '" xpath node is not visible and it should be visible';
d1e55a47
DM
515 $exception = new ExpectationException($msg, $this->getSession());
516
c1faf86b 517 // It will stop spinning once the isVisible() method returns true.
d1e55a47
DM
518 $this->spin(
519 function($context, $args) {
520 if ($args->isVisible()) {
521 return true;
522 }
c1faf86b 523 return false;
d1e55a47
DM
524 },
525 $node,
526 self::EXTENDED_TIMEOUT,
527 $exception,
528 true
529 );
530 }
531
532 /**
533 * Ensures that the provided element is visible and we can interact with it.
534 *
535 * Returns the node in case other actions are interested in using it.
536 *
537 * @throws ExpectationException
538 * @param string $element
539 * @param string $selectortype
540 * @return NodeElement Throws an exception if it times out without being visible
541 */
542 protected function ensure_element_is_visible($element, $selectortype) {
543
544 if (!$this->running_javascript()) {
545 return;
546 }
547
548 $node = $this->get_selected_node($selectortype, $element);
549 $this->ensure_node_is_visible($node);
550
551 return $node;
552 }
553
554 /**
555 * Ensures that all the page's editors are loaded.
556 *
557 * This method is expensive as it waits for .mceEditor CSS
558 * so use with caution and only where there will be editors.
559 *
560 * @throws ElementNotFoundException
c1faf86b 561 * @throws ExpectationException
d1e55a47
DM
562 * @return void
563 */
564 protected function ensure_editors_are_loaded() {
565
566 if (!$this->running_javascript()) {
567 return;
568 }
569
d1e55a47 570 // If there are no editors we don't need to wait.
d1e55a47
DM
571 try {
572 $this->find('css', '.mceEditor');
573 } catch (ElementNotFoundException $e) {
574 return;
575 }
576
c1faf86b
DM
577 // Exception if it timesout and the element is not appearing.
578 $msg = 'The editors are not completely loaded';
579 $exception = new ExpectationException($msg, $this->getSession());
d1e55a47 580
c1faf86b
DM
581 // Here we know that there are .mceEditor editors in the page and we will
582 // probably need to interact with them, if we use tinyMCE JS var before
583 // it exists it will throw an exception and we want to catch it until all
584 // the page's editors are ready to interact with them.
585 $this->spin(
586 function($context) {
d1e55a47
DM
587
588 // It may return 0 if tinyMCE is loaded but not the instances, so we just loop again.
c1faf86b
DM
589 $neditors = $context->getSession()->evaluateScript('return tinyMCE.editors.length;');
590 if ($neditors == 0) {
591 return false;
d1e55a47
DM
592 }
593
c1faf86b
DM
594 // It may be there but not ready.
595 $iframeready = $context->getSession()->evaluateScript('
596 var readyeditors = new Array;
597 for (editorid in tinyMCE.editors) {
598 if (tinyMCE.editors[editorid].getDoc().readyState === "complete") {
599 readyeditors[editorid] = editorid;
600 }
601 }
602 if (tinyMCE.editors.length === readyeditors.length) {
603 return "complete";
604 }
605 return "";
606 ');
d1e55a47 607
c1faf86b
DM
608 // Now we know that the editors are there.
609 if ($iframeready) {
610 return true;
611 }
d1e55a47 612
c1faf86b
DM
613 // Loop again if it is not ready.
614 return false;
615 },
616 false,
617 self::EXTENDED_TIMEOUT,
618 $exception,
619 true
620 );
d1e55a47 621 }
c1faf86b 622
d4322e38 623}