Merge branch 'MDL-48373' of git://github.com/timhunt/moodle
[moodle.git] / question / engine / tests / helpers.php
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 // GNU General Public License for more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
17 /**
18  * This file contains helper classes for testing the question engine.
19  *
20  * @package    moodlecore
21  * @subpackage questionengine
22  * @copyright  2009 The Open University
23  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24  */
27 defined('MOODLE_INTERNAL') || die();
29 global $CFG;
30 require_once(__DIR__ . '/../lib.php');
31 require_once($CFG->dirroot . '/lib/phpunit/lib.php');
34 /**
35  * Makes some protected methods of question_attempt public to facilitate testing.
36  *
37  * @copyright  2009 The Open University
38  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
39  */
40 class testable_question_attempt extends question_attempt {
41     public function add_step(question_attempt_step $step) {
42         parent::add_step($step);
43     }
44     public function set_min_fraction($fraction) {
45         $this->minfraction = $fraction;
46     }
47     public function set_max_fraction($fraction) {
48         $this->maxfraction = $fraction;
49     }
50     public function set_behaviour(question_behaviour $behaviour) {
51         $this->behaviour = $behaviour;
52     }
53 }
56 /**
57  * Test subclass to allow access to some protected data so that the correct
58  * behaviour can be verified.
59  *
60  * @copyright  2012 The Open University
61  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
62  */
63 class testable_question_engine_unit_of_work extends question_engine_unit_of_work {
64     public function get_modified() {
65         return $this->modified;
66     }
68     public function get_attempts_added() {
69         return $this->attemptsadded;
70     }
72     public function get_attempts_modified() {
73         return $this->attemptsmodified;
74     }
76     public function get_steps_added() {
77         return $this->stepsadded;
78     }
80     public function get_steps_modified() {
81         return $this->stepsmodified;
82     }
84     public function get_steps_deleted() {
85         return $this->stepsdeleted;
86     }
87 }
90 /**
91  * Base class for question type test helpers.
92  *
93  * @copyright  2011 The Open University
94  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
95  */
96 abstract class question_test_helper {
97     /**
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.
101      */
102     abstract public function get_test_questions();
104     /**
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.
108      * @return moodleform
109      */
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);
124     }
128 /**
129  * This class creates questions of various types, which can then be used when
130  * testing.
131  *
132  * @copyright  2009 The Open University
133  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
134  */
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();
144     /**
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.
151      */
152     public static function get_a_qa($question, $maxmark = 3) {
153         return new question_attempt($question, 13, null, $maxmark);
154     }
156     /**
157      * Initialise the common fields of a question of any type.
158      */
159     public static function initialise_a_question($q) {
160         global $USER;
162         $q->id = 0;
163         $q->category = 0;
164         $q->parent = 0;
165         $q->questiontextformat = FORMAT_HTML;
166         $q->generalfeedbackformat = FORMAT_HTML;
167         $q->defaultmark = 1;
168         $q->penalty = 0.3333333;
169         $q->length = 1;
170         $q->stamp = make_unique_id_code();
171         $q->version = make_unique_id_code();
172         $q->hidden = 0;
173         $q->timecreated = time();
174         $q->timemodified = time();
175         $q->createdby = $USER->id;
176         $q->modifiedby = $USER->id;
177     }
179     public static function initialise_question_data($qdata) {
180         global $USER;
182         $qdata->id = 0;
183         $qdata->category = 0;
184         $qdata->contextid = 0;
185         $qdata->parent = 0;
186         $qdata->questiontextformat = FORMAT_HTML;
187         $qdata->generalfeedbackformat = FORMAT_HTML;
188         $qdata->defaultmark = 1;
189         $qdata->penalty = 0.3333333;
190         $qdata->length = 1;
191         $qdata->stamp = make_unique_id_code();
192         $qdata->version = make_unique_id_code();
193         $qdata->hidden = 0;
194         $qdata->timecreated = time();
195         $qdata->timemodified = time();
196         $qdata->createdby = $USER->id;
197         $qdata->modifiedby = $USER->id;
198         $qdata->hints = array();
199     }
201     /**
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.
205      */
206     public static function get_test_helper($qtype) {
207         global $CFG;
209         if (array_key_exists($qtype, self::$testhelpers)) {
210             return self::$testhelpers[$qtype];
211         }
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.');
217         }
218         include_once($file);
220         $class = 'qtype_' . $qtype . '_test_helper';
221         if (!class_exists($class)) {
222             throw new coding_exception('Class ' . $class . ' is not defined in ' . $file);
223         }
225         self::$testhelpers[$qtype] = new $class();
226         return self::$testhelpers[$qtype];
227     }
229     /**
230      * Call a method on a qtype_{$qtype}_test_helper class and return the result.
231      *
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
237      */
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.');
248         }
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.');
256         }
258         return $helper->$method();
259     }
261     /**
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.
266      *
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.
271      */
272     public static function make_question($qtype, $which = null) {
273         return self::call_question_helper_method('make_{qtype}_question_{which}',
274             $qtype, $which);
275     }
277     /**
278      * Like {@link make_question()} but returns the datastructure from
279      * get_question_options instead of the question_definition object.
280      *
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.
285      */
286     public static function get_question_data($qtype, $which = null) {
287         return self::call_question_helper_method('get_{qtype}_question_data_{which}',
288             $qtype, $which);
289     }
291     /**
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.
294      *
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.
299      */
300     public static function get_question_form_data($qtype, $which = null) {
301         return self::call_question_helper_method('get_{qtype}_question_form_data_{which}',
302             $qtype, $which);
303     }
305     /**
306      * Makes a multichoice question with choices 'A', 'B' and 'C' shuffled. 'A'
307      * is correct, defaultmark 1.
308      * @return qtype_multichoice_single_question
309      */
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),
326         );
328         return $mc;
329     }
331     /**
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
335      */
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),
355         );
357         return $mc;
358     }
360     /**
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
365      */
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]);
389         return $match;
390     }
392     /**
393      * Makes a truefalse question with correct ansewer true, defaultmark 1.
394      * @return qtype_essay_question
395      */
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.';
403         $essay->penalty = 0;
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;
416         return $essay;
417     }
419     /**
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.
424      */
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;
433     }
435     /**
436      * Add some standard overall feedback to a question's form data.
437      */
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);
446     }
450 /**
451  * Helper for tests that need to simulate records loaded from the database.
452  *
453  * @copyright  2009 The Open University
454  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
455  */
456 abstract class testing_db_record_builder {
457     public static function build_db_records(array $table) {
458         $columns = array_shift($table);
459         $records = array();
460         foreach ($table as $row) {
461             if (count($row) != count($columns)) {
462                 throw new coding_exception("Row contains the wrong number of fields.");
463             }
464             $rec = new stdClass();
465             foreach ($columns as $i => $name) {
466                 $rec->$name = $row[$i];
467             }
468             $records[] = $rec;
469         }
470         return $records;
471     }
475 /**
476  * Helper base class for tests that need to simulate records loaded from the
477  * database.
478  *
479  * @copyright  2009 The Open University
480  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
481  */
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);
485     }
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);
496             return;
498         } else if (get_class($expectation) === 'question_no_pattern_expectation') {
499             $this->assertNotRegExp($expectation->pattern, $compare,
500                     'Unexpected regex ' . $expectation->pattern . ' found in ' . $compare);
501             return;
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;
508                 $attr[$k] = $v;
509                 $this->assertNotTag(array('tag'=>$expectation->tag, 'attributes'=>$attr), $compare,
510                         $expectation->tag . ' had a ' . $k . ' attribute that should not be there in ' . $compare);
511             }
512             return;
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);
518             return;
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);
523             return;
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) {
531                 // TODO
532             }
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'));
536                 } else {
537                     $tag['child'] = array('tag'=>'option', 'attributes'=>array('value'=>$value));
538                 }
539             }
541             $this->assertTag($tag, $compare, 'expected select not found in ' . $compare);
542             return;
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");
550                 }
551                 if ($v != $compare[$k]) {
552                     $this->fail("Property {$k} is different");
553                 }
554             }
555             $this->assertTrue(true);
556             return;
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);
561             return;
562         }
564         throw new coding_exception('Unknown expectiontion:'.get_class($expectation));
565     }
569 class question_contains_tag_with_contents {
570     public $tag;
571     public $content;
572     public $message;
574     public function __construct($tag, $content, $message = '') {
575         $this->tag = $tag;
576         $this->content = $content;
577         $this->message = $message;
578     }
582 class question_check_specified_fields_expectation {
583     public $expect;
584     public $message;
586     function __construct($expected, $message = '') {
587         $this->expect = $expected;
588         $this->message = $message;
589     }
593 class question_contains_select_expectation {
594     public $name;
595     public $choices;
596     public $selected;
597     public $enabled;
598     public $message;
600     public function __construct($name, $choices, $selected = null, $enabled = null, $message = '') {
601         $this->name = $name;
602         $this->choices = $choices;
603         $this->selected = $selected;
604         $this->enabled = $enabled;
605         $this->message = $message;
606     }
610 class question_does_not_contain_tag_with_attributes {
611     public $tag;
612     public $attributes;
613     public $message;
615     public function __construct($tag, $attributes, $message = '') {
616         $this->tag = $tag;
617         $this->attributes = $attributes;
618         $this->message = $message;
619     }
623 class question_contains_tag_with_attribute {
624     public $tag;
625     public $attribute;
626     public $value;
627     public $message;
629     public function __construct($tag, $attribute, $value, $message = '') {
630         $this->tag = $tag;
631         $this->attribute = $attribute;
632         $this->value = $value;
633         $this->message = $message;
634     }
638 class question_contains_tag_with_attributes {
639     public $tag;
640     public $expectedvalues = array();
641     public $forbiddenvalues = array();
642     public $message;
644     public function __construct($tag, $expectedvalues, $forbiddenvalues=array(), $message = '') {
645         $this->tag = $tag;
646         $this->expectedvalues = $expectedvalues;
647         $this->forbiddenvalues = $forbiddenvalues;
648         $this->message = $message;
649     }
653 class question_pattern_expectation {
654     public $pattern;
655     public $message;
657     public function __construct($pattern, $message = '') {
658         $this->pattern = $pattern;
659         $this->message = $message;
660     }
664 class question_no_pattern_expectation {
665     public $pattern;
666     public $message;
668     public function __construct($pattern, $message = '') {
669         $this->pattern = $pattern;
670         $this->message = $message;
671     }
675 /**
676  * Helper base class for tests that walk a question through a sequents of
677  * interactions under the control of a particular behaviour.
678  *
679  * @copyright  2009 The Open University
680  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
681  */
682 abstract class qbehaviour_walkthrough_test_base extends question_testcase {
683     /** @var question_display_options */
684     protected $displayoptions;
685     /** @var question_usage_by_activity */
686     protected $quba;
687     /** @var integer */
689     protected $slot;
690     /**
691      * @var string after {@link render()} has been called, this contains the
692      * display of the question in its current state.
693      */
694     protected $currentoutput = '';
696     protected function setUp() {
697         parent::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());
703     }
705     protected function tearDown() {
706         $this->displayoptions = null;
707         $this->quba = null;
708         parent::tearDown();
709     }
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);
716     }
718     /**
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.
722      */
723     protected function response_data_to_post($data) {
724         $prefix = $this->quba->get_field_prefix($this->slot);
725         $fulldata = array(
726             'slots' => $this->slot,
727             $prefix . ':sequencecheck' => $this->get_question_attempt()->get_sequence_check_count(),
728         );
729         foreach ($data as $name => $value) {
730             $fulldata[$prefix . $name] = $value;
731         }
732         return $fulldata;
733     }
735     protected function process_submission($data) {
736         // Backwards compatibility.
737         reset($data);
738         if (count($data) == 1 && key($data) === '-finish') {
739             $this->finish();
740         }
742         $this->quba->process_all_actions(time(), $this->response_data_to_post($data));
743     }
745     protected function process_autosave($data) {
746         $this->quba->process_all_autosaves(null, $this->response_data_to_post($data));
747     }
749     protected function finish() {
750         $this->quba->finish_all_questions();
751     }
753     protected function manual_grade($comment, $mark, $commentformat = null) {
754         $this->quba->manual_grade($this->slot, $comment, $mark, $commentformat);
755     }
757     protected function save_quba(moodle_database $db = null) {
758         question_engine::save_questions_usage_by_activity($this->quba, $db);
759     }
761     protected function load_quba(moodle_database $db = null) {
762         $this->quba = question_engine::load_questions_usage_by_activity($this->quba->get_id(), $db);
763     }
765     protected function delete_quba() {
766         question_engine::delete_questions_usage_by_activity($this->quba->get_id());
767         $this->quba = null;
768     }
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.');
773     }
775     protected function check_current_mark($mark) {
776         if (is_null($mark)) {
777             $this->assertNull($this->quba->get_question_mark($this->slot));
778         } else {
779             if ($mark == 0) {
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));
783             }
784             $this->assertEquals($mark, $this->quba->get_question_mark($this->slot),
785                 'Expected mark and actual mark differ.', 0.000001);
786         }
787     }
789     /**
790      * Generate the HTML rendering of the question in its current state in
791      * $this->currentoutput so that it can be verified.
792      */
793     protected function render() {
794         $this->currentoutput = $this->quba->render_question($this->slot, $this->displayoptions);
795     }
797     protected function check_output_contains_text_input($name, $value = null, $enabled = true) {
798         $attributes = array(
799             'type' => 'text',
800             'name' => $this->quba->get_field_prefix($this->slot) . $name,
801         );
802         if (!is_null($value)) {
803             $attributes['value'] = $value;
804         }
805         if (!$enabled) {
806             $attributes['readonly'] = 'readonly';
807         }
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);
812         if ($enabled) {
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);
817         }
818     }
820     protected function check_output_contains_text_input_with_class($name, $class = null) {
821         $attributes = array(
822             'type' => 'text',
823             'name' => $this->quba->get_field_prefix($this->slot) . $name,
824         );
825         if (!is_null($class)) {
826             $attributes['class'] = 'regexp:/\b' . $class . '\b/';
827         }
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);
832     }
834     protected function check_output_does_not_contain_text_input_with_class($name, $class = null) {
835         $attributes = array(
836             'type' => 'text',
837             'name' => $this->quba->get_field_prefix($this->slot) . $name,
838         );
839         if (!is_null($class)) {
840             $attributes['class'] = 'regexp:/\b' . $class . '\b/';
841         }
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);
846     }
848     protected function check_output_contains_hidden_input($name, $value) {
849         $attributes = array(
850             'type' => 'hidden',
851             'name' => $this->quba->get_field_prefix($this->slot) . $name,
852             'value' => $value,
853         );
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);
856     }
858     protected function check_output_contains($string) {
859         $this->render();
860         $this->assertContains($string, $this->currentoutput,
861                 'Expected string ' . $string . ' not found in ' . $this->currentoutput);
862     }
864     protected function check_output_does_not_contain($string) {
865         $this->render();
866         $this->assertNotContains($string, $this->currentoutput,
867                 'String ' . $string . ' unexpectedly found in ' . $this->currentoutput);
868     }
870     protected function check_output_contains_lang_string($identifier, $component = '', $a = null) {
871         $this->check_output_contains(get_string($identifier, $component, $a));
872     }
874     protected function get_tag_matcher($tag, $attributes) {
875         return array(
876             'tag' => $tag,
877             'attributes' => $attributes,
878         );
879     }
881     /**
882      * @param $condition one or more Expectations. (users varargs).
883      */
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);
888         }
889     }
891     protected function get_question_attempt() {
892         return $this->quba->get_question_attempt($this->slot);
893     }
895     protected function get_step_count() {
896         return $this->get_question_attempt()->get_num_steps();
897     }
899     protected function check_step_count($expectednumsteps) {
900         $this->assertEquals($expectednumsteps, $this->get_step_count());
901     }
903     protected function get_step($stepnum) {
904         return $this->get_question_attempt()->get_step($stepnum);
905     }
907     protected function get_contains_question_text_expectation($question) {
908         return new question_pattern_expectation('/' . preg_quote($question->questiontext, '/') . '/');
909     }
911     protected function get_contains_general_feedback_expectation($question) {
912         return new question_pattern_expectation('/' . preg_quote($question->generalfeedback, '/') . '/');
913     }
915     protected function get_does_not_contain_correctness_expectation() {
916         return new question_no_pattern_expectation('/class=\"correctness/');
917     }
919     protected function get_contains_correct_expectation() {
920         return new question_pattern_expectation('/' . preg_quote(get_string('correct', 'question'), '/') . '/');
921     }
923     protected function get_contains_partcorrect_expectation() {
924         return new question_pattern_expectation('/' .
925             preg_quote(get_string('partiallycorrect', 'question'), '/') . '/');
926     }
928     protected function get_contains_incorrect_expectation() {
929         return new question_pattern_expectation('/' . preg_quote(get_string('incorrect', 'question'), '/') . '/');
930     }
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, '/') . '/');
935     }
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, '/') . '/');
940     }
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, '/') . '/');
945     }
947     protected function get_does_not_contain_feedback_expectation() {
948         return new question_no_pattern_expectation('/class="feedback"/');
949     }
951     protected function get_does_not_contain_num_parts_correct() {
952         return new question_no_pattern_expectation('/class="numpartscorrect"/');
953     }
955     protected function get_contains_num_parts_correct($num) {
956         $a = new stdClass();
957         $a->num = $num;
958         return new question_pattern_expectation('/<div class="numpartscorrect">' .
959             preg_quote(get_string('yougotnright', 'question', $a), '/') . '/');
960     }
962     protected function get_does_not_contain_specific_feedback_expectation() {
963         return new question_no_pattern_expectation('/class="specificfeedback"/');
964     }
966     protected function get_contains_validation_error_expectation() {
967         return new question_contains_tag_with_attribute('div', 'class', 'validationerror');
968     }
970     protected function get_does_not_contain_validation_error_expectation() {
971         return new question_no_pattern_expectation('/class="validationerror"/');
972     }
974     protected function get_contains_mark_summary($mark) {
975         $a = new stdClass();
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), '/') . '/');
981     }
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), '/') . '/');
988     }
990     protected function get_does_not_contain_mark_summary() {
991         return new question_no_pattern_expectation('/<div class="grade">/');
992     }
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';
1002         }
1003         if ($checked === true) {
1004             $expectedattributes['checked'] = 'checked';
1005         } else if ($checked === false) {
1006             $forbiddenattributes['checked'] = 'checked';
1007         }
1008         return new question_contains_tag_with_attributes('input', $expectedattributes, $forbiddenattributes);
1009     }
1011     protected function get_contains_mc_checkbox_expectation($index, $enabled = null,
1012                                                             $checked = null) {
1013         return $this->get_contains_checkbox_expectation(array(
1014             'name' => $this->quba->get_field_prefix($this->slot) . $index,
1015             'value' => 1,
1016         ), $enabled, $checked);
1017     }
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';
1027         }
1028         if ($checked === true) {
1029             $expectedattributes['checked'] = 'checked';
1030         } else if ($checked === false) {
1031             $forbiddenattributes['checked'] = 'checked';
1032         }
1033         return new question_contains_tag_with_attributes('input', $expectedattributes, $forbiddenattributes);
1034     }
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',
1039             'value' => $index,
1040         ), $enabled, $checked);
1041     }
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);
1047         }
1048         return new question_contains_tag_with_attributes('input', $expectedattributes);
1049     }
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);
1055         }
1056         return new question_does_not_contain_tag_with_attributes('input', $expectedattributes);
1057     }
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',
1062             'value' => 1,
1063         ), $enabled, $checked);
1064     }
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',
1069             'value' => 0,
1070         ), $enabled, $checked);
1071     }
1073     protected function get_contains_cbm_radio_expectation($certainty, $enabled = null,
1074                                                           $checked = 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);
1079     }
1081     protected function get_contains_button_expectation($name, $value = null, $enabled = null) {
1082         $expectedattributes = array(
1083             'type' => 'submit',
1084             'name' => $name,
1085         );
1086         $forbiddenattributes = array();
1087         if (!is_null($value)) {
1088             $expectedattributes['value'] = $value;
1089         }
1090         if ($enabled === true) {
1091             $forbiddenattributes['disabled'] = 'disabled';
1092         } else if ($enabled === false) {
1093             $expectedattributes['disabled'] = 'disabled';
1094         }
1095         return new question_contains_tag_with_attributes('input', $expectedattributes, $forbiddenattributes);
1096     }
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);
1101     }
1103     protected function get_tries_remaining_expectation($n) {
1104         return new question_pattern_expectation('/' .
1105             preg_quote(get_string('triesremaining', 'qbehaviour_interactive', $n), '/') . '/');
1106     }
1108     protected function get_invalid_answer_expectation() {
1109         return new question_pattern_expectation('/' .
1110             preg_quote(get_string('invalidanswer', 'question'), '/') . '/');
1111     }
1113     protected function get_contains_try_again_button_expectation($enabled = null) {
1114         $expectedattributes = array(
1115             'type' => 'submit',
1116             'name' => $this->quba->get_field_prefix($this->slot) . '-tryagain',
1117         );
1118         $forbiddenattributes = array();
1119         if ($enabled === true) {
1120             $forbiddenattributes['disabled'] = 'disabled';
1121         } else if ($enabled === false) {
1122             $expectedattributes['disabled'] = 'disabled';
1123         }
1124         return new question_contains_tag_with_attributes('input', $expectedattributes, $forbiddenattributes);
1125     }
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"/');
1130     }
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);
1136     }
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) {
1142                 return $i;
1143             }
1144         }
1145         $this->fail('This multiple choice question does not seem to have a right answer!');
1146     }
1148     protected function get_no_hint_visible_expectation() {
1149         return new question_no_pattern_expectation('/class="hint"/');
1150     }
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');
1155     }
1158 /**
1159  * Simple class that implements the {@link moodle_recordset} API based on an
1160  * array of test data.
1161  *
1162  *  See the {@link question_attempt_step_db_test} class in
1163  *  question/engine/tests/testquestionattemptstep.php for an example of how
1164  *  this is used.
1165  *
1166  * @copyright  2011 The Open University
1167  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1168  */
1169 class question_test_recordset extends moodle_recordset {
1170     protected $records;
1172     /**
1173      * Constructor
1174      * @param $table as for {@link testing_db_record_builder::build_db_records()}
1175      *      but does not need a unique first column.
1176      */
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.");
1183             }
1184             $rec = array();
1185             foreach ($columns as $i => $name) {
1186                 $rec[$name] = $row[$i];
1187             }
1188             $this->records[] = $rec;
1189         }
1190         reset($this->records);
1191     }
1193     public function __destruct() {
1194         $this->close();
1195     }
1197     public function current() {
1198         return (object) current($this->records);
1199     }
1201     public function key() {
1202         if (is_null(key($this->records))) {
1203             return false;
1204         }
1205         $current = current($this->records);
1206         return reset($current);
1207     }
1209     public function next() {
1210         next($this->records);
1211     }
1213     public function valid() {
1214         return !is_null(key($this->records));
1215     }
1217     public function close() {
1218         $this->records = null;
1219     }