2 // This file is part of Moodle - http://moodle.org/
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.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * This file contains helper classes for testing the question engine.
21 * @subpackage questionengine
22 * @copyright 2009 The Open University
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 defined('MOODLE_INTERNAL') || die();
30 require_once(dirname(__FILE__) . '/../lib.php');
34 * Makes some protected methods of question_attempt public to facilitate testing.
36 * @copyright 2009 The Open University
37 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
39 class testable_question_attempt extends question_attempt {
40 public function add_step(question_attempt_step $step) {
41 parent::add_step($step);
43 public function set_min_fraction($fraction) {
44 $this->minfraction = $fraction;
46 public function set_behaviour(question_behaviour $behaviour) {
47 $this->behaviour = $behaviour;
53 * Test subclass to allow access to some protected data so that the correct
54 * behaviour can be verified.
56 * @copyright 2012 The Open University
57 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
59 class testable_question_engine_unit_of_work extends question_engine_unit_of_work {
60 public function get_modified() {
61 return $this->modified;
64 public function get_attempts_added() {
65 return $this->attemptsadded;
68 public function get_attempts_modified() {
69 return $this->attemptsmodified;
72 public function get_steps_added() {
73 return $this->stepsadded;
76 public function get_steps_modified() {
77 return $this->stepsmodified;
80 public function get_steps_deleted() {
81 return $this->stepsdeleted;
87 * Base class for question type test helpers.
89 * @copyright 2011 The Open University
90 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
92 abstract class question_test_helper {
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
98 abstract public function get_test_questions();
103 * This class creates questions of various types, which can then be used when
106 * @copyright 2009 The Open University
107 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
109 class 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.';
115 /** @var array qtype => qtype test helper class. */
116 protected static $testhelpers = array();
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.
126 public static function get_a_qa($question, $maxmark = 3) {
127 return new question_attempt($question, 13, null, $maxmark);
131 * Initialise the common fields of a question of any type.
133 public static function initialise_a_question($q) {
139 $q->questiontextformat = FORMAT_HTML;
140 $q->generalfeedbackformat = FORMAT_HTML;
142 $q->penalty = 0.3333333;
144 $q->stamp = make_unique_id_code();
145 $q->version = make_unique_id_code();
147 $q->timecreated = time();
148 $q->timemodified = time();
149 $q->createdby = $USER->id;
150 $q->modifiedby = $USER->id;
153 public static function initialise_question_data($qdata) {
157 $qdata->category = 0;
158 $qdata->contextid = 0;
160 $qdata->questiontextformat = FORMAT_HTML;
161 $qdata->generalfeedbackformat = FORMAT_HTML;
162 $qdata->defaultmark = 1;
163 $qdata->penalty = 0.3333333;
165 $qdata->stamp = make_unique_id_code();
166 $qdata->version = make_unique_id_code();
168 $qdata->timecreated = time();
169 $qdata->timemodified = time();
170 $qdata->createdby = $USER->id;
171 $qdata->modifiedby = $USER->id;
172 $qdata->hints = array();
175 public static function initialise_question_form_data($qdata) {
176 $formdata = new stdClass();
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;
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.
192 public static function get_test_helper($qtype) {
195 if (array_key_exists($qtype, self::$testhelpers)) {
196 return self::$testhelpers[$qtype];
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.');
206 $class = 'qtype_' . $qtype . '_test_helper';
207 if (!class_exists($class)) {
208 throw new coding_exception('Class ' . $class . ' is not defined in ' . $file);
211 self::$testhelpers[$qtype] = new $class();
212 return self::$testhelpers[$qtype];
216 * Call a method on a qtype_{$qtype}_test_helper class and return the result.
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
224 protected static function call_question_helper_method($methodtemplate, $qtype, $which = null) {
225 $helper = self::get_test_helper($qtype);
227 $available = $helper->get_test_questions();
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.');
236 $method = str_replace(array('{qtype}', '{which}'),
237 array($qtype, $which), $methodtemplate);
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.');
244 return $helper->$method();
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.
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.
258 public static function make_question($qtype, $which = null) {
259 return self::call_question_helper_method('make_{qtype}_question_{which}',
264 * Like {@link make_question()} but returns the datastructure from
265 * get_question_options instead of the question_definition object.
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.
272 public static function get_question_data($qtype, $which = null) {
273 return self::call_question_helper_method('get_{qtype}_question_data_{which}',
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.
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.
286 public static function get_question_form_data($qtype, $which = null) {
287 return self::call_question_helper_method('get_{qtype}_question_form_data_{which}',
292 * Makes a multichoice question with choices 'A', 'B' and 'C' shuffled. 'A'
293 * is correct, defaultmark 1.
294 * @return qtype_multichoice_single_question
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');
305 $mc->shuffleanswers = 1;
306 $mc->answernumbering = 'abc';
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),
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
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');
331 $mc->shuffleanswers = 1;
332 $mc->answernumbering = 'abc';
334 self::set_standard_combined_feedback_fields($mc);
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),
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
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');
361 $match->shufflestems = 1;
363 self::set_standard_combined_feedback_fields($match);
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]);
379 * Makes a truefalse question with correct ansewer true, defaultmark 1.
380 * @return qtype_essay_question
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.';
390 $essay->qtype = question_bank::get_qtype('essay');
392 $essay->responseformat = 'editor';
393 $essay->responsefieldlines = 15;
394 $essay->attachments = 0;
395 $essay->graderinfo = '';
396 $essay->graderinfoformat = FORMAT_MOODLE;
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.
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;
420 * Helper for tests that need to simulate records loaded from the database.
422 * @copyright 2009 The Open University
423 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
425 abstract class testing_db_record_builder {
426 public static function build_db_records(array $table) {
427 $columns = array_shift($table);
429 foreach ($table as $row) {
430 if (count($row) != count($columns)) {
431 throw new coding_exception("Row contains the wrong number of fields.");
433 $rec = new stdClass();
434 foreach ($columns as $i => $name) {
435 $rec->$name = $row[$i];
445 * Helper base class for tests that need to simulate records loaded from the
448 * @copyright 2009 The Open University
449 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
451 abstract class data_loading_method_test_base extends advanced_testcase {
452 public function build_db_records(array $table) {
453 return testing_db_record_builder::build_db_records($table);
458 abstract class question_testcase extends advanced_testcase {
460 public function assert($expectation, $compare, $notused = '') {
462 if (get_class($expectation) === 'question_pattern_expectation') {
463 $this->assertRegExp($expectation->pattern, $compare,
464 'Expected regex ' . $expectation->pattern . ' not found in ' . $compare);
467 } else if (get_class($expectation) === 'question_no_pattern_expectation') {
468 $this->assertNotRegExp($expectation->pattern, $compare,
469 'Unexpected regex ' . $expectation->pattern . ' found in ' . $compare);
472 } else if (get_class($expectation) === 'question_contains_tag_with_attributes') {
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);
475 foreach ($expectation->forbiddenvalues as $k=>$v) {
476 $attr = $expectation->expectedvalues;
478 $this->assertNotTag(array('tag'=>$expectation->tag, 'attributes'=>$attr), $compare,
479 $expectation->tag . ' had a ' . $k . ' attribute that should not be there in ' . $compare);
483 } else if (get_class($expectation) === 'question_contains_tag_with_attribute') {
484 $attr = array($expectation->attribute=>$expectation->value);
485 $this->assertTag(array('tag'=>$expectation->tag, 'attributes'=>$attr), $compare,
486 'Looking for a ' . $expectation->tag . ' with attribute ' . html_writer::attributes($attr) . ' in ' . $compare);
489 } else if (get_class($expectation) === 'question_does_not_contain_tag_with_attributes') {
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);
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)));
497 if ($expectation->enabled === false) {
498 $tag['attributes']['disabled'] = 'disabled';
499 } else if ($expectation->enabled === true) {
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'));
506 $tag['child'] = array('tag'=>'option', 'attributes'=>array('value'=>$value));
510 $this->assertTag($tag, $compare, 'expected select not found in ' . $compare);
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)) {
518 $this->fail("Property $k does not exist");
520 if ($v != $compare[$k]) {
521 $this->fail("Property $k is different");
524 $this->assertTrue(true);
527 } else if (get_class($expectation) === 'question_contains_tag_with_contents') {
528 $this->assertTag(array('tag'=>$expectation->tag, 'content'=>$expectation->content), $compare,
529 'Looking for a ' . $expectation->tag . ' with content ' . $expectation->content . ' in ' . $compare);
533 throw new coding_exception('Unknown expectiontion:'.get_class($expectation));
538 class question_contains_tag_with_contents {
543 public function __construct($tag, $content, $message = '') {
545 $this->content = $content;
546 $this->message = $message;
551 class question_check_specified_fields_expectation {
555 function __construct($expected, $message = '') {
556 $this->expect = $expected;
557 $this->message = $message;
562 class question_contains_select_expectation {
569 public function __construct($name, $choices, $selected = null, $enabled = null, $message = '') {
571 $this->choices = $choices;
572 $this->selected = $selected;
573 $this->enabled = $enabled;
574 $this->message = $message;
579 class question_does_not_contain_tag_with_attributes {
584 public function __construct($tag, $attributes, $message = '') {
586 $this->attributes = $attributes;
587 $this->message = $message;
592 class question_contains_tag_with_attribute {
598 public function __construct($tag, $attribute, $value, $message = '') {
600 $this->attribute = $attribute;
601 $this->value = $value;
602 $this->message = $message;
607 class question_contains_tag_with_attributes {
609 public $expectedvalues = array();
610 public $forbiddenvalues = array();
613 public function __construct($tag, $expectedvalues, $forbiddenvalues=array(), $message = '') {
615 $this->expectedvalues = $expectedvalues;
616 $this->forbiddenvalues = $forbiddenvalues;
617 $this->message = $message;
622 class question_pattern_expectation {
626 public function __construct($pattern, $message = '') {
627 $this->pattern = $pattern;
628 $this->message = $message;
633 class question_no_pattern_expectation {
637 public function __construct($pattern, $message = '') {
638 $this->pattern = $pattern;
639 $this->message = $message;
645 * Helper base class for tests that walk a question through a sequents of
646 * interactions under the control of a particular behaviour.
648 * @copyright 2009 The Open University
649 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
651 abstract class qbehaviour_walkthrough_test_base extends question_testcase {
652 /** @var question_display_options */
653 protected $displayoptions;
654 /** @var question_usage_by_activity */
660 * @var string after {@link render()} has been called, this contains the
661 * display of the question in its current state.
663 protected $currentoutput = '';
665 protected function setUp() {
667 $this->resetAfterTest(true);
669 $this->displayoptions = new question_display_options();
670 $this->quba = question_engine::make_questions_usage_by_activity('unit_test',
671 context_system::instance());
674 protected function tearDown() {
675 $this->displayoptions = null;
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);
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.
692 protected function response_data_to_post($data) {
693 $prefix = $this->quba->get_field_prefix($this->slot);
695 'slots' => $this->slot,
696 $prefix . ':sequencecheck' => $this->get_question_attempt()->get_sequence_check_count(),
698 foreach ($data as $name => $value) {
699 $fulldata[$prefix . $name] = $value;
704 protected function process_submission($data) {
705 // Backwards compatibility.
707 if (count($data) == 1 && key($data) === '-finish') {
711 $this->quba->process_all_actions(time(), $this->response_data_to_post($data));
714 protected function process_autosave($data) {
715 $this->quba->process_all_autosaves(null, $this->response_data_to_post($data));
718 protected function finish() {
719 $this->quba->finish_all_questions();
722 protected function manual_grade($comment, $mark, $commentformat = null) {
723 $this->quba->manual_grade($this->slot, $comment, $mark, $commentformat);
726 protected function save_quba(moodle_database $db = null) {
727 question_engine::save_questions_usage_by_activity($this->quba, $db);
730 protected function load_quba(moodle_database $db = null) {
731 $this->quba = question_engine::load_questions_usage_by_activity($this->quba->get_id(), $db);
734 protected function delete_quba() {
735 question_engine::delete_questions_usage_by_activity($this->quba->get_id());
739 protected function check_current_state($state) {
740 $this->assertEquals($state, $this->quba->get_question_state($this->slot),
741 'Questions is in the wrong state.');
744 protected function check_current_mark($mark) {
745 if (is_null($mark)) {
746 $this->assertNull($this->quba->get_question_mark($this->slot));
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));
753 $this->assertEquals($mark, $this->quba->get_question_mark($this->slot),
754 'Expected mark and actual mark differ.', 0.000001);
759 * Generate the HTML rendering of the question in its current state in
760 * $this->currentoutput so that it can be verified.
762 protected function render() {
763 $this->currentoutput = $this->quba->render_question($this->slot, $this->displayoptions);
766 protected function check_output_contains_text_input($name, $value = null, $enabled = true) {
769 'name' => $this->quba->get_field_prefix($this->slot) . $name,
771 if (!is_null($value)) {
772 $attributes['value'] = $value;
775 $attributes['readonly'] = 'readonly';
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);
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);
789 protected function check_output_contains_text_input_with_class($name, $class = null) {
792 'name' => $this->quba->get_field_prefix($this->slot) . $name,
794 if (!is_null($class)) {
795 $attributes['class'] = 'regexp:/\b' . $class . '\b/';
798 $matcher = $this->get_tag_matcher('input', $attributes);
799 $this->assertTag($matcher, $this->currentoutput,
800 'Looking for an input with attributes ' . html_writer::attributes($attributes) . ' in ' . $this->currentoutput);
803 protected function check_output_does_not_contain_text_input_with_class($name, $class = null) {
806 'name' => $this->quba->get_field_prefix($this->slot) . $name,
808 if (!is_null($class)) {
809 $attributes['class'] = 'regexp:/\b' . $class . '\b/';
812 $matcher = $this->get_tag_matcher('input', $attributes);
813 $this->assertNotTag($matcher, $this->currentoutput,
814 'Unexpected input with attributes ' . html_writer::attributes($attributes) . ' found in ' . $this->currentoutput);
817 protected function check_output_contains_hidden_input($name, $value) {
820 'name' => $this->quba->get_field_prefix($this->slot) . $name,
823 $this->assertTag($this->get_tag_matcher('input', $attributes), $this->currentoutput,
824 'Looking for a hidden input with attributes ' . html_writer::attributes($attributes) . ' in ' . $this->currentoutput);
827 protected function check_output_contains_lang_string($identifier, $component = '', $a = null) {
829 $string = get_string($identifier, $component, $a);
830 $this->assertContains($string, $this->currentoutput,
831 'Expected string ' . $string . ' not found in ' . $this->currentoutput);
834 protected function get_tag_matcher($tag, $attributes) {
837 'attributes' => $attributes,
842 * @param $condition one or more Expectations. (users varargs).
844 protected function check_current_output() {
845 $html = $this->quba->render_question($this->slot, $this->displayoptions);
846 foreach (func_get_args() as $condition) {
847 $this->assert($condition, $html);
851 protected function get_question_attempt() {
852 return $this->quba->get_question_attempt($this->slot);
855 protected function get_step_count() {
856 return $this->get_question_attempt()->get_num_steps();
859 protected function check_step_count($expectednumsteps) {
860 $this->assertEquals($expectednumsteps, $this->get_step_count());
863 protected function get_step($stepnum) {
864 return $this->get_question_attempt()->get_step($stepnum);
867 protected function get_contains_question_text_expectation($question) {
868 return new question_pattern_expectation('/' . preg_quote($question->questiontext, '/') . '/');
871 protected function get_contains_general_feedback_expectation($question) {
872 return new question_pattern_expectation('/' . preg_quote($question->generalfeedback, '/') . '/');
875 protected function get_does_not_contain_correctness_expectation() {
876 return new question_no_pattern_expectation('/class=\"correctness/');
879 protected function get_contains_correct_expectation() {
880 return new question_pattern_expectation('/' . preg_quote(get_string('correct', 'question'), '/') . '/');
883 protected function get_contains_partcorrect_expectation() {
884 return new question_pattern_expectation('/' .
885 preg_quote(get_string('partiallycorrect', 'question'), '/') . '/');
888 protected function get_contains_incorrect_expectation() {
889 return new question_pattern_expectation('/' . preg_quote(get_string('incorrect', 'question'), '/') . '/');
892 protected function get_contains_standard_correct_combined_feedback_expectation() {
893 return new question_pattern_expectation('/' .
894 preg_quote(test_question_maker::STANDARD_OVERALL_CORRECT_FEEDBACK, '/') . '/');
897 protected function get_contains_standard_partiallycorrect_combined_feedback_expectation() {
898 return new question_pattern_expectation('/' .
899 preg_quote(test_question_maker::STANDARD_OVERALL_PARTIALLYCORRECT_FEEDBACK, '/') . '/');
902 protected function get_contains_standard_incorrect_combined_feedback_expectation() {
903 return new question_pattern_expectation('/' .
904 preg_quote(test_question_maker::STANDARD_OVERALL_INCORRECT_FEEDBACK, '/') . '/');
907 protected function get_does_not_contain_feedback_expectation() {
908 return new question_no_pattern_expectation('/class="feedback"/');
911 protected function get_does_not_contain_num_parts_correct() {
912 return new question_no_pattern_expectation('/class="numpartscorrect"/');
915 protected function get_contains_num_parts_correct($num) {
918 return new question_pattern_expectation('/<div class="numpartscorrect">' .
919 preg_quote(get_string('yougotnright', 'question', $a), '/') . '/');
922 protected function get_does_not_contain_specific_feedback_expectation() {
923 return new question_no_pattern_expectation('/class="specificfeedback"/');
926 protected function get_contains_validation_error_expectation() {
927 return new question_contains_tag_with_attribute('div', 'class', 'validationerror');
930 protected function get_does_not_contain_validation_error_expectation() {
931 return new question_no_pattern_expectation('/class="validationerror"/');
934 protected function get_contains_mark_summary($mark) {
936 $a->mark = format_float($mark, $this->displayoptions->markdp);
937 $a->max = format_float($this->quba->get_question_max_mark($this->slot),
938 $this->displayoptions->markdp);
939 return new question_pattern_expectation('/' .
940 preg_quote(get_string('markoutofmax', 'question', $a), '/') . '/');
943 protected function get_contains_marked_out_of_summary() {
944 $max = format_float($this->quba->get_question_max_mark($this->slot),
945 $this->displayoptions->markdp);
946 return new question_pattern_expectation('/' .
947 preg_quote(get_string('markedoutofmax', 'question', $max), '/') . '/');
950 protected function get_does_not_contain_mark_summary() {
951 return new question_no_pattern_expectation('/<div class="grade">/');
954 protected function get_contains_checkbox_expectation($baseattr, $enabled, $checked) {
955 $expectedattributes = $baseattr;
956 $forbiddenattributes = array();
957 $expectedattributes['type'] = 'checkbox';
958 if ($enabled === true) {
959 $forbiddenattributes['disabled'] = 'disabled';
960 } else if ($enabled === false) {
961 $expectedattributes['disabled'] = 'disabled';
963 if ($checked === true) {
964 $expectedattributes['checked'] = 'checked';
965 } else if ($checked === false) {
966 $forbiddenattributes['checked'] = 'checked';
968 return new question_contains_tag_with_attributes('input', $expectedattributes, $forbiddenattributes);
971 protected function get_contains_mc_checkbox_expectation($index, $enabled = null,
973 return $this->get_contains_checkbox_expectation(array(
974 'name' => $this->quba->get_field_prefix($this->slot) . $index,
976 ), $enabled, $checked);
979 protected function get_contains_radio_expectation($baseattr, $enabled, $checked) {
980 $expectedattributes = $baseattr;
981 $forbiddenattributes = array();
982 $expectedattributes['type'] = 'radio';
983 if ($enabled === true) {
984 $forbiddenattributes['disabled'] = 'disabled';
985 } else if ($enabled === false) {
986 $expectedattributes['disabled'] = 'disabled';
988 if ($checked === true) {
989 $expectedattributes['checked'] = 'checked';
990 } else if ($checked === false) {
991 $forbiddenattributes['checked'] = 'checked';
993 return new question_contains_tag_with_attributes('input', $expectedattributes, $forbiddenattributes);
996 protected function get_contains_mc_radio_expectation($index, $enabled = null, $checked = null) {
997 return $this->get_contains_radio_expectation(array(
998 'name' => $this->quba->get_field_prefix($this->slot) . 'answer',
1000 ), $enabled, $checked);
1003 protected function get_contains_hidden_expectation($name, $value = null) {
1004 $expectedattributes = array('type' => 'hidden', 'name' => s($name));
1005 if (!is_null($value)) {
1006 $expectedattributes['value'] = s($value);
1008 return new question_contains_tag_with_attributes('input', $expectedattributes);
1011 protected function get_does_not_contain_hidden_expectation($name, $value = null) {
1012 $expectedattributes = array('type' => 'hidden', 'name' => s($name));
1013 if (!is_null($value)) {
1014 $expectedattributes['value'] = s($value);
1016 return new question_does_not_contain_tag_with_attributes('input', $expectedattributes);
1019 protected function get_contains_tf_true_radio_expectation($enabled = null, $checked = null) {
1020 return $this->get_contains_radio_expectation(array(
1021 'name' => $this->quba->get_field_prefix($this->slot) . 'answer',
1023 ), $enabled, $checked);
1026 protected function get_contains_tf_false_radio_expectation($enabled = null, $checked = null) {
1027 return $this->get_contains_radio_expectation(array(
1028 'name' => $this->quba->get_field_prefix($this->slot) . 'answer',
1030 ), $enabled, $checked);
1033 protected function get_contains_cbm_radio_expectation($certainty, $enabled = null,
1035 return $this->get_contains_radio_expectation(array(
1036 'name' => $this->quba->get_field_prefix($this->slot) . '-certainty',
1037 'value' => $certainty,
1038 ), $enabled, $checked);
1041 protected function get_contains_button_expectation($name, $value = null, $enabled = null) {
1042 $expectedattributes = array(
1046 $forbiddenattributes = array();
1047 if (!is_null($value)) {
1048 $expectedattributes['value'] = $value;
1050 if ($enabled === true) {
1051 $forbiddenattributes['disabled'] = 'disabled';
1052 } else if ($enabled === false) {
1053 $expectedattributes['disabled'] = 'disabled';
1055 return new question_contains_tag_with_attributes('input', $expectedattributes, $forbiddenattributes);
1058 protected function get_contains_submit_button_expectation($enabled = null) {
1059 return $this->get_contains_button_expectation(
1060 $this->quba->get_field_prefix($this->slot) . '-submit', null, $enabled);
1063 protected function get_tries_remaining_expectation($n) {
1064 return new question_pattern_expectation('/' .
1065 preg_quote(get_string('triesremaining', 'qbehaviour_interactive', $n), '/') . '/');
1068 protected function get_invalid_answer_expectation() {
1069 return new question_pattern_expectation('/' .
1070 preg_quote(get_string('invalidanswer', 'question'), '/') . '/');
1073 protected function get_contains_try_again_button_expectation($enabled = null) {
1074 $expectedattributes = array(
1076 'name' => $this->quba->get_field_prefix($this->slot) . '-tryagain',
1078 $forbiddenattributes = array();
1079 if ($enabled === true) {
1080 $forbiddenattributes['disabled'] = 'disabled';
1081 } else if ($enabled === false) {
1082 $expectedattributes['disabled'] = 'disabled';
1084 return new question_contains_tag_with_attributes('input', $expectedattributes, $forbiddenattributes);
1087 protected function get_does_not_contain_try_again_button_expectation() {
1088 return new question_no_pattern_expectation('/name="' .
1089 $this->quba->get_field_prefix($this->slot) . '-tryagain"/');
1092 protected function get_contains_select_expectation($name, $choices,
1093 $selected = null, $enabled = null) {
1094 $fullname = $this->quba->get_field_prefix($this->slot) . $name;
1095 return new question_contains_select_expectation($fullname, $choices, $selected, $enabled);
1098 protected function get_mc_right_answer_index($mc) {
1099 $order = $mc->get_order($this->get_question_attempt());
1100 foreach ($order as $i => $ansid) {
1101 if ($mc->answers[$ansid]->fraction == 1) {
1105 $this->fail('This multiple choice question does not seem to have a right answer!');
1108 protected function get_no_hint_visible_expectation() {
1109 return new question_no_pattern_expectation('/class="hint"/');
1112 protected function get_contains_hint_expectation($hinttext) {
1113 // Does not currently verify hint text.
1114 return new question_contains_tag_with_attribute('div', 'class', 'hint');
1119 * Simple class that implements the {@link moodle_recordset} API based on an
1120 * array of test data.
1122 * See the {@link question_attempt_step_db_test} class in
1123 * question/engine/tests/testquestionattemptstep.php for an example of how
1126 * @copyright 2011 The Open University
1127 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1129 class question_test_recordset extends moodle_recordset {
1134 * @param $table as for {@link testing_db_record_builder::build_db_records()}
1135 * but does not need a unique first column.
1137 public function __construct(array $table) {
1138 $columns = array_shift($table);
1139 $this->records = array();
1140 foreach ($table as $row) {
1141 if (count($row) != count($columns)) {
1142 throw new coding_exception("Row contains the wrong number of fields.");
1145 foreach ($columns as $i => $name) {
1146 $rec[$name] = $row[$i];
1148 $this->records[] = $rec;
1150 reset($this->records);
1153 public function __destruct() {
1157 public function current() {
1158 return (object) current($this->records);
1161 public function key() {
1162 if (is_null(key($this->records))) {
1165 $current = current($this->records);
1166 return reset($current);
1169 public function next() {
1170 next($this->records);
1173 public function valid() {
1174 return !is_null(key($this->records));
1177 public function close() {
1178 $this->records = null;