MDL-63185 mod_quiz: convert responses report behat to use new step
[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
b095b36c
MN
31use Behat\Mink\Exception\DriverException,
32 Behat\Mink\Exception\ExpectationException as ExpectationException,
fcb6ed47
MG
33 Behat\Mink\Exception\ElementNotFoundException as ElementNotFoundException,
34 Behat\Mink\Element\NodeElement as NodeElement;
ff48a235 35
d4322e38
DM
36/**
37 * Steps definitions base class.
38 *
39 * To extend by the steps definitions of the different Moodle components.
40 *
41 * It can not contain steps definitions to avoid duplicates, only utility
42 * methods shared between steps.
43 *
fcb6ed47
MG
44 * @method NodeElement find_field(string $locator) Finds a form element
45 * @method NodeElement find_button(string $locator) Finds a form input submit element or a button
46 * @method NodeElement find_link(string $locator) Finds a link on a page
47 * @method NodeElement find_file(string $locator) Finds a forum input file element
48 *
d4322e38
DM
49 * @package core
50 * @category test
51 * @copyright 2012 David MonllaĆ³
52 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
53 */
54class behat_base extends Behat\MinkExtension\Context\RawMinkContext {
55
74c78e74
DM
56 /**
57 * Small timeout.
58 *
59 * A reduced timeout for cases where self::TIMEOUT is too much
60 * and a simple $this->getSession()->getPage()->find() could not
61 * be enough.
62 */
63 const REDUCED_TIMEOUT = 2;
64
d4322e38
DM
65 /**
66 * The timeout for each Behat step (load page, wait for an element to load...).
67 */
845ceaff 68 const TIMEOUT = 6;
d1e55a47
DM
69
70 /**
71 * And extended timeout for specific cases.
72 */
73 const EXTENDED_TIMEOUT = 10;
74
d1e55a47
DM
75 /**
76 * The JS code to check that the page is ready.
77 */
41f4dabe 78 const PAGE_READY_JS = '(typeof M !== "undefined" && M.util && M.util.pending_js && !Boolean(M.util.pending_js.length)) && (document.readyState === "complete")';
d4322e38 79
786ea937
DM
80 /**
81 * Locates url, based on provided path.
82 * Override to provide custom routing mechanism.
83 *
84 * @see Behat\MinkExtension\Context\MinkContext
85 * @param string $path
86 * @return string
87 */
40923977 88 protected function locate_path($path) {
46ac40cd
DM
89 $starturl = rtrim($this->getMinkParameter('base_url'), '/') . '/';
90 return 0 !== strpos($path, 'http') ? $starturl . ltrim($path, '/') : $path;
786ea937
DM
91 }
92
ff48a235 93 /**
f8f1bdc3 94 * Returns the first matching element.
ff48a235
DM
95 *
96 * @link http://mink.behat.org/#traverse-the-page-selectors
ff48a235
DM
97 * @param string $selector The selector type (css, xpath, named...)
98 * @param mixed $locator It depends on the $selector, can be the xpath, a name, a css locator...
40923977 99 * @param Exception $exception Otherwise we throw exception with generic info
072f67fc 100 * @param NodeElement $node Spins around certain DOM node instead of the whole page
74c78e74 101 * @param int $timeout Forces a specific time out (in seconds).
ff48a235
DM
102 * @return NodeElement
103 */
74c78e74 104 protected function find($selector, $locator, $exception = false, $node = false, $timeout = false) {
ff48a235 105
42ad096f
RT
106 // Throw exception, so dev knows it is not supported.
107 if ($selector === 'named') {
108 $exception = 'Using the "named" selector is deprecated as of 3.1. '
109 .' Use the "named_partial" or use the "named_exact" selector instead.';
110 throw new ExpectationException($exception, $this->getSession());
111 }
112
f8f1bdc3 113 // Returns the first match.
74c78e74 114 $items = $this->find_all($selector, $locator, $exception, $node, $timeout);
f8f1bdc3
DM
115 return count($items) ? reset($items) : null;
116 }
117
118 /**
119 * Returns all matching elements.
120 *
121 * Adapter to Behat\Mink\Element\Element::findAll() using the spin() method.
122 *
123 * @link http://mink.behat.org/#traverse-the-page-selectors
124 * @param string $selector The selector type (css, xpath, named...)
125 * @param mixed $locator It depends on the $selector, can be the xpath, a name, a css locator...
126 * @param Exception $exception Otherwise we throw expcetion with generic info
127 * @param NodeElement $node Spins around certain DOM node instead of the whole page
74c78e74 128 * @param int $timeout Forces a specific time out (in seconds). If 0 is provided the default timeout will be applied.
f8f1bdc3
DM
129 * @return array NodeElements list
130 */
74c78e74 131 protected function find_all($selector, $locator, $exception = false, $node = false, $timeout = false) {
f8f1bdc3 132
42ad096f
RT
133 // Throw exception, so dev knows it is not supported.
134 if ($selector === 'named') {
135 $exception = 'Using the "named" selector is deprecated as of 3.1. '
136 .' Use the "named_partial" or use the "named_exact" selector instead.';
137 throw new ExpectationException($exception, $this->getSession());
138 }
139
ff48a235
DM
140 // Generic info.
141 if (!$exception) {
142
143 // With named selectors we can be more specific.
07298309 144 if (($selector == 'named_exact') || ($selector == 'named_partial')) {
ff48a235
DM
145 $exceptiontype = $locator[0];
146 $exceptionlocator = $locator[1];
0a7f6a02
DM
147
148 // If we are in a @javascript session all contents would be displayed as HTML characters.
eff79d53 149 if ($this->running_javascript()) {
0a7f6a02
DM
150 $locator[1] = html_entity_decode($locator[1], ENT_NOQUOTES);
151 }
152
ff48a235
DM
153 } else {
154 $exceptiontype = $selector;
155 $exceptionlocator = $locator;
156 }
157
158 $exception = new ElementNotFoundException($this->getSession(), $exceptiontype, null, $exceptionlocator);
159 }
160
072f67fc
DM
161 $params = array('selector' => $selector, 'locator' => $locator);
162 // Pushing $node if required.
163 if ($node) {
164 $params['node'] = $node;
165 }
166
74c78e74
DM
167 // How much we will be waiting for the element to appear.
168 if (!$timeout) {
169 $timeout = self::TIMEOUT;
170 $microsleep = false;
171 } else {
172 // Spinning each 0.1 seconds if the timeout was forced as we understand
173 // that is a special case and is good to refine the performance as much
174 // as possible.
175 $microsleep = true;
176 }
177
ff48a235
DM
178 // Waits for the node to appear if it exists, otherwise will timeout and throw the provided exception.
179 return $this->spin(
180 function($context, $args) {
072f67fc
DM
181
182 // If no DOM node provided look in all the page.
183 if (empty($args['node'])) {
f8f1bdc3 184 return $context->getSession()->getPage()->findAll($args['selector'], $args['locator']);
072f67fc
DM
185 }
186
187 // For nodes contained in other nodes we can not use the basic named selectors
188 // as they include unions and they would look for matches in the DOM root.
189 $elementxpath = $context->getSession()->getSelectorsHandler()->selectorToXpath($args['selector'], $args['locator']);
190
191 // Split the xpath in unions and prefix them with the container xpath.
192 $unions = explode('|', $elementxpath);
193 foreach ($unions as $key => $union) {
194 $union = trim($union);
195
196 // We are in the container node.
197 if (strpos($union, '.') === 0) {
198 $union = substr($union, 1);
3db1aec5
DM
199 } else if (strpos($union, '/') !== 0) {
200 // Adding the path separator in case it is not there.
201 $union = '/' . $union;
072f67fc
DM
202 }
203 $unions[$key] = $args['node']->getXpath() . $union;
204 }
205
206 // We can not use usual Element::find() as it prefixes with DOM root.
f8f1bdc3 207 return $context->getSession()->getDriver()->find(implode('|', $unions));
ff48a235 208 },
072f67fc 209 $params,
74c78e74
DM
210 $timeout,
211 $exception,
212 $microsleep
46ac40cd 213 );
ff48a235
DM
214 }
215
216 /**
217 * Finds DOM nodes in the page using named selectors.
218 *
219 * The point of using this method instead of Mink ones is the spin
220 * method of behat_base::find() that looks for the element until it
221 * is available or it timeouts, this avoids the false failures received
222 * when selenium tries to execute commands on elements that are not
223 * ready to be used.
224 *
225 * All steps that requires elements to be available before interact with
226 * them should use one of the find* methods.
227 *
228 * The methods calls requires a {'find_' . $elementtype}($locator)
229 * format, like find_link($locator), find_select($locator),
230 * find_button($locator)...
231 *
232 * @link http://mink.behat.org/#named-selectors
233 * @throws coding_exception
46ac40cd 234 * @param string $name The name of the called method
ff48a235
DM
235 * @param mixed $arguments
236 * @return NodeElement
237 */
238 public function __call($name, $arguments) {
239
240 if (substr($name, 0, 5) !== 'find_') {
241 throw new coding_exception('The "' . $name . '" method does not exist');
242 }
243
244 // Only the named selector identifier.
245 $cleanname = substr($name, 5);
246
247 // All named selectors shares the interface.
248 if (count($arguments) !== 1) {
249 throw new coding_exception('The "' . $cleanname . '" named selector needs the locator as it\'s single argument');
250 }
251
252 // Redirecting execution to the find method with the specified selector.
253 // It will detect if it's pointing to an unexisting named selector.
42ad096f 254 return $this->find('named_partial',
ff48a235
DM
255 array(
256 $cleanname,
921faad9 257 behat_context_helper::escape($arguments[0])
ff48a235
DM
258 )
259 );
260 }
261
49d91129
DM
262 /**
263 * Escapes the double quote character.
264 *
265 * Double quote is the argument delimiter, it can be escaped
266 * with a backslash, but we auto-remove this backslashes
267 * before the step execution, this method is useful when using
268 * arguments as arguments for other steps.
269 *
270 * @param string $string
271 * @return string
272 */
273 public function escape($string) {
274 return str_replace('"', '\"', $string);
275 }
276
786ea937
DM
277 /**
278 * Executes the passed closure until returns true or time outs.
279 *
280 * In most cases the document.readyState === 'complete' will be enough, but sometimes JS
281 * requires more time to be completely loaded or an element to be visible or whatever is required to
282 * perform some action on an element; this method receives a closure which should contain the
283 * required statements to ensure the step definition actions and assertions have all their needs
284 * satisfied and executes it until they are satisfied or it timeouts. Redirects the return of the
285 * closure to the caller.
286 *
287 * The closures requirements to work well with this spin method are:
288 * - Must return false, null or '' if something goes wrong
289 * - Must return something != false if finishes as expected, this will be the (mixed) value
290 * returned by spin()
291 *
ff48a235 292 * The arguments of the closure are mixed, use $args depending on your needs.
786ea937 293 *
ff48a235 294 * You can provide an exception to give more accurate feedback to tests writers, otherwise the
c51c3b55 295 * closure exception will be used, but you must provide an exception if the closure does not throw
ff48a235
DM
296 * an exception.
297 *
8e5f86bc
SH
298 * @throws Exception If it timeouts without receiving something != false from the closure
299 * @param Function|array|string $lambda The function to execute or an array passed to call_user_func (maps to a class method)
300 * @param mixed $args Arguments to pass to the closure
301 * @param int $timeout Timeout in seconds
302 * @param Exception $exception The exception to throw in case it time outs.
303 * @param bool $microsleep If set to true it'll sleep micro seconds rather than seconds.
786ea937
DM
304 * @return mixed The value returned by the closure
305 */
8e5f86bc 306 protected function spin($lambda, $args = false, $timeout = false, $exception = false, $microsleep = false) {
786ea937
DM
307
308 // Using default timeout which is pretty high.
309 if (!$timeout) {
310 $timeout = self::TIMEOUT;
311 }
8e5f86bc
SH
312 if ($microsleep) {
313 // Will sleep 1/10th of a second by default for self::TIMEOUT seconds.
314 $loops = $timeout * 10;
315 } else {
316 // Will sleep for self::TIMEOUT seconds.
317 $loops = $timeout;
318 }
786ea937 319
80ac8522
TL
320 // DOM will never change on non-javascript case; do not wait or try again.
321 if (!$this->running_javascript()) {
322 $loops = 1;
323 }
324
8e5f86bc 325 for ($i = 0; $i < $loops; $i++) {
786ea937
DM
326 // We catch the exception thrown by the step definition to execute it again.
327 try {
786ea937 328 // We don't check with !== because most of the time closures will return
ff48a235
DM
329 // direct Behat methods returns and we are not sure it will be always (bool)false
330 // if it just runs the behat method without returning anything $return == null.
8e5f86bc 331 if ($return = call_user_func($lambda, $this, $args)) {
786ea937
DM
332 return $return;
333 }
46ac40cd 334 } catch (Exception $e) {
ff48a235
DM
335 // We would use the first closure exception if no exception has been provided.
336 if (!$exception) {
337 $exception = $e;
338 }
786ea937
DM
339 }
340
80ac8522
TL
341 if ($this->running_javascript()) {
342 if ($microsleep) {
343 usleep(100000);
344 } else {
345 sleep(1);
346 }
8e5f86bc 347 }
786ea937
DM
348 }
349
ff48a235
DM
350 // Using coding_exception as is a development issue if no exception has been provided.
351 if (!$exception) {
8e5f86bc 352 $exception = new coding_exception('spin method requires an exception if the callback does not throw an exception');
ff48a235
DM
353 }
354
786ea937
DM
355 // Throwing exception to the user.
356 throw $exception;
357 }
358
40923977
DM
359 /**
360 * Gets a NodeElement based on the locator and selector type received as argument from steps definitions.
361 *
072f67fc
DM
362 * Use behat_base::get_text_selector_node() for text-based selectors.
363 *
40923977
DM
364 * @throws ElementNotFoundException Thrown by behat_base::find
365 * @param string $selectortype
366 * @param string $element
367 * @return NodeElement
368 */
369 protected function get_selected_node($selectortype, $element) {
370
371 // Getting Mink selector and locator.
372 list($selector, $locator) = $this->transform_selector($selectortype, $element);
373
374 // Returns the NodeElement.
375 return $this->find($selector, $locator);
376 }
377
072f67fc
DM
378 /**
379 * Gets a NodeElement based on the locator and selector type received as argument from steps definitions.
380 *
381 * @throws ElementNotFoundException Thrown by behat_base::find
382 * @param string $selectortype
383 * @param string $element
384 * @return NodeElement
385 */
386 protected function get_text_selector_node($selectortype, $element) {
387
388 // Getting Mink selector and locator.
389 list($selector, $locator) = $this->transform_text_selector($selectortype, $element);
390
391 // Returns the NodeElement.
392 return $this->find($selector, $locator);
393 }
394
395 /**
396 * Gets the requested element inside the specified container.
397 *
398 * @throws ElementNotFoundException Thrown by behat_base::find
399 * @param mixed $selectortype The element selector type.
400 * @param mixed $element The element locator.
401 * @param mixed $containerselectortype The container selector type.
402 * @param mixed $containerelement The container locator.
403 * @return NodeElement
404 */
405 protected function get_node_in_container($selectortype, $element, $containerselectortype, $containerelement) {
406
407 // Gets the container, it will always be text based.
408 $containernode = $this->get_text_selector_node($containerselectortype, $containerelement);
409
410 list($selector, $locator) = $this->transform_selector($selectortype, $element);
411
412 // Specific exception giving info about where can't we find the element.
413 $locatorexceptionmsg = $element . '" in the "' . $containerelement. '" "' . $containerselectortype. '"';
414 $exception = new ElementNotFoundException($this->getSession(), $selectortype, null, $locatorexceptionmsg);
415
416 // Looks for the requested node inside the container node.
417 return $this->find($selector, $locator, $exception, $containernode);
418 }
419
40923977
DM
420 /**
421 * Transforms from step definition's argument style to Mink format.
422 *
423 * Mink has 3 different selectors css, xpath and named, where named
424 * selectors includes link, button, field... to simplify and group multiple
425 * steps in one we use the same interface, considering all link, buttons...
426 * at the same level as css selectors and xpath; this method makes the
427 * conversion from the arguments received by the steps to the selectors and locators
428 * required to interact with Mink.
429 *
430 * @throws ExpectationException
431 * @param string $selectortype It can be css, xpath or any of the named selectors.
432 * @param string $element The locator (or string) we are looking for.
433 * @return array Contains the selector and the locator expected by Mink.
434 */
435 protected function transform_selector($selectortype, $element) {
436
17344d4c
DM
437 // Here we don't know if an allowed text selector is being used.
438 $selectors = behat_selectors::get_allowed_selectors();
439 if (!isset($selectors[$selectortype])) {
40923977
DM
440 throw new ExpectationException('The "' . $selectortype . '" selector type does not exist', $this->getSession());
441 }
442
17344d4c 443 return behat_selectors::get_behat_selector($selectortype, $element, $this->getSession());
40923977
DM
444 }
445
072f67fc
DM
446 /**
447 * Transforms from step definition's argument style to Mink format.
448 *
449 * Delegates all the process to behat_base::transform_selector() checking
450 * the provided $selectortype.
451 *
452 * @throws ExpectationException
453 * @param string $selectortype It can be css, xpath or any of the named selectors.
454 * @param string $element The locator (or string) we are looking for.
455 * @return array Contains the selector and the locator expected by Mink.
456 */
457 protected function transform_text_selector($selectortype, $element) {
458
17344d4c
DM
459 $selectors = behat_selectors::get_allowed_text_selectors();
460 if (empty($selectors[$selectortype])) {
072f67fc
DM
461 throw new ExpectationException('The "' . $selectortype . '" selector can not be used to select text nodes', $this->getSession());
462 }
463
464 return $this->transform_selector($selectortype, $element);
465 }
466
eff79d53
DM
467 /**
468 * Returns whether the scenario is running in a browser that can run Javascript or not.
469 *
470 * @return boolean
471 */
472 protected function running_javascript() {
28abad1a 473 return get_class($this->getSession()->getDriver()) !== 'Behat\Mink\Driver\GoutteDriver';
eff79d53
DM
474 }
475
d1e55a47
DM
476 /**
477 * Spins around an element until it exists
478 *
479 * @throws ExpectationException
480 * @param string $element
481 * @param string $selectortype
482 * @return void
483 */
484 protected function ensure_element_exists($element, $selectortype) {
485
486 // Getting the behat selector & locator.
487 list($selector, $locator) = $this->transform_selector($selectortype, $element);
488
489 // Exception if it timesout and the element is still there.
c1faf86b 490 $msg = 'The "' . $element . '" element does not exist and should exist';
d1e55a47
DM
491 $exception = new ExpectationException($msg, $this->getSession());
492
c1faf86b 493 // It will stop spinning once the find() method returns true.
d1e55a47
DM
494 $this->spin(
495 function($context, $args) {
496 // We don't use behat_base::find as it is already spinning.
497 if ($context->getSession()->getPage()->find($args['selector'], $args['locator'])) {
498 return true;
499 }
c1faf86b 500 return false;
d1e55a47
DM
501 },
502 array('selector' => $selector, 'locator' => $locator),
503 self::EXTENDED_TIMEOUT,
504 $exception,
505 true
506 );
507
508 }
509
510 /**
511 * Spins until the element does not exist
512 *
513 * @throws ExpectationException
514 * @param string $element
515 * @param string $selectortype
516 * @return void
517 */
518 protected function ensure_element_does_not_exist($element, $selectortype) {
519
520 // Getting the behat selector & locator.
521 list($selector, $locator) = $this->transform_selector($selectortype, $element);
522
523 // Exception if it timesout and the element is still there.
c1faf86b 524 $msg = 'The "' . $element . '" element exists and should not exist';
d1e55a47
DM
525 $exception = new ExpectationException($msg, $this->getSession());
526
c1faf86b 527 // It will stop spinning once the find() method returns false.
d1e55a47
DM
528 $this->spin(
529 function($context, $args) {
c1faf86b 530 // We don't use behat_base::find() as we are already spinning.
d1e55a47
DM
531 if (!$context->getSession()->getPage()->find($args['selector'], $args['locator'])) {
532 return true;
533 }
c1faf86b 534 return false;
d1e55a47
DM
535 },
536 array('selector' => $selector, 'locator' => $locator),
537 self::EXTENDED_TIMEOUT,
538 $exception,
539 true
540 );
541 }
542
543 /**
544 * Ensures that the provided node is visible and we can interact with it.
545 *
546 * @throws ExpectationException
547 * @param NodeElement $node
548 * @return void Throws an exception if it times out without the element being visible
549 */
550 protected function ensure_node_is_visible($node) {
551
552 if (!$this->running_javascript()) {
553 return;
554 }
555
556 // Exception if it timesout and the element is still there.
c1faf86b 557 $msg = 'The "' . $node->getXPath() . '" xpath node is not visible and it should be visible';
d1e55a47
DM
558 $exception = new ExpectationException($msg, $this->getSession());
559
c1faf86b 560 // It will stop spinning once the isVisible() method returns true.
d1e55a47
DM
561 $this->spin(
562 function($context, $args) {
563 if ($args->isVisible()) {
564 return true;
565 }
c1faf86b 566 return false;
d1e55a47
DM
567 },
568 $node,
569 self::EXTENDED_TIMEOUT,
570 $exception,
571 true
572 );
573 }
574
3df6e801
RT
575 /**
576 * Ensures that the provided node has a attribute value set. This step can be used to check if specific
577 * JS has finished modifying the node.
578 *
579 * @throws ExpectationException
580 * @param NodeElement $node
581 * @param string $attribute attribute name
582 * @param string $attributevalue attribute value to check.
583 * @return void Throws an exception if it times out without the element being visible
584 */
585 protected function ensure_node_attribute_is_set($node, $attribute, $attributevalue) {
586
587 if (!$this->running_javascript()) {
588 return;
589 }
590
591 // Exception if it timesout and the element is still there.
592 $msg = 'The "' . $node->getXPath() . '" xpath node is not visible and it should be visible';
593 $exception = new ExpectationException($msg, $this->getSession());
594
595 // It will stop spinning once the $args[1]) == $args[2], and method returns true.
596 $this->spin(
597 function($context, $args) {
598 if ($args[0]->getAttribute($args[1]) == $args[2]) {
599 return true;
600 }
601 return false;
602 },
603 array($node, $attribute, $attributevalue),
604 self::EXTENDED_TIMEOUT,
605 $exception,
606 true
607 );
608 }
609
d1e55a47
DM
610 /**
611 * Ensures that the provided element is visible and we can interact with it.
612 *
613 * Returns the node in case other actions are interested in using it.
614 *
615 * @throws ExpectationException
616 * @param string $element
617 * @param string $selectortype
618 * @return NodeElement Throws an exception if it times out without being visible
619 */
620 protected function ensure_element_is_visible($element, $selectortype) {
621
622 if (!$this->running_javascript()) {
623 return;
624 }
625
626 $node = $this->get_selected_node($selectortype, $element);
627 $this->ensure_node_is_visible($node);
628
629 return $node;
630 }
631
632 /**
633 * Ensures that all the page's editors are loaded.
634 *
9f07f05a 635 * @deprecated since Moodle 2.7 MDL-44084 - please do not use this function any more.
d1e55a47 636 * @throws ElementNotFoundException
c1faf86b 637 * @throws ExpectationException
d1e55a47
DM
638 * @return void
639 */
640 protected function ensure_editors_are_loaded() {
786ced99
DW
641 global $CFG;
642
643 if (empty($CFG->behat_usedeprecated)) {
644 debugging('Function behat_base::ensure_editors_are_loaded() is deprecated. It is no longer required.');
645 }
9f07f05a 646 return;
d1e55a47 647 }
c1faf86b 648
3b0b5e57
RT
649 /**
650 * Change browser window size.
651 * - small: 640x480
652 * - medium: 1024x768
653 * - large: 2560x1600
654 *
655 * @param string $windowsize size of window.
5a14c4d9 656 * @param bool $viewport If true, changes viewport rather than window size
3b0b5e57
RT
657 * @throws ExpectationException
658 */
5a14c4d9 659 protected function resize_window($windowsize, $viewport = false) {
3233f32d
RT
660 // Non JS don't support resize window.
661 if (!$this->running_javascript()) {
662 return;
663 }
664
3b0b5e57
RT
665 switch ($windowsize) {
666 case "small":
667 $width = 640;
668 $height = 480;
669 break;
670 case "medium":
671 $width = 1024;
672 $height = 768;
673 break;
674 case "large":
675 $width = 2560;
676 $height = 1600;
677 break;
678 default:
3233f32d 679 preg_match('/^(\d+x\d+)$/', $windowsize, $matches);
3b0b5e57
RT
680 if (empty($matches) || (count($matches) != 2)) {
681 throw new ExpectationException("Invalid screen size, can't resize", $this->getSession());
682 }
683 $size = explode('x', $windowsize);
684 $width = (int) $size[0];
685 $height = (int) $size[1];
686 }
5a14c4d9 687 if ($viewport) {
688 // When setting viewport size, we set it so that the document width will be exactly
689 // as specified, assuming that there is a vertical scrollbar. (In cases where there is
690 // no scrollbar it will be slightly wider. We presume this is rare and predictable.)
691 // The window inner height will be as specified, which means the available viewport will
692 // actually be smaller if there is a horizontal scrollbar. We assume that horizontal
693 // scrollbars are rare so this doesn't matter.
694 $offset = $this->getSession()->getDriver()->evaluateScript(
695 'return (function() { var before = document.body.style.overflowY;' .
696 'document.body.style.overflowY = "scroll";' .
697 'var result = {};' .
698 'result.x = window.outerWidth - document.body.offsetWidth;' .
699 'result.y = window.outerHeight - window.innerHeight;' .
700 'document.body.style.overflowY = before;' .
701 'return result; })();');
702 $width += $offset['x'];
703 $height += $offset['y'];
704 }
705
3b0b5e57
RT
706 $this->getSession()->getDriver()->resizeWindow($width, $height);
707 }
07298309
RT
708
709 /**
710 * Waits for all the JS to be loaded.
711 *
712 * @throws \Exception
713 * @throws NoSuchWindow
714 * @throws UnknownError
715 * @return bool True or false depending whether all the JS is loaded or not.
716 */
717 public function wait_for_pending_js() {
718 // Waiting for JS is only valid for JS scenarios.
719 if (!$this->running_javascript()) {
720 return;
721 }
722
723 // We don't use behat_base::spin() here as we don't want to end up with an exception
724 // if the page & JSs don't finish loading properly.
725 for ($i = 0; $i < self::EXTENDED_TIMEOUT * 10; $i++) {
726 $pending = '';
727 try {
728 $jscode = '
5536bf4f 729 return (function() {
07298309
RT
730 if (typeof M === "undefined") {
731 if (document.readyState === "complete") {
732 return "";
733 } else {
734 return "incomplete";
735 }
736 } else if (' . self::PAGE_READY_JS . ') {
737 return "";
eb9ca848 738 } else if (typeof M.util !== "undefined") {
07298309 739 return M.util.pending_js.join(":");
eb9ca848
RT
740 } else {
741 return "incomplete"
07298309 742 }
5536bf4f 743 }());';
07298309
RT
744 $pending = $this->getSession()->evaluateScript($jscode);
745 } catch (NoSuchWindow $nsw) {
746 // We catch an exception here, in case we just closed the window we were interacting with.
747 // No javascript is running if there is no window right?
748 $pending = '';
749 } catch (UnknownError $e) {
750 // M is not defined when the window or the frame don't exist anymore.
751 if (strstr($e->getMessage(), 'M is not defined') != false) {
752 $pending = '';
753 }
754 }
755
756 // If there are no pending JS we stop waiting.
757 if ($pending === '') {
758 return true;
759 }
760
761 // 0.1 seconds.
762 usleep(100000);
763 }
764
765 // Timeout waiting for JS to complete. It will be catched and forwarded to behat_hooks::i_look_for_exceptions().
766 // It is unlikely that Javascript code of a page or an AJAX request needs more than self::EXTENDED_TIMEOUT seconds
767 // to be loaded, although when pages contains Javascript errors M.util.js_complete() can not be executed, so the
768 // number of JS pending code and JS completed code will not match and we will reach this point.
769 throw new \Exception('Javascript code and/or AJAX requests are not ready after ' . self::EXTENDED_TIMEOUT .
770 ' seconds. There is a Javascript error or the code is extremely slow.');
771 }
eb9ca848
RT
772
773 /**
774 * Internal step definition to find exceptions, debugging() messages and PHP debug messages.
775 *
776 * Part of behat_hooks class as is part of the testing framework, is auto-executed
777 * after each step so no features will splicitly use it.
778 *
779 * @throws Exception Unknown type, depending on what we caught in the hook or basic \Exception.
780 * @see Moodle\BehatExtension\Tester\MoodleStepTester
781 */
782 public function look_for_exceptions() {
783 // Wrap in try in case we were interacting with a closed window.
784 try {
785
786 // Exceptions.
787 $exceptionsxpath = "//div[@data-rel='fatalerror']";
788 // Debugging messages.
789 $debuggingxpath = "//div[@data-rel='debugging']";
790 // PHP debug messages.
791 $phperrorxpath = "//div[@data-rel='phpdebugmessage']";
792 // Any other backtrace.
793 $othersxpath = "(//*[contains(., ': call to ')])[1]";
794
795 $xpaths = array($exceptionsxpath, $debuggingxpath, $phperrorxpath, $othersxpath);
796 $joinedxpath = implode(' | ', $xpaths);
797
798 // Joined xpath expression. Most of the time there will be no exceptions, so this pre-check
799 // is faster than to send the 4 xpath queries for each step.
800 if (!$this->getSession()->getDriver()->find($joinedxpath)) {
0c1bcb63
RT
801 // Check if we have recorded any errors in driver process.
802 $phperrors = behat_get_shutdown_process_errors();
803 if (!empty($phperrors)) {
804 foreach ($phperrors as $error) {
805 $errnostring = behat_get_error_string($error['type']);
806 $msgs[] = $errnostring . ": " .$error['message'] . " at " . $error['file'] . ": " . $error['line'];
807 }
808 $msg = "PHP errors found:\n" . implode("\n", $msgs);
809 throw new \Exception(htmlentities($msg));
810 }
811
eb9ca848
RT
812 return;
813 }
814
815 // Exceptions.
816 if ($errormsg = $this->getSession()->getPage()->find('xpath', $exceptionsxpath)) {
817
818 // Getting the debugging info and the backtrace.
819 $errorinfoboxes = $this->getSession()->getPage()->findAll('css', 'div.alert-error');
63e4df60
DW
820 // If errorinfoboxes is empty, try find alert-danger (bootstrap4) class.
821 if (empty($errorinfoboxes)) {
822 $errorinfoboxes = $this->getSession()->getPage()->findAll('css', 'div.alert-danger');
823 }
eb9ca848
RT
824 // If errorinfoboxes is empty, try find notifytiny (original) class.
825 if (empty($errorinfoboxes)) {
826 $errorinfoboxes = $this->getSession()->getPage()->findAll('css', 'div.notifytiny');
827 }
0c1bcb63
RT
828
829 // If errorinfoboxes is empty, try find ajax/JS exception in dialogue.
830 if (empty($errorinfoboxes)) {
831 $errorinfoboxes = $this->getSession()->getPage()->findAll('css', 'div.moodle-exception-message');
832
833 // If ajax/JS exception.
834 if ($errorinfoboxes) {
835 $errorinfo = $this->get_debug_text($errorinfoboxes[0]->getHtml());
836 }
837
838 } else {
839 $errorinfo = $this->get_debug_text($errorinfoboxes[0]->getHtml()) . "\n" .
840 $this->get_debug_text($errorinfoboxes[1]->getHtml());
841 }
eb9ca848
RT
842
843 $msg = "Moodle exception: " . $errormsg->getText() . "\n" . $errorinfo;
844 throw new \Exception(html_entity_decode($msg));
845 }
846
847 // Debugging messages.
848 if ($debuggingmessages = $this->getSession()->getPage()->findAll('xpath', $debuggingxpath)) {
849 $msgs = array();
850 foreach ($debuggingmessages as $debuggingmessage) {
851 $msgs[] = $this->get_debug_text($debuggingmessage->getHtml());
852 }
853 $msg = "debugging() message/s found:\n" . implode("\n", $msgs);
854 throw new \Exception(html_entity_decode($msg));
855 }
856
857 // PHP debug messages.
858 if ($phpmessages = $this->getSession()->getPage()->findAll('xpath', $phperrorxpath)) {
859
860 $msgs = array();
861 foreach ($phpmessages as $phpmessage) {
862 $msgs[] = $this->get_debug_text($phpmessage->getHtml());
863 }
864 $msg = "PHP debug message/s found:\n" . implode("\n", $msgs);
865 throw new \Exception(html_entity_decode($msg));
866 }
867
868 // Any other backtrace.
869 // First looking through xpath as it is faster than get and parse the whole page contents,
870 // we get the contents and look for matches once we found something to suspect that there is a backtrace.
871 if ($this->getSession()->getDriver()->find($othersxpath)) {
872 $backtracespattern = '/(line [0-9]* of [^:]*: call to [\->&;:a-zA-Z_\x7f-\xff][\->&;:a-zA-Z0-9_\x7f-\xff]*)/';
873 if (preg_match_all($backtracespattern, $this->getSession()->getPage()->getContent(), $backtraces)) {
874 $msgs = array();
875 foreach ($backtraces[0] as $backtrace) {
876 $msgs[] = $backtrace . '()';
877 }
878 $msg = "Other backtraces found:\n" . implode("\n", $msgs);
879 throw new \Exception(htmlentities($msg));
880 }
881 }
882
883 } catch (NoSuchWindow $e) {
884 // If we were interacting with a popup window it will not exists after closing it.
b095b36c
MN
885 } catch (DriverException $e) {
886 // Same reason as above.
eb9ca848
RT
887 }
888 }
889
8918a811
DM
890 /**
891 * Converts HTML tags to line breaks to display the info in CLI
892 *
893 * @param string $html
894 * @return string
895 */
896 protected function get_debug_text($html) {
897
898 // Replacing HTML tags for new lines and keeping only the text.
899 $notags = preg_replace('/<+\s*\/*\s*([A-Z][A-Z0-9]*)\b[^>]*\/*\s*>*/i', "\n", $html);
900 return preg_replace("/(\n)+/s", "\n", $notags);
901 }
902
eb9ca848
RT
903 /**
904 * Helper function to execute api in a given context.
905 *
906 * @param string $contextapi context in which api is defined.
907 * @param array $params list of params to pass.
908 * @throws Exception
909 */
910 protected function execute($contextapi, $params = array()) {
911 if (!is_array($params)) {
912 $params = array($params);
913 }
914
915 // Get required context and execute the api.
916 $contextapi = explode("::", $contextapi);
917 $context = behat_context_helper::get($contextapi[0]);
918 call_user_func_array(array($context, $contextapi[1]), $params);
919
920 // NOTE: Wait for pending js and look for exception are not optional, as this might lead to unexpected results.
921 // Don't make them optional for performance reasons.
922
923 // Wait for pending js.
924 $this->wait_for_pending_js();
925
926 // Look for exceptions.
927 $this->look_for_exceptions();
928 }
353e7876 929
930 /**
931 * Get the actual user in the behat session (note $USER does not correspond to the behat session's user).
932 * @return mixed
933 * @throws coding_exception
934 */
935 protected function get_session_user() {
936 global $DB;
937
938 $sid = $this->getSession()->getCookie('MoodleSession');
939 if (empty($sid)) {
940 throw new coding_exception('failed to get moodle session');
941 }
942 $userid = $DB->get_field('sessions', 'userid', ['sid' => $sid]);
943 if (empty($userid)) {
944 throw new coding_exception('failed to get user from seession id '.$sid);
945 }
946 return $DB->get_record('user', ['id' => $userid]);
947 }
01f2a530 948
949 /**
950 * Trigger click on node via javascript instead of actually clicking on it via pointer.
951 *
952 * This function resolves the issue of nested elements with click listeners or links - in these cases clicking via
953 * the pointer may accidentally cause a click on the wrong element.
954 * Example of issue: clicking to expand navigation nodes when the config value linkadmincategories is enabled.
955 * @param NodeElement $node
956 */
957 protected function js_trigger_click($node) {
958 if (!$this->running_javascript()) {
959 $node->click();
960 }
961 $this->ensure_node_is_visible($node); // Ensures hidden elements can't be clicked.
962 $xpath = $node->getXpath();
b5be3875
MN
963 $driver = $this->getSession()->getDriver();
964 if ($driver instanceof \Moodle\BehatExtension\Driver\MoodleSelenium2Driver) {
965 $script = "Syn.click({{ELEMENT}})";
966 $driver->triggerSynScript($xpath, $script);
967 } else {
968 $driver->click($xpath);
969 }
01f2a530 970 }
d4322e38 971}