MDL-59548 behat: fix trailing whitespace
[moodle.git] / lib / tests / behat / behat_forms.php
CommitLineData
23ebc481
DM
1<?php
2// This file is part of Moodle - http://moodle.org/
3//
4// Moodle is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// Moodle is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
16
17/**
18 * Steps definitions related with forms.
19 *
20 * @package core
21 * @category test
22 * @copyright 2012 David MonllaĆ³
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 */
25
26// NOTE: no MOODLE_INTERNAL test here, this file may be required by behat before including /config.php.
27
28require_once(__DIR__ . '/../../../lib/behat/behat_base.php');
a4534dce 29require_once(__DIR__ . '/../../../lib/behat/behat_field_manager.php');
23ebc481 30
42ad096f 31use Behat\Gherkin\Node\TableNode as TableNode,
9776f3dc 32 Behat\Gherkin\Node\PyStringNode as PyStringNode,
23ebc481
DM
33 Behat\Mink\Exception\ExpectationException as ExpectationException,
34 Behat\Mink\Exception\ElementNotFoundException as ElementNotFoundException;
35
36/**
37 * Forms-related steps definitions.
38 *
39 * @package core
40 * @category test
41 * @copyright 2012 David MonllaĆ³
42 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
43 */
44class behat_forms extends behat_base {
45
46 /**
47 * Presses button with specified id|name|title|alt|value.
48 *
23ebc481 49 * @When /^I press "(?P<button_string>(?:[^"]|\\")*)"$/
1f9ffbdb 50 * @throws ElementNotFoundException Thrown by behat_base::find
46ac40cd 51 * @param string $button
23ebc481
DM
52 */
53 public function press_button($button) {
1f9ffbdb
DM
54
55 // Ensures the button is present.
56 $buttonnode = $this->find_button($button);
ddf36bf5
RT
57 // Focus on button to ensure it is in viewport, before pressing it.
58 if ($this->running_javascript()) {
59 $buttonnode->focus();
60 }
1f9ffbdb 61 $buttonnode->press();
23ebc481
DM
62 }
63
1ef6a5e3
RT
64 /**
65 * Press button with specified id|name|title|alt|value and switch to main window.
66 *
67 * @When /^I press "(?P<button_string>(?:[^"]|\\")*)" and switch to main window$/
68 * @throws ElementNotFoundException Thrown by behat_base::find
69 * @param string $button
70 */
71 public function press_button_and_switch_to_main_window($button) {
72 // Ensures the button is present, before pressing.
73 $buttonnode = $this->find_button($button);
74 $buttonnode->press();
75
76 // Switch to main window.
77 $this->getSession()->switchToWindow(behat_general::MAIN_WINDOW_NAME);
78 }
79
23ebc481 80 /**
a5254141 81 * Fills a form with field/value data. More info in http://docs.moodle.org/dev/Acceptance_testing#Providing_values_to_steps.
23ebc481 82 *
a5254141 83 * @Given /^I set the following fields to these values:$/
1f9ffbdb 84 * @throws ElementNotFoundException Thrown by behat_base::find
23ebc481
DM
85 * @param TableNode $data
86 */
a5254141 87 public function i_set_the_following_fields_to_these_values(TableNode $data) {
23ebc481 88
f8f1bdc3
DM
89 // Expand all fields in case we have.
90 $this->expand_all_fields();
91
23ebc481
DM
92 $datahash = $data->getRowsHash();
93
94 // The action depends on the field type.
95 foreach ($datahash as $locator => $value) {
a5254141 96 $this->set_field_value($locator, $value);
23ebc481
DM
97 }
98 }
99
f8f1bdc3
DM
100 /**
101 * Expands all moodleform's fields, including collapsed fieldsets and advanced fields if they are present.
102 * @Given /^I expand all fieldsets$/
103 */
104 public function i_expand_all_fieldsets() {
105 $this->expand_all_fields();
106 }
107
108 /**
109 * Expands all moodle form fieldsets if they exists.
110 *
111 * Externalized from i_expand_all_fields to call it from
112 * other form-related steps without having to use steps-group calls.
113 *
114 * @throws ElementNotFoundException Thrown by behat_base::find_all
115 * @return void
116 */
117 protected function expand_all_fields() {
20153f63
RT
118 // Expand only if JS mode, else not needed.
119 if (!$this->running_javascript()) {
120 return;
121 }
f8f1bdc3 122
74c78e74
DM
123 // We already know that we waited for the DOM and the JS to be loaded, even the editor
124 // so, we will use the reduced timeout as it is a common task and we should save time.
f8f1bdc3
DM
125 try {
126
8cda2e6f 127 // Expand fieldsets link.
74c78e74 128 $xpath = "//div[@class='collapsible-actions']" .
8cda2e6f 129 "/descendant::a[contains(concat(' ', @class, ' '), ' collapseexpand ')]" .
74c78e74
DM
130 "[not(contains(concat(' ', @class, ' '), ' collapse-all '))]";
131 $collapseexpandlink = $this->find('xpath', $xpath, false, false, self::REDUCED_TIMEOUT);
8cda2e6f 132 $collapseexpandlink->click();
f8f1bdc3
DM
133
134 } catch (ElementNotFoundException $e) {
74c78e74
DM
135 // The behat_base::find() method throws an exception if there are no elements,
136 // we should not fail a test because of this. We continue if there are not expandable fields.
f8f1bdc3
DM
137 }
138
139 // Different try & catch as we can have expanded fieldsets with advanced fields on them.
140 try {
141
8cda2e6f
DM
142 // Expand all fields xpath.
143 $showmorexpath = "//a[normalize-space(.)='" . get_string('showmore', 'form') . "']" .
144 "[contains(concat(' ', normalize-space(@class), ' '), ' moreless-toggler')]";
f8f1bdc3 145
8cda2e6f 146 // We don't wait here as we already waited when getting the expand fieldsets links.
74c78e74
DM
147 if (!$showmores = $this->getSession()->getPage()->findAll('xpath', $showmorexpath)) {
148 return;
149 }
f8f1bdc3 150
7cde2bb3
MN
151 if ($this->getSession()->getDriver() instanceof \DMore\ChromeDriver\ChromeDriver) {
152 // Chrome Driver produces unique xpaths for each element.
153 foreach ($showmores as $showmore) {
154 $showmore->click();
155 }
156 } else {
157 // Funny thing about this, with findAll() we specify a pattern and each element matching the pattern
158 // is added to the array with of xpaths with a [0], [1]... sufix, but when we click on an element it
159 // does not matches the specified xpath anymore (now is a "Show less..." link) so [1] becomes [0],
160 // that's why we always click on the first XPath match, will be always the next one.
161 $iterations = count($showmores);
162 for ($i = 0; $i < $iterations; $i++) {
163 $showmores[0]->click();
164 }
f8f1bdc3
DM
165 }
166
167 } catch (ElementNotFoundException $e) {
168 // We continue with the test.
169 }
170
171 }
172
01e8bfd7
JO
173 /**
174 * Sets the field to wwwroot plus the given path. Include the first slash.
175 *
176 * @Given /^I set the field "(?P<field_string>(?:[^"]|\\")*)" to local url "(?P<field_path_string>(?:[^"]|\\")*)"$/
177 * @throws ElementNotFoundException Thrown by behat_base::find
178 * @param string $field
179 * @param string $path
180 * @return void
181 */
182 public function i_set_the_field_to_local_url($field, $path) {
183 global $CFG;
184 $this->set_field_value($field, $CFG->wwwroot . $path);
185 }
186
23ebc481 187 /**
a5254141 188 * Sets the specified value to the field.
23ebc481 189 *
decf1e14 190 * @Given /^I set the field "(?P<field_string>(?:[^"]|\\")*)" to "(?P<field_value_string>(?:[^"]|\\")*)"$/
1f9ffbdb 191 * @throws ElementNotFoundException Thrown by behat_base::find
46ac40cd
DM
192 * @param string $field
193 * @param string $value
a5254141 194 * @return void
23ebc481 195 */
a5254141 196 public function i_set_the_field_to($field, $value) {
c3f1e953 197 $this->set_field_value($field, $value);
23ebc481
DM
198 }
199
0cf72524
MG
200 /**
201 * Press the key in the field to trigger the javascript keypress event
202 *
203 * Note that the character key will not actually be typed in the input field
204 *
205 * @Given /^I press key "(?P<key_string>(?:[^"]|\\")*)" in the field "(?P<field_string>(?:[^"]|\\")*)"$/
206 * @throws ElementNotFoundException Thrown by behat_base::find
207 * @param string $key either char-code or character itself,
208 * may optionally be prefixed with ctrl-, alt-, shift- or meta-
209 * @param string $field
210 * @return void
211 */
212 public function i_press_key_in_the_field($key, $field) {
213 if (!$this->running_javascript()) {
8a6900ff 214 throw new DriverException('Key press step is not available with Javascript disabled');
0cf72524
MG
215 }
216 $fld = behat_field_manager::get_form_field_from_label($field, $this);
217 $modifier = null;
218 $char = $key;
219 if (preg_match('/-/', $key)) {
220 list($modifier, $char) = preg_split('/-/', $key, 2);
221 }
222 if (is_numeric($char)) {
223 $char = (int)$char;
224 }
225 $fld->key_press($char, $modifier);
226 }
227
9776f3dc
JO
228 /**
229 * Sets the specified value to the field.
230 *
e259795c 231 * @Given /^I set the field "(?P<field_string>(?:[^"]|\\")*)" to multiline:$/
9776f3dc
JO
232 * @throws ElementNotFoundException Thrown by behat_base::find
233 * @param string $field
234 * @param PyStringNode $value
235 * @return void
236 */
237 public function i_set_the_field_to_multiline($field, PyStringNode $value) {
238 $this->set_field_value($field, (string)$value);
239 }
240
6c396b6b
RT
241 /**
242 * Sets the specified value to the field with xpath.
243 *
244 * @Given /^I set the field with xpath "(?P<fieldxpath_string>(?:[^"]|\\")*)" to "(?P<field_value_string>(?:[^"]|\\")*)"$/
245 * @throws ElementNotFoundException Thrown by behat_base::find
246 * @param string $field
247 * @param string $value
248 * @return void
249 */
250 public function i_set_the_field_with_xpath_to($fieldxpath, $value) {
acdda4f5
RT
251 $fieldnode = $this->find('xpath', $fieldxpath);
252 $this->ensure_node_is_visible($fieldnode);
253 $field = behat_field_manager::get_form_field($fieldnode, $this->getSession());
6c396b6b
RT
254 $field->set_value($value);
255 }
256
23ebc481 257 /**
a5254141 258 * Checks, the field matches the value. More info in http://docs.moodle.org/dev/Acceptance_testing#Providing_values_to_steps.
23ebc481 259 *
decf1e14 260 * @Then /^the field "(?P<field_string>(?:[^"]|\\")*)" matches value "(?P<field_value_string>(?:[^"]|\\")*)"$/
1f9ffbdb 261 * @throws ElementNotFoundException Thrown by behat_base::find
a5254141 262 * @param string $field
46ac40cd 263 * @param string $value
a5254141 264 * @return void
23ebc481 265 */
a5254141 266 public function the_field_matches_value($field, $value) {
23ebc481 267
49d91129 268 // Get the field.
af4830a2 269 $formfield = behat_field_manager::get_form_field_from_label($field, $this);
23ebc481
DM
270
271 // Checks if the provided value matches the current field value.
a5254141
DM
272 if (!$formfield->matches($value)) {
273 $fieldvalue = $formfield->get_value();
23ebc481 274 throw new ExpectationException(
a5254141 275 'The \'' . $field . '\' value is \'' . $fieldvalue . '\', \'' . $value . '\' expected' ,
d9fddb0b
AH
276 $this->getSession()
277 );
278 }
279 }
280
281 /**
267033a9
T
282 * Checks, the field does not match the value. More info in http://docs.moodle.org/dev/Acceptance_testing#Providing_values_to_steps.
283 *
284 * @Then /^the field "(?P<field_string>(?:[^"]|\\")*)" does not match value "(?P<field_value_string>(?:[^"]|\\")*)"$/
285 * @throws ExpectationException
286 * @throws ElementNotFoundException Thrown by behat_base::find
287 * @param string $field
288 * @param string $value
289 * @return void
290 */
291 public function the_field_does_not_match_value($field, $value) {
292
293 // Get the field.
294 $formfield = behat_field_manager::get_form_field_from_label($field, $this);
295
296 // Checks if the provided value matches the current field value.
297 if ($formfield->matches($value)) {
298 throw new ExpectationException(
299 'The \'' . $field . '\' value matches \'' . $value . '\' and it should not match it' ,
300 $this->getSession()
301 );
302 }
303 }
304
305 /**
306 * Checks, the field matches the value.
d9fddb0b 307 *
267033a9
T
308 * @Then /^the field with xpath "(?P<xpath_string>(?:[^"]|\\")*)" matches value "(?P<field_value_string>(?:[^"]|\\")*)"$/
309 * @throws ExpectationException
d9fddb0b
AH
310 * @throws ElementNotFoundException Thrown by behat_base::find
311 * @param string $fieldxpath
312 * @param string $value
313 * @return void
314 */
315 public function the_field_with_xpath_matches_value($fieldxpath, $value) {
316
317 // Get the field.
318 $fieldnode = $this->find('xpath', $fieldxpath);
319 $formfield = behat_field_manager::get_form_field($fieldnode, $this->getSession());
320
321 // Checks if the provided value matches the current field value.
322 if (!$formfield->matches($value)) {
323 $fieldvalue = $formfield->get_value();
324 throw new ExpectationException(
325 'The \'' . $fieldxpath . '\' value is \'' . $fieldvalue . '\', \'' . $value . '\' expected' ,
23ebc481
DM
326 $this->getSession()
327 );
328 }
329 }
330
c3f1e953 331 /**
267033a9 332 * Checks, the field does not match the value.
c3f1e953 333 *
267033a9 334 * @Then /^the field with xpath "(?P<xpath_string>(?:[^"]|\\")*)" does not match value "(?P<field_value_string>(?:[^"]|\\")*)"$/
c3f1e953
DM
335 * @throws ExpectationException
336 * @throws ElementNotFoundException Thrown by behat_base::find
267033a9 337 * @param string $fieldxpath
c3f1e953
DM
338 * @param string $value
339 * @return void
340 */
267033a9 341 public function the_field_with_xpath_does_not_match_value($fieldxpath, $value) {
c3f1e953 342
c3f1e953 343 // Get the field.
267033a9
T
344 $fieldnode = $this->find('xpath', $fieldxpath);
345 $formfield = behat_field_manager::get_form_field($fieldnode, $this->getSession());
c3f1e953
DM
346
347 // Checks if the provided value matches the current field value.
a5254141 348 if ($formfield->matches($value)) {
c3f1e953 349 throw new ExpectationException(
267033a9 350 'The \'' . $fieldxpath . '\' value matches \'' . $value . '\' and it should not match it' ,
c3f1e953
DM
351 $this->getSession()
352 );
353 }
354 }
355
356 /**
a5254141 357 * Checks, the provided field/value matches. More info in http://docs.moodle.org/dev/Acceptance_testing#Providing_values_to_steps.
c3f1e953
DM
358 *
359 * @Then /^the following fields match these values:$/
360 * @throws ExpectationException
a5254141 361 * @param TableNode $data Pairs of | field | value |
c3f1e953
DM
362 */
363 public function the_following_fields_match_these_values(TableNode $data) {
364
365 // Expand all fields in case we have.
366 $this->expand_all_fields();
367
368 $datahash = $data->getRowsHash();
369
370 // The action depends on the field type.
371 foreach ($datahash as $locator => $value) {
a5254141 372 $this->the_field_matches_value($locator, $value);
c3f1e953
DM
373 }
374 }
375
376 /**
decf1e14 377 * Checks that the provided field/value pairs don't match. More info in http://docs.moodle.org/dev/Acceptance_testing#Providing_values_to_steps.
c3f1e953
DM
378 *
379 * @Then /^the following fields do not match these values:$/
380 * @throws ExpectationException
a5254141 381 * @param TableNode $data Pairs of | field | value |
c3f1e953
DM
382 */
383 public function the_following_fields_do_not_match_these_values(TableNode $data) {
384
385 // Expand all fields in case we have.
386 $this->expand_all_fields();
387
388 $datahash = $data->getRowsHash();
389
390 // The action depends on the field type.
391 foreach ($datahash as $locator => $value) {
392 $this->the_field_does_not_match_value($locator, $value);
393 }
394 }
395
23ebc481
DM
396 /**
397 * Checks, that given select box contains the specified option.
398 *
23ebc481 399 * @Then /^the "(?P<select_string>(?:[^"]|\\")*)" select box should contain "(?P<option_string>(?:[^"]|\\")*)"$/
1f9ffbdb
DM
400 * @throws ExpectationException
401 * @throws ElementNotFoundException Thrown by behat_base::find
23ebc481 402 * @param string $select The select element name
5f66d46e
EL
403 * @param string $option The option text/value. Plain value or comma separated
404 * values if multiple. Commas in multiple values escaped with backslash.
23ebc481
DM
405 */
406 public function the_select_box_should_contain($select, $option) {
407
1f9ffbdb 408 $selectnode = $this->find_field($select);
5f66d46e
EL
409 $multiple = $selectnode->hasAttribute('multiple');
410 $optionsarr = array(); // Array of passed value/text options to test.
23ebc481 411
5f66d46e
EL
412 if ($multiple) {
413 // Can pass multiple comma separated, with valuable commas escaped with backslash.
414 foreach (preg_replace('/\\\,/', ',', preg_split('/(?<!\\\),/', $option)) as $opt) {
415 $optionsarr[] = trim($opt);
416 }
417 } else {
418 // Only one option has been passed.
419 $optionsarr[] = trim($option);
420 }
421
422 // Now get all the values and texts in the select.
423 $options = $selectnode->findAll('xpath', '//option');
424 $values = array();
425 foreach ($options as $opt) {
426 $values[trim($opt->getValue())] = trim($opt->getText());
23ebc481
DM
427 }
428
5f66d46e
EL
429 foreach ($optionsarr as $opt) {
430 // Verify every option is a valid text or value.
431 if (!in_array($opt, $values) && !array_key_exists($opt, $values)) {
432 throw new ExpectationException(
433 'The select box "' . $select . '" does not contain the option "' . $opt . '"',
434 $this->getSession()
435 );
436 }
437 }
23ebc481
DM
438 }
439
440 /**
441 * Checks, that given select box does not contain the specified option.
442 *
23ebc481 443 * @Then /^the "(?P<select_string>(?:[^"]|\\")*)" select box should not contain "(?P<option_string>(?:[^"]|\\")*)"$/
1f9ffbdb
DM
444 * @throws ExpectationException
445 * @throws ElementNotFoundException Thrown by behat_base::find
23ebc481 446 * @param string $select The select element name
5f66d46e
EL
447 * @param string $option The option text/value. Plain value or comma separated
448 * values if multiple. Commas in multiple values escaped with backslash.
23ebc481
DM
449 */
450 public function the_select_box_should_not_contain($select, $option) {
451
1f9ffbdb 452 $selectnode = $this->find_field($select);
5f66d46e
EL
453 $multiple = $selectnode->hasAttribute('multiple');
454 $optionsarr = array(); // Array of passed value/text options to test.
23ebc481 455
5f66d46e
EL
456 if ($multiple) {
457 // Can pass multiple comma separated, with valuable commas escaped with backslash.
458 foreach (preg_replace('/\\\,/', ',', preg_split('/(?<!\\\),/', $option)) as $opt) {
459 $optionsarr[] = trim($opt);
460 }
461 } else {
462 // Only one option has been passed.
463 $optionsarr[] = trim($option);
464 }
465
466 // Now get all the values and texts in the select.
467 $options = $selectnode->findAll('xpath', '//option');
468 $values = array();
469 foreach ($options as $opt) {
470 $values[trim($opt->getValue())] = trim($opt->getText());
471 }
472
473 foreach ($optionsarr as $opt) {
474 // Verify every option is not a valid text or value.
475 if (in_array($opt, $values) || array_key_exists($opt, $values)) {
476 throw new ExpectationException(
477 'The select box "' . $select . '" contains the option "' . $opt . '"',
478 $this->getSession()
479 );
480 }
481 }
482 }
483
484 /**
c3f1e953 485 * Generic field setter.
5f66d46e 486 *
c3f1e953
DM
487 * Internal API method, a generic *I set "VALUE" to "FIELD" field*
488 * could be created based on it.
5f66d46e 489 *
c3f1e953
DM
490 * @param string $fieldlocator The pointer to the field, it will depend on the field type.
491 * @param string $value
492 * @return void
5f66d46e 493 */
c3f1e953 494 protected function set_field_value($fieldlocator, $value) {
5f66d46e 495
c3f1e953
DM
496 // We delegate to behat_form_field class, it will
497 // guess the type properly as it is a select tag.
af4830a2 498 $field = behat_field_manager::get_form_field_from_label($fieldlocator, $this);
c3f1e953 499 $field->set_value($value);
23ebc481
DM
500 }
501
2b964e1d
AN
502 /**
503 * Select a value from single select and redirect.
504 *
505 * @Given /^I select "(?P<singleselect_option_string>(?:[^"]|\\")*)" from the "(?P<singleselect_name_string>(?:[^"]|\\")*)" singleselect$/
506 */
507 public function i_select_from_the_singleselect($option, $singleselect) {
eb9ca848
RT
508
509 $this->execute('behat_forms::i_set_the_field_to', array($this->escape($singleselect), $this->escape($option)));
2b964e1d
AN
510
511 if (!$this->running_javascript()) {
bf4c3ee0 512 // Press button in the specified select container.
bc7a5953
RT
513 $containerxpath = "//div[" .
514 "(contains(concat(' ', normalize-space(@class), ' '), ' singleselect ') " .
515 "or contains(concat(' ', normalize-space(@class), ' '), ' urlselect ')".
516 ") and (
517 .//label[contains(normalize-space(string(.)), '" . $singleselect . "')] " .
518 "or .//select[(./@name='" . $singleselect . "' or ./@id='". $singleselect . "')]" .
519 ")]";
bf4c3ee0 520
eb9ca848
RT
521 $this->execute('behat_general::i_click_on_in_the',
522 array(get_string('go'), "button", $containerxpath, "xpath_element")
523 );
2b964e1d 524 }
2b964e1d
AN
525 }
526
dda64b6f
DW
527 /**
528 * Select item from autocomplete list.
529 *
530 * @Given /^I click on "([^"]*)" item in the autocomplete list$/
531 *
532 * @param string $item
533 */
534 public function i_click_on_item_in_the_autocomplete_list($item) {
535 $xpathtarget = "//ul[@class='form-autocomplete-suggestions']//*[contains(.,'" . $item . "')]";
536
537 $this->execute('behat_general::i_click_on', [$xpathtarget, 'xpath_element']);
538
539 $this->execute('behat_general::i_press_key_in_element', ['13', 'body', 'xpath_element']);
540 }
541
542 /**
543 * Open the auto-complete suggestions list (Assuming there is only one on the page.).
544 *
545 * @Given /^I open the autocomplete suggestions list$/
546 */
547 public function i_open_the_autocomplete_suggestions_list() {
548 $csstarget = ".form-autocomplete-downarrow";
549 $this->execute('behat_general::i_click_on', [$csstarget, 'css_element']);
550 }
23ebc481 551}