MDL-31226: quiz: Fix message for attempts built on previous.
[moodle.git] / question / engine / tests / helpers.php
CommitLineData
603bd001
PS
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 * This file contains helper classes for testing the question engine.
19 *
20 * @package moodlecore
21 * @subpackage questionengine
22 * @copyright 2009 The Open University
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 */
25
26
27defined('MOODLE_INTERNAL') || die();
28
29global $CFG;
30require_once(dirname(__FILE__) . '/../lib.php');
31
32
33/**
34 * Makes some protected methods of question_attempt public to facilitate testing.
35 *
36 * @copyright 2009 The Open University
37 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
38 */
39class testable_question_attempt extends question_attempt {
40 public function add_step(question_attempt_step $step) {
41 parent::add_step($step);
42 }
43 public function set_min_fraction($fraction) {
44 $this->minfraction = $fraction;
45 }
46 public function set_behaviour(question_behaviour $behaviour) {
47 $this->behaviour = $behaviour;
48 }
49}
50
51
eca230b5
TH
52/**
53 * Test subclass to allow access to some protected data so that the correct
54 * behaviour can be verified.
55 *
56 * @copyright 2012 The Open University
57 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
58 */
59class testable_question_engine_unit_of_work extends question_engine_unit_of_work {
60 public function get_modified() {
61 return $this->modified;
62 }
63
64 public function get_attempts_added() {
65 return $this->attemptsadded;
66 }
67
68 public function get_attempts_modified() {
69 return $this->attemptsmodified;
70 }
71
72 public function get_steps_added() {
73 return $this->stepsadded;
74 }
75
76 public function get_steps_modified() {
77 return $this->stepsmodified;
78 }
79
80 public function get_steps_deleted() {
81 return $this->stepsdeleted;
82 }
83}
84
85
603bd001
PS
86/**
87 * Base class for question type test helpers.
88 *
89 * @copyright 2011 The Open University
90 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
91 */
92abstract class question_test_helper {
93 /**
94 * @return array of example question names that can be passed as the $which
95 * argument of {@link test_question_maker::make_question} when $qtype is
96 * this question type.
97 */
98 abstract public function get_test_questions();
99}
100
101
102/**
103 * This class creates questions of various types, which can then be used when
104 * testing.
105 *
106 * @copyright 2009 The Open University
107 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
108 */
109class test_question_maker {
110 const STANDARD_OVERALL_CORRECT_FEEDBACK = 'Well done!';
111 const STANDARD_OVERALL_PARTIALLYCORRECT_FEEDBACK =
112 'Parts, but only parts, of your response are correct.';
113 const STANDARD_OVERALL_INCORRECT_FEEDBACK = 'That is not right at all.';
114
115 /** @var array qtype => qtype test helper class. */
116 protected static $testhelpers = array();
117
118 /**
119 * Just make a question_attempt at a question. Useful for unit tests that
120 * need to pass a $qa to methods that call format_text. Probably not safe
121 * to use for anything beyond that.
122 * @param question_definition $question a question.
123 * @param number $maxmark the max mark to set.
124 * @return question_attempt the question attempt.
125 */
126 public static function get_a_qa($question, $maxmark = 3) {
127 return new question_attempt($question, 13, null, $maxmark);
128 }
129
130 /**
131 * Initialise the common fields of a question of any type.
132 */
133 public static function initialise_a_question($q) {
134 global $USER;
135
136 $q->id = 0;
137 $q->category = 0;
138 $q->parent = 0;
139 $q->questiontextformat = FORMAT_HTML;
140 $q->generalfeedbackformat = FORMAT_HTML;
141 $q->defaultmark = 1;
142 $q->penalty = 0.3333333;
143 $q->length = 1;
144 $q->stamp = make_unique_id_code();
145 $q->version = make_unique_id_code();
146 $q->hidden = 0;
147 $q->timecreated = time();
148 $q->timemodified = time();
149 $q->createdby = $USER->id;
150 $q->modifiedby = $USER->id;
151 }
152
153 public static function initialise_question_data($qdata) {
154 global $USER;
155
156 $qdata->id = 0;
157 $qdata->category = 0;
158 $qdata->contextid = 0;
159 $qdata->parent = 0;
160 $qdata->questiontextformat = FORMAT_HTML;
161 $qdata->generalfeedbackformat = FORMAT_HTML;
162 $qdata->defaultmark = 1;
163 $qdata->penalty = 0.3333333;
164 $qdata->length = 1;
165 $qdata->stamp = make_unique_id_code();
166 $qdata->version = make_unique_id_code();
167 $qdata->hidden = 0;
168 $qdata->timecreated = time();
169 $qdata->timemodified = time();
170 $qdata->createdby = $USER->id;
171 $qdata->modifiedby = $USER->id;
172 $qdata->hints = array();
173 }
174
175 public static function initialise_question_form_data($qdata) {
176 $formdata = new stdClass();
177 $formdata->id = 0;
178 $formdata->category = '0,0';
179 $formdata->usecurrentcat = 1;
180 $formdata->categorymoveto = '0,0';
181 $formdata->tags = array();
182 $formdata->penalty = 0.3333333;
183 $formdata->questiontextformat = FORMAT_HTML;
184 $formdata->generalfeedbackformat = FORMAT_HTML;
185 }
186
187 /**
188 * Get the test helper class for a particular question type.
189 * @param $qtype the question type name, e.g. 'multichoice'.
190 * @return question_test_helper the test helper class.
191 */
192 public static function get_test_helper($qtype) {
193 global $CFG;
194
195 if (array_key_exists($qtype, self::$testhelpers)) {
196 return self::$testhelpers[$qtype];
197 }
198
199 $file = get_plugin_directory('qtype', $qtype) . '/tests/helper.php';
200 if (!is_readable($file)) {
201 throw new coding_exception('Question type ' . $qtype .
202 ' does not have test helper code.');
203 }
204 include_once($file);
205
206 $class = 'qtype_' . $qtype . '_test_helper';
207 if (!class_exists($class)) {
208 throw new coding_exception('Class ' . $class . ' is not defined in ' . $file);
209 }
210
211 self::$testhelpers[$qtype] = new $class();
212 return self::$testhelpers[$qtype];
213 }
214
215 /**
216 * Call a method on a qtype_{$qtype}_test_helper class and return the result.
217 *
218 * @param string $methodtemplate e.g. 'make_{qtype}_question_{which}';
219 * @param string $qtype the question type to get a test question for.
220 * @param string $which one of the names returned by the get_test_questions
221 * method of the relevant qtype_{$qtype}_test_helper class.
222 * @param unknown_type $which
223 */
224 protected static function call_question_helper_method($methodtemplate, $qtype, $which = null) {
225 $helper = self::get_test_helper($qtype);
226
227 $available = $helper->get_test_questions();
228
229 if (is_null($which)) {
230 $which = reset($available);
231 } else if (!in_array($which, $available)) {
232 throw new coding_exception('Example question ' . $which . ' of type ' .
233 $qtype . ' does not exist.');
234 }
235
236 $method = str_replace(array('{qtype}', '{which}'),
237 array($qtype, $which), $methodtemplate);
238
239 if (!method_exists($helper, $method)) {
240 throw new coding_exception('Method ' . $method . ' does not exist on the' .
241 $qtype . ' question type test helper class.');
242 }
243
244 return $helper->$method();
245 }
246
247 /**
248 * Question types can provide a number of test question defintions.
249 * They do this by creating a qtype_{$qtype}_test_helper class that extends
250 * question_test_helper. The get_test_questions method returns the list of
251 * test questions available for this question type.
252 *
253 * @param string $qtype the question type to get a test question for.
254 * @param string $which one of the names returned by the get_test_questions
255 * method of the relevant qtype_{$qtype}_test_helper class.
256 * @return question_definition the requested question object.
257 */
258 public static function make_question($qtype, $which = null) {
259 return self::call_question_helper_method('make_{qtype}_question_{which}',
260 $qtype, $which);
261 }
262
263 /**
264 * Like {@link make_question()} but returns the datastructure from
265 * get_question_options instead of the question_definition object.
266 *
267 * @param string $qtype the question type to get a test question for.
268 * @param string $which one of the names returned by the get_test_questions
269 * method of the relevant qtype_{$qtype}_test_helper class.
270 * @return stdClass the requested question object.
271 */
272 public static function get_question_data($qtype, $which = null) {
273 return self::call_question_helper_method('get_{qtype}_question_data_{which}',
274 $qtype, $which);
275 }
276
277 /**
278 * Like {@link make_question()} but returns the data what would be saved from
279 * the question editing form instead of the question_definition object.
280 *
281 * @param string $qtype the question type to get a test question for.
282 * @param string $which one of the names returned by the get_test_questions
283 * method of the relevant qtype_{$qtype}_test_helper class.
284 * @return stdClass the requested question object.
285 */
286 public static function get_question_form_data($qtype, $which = null) {
287 return self::call_question_helper_method('get_{qtype}_question_form_data_{which}',
288 $qtype, $which);
289 }
290
291 /**
292 * Makes a multichoice question with choices 'A', 'B' and 'C' shuffled. 'A'
293 * is correct, defaultmark 1.
294 * @return qtype_multichoice_single_question
295 */
296 public static function make_a_multichoice_single_question() {
297 question_bank::load_question_definition_classes('multichoice');
298 $mc = new qtype_multichoice_single_question();
299 self::initialise_a_question($mc);
300 $mc->name = 'Multi-choice question, single response';
301 $mc->questiontext = 'The answer is A.';
302 $mc->generalfeedback = 'You should have selected A.';
303 $mc->qtype = question_bank::get_qtype('multichoice');
304
305 $mc->shuffleanswers = 1;
306 $mc->answernumbering = 'abc';
307
308 $mc->answers = array(
309 13 => new question_answer(13, 'A', 1, 'A is right', FORMAT_HTML),
310 14 => new question_answer(14, 'B', -0.3333333, 'B is wrong', FORMAT_HTML),
311 15 => new question_answer(15, 'C', -0.3333333, 'C is wrong', FORMAT_HTML),
312 );
313
314 return $mc;
315 }
316
317 /**
318 * Makes a multichoice question with choices 'A', 'B', 'C' and 'D' shuffled.
319 * 'A' and 'C' is correct, defaultmark 1.
320 * @return qtype_multichoice_multi_question
321 */
322 public static function make_a_multichoice_multi_question() {
323 question_bank::load_question_definition_classes('multichoice');
324 $mc = new qtype_multichoice_multi_question();
325 self::initialise_a_question($mc);
326 $mc->name = 'Multi-choice question, multiple response';
327 $mc->questiontext = 'The answer is A and C.';
328 $mc->generalfeedback = 'You should have selected A and C.';
329 $mc->qtype = question_bank::get_qtype('multichoice');
330
331 $mc->shuffleanswers = 1;
332 $mc->answernumbering = 'abc';
333
334 self::set_standard_combined_feedback_fields($mc);
335
336 $mc->answers = array(
337 13 => new question_answer(13, 'A', 0.5, 'A is part of the right answer', FORMAT_HTML),
338 14 => new question_answer(14, 'B', -1, 'B is wrong', FORMAT_HTML),
339 15 => new question_answer(15, 'C', 0.5, 'C is part of the right answer', FORMAT_HTML),
340 16 => new question_answer(16, 'D', -1, 'D is wrong', FORMAT_HTML),
341 );
342
343 return $mc;
344 }
345
346 /**
347 * Makes a matching question to classify 'Dog', 'Frog', 'Toad' and 'Cat' as
348 * 'Mammal', 'Amphibian' or 'Insect'.
349 * defaultmark 1. Stems are shuffled by default.
350 * @return qtype_match_question
351 */
352 public static function make_a_matching_question() {
353 question_bank::load_question_definition_classes('match');
354 $match = new qtype_match_question();
355 self::initialise_a_question($match);
356 $match->name = 'Matching question';
357 $match->questiontext = 'Classify the animals.';
358 $match->generalfeedback = 'Frogs and toads are amphibians, the others are mammals.';
359 $match->qtype = question_bank::get_qtype('match');
360
361 $match->shufflestems = 1;
362
363 self::set_standard_combined_feedback_fields($match);
364
365 // Using unset to get 1-based arrays.
366 $match->stems = array('', 'Dog', 'Frog', 'Toad', 'Cat');
367 $match->stemformat = array('', FORMAT_HTML, FORMAT_HTML, FORMAT_HTML, FORMAT_HTML);
368 $match->choices = array('', 'Mammal', 'Amphibian', 'Insect');
369 $match->right = array('', 1, 2, 2, 1);
370 unset($match->stems[0]);
371 unset($match->stemformat[0]);
372 unset($match->choices[0]);
373 unset($match->right[0]);
374
375 return $match;
376 }
377
378 /**
379 * Makes a truefalse question with correct ansewer true, defaultmark 1.
380 * @return qtype_essay_question
381 */
382 public static function make_an_essay_question() {
383 question_bank::load_question_definition_classes('essay');
384 $essay = new qtype_essay_question();
385 self::initialise_a_question($essay);
386 $essay->name = 'Essay question';
387 $essay->questiontext = 'Write an essay.';
388 $essay->generalfeedback = 'I hope you wrote an interesting essay.';
389 $essay->penalty = 0;
390 $essay->qtype = question_bank::get_qtype('essay');
391
392 $essay->responseformat = 'editor';
393 $essay->responsefieldlines = 15;
394 $essay->attachments = 0;
395 $essay->graderinfo = '';
396 $essay->graderinfoformat = FORMAT_MOODLE;
397
398 return $essay;
399 }
400
401 /**
402 * Add some standard overall feedback to a question. You need to use these
403 * specific feedback strings for the corresponding contains_..._feedback
404 * methods in {@link qbehaviour_walkthrough_test_base} to works.
405 * @param question_definition $q the question to add the feedback to.
406 */
407 public static function set_standard_combined_feedback_fields($q) {
408 $q->correctfeedback = self::STANDARD_OVERALL_CORRECT_FEEDBACK;
409 $q->correctfeedbackformat = FORMAT_HTML;
410 $q->partiallycorrectfeedback = self::STANDARD_OVERALL_PARTIALLYCORRECT_FEEDBACK;
411 $q->partiallycorrectfeedbackformat = FORMAT_HTML;
412 $q->shownumcorrect = true;
413 $q->incorrectfeedback = self::STANDARD_OVERALL_INCORRECT_FEEDBACK;
414 $q->incorrectfeedbackformat = FORMAT_HTML;
415 }
416}
417
418
419/**
420 * Helper for tests that need to simulate records loaded from the database.
421 *
422 * @copyright 2009 The Open University
423 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
424 */
425abstract class testing_db_record_builder {
426 public static function build_db_records(array $table) {
427 $columns = array_shift($table);
428 $records = array();
429 foreach ($table as $row) {
430 if (count($row) != count($columns)) {
431 throw new coding_exception("Row contains the wrong number of fields.");
432 }
433 $rec = new stdClass();
434 foreach ($columns as $i => $name) {
435 $rec->$name = $row[$i];
436 }
437 $records[] = $rec;
438 }
439 return $records;
440 }
441}
442
443
444/**
445 * Helper base class for tests that need to simulate records loaded from the
446 * database.
447 *
448 * @copyright 2009 The Open University
449 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
450 */
a4d53e4b 451abstract class data_loading_method_test_base extends advanced_testcase {
603bd001
PS
452 public function build_db_records(array $table) {
453 return testing_db_record_builder::build_db_records($table);
454 }
603bd001
PS
455}
456
457
a4d53e4b 458abstract class question_testcase extends advanced_testcase {
603bd001 459
5ef18d82 460 public function assert($expectation, $compare, $notused = '') {
603bd001
PS
461
462 if (get_class($expectation) === 'question_pattern_expectation') {
5ef18d82
TH
463 $this->assertRegExp($expectation->pattern, $compare,
464 'Expected regex ' . $expectation->pattern . ' not found in ' . $compare);
603bd001
PS
465 return;
466
467 } else if (get_class($expectation) === 'question_no_pattern_expectation') {
5ef18d82
TH
468 $this->assertNotRegExp($expectation->pattern, $compare,
469 'Unexpected regex ' . $expectation->pattern . ' found in ' . $compare);
603bd001
PS
470 return;
471
472 } else if (get_class($expectation) === 'question_contains_tag_with_attributes') {
5ef18d82
TH
473 $this->assertTag(array('tag'=>$expectation->tag, 'attributes'=>$expectation->expectedvalues), $compare,
474 'Looking for a ' . $expectation->tag . ' with attributes ' . html_writer::attributes($expectation->expectedvalues) . ' in ' . $compare);
603bd001
PS
475 foreach ($expectation->forbiddenvalues as $k=>$v) {
476 $attr = $expectation->expectedvalues;
477 $attr[$k] = $v;
5ef18d82
TH
478 $this->assertNotTag(array('tag'=>$expectation->tag, 'attributes'=>$attr), $compare,
479 $expectation->tag . ' had a ' . $k . ' attribute that should not be there in ' . $compare);
603bd001
PS
480 }
481 return;
482
483 } else if (get_class($expectation) === 'question_contains_tag_with_attribute') {
484 $attr = array($expectation->attribute=>$expectation->value);
5ef18d82
TH
485 $this->assertTag(array('tag'=>$expectation->tag, 'attributes'=>$attr), $compare,
486 'Looking for a ' . $expectation->tag . ' with attribute ' . html_writer::attributes($attr) . ' in ' . $compare);
603bd001
PS
487 return;
488
489 } else if (get_class($expectation) === 'question_does_not_contain_tag_with_attributes') {
5ef18d82
TH
490 $this->assertNotTag(array('tag'=>$expectation->tag, 'attributes'=>$expectation->attributes), $compare,
491 'Unexpected ' . $expectation->tag . ' with attributes ' . html_writer::attributes($expectation->attributes) . ' found in ' . $compare);
603bd001
PS
492 return;
493
494 } else if (get_class($expectation) === 'question_contains_select_expectation') {
495 $tag = array('tag'=>'select', 'attributes'=>array('name'=>$expectation->name),
496 'children'=>array('count'=>count($expectation->choices)));
6cdef715 497 if ($expectation->enabled === false) {
603bd001 498 $tag['attributes']['disabled'] = 'disabled';
6cdef715
TH
499 } else if ($expectation->enabled === true) {
500 // TODO
603bd001
PS
501 }
502 foreach(array_keys($expectation->choices) as $value) {
503 if ($expectation->selected === $value) {
504 $tag['child'] = array('tag'=>'option', 'attributes'=>array('value'=>$value, 'selected'=>'selected'));
505 } else {
506 $tag['child'] = array('tag'=>'option', 'attributes'=>array('value'=>$value));
507 }
603bd001 508 }
6cdef715
TH
509
510 $this->assertTag($tag, $compare, 'expected select not found in ' . $compare);
603bd001
PS
511 return;
512
513 } else if (get_class($expectation) === 'question_check_specified_fields_expectation') {
514 $expect = (array)$expectation->expect;
515 $compare = (array)$compare;
516 foreach ($expect as $k=>$v) {
517 if (!array_key_exists($k, $compare)) {
ba6425ab 518 $this->fail("Property $k does not exist");
603bd001
PS
519 }
520 if ($v != $compare[$k]) {
ba6425ab 521 $this->fail("Property $k is different");
603bd001
PS
522 }
523 }
524 $this->assertTrue(true);
525 return;
526
527 } else if (get_class($expectation) === 'question_contains_tag_with_contents') {
5ef18d82
TH
528 $this->assertTag(array('tag'=>$expectation->tag, 'content'=>$expectation->content), $compare,
529 'Looking for a ' . $expectation->tag . ' with content ' . $expectation->content . ' in ' . $compare);
603bd001
PS
530 return;
531 }
532
533 throw new coding_exception('Unknown expectiontion:'.get_class($expectation));
534 }
535}
536
537
538class question_contains_tag_with_contents {
539 public $tag;
540 public $content;
541 public $message;
542
543 public function __construct($tag, $content, $message = '') {
544 $this->tag = $tag;
545 $this->content = $content;
546 $this->message = $message;
547 }
548
549}
550
551class question_check_specified_fields_expectation {
552 public $expect;
553 public $message;
554
555 function __construct($expected, $message = '') {
556 $this->expect = $expected;
557 $this->message = $message;
558 }
559}
560
561
562class question_contains_select_expectation {
563 public $name;
564 public $choices;
565 public $selected;
566 public $enabled;
567 public $message;
568
569 public function __construct($name, $choices, $selected = null, $enabled = null, $message = '') {
570 $this->name = $name;
571 $this->choices = $choices;
572 $this->selected = $selected;
573 $this->enabled = $enabled;
574 $this->message = $message;
575 }
576}
577
578
579class question_does_not_contain_tag_with_attributes {
580 public $tag;
581 public $attributes;
582 public $message;
583
584 public function __construct($tag, $attributes, $message = '') {
585 $this->tag = $tag;
586 $this->attributes = $attributes;
587 $this->message = $message;
588 }
589}
590
591
592class question_contains_tag_with_attribute {
593 public $tag;
594 public $attribute;
595 public $value;
596 public $message;
597
598 public function __construct($tag, $attribute, $value, $message = '') {
599 $this->tag = $tag;
600 $this->attribute = $attribute;
601 $this->value = $value;
602 $this->message = $message;
603 }
604}
605
606
607class question_contains_tag_with_attributes {
608 public $tag;
609 public $expectedvalues = array();
610 public $forbiddenvalues = array();
611 public $message;
612
613 public function __construct($tag, $expectedvalues, $forbiddenvalues=array(), $message = '') {
614 $this->tag = $tag;
615 $this->expectedvalues = $expectedvalues;
616 $this->forbiddenvalues = $forbiddenvalues;
617 $this->message = $message;
618 }
619}
620
621
622class question_pattern_expectation {
623 public $pattern;
624 public $message;
625
626 public function __construct($pattern, $message = '') {
627 $this->pattern = $pattern;
628 $this->message = $message;
629 }
630}
631
632
633class question_no_pattern_expectation {
634 public $pattern;
635 public $message;
636
637 public function __construct($pattern, $message = '') {
638 $this->pattern = $pattern;
639 $this->message = $message;
640 }
641}
642
643
644/**
645 * Helper base class for tests that walk a question through a sequents of
646 * interactions under the control of a particular behaviour.
647 *
648 * @copyright 2009 The Open University
649 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
650 */
a4d53e4b 651abstract class qbehaviour_walkthrough_test_base extends question_testcase {
603bd001
PS
652 /** @var question_display_options */
653 protected $displayoptions;
654 /** @var question_usage_by_activity */
655 protected $quba;
c0d12fc1
TH
656 /** @var integer */
657
603bd001 658 protected $slot;
c0d12fc1
TH
659 /**
660 * @var string after {@link render()} has been called, this contains the
661 * display of the question in its current state.
662 */
663 protected $currentoutput = '';
603bd001
PS
664
665 protected function setUp() {
666 parent::setUp();
667 $this->resetAfterTest(true);
668
669 $this->displayoptions = new question_display_options();
670 $this->quba = question_engine::make_questions_usage_by_activity('unit_test',
21c08c63 671 context_system::instance());
603bd001
PS
672 }
673
674 protected function tearDown() {
675 $this->displayoptions = null;
676 $this->quba = null;
677 parent::tearDown();
678 }
679
680 protected function start_attempt_at_question($question, $preferredbehaviour,
681 $maxmark = null, $variant = 1) {
682 $this->quba->set_preferred_behaviour($preferredbehaviour);
683 $this->slot = $this->quba->add_question($question, $maxmark);
684 $this->quba->start_question($this->slot, $variant);
685 }
eca230b5 686
d122fe32
TH
687 /**
688 * Convert an array of data destined for one question to the equivalent POST data.
689 * @param array $data the data for the quetsion.
690 * @return array the complete post data.
691 */
692 protected function response_data_to_post($data) {
eca230b5
TH
693 $prefix = $this->quba->get_field_prefix($this->slot);
694 $fulldata = array(
695 'slots' => $this->slot,
c7fbfe46 696 $prefix . ':sequencecheck' => $this->get_question_attempt()->get_sequence_check_count(),
eca230b5
TH
697 );
698 foreach ($data as $name => $value) {
699 $fulldata[$prefix . $name] = $value;
700 }
d122fe32
TH
701 return $fulldata;
702 }
703
704 protected function process_submission($data) {
705 // Backwards compatibility.
706 reset($data);
707 if (count($data) == 1 && key($data) === '-finish') {
708 $this->finish();
709 }
710
711 $this->quba->process_all_actions(time(), $this->response_data_to_post($data));
eca230b5
TH
712 }
713
714 protected function process_autosave($data) {
d122fe32 715 $this->quba->process_all_autosaves(null, $this->response_data_to_post($data));
eca230b5
TH
716 }
717
718 protected function finish() {
719 $this->quba->finish_all_questions();
603bd001
PS
720 }
721
53b8e256
TH
722 protected function manual_grade($comment, $mark, $commentformat = null) {
723 $this->quba->manual_grade($this->slot, $comment, $mark, $commentformat);
603bd001
PS
724 }
725
eca230b5
TH
726 protected function save_quba(moodle_database $db = null) {
727 question_engine::save_questions_usage_by_activity($this->quba, $db);
728 }
729
730 protected function load_quba(moodle_database $db = null) {
731 $this->quba = question_engine::load_questions_usage_by_activity($this->quba->get_id(), $db);
732 }
733
734 protected function delete_quba() {
735 question_engine::delete_questions_usage_by_activity($this->quba->get_id());
736 $this->quba = null;
737 }
738
603bd001 739 protected function check_current_state($state) {
5ef18d82
TH
740 $this->assertEquals($state, $this->quba->get_question_state($this->slot),
741 'Questions is in the wrong state.');
603bd001
PS
742 }
743
744 protected function check_current_mark($mark) {
745 if (is_null($mark)) {
746 $this->assertNull($this->quba->get_question_mark($this->slot));
747 } else {
748 if ($mark == 0) {
749 // PHP will think a null mark and a mark of 0 are equal,
750 // so explicity check not null in this case.
751 $this->assertNotNull($this->quba->get_question_mark($this->slot));
752 }
753 $this->assertEquals($mark, $this->quba->get_question_mark($this->slot),
5ef18d82 754 'Expected mark and actual mark differ.', 0.000001);
603bd001
PS
755 }
756 }
757
c0d12fc1
TH
758 /**
759 * Generate the HTML rendering of the question in its current state in
760 * $this->currentoutput so that it can be verified.
761 */
762 protected function render() {
763 $this->currentoutput = $this->quba->render_question($this->slot, $this->displayoptions);
764 }
765
eca230b5
TH
766 protected function check_output_contains_text_input($name, $value = null, $enabled = true) {
767 $attributes = array(
768 'type' => 'text',
769 'name' => $this->quba->get_field_prefix($this->slot) . $name,
770 );
771 if (!is_null($value)) {
772 $attributes['value'] = $value;
773 }
774 if (!$enabled) {
775 $attributes['readonly'] = 'readonly';
776 }
777 $matcher = $this->get_tag_matcher('input', $attributes);
778 $this->assertTag($matcher, $this->currentoutput,
779 'Looking for an input with attributes ' . html_writer::attributes($attributes) . ' in ' . $this->currentoutput);
780
781 if ($enabled) {
782 $matcher['attributes']['readonly'] = 'readonly';
783 $this->assertNotTag($matcher, $this->currentoutput,
784 'input with attributes ' . html_writer::attributes($attributes) .
785 ' should not be read-only in ' . $this->currentoutput);
786 }
787 }
788
d56ab3b9
JMV
789 protected function check_output_contains_text_input_with_class($name, $class = null) {
790 $attributes = array(
791 'type' => 'text',
792 'name' => $this->quba->get_field_prefix($this->slot) . $name,
793 );
794 if (!is_null($class)) {
795 $attributes['class'] = 'regexp:/\b' . $class . '\b/';
796 }
797
798 $matcher = $this->get_tag_matcher('input', $attributes);
799 $this->assertTag($matcher, $this->currentoutput,
800 'Looking for an input with attributes ' . html_writer::attributes($attributes) . ' in ' . $this->currentoutput);
801 }
802
803 protected function check_output_does_not_contain_text_input_with_class($name, $class = null) {
804 $attributes = array(
805 'type' => 'text',
806 'name' => $this->quba->get_field_prefix($this->slot) . $name,
807 );
808 if (!is_null($class)) {
809 $attributes['class'] = 'regexp:/\b' . $class . '\b/';
810 }
811
812 $matcher = $this->get_tag_matcher('input', $attributes);
813 $this->assertNotTag($matcher, $this->currentoutput,
814 'Unexpected input with attributes ' . html_writer::attributes($attributes) . ' found in ' . $this->currentoutput);
815 }
816
c7fbfe46
TH
817 protected function check_output_contains_hidden_input($name, $value) {
818 $attributes = array(
819 'type' => 'hidden',
820 'name' => $this->quba->get_field_prefix($this->slot) . $name,
821 'value' => $value,
822 );
823 $this->assertTag($this->get_tag_matcher('input', $attributes), $this->currentoutput,
824 'Looking for a hidden input with attributes ' . html_writer::attributes($attributes) . ' in ' . $this->currentoutput);
825 }
826
f8e28244
RK
827 protected function check_output_contains_lang_string($identifier, $component = '', $a = null) {
828 $this->render();
829 $string = get_string($identifier, $component, $a);
830 $this->assertContains($string, $this->currentoutput,
831 'Expected string ' . $string . ' not found in ' . $this->currentoutput);
832 }
833
eca230b5
TH
834 protected function get_tag_matcher($tag, $attributes) {
835 return array(
836 'tag' => $tag,
837 'attributes' => $attributes,
838 );
839 }
840
603bd001
PS
841 /**
842 * @param $condition one or more Expectations. (users varargs).
843 */
844 protected function check_current_output() {
845 $html = $this->quba->render_question($this->slot, $this->displayoptions);
846 foreach (func_get_args() as $condition) {
847 $this->assert($condition, $html);
848 }
849 }
850
851 protected function get_question_attempt() {
852 return $this->quba->get_question_attempt($this->slot);
853 }
854
855 protected function get_step_count() {
856 return $this->get_question_attempt()->get_num_steps();
857 }
858
859 protected function check_step_count($expectednumsteps) {
860 $this->assertEquals($expectednumsteps, $this->get_step_count());
861 }
862
863 protected function get_step($stepnum) {
864 return $this->get_question_attempt()->get_step($stepnum);
865 }
866
867 protected function get_contains_question_text_expectation($question) {
03cefcc9 868 return new question_pattern_expectation('/' . preg_quote($question->questiontext, '/') . '/');
603bd001
PS
869 }
870
871 protected function get_contains_general_feedback_expectation($question) {
03cefcc9 872 return new question_pattern_expectation('/' . preg_quote($question->generalfeedback, '/') . '/');
603bd001
PS
873 }
874
875 protected function get_does_not_contain_correctness_expectation() {
876 return new question_no_pattern_expectation('/class=\"correctness/');
877 }
878
879 protected function get_contains_correct_expectation() {
03cefcc9 880 return new question_pattern_expectation('/' . preg_quote(get_string('correct', 'question'), '/') . '/');
603bd001
PS
881 }
882
883 protected function get_contains_partcorrect_expectation() {
884 return new question_pattern_expectation('/' .
03cefcc9 885 preg_quote(get_string('partiallycorrect', 'question'), '/') . '/');
603bd001
PS
886 }
887
888 protected function get_contains_incorrect_expectation() {
03cefcc9 889 return new question_pattern_expectation('/' . preg_quote(get_string('incorrect', 'question'), '/') . '/');
603bd001
PS
890 }
891
892 protected function get_contains_standard_correct_combined_feedback_expectation() {
893 return new question_pattern_expectation('/' .
03cefcc9 894 preg_quote(test_question_maker::STANDARD_OVERALL_CORRECT_FEEDBACK, '/') . '/');
603bd001
PS
895 }
896
897 protected function get_contains_standard_partiallycorrect_combined_feedback_expectation() {
898 return new question_pattern_expectation('/' .
03cefcc9 899 preg_quote(test_question_maker::STANDARD_OVERALL_PARTIALLYCORRECT_FEEDBACK, '/') . '/');
603bd001
PS
900 }
901
902 protected function get_contains_standard_incorrect_combined_feedback_expectation() {
903 return new question_pattern_expectation('/' .
03cefcc9 904 preg_quote(test_question_maker::STANDARD_OVERALL_INCORRECT_FEEDBACK, '/') . '/');
603bd001
PS
905 }
906
907 protected function get_does_not_contain_feedback_expectation() {
908 return new question_no_pattern_expectation('/class="feedback"/');
909 }
910
911 protected function get_does_not_contain_num_parts_correct() {
912 return new question_no_pattern_expectation('/class="numpartscorrect"/');
913 }
914
915 protected function get_contains_num_parts_correct($num) {
916 $a = new stdClass();
917 $a->num = $num;
918 return new question_pattern_expectation('/<div class="numpartscorrect">' .
03cefcc9 919 preg_quote(get_string('yougotnright', 'question', $a), '/') . '/');
603bd001
PS
920 }
921
922 protected function get_does_not_contain_specific_feedback_expectation() {
923 return new question_no_pattern_expectation('/class="specificfeedback"/');
924 }
925
926 protected function get_contains_validation_error_expectation() {
927 return new question_contains_tag_with_attribute('div', 'class', 'validationerror');
928 }
929
930 protected function get_does_not_contain_validation_error_expectation() {
931 return new question_no_pattern_expectation('/class="validationerror"/');
932 }
933
934 protected function get_contains_mark_summary($mark) {
935 $a = new stdClass();
936 $a->mark = format_float($mark, $this->displayoptions->markdp);
937 $a->max = format_float($this->quba->get_question_max_mark($this->slot),
938 $this->displayoptions->markdp);
939 return new question_pattern_expectation('/' .
03cefcc9 940 preg_quote(get_string('markoutofmax', 'question', $a), '/') . '/');
603bd001
PS
941 }
942
943 protected function get_contains_marked_out_of_summary() {
944 $max = format_float($this->quba->get_question_max_mark($this->slot),
945 $this->displayoptions->markdp);
946 return new question_pattern_expectation('/' .
03cefcc9 947 preg_quote(get_string('markedoutofmax', 'question', $max), '/') . '/');
603bd001
PS
948 }
949
950 protected function get_does_not_contain_mark_summary() {
951 return new question_no_pattern_expectation('/<div class="grade">/');
952 }
953
954 protected function get_contains_checkbox_expectation($baseattr, $enabled, $checked) {
955 $expectedattributes = $baseattr;
956 $forbiddenattributes = array();
957 $expectedattributes['type'] = 'checkbox';
958 if ($enabled === true) {
959 $forbiddenattributes['disabled'] = 'disabled';
960 } else if ($enabled === false) {
961 $expectedattributes['disabled'] = 'disabled';
962 }
963 if ($checked === true) {
964 $expectedattributes['checked'] = 'checked';
965 } else if ($checked === false) {
966 $forbiddenattributes['checked'] = 'checked';
967 }
968 return new question_contains_tag_with_attributes('input', $expectedattributes, $forbiddenattributes);
969 }
970
971 protected function get_contains_mc_checkbox_expectation($index, $enabled = null,
972 $checked = null) {
973 return $this->get_contains_checkbox_expectation(array(
974 'name' => $this->quba->get_field_prefix($this->slot) . $index,
975 'value' => 1,
976 ), $enabled, $checked);
977 }
978
979 protected function get_contains_radio_expectation($baseattr, $enabled, $checked) {
980 $expectedattributes = $baseattr;
981 $forbiddenattributes = array();
982 $expectedattributes['type'] = 'radio';
983 if ($enabled === true) {
984 $forbiddenattributes['disabled'] = 'disabled';
985 } else if ($enabled === false) {
986 $expectedattributes['disabled'] = 'disabled';
987 }
988 if ($checked === true) {
989 $expectedattributes['checked'] = 'checked';
990 } else if ($checked === false) {
991 $forbiddenattributes['checked'] = 'checked';
992 }
993 return new question_contains_tag_with_attributes('input', $expectedattributes, $forbiddenattributes);
994 }
995
996 protected function get_contains_mc_radio_expectation($index, $enabled = null, $checked = null) {
997 return $this->get_contains_radio_expectation(array(
998 'name' => $this->quba->get_field_prefix($this->slot) . 'answer',
999 'value' => $index,
1000 ), $enabled, $checked);
1001 }
1002
1003 protected function get_contains_hidden_expectation($name, $value = null) {
1004 $expectedattributes = array('type' => 'hidden', 'name' => s($name));
1005 if (!is_null($value)) {
1006 $expectedattributes['value'] = s($value);
1007 }
1008 return new question_contains_tag_with_attributes('input', $expectedattributes);
1009 }
1010
1011 protected function get_does_not_contain_hidden_expectation($name, $value = null) {
1012 $expectedattributes = array('type' => 'hidden', 'name' => s($name));
1013 if (!is_null($value)) {
1014 $expectedattributes['value'] = s($value);
1015 }
1016 return new question_does_not_contain_tag_with_attributes('input', $expectedattributes);
1017 }
1018
1019 protected function get_contains_tf_true_radio_expectation($enabled = null, $checked = null) {
1020 return $this->get_contains_radio_expectation(array(
1021 'name' => $this->quba->get_field_prefix($this->slot) . 'answer',
1022 'value' => 1,
1023 ), $enabled, $checked);
1024 }
1025
1026 protected function get_contains_tf_false_radio_expectation($enabled = null, $checked = null) {
1027 return $this->get_contains_radio_expectation(array(
1028 'name' => $this->quba->get_field_prefix($this->slot) . 'answer',
1029 'value' => 0,
1030 ), $enabled, $checked);
1031 }
1032
1033 protected function get_contains_cbm_radio_expectation($certainty, $enabled = null,
1034 $checked = null) {
1035 return $this->get_contains_radio_expectation(array(
1036 'name' => $this->quba->get_field_prefix($this->slot) . '-certainty',
1037 'value' => $certainty,
1038 ), $enabled, $checked);
1039 }
1040
1041 protected function get_contains_button_expectation($name, $value = null, $enabled = null) {
1042 $expectedattributes = array(
1043 'type' => 'submit',
1044 'name' => $name,
1045 );
1046 $forbiddenattributes = array();
1047 if (!is_null($value)) {
1048 $expectedattributes['value'] = $value;
1049 }
1050 if ($enabled === true) {
1051 $forbiddenattributes['disabled'] = 'disabled';
1052 } else if ($enabled === false) {
1053 $expectedattributes['disabled'] = 'disabled';
1054 }
1055 return new question_contains_tag_with_attributes('input', $expectedattributes, $forbiddenattributes);
1056 }
1057
1058 protected function get_contains_submit_button_expectation($enabled = null) {
1059 return $this->get_contains_button_expectation(
1060 $this->quba->get_field_prefix($this->slot) . '-submit', null, $enabled);
1061 }
1062
1063 protected function get_tries_remaining_expectation($n) {
1064 return new question_pattern_expectation('/' .
03cefcc9 1065 preg_quote(get_string('triesremaining', 'qbehaviour_interactive', $n), '/') . '/');
603bd001
PS
1066 }
1067
1068 protected function get_invalid_answer_expectation() {
1069 return new question_pattern_expectation('/' .
03cefcc9 1070 preg_quote(get_string('invalidanswer', 'question'), '/') . '/');
603bd001
PS
1071 }
1072
1073 protected function get_contains_try_again_button_expectation($enabled = null) {
1074 $expectedattributes = array(
1075 'type' => 'submit',
1076 'name' => $this->quba->get_field_prefix($this->slot) . '-tryagain',
1077 );
1078 $forbiddenattributes = array();
1079 if ($enabled === true) {
1080 $forbiddenattributes['disabled'] = 'disabled';
1081 } else if ($enabled === false) {
1082 $expectedattributes['disabled'] = 'disabled';
1083 }
1084 return new question_contains_tag_with_attributes('input', $expectedattributes, $forbiddenattributes);
1085 }
1086
1087 protected function get_does_not_contain_try_again_button_expectation() {
1088 return new question_no_pattern_expectation('/name="' .
1089 $this->quba->get_field_prefix($this->slot) . '-tryagain"/');
1090 }
1091
1092 protected function get_contains_select_expectation($name, $choices,
1093 $selected = null, $enabled = null) {
1094 $fullname = $this->quba->get_field_prefix($this->slot) . $name;
1095 return new question_contains_select_expectation($fullname, $choices, $selected, $enabled);
1096 }
1097
1098 protected function get_mc_right_answer_index($mc) {
1099 $order = $mc->get_order($this->get_question_attempt());
1100 foreach ($order as $i => $ansid) {
1101 if ($mc->answers[$ansid]->fraction == 1) {
1102 return $i;
1103 }
1104 }
1105 $this->fail('This multiple choice question does not seem to have a right answer!');
1106 }
1107
1108 protected function get_no_hint_visible_expectation() {
1109 return new question_no_pattern_expectation('/class="hint"/');
1110 }
1111
1112 protected function get_contains_hint_expectation($hinttext) {
1113 // Does not currently verify hint text.
1114 return new question_contains_tag_with_attribute('div', 'class', 'hint');
1115 }
1116}
1117
1118/**
1119 * Simple class that implements the {@link moodle_recordset} API based on an
1120 * array of test data.
1121 *
1122 * See the {@link question_attempt_step_db_test} class in
1123 * question/engine/tests/testquestionattemptstep.php for an example of how
1124 * this is used.
1125 *
1126 * @copyright 2011 The Open University
1127 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1128 */
1129class question_test_recordset extends moodle_recordset {
1130 protected $records;
1131
1132 /**
1133 * Constructor
1134 * @param $table as for {@link testing_db_record_builder::build_db_records()}
1135 * but does not need a unique first column.
1136 */
1137 public function __construct(array $table) {
1138 $columns = array_shift($table);
1139 $this->records = array();
1140 foreach ($table as $row) {
1141 if (count($row) != count($columns)) {
1142 throw new coding_exception("Row contains the wrong number of fields.");
1143 }
1144 $rec = array();
1145 foreach ($columns as $i => $name) {
1146 $rec[$name] = $row[$i];
1147 }
1148 $this->records[] = $rec;
1149 }
1150 reset($this->records);
1151 }
1152
1153 public function __destruct() {
1154 $this->close();
1155 }
1156
1157 public function current() {
1158 return (object) current($this->records);
1159 }
1160
1161 public function key() {
1162 if (is_null(key($this->records))) {
1163 return false;
1164 }
1165 $current = current($this->records);
1166 return reset($current);
1167 }
1168
1169 public function next() {
1170 next($this->records);
1171 }
1172
1173 public function valid() {
1174 return !is_null(key($this->records));
1175 }
1176
1177 public function close() {
1178 $this->records = null;
1179 }
1180}