2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * Navigation steps definitions.
22 * @copyright 2012 David Monllaó
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 // NOTE: no MOODLE_INTERNAL test here, this file may be required by behat before including /config.php.
28 require_once(__DIR__ . '/../../behat/behat_base.php');
30 use Behat\Mink\Exception\ExpectationException as ExpectationException;
31 use Behat\Mink\Exception\DriverException as DriverException;
34 * Steps definitions to navigate through the navigation tree nodes.
38 * @copyright 2012 David Monllaó
39 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
41 class behat_navigation extends behat_base {
44 * Helper function to get a navigation nodes text element given its text from within the navigation block.
46 * This function finds the node with the given text from within the navigation block.
47 * It checks to make sure the node is visible, and then returns it.
50 * @param bool $branch Set this true if you're only interested in the node if its a branch.
51 * @param null|bool $collapsed Set this to true or false if you want the node to either be collapsed or not.
52 * If its left as null then we don't worry about it.
53 * @param null|string|Exception|false $exception The exception to throw if the node is not found.
54 * @return \Behat\Mink\Element\NodeElement
56 protected function get_node_text_node($text, $branch = false, $collapsed = null, $exception = null) {
57 if ($exception === null) {
58 $exception = new ExpectationException('The "' . $text . '" node could not be found', $this->getSession());
59 } else if (is_string($exception)) {
60 $exception = new ExpectationException($exception, $this->getSession());
63 $nodetextliteral = behat_context_helper::escape($text);
64 $hasblocktree = "[contains(concat(' ', normalize-space(@class), ' '), ' block_tree ')]";
65 $hasbranch = "[contains(concat(' ', normalize-space(@class), ' '), ' branch ')]";
66 $hascollapsed = "p[@aria-expanded='false']";
67 $notcollapsed = "p[@aria-expanded='true']";
68 $match = "[normalize-space(.)={$nodetextliteral}]";
70 // Avoid problems with quotes.
71 $isbranch = ($branch) ? $hasbranch : '';
72 if ($collapsed === true) {
73 $iscollapsed = $hascollapsed;
74 } else if ($collapsed === false) {
75 $iscollapsed = $notcollapsed;
80 // First check root nodes, it can be a span or link.
81 $xpath = "//ul{$hasblocktree}/li/{$hascollapsed}{$isbranch}/span{$match}|";
82 $xpath .= "//ul{$hasblocktree}/li/{$hascollapsed}{$isbranch}/a{$match}|";
84 // Next search for the node containing the text within a link.
85 $xpath .= "//ul{$hasblocktree}//ul/li/{$iscollapsed}{$isbranch}/a{$match}|";
87 // Finally search for the node containing the text within a span.
88 $xpath .= "//ul{$hasblocktree}//ul/li/{$iscollapsed}{$isbranch}/span{$match}";
90 $node = $this->find('xpath', $xpath, $exception);
91 $this->ensure_node_is_visible($node);
96 * Returns true if the navigation node with the given text is expandable.
98 * @Given /^navigation node "([^"]*)" should be expandable$/
100 * @throws ExpectationException
101 * @param string $nodetext
104 public function navigation_node_should_be_expandable($nodetext) {
105 if (!$this->running_javascript()) {
106 // Nodes are only expandable when JavaScript is enabled.
110 $node = $this->get_node_text_node($nodetext, true);
111 $node = $node->getParent();
112 if ($node->hasClass('emptybranch')) {
113 throw new ExpectationException('The "' . $nodetext . '" node is not expandable', $this->getSession());
120 * Returns true if the navigation node with the given text is not expandable.
122 * @Given /^navigation node "([^"]*)" should not be expandable$/
124 * @throws ExpectationException
125 * @param string $nodetext
128 public function navigation_node_should_not_be_expandable($nodetext) {
129 if (!$this->running_javascript()) {
130 // Nodes are only expandable when JavaScript is enabled.
134 $node = $this->get_node_text_node($nodetext);
135 $node = $node->getParent();
137 if ($node->hasClass('emptybranch') || $node->hasClass('tree_item')) {
140 throw new ExpectationException('The "' . $nodetext . '" node is expandable', $this->getSession());
144 * Click on an entry in the user menu.
145 * @Given /^I follow "(?P<nodetext_string>(?:[^"]|\\")*)" in the user menu$/
147 * @param string $nodetext
149 public function i_follow_in_the_user_menu($nodetext) {
151 if ($this->running_javascript()) {
152 // The user menu must be expanded when JS is enabled.
153 $xpath = "//div[@class='usermenu']//a[contains(concat(' ', @class, ' '), ' toggle-display ')]";
154 $this->execute("behat_general::i_click_on", array($this->escape($xpath), "xpath_element"));
157 // Now select the link.
158 // The CSS path is always present, with or without JS.
159 $csspath = ".usermenu [data-rel='menu-content']";
161 $this->execute('behat_general::i_click_on_in_the',
162 array($nodetext, "link", $csspath, "css_element")
167 * Expands the selected node of the navigation tree that matches the text.
168 * @Given /^I expand "(?P<nodetext_string>(?:[^"]|\\")*)" node$/
170 * @throws ExpectationException
171 * @param string $nodetext
174 public function i_expand_node($nodetext) {
176 // This step is useless with Javascript disabled as Moodle auto expands
177 // all of tree's nodes; adding this because of scenarios that shares the
178 // same steps with and without Javascript enabled.
179 if (!$this->running_javascript()) {
180 if ($nodetext === get_string('administrationsite')) {
181 // Administration menu is not loaded by default any more. Click the link to expand.
182 $this->execute('behat_general::i_click_on_in_the',
183 array($nodetext, "link", get_string('administration'), "block")
190 $node = $this->get_node_text_node($nodetext, true, true, 'The "' . $nodetext . '" node can not be expanded');
191 // Check if the node is a link AND a branch.
192 if (strtolower($node->getTagName()) === 'a') {
193 // We just want to expand the node, we don't want to follow it.
194 $node = $node->getParent();
200 * Collapses the selected node of the navigation tree that matches the text.
202 * @Given /^I collapse "(?P<nodetext_string>(?:[^"]|\\")*)" node$/
203 * @throws ExpectationException
204 * @param string $nodetext
207 public function i_collapse_node($nodetext) {
209 // No collapsible nodes with non-JS browsers.
210 if (!$this->running_javascript()) {
214 $node = $this->get_node_text_node($nodetext, true, false, 'The "' . $nodetext . '" node can not be collapsed');
215 // Check if the node is a link AND a branch.
216 if (strtolower($node->getTagName()) === 'a') {
217 // We just want to expand the node, we don't want to follow it.
218 $node = $node->getParent();
224 * Click link in navigation tree that matches the text in parentnode/s (seperated using greater-than character if more than one)
226 * @Given /^I navigate to "(?P<nodetext_string>(?:[^"]|\\")*)" node in "(?P<parentnodes_string>(?:[^"]|\\")*)"$/
228 * @todo MDL-57281 deprecate in Moodle 3.1
230 * @throws ExpectationException
231 * @param string $nodetext navigation node to click.
232 * @param string $parentnodes comma seperated list of parent nodes.
235 public function i_navigate_to_node_in($nodetext, $parentnodes) {
236 // This step needs to be deprecated and replaced with one of:
237 // - I navigate to "PATH" in current page administration
238 // - I navigate to "PATH" in site administration
239 // - I navigate to course participants
240 // - I navigate to "PATH" in the course gradebook
241 // - I click on "LINK" "link" in the "Navigation" "block" .
242 $parentnodes = array_map('trim', explode('>', $parentnodes));
243 $this->select_node_in_navigation($nodetext, $parentnodes);
247 * Finds a node in the Navigation or Administration tree
249 * @param string $nodetext
250 * @param array $parentnodes
251 * @param string $nodetype node type (link or text)
252 * @return NodeElement|null
253 * @throws ExpectationException when one of the parent nodes is not found
255 protected function find_node_in_navigation($nodetext, $parentnodes, $nodetype = 'link') {
256 // Site admin is different and needs special treatment.
257 $siteadminstr = get_string('administrationsite');
259 // Create array of all parentnodes.
260 $countparentnode = count($parentnodes);
262 // If JS is disabled and Site administration is not expanded we
263 // should follow it, so all the lower-level nodes are available.
264 if (!$this->running_javascript()) {
265 if ($parentnodes[0] === $siteadminstr) {
266 // We don't know if there if Site admin is already expanded so
267 // don't wait, it is non-JS and we already waited for the DOM.
268 $siteadminlink = $this->getSession()->getPage()->find('named_exact', array('link', "'" . $siteadminstr . "'"));
269 if ($siteadminlink) {
270 $siteadminlink->click();
275 // Get top level node.
276 $node = $this->get_top_navigation_node($parentnodes[0]);
279 for ($i = 0; $i < $countparentnode; $i++) {
281 // Sub nodes within top level node.
282 $node = $this->get_navigation_node($parentnodes[$i], $node);
285 // The p node contains the aria jazz.
286 $pnodexpath = "/p[contains(concat(' ', normalize-space(@class), ' '), ' tree_item ')]";
287 $pnode = $node->find('xpath', $pnodexpath);
289 // Keep expanding all sub-parents if js enabled.
290 if ($pnode && $this->running_javascript() && $pnode->hasAttribute('aria-expanded') &&
291 ($pnode->getAttribute('aria-expanded') == "false")) {
293 $this->js_trigger_click($pnode);
295 // Wait for node to load, if not loaded before.
296 if ($pnode->hasAttribute('data-loaded') && $pnode->getAttribute('data-loaded') == "false") {
297 $jscondition = '(document.evaluate("' . $pnode->getXpath() . '", document, null, '.
298 'XPathResult.ANY_TYPE, null).iterateNext().getAttribute(\'data-loaded\') == "true")';
300 $this->getSession()->wait(self::EXTENDED_TIMEOUT * 1000, $jscondition);
305 // Finally, click on requested node under navigation.
306 $nodetextliteral = behat_context_helper::escape($nodetext);
307 $tagname = ($nodetype === 'link') ? 'a' : 'span';
308 $xpath = "/ul/li/p[contains(concat(' ', normalize-space(@class), ' '), ' tree_item ')]" .
309 "/{$tagname}[normalize-space(.)=" . $nodetextliteral . "]";
310 return $node->find('xpath', $xpath);
314 * Finds a node in the Navigation or Administration tree and clicks on it.
316 * @param string $nodetext
317 * @param array $parentnodes
318 * @throws ExpectationException
320 protected function select_node_in_navigation($nodetext, $parentnodes) {
321 $nodetoclick = $this->find_node_in_navigation($nodetext, $parentnodes);
322 // Throw exception if no node found.
324 throw new ExpectationException('Navigation node "' . $nodetext . '" not found under "' .
325 implode($parentnodes, ' > ') . '"', $this->getSession());
328 $nodetoclick->click();
332 * Helper function to get top navigation node in tree.
334 * @throws ExpectationException if note not found.
335 * @param string $nodetext name of top navigation node in tree.
336 * @return NodeElement
338 protected function get_top_navigation_node($nodetext) {
340 // Avoid problems with quotes.
341 $nodetextliteral = behat_context_helper::escape($nodetext);
342 $exception = new ExpectationException('Top navigation node "' . $nodetext . ' not found in "', $this->getSession());
344 // First find in navigation block.
345 $xpath = "//div[contains(concat(' ', normalize-space(@class), ' '), ' content ')]" .
346 "/ul[contains(concat(' ', normalize-space(@class), ' '), ' block_tree ')]" .
347 "/li[contains(concat(' ', normalize-space(@class), ' '), ' contains_branch ')]" .
348 "/ul/li[contains(concat(' ', normalize-space(@class), ' '), ' contains_branch ')]" .
349 "[p[contains(concat(' ', normalize-space(@class), ' '), ' branch ')]" .
350 "[span[normalize-space(.)=" . $nodetextliteral ."] or a[normalize-space(.)=" . $nodetextliteral ."]]]" .
352 "//div[contains(concat(' ', normalize-space(@class), ' '), ' content ')]/div" .
353 "/ul[contains(concat(' ', normalize-space(@class), ' '), ' block_tree ')]" .
354 "/li[contains(concat(' ', normalize-space(@class), ' '), ' contains_branch ')]" .
355 "/ul/li[contains(concat(' ', normalize-space(@class), ' '), ' contains_branch ')]" .
356 "[p[contains(concat(' ', normalize-space(@class), ' '), ' branch ')]" .
357 "/span[normalize-space(.)=" . $nodetextliteral ."]]" .
359 "//div[contains(concat(' ', normalize-space(@class), ' '), ' content ')]/div" .
360 "/ul[contains(concat(' ', normalize-space(@class), ' '), ' block_tree ')]" .
361 "/li[p[contains(concat(' ', normalize-space(@class), ' '), ' branch ')]" .
362 "/span[normalize-space(.)=" . $nodetextliteral ."]]" .
364 "//div[contains(concat(' ', normalize-space(@class), ' '), ' content ')]/div" .
365 "/ul[contains(concat(' ', normalize-space(@class), ' '), ' block_tree ')]" .
366 "/li[p[contains(concat(' ', normalize-space(@class), ' '), ' branch ')]" .
367 "/a[normalize-space(.)=" . $nodetextliteral ."]]";
369 $node = $this->find('xpath', $xpath, $exception);
375 * Helper function to get sub-navigation node.
377 * @throws ExpectationException if note not found.
378 * @param string $nodetext node to find.
379 * @param NodeElement $parentnode parent navigation node.
380 * @return NodeElement.
382 protected function get_navigation_node($nodetext, $parentnode = null) {
384 // Avoid problems with quotes.
385 $nodetextliteral = behat_context_helper::escape($nodetext);
387 $xpath = "/ul/li[contains(concat(' ', normalize-space(@class), ' '), ' contains_branch ')]" .
388 "[child::p[contains(concat(' ', normalize-space(@class), ' '), ' branch ')]" .
389 "/child::span[normalize-space(.)=" . $nodetextliteral ."]]";
390 $node = $parentnode->find('xpath', $xpath);
392 $xpath = "/ul/li[contains(concat(' ', normalize-space(@class), ' '), ' contains_branch ')]" .
393 "[child::p[contains(concat(' ', normalize-space(@class), ' '), ' branch ')]" .
394 "/child::a[normalize-space(.)=" . $nodetextliteral ."]]";
395 $node = $parentnode->find('xpath', $xpath);
399 throw new ExpectationException('Sub-navigation node "' . $nodetext . '" not found under "' .
400 $parentnode->getText() . '"', $this->getSession());
406 * Step to open the navigation bar if it is needed.
408 * The top log in and log out links are hidden when middle or small
409 * size windows (or devices) are used. This step returns a step definition
410 * clicking to expand the navbar if it is hidden.
412 * @Given /^I expand navigation bar$/
414 public function get_expand_navbar_step() {
416 // Checking if we need to click the navbar button to show the navigation menu, it
417 // is hidden by default when using clean theme and a medium or small screen size.
419 // The DOM and the JS should be all ready and loaded. Running without spinning
420 // as this is a widely used step and we can not spend time here trying to see
421 // a DOM node that is not always there (at the moment clean is not even the
422 // default theme...).
423 $navbuttonjs = "return (
424 Y.one('.btn-navbar') &&
425 Y.one('.btn-navbar').getComputedStyle('display') !== 'none'
428 // Adding an extra click we need to show the 'Log in' link.
429 if (!$this->getSession()->getDriver()->evaluateScript($navbuttonjs)) {
433 $this->execute('behat_general::i_click_on', array(".btn-navbar", "css_element"));
437 * Go to current page setting item
439 * This can be used on front page, course, category or modules pages.
441 * @Given /^I navigate to "(?P<nodetext_string>(?:[^"]|\\")*)" in current page administration$/
443 * @throws ExpectationException
444 * @param string $nodetext navigation node to click, may contain path, for example "Reports > Overview"
447 public function i_navigate_to_in_current_page_administration($nodetext) {
448 $parentnodes = array_map('trim', explode('>', $nodetext));
449 // Find the name of the first category of the administration block tree.
450 $xpath = '//div[contains(@class,\'block_settings\')]//div[@id=\'settingsnav\']/ul/li[1]/p[1]/span';
451 $node = $this->find('xpath', $xpath);
452 array_unshift($parentnodes, $node->getText());
453 $lastnode = array_pop($parentnodes);
454 $this->select_node_in_navigation($lastnode, $parentnodes);
458 * Checks that current page administration contains text
460 * @Given /^"(?P<element_string>(?:[^"]|\\")*)" "(?P<selector_string>[^"]*)" should exist in current page administration$/
462 * @throws ExpectationException
463 * @param string $element The locator of the specified selector.
464 * This may be a path, for example "Subscription mode > Forced subscription"
465 * @param string $selectortype The selector type (link or text)
468 public function should_exist_in_current_page_administration($element, $selectortype) {
469 $parentnodes = array_map('trim', explode('>', $element));
470 // Find the name of the first category of the administration block tree.
471 $xpath = '//div[contains(@class,\'block_settings\')]//div[@id=\'settingsnav\']/ul/li[1]/p[1]/span';
472 $node = $this->find('xpath', $xpath);
473 array_unshift($parentnodes, $node->getText());
474 $lastnode = array_pop($parentnodes);
476 if (!$this->find_node_in_navigation($lastnode, $parentnodes, strtolower($selectortype))) {
477 throw new ExpectationException(ucfirst($selectortype) . ' "' . $element .
478 '" not found in current page administration"', $this->getSession());
483 * Checks that current page administration contains text
485 * @Given /^"(?P<element_string>(?:[^"]|\\")*)" "(?P<selector_string>[^"]*)" should not exist in current page administration$/
487 * @throws ExpectationException
488 * @param string $element The locator of the specified selector.
489 * This may be a path, for example "Subscription mode > Forced subscription"
490 * @param string $selectortype The selector type (link or text)
493 public function should_not_exist_in_current_page_administration($element, $selectortype) {
494 $parentnodes = array_map('trim', explode('>', $element));
495 // Find the name of the first category of the administration block tree.
496 $xpath = '//div[contains(@class,\'block_settings\')]//div[@id=\'settingsnav\']/ul/li[1]/p[1]/span';
497 $node = $this->find('xpath', $xpath);
498 array_unshift($parentnodes, $node->getText());
499 $lastnode = array_pop($parentnodes);
501 if ($this->find_node_in_navigation($lastnode, $parentnodes, strtolower($selectortype))) {
502 throw new ExpectationException(ucfirst($selectortype) . ' "' . $element .
503 '" found in current page administration"', $this->getSession());
508 * Go to site administration item
510 * @Given /^I navigate to "(?P<nodetext_string>(?:[^"]|\\")*)" in site administration$/
512 * @throws ExpectationException
513 * @param string $nodetext navigation node to click, may contain path, for example "Reports > Overview"
516 public function i_navigate_to_in_site_administration($nodetext) {
517 $parentnodes = array_map('trim', explode('>', $nodetext));
518 array_unshift($parentnodes, get_string('administrationsite'));
519 $lastnode = array_pop($parentnodes);
520 $this->select_node_in_navigation($lastnode, $parentnodes);
524 * Opens the current users profile page in edit mode.
526 * @Given /^I open my profile in edit mode$/
527 * @throws coding_exception
530 public function i_open_my_profile_in_edit_mode() {
533 $user = $this->get_session_user();
535 $USER = $user; // We need this set to the behat session user so we can call isloggedin.
537 $systemcontext = context_system::instance();
539 $bodynode = $this->find('xpath', 'body');
540 $bodyclass = $bodynode->getAttribute('class');
542 if (preg_match('/(?<=^course-|\scourse-)\d/', $bodyclass, $matches) && !empty($matches)) {
543 $courseid = intval($matches[0]);
548 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
549 if (is_siteadmin($user) || has_capability('moodle/user:update', $systemcontext)) {
550 $url = new moodle_url('/user/editadvanced.php', array('id' => $user->id, 'course' => SITEID,
551 'returnto' => 'profile'));
552 } else if (has_capability('moodle/user:editownprofile', $systemcontext)) {
553 $userauthplugin = false;
554 if (!empty($user->auth)) {
555 $userauthplugin = get_auth_plugin($user->auth);
557 if ($userauthplugin && $userauthplugin->can_edit_profile()) {
558 $url = $userauthplugin->edit_profile_url();
560 if (empty($course)) {
561 $url = new moodle_url('/user/edit.php', array('id' => $user->id, 'returnto' => 'profile'));
563 $url = new moodle_url('/user/edit.php', array('id' => $user->id, 'course' => $courseid,
564 'returnto' => 'profile'));
570 $this->getSession()->visit($this->locate_path($url->out_as_local_url()));
573 // Restore global user variable.
578 * Opens the course homepage.
580 * @Given /^I am on "(?P<coursefullname_string>(?:[^"]|\\")*)" course homepage$/
581 * @throws coding_exception
582 * @param $coursefullname string The full name of the course.
585 public function i_am_on_course_homepage($coursefullname) {
587 $course = $DB->get_record("course", array("fullname" => $coursefullname), 'id', MUST_EXIST);
588 $url = new moodle_url('/course/view.php', ['id' => $course->id]);
589 $this->getSession()->visit($this->locate_path($url->out_as_local_url(false)));
593 * Opens the course homepage with editing mode on.
595 * @Given /^I am on "(?P<coursefullname_string>(?:[^"]|\\")*)" course homepage with editing mode on$/
596 * @throws coding_exception
597 * @param $coursefullname string The course full name of the course.
600 public function i_am_on_course_homepage_with_editing_mode_on($coursefullname) {
602 $course = $DB->get_record("course", array("fullname" => $coursefullname), 'id', MUST_EXIST);
603 $url = new moodle_url('/course/view.php', ['id' => $course->id]);
604 $this->getSession()->visit($this->locate_path($url->out_as_local_url(false)));
606 $this->execute("behat_forms::press_button", get_string('turneditingon'));
607 } catch (Exception $e) {
608 $this->execute("behat_navigation::i_navigate_to_in_current_page_administration", [get_string('turneditingon')]);