MDL-63185 mod_quiz: replace existing tests to use new step
[moodle.git] / mod / quiz / tests / behat / behat_mod_quiz.php
blobfb8e540e9722557221b3f3be2dc6434f5aa309b4
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.
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/>.
17 /**
18 * Steps definitions related to mod_quiz.
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
26 // NOTE: no MOODLE_INTERNAL test here, this file may be required by behat before including /config.php.
28 require_once(__DIR__ . '/../../../../lib/behat/behat_base.php');
29 require_once(__DIR__ . '/../../../../question/tests/behat/behat_question_base.php');
31 use Behat\Gherkin\Node\TableNode as TableNode;
33 use Behat\Mink\Exception\ExpectationException as ExpectationException;
35 /**
36 * Steps definitions related to mod_quiz.
38 * @copyright 2014 Marina Glancy
39 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
41 class behat_mod_quiz extends behat_question_base {
43 /**
44 * Put the specified questions on the specified pages of a given quiz.
46 * The first row should be column names:
47 * | question | page | maxmark | requireprevious |
48 * The first two of those are required. The others are optional.
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.
54 * requireprevious The question can only be attempted after the previous one was completed.
56 * Then there should be a number of rows of data, one for each question you want to add.
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 |.
62 * @param string $quizname the name of the quiz to add questions to.
63 * @param TableNode $data information about the questions to add.
65 * @Given /^quiz "([^"]*)" contains the following questions:$/
67 public function quiz_contains_the_following_questions($quizname, TableNode $data) {
68 global $DB;
70 $quiz = $DB->get_record('quiz', array('name' => $quizname), '*', MUST_EXIST);
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 {
80 throw new ExpectationException('When adding questions to a quiz, you should give 2 or three 3 things: ' .
81 ' the question name, the page number, and optionally the maximum mark. ' .
82 count($firstrow) . ' values passed.', $this->getSession());
84 $rows = $data->getRows();
85 array_unshift($rows, $headings);
86 $data = new TableNode($rows);
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());
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());
101 // Question id, category and type.
102 $question = $DB->get_record('question', array('name' => $questiondata['question']), 'id, category, qtype', MUST_EXIST);
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());
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());
117 $lastpage = $page;
119 // Max mark.
120 if (!array_key_exists('maxmark', $questiondata) || $questiondata['maxmark'] === '') {
121 $maxmark = null;
122 } else {
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.',
127 $this->getSession());
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);
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);
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());
157 quiz_update_sumgrades($quiz);
161 * Put the specified section headings to start at specified pages of a given quiz.
163 * The first row should be column names:
164 * | heading | firstslot | shufflequestions |
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)
170 * Then there should be a number of rows of data, one for each section you want to add.
172 * @param string $quizname the name of the quiz to add sections to.
173 * @param TableNode $data information about the sections to add.
175 * @Given /^quiz "([^"]*)" contains the following sections:$/
177 public function quiz_contains_the_following_sections($quizname, TableNode $data) {
178 global $DB;
180 $quiz = $DB->get_record('quiz', array('name' => $quizname), '*', MUST_EXIST);
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());
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());
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());
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;
205 // Heading.
206 $section->heading = $sectiondata['heading'];
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());
216 if ($rownumber == 0 && $section->firstslot != 1) {
217 throw new ExpectationException('The first section must have firstslot set to 1.',
218 $this->getSession());
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());
229 if ($rownumber == 0) {
230 $DB->update_record('quiz_sections', $section);
231 } else {
232 $DB->insert_record('quiz_sections', $section);
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());
243 * Adds a question to the existing quiz with filling the form.
245 * The form for creating a question should be on one page.
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
250 * @param TableNode $questiondata with data for filling the add question form
252 public function i_add_question_to_the_quiz_with($questiontype, $quizname, TableNode $questiondata) {
253 $quizname = $this->escape($quizname);
254 $editquiz = $this->escape(get_string('editquiz', 'quiz'));
255 $quizadmin = $this->escape(get_string('pluginadministration', 'quiz'));
256 $addaquestion = $this->escape(get_string('addaquestion', 'quiz'));
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 ')]";
260 $this->execute('behat_general::click_link', $quizname);
262 $this->execute("behat_navigation::i_navigate_to_in_current_page_administration", $editquiz);
264 $this->execute("behat_general::i_click_on", array($menuxpath, "xpath_element"));
265 $this->execute("behat_general::i_click_on", array($itemxpath, "xpath_element"));
267 $this->finish_adding_question($questiontype, $questiondata);
271 * Set the max mark for a question on the Edit quiz page.
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
277 public function i_set_the_max_mark_for_quiz_question($questionname, $newmark) {
278 $this->execute('behat_general::click_link', $this->escape(get_string('editmaxmark', 'quiz')));
280 $this->execute('behat_general::wait_until_exists', array("li input[name=maxmark]", "css_element"));
282 $this->execute('behat_general::assert_page_contains_text', $this->escape(get_string('edittitleinstructions')));
284 $this->execute('behat_forms::i_set_the_field_to', array('maxmark', $this->escape($newmark) . chr(10)));
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".
292 public function i_open_the_add_to_quiz_menu_for($pageorlast) {
294 if (!$this->running_javascript()) {
295 throw new DriverException('Activities actions menu not available when Javascript is disabled');
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'.");
305 $this->find('xpath', $xpath)->click();
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.
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 . "')]]";
319 $this->execute('behat_general::should_exist', array($xpath, 'xpath_element'));
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.
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 . "')]]";
333 $this->execute('behat_general::should_not_exist', array($xpath, 'xpath_element'));
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.
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) . "')]";
348 $this->execute('behat_general::should_exist', array($xpath, 'xpath_element'));
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.
357 public function should_have_number_on_the_edit_quiz_page($questionname, $number) {
358 $xpath = "//li[contains(@class, 'slot') and contains(., '" . $this->escape($questionname) .
359 "')]//span[contains(@class, 'slotnumber') and normalize-space(text()) = '" . $this->escape($number) . "']";
361 $this->execute('behat_general::should_exist', array($xpath, 'xpath_element'));
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.
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']";
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.
381 public function i_click_on_the_page_break_icon_after_question($addorremoves, $questionname) {
382 $xpath = $this->get_xpath_page_break_icon_after_question($addorremoves, $questionname);
384 $this->execute("behat_general::i_click_on", array($xpath, "xpath_element"));
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.
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);
397 $this->execute('behat_general::should_exist', array($xpath, 'xpath_element'));
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.
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);
410 $this->execute('behat_general::should_not_exist', array($xpath, 'xpath_element'));
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.
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);
424 $this->execute("behat_general::i_click_on", array($xpath, "xpath_element"));
428 * Set Shuffle for shuffling questions within sections
430 * @param string $heading the heading of the section to change shuffle for.
432 * @Given /^I click on shuffle for section "([^"]*)" on the quiz edit page$/
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();
442 * Check the shuffle checkbox for a particular section.
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.
447 * @Given /^shuffle for section "([^"]*)" should be "(On|Off)" on the quiz edit page$/
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());
467 * Return the xpath for shuffle checkbox in section heading
468 * @param string $heading
469 * @return string
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']";
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".
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')]";
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"));
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"
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) . "')]";
504 $this->execute('behat_general::i_drag_and_i_drop_it_in',
505 array($iconxpath, 'xpath_element', $destinationxpath, 'xpath_element')
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.
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')]";
521 $this->execute("behat_general::i_click_on", array($slotxpath . $deletexpath, "xpath_element"));
523 $this->execute('behat_general::i_click_on_in_the',
524 array('Yes', "button", "Confirm", "dialogue")
529 * Set the section heading for a given section on the Edit quiz page
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.
535 public function i_set_the_section_heading_for($sectionname, $sectionheading) {
536 $this->execute('behat_general::click_link', $this->escape("Edit heading '{$sectionname}'"));
538 $this->execute('behat_general::assert_page_contains_text', $this->escape(get_string('edittitleinstructions')));
540 $this->execute('behat_forms::i_set_the_field_to', array('section', $this->escape($sectionheading) . chr(10)));
544 * Check that a given question comes after a given section heading in the
545 * quiz navigation block.
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.
551 public function i_should_see_question_in_section_in_the_quiz_navigation($questionnumber, $sectionheading) {
553 // Using xpath literal to avoid quotes problems.
554 $questionnumberliteral = behat_context_helper::escape('Question ' . $questionnumber);
555 $headingliteral = behat_context_helper::escape($sectionheading);
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);
566 * Attempt a quiz.
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.
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.
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.
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 /^user "([^"]*)" has attempted "([^"]*)" with responses:$/
597 public function user_has_attempted_with_responses($username, $quizname, TableNode $attemptinfo) {
598 global $DB, $USER;
600 /** @var mod_quiz_generator $quizgenerator */
601 $quizgenerator = behat_util::get_data_generator()->get_plugin_generator('mod_quiz');
603 $quizid = $DB->get_field('quiz', 'id', ['name' => $quizname], MUST_EXIST);
604 $user = $DB->get_record('user', ['username' => $username], '*', MUST_EXIST);
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());
614 if (!array_key_exists('response', $slotinfo)) {
615 throw new ExpectationException('When simulating a quiz attempt, ' .
616 'the response column is required.', $this->getSession());
618 $responses[$slotinfo['slot']] = $slotinfo['response'];
620 if (!empty($slotinfo['actualquestion'])) {
621 $forcedrandomquestions[$slotinfo['slot']] = $DB->get_field('question', 'id',
622 ['name' => $slotinfo['actualquestion']], MUST_EXIST);
625 if (!empty($slotinfo['variant'])) {
626 $forcedvariants[$slotinfo['slot']] = (int) $slotinfo['variant'];
630 $saveduser = $USER; // TODO there is probably a better way to do this. If not, there should be.
631 $USER = $user;
633 $attempt = $quizgenerator->create_attempt($quizid, $user->id,
634 $forcedrandomquestions, $forcedvariants);
636 $quizgenerator->submit_responses($attempt->id, $responses, true);
638 $USER = $saveduser;