MDL-70148 behat: Add steps to send keys without an element
[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
7bfb575f
AN
31use Behat\Mink\Exception\DriverException;
32use Behat\Mink\Exception\ExpectationException;
33use Behat\Mink\Exception\ElementNotFoundException;
34use Behat\Mink\Element\NodeElement;
700682dc 35use Behat\Mink\Element\Element;
7bfb575f 36use Behat\Mink\Session;
ff48a235 37
61832fae
AN
38require_once(__DIR__ . '/classes/component_named_selector.php');
39require_once(__DIR__ . '/classes/component_named_replacement.php');
40
e9b443b3
AN
41// Alias the WebDriver\Key class to behat_keys to make future transition to a different WebDriver implementation
42// easier.
43class_alias('WebDriver\\Key', 'behat_keys');
44
d4322e38
DM
45/**
46 * Steps definitions base class.
47 *
48 * To extend by the steps definitions of the different Moodle components.
49 *
50 * It can not contain steps definitions to avoid duplicates, only utility
51 * methods shared between steps.
52 *
fcb6ed47
MG
53 * @method NodeElement find_field(string $locator) Finds a form element
54 * @method NodeElement find_button(string $locator) Finds a form input submit element or a button
55 * @method NodeElement find_link(string $locator) Finds a link on a page
56 * @method NodeElement find_file(string $locator) Finds a forum input file element
57 *
d4322e38
DM
58 * @package core
59 * @category test
60 * @copyright 2012 David MonllaĆ³
61 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
62 */
63class behat_base extends Behat\MinkExtension\Context\RawMinkContext {
64
74c78e74
DM
65 /**
66 * Small timeout.
67 *
68 * A reduced timeout for cases where self::TIMEOUT is too much
69 * and a simple $this->getSession()->getPage()->find() could not
70 * be enough.
05a5d547 71 *
72 * @deprecated since Moodle 3.7 MDL-64979 - please use get_reduced_timeout() instead
84524186 73 * @todo MDL-64982 This will be deleted in Moodle 3.11
05a5d547 74 * @see behat_base::get_reduced_timeout()
74c78e74
DM
75 */
76 const REDUCED_TIMEOUT = 2;
77
d4322e38
DM
78 /**
79 * The timeout for each Behat step (load page, wait for an element to load...).
05a5d547 80 *
81 * @deprecated since Moodle 3.7 MDL-64979 - please use get_timeout() instead
84524186 82 * @todo MDL-64982 This will be deleted in Moodle 3.11
05a5d547 83 * @see behat_base::get_timeout()
d4322e38 84 */
845ceaff 85 const TIMEOUT = 6;
d1e55a47
DM
86
87 /**
88 * And extended timeout for specific cases.
05a5d547 89 *
90 * @deprecated since Moodle 3.7 MDL-64979 - please use get_extended_timeout() instead
84524186 91 * @todo MDL-64982 This will be deleted in Moodle 3.11
05a5d547 92 * @see behat_base::get_extended_timeout()
d1e55a47
DM
93 */
94 const EXTENDED_TIMEOUT = 10;
95
d1e55a47
DM
96 /**
97 * The JS code to check that the page is ready.
d8892dcc
NDM
98 *
99 * The document must be complete and either M.util.pending_js must be empty, or it must not be defined at all.
d1e55a47 100 */
d8892dcc
NDM
101 const PAGE_READY_JS = "document.readyState === 'complete' && " .
102 "(typeof M !== 'object' || typeof M.util !== 'object' || " .
103 "typeof M.util.pending_js === 'undefined' || M.util.pending_js.length === 0)";
d4322e38 104
786ea937
DM
105 /**
106 * Locates url, based on provided path.
107 * Override to provide custom routing mechanism.
108 *
109 * @see Behat\MinkExtension\Context\MinkContext
110 * @param string $path
111 * @return string
112 */
40923977 113 protected function locate_path($path) {
46ac40cd
DM
114 $starturl = rtrim($this->getMinkParameter('base_url'), '/') . '/';
115 return 0 !== strpos($path, 'http') ? $starturl . ltrim($path, '/') : $path;
786ea937
DM
116 }
117
ff48a235 118 /**
f8f1bdc3 119 * Returns the first matching element.
ff48a235
DM
120 *
121 * @link http://mink.behat.org/#traverse-the-page-selectors
ff48a235
DM
122 * @param string $selector The selector type (css, xpath, named...)
123 * @param mixed $locator It depends on the $selector, can be the xpath, a name, a css locator...
40923977 124 * @param Exception $exception Otherwise we throw exception with generic info
072f67fc 125 * @param NodeElement $node Spins around certain DOM node instead of the whole page
74c78e74 126 * @param int $timeout Forces a specific time out (in seconds).
ff48a235
DM
127 * @return NodeElement
128 */
74c78e74 129 protected function find($selector, $locator, $exception = false, $node = false, $timeout = false) {
34503872
AN
130 if ($selector === 'NodeElement' && is_a($locator, NodeElement::class)) {
131 // Support a NodeElement being passed in for use in step chaining.
132 return $locator;
133 }
134
f8f1bdc3 135 // Returns the first match.
74c78e74 136 $items = $this->find_all($selector, $locator, $exception, $node, $timeout);
f8f1bdc3
DM
137 return count($items) ? reset($items) : null;
138 }
139
140 /**
141 * Returns all matching elements.
142 *
143 * Adapter to Behat\Mink\Element\Element::findAll() using the spin() method.
144 *
145 * @link http://mink.behat.org/#traverse-the-page-selectors
146 * @param string $selector The selector type (css, xpath, named...)
147 * @param mixed $locator It depends on the $selector, can be the xpath, a name, a css locator...
148 * @param Exception $exception Otherwise we throw expcetion with generic info
700682dc 149 * @param NodeElement $container Restrict the search to just children of the specified container
74c78e74 150 * @param int $timeout Forces a specific time out (in seconds). If 0 is provided the default timeout will be applied.
f8f1bdc3
DM
151 * @return array NodeElements list
152 */
700682dc 153 protected function find_all($selector, $locator, $exception = false, $container = false, $timeout = false) {
42ad096f
RT
154 // Throw exception, so dev knows it is not supported.
155 if ($selector === 'named') {
156 $exception = 'Using the "named" selector is deprecated as of 3.1. '
157 .' Use the "named_partial" or use the "named_exact" selector instead.';
158 throw new ExpectationException($exception, $this->getSession());
159 }
160
ff48a235
DM
161 // Generic info.
162 if (!$exception) {
ff48a235 163 // With named selectors we can be more specific.
07298309 164 if (($selector == 'named_exact') || ($selector == 'named_partial')) {
ff48a235
DM
165 $exceptiontype = $locator[0];
166 $exceptionlocator = $locator[1];
0a7f6a02
DM
167
168 // If we are in a @javascript session all contents would be displayed as HTML characters.
eff79d53 169 if ($this->running_javascript()) {
0a7f6a02
DM
170 $locator[1] = html_entity_decode($locator[1], ENT_NOQUOTES);
171 }
172
ff48a235
DM
173 } else {
174 $exceptiontype = $selector;
175 $exceptionlocator = $locator;
176 }
177
178 $exception = new ElementNotFoundException($this->getSession(), $exceptiontype, null, $exceptionlocator);
179 }
180
74c78e74
DM
181 // How much we will be waiting for the element to appear.
182 if (!$timeout) {
05a5d547 183 $timeout = self::get_timeout();
74c78e74
DM
184 $microsleep = false;
185 } else {
186 // Spinning each 0.1 seconds if the timeout was forced as we understand
187 // that is a special case and is good to refine the performance as much
188 // as possible.
189 $microsleep = true;
190 }
191
700682dc
AN
192 // Normalise the values in order to perform the search.
193 [
194 'selector' => $selector,
195 'locator' => $locator,
196 'container' => $container,
197 ] = $this->normalise_selector($selector, $locator, $container ?: $this->getSession()->getPage());
198
ff48a235
DM
199 // Waits for the node to appear if it exists, otherwise will timeout and throw the provided exception.
200 return $this->spin(
700682dc
AN
201 function() use ($selector, $locator, $container) {
202 return $container->findAll($selector, $locator);
203 }, [], $timeout, $exception, $microsleep
204 );
205 }
072f67fc 206
700682dc
AN
207 /**
208 * Normalise the locator and selector.
209 *
210 * @param string $selector The type of thing to search
211 * @param mixed $locator The locator value. Can be an array, but is more likely a string.
212 * @param Element $container An optional container to search within
213 * @return array The selector, locator, and container to search within
214 */
215 public function normalise_selector(string $selector, $locator, Element $container): array {
b983ae4a
AN
216 // Check for specific transformations for this selector type.
217 $transformfunction = "transform_find_for_{$selector}";
218 if (method_exists('behat_selectors', $transformfunction)) {
219 // A selector-specific transformation exists.
220 // Perform initial transformation of the selector within the current container.
221 [
222 'selector' => $selector,
223 'locator' => $locator,
224 'container' => $container,
225 ] = behat_selectors::{$transformfunction}($this, $locator, $container);
226 }
227
700682dc
AN
228 // Normalise the css and xpath selector types.
229 if ('css_element' === $selector) {
230 $selector = 'css';
231 } else if ('xpath_element' === $selector) {
232 $selector = 'xpath';
233 }
072f67fc 234
61832fae 235 // Convert to a named selector where the selector type is not a known selector.
700682dc
AN
236 $converttonamed = !$this->getSession()->getSelectorsHandler()->isSelectorRegistered($selector);
237 $converttonamed = $converttonamed && 'xpath' !== $selector;
238 if ($converttonamed) {
61832fae
AN
239 if (behat_partial_named_selector::is_deprecated_selector($selector)) {
240 if ($replacement = behat_partial_named_selector::get_deprecated_replacement($selector)) {
241 error_log("The '{$selector}' selector has been replaced with {$replacement}");
242 $selector = $replacement;
243 }
244 } else if (behat_exact_named_selector::is_deprecated_selector($selector)) {
245 if ($replacement = behat_exact_named_selector::get_deprecated_replacement($selector)) {
246 error_log("The '{$selector}' selector has been replaced with {$replacement}");
247 $selector = $replacement;
248 }
249 }
250
700682dc
AN
251 $allowedpartialselectors = behat_partial_named_selector::get_allowed_selectors();
252 $allowedexactselectors = behat_exact_named_selector::get_allowed_selectors();
253 if (isset($allowedpartialselectors[$selector])) {
254 $locator = behat_selectors::normalise_named_selector($allowedpartialselectors[$selector], $locator);
255 $selector = 'named_partial';
256 } else if (isset($allowedexactselectors[$selector])) {
257 $locator = behat_selectors::normalise_named_selector($allowedexactselectors[$selector], $locator);
258 $selector = 'named_exact';
259 } else {
61832fae 260 throw new ExpectationException("The '{$selector}' selector type is not registered.", $this->getSession()->getDriver());
700682dc
AN
261 }
262 }
263
264 return [
265 'selector' => $selector,
266 'locator' => $locator,
267 'container' => $container,
268 ];
ff48a235
DM
269 }
270
e9b443b3
AN
271 /**
272 * Send key presses straight to the currently active element.
273 *
274 * The `$keys` array contains a list of key values to send to the session as defined in the WebDriver and JsonWire
275 * specifications:
276 * - JsonWire: https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol#sessionsessionidkeys
277 * - W3C WebDriver: https://www.w3.org/TR/webdriver/#keyboard-actions
278 *
279 * This may be a combination of typable characters, modifier keys, and other supported keypoints.
280 *
281 * The NULL_KEY should be used to release modifier keys. If the NULL_KEY is not used then modifier keys will remain
282 * in the pressed state.
283 *
284 * Example usage:
285 *
286 * behat_base::type_keys($this->getSession(), [behat_keys::SHIFT, behat_keys::TAB, behat_keys::NULL_KEY]);
287 * behat_base::type_keys($this->getSession(), [behat_keys::ENTER, behat_keys::NULL_KEY]);
288 * behat_base::type_keys($this->getSession(), [behat_keys::ESCAPE, behat_keys::NULL_KEY]);
289 *
290 * It can also be used to send text input, for example:
291 *
292 * behat_base::type_keys(
293 * $this->getSession(),
294 * ['D', 'o', ' ', 'y', 'o', 'u', ' ', 'p', 'l', 'a' 'y', ' ', 'G', 'o', '?', behat_base::NULL_KEY]
295 * );
296 *
297 *
298 * Please note: This function does not use the element/sendKeys variants but sends keys straight to the browser.
299 *
300 * @param Session $session
301 * @param string[] $keys
302 */
303 public static function type_keys(Session $session, array $keys): void {
304 $session->getDriver()->getWebDriverSession()->keys([
305 'value' => $keys,
306 ]);
307 }
308
ff48a235
DM
309 /**
310 * Finds DOM nodes in the page using named selectors.
311 *
312 * The point of using this method instead of Mink ones is the spin
313 * method of behat_base::find() that looks for the element until it
314 * is available or it timeouts, this avoids the false failures received
315 * when selenium tries to execute commands on elements that are not
316 * ready to be used.
317 *
318 * All steps that requires elements to be available before interact with
319 * them should use one of the find* methods.
320 *
321 * The methods calls requires a {'find_' . $elementtype}($locator)
322 * format, like find_link($locator), find_select($locator),
323 * find_button($locator)...
324 *
325 * @link http://mink.behat.org/#named-selectors
326 * @throws coding_exception
46ac40cd 327 * @param string $name The name of the called method
ff48a235
DM
328 * @param mixed $arguments
329 * @return NodeElement
330 */
331 public function __call($name, $arguments) {
700682dc
AN
332 if (substr($name, 0, 5) === 'find_') {
333 return call_user_func_array([$this, 'find'], array_merge(
334 [substr($name, 5)],
335 $arguments
336 ));
ff48a235
DM
337 }
338
700682dc 339 throw new coding_exception("The '{$name}' method does not exist");
ff48a235
DM
340 }
341
49d91129
DM
342 /**
343 * Escapes the double quote character.
344 *
345 * Double quote is the argument delimiter, it can be escaped
346 * with a backslash, but we auto-remove this backslashes
347 * before the step execution, this method is useful when using
348 * arguments as arguments for other steps.
349 *
350 * @param string $string
351 * @return string
352 */
353 public function escape($string) {
354 return str_replace('"', '\"', $string);
355 }
356
786ea937
DM
357 /**
358 * Executes the passed closure until returns true or time outs.
359 *
360 * In most cases the document.readyState === 'complete' will be enough, but sometimes JS
361 * requires more time to be completely loaded or an element to be visible or whatever is required to
362 * perform some action on an element; this method receives a closure which should contain the
363 * required statements to ensure the step definition actions and assertions have all their needs
364 * satisfied and executes it until they are satisfied or it timeouts. Redirects the return of the
365 * closure to the caller.
366 *
367 * The closures requirements to work well with this spin method are:
368 * - Must return false, null or '' if something goes wrong
369 * - Must return something != false if finishes as expected, this will be the (mixed) value
370 * returned by spin()
371 *
ff48a235 372 * The arguments of the closure are mixed, use $args depending on your needs.
786ea937 373 *
ff48a235 374 * You can provide an exception to give more accurate feedback to tests writers, otherwise the
c51c3b55 375 * closure exception will be used, but you must provide an exception if the closure does not throw
ff48a235
DM
376 * an exception.
377 *
8e5f86bc
SH
378 * @throws Exception If it timeouts without receiving something != false from the closure
379 * @param Function|array|string $lambda The function to execute or an array passed to call_user_func (maps to a class method)
380 * @param mixed $args Arguments to pass to the closure
381 * @param int $timeout Timeout in seconds
382 * @param Exception $exception The exception to throw in case it time outs.
383 * @param bool $microsleep If set to true it'll sleep micro seconds rather than seconds.
786ea937
DM
384 * @return mixed The value returned by the closure
385 */
8e5f86bc 386 protected function spin($lambda, $args = false, $timeout = false, $exception = false, $microsleep = false) {
786ea937
DM
387
388 // Using default timeout which is pretty high.
389 if (!$timeout) {
05a5d547 390 $timeout = self::get_timeout();
786ea937
DM
391 }
392
c7807a10
AN
393 $start = microtime(true);
394 $end = $start + $timeout;
80ac8522 395
c7807a10 396 do {
786ea937
DM
397 // We catch the exception thrown by the step definition to execute it again.
398 try {
786ea937 399 // We don't check with !== because most of the time closures will return
ff48a235
DM
400 // direct Behat methods returns and we are not sure it will be always (bool)false
401 // if it just runs the behat method without returning anything $return == null.
8e5f86bc 402 if ($return = call_user_func($lambda, $this, $args)) {
786ea937
DM
403 return $return;
404 }
46ac40cd 405 } catch (Exception $e) {
ff48a235
DM
406 // We would use the first closure exception if no exception has been provided.
407 if (!$exception) {
408 $exception = $e;
409 }
786ea937
DM
410 }
411
c7807a10
AN
412 if (!$this->running_javascript()) {
413 break;
8e5f86bc 414 }
c7807a10
AN
415
416 usleep(100000);
417
418 } while (microtime(true) < $end);
786ea937 419
ff48a235
DM
420 // Using coding_exception as is a development issue if no exception has been provided.
421 if (!$exception) {
8e5f86bc 422 $exception = new coding_exception('spin method requires an exception if the callback does not throw an exception');
ff48a235
DM
423 }
424
786ea937
DM
425 // Throwing exception to the user.
426 throw $exception;
427 }
428
40923977
DM
429 /**
430 * Gets a NodeElement based on the locator and selector type received as argument from steps definitions.
431 *
072f67fc
DM
432 * Use behat_base::get_text_selector_node() for text-based selectors.
433 *
40923977
DM
434 * @throws ElementNotFoundException Thrown by behat_base::find
435 * @param string $selectortype
436 * @param string $element
437 * @return NodeElement
438 */
439 protected function get_selected_node($selectortype, $element) {
d10ed4d2 440 return $this->find($selectortype, $element);
40923977
DM
441 }
442
072f67fc
DM
443 /**
444 * Gets a NodeElement based on the locator and selector type received as argument from steps definitions.
445 *
446 * @throws ElementNotFoundException Thrown by behat_base::find
447 * @param string $selectortype
448 * @param string $element
449 * @return NodeElement
450 */
451 protected function get_text_selector_node($selectortype, $element) {
072f67fc
DM
452 // Getting Mink selector and locator.
453 list($selector, $locator) = $this->transform_text_selector($selectortype, $element);
454
455 // Returns the NodeElement.
456 return $this->find($selector, $locator);
457 }
458
459 /**
460 * Gets the requested element inside the specified container.
461 *
462 * @throws ElementNotFoundException Thrown by behat_base::find
463 * @param mixed $selectortype The element selector type.
464 * @param mixed $element The element locator.
465 * @param mixed $containerselectortype The container selector type.
466 * @param mixed $containerelement The container locator.
467 * @return NodeElement
468 */
469 protected function get_node_in_container($selectortype, $element, $containerselectortype, $containerelement) {
072f67fc
DM
470 // Gets the container, it will always be text based.
471 $containernode = $this->get_text_selector_node($containerselectortype, $containerelement);
472
072f67fc
DM
473 $locatorexceptionmsg = $element . '" in the "' . $containerelement. '" "' . $containerselectortype. '"';
474 $exception = new ElementNotFoundException($this->getSession(), $selectortype, null, $locatorexceptionmsg);
475
d10ed4d2 476 return $this->find($selectortype, $element, $exception, $containernode);
072f67fc
DM
477 }
478
40923977
DM
479 /**
480 * Transforms from step definition's argument style to Mink format.
481 *
482 * Mink has 3 different selectors css, xpath and named, where named
483 * selectors includes link, button, field... to simplify and group multiple
484 * steps in one we use the same interface, considering all link, buttons...
485 * at the same level as css selectors and xpath; this method makes the
486 * conversion from the arguments received by the steps to the selectors and locators
487 * required to interact with Mink.
488 *
489 * @throws ExpectationException
490 * @param string $selectortype It can be css, xpath or any of the named selectors.
491 * @param string $element The locator (or string) we are looking for.
492 * @return array Contains the selector and the locator expected by Mink.
493 */
494 protected function transform_selector($selectortype, $element) {
17344d4c
DM
495 // Here we don't know if an allowed text selector is being used.
496 $selectors = behat_selectors::get_allowed_selectors();
497 if (!isset($selectors[$selectortype])) {
40923977
DM
498 throw new ExpectationException('The "' . $selectortype . '" selector type does not exist', $this->getSession());
499 }
500
700682dc
AN
501 [
502 'selector' => $selector,
503 'locator' => $locator,
504 ] = $this->normalise_selector($selectortype, $element, $this->getSession()->getPage());
505
506 return [$selector, $locator];
40923977
DM
507 }
508
072f67fc
DM
509 /**
510 * Transforms from step definition's argument style to Mink format.
511 *
512 * Delegates all the process to behat_base::transform_selector() checking
513 * the provided $selectortype.
514 *
515 * @throws ExpectationException
516 * @param string $selectortype It can be css, xpath or any of the named selectors.
517 * @param string $element The locator (or string) we are looking for.
518 * @return array Contains the selector and the locator expected by Mink.
519 */
520 protected function transform_text_selector($selectortype, $element) {
521
17344d4c
DM
522 $selectors = behat_selectors::get_allowed_text_selectors();
523 if (empty($selectors[$selectortype])) {
072f67fc
DM
524 throw new ExpectationException('The "' . $selectortype . '" selector can not be used to select text nodes', $this->getSession());
525 }
526
527 return $this->transform_selector($selectortype, $element);
528 }
529
eff79d53 530 /**
6d5d1935 531 * Whether Javascript is available in the current Session.
eff79d53
DM
532 *
533 * @return boolean
534 */
535 protected function running_javascript() {
6d5d1935
AN
536 return self::running_javascript_in_session($this->getSession());
537 }
538
539 /**
540 * Require that javascript be available in the current Session.
541 *
542 * @throws DriverException
543 */
544 protected function require_javascript() {
545 return self::require_javascript_in_session($this->getSession());
546 }
547
548 /**
549 * Whether Javascript is available in the specified Session.
550 *
551 * @param Session $session
552 * @return boolean
553 */
554 protected static function running_javascript_in_session(Session $session): bool {
555 return get_class($session->getDriver()) !== 'Behat\Mink\Driver\GoutteDriver';
556 }
557
558 /**
559 * Require that javascript be available for the specified Session.
560 *
561 * @param Session $session
562 * @throws DriverException
563 */
564 protected static function require_javascript_in_session(Session $session): void {
565 if (self::running_javascript_in_session($session)) {
566 return;
567 }
568
569 throw new DriverException('Javascript is required');
eff79d53
DM
570 }
571
079eae37 572 /**
573 * Checks if the current page is part of the mobile app.
574 *
575 * @return bool True if it's in the app
576 */
577 protected function is_in_app() : bool {
578 // Cannot be in the app if there's no @app tag on scenario.
579 if (!$this->has_tag('app')) {
580 return false;
581 }
582
583 // Check on page to see if it's an app page. Safest way is to look for added JavaScript.
cd6eadd4 584 return $this->evaluate_script('return typeof window.behat') === 'object';
079eae37 585 }
586
d1e55a47
DM
587 /**
588 * Spins around an element until it exists
589 *
590 * @throws ExpectationException
d10ed4d2 591 * @param string $locator
d1e55a47
DM
592 * @param string $selectortype
593 * @return void
594 */
d10ed4d2 595 protected function ensure_element_exists($locator, $selectortype) {
d1e55a47 596 // Exception if it timesout and the element is still there.
d10ed4d2 597 $msg = "The '{$locator}' element does not exist and should";
d1e55a47
DM
598 $exception = new ExpectationException($msg, $this->getSession());
599
d10ed4d2
AN
600 // Normalise the values in order to perform the search.
601 [
602 'selector' => $selector,
603 'locator' => $locator,
604 'container' => $container,
605 ] = $this->normalise_selector($selectortype, $locator, $this->getSession()->getPage());
606
c1faf86b 607 // It will stop spinning once the find() method returns true.
d1e55a47 608 $this->spin(
d10ed4d2
AN
609 function() use ($selector, $locator, $container) {
610 if ($container->find($selector, $locator)) {
d1e55a47
DM
611 return true;
612 }
c1faf86b 613 return false;
d1e55a47 614 },
d10ed4d2 615 [],
05a5d547 616 self::get_extended_timeout(),
d1e55a47
DM
617 $exception,
618 true
619 );
d1e55a47
DM
620 }
621
622 /**
623 * Spins until the element does not exist
624 *
625 * @throws ExpectationException
d10ed4d2 626 * @param string $locator
d1e55a47
DM
627 * @param string $selectortype
628 * @return void
629 */
d10ed4d2 630 protected function ensure_element_does_not_exist($locator, $selectortype) {
d1e55a47 631 // Exception if it timesout and the element is still there.
d10ed4d2 632 $msg = "The '{$locator}' element exists and should not exist";
d1e55a47
DM
633 $exception = new ExpectationException($msg, $this->getSession());
634
d10ed4d2
AN
635 // Normalise the values in order to perform the search.
636 [
637 'selector' => $selector,
638 'locator' => $locator,
639 'container' => $container,
640 ] = $this->normalise_selector($selectortype, $locator, $this->getSession()->getPage());
641
c1faf86b 642 // It will stop spinning once the find() method returns false.
d1e55a47 643 $this->spin(
d10ed4d2
AN
644 function() use ($selector, $locator, $container) {
645 if ($container->find($selector, $locator)) {
646 return false;
d1e55a47 647 }
d10ed4d2 648 return true;
d1e55a47 649 },
d10ed4d2
AN
650 // Note: We cannot use $this because the find will then be $this->find(), which leads us to a nested spin().
651 // We cannot nest spins because the outer spin times out before the inner spin completes.
652 [],
05a5d547 653 self::get_extended_timeout(),
d1e55a47
DM
654 $exception,
655 true
656 );
657 }
658
659 /**
660 * Ensures that the provided node is visible and we can interact with it.
661 *
662 * @throws ExpectationException
663 * @param NodeElement $node
664 * @return void Throws an exception if it times out without the element being visible
665 */
666 protected function ensure_node_is_visible($node) {
667
668 if (!$this->running_javascript()) {
669 return;
670 }
671
672 // Exception if it timesout and the element is still there.
c1faf86b 673 $msg = 'The "' . $node->getXPath() . '" xpath node is not visible and it should be visible';
d1e55a47
DM
674 $exception = new ExpectationException($msg, $this->getSession());
675
c1faf86b 676 // It will stop spinning once the isVisible() method returns true.
d1e55a47
DM
677 $this->spin(
678 function($context, $args) {
679 if ($args->isVisible()) {
680 return true;
681 }
c1faf86b 682 return false;
d1e55a47
DM
683 },
684 $node,
05a5d547 685 self::get_extended_timeout(),
d1e55a47
DM
686 $exception,
687 true
688 );
689 }
690
3df6e801
RT
691 /**
692 * Ensures that the provided node has a attribute value set. This step can be used to check if specific
693 * JS has finished modifying the node.
694 *
695 * @throws ExpectationException
696 * @param NodeElement $node
697 * @param string $attribute attribute name
698 * @param string $attributevalue attribute value to check.
699 * @return void Throws an exception if it times out without the element being visible
700 */
701 protected function ensure_node_attribute_is_set($node, $attribute, $attributevalue) {
702
703 if (!$this->running_javascript()) {
704 return;
705 }
706
707 // Exception if it timesout and the element is still there.
708 $msg = 'The "' . $node->getXPath() . '" xpath node is not visible and it should be visible';
709 $exception = new ExpectationException($msg, $this->getSession());
710
711 // It will stop spinning once the $args[1]) == $args[2], and method returns true.
712 $this->spin(
713 function($context, $args) {
714 if ($args[0]->getAttribute($args[1]) == $args[2]) {
715 return true;
716 }
717 return false;
718 },
719 array($node, $attribute, $attributevalue),
05a5d547 720 self::get_extended_timeout(),
3df6e801
RT
721 $exception,
722 true
723 );
724 }
725
d1e55a47
DM
726 /**
727 * Ensures that the provided element is visible and we can interact with it.
728 *
729 * Returns the node in case other actions are interested in using it.
730 *
731 * @throws ExpectationException
732 * @param string $element
733 * @param string $selectortype
734 * @return NodeElement Throws an exception if it times out without being visible
735 */
736 protected function ensure_element_is_visible($element, $selectortype) {
737
738 if (!$this->running_javascript()) {
739 return;
740 }
741
742 $node = $this->get_selected_node($selectortype, $element);
743 $this->ensure_node_is_visible($node);
744
745 return $node;
746 }
747
748 /**
749 * Ensures that all the page's editors are loaded.
750 *
9f07f05a 751 * @deprecated since Moodle 2.7 MDL-44084 - please do not use this function any more.
d1e55a47 752 * @throws ElementNotFoundException
c1faf86b 753 * @throws ExpectationException
d1e55a47
DM
754 * @return void
755 */
756 protected function ensure_editors_are_loaded() {
786ced99
DW
757 global $CFG;
758
759 if (empty($CFG->behat_usedeprecated)) {
760 debugging('Function behat_base::ensure_editors_are_loaded() is deprecated. It is no longer required.');
761 }
9f07f05a 762 return;
d1e55a47 763 }
c1faf86b 764
66901a69 765 /**
766 * Checks if the current scenario, or its feature, has a specified tag.
767 *
768 * @param string $tag Tag to check
769 * @return bool True if the tag exists in scenario or feature
770 */
771 public function has_tag(string $tag) : bool {
772 return array_key_exists($tag, behat_hooks::get_tags_for_scenario());
773 }
774
3b0b5e57
RT
775 /**
776 * Change browser window size.
777 * - small: 640x480
778 * - medium: 1024x768
779 * - large: 2560x1600
780 *
781 * @param string $windowsize size of window.
5a14c4d9 782 * @param bool $viewport If true, changes viewport rather than window size
3b0b5e57
RT
783 * @throws ExpectationException
784 */
5a14c4d9 785 protected function resize_window($windowsize, $viewport = false) {
3233f32d
RT
786 // Non JS don't support resize window.
787 if (!$this->running_javascript()) {
788 return;
789 }
790
3b0b5e57
RT
791 switch ($windowsize) {
792 case "small":
3d18e5cf
AN
793 $width = 1024;
794 $height = 768;
3b0b5e57
RT
795 break;
796 case "medium":
3d18e5cf 797 $width = 1366;
3b0b5e57
RT
798 $height = 768;
799 break;
800 case "large":
801 $width = 2560;
802 $height = 1600;
803 break;
804 default:
3233f32d 805 preg_match('/^(\d+x\d+)$/', $windowsize, $matches);
3b0b5e57
RT
806 if (empty($matches) || (count($matches) != 2)) {
807 throw new ExpectationException("Invalid screen size, can't resize", $this->getSession());
808 }
809 $size = explode('x', $windowsize);
810 $width = (int) $size[0];
811 $height = (int) $size[1];
812 }
5a14c4d9 813 if ($viewport) {
814 // When setting viewport size, we set it so that the document width will be exactly
815 // as specified, assuming that there is a vertical scrollbar. (In cases where there is
816 // no scrollbar it will be slightly wider. We presume this is rare and predictable.)
817 // The window inner height will be as specified, which means the available viewport will
818 // actually be smaller if there is a horizontal scrollbar. We assume that horizontal
819 // scrollbars are rare so this doesn't matter.
cd6eadd4
AN
820 $js = <<<EOF
821return (function() {
822 var before = document.body.style.overflowY;
823 document.body.style.overflowY = "scroll";
824 var result = {};
825 result.x = window.outerWidth - document.body.offsetWidth;
826 result.y = window.outerHeight - window.innerHeight;
827 document.body.style.overflowY = before;
828 return result;
829})();
830EOF;
831 $offset = $this->evaluate_script($js);
5a14c4d9 832 $width += $offset['x'];
833 $height += $offset['y'];
834 }
835
3b0b5e57
RT
836 $this->getSession()->getDriver()->resizeWindow($width, $height);
837 }
07298309
RT
838
839 /**
840 * Waits for all the JS to be loaded.
841 *
7bfb575f 842 * @return bool Whether any JS is still pending completion.
07298309
RT
843 */
844 public function wait_for_pending_js() {
07298309 845 if (!$this->running_javascript()) {
7bfb575f
AN
846 // JS is not available therefore there is nothing to wait for.
847 return false;
07298309
RT
848 }
849
7bfb575f
AN
850 return static::wait_for_pending_js_in_session($this->getSession());
851 }
852
853 /**
854 * Waits for all the JS to be loaded.
855 *
856 * @param Session $session The Mink Session where JS can be run
857 * @return bool Whether any JS is still pending completion.
858 */
859 public static function wait_for_pending_js_in_session(Session $session) {
07298309
RT
860 // We don't use behat_base::spin() here as we don't want to end up with an exception
861 // if the page & JSs don't finish loading properly.
05a5d547 862 for ($i = 0; $i < self::get_extended_timeout() * 10; $i++) {
07298309
RT
863 $pending = '';
864 try {
7bfb575f 865 $jscode = trim(preg_replace('/\s+/', ' ', '
5536bf4f 866 return (function() {
d8892dcc
NDM
867 if (document.readyState !== "complete") {
868 return "incomplete";
869 }
870
871 if (typeof M !== "object" || typeof M.util !== "object" || typeof M.util.pending_js === "undefined") {
07298309 872 return "";
07298309 873 }
d8892dcc
NDM
874
875 return M.util.pending_js.join(":");
cd6eadd4
AN
876 })()'));
877 $pending = self::evaluate_script_in_session($session, $jscode);
07298309
RT
878 } catch (NoSuchWindow $nsw) {
879 // We catch an exception here, in case we just closed the window we were interacting with.
880 // No javascript is running if there is no window right?
881 $pending = '';
882 } catch (UnknownError $e) {
883 // M is not defined when the window or the frame don't exist anymore.
884 if (strstr($e->getMessage(), 'M is not defined') != false) {
885 $pending = '';
886 }
887 }
888
889 // If there are no pending JS we stop waiting.
890 if ($pending === '') {
891 return true;
892 }
893
894 // 0.1 seconds.
895 usleep(100000);
896 }
897
7bfb575f 898 // Timeout waiting for JS to complete. It will be caught and forwarded to behat_hooks::i_look_for_exceptions().
05a5d547 899 // It is unlikely that Javascript code of a page or an AJAX request needs more than get_extended_timeout() seconds
07298309
RT
900 // to be loaded, although when pages contains Javascript errors M.util.js_complete() can not be executed, so the
901 // number of JS pending code and JS completed code will not match and we will reach this point.
05a5d547 902 throw new \Exception('Javascript code and/or AJAX requests are not ready after ' .
903 self::get_extended_timeout() .
82ee6f0d
JB
904 ' seconds. There is a Javascript error or the code is extremely slow (' . $pending .
905 '). If you are using a slow machine, consider setting $CFG->behat_increasetimeout.');
07298309 906 }
eb9ca848
RT
907
908 /**
909 * Internal step definition to find exceptions, debugging() messages and PHP debug messages.
910 *
911 * Part of behat_hooks class as is part of the testing framework, is auto-executed
912 * after each step so no features will splicitly use it.
913 *
914 * @throws Exception Unknown type, depending on what we caught in the hook or basic \Exception.
915 * @see Moodle\BehatExtension\Tester\MoodleStepTester
916 */
917 public function look_for_exceptions() {
918 // Wrap in try in case we were interacting with a closed window.
919 try {
920
921 // Exceptions.
922 $exceptionsxpath = "//div[@data-rel='fatalerror']";
923 // Debugging messages.
924 $debuggingxpath = "//div[@data-rel='debugging']";
925 // PHP debug messages.
926 $phperrorxpath = "//div[@data-rel='phpdebugmessage']";
927 // Any other backtrace.
928 $othersxpath = "(//*[contains(., ': call to ')])[1]";
929
930 $xpaths = array($exceptionsxpath, $debuggingxpath, $phperrorxpath, $othersxpath);
931 $joinedxpath = implode(' | ', $xpaths);
932
933 // Joined xpath expression. Most of the time there will be no exceptions, so this pre-check
934 // is faster than to send the 4 xpath queries for each step.
935 if (!$this->getSession()->getDriver()->find($joinedxpath)) {
0c1bcb63
RT
936 // Check if we have recorded any errors in driver process.
937 $phperrors = behat_get_shutdown_process_errors();
938 if (!empty($phperrors)) {
939 foreach ($phperrors as $error) {
940 $errnostring = behat_get_error_string($error['type']);
941 $msgs[] = $errnostring . ": " .$error['message'] . " at " . $error['file'] . ": " . $error['line'];
942 }
943 $msg = "PHP errors found:\n" . implode("\n", $msgs);
944 throw new \Exception(htmlentities($msg));
945 }
946
eb9ca848
RT
947 return;
948 }
949
950 // Exceptions.
951 if ($errormsg = $this->getSession()->getPage()->find('xpath', $exceptionsxpath)) {
952
953 // Getting the debugging info and the backtrace.
954 $errorinfoboxes = $this->getSession()->getPage()->findAll('css', 'div.alert-error');
63e4df60
DW
955 // If errorinfoboxes is empty, try find alert-danger (bootstrap4) class.
956 if (empty($errorinfoboxes)) {
957 $errorinfoboxes = $this->getSession()->getPage()->findAll('css', 'div.alert-danger');
958 }
eb9ca848
RT
959 // If errorinfoboxes is empty, try find notifytiny (original) class.
960 if (empty($errorinfoboxes)) {
961 $errorinfoboxes = $this->getSession()->getPage()->findAll('css', 'div.notifytiny');
962 }
0c1bcb63
RT
963
964 // If errorinfoboxes is empty, try find ajax/JS exception in dialogue.
965 if (empty($errorinfoboxes)) {
966 $errorinfoboxes = $this->getSession()->getPage()->findAll('css', 'div.moodle-exception-message');
967
968 // If ajax/JS exception.
969 if ($errorinfoboxes) {
970 $errorinfo = $this->get_debug_text($errorinfoboxes[0]->getHtml());
971 }
972
973 } else {
974 $errorinfo = $this->get_debug_text($errorinfoboxes[0]->getHtml()) . "\n" .
975 $this->get_debug_text($errorinfoboxes[1]->getHtml());
976 }
eb9ca848
RT
977
978 $msg = "Moodle exception: " . $errormsg->getText() . "\n" . $errorinfo;
979 throw new \Exception(html_entity_decode($msg));
980 }
981
982 // Debugging messages.
983 if ($debuggingmessages = $this->getSession()->getPage()->findAll('xpath', $debuggingxpath)) {
984 $msgs = array();
985 foreach ($debuggingmessages as $debuggingmessage) {
986 $msgs[] = $this->get_debug_text($debuggingmessage->getHtml());
987 }
988 $msg = "debugging() message/s found:\n" . implode("\n", $msgs);
989 throw new \Exception(html_entity_decode($msg));
990 }
991
992 // PHP debug messages.
993 if ($phpmessages = $this->getSession()->getPage()->findAll('xpath', $phperrorxpath)) {
994
995 $msgs = array();
996 foreach ($phpmessages as $phpmessage) {
997 $msgs[] = $this->get_debug_text($phpmessage->getHtml());
998 }
999 $msg = "PHP debug message/s found:\n" . implode("\n", $msgs);
1000 throw new \Exception(html_entity_decode($msg));
1001 }
1002
1003 // Any other backtrace.
1004 // First looking through xpath as it is faster than get and parse the whole page contents,
1005 // we get the contents and look for matches once we found something to suspect that there is a backtrace.
1006 if ($this->getSession()->getDriver()->find($othersxpath)) {
1007 $backtracespattern = '/(line [0-9]* of [^:]*: call to [\->&;:a-zA-Z_\x7f-\xff][\->&;:a-zA-Z0-9_\x7f-\xff]*)/';
1008 if (preg_match_all($backtracespattern, $this->getSession()->getPage()->getContent(), $backtraces)) {
1009 $msgs = array();
1010 foreach ($backtraces[0] as $backtrace) {
1011 $msgs[] = $backtrace . '()';
1012 }
1013 $msg = "Other backtraces found:\n" . implode("\n", $msgs);
1014 throw new \Exception(htmlentities($msg));
1015 }
1016 }
1017
1018 } catch (NoSuchWindow $e) {
1019 // If we were interacting with a popup window it will not exists after closing it.
b095b36c
MN
1020 } catch (DriverException $e) {
1021 // Same reason as above.
eb9ca848
RT
1022 }
1023 }
1024
8918a811
DM
1025 /**
1026 * Converts HTML tags to line breaks to display the info in CLI
1027 *
1028 * @param string $html
1029 * @return string
1030 */
1031 protected function get_debug_text($html) {
1032
1033 // Replacing HTML tags for new lines and keeping only the text.
1034 $notags = preg_replace('/<+\s*\/*\s*([A-Z][A-Z0-9]*)\b[^>]*\/*\s*>*/i', "\n", $html);
1035 return preg_replace("/(\n)+/s", "\n", $notags);
1036 }
1037
eb9ca848
RT
1038 /**
1039 * Helper function to execute api in a given context.
1040 *
1041 * @param string $contextapi context in which api is defined.
1042 * @param array $params list of params to pass.
1043 * @throws Exception
1044 */
1045 protected function execute($contextapi, $params = array()) {
1046 if (!is_array($params)) {
1047 $params = array($params);
1048 }
1049
1050 // Get required context and execute the api.
1051 $contextapi = explode("::", $contextapi);
1052 $context = behat_context_helper::get($contextapi[0]);
1053 call_user_func_array(array($context, $contextapi[1]), $params);
1054
1055 // NOTE: Wait for pending js and look for exception are not optional, as this might lead to unexpected results.
1056 // Don't make them optional for performance reasons.
1057
1058 // Wait for pending js.
1059 $this->wait_for_pending_js();
1060
1061 // Look for exceptions.
1062 $this->look_for_exceptions();
1063 }
353e7876 1064
1065 /**
1066 * Get the actual user in the behat session (note $USER does not correspond to the behat session's user).
1067 * @return mixed
1068 * @throws coding_exception
1069 */
1070 protected function get_session_user() {
1071 global $DB;
1072
1073 $sid = $this->getSession()->getCookie('MoodleSession');
1074 if (empty($sid)) {
1075 throw new coding_exception('failed to get moodle session');
1076 }
1077 $userid = $DB->get_field('sessions', 'userid', ['sid' => $sid]);
1078 if (empty($userid)) {
1079 throw new coding_exception('failed to get user from seession id '.$sid);
1080 }
1081 return $DB->get_record('user', ['id' => $userid]);
1082 }
01f2a530 1083
1084 /**
a1909105 1085 * Set current $USER, reset access cache.
9b1fc262
SL
1086 *
1087 * In some cases, behat will execute the code as admin but in many cases we need to set an specific user as some
1088 * API's might rely on the logged user to take some action.
1089 *
a1909105 1090 * @param null|int|stdClass $user user record, null or 0 means non-logged-in, positive integer means userid
a1909105
SL
1091 */
1092 public static function set_user($user = null) {
1093 global $DB;
1094
1095 if (is_object($user)) {
1096 $user = clone($user);
1097 } else if (!$user) {
1098 // Assign valid data to admin user (some generator-related code needs a valid user).
1099 $user = $DB->get_record('user', array('username' => 'admin'));
1100 } else {
9b1fc262 1101 $user = $DB->get_record('user', array('id' => $user));
a1909105
SL
1102 }
1103 unset($user->description);
1104 unset($user->access);
1105 unset($user->preference);
1106
9b1fc262 1107 // Ensure session is empty, as it may contain caches and user specific info.
a1909105
SL
1108 \core\session\manager::init_empty_session();
1109
1110 \core\session\manager::set_user($user);
1111 }
1112 /**
01f2a530 1113 * Trigger click on node via javascript instead of actually clicking on it via pointer.
1114 *
1115 * This function resolves the issue of nested elements with click listeners or links - in these cases clicking via
1116 * the pointer may accidentally cause a click on the wrong element.
1117 * Example of issue: clicking to expand navigation nodes when the config value linkadmincategories is enabled.
1118 * @param NodeElement $node
1119 */
1120 protected function js_trigger_click($node) {
1121 if (!$this->running_javascript()) {
1122 $node->click();
1123 }
1124 $this->ensure_node_is_visible($node); // Ensures hidden elements can't be clicked.
1125 $xpath = $node->getXpath();
b5be3875
MN
1126 $driver = $this->getSession()->getDriver();
1127 if ($driver instanceof \Moodle\BehatExtension\Driver\MoodleSelenium2Driver) {
1128 $script = "Syn.click({{ELEMENT}})";
1129 $driver->triggerSynScript($xpath, $script);
1130 } else {
1131 $driver->click($xpath);
1132 }
01f2a530 1133 }
05a5d547 1134
4024556b
TH
1135 /**
1136 * Convert page names to URLs for steps like 'When I am on the "[page name]" page'.
1137 *
1138 * You should override this as appropriate for your plugin. The method
1139 * {@link behat_navigation::resolve_core_page_url()} is a good example.
1140 *
1141 * Your overridden method should document the recognised page types with
1142 * a table like this:
1143 *
1144 * Recognised page names are:
1145 * | Page | Description |
1146 *
1147 * @param string $page name of the page, with the component name removed e.g. 'Admin notification'.
1148 * @return moodle_url the corresponding URL.
1149 * @throws Exception with a meaningful error message if the specified page cannot be found.
1150 */
1151 protected function resolve_page_url(string $page): moodle_url {
1152 throw new Exception('Component "' . get_class($this) .
1153 '" does not support the generic \'When I am on the "' . $page .
1154 '" page\' navigation step.');
1155 }
1156
1157 /**
1158 * Convert page names to URLs for steps like 'When I am on the "[identifier]" "[page type]" page'.
1159 *
1160 * A typical example might be:
1161 * When I am on the "Test quiz" "mod_quiz > Responses report" page
1162 * which would cause this method in behat_mod_quiz to be called with
1163 * arguments 'Responses report', 'Test quiz'.
1164 *
1165 * You should override this as appropriate for your plugin. The method
1166 * {@link behat_navigation::resolve_core_page_instance_url()} is a good example.
1167 *
1168 * Your overridden method should document the recognised page types with
1169 * a table like this:
1170 *
1171 * Recognised page names are:
1172 * | Type | identifier meaning | Description |
1173 *
1174 * @param string $type identifies which type of page this is, e.g. 'Attempt review'.
1175 * @param string $identifier identifies the particular page, e.g. 'Test quiz > student > Attempt 1'.
1176 * @return moodle_url the corresponding URL.
1177 * @throws Exception with a meaningful error message if the specified page cannot be found.
1178 */
1179 protected function resolve_page_instance_url(string $type, string $identifier): moodle_url {
1180 throw new Exception('Component "' . get_class($this) .
1181 '" does not support the generic \'When I am on the "' . $identifier .
1182 '" "' . $type . '" page\' navigation step.');
1183 }
1184
05a5d547 1185 /**
1186 * Gets the required timeout in seconds.
1187 *
1188 * @param int $timeout One of the TIMEOUT constants
1189 * @return int Actual timeout (in seconds)
1190 */
1191 protected static function get_real_timeout(int $timeout) : int {
1192 global $CFG;
1193 if (!empty($CFG->behat_increasetimeout)) {
1194 return $timeout * $CFG->behat_increasetimeout;
1195 } else {
1196 return $timeout;
1197 }
1198 }
1199
1200 /**
1201 * Gets the default timeout.
1202 *
1203 * The timeout for each Behat step (load page, wait for an element to load...).
1204 *
1205 * @return int Timeout in seconds
1206 */
1207 public static function get_timeout() : int {
1208 return self::get_real_timeout(6);
1209 }
1210
1211 /**
1212 * Gets the reduced timeout.
1213 *
1214 * A reduced timeout for cases where self::get_timeout() is too much
1215 * and a simple $this->getSession()->getPage()->find() could not
1216 * be enough.
1217 *
1218 * @return int Timeout in seconds
1219 */
1220 public static function get_reduced_timeout() : int {
1221 return self::get_real_timeout(2);
1222 }
1223
1224 /**
1225 * Gets the extended timeout.
1226 *
1227 * A longer timeout for cases where the normal timeout is not enough.
1228 *
1229 * @return int Timeout in seconds
1230 */
1231 public static function get_extended_timeout() : int {
1232 return self::get_real_timeout(10);
1233 }
61832fae
AN
1234
1235 /**
1236 * Return a list of the exact named selectors for the component.
1237 *
33da028c
TH
1238 * Named selectors are what make Behat steps like
1239 * Then I should see "Useful text" in the "General" "fieldset"
1240 * work. Here, "fieldset" is the named selector, and "General" is the locator.
1241 *
1242 * If you override this method in your plugin (e.g. mod_mymod), to define
1243 * new selectors specific to your plugin. For example, if you returned
1244 * new behat_component_named_selector('Thingy',
1245 * [".//some/xpath//img[contains(@alt, %locator%)]/.."])
1246 * then
1247 * Then I should see "Useful text" in the "Whatever" "mod_mymod > Thingy"
1248 * would work.
1249 *
1250 * This method should return a list of {@link behat_component_named_selector} and
1251 * the docs on that class explain how it works.
1252 *
61832fae
AN
1253 * @return behat_component_named_selector[]
1254 */
1255 public static function get_exact_named_selectors(): array {
1256 return [];
1257 }
1258
1259 /**
1260 * Return a list of the partial named selectors for the component.
1261 *
33da028c
TH
1262 * Like the exact named selectors above, but the locator only
1263 * needs to match part of the text. For example, the standard
1264 * "button" is a partial selector, so:
1265 * When I click "Save" "button"
1266 * will activate "Save changes".
1267 *
61832fae
AN
1268 * @return behat_component_named_selector[]
1269 */
1270 public static function get_partial_named_selectors(): array {
1271 return [];
1272 }
1273
1274 /**
33da028c
TH
1275 * Return a list of the Mink named replacements for the component.
1276 *
1277 * Named replacements allow you to define parts of an xpath that can be reused multiple times, or in multiple
1278 * xpaths.
1279 *
1280 * This method should return a list of {@link behat_component_named_replacement} and the docs on that class explain
1281 * how it works.
61832fae
AN
1282 *
1283 * @return behat_component_named_replacement[]
1284 */
1285 public static function get_named_replacements(): array {
1286 return [];
1287 }
6d5d1935
AN
1288
1289 /**
1290 * Evaluate the supplied script in the current session, returning the result.
1291 *
1292 * @param string $script
1293 * @return mixed
1294 */
1295 public function evaluate_script(string $script) {
1296 return self::evaluate_script_in_session($this->getSession(), $script);
1297 }
1298
1299 /**
1300 * Evaluate the supplied script in the specified session, returning the result.
1301 *
1302 * @param Session $session
1303 * @param string $script
1304 * @return mixed
1305 */
1306 public static function evaluate_script_in_session(Session $session, string $script) {
1307 self::require_javascript_in_session($session);
1308
1309 return $session->evaluateScript($script);
1310 }
1311
1312 /**
1313 * Execute the supplied script in the current session.
1314 *
1315 * No result will be returned.
1316 *
1317 * @param string $script
1318 */
1319 public function execute_script(string $script): void {
1320 self::execute_script_in_session($this->getSession(), $script);
1321 }
1322
1323 /**
1324 * Excecute the supplied script in the specified session.
1325 *
1326 * No result will be returned.
1327 *
1328 * @param Session $session
1329 * @param string $script
1330 */
1331 public static function execute_script_in_session(Session $session, string $script): void {
1332 self::require_javascript_in_session($session);
1333
1334 $session->executeScript($script);
1335 }
083604ea
AN
1336
1337 /**
1338 * Get the session key for the current session via Javascript.
1339 *
1340 * @return string
1341 */
1342 public function get_sesskey(): string {
1343 $script = <<<EOF
1344return (function() {
1345if (M && M.cfg && M.cfg.sesskey) {
1346 return M.cfg.sesskey;
1347}
1348return '';
1349})()
1350EOF;
1351
1352 return $this->evaluate_script($script);
1353 }
d4322e38 1354}