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