Proyectos de Subversion Moodle

Rev

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

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
// This file is part of Moodle - http://moodle.org/
3
//
4
// Moodle is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8
//
9
// Moodle is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13
//
14
// You should have received a copy of the GNU General Public License
15
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
16
 
17
/**
18
 * 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
 
28
require_once(__DIR__ . '/../../../lib/behat/behat_base.php');
29
require_once(__DIR__ . '/../../../lib/behat/behat_field_manager.php');
30
 
31
use Behat\Gherkin\Node\{TableNode, PyStringNode};
32
use Behat\Mink\Element\NodeElement;
33
use Behat\Mink\Exception\{ElementNotFoundException, ExpectationException};
34
 
35
/**
36
 * Forms-related steps definitions.
37
 *
38
 * Note, Behat tests to verify that the steps defined here work as advertised
39
 * are kept in admin/tool/behat/tests/behat.
40
 *
41
 * @package    core
42
 * @category   test
43
 * @copyright  2012 David Monllaó
44
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
45
 */
46
class behat_forms extends behat_base {
47
 
48
    /**
49
     * Presses button with specified id|name|title|alt|value.
50
     *
51
     * @When /^I press "(?P<button_string>(?:[^"]|\\")*)"$/
52
     * @throws ElementNotFoundException Thrown by behat_base::find
53
     * @param string $button
54
     */
55
    public function press_button($button) {
56
        $this->execute('behat_general::i_click_on', [$button, 'button']);
57
    }
58
 
59
    /**
60
     * Press button with specified id|name|title|alt|value and switch to main window.
61
     *
62
     * @When /^I press "(?P<button_string>(?:[^"]|\\")*)" and switch to main window$/
63
     * @throws ElementNotFoundException Thrown by behat_base::find
64
     * @param string $button
65
     */
66
    public function press_button_and_switch_to_main_window($button) {
67
        // Ensures the button is present, before pressing.
68
        $buttonnode = $this->find_button($button);
69
        $buttonnode->press();
70
        $this->wait_for_pending_js();
71
        $this->look_for_exceptions();
72
 
73
        // Switch to main window.
74
        $this->execute('behat_general::switch_to_the_main_window');
75
    }
76
 
77
    /**
78
     * Fills a form with field/value data.
79
     *
80
     * @Given /^I set the following fields to these values:$/
81
     * @throws ElementNotFoundException Thrown by behat_base::find
82
     * @param TableNode $data
83
     */
84
    public function i_set_the_following_fields_to_these_values(TableNode $data) {
85
 
86
        // Expand all fields in case we have.
87
        $this->expand_all_fields();
88
 
89
        $datahash = $data->getRowsHash();
90
 
91
        // The action depends on the field type.
92
        foreach ($datahash as $locator => $value) {
93
            $this->set_field_value($locator, $value);
94
        }
95
    }
96
 
97
    /**
98
     * Fills a form with field/value data.
99
     *
100
     * @Given /^I set the following fields in the "(?P<element_container_string>(?:[^"]|\\")*)" "(?P<text_selector_string>[^"]*)" to these values:$/
101
     * @throws ElementNotFoundException Thrown by behat_base::find
102
     * @param string $containerelement Element we look in
103
     * @param string $containerselectortype The type of selector where we look in
104
     * @param TableNode $data
105
     */
106
    public function i_set_the_following_fields_in_container_to_these_values(
107
            $containerelement, $containerselectortype, TableNode $data) {
108
 
109
        // Expand all fields in case we have.
110
        $this->expand_all_fields();
111
 
112
        $datahash = $data->getRowsHash();
113
 
114
        // The action depends on the field type.
115
        foreach ($datahash as $locator => $value) {
116
            $this->set_field_value_in_container($locator, $value, $containerselectortype, $containerelement);
117
        }
118
    }
119
 
120
    /**
121
     * Expands all moodleform's fields, including collapsed fieldsets and advanced fields if they are present.
122
     * @Given /^I expand all fieldsets$/
123
     */
124
    public function i_expand_all_fieldsets() {
125
        $this->expand_all_fields();
126
    }
127
 
128
    /**
129
     * Expands all moodle form fieldsets if they exists.
130
     *
131
     * Externalized from i_expand_all_fields to call it from
132
     * other form-related steps without having to use steps-group calls.
133
     *
134
     * @throws ElementNotFoundException Thrown by behat_base::find_all
135
     * @return void
136
     */
137
    protected function expand_all_fields() {
138
        // Expand only if JS mode, else not needed.
139
        if (!$this->running_javascript()) {
140
            return;
141
        }
142
 
143
        // We already know that we waited for the DOM and the JS to be loaded, even the editor
144
        // so, we will use the reduced timeout as it is a common task and we should save time.
145
        try {
146
            $this->wait_for_pending_js();
147
            // Expand all fieldsets link - which will only be there if there is more than one collapsible section.
148
            $expandallxpath = "//div[@class='collapsible-actions']" .
149
                "//a[contains(concat(' ', @class, ' '), ' collapsed ')]" .
150
                "//span[contains(concat(' ', @class, ' '), ' expandall ')]";
151
            // Else, look for the first expand fieldset link (old theme structure).
152
            $expandsectionold = "//legend[@class='ftoggler']" .
153
                    "//a[contains(concat(' ', @class, ' '), ' icons-collapse-expand ') and @aria-expanded = 'false']";
154
            // Else, look for the first expand fieldset link (current theme structure).
155
            $expandsectioncurrent = "//fieldset//div[contains(concat(' ', @class, ' '), ' ftoggler ')]" .
156
                    "//a[contains(concat(' ', @class, ' '), ' icons-collapse-expand ') and @aria-expanded = 'false']";
157
 
158
            $collapseexpandlink = $this->find('xpath', $expandallxpath . '|' . $expandsectionold . '|' . $expandsectioncurrent,
159
                    false, false, behat_base::get_reduced_timeout());
160
            $collapseexpandlink->click();
161
            $this->wait_for_pending_js();
162
 
163
        } catch (ElementNotFoundException $e) {
164
            // The behat_base::find() method throws an exception if there are no elements,
165
            // we should not fail a test because of this. We continue if there are not expandable fields.
166
        }
167
 
168
        // Different try & catch as we can have expanded fieldsets with advanced fields on them.
169
        try {
1441 ariadna 170
            $this->wait_for_pending_js();
1 efrain 171
            // Expand all fields xpath.
172
            $showmorexpath = "//a[normalize-space(.)='" . get_string('showmore', 'form') . "']" .
173
                "[contains(concat(' ', normalize-space(@class), ' '), ' moreless-toggler')]";
174
 
175
            // We don't wait here as we already waited when getting the expand fieldsets links.
176
            if (!$showmores = $this->getSession()->getPage()->findAll('xpath', $showmorexpath)) {
177
                return;
178
            }
179
 
1441 ariadna 180
            $js = <<<EOF
181
            require(['core/pending'], function(Pending) {
182
                const query = document.evaluate("{$showmorexpath}", document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
183
                if (query.snapshotLength > 0) {
184
                    const pendingPromise = new Pending('showmore:expand');
185
                    for (let i = 0, length = query.snapshotLength; i < length; ++i) {
186
                        query.snapshotItem(i).click();
187
                        if (i === length - 1) {
188
                            pendingPromise.resolve();
189
                        }
190
                    }
1 efrain 191
                }
1441 ariadna 192
            });
193
            EOF;
1 efrain 194
 
1441 ariadna 195
            $this->execute_script($js);
196
            $this->wait_for_pending_js();
1 efrain 197
        } catch (ElementNotFoundException $e) {
198
            // We continue with the test.
199
        }
200
 
201
    }
202
 
203
    /**
204
     * Sets the field to wwwroot plus the given path. Include the first slash.
205
     *
206
     * @Given /^I set the field "(?P<field_string>(?:[^"]|\\")*)" to local url "(?P<field_path_string>(?:[^"]|\\")*)"$/
207
     * @throws ElementNotFoundException Thrown by behat_base::find
208
     * @param string $field
209
     * @param string $path
210
     * @return void
211
     */
212
    public function i_set_the_field_to_local_url($field, $path) {
213
        global $CFG;
214
        $this->set_field_value($field, $CFG->wwwroot . $path);
215
    }
216
 
217
    /**
218
     * Sets the specified value to the field.
219
     *
220
     * @Given /^I set the field "(?P<field_string>(?:[^"]|\\")*)" to "(?P<field_value_string>(?:[^"]|\\")*)"$/
221
     * @throws ElementNotFoundException Thrown by behat_base::find
222
     * @param string $field
223
     * @param string $value
224
     * @return void
225
     */
226
    public function i_set_the_field_to($field, $value) {
227
        $this->set_field_value($field, $value);
228
    }
229
 
230
    /**
231
     * Sets the specified value to the field.
232
     *
233
     * @Given /^I set the field "(?P<field_string>(?:[^"]|\\")*)" in the "(?P<element_container_string>(?:[^"]|\\")*)" "(?P<text_selector_string>[^"]*)" to "(?P<field_value_string>(?:[^"]|\\")*)"$/
234
     * @throws ElementNotFoundException Thrown by behat_base::find
235
     * @param string $field
236
     * @param string $containerelement Element we look in
237
     * @param string $containerselectortype The type of selector where we look in
238
     * @param string $value
239
     */
240
    public function i_set_the_field_in_container_to($field, $containerelement, $containerselectortype, $value) {
241
        $this->set_field_value_in_container($field, $value, $containerselectortype, $containerelement);
242
    }
243
 
244
    /**
245
     * Press the key in the field to trigger the javascript keypress event
246
     *
247
     * Note that the character key will not actually be typed in the input field
248
     *
249
     * @Given /^I press key "(?P<key_string>(?:[^"]|\\")*)" in the field "(?P<field_string>(?:[^"]|\\")*)"$/
250
     * @throws ElementNotFoundException Thrown by behat_base::find
251
     * @param string $key either char-code or character itself,
252
     *          may optionally be prefixed with ctrl-, alt-, shift- or meta-
253
     * @param string $field
254
     * @return void
255
     */
256
    public function i_press_key_in_the_field($key, $field) {
257
        if (!$this->running_javascript()) {
258
            throw new DriverException('Key press step is not available with Javascript disabled');
259
        }
260
        $fld = behat_field_manager::get_form_field_from_label($field, $this);
261
        $modifier = null;
262
        $char = $key;
263
        if (preg_match('/-/', $key)) {
264
            list($modifier, $char) = preg_split('/-/', $key, 2);
265
        }
266
        if (is_numeric($char)) {
267
            $char = (int)$char;
268
        }
269
        $fld->key_press($char, $modifier);
270
    }
271
 
272
    /**
273
     * Sets the specified value to the field.
274
     *
275
     * @Given /^I set the field "(?P<field_string>(?:[^"]|\\")*)" to multiline:$/
276
     * @throws ElementNotFoundException Thrown by behat_base::find
277
     * @param string $field
278
     * @param PyStringNode $value
279
     * @return void
280
     */
281
    public function i_set_the_field_to_multiline($field, PyStringNode $value) {
282
        $this->set_field_value($field, (string)$value);
283
    }
284
 
285
    /**
286
     * Sets the specified value to the field with xpath.
287
     *
288
     * @Given /^I set the field with xpath "(?P<fieldxpath_string>(?:[^"]|\\")*)" to "(?P<field_value_string>(?:[^"]|\\")*)"$/
289
     * @throws ElementNotFoundException Thrown by behat_base::find
290
     * @param string $field
291
     * @param string $value
292
     * @return void
293
     */
294
    public function i_set_the_field_with_xpath_to($fieldxpath, $value) {
295
        $this->set_field_node_value($this->find('xpath', $fieldxpath), $value);
296
    }
297
 
298
    /**
299
     * Checks, the field matches the value.
300
     *
301
     * @Then /^the field "(?P<field_string>(?:[^"]|\\")*)" matches value "(?P<field_value_string>(?:[^"]|\\")*)"$/
302
     * @throws ElementNotFoundException Thrown by behat_base::find
303
     * @param string $field
304
     * @param string $value
305
     * @return void
306
     */
307
    public function the_field_matches_value($field, $value) {
308
 
309
        // Get the field.
310
        $formfield = behat_field_manager::get_form_field_from_label($field, $this);
311
 
312
        // Checks if the provided value matches the current field value.
313
        if (!$formfield->matches($value)) {
314
            $fieldvalue = $formfield->get_value();
315
            throw new ExpectationException(
316
                'The \'' . $field . '\' value is \'' . $fieldvalue . '\', \'' . $value . '\' expected' ,
317
                $this->getSession()
318
            );
319
        }
320
    }
321
 
322
    /**
323
     * Checks, the field contains the value.
324
     *
325
     * @Then /^the field "(?P<field_string>(?:[^"]|\\")*)" (?P<doesnot_bool>does not )?match(?:es)* expression "(?P<expression_string>(?:[^"]|\\")*)"$/
326
     * @throws ElementNotFoundException Thrown by behat_base::find
327
     * @param string $field The naem or reference to the field
328
     * @param bool $doesnot
329
     * @param string $expression The Perl-like regular expression, including any delimeters and flag
330
     * @return void
331
     */
332
    public function the_field_matches_expression(
333
        string $field,
334
        bool $doesnot,
335
        string $expression,
336
    ): void {
337
        // Get the field.
338
        $formfield = behat_field_manager::get_form_field_from_label($field, $this);
339
 
340
        // Checks if the provided value matches the current field value.
341
        $fieldvalue = $formfield->get_value();
342
        $matches = preg_match($expression, $fieldvalue);
343
        if ($matches === 1 && $doesnot) {
344
            throw new ExpectationException(
345
                "The '{$field}' field matches the expression '{$expression}' and it should not",
346
                $this->getSession()
347
            );
348
        } else if ($matches === 0 && !$doesnot) {
349
            throw new ExpectationException(
350
                "The '{$field}' field does not match the expression '{$expression}'",
351
                $this->getSession()
352
            );
353
        } else if ($matches === false) {
354
            throw new coding_exception(
355
                "The expression '{$expression}' was not valid",
356
            );
357
        }
358
    }
359
 
360
    /**
361
     * Checks, the field matches the value.
362
     *
363
     * @Then /^the field "(?P<field_string>(?:[^"]|\\")*)" matches multiline:$/
364
     * @throws ElementNotFoundException Thrown by behat_base::find
365
     * @param string $field
366
     * @param PyStringNode $value
367
     * @return void
368
     */
369
    public function the_field_matches_multiline($field, PyStringNode $value) {
370
        $this->the_field_matches_value($field, (string)$value);
371
    }
372
 
373
    /**
374
     * Checks, the field does not match the value.
375
     *
376
     * @Then /^the field "(?P<field_string>(?:[^"]|\\")*)" does not match value "(?P<field_value_string>(?:[^"]|\\")*)"$/
377
     * @throws ExpectationException
378
     * @throws ElementNotFoundException Thrown by behat_base::find
379
     * @param string $field
380
     * @param string $value
381
     */
382
    public function the_field_does_not_match_value($field, $value) {
383
 
384
        // Get the field.
385
        $formfield = behat_field_manager::get_form_field_from_label($field, $this);
386
 
387
        // Checks if the provided value matches the current field value.
388
        if ($formfield->matches($value)) {
389
            throw new ExpectationException(
390
                'The \'' . $field . '\' value matches \'' . $value . '\' and it should not match it' ,
391
                $this->getSession()
392
            );
393
        }
394
    }
395
 
396
    /**
397
     * Checks, the field matches the value.
398
     *
399
     * @Then /^the field "(?P<field_string>(?:[^"]|\\")*)" in the "(?P<element_container_string>(?:[^"]|\\")*)" "(?P<text_selector_string>[^"]*)" matches value "(?P<field_value_string>(?:[^"]|\\")*)"$/
400
     * @throws ElementNotFoundException Thrown by behat_base::find
401
     * @param string $field
402
     * @param string $containerelement Element we look in
403
     * @param string $containerselectortype The type of selector where we look in
404
     * @param string $value
405
     */
406
    public function the_field_in_container_matches_value($field, $containerelement, $containerselectortype, $value) {
407
 
408
        // Get the field.
409
        $node = $this->get_node_in_container('field', $field, $containerselectortype, $containerelement);
410
        $formfield = behat_field_manager::get_form_field($node, $this->getSession());
411
 
412
        // Checks if the provided value matches the current field value.
413
        if (!$formfield->matches($value)) {
414
            $fieldvalue = $formfield->get_value();
415
            throw new ExpectationException(
416
                    'The \'' . $field . '\' value is \'' . $fieldvalue . '\', \'' . $value . '\' expected' ,
417
                    $this->getSession()
418
            );
419
        }
420
    }
421
 
422
    /**
423
     * Checks, the field does not match the value.
424
     *
425
     * @Then /^the field "(?P<field_string>(?:[^"]|\\")*)" in the "(?P<element_container_string>(?:[^"]|\\")*)" "(?P<text_selector_string>[^"]*)" does not match value "(?P<field_value_string>(?:[^"]|\\")*)"$/
426
     * @throws ExpectationException
427
     * @throws ElementNotFoundException Thrown by behat_base::find
428
     * @param string $field
429
     * @param string $containerelement Element we look in
430
     * @param string $containerselectortype The type of selector where we look in
431
     * @param string $value
432
     */
433
    public function the_field_in_container_does_not_match_value($field, $containerelement, $containerselectortype, $value) {
434
 
435
        // Get the field.
436
        $node = $this->get_node_in_container('field', $field, $containerselectortype, $containerelement);
437
        $formfield = behat_field_manager::get_form_field($node, $this->getSession());
438
 
439
        // Checks if the provided value matches the current field value.
440
        if ($formfield->matches($value)) {
441
            throw new ExpectationException(
442
                    'The \'' . $field . '\' value matches \'' . $value . '\' and it should not match it' ,
443
                    $this->getSession()
444
            );
445
        }
446
    }
447
 
448
    /**
449
     * Checks, the field matches the value.
450
     *
451
     * @Then /^the field with xpath "(?P<xpath_string>(?:[^"]|\\")*)" matches value "(?P<field_value_string>(?:[^"]|\\")*)"$/
452
     * @throws ExpectationException
453
     * @throws ElementNotFoundException Thrown by behat_base::find
454
     * @param string $fieldxpath
455
     * @param string $value
456
     * @return void
457
     */
458
    public function the_field_with_xpath_matches_value($fieldxpath, $value) {
459
 
460
        // Get the field.
461
        $fieldnode = $this->find('xpath', $fieldxpath);
462
        $formfield = behat_field_manager::get_form_field($fieldnode, $this->getSession());
463
 
464
        // Checks if the provided value matches the current field value.
465
        if (!$formfield->matches($value)) {
466
            $fieldvalue = $formfield->get_value();
467
            throw new ExpectationException(
468
                'The \'' . $fieldxpath . '\' value is \'' . $fieldvalue . '\', \'' . $value . '\' expected' ,
469
                $this->getSession()
470
            );
471
        }
472
    }
473
 
474
    /**
475
     * Checks, the field does not match the value.
476
     *
477
     * @Then /^the field with xpath "(?P<xpath_string>(?:[^"]|\\")*)" does not match value "(?P<field_value_string>(?:[^"]|\\")*)"$/
478
     * @throws ExpectationException
479
     * @throws ElementNotFoundException Thrown by behat_base::find
480
     * @param string $fieldxpath
481
     * @param string $value
482
     * @return void
483
     */
484
    public function the_field_with_xpath_does_not_match_value($fieldxpath, $value) {
485
 
486
        // Get the field.
487
        $fieldnode = $this->find('xpath', $fieldxpath);
488
        $formfield = behat_field_manager::get_form_field($fieldnode, $this->getSession());
489
 
490
        // Checks if the provided value matches the current field value.
491
        if ($formfield->matches($value)) {
492
            throw new ExpectationException(
493
                'The \'' . $fieldxpath . '\' value matches \'' . $value . '\' and it should not match it' ,
494
                $this->getSession()
495
            );
496
        }
497
    }
498
 
499
    /**
500
     * Checks, the provided field/value matches.
501
     *
502
     * @Then /^the following fields match these values:$/
503
     * @throws ExpectationException
504
     * @param TableNode $data Pairs of | field | value |
505
     */
506
    public function the_following_fields_match_these_values(TableNode $data) {
507
 
508
        // Expand all fields in case we have.
509
        $this->expand_all_fields();
510
 
511
        $datahash = $data->getRowsHash();
512
 
513
        // The action depends on the field type.
514
        foreach ($datahash as $locator => $value) {
515
            $this->the_field_matches_value($locator, $value);
516
        }
517
    }
518
 
519
    /**
520
     * Checks that the provided field/value pairs don't match.
521
     *
522
     * @Then /^the following fields do not match these values:$/
523
     * @throws ExpectationException
524
     * @param TableNode $data Pairs of | field | value |
525
     */
526
    public function the_following_fields_do_not_match_these_values(TableNode $data) {
527
 
528
        // Expand all fields in case we have.
529
        $this->expand_all_fields();
530
 
531
        $datahash = $data->getRowsHash();
532
 
533
        // The action depends on the field type.
534
        foreach ($datahash as $locator => $value) {
535
            $this->the_field_does_not_match_value($locator, $value);
536
        }
537
    }
538
 
539
    /**
540
     * Checks, the provided field/value matches.
541
     *
542
     * @Then /^the following fields in the "(?P<element_container_string>(?:[^"]|\\")*)" "(?P<text_selector_string>[^"]*)" match these values:$/
543
     * @throws ExpectationException
544
     * @param string $containerelement Element we look in
545
     * @param string $containerselectortype The type of selector where we look in
546
     * @param TableNode $data Pairs of | field | value |
547
     */
548
    public function the_following_fields_in_container_match_these_values(
549
            $containerelement, $containerselectortype, TableNode $data) {
550
 
551
        // Expand all fields in case we have.
552
        $this->expand_all_fields();
553
 
554
        $datahash = $data->getRowsHash();
555
 
556
        // The action depends on the field type.
557
        foreach ($datahash as $locator => $value) {
558
            $this->the_field_in_container_matches_value($locator, $containerelement, $containerselectortype, $value);
559
        }
560
    }
561
 
562
    /**
563
     * Checks that the provided field/value pairs don't match.
564
     *
565
     * @Then /^the following fields in the "(?P<element_container_string>(?:[^"]|\\")*)" "(?P<text_selector_string>[^"]*)" do not match these values:$/
566
     * @throws ExpectationException
567
     * @param string $containerelement Element we look in
568
     * @param string $containerselectortype The type of selector where we look in
569
     * @param TableNode $data Pairs of | field | value |
570
     */
571
    public function the_following_fields_in_container_do_not_match_these_values(
572
            $containerelement, $containerselectortype, TableNode $data) {
573
 
574
        // Expand all fields in case we have.
575
        $this->expand_all_fields();
576
 
577
        $datahash = $data->getRowsHash();
578
 
579
        // The action depends on the field type.
580
        foreach ($datahash as $locator => $value) {
581
            $this->the_field_in_container_does_not_match_value($locator, $containerelement, $containerselectortype, $value);
582
        }
583
    }
584
 
585
    /**
586
     * Checks, that given select box contains the specified option.
587
     *
588
     * @Then /^the "(?P<select_string>(?:[^"]|\\")*)" select box should contain "(?P<option_string>(?:[^"]|\\")*)"$/
589
     * @throws ExpectationException
590
     * @throws ElementNotFoundException Thrown by behat_base::find
591
     * @param string $select The select element name
592
     * @param string $option The option text/value. Plain value or comma separated
593
     *                       values if multiple. Commas in multiple values escaped with backslash.
594
     */
595
    public function the_select_box_should_contain($select, $option) {
596
 
597
        $selectnode = $this->find_field($select);
598
        $multiple = $selectnode->hasAttribute('multiple');
599
        $optionsarr = array(); // Array of passed value/text options to test.
600
 
601
        if ($multiple) {
602
            // Can pass multiple comma separated, with valuable commas escaped with backslash.
603
            foreach (preg_replace('/\\\,/', ',',  preg_split('/(?<!\\\),/', $option)) as $opt) {
604
                $optionsarr[] = trim($opt);
605
            }
606
        } else {
607
            // Only one option has been passed.
608
            $optionsarr[] = trim($option);
609
        }
610
 
611
        // Now get all the values and texts in the select.
612
        $options = $selectnode->findAll('xpath', '//option');
613
        $values = array();
614
        foreach ($options as $opt) {
615
            $values[trim($opt->getValue())] = trim($opt->getText());
616
        }
617
 
618
        foreach ($optionsarr as $opt) {
619
            // Verify every option is a valid text or value.
620
            if (!in_array($opt, $values) && !array_key_exists($opt, $values)) {
621
                throw new ExpectationException(
622
                    'The select box "' . $select . '" does not contain the option "' . $opt . '"',
623
                    $this->getSession()
624
                );
625
            }
626
        }
627
    }
628
 
629
    /**
630
     * Checks, that given select box does not contain the specified option.
631
     *
632
     * @Then /^the "(?P<select_string>(?:[^"]|\\")*)" select box should not contain "(?P<option_string>(?:[^"]|\\")*)"$/
633
     * @throws ExpectationException
634
     * @throws ElementNotFoundException Thrown by behat_base::find
635
     * @param string $select The select element name
636
     * @param string $option The option text/value. Plain value or comma separated
637
     *                       values if multiple. Commas in multiple values escaped with backslash.
638
     */
639
    public function the_select_box_should_not_contain($select, $option) {
640
 
641
        $selectnode = $this->find_field($select);
642
        $multiple = $selectnode->hasAttribute('multiple');
643
        $optionsarr = array(); // Array of passed value/text options to test.
644
 
645
        if ($multiple) {
646
            // Can pass multiple comma separated, with valuable commas escaped with backslash.
647
            foreach (preg_replace('/\\\,/', ',',  preg_split('/(?<!\\\),/', $option)) as $opt) {
648
                $optionsarr[] = trim($opt);
649
            }
650
        } else {
651
            // Only one option has been passed.
652
            $optionsarr[] = trim($option);
653
        }
654
 
655
        // Now get all the values and texts in the select.
656
        $options = $selectnode->findAll('xpath', '//option');
657
        $values = array();
658
        foreach ($options as $opt) {
659
            $values[trim($opt->getValue())] = trim($opt->getText());
660
        }
661
 
662
        foreach ($optionsarr as $opt) {
663
            // Verify every option is not a valid text or value.
664
            if (in_array($opt, $values) || array_key_exists($opt, $values)) {
665
                throw new ExpectationException(
666
                    'The select box "' . $select . '" contains the option "' . $opt . '"',
667
                    $this->getSession()
668
                );
669
            }
670
        }
671
    }
672
 
673
    /**
674
     * Generic field setter.
675
     *
676
     * Internal API method, a generic *I set "VALUE" to "FIELD" field*
677
     * could be created based on it.
678
     *
679
     * @param string $fieldlocator The pointer to the field, it will depend on the field type.
680
     * @param string $value
681
     * @return void
682
     */
683
    protected function set_field_value($fieldlocator, $value) {
684
        // We delegate to behat_form_field class, it will
685
        // guess the type properly as it is a select tag.
686
        $field = behat_field_manager::get_form_field_from_label($fieldlocator, $this);
687
        $field->set_value($value);
688
    }
689
 
690
    /**
691
     * Generic field setter to be used by chainable steps.
692
     *
693
     * @param NodeElement $fieldnode
694
     * @param string $value
695
     */
696
    public function set_field_node_value(NodeElement $fieldnode, string $value): void {
697
        $field = behat_field_manager::get_form_field($fieldnode, $this->getSession());
698
        $field->set_value($value);
699
    }
700
 
701
    /**
702
     * Generic field setter.
703
     *
704
     * Internal API method, a generic *I set "VALUE" to "FIELD" field*
705
     * could be created based on it.
706
     *
707
     * @param string $fieldlocator The pointer to the field, it will depend on the field type.
708
     * @param string $value the value to set
709
     * @param string $containerselectortype The type of selector where we look in
710
     * @param string $containerelement Element we look in
711
     */
712
    protected function set_field_value_in_container($fieldlocator, $value, $containerselectortype, $containerelement) {
713
        $node = $this->get_node_in_container('field', $fieldlocator, $containerselectortype, $containerelement);
714
        $this->set_field_node_value($node, $value);
715
    }
716
 
717
    /**
718
     * Select a value from single select and redirect.
719
     *
720
     * @Given /^I select "(?P<singleselect_option_string>(?:[^"]|\\")*)" from the "(?P<singleselect_name_string>(?:[^"]|\\")*)" singleselect$/
721
     */
722
    public function i_select_from_the_singleselect($option, $singleselect) {
723
 
724
        $this->execute('behat_forms::i_set_the_field_to', array($this->escape($singleselect), $this->escape($option)));
725
 
726
        if (!$this->running_javascript()) {
727
            // Press button in the specified select container.
728
            $containerxpath = "//div[" .
729
                "(contains(concat(' ', normalize-space(@class), ' '), ' singleselect ') " .
730
                    "or contains(concat(' ', normalize-space(@class), ' '), ' urlselect ')".
731
                ") and (
732
                .//label[contains(normalize-space(string(.)), '" . $singleselect . "')] " .
733
                    "or .//select[(./@name='" . $singleselect . "' or ./@id='". $singleselect . "')]" .
734
                ")]";
735
 
736
            $this->execute('behat_general::i_click_on_in_the',
737
                array(get_string('go'), "button", $containerxpath, "xpath_element")
738
            );
739
        }
740
    }
741
 
742
    /**
743
     * Select item from autocomplete list.
744
     *
745
     * @Given /^I click on "([^"]*)" item in the autocomplete list$/
746
     *
747
     * @param string $item
748
     */
749
    public function i_click_on_item_in_the_autocomplete_list($item) {
750
        $xpathtarget = "//ul[@class='form-autocomplete-suggestions']//*" .
751
            "[contains(concat('|', normalize-space(.), '|'),'|" . $item . "|')]";
752
 
753
        $this->execute('behat_general::i_click_on', [$xpathtarget, 'xpath_element']);
754
    }
755
 
756
    /**
757
     * Open the auto-complete suggestions list (Assuming there is only one on the page.).
758
     *
759
     * @Given I open the autocomplete suggestions list
760
     * @Given I open the autocomplete suggestions list in the :container :containertype
761
     */
762
    public function i_open_the_autocomplete_suggestions_list($container = null, $containertype = null) {
763
        $csstarget = ".form-autocomplete-downarrow";
764
        if ($container && $containertype) {
765
            $this->execute('behat_general::i_click_on_in_the', [$csstarget, 'css_element', $container, $containertype]);
766
        } else {
767
            $this->execute('behat_general::i_click_on', [$csstarget, 'css_element']);
768
        }
769
    }
770
 
771
    /**
772
     * Expand the given autocomplete list
773
     *
774
     * @Given /^I expand the "(?P<field_string>(?:[^"]|\\")*)" autocomplete$/
775
     *
776
     * @param string $field Field name
777
     */
778
    public function i_expand_the_autocomplete($field) {
779
        $csstarget = '.form-autocomplete-downarrow';
780
        $node = $this->get_node_in_container('css_element', $csstarget, 'form_row', $field);
781
        $node->click();
782
    }
783
 
784
    /**
785
     * Assert the given option exist in the given autocomplete list
786
     *
787
     * @Given /^I should see "(?P<option_string>(?:[^"]|\\")*)" in the list of options for the "(?P<field_string>(?:[^"]|\\")*)" autocomplete$$/
788
     *
789
     * @param string $option Name of option
790
     * @param string $field Field name
791
     */
792
    public function i_should_see_in_the_list_of_option_for_the_autocomplete($option, $field) {
793
        $xpathtarget = "//div[contains(@class, 'form-autocomplete-selection') and contains(.//div, '" . $option . "')]";
794
        $node = $this->get_node_in_container('xpath_element', $xpathtarget, 'form_row', $field);
795
        $this->ensure_node_is_visible($node);
796
    }
797
 
798
    /**
799
     * Checks whether the select menu contains an option with specified text or not.
800
     *
801
     * @Then the :name select menu should contain :option
802
     * @Then the :name select menu should :not contain :option
803
     *
804
     * @throws ExpectationException When the expectation is not satisfied
805
     * @param string $label The label of the select menu element
806
     * @param string $option The string that is used to identify an option within the select menu. If the string
807
     *                       has two items separated by '>' (ex. "Group > Option"), the first item ("Group") will be
808
     *                       used to identify a particular group within the select menu, while the second ("Option")
809
     *                       will be used to identify an option within that group. Otherwise, a string with a single
810
     *                       item (ex. "Option") will be used to identify an option within the select menu regardless
811
     *                       of any existing groups.
812
     * @param string|null $not If set, the select menu should not contain the specified option. If null, the option
813
     *                         should be present.
814
     */
815
    public function the_select_menu_should_contain(string $label, string $option, ?string $not = null) {
816
 
817
        $field = behat_field_manager::get_form_field_from_label($label, $this);
818
 
819
        if (!method_exists($field, 'has_option')) {
820
            throw new coding_exception('Field does not support the has_option function.');
821
        }
822
 
823
        // If the select menu contains the specified option but it should not.
824
        if ($field->has_option($option) && $not) {
825
            throw new ExpectationException(
826
                "The select menu should not contain \"{$option}\" but it does.",
827
                $this->getSession()
828
            );
829
        }
830
        // If the select menu does not contain the specified option but it should.
831
        if (!$field->has_option($option) && !$not) {
832
            throw new ExpectationException(
833
                "The select menu should contain \"{$option}\" but it does not.",
834
                $this->getSession()
835
            );
836
        }
837
    }
1441 ariadna 838
 
839
    /**
840
     * Check that the validationMessage property on a form field element includes the given text.
841
     *
842
     * @Then the :field field validation message should contain :text
843
     * @param string $field The css selector for the input field
844
     * @param string $text The text which should be found in the validation message
845
     */
846
    public function the_field_validation_message_should_contain(string $field, string $text): void {
847
 
848
        // We can't use this assertion if javascript is not running.
849
        $this->require_javascript();
850
 
851
        // Check that the element exists.
852
        // This is fail and go no further, if the element does not exist.
853
        $node = $this->get_selected_node('field', $field);
854
 
855
        // Get the validity result.
856
        $wdelement = $this->get_webdriver_element_from_node_element($node);
857
        $webdriver = $this->getSession()->getDriver()->getWebDriver();
858
        $message = $webdriver->executeScript("return arguments[0].validationMessage;", [$wdelement]);
859
        if (strpos($message, $text) === false) {
860
            throw new ExpectationException(
861
                '"' . $field . '" validation message does not contain "' . $text . '"', $this->getSession()
862
            );
863
        }
864
 
865
    }
866
 
867
    /**
868
     * Check that the result of calling the checkValidity API on a form field element matches the expected result.
869
     *
870
     * @Then the :field field validity check should return :result
871
     * @param string $field The css selector for the input field
872
     * @param string $expected "true" or "false"
873
     */
874
    public function the_field_validity_check_should_return(string $field, string $expected): void {
875
 
876
        // We can't use this assertion if javascript is not running.
877
        $this->require_javascript();
878
 
879
        // Expected value can only be 'true' or 'false'.
880
        $expected = strtolower($expected);
881
        if (!in_array($expected, ['true', 'false'])) {
882
            throw new ExpectationException(
883
                'Invalid value for expected value "' . $expected . '". Should be "true" or "false".',
884
                $this->getSession());
885
        }
886
 
887
        // Convert the expected result from a string to bool.
888
        $expected = ($expected === "true");
889
 
890
        // Check that the element exists.
891
        // This is fail and go no further, if the element does not exist.
892
        $node = $this->get_selected_node('field', $field);
893
 
894
        // Get the validity result.
895
        $wdelement = $this->get_webdriver_element_from_node_element($node);
896
        $webdriver = $this->getSession()->getDriver()->getWebDriver();
897
        $result = $webdriver->executeScript("return arguments[0].checkValidity();", [$wdelement]);
898
        if ($result !== $expected) {
899
 
900
            // Convert booleans to strings for the exception message.
901
            $result = ($result) ? "true" : "false";
902
            $expected = ($expected) ? "true" : "false";
903
 
904
            throw new ExpectationException(
905
                '"' . $field . '" validation check was "' . $result . '". Expected: "' .
906
                $expected . '"', $this->getSession()
907
            );
908
 
909
        }
910
 
911
    }
912
 
1 efrain 913
}