"Fossies" - the Fresh Open Source Software Archive

Member "moodle/lib/behat/behat_base.php" (6 Sep 2019, 41752 Bytes) of package /linux/www/moodle-3.6.6.tgz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) PHP source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file. For more information about "behat_base.php" see the Fossies "Dox" file reference documentation and the latest Fossies "Diffs" side-by-side code changes report: 3.6.5_vs_3.6.6.

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