Proyectos de Subversion Moodle

Rev

Rev 11 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 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
 * A trait containing functionality used by the behat base context, and form fields.
19
 *
20
 * @package    core
21
 * @category   test
22
 * @copyright  2020 Andrew Nicols <andrew@nicols.co.uk>
23
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24
 */
25
 
26
use Behat\Mink\Element\NodeElement;
27
use Behat\Mink\Element\Element;
28
use Behat\Mink\Exception\DriverException;
29
use Behat\Mink\Exception\ExpectationException;
30
use Behat\Mink\Exception\ElementNotFoundException;
31
use Behat\Mink\Exception\NoSuchWindowException;
32
use Behat\Mink\Session;
33
use Behat\Testwork\Hook\Scope\HookScope;
34
use Facebook\WebDriver\Exception\ScriptTimeoutException;
35
use Facebook\WebDriver\WebDriverBy;
36
use Facebook\WebDriver\WebDriverElement;
37
 
38
// NOTE: no MOODLE_INTERNAL test here, this file may be required by behat before including /config.php.
39
 
40
require_once(__DIR__ . '/component_named_replacement.php');
41
require_once(__DIR__ . '/component_named_selector.php');
42
 
43
// Alias the Facebook\WebDriver\WebDriverKeys class to behat_keys for better b/c with the older Instaclick driver.
44
class_alias('Facebook\WebDriver\WebDriverKeys', 'behat_keys');
45
 
46
/**
47
 * A trait containing functionality used by the behat base context, and form fields.
48
 *
49
 * This trait should be used by the behat_base context, and behat form fields, and it should be paired with the
50
 * behat_session_interface interface.
51
 *
52
 * It should not be necessary to use this trait, and the behat_session_interface interface in normal circumstances.
53
 *
54
 * @package    core
55
 * @category   test
56
 * @copyright  2020 Andrew Nicols <andrew@nicols.co.uk>
57
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
58
 */
59
trait behat_session_trait {
60
 
61
    /**
62
     * Locates url, based on provided path.
63
     * Override to provide custom routing mechanism.
64
     *
65
     * @see Behat\MinkExtension\Context\MinkContext
66
     * @param string $path
67
     * @return string
68
     */
69
    protected function locate_path($path) {
70
        $starturl = rtrim($this->getMinkParameter('base_url'), '/') . '/';
71
        return 0 !== strpos($path, 'http') ? $starturl . ltrim($path, '/') : $path;
72
    }
73
 
74
    /**
75
     * Returns the first matching element.
76
     *
77
     * @link http://mink.behat.org/#traverse-the-page-selectors
78
     * @param string $selector The selector type (css, xpath, named...)
79
     * @param mixed $locator It depends on the $selector, can be the xpath, a name, a css locator...
80
     * @param Exception $exception Otherwise we throw exception with generic info
81
     * @param NodeElement $node Spins around certain DOM node instead of the whole page
82
     * @param int $timeout Forces a specific time out (in seconds).
83
     * @return NodeElement
84
     */
85
    protected function find($selector, $locator, $exception = false, $node = false, $timeout = false) {
86
        if ($selector === 'NodeElement' && is_a($locator, NodeElement::class)) {
87
            // Support a NodeElement being passed in for use in step chaining.
88
            return $locator;
89
        }
90
 
91
        // Returns the first match.
92
        $items = $this->find_all($selector, $locator, $exception, $node, $timeout);
93
        return count($items) ? reset($items) : null;
94
    }
95
 
96
    /**
97
     * Returns all matching elements.
98
     *
99
     * Adapter to Behat\Mink\Element\Element::findAll() using the spin() method.
100
     *
101
     * @link http://mink.behat.org/#traverse-the-page-selectors
102
     * @param string $selector The selector type (css, xpath, named...)
103
     * @param mixed $locator It depends on the $selector, can be the xpath, a name, a css locator...
104
     * @param Exception $exception Otherwise we throw expcetion with generic info
105
     * @param NodeElement $container Restrict the search to just children of the specified container
106
     * @param int $timeout Forces a specific time out (in seconds). If 0 is provided the default timeout will be applied.
107
     * @return array NodeElements list
108
     */
109
    protected function find_all($selector, $locator, $exception = false, $container = false, $timeout = false) {
110
        // Throw exception, so dev knows it is not supported.
111
        if ($selector === 'named') {
112
            $exception = 'Using the "named" selector is deprecated as of 3.1. '
113
                .' Use the "named_partial" or use the "named_exact" selector instead.';
114
            throw new ExpectationException($exception, $this->getSession());
115
        }
116
 
117
        // Generic info.
118
        if (!$exception) {
119
            // With named selectors we can be more specific.
120
            if (($selector == 'named_exact') || ($selector == 'named_partial')) {
121
                $exceptiontype = $locator[0];
122
                $exceptionlocator = $locator[1];
123
 
124
                // If we are in a @javascript session all contents would be displayed as HTML characters.
125
                if ($this->running_javascript()) {
126
                    $locator[1] = html_entity_decode($locator[1], ENT_NOQUOTES);
127
                }
128
 
129
            } else {
130
                $exceptiontype = $selector;
131
                $exceptionlocator = $locator;
132
            }
133
 
134
            $exception = new ElementNotFoundException($this->getSession(), $exceptiontype, null, $exceptionlocator);
135
        }
136
 
137
        // How much we will be waiting for the element to appear.
138
        if ($timeout === false) {
139
            $timeout = self::get_timeout();
140
            $microsleep = false;
141
        } else {
142
            // Spinning each 0.1 seconds if the timeout was forced as we understand
143
            // that is a special case and is good to refine the performance as much
144
            // as possible.
145
            $microsleep = true;
146
        }
147
 
148
        // Normalise the values in order to perform the search.
149
        [
150
            'selector' => $selector,
151
            'locator' => $locator,
152
            'container' => $container,
153
        ] = $this->normalise_selector($selector, $locator, $container ?: $this->getSession()->getPage());
154
 
155
        // Waits for the node to appear if it exists, otherwise will timeout and throw the provided exception.
156
        return $this->spin(
157
            function() use ($selector, $locator, $container) {
158
                return $container->findAll($selector, $locator);
159
            }, [], $timeout, $exception, $microsleep
160
        );
161
    }
162
 
163
    /**
164
     * Normalise the locator and selector.
165
     *
166
     * @param string $selector The type of thing to search
167
     * @param mixed $locator The locator value. Can be an array, but is more likely a string.
168
     * @param Element $container An optional container to search within
169
     * @return array The selector, locator, and container to search within
170
     */
171
    public function normalise_selector(string $selector, $locator, Element $container): array {
172
        // Check for specific transformations for this selector type.
173
        $transformfunction = "transform_find_for_{$selector}";
174
        if (method_exists('behat_selectors', $transformfunction)) {
175
            // A selector-specific transformation exists.
176
            // Perform initial transformation of the selector within the current container.
177
            [
178
                'selector' => $selector,
179
                'locator' => $locator,
180
                'container' => $container,
181
            ] = behat_selectors::{$transformfunction}($this, $locator, $container);
182
        }
183
 
184
        // Normalise the css and xpath selector types.
185
        if ('css_element' === $selector) {
186
            $selector = 'css';
187
        } else if ('xpath_element' === $selector) {
188
            $selector = 'xpath';
189
        }
190
 
191
        // Convert to a named selector where the selector type is not a known selector.
192
        $converttonamed = !$this->getSession()->getSelectorsHandler()->isSelectorRegistered($selector);
193
        $converttonamed = $converttonamed && 'xpath' !== $selector;
194
        if ($converttonamed) {
195
            if (behat_partial_named_selector::is_deprecated_selector($selector)) {
196
                if ($replacement = behat_partial_named_selector::get_deprecated_replacement($selector)) {
197
                    error_log("The '{$selector}' selector has been replaced with {$replacement}");
198
                    $selector = $replacement;
199
                }
200
            } else if (behat_exact_named_selector::is_deprecated_selector($selector)) {
201
                if ($replacement = behat_exact_named_selector::get_deprecated_replacement($selector)) {
202
                    error_log("The '{$selector}' selector has been replaced with {$replacement}");
203
                    $selector = $replacement;
204
                }
205
            }
206
 
207
            $allowedpartialselectors = behat_partial_named_selector::get_allowed_selectors();
208
            $allowedexactselectors = behat_exact_named_selector::get_allowed_selectors();
209
            if (isset($allowedpartialselectors[$selector])) {
210
                $locator = behat_selectors::normalise_named_selector($allowedpartialselectors[$selector], $locator);
211
                $selector = 'named_partial';
212
            } else if (isset($allowedexactselectors[$selector])) {
213
                $locator = behat_selectors::normalise_named_selector($allowedexactselectors[$selector], $locator);
214
                $selector = 'named_exact';
215
            } else {
216
                throw new ExpectationException("The '{$selector}' selector type is not registered.", $this->getSession()->getDriver());
217
            }
218
        }
219
 
220
        return [
221
            'selector' => $selector,
222
            'locator' => $locator,
223
            'container' => $container,
224
        ];
225
    }
226
 
227
    /**
228
     * Get a description of the selector and locator to use in an exception message.
229
     *
230
     * @param string $selector The type of locator
231
     * @param mixed $locator The locator text
232
     * @return string
233
     */
234
    protected function get_selector_description(string $selector, $locator): string {
235
        if ($selector === 'NodeElement') {
236
            $description = $locator->getText();
237
            return "'{$description}' {$selector}";
238
        }
239
 
240
        return "'{$locator}' {$selector}";
241
    }
242
 
243
    /**
244
     * Send key presses straight to the currently active element.
245
     *
246
     * The `$keys` array contains a list of key values to send to the session as defined in the WebDriver and JsonWire
247
     * specifications:
248
     * - JsonWire: https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol#sessionsessionidkeys
249
     * - W3C WebDriver: https://www.w3.org/TR/webdriver/#keyboard-actions
250
     *
251
     * This may be a combination of typable characters, modifier keys, and other supported keypoints.
252
     *
253
     * The NULL_KEY should be used to release modifier keys. If the NULL_KEY is not used then modifier keys will remain
254
     * in the pressed state.
255
     *
256
     * Example usage:
257
     *
258
     *      behat_base::type_keys($this->getSession(), [behat_keys::SHIFT, behat_keys::TAB, behat_keys::NULL_KEY]);
259
     *      behat_base::type_keys($this->getSession(), [behat_keys::ENTER, behat_keys::NULL_KEY]);
260
     *      behat_base::type_keys($this->getSession(), [behat_keys::ESCAPE, behat_keys::NULL_KEY]);
261
     *
262
     * It can also be used to send text input, for example:
263
     *
264
     *      behat_base::type_keys(
265
     *          $this->getSession(),
266
     *          ['D', 'o', ' ', 'y', 'o', 'u', ' ', 'p', 'l', 'a' 'y', ' ', 'G', 'o', '?', behat_base::NULL_KEY]
267
     *      );
268
     *
269
     *
270
     * Please note: This function does not use the element/sendKeys variants but sends keys straight to the browser.
271
     *
272
     * @param Session $session
273
     * @param string[] $keys
274
     */
275
    public static function type_keys(Session $session, array $keys): void {
276
        $session->getDriver()->getWebDriver()->getKeyboard()->sendKeys($keys);
277
    }
278
 
279
    /**
280
     * Finds DOM nodes in the page using named selectors.
281
     *
282
     * The point of using this method instead of Mink ones is the spin
283
     * method of behat_base::find() that looks for the element until it
284
     * is available or it timeouts, this avoids the false failures received
285
     * when selenium tries to execute commands on elements that are not
286
     * ready to be used.
287
     *
288
     * All steps that requires elements to be available before interact with
289
     * them should use one of the find* methods.
290
     *
291
     * The methods calls requires a {'find_' . $elementtype}($locator)
292
     * format, like find_link($locator), find_select($locator),
293
     * find_button($locator)...
294
     *
295
     * @link http://mink.behat.org/#named-selectors
296
     * @throws coding_exception
297
     * @param string $name The name of the called method
298
     * @param mixed $arguments
299
     * @return NodeElement
300
     */
301
    public function __call($name, $arguments) {
302
        if (substr($name, 0, 5) === 'find_') {
303
            return call_user_func_array([$this, 'find'], array_merge(
304
                [substr($name, 5)],
305
                $arguments
306
            ));
307
        }
308
 
309
        throw new coding_exception("The '{$name}' method does not exist");
310
    }
311
 
312
    /**
313
     * Escapes the double quote character.
314
     *
315
     * Double quote is the argument delimiter, it can be escaped
316
     * with a backslash, but we auto-remove this backslashes
317
     * before the step execution, this method is useful when using
318
     * arguments as arguments for other steps.
319
     *
320
     * @param string $string
321
     * @return string
322
     */
323
    public function escape($string) {
324
        return str_replace('"', '\"', $string);
325
    }
326
 
327
    /**
328
     * Executes the passed closure until returns true or time outs.
329
     *
330
     * In most cases the document.readyState === 'complete' will be enough, but sometimes JS
331
     * requires more time to be completely loaded or an element to be visible or whatever is required to
332
     * perform some action on an element; this method receives a closure which should contain the
333
     * required statements to ensure the step definition actions and assertions have all their needs
334
     * satisfied and executes it until they are satisfied or it timeouts. Redirects the return of the
335
     * closure to the caller.
336
     *
337
     * The closures requirements to work well with this spin method are:
338
     * - Must return false, null or '' if something goes wrong
339
     * - Must return something != false if finishes as expected, this will be the (mixed) value
340
     * returned by spin()
341
     *
342
     * The arguments of the closure are mixed, use $args depending on your needs.
343
     *
344
     * You can provide an exception to give more accurate feedback to tests writers, otherwise the
345
     * closure exception will be used, but you must provide an exception if the closure does not throw
346
     * an exception.
347
     *
348
     * @throws Exception If it timeouts without receiving something != false from the closure
349
     * @param callable $lambda The function to execute or an array passed to call_user_func (maps to a class method)
350
     * @param mixed $args Arguments to pass to the closure
351
     * @param int $timeout Timeout in seconds
352
     * @param Exception $exception The exception to throw in case it time outs.
353
     * @param bool $microsleep If set to true it'll sleep micro seconds rather than seconds.
354
     * @return mixed The value returned by the closure
355
     */
356
    protected function spin($lambda, $args = false, $timeout = false, $exception = false, $microsleep = false) {
357
 
358
        // Using default timeout which is pretty high.
359
        if ($timeout === false) {
360
            $timeout = self::get_timeout();
361
        }
362
 
363
        $start = microtime(true);
364
        $end = $start + $timeout;
365
 
366
        do {
367
            // We catch the exception thrown by the step definition to execute it again.
368
            try {
369
                // We don't check with !== because most of the time closures will return
370
                // direct Behat methods returns and we are not sure it will be always (bool)false
371
                // if it just runs the behat method without returning anything $return == null.
372
                if ($return = call_user_func($lambda, $this, $args)) {
373
                    return $return;
374
                }
375
            } catch (Exception $e) {
376
                // We would use the first closure exception if no exception has been provided.
377
                if (!$exception) {
378
                    $exception = $e;
379
                }
380
            }
381
 
382
            if (!$this->running_javascript()) {
383
                break;
384
            }
385
 
386
            usleep(100000);
387
 
388
        } while (microtime(true) < $end);
389
 
390
        // Using coding_exception as is a development issue if no exception has been provided.
391
        if (!$exception) {
392
            $exception = new coding_exception('spin method requires an exception if the callback does not throw an exception');
393
        }
394
 
395
        // Throwing exception to the user.
396
        throw $exception;
397
    }
398
 
399
    /**
400
     * Gets a NodeElement based on the locator and selector type received as argument from steps definitions.
401
     *
402
     * Use behat_base::get_text_selector_node() for text-based selectors.
403
     *
404
     * @throws ElementNotFoundException Thrown by behat_base::find
405
     * @param string $selectortype
406
     * @param string $element
407
     * @return NodeElement
408
     */
409
    protected function get_selected_node($selectortype, $element) {
410
        return $this->find($selectortype, $element);
411
    }
412
 
413
    /**
414
     * Gets a NodeElement based on the locator and selector type received as argument from steps definitions.
415
     *
416
     * @throws ElementNotFoundException Thrown by behat_base::find
417
     * @param string $selectortype
418
     * @param string $element
419
     * @return NodeElement
420
     */
421
    protected function get_text_selector_node($selectortype, $element) {
422
        // Getting Mink selector and locator.
423
        list($selector, $locator) = $this->transform_text_selector($selectortype, $element);
424
 
425
        // Returns the NodeElement.
426
        return $this->find($selector, $locator);
427
    }
428
 
429
    /**
430
     * Gets the requested element inside the specified container.
431
     *
432
     * @throws ElementNotFoundException Thrown by behat_base::find
433
     * @param mixed $selectortype The element selector type.
434
     * @param mixed $element The element locator.
435
     * @param mixed $containerselectortype The container selector type.
436
     * @param mixed $containerelement The container locator.
437
     * @return NodeElement
438
     */
439
    protected function get_node_in_container($selectortype, $element, $containerselectortype, $containerelement) {
440
        if ($containerselectortype === 'NodeElement' && is_a($containerelement, NodeElement::class)) {
441
            // Support a NodeElement being passed in for use in step chaining.
442
            $containernode = $containerelement;
443
        } else {
444
            // Gets the container, it will always be text based.
445
            $containernode = $this->get_text_selector_node($containerselectortype, $containerelement);
446
        }
447
 
448
        $locatorexceptionmsg = $element . '" in the "' . $this->get_selector_description($containerselectortype, $containerelement);
449
        $exception = new ElementNotFoundException($this->getSession(), $selectortype, null, $locatorexceptionmsg);
450
 
451
        return $this->find($selectortype, $element, $exception, $containernode);
452
    }
453
 
454
    /**
455
     * Transforms from step definition's argument style to Mink format.
456
     *
457
     * Mink has 3 different selectors css, xpath and named, where named
458
     * selectors includes link, button, field... to simplify and group multiple
459
     * steps in one we use the same interface, considering all link, buttons...
460
     * at the same level as css selectors and xpath; this method makes the
461
     * conversion from the arguments received by the steps to the selectors and locators
462
     * required to interact with Mink.
463
     *
464
     * @throws ExpectationException
465
     * @param string $selectortype It can be css, xpath or any of the named selectors.
466
     * @param string $element The locator (or string) we are looking for.
467
     * @return array Contains the selector and the locator expected by Mink.
468
     */
469
    protected function transform_selector($selectortype, $element) {
470
        // Here we don't know if an allowed text selector is being used.
471
        $selectors = behat_selectors::get_allowed_selectors();
472
        if (!isset($selectors[$selectortype])) {
473
            throw new ExpectationException('The "' . $selectortype . '" selector type does not exist', $this->getSession());
474
        }
475
 
476
        [
477
            'selector' => $selector,
478
            'locator' => $locator,
479
        ] = $this->normalise_selector($selectortype, $element, $this->getSession()->getPage());
480
 
481
        return [$selector, $locator];
482
    }
483
 
484
    /**
485
     * Transforms from step definition's argument style to Mink format.
486
     *
487
     * Delegates all the process to behat_base::transform_selector() checking
488
     * the provided $selectortype.
489
     *
490
     * @throws ExpectationException
491
     * @param string $selectortype It can be css, xpath or any of the named selectors.
492
     * @param string $element The locator (or string) we are looking for.
493
     * @return array Contains the selector and the locator expected by Mink.
494
     */
495
    protected function transform_text_selector($selectortype, $element) {
496
 
497
        $selectors = behat_selectors::get_allowed_text_selectors();
498
        if (empty($selectors[$selectortype])) {
499
            throw new ExpectationException('The "' . $selectortype . '" selector can not be used to select text nodes', $this->getSession());
500
        }
501
 
502
        return $this->transform_selector($selectortype, $element);
503
    }
504
 
505
    /**
506
     * Whether Javascript is available in the current Session.
507
     *
508
     * @return boolean
509
     */
510
    protected function running_javascript() {
511
        return self::running_javascript_in_session($this->getSession());
512
    }
513
 
514
    /**
515
     * Require that javascript be available in the current Session.
516
     *
517
     * @param null|string $message An additional information message to show when JS is not available
518
     * @throws DriverException
519
     */
520
    protected function require_javascript(?string $message = null) {
521
        return self::require_javascript_in_session($this->getSession(), $message);
522
    }
523
 
524
    /**
525
     * Whether Javascript is available in the specified Session.
526
     *
527
     * @param Session $session
528
     * @return boolean
529
     */
530
    protected static function running_javascript_in_session(Session $session): bool {
531
        return get_class($session->getDriver()) !== 'Behat\Mink\Driver\BrowserKitDriver';
532
    }
533
 
534
    /**
535
     * Require that javascript be available for the specified Session.
536
     *
537
     * @param Session $session
538
     * @param null|string $message An additional information message to show when JS is not available
539
     * @throws DriverException
540
     */
541
    protected static function require_javascript_in_session(Session $session, ?string $message = null): void {
542
        if (self::running_javascript_in_session($session)) {
543
            return;
544
        }
545
 
546
        $error = "Javascript is required for this step.";
547
        if ($message) {
548
            $error = "{$error} {$message}";
549
        }
550
        throw new DriverException($error);
551
    }
552
 
553
    /**
554
     * Checks if the current page is part of the mobile app.
555
     *
556
     * @return bool True if it's in the app
557
     */
558
    protected function is_in_app(): bool {
559
        // Cannot be in the app if there's no @app tag on scenario.
560
        if (!$this->has_tag('app')) {
561
            return false;
562
        }
563
 
564
        // Check on page to see if it's an app page. Safest way is to look for added JavaScript.
565
        return $this->evaluate_script('return typeof window.behat') === 'object';
566
    }
567
 
568
    /**
569
     * Spins around an element until it exists
570
     *
571
     * @throws ExpectationException
572
     * @param string $locator
573
     * @param string $selectortype
574
     * @return void
575
     */
576
    protected function ensure_element_exists($locator, $selectortype) {
577
        // Exception if it timesout and the element is still there.
578
        $msg = "The '{$locator}' element does not exist and should";
579
        $exception = new ExpectationException($msg, $this->getSession());
580
 
581
        // Normalise the values in order to perform the search.
582
        [
583
            'selector' => $selector,
584
            'locator' => $locator,
585
            'container' => $container,
586
        ] = $this->normalise_selector($selectortype, $locator, $this->getSession()->getPage());
587
 
588
        // It will stop spinning once the find() method returns true.
589
        $this->spin(
590
            function() use ($selector, $locator, $container) {
591
                if ($container->find($selector, $locator)) {
592
                    return true;
593
                }
594
                return false;
595
            },
596
            [],
597
            self::get_extended_timeout(),
598
            $exception,
599
            true
600
        );
601
    }
602
 
603
    /**
604
     * Spins until the element does not exist
605
     *
606
     * @throws ExpectationException
607
     * @param string $locator
608
     * @param string $selectortype
609
     * @return void
610
     */
611
    protected function ensure_element_does_not_exist($locator, $selectortype) {
612
        // Exception if it timesout and the element is still there.
613
        $msg = "The '{$locator}' element exists and should not exist";
614
        $exception = new ExpectationException($msg, $this->getSession());
615
 
616
        // Normalise the values in order to perform the search.
617
        [
618
            'selector' => $selector,
619
            'locator' => $locator,
620
            'container' => $container,
621
        ] = $this->normalise_selector($selectortype, $locator, $this->getSession()->getPage());
622
 
623
        // It will stop spinning once the find() method returns false.
624
        $this->spin(
625
            function() use ($selector, $locator, $container) {
626
                if ($container->find($selector, $locator)) {
627
                    return false;
628
                }
629
                return true;
630
            },
631
            // Note: We cannot use $this because the find will then be $this->find(), which leads us to a nested spin().
632
            // We cannot nest spins because the outer spin times out before the inner spin completes.
633
            [],
634
            self::get_extended_timeout(),
635
            $exception,
636
            true
637
        );
638
    }
639
 
640
    /**
641
     * Ensures that the provided node is visible and we can interact with it.
642
     *
643
     * @throws ExpectationException
644
     * @param NodeElement $node
645
     * @return void Throws an exception if it times out without the element being visible
646
     */
647
    protected function ensure_node_is_visible($node) {
648
        if (!$this->running_javascript()) {
649
            return;
650
        }
651
 
652
        // Exception if it timesout and the element is still there.
653
        $msg = 'The "' . $node->getXPath() . '" xpath node is not visible and it should be visible';
654
        $exception = new ExpectationException($msg, $this->getSession());
655
 
656
        // It will stop spinning once the isVisible() method returns true.
657
        $this->spin(
658
            function($context, $args) {
659
                if ($args->isVisible()) {
660
                    return true;
661
                }
662
                return false;
663
            },
664
            $node,
665
            self::get_extended_timeout(),
666
            $exception,
667
            true
668
        );
669
    }
670
 
671
    /**
672
     * Ensures that the provided node has a attribute value set. This step can be used to check if specific
673
     * JS has finished modifying the node.
674
     *
675
     * @throws ExpectationException
676
     * @param NodeElement $node
677
     * @param string $attribute attribute name
678
     * @param string $attributevalue attribute value to check.
679
     * @return void Throws an exception if it times out without the element being visible
680
     */
681
    protected function ensure_node_attribute_is_set($node, $attribute, $attributevalue) {
682
 
683
        if (!$this->running_javascript()) {
684
            return;
685
        }
686
 
687
        // Exception if it timesout and the element is still there.
688
        $msg = 'The "' . $node->getXPath() . '" xpath node is not visible and it should be visible';
689
        $exception = new ExpectationException($msg, $this->getSession());
690
 
691
        // It will stop spinning once the $args[1]) == $args[2], and method returns true.
692
        $this->spin(
693
            function($context, $args) {
694
                if ($args[0]->getAttribute($args[1]) == $args[2]) {
695
                    return true;
696
                }
697
                return false;
698
            },
699
            array($node, $attribute, $attributevalue),
700
            self::get_extended_timeout(),
701
            $exception,
702
            true
703
        );
704
    }
705
 
706
    /**
707
     * Ensures that the provided element is visible and we can interact with it.
708
     *
709
     * Returns the node in case other actions are interested in using it.
710
     *
711
     * @throws ExpectationException
712
     * @param string $element
713
     * @param string $selectortype
714
     * @return NodeElement Throws an exception if it times out without being visible
715
     */
716
    protected function ensure_element_is_visible($element, $selectortype) {
717
        if (!$this->running_javascript()) {
718
            return;
719
        }
720
 
721
        $node = $this->get_selected_node($selectortype, $element);
722
        $this->ensure_node_is_visible($node);
723
 
724
        return $node;
725
    }
726
 
727
    /**
728
     * Checks if the current scenario, or its feature, has a specified tag.
729
     *
730
     * @param string $tag Tag to check
731
     * @return bool True if the tag exists in scenario or feature
732
     */
733
    public function has_tag(string $tag): bool {
734
        return array_key_exists($tag, behat_hooks::get_tags_for_scenario());
735
    }
736
 
737
    /**
738
     * Change browser window size.
739
     *   - mobile: 425x750
740
     *   - tablet: 768x1024
741
     *   - small: 1024x768
742
     *   - medium: 1366x768
743
     *   - large: 2560x1600
744
     *
745
     * @param string $windowsize size of window.
746
     * @param bool $viewport If true, changes viewport rather than window size
1441 ariadna 747
     * @param bool $scalesize Whether to scale the size by the WINDOWSCALE environment variable
1 efrain 748
     * @throws ExpectationException
749
     */
1441 ariadna 750
    protected function resize_window(
751
        string $windowsize,
752
        bool $viewport = false,
753
        bool $scalesize = true,
754
    ): void {
1 efrain 755
        global $CFG;
756
 
757
        // Non JS don't support resize window.
758
        if (!$this->running_javascript()) {
759
            return;
760
        }
761
 
762
        switch ($windowsize) {
763
            case "mobile":
764
                $width = 425;
765
                $height = 750;
766
                break;
767
            case "tablet":
768
                $width = 768;
769
                $height = 1024;
770
                break;
771
            case "small":
772
                $width = 1024;
773
                $height = 768;
774
                break;
775
            case "medium":
776
                $width = 1366;
777
                $height = 768;
778
                break;
779
            case "large":
780
                $width = 2560;
781
                $height = 1600;
782
                break;
783
            default:
784
                preg_match('/^(\d+x\d+)$/', $windowsize, $matches);
785
                if (empty($matches) || (count($matches) != 2)) {
786
                    throw new ExpectationException("Invalid screen size, can't resize", $this->getSession());
787
                }
788
                $size = explode('x', $windowsize);
789
                $width = (int) $size[0];
790
                $height = (int) $size[1];
791
        }
792
 
793
        if (isset($CFG->behat_window_size_modifier) && is_numeric($CFG->behat_window_size_modifier)) {
794
            $width *= $CFG->behat_window_size_modifier;
795
            $height *= $CFG->behat_window_size_modifier;
796
        }
797
 
1441 ariadna 798
        if ($scalesize) {
799
            // Scale the window size by the WINDOWSCALE environment variable.
800
            // This is intended to be used for Behat reruns to negate the impact of browser window size issues.
801
            // This allows a per-run, runtime configuration of the scaling, unlike behat_window_size_modifier which
802
            // typically applies to all runs.
803
            $scalefactor = getenv('WINDOWSCALE') ? floatval(getenv('WINDOWSCALE')) : 1;
804
            $width *= $scalefactor;
805
            $height *= $scalefactor;
806
        }
807
 
1 efrain 808
        if ($viewport) {
809
            // When setting viewport size, we set it so that the document width will be exactly
810
            // as specified, assuming that there is a vertical scrollbar. (In cases where there is
811
            // no scrollbar it will be slightly wider. We presume this is rare and predictable.)
812
            // The window inner height will be as specified, which means the available viewport will
813
            // actually be smaller if there is a horizontal scrollbar. We assume that horizontal
814
            // scrollbars are rare so this doesn't matter.
815
            $js = <<<EOF
816
return (function() {
817
    var before = document.body.style.overflowY;
818
    document.body.style.overflowY = "scroll";
819
    var result = {};
820
    result.x = window.outerWidth - document.body.offsetWidth;
821
    result.y = window.outerHeight - window.innerHeight;
822
    document.body.style.overflowY = before;
823
    return result;
824
})();
825
EOF;
826
            $offset = $this->evaluate_script($js);
827
            $width += $offset['x'];
828
            $height += $offset['y'];
829
        }
830
 
831
        $this->getSession()->getDriver()->resizeWindow($width, $height);
832
    }
833
 
834
    /**
835
     * Waits for all the JS to be loaded.
836
     *
837
     * @return  bool Whether any JS is still pending completion.
838
     */
839
    public function wait_for_pending_js() {
840
        return static::wait_for_pending_js_in_session($this->getSession());
841
    }
842
 
843
    /**
844
     * Waits for all the JS to be loaded.
845
     *
846
     * @param   Session $session The Mink Session where JS can be run
847
     * @return  bool Whether any JS is still pending completion.
848
     */
849
    public static function wait_for_pending_js_in_session(Session $session) {
850
        if (!self::running_javascript_in_session($session)) {
851
            // JS is not available therefore there is nothing to wait for.
852
            return false;
853
        }
854
 
855
        // We don't use behat_base::spin() here as we don't want to end up with an exception
856
        // if the page & JSs don't finish loading properly.
857
        for ($i = 0; $i < self::get_extended_timeout() * 10; $i++) {
858
            $pending = '';
859
            try {
860
                $jscode = trim(preg_replace('/\s+/', ' ', '
861
                    return (function() {
862
                        if (document.readyState !== "complete") {
863
                            return "incomplete";
864
                        }
865
 
866
                        if (typeof M !== "object" || typeof M.util !== "object" || typeof M.util.pending_js === "undefined") {
867
                            return "";
868
                        }
869
 
870
                        return M.util.pending_js.join(":");
871
                    })()'));
872
                $pending = self::evaluate_script_in_session($session, $jscode);
873
            } catch (NoSuchWindowException $nsw) {
874
                // We catch an exception here, in case we just closed the window we were interacting with.
875
                // No javascript is running if there is no window right?
876
                $pending = '';
877
            } catch (UnknownError $e) {
878
                // M is not defined when the window or the frame don't exist anymore.
879
                if (strstr($e->getMessage(), 'M is not defined') != false) {
880
                    $pending = '';
881
                }
882
            }
883
 
884
            // If there are no pending JS we stop waiting.
885
            if ($pending === '') {
886
                return true;
887
            }
888
 
889
            // 0.1 seconds.
890
            usleep(100000);
891
        }
892
 
893
        // Timeout waiting for JS to complete. It will be caught and forwarded to behat_hooks::i_look_for_exceptions().
894
        // It is unlikely that Javascript code of a page or an AJAX request needs more than get_extended_timeout() seconds
895
        // to be loaded, although when pages contains Javascript errors M.util.js_complete() can not be executed, so the
896
        // number of JS pending code and JS completed code will not match and we will reach this point.
897
        throw new \Exception('Javascript code and/or AJAX requests are not ready after ' .
898
                self::get_extended_timeout() .
899
                ' seconds. There is a Javascript error or the code is extremely slow (' . $pending .
900
                '). If you are using a slow machine, consider setting $CFG->behat_increasetimeout.');
901
    }
902
 
903
    /**
904
     * Internal step definition to find exceptions, debugging() messages and PHP debug messages.
905
     *
906
     * Part of behat_hooks class as is part of the testing framework, is auto-executed
907
     * after each step so no features will splicitly use it.
908
     *
909
     * @throws Exception Unknown type, depending on what we caught in the hook or basic \Exception.
910
     * @see Moodle\BehatExtension\Tester\MoodleStepTester
911
     */
912
    public function look_for_exceptions() {
913
        // Wrap in try in case we were interacting with a closed window.
914
        try {
915
 
916
            // Exceptions.
917
            $exceptionsxpath = "//div[@data-rel='fatalerror']";
918
            // Debugging messages.
919
            $debuggingxpath = "//div[@data-rel='debugging']";
920
            // PHP debug messages.
921
            $phperrorxpath = "//div[@data-rel='phpdebugmessage']";
922
            // Any other backtrace.
923
            $othersxpath = "(//*[contains(., ': call to ')])[1]";
924
 
925
            $xpaths = array($exceptionsxpath, $debuggingxpath, $phperrorxpath, $othersxpath);
926
            $joinedxpath = implode(' | ', $xpaths);
927
 
928
            // Joined xpath expression. Most of the time there will be no exceptions, so this pre-check
929
            // is faster than to send the 4 xpath queries for each step.
930
            if (!$this->getSession()->getDriver()->find($joinedxpath)) {
931
                // Check if we have recorded any errors in driver process.
932
                $phperrors = behat_get_shutdown_process_errors();
933
                if (!empty($phperrors)) {
934
                    foreach ($phperrors as $error) {
935
                        $errnostring = behat_get_error_string($error['type']);
936
                        $msgs[] = $errnostring . ": " .$error['message'] . " at " . $error['file'] . ": " . $error['line'];
937
                    }
938
                    $msg = "PHP errors found:\n" . implode("\n", $msgs);
939
                    throw new \Exception(htmlentities($msg, ENT_COMPAT));
940
                }
941
 
942
                return;
943
            }
944
 
945
            // Exceptions.
946
            if ($errormsg = $this->getSession()->getPage()->find('xpath', $exceptionsxpath)) {
947
 
948
                // Getting the debugging info and the backtrace.
949
                $errorinfoboxes = $this->getSession()->getPage()->findAll('css', 'div.alert-error');
950
                // If errorinfoboxes is empty, try find alert-danger (bootstrap4) class.
951
                if (empty($errorinfoboxes)) {
952
                    $errorinfoboxes = $this->getSession()->getPage()->findAll('css', 'div.alert-danger');
953
                }
954
                // If errorinfoboxes is empty, try find notifytiny (original) class.
955
                if (empty($errorinfoboxes)) {
956
                    $errorinfoboxes = $this->getSession()->getPage()->findAll('css', 'div.notifytiny');
957
                }
958
 
959
                // If errorinfoboxes is empty, try find ajax/JS exception in dialogue.
960
                if (empty($errorinfoboxes)) {
961
                    $errorinfoboxes = $this->getSession()->getPage()->findAll('css', 'div.moodle-exception-message');
962
 
963
                    // If ajax/JS exception.
964
                    if ($errorinfoboxes) {
965
                        $errorinfo = $this->get_debug_text($errorinfoboxes[0]->getHtml());
966
                    }
967
 
968
                } else {
969
                    $errorinfo = implode("\n", [
970
                        $this->get_debug_text($errorinfoboxes[0]->getHtml()),
971
                        $this->get_debug_text($errorinfoboxes[1]->getHtml()),
972
                        html_to_text($errorinfoboxes[2]->find('css', 'ul')->getHtml()),
973
                    ]);
974
                }
975
 
976
                $msg = "Moodle exception: " . $errormsg->getText() . "\n" . $errorinfo;
977
                throw new \Exception(html_entity_decode($msg, ENT_COMPAT));
978
            }
979
 
980
            // Debugging messages.
981
            if ($debuggingmessages = $this->getSession()->getPage()->findAll('xpath', $debuggingxpath)) {
982
                $msgs = array();
983
                foreach ($debuggingmessages as $debuggingmessage) {
984
                    $msgs[] = $this->get_debug_text($debuggingmessage->getHtml());
985
                }
986
                $msg = "debugging() message/s found:\n" . implode("\n", $msgs);
987
                throw new \Exception(html_entity_decode($msg, ENT_COMPAT));
988
            }
989
 
990
            // PHP debug messages.
991
            if ($phpmessages = $this->getSession()->getPage()->findAll('xpath', $phperrorxpath)) {
992
 
993
                $msgs = array();
994
                foreach ($phpmessages as $phpmessage) {
995
                    $msgs[] = $this->get_debug_text($phpmessage->getHtml());
996
                }
997
                $msg = "PHP debug message/s found:\n" . implode("\n", $msgs);
998
                throw new \Exception(html_entity_decode($msg, ENT_COMPAT));
999
            }
1000
 
1001
            // Any other backtrace.
1002
            // First looking through xpath as it is faster than get and parse the whole page contents,
1003
            // we get the contents and look for matches once we found something to suspect that there is a backtrace.
1004
            if ($this->getSession()->getDriver()->find($othersxpath)) {
1005
                $backtracespattern = '/(line [0-9]* of [^:]*: call to [\->&;:a-zA-Z_\x7f-\xff][\->&;:a-zA-Z0-9_\x7f-\xff]*)/';
1006
                if (preg_match_all($backtracespattern, $this->getSession()->getPage()->getContent(), $backtraces)) {
1007
                    $msgs = array();
1008
                    foreach ($backtraces[0] as $backtrace) {
1009
                        $msgs[] = $backtrace . '()';
1010
                    }
1011
                    $msg = "Other backtraces found:\n" . implode("\n", $msgs);
1012
                    throw new \Exception(htmlentities($msg, ENT_COMPAT));
1013
                }
1014
            }
1015
 
1016
        } catch (NoSuchWindowException $e) {
1017
            // If we were interacting with a popup window it will not exists after closing it.
1018
        } catch (DriverException $e) {
1019
            // Same reason as above.
1020
        }
1021
    }
1022
 
1023
    /**
1024
     * Internal step definition to find deprecated styles.
1025
     *
1026
     * Part of behat_hooks class as is part of the testing framework, is auto-executed
1027
     * after each step so no features will splicitly use it.
1028
     *
1029
     * @throws Exception Unknown type, depending on what we caught in the hook or basic \Exception.
1030
     * @see Moodle\BehatExtension\Tester\MoodleStepTester
1031
     */
1032
    public function look_for_deprecated_styles() {
1033
        if (!behat_config_manager::get_behat_run_config_value('scss-deprecations')) {
1034
            return;
1035
        }
1036
 
1037
        if (!$this->running_javascript()) {
1038
            return;
1039
        }
1040
 
1441 ariadna 1041
        // Look for DOM elements with deprecated message in before pseudo-element.
1 efrain 1042
        $js = <<<EOF
1441 ariadna 1043
            [...document.querySelectorAll('*')].flatMap(el => {
1044
                const beforeContent = window.getComputedStyle(el, ':before').content;
1045
                if (beforeContent.startsWith('"Deprecated style in use')) {
1046
                    const deprecatedClass = beforeContent.match(/\(([^)]+)\)/)?.[1] ?? 'unknown';
1047
                    return [deprecatedClass + ' (found in: ' + el.classList + ')'];
1048
                }
1049
                return [];
1050
            });
1051
        EOF;
1052
 
1053
        $deprecations = $this->evaluate_script($js);
1054
        if ($deprecations) {
1055
            $deprecationdata = "Deprecated styles found:\n";
1056
            foreach ($deprecations as $deprecation) {
1057
                $deprecationdata .= "  {$deprecation}\n";
1058
            }
1059
            throw new \Exception(html_entity_decode($deprecationdata, ENT_COMPAT));
1060
        }
1061
    }
1062
 
1063
 
1064
    /**
1065
     * Internal step definition to find deprecated icons.
1066
     *
1067
     * Part of behat_hooks class as is part of the testing framework, is auto-executed
1068
     * after each step so no features will splicitly use it.
1069
     *
1070
     * @throws Exception Unknown type, depending on what we caught in the hook or basic \Exception.
1071
     * @see Moodle\BehatExtension\Tester\MoodleStepTester
1072
     */
1073
    public function look_for_deprecated_icons() {
1074
        if (behat_config_manager::get_behat_run_config_value('no-icon-deprecations')) {
1075
            return;
1076
        }
1077
 
1078
        if (!$this->running_javascript()) {
1079
            return;
1080
        }
1081
 
1082
        // Look for any DOM element with deprecated icon.
1083
        $js = <<<EOF
1084
            [...document.querySelectorAll('.icon.deprecated')].some(
1085
                deprecatedicon => true
1 efrain 1086
            );
1087
        EOF;
1088
        if ($this->evaluate_script($js)) {
1441 ariadna 1089
            throw new \Exception(html_entity_decode(
1090
                "Deprecated icon in use. Enable \$CFG->debugdisplay for detailed debugging information in the console",
1091
                ENT_COMPAT,
1092
            ));
1 efrain 1093
        }
1094
    }
1095
 
1096
    /**
1097
     * Converts HTML tags to line breaks to display the info in CLI
1098
     *
1099
     * @param string $html
1100
     * @return string
1101
     */
1102
    protected function get_debug_text($html) {
1103
 
1104
        // Replacing HTML tags for new lines and keeping only the text.
1105
        $notags = preg_replace('/<+\s*\/*\s*([A-Z][A-Z0-9]*)\b[^>]*\/*\s*>*/i', "\n", $html);
1106
        return preg_replace("/(\n)+/s", "\n", $notags);
1107
    }
1108
 
1109
    /**
1110
     * Helper function to execute api in a given context.
1111
     *
1441 ariadna 1112
     * Note: The contextapi does not support a callback.
1113
     *
1114
     * @param string|array $contextapi context in which api is defined.
1 efrain 1115
     * @param array|mixed $params list of params to pass or a single parameter
1116
     * @throws Exception
1441 ariadna 1117
     * @throws DriverException
1 efrain 1118
     */
1441 ariadna 1119
    protected function execute(
1120
        string|array $contextapi,
1121
        mixed $params = [],
1122
    ): void {
1 efrain 1123
        if (!is_array($params)) {
1441 ariadna 1124
            $params = [$params];
1 efrain 1125
        }
1126
 
1441 ariadna 1127
        if (is_string($contextapi)) {
1128
            $contextapi = explode('::', $contextapi);
1129
        }
1130
 
1131
        if (count($contextapi) !== 2) {
1132
            throw new DriverException('Invalid contextapi format, expected "context::api" or ["context", "api"]');
1133
        }
1134
 
1 efrain 1135
        // Get required context and execute the api.
1441 ariadna 1136
        [$classname, $method] = $contextapi;
1137
        if (!is_string($classname) || !is_string($method)) {
1138
            throw new DriverException('Invalid contextapi format, expected "context::api" or ["context", "api"]');
1139
        }
1 efrain 1140
 
1441 ariadna 1141
        $context = behat_context_helper::get($classname);
1142
        call_user_func_array([$context, $method], $params);
1143
 
1 efrain 1144
        // NOTE: Wait for pending js and look for exception are not optional, as this might lead to unexpected results.
1145
        // Don't make them optional for performance reasons.
1146
 
1147
        // Wait for pending js.
1148
        $this->wait_for_pending_js();
1149
 
1150
        // Look for exceptions.
1151
        $this->look_for_exceptions();
1152
 
1153
        // Look for deprecated styles.
1154
        $this->look_for_deprecated_styles();
1441 ariadna 1155
 
1156
        // Look for deprecated icons.
1157
        $this->look_for_deprecated_icons();
1 efrain 1158
    }
1159
 
1160
    /**
1161
     * Execute a function in a specific behat context.
1162
     *
1163
     * For example, to call the 'set_editor_value' function for all editors, you would call:
1164
     *
1165
     *     behat_base::execute_in_matching_contexts('editor', 'set_editor_value', ['Some value']);
1166
     *
1167
     * This would find all behat contexts whose class name starts with 'behat_editor_' and
1168
     * call the 'set_editor_value' function on that context.
1169
     *
1170
     * @param string $prefix
1171
     * @param string $method
1172
     * @param array $params
1173
     */
1174
    public static function execute_in_matching_contexts(string $prefix, string $method, array $params): void {
1175
        $contexts = behat_context_helper::get_prefixed_contexts("behat_{$prefix}_");
1176
        foreach ($contexts as $context) {
1177
            if (method_exists($context, $method) && is_callable([$context, $method])) {
1178
                call_user_func_array([$context, $method], $params);
1179
            }
1180
        }
1181
    }
1182
 
1183
    /**
1184
     * Get the actual user in the behat session (note $USER does not correspond to the behat session's user).
1185
     * @return mixed
1186
     * @throws coding_exception
1187
     */
1188
    protected function get_session_user() {
1189
        global $DB;
1190
 
1191
        $sid = $this->getSession()->getCookie('MoodleSession');
1192
        if (empty($sid)) {
1193
            throw new coding_exception('failed to get moodle session');
1194
        }
1441 ariadna 1195
        $session = \core\session\manager::get_session_by_sid($sid);
1196
        if (empty($session->userid)) {
1197
            throw new coding_exception('failed to get user from session id: '.$sid);
1 efrain 1198
        }
1441 ariadna 1199
        return $DB->get_record('user', ['id' => $session->userid]);
1 efrain 1200
    }
1201
 
1202
    /**
1203
     * Set current $USER, reset access cache.
1204
     *
1205
     * In some cases, behat will execute the code as admin but in many cases we need to set an specific user as some
1206
     * API's might rely on the logged user to take some action.
1207
     *
1208
     * @param null|int|stdClass $user user record, null or 0 means non-logged-in, positive integer means userid
1209
     */
1210
    public static function set_user($user = null) {
1211
        global $DB;
1212
 
1213
        if (is_object($user)) {
1214
            $user = clone($user);
1215
        } else if (!$user) {
1216
            // Assign valid data to admin user (some generator-related code needs a valid user).
1217
            $user = $DB->get_record('user', array('username' => 'admin'));
1218
        } else {
1219
            $user = $DB->get_record('user', array('id' => $user));
1220
        }
1221
        unset($user->description);
1222
        unset($user->access);
1223
        unset($user->preference);
1224
 
1225
        // Ensure session is empty, as it may contain caches and user specific info.
1226
        \core\session\manager::init_empty_session();
1227
 
1228
        \core\session\manager::set_user($user);
1229
    }
1230
 
1231
    /**
1232
     * Gets the internal moodle context id from the context reference.
1233
     *
1234
     * The context reference changes depending on the context
1235
     * level, it can be the system, a user, a category, a course or
1236
     * a module.
1237
     *
1238
     * @throws Exception
1239
     * @param string $levelname The context level string introduced by the test writer
1240
     * @param string $contextref The context reference introduced by the test writer
1241
     * @return context
1242
     */
1243
    public static function get_context(string $levelname, string $contextref): context {
1244
        $context = \core\context_helper::resolve_behat_reference($levelname, $contextref);
1245
        if ($context) {
1246
            return $context;
1247
        }
1248
 
1249
        throw new Exception("The specified context \"$levelname, $contextref\" does not exist");
1250
    }
1251
 
1252
    /**
1253
     * Trigger click on node via javascript instead of actually clicking on it via pointer.
1254
     *
1255
     * This function resolves the issue of nested elements with click listeners or links - in these cases clicking via
1256
     * the pointer may accidentally cause a click on the wrong element.
1257
     * Example of issue: clicking to expand navigation nodes when the config value linkadmincategories is enabled.
1258
     * @param NodeElement $node
1259
     */
1260
    protected function js_trigger_click($node) {
1261
        if (!$this->running_javascript()) {
1262
            $node->click();
1263
        }
1264
        $driver = $this->getSession()->getDriver();
1265
        if ($driver instanceof \Moodle\BehatExtension\Driver\WebDriver) {
1266
            $this->execute_js_on_node($node, '{{ELEMENT}}.click();');
1267
        } else {
1268
            $this->ensure_node_is_visible($node); // Ensures hidden elements can't be clicked.
1269
            $driver->click($node->getXpath());
1270
        }
1271
    }
1272
 
1273
    /**
1274
     * Execute JS on the specified NodeElement.
1275
     *
1276
     * @param NodeElement $node
1277
     * @param string $script
1278
     * @param bool $async
1279
     */
1280
    protected function execute_js_on_node(NodeElement $node, string $script, bool $async = false): void {
1281
        $driver = $this->getSession()->getDriver();
1282
        if (!($driver instanceof \Moodle\BehatExtension\Driver\WebDriver)) {
1283
            throw new \coding_exception('Unknown driver');
1284
        }
1285
 
1286
        if (preg_match('/^function[\s\(]/', $script)) {
1287
            $script = preg_replace('/;$/', '', $script);
1288
            $script = '(' . $script . ')';
1289
        }
1290
 
1291
        $script = str_replace('{{ELEMENT}}', 'arguments[0]', $script);
1292
 
1293
        $webdriver = $driver->getWebDriver();
1294
 
1295
        $element = $this->get_webdriver_element_from_node_element($node);
1296
        if ($async) {
1297
            try {
1298
                $webdriver->executeAsyncScript($script, [$element]);
1299
            } catch (ScriptTimeoutException $e) {
1300
                throw new DriverException($e->getMessage(), $e->getCode(), $e);
1301
            }
1302
        } else {
1303
            $webdriver->executeScript($script, [$element]);
1304
        }
1305
    }
1306
 
1307
    /**
1308
     * Translate a Mink NodeElement into a WebDriver Element.
1309
     *
1310
     * @param NodeElement $node
1311
     * @return WebDriverElement
1312
     */
1313
    protected function get_webdriver_element_from_node_element(NodeElement $node): WebDriverElement {
1314
        return $this->getSession()
1315
            ->getDriver()
1316
            ->getWebDriver()
1317
            ->findElement(WebDriverBy::xpath($node->getXpath()));
1318
    }
1319
 
1320
    /**
1321
     * Convert page names to URLs for steps like 'When I am on the "[page name]" page'.
1322
     *
1323
     * You should override this as appropriate for your plugin. The method
1324
     * {@link behat_navigation::resolve_core_page_url()} is a good example.
1325
     *
1326
     * Your overridden method should document the recognised page types with
1327
     * a table like this:
1328
     *
1329
     * Recognised page names are:
1330
     * | Page            | Description                                                    |
1331
     *
1332
     * @param string $page name of the page, with the component name removed e.g. 'Admin notification'.
1333
     * @return moodle_url the corresponding URL.
1334
     * @throws Exception with a meaningful error message if the specified page cannot be found.
1335
     */
1336
    protected function resolve_page_url(string $page): moodle_url {
1337
        throw new Exception('Component "' . get_class($this) .
1338
                '" does not support the generic \'When I am on the "' . $page .
1339
                '" page\' navigation step.');
1340
    }
1341
 
1342
    /**
1343
     * Convert page names to URLs for steps like 'When I am on the "[identifier]" "[page type]" page'.
1344
     *
1345
     * A typical example might be:
1346
     *     When I am on the "Test quiz" "mod_quiz > Responses report" page
1347
     * which would cause this method in behat_mod_quiz to be called with
1348
     * arguments 'Responses report', 'Test quiz'.
1349
     *
1350
     * You should override this as appropriate for your plugin. The method
1351
     * {@link behat_navigation::resolve_core_page_instance_url()} is a good example.
1352
     *
1353
     * Your overridden method should document the recognised page types with
1354
     * a table like this:
1355
     *
1356
     * Recognised page names are:
1357
     * | Type      | identifier meaning | Description                                     |
1358
     *
1359
     * @param string $type identifies which type of page this is, e.g. 'Attempt review'.
1360
     * @param string $identifier identifies the particular page, e.g. 'Test quiz > student > Attempt 1'.
1361
     * @return moodle_url the corresponding URL.
1362
     * @throws Exception with a meaningful error message if the specified page cannot be found.
1363
     */
1364
    protected function resolve_page_instance_url(string $type, string $identifier): moodle_url {
1365
        throw new Exception('Component "' . get_class($this) .
1366
                '" does not support the generic \'When I am on the "' . $identifier .
1367
                '" "' . $type . '" page\' navigation step.');
1368
    }
1369
 
1370
    /**
1371
     * Gets the required timeout in seconds.
1372
     *
1373
     * @param int $timeout One of the TIMEOUT constants
1374
     * @return int Actual timeout (in seconds)
1375
     */
1376
    protected static function get_real_timeout(int $timeout): int {
1377
        global $CFG;
1378
        if (!empty($CFG->behat_increasetimeout)) {
1379
            return $timeout * $CFG->behat_increasetimeout;
1380
        } else {
1381
            return $timeout;
1382
        }
1383
    }
1384
 
1385
    /**
1386
     * Gets the default timeout.
1387
     *
1388
     * The timeout for each Behat step (load page, wait for an element to load...).
1389
     *
1390
     * @return int Timeout in seconds
1391
     */
1392
    public static function get_timeout(): int {
1393
        return self::get_real_timeout(6);
1394
    }
1395
 
1396
    /**
1397
     * Gets the reduced timeout.
1398
     *
1399
     * A reduced timeout for cases where self::get_timeout() is too much
1400
     * and a simple $this->getSession()->getPage()->find() could not
1401
     * be enough.
1402
     *
1403
     * @return int Timeout in seconds
1404
     */
1405
    public static function get_reduced_timeout(): int {
1406
        return self::get_real_timeout(2);
1407
    }
1408
 
1409
    /**
1410
     * Gets the extended timeout.
1411
     *
1412
     * A longer timeout for cases where the normal timeout is not enough.
1413
     *
1414
     * @return int Timeout in seconds
1415
     */
1416
    public static function get_extended_timeout(): int {
1417
        return self::get_real_timeout(10);
1418
    }
1419
 
1420
    /**
1421
     * Return a list of the exact named selectors for the component.
1422
     *
1423
     * Named selectors are what make Behat steps like
1424
     *   Then I should see "Useful text" in the "General" "fieldset"
1425
     * work. Here, "fieldset" is the named selector, and "General" is the locator.
1426
     *
1427
     * If you override this method in your plugin (e.g. mod_mymod), to define
1428
     * new selectors specific to your plugin. For example, if you returned
1429
     *   new behat_component_named_selector('Thingy',
1430
     *           [".//some/xpath//img[contains(@alt, %locator%)]/.."])
1431
     * then
1432
     *   Then I should see "Useful text" in the "Whatever" "mod_mymod > Thingy"
1433
     * would work.
1434
     *
1435
     * This method should return a list of {@link behat_component_named_selector} and
1436
     * the docs on that class explain how it works.
1437
     *
1438
     * @return behat_component_named_selector[]
1439
     */
1440
    public static function get_exact_named_selectors(): array {
1441
        return [];
1442
    }
1443
 
1444
    /**
1445
     * Return a list of the partial named selectors for the component.
1446
     *
1447
     * Like the exact named selectors above, but the locator only
1448
     * needs to match part of the text. For example, the standard
1449
     * "button" is a partial selector, so:
1450
     *   When I click "Save" "button"
1451
     * will activate "Save changes".
1452
     *
1453
     * @return behat_component_named_selector[]
1454
     */
1455
    public static function get_partial_named_selectors(): array {
1456
        return [];
1457
    }
1458
 
1459
    /**
1460
     * Return a list of the Mink named replacements for the component.
1461
     *
1462
     * Named replacements allow you to define parts of an xpath that can be reused multiple times, or in multiple
1463
     * xpaths.
1464
     *
1465
     * This method should return a list of {@link behat_component_named_replacement} and the docs on that class explain
1466
     * how it works.
1467
     *
1468
     * @return behat_component_named_replacement[]
1469
     */
1470
    public static function get_named_replacements(): array {
1471
        return [];
1472
    }
1473
 
1474
    /**
1475
     * Evaluate the supplied script in the current session, returning the result.
1476
     *
1477
     * @param string $script
1478
     * @return mixed
1479
     */
1480
    public function evaluate_script(string $script) {
1481
        return self::evaluate_script_in_session($this->getSession(), $script);
1482
    }
1483
 
1484
    /**
1485
     * Evaluate the supplied script in the specified session, returning the result.
1486
     *
1487
     * @param Session $session
1488
     * @param string $script
1489
     * @return mixed
1490
     */
1491
    public static function evaluate_script_in_session(Session $session, string $script) {
1492
        self::require_javascript_in_session($session);
1493
 
1494
        return $session->evaluateScript($script);
1495
    }
1496
 
1497
    /**
1498
     * Execute the supplied script in the current session.
1499
     *
1500
     * No result will be returned.
1501
     *
1502
     * @param string $script
1503
     */
1504
    public function execute_script(string $script): void {
1505
        self::execute_script_in_session($this->getSession(), $script);
1506
    }
1507
 
1508
    /**
1509
     * Excecute the supplied script in the specified session.
1510
     *
1511
     * No result will be returned.
1512
     *
1513
     * @param Session $session
1514
     * @param string $script
1515
     */
1516
    public static function execute_script_in_session(Session $session, string $script): void {
1517
        self::require_javascript_in_session($session);
1518
 
1519
        $session->executeScript($script);
1520
    }
1521
 
1522
    /**
1523
     * Get the session key for the current session via Javascript.
1524
     *
1525
     * @return string
1526
     */
1527
    public function get_sesskey(): string {
1528
        $script = <<<EOF
1529
return (function() {
1530
if (M && M.cfg && M.cfg.sesskey) {
1531
    return M.cfg.sesskey;
1532
}
1533
return '';
1534
})()
1535
EOF;
1536
 
1537
        return $this->evaluate_script($script);
1538
    }
1539
 
1540
    /**
1541
     * Set the timeout factor for the remaining lifetime of the session.
1542
     *
1543
     * @param   int $factor A multiplication factor to use when calculating the timeout
1544
     */
1545
    public function set_test_timeout_factor(int $factor = 1): void {
1546
        $driver = $this->getSession()->getDriver();
1547
 
1548
        if (!$driver instanceof \OAndreyev\Mink\Driver\WebDriver) {
1549
            // This is a feature of the OAndreyev MinkWebDriver.
1550
            return;
1551
        }
1552
 
1553
        // The standard curl timeout is 30 seconds.
1554
        // Use get_real_timeout and multiply by the timeout factor to get the final timeout.
1555
        $timeout = self::get_real_timeout(30) * 1000 * $factor;
1556
        $driver->getWebDriver()->getCommandExecutor()->setRequestTimeout($timeout);
1557
    }
1558
 
1559
    /**
1560
     * Get the course category id from an identifier.
1561
     *
1562
     * The category idnumber, and name are checked.
1563
     *
1564
     * @param string $identifier
1565
     * @return int|null
1566
     */
1567
    protected function get_category_id(string $identifier): ?int {
1568
        global $DB;
1569
 
1570
        $sql = <<<EOF
1571
    SELECT id
1572
      FROM {course_categories}
1573
     WHERE idnumber = :idnumber
1574
        OR name = :name
1575
EOF;
1576
 
1577
        $result = $DB->get_field_sql($sql, [
1578
            'idnumber' => $identifier,
1579
            'name' => $identifier,
1580
        ]);
1581
 
1582
        return $result ?: null;
1583
    }
1584
 
1585
    /**
1586
     * Get the course id from an identifier.
1587
     *
1588
     * The course idnumber, shortname, and fullname are checked.
1589
     *
1590
     * @param string $identifier
1591
     * @return int|null
1592
     */
1593
    protected function get_course_id(string $identifier): ?int {
1594
        global $DB;
1595
 
1596
        $sql = <<<EOF
1597
    SELECT id
1598
      FROM {course}
1599
     WHERE idnumber = :idnumber
1600
        OR shortname = :shortname
1601
        OR fullname = :fullname
1602
EOF;
1603
 
1604
        $result = $DB->get_field_sql($sql, [
1605
            'idnumber' => $identifier,
1606
            'shortname' => $identifier,
1607
            'fullname' => $identifier,
1608
        ]);
1609
 
1610
        return $result ?: null;
1611
    }
1612
 
1613
    /**
1614
     * Get the activity course module id from its idnumber.
1615
     *
1616
     * Note: Only idnumber is supported here, not name at this time.
1617
     *
1618
     * @param string $identifier
1619
     * @return cm_info|null
1620
     */
1621
    protected function get_course_module_for_identifier(string $identifier): ?cm_info {
1622
        global $DB;
1623
 
1624
        $coursetable = new \core\dml\table('course', 'c', 'c');
1625
        $courseselect = $coursetable->get_field_select();
1626
        $coursefrom = $coursetable->get_from_sql();
1627
 
1628
        $cmtable = new \core\dml\table('course_modules', 'cm', 'cm');
1629
        $cmfrom = $cmtable->get_from_sql();
1630
 
1631
        $sql = <<<EOF
1632
    SELECT {$courseselect}, cm.id as cmid
1633
      FROM {$cmfrom}
1634
INNER JOIN {$coursefrom} ON c.id = cm.course
1635
     WHERE cm.idnumber = :idnumber
1636
EOF;
1637
 
1638
        $result = $DB->get_record_sql($sql, [
1639
            'idnumber' => $identifier,
1640
        ]);
1641
 
1642
        if ($result) {
1643
            $course = $coursetable->extract_from_result($result);
1644
            return get_fast_modinfo($course)->get_cm($result->cmid);
1645
        }
1646
 
1647
        return null;
1648
    }
1649
 
1650
    /**
1651
     * Get a coursemodule from an activity name or idnumber.
1652
     *
1653
     * @param string $activity
1654
     * @param string $identifier
1655
     * @return cm_info
1656
     */
1657
    protected function get_cm_by_activity_name(string $activity, string $identifier): cm_info {
1658
        global $DB;
1659
 
1660
        $coursetable = new \core\dml\table('course', 'c', 'c');
1661
        $courseselect = $coursetable->get_field_select();
1662
        $coursefrom = $coursetable->get_from_sql();
1663
 
1664
        $cmtable = new \core\dml\table('course_modules', 'cm', 'cm');
1665
        $cmfrom = $cmtable->get_from_sql();
1666
 
1667
        $acttable = new \core\dml\table($activity, 'a', 'a');
1668
        $actselect = $acttable->get_field_select();
1669
        $actfrom = $acttable->get_from_sql();
1670
 
1671
        $sql = <<<EOF
1672
    SELECT cm.id as cmid, {$courseselect}, {$actselect}
1673
      FROM {$cmfrom}
1674
INNER JOIN {$coursefrom} ON c.id = cm.course
1675
INNER JOIN {modules} m ON m.id = cm.module AND m.name = :modname
1676
INNER JOIN {$actfrom} ON cm.instance = a.id
1677
     WHERE cm.idnumber = :idnumber OR a.name = :name
1678
EOF;
1679
 
1680
        $result = $DB->get_record_sql($sql, [
1681
            'modname' => $activity,
1682
            'idnumber' => $identifier,
1683
            'name' => $identifier,
1684
        ], MUST_EXIST);
1685
 
1686
        $course = $coursetable->extract_from_result($result);
1687
        $instancedata = $acttable->extract_from_result($result);
1688
 
1689
        return get_fast_modinfo($course)->get_cm($result->cmid);
1690
    }
1691
 
1692
    /**
1693
     * Check whether any of the tags availble to the current scope match using the given callable.
1694
     *
1695
     * This function is typically called from within a Behat Hook, such as BeforeFeature, BeforeScenario, AfterStep, etc.
1696
     *
1697
     * The callable is used as the second argument to `array_filter()`, and is passed a single string argument for each of the
1698
     * tags available in the scope.
1699
     *
1700
     * The tags passed will include:
1701
     * - For a FeatureScope, the Feature tags only
1702
     * - For a ScenarioScope, the Feature and Scenario tags
1703
     * - For a StepScope, the Feature, Scenario, and Step tags
1704
     *
1705
     * An example usage may be:
1706
     *
1707
     *    // Note: phpDoc beforeStep attribution not shown.
1708
     *    public function before_step(StepScope $scope) {
1709
     *        $callback = function (string $tag): bool {
1441 ariadna 1710
     *            return $tag === 'editor_tiny' || substr($tag, 0, 5) === 'tiny_';
1 efrain 1711
     *        };
1712
     *
1713
     *        if (!self::scope_tags_match($scope, $callback)) {
1714
     *            return;
1715
     *        }
1716
     *
1717
     *        // Do something here.
1718
     *    }
1719
     *
1720
     * @param HookScope $scope The scope to check
1721
     * @param callable $callback The callable to use to check the scope
1722
     * @return boolean Whether any of the scope tags match
1723
     */
1724
    public static function scope_tags_match(HookScope $scope, callable $callback): bool {
1725
        $tags = [];
1726
 
1727
        if (is_subclass_of($scope, \Behat\Behat\Hook\Scope\FeatureScope::class)) {
1728
            $tags = $scope->getFeature()->getTags();
1729
        }
1730
 
1731
        if (is_subclass_of($scope, \Behat\Behat\Hook\Scope\ScenarioScope::class)) {
1732
            $tags = array_merge(
1733
                $scope->getFeature()->getTags(),
1734
                $scope->getScenario()->getTags()
1735
            );
1736
        }
1737
 
1738
        if (is_subclass_of($scope, \Behat\Behat\Hook\Scope\StepScope::class)) {
1739
            $tags = array_merge(
1740
                $scope->getFeature()->getTags(),
1741
                $scope->getScenario()->getTags(),
1742
                $scope->getStep()->getTags()
1743
            );
1744
        }
1745
 
1746
        $matches = array_filter($tags, $callback);
1747
 
1748
        return !empty($matches);
1749
    }
1750
 
1751
    /**
1441 ariadna 1752
     * Get the user object from an identifier.
1753
     *
1754
     * The user username and email fields are checked.
1755
     *
1756
     * @param string $identifier The user's username or email.
1757
     * @return stdClass|null The user id or null if not found.
1758
     */
1759
    protected function get_user_by_identifier(string $identifier): ?stdClass {
1760
        global $DB;
1761
 
1762
        $sql = <<<EOF
1763
            SELECT *
1764
              FROM {user}
1765
             WHERE username = :username
1766
                OR email = :email
1767
        EOF;
1768
 
1769
        $result = $DB->get_record_sql($sql, [
1770
            'username' => $identifier,
1771
            'email' => $identifier,
1772
        ]);
1773
 
1774
        return $result ?: null;
1775
    }
1776
 
1777
    /**
1 efrain 1778
     * Get the user id from an identifier.
1779
     *
1780
     * The user username and email fields are checked.
1781
     *
1782
     * @param string $identifier The user's username or email.
1783
     * @return int|null The user id or null if not found.
1784
     */
1785
    protected function get_user_id_by_identifier(string $identifier): ?int {
1786
        global $DB;
1787
 
1788
        $sql = <<<EOF
1789
    SELECT id
1790
      FROM {user}
1791
     WHERE username = :username
1792
        OR email = :email
1793
EOF;
1794
 
1795
        $result = $DB->get_field_sql($sql, [
1796
            'username' => $identifier,
1797
            'email' => $identifier,
1798
        ]);
1799
 
1800
        return $result ?: null;
1801
    }
1441 ariadna 1802
 
1803
    /**
1804
     * Prepare an xpath for insertion into Selenium JavaScript.
1805
     *
1806
     * @param string $xpath
1807
     * @return string
1808
     */
1809
    protected function prepare_xpath_for_javascript(string $xpath): string {
1810
        $newlines = [
1811
            "\r\n",
1812
            "\r",
1813
            "\n",
1814
        ];
1815
        return str_replace($newlines, ' ', $xpath);
1816
    }
1 efrain 1817
}