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(__DIR__ . '/../lib.php');
31 require_once($CFG->dirroot . '/lib/phpunit/lib.php');
35 * Makes some protected methods of question_attempt public to facilitate testing.
37 * @copyright 2009 The Open University
38 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
40 class testable_question_attempt extends question_attempt {
41 public function add_step(question_attempt_step $step) {
42 parent::add_step($step);
44 public function set_min_fraction($fraction) {
45 $this->minfraction = $fraction;
47 public function set_max_fraction($fraction) {
48 $this->maxfraction = $fraction;
50 public function set_behaviour(question_behaviour $behaviour) {
51 $this->behaviour = $behaviour;
57 * Test subclass to allow access to some protected data so that the correct
58 * behaviour can be verified.
60 * @copyright 2012 The Open University
61 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
63 class testable_question_engine_unit_of_work extends question_engine_unit_of_work {
64 public function get_modified() {
65 return $this->modified;
68 public function get_attempts_added() {
69 return $this->attemptsadded;
72 public function get_attempts_modified() {
73 return $this->attemptsmodified;
76 public function get_steps_added() {
77 return $this->stepsadded;
80 public function get_steps_modified() {
81 return $this->stepsmodified;
84 public function get_steps_deleted() {
85 return $this->stepsdeleted;
91 * Base class for question type test helpers.
93 * @copyright 2011 The Open University
94 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
96 abstract class question_test_helper {
98 * @return array of example question names that can be passed as the $which
99 * argument of {@link test_question_maker::make_question} when $qtype is
100 * this question type.
102 abstract public function get_test_questions();
105 * Set up a form to create a question in $cat. This method also sets cat and contextid on $questiondata object.
106 * @param object $cat the category
107 * @param object $questiondata form initialisation requires question data.
110 public static function get_question_editing_form($cat, $questiondata) {
111 $catcontext = context::instance_by_id($cat->contextid, MUST_EXIST);
112 $contexts = new question_edit_contexts($catcontext);
113 $dataforformconstructor = new stdClass();
114 $dataforformconstructor->qtype = $questiondata->qtype;
115 $dataforformconstructor->contextid = $questiondata->contextid = $catcontext->id;
116 $dataforformconstructor->category = $questiondata->category = $cat->id;
117 $dataforformconstructor->formoptions = new stdClass();
118 $dataforformconstructor->formoptions->canmove = true;
119 $dataforformconstructor->formoptions->cansaveasnew = true;
120 $dataforformconstructor->formoptions->canedit = true;
121 $dataforformconstructor->formoptions->repeatelements = true;
122 $qtype = question_bank::get_qtype($questiondata->qtype);
123 return $qtype->create_editing_form('question.php', $dataforformconstructor, $cat, $contexts, true);
129 * This class creates questions of various types, which can then be used when
132 * @copyright 2009 The Open University
133 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
135 class test_question_maker {
136 const STANDARD_OVERALL_CORRECT_FEEDBACK = 'Well done!';
137 const STANDARD_OVERALL_PARTIALLYCORRECT_FEEDBACK =
138 'Parts, but only parts, of your response are correct.';
139 const STANDARD_OVERALL_INCORRECT_FEEDBACK = 'That is not right at all.';
141 /** @var array qtype => qtype test helper class. */
142 protected static $testhelpers = array();
145 * Just make a question_attempt at a question. Useful for unit tests that
146 * need to pass a $qa to methods that call format_text. Probably not safe
147 * to use for anything beyond that.
148 * @param question_definition $question a question.
149 * @param number $maxmark the max mark to set.
150 * @return question_attempt the question attempt.
152 public static function get_a_qa($question, $maxmark = 3) {
153 return new question_attempt($question, 13, null, $maxmark);
157 * Initialise the common fields of a question of any type.
159 public static function initialise_a_question($q) {
165 $q->questiontextformat = FORMAT_HTML;
166 $q->generalfeedbackformat = FORMAT_HTML;
168 $q->penalty = 0.3333333;
170 $q->stamp = make_unique_id_code();
171 $q->version = make_unique_id_code();
173 $q->timecreated = time();
174 $q->timemodified = time();
175 $q->createdby = $USER->id;
176 $q->modifiedby = $USER->id;
179 public static function initialise_question_data($qdata) {
183 $qdata->category = 0;
184 $qdata->contextid = 0;
186 $qdata->questiontextformat = FORMAT_HTML;
187 $qdata->generalfeedbackformat = FORMAT_HTML;
188 $qdata->defaultmark = 1;
189 $qdata->penalty = 0.3333333;
191 $qdata->stamp = make_unique_id_code();
192 $qdata->version = make_unique_id_code();
194 $qdata->timecreated = time();
195 $qdata->timemodified = time();
196 $qdata->createdby = $USER->id;
197 $qdata->modifiedby = $USER->id;
198 $qdata->hints = array();
202 * Get the test helper class for a particular question type.
203 * @param $qtype the question type name, e.g. 'multichoice'.
204 * @return question_test_helper the test helper class.
206 public static function get_test_helper($qtype) {
209 if (array_key_exists($qtype, self::$testhelpers)) {
210 return self::$testhelpers[$qtype];
213 $file = core_component::get_plugin_directory('qtype', $qtype) . '/tests/helper.php';
214 if (!is_readable($file)) {
215 throw new coding_exception('Question type ' . $qtype .
216 ' does not have test helper code.');
220 $class = 'qtype_' . $qtype . '_test_helper';
221 if (!class_exists($class)) {
222 throw new coding_exception('Class ' . $class . ' is not defined in ' . $file);
225 self::$testhelpers[$qtype] = new $class();
226 return self::$testhelpers[$qtype];
230 * Call a method on a qtype_{$qtype}_test_helper class and return the result.
232 * @param string $methodtemplate e.g. 'make_{qtype}_question_{which}';
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 * @param unknown_type $which
238 protected static function call_question_helper_method($methodtemplate, $qtype, $which = null) {
239 $helper = self::get_test_helper($qtype);
241 $available = $helper->get_test_questions();
243 if (is_null($which)) {
244 $which = reset($available);
245 } else if (!in_array($which, $available)) {
246 throw new coding_exception('Example question ' . $which . ' of type ' .
247 $qtype . ' does not exist.');
250 $method = str_replace(array('{qtype}', '{which}'),
251 array($qtype, $which), $methodtemplate);
253 if (!method_exists($helper, $method)) {
254 throw new coding_exception('Method ' . $method . ' does not exist on the ' .
255 $qtype . ' question type test helper class.');
258 return $helper->$method();
262 * Question types can provide a number of test question defintions.
263 * They do this by creating a qtype_{$qtype}_test_helper class that extends
264 * question_test_helper. The get_test_questions method returns the list of
265 * test questions available for this question type.
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 question_definition the requested question object.
272 public static function make_question($qtype, $which = null) {
273 return self::call_question_helper_method('make_{qtype}_question_{which}',
278 * Like {@link make_question()} but returns the datastructure from
279 * get_question_options 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_data($qtype, $which = null) {
287 return self::call_question_helper_method('get_{qtype}_question_data_{which}',
292 * Like {@link make_question()} but returns the data what would be saved from
293 * the question editing form instead of the question_definition object.
295 * @param string $qtype the question type to get a test question for.
296 * @param string $which one of the names returned by the get_test_questions
297 * method of the relevant qtype_{$qtype}_test_helper class.
298 * @return stdClass the requested question object.
300 public static function get_question_form_data($qtype, $which = null) {
301 return self::call_question_helper_method('get_{qtype}_question_form_data_{which}',
306 * Makes a multichoice question with choices 'A', 'B' and 'C' shuffled. 'A'
307 * is correct, defaultmark 1.
308 * @return qtype_multichoice_single_question
310 public static function make_a_multichoice_single_question() {
311 question_bank::load_question_definition_classes('multichoice');
312 $mc = new qtype_multichoice_single_question();
313 self::initialise_a_question($mc);
314 $mc->name = 'Multi-choice question, single response';
315 $mc->questiontext = 'The answer is A.';
316 $mc->generalfeedback = 'You should have selected A.';
317 $mc->qtype = question_bank::get_qtype('multichoice');
319 $mc->shuffleanswers = 1;
320 $mc->answernumbering = 'abc';
322 $mc->answers = array(
323 13 => new question_answer(13, 'A', 1, 'A is right', FORMAT_HTML),
324 14 => new question_answer(14, 'B', -0.3333333, 'B is wrong', FORMAT_HTML),
325 15 => new question_answer(15, 'C', -0.3333333, 'C is wrong', FORMAT_HTML),
332 * Makes a multichoice question with choices 'A', 'B', 'C' and 'D' shuffled.
333 * 'A' and 'C' is correct, defaultmark 1.
334 * @return qtype_multichoice_multi_question
336 public static function make_a_multichoice_multi_question() {
337 question_bank::load_question_definition_classes('multichoice');
338 $mc = new qtype_multichoice_multi_question();
339 self::initialise_a_question($mc);
340 $mc->name = 'Multi-choice question, multiple response';
341 $mc->questiontext = 'The answer is A and C.';
342 $mc->generalfeedback = 'You should have selected A and C.';
343 $mc->qtype = question_bank::get_qtype('multichoice');
345 $mc->shuffleanswers = 1;
346 $mc->answernumbering = 'abc';
348 self::set_standard_combined_feedback_fields($mc);
350 $mc->answers = array(
351 13 => new question_answer(13, 'A', 0.5, 'A is part of the right answer', FORMAT_HTML),
352 14 => new question_answer(14, 'B', -1, 'B is wrong', FORMAT_HTML),
353 15 => new question_answer(15, 'C', 0.5, 'C is part of the right answer', FORMAT_HTML),
354 16 => new question_answer(16, 'D', -1, 'D is wrong', FORMAT_HTML),
361 * Makes a matching question to classify 'Dog', 'Frog', 'Toad' and 'Cat' as
362 * 'Mammal', 'Amphibian' or 'Insect'.
363 * defaultmark 1. Stems are shuffled by default.
364 * @return qtype_match_question
366 public static function make_a_matching_question() {
367 question_bank::load_question_definition_classes('match');
368 $match = new qtype_match_question();
369 self::initialise_a_question($match);
370 $match->name = 'Matching question';
371 $match->questiontext = 'Classify the animals.';
372 $match->generalfeedback = 'Frogs and toads are amphibians, the others are mammals.';
373 $match->qtype = question_bank::get_qtype('match');
375 $match->shufflestems = 1;
377 self::set_standard_combined_feedback_fields($match);
379 // Using unset to get 1-based arrays.
380 $match->stems = array('', 'Dog', 'Frog', 'Toad', 'Cat');
381 $match->stemformat = array('', FORMAT_HTML, FORMAT_HTML, FORMAT_HTML, FORMAT_HTML);
382 $match->choices = array('', 'Mammal', 'Amphibian', 'Insect');
383 $match->right = array('', 1, 2, 2, 1);
384 unset($match->stems[0]);
385 unset($match->stemformat[0]);
386 unset($match->choices[0]);
387 unset($match->right[0]);
393 * Makes a truefalse question with correct ansewer true, defaultmark 1.
394 * @return qtype_essay_question
396 public static function make_an_essay_question() {
397 question_bank::load_question_definition_classes('essay');
398 $essay = new qtype_essay_question();
399 self::initialise_a_question($essay);
400 $essay->name = 'Essay question';
401 $essay->questiontext = 'Write an essay.';
402 $essay->generalfeedback = 'I hope you wrote an interesting essay.';
404 $essay->qtype = question_bank::get_qtype('essay');
406 $essay->responseformat = 'editor';
407 $essay->responserequired = 1;
408 $essay->responsefieldlines = 15;
409 $essay->attachments = 0;
410 $essay->attachmentsrequired = 0;
411 $essay->responsetemplate = '';
412 $essay->responsetemplateformat = FORMAT_MOODLE;
413 $essay->graderinfo = '';
414 $essay->graderinfoformat = FORMAT_MOODLE;
420 * Add some standard overall feedback to a question. You need to use these
421 * specific feedback strings for the corresponding contains_..._feedback
422 * methods in {@link qbehaviour_walkthrough_test_base} to works.
423 * @param question_definition $q the question to add the feedback to.
425 public static function set_standard_combined_feedback_fields($q) {
426 $q->correctfeedback = self::STANDARD_OVERALL_CORRECT_FEEDBACK;
427 $q->correctfeedbackformat = FORMAT_HTML;
428 $q->partiallycorrectfeedback = self::STANDARD_OVERALL_PARTIALLYCORRECT_FEEDBACK;
429 $q->partiallycorrectfeedbackformat = FORMAT_HTML;
430 $q->shownumcorrect = true;
431 $q->incorrectfeedback = self::STANDARD_OVERALL_INCORRECT_FEEDBACK;
432 $q->incorrectfeedbackformat = FORMAT_HTML;
436 * Add some standard overall feedback to a question's form data.
438 public static function set_standard_combined_feedback_form_data($form) {
439 $form->correctfeedback = array('text' => self::STANDARD_OVERALL_CORRECT_FEEDBACK,
440 'format' => FORMAT_HTML);
441 $form->partiallycorrectfeedback = array('text' => self::STANDARD_OVERALL_PARTIALLYCORRECT_FEEDBACK,
442 'format' => FORMAT_HTML);
443 $form->shownumcorrect = true;
444 $form->incorrectfeedback = array('text' => self::STANDARD_OVERALL_INCORRECT_FEEDBACK,
445 'format' => FORMAT_HTML);
451 * Helper for tests that need to simulate records loaded from the database.
453 * @copyright 2009 The Open University
454 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
456 abstract class testing_db_record_builder {
457 public static function build_db_records(array $table) {
458 $columns = array_shift($table);
460 foreach ($table as $row) {
461 if (count($row) != count($columns)) {
462 throw new coding_exception("Row contains the wrong number of fields.");
464 $rec = new stdClass();
465 foreach ($columns as $i => $name) {
466 $rec->$name = $row[$i];
476 * Helper base class for tests that need to simulate records loaded from the
479 * @copyright 2009 The Open University
480 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
482 abstract class data_loading_method_test_base extends advanced_testcase {
483 public function build_db_records(array $table) {
484 return testing_db_record_builder::build_db_records($table);
489 abstract class question_testcase extends advanced_testcase {
491 public function assert($expectation, $compare, $notused = '') {
493 if (get_class($expectation) === 'question_pattern_expectation') {
494 $this->assertRegExp($expectation->pattern, $compare,
495 'Expected regex ' . $expectation->pattern . ' not found in ' . $compare);
498 } else if (get_class($expectation) === 'question_no_pattern_expectation') {
499 $this->assertNotRegExp($expectation->pattern, $compare,
500 'Unexpected regex ' . $expectation->pattern . ' found in ' . $compare);
503 } else if (get_class($expectation) === 'question_contains_tag_with_attributes') {
504 $this->assertTag(array('tag'=>$expectation->tag, 'attributes'=>$expectation->expectedvalues), $compare,
505 'Looking for a ' . $expectation->tag . ' with attributes ' . html_writer::attributes($expectation->expectedvalues) . ' in ' . $compare);
506 foreach ($expectation->forbiddenvalues as $k=>$v) {
507 $attr = $expectation->expectedvalues;
509 $this->assertNotTag(array('tag'=>$expectation->tag, 'attributes'=>$attr), $compare,
510 $expectation->tag . ' had a ' . $k . ' attribute that should not be there in ' . $compare);
514 } else if (get_class($expectation) === 'question_contains_tag_with_attribute') {
515 $attr = array($expectation->attribute=>$expectation->value);
516 $this->assertTag(array('tag'=>$expectation->tag, 'attributes'=>$attr), $compare,
517 'Looking for a ' . $expectation->tag . ' with attribute ' . html_writer::attributes($attr) . ' in ' . $compare);
520 } else if (get_class($expectation) === 'question_does_not_contain_tag_with_attributes') {
521 $this->assertNotTag(array('tag'=>$expectation->tag, 'attributes'=>$expectation->attributes), $compare,
522 'Unexpected ' . $expectation->tag . ' with attributes ' . html_writer::attributes($expectation->attributes) . ' found in ' . $compare);
525 } else if (get_class($expectation) === 'question_contains_select_expectation') {
526 $tag = array('tag'=>'select', 'attributes'=>array('name'=>$expectation->name),
527 'children'=>array('count'=>count($expectation->choices)));
528 if ($expectation->enabled === false) {
529 $tag['attributes']['disabled'] = 'disabled';
530 } else if ($expectation->enabled === true) {
533 foreach(array_keys($expectation->choices) as $value) {
534 if ($expectation->selected === $value) {
535 $tag['child'] = array('tag'=>'option', 'attributes'=>array('value'=>$value, 'selected'=>'selected'));
537 $tag['child'] = array('tag'=>'option', 'attributes'=>array('value'=>$value));
541 $this->assertTag($tag, $compare, 'expected select not found in ' . $compare);
544 } else if (get_class($expectation) === 'question_check_specified_fields_expectation') {
545 $expect = (array)$expectation->expect;
546 $compare = (array)$compare;
547 foreach ($expect as $k=>$v) {
548 if (!array_key_exists($k, $compare)) {
549 $this->fail("Property {$k} does not exist");
551 if ($v != $compare[$k]) {
552 $this->fail("Property {$k} is different");
555 $this->assertTrue(true);
558 } else if (get_class($expectation) === 'question_contains_tag_with_contents') {
559 $this->assertTag(array('tag'=>$expectation->tag, 'content'=>$expectation->content), $compare,
560 'Looking for a ' . $expectation->tag . ' with content ' . $expectation->content . ' in ' . $compare);
564 throw new coding_exception('Unknown expectiontion:'.get_class($expectation));
569 class question_contains_tag_with_contents {
574 public function __construct($tag, $content, $message = '') {
576 $this->content = $content;
577 $this->message = $message;
582 class question_check_specified_fields_expectation {
586 function __construct($expected, $message = '') {
587 $this->expect = $expected;
588 $this->message = $message;
593 class question_contains_select_expectation {
600 public function __construct($name, $choices, $selected = null, $enabled = null, $message = '') {
602 $this->choices = $choices;
603 $this->selected = $selected;
604 $this->enabled = $enabled;
605 $this->message = $message;
610 class question_does_not_contain_tag_with_attributes {
615 public function __construct($tag, $attributes, $message = '') {
617 $this->attributes = $attributes;
618 $this->message = $message;
623 class question_contains_tag_with_attribute {
629 public function __construct($tag, $attribute, $value, $message = '') {
631 $this->attribute = $attribute;
632 $this->value = $value;
633 $this->message = $message;
638 class question_contains_tag_with_attributes {
640 public $expectedvalues = array();
641 public $forbiddenvalues = array();
644 public function __construct($tag, $expectedvalues, $forbiddenvalues=array(), $message = '') {
646 $this->expectedvalues = $expectedvalues;
647 $this->forbiddenvalues = $forbiddenvalues;
648 $this->message = $message;
653 class question_pattern_expectation {
657 public function __construct($pattern, $message = '') {
658 $this->pattern = $pattern;
659 $this->message = $message;
664 class question_no_pattern_expectation {
668 public function __construct($pattern, $message = '') {
669 $this->pattern = $pattern;
670 $this->message = $message;
676 * Helper base class for tests that walk a question through a sequents of
677 * interactions under the control of a particular behaviour.
679 * @copyright 2009 The Open University
680 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
682 abstract class qbehaviour_walkthrough_test_base extends question_testcase {
683 /** @var question_display_options */
684 protected $displayoptions;
685 /** @var question_usage_by_activity */
691 * @var string after {@link render()} has been called, this contains the
692 * display of the question in its current state.
694 protected $currentoutput = '';
696 protected function setUp() {
698 $this->resetAfterTest(true);
700 $this->displayoptions = new question_display_options();
701 $this->quba = question_engine::make_questions_usage_by_activity('unit_test',
702 context_system::instance());
705 protected function tearDown() {
706 $this->displayoptions = null;
711 protected function start_attempt_at_question($question, $preferredbehaviour,
712 $maxmark = null, $variant = 1) {
713 $this->quba->set_preferred_behaviour($preferredbehaviour);
714 $this->slot = $this->quba->add_question($question, $maxmark);
715 $this->quba->start_question($this->slot, $variant);
719 * Convert an array of data destined for one question to the equivalent POST data.
720 * @param array $data the data for the quetsion.
721 * @return array the complete post data.
723 protected function response_data_to_post($data) {
724 $prefix = $this->quba->get_field_prefix($this->slot);
726 'slots' => $this->slot,
727 $prefix . ':sequencecheck' => $this->get_question_attempt()->get_sequence_check_count(),
729 foreach ($data as $name => $value) {
730 $fulldata[$prefix . $name] = $value;
735 protected function process_submission($data) {
736 // Backwards compatibility.
738 if (count($data) == 1 && key($data) === '-finish') {
742 $this->quba->process_all_actions(time(), $this->response_data_to_post($data));
745 protected function process_autosave($data) {
746 $this->quba->process_all_autosaves(null, $this->response_data_to_post($data));
749 protected function finish() {
750 $this->quba->finish_all_questions();
753 protected function manual_grade($comment, $mark, $commentformat = null) {
754 $this->quba->manual_grade($this->slot, $comment, $mark, $commentformat);
757 protected function save_quba(moodle_database $db = null) {
758 question_engine::save_questions_usage_by_activity($this->quba, $db);
761 protected function load_quba(moodle_database $db = null) {
762 $this->quba = question_engine::load_questions_usage_by_activity($this->quba->get_id(), $db);
765 protected function delete_quba() {
766 question_engine::delete_questions_usage_by_activity($this->quba->get_id());
770 protected function check_current_state($state) {
771 $this->assertEquals($state, $this->quba->get_question_state($this->slot),
772 'Questions is in the wrong state.');
775 protected function check_current_mark($mark) {
776 if (is_null($mark)) {
777 $this->assertNull($this->quba->get_question_mark($this->slot));
780 // PHP will think a null mark and a mark of 0 are equal,
781 // so explicity check not null in this case.
782 $this->assertNotNull($this->quba->get_question_mark($this->slot));
784 $this->assertEquals($mark, $this->quba->get_question_mark($this->slot),
785 'Expected mark and actual mark differ.', 0.000001);
790 * Generate the HTML rendering of the question in its current state in
791 * $this->currentoutput so that it can be verified.
793 protected function render() {
794 $this->currentoutput = $this->quba->render_question($this->slot, $this->displayoptions);
797 protected function check_output_contains_text_input($name, $value = null, $enabled = true) {
800 'name' => $this->quba->get_field_prefix($this->slot) . $name,
802 if (!is_null($value)) {
803 $attributes['value'] = $value;
806 $attributes['readonly'] = 'readonly';
808 $matcher = $this->get_tag_matcher('input', $attributes);
809 $this->assertTag($matcher, $this->currentoutput,
810 'Looking for an input with attributes ' . html_writer::attributes($attributes) . ' in ' . $this->currentoutput);
813 $matcher['attributes']['readonly'] = 'readonly';
814 $this->assertNotTag($matcher, $this->currentoutput,
815 'input with attributes ' . html_writer::attributes($attributes) .
816 ' should not be read-only in ' . $this->currentoutput);
820 protected function check_output_contains_text_input_with_class($name, $class = null) {
823 'name' => $this->quba->get_field_prefix($this->slot) . $name,
825 if (!is_null($class)) {
826 $attributes['class'] = 'regexp:/\b' . $class . '\b/';
829 $matcher = $this->get_tag_matcher('input', $attributes);
830 $this->assertTag($matcher, $this->currentoutput,
831 'Looking for an input with attributes ' . html_writer::attributes($attributes) . ' in ' . $this->currentoutput);
834 protected function check_output_does_not_contain_text_input_with_class($name, $class = null) {
837 'name' => $this->quba->get_field_prefix($this->slot) . $name,
839 if (!is_null($class)) {
840 $attributes['class'] = 'regexp:/\b' . $class . '\b/';
843 $matcher = $this->get_tag_matcher('input', $attributes);
844 $this->assertNotTag($matcher, $this->currentoutput,
845 'Unexpected input with attributes ' . html_writer::attributes($attributes) . ' found in ' . $this->currentoutput);
848 protected function check_output_contains_hidden_input($name, $value) {
851 'name' => $this->quba->get_field_prefix($this->slot) . $name,
854 $this->assertTag($this->get_tag_matcher('input', $attributes), $this->currentoutput,
855 'Looking for a hidden input with attributes ' . html_writer::attributes($attributes) . ' in ' . $this->currentoutput);
858 protected function check_output_contains($string) {
860 $this->assertContains($string, $this->currentoutput,
861 'Expected string ' . $string . ' not found in ' . $this->currentoutput);
864 protected function check_output_does_not_contain($string) {
866 $this->assertNotContains($string, $this->currentoutput,
867 'String ' . $string . ' unexpectedly found in ' . $this->currentoutput);
870 protected function check_output_contains_lang_string($identifier, $component = '', $a = null) {
871 $this->check_output_contains(get_string($identifier, $component, $a));
874 protected function get_tag_matcher($tag, $attributes) {
877 'attributes' => $attributes,
882 * @param $condition one or more Expectations. (users varargs).
884 protected function check_current_output() {
885 $html = $this->quba->render_question($this->slot, $this->displayoptions);
886 foreach (func_get_args() as $condition) {
887 $this->assert($condition, $html);
891 protected function get_question_attempt() {
892 return $this->quba->get_question_attempt($this->slot);
895 protected function get_step_count() {
896 return $this->get_question_attempt()->get_num_steps();
899 protected function check_step_count($expectednumsteps) {
900 $this->assertEquals($expectednumsteps, $this->get_step_count());
903 protected function get_step($stepnum) {
904 return $this->get_question_attempt()->get_step($stepnum);
907 protected function get_contains_question_text_expectation($question) {
908 return new question_pattern_expectation('/' . preg_quote($question->questiontext, '/') . '/');
911 protected function get_contains_general_feedback_expectation($question) {
912 return new question_pattern_expectation('/' . preg_quote($question->generalfeedback, '/') . '/');
915 protected function get_does_not_contain_correctness_expectation() {
916 return new question_no_pattern_expectation('/class=\"correctness/');
919 protected function get_contains_correct_expectation() {
920 return new question_pattern_expectation('/' . preg_quote(get_string('correct', 'question'), '/') . '/');
923 protected function get_contains_partcorrect_expectation() {
924 return new question_pattern_expectation('/' .
925 preg_quote(get_string('partiallycorrect', 'question'), '/') . '/');
928 protected function get_contains_incorrect_expectation() {
929 return new question_pattern_expectation('/' . preg_quote(get_string('incorrect', 'question'), '/') . '/');
932 protected function get_contains_standard_correct_combined_feedback_expectation() {
933 return new question_pattern_expectation('/' .
934 preg_quote(test_question_maker::STANDARD_OVERALL_CORRECT_FEEDBACK, '/') . '/');
937 protected function get_contains_standard_partiallycorrect_combined_feedback_expectation() {
938 return new question_pattern_expectation('/' .
939 preg_quote(test_question_maker::STANDARD_OVERALL_PARTIALLYCORRECT_FEEDBACK, '/') . '/');
942 protected function get_contains_standard_incorrect_combined_feedback_expectation() {
943 return new question_pattern_expectation('/' .
944 preg_quote(test_question_maker::STANDARD_OVERALL_INCORRECT_FEEDBACK, '/') . '/');
947 protected function get_does_not_contain_feedback_expectation() {
948 return new question_no_pattern_expectation('/class="feedback"/');
951 protected function get_does_not_contain_num_parts_correct() {
952 return new question_no_pattern_expectation('/class="numpartscorrect"/');
955 protected function get_contains_num_parts_correct($num) {
958 return new question_pattern_expectation('/<div class="numpartscorrect">' .
959 preg_quote(get_string('yougotnright', 'question', $a), '/') . '/');
962 protected function get_does_not_contain_specific_feedback_expectation() {
963 return new question_no_pattern_expectation('/class="specificfeedback"/');
966 protected function get_contains_validation_error_expectation() {
967 return new question_contains_tag_with_attribute('div', 'class', 'validationerror');
970 protected function get_does_not_contain_validation_error_expectation() {
971 return new question_no_pattern_expectation('/class="validationerror"/');
974 protected function get_contains_mark_summary($mark) {
976 $a->mark = format_float($mark, $this->displayoptions->markdp);
977 $a->max = format_float($this->quba->get_question_max_mark($this->slot),
978 $this->displayoptions->markdp);
979 return new question_pattern_expectation('/' .
980 preg_quote(get_string('markoutofmax', 'question', $a), '/') . '/');
983 protected function get_contains_marked_out_of_summary() {
984 $max = format_float($this->quba->get_question_max_mark($this->slot),
985 $this->displayoptions->markdp);
986 return new question_pattern_expectation('/' .
987 preg_quote(get_string('markedoutofmax', 'question', $max), '/') . '/');
990 protected function get_does_not_contain_mark_summary() {
991 return new question_no_pattern_expectation('/<div class="grade">/');
994 protected function get_contains_checkbox_expectation($baseattr, $enabled, $checked) {
995 $expectedattributes = $baseattr;
996 $forbiddenattributes = array();
997 $expectedattributes['type'] = 'checkbox';
998 if ($enabled === true) {
999 $forbiddenattributes['disabled'] = 'disabled';
1000 } else if ($enabled === false) {
1001 $expectedattributes['disabled'] = 'disabled';
1003 if ($checked === true) {
1004 $expectedattributes['checked'] = 'checked';
1005 } else if ($checked === false) {
1006 $forbiddenattributes['checked'] = 'checked';
1008 return new question_contains_tag_with_attributes('input', $expectedattributes, $forbiddenattributes);
1011 protected function get_contains_mc_checkbox_expectation($index, $enabled = null,
1013 return $this->get_contains_checkbox_expectation(array(
1014 'name' => $this->quba->get_field_prefix($this->slot) . $index,
1016 ), $enabled, $checked);
1019 protected function get_contains_radio_expectation($baseattr, $enabled, $checked) {
1020 $expectedattributes = $baseattr;
1021 $forbiddenattributes = array();
1022 $expectedattributes['type'] = 'radio';
1023 if ($enabled === true) {
1024 $forbiddenattributes['disabled'] = 'disabled';
1025 } else if ($enabled === false) {
1026 $expectedattributes['disabled'] = 'disabled';
1028 if ($checked === true) {
1029 $expectedattributes['checked'] = 'checked';
1030 } else if ($checked === false) {
1031 $forbiddenattributes['checked'] = 'checked';
1033 return new question_contains_tag_with_attributes('input', $expectedattributes, $forbiddenattributes);
1036 protected function get_contains_mc_radio_expectation($index, $enabled = null, $checked = null) {
1037 return $this->get_contains_radio_expectation(array(
1038 'name' => $this->quba->get_field_prefix($this->slot) . 'answer',
1040 ), $enabled, $checked);
1043 protected function get_contains_hidden_expectation($name, $value = null) {
1044 $expectedattributes = array('type' => 'hidden', 'name' => s($name));
1045 if (!is_null($value)) {
1046 $expectedattributes['value'] = s($value);
1048 return new question_contains_tag_with_attributes('input', $expectedattributes);
1051 protected function get_does_not_contain_hidden_expectation($name, $value = null) {
1052 $expectedattributes = array('type' => 'hidden', 'name' => s($name));
1053 if (!is_null($value)) {
1054 $expectedattributes['value'] = s($value);
1056 return new question_does_not_contain_tag_with_attributes('input', $expectedattributes);
1059 protected function get_contains_tf_true_radio_expectation($enabled = null, $checked = null) {
1060 return $this->get_contains_radio_expectation(array(
1061 'name' => $this->quba->get_field_prefix($this->slot) . 'answer',
1063 ), $enabled, $checked);
1066 protected function get_contains_tf_false_radio_expectation($enabled = null, $checked = null) {
1067 return $this->get_contains_radio_expectation(array(
1068 'name' => $this->quba->get_field_prefix($this->slot) . 'answer',
1070 ), $enabled, $checked);
1073 protected function get_contains_cbm_radio_expectation($certainty, $enabled = null,
1075 return $this->get_contains_radio_expectation(array(
1076 'name' => $this->quba->get_field_prefix($this->slot) . '-certainty',
1077 'value' => $certainty,
1078 ), $enabled, $checked);
1081 protected function get_contains_button_expectation($name, $value = null, $enabled = null) {
1082 $expectedattributes = array(
1086 $forbiddenattributes = array();
1087 if (!is_null($value)) {
1088 $expectedattributes['value'] = $value;
1090 if ($enabled === true) {
1091 $forbiddenattributes['disabled'] = 'disabled';
1092 } else if ($enabled === false) {
1093 $expectedattributes['disabled'] = 'disabled';
1095 return new question_contains_tag_with_attributes('input', $expectedattributes, $forbiddenattributes);
1098 protected function get_contains_submit_button_expectation($enabled = null) {
1099 return $this->get_contains_button_expectation(
1100 $this->quba->get_field_prefix($this->slot) . '-submit', null, $enabled);
1103 protected function get_tries_remaining_expectation($n) {
1104 return new question_pattern_expectation('/' .
1105 preg_quote(get_string('triesremaining', 'qbehaviour_interactive', $n), '/') . '/');
1108 protected function get_invalid_answer_expectation() {
1109 return new question_pattern_expectation('/' .
1110 preg_quote(get_string('invalidanswer', 'question'), '/') . '/');
1113 protected function get_contains_try_again_button_expectation($enabled = null) {
1114 $expectedattributes = array(
1116 'name' => $this->quba->get_field_prefix($this->slot) . '-tryagain',
1118 $forbiddenattributes = array();
1119 if ($enabled === true) {
1120 $forbiddenattributes['disabled'] = 'disabled';
1121 } else if ($enabled === false) {
1122 $expectedattributes['disabled'] = 'disabled';
1124 return new question_contains_tag_with_attributes('input', $expectedattributes, $forbiddenattributes);
1127 protected function get_does_not_contain_try_again_button_expectation() {
1128 return new question_no_pattern_expectation('/name="' .
1129 $this->quba->get_field_prefix($this->slot) . '-tryagain"/');
1132 protected function get_contains_select_expectation($name, $choices,
1133 $selected = null, $enabled = null) {
1134 $fullname = $this->quba->get_field_prefix($this->slot) . $name;
1135 return new question_contains_select_expectation($fullname, $choices, $selected, $enabled);
1138 protected function get_mc_right_answer_index($mc) {
1139 $order = $mc->get_order($this->get_question_attempt());
1140 foreach ($order as $i => $ansid) {
1141 if ($mc->answers[$ansid]->fraction == 1) {
1145 $this->fail('This multiple choice question does not seem to have a right answer!');
1148 protected function get_no_hint_visible_expectation() {
1149 return new question_no_pattern_expectation('/class="hint"/');
1152 protected function get_contains_hint_expectation($hinttext) {
1153 // Does not currently verify hint text.
1154 return new question_contains_tag_with_attribute('div', 'class', 'hint');
1159 * Simple class that implements the {@link moodle_recordset} API based on an
1160 * array of test data.
1162 * See the {@link question_attempt_step_db_test} class in
1163 * question/engine/tests/testquestionattemptstep.php for an example of how
1166 * @copyright 2011 The Open University
1167 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1169 class question_test_recordset extends moodle_recordset {
1174 * @param $table as for {@link testing_db_record_builder::build_db_records()}
1175 * but does not need a unique first column.
1177 public function __construct(array $table) {
1178 $columns = array_shift($table);
1179 $this->records = array();
1180 foreach ($table as $row) {
1181 if (count($row) != count($columns)) {
1182 throw new coding_exception("Row contains the wrong number of fields.");
1185 foreach ($columns as $i => $name) {
1186 $rec[$name] = $row[$i];
1188 $this->records[] = $rec;
1190 reset($this->records);
1193 public function __destruct() {
1197 public function current() {
1198 return (object) current($this->records);
1201 public function key() {
1202 if (is_null(key($this->records))) {
1205 $current = current($this->records);
1206 return reset($current);
1209 public function next() {
1210 next($this->records);
1213 public function valid() {
1214 return !is_null(key($this->records));
1217 public function close() {
1218 $this->records = null;