on demand release 2.5beta+
[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
c7fbfe46
TH
789 protected function check_output_contains_hidden_input($name, $value) {
790 $attributes = array(
791 'type' => 'hidden',
792 'name' => $this->quba->get_field_prefix($this->slot) . $name,
793 'value' => $value,
794 );
795 $this->assertTag($this->get_tag_matcher('input', $attributes), $this->currentoutput,
796 'Looking for a hidden input with attributes ' . html_writer::attributes($attributes) . ' in ' . $this->currentoutput);
797 }
798
eca230b5
TH
799 protected function get_tag_matcher($tag, $attributes) {
800 return array(
801 'tag' => $tag,
802 'attributes' => $attributes,
803 );
804 }
805
603bd001
PS
806 /**
807 * @param $condition one or more Expectations. (users varargs).
808 */
809 protected function check_current_output() {
810 $html = $this->quba->render_question($this->slot, $this->displayoptions);
811 foreach (func_get_args() as $condition) {
812 $this->assert($condition, $html);
813 }
814 }
815
816 protected function get_question_attempt() {
817 return $this->quba->get_question_attempt($this->slot);
818 }
819
820 protected function get_step_count() {
821 return $this->get_question_attempt()->get_num_steps();
822 }
823
824 protected function check_step_count($expectednumsteps) {
825 $this->assertEquals($expectednumsteps, $this->get_step_count());
826 }
827
828 protected function get_step($stepnum) {
829 return $this->get_question_attempt()->get_step($stepnum);
830 }
831
832 protected function get_contains_question_text_expectation($question) {
03cefcc9 833 return new question_pattern_expectation('/' . preg_quote($question->questiontext, '/') . '/');
603bd001
PS
834 }
835
836 protected function get_contains_general_feedback_expectation($question) {
03cefcc9 837 return new question_pattern_expectation('/' . preg_quote($question->generalfeedback, '/') . '/');
603bd001
PS
838 }
839
840 protected function get_does_not_contain_correctness_expectation() {
841 return new question_no_pattern_expectation('/class=\"correctness/');
842 }
843
844 protected function get_contains_correct_expectation() {
03cefcc9 845 return new question_pattern_expectation('/' . preg_quote(get_string('correct', 'question'), '/') . '/');
603bd001
PS
846 }
847
848 protected function get_contains_partcorrect_expectation() {
849 return new question_pattern_expectation('/' .
03cefcc9 850 preg_quote(get_string('partiallycorrect', 'question'), '/') . '/');
603bd001
PS
851 }
852
853 protected function get_contains_incorrect_expectation() {
03cefcc9 854 return new question_pattern_expectation('/' . preg_quote(get_string('incorrect', 'question'), '/') . '/');
603bd001
PS
855 }
856
857 protected function get_contains_standard_correct_combined_feedback_expectation() {
858 return new question_pattern_expectation('/' .
03cefcc9 859 preg_quote(test_question_maker::STANDARD_OVERALL_CORRECT_FEEDBACK, '/') . '/');
603bd001
PS
860 }
861
862 protected function get_contains_standard_partiallycorrect_combined_feedback_expectation() {
863 return new question_pattern_expectation('/' .
03cefcc9 864 preg_quote(test_question_maker::STANDARD_OVERALL_PARTIALLYCORRECT_FEEDBACK, '/') . '/');
603bd001
PS
865 }
866
867 protected function get_contains_standard_incorrect_combined_feedback_expectation() {
868 return new question_pattern_expectation('/' .
03cefcc9 869 preg_quote(test_question_maker::STANDARD_OVERALL_INCORRECT_FEEDBACK, '/') . '/');
603bd001
PS
870 }
871
872 protected function get_does_not_contain_feedback_expectation() {
873 return new question_no_pattern_expectation('/class="feedback"/');
874 }
875
876 protected function get_does_not_contain_num_parts_correct() {
877 return new question_no_pattern_expectation('/class="numpartscorrect"/');
878 }
879
880 protected function get_contains_num_parts_correct($num) {
881 $a = new stdClass();
882 $a->num = $num;
883 return new question_pattern_expectation('/<div class="numpartscorrect">' .
03cefcc9 884 preg_quote(get_string('yougotnright', 'question', $a), '/') . '/');
603bd001
PS
885 }
886
887 protected function get_does_not_contain_specific_feedback_expectation() {
888 return new question_no_pattern_expectation('/class="specificfeedback"/');
889 }
890
891 protected function get_contains_validation_error_expectation() {
892 return new question_contains_tag_with_attribute('div', 'class', 'validationerror');
893 }
894
895 protected function get_does_not_contain_validation_error_expectation() {
896 return new question_no_pattern_expectation('/class="validationerror"/');
897 }
898
899 protected function get_contains_mark_summary($mark) {
900 $a = new stdClass();
901 $a->mark = format_float($mark, $this->displayoptions->markdp);
902 $a->max = format_float($this->quba->get_question_max_mark($this->slot),
903 $this->displayoptions->markdp);
904 return new question_pattern_expectation('/' .
03cefcc9 905 preg_quote(get_string('markoutofmax', 'question', $a), '/') . '/');
603bd001
PS
906 }
907
908 protected function get_contains_marked_out_of_summary() {
909 $max = format_float($this->quba->get_question_max_mark($this->slot),
910 $this->displayoptions->markdp);
911 return new question_pattern_expectation('/' .
03cefcc9 912 preg_quote(get_string('markedoutofmax', 'question', $max), '/') . '/');
603bd001
PS
913 }
914
915 protected function get_does_not_contain_mark_summary() {
916 return new question_no_pattern_expectation('/<div class="grade">/');
917 }
918
919 protected function get_contains_checkbox_expectation($baseattr, $enabled, $checked) {
920 $expectedattributes = $baseattr;
921 $forbiddenattributes = array();
922 $expectedattributes['type'] = 'checkbox';
923 if ($enabled === true) {
924 $forbiddenattributes['disabled'] = 'disabled';
925 } else if ($enabled === false) {
926 $expectedattributes['disabled'] = 'disabled';
927 }
928 if ($checked === true) {
929 $expectedattributes['checked'] = 'checked';
930 } else if ($checked === false) {
931 $forbiddenattributes['checked'] = 'checked';
932 }
933 return new question_contains_tag_with_attributes('input', $expectedattributes, $forbiddenattributes);
934 }
935
936 protected function get_contains_mc_checkbox_expectation($index, $enabled = null,
937 $checked = null) {
938 return $this->get_contains_checkbox_expectation(array(
939 'name' => $this->quba->get_field_prefix($this->slot) . $index,
940 'value' => 1,
941 ), $enabled, $checked);
942 }
943
944 protected function get_contains_radio_expectation($baseattr, $enabled, $checked) {
945 $expectedattributes = $baseattr;
946 $forbiddenattributes = array();
947 $expectedattributes['type'] = 'radio';
948 if ($enabled === true) {
949 $forbiddenattributes['disabled'] = 'disabled';
950 } else if ($enabled === false) {
951 $expectedattributes['disabled'] = 'disabled';
952 }
953 if ($checked === true) {
954 $expectedattributes['checked'] = 'checked';
955 } else if ($checked === false) {
956 $forbiddenattributes['checked'] = 'checked';
957 }
958 return new question_contains_tag_with_attributes('input', $expectedattributes, $forbiddenattributes);
959 }
960
961 protected function get_contains_mc_radio_expectation($index, $enabled = null, $checked = null) {
962 return $this->get_contains_radio_expectation(array(
963 'name' => $this->quba->get_field_prefix($this->slot) . 'answer',
964 'value' => $index,
965 ), $enabled, $checked);
966 }
967
968 protected function get_contains_hidden_expectation($name, $value = null) {
969 $expectedattributes = array('type' => 'hidden', 'name' => s($name));
970 if (!is_null($value)) {
971 $expectedattributes['value'] = s($value);
972 }
973 return new question_contains_tag_with_attributes('input', $expectedattributes);
974 }
975
976 protected function get_does_not_contain_hidden_expectation($name, $value = null) {
977 $expectedattributes = array('type' => 'hidden', 'name' => s($name));
978 if (!is_null($value)) {
979 $expectedattributes['value'] = s($value);
980 }
981 return new question_does_not_contain_tag_with_attributes('input', $expectedattributes);
982 }
983
984 protected function get_contains_tf_true_radio_expectation($enabled = null, $checked = null) {
985 return $this->get_contains_radio_expectation(array(
986 'name' => $this->quba->get_field_prefix($this->slot) . 'answer',
987 'value' => 1,
988 ), $enabled, $checked);
989 }
990
991 protected function get_contains_tf_false_radio_expectation($enabled = null, $checked = null) {
992 return $this->get_contains_radio_expectation(array(
993 'name' => $this->quba->get_field_prefix($this->slot) . 'answer',
994 'value' => 0,
995 ), $enabled, $checked);
996 }
997
998 protected function get_contains_cbm_radio_expectation($certainty, $enabled = null,
999 $checked = null) {
1000 return $this->get_contains_radio_expectation(array(
1001 'name' => $this->quba->get_field_prefix($this->slot) . '-certainty',
1002 'value' => $certainty,
1003 ), $enabled, $checked);
1004 }
1005
1006 protected function get_contains_button_expectation($name, $value = null, $enabled = null) {
1007 $expectedattributes = array(
1008 'type' => 'submit',
1009 'name' => $name,
1010 );
1011 $forbiddenattributes = array();
1012 if (!is_null($value)) {
1013 $expectedattributes['value'] = $value;
1014 }
1015 if ($enabled === true) {
1016 $forbiddenattributes['disabled'] = 'disabled';
1017 } else if ($enabled === false) {
1018 $expectedattributes['disabled'] = 'disabled';
1019 }
1020 return new question_contains_tag_with_attributes('input', $expectedattributes, $forbiddenattributes);
1021 }
1022
1023 protected function get_contains_submit_button_expectation($enabled = null) {
1024 return $this->get_contains_button_expectation(
1025 $this->quba->get_field_prefix($this->slot) . '-submit', null, $enabled);
1026 }
1027
1028 protected function get_tries_remaining_expectation($n) {
1029 return new question_pattern_expectation('/' .
03cefcc9 1030 preg_quote(get_string('triesremaining', 'qbehaviour_interactive', $n), '/') . '/');
603bd001
PS
1031 }
1032
1033 protected function get_invalid_answer_expectation() {
1034 return new question_pattern_expectation('/' .
03cefcc9 1035 preg_quote(get_string('invalidanswer', 'question'), '/') . '/');
603bd001
PS
1036 }
1037
1038 protected function get_contains_try_again_button_expectation($enabled = null) {
1039 $expectedattributes = array(
1040 'type' => 'submit',
1041 'name' => $this->quba->get_field_prefix($this->slot) . '-tryagain',
1042 );
1043 $forbiddenattributes = array();
1044 if ($enabled === true) {
1045 $forbiddenattributes['disabled'] = 'disabled';
1046 } else if ($enabled === false) {
1047 $expectedattributes['disabled'] = 'disabled';
1048 }
1049 return new question_contains_tag_with_attributes('input', $expectedattributes, $forbiddenattributes);
1050 }
1051
1052 protected function get_does_not_contain_try_again_button_expectation() {
1053 return new question_no_pattern_expectation('/name="' .
1054 $this->quba->get_field_prefix($this->slot) . '-tryagain"/');
1055 }
1056
1057 protected function get_contains_select_expectation($name, $choices,
1058 $selected = null, $enabled = null) {
1059 $fullname = $this->quba->get_field_prefix($this->slot) . $name;
1060 return new question_contains_select_expectation($fullname, $choices, $selected, $enabled);
1061 }
1062
1063 protected function get_mc_right_answer_index($mc) {
1064 $order = $mc->get_order($this->get_question_attempt());
1065 foreach ($order as $i => $ansid) {
1066 if ($mc->answers[$ansid]->fraction == 1) {
1067 return $i;
1068 }
1069 }
1070 $this->fail('This multiple choice question does not seem to have a right answer!');
1071 }
1072
1073 protected function get_no_hint_visible_expectation() {
1074 return new question_no_pattern_expectation('/class="hint"/');
1075 }
1076
1077 protected function get_contains_hint_expectation($hinttext) {
1078 // Does not currently verify hint text.
1079 return new question_contains_tag_with_attribute('div', 'class', 'hint');
1080 }
1081}
1082
1083/**
1084 * Simple class that implements the {@link moodle_recordset} API based on an
1085 * array of test data.
1086 *
1087 * See the {@link question_attempt_step_db_test} class in
1088 * question/engine/tests/testquestionattemptstep.php for an example of how
1089 * this is used.
1090 *
1091 * @copyright 2011 The Open University
1092 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1093 */
1094class question_test_recordset extends moodle_recordset {
1095 protected $records;
1096
1097 /**
1098 * Constructor
1099 * @param $table as for {@link testing_db_record_builder::build_db_records()}
1100 * but does not need a unique first column.
1101 */
1102 public function __construct(array $table) {
1103 $columns = array_shift($table);
1104 $this->records = array();
1105 foreach ($table as $row) {
1106 if (count($row) != count($columns)) {
1107 throw new coding_exception("Row contains the wrong number of fields.");
1108 }
1109 $rec = array();
1110 foreach ($columns as $i => $name) {
1111 $rec[$name] = $row[$i];
1112 }
1113 $this->records[] = $rec;
1114 }
1115 reset($this->records);
1116 }
1117
1118 public function __destruct() {
1119 $this->close();
1120 }
1121
1122 public function current() {
1123 return (object) current($this->records);
1124 }
1125
1126 public function key() {
1127 if (is_null(key($this->records))) {
1128 return false;
1129 }
1130 $current = current($this->records);
1131 return reset($current);
1132 }
1133
1134 public function next() {
1135 next($this->records);
1136 }
1137
1138 public function valid() {
1139 return !is_null(key($this->records));
1140 }
1141
1142 public function close() {
1143 $this->records = null;
1144 }
1145}