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();
101 * Set up a form to create a question in $cat. This method also sets cat and contextid on $questiondata object.
102 * @param object $cat the category
103 * @param object $questiondata form initialisation requires question data.
106 public static function get_question_editing_form($cat, $questiondata) {
107 $catcontext = context::instance_by_id($cat->contextid, MUST_EXIST);
108 $contexts = new question_edit_contexts($catcontext);
109 $dataforformconstructor = new stdClass();
110 $dataforformconstructor->qtype = $questiondata->qtype;
111 $dataforformconstructor->contextid = $questiondata->contextid = $catcontext->id;
112 $dataforformconstructor->category = $questiondata->category = $cat->id;
113 $dataforformconstructor->formoptions = new stdClass();
114 $dataforformconstructor->formoptions->canmove = true;
115 $dataforformconstructor->formoptions->cansaveasnew = true;
116 $dataforformconstructor->formoptions->movecontext = false;
117 $dataforformconstructor->formoptions->canedit = true;
118 $dataforformconstructor->formoptions->repeatelements = true;
119 $qtype = question_bank::get_qtype($questiondata->qtype);
120 return $qtype->create_editing_form('question.php', $dataforformconstructor, $cat, $contexts, true);
126 * This class creates questions of various types, which can then be used when
129 * @copyright 2009 The Open University
130 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
132 class test_question_maker {
133 const STANDARD_OVERALL_CORRECT_FEEDBACK = 'Well done!';
134 const STANDARD_OVERALL_PARTIALLYCORRECT_FEEDBACK =
135 'Parts, but only parts, of your response are correct.';
136 const STANDARD_OVERALL_INCORRECT_FEEDBACK = 'That is not right at all.';
138 /** @var array qtype => qtype test helper class. */
139 protected static $testhelpers = array();
142 * Just make a question_attempt at a question. Useful for unit tests that
143 * need to pass a $qa to methods that call format_text. Probably not safe
144 * to use for anything beyond that.
145 * @param question_definition $question a question.
146 * @param number $maxmark the max mark to set.
147 * @return question_attempt the question attempt.
149 public static function get_a_qa($question, $maxmark = 3) {
150 return new question_attempt($question, 13, null, $maxmark);
154 * Initialise the common fields of a question of any type.
156 public static function initialise_a_question($q) {
162 $q->questiontextformat = FORMAT_HTML;
163 $q->generalfeedbackformat = FORMAT_HTML;
165 $q->penalty = 0.3333333;
167 $q->stamp = make_unique_id_code();
168 $q->version = make_unique_id_code();
170 $q->timecreated = time();
171 $q->timemodified = time();
172 $q->createdby = $USER->id;
173 $q->modifiedby = $USER->id;
176 public static function initialise_question_data($qdata) {
180 $qdata->category = 0;
181 $qdata->contextid = 0;
183 $qdata->questiontextformat = FORMAT_HTML;
184 $qdata->generalfeedbackformat = FORMAT_HTML;
185 $qdata->defaultmark = 1;
186 $qdata->penalty = 0.3333333;
188 $qdata->stamp = make_unique_id_code();
189 $qdata->version = make_unique_id_code();
191 $qdata->timecreated = time();
192 $qdata->timemodified = time();
193 $qdata->createdby = $USER->id;
194 $qdata->modifiedby = $USER->id;
195 $qdata->hints = array();
199 * Get the test helper class for a particular question type.
200 * @param $qtype the question type name, e.g. 'multichoice'.
201 * @return question_test_helper the test helper class.
203 public static function get_test_helper($qtype) {
206 if (array_key_exists($qtype, self::$testhelpers)) {
207 return self::$testhelpers[$qtype];
210 $file = core_component::get_plugin_directory('qtype', $qtype) . '/tests/helper.php';
211 if (!is_readable($file)) {
212 throw new coding_exception('Question type ' . $qtype .
213 ' does not have test helper code.');
217 $class = 'qtype_' . $qtype . '_test_helper';
218 if (!class_exists($class)) {
219 throw new coding_exception('Class ' . $class . ' is not defined in ' . $file);
222 self::$testhelpers[$qtype] = new $class();
223 return self::$testhelpers[$qtype];
227 * Call a method on a qtype_{$qtype}_test_helper class and return the result.
229 * @param string $methodtemplate e.g. 'make_{qtype}_question_{which}';
230 * @param string $qtype the question type to get a test question for.
231 * @param string $which one of the names returned by the get_test_questions
232 * method of the relevant qtype_{$qtype}_test_helper class.
233 * @param unknown_type $which
235 protected static function call_question_helper_method($methodtemplate, $qtype, $which = null) {
236 $helper = self::get_test_helper($qtype);
238 $available = $helper->get_test_questions();
240 if (is_null($which)) {
241 $which = reset($available);
242 } else if (!in_array($which, $available)) {
243 throw new coding_exception('Example question ' . $which . ' of type ' .
244 $qtype . ' does not exist.');
247 $method = str_replace(array('{qtype}', '{which}'),
248 array($qtype, $which), $methodtemplate);
250 if (!method_exists($helper, $method)) {
251 throw new coding_exception('Method ' . $method . ' does not exist on the' .
252 $qtype . ' question type test helper class.');
255 return $helper->$method();
259 * Question types can provide a number of test question defintions.
260 * They do this by creating a qtype_{$qtype}_test_helper class that extends
261 * question_test_helper. The get_test_questions method returns the list of
262 * test questions available for this question type.
264 * @param string $qtype the question type to get a test question for.
265 * @param string $which one of the names returned by the get_test_questions
266 * method of the relevant qtype_{$qtype}_test_helper class.
267 * @return question_definition the requested question object.
269 public static function make_question($qtype, $which = null) {
270 return self::call_question_helper_method('make_{qtype}_question_{which}',
275 * Like {@link make_question()} but returns the datastructure from
276 * get_question_options instead of the question_definition object.
278 * @param string $qtype the question type to get a test question for.
279 * @param string $which one of the names returned by the get_test_questions
280 * method of the relevant qtype_{$qtype}_test_helper class.
281 * @return stdClass the requested question object.
283 public static function get_question_data($qtype, $which = null) {
284 return self::call_question_helper_method('get_{qtype}_question_data_{which}',
289 * Like {@link make_question()} but returns the data what would be saved from
290 * the question editing form instead of the question_definition object.
292 * @param string $qtype the question type to get a test question for.
293 * @param string $which one of the names returned by the get_test_questions
294 * method of the relevant qtype_{$qtype}_test_helper class.
295 * @return stdClass the requested question object.
297 public static function get_question_form_data($qtype, $which = null) {
298 return self::call_question_helper_method('get_{qtype}_question_form_data_{which}',
303 * Makes a multichoice question with choices 'A', 'B' and 'C' shuffled. 'A'
304 * is correct, defaultmark 1.
305 * @return qtype_multichoice_single_question
307 public static function make_a_multichoice_single_question() {
308 question_bank::load_question_definition_classes('multichoice');
309 $mc = new qtype_multichoice_single_question();
310 self::initialise_a_question($mc);
311 $mc->name = 'Multi-choice question, single response';
312 $mc->questiontext = 'The answer is A.';
313 $mc->generalfeedback = 'You should have selected A.';
314 $mc->qtype = question_bank::get_qtype('multichoice');
316 $mc->shuffleanswers = 1;
317 $mc->answernumbering = 'abc';
319 $mc->answers = array(
320 13 => new question_answer(13, 'A', 1, 'A is right', FORMAT_HTML),
321 14 => new question_answer(14, 'B', -0.3333333, 'B is wrong', FORMAT_HTML),
322 15 => new question_answer(15, 'C', -0.3333333, 'C is wrong', FORMAT_HTML),
329 * Makes a multichoice question with choices 'A', 'B', 'C' and 'D' shuffled.
330 * 'A' and 'C' is correct, defaultmark 1.
331 * @return qtype_multichoice_multi_question
333 public static function make_a_multichoice_multi_question() {
334 question_bank::load_question_definition_classes('multichoice');
335 $mc = new qtype_multichoice_multi_question();
336 self::initialise_a_question($mc);
337 $mc->name = 'Multi-choice question, multiple response';
338 $mc->questiontext = 'The answer is A and C.';
339 $mc->generalfeedback = 'You should have selected A and C.';
340 $mc->qtype = question_bank::get_qtype('multichoice');
342 $mc->shuffleanswers = 1;
343 $mc->answernumbering = 'abc';
345 self::set_standard_combined_feedback_fields($mc);
347 $mc->answers = array(
348 13 => new question_answer(13, 'A', 0.5, 'A is part of the right answer', FORMAT_HTML),
349 14 => new question_answer(14, 'B', -1, 'B is wrong', FORMAT_HTML),
350 15 => new question_answer(15, 'C', 0.5, 'C is part of the right answer', FORMAT_HTML),
351 16 => new question_answer(16, 'D', -1, 'D is wrong', FORMAT_HTML),
358 * Makes a matching question to classify 'Dog', 'Frog', 'Toad' and 'Cat' as
359 * 'Mammal', 'Amphibian' or 'Insect'.
360 * defaultmark 1. Stems are shuffled by default.
361 * @return qtype_match_question
363 public static function make_a_matching_question() {
364 question_bank::load_question_definition_classes('match');
365 $match = new qtype_match_question();
366 self::initialise_a_question($match);
367 $match->name = 'Matching question';
368 $match->questiontext = 'Classify the animals.';
369 $match->generalfeedback = 'Frogs and toads are amphibians, the others are mammals.';
370 $match->qtype = question_bank::get_qtype('match');
372 $match->shufflestems = 1;
374 self::set_standard_combined_feedback_fields($match);
376 // Using unset to get 1-based arrays.
377 $match->stems = array('', 'Dog', 'Frog', 'Toad', 'Cat');
378 $match->stemformat = array('', FORMAT_HTML, FORMAT_HTML, FORMAT_HTML, FORMAT_HTML);
379 $match->choices = array('', 'Mammal', 'Amphibian', 'Insect');
380 $match->right = array('', 1, 2, 2, 1);
381 unset($match->stems[0]);
382 unset($match->stemformat[0]);
383 unset($match->choices[0]);
384 unset($match->right[0]);
390 * Makes a truefalse question with correct ansewer true, defaultmark 1.
391 * @return qtype_essay_question
393 public static function make_an_essay_question() {
394 question_bank::load_question_definition_classes('essay');
395 $essay = new qtype_essay_question();
396 self::initialise_a_question($essay);
397 $essay->name = 'Essay question';
398 $essay->questiontext = 'Write an essay.';
399 $essay->generalfeedback = 'I hope you wrote an interesting essay.';
401 $essay->qtype = question_bank::get_qtype('essay');
403 $essay->responseformat = 'editor';
404 $essay->responsefieldlines = 15;
405 $essay->attachments = 0;
406 $essay->graderinfo = '';
407 $essay->graderinfoformat = FORMAT_MOODLE;
413 * Add some standard overall feedback to a question. You need to use these
414 * specific feedback strings for the corresponding contains_..._feedback
415 * methods in {@link qbehaviour_walkthrough_test_base} to works.
416 * @param question_definition $q the question to add the feedback to.
418 public static function set_standard_combined_feedback_fields($q) {
419 $q->correctfeedback = self::STANDARD_OVERALL_CORRECT_FEEDBACK;
420 $q->correctfeedbackformat = FORMAT_HTML;
421 $q->partiallycorrectfeedback = self::STANDARD_OVERALL_PARTIALLYCORRECT_FEEDBACK;
422 $q->partiallycorrectfeedbackformat = FORMAT_HTML;
423 $q->shownumcorrect = true;
424 $q->incorrectfeedback = self::STANDARD_OVERALL_INCORRECT_FEEDBACK;
425 $q->incorrectfeedbackformat = FORMAT_HTML;
429 * Add some standard overall feedback to a question's form data.
431 public static function set_standard_combined_feedback_form_data($form) {
432 $form->correctfeedback = array('text' => self::STANDARD_OVERALL_CORRECT_FEEDBACK,
433 'format' => FORMAT_HTML);
434 $form->partiallycorrectfeedback = array('text' => self::STANDARD_OVERALL_PARTIALLYCORRECT_FEEDBACK,
435 'format' => FORMAT_HTML);
436 $form->shownumcorrect = true;
437 $form->incorrectfeedback = array('text' => self::STANDARD_OVERALL_INCORRECT_FEEDBACK,
438 'format' => FORMAT_HTML);
444 * Helper for tests that need to simulate records loaded from the database.
446 * @copyright 2009 The Open University
447 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
449 abstract class testing_db_record_builder {
450 public static function build_db_records(array $table) {
451 $columns = array_shift($table);
453 foreach ($table as $row) {
454 if (count($row) != count($columns)) {
455 throw new coding_exception("Row contains the wrong number of fields.");
457 $rec = new stdClass();
458 foreach ($columns as $i => $name) {
459 $rec->$name = $row[$i];
469 * Helper base class for tests that need to simulate records loaded from the
472 * @copyright 2009 The Open University
473 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
475 abstract class data_loading_method_test_base extends advanced_testcase {
476 public function build_db_records(array $table) {
477 return testing_db_record_builder::build_db_records($table);
482 abstract class question_testcase extends advanced_testcase {
484 public function assert($expectation, $compare, $notused = '') {
486 if (get_class($expectation) === 'question_pattern_expectation') {
487 $this->assertRegExp($expectation->pattern, $compare,
488 'Expected regex ' . $expectation->pattern . ' not found in ' . $compare);
491 } else if (get_class($expectation) === 'question_no_pattern_expectation') {
492 $this->assertNotRegExp($expectation->pattern, $compare,
493 'Unexpected regex ' . $expectation->pattern . ' found in ' . $compare);
496 } else if (get_class($expectation) === 'question_contains_tag_with_attributes') {
497 $this->assertTag(array('tag'=>$expectation->tag, 'attributes'=>$expectation->expectedvalues), $compare,
498 'Looking for a ' . $expectation->tag . ' with attributes ' . html_writer::attributes($expectation->expectedvalues) . ' in ' . $compare);
499 foreach ($expectation->forbiddenvalues as $k=>$v) {
500 $attr = $expectation->expectedvalues;
502 $this->assertNotTag(array('tag'=>$expectation->tag, 'attributes'=>$attr), $compare,
503 $expectation->tag . ' had a ' . $k . ' attribute that should not be there in ' . $compare);
507 } else if (get_class($expectation) === 'question_contains_tag_with_attribute') {
508 $attr = array($expectation->attribute=>$expectation->value);
509 $this->assertTag(array('tag'=>$expectation->tag, 'attributes'=>$attr), $compare,
510 'Looking for a ' . $expectation->tag . ' with attribute ' . html_writer::attributes($attr) . ' in ' . $compare);
513 } else if (get_class($expectation) === 'question_does_not_contain_tag_with_attributes') {
514 $this->assertNotTag(array('tag'=>$expectation->tag, 'attributes'=>$expectation->attributes), $compare,
515 'Unexpected ' . $expectation->tag . ' with attributes ' . html_writer::attributes($expectation->attributes) . ' found in ' . $compare);
518 } else if (get_class($expectation) === 'question_contains_select_expectation') {
519 $tag = array('tag'=>'select', 'attributes'=>array('name'=>$expectation->name),
520 'children'=>array('count'=>count($expectation->choices)));
521 if ($expectation->enabled === false) {
522 $tag['attributes']['disabled'] = 'disabled';
523 } else if ($expectation->enabled === true) {
526 foreach(array_keys($expectation->choices) as $value) {
527 if ($expectation->selected === $value) {
528 $tag['child'] = array('tag'=>'option', 'attributes'=>array('value'=>$value, 'selected'=>'selected'));
530 $tag['child'] = array('tag'=>'option', 'attributes'=>array('value'=>$value));
534 $this->assertTag($tag, $compare, 'expected select not found in ' . $compare);
537 } else if (get_class($expectation) === 'question_check_specified_fields_expectation') {
538 $expect = (array)$expectation->expect;
539 $compare = (array)$compare;
540 foreach ($expect as $k=>$v) {
541 if (!array_key_exists($k, $compare)) {
542 $this->fail("Property $k does not exist");
544 if ($v != $compare[$k]) {
545 $this->fail("Property $k is different");
548 $this->assertTrue(true);
551 } else if (get_class($expectation) === 'question_contains_tag_with_contents') {
552 $this->assertTag(array('tag'=>$expectation->tag, 'content'=>$expectation->content), $compare,
553 'Looking for a ' . $expectation->tag . ' with content ' . $expectation->content . ' in ' . $compare);
557 throw new coding_exception('Unknown expectiontion:'.get_class($expectation));
562 class question_contains_tag_with_contents {
567 public function __construct($tag, $content, $message = '') {
569 $this->content = $content;
570 $this->message = $message;
575 class question_check_specified_fields_expectation {
579 function __construct($expected, $message = '') {
580 $this->expect = $expected;
581 $this->message = $message;
586 class question_contains_select_expectation {
593 public function __construct($name, $choices, $selected = null, $enabled = null, $message = '') {
595 $this->choices = $choices;
596 $this->selected = $selected;
597 $this->enabled = $enabled;
598 $this->message = $message;
603 class question_does_not_contain_tag_with_attributes {
608 public function __construct($tag, $attributes, $message = '') {
610 $this->attributes = $attributes;
611 $this->message = $message;
616 class question_contains_tag_with_attribute {
622 public function __construct($tag, $attribute, $value, $message = '') {
624 $this->attribute = $attribute;
625 $this->value = $value;
626 $this->message = $message;
631 class question_contains_tag_with_attributes {
633 public $expectedvalues = array();
634 public $forbiddenvalues = array();
637 public function __construct($tag, $expectedvalues, $forbiddenvalues=array(), $message = '') {
639 $this->expectedvalues = $expectedvalues;
640 $this->forbiddenvalues = $forbiddenvalues;
641 $this->message = $message;
646 class question_pattern_expectation {
650 public function __construct($pattern, $message = '') {
651 $this->pattern = $pattern;
652 $this->message = $message;
657 class question_no_pattern_expectation {
661 public function __construct($pattern, $message = '') {
662 $this->pattern = $pattern;
663 $this->message = $message;
669 * Helper base class for tests that walk a question through a sequents of
670 * interactions under the control of a particular behaviour.
672 * @copyright 2009 The Open University
673 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
675 abstract class qbehaviour_walkthrough_test_base extends question_testcase {
676 /** @var question_display_options */
677 protected $displayoptions;
678 /** @var question_usage_by_activity */
684 * @var string after {@link render()} has been called, this contains the
685 * display of the question in its current state.
687 protected $currentoutput = '';
689 protected function setUp() {
691 $this->resetAfterTest(true);
693 $this->displayoptions = new question_display_options();
694 $this->quba = question_engine::make_questions_usage_by_activity('unit_test',
695 context_system::instance());
698 protected function tearDown() {
699 $this->displayoptions = null;
704 protected function start_attempt_at_question($question, $preferredbehaviour,
705 $maxmark = null, $variant = 1) {
706 $this->quba->set_preferred_behaviour($preferredbehaviour);
707 $this->slot = $this->quba->add_question($question, $maxmark);
708 $this->quba->start_question($this->slot, $variant);
712 * Convert an array of data destined for one question to the equivalent POST data.
713 * @param array $data the data for the quetsion.
714 * @return array the complete post data.
716 protected function response_data_to_post($data) {
717 $prefix = $this->quba->get_field_prefix($this->slot);
719 'slots' => $this->slot,
720 $prefix . ':sequencecheck' => $this->get_question_attempt()->get_sequence_check_count(),
722 foreach ($data as $name => $value) {
723 $fulldata[$prefix . $name] = $value;
728 protected function process_submission($data) {
729 // Backwards compatibility.
731 if (count($data) == 1 && key($data) === '-finish') {
735 $this->quba->process_all_actions(time(), $this->response_data_to_post($data));
738 protected function process_autosave($data) {
739 $this->quba->process_all_autosaves(null, $this->response_data_to_post($data));
742 protected function finish() {
743 $this->quba->finish_all_questions();
746 protected function manual_grade($comment, $mark, $commentformat = null) {
747 $this->quba->manual_grade($this->slot, $comment, $mark, $commentformat);
750 protected function save_quba(moodle_database $db = null) {
751 question_engine::save_questions_usage_by_activity($this->quba, $db);
754 protected function load_quba(moodle_database $db = null) {
755 $this->quba = question_engine::load_questions_usage_by_activity($this->quba->get_id(), $db);
758 protected function delete_quba() {
759 question_engine::delete_questions_usage_by_activity($this->quba->get_id());
763 protected function check_current_state($state) {
764 $this->assertEquals($state, $this->quba->get_question_state($this->slot),
765 'Questions is in the wrong state.');
768 protected function check_current_mark($mark) {
769 if (is_null($mark)) {
770 $this->assertNull($this->quba->get_question_mark($this->slot));
773 // PHP will think a null mark and a mark of 0 are equal,
774 // so explicity check not null in this case.
775 $this->assertNotNull($this->quba->get_question_mark($this->slot));
777 $this->assertEquals($mark, $this->quba->get_question_mark($this->slot),
778 'Expected mark and actual mark differ.', 0.000001);
783 * Generate the HTML rendering of the question in its current state in
784 * $this->currentoutput so that it can be verified.
786 protected function render() {
787 $this->currentoutput = $this->quba->render_question($this->slot, $this->displayoptions);
790 protected function check_output_contains_text_input($name, $value = null, $enabled = true) {
793 'name' => $this->quba->get_field_prefix($this->slot) . $name,
795 if (!is_null($value)) {
796 $attributes['value'] = $value;
799 $attributes['readonly'] = 'readonly';
801 $matcher = $this->get_tag_matcher('input', $attributes);
802 $this->assertTag($matcher, $this->currentoutput,
803 'Looking for an input with attributes ' . html_writer::attributes($attributes) . ' in ' . $this->currentoutput);
806 $matcher['attributes']['readonly'] = 'readonly';
807 $this->assertNotTag($matcher, $this->currentoutput,
808 'input with attributes ' . html_writer::attributes($attributes) .
809 ' should not be read-only in ' . $this->currentoutput);
813 protected function check_output_contains_text_input_with_class($name, $class = null) {
816 'name' => $this->quba->get_field_prefix($this->slot) . $name,
818 if (!is_null($class)) {
819 $attributes['class'] = 'regexp:/\b' . $class . '\b/';
822 $matcher = $this->get_tag_matcher('input', $attributes);
823 $this->assertTag($matcher, $this->currentoutput,
824 'Looking for an input with attributes ' . html_writer::attributes($attributes) . ' in ' . $this->currentoutput);
827 protected function check_output_does_not_contain_text_input_with_class($name, $class = null) {
830 'name' => $this->quba->get_field_prefix($this->slot) . $name,
832 if (!is_null($class)) {
833 $attributes['class'] = 'regexp:/\b' . $class . '\b/';
836 $matcher = $this->get_tag_matcher('input', $attributes);
837 $this->assertNotTag($matcher, $this->currentoutput,
838 'Unexpected input with attributes ' . html_writer::attributes($attributes) . ' found in ' . $this->currentoutput);
841 protected function check_output_contains_hidden_input($name, $value) {
844 'name' => $this->quba->get_field_prefix($this->slot) . $name,
847 $this->assertTag($this->get_tag_matcher('input', $attributes), $this->currentoutput,
848 'Looking for a hidden input with attributes ' . html_writer::attributes($attributes) . ' in ' . $this->currentoutput);
851 protected function get_tag_matcher($tag, $attributes) {
854 'attributes' => $attributes,
859 * @param $condition one or more Expectations. (users varargs).
861 protected function check_current_output() {
862 $html = $this->quba->render_question($this->slot, $this->displayoptions);
863 foreach (func_get_args() as $condition) {
864 $this->assert($condition, $html);
868 protected function get_question_attempt() {
869 return $this->quba->get_question_attempt($this->slot);
872 protected function get_step_count() {
873 return $this->get_question_attempt()->get_num_steps();
876 protected function check_step_count($expectednumsteps) {
877 $this->assertEquals($expectednumsteps, $this->get_step_count());
880 protected function get_step($stepnum) {
881 return $this->get_question_attempt()->get_step($stepnum);
884 protected function get_contains_question_text_expectation($question) {
885 return new question_pattern_expectation('/' . preg_quote($question->questiontext, '/') . '/');
888 protected function get_contains_general_feedback_expectation($question) {
889 return new question_pattern_expectation('/' . preg_quote($question->generalfeedback, '/') . '/');
892 protected function get_does_not_contain_correctness_expectation() {
893 return new question_no_pattern_expectation('/class=\"correctness/');
896 protected function get_contains_correct_expectation() {
897 return new question_pattern_expectation('/' . preg_quote(get_string('correct', 'question'), '/') . '/');
900 protected function get_contains_partcorrect_expectation() {
901 return new question_pattern_expectation('/' .
902 preg_quote(get_string('partiallycorrect', 'question'), '/') . '/');
905 protected function get_contains_incorrect_expectation() {
906 return new question_pattern_expectation('/' . preg_quote(get_string('incorrect', 'question'), '/') . '/');
909 protected function get_contains_standard_correct_combined_feedback_expectation() {
910 return new question_pattern_expectation('/' .
911 preg_quote(test_question_maker::STANDARD_OVERALL_CORRECT_FEEDBACK, '/') . '/');
914 protected function get_contains_standard_partiallycorrect_combined_feedback_expectation() {
915 return new question_pattern_expectation('/' .
916 preg_quote(test_question_maker::STANDARD_OVERALL_PARTIALLYCORRECT_FEEDBACK, '/') . '/');
919 protected function get_contains_standard_incorrect_combined_feedback_expectation() {
920 return new question_pattern_expectation('/' .
921 preg_quote(test_question_maker::STANDARD_OVERALL_INCORRECT_FEEDBACK, '/') . '/');
924 protected function get_does_not_contain_feedback_expectation() {
925 return new question_no_pattern_expectation('/class="feedback"/');
928 protected function get_does_not_contain_num_parts_correct() {
929 return new question_no_pattern_expectation('/class="numpartscorrect"/');
932 protected function get_contains_num_parts_correct($num) {
935 return new question_pattern_expectation('/<div class="numpartscorrect">' .
936 preg_quote(get_string('yougotnright', 'question', $a), '/') . '/');
939 protected function get_does_not_contain_specific_feedback_expectation() {
940 return new question_no_pattern_expectation('/class="specificfeedback"/');
943 protected function get_contains_validation_error_expectation() {
944 return new question_contains_tag_with_attribute('div', 'class', 'validationerror');
947 protected function get_does_not_contain_validation_error_expectation() {
948 return new question_no_pattern_expectation('/class="validationerror"/');
951 protected function get_contains_mark_summary($mark) {
953 $a->mark = format_float($mark, $this->displayoptions->markdp);
954 $a->max = format_float($this->quba->get_question_max_mark($this->slot),
955 $this->displayoptions->markdp);
956 return new question_pattern_expectation('/' .
957 preg_quote(get_string('markoutofmax', 'question', $a), '/') . '/');
960 protected function get_contains_marked_out_of_summary() {
961 $max = format_float($this->quba->get_question_max_mark($this->slot),
962 $this->displayoptions->markdp);
963 return new question_pattern_expectation('/' .
964 preg_quote(get_string('markedoutofmax', 'question', $max), '/') . '/');
967 protected function get_does_not_contain_mark_summary() {
968 return new question_no_pattern_expectation('/<div class="grade">/');
971 protected function get_contains_checkbox_expectation($baseattr, $enabled, $checked) {
972 $expectedattributes = $baseattr;
973 $forbiddenattributes = array();
974 $expectedattributes['type'] = 'checkbox';
975 if ($enabled === true) {
976 $forbiddenattributes['disabled'] = 'disabled';
977 } else if ($enabled === false) {
978 $expectedattributes['disabled'] = 'disabled';
980 if ($checked === true) {
981 $expectedattributes['checked'] = 'checked';
982 } else if ($checked === false) {
983 $forbiddenattributes['checked'] = 'checked';
985 return new question_contains_tag_with_attributes('input', $expectedattributes, $forbiddenattributes);
988 protected function get_contains_mc_checkbox_expectation($index, $enabled = null,
990 return $this->get_contains_checkbox_expectation(array(
991 'name' => $this->quba->get_field_prefix($this->slot) . $index,
993 ), $enabled, $checked);
996 protected function get_contains_radio_expectation($baseattr, $enabled, $checked) {
997 $expectedattributes = $baseattr;
998 $forbiddenattributes = array();
999 $expectedattributes['type'] = 'radio';
1000 if ($enabled === true) {
1001 $forbiddenattributes['disabled'] = 'disabled';
1002 } else if ($enabled === false) {
1003 $expectedattributes['disabled'] = 'disabled';
1005 if ($checked === true) {
1006 $expectedattributes['checked'] = 'checked';
1007 } else if ($checked === false) {
1008 $forbiddenattributes['checked'] = 'checked';
1010 return new question_contains_tag_with_attributes('input', $expectedattributes, $forbiddenattributes);
1013 protected function get_contains_mc_radio_expectation($index, $enabled = null, $checked = null) {
1014 return $this->get_contains_radio_expectation(array(
1015 'name' => $this->quba->get_field_prefix($this->slot) . 'answer',
1017 ), $enabled, $checked);
1020 protected function get_contains_hidden_expectation($name, $value = null) {
1021 $expectedattributes = array('type' => 'hidden', 'name' => s($name));
1022 if (!is_null($value)) {
1023 $expectedattributes['value'] = s($value);
1025 return new question_contains_tag_with_attributes('input', $expectedattributes);
1028 protected function get_does_not_contain_hidden_expectation($name, $value = null) {
1029 $expectedattributes = array('type' => 'hidden', 'name' => s($name));
1030 if (!is_null($value)) {
1031 $expectedattributes['value'] = s($value);
1033 return new question_does_not_contain_tag_with_attributes('input', $expectedattributes);
1036 protected function get_contains_tf_true_radio_expectation($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_tf_false_radio_expectation($enabled = null, $checked = null) {
1044 return $this->get_contains_radio_expectation(array(
1045 'name' => $this->quba->get_field_prefix($this->slot) . 'answer',
1047 ), $enabled, $checked);
1050 protected function get_contains_cbm_radio_expectation($certainty, $enabled = null,
1052 return $this->get_contains_radio_expectation(array(
1053 'name' => $this->quba->get_field_prefix($this->slot) . '-certainty',
1054 'value' => $certainty,
1055 ), $enabled, $checked);
1058 protected function get_contains_button_expectation($name, $value = null, $enabled = null) {
1059 $expectedattributes = array(
1063 $forbiddenattributes = array();
1064 if (!is_null($value)) {
1065 $expectedattributes['value'] = $value;
1067 if ($enabled === true) {
1068 $forbiddenattributes['disabled'] = 'disabled';
1069 } else if ($enabled === false) {
1070 $expectedattributes['disabled'] = 'disabled';
1072 return new question_contains_tag_with_attributes('input', $expectedattributes, $forbiddenattributes);
1075 protected function get_contains_submit_button_expectation($enabled = null) {
1076 return $this->get_contains_button_expectation(
1077 $this->quba->get_field_prefix($this->slot) . '-submit', null, $enabled);
1080 protected function get_tries_remaining_expectation($n) {
1081 return new question_pattern_expectation('/' .
1082 preg_quote(get_string('triesremaining', 'qbehaviour_interactive', $n), '/') . '/');
1085 protected function get_invalid_answer_expectation() {
1086 return new question_pattern_expectation('/' .
1087 preg_quote(get_string('invalidanswer', 'question'), '/') . '/');
1090 protected function get_contains_try_again_button_expectation($enabled = null) {
1091 $expectedattributes = array(
1093 'name' => $this->quba->get_field_prefix($this->slot) . '-tryagain',
1095 $forbiddenattributes = array();
1096 if ($enabled === true) {
1097 $forbiddenattributes['disabled'] = 'disabled';
1098 } else if ($enabled === false) {
1099 $expectedattributes['disabled'] = 'disabled';
1101 return new question_contains_tag_with_attributes('input', $expectedattributes, $forbiddenattributes);
1104 protected function get_does_not_contain_try_again_button_expectation() {
1105 return new question_no_pattern_expectation('/name="' .
1106 $this->quba->get_field_prefix($this->slot) . '-tryagain"/');
1109 protected function get_contains_select_expectation($name, $choices,
1110 $selected = null, $enabled = null) {
1111 $fullname = $this->quba->get_field_prefix($this->slot) . $name;
1112 return new question_contains_select_expectation($fullname, $choices, $selected, $enabled);
1115 protected function get_mc_right_answer_index($mc) {
1116 $order = $mc->get_order($this->get_question_attempt());
1117 foreach ($order as $i => $ansid) {
1118 if ($mc->answers[$ansid]->fraction == 1) {
1122 $this->fail('This multiple choice question does not seem to have a right answer!');
1125 protected function get_no_hint_visible_expectation() {
1126 return new question_no_pattern_expectation('/class="hint"/');
1129 protected function get_contains_hint_expectation($hinttext) {
1130 // Does not currently verify hint text.
1131 return new question_contains_tag_with_attribute('div', 'class', 'hint');
1136 * Simple class that implements the {@link moodle_recordset} API based on an
1137 * array of test data.
1139 * See the {@link question_attempt_step_db_test} class in
1140 * question/engine/tests/testquestionattemptstep.php for an example of how
1143 * @copyright 2011 The Open University
1144 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1146 class question_test_recordset extends moodle_recordset {
1151 * @param $table as for {@link testing_db_record_builder::build_db_records()}
1152 * but does not need a unique first column.
1154 public function __construct(array $table) {
1155 $columns = array_shift($table);
1156 $this->records = array();
1157 foreach ($table as $row) {
1158 if (count($row) != count($columns)) {
1159 throw new coding_exception("Row contains the wrong number of fields.");
1162 foreach ($columns as $i => $name) {
1163 $rec[$name] = $row[$i];
1165 $this->records[] = $rec;
1167 reset($this->records);
1170 public function __destruct() {
1174 public function current() {
1175 return (object) current($this->records);
1178 public function key() {
1179 if (is_null(key($this->records))) {
1182 $current = current($this->records);
1183 return reset($current);
1186 public function next() {
1187 next($this->records);
1190 public function valid() {
1191 return !is_null(key($this->records));
1194 public function close() {
1195 $this->records = null;
1200 * A {@link question_variant_selection_strategy} designed for testing.
1201 * For selected. questions it wil return a specific variants. In for the other
1202 * slots it will use a fallback strategy.
1204 * @copyright 2013 The Open University
1205 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1207 class question_variant_forced_choices_selection_strategy
1208 implements question_variant_selection_strategy {
1210 /** @var array seed => variant to select. */
1211 protected $forcedchoices;
1213 /** @var question_variant_selection_strategy strategy used to make the non-forced choices. */
1214 protected $basestrategy;
1218 * @param array $forcedchoice array seed => variant to select.
1219 * @param question_variant_selection_strategy $basestrategy strategy used
1220 * to make the non-forced choices.
1222 public function __construct(array $forcedchoices, question_variant_selection_strategy $basestrategy) {
1223 $this->forcedchoices = $forcedchoices;
1224 $this->basestrategy = $basestrategy;
1227 public function choose_variant($maxvariants, $seed) {
1228 if (array_key_exists($seed, $this->forcedchoices)) {
1229 if ($this->forcedchoices[$seed] > $maxvariants) {
1230 throw new coding_exception('Forced variant out of range.');
1232 return $this->forcedchoices[$seed];
1234 return $this->basestrategy->choose_variant($maxvariants, $seed);
1239 * Helper method for preparing the $forcedchoices array.
1240 * @param array $variantsbyslot slot number => variant to select.
1241 * @param question_usage_by_activity $quba the question usage we need a strategy for.
1242 * @return array that can be passed to the constructor as $forcedchoices.
1244 public static function prepare_forced_choices_array(array $variantsbyslot,
1245 question_usage_by_activity $quba) {
1247 $forcedchoices = array();
1249 foreach ($variantsbyslot as $slot => $varianttochoose) {
1250 $question = $quba->get_question($slot);
1251 $seed = $question->get_variants_selection_seed();
1252 if (array_key_exists($seed, $forcedchoices) && $forcedchoices[$seed] != $varianttochoose) {
1253 throw new coding_exception('Inconsistent forced variant detected at slot ' . $slot);
1255 if ($varianttochoose > $question->get_num_variants()) {
1256 throw new coding_exception('Forced variant out of range at slot ' . $slot);
1258 $forcedchoices[$seed] = $varianttochoose;
1260 return $forcedchoices;