diff --git a/admin/tool/behat/tests/behat/inplaceeditable.feature b/admin/tool/behat/tests/behat/inplaceeditable.feature new file mode 100644 index 00000000000..014c5f5972b --- /dev/null +++ b/admin/tool/behat/tests/behat/inplaceeditable.feature @@ -0,0 +1,30 @@ +@tool_behat +Feature: Verify that the inplace editable field works as expected + In order to use behat step definitions + As a test write + I need to ensure that the inplace editable works in forms + + Background: + Given the following "course" exists: + | fullname | Course 1 | + | shortname | C1 | + And the following "activities" exist: + | activity | course | name | idnumber | + | forum | C1 | My first forum | forum1 | + | assign | C1 | My first assignment | assign1 | + | quiz | C1 | My first quiz | quiz1 | + And I log in as "admin" + And I am on "Course 1" course homepage with editing mode on + + @javascript + Scenario: Using an inplace editable updates the name of an activity + When I set the field "Edit title" in the "My first assignment" "activity" to "Coursework submission" + Then I should see "Coursework submission" + And I should not see "My first assignment" + But I should see "My first forum" + And I should see "My first quiz" + And I set the field "Edit title" in the "Coursework submission" "activity" to "My first assignment" + And I should not see "Coursework submission" + But I should see "My first assignment" + And I should see "My first forum" + And I should see "My first quiz" diff --git a/blocks/site_main_menu/tests/behat/behat_block_site_main_menu.php b/blocks/site_main_menu/tests/behat/behat_block_site_main_menu.php index b80713c60c6..f99f479b5d9 100644 --- a/blocks/site_main_menu/tests/behat/behat_block_site_main_menu.php +++ b/blocks/site_main_menu/tests/behat/behat_block_site_main_menu.php @@ -150,4 +150,17 @@ class behat_block_site_main_menu extends behat_base { $xpath = "//*[contains(concat(' ',normalize-space(@class),' '),' block_site_main_menu ')]//li[contains(., $activityname)]"; $this->execute('behat_action_menu::i_open_the_action_menu_in', [$xpath, 'xpath_element']); } + + /** + * Return the list of partial named selectors. + * + * @return array + */ + public static function get_partial_named_selectors(): array { + return [ + new behat_component_named_selector('Activity', [ + "//*[contains(concat(' ',normalize-space(@class),' '),' block_site_main_menu ')]//li[contains(., %locator%)]" + ]), + ]; + } } diff --git a/blocks/site_main_menu/tests/behat/edit_activities.feature b/blocks/site_main_menu/tests/behat/edit_activities.feature index 0f6d8c28e37..51b60ea5500 100644 --- a/blocks/site_main_menu/tests/behat/edit_activities.feature +++ b/blocks/site_main_menu/tests/behat/edit_activities.feature @@ -6,15 +6,16 @@ Feature: Edit activities in main menu block @javascript Scenario: Edit name of acitivity in-place in site main menu block - Given I log in as "admin" + Given the following "activity" exists: + | activity | forum | + | course | Acceptance test site | + | name | My forum name | + | idnumber | forum | + And I log in as "admin" And I am on site homepage And I navigate to "Turn editing on" in current page administration And I add the "Main menu" block - When I add a "Forum" to section "0" and I fill the form with: - | Forum name | My forum name | - And I click on "Edit title" "link" in the "My forum name" activity in site main menu block - And I set the field "New name for activity My forum name" to "New forum name" - And I press the enter key + When I set the field "Edit title" in the "My forum name" "block_site_main_menu > Activity" to "New forum name" Then I should not see "My forum name" And I should see "New forum name" And I follow "New forum name" diff --git a/blocks/social_activities/tests/behat/behat_block_social_activities.php b/blocks/social_activities/tests/behat/behat_block_social_activities.php index 167b24d51a2..eb285231f83 100644 --- a/blocks/social_activities/tests/behat/behat_block_social_activities.php +++ b/blocks/social_activities/tests/behat/behat_block_social_activities.php @@ -158,4 +158,17 @@ class behat_block_social_activities extends behat_base { $xpath = "//*[contains(concat(' ',normalize-space(@class),' '),' block_social_activities ')]//li[contains(., $activityname)]"; $this->execute('behat_action_menu::i_open_the_action_menu_in', [$xpath, 'xpath_element']); } + + /** + * Return the list of partial named selectors. + * + * @return array + */ + public static function get_partial_named_selectors(): array { + return [ + new behat_component_named_selector('Activity', [ + "//*[contains(concat(' ',normalize-space(@class),' '),' block_social_activities ')]//li[contains(., %locator%)]", + ]), + ]; + } } diff --git a/blocks/social_activities/tests/behat/edit_activities.feature b/blocks/social_activities/tests/behat/edit_activities.feature index 87c77369fef..9ea303183c2 100644 --- a/blocks/social_activities/tests/behat/edit_activities.feature +++ b/blocks/social_activities/tests/behat/edit_activities.feature @@ -24,9 +24,7 @@ Feature: Edit activities in social activities block And I set the field "Add an activity to section 'section 0'" to "Forum" And I set the field "Forum name" to "My forum name" And I press "Save and return to course" - And I click on "Edit title" "link" in the "My forum name" activity in social activities block - And I set the field "New name for activity My forum name" to "New forum name" - And I press the enter key + When I set the field "Edit title" in the "My forum name" "block_social_activities > Activity" to "New forum name" Then I should not see "My forum name" in the "Social activities" "block" And I should see "New forum name" And I follow "New forum name" @@ -82,4 +80,3 @@ Feature: Edit activities in social activities block And I should not see "My forum name" in the "Social activities" "block" And I click on "My forum name" "link" in the "Recent activity" "block" And I should see "My forum name" in the ".breadcrumb" "css_element" - And I log out diff --git a/cohort/tests/behat/add_cohort.feature b/cohort/tests/behat/add_cohort.feature index 09fa8164ca3..e7c14ffe1ee 100644 --- a/cohort/tests/behat/add_cohort.feature +++ b/cohort/tests/behat/add_cohort.feature @@ -59,9 +59,7 @@ Feature: Add cohorts of users @javascript Scenario: Edit cohort name in-place When I follow "Cohorts" - And I click on "Edit cohort name" "link" in the "Test cohort name" "table_row" - And I set the field "New name for cohort Test cohort name" to "Students cohort" - And I press the enter key + And I set the field "Edit cohort name" to "Students cohort" Then I should not see "Test cohort name" And I should see "Students cohort" And I follow "Cohorts" diff --git a/course/format/topics/tests/behat/edit_delete_sections.feature b/course/format/topics/tests/behat/edit_delete_sections.feature index a1e205b3c19..573c7e50fcd 100644 --- a/course/format/topics/tests/behat/edit_delete_sections.feature +++ b/course/format/topics/tests/behat/edit_delete_sections.feature @@ -53,9 +53,7 @@ Feature: Sections can be edited and deleted in topics format @javascript Scenario: Inline edit section name in topics format - When I click on "Edit topic name" "link" in the "li#section-1" "css_element" - And I set the field "New name for topic Topic 1" to "Midterm evaluation" - And I press the enter key + When I set the field "Edit topic name" in the "li#section-1" "css_element" to "Midterm evaluation" Then I should not see "Topic 1" in the "region-main" "region" And "New name for topic" "field" should not exist And I should see "Midterm evaluation" in the "li#section-1" "css_element" diff --git a/course/format/weeks/tests/behat/edit_delete_sections.feature b/course/format/weeks/tests/behat/edit_delete_sections.feature index 5d8ff891130..6fdc14aef26 100644 --- a/course/format/weeks/tests/behat/edit_delete_sections.feature +++ b/course/format/weeks/tests/behat/edit_delete_sections.feature @@ -54,9 +54,7 @@ Feature: Sections can be edited and deleted in weeks format @javascript Scenario: Inline edit section name in weeks format - When I click on "Edit week name" "link" in the "li#section-1" "css_element" - And I set the field "New name for week 1 May - 7 May" to "Midterm evaluation" - And I press the enter key + When I set the field "Edit week name" in the "li#section-1" "css_element" to "Midterm evaluation" Then I should not see "1 May - 7 May" in the "region-main" "region" And "New name for week" "field" should not exist And I should see "Midterm evaluation" in the "li#section-1" "css_element" diff --git a/course/tests/behat/activities_edit_name.feature b/course/tests/behat/activities_edit_name.feature index 7372c1741a1..18217384e98 100644 --- a/course/tests/behat/activities_edit_name.feature +++ b/course/tests/behat/activities_edit_name.feature @@ -15,15 +15,16 @@ Feature: Edit activity name in-place And the following "course enrolments" exist: | user | course | role | | teacher1 | C1 | editingteacher | + And the following "activity" exists: + | course | C1 | + | activity | forum | + | name | Test forum name | + | description | Test forum description | + | idnumber | forum1 | When I log in as "teacher1" And I am on "Course 1" course homepage with editing mode on - And I add a "Forum" to section "1" and I fill the form with: - | Forum name | Test forum name | - | Description | Test forum description | # Rename activity - And I click on "Edit title" "link" in the "//div[contains(@class,'activityinstance') and contains(.,'Test forum name')]" "xpath_element" - And I set the field "New name for activity Test forum name" to "Good news" - And I press the enter key + And I set the field "Edit title" in the "Test forum name" "activity" to "Good news" Then I should not see "Test forum name" in the ".course-content" "css_element" And "New name for activity Test forum name" "field" should not exist And I should see "Good news" @@ -32,7 +33,7 @@ Feature: Edit activity name in-place And I should not see "Test forum name" # Cancel renaming And I click on "Edit title" "link" in the "//div[contains(@class,'activityinstance') and contains(.,'Good news')]" "xpath_element" - And I set the field "New name for activity Good news" to "Terrible news" + And I type "Terrible news" And I press the escape key And "New name for activity Good news" "field" should not exist And I should see "Good news" diff --git a/course/tests/behat/behat_course.php b/course/tests/behat/behat_course.php index 26cecd130b7..d06a8bf6c0d 100644 --- a/course/tests/behat/behat_course.php +++ b/course/tests/behat/behat_course.php @@ -852,22 +852,12 @@ class behat_course extends behat_base { * @param string $newactivityname */ public function i_change_activity_name_to($activityname, $newactivityname) { - - if (!$this->running_javascript()) { - throw new DriverException('Change activity name step is not available with Javascript disabled'); - } - - $activity = $this->escape($activityname); - - $this->execute('behat_course::i_click_on_in_the_activity', - array(get_string('edittitle'), "link", $activity) - ); - - // Adding chr(10) to save changes. - $this->execute('behat_forms::i_set_the_field_to', - array('title', $this->escape($newactivityname) . chr(10)) - ); - + $this->execute('behat_forms::i_set_the_field_in_container_to', [ + get_string('edittitle'), + $activityname, + 'activity', + $newactivityname + ]); } /** diff --git a/customfield/tests/behat/edit_categories.feature b/customfield/tests/behat/edit_categories.feature index 2b88046c088..b44a66163fc 100644 --- a/customfield/tests/behat/edit_categories.feature +++ b/customfield/tests/behat/edit_categories.feature @@ -12,7 +12,6 @@ Feature: Managers can manage categories for course custom fields Then I should see "Other fields" in the "#customfield_catlist" "css_element" And I navigate to "Reports > Logs" in site administration And I press "Get these logs" - And I log out Scenario: Edit a category name for custom course fields Given the following "custom field categories" exist: @@ -20,15 +19,12 @@ Feature: Managers can manage categories for course custom fields | Category for test | core_course | course | 0 | And I log in as "admin" And I navigate to "Courses > Course custom fields" in site administration - And I click on "Edit category name" "link" in the "//div[contains(@class,'categoryinstance') and contains(.,'Category for test')]" "xpath_element" - And I set the field "New value for Category for test" to "Good fields" - And I press the enter key + And I set the field "Edit category name" in the "//div[contains(@class,'categoryinstance') and contains(.,'Category for test')]" "xpath_element" to "Good fields" Then I should not see "Category for test" in the "#customfield_catlist" "css_element" And "New value for Category for test" "field" should not exist And I should see "Good fields" in the "#customfield_catlist" "css_element" And I navigate to "Reports > Logs" in site administration And I press "Get these logs" - And I log out Scenario: Delete a category for custom course fields Given the following "custom field categories" exist: @@ -46,7 +42,6 @@ Feature: Managers can manage categories for course custom fields Then I should not see "Test category" in the "#customfield_catlist" "css_element" And I navigate to "Reports > Logs" in site administration And I press "Get these logs" - And I log out Scenario: Move field in the course custom fields to another category Given the following "custom field categories" exist: @@ -78,7 +73,6 @@ Feature: Managers can manage categories for course custom fields And I press "Move \"Field1\"" And I follow "After field Field2" And "Field1" "text" should appear after "Field2" "text" - And I log out Scenario: Reorder course custom field categories Given the following "custom field categories" exist: @@ -108,4 +102,3 @@ Feature: Managers can manage categories for course custom fields And "Field1" "text" should appear after "Category1" "text" And "Category2" "text" should appear after "Field1" "text" And "Category3" "text" should appear after "Category2" "text" - And I log out diff --git a/lib/behat/behat_base.php b/lib/behat/behat_base.php index e995d70962c..0fe5c09bc79 100644 --- a/lib/behat/behat_base.php +++ b/lib/behat/behat_base.php @@ -28,19 +28,8 @@ // NOTE: no MOODLE_INTERNAL test here, this file may be required by behat before including /config.php. -use Behat\Mink\Exception\DriverException; -use Behat\Mink\Exception\ExpectationException; -use Behat\Mink\Exception\ElementNotFoundException; -use Behat\Mink\Element\NodeElement; -use Behat\Mink\Element\Element; -use Behat\Mink\Session; - -require_once(__DIR__ . '/classes/component_named_selector.php'); -require_once(__DIR__ . '/classes/component_named_replacement.php'); - -// Alias the WebDriver\Key class to behat_keys to make future transition to a different WebDriver implementation -// easier. -class_alias('WebDriver\\Key', 'behat_keys'); +require_once(__DIR__ . '/classes/behat_session_interface.php'); +require_once(__DIR__ . '/classes/behat_session_trait.php'); /** * Steps definitions base class. @@ -60,1295 +49,8 @@ class_alias('WebDriver\\Key', 'behat_keys'); * @copyright 2012 David Monllaó * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ -class behat_base extends Behat\MinkExtension\Context\RawMinkContext { +class behat_base extends Behat\MinkExtension\Context\RawMinkContext implements behat_session_interface { - /** - * Small timeout. - * - * A reduced timeout for cases where self::TIMEOUT is too much - * and a simple $this->getSession()->getPage()->find() could not - * be enough. - * - * @deprecated since Moodle 3.7 MDL-64979 - please use get_reduced_timeout() instead - * @todo MDL-64982 This will be deleted in Moodle 4.1 - * @see behat_base::get_reduced_timeout() - */ - const REDUCED_TIMEOUT = 2; - - /** - * The timeout for each Behat step (load page, wait for an element to load...). - * - * @deprecated since Moodle 3.7 MDL-64979 - please use get_timeout() instead - * @todo MDL-64982 This will be deleted in Moodle 4.1 - * @see behat_base::get_timeout() - */ - const TIMEOUT = 6; - - /** - * And extended timeout for specific cases. - * - * @deprecated since Moodle 3.7 MDL-64979 - please use get_extended_timeout() instead - * @todo MDL-64982 This will be deleted in Moodle 4.1 - * @see behat_base::get_extended_timeout() - */ - const EXTENDED_TIMEOUT = 10; - - /** - * The JS code to check that the page is ready. - * - * The document must be complete and either M.util.pending_js must be empty, or it must not be defined at all. - */ - const PAGE_READY_JS = "document.readyState === 'complete' && " . - "(typeof M !== 'object' || typeof M.util !== 'object' || " . - "typeof M.util.pending_js === 'undefined' || M.util.pending_js.length === 0)"; - - /** - * Locates url, based on provided path. - * Override to provide custom routing mechanism. - * - * @see Behat\MinkExtension\Context\MinkContext - * @param string $path - * @return string - */ - protected function locate_path($path) { - $starturl = rtrim($this->getMinkParameter('base_url'), '/') . '/'; - return 0 !== strpos($path, 'http') ? $starturl . ltrim($path, '/') : $path; - } - - /** - * Returns the first matching element. - * - * @link http://mink.behat.org/#traverse-the-page-selectors - * @param string $selector The selector type (css, xpath, named...) - * @param mixed $locator It depends on the $selector, can be the xpath, a name, a css locator... - * @param Exception $exception Otherwise we throw exception with generic info - * @param NodeElement $node Spins around certain DOM node instead of the whole page - * @param int $timeout Forces a specific time out (in seconds). - * @return NodeElement - */ - protected function find($selector, $locator, $exception = false, $node = false, $timeout = false) { - if ($selector === 'NodeElement' && is_a($locator, NodeElement::class)) { - // Support a NodeElement being passed in for use in step chaining. - return $locator; - } - - // Returns the first match. - $items = $this->find_all($selector, $locator, $exception, $node, $timeout); - return count($items) ? reset($items) : null; - } - - /** - * Returns all matching elements. - * - * Adapter to Behat\Mink\Element\Element::findAll() using the spin() method. - * - * @link http://mink.behat.org/#traverse-the-page-selectors - * @param string $selector The selector type (css, xpath, named...) - * @param mixed $locator It depends on the $selector, can be the xpath, a name, a css locator... - * @param Exception $exception Otherwise we throw expcetion with generic info - * @param NodeElement $container Restrict the search to just children of the specified container - * @param int $timeout Forces a specific time out (in seconds). If 0 is provided the default timeout will be applied. - * @return array NodeElements list - */ - protected function find_all($selector, $locator, $exception = false, $container = false, $timeout = false) { - // Throw exception, so dev knows it is not supported. - if ($selector === 'named') { - $exception = 'Using the "named" selector is deprecated as of 3.1. ' - .' Use the "named_partial" or use the "named_exact" selector instead.'; - throw new ExpectationException($exception, $this->getSession()); - } - - // Generic info. - if (!$exception) { - // With named selectors we can be more specific. - if (($selector == 'named_exact') || ($selector == 'named_partial')) { - $exceptiontype = $locator[0]; - $exceptionlocator = $locator[1]; - - // If we are in a @javascript session all contents would be displayed as HTML characters. - if ($this->running_javascript()) { - $locator[1] = html_entity_decode($locator[1], ENT_NOQUOTES); - } - - } else { - $exceptiontype = $selector; - $exceptionlocator = $locator; - } - - $exception = new ElementNotFoundException($this->getSession(), $exceptiontype, null, $exceptionlocator); - } - - // How much we will be waiting for the element to appear. - if (!$timeout) { - $timeout = self::get_timeout(); - $microsleep = false; - } else { - // Spinning each 0.1 seconds if the timeout was forced as we understand - // that is a special case and is good to refine the performance as much - // as possible. - $microsleep = true; - } - - // Normalise the values in order to perform the search. - [ - 'selector' => $selector, - 'locator' => $locator, - 'container' => $container, - ] = $this->normalise_selector($selector, $locator, $container ?: $this->getSession()->getPage()); - - // Waits for the node to appear if it exists, otherwise will timeout and throw the provided exception. - return $this->spin( - function() use ($selector, $locator, $container) { - return $container->findAll($selector, $locator); - }, [], $timeout, $exception, $microsleep - ); - } - - /** - * Normalise the locator and selector. - * - * @param string $selector The type of thing to search - * @param mixed $locator The locator value. Can be an array, but is more likely a string. - * @param Element $container An optional container to search within - * @return array The selector, locator, and container to search within - */ - public function normalise_selector(string $selector, $locator, Element $container): array { - // Check for specific transformations for this selector type. - $transformfunction = "transform_find_for_{$selector}"; - if (method_exists('behat_selectors', $transformfunction)) { - // A selector-specific transformation exists. - // Perform initial transformation of the selector within the current container. - [ - 'selector' => $selector, - 'locator' => $locator, - 'container' => $container, - ] = behat_selectors::{$transformfunction}($this, $locator, $container); - } - - // Normalise the css and xpath selector types. - if ('css_element' === $selector) { - $selector = 'css'; - } else if ('xpath_element' === $selector) { - $selector = 'xpath'; - } - - // Convert to a named selector where the selector type is not a known selector. - $converttonamed = !$this->getSession()->getSelectorsHandler()->isSelectorRegistered($selector); - $converttonamed = $converttonamed && 'xpath' !== $selector; - if ($converttonamed) { - if (behat_partial_named_selector::is_deprecated_selector($selector)) { - if ($replacement = behat_partial_named_selector::get_deprecated_replacement($selector)) { - error_log("The '{$selector}' selector has been replaced with {$replacement}"); - $selector = $replacement; - } - } else if (behat_exact_named_selector::is_deprecated_selector($selector)) { - if ($replacement = behat_exact_named_selector::get_deprecated_replacement($selector)) { - error_log("The '{$selector}' selector has been replaced with {$replacement}"); - $selector = $replacement; - } - } - - $allowedpartialselectors = behat_partial_named_selector::get_allowed_selectors(); - $allowedexactselectors = behat_exact_named_selector::get_allowed_selectors(); - if (isset($allowedpartialselectors[$selector])) { - $locator = behat_selectors::normalise_named_selector($allowedpartialselectors[$selector], $locator); - $selector = 'named_partial'; - } else if (isset($allowedexactselectors[$selector])) { - $locator = behat_selectors::normalise_named_selector($allowedexactselectors[$selector], $locator); - $selector = 'named_exact'; - } else { - throw new ExpectationException("The '{$selector}' selector type is not registered.", $this->getSession()->getDriver()); - } - } - - return [ - 'selector' => $selector, - 'locator' => $locator, - 'container' => $container, - ]; - } - - /** - * Send key presses straight to the currently active element. - * - * The `$keys` array contains a list of key values to send to the session as defined in the WebDriver and JsonWire - * specifications: - * - JsonWire: https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol#sessionsessionidkeys - * - W3C WebDriver: https://www.w3.org/TR/webdriver/#keyboard-actions - * - * This may be a combination of typable characters, modifier keys, and other supported keypoints. - * - * The NULL_KEY should be used to release modifier keys. If the NULL_KEY is not used then modifier keys will remain - * in the pressed state. - * - * Example usage: - * - * behat_base::type_keys($this->getSession(), [behat_keys::SHIFT, behat_keys::TAB, behat_keys::NULL_KEY]); - * behat_base::type_keys($this->getSession(), [behat_keys::ENTER, behat_keys::NULL_KEY]); - * behat_base::type_keys($this->getSession(), [behat_keys::ESCAPE, behat_keys::NULL_KEY]); - * - * It can also be used to send text input, for example: - * - * behat_base::type_keys( - * $this->getSession(), - * ['D', 'o', ' ', 'y', 'o', 'u', ' ', 'p', 'l', 'a' 'y', ' ', 'G', 'o', '?', behat_base::NULL_KEY] - * ); - * - * - * Please note: This function does not use the element/sendKeys variants but sends keys straight to the browser. - * - * @param Session $session - * @param string[] $keys - */ - public static function type_keys(Session $session, array $keys): void { - $session->getDriver()->getWebDriverSession()->keys([ - 'value' => $keys, - ]); - } - - /** - * Finds DOM nodes in the page using named selectors. - * - * The point of using this method instead of Mink ones is the spin - * method of behat_base::find() that looks for the element until it - * is available or it timeouts, this avoids the false failures received - * when selenium tries to execute commands on elements that are not - * ready to be used. - * - * All steps that requires elements to be available before interact with - * them should use one of the find* methods. - * - * The methods calls requires a {'find_' . $elementtype}($locator) - * format, like find_link($locator), find_select($locator), - * find_button($locator)... - * - * @link http://mink.behat.org/#named-selectors - * @throws coding_exception - * @param string $name The name of the called method - * @param mixed $arguments - * @return NodeElement - */ - public function __call($name, $arguments) { - if (substr($name, 0, 5) === 'find_') { - return call_user_func_array([$this, 'find'], array_merge( - [substr($name, 5)], - $arguments - )); - } - - throw new coding_exception("The '{$name}' method does not exist"); - } - - /** - * Escapes the double quote character. - * - * Double quote is the argument delimiter, it can be escaped - * with a backslash, but we auto-remove this backslashes - * before the step execution, this method is useful when using - * arguments as arguments for other steps. - * - * @param string $string - * @return string - */ - public function escape($string) { - return str_replace('"', '\"', $string); - } - - /** - * Executes the passed closure until returns true or time outs. - * - * In most cases the document.readyState === 'complete' will be enough, but sometimes JS - * requires more time to be completely loaded or an element to be visible or whatever is required to - * perform some action on an element; this method receives a closure which should contain the - * required statements to ensure the step definition actions and assertions have all their needs - * satisfied and executes it until they are satisfied or it timeouts. Redirects the return of the - * closure to the caller. - * - * The closures requirements to work well with this spin method are: - * - Must return false, null or '' if something goes wrong - * - Must return something != false if finishes as expected, this will be the (mixed) value - * returned by spin() - * - * The arguments of the closure are mixed, use $args depending on your needs. - * - * You can provide an exception to give more accurate feedback to tests writers, otherwise the - * closure exception will be used, but you must provide an exception if the closure does not throw - * an exception. - * - * @throws Exception If it timeouts without receiving something != false from the closure - * @param Function|array|string $lambda The function to execute or an array passed to call_user_func (maps to a class method) - * @param mixed $args Arguments to pass to the closure - * @param int $timeout Timeout in seconds - * @param Exception $exception The exception to throw in case it time outs. - * @param bool $microsleep If set to true it'll sleep micro seconds rather than seconds. - * @return mixed The value returned by the closure - */ - protected function spin($lambda, $args = false, $timeout = false, $exception = false, $microsleep = false) { - - // Using default timeout which is pretty high. - if (!$timeout) { - $timeout = self::get_timeout(); - } - - $start = microtime(true); - $end = $start + $timeout; - - do { - // We catch the exception thrown by the step definition to execute it again. - try { - // We don't check with !== because most of the time closures will return - // direct Behat methods returns and we are not sure it will be always (bool)false - // if it just runs the behat method without returning anything $return == null. - if ($return = call_user_func($lambda, $this, $args)) { - return $return; - } - } catch (Exception $e) { - // We would use the first closure exception if no exception has been provided. - if (!$exception) { - $exception = $e; - } - } - - if (!$this->running_javascript()) { - break; - } - - usleep(100000); - - } while (microtime(true) < $end); - - // Using coding_exception as is a development issue if no exception has been provided. - if (!$exception) { - $exception = new coding_exception('spin method requires an exception if the callback does not throw an exception'); - } - - // Throwing exception to the user. - throw $exception; - } - - /** - * Gets a NodeElement based on the locator and selector type received as argument from steps definitions. - * - * Use behat_base::get_text_selector_node() for text-based selectors. - * - * @throws ElementNotFoundException Thrown by behat_base::find - * @param string $selectortype - * @param string $element - * @return NodeElement - */ - protected function get_selected_node($selectortype, $element) { - return $this->find($selectortype, $element); - } - - /** - * Gets a NodeElement based on the locator and selector type received as argument from steps definitions. - * - * @throws ElementNotFoundException Thrown by behat_base::find - * @param string $selectortype - * @param string $element - * @return NodeElement - */ - protected function get_text_selector_node($selectortype, $element) { - // Getting Mink selector and locator. - list($selector, $locator) = $this->transform_text_selector($selectortype, $element); - - // Returns the NodeElement. - return $this->find($selector, $locator); - } - - /** - * Gets the requested element inside the specified container. - * - * @throws ElementNotFoundException Thrown by behat_base::find - * @param mixed $selectortype The element selector type. - * @param mixed $element The element locator. - * @param mixed $containerselectortype The container selector type. - * @param mixed $containerelement The container locator. - * @return NodeElement - */ - protected function get_node_in_container($selectortype, $element, $containerselectortype, $containerelement) { - // Gets the container, it will always be text based. - $containernode = $this->get_text_selector_node($containerselectortype, $containerelement); - - $locatorexceptionmsg = $element . '" in the "' . $containerelement. '" "' . $containerselectortype. '"'; - $exception = new ElementNotFoundException($this->getSession(), $selectortype, null, $locatorexceptionmsg); - - return $this->find($selectortype, $element, $exception, $containernode); - } - - /** - * Transforms from step definition's argument style to Mink format. - * - * Mink has 3 different selectors css, xpath and named, where named - * selectors includes link, button, field... to simplify and group multiple - * steps in one we use the same interface, considering all link, buttons... - * at the same level as css selectors and xpath; this method makes the - * conversion from the arguments received by the steps to the selectors and locators - * required to interact with Mink. - * - * @throws ExpectationException - * @param string $selectortype It can be css, xpath or any of the named selectors. - * @param string $element The locator (or string) we are looking for. - * @return array Contains the selector and the locator expected by Mink. - */ - protected function transform_selector($selectortype, $element) { - // Here we don't know if an allowed text selector is being used. - $selectors = behat_selectors::get_allowed_selectors(); - if (!isset($selectors[$selectortype])) { - throw new ExpectationException('The "' . $selectortype . '" selector type does not exist', $this->getSession()); - } - - [ - 'selector' => $selector, - 'locator' => $locator, - ] = $this->normalise_selector($selectortype, $element, $this->getSession()->getPage()); - - return [$selector, $locator]; - } - - /** - * Transforms from step definition's argument style to Mink format. - * - * Delegates all the process to behat_base::transform_selector() checking - * the provided $selectortype. - * - * @throws ExpectationException - * @param string $selectortype It can be css, xpath or any of the named selectors. - * @param string $element The locator (or string) we are looking for. - * @return array Contains the selector and the locator expected by Mink. - */ - protected function transform_text_selector($selectortype, $element) { - - $selectors = behat_selectors::get_allowed_text_selectors(); - if (empty($selectors[$selectortype])) { - throw new ExpectationException('The "' . $selectortype . '" selector can not be used to select text nodes', $this->getSession()); - } - - return $this->transform_selector($selectortype, $element); - } - - /** - * Whether Javascript is available in the current Session. - * - * @return boolean - */ - protected function running_javascript() { - return self::running_javascript_in_session($this->getSession()); - } - - /** - * Require that javascript be available in the current Session. - * - * @throws DriverException - */ - protected function require_javascript() { - return self::require_javascript_in_session($this->getSession()); - } - - /** - * Whether Javascript is available in the specified Session. - * - * @param Session $session - * @return boolean - */ - protected static function running_javascript_in_session(Session $session): bool { - return get_class($session->getDriver()) !== 'Behat\Mink\Driver\GoutteDriver'; - } - - /** - * Require that javascript be available for the specified Session. - * - * @param Session $session - * @throws DriverException - */ - protected static function require_javascript_in_session(Session $session): void { - if (self::running_javascript_in_session($session)) { - return; - } - - throw new DriverException('Javascript is required'); - } - - /** - * Checks if the current page is part of the mobile app. - * - * @return bool True if it's in the app - */ - protected function is_in_app() : bool { - // Cannot be in the app if there's no @app tag on scenario. - if (!$this->has_tag('app')) { - return false; - } - - // Check on page to see if it's an app page. Safest way is to look for added JavaScript. - return $this->evaluate_script('return typeof window.behat') === 'object'; - } - - /** - * Spins around an element until it exists - * - * @throws ExpectationException - * @param string $locator - * @param string $selectortype - * @return void - */ - protected function ensure_element_exists($locator, $selectortype) { - // Exception if it timesout and the element is still there. - $msg = "The '{$locator}' element does not exist and should"; - $exception = new ExpectationException($msg, $this->getSession()); - - // Normalise the values in order to perform the search. - [ - 'selector' => $selector, - 'locator' => $locator, - 'container' => $container, - ] = $this->normalise_selector($selectortype, $locator, $this->getSession()->getPage()); - - // It will stop spinning once the find() method returns true. - $this->spin( - function() use ($selector, $locator, $container) { - if ($container->find($selector, $locator)) { - return true; - } - return false; - }, - [], - self::get_extended_timeout(), - $exception, - true - ); - } - - /** - * Spins until the element does not exist - * - * @throws ExpectationException - * @param string $locator - * @param string $selectortype - * @return void - */ - protected function ensure_element_does_not_exist($locator, $selectortype) { - // Exception if it timesout and the element is still there. - $msg = "The '{$locator}' element exists and should not exist"; - $exception = new ExpectationException($msg, $this->getSession()); - - // Normalise the values in order to perform the search. - [ - 'selector' => $selector, - 'locator' => $locator, - 'container' => $container, - ] = $this->normalise_selector($selectortype, $locator, $this->getSession()->getPage()); - - // It will stop spinning once the find() method returns false. - $this->spin( - function() use ($selector, $locator, $container) { - if ($container->find($selector, $locator)) { - return false; - } - return true; - }, - // Note: We cannot use $this because the find will then be $this->find(), which leads us to a nested spin(). - // We cannot nest spins because the outer spin times out before the inner spin completes. - [], - self::get_extended_timeout(), - $exception, - true - ); - } - - /** - * Ensures that the provided node is visible and we can interact with it. - * - * @throws ExpectationException - * @param NodeElement $node - * @return void Throws an exception if it times out without the element being visible - */ - protected function ensure_node_is_visible($node) { - - if (!$this->running_javascript()) { - return; - } - - // Exception if it timesout and the element is still there. - $msg = 'The "' . $node->getXPath() . '" xpath node is not visible and it should be visible'; - $exception = new ExpectationException($msg, $this->getSession()); - - // It will stop spinning once the isVisible() method returns true. - $this->spin( - function($context, $args) { - if ($args->isVisible()) { - return true; - } - return false; - }, - $node, - self::get_extended_timeout(), - $exception, - true - ); - } - - /** - * Ensures that the provided node has a attribute value set. This step can be used to check if specific - * JS has finished modifying the node. - * - * @throws ExpectationException - * @param NodeElement $node - * @param string $attribute attribute name - * @param string $attributevalue attribute value to check. - * @return void Throws an exception if it times out without the element being visible - */ - protected function ensure_node_attribute_is_set($node, $attribute, $attributevalue) { - - if (!$this->running_javascript()) { - return; - } - - // Exception if it timesout and the element is still there. - $msg = 'The "' . $node->getXPath() . '" xpath node is not visible and it should be visible'; - $exception = new ExpectationException($msg, $this->getSession()); - - // It will stop spinning once the $args[1]) == $args[2], and method returns true. - $this->spin( - function($context, $args) { - if ($args[0]->getAttribute($args[1]) == $args[2]) { - return true; - } - return false; - }, - array($node, $attribute, $attributevalue), - self::get_extended_timeout(), - $exception, - true - ); - } - - /** - * Ensures that the provided element is visible and we can interact with it. - * - * Returns the node in case other actions are interested in using it. - * - * @throws ExpectationException - * @param string $element - * @param string $selectortype - * @return NodeElement Throws an exception if it times out without being visible - */ - protected function ensure_element_is_visible($element, $selectortype) { - - if (!$this->running_javascript()) { - return; - } - - $node = $this->get_selected_node($selectortype, $element); - $this->ensure_node_is_visible($node); - - return $node; - } - - /** - * Ensures that all the page's editors are loaded. - * - * @deprecated since Moodle 2.7 MDL-44084 - please do not use this function any more. - * @throws ElementNotFoundException - * @throws ExpectationException - * @return void - */ - protected function ensure_editors_are_loaded() { - global $CFG; - - if (empty($CFG->behat_usedeprecated)) { - debugging('Function behat_base::ensure_editors_are_loaded() is deprecated. It is no longer required.'); - } - return; - } - - /** - * Checks if the current scenario, or its feature, has a specified tag. - * - * @param string $tag Tag to check - * @return bool True if the tag exists in scenario or feature - */ - public function has_tag(string $tag) : bool { - return array_key_exists($tag, behat_hooks::get_tags_for_scenario()); - } - - /** - * Change browser window size. - * - small: 640x480 - * - medium: 1024x768 - * - large: 2560x1600 - * - * @param string $windowsize size of window. - * @param bool $viewport If true, changes viewport rather than window size - * @throws ExpectationException - */ - protected function resize_window($windowsize, $viewport = false) { - // Non JS don't support resize window. - if (!$this->running_javascript()) { - return; - } - - switch ($windowsize) { - case "small": - $width = 1024; - $height = 768; - break; - case "medium": - $width = 1366; - $height = 768; - break; - case "large": - $width = 2560; - $height = 1600; - break; - default: - preg_match('/^(\d+x\d+)$/', $windowsize, $matches); - if (empty($matches) || (count($matches) != 2)) { - throw new ExpectationException("Invalid screen size, can't resize", $this->getSession()); - } - $size = explode('x', $windowsize); - $width = (int) $size[0]; - $height = (int) $size[1]; - } - if ($viewport) { - // When setting viewport size, we set it so that the document width will be exactly - // as specified, assuming that there is a vertical scrollbar. (In cases where there is - // no scrollbar it will be slightly wider. We presume this is rare and predictable.) - // The window inner height will be as specified, which means the available viewport will - // actually be smaller if there is a horizontal scrollbar. We assume that horizontal - // scrollbars are rare so this doesn't matter. - $js = <<evaluate_script($js); - $width += $offset['x']; - $height += $offset['y']; - } - - $this->getSession()->getDriver()->resizeWindow($width, $height); - } - - /** - * Waits for all the JS to be loaded. - * - * @return bool Whether any JS is still pending completion. - */ - public function wait_for_pending_js() { - if (!$this->running_javascript()) { - // JS is not available therefore there is nothing to wait for. - return false; - } - - return static::wait_for_pending_js_in_session($this->getSession()); - } - - /** - * Waits for all the JS to be loaded. - * - * @param Session $session The Mink Session where JS can be run - * @return bool Whether any JS is still pending completion. - */ - public static function wait_for_pending_js_in_session(Session $session) { - // We don't use behat_base::spin() here as we don't want to end up with an exception - // if the page & JSs don't finish loading properly. - for ($i = 0; $i < self::get_extended_timeout() * 10; $i++) { - $pending = ''; - try { - $jscode = trim(preg_replace('/\s+/', ' ', ' - return (function() { - if (document.readyState !== "complete") { - return "incomplete"; - } - - if (typeof M !== "object" || typeof M.util !== "object" || typeof M.util.pending_js === "undefined") { - return ""; - } - - return M.util.pending_js.join(":"); - })()')); - $pending = self::evaluate_script_in_session($session, $jscode); - } catch (NoSuchWindow $nsw) { - // We catch an exception here, in case we just closed the window we were interacting with. - // No javascript is running if there is no window right? - $pending = ''; - } catch (UnknownError $e) { - // M is not defined when the window or the frame don't exist anymore. - if (strstr($e->getMessage(), 'M is not defined') != false) { - $pending = ''; - } - } - - // If there are no pending JS we stop waiting. - if ($pending === '') { - return true; - } - - // 0.1 seconds. - usleep(100000); - } - - // Timeout waiting for JS to complete. It will be caught and forwarded to behat_hooks::i_look_for_exceptions(). - // It is unlikely that Javascript code of a page or an AJAX request needs more than get_extended_timeout() seconds - // to be loaded, although when pages contains Javascript errors M.util.js_complete() can not be executed, so the - // number of JS pending code and JS completed code will not match and we will reach this point. - throw new \Exception('Javascript code and/or AJAX requests are not ready after ' . - self::get_extended_timeout() . - ' seconds. There is a Javascript error or the code is extremely slow (' . $pending . - '). If you are using a slow machine, consider setting $CFG->behat_increasetimeout.'); - } - - /** - * Internal step definition to find exceptions, debugging() messages and PHP debug messages. - * - * Part of behat_hooks class as is part of the testing framework, is auto-executed - * after each step so no features will splicitly use it. - * - * @throws Exception Unknown type, depending on what we caught in the hook or basic \Exception. - * @see Moodle\BehatExtension\Tester\MoodleStepTester - */ - public function look_for_exceptions() { - // Wrap in try in case we were interacting with a closed window. - try { - - // Exceptions. - $exceptionsxpath = "//div[@data-rel='fatalerror']"; - // Debugging messages. - $debuggingxpath = "//div[@data-rel='debugging']"; - // PHP debug messages. - $phperrorxpath = "//div[@data-rel='phpdebugmessage']"; - // Any other backtrace. - $othersxpath = "(//*[contains(., ': call to ')])[1]"; - - $xpaths = array($exceptionsxpath, $debuggingxpath, $phperrorxpath, $othersxpath); - $joinedxpath = implode(' | ', $xpaths); - - // Joined xpath expression. Most of the time there will be no exceptions, so this pre-check - // is faster than to send the 4 xpath queries for each step. - if (!$this->getSession()->getDriver()->find($joinedxpath)) { - // Check if we have recorded any errors in driver process. - $phperrors = behat_get_shutdown_process_errors(); - if (!empty($phperrors)) { - foreach ($phperrors as $error) { - $errnostring = behat_get_error_string($error['type']); - $msgs[] = $errnostring . ": " .$error['message'] . " at " . $error['file'] . ": " . $error['line']; - } - $msg = "PHP errors found:\n" . implode("\n", $msgs); - throw new \Exception(htmlentities($msg)); - } - - return; - } - - // Exceptions. - if ($errormsg = $this->getSession()->getPage()->find('xpath', $exceptionsxpath)) { - - // Getting the debugging info and the backtrace. - $errorinfoboxes = $this->getSession()->getPage()->findAll('css', 'div.alert-error'); - // If errorinfoboxes is empty, try find alert-danger (bootstrap4) class. - if (empty($errorinfoboxes)) { - $errorinfoboxes = $this->getSession()->getPage()->findAll('css', 'div.alert-danger'); - } - // If errorinfoboxes is empty, try find notifytiny (original) class. - if (empty($errorinfoboxes)) { - $errorinfoboxes = $this->getSession()->getPage()->findAll('css', 'div.notifytiny'); - } - - // If errorinfoboxes is empty, try find ajax/JS exception in dialogue. - if (empty($errorinfoboxes)) { - $errorinfoboxes = $this->getSession()->getPage()->findAll('css', 'div.moodle-exception-message'); - - // If ajax/JS exception. - if ($errorinfoboxes) { - $errorinfo = $this->get_debug_text($errorinfoboxes[0]->getHtml()); - } - - } else { - $errorinfo = $this->get_debug_text($errorinfoboxes[0]->getHtml()) . "\n" . - $this->get_debug_text($errorinfoboxes[1]->getHtml()); - } - - $msg = "Moodle exception: " . $errormsg->getText() . "\n" . $errorinfo; - throw new \Exception(html_entity_decode($msg)); - } - - // Debugging messages. - if ($debuggingmessages = $this->getSession()->getPage()->findAll('xpath', $debuggingxpath)) { - $msgs = array(); - foreach ($debuggingmessages as $debuggingmessage) { - $msgs[] = $this->get_debug_text($debuggingmessage->getHtml()); - } - $msg = "debugging() message/s found:\n" . implode("\n", $msgs); - throw new \Exception(html_entity_decode($msg)); - } - - // PHP debug messages. - if ($phpmessages = $this->getSession()->getPage()->findAll('xpath', $phperrorxpath)) { - - $msgs = array(); - foreach ($phpmessages as $phpmessage) { - $msgs[] = $this->get_debug_text($phpmessage->getHtml()); - } - $msg = "PHP debug message/s found:\n" . implode("\n", $msgs); - throw new \Exception(html_entity_decode($msg)); - } - - // Any other backtrace. - // First looking through xpath as it is faster than get and parse the whole page contents, - // we get the contents and look for matches once we found something to suspect that there is a backtrace. - if ($this->getSession()->getDriver()->find($othersxpath)) { - $backtracespattern = '/(line [0-9]* of [^:]*: call to [\->&;:a-zA-Z_\x7f-\xff][\->&;:a-zA-Z0-9_\x7f-\xff]*)/'; - if (preg_match_all($backtracespattern, $this->getSession()->getPage()->getContent(), $backtraces)) { - $msgs = array(); - foreach ($backtraces[0] as $backtrace) { - $msgs[] = $backtrace . '()'; - } - $msg = "Other backtraces found:\n" . implode("\n", $msgs); - throw new \Exception(htmlentities($msg)); - } - } - - } catch (NoSuchWindow $e) { - // If we were interacting with a popup window it will not exists after closing it. - } catch (DriverException $e) { - // Same reason as above. - } - } - - /** - * Converts HTML tags to line breaks to display the info in CLI - * - * @param string $html - * @return string - */ - protected function get_debug_text($html) { - - // Replacing HTML tags for new lines and keeping only the text. - $notags = preg_replace('/<+\s*\/*\s*([A-Z][A-Z0-9]*)\b[^>]*\/*\s*>*/i', "\n", $html); - return preg_replace("/(\n)+/s", "\n", $notags); - } - - /** - * Helper function to execute api in a given context. - * - * @param string $contextapi context in which api is defined. - * @param array $params list of params to pass. - * @throws Exception - */ - protected function execute($contextapi, $params = array()) { - if (!is_array($params)) { - $params = array($params); - } - - // Get required context and execute the api. - $contextapi = explode("::", $contextapi); - $context = behat_context_helper::get($contextapi[0]); - call_user_func_array(array($context, $contextapi[1]), $params); - - // NOTE: Wait for pending js and look for exception are not optional, as this might lead to unexpected results. - // Don't make them optional for performance reasons. - - // Wait for pending js. - $this->wait_for_pending_js(); - - // Look for exceptions. - $this->look_for_exceptions(); - } - - /** - * Get the actual user in the behat session (note $USER does not correspond to the behat session's user). - * @return mixed - * @throws coding_exception - */ - protected function get_session_user() { - global $DB; - - $sid = $this->getSession()->getCookie('MoodleSession'); - if (empty($sid)) { - throw new coding_exception('failed to get moodle session'); - } - $userid = $DB->get_field('sessions', 'userid', ['sid' => $sid]); - if (empty($userid)) { - throw new coding_exception('failed to get user from seession id '.$sid); - } - return $DB->get_record('user', ['id' => $userid]); - } - - /** - * Set current $USER, reset access cache. - * - * In some cases, behat will execute the code as admin but in many cases we need to set an specific user as some - * API's might rely on the logged user to take some action. - * - * @param null|int|stdClass $user user record, null or 0 means non-logged-in, positive integer means userid - */ - public static function set_user($user = null) { - global $DB; - - if (is_object($user)) { - $user = clone($user); - } else if (!$user) { - // Assign valid data to admin user (some generator-related code needs a valid user). - $user = $DB->get_record('user', array('username' => 'admin')); - } else { - $user = $DB->get_record('user', array('id' => $user)); - } - unset($user->description); - unset($user->access); - unset($user->preference); - - // Ensure session is empty, as it may contain caches and user specific info. - \core\session\manager::init_empty_session(); - - \core\session\manager::set_user($user); - } - /** - * Trigger click on node via javascript instead of actually clicking on it via pointer. - * - * This function resolves the issue of nested elements with click listeners or links - in these cases clicking via - * the pointer may accidentally cause a click on the wrong element. - * Example of issue: clicking to expand navigation nodes when the config value linkadmincategories is enabled. - * @param NodeElement $node - */ - protected function js_trigger_click($node) { - if (!$this->running_javascript()) { - $node->click(); - } - $this->ensure_node_is_visible($node); // Ensures hidden elements can't be clicked. - $xpath = $node->getXpath(); - $driver = $this->getSession()->getDriver(); - if ($driver instanceof \Moodle\BehatExtension\Driver\MoodleSelenium2Driver) { - $script = "Syn.click({{ELEMENT}})"; - $driver->triggerSynScript($xpath, $script); - } else { - $driver->click($xpath); - } - } - - /** - * Convert page names to URLs for steps like 'When I am on the "[page name]" page'. - * - * You should override this as appropriate for your plugin. The method - * {@link behat_navigation::resolve_core_page_url()} is a good example. - * - * Your overridden method should document the recognised page types with - * a table like this: - * - * Recognised page names are: - * | Page | Description | - * - * @param string $page name of the page, with the component name removed e.g. 'Admin notification'. - * @return moodle_url the corresponding URL. - * @throws Exception with a meaningful error message if the specified page cannot be found. - */ - protected function resolve_page_url(string $page): moodle_url { - throw new Exception('Component "' . get_class($this) . - '" does not support the generic \'When I am on the "' . $page . - '" page\' navigation step.'); - } - - /** - * Convert page names to URLs for steps like 'When I am on the "[identifier]" "[page type]" page'. - * - * A typical example might be: - * When I am on the "Test quiz" "mod_quiz > Responses report" page - * which would cause this method in behat_mod_quiz to be called with - * arguments 'Responses report', 'Test quiz'. - * - * You should override this as appropriate for your plugin. The method - * {@link behat_navigation::resolve_core_page_instance_url()} is a good example. - * - * Your overridden method should document the recognised page types with - * a table like this: - * - * Recognised page names are: - * | Type | identifier meaning | Description | - * - * @param string $type identifies which type of page this is, e.g. 'Attempt review'. - * @param string $identifier identifies the particular page, e.g. 'Test quiz > student > Attempt 1'. - * @return moodle_url the corresponding URL. - * @throws Exception with a meaningful error message if the specified page cannot be found. - */ - protected function resolve_page_instance_url(string $type, string $identifier): moodle_url { - throw new Exception('Component "' . get_class($this) . - '" does not support the generic \'When I am on the "' . $identifier . - '" "' . $type . '" page\' navigation step.'); - } - - /** - * Gets the required timeout in seconds. - * - * @param int $timeout One of the TIMEOUT constants - * @return int Actual timeout (in seconds) - */ - protected static function get_real_timeout(int $timeout) : int { - global $CFG; - if (!empty($CFG->behat_increasetimeout)) { - return $timeout * $CFG->behat_increasetimeout; - } else { - return $timeout; - } - } - - /** - * Gets the default timeout. - * - * The timeout for each Behat step (load page, wait for an element to load...). - * - * @return int Timeout in seconds - */ - public static function get_timeout() : int { - return self::get_real_timeout(6); - } - - /** - * Gets the reduced timeout. - * - * A reduced timeout for cases where self::get_timeout() is too much - * and a simple $this->getSession()->getPage()->find() could not - * be enough. - * - * @return int Timeout in seconds - */ - public static function get_reduced_timeout() : int { - return self::get_real_timeout(2); - } - - /** - * Gets the extended timeout. - * - * A longer timeout for cases where the normal timeout is not enough. - * - * @return int Timeout in seconds - */ - public static function get_extended_timeout() : int { - return self::get_real_timeout(10); - } - - /** - * Return a list of the exact named selectors for the component. - * - * Named selectors are what make Behat steps like - * Then I should see "Useful text" in the "General" "fieldset" - * work. Here, "fieldset" is the named selector, and "General" is the locator. - * - * If you override this method in your plugin (e.g. mod_mymod), to define - * new selectors specific to your plugin. For example, if you returned - * new behat_component_named_selector('Thingy', - * [".//some/xpath//img[contains(@alt, %locator%)]/.."]) - * then - * Then I should see "Useful text" in the "Whatever" "mod_mymod > Thingy" - * would work. - * - * This method should return a list of {@link behat_component_named_selector} and - * the docs on that class explain how it works. - * - * @return behat_component_named_selector[] - */ - public static function get_exact_named_selectors(): array { - return []; - } - - /** - * Return a list of the partial named selectors for the component. - * - * Like the exact named selectors above, but the locator only - * needs to match part of the text. For example, the standard - * "button" is a partial selector, so: - * When I click "Save" "button" - * will activate "Save changes". - * - * @return behat_component_named_selector[] - */ - public static function get_partial_named_selectors(): array { - return []; - } - - /** - * Return a list of the Mink named replacements for the component. - * - * Named replacements allow you to define parts of an xpath that can be reused multiple times, or in multiple - * xpaths. - * - * This method should return a list of {@link behat_component_named_replacement} and the docs on that class explain - * how it works. - * - * @return behat_component_named_replacement[] - */ - public static function get_named_replacements(): array { - return []; - } - - /** - * Evaluate the supplied script in the current session, returning the result. - * - * @param string $script - * @return mixed - */ - public function evaluate_script(string $script) { - return self::evaluate_script_in_session($this->getSession(), $script); - } - - /** - * Evaluate the supplied script in the specified session, returning the result. - * - * @param Session $session - * @param string $script - * @return mixed - */ - public static function evaluate_script_in_session(Session $session, string $script) { - self::require_javascript_in_session($session); - - return $session->evaluateScript($script); - } - - /** - * Execute the supplied script in the current session. - * - * No result will be returned. - * - * @param string $script - */ - public function execute_script(string $script): void { - self::execute_script_in_session($this->getSession(), $script); - } - - /** - * Excecute the supplied script in the specified session. - * - * No result will be returned. - * - * @param Session $session - * @param string $script - */ - public static function execute_script_in_session(Session $session, string $script): void { - self::require_javascript_in_session($session); - - $session->executeScript($script); - } - - /** - * Get the session key for the current session via Javascript. - * - * @return string - */ - public function get_sesskey(): string { - $script = <<evaluate_script($script); - } + // All of the functionality of behat_base is shared with form fields via the behat_session_trait trait. + use behat_session_trait; } diff --git a/lib/behat/behat_field_manager.php b/lib/behat/behat_field_manager.php index 6d9b4c7a7ea..1a807a20a14 100644 --- a/lib/behat/behat_field_manager.php +++ b/lib/behat/behat_field_manager.php @@ -48,7 +48,6 @@ class behat_field_manager { * @return behat_form_field */ public static function get_form_field_from_label($label, RawMinkContext $context) { - // There are moodle form elements that are not directly related with // a basic HTML form field, we should also take care of them. // The DOM node. @@ -172,6 +171,10 @@ class behat_field_manager { } else if ($tagname == 'select') { // Select tag. return 'select'; + } else if ($tagname == 'span') { + if ($fieldnode->hasAttribute('data-inplaceeditable') && $fieldnode->getAttribute('data-inplaceeditable')) { + return 'inplaceeditable'; + } } // We can not provide a closer field type. diff --git a/lib/behat/classes/behat_session_interface.php b/lib/behat/classes/behat_session_interface.php new file mode 100644 index 00000000000..2746070974c --- /dev/null +++ b/lib/behat/classes/behat_session_interface.php @@ -0,0 +1,87 @@ +. + +/** + * The Interface for a behat root context. + * + * @package core + * @category test + * @copyright 2020 Andrew Nicols + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +/** + * The Interface for a behat root context. + * + * This interface should be implemented by the behat_base context, and behat form fields, and it should be paired with + * the behat_session_trait. + * + * It should not be necessary to implement this interface, and the behat_session_trait trait in normal circumstances. + * + * @package core + * @category test + * @copyright 2020 Andrew Nicols + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +interface behat_session_interface { + /** + * Small timeout. + * + * A reduced timeout for cases where self::TIMEOUT is too much + * and a simple $this->getSession()->getPage()->find() could not + * be enough. + * + * @deprecated since Moodle 3.7 MDL-64979 - please use get_reduced_timeout() instead + * @todo MDL-64982 This will be deleted in Moodle 3.11 + * @see behat_base::get_reduced_timeout() + */ + const REDUCED_TIMEOUT = 2; + + /** + * The timeout for each Behat step (load page, wait for an element to load...). + * + * @deprecated since Moodle 3.7 MDL-64979 - please use get_timeout() instead + * @todo MDL-64982 This will be deleted in Moodle 3.11 + * @see behat_base::get_timeout() + */ + const TIMEOUT = 6; + + /** + * And extended timeout for specific cases. + * + * @deprecated since Moodle 3.7 MDL-64979 - please use get_extended_timeout() instead + * @todo MDL-64982 This will be deleted in Moodle 3.11 + * @see behat_base::get_extended_timeout() + */ + const EXTENDED_TIMEOUT = 10; + + /** + * The JS code to check that the page is ready. + * + * The document must be complete and either M.util.pending_js must be empty, or it must not be defined at all. + */ + const PAGE_READY_JS = "document.readyState === 'complete' && " . + "(typeof M !== 'object' || typeof M.util !== 'object' || " . + "typeof M.util.pending_js === 'undefined' || M.util.pending_js.length === 0)"; + + /** + * Returns the Mink session. + * + * @param string|null $name name of the session OR active session will be used + * @return \Behat\Mink\Session + */ + public function getSession($name = null); +} diff --git a/lib/behat/classes/behat_session_trait.php b/lib/behat/classes/behat_session_trait.php new file mode 100644 index 00000000000..5e9d3c0d35d --- /dev/null +++ b/lib/behat/classes/behat_session_trait.php @@ -0,0 +1,1312 @@ +. + +/** + * A trait containing functionality used by the behat base context, and form fields. + * + * @package core + * @category test + * @copyright 2020 Andrew Nicols + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +use Behat\Mink\Exception\DriverException; +use Behat\Mink\Exception\ExpectationException; +use Behat\Mink\Exception\ElementNotFoundException; +use Behat\Mink\Element\NodeElement; +use Behat\Mink\Element\Element; +use Behat\Mink\Session; + +// NOTE: no MOODLE_INTERNAL test here, this file may be required by behat before including /config.php. + +require_once(__DIR__ . '/component_named_replacement.php'); +require_once(__DIR__ . '/component_named_selector.php'); + +// Alias the WebDriver\Key class to behat_keys to make future transition to a different WebDriver implementation +// easier. +class_alias('WebDriver\\Key', 'behat_keys'); + +/** + * A trait containing functionality used by the behat base context, and form fields. + * + * This trait should be used by the behat_base context, and behat form fields, and it should be paired with the + * behat_session_interface interface. + * + * It should not be necessary to use this trait, and the behat_session_interface interface in normal circumstances. + * + * @package core + * @category test + * @copyright 2020 Andrew Nicols + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +trait behat_session_trait { + + /** + * Locates url, based on provided path. + * Override to provide custom routing mechanism. + * + * @see Behat\MinkExtension\Context\MinkContext + * @param string $path + * @return string + */ + protected function locate_path($path) { + $starturl = rtrim($this->getMinkParameter('base_url'), '/') . '/'; + return 0 !== strpos($path, 'http') ? $starturl . ltrim($path, '/') : $path; + } + + /** + * Returns the first matching element. + * + * @link http://mink.behat.org/#traverse-the-page-selectors + * @param string $selector The selector type (css, xpath, named...) + * @param mixed $locator It depends on the $selector, can be the xpath, a name, a css locator... + * @param Exception $exception Otherwise we throw exception with generic info + * @param NodeElement $node Spins around certain DOM node instead of the whole page + * @param int $timeout Forces a specific time out (in seconds). + * @return NodeElement + */ + protected function find($selector, $locator, $exception = false, $node = false, $timeout = false) { + if ($selector === 'NodeElement' && is_a($locator, NodeElement::class)) { + // Support a NodeElement being passed in for use in step chaining. + return $locator; + } + + // Returns the first match. + $items = $this->find_all($selector, $locator, $exception, $node, $timeout); + return count($items) ? reset($items) : null; + } + + /** + * Returns all matching elements. + * + * Adapter to Behat\Mink\Element\Element::findAll() using the spin() method. + * + * @link http://mink.behat.org/#traverse-the-page-selectors + * @param string $selector The selector type (css, xpath, named...) + * @param mixed $locator It depends on the $selector, can be the xpath, a name, a css locator... + * @param Exception $exception Otherwise we throw expcetion with generic info + * @param NodeElement $container Restrict the search to just children of the specified container + * @param int $timeout Forces a specific time out (in seconds). If 0 is provided the default timeout will be applied. + * @return array NodeElements list + */ + protected function find_all($selector, $locator, $exception = false, $container = false, $timeout = false) { + // Throw exception, so dev knows it is not supported. + if ($selector === 'named') { + $exception = 'Using the "named" selector is deprecated as of 3.1. ' + .' Use the "named_partial" or use the "named_exact" selector instead.'; + throw new ExpectationException($exception, $this->getSession()); + } + + // Generic info. + if (!$exception) { + // With named selectors we can be more specific. + if (($selector == 'named_exact') || ($selector == 'named_partial')) { + $exceptiontype = $locator[0]; + $exceptionlocator = $locator[1]; + + // If we are in a @javascript session all contents would be displayed as HTML characters. + if ($this->running_javascript()) { + $locator[1] = html_entity_decode($locator[1], ENT_NOQUOTES); + } + + } else { + $exceptiontype = $selector; + $exceptionlocator = $locator; + } + + $exception = new ElementNotFoundException($this->getSession(), $exceptiontype, null, $exceptionlocator); + } + + // How much we will be waiting for the element to appear. + if (!$timeout) { + $timeout = self::get_timeout(); + $microsleep = false; + } else { + // Spinning each 0.1 seconds if the timeout was forced as we understand + // that is a special case and is good to refine the performance as much + // as possible. + $microsleep = true; + } + + // Normalise the values in order to perform the search. + [ + 'selector' => $selector, + 'locator' => $locator, + 'container' => $container, + ] = $this->normalise_selector($selector, $locator, $container ?: $this->getSession()->getPage()); + + // Waits for the node to appear if it exists, otherwise will timeout and throw the provided exception. + return $this->spin( + function() use ($selector, $locator, $container) { + return $container->findAll($selector, $locator); + }, [], $timeout, $exception, $microsleep + ); + } + + /** + * Normalise the locator and selector. + * + * @param string $selector The type of thing to search + * @param mixed $locator The locator value. Can be an array, but is more likely a string. + * @param Element $container An optional container to search within + * @return array The selector, locator, and container to search within + */ + public function normalise_selector(string $selector, $locator, Element $container): array { + // Check for specific transformations for this selector type. + $transformfunction = "transform_find_for_{$selector}"; + if (method_exists('behat_selectors', $transformfunction)) { + // A selector-specific transformation exists. + // Perform initial transformation of the selector within the current container. + [ + 'selector' => $selector, + 'locator' => $locator, + 'container' => $container, + ] = behat_selectors::{$transformfunction}($this, $locator, $container); + } + + // Normalise the css and xpath selector types. + if ('css_element' === $selector) { + $selector = 'css'; + } else if ('xpath_element' === $selector) { + $selector = 'xpath'; + } + + // Convert to a named selector where the selector type is not a known selector. + $converttonamed = !$this->getSession()->getSelectorsHandler()->isSelectorRegistered($selector); + $converttonamed = $converttonamed && 'xpath' !== $selector; + if ($converttonamed) { + if (behat_partial_named_selector::is_deprecated_selector($selector)) { + if ($replacement = behat_partial_named_selector::get_deprecated_replacement($selector)) { + error_log("The '{$selector}' selector has been replaced with {$replacement}"); + $selector = $replacement; + } + } else if (behat_exact_named_selector::is_deprecated_selector($selector)) { + if ($replacement = behat_exact_named_selector::get_deprecated_replacement($selector)) { + error_log("The '{$selector}' selector has been replaced with {$replacement}"); + $selector = $replacement; + } + } + + $allowedpartialselectors = behat_partial_named_selector::get_allowed_selectors(); + $allowedexactselectors = behat_exact_named_selector::get_allowed_selectors(); + if (isset($allowedpartialselectors[$selector])) { + $locator = behat_selectors::normalise_named_selector($allowedpartialselectors[$selector], $locator); + $selector = 'named_partial'; + } else if (isset($allowedexactselectors[$selector])) { + $locator = behat_selectors::normalise_named_selector($allowedexactselectors[$selector], $locator); + $selector = 'named_exact'; + } else { + throw new ExpectationException("The '{$selector}' selector type is not registered.", $this->getSession()->getDriver()); + } + } + + return [ + 'selector' => $selector, + 'locator' => $locator, + 'container' => $container, + ]; + } + + /** + * Send key presses straight to the currently active element. + * + * The `$keys` array contains a list of key values to send to the session as defined in the WebDriver and JsonWire + * specifications: + * - JsonWire: https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol#sessionsessionidkeys + * - W3C WebDriver: https://www.w3.org/TR/webdriver/#keyboard-actions + * + * This may be a combination of typable characters, modifier keys, and other supported keypoints. + * + * The NULL_KEY should be used to release modifier keys. If the NULL_KEY is not used then modifier keys will remain + * in the pressed state. + * + * Example usage: + * + * behat_base::type_keys($this->getSession(), [behat_keys::SHIFT, behat_keys::TAB, behat_keys::NULL_KEY]); + * behat_base::type_keys($this->getSession(), [behat_keys::ENTER, behat_keys::NULL_KEY]); + * behat_base::type_keys($this->getSession(), [behat_keys::ESCAPE, behat_keys::NULL_KEY]); + * + * It can also be used to send text input, for example: + * + * behat_base::type_keys( + * $this->getSession(), + * ['D', 'o', ' ', 'y', 'o', 'u', ' ', 'p', 'l', 'a' 'y', ' ', 'G', 'o', '?', behat_base::NULL_KEY] + * ); + * + * + * Please note: This function does not use the element/sendKeys variants but sends keys straight to the browser. + * + * @param Session $session + * @param string[] $keys + */ + public static function type_keys(Session $session, array $keys): void { + $session->getDriver()->getWebDriverSession()->keys([ + 'value' => $keys, + ]); + } + + /** + * Finds DOM nodes in the page using named selectors. + * + * The point of using this method instead of Mink ones is the spin + * method of behat_base::find() that looks for the element until it + * is available or it timeouts, this avoids the false failures received + * when selenium tries to execute commands on elements that are not + * ready to be used. + * + * All steps that requires elements to be available before interact with + * them should use one of the find* methods. + * + * The methods calls requires a {'find_' . $elementtype}($locator) + * format, like find_link($locator), find_select($locator), + * find_button($locator)... + * + * @link http://mink.behat.org/#named-selectors + * @throws coding_exception + * @param string $name The name of the called method + * @param mixed $arguments + * @return NodeElement + */ + public function __call($name, $arguments) { + if (substr($name, 0, 5) === 'find_') { + return call_user_func_array([$this, 'find'], array_merge( + [substr($name, 5)], + $arguments + )); + } + + throw new coding_exception("The '{$name}' method does not exist"); + } + + /** + * Escapes the double quote character. + * + * Double quote is the argument delimiter, it can be escaped + * with a backslash, but we auto-remove this backslashes + * before the step execution, this method is useful when using + * arguments as arguments for other steps. + * + * @param string $string + * @return string + */ + public function escape($string) { + return str_replace('"', '\"', $string); + } + + /** + * Executes the passed closure until returns true or time outs. + * + * In most cases the document.readyState === 'complete' will be enough, but sometimes JS + * requires more time to be completely loaded or an element to be visible or whatever is required to + * perform some action on an element; this method receives a closure which should contain the + * required statements to ensure the step definition actions and assertions have all their needs + * satisfied and executes it until they are satisfied or it timeouts. Redirects the return of the + * closure to the caller. + * + * The closures requirements to work well with this spin method are: + * - Must return false, null or '' if something goes wrong + * - Must return something != false if finishes as expected, this will be the (mixed) value + * returned by spin() + * + * The arguments of the closure are mixed, use $args depending on your needs. + * + * You can provide an exception to give more accurate feedback to tests writers, otherwise the + * closure exception will be used, but you must provide an exception if the closure does not throw + * an exception. + * + * @throws Exception If it timeouts without receiving something != false from the closure + * @param Function|array|string $lambda The function to execute or an array passed to call_user_func (maps to a class method) + * @param mixed $args Arguments to pass to the closure + * @param int $timeout Timeout in seconds + * @param Exception $exception The exception to throw in case it time outs. + * @param bool $microsleep If set to true it'll sleep micro seconds rather than seconds. + * @return mixed The value returned by the closure + */ + protected function spin($lambda, $args = false, $timeout = false, $exception = false, $microsleep = false) { + + // Using default timeout which is pretty high. + if (!$timeout) { + $timeout = self::get_timeout(); + } + + $start = microtime(true); + $end = $start + $timeout; + + do { + // We catch the exception thrown by the step definition to execute it again. + try { + // We don't check with !== because most of the time closures will return + // direct Behat methods returns and we are not sure it will be always (bool)false + // if it just runs the behat method without returning anything $return == null. + if ($return = call_user_func($lambda, $this, $args)) { + return $return; + } + } catch (Exception $e) { + // We would use the first closure exception if no exception has been provided. + if (!$exception) { + $exception = $e; + } + } + + if (!$this->running_javascript()) { + break; + } + + usleep(100000); + + } while (microtime(true) < $end); + + // Using coding_exception as is a development issue if no exception has been provided. + if (!$exception) { + $exception = new coding_exception('spin method requires an exception if the callback does not throw an exception'); + } + + // Throwing exception to the user. + throw $exception; + } + + /** + * Gets a NodeElement based on the locator and selector type received as argument from steps definitions. + * + * Use behat_base::get_text_selector_node() for text-based selectors. + * + * @throws ElementNotFoundException Thrown by behat_base::find + * @param string $selectortype + * @param string $element + * @return NodeElement + */ + protected function get_selected_node($selectortype, $element) { + return $this->find($selectortype, $element); + } + + /** + * Gets a NodeElement based on the locator and selector type received as argument from steps definitions. + * + * @throws ElementNotFoundException Thrown by behat_base::find + * @param string $selectortype + * @param string $element + * @return NodeElement + */ + protected function get_text_selector_node($selectortype, $element) { + // Getting Mink selector and locator. + list($selector, $locator) = $this->transform_text_selector($selectortype, $element); + + // Returns the NodeElement. + return $this->find($selector, $locator); + } + + /** + * Gets the requested element inside the specified container. + * + * @throws ElementNotFoundException Thrown by behat_base::find + * @param mixed $selectortype The element selector type. + * @param mixed $element The element locator. + * @param mixed $containerselectortype The container selector type. + * @param mixed $containerelement The container locator. + * @return NodeElement + */ + protected function get_node_in_container($selectortype, $element, $containerselectortype, $containerelement) { + if ($containerselectortype === 'NodeElement' && is_a($containerelement, NodeElement::class)) { + // Support a NodeElement being passed in for use in step chaining. + $containernode = $containerelement; + $locatorexceptionmsg = $element; + } else { + // Gets the container, it will always be text based. + $containernode = $this->get_text_selector_node($containerselectortype, $containerelement); + $locatorexceptionmsg = $element . '" in the "' . $containerelement. '" "' . $containerselectortype. '"'; + } + + $exception = new ElementNotFoundException($this->getSession(), $selectortype, null, $locatorexceptionmsg); + + return $this->find($selectortype, $element, $exception, $containernode); + } + + /** + * Transforms from step definition's argument style to Mink format. + * + * Mink has 3 different selectors css, xpath and named, where named + * selectors includes link, button, field... to simplify and group multiple + * steps in one we use the same interface, considering all link, buttons... + * at the same level as css selectors and xpath; this method makes the + * conversion from the arguments received by the steps to the selectors and locators + * required to interact with Mink. + * + * @throws ExpectationException + * @param string $selectortype It can be css, xpath or any of the named selectors. + * @param string $element The locator (or string) we are looking for. + * @return array Contains the selector and the locator expected by Mink. + */ + protected function transform_selector($selectortype, $element) { + // Here we don't know if an allowed text selector is being used. + $selectors = behat_selectors::get_allowed_selectors(); + if (!isset($selectors[$selectortype])) { + throw new ExpectationException('The "' . $selectortype . '" selector type does not exist', $this->getSession()); + } + + [ + 'selector' => $selector, + 'locator' => $locator, + ] = $this->normalise_selector($selectortype, $element, $this->getSession()->getPage()); + + return [$selector, $locator]; + } + + /** + * Transforms from step definition's argument style to Mink format. + * + * Delegates all the process to behat_base::transform_selector() checking + * the provided $selectortype. + * + * @throws ExpectationException + * @param string $selectortype It can be css, xpath or any of the named selectors. + * @param string $element The locator (or string) we are looking for. + * @return array Contains the selector and the locator expected by Mink. + */ + protected function transform_text_selector($selectortype, $element) { + + $selectors = behat_selectors::get_allowed_text_selectors(); + if (empty($selectors[$selectortype])) { + throw new ExpectationException('The "' . $selectortype . '" selector can not be used to select text nodes', $this->getSession()); + } + + return $this->transform_selector($selectortype, $element); + } + + /** + * Whether Javascript is available in the current Session. + * + * @return boolean + */ + protected function running_javascript() { + return self::running_javascript_in_session($this->getSession()); + } + + /** + * Require that javascript be available in the current Session. + * + * @throws DriverException + */ + protected function require_javascript() { + return self::require_javascript_in_session($this->getSession()); + } + + /** + * Whether Javascript is available in the specified Session. + * + * @param Session $session + * @return boolean + */ + protected static function running_javascript_in_session(Session $session): bool { + return get_class($session->getDriver()) !== 'Behat\Mink\Driver\GoutteDriver'; + } + + /** + * Require that javascript be available for the specified Session. + * + * @param Session $session + * @throws DriverException + */ + protected static function require_javascript_in_session(Session $session): void { + if (self::running_javascript_in_session($session)) { + return; + } + + throw new DriverException('Javascript is required'); + } + + /** + * Checks if the current page is part of the mobile app. + * + * @return bool True if it's in the app + */ + protected function is_in_app() : bool { + // Cannot be in the app if there's no @app tag on scenario. + if (!$this->has_tag('app')) { + return false; + } + + // Check on page to see if it's an app page. Safest way is to look for added JavaScript. + return $this->evaluate_script('return typeof window.behat') === 'object'; + } + + /** + * Spins around an element until it exists + * + * @throws ExpectationException + * @param string $locator + * @param string $selectortype + * @return void + */ + protected function ensure_element_exists($locator, $selectortype) { + // Exception if it timesout and the element is still there. + $msg = "The '{$locator}' element does not exist and should"; + $exception = new ExpectationException($msg, $this->getSession()); + + // Normalise the values in order to perform the search. + [ + 'selector' => $selector, + 'locator' => $locator, + 'container' => $container, + ] = $this->normalise_selector($selectortype, $locator, $this->getSession()->getPage()); + + // It will stop spinning once the find() method returns true. + $this->spin( + function() use ($selector, $locator, $container) { + if ($container->find($selector, $locator)) { + return true; + } + return false; + }, + [], + self::get_extended_timeout(), + $exception, + true + ); + } + + /** + * Spins until the element does not exist + * + * @throws ExpectationException + * @param string $locator + * @param string $selectortype + * @return void + */ + protected function ensure_element_does_not_exist($locator, $selectortype) { + // Exception if it timesout and the element is still there. + $msg = "The '{$locator}' element exists and should not exist"; + $exception = new ExpectationException($msg, $this->getSession()); + + // Normalise the values in order to perform the search. + [ + 'selector' => $selector, + 'locator' => $locator, + 'container' => $container, + ] = $this->normalise_selector($selectortype, $locator, $this->getSession()->getPage()); + + // It will stop spinning once the find() method returns false. + $this->spin( + function() use ($selector, $locator, $container) { + if ($container->find($selector, $locator)) { + return false; + } + return true; + }, + // Note: We cannot use $this because the find will then be $this->find(), which leads us to a nested spin(). + // We cannot nest spins because the outer spin times out before the inner spin completes. + [], + self::get_extended_timeout(), + $exception, + true + ); + } + + /** + * Ensures that the provided node is visible and we can interact with it. + * + * @throws ExpectationException + * @param NodeElement $node + * @return void Throws an exception if it times out without the element being visible + */ + protected function ensure_node_is_visible($node) { + + if (!$this->running_javascript()) { + return; + } + + // Exception if it timesout and the element is still there. + $msg = 'The "' . $node->getXPath() . '" xpath node is not visible and it should be visible'; + $exception = new ExpectationException($msg, $this->getSession()); + + // It will stop spinning once the isVisible() method returns true. + $this->spin( + function($context, $args) { + if ($args->isVisible()) { + return true; + } + return false; + }, + $node, + self::get_extended_timeout(), + $exception, + true + ); + } + + /** + * Ensures that the provided node has a attribute value set. This step can be used to check if specific + * JS has finished modifying the node. + * + * @throws ExpectationException + * @param NodeElement $node + * @param string $attribute attribute name + * @param string $attributevalue attribute value to check. + * @return void Throws an exception if it times out without the element being visible + */ + protected function ensure_node_attribute_is_set($node, $attribute, $attributevalue) { + + if (!$this->running_javascript()) { + return; + } + + // Exception if it timesout and the element is still there. + $msg = 'The "' . $node->getXPath() . '" xpath node is not visible and it should be visible'; + $exception = new ExpectationException($msg, $this->getSession()); + + // It will stop spinning once the $args[1]) == $args[2], and method returns true. + $this->spin( + function($context, $args) { + if ($args[0]->getAttribute($args[1]) == $args[2]) { + return true; + } + return false; + }, + array($node, $attribute, $attributevalue), + self::get_extended_timeout(), + $exception, + true + ); + } + + /** + * Ensures that the provided element is visible and we can interact with it. + * + * Returns the node in case other actions are interested in using it. + * + * @throws ExpectationException + * @param string $element + * @param string $selectortype + * @return NodeElement Throws an exception if it times out without being visible + */ + protected function ensure_element_is_visible($element, $selectortype) { + + if (!$this->running_javascript()) { + return; + } + + $node = $this->get_selected_node($selectortype, $element); + $this->ensure_node_is_visible($node); + + return $node; + } + + /** + * Ensures that all the page's editors are loaded. + * + * @deprecated since Moodle 2.7 MDL-44084 - please do not use this function any more. + * @throws ElementNotFoundException + * @throws ExpectationException + * @return void + */ + protected function ensure_editors_are_loaded() { + global $CFG; + + if (empty($CFG->behat_usedeprecated)) { + debugging('Function behat_base::ensure_editors_are_loaded() is deprecated. It is no longer required.'); + } + return; + } + + /** + * Checks if the current scenario, or its feature, has a specified tag. + * + * @param string $tag Tag to check + * @return bool True if the tag exists in scenario or feature + */ + public function has_tag(string $tag) : bool { + return array_key_exists($tag, behat_hooks::get_tags_for_scenario()); + } + + /** + * Change browser window size. + * - small: 640x480 + * - medium: 1024x768 + * - large: 2560x1600 + * + * @param string $windowsize size of window. + * @param bool $viewport If true, changes viewport rather than window size + * @throws ExpectationException + */ + protected function resize_window($windowsize, $viewport = false) { + // Non JS don't support resize window. + if (!$this->running_javascript()) { + return; + } + + switch ($windowsize) { + case "small": + $width = 1024; + $height = 768; + break; + case "medium": + $width = 1366; + $height = 768; + break; + case "large": + $width = 2560; + $height = 1600; + break; + default: + preg_match('/^(\d+x\d+)$/', $windowsize, $matches); + if (empty($matches) || (count($matches) != 2)) { + throw new ExpectationException("Invalid screen size, can't resize", $this->getSession()); + } + $size = explode('x', $windowsize); + $width = (int) $size[0]; + $height = (int) $size[1]; + } + if ($viewport) { + // When setting viewport size, we set it so that the document width will be exactly + // as specified, assuming that there is a vertical scrollbar. (In cases where there is + // no scrollbar it will be slightly wider. We presume this is rare and predictable.) + // The window inner height will be as specified, which means the available viewport will + // actually be smaller if there is a horizontal scrollbar. We assume that horizontal + // scrollbars are rare so this doesn't matter. + $js = <<evaluate_script($js); + $width += $offset['x']; + $height += $offset['y']; + } + + $this->getSession()->getDriver()->resizeWindow($width, $height); + } + + /** + * Waits for all the JS to be loaded. + * + * @return bool Whether any JS is still pending completion. + */ + public function wait_for_pending_js() { + return static::wait_for_pending_js_in_session($this->getSession()); + } + + /** + * Waits for all the JS to be loaded. + * + * @param Session $session The Mink Session where JS can be run + * @return bool Whether any JS is still pending completion. + */ + public static function wait_for_pending_js_in_session(Session $session) { + if (!self::running_javascript_in_session($session)) { + // JS is not available therefore there is nothing to wait for. + return false; + } + + // We don't use behat_base::spin() here as we don't want to end up with an exception + // if the page & JSs don't finish loading properly. + for ($i = 0; $i < self::get_extended_timeout() * 10; $i++) { + $pending = ''; + try { + $jscode = trim(preg_replace('/\s+/', ' ', ' + return (function() { + if (document.readyState !== "complete") { + return "incomplete"; + } + + if (typeof M !== "object" || typeof M.util !== "object" || typeof M.util.pending_js === "undefined") { + return ""; + } + + return M.util.pending_js.join(":"); + })()')); + $pending = self::evaluate_script_in_session($session, $jscode); + } catch (NoSuchWindow $nsw) { + // We catch an exception here, in case we just closed the window we were interacting with. + // No javascript is running if there is no window right? + $pending = ''; + } catch (UnknownError $e) { + // M is not defined when the window or the frame don't exist anymore. + if (strstr($e->getMessage(), 'M is not defined') != false) { + $pending = ''; + } + } + + // If there are no pending JS we stop waiting. + if ($pending === '') { + return true; + } + + // 0.1 seconds. + usleep(100000); + } + + // Timeout waiting for JS to complete. It will be caught and forwarded to behat_hooks::i_look_for_exceptions(). + // It is unlikely that Javascript code of a page or an AJAX request needs more than get_extended_timeout() seconds + // to be loaded, although when pages contains Javascript errors M.util.js_complete() can not be executed, so the + // number of JS pending code and JS completed code will not match and we will reach this point. + throw new \Exception('Javascript code and/or AJAX requests are not ready after ' . + self::get_extended_timeout() . + ' seconds. There is a Javascript error or the code is extremely slow (' . $pending . + '). If you are using a slow machine, consider setting $CFG->behat_increasetimeout.'); + } + + /** + * Internal step definition to find exceptions, debugging() messages and PHP debug messages. + * + * Part of behat_hooks class as is part of the testing framework, is auto-executed + * after each step so no features will splicitly use it. + * + * @throws Exception Unknown type, depending on what we caught in the hook or basic \Exception. + * @see Moodle\BehatExtension\Tester\MoodleStepTester + */ + public function look_for_exceptions() { + // Wrap in try in case we were interacting with a closed window. + try { + + // Exceptions. + $exceptionsxpath = "//div[@data-rel='fatalerror']"; + // Debugging messages. + $debuggingxpath = "//div[@data-rel='debugging']"; + // PHP debug messages. + $phperrorxpath = "//div[@data-rel='phpdebugmessage']"; + // Any other backtrace. + $othersxpath = "(//*[contains(., ': call to ')])[1]"; + + $xpaths = array($exceptionsxpath, $debuggingxpath, $phperrorxpath, $othersxpath); + $joinedxpath = implode(' | ', $xpaths); + + // Joined xpath expression. Most of the time there will be no exceptions, so this pre-check + // is faster than to send the 4 xpath queries for each step. + if (!$this->getSession()->getDriver()->find($joinedxpath)) { + // Check if we have recorded any errors in driver process. + $phperrors = behat_get_shutdown_process_errors(); + if (!empty($phperrors)) { + foreach ($phperrors as $error) { + $errnostring = behat_get_error_string($error['type']); + $msgs[] = $errnostring . ": " .$error['message'] . " at " . $error['file'] . ": " . $error['line']; + } + $msg = "PHP errors found:\n" . implode("\n", $msgs); + throw new \Exception(htmlentities($msg)); + } + + return; + } + + // Exceptions. + if ($errormsg = $this->getSession()->getPage()->find('xpath', $exceptionsxpath)) { + + // Getting the debugging info and the backtrace. + $errorinfoboxes = $this->getSession()->getPage()->findAll('css', 'div.alert-error'); + // If errorinfoboxes is empty, try find alert-danger (bootstrap4) class. + if (empty($errorinfoboxes)) { + $errorinfoboxes = $this->getSession()->getPage()->findAll('css', 'div.alert-danger'); + } + // If errorinfoboxes is empty, try find notifytiny (original) class. + if (empty($errorinfoboxes)) { + $errorinfoboxes = $this->getSession()->getPage()->findAll('css', 'div.notifytiny'); + } + + // If errorinfoboxes is empty, try find ajax/JS exception in dialogue. + if (empty($errorinfoboxes)) { + $errorinfoboxes = $this->getSession()->getPage()->findAll('css', 'div.moodle-exception-message'); + + // If ajax/JS exception. + if ($errorinfoboxes) { + $errorinfo = $this->get_debug_text($errorinfoboxes[0]->getHtml()); + } + + } else { + $errorinfo = $this->get_debug_text($errorinfoboxes[0]->getHtml()) . "\n" . + $this->get_debug_text($errorinfoboxes[1]->getHtml()); + } + + $msg = "Moodle exception: " . $errormsg->getText() . "\n" . $errorinfo; + throw new \Exception(html_entity_decode($msg)); + } + + // Debugging messages. + if ($debuggingmessages = $this->getSession()->getPage()->findAll('xpath', $debuggingxpath)) { + $msgs = array(); + foreach ($debuggingmessages as $debuggingmessage) { + $msgs[] = $this->get_debug_text($debuggingmessage->getHtml()); + } + $msg = "debugging() message/s found:\n" . implode("\n", $msgs); + throw new \Exception(html_entity_decode($msg)); + } + + // PHP debug messages. + if ($phpmessages = $this->getSession()->getPage()->findAll('xpath', $phperrorxpath)) { + + $msgs = array(); + foreach ($phpmessages as $phpmessage) { + $msgs[] = $this->get_debug_text($phpmessage->getHtml()); + } + $msg = "PHP debug message/s found:\n" . implode("\n", $msgs); + throw new \Exception(html_entity_decode($msg)); + } + + // Any other backtrace. + // First looking through xpath as it is faster than get and parse the whole page contents, + // we get the contents and look for matches once we found something to suspect that there is a backtrace. + if ($this->getSession()->getDriver()->find($othersxpath)) { + $backtracespattern = '/(line [0-9]* of [^:]*: call to [\->&;:a-zA-Z_\x7f-\xff][\->&;:a-zA-Z0-9_\x7f-\xff]*)/'; + if (preg_match_all($backtracespattern, $this->getSession()->getPage()->getContent(), $backtraces)) { + $msgs = array(); + foreach ($backtraces[0] as $backtrace) { + $msgs[] = $backtrace . '()'; + } + $msg = "Other backtraces found:\n" . implode("\n", $msgs); + throw new \Exception(htmlentities($msg)); + } + } + + } catch (NoSuchWindow $e) { + // If we were interacting with a popup window it will not exists after closing it. + } catch (DriverException $e) { + // Same reason as above. + } + } + + /** + * Converts HTML tags to line breaks to display the info in CLI + * + * @param string $html + * @return string + */ + protected function get_debug_text($html) { + + // Replacing HTML tags for new lines and keeping only the text. + $notags = preg_replace('/<+\s*\/*\s*([A-Z][A-Z0-9]*)\b[^>]*\/*\s*>*/i', "\n", $html); + return preg_replace("/(\n)+/s", "\n", $notags); + } + + /** + * Helper function to execute api in a given context. + * + * @param string $contextapi context in which api is defined. + * @param array $params list of params to pass. + * @throws Exception + */ + protected function execute($contextapi, $params = array()) { + if (!is_array($params)) { + $params = array($params); + } + + // Get required context and execute the api. + $contextapi = explode("::", $contextapi); + $context = behat_context_helper::get($contextapi[0]); + call_user_func_array(array($context, $contextapi[1]), $params); + + // NOTE: Wait for pending js and look for exception are not optional, as this might lead to unexpected results. + // Don't make them optional for performance reasons. + + // Wait for pending js. + $this->wait_for_pending_js(); + + // Look for exceptions. + $this->look_for_exceptions(); + } + + /** + * Get the actual user in the behat session (note $USER does not correspond to the behat session's user). + * @return mixed + * @throws coding_exception + */ + protected function get_session_user() { + global $DB; + + $sid = $this->getSession()->getCookie('MoodleSession'); + if (empty($sid)) { + throw new coding_exception('failed to get moodle session'); + } + $userid = $DB->get_field('sessions', 'userid', ['sid' => $sid]); + if (empty($userid)) { + throw new coding_exception('failed to get user from seession id '.$sid); + } + return $DB->get_record('user', ['id' => $userid]); + } + + /** + * Set current $USER, reset access cache. + * + * In some cases, behat will execute the code as admin but in many cases we need to set an specific user as some + * API's might rely on the logged user to take some action. + * + * @param null|int|stdClass $user user record, null or 0 means non-logged-in, positive integer means userid + */ + public static function set_user($user = null) { + global $DB; + + if (is_object($user)) { + $user = clone($user); + } else if (!$user) { + // Assign valid data to admin user (some generator-related code needs a valid user). + $user = $DB->get_record('user', array('username' => 'admin')); + } else { + $user = $DB->get_record('user', array('id' => $user)); + } + unset($user->description); + unset($user->access); + unset($user->preference); + + // Ensure session is empty, as it may contain caches and user specific info. + \core\session\manager::init_empty_session(); + + \core\session\manager::set_user($user); + } + /** + * Trigger click on node via javascript instead of actually clicking on it via pointer. + * + * This function resolves the issue of nested elements with click listeners or links - in these cases clicking via + * the pointer may accidentally cause a click on the wrong element. + * Example of issue: clicking to expand navigation nodes when the config value linkadmincategories is enabled. + * @param NodeElement $node + */ + protected function js_trigger_click($node) { + if (!$this->running_javascript()) { + $node->click(); + } + $this->ensure_node_is_visible($node); // Ensures hidden elements can't be clicked. + $xpath = $node->getXpath(); + $driver = $this->getSession()->getDriver(); + if ($driver instanceof \Moodle\BehatExtension\Driver\MoodleSelenium2Driver) { + $script = "Syn.click({{ELEMENT}})"; + $driver->triggerSynScript($xpath, $script); + } else { + $driver->click($xpath); + } + } + + /** + * Convert page names to URLs for steps like 'When I am on the "[page name]" page'. + * + * You should override this as appropriate for your plugin. The method + * {@link behat_navigation::resolve_core_page_url()} is a good example. + * + * Your overridden method should document the recognised page types with + * a table like this: + * + * Recognised page names are: + * | Page | Description | + * + * @param string $page name of the page, with the component name removed e.g. 'Admin notification'. + * @return moodle_url the corresponding URL. + * @throws Exception with a meaningful error message if the specified page cannot be found. + */ + protected function resolve_page_url(string $page): moodle_url { + throw new Exception('Component "' . get_class($this) . + '" does not support the generic \'When I am on the "' . $page . + '" page\' navigation step.'); + } + + /** + * Convert page names to URLs for steps like 'When I am on the "[identifier]" "[page type]" page'. + * + * A typical example might be: + * When I am on the "Test quiz" "mod_quiz > Responses report" page + * which would cause this method in behat_mod_quiz to be called with + * arguments 'Responses report', 'Test quiz'. + * + * You should override this as appropriate for your plugin. The method + * {@link behat_navigation::resolve_core_page_instance_url()} is a good example. + * + * Your overridden method should document the recognised page types with + * a table like this: + * + * Recognised page names are: + * | Type | identifier meaning | Description | + * + * @param string $type identifies which type of page this is, e.g. 'Attempt review'. + * @param string $identifier identifies the particular page, e.g. 'Test quiz > student > Attempt 1'. + * @return moodle_url the corresponding URL. + * @throws Exception with a meaningful error message if the specified page cannot be found. + */ + protected function resolve_page_instance_url(string $type, string $identifier): moodle_url { + throw new Exception('Component "' . get_class($this) . + '" does not support the generic \'When I am on the "' . $identifier . + '" "' . $type . '" page\' navigation step.'); + } + + /** + * Gets the required timeout in seconds. + * + * @param int $timeout One of the TIMEOUT constants + * @return int Actual timeout (in seconds) + */ + protected static function get_real_timeout(int $timeout) : int { + global $CFG; + if (!empty($CFG->behat_increasetimeout)) { + return $timeout * $CFG->behat_increasetimeout; + } else { + return $timeout; + } + } + + /** + * Gets the default timeout. + * + * The timeout for each Behat step (load page, wait for an element to load...). + * + * @return int Timeout in seconds + */ + public static function get_timeout() : int { + return self::get_real_timeout(6); + } + + /** + * Gets the reduced timeout. + * + * A reduced timeout for cases where self::get_timeout() is too much + * and a simple $this->getSession()->getPage()->find() could not + * be enough. + * + * @return int Timeout in seconds + */ + public static function get_reduced_timeout() : int { + return self::get_real_timeout(2); + } + + /** + * Gets the extended timeout. + * + * A longer timeout for cases where the normal timeout is not enough. + * + * @return int Timeout in seconds + */ + public static function get_extended_timeout() : int { + return self::get_real_timeout(10); + } + + /** + * Return a list of the exact named selectors for the component. + * + * Named selectors are what make Behat steps like + * Then I should see "Useful text" in the "General" "fieldset" + * work. Here, "fieldset" is the named selector, and "General" is the locator. + * + * If you override this method in your plugin (e.g. mod_mymod), to define + * new selectors specific to your plugin. For example, if you returned + * new behat_component_named_selector('Thingy', + * [".//some/xpath//img[contains(@alt, %locator%)]/.."]) + * then + * Then I should see "Useful text" in the "Whatever" "mod_mymod > Thingy" + * would work. + * + * This method should return a list of {@link behat_component_named_selector} and + * the docs on that class explain how it works. + * + * @return behat_component_named_selector[] + */ + public static function get_exact_named_selectors(): array { + return []; + } + + /** + * Return a list of the partial named selectors for the component. + * + * Like the exact named selectors above, but the locator only + * needs to match part of the text. For example, the standard + * "button" is a partial selector, so: + * When I click "Save" "button" + * will activate "Save changes". + * + * @return behat_component_named_selector[] + */ + public static function get_partial_named_selectors(): array { + return []; + } + + /** + * Return a list of the Mink named replacements for the component. + * + * Named replacements allow you to define parts of an xpath that can be reused multiple times, or in multiple + * xpaths. + * + * This method should return a list of {@link behat_component_named_replacement} and the docs on that class explain + * how it works. + * + * @return behat_component_named_replacement[] + */ + public static function get_named_replacements(): array { + return []; + } + + /** + * Evaluate the supplied script in the current session, returning the result. + * + * @param string $script + * @return mixed + */ + public function evaluate_script(string $script) { + return self::evaluate_script_in_session($this->getSession(), $script); + } + + /** + * Evaluate the supplied script in the specified session, returning the result. + * + * @param Session $session + * @param string $script + * @return mixed + */ + public static function evaluate_script_in_session(Session $session, string $script) { + self::require_javascript_in_session($session); + + return $session->evaluateScript($script); + } + + /** + * Execute the supplied script in the current session. + * + * No result will be returned. + * + * @param string $script + */ + public function execute_script(string $script): void { + self::execute_script_in_session($this->getSession(), $script); + } + + /** + * Excecute the supplied script in the specified session. + * + * No result will be returned. + * + * @param Session $session + * @param string $script + */ + public static function execute_script_in_session(Session $session, string $script): void { + self::require_javascript_in_session($session); + + $session->executeScript($script); + } + + /** + * Get the session key for the current session via Javascript. + * + * @return string + */ + public function get_sesskey(): string { + $script = <<evaluate_script($script); + } +} diff --git a/lib/behat/classes/partial_named_selector.php b/lib/behat/classes/partial_named_selector.php index 18c1526c55b..74054eeb4a8 100644 --- a/lib/behat/classes/partial_named_selector.php +++ b/lib/behat/classes/partial_named_selector.php @@ -135,7 +135,7 @@ class behat_partial_named_selector extends \Behat\Mink\Selector\PartialNamedSele */ protected static $moodleselectors = array( 'activity' => << << <<session; + } + /** * General constructor with the node and the session to interact with. diff --git a/lib/behat/form_field/behat_form_inplaceeditable.php b/lib/behat/form_field/behat_form_inplaceeditable.php new file mode 100644 index 00000000000..57cc8b77c94 --- /dev/null +++ b/lib/behat/form_field/behat_form_inplaceeditable.php @@ -0,0 +1,74 @@ +. + +/** + * Custom interaction with inplace editable elements. + * + * @package core_form + * @category test + * @copyright 2019 Andrew Nicols + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +// NOTE: no MOODLE_INTERNAL test here, this file may be required by behat before including /config.php. + +require_once(__DIR__ . '/behat_form_text.php'); + +/** + * Custom interaction with inplace editable elements. + * + * @package core_form + * @category test + * @copyright 2019 Andrew Nicols + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class behat_form_inplaceeditable extends behat_form_text { + /** + * Sets the value to a field. + * + * @param string $value + * @return void + */ + public function set_value($value) { + // Require JS to run this step. + self::require_javascript(); + + // Click to enable editing. + self::execute( + 'behat_general::i_click_on_in_the', + [ + '[data-inplaceeditablelink]', + 'css_element', + $this->field, + 'NodeElement', + ] + ); + + // Note: It is not possible to use the NodeElement->keyDown() and related functions because + // this can trigger a focusOnElement call each time. + // Instead use the behat_base::type_keys() function. + + // The inplace editable selects all existing content on focus. + // Clear the existing value. + self::type_keys($this->session, [behat_keys::BACKSPACE]); + + // Type in the new value, followed by ENTER to save the value. + self::type_keys($this->session, array_merge( + str_split($value), + [behat_keys::ENTER] + )); + } +} diff --git a/mod/book/tests/behat/edit_tags.feature b/mod/book/tests/behat/edit_tags.feature index 938b07f9a2d..7b2b8c70e60 100644 --- a/mod/book/tests/behat/edit_tags.feature +++ b/mod/book/tests/behat/edit_tags.feature @@ -12,16 +12,16 @@ Feature: Edited book chapters handle tags correctly And the following "courses" exist: | fullname | shortname | format | | Course 1 | C1 | topics | + And the following "activity" exists: + | activity | book | + | course | C1 | + | idnumber | book1 | + | name | Test book | + | description | A book about dreams | And the following "course enrolments" exist: | user | course | role | | teacher1 | C1 | editingteacher | | student1 | C1 | student | - And I log in as "teacher1" - And I am on "Course 1" course homepage with editing mode on - And I add a "Book" to section "1" and I fill the form with: - | Name | Test book | - | Description | A book about dreams! | - And I log out Scenario: Book chapter edition of custom tags works as expected Given I log in as "teacher1" diff --git a/mod/forum/tests/behat/advanced_search.feature b/mod/forum/tests/behat/advanced_search.feature index 90dd16298c8..dbcca3b8797 100644 --- a/mod/forum/tests/behat/advanced_search.feature +++ b/mod/forum/tests/behat/advanced_search.feature @@ -130,8 +130,7 @@ Feature: The forum search allows users to perform advanced searches for forum po And I press "Search forums" And I should see "Advanced search" And I set the field "Is tagged with" to "SearchedTag" - And I click on "[data-value='SearchedTag']" "css_element" - And I press the escape key + And I press the enter key When I press "Search forums" Then I should see "My subject" And I should not see "Your subjective" diff --git a/mod/lti/tests/behat/renametool.feature b/mod/lti/tests/behat/renametool.feature index 30eed0702d0..48eee71af4c 100644 --- a/mod/lti/tests/behat/renametool.feature +++ b/mod/lti/tests/behat/renametool.feature @@ -21,9 +21,7 @@ Feature: Rename external tools via inline editing And I am on "Course 1" course homepage with editing mode on And I add a "External tool" to section "1" and I fill the form with: | Activity name | Test tool activity 1 | - And I click on "Edit title" "link" in the "li#section-1" "css_element" - And I set the field "New name for activity Test tool activity 1" to "Test tool activity renamed" - And I press the enter key + And I set the field "Edit title" in the "li#section-1" "css_element" to "Test tool activity renamed" And I navigate to "Setup > Gradebook setup" in the course gradebook Then I should not see "Test tool activity 1" And I should see "Test tool activity renamed" diff --git a/mod/quiz/tests/behat/behat_mod_quiz.php b/mod/quiz/tests/behat/behat_mod_quiz.php index 5db5ba702e7..417b26d370a 100644 --- a/mod/quiz/tests/behat/behat_mod_quiz.php +++ b/mod/quiz/tests/behat/behat_mod_quiz.php @@ -397,7 +397,8 @@ class behat_mod_quiz extends behat_question_base { $this->execute('behat_general::assert_page_contains_text', $this->escape(get_string('edittitleinstructions'))); - $this->execute('behat_forms::i_set_the_field_to', array('maxmark', $this->escape($newmark) . chr(10))); + $this->execute('behat_general::i_type', [$newmark]); + $this->execute('behat_general::i_press_named_key', ['', 'enter']); } /** @@ -653,7 +654,9 @@ class behat_mod_quiz extends behat_question_base { $this->execute('behat_general::assert_page_contains_text', $this->escape(get_string('edittitleinstructions'))); - $this->execute('behat_forms::i_set_the_field_to', array('section', $this->escape($sectionheading) . chr(10))); + $this->execute('behat_general::i_press_named_key', ['', 'backspace']); + $this->execute('behat_general::i_type', [$sectionheading]); + $this->execute('behat_general::i_press_named_key', ['', 'enter']); } /** diff --git a/mod/quiz/tests/behat/editing_set_marks_no_attempts.feature b/mod/quiz/tests/behat/editing_set_marks_no_attempts.feature index b4bee513a0b..47a382f1762 100644 --- a/mod/quiz/tests/behat/editing_set_marks_no_attempts.feature +++ b/mod/quiz/tests/behat/editing_set_marks_no_attempts.feature @@ -17,16 +17,19 @@ Feature: Edit quiz marks with no attempts And the following "activities" exist: | activity | name | course | idnumber | grade | decimalpoints | questiondecimalpoints | | quiz | Quiz 1 | C1 | quiz1 | 20 | 2 | -1 | - And I log in as "teacher1" - And I am on "Course 1" course homepage - And I add a "True/False" question to the "Quiz 1" quiz with: - | Question name | First question | - | Question text | Answer me | - | Default mark | 2.0 | - And I add a "True/False" question to the "Quiz 1" quiz with: - | Question name | Second question | - | Question text | Answer again | - | Default mark | 3.0 | + + And the following "question categories" exist: + | contextlevel | reference | name | + | Course | C1 | Test questions | + And the following "questions" exist: + | questioncategory | qtype | name | questiontext | + | Test questions | truefalse | First question | Answer me | + | Test questions | truefalse | Second question | Answer again | + And quiz "Quiz 1" contains the following questions: + | question | page | maxmark | + | First question | 1 | 2.0 | + | Second question | 1 | 3.0 | + And I am on the "Quiz 1" "mod_quiz > Edit" page logged in as "teacher1" @javascript Scenario: Set the max mark for a question. diff --git a/tag/tests/behat/collections.feature b/tag/tests/behat/collections.feature index 6cdb568b7c4..50bdd8bf9cb 100644 --- a/tag/tests/behat/collections.feature +++ b/tag/tests/behat/collections.feature @@ -28,15 +28,11 @@ Feature: Managers can create and manage tag collections Scenario: Adding tag collections When I follow "Hobbies" Then I should see "Nothing to display" - And I log out Scenario: Editing tag collections - When I click on "Edit tag collection name" "link" in the "//table[contains(@class,'tag-collections-table')]//tr[contains(.,'Hobbies')]" "xpath_element" - And I set the field "New name for tag collection Hobbies" to "Newname" - And I press the enter key + When I set the field "Edit tag collection name" in the "//table[contains(@class,'tag-collections-table')]//tr[contains(.,'Hobbies')]" "xpath_element" to "Newname" Then I should not see "Hobbies" And I should see "Newname" - And I log out Scenario: Resorting tag collections When I follow "Add tag collection" @@ -48,41 +44,34 @@ Feature: Managers can create and manage tag collections And "Blogging" "link" should appear before "Hobbies" "link" And I click on "Move down" "link" in the "Blogging" "table_row" And "Blogging" "link" should appear after "Hobbies" "link" - And I log out Scenario: Deleting tag collections When I click on "Delete" "link" in the "Hobbies" "table_row" Then I should see "Are you sure you want to delete tag collection \"Hobbies\"?" And I press "Yes" And I should not see "Hobbies" - And I log out Scenario: Assigning tag area to tag collection And I should see "User interests" in the "//table[contains(@class,'tag-collections-table')]//tr[contains(.,'Default collection')]" "xpath_element" And I should not see "User interests" in the "//table[contains(@class,'tag-collections-table')]//tr[contains(.,'Hobbies')]" "xpath_element" - When I click on "Change tag collection" "link" in the "//table[contains(@class,'tag-areas-table')]//tr[contains(.,'User interests')]" "xpath_element" - And I set the field "Change tag collection of area User interests" to "Hobbies" + When I set the field "Change tag collection" in the "//table[contains(@class,'tag-areas-table')]//tr[contains(.,'User interests')]" "xpath_element" to "Hobbies" Then I should not see "User interests" in the "//table[contains(@class,'tag-collections-table')]//tr[contains(.,'Default collection')]" "xpath_element" And I should see "User interests" in the "//table[contains(@class,'tag-collections-table')]//tr[contains(.,'Hobbies')]" "xpath_element" And I should see "Hobbies" in the "//table[contains(@class,'tag-areas-table')]//tr[contains(.,'User interests')]" "xpath_element" - And I log out Scenario: Disabling tag areas When I click on "Disable" "link" in the "//table[contains(@class,'tag-areas-table')]//tr[contains(.,'User interests')]" "xpath_element" And I should not see "User interests" in the "table.tag-collections-table" "css_element" And I click on "Enable" "link" in the "//table[contains(@class,'tag-areas-table')]//tr[contains(.,'User interests')]" "xpath_element" And I should see "User interests" in the "//table[contains(@class,'tag-collections-table')]//tr[contains(.,'Default collection')]" "xpath_element" - And I log out Scenario: Deleting non-empty tag collections - When I click on "Change tag collection" "link" in the "//table[contains(@class,'tag-areas-table')]//tr[contains(.,'User interests')]" "xpath_element" - And I set the field "Change tag collection of area User interests" to "Hobbies" + When I set the field "Change tag collection" in the "//table[contains(@class,'tag-areas-table')]//tr[contains(.,'User interests')]" "xpath_element" to "Hobbies" And I click on "Delete" "link" in the "Hobbies" "table_row" Then I should see "Are you sure you want to delete tag collection \"Hobbies\"?" And I press "Yes" And I should not see "Hobbies" And I should see "User interests" in the "//table[contains(@class,'tag-collections-table')]//tr[contains(.,'Default collection')]" "xpath_element" - And I log out Scenario: Moving tags when changing tag collections And I open my profile in edit mode @@ -90,8 +79,7 @@ Feature: Managers can create and manage tag collections And I set the field "List of interests" to "Swimming, Tag0, Tag3" And I press "Update profile" And I navigate to "Appearance > Manage tags" in site administration - When I click on "Change tag collection" "link" in the "//table[contains(@class,'tag-areas-table')]//tr[contains(.,'User interests')]" "xpath_element" - And I set the field "Change tag collection of area User interests" to "Hobbies" + When I set the field "Change tag collection" in the "//table[contains(@class,'tag-areas-table')]//tr[contains(.,'User interests')]" "xpath_element" to "Hobbies" And I follow "Hobbies" Then I should see "Swimming" And I should see "Tag0" @@ -107,7 +95,6 @@ Feature: Managers can create and manage tag collections And I should see "Tag3" And I should see "Tag1" And I should see "Tag2" - And I log out Scenario: Creating searchable and non-searchable tag collections And I follow "Add tag collection" @@ -129,4 +116,3 @@ Feature: Managers can create and manage tag collections And I click on "Site pages" "list_item" in the "Navigation" "block" And I click on "Tags" "link" in the "Navigation" "block" And "Select tag collection" "select" should not exist - And I log out diff --git a/tag/tests/behat/edit_tag.feature b/tag/tests/behat/edit_tag.feature index 4682edb587b..c3bc35e51ec 100644 --- a/tag/tests/behat/edit_tag.feature +++ b/tag/tests/behat/edit_tag.feature @@ -158,19 +158,14 @@ Feature: Users can edit tags to add description or rename And I navigate to "Appearance > Manage tags" in site administration And I follow "Default collection" # Renaming tag to a valid name - And I click on "Edit tag name" "link" in the "Cat" "table_row" - And I set the field "New name for tag Cat" to "Kitten" - And I press the enter key + And I set the field "Edit tag name" in the "Cat" "table_row" to "Kitten" Then I should not see "Cat" And "New name for tag" "field" should not exist - And I wait until "Kitten" "link" exists And I follow "Default collection" And I should see "Kitten" And I should not see "Cat" # Renaming tag to an invalid name - And I click on "Edit tag name" "link" in the "Turtle" "table_row" - And I set the field "New name for tag Turtle" to "DOG" - And I press the enter key + And I set the field "Edit tag name" in the "Turtle" "table_row" to "DOG" And I should see "The tag name is already in use. Do you want to combine these tags?" And I click on "Cancel" "button" in the "Confirm" "dialogue" And "New name for tag" "field" should not exist @@ -183,7 +178,7 @@ Feature: Users can edit tags to add description or rename And I should not see "DOG" # Cancel tag renaming And I click on "Edit tag name" "link" in the "Dog" "table_row" - And I set the field "New name for tag Dog" to "Penguin" + And I type "Penguin" And I press the escape key And "New name for tag" "field" should not exist And I should see "Turtle" @@ -197,9 +192,7 @@ Feature: Users can edit tags to add description or rename When I log in as "manager1" And I navigate to "Appearance > Manage tags" in site administration And I follow "Default collection" - And I click on "Edit tag name" "link" in the "Turtle" "table_row" - And I set the field "New name for tag Turtle" to "DOG" - And I press the enter key + And I set the field "Edit tag name" in the "Turtle" "table_row" to "DOG" And I should see "The tag name is already in use. Do you want to combine these tags?" And I press "Yes" Then I should not see "Turtle"