MDL-32323 convert question tests
[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 */
417class data_loading_method_test_base extends advanced_testcase {
418 public function build_db_records(array $table) {
419 return testing_db_record_builder::build_db_records($table);
420 }
421 public function test_must_have_methods() {
422 // each test case must have at least one method..
423 }
424}
425
426
427class question_testcase extends advanced_testcase {
428
429 public function test_must_have_methods() {
430 // each test case must have at least one method..
431 }
432
433 public function assert($expectation, $compare, $message = '') {
434 $message = (isset($expectation->message) and $expectation->message !== '') ? $expectation->message : $message;
435
436 if (get_class($expectation) === 'question_pattern_expectation') {
437 $this->assertRegExp($expectation->pattern, $compare, $message);
438 return;
439
440 } else if (get_class($expectation) === 'question_no_pattern_expectation') {
441 $this->assertNotRegExp($expectation->pattern, $compare, $message);
442 return;
443
444 } else if (get_class($expectation) === 'question_contains_tag_with_attributes') {
445 $this->assertTag(array('tag'=>$expectation->tag, 'attributes'=>$expectation->expectedvalues), $compare, $message);
446 foreach ($expectation->forbiddenvalues as $k=>$v) {
447 $attr = $expectation->expectedvalues;
448 $attr[$k] = $v;
449 $this->assertNotTag(array('tag'=>$expectation->tag, 'attributes'=>$attr), $compare, $message);
450 }
451 return;
452
453 } else if (get_class($expectation) === 'question_contains_tag_with_attribute') {
454 $attr = array($expectation->attribute=>$expectation->value);
455 $this->assertTag(array('tag'=>$expectation->tag, 'attributes'=>$attr), $compare, $message);
456 return;
457
458 } else if (get_class($expectation) === 'question_does_not_contain_tag_with_attributes') {
459 $this->assertNotTag(array('tag'=>$expectation->tag, 'attributes'=>$expectation->attributes), $compare, $message);
460 return;
461
462 } else if (get_class($expectation) === 'question_contains_select_expectation') {
463 $tag = array('tag'=>'select', 'attributes'=>array('name'=>$expectation->name),
464 'children'=>array('count'=>count($expectation->choices)));
465 if (!$expectation->enabled) {
466 $tag['attributes']['disabled'] = 'disabled';
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 }
474 $this->assertTag($tag, $compare, $message);
475 }
476 return;
477
478 } else if (get_class($expectation) === 'question_check_specified_fields_expectation') {
479 $expect = (array)$expectation->expect;
480 $compare = (array)$compare;
481 foreach ($expect as $k=>$v) {
482 if (!array_key_exists($k, $compare)) {
483 if (!$message) {
484 $message = "Property $k does not exist";
485 }
486 $this->fail($message);
487 }
488 if ($v != $compare[$k]) {
489 if (!$message) {
490 $message = "Property $k is different";
491 }
492 $this->fail($message);
493 }
494 }
495 $this->assertTrue(true);
496 return;
497
498 } else if (get_class($expectation) === 'question_contains_tag_with_contents') {
499 $this->assertTag(array('tag'=>$expectation->tag, 'content'=>$expectation->content), $compare, $message);
500 return;
501 }
502
503 throw new coding_exception('Unknown expectiontion:'.get_class($expectation));
504 }
505}
506
507
508class question_contains_tag_with_contents {
509 public $tag;
510 public $content;
511 public $message;
512
513 public function __construct($tag, $content, $message = '') {
514 $this->tag = $tag;
515 $this->content = $content;
516 $this->message = $message;
517 }
518
519}
520
521class question_check_specified_fields_expectation {
522 public $expect;
523 public $message;
524
525 function __construct($expected, $message = '') {
526 $this->expect = $expected;
527 $this->message = $message;
528 }
529}
530
531
532class question_contains_select_expectation {
533 public $name;
534 public $choices;
535 public $selected;
536 public $enabled;
537 public $message;
538
539 public function __construct($name, $choices, $selected = null, $enabled = null, $message = '') {
540 $this->name = $name;
541 $this->choices = $choices;
542 $this->selected = $selected;
543 $this->enabled = $enabled;
544 $this->message = $message;
545 }
546}
547
548
549class question_does_not_contain_tag_with_attributes {
550 public $tag;
551 public $attributes;
552 public $message;
553
554 public function __construct($tag, $attributes, $message = '') {
555 $this->tag = $tag;
556 $this->attributes = $attributes;
557 $this->message = $message;
558 }
559}
560
561
562class question_contains_tag_with_attribute {
563 public $tag;
564 public $attribute;
565 public $value;
566 public $message;
567
568 public function __construct($tag, $attribute, $value, $message = '') {
569 $this->tag = $tag;
570 $this->attribute = $attribute;
571 $this->value = $value;
572 $this->message = $message;
573 }
574}
575
576
577class question_contains_tag_with_attributes {
578 public $tag;
579 public $expectedvalues = array();
580 public $forbiddenvalues = array();
581 public $message;
582
583 public function __construct($tag, $expectedvalues, $forbiddenvalues=array(), $message = '') {
584 $this->tag = $tag;
585 $this->expectedvalues = $expectedvalues;
586 $this->forbiddenvalues = $forbiddenvalues;
587 $this->message = $message;
588 }
589}
590
591
592class question_pattern_expectation {
593 public $pattern;
594 public $message;
595
596 public function __construct($pattern, $message = '') {
597 $this->pattern = $pattern;
598 $this->message = $message;
599 }
600}
601
602
603class question_no_pattern_expectation {
604 public $pattern;
605 public $message;
606
607 public function __construct($pattern, $message = '') {
608 $this->pattern = $pattern;
609 $this->message = $message;
610 }
611}
612
613
614/**
615 * Helper base class for tests that walk a question through a sequents of
616 * interactions under the control of a particular behaviour.
617 *
618 * @copyright 2009 The Open University
619 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
620 */
621class qbehaviour_walkthrough_test_base extends question_testcase {
622 /** @var question_display_options */
623 protected $displayoptions;
624 /** @var question_usage_by_activity */
625 protected $quba;
626 /** @var unknown_type integer */
627 protected $slot;
628
629 protected function setUp() {
630 parent::setUp();
631 $this->resetAfterTest(true);
632
633 $this->displayoptions = new question_display_options();
634 $this->quba = question_engine::make_questions_usage_by_activity('unit_test',
635 get_context_instance(CONTEXT_SYSTEM));
636 }
637
638 protected function tearDown() {
639 $this->displayoptions = null;
640 $this->quba = null;
641 parent::tearDown();
642 }
643
644 protected function start_attempt_at_question($question, $preferredbehaviour,
645 $maxmark = null, $variant = 1) {
646 $this->quba->set_preferred_behaviour($preferredbehaviour);
647 $this->slot = $this->quba->add_question($question, $maxmark);
648 $this->quba->start_question($this->slot, $variant);
649 }
650 protected function process_submission($data) {
651 $this->quba->process_action($this->slot, $data);
652 }
653
654 protected function manual_grade($comment, $mark) {
655 $this->quba->manual_grade($this->slot, $comment, $mark);
656 }
657
658 protected function check_current_state($state) {
659 $this->assertEquals($this->quba->get_question_state($this->slot), $state,
660 'Questions is in the wrong state: %s.');
661 }
662
663 protected function check_current_mark($mark) {
664 if (is_null($mark)) {
665 $this->assertNull($this->quba->get_question_mark($this->slot));
666 } else {
667 if ($mark == 0) {
668 // PHP will think a null mark and a mark of 0 are equal,
669 // so explicity check not null in this case.
670 $this->assertNotNull($this->quba->get_question_mark($this->slot));
671 }
672 $this->assertEquals($mark, $this->quba->get_question_mark($this->slot),
673 'Expected mark and actual mark differ: %s.', 0.000001);
674 }
675 }
676
677 /**
678 * @param $condition one or more Expectations. (users varargs).
679 */
680 protected function check_current_output() {
681 $html = $this->quba->render_question($this->slot, $this->displayoptions);
682 foreach (func_get_args() as $condition) {
683 $this->assert($condition, $html);
684 }
685 }
686
687 protected function get_question_attempt() {
688 return $this->quba->get_question_attempt($this->slot);
689 }
690
691 protected function get_step_count() {
692 return $this->get_question_attempt()->get_num_steps();
693 }
694
695 protected function check_step_count($expectednumsteps) {
696 $this->assertEquals($expectednumsteps, $this->get_step_count());
697 }
698
699 protected function get_step($stepnum) {
700 return $this->get_question_attempt()->get_step($stepnum);
701 }
702
703 protected function get_contains_question_text_expectation($question) {
704 return new question_pattern_expectation('/' . preg_quote($question->questiontext) . '/');
705 }
706
707 protected function get_contains_general_feedback_expectation($question) {
708 return new question_pattern_expectation('/' . preg_quote($question->generalfeedback) . '/');
709 }
710
711 protected function get_does_not_contain_correctness_expectation() {
712 return new question_no_pattern_expectation('/class=\"correctness/');
713 }
714
715 protected function get_contains_correct_expectation() {
716 return new question_pattern_expectation('/' . preg_quote(get_string('correct', 'question')) . '/');
717 }
718
719 protected function get_contains_partcorrect_expectation() {
720 return new question_pattern_expectation('/' .
721 preg_quote(get_string('partiallycorrect', 'question')) . '/');
722 }
723
724 protected function get_contains_incorrect_expectation() {
725 return new question_pattern_expectation('/' . preg_quote(get_string('incorrect', 'question')) . '/');
726 }
727
728 protected function get_contains_standard_correct_combined_feedback_expectation() {
729 return new question_pattern_expectation('/' .
730 preg_quote(test_question_maker::STANDARD_OVERALL_CORRECT_FEEDBACK) . '/');
731 }
732
733 protected function get_contains_standard_partiallycorrect_combined_feedback_expectation() {
734 return new question_pattern_expectation('/' .
735 preg_quote(test_question_maker::STANDARD_OVERALL_PARTIALLYCORRECT_FEEDBACK) . '/');
736 }
737
738 protected function get_contains_standard_incorrect_combined_feedback_expectation() {
739 return new question_pattern_expectation('/' .
740 preg_quote(test_question_maker::STANDARD_OVERALL_INCORRECT_FEEDBACK) . '/');
741 }
742
743 protected function get_does_not_contain_feedback_expectation() {
744 return new question_no_pattern_expectation('/class="feedback"/');
745 }
746
747 protected function get_does_not_contain_num_parts_correct() {
748 return new question_no_pattern_expectation('/class="numpartscorrect"/');
749 }
750
751 protected function get_contains_num_parts_correct($num) {
752 $a = new stdClass();
753 $a->num = $num;
754 return new question_pattern_expectation('/<div class="numpartscorrect">' .
755 preg_quote(get_string('yougotnright', 'question', $a)) . '/');
756 }
757
758 protected function get_does_not_contain_specific_feedback_expectation() {
759 return new question_no_pattern_expectation('/class="specificfeedback"/');
760 }
761
762 protected function get_contains_validation_error_expectation() {
763 return new question_contains_tag_with_attribute('div', 'class', 'validationerror');
764 }
765
766 protected function get_does_not_contain_validation_error_expectation() {
767 return new question_no_pattern_expectation('/class="validationerror"/');
768 }
769
770 protected function get_contains_mark_summary($mark) {
771 $a = new stdClass();
772 $a->mark = format_float($mark, $this->displayoptions->markdp);
773 $a->max = format_float($this->quba->get_question_max_mark($this->slot),
774 $this->displayoptions->markdp);
775 return new question_pattern_expectation('/' .
776 preg_quote(get_string('markoutofmax', 'question', $a)) . '/');
777 }
778
779 protected function get_contains_marked_out_of_summary() {
780 $max = format_float($this->quba->get_question_max_mark($this->slot),
781 $this->displayoptions->markdp);
782 return new question_pattern_expectation('/' .
783 preg_quote(get_string('markedoutofmax', 'question', $max)) . '/');
784 }
785
786 protected function get_does_not_contain_mark_summary() {
787 return new question_no_pattern_expectation('/<div class="grade">/');
788 }
789
790 protected function get_contains_checkbox_expectation($baseattr, $enabled, $checked) {
791 $expectedattributes = $baseattr;
792 $forbiddenattributes = array();
793 $expectedattributes['type'] = 'checkbox';
794 if ($enabled === true) {
795 $forbiddenattributes['disabled'] = 'disabled';
796 } else if ($enabled === false) {
797 $expectedattributes['disabled'] = 'disabled';
798 }
799 if ($checked === true) {
800 $expectedattributes['checked'] = 'checked';
801 } else if ($checked === false) {
802 $forbiddenattributes['checked'] = 'checked';
803 }
804 return new question_contains_tag_with_attributes('input', $expectedattributes, $forbiddenattributes);
805 }
806
807 protected function get_contains_mc_checkbox_expectation($index, $enabled = null,
808 $checked = null) {
809 return $this->get_contains_checkbox_expectation(array(
810 'name' => $this->quba->get_field_prefix($this->slot) . $index,
811 'value' => 1,
812 ), $enabled, $checked);
813 }
814
815 protected function get_contains_radio_expectation($baseattr, $enabled, $checked) {
816 $expectedattributes = $baseattr;
817 $forbiddenattributes = array();
818 $expectedattributes['type'] = 'radio';
819 if ($enabled === true) {
820 $forbiddenattributes['disabled'] = 'disabled';
821 } else if ($enabled === false) {
822 $expectedattributes['disabled'] = 'disabled';
823 }
824 if ($checked === true) {
825 $expectedattributes['checked'] = 'checked';
826 } else if ($checked === false) {
827 $forbiddenattributes['checked'] = 'checked';
828 }
829 return new question_contains_tag_with_attributes('input', $expectedattributes, $forbiddenattributes);
830 }
831
832 protected function get_contains_mc_radio_expectation($index, $enabled = null, $checked = null) {
833 return $this->get_contains_radio_expectation(array(
834 'name' => $this->quba->get_field_prefix($this->slot) . 'answer',
835 'value' => $index,
836 ), $enabled, $checked);
837 }
838
839 protected function get_contains_hidden_expectation($name, $value = null) {
840 $expectedattributes = array('type' => 'hidden', 'name' => s($name));
841 if (!is_null($value)) {
842 $expectedattributes['value'] = s($value);
843 }
844 return new question_contains_tag_with_attributes('input', $expectedattributes);
845 }
846
847 protected function get_does_not_contain_hidden_expectation($name, $value = null) {
848 $expectedattributes = array('type' => 'hidden', 'name' => s($name));
849 if (!is_null($value)) {
850 $expectedattributes['value'] = s($value);
851 }
852 return new question_does_not_contain_tag_with_attributes('input', $expectedattributes);
853 }
854
855 protected function get_contains_tf_true_radio_expectation($enabled = null, $checked = null) {
856 return $this->get_contains_radio_expectation(array(
857 'name' => $this->quba->get_field_prefix($this->slot) . 'answer',
858 'value' => 1,
859 ), $enabled, $checked);
860 }
861
862 protected function get_contains_tf_false_radio_expectation($enabled = null, $checked = null) {
863 return $this->get_contains_radio_expectation(array(
864 'name' => $this->quba->get_field_prefix($this->slot) . 'answer',
865 'value' => 0,
866 ), $enabled, $checked);
867 }
868
869 protected function get_contains_cbm_radio_expectation($certainty, $enabled = null,
870 $checked = null) {
871 return $this->get_contains_radio_expectation(array(
872 'name' => $this->quba->get_field_prefix($this->slot) . '-certainty',
873 'value' => $certainty,
874 ), $enabled, $checked);
875 }
876
877 protected function get_contains_button_expectation($name, $value = null, $enabled = null) {
878 $expectedattributes = array(
879 'type' => 'submit',
880 'name' => $name,
881 );
882 $forbiddenattributes = array();
883 if (!is_null($value)) {
884 $expectedattributes['value'] = $value;
885 }
886 if ($enabled === true) {
887 $forbiddenattributes['disabled'] = 'disabled';
888 } else if ($enabled === false) {
889 $expectedattributes['disabled'] = 'disabled';
890 }
891 return new question_contains_tag_with_attributes('input', $expectedattributes, $forbiddenattributes);
892 }
893
894 protected function get_contains_submit_button_expectation($enabled = null) {
895 return $this->get_contains_button_expectation(
896 $this->quba->get_field_prefix($this->slot) . '-submit', null, $enabled);
897 }
898
899 protected function get_tries_remaining_expectation($n) {
900 return new question_pattern_expectation('/' .
901 preg_quote(get_string('triesremaining', 'qbehaviour_interactive', $n)) . '/');
902 }
903
904 protected function get_invalid_answer_expectation() {
905 return new question_pattern_expectation('/' .
906 preg_quote(get_string('invalidanswer', 'question')) . '/');
907 }
908
909 protected function get_contains_try_again_button_expectation($enabled = null) {
910 $expectedattributes = array(
911 'type' => 'submit',
912 'name' => $this->quba->get_field_prefix($this->slot) . '-tryagain',
913 );
914 $forbiddenattributes = array();
915 if ($enabled === true) {
916 $forbiddenattributes['disabled'] = 'disabled';
917 } else if ($enabled === false) {
918 $expectedattributes['disabled'] = 'disabled';
919 }
920 return new question_contains_tag_with_attributes('input', $expectedattributes, $forbiddenattributes);
921 }
922
923 protected function get_does_not_contain_try_again_button_expectation() {
924 return new question_no_pattern_expectation('/name="' .
925 $this->quba->get_field_prefix($this->slot) . '-tryagain"/');
926 }
927
928 protected function get_contains_select_expectation($name, $choices,
929 $selected = null, $enabled = null) {
930 $fullname = $this->quba->get_field_prefix($this->slot) . $name;
931 return new question_contains_select_expectation($fullname, $choices, $selected, $enabled);
932 }
933
934 protected function get_mc_right_answer_index($mc) {
935 $order = $mc->get_order($this->get_question_attempt());
936 foreach ($order as $i => $ansid) {
937 if ($mc->answers[$ansid]->fraction == 1) {
938 return $i;
939 }
940 }
941 $this->fail('This multiple choice question does not seem to have a right answer!');
942 }
943
944 protected function get_no_hint_visible_expectation() {
945 return new question_no_pattern_expectation('/class="hint"/');
946 }
947
948 protected function get_contains_hint_expectation($hinttext) {
949 // Does not currently verify hint text.
950 return new question_contains_tag_with_attribute('div', 'class', 'hint');
951 }
952}
953
954/**
955 * Simple class that implements the {@link moodle_recordset} API based on an
956 * array of test data.
957 *
958 * See the {@link question_attempt_step_db_test} class in
959 * question/engine/tests/testquestionattemptstep.php for an example of how
960 * this is used.
961 *
962 * @copyright 2011 The Open University
963 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
964 */
965class question_test_recordset extends moodle_recordset {
966 protected $records;
967
968 /**
969 * Constructor
970 * @param $table as for {@link testing_db_record_builder::build_db_records()}
971 * but does not need a unique first column.
972 */
973 public function __construct(array $table) {
974 $columns = array_shift($table);
975 $this->records = array();
976 foreach ($table as $row) {
977 if (count($row) != count($columns)) {
978 throw new coding_exception("Row contains the wrong number of fields.");
979 }
980 $rec = array();
981 foreach ($columns as $i => $name) {
982 $rec[$name] = $row[$i];
983 }
984 $this->records[] = $rec;
985 }
986 reset($this->records);
987 }
988
989 public function __destruct() {
990 $this->close();
991 }
992
993 public function current() {
994 return (object) current($this->records);
995 }
996
997 public function key() {
998 if (is_null(key($this->records))) {
999 return false;
1000 }
1001 $current = current($this->records);
1002 return reset($current);
1003 }
1004
1005 public function next() {
1006 next($this->records);
1007 }
1008
1009 public function valid() {
1010 return !is_null(key($this->records));
1011 }
1012
1013 public function close() {
1014 $this->records = null;
1015 }
1016}