source: moodle/trunk/fuentes/lib/behat/form_field/behat_form_select.php @ 1331

Last change on this file since 1331 was 1331, checked in by jrpelegrina, 3 years ago

Updated to moodle 3.0.3

File size: 14.4 KB
Line 
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 * Single select form field class.
19 *
20 * @package    core_form
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__  . '/behat_form_field.php');
29
30/**
31 * Single select form field.
32 *
33 * @package    core_form
34 * @category   test
35 * @copyright  2012 David Monllaó
36 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
37 */
38class behat_form_select extends behat_form_field {
39
40    /**
41     * Sets the value(s) of a select element.
42     *
43     * Seems an easy select, but there are lots of combinations
44     * of browsers and operative systems and each one manages the
45     * autosubmits and the multiple option selects in a different way.
46     *
47     * @param string $value plain value or comma separated values if multiple. Commas in values escaped with backslash.
48     * @return void
49     */
50    public function set_value($value) {
51
52        // In some browsers we select an option and it triggers all the
53        // autosubmits and works as expected but not in all of them, so we
54        // try to catch all the possibilities to make this function work as
55        // expected.
56
57        // Get the internal id of the element we are going to click.
58        // This kind of internal IDs are only available in the selenium wire
59        // protocol, so only available using selenium drivers, phantomjs and family.
60        if ($this->running_javascript()) {
61            $currentelementid = $this->get_internal_field_id();
62        }
63
64        // Is the select multiple?
65        $multiple = $this->field->hasAttribute('multiple');
66
67        // By default, assume the passed value is a non-multiple option.
68        $options = array(trim($value));
69
70        // Here we select the option(s).
71        if ($multiple) {
72            // Split and decode values. Comma separated list of values allowed. With valuable commas escaped with backslash.
73            $options = preg_replace('/\\\,/', ',',  preg_split('/(?<!\\\),/', $value));
74            // This is a multiple select, let's pass the multiple flag after first option.
75            $afterfirstoption = false;
76            foreach ($options as $option) {
77                $this->field->selectOption(trim($option), $afterfirstoption);
78                $afterfirstoption = true;
79            }
80        } else {
81            // If value is already set then don't set it again.
82            if ($this->field->getValue() == $value) {
83                return;
84            } else {
85                $opt = $this->field->find('named', array(
86                    'option', $this->field->getSession()->getSelectorsHandler()->xpathLiteral($value)
87                ));
88                if ($opt && ($this->field->getValue() == $opt->getValue())) {
89                    return;
90                }
91            }
92
93            // If not running JS or not a singleselect then use selectOption.
94            // For singleselect only click event is enough.
95            if (!$this->running_javascript() ||
96                !($this->field->hasClass('singleselect') || $this->field->hasClass('urlselect'))) {
97
98                // This is a single select, let's pass the last one specified.
99                $this->field->selectOption(end($options));
100            }
101        }
102
103        // With JS disabled this is enough and we finish here.
104        if (!$this->running_javascript()) {
105            return;
106        }
107
108        // With JS enabled we add more clicks as some selenium
109        // drivers requires it to fire JS events.
110
111        // In some browsers the selectOption actions can perform a form submit or reload page
112        // so we need to ensure the element is still available to continue interacting
113        // with it. We don't wait here.
114        // getXpath() does not send a query to selenium, so we don't need to wrap it in a try & catch.
115        $selectxpath = $this->field->getXpath();
116        if (!$this->session->getDriver()->find($selectxpath)) {
117            return;
118        }
119
120        // We also check the selenium internal element id, if it have changed
121        // we are dealing with an autosubmit that was already executed, and we don't to
122        // execute anything else as the action we wanted was already performed.
123        if ($currentelementid != $this->get_internal_field_id()) {
124            return;
125        }
126
127        // Wait for all the possible AJAX requests that have been
128        // already triggered by selectOption() to be finished.
129        $this->session->wait(behat_base::TIMEOUT * 1000, behat_base::PAGE_READY_JS);
130
131        // Wrapped in try & catch as the element may disappear if an AJAX request was submitted.
132        try {
133            $multiple = $this->field->hasAttribute('multiple');
134        } catch (Exception $e) {
135            // We do not specify any specific Exception type as there are
136            // different exceptions that can be thrown by the driver and
137            // we can not control them all, also depending on the selenium
138            // version the exception type can change.
139            return;
140        }
141
142        // Single select sometimes needs an extra click in the option.
143        if (!$multiple) {
144
145            // Var $options only contains 1 option.
146            $optionxpath = $this->get_option_xpath(end($options), $selectxpath);
147
148            // Using the driver direcly because Element methods are messy when dealing
149            // with elements inside containers.
150            if ($optionnodes = $this->session->getDriver()->find($optionxpath)) {
151
152                // Wrapped in a try & catch as we can fall into race conditions
153                // and the element may not be there.
154                try {
155                    current($optionnodes)->click();
156                } catch (Exception $e) {
157                    // We continue and return as this means that the element is not there or it is not the same.
158                    return;
159                }
160            }
161
162        } else {
163
164            // Wrapped in a try & catch as we can fall into race conditions
165            // and the element may not be there.
166            try {
167                // Multiple ones needs the click in the select.
168                $this->field->click();
169            } catch (Exception $e) {
170                // We continue and return as this means that the element is not there or it is not the same.
171                return;
172            }
173
174            // We also check that the option(s) are still there. We neither wait.
175            foreach ($options as $option) {
176                $optionxpath = $this->get_option_xpath($option, $selectxpath);
177                if (!$this->session->getDriver()->find($optionxpath)) {
178                    return;
179                }
180            }
181
182            // Wait for all the possible AJAX requests that have been
183            // already triggered by clicking on the field to be finished.
184            $this->session->wait(behat_base::TIMEOUT * 1000, behat_base::PAGE_READY_JS);
185
186            // Wrapped in a try & catch as we can fall into race conditions
187            // and the element may not be there.
188            try {
189
190                // Repeating the select(s) as some drivers (chrome that I know) are moving
191                // to another option after the general select field click above.
192                $afterfirstoption = false;
193                foreach ($options as $option) {
194                    $this->field->selectOption(trim($option), $afterfirstoption);
195                    $afterfirstoption = true;
196                }
197            } catch (Exception $e) {
198                // We continue and return as this means that the element is not there or it is not the same.
199                return;
200            }
201        }
202    }
203
204    /**
205     * Returns the text of the currently selected options.
206     *
207     * @return string Comma separated if multiple options are selected. Commas in option texts escaped with backslash.
208     */
209    public function get_value() {
210        return $this->get_selected_options();
211    }
212
213    /**
214     * Returns whether the provided argument matches the current value.
215     *
216     * @param mixed $expectedvalue
217     * @return bool
218     */
219    public function matches($expectedvalue) {
220
221        $multiple = $this->field->hasAttribute('multiple');
222
223        // Same implementation as the parent if it is a single select.
224        if (!$multiple) {
225            $cleanexpectedvalue = trim($expectedvalue);
226            $selectedtext = trim($this->get_selected_options());
227            $selectedvalue = trim($this->get_selected_options(false));
228            if ($cleanexpectedvalue != $selectedvalue && $cleanexpectedvalue != $selectedtext) {
229                return false;
230            }
231            return true;
232        }
233
234        // We are dealing with a multi-select.
235
236        // Can pass multiple comma separated, with valuable commas escaped with backslash.
237        $expectedarr = array(); // Array of passed text options to test.
238
239        // Unescape + trim all options and flip it to have the expected values as keys.
240        $expectedoptions = $this->get_unescaped_options($expectedvalue);
241
242        // Get currently selected option's texts.
243        $texts = $this->get_selected_options(true);
244        $selectedoptiontexts = $this->get_unescaped_options($texts);
245
246        // Get currently selected option's values.
247        $values = $this->get_selected_options(false);
248        $selectedoptionvalues = $this->get_unescaped_options($values);
249
250        // Precheck to speed things up.
251        if (count($expectedoptions) !== count($selectedoptiontexts) ||
252                count($expectedoptions) !== count($selectedoptionvalues)) {
253            return false;
254        }
255
256        // We check against string-ordered lists of options.
257        if ($expectedoptions != $selectedoptiontexts &&
258                $expectedoptions != $selectedoptionvalues) {
259            return false;
260        }
261
262        return true;
263    }
264
265    /**
266     * Cleans the list of options and returns it as a string separating options with |||.
267     *
268     * @param string $value The string containing the escaped options.
269     * @return string The options
270     */
271    protected function get_unescaped_options($value) {
272
273        // Can be multiple comma separated, with valuable commas escaped with backslash.
274        $optionsarray = array_map(
275            'trim',
276            preg_replace('/\\\,/', ',',
277                preg_split('/(?<!\\\),/', $value)
278           )
279        );
280
281        // Sort by value (keeping the keys is irrelevant).
282        core_collator::asort($optionsarray, SORT_STRING);
283
284        // Returning it as a string which is easier to match against other values.
285        return implode('|||', $optionsarray);
286    }
287
288    /**
289     * Returns the field selected values.
290     *
291     * Externalized from the common behat_form_field API method get_value() as
292     * matches() needs to check against both values and texts.
293     *
294     * @param bool $returntexts Returns the options texts or the options values.
295     * @return string
296     */
297    protected function get_selected_options($returntexts = true) {
298
299        $method = 'getHtml';
300        if ($returntexts === false) {
301            $method = 'getValue';
302        }
303
304        // Is the select multiple?
305        $multiple = $this->field->hasAttribute('multiple');
306
307        $selectedoptions = array(); // To accumulate found selected options.
308
309        // Selenium getValue() implementation breaks - separates - values having
310        // commas within them, so we'll be looking for options with the 'selected' attribute instead.
311        if ($this->running_javascript()) {
312            // Get all the options in the select and extract their value/text pairs.
313            $alloptions = $this->field->findAll('xpath', '//option');
314            foreach ($alloptions as $option) {
315                // Is it selected?
316                if ($option->hasAttribute('selected')) {
317                    if ($multiple) {
318                        // If the select is multiple, text commas must be encoded.
319                        $selectedoptions[] = trim(str_replace(',', '\,', $option->{$method}()));
320                    } else {
321                        $selectedoptions[] = trim($option->{$method}());
322                    }
323                }
324            }
325
326        } else {
327            // Goutte does not keep the 'selected' attribute updated, but its getValue() returns
328            // the selected elements correctly, also those having commas within them.
329
330            // Goutte returns the values as an array or as a string depending
331            // on whether multiple options are selected or not.
332            $values = $this->field->getValue();
333            if (!is_array($values)) {
334                $values = array($values);
335            }
336
337            // Get all the options in the select and extract their value/text pairs.
338            $alloptions = $this->field->findAll('xpath', '//option');
339            foreach ($alloptions as $option) {
340                // Is it selected?
341                if (in_array($option->getValue(), $values)) {
342                    if ($multiple) {
343                        // If the select is multiple, text commas must be encoded.
344                        $selectedoptions[] = trim(str_replace(',', '\,', $option->{$method}()));
345                    } else {
346                        $selectedoptions[] = trim($option->{$method}());
347                    }
348                }
349            }
350        }
351
352        return implode(', ', $selectedoptions);
353    }
354
355    /**
356     * Returns the opton XPath based on it's select xpath.
357     *
358     * @param string $option
359     * @param string $selectxpath
360     * @return string xpath
361     */
362    protected function get_option_xpath($option, $selectxpath) {
363        $valueliteral = $this->session->getSelectorsHandler()->xpathLiteral(trim($option));
364        return $selectxpath . "/descendant::option[(./@value=$valueliteral or normalize-space(.)=$valueliteral)]";
365    }
366}
Note: See TracBrowser for help on using the repository browser.