MDL-63185 mod_quiz: add custom behat step to create user attempts
[moodle.git] / mod / quiz / tests / behat / behat_mod_quiz.php
CommitLineData
7f051de2
MG
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 to mod_quiz.
19 *
e1a2d0d9
CC
20 * @package mod_quiz
21 * @category test
22 * @copyright 2014 Marina Glancy
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7f051de2
MG
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');
2f83d71c 29require_once(__DIR__ . '/../../../../question/tests/behat/behat_question_base.php');
7f051de2 30
eb9ca848 31use Behat\Gherkin\Node\TableNode as TableNode;
42ad096f
RT
32
33use Behat\Mink\Exception\ExpectationException as ExpectationException;
7f051de2
MG
34
35/**
36 * Steps definitions related to mod_quiz.
37 *
e1a2d0d9
CC
38 * @copyright 2014 Marina Glancy
39 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7f051de2 40 */
2f83d71c 41class behat_mod_quiz extends behat_question_base {
8fec847c
TH
42
43 /**
44 * Put the specified questions on the specified pages of a given quiz.
45 *
eeb75525 46 * The first row should be column names:
441d284a 47 * | question | page | maxmark | requireprevious |
eeb75525
TH
48 * The first two of those are required. The others are optional.
49 *
50 * question needs to uniquely match a question name.
51 * page is a page number. Must start at 1, and on each following
52 * row should be the same as the previous, or one more.
53 * maxmark What the question is marked out of. Defaults to question.defaultmark.
441d284a 54 * requireprevious The question can only be attempted after the previous one was completed.
eeb75525
TH
55 *
56 * Then there should be a number of rows of data, one for each question you want to add.
57 *
58 * For backwards-compatibility reasons, specifying the column names is optional
59 * (but strongly encouraged). If not specified, the columns are asseumed to be
60 * | question | page | maxmark |.
8fec847c
TH
61 *
62 * @param string $quizname the name of the quiz to add questions to.
63 * @param TableNode $data information about the questions to add.
64 *
65 * @Given /^quiz "([^"]*)" contains the following questions:$/
66 */
67 public function quiz_contains_the_following_questions($quizname, TableNode $data) {
68 global $DB;
69
70 $quiz = $DB->get_record('quiz', array('name' => $quizname), '*', MUST_EXIST);
71
eeb75525
TH
72 // Deal with backwards-compatibility, optional first row.
73 $firstrow = $data->getRow(0);
74 if (!in_array('question', $firstrow) && !in_array('page', $firstrow)) {
75 if (count($firstrow) == 2) {
76 $headings = array('question', 'page');
77 } else if (count($firstrow) == 3) {
78 $headings = array('question', 'page', 'maxmark');
79 } else {
8fec847c 80 throw new ExpectationException('When adding questions to a quiz, you should give 2 or three 3 things: ' .
4fa49cc6 81 ' the question name, the page number, and optionally the maximum mark. ' .
eeb75525
TH
82 count($firstrow) . ' values passed.', $this->getSession());
83 }
84 $rows = $data->getRows();
85 array_unshift($rows, $headings);
42ad096f 86 $data = new TableNode($rows);
eeb75525
TH
87 }
88
89 // Add the questions.
90 $lastpage = 0;
91 foreach ($data->getHash() as $questiondata) {
92 if (!array_key_exists('question', $questiondata)) {
93 throw new ExpectationException('When adding questions to a quiz, ' .
94 'the question name column is required.', $this->getSession());
95 }
96 if (!array_key_exists('page', $questiondata)) {
97 throw new ExpectationException('When adding questions to a quiz, ' .
98 'the page number column is required.', $this->getSession());
99 }
100
4fa49cc6
SR
101 // Question id, category and type.
102 $question = $DB->get_record('question', array('name' => $questiondata['question']), 'id, category, qtype', MUST_EXIST);
eeb75525
TH
103
104 // Page number.
105 $page = clean_param($questiondata['page'], PARAM_INT);
106 if ($page <= 0 || (string) $page !== $questiondata['page']) {
107 throw new ExpectationException('The page number for question "' .
108 $questiondata['question'] . '" must be a positive integer.',
109 $this->getSession());
110 }
111 if ($page < $lastpage || $page > $lastpage + 1) {
112 throw new ExpectationException('When adding questions to a quiz, ' .
113 'the page number for each question must either be the same, ' .
114 'or one more, then the page number for the previous question.',
115 $this->getSession());
8fec847c 116 }
eeb75525 117 $lastpage = $page;
8fec847c 118
eeb75525
TH
119 // Max mark.
120 if (!array_key_exists('maxmark', $questiondata) || $questiondata['maxmark'] === '') {
8fec847c
TH
121 $maxmark = null;
122 } else {
eeb75525
TH
123 $maxmark = clean_param($questiondata['maxmark'], PARAM_FLOAT);
124 if (!is_numeric($questiondata['maxmark']) || $maxmark < 0) {
125 throw new ExpectationException('The max mark for question "' .
126 $questiondata['question'] . '" must be a positive number.',
8fec847c
TH
127 $this->getSession());
128 }
129 }
130
4fa49cc6
SR
131 if ($question->qtype == 'random') {
132 if (!array_key_exists('includingsubcategories', $questiondata) || $questiondata['includingsubcategories'] === '') {
133 $includingsubcategories = false;
134 } else {
135 $includingsubcategories = clean_param($questiondata['includingsubcategories'], PARAM_BOOL);
136 }
137 quiz_add_random_questions($quiz, $page, $question->category, 1, $includingsubcategories);
138 } else {
139 // Add the question.
140 quiz_add_quiz_question($question->id, $quiz, $page, $maxmark);
141 }
441d284a
TH
142
143 // Require previous.
144 if (array_key_exists('requireprevious', $questiondata)) {
145 if ($questiondata['requireprevious'] === '1') {
146 $slot = $DB->get_field('quiz_slots', 'MAX(slot)', array('quizid' => $quiz->id));
147 $DB->set_field('quiz_slots', 'requireprevious', 1,
148 array('quizid' => $quiz->id, 'slot' => $slot));
149 } else if ($questiondata['requireprevious'] !== '' && $questiondata['requireprevious'] !== '0') {
150 throw new ExpectationException('Require previous for question "' .
151 $questiondata['question'] . '" should be 0, 1 or blank.',
152 $this->getSession());
153 }
154 }
8fec847c 155 }
eeb75525 156
8fec847c
TH
157 quiz_update_sumgrades($quiz);
158 }
159
5d949702
K
160 /**
161 * Put the specified section headings to start at specified pages of a given quiz.
162 *
163 * The first row should be column names:
164 * | heading | firstslot | shufflequestions |
165 *
166 * heading is the section heading text
167 * firstslot is the slot number where the section starts
168 * shuffle whether this section is shuffled (0 or 1)
169 *
170 * Then there should be a number of rows of data, one for each section you want to add.
171 *
172 * @param string $quizname the name of the quiz to add sections to.
173 * @param TableNode $data information about the sections to add.
174 *
175 * @Given /^quiz "([^"]*)" contains the following sections:$/
176 */
177 public function quiz_contains_the_following_sections($quizname, TableNode $data) {
178 global $DB;
179
180 $quiz = $DB->get_record('quiz', array('name' => $quizname), '*', MUST_EXIST);
181
182 // Add the sections.
183 $previousfirstslot = 0;
184 foreach ($data->getHash() as $rownumber => $sectiondata) {
185 if (!array_key_exists('heading', $sectiondata)) {
186 throw new ExpectationException('When adding sections to a quiz, ' .
187 'the heading name column is required.', $this->getSession());
188 }
189 if (!array_key_exists('firstslot', $sectiondata)) {
190 throw new ExpectationException('When adding sections to a quiz, ' .
191 'the firstslot name column is required.', $this->getSession());
192 }
193 if (!array_key_exists('shuffle', $sectiondata)) {
194 throw new ExpectationException('When adding sections to a quiz, ' .
195 'the shuffle name column is required.', $this->getSession());
196 }
197
198 if ($rownumber == 0) {
199 $section = $DB->get_record('quiz_sections', array('quizid' => $quiz->id), '*', MUST_EXIST);
200 } else {
201 $section = new stdClass();
202 $section->quizid = $quiz->id;
203 }
204
205 // Heading.
206 $section->heading = $sectiondata['heading'];
207
208 // First slot.
209 $section->firstslot = clean_param($sectiondata['firstslot'], PARAM_INT);
210 if ($section->firstslot <= $previousfirstslot ||
211 (string) $section->firstslot !== $sectiondata['firstslot']) {
212 throw new ExpectationException('The firstslot number for section "' .
213 $sectiondata['heading'] . '" must an integer greater than the previous section firstslot.',
214 $this->getSession());
215 }
216 if ($rownumber == 0 && $section->firstslot != 1) {
217 throw new ExpectationException('The first section must have firstslot set to 1.',
218 $this->getSession());
219 }
220
221 // Shuffle.
222 $section->shufflequestions = clean_param($sectiondata['shuffle'], PARAM_INT);
223 if ((string) $section->shufflequestions !== $sectiondata['shuffle']) {
224 throw new ExpectationException('The shuffle value for section "' .
225 $sectiondata['heading'] . '" must be 0 or 1.',
226 $this->getSession());
227 }
228
229 if ($rownumber == 0) {
230 $DB->update_record('quiz_sections', $section);
231 } else {
232 $DB->insert_record('quiz_sections', $section);
233 }
234 }
235
236 if ($section->firstslot > $DB->count_records('quiz_slots', array('quizid' => $quiz->id))) {
237 throw new ExpectationException('The section firstslot must be less than the total number of slots in the quiz.',
238 $this->getSession());
239 }
240 }
241
7f051de2
MG
242 /**
243 * Adds a question to the existing quiz with filling the form.
244 *
245 * The form for creating a question should be on one page.
246 *
247 * @When /^I add a "(?P<question_type_string>(?:[^"]|\\")*)" question to the "(?P<quiz_name_string>(?:[^"]|\\")*)" quiz with:$/
248 * @param string $questiontype
249 * @param string $quizname
2f83d71c 250 * @param TableNode $questiondata with data for filling the add question form
7f051de2 251 */
2f83d71c 252 public function i_add_question_to_the_quiz_with($questiontype, $quizname, TableNode $questiondata) {
7f051de2
MG
253 $quizname = $this->escape($quizname);
254 $editquiz = $this->escape(get_string('editquiz', 'quiz'));
b8871eff 255 $quizadmin = $this->escape(get_string('pluginadministration', 'quiz'));
7f051de2 256 $addaquestion = $this->escape(get_string('addaquestion', 'quiz'));
e1a2d0d9
CC
257 $menuxpath = "//div[contains(@class, ' page-add-actions ')][last()]//a[contains(@class, ' textmenu')]";
258 $itemxpath = "//div[contains(@class, ' page-add-actions ')][last()]//a[contains(@class, ' addquestion ')]";
eb9ca848
RT
259
260 $this->execute('behat_general::click_link', $quizname);
261
02fda279 262 $this->execute("behat_navigation::i_navigate_to_in_current_page_administration", $editquiz);
eb9ca848
RT
263
264 $this->execute("behat_general::i_click_on", array($menuxpath, "xpath_element"));
265 $this->execute("behat_general::i_click_on", array($itemxpath, "xpath_element"));
266
267 $this->finish_adding_question($questiontype, $questiondata);
7f051de2 268 }
e1a2d0d9
CC
269
270 /**
271 * Set the max mark for a question on the Edit quiz page.
272 *
273 * @When /^I set the max mark for question "(?P<question_name_string>(?:[^"]|\\")*)" to "(?P<new_mark_string>(?:[^"]|\\")*)"$/
274 * @param string $questionname the name of the question to set the max mark for.
275 * @param string $newmark the mark to set
276 */
277 public function i_set_the_max_mark_for_quiz_question($questionname, $newmark) {
eb9ca848
RT
278 $this->execute('behat_general::click_link', $this->escape(get_string('editmaxmark', 'quiz')));
279
280 $this->execute('behat_general::wait_until_exists', array("li input[name=maxmark]", "css_element"));
281
282 $this->execute('behat_general::assert_page_contains_text', $this->escape(get_string('edittitleinstructions')));
283
284 $this->execute('behat_forms::i_set_the_field_to', array('maxmark', $this->escape($newmark) . chr(10)));
e1a2d0d9
CC
285 }
286
287 /**
288 * Open the add menu on a given page, or at the end of the Edit quiz page.
289 * @Given /^I open the "(?P<page_n_or_last_string>(?:[^"]|\\")*)" add to quiz menu$/
290 * @param string $pageorlast either "Page n" or "last".
291 */
292 public function i_open_the_add_to_quiz_menu_for($pageorlast) {
293
294 if (!$this->running_javascript()) {
295 throw new DriverException('Activities actions menu not available when Javascript is disabled');
296 }
297
298 if ($pageorlast == 'last') {
299 $xpath = "//div[@class = 'last-add-menu']//a[contains(@class, 'textmenu') and contains(., 'Add')]";
300 } else if (preg_match('~Page (\d+)~', $pageorlast, $matches)) {
301 $xpath = "//li[@id = 'page-{$matches[1]}']//a[contains(@class, 'textmenu') and contains(., 'Add')]";
302 } else {
303 throw new ExpectationException("The I open the add to quiz menu step must specify either 'Page N' or 'last'.");
304 }
eb9ca848 305 $this->find('xpath', $xpath)->click();
e1a2d0d9
CC
306 }
307
e1a2d0d9
CC
308 /**
309 * Check whether a particular question is on a particular page of the quiz on the Edit quiz page.
310 * @Given /^I should see "(?P<question_name>(?:[^"]|\\")*)" on quiz page "(?P<page_number>\d+)"$/
311 * @param string $questionname the name of the question we are looking for.
312 * @param number $pagenumber the page it should be found on.
e1a2d0d9
CC
313 */
314 public function i_should_see_on_quiz_page($questionname, $pagenumber) {
315 $xpath = "//li[contains(., '" . $this->escape($questionname) .
316 "')][./preceding-sibling::li[contains(@class, 'pagenumber')][1][contains(., 'Page " .
317 $pagenumber . "')]]";
eb9ca848
RT
318
319 $this->execute('behat_general::should_exist', array($xpath, 'xpath_element'));
e1a2d0d9
CC
320 }
321
a69f81f0
CC
322 /**
323 * Check whether a particular question is not on a particular page of the quiz on the Edit quiz page.
324 * @Given /^I should not see "(?P<question_name>(?:[^"]|\\")*)" on quiz page "(?P<page_number>\d+)"$/
325 * @param string $questionname the name of the question we are looking for.
326 * @param number $pagenumber the page it should be found on.
a69f81f0
CC
327 */
328 public function i_should_not_see_on_quiz_page($questionname, $pagenumber) {
329 $xpath = "//li[contains(., '" . $this->escape($questionname) .
330 "')][./preceding-sibling::li[contains(@class, 'pagenumber')][1][contains(., 'Page " .
331 $pagenumber . "')]]";
eb9ca848
RT
332
333 $this->execute('behat_general::should_not_exist', array($xpath, 'xpath_element'));
a69f81f0
CC
334 }
335
e1a2d0d9
CC
336 /**
337 * Check whether one question comes before another on the Edit quiz page.
338 * The two questions must be on the same page.
339 * @Given /^I should see "(?P<first_q_name>(?:[^"]|\\")*)" before "(?P<second_q_name>(?:[^"]|\\")*)" on the edit quiz page$/
340 * @param string $firstquestionname the name of the question that should come first in order.
341 * @param string $secondquestionname the name of the question that should come immediately after it in order.
e1a2d0d9
CC
342 */
343 public function i_should_see_before_on_the_edit_quiz_page($firstquestionname, $secondquestionname) {
344 $xpath = "//li[contains(@class, ' slot ') and contains(., '" . $this->escape($firstquestionname) .
345 "')]/following-sibling::li[contains(@class, ' slot ')][1]" .
346 "[contains(., '" . $this->escape($secondquestionname) . "')]";
eb9ca848
RT
347
348 $this->execute('behat_general::should_exist', array($xpath, 'xpath_element'));
e1a2d0d9
CC
349 }
350
351 /**
352 * Check the number displayed alongside a question on the Edit quiz page.
353 * @Given /^"(?P<question_name>(?:[^"]|\\")*)" should have number "(?P<number>(?:[^"]|\\")*)" on the edit quiz page$/
354 * @param string $questionname the name of the question we are looking for.
355 * @param number $number the number (or 'i') that should be displayed beside that question.
e1a2d0d9
CC
356 */
357 public function should_have_number_on_the_edit_quiz_page($questionname, $number) {
a69f81f0
CC
358 $xpath = "//li[contains(@class, 'slot') and contains(., '" . $this->escape($questionname) .
359 "')]//span[contains(@class, 'slotnumber') and normalize-space(text()) = '" . $this->escape($number) . "']";
eb9ca848
RT
360
361 $this->execute('behat_general::should_exist', array($xpath, 'xpath_element'));
e1a2d0d9
CC
362 }
363
a69f81f0
CC
364 /**
365 * Get the xpath for a partcular add/remove page-break icon.
366 * @param string $addorremoves 'Add' or 'Remove'.
367 * @param string $questionname the name of the question before the icon.
368 * @return string the requried xpath.
369 */
370 protected function get_xpath_page_break_icon_after_question($addorremoves, $questionname) {
371 return "//li[contains(@class, 'slot') and contains(., '" . $this->escape($questionname) .
372 "')]//a[contains(@class, 'page_split_join') and @title = '" . $addorremoves . " page break']";
373 }
374
e1a2d0d9
CC
375 /**
376 * Click the add or remove page-break icon after a particular question.
377 * @When /^I click on the "(Add|Remove)" page break icon after question "(?P<question_name>(?:[^"]|\\")*)"$/
378 * @param string $addorremoves 'Add' or 'Remove'.
379 * @param string $questionname the name of the question before the icon to click.
e1a2d0d9
CC
380 */
381 public function i_click_on_the_page_break_icon_after_question($addorremoves, $questionname) {
a69f81f0 382 $xpath = $this->get_xpath_page_break_icon_after_question($addorremoves, $questionname);
eb9ca848
RT
383
384 $this->execute("behat_general::i_click_on", array($xpath, "xpath_element"));
a69f81f0
CC
385 }
386
387 /**
388 * Assert the add or remove page-break icon after a particular question exists.
389 * @When /^the "(Add|Remove)" page break icon after question "(?P<question_name>(?:[^"]|\\")*)" should exist$/
390 * @param string $addorremoves 'Add' or 'Remove'.
391 * @param string $questionname the name of the question before the icon to click.
392 * @return array of steps.
393 */
394 public function the_page_break_icon_after_question_should_exist($addorremoves, $questionname) {
395 $xpath = $this->get_xpath_page_break_icon_after_question($addorremoves, $questionname);
eb9ca848
RT
396
397 $this->execute('behat_general::should_exist', array($xpath, 'xpath_element'));
a69f81f0
CC
398 }
399
400 /**
401 * Assert the add or remove page-break icon after a particular question does not exist.
402 * @When /^the "(Add|Remove)" page break icon after question "(?P<question_name>(?:[^"]|\\")*)" should not exist$/
403 * @param string $addorremoves 'Add' or 'Remove'.
404 * @param string $questionname the name of the question before the icon to click.
405 * @return array of steps.
406 */
407 public function the_page_break_icon_after_question_should_not_exist($addorremoves, $questionname) {
408 $xpath = $this->get_xpath_page_break_icon_after_question($addorremoves, $questionname);
eb9ca848
RT
409
410 $this->execute('behat_general::should_not_exist', array($xpath, 'xpath_element'));
a69f81f0
CC
411 }
412
413 /**
414 * Check the add or remove page-break link after a particular question contains the given parameters in its url.
415 * @When /^the "(Add|Remove)" page break link after question "(?P<question_name>(?:[^"]|\\")*) should contain:"$/
416 * @param string $addorremoves 'Add' or 'Remove'.
417 * @param string $questionname the name of the question before the icon to click.
418 * @param TableNode $paramdata with data for checking the page break url
419 * @return array of steps.
420 */
421 public function the_page_break_link_after_question_should_contain($addorremoves, $questionname, $paramdata) {
422 $xpath = $this->get_xpath_page_break_icon_after_question($addorremoves, $questionname);
eb9ca848
RT
423
424 $this->execute("behat_general::i_click_on", array($xpath, "xpath_element"));
e1a2d0d9
CC
425 }
426
5d949702
K
427 /**
428 * Set Shuffle for shuffling questions within sections
429 *
430 * @param string $heading the heading of the section to change shuffle for.
431 *
432 * @Given /^I click on shuffle for section "([^"]*)" on the quiz edit page$/
433 */
434 public function i_click_on_shuffle_for_section($heading) {
435 $xpath = $this->get_xpath_for_shuffle_checkbox($heading);
436 $checkbox = $this->find('xpath', $xpath);
437 $this->ensure_node_is_visible($checkbox);
438 $checkbox->click();
439 }
440
441 /**
442 * Check the shuffle checkbox for a particular section.
443 *
444 * @param string $heading the heading of the section to check shuffle for
445 * @param int $value whether the shuffle checkbox should be on or off.
446 *
447 * @Given /^shuffle for section "([^"]*)" should be "(On|Off)" on the quiz edit page$/
448 */
449 public function shuffle_for_section_should_be($heading, $value) {
450 $xpath = $this->get_xpath_for_shuffle_checkbox($heading);
451 $checkbox = $this->find('xpath', $xpath);
452 $this->ensure_node_is_visible($checkbox);
453 if ($value == 'On' && !$checkbox->isChecked()) {
454 $msg = "Shuffle for section '$heading' is not checked, but you are expecting it to be checked ($value). " .
455 "Check the line with: \nshuffle for section \"$heading\" should be \"$value\" on the quiz edit page" .
456 "\nin your behat script";
457 throw new ExpectationException($msg, $this->getSession());
458 } else if ($value == 'Off' && $checkbox->isChecked()) {
459 $msg = "Shuffle for section '$heading' is checked, but you are expecting it not to be ($value). " .
460 "Check the line with: \nshuffle for section \"$heading\" should be \"$value\" on the quiz edit page" .
461 "\nin your behat script";
462 throw new ExpectationException($msg, $this->getSession());
463 }
464 }
465
466 /**
467 * Return the xpath for shuffle checkbox in section heading
eb9ca848 468 * @param string $heading
5d949702
K
469 * @return string
470 */
471 protected function get_xpath_for_shuffle_checkbox($heading) {
472 return "//div[contains(@class, 'section-heading') and contains(., '" . $this->escape($heading) .
473 "')]//input[@type = 'checkbox']";
474 }
475
e1a2d0d9
CC
476 /**
477 * Move a question on the Edit quiz page by first clicking on the Move icon,
478 * then clicking one of the "After ..." links.
479 * @When /^I move "(?P<question_name>(?:[^"]|\\")*)" to "(?P<target>(?:[^"]|\\")*)" in the quiz by clicking the move icon$/
480 * @param string $questionname the name of the question we are looking for.
481 * @param string $target the target place to move to. One of the links in the pop-up like
482 * "After Page 1" or "After Question N".
e1a2d0d9
CC
483 */
484 public function i_move_question_after_item_by_clicking_the_move_icon($questionname, $target) {
485 $iconxpath = "//li[contains(@class, ' slot ') and contains(., '" . $this->escape($questionname) .
486 "')]//span[contains(@class, 'editing_move')]";
eb9ca848
RT
487
488 $this->execute("behat_general::i_click_on", array($iconxpath, "xpath_element"));
489 $this->execute("behat_general::i_click_on", array($this->escape($target), "text"));
e1a2d0d9
CC
490 }
491
492 /**
493 * Move a question on the Edit quiz page by dragging a given question on top of another item.
494 * @When /^I move "(?P<question_name>(?:[^"]|\\")*)" to "(?P<target>(?:[^"]|\\")*)" in the quiz by dragging$/
495 * @param string $questionname the name of the question we are looking for.
496 * @param string $target the target place to move to. Ether a question name, or "Page N"
e1a2d0d9
CC
497 */
498 public function i_move_question_after_item_by_dragging($questionname, $target) {
499 $iconxpath = "//li[contains(@class, ' slot ') and contains(., '" . $this->escape($questionname) .
500 "')]//span[contains(@class, 'editing_move')]//img";
501 $destinationxpath = "//li[contains(@class, ' slot ') or contains(@class, 'pagenumber ')]" .
502 "[contains(., '" . $this->escape($target) . "')]";
eb9ca848
RT
503
504 $this->execute('behat_general::i_drag_and_i_drop_it_in',
505 array($iconxpath, 'xpath_element', $destinationxpath, 'xpath_element')
e1a2d0d9
CC
506 );
507 }
a69f81f0
CC
508
509 /**
510 * Delete a question on the Edit quiz page by first clicking on the Delete icon,
511 * then clicking one of the "After ..." links.
512 * @When /^I delete "(?P<question_name>(?:[^"]|\\")*)" in the quiz by clicking the delete icon$/
513 * @param string $questionname the name of the question we are looking for.
514 * @return array of steps.
515 */
516 public function i_delete_question_by_clicking_the_delete_icon($questionname) {
517 $slotxpath = "//li[contains(@class, ' slot ') and contains(., '" . $this->escape($questionname) .
518 "')]";
519 $deletexpath = "//a[contains(@class, 'editing_delete')]";
eb9ca848
RT
520
521 $this->execute("behat_general::i_click_on", array($slotxpath . $deletexpath, "xpath_element"));
522
523 $this->execute('behat_general::i_click_on_in_the',
524 array('Yes', "button", "Confirm", "dialogue")
a69f81f0
CC
525 );
526 }
5d949702
K
527
528 /**
529 * Set the section heading for a given section on the Edit quiz page
530 *
531 * @When /^I change quiz section heading "(?P<section_name_string>(?:[^"]|\\")*)" to "(?P<new_section_heading_string>(?:[^"]|\\")*)"$/
532 * @param string $sectionname the heading to change.
533 * @param string $sectionheading the new heading to set.
534 */
535 public function i_set_the_section_heading_for($sectionname, $sectionheading) {
eb9ca848
RT
536 $this->execute('behat_general::click_link', $this->escape("Edit heading '{$sectionname}'"));
537
538 $this->execute('behat_general::assert_page_contains_text', $this->escape(get_string('edittitleinstructions')));
539
540 $this->execute('behat_forms::i_set_the_field_to', array('section', $this->escape($sectionheading) . chr(10)));
5d949702
K
541 }
542
543 /**
544 * Check that a given question comes after a given section heading in the
545 * quiz navigation block.
546 *
547 * @Then /^I should see question "(?P<questionnumber>\d+)" in section "(?P<section_heading_string>(?:[^"]|\\")*)" in the quiz navigation$/
548 * @param int $questionnumber the number of the question to check.
549 * @param string $sectionheading which section heading it should appear after.
550 */
551 public function i_should_see_question_in_section_in_the_quiz_navigation($questionnumber, $sectionheading) {
552
553 // Using xpath literal to avoid quotes problems.
921faad9
RT
554 $questionnumberliteral = behat_context_helper::escape('Question ' . $questionnumber);
555 $headingliteral = behat_context_helper::escape($sectionheading);
5d949702
K
556
557 // Split in two checkings to give more feedback in case of exception.
558 $exception = new ExpectationException('Question "' . $questionnumber . '" is not in section "' .
559 $sectionheading . '" in the quiz navigation.', $this->getSession());
560 $xpath = "//div[@id = 'mod_quiz_navblock']//*[contains(concat(' ', normalize-space(@class), ' '), ' qnbutton ') and " .
561 "contains(., {$questionnumberliteral}) and contains(preceding-sibling::h3[1], {$headingliteral})]";
562 $this->find('xpath', $xpath);
563 }
35aa9ade
SL
564
565 /**
566 * Attempt a quiz.
567 *
568 * The first row should be column names:
569 * | slot | actualquestion | variant | response |
570 * The first two of those are required. The others are optional.
571 *
572 * slot The slot
573 * actualquestion This column is optional, and is only needed if the quiz contains
574 * random questions. If so, this will let you control which acutal
575 * question gets picked when this slot is 'randomised' at the
576 * start of the attempt. If you don't specify, then one will be picked
577 * at random (which might make the reponse meaningless).
578 * variant This column is similar, and also options. It is only needed if
579 * the question that ends up in this slot returns something greater
580 * than 1 for $question->get_num_variants(). Like with actualquestion,
581 * if you specify a value here it is used the fix the 'random' choice
582 * made when the quiz is started.
583 * response The response that was submitted. How this is interpreted depends on
584 * the question type. It gets passed to
585 * {@link core_question_generator::get_simulated_post_data_for_question_attempt()
586 * and therefore to the un_summarise_response method of the question to decode.
587 *
588 * Then there should be a number of rows of data, one for each question you want to add.
589 * There is no need to supply answers to all questions. If so, other qusetions will be
590 * left unanswered.
591 *
592 * @param string $quizname the name of the quiz the user will attempt.
593 * @param string $username the username of the user that will attempt.
594 * @param TableNode $attemptinfo information about the questions to add, as above.
595 * @Given /^I attempt quiz "([^"]*)" as "([^"]*)" with the following responses:$/
596 */
597 public function i_attempt_quiz_as_user_setting_the_following_responses($quizname, $username, TableNode $attemptinfo) {
598 global $DB, $USER;
599
600 /** @var mod_quiz_generator $quizgenerator */
601 $quizgenerator = behat_util::get_data_generator()->get_plugin_generator('mod_quiz');
602
603 $quizid = $DB->get_field('quiz', 'id', ['name' => $quizname], MUST_EXIST);
604 $user = $DB->get_record('user', ['username' => $username], '*', MUST_EXIST);
605
606 $forcedrandomquestions = [];
607 $forcedvariants = [];
608 $responses = [];
609 foreach ($attemptinfo->getHash() as $slotinfo) {
610 if (empty($slotinfo['slot'])) {
611 throw new ExpectationException('When simulating a quiz attempt, ' .
612 'the slot column is required.', $this->getSession());
613 }
614 if (!array_key_exists('response', $slotinfo)) {
615 throw new ExpectationException('When simulating a quiz attempt, ' .
616 'the response column is required.', $this->getSession());
617 }
618 $responses[$slotinfo['slot']] = $slotinfo['response'];
619
620 if (!empty($slotinfo['actualquestion'])) {
621 $forcedrandomquestions[$slotinfo['slot']] = $DB->get_field('question', 'id',
622 ['name' => $slotinfo['actualquestion']], MUST_EXIST);
623 }
624
625 if (!empty($slotinfo['variant'])) {
626 $forcedvariants[$slotinfo['slot']] = (int) $slotinfo['variant'];
627 }
628 }
629
630 $saveduser = $USER; // TODO there is probably a better way to do this. If not, there should be.
631 $USER = $user;
632
633 $attempt = $quizgenerator->create_attempt($quizid, $user->id,
634 $forcedrandomquestions, $forcedvariants);
635
636 $quizgenerator->submit_responses($attempt->id, $responses, true);
637
638 $USER = $saveduser;
639 }
7f051de2 640}