MDL-64420 qtype: gapselect unit tests unsafe
[moodle.git] / question / engine / tests / helpers.php
CommitLineData
603bd001
PS
1<?php
2// This file is part of Moodle - http://moodle.org/
3//
4// Moodle is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// Moodle is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
16
17/**
18 * This file contains helper classes for testing the question engine.
19 *
20 * @package moodlecore
21 * @subpackage questionengine
22 * @copyright 2009 The Open University
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 */
25
26
27defined('MOODLE_INTERNAL') || die();
28
29global $CFG;
df44db5b
TH
30require_once(__DIR__ . '/../lib.php');
31require_once($CFG->dirroot . '/lib/phpunit/lib.php');
603bd001
PS
32
33
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 */
40class 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 }
4e3d8293
TH
47 public function set_max_fraction($fraction) {
48 $this->maxfraction = $fraction;
49 }
603bd001
PS
50 public function set_behaviour(question_behaviour $behaviour) {
51 $this->behaviour = $behaviour;
52 }
53}
54
55
eca230b5
TH
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 */
63class testable_question_engine_unit_of_work extends question_engine_unit_of_work {
64 public function get_modified() {
65 return $this->modified;
66 }
67
68 public function get_attempts_added() {
69 return $this->attemptsadded;
70 }
71
72 public function get_attempts_modified() {
73 return $this->attemptsmodified;
74 }
75
76 public function get_steps_added() {
77 return $this->stepsadded;
78 }
79
80 public function get_steps_modified() {
81 return $this->stepsmodified;
82 }
83
84 public function get_steps_deleted() {
85 return $this->stepsdeleted;
86 }
f6579bea
TH
87
88 public function get_metadata_added() {
89 return $this->metadataadded;
90 }
91
92 public function get_metadata_modified() {
93 return $this->metadatamodified;
94 }
eca230b5
TH
95}
96
97
603bd001
PS
98/**
99 * Base class for question type test helpers.
100 *
101 * @copyright 2011 The Open University
102 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
103 */
104abstract class question_test_helper {
105 /**
106 * @return array of example question names that can be passed as the $which
107 * argument of {@link test_question_maker::make_question} when $qtype is
108 * this question type.
109 */
110 abstract public function get_test_questions();
01c898ec
JP
111
112 /**
113 * Set up a form to create a question in $cat. This method also sets cat and contextid on $questiondata object.
114 * @param object $cat the category
115 * @param object $questiondata form initialisation requires question data.
116 * @return moodleform
117 */
118 public static function get_question_editing_form($cat, $questiondata) {
119 $catcontext = context::instance_by_id($cat->contextid, MUST_EXIST);
120 $contexts = new question_edit_contexts($catcontext);
121 $dataforformconstructor = new stdClass();
2cf7bde8 122 $dataforformconstructor->createdby = $questiondata->createdby;
01c898ec
JP
123 $dataforformconstructor->qtype = $questiondata->qtype;
124 $dataforformconstructor->contextid = $questiondata->contextid = $catcontext->id;
125 $dataforformconstructor->category = $questiondata->category = $cat->id;
126 $dataforformconstructor->formoptions = new stdClass();
127 $dataforformconstructor->formoptions->canmove = true;
128 $dataforformconstructor->formoptions->cansaveasnew = true;
01c898ec
JP
129 $dataforformconstructor->formoptions->canedit = true;
130 $dataforformconstructor->formoptions->repeatelements = true;
131 $qtype = question_bank::get_qtype($questiondata->qtype);
132 return $qtype->create_editing_form('question.php', $dataforformconstructor, $cat, $contexts, true);
133 }
603bd001
PS
134}
135
136
137/**
138 * This class creates questions of various types, which can then be used when
139 * testing.
140 *
141 * @copyright 2009 The Open University
142 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
143 */
144class test_question_maker {
145 const STANDARD_OVERALL_CORRECT_FEEDBACK = 'Well done!';
146 const STANDARD_OVERALL_PARTIALLYCORRECT_FEEDBACK =
147 'Parts, but only parts, of your response are correct.';
148 const STANDARD_OVERALL_INCORRECT_FEEDBACK = 'That is not right at all.';
149
150 /** @var array qtype => qtype test helper class. */
151 protected static $testhelpers = array();
152
153 /**
154 * Just make a question_attempt at a question. Useful for unit tests that
155 * need to pass a $qa to methods that call format_text. Probably not safe
156 * to use for anything beyond that.
157 * @param question_definition $question a question.
158 * @param number $maxmark the max mark to set.
159 * @return question_attempt the question attempt.
160 */
161 public static function get_a_qa($question, $maxmark = 3) {
162 return new question_attempt($question, 13, null, $maxmark);
163 }
164
165 /**
166 * Initialise the common fields of a question of any type.
167 */
168 public static function initialise_a_question($q) {
169 global $USER;
170
171 $q->id = 0;
172 $q->category = 0;
6189fda4 173 $q->idnumber = null;
603bd001
PS
174 $q->parent = 0;
175 $q->questiontextformat = FORMAT_HTML;
176 $q->generalfeedbackformat = FORMAT_HTML;
177 $q->defaultmark = 1;
178 $q->penalty = 0.3333333;
179 $q->length = 1;
180 $q->stamp = make_unique_id_code();
181 $q->version = make_unique_id_code();
182 $q->hidden = 0;
183 $q->timecreated = time();
184 $q->timemodified = time();
185 $q->createdby = $USER->id;
186 $q->modifiedby = $USER->id;
187 }
188
189 public static function initialise_question_data($qdata) {
190 global $USER;
191
192 $qdata->id = 0;
193 $qdata->category = 0;
6189fda4 194 $qdata->idnumber = null;
603bd001
PS
195 $qdata->contextid = 0;
196 $qdata->parent = 0;
197 $qdata->questiontextformat = FORMAT_HTML;
198 $qdata->generalfeedbackformat = FORMAT_HTML;
199 $qdata->defaultmark = 1;
200 $qdata->penalty = 0.3333333;
201 $qdata->length = 1;
202 $qdata->stamp = make_unique_id_code();
203 $qdata->version = make_unique_id_code();
204 $qdata->hidden = 0;
205 $qdata->timecreated = time();
206 $qdata->timemodified = time();
207 $qdata->createdby = $USER->id;
208 $qdata->modifiedby = $USER->id;
209 $qdata->hints = array();
210 }
211
603bd001
PS
212 /**
213 * Get the test helper class for a particular question type.
214 * @param $qtype the question type name, e.g. 'multichoice'.
215 * @return question_test_helper the test helper class.
216 */
217 public static function get_test_helper($qtype) {
218 global $CFG;
219
220 if (array_key_exists($qtype, self::$testhelpers)) {
221 return self::$testhelpers[$qtype];
222 }
223
1c74b260 224 $file = core_component::get_plugin_directory('qtype', $qtype) . '/tests/helper.php';
603bd001
PS
225 if (!is_readable($file)) {
226 throw new coding_exception('Question type ' . $qtype .
227 ' does not have test helper code.');
228 }
229 include_once($file);
230
231 $class = 'qtype_' . $qtype . '_test_helper';
232 if (!class_exists($class)) {
233 throw new coding_exception('Class ' . $class . ' is not defined in ' . $file);
234 }
235
236 self::$testhelpers[$qtype] = new $class();
237 return self::$testhelpers[$qtype];
238 }
239
240 /**
241 * Call a method on a qtype_{$qtype}_test_helper class and return the result.
242 *
243 * @param string $methodtemplate e.g. 'make_{qtype}_question_{which}';
244 * @param string $qtype the question type to get a test question for.
245 * @param string $which one of the names returned by the get_test_questions
246 * method of the relevant qtype_{$qtype}_test_helper class.
247 * @param unknown_type $which
248 */
249 protected static function call_question_helper_method($methodtemplate, $qtype, $which = null) {
250 $helper = self::get_test_helper($qtype);
251
252 $available = $helper->get_test_questions();
253
254 if (is_null($which)) {
255 $which = reset($available);
256 } else if (!in_array($which, $available)) {
257 throw new coding_exception('Example question ' . $which . ' of type ' .
258 $qtype . ' does not exist.');
259 }
260
261 $method = str_replace(array('{qtype}', '{which}'),
262 array($qtype, $which), $methodtemplate);
263
264 if (!method_exists($helper, $method)) {
5b0a31bf 265 throw new coding_exception('Method ' . $method . ' does not exist on the ' .
603bd001
PS
266 $qtype . ' question type test helper class.');
267 }
268
269 return $helper->$method();
270 }
271
272 /**
273 * Question types can provide a number of test question defintions.
274 * They do this by creating a qtype_{$qtype}_test_helper class that extends
275 * question_test_helper. The get_test_questions method returns the list of
276 * test questions available for this question type.
277 *
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 question_definition the requested question object.
282 */
283 public static function make_question($qtype, $which = null) {
284 return self::call_question_helper_method('make_{qtype}_question_{which}',
285 $qtype, $which);
286 }
287
288 /**
289 * Like {@link make_question()} but returns the datastructure from
290 * get_question_options instead of the question_definition object.
291 *
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.
296 */
297 public static function get_question_data($qtype, $which = null) {
298 return self::call_question_helper_method('get_{qtype}_question_data_{which}',
299 $qtype, $which);
300 }
301
302 /**
303 * Like {@link make_question()} but returns the data what would be saved from
304 * the question editing form instead of the question_definition object.
305 *
306 * @param string $qtype the question type to get a test question for.
307 * @param string $which one of the names returned by the get_test_questions
308 * method of the relevant qtype_{$qtype}_test_helper class.
309 * @return stdClass the requested question object.
310 */
311 public static function get_question_form_data($qtype, $which = null) {
312 return self::call_question_helper_method('get_{qtype}_question_form_data_{which}',
313 $qtype, $which);
314 }
315
316 /**
317 * Makes a multichoice question with choices 'A', 'B' and 'C' shuffled. 'A'
318 * is correct, defaultmark 1.
319 * @return qtype_multichoice_single_question
320 */
321 public static function make_a_multichoice_single_question() {
322 question_bank::load_question_definition_classes('multichoice');
323 $mc = new qtype_multichoice_single_question();
324 self::initialise_a_question($mc);
325 $mc->name = 'Multi-choice question, single response';
326 $mc->questiontext = 'The answer is A.';
327 $mc->generalfeedback = 'You should have selected A.';
328 $mc->qtype = question_bank::get_qtype('multichoice');
329
330 $mc->shuffleanswers = 1;
331 $mc->answernumbering = 'abc';
332
333 $mc->answers = array(
334 13 => new question_answer(13, 'A', 1, 'A is right', FORMAT_HTML),
335 14 => new question_answer(14, 'B', -0.3333333, 'B is wrong', FORMAT_HTML),
336 15 => new question_answer(15, 'C', -0.3333333, 'C is wrong', FORMAT_HTML),
337 );
338
339 return $mc;
340 }
341
342 /**
343 * Makes a multichoice question with choices 'A', 'B', 'C' and 'D' shuffled.
344 * 'A' and 'C' is correct, defaultmark 1.
345 * @return qtype_multichoice_multi_question
346 */
347 public static function make_a_multichoice_multi_question() {
348 question_bank::load_question_definition_classes('multichoice');
349 $mc = new qtype_multichoice_multi_question();
350 self::initialise_a_question($mc);
351 $mc->name = 'Multi-choice question, multiple response';
352 $mc->questiontext = 'The answer is A and C.';
353 $mc->generalfeedback = 'You should have selected A and C.';
354 $mc->qtype = question_bank::get_qtype('multichoice');
355
356 $mc->shuffleanswers = 1;
357 $mc->answernumbering = 'abc';
358
359 self::set_standard_combined_feedback_fields($mc);
360
361 $mc->answers = array(
362 13 => new question_answer(13, 'A', 0.5, 'A is part of the right answer', FORMAT_HTML),
363 14 => new question_answer(14, 'B', -1, 'B is wrong', FORMAT_HTML),
364 15 => new question_answer(15, 'C', 0.5, 'C is part of the right answer', FORMAT_HTML),
365 16 => new question_answer(16, 'D', -1, 'D is wrong', FORMAT_HTML),
366 );
367
368 return $mc;
369 }
370
371 /**
372 * Makes a matching question to classify 'Dog', 'Frog', 'Toad' and 'Cat' as
373 * 'Mammal', 'Amphibian' or 'Insect'.
374 * defaultmark 1. Stems are shuffled by default.
375 * @return qtype_match_question
376 */
377 public static function make_a_matching_question() {
378 question_bank::load_question_definition_classes('match');
379 $match = new qtype_match_question();
380 self::initialise_a_question($match);
381 $match->name = 'Matching question';
382 $match->questiontext = 'Classify the animals.';
383 $match->generalfeedback = 'Frogs and toads are amphibians, the others are mammals.';
384 $match->qtype = question_bank::get_qtype('match');
385
386 $match->shufflestems = 1;
387
388 self::set_standard_combined_feedback_fields($match);
389
390 // Using unset to get 1-based arrays.
391 $match->stems = array('', 'Dog', 'Frog', 'Toad', 'Cat');
392 $match->stemformat = array('', FORMAT_HTML, FORMAT_HTML, FORMAT_HTML, FORMAT_HTML);
393 $match->choices = array('', 'Mammal', 'Amphibian', 'Insect');
394 $match->right = array('', 1, 2, 2, 1);
395 unset($match->stems[0]);
396 unset($match->stemformat[0]);
397 unset($match->choices[0]);
398 unset($match->right[0]);
399
400 return $match;
401 }
402
403 /**
404 * Makes a truefalse question with correct ansewer true, defaultmark 1.
405 * @return qtype_essay_question
406 */
407 public static function make_an_essay_question() {
408 question_bank::load_question_definition_classes('essay');
409 $essay = new qtype_essay_question();
410 self::initialise_a_question($essay);
411 $essay->name = 'Essay question';
412 $essay->questiontext = 'Write an essay.';
413 $essay->generalfeedback = 'I hope you wrote an interesting essay.';
414 $essay->penalty = 0;
415 $essay->qtype = question_bank::get_qtype('essay');
416
417 $essay->responseformat = 'editor';
a4f765eb 418 $essay->responserequired = 1;
603bd001
PS
419 $essay->responsefieldlines = 15;
420 $essay->attachments = 0;
a4f765eb
KT
421 $essay->attachmentsrequired = 0;
422 $essay->responsetemplate = '';
423 $essay->responsetemplateformat = FORMAT_MOODLE;
603bd001
PS
424 $essay->graderinfo = '';
425 $essay->graderinfoformat = FORMAT_MOODLE;
426
427 return $essay;
428 }
429
430 /**
431 * Add some standard overall feedback to a question. You need to use these
432 * specific feedback strings for the corresponding contains_..._feedback
433 * methods in {@link qbehaviour_walkthrough_test_base} to works.
434 * @param question_definition $q the question to add the feedback to.
435 */
436 public static function set_standard_combined_feedback_fields($q) {
437 $q->correctfeedback = self::STANDARD_OVERALL_CORRECT_FEEDBACK;
438 $q->correctfeedbackformat = FORMAT_HTML;
439 $q->partiallycorrectfeedback = self::STANDARD_OVERALL_PARTIALLYCORRECT_FEEDBACK;
440 $q->partiallycorrectfeedbackformat = FORMAT_HTML;
441 $q->shownumcorrect = true;
442 $q->incorrectfeedback = self::STANDARD_OVERALL_INCORRECT_FEEDBACK;
443 $q->incorrectfeedbackformat = FORMAT_HTML;
444 }
01c898ec
JP
445
446 /**
447 * Add some standard overall feedback to a question's form data.
448 */
449 public static function set_standard_combined_feedback_form_data($form) {
450 $form->correctfeedback = array('text' => self::STANDARD_OVERALL_CORRECT_FEEDBACK,
451 'format' => FORMAT_HTML);
452 $form->partiallycorrectfeedback = array('text' => self::STANDARD_OVERALL_PARTIALLYCORRECT_FEEDBACK,
453 'format' => FORMAT_HTML);
454 $form->shownumcorrect = true;
455 $form->incorrectfeedback = array('text' => self::STANDARD_OVERALL_INCORRECT_FEEDBACK,
456 'format' => FORMAT_HTML);
457 }
603bd001
PS
458}
459
460
461/**
462 * Helper for tests that need to simulate records loaded from the database.
463 *
464 * @copyright 2009 The Open University
465 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
466 */
467abstract class testing_db_record_builder {
468 public static function build_db_records(array $table) {
469 $columns = array_shift($table);
470 $records = array();
471 foreach ($table as $row) {
472 if (count($row) != count($columns)) {
473 throw new coding_exception("Row contains the wrong number of fields.");
474 }
475 $rec = new stdClass();
476 foreach ($columns as $i => $name) {
477 $rec->$name = $row[$i];
478 }
479 $records[] = $rec;
480 }
481 return $records;
482 }
483}
484
485
486/**
487 * Helper base class for tests that need to simulate records loaded from the
488 * database.
489 *
490 * @copyright 2009 The Open University
491 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
492 */
a4d53e4b 493abstract class data_loading_method_test_base extends advanced_testcase {
603bd001
PS
494 public function build_db_records(array $table) {
495 return testing_db_record_builder::build_db_records($table);
496 }
603bd001
PS
497}
498
499
a4d53e4b 500abstract class question_testcase extends advanced_testcase {
603bd001 501
5ef18d82 502 public function assert($expectation, $compare, $notused = '') {
603bd001
PS
503
504 if (get_class($expectation) === 'question_pattern_expectation') {
5ef18d82
TH
505 $this->assertRegExp($expectation->pattern, $compare,
506 'Expected regex ' . $expectation->pattern . ' not found in ' . $compare);
603bd001
PS
507 return;
508
509 } else if (get_class($expectation) === 'question_no_pattern_expectation') {
5ef18d82
TH
510 $this->assertNotRegExp($expectation->pattern, $compare,
511 'Unexpected regex ' . $expectation->pattern . ' found in ' . $compare);
603bd001
PS
512 return;
513
514 } else if (get_class($expectation) === 'question_contains_tag_with_attributes') {
5ef18d82
TH
515 $this->assertTag(array('tag'=>$expectation->tag, 'attributes'=>$expectation->expectedvalues), $compare,
516 'Looking for a ' . $expectation->tag . ' with attributes ' . html_writer::attributes($expectation->expectedvalues) . ' in ' . $compare);
603bd001
PS
517 foreach ($expectation->forbiddenvalues as $k=>$v) {
518 $attr = $expectation->expectedvalues;
519 $attr[$k] = $v;
5ef18d82
TH
520 $this->assertNotTag(array('tag'=>$expectation->tag, 'attributes'=>$attr), $compare,
521 $expectation->tag . ' had a ' . $k . ' attribute that should not be there in ' . $compare);
603bd001
PS
522 }
523 return;
524
525 } else if (get_class($expectation) === 'question_contains_tag_with_attribute') {
526 $attr = array($expectation->attribute=>$expectation->value);
5ef18d82
TH
527 $this->assertTag(array('tag'=>$expectation->tag, 'attributes'=>$attr), $compare,
528 'Looking for a ' . $expectation->tag . ' with attribute ' . html_writer::attributes($attr) . ' in ' . $compare);
603bd001
PS
529 return;
530
531 } else if (get_class($expectation) === 'question_does_not_contain_tag_with_attributes') {
5ef18d82
TH
532 $this->assertNotTag(array('tag'=>$expectation->tag, 'attributes'=>$expectation->attributes), $compare,
533 'Unexpected ' . $expectation->tag . ' with attributes ' . html_writer::attributes($expectation->attributes) . ' found in ' . $compare);
603bd001
PS
534 return;
535
536 } else if (get_class($expectation) === 'question_contains_select_expectation') {
537 $tag = array('tag'=>'select', 'attributes'=>array('name'=>$expectation->name),
538 'children'=>array('count'=>count($expectation->choices)));
6cdef715 539 if ($expectation->enabled === false) {
603bd001 540 $tag['attributes']['disabled'] = 'disabled';
6cdef715
TH
541 } else if ($expectation->enabled === true) {
542 // TODO
603bd001
PS
543 }
544 foreach(array_keys($expectation->choices) as $value) {
545 if ($expectation->selected === $value) {
546 $tag['child'] = array('tag'=>'option', 'attributes'=>array('value'=>$value, 'selected'=>'selected'));
547 } else {
548 $tag['child'] = array('tag'=>'option', 'attributes'=>array('value'=>$value));
549 }
603bd001 550 }
6cdef715
TH
551
552 $this->assertTag($tag, $compare, 'expected select not found in ' . $compare);
603bd001
PS
553 return;
554
555 } else if (get_class($expectation) === 'question_check_specified_fields_expectation') {
556 $expect = (array)$expectation->expect;
557 $compare = (array)$compare;
558 foreach ($expect as $k=>$v) {
559 if (!array_key_exists($k, $compare)) {
f4fe3968 560 $this->fail("Property {$k} does not exist");
603bd001
PS
561 }
562 if ($v != $compare[$k]) {
f4fe3968 563 $this->fail("Property {$k} is different");
603bd001
PS
564 }
565 }
566 $this->assertTrue(true);
567 return;
568
569 } else if (get_class($expectation) === 'question_contains_tag_with_contents') {
5ef18d82
TH
570 $this->assertTag(array('tag'=>$expectation->tag, 'content'=>$expectation->content), $compare,
571 'Looking for a ' . $expectation->tag . ' with content ' . $expectation->content . ' in ' . $compare);
603bd001
PS
572 return;
573 }
574
575 throw new coding_exception('Unknown expectiontion:'.get_class($expectation));
576 }
0d3be6d6
JB
577
578 /**
579 * Use this function rather than assert when checking the value of options within a select element.
580 *
581 * @param question_contains_select_expectation $expectation The select expectation class
582 * @param string $html The rendered output to check against
583 */
584 public function assert_select_options($expectation, $html) {
585 if (get_class($expectation) !== 'question_contains_select_expectation') {
586 throw new coding_exception('Unsuitable expectiontion: '.get_class($expectation));
587 }
588 $dom = new DOMDocument();
589 $dom->loadHTML($html);
590 $selects = $dom->getElementsByTagName('select');
591 foreach ($selects as $select) {
592 if ($select->getAttribute('name') == $expectation->name) {
593 $options = $select->getElementsByTagName('option');
594 foreach ($options as $key => $option) {
595 if ($key == 0) {
596 // Check the value of the first option. This is often 'Choose...' or a nbsp.
597 // Note it is necessary to pass a nbsp character in the test here and not just ' '.
598 // Many tests do not require checking of this option.
599 if (isset($expectation->choices[$option->getAttribute('value')])) {
600 $this->assertEquals($expectation->choices[$option->getAttribute('value')], $option->textContent);
601 }
602 continue;
603 }
604 // Check the value of the options in the select.
605 $this->assertEquals($expectation->choices[$option->getAttribute('value')], $option->textContent);
606 if ($expectation->selected && $option->getAttribute('value') == $expectation->selected) {
607 // Check the right option is selected.
608 $this->assertTrue(!empty($option->getAttribute('selected')));
609 }
610 }
611 if ($expectation->enabled) {
612 // Check the select element is enabled.
613 $this->assertTrue(!$select->getAttribute('disabled'));
614 }
615 }
616 }
617 return;
618 }
603bd001
PS
619}
620
621
622class question_contains_tag_with_contents {
623 public $tag;
624 public $content;
625 public $message;
626
627 public function __construct($tag, $content, $message = '') {
628 $this->tag = $tag;
629 $this->content = $content;
630 $this->message = $message;
631 }
632
633}
634
635class question_check_specified_fields_expectation {
636 public $expect;
637 public $message;
638
639 function __construct($expected, $message = '') {
640 $this->expect = $expected;
641 $this->message = $message;
642 }
643}
644
645
646class question_contains_select_expectation {
647 public $name;
648 public $choices;
649 public $selected;
650 public $enabled;
651 public $message;
652
653 public function __construct($name, $choices, $selected = null, $enabled = null, $message = '') {
654 $this->name = $name;
655 $this->choices = $choices;
656 $this->selected = $selected;
657 $this->enabled = $enabled;
658 $this->message = $message;
659 }
660}
661
662
663class question_does_not_contain_tag_with_attributes {
664 public $tag;
665 public $attributes;
666 public $message;
667
668 public function __construct($tag, $attributes, $message = '') {
669 $this->tag = $tag;
670 $this->attributes = $attributes;
671 $this->message = $message;
672 }
673}
674
675
676class question_contains_tag_with_attribute {
677 public $tag;
678 public $attribute;
679 public $value;
680 public $message;
681
682 public function __construct($tag, $attribute, $value, $message = '') {
683 $this->tag = $tag;
684 $this->attribute = $attribute;
685 $this->value = $value;
686 $this->message = $message;
687 }
688}
689
690
691class question_contains_tag_with_attributes {
692 public $tag;
693 public $expectedvalues = array();
694 public $forbiddenvalues = array();
695 public $message;
696
697 public function __construct($tag, $expectedvalues, $forbiddenvalues=array(), $message = '') {
698 $this->tag = $tag;
699 $this->expectedvalues = $expectedvalues;
700 $this->forbiddenvalues = $forbiddenvalues;
701 $this->message = $message;
702 }
703}
704
705
706class question_pattern_expectation {
707 public $pattern;
708 public $message;
709
710 public function __construct($pattern, $message = '') {
711 $this->pattern = $pattern;
712 $this->message = $message;
713 }
714}
715
716
717class question_no_pattern_expectation {
718 public $pattern;
719 public $message;
720
721 public function __construct($pattern, $message = '') {
722 $this->pattern = $pattern;
723 $this->message = $message;
724 }
725}
726
727
728/**
729 * Helper base class for tests that walk a question through a sequents of
730 * interactions under the control of a particular behaviour.
731 *
732 * @copyright 2009 The Open University
733 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
734 */
a4d53e4b 735abstract class qbehaviour_walkthrough_test_base extends question_testcase {
603bd001
PS
736 /** @var question_display_options */
737 protected $displayoptions;
738 /** @var question_usage_by_activity */
739 protected $quba;
c0d12fc1
TH
740 /** @var integer */
741
603bd001 742 protected $slot;
c0d12fc1
TH
743 /**
744 * @var string after {@link render()} has been called, this contains the
745 * display of the question in its current state.
746 */
747 protected $currentoutput = '';
603bd001
PS
748
749 protected function setUp() {
750 parent::setUp();
751 $this->resetAfterTest(true);
752
753 $this->displayoptions = new question_display_options();
754 $this->quba = question_engine::make_questions_usage_by_activity('unit_test',
21c08c63 755 context_system::instance());
603bd001
PS
756 }
757
758 protected function tearDown() {
759 $this->displayoptions = null;
760 $this->quba = null;
761 parent::tearDown();
762 }
763
764 protected function start_attempt_at_question($question, $preferredbehaviour,
765 $maxmark = null, $variant = 1) {
766 $this->quba->set_preferred_behaviour($preferredbehaviour);
767 $this->slot = $this->quba->add_question($question, $maxmark);
768 $this->quba->start_question($this->slot, $variant);
769 }
eca230b5 770
d122fe32
TH
771 /**
772 * Convert an array of data destined for one question to the equivalent POST data.
773 * @param array $data the data for the quetsion.
774 * @return array the complete post data.
775 */
776 protected function response_data_to_post($data) {
eca230b5
TH
777 $prefix = $this->quba->get_field_prefix($this->slot);
778 $fulldata = array(
779 'slots' => $this->slot,
c7fbfe46 780 $prefix . ':sequencecheck' => $this->get_question_attempt()->get_sequence_check_count(),
eca230b5
TH
781 );
782 foreach ($data as $name => $value) {
783 $fulldata[$prefix . $name] = $value;
784 }
d122fe32
TH
785 return $fulldata;
786 }
787
788 protected function process_submission($data) {
789 // Backwards compatibility.
790 reset($data);
791 if (count($data) == 1 && key($data) === '-finish') {
792 $this->finish();
793 }
794
795 $this->quba->process_all_actions(time(), $this->response_data_to_post($data));
eca230b5
TH
796 }
797
798 protected function process_autosave($data) {
d122fe32 799 $this->quba->process_all_autosaves(null, $this->response_data_to_post($data));
eca230b5
TH
800 }
801
802 protected function finish() {
803 $this->quba->finish_all_questions();
603bd001
PS
804 }
805
53b8e256
TH
806 protected function manual_grade($comment, $mark, $commentformat = null) {
807 $this->quba->manual_grade($this->slot, $comment, $mark, $commentformat);
603bd001
PS
808 }
809
eca230b5
TH
810 protected function save_quba(moodle_database $db = null) {
811 question_engine::save_questions_usage_by_activity($this->quba, $db);
812 }
813
814 protected function load_quba(moodle_database $db = null) {
815 $this->quba = question_engine::load_questions_usage_by_activity($this->quba->get_id(), $db);
816 }
817
818 protected function delete_quba() {
819 question_engine::delete_questions_usage_by_activity($this->quba->get_id());
820 $this->quba = null;
821 }
822
305d2716
SR
823 /**
824 * Asserts if the manual comment for the question is equal to the provided arguments.
825 * @param $comment Comment text
826 * @param $commentformat Comment format
827 */
828 protected function check_comment($comment, $commentformat) {
829 $actualcomment = $this->quba->get_question_attempt($this->slot)->get_manual_comment();
830
831 $this->assertEquals(
832 [$comment, $commentformat],
833 [$actualcomment[0], $actualcomment[1]]
834 );
835 }
836
603bd001 837 protected function check_current_state($state) {
5ef18d82
TH
838 $this->assertEquals($state, $this->quba->get_question_state($this->slot),
839 'Questions is in the wrong state.');
603bd001
PS
840 }
841
842 protected function check_current_mark($mark) {
843 if (is_null($mark)) {
844 $this->assertNull($this->quba->get_question_mark($this->slot));
845 } else {
846 if ($mark == 0) {
847 // PHP will think a null mark and a mark of 0 are equal,
848 // so explicity check not null in this case.
849 $this->assertNotNull($this->quba->get_question_mark($this->slot));
850 }
851 $this->assertEquals($mark, $this->quba->get_question_mark($this->slot),
5ef18d82 852 'Expected mark and actual mark differ.', 0.000001);
603bd001
PS
853 }
854 }
855
c0d12fc1
TH
856 /**
857 * Generate the HTML rendering of the question in its current state in
858 * $this->currentoutput so that it can be verified.
859 */
860 protected function render() {
861 $this->currentoutput = $this->quba->render_question($this->slot, $this->displayoptions);
862 }
863
eca230b5
TH
864 protected function check_output_contains_text_input($name, $value = null, $enabled = true) {
865 $attributes = array(
866 'type' => 'text',
867 'name' => $this->quba->get_field_prefix($this->slot) . $name,
868 );
869 if (!is_null($value)) {
870 $attributes['value'] = $value;
871 }
872 if (!$enabled) {
873 $attributes['readonly'] = 'readonly';
874 }
875 $matcher = $this->get_tag_matcher('input', $attributes);
876 $this->assertTag($matcher, $this->currentoutput,
877 'Looking for an input with attributes ' . html_writer::attributes($attributes) . ' in ' . $this->currentoutput);
878
879 if ($enabled) {
880 $matcher['attributes']['readonly'] = 'readonly';
881 $this->assertNotTag($matcher, $this->currentoutput,
882 'input with attributes ' . html_writer::attributes($attributes) .
883 ' should not be read-only in ' . $this->currentoutput);
884 }
885 }
886
d56ab3b9
JMV
887 protected function check_output_contains_text_input_with_class($name, $class = null) {
888 $attributes = array(
889 'type' => 'text',
890 'name' => $this->quba->get_field_prefix($this->slot) . $name,
891 );
892 if (!is_null($class)) {
893 $attributes['class'] = 'regexp:/\b' . $class . '\b/';
894 }
895
896 $matcher = $this->get_tag_matcher('input', $attributes);
897 $this->assertTag($matcher, $this->currentoutput,
898 'Looking for an input with attributes ' . html_writer::attributes($attributes) . ' in ' . $this->currentoutput);
899 }
900
901 protected function check_output_does_not_contain_text_input_with_class($name, $class = null) {
902 $attributes = array(
903 'type' => 'text',
904 'name' => $this->quba->get_field_prefix($this->slot) . $name,
905 );
906 if (!is_null($class)) {
907 $attributes['class'] = 'regexp:/\b' . $class . '\b/';
908 }
909
910 $matcher = $this->get_tag_matcher('input', $attributes);
911 $this->assertNotTag($matcher, $this->currentoutput,
912 'Unexpected input with attributes ' . html_writer::attributes($attributes) . ' found in ' . $this->currentoutput);
913 }
914
c7fbfe46
TH
915 protected function check_output_contains_hidden_input($name, $value) {
916 $attributes = array(
917 'type' => 'hidden',
918 'name' => $this->quba->get_field_prefix($this->slot) . $name,
919 'value' => $value,
920 );
921 $this->assertTag($this->get_tag_matcher('input', $attributes), $this->currentoutput,
922 'Looking for a hidden input with attributes ' . html_writer::attributes($attributes) . ' in ' . $this->currentoutput);
923 }
924
e101ec9f 925 protected function check_output_contains($string) {
f8e28244 926 $this->render();
f8e28244
RK
927 $this->assertContains($string, $this->currentoutput,
928 'Expected string ' . $string . ' not found in ' . $this->currentoutput);
929 }
930
e101ec9f
TH
931 protected function check_output_does_not_contain($string) {
932 $this->render();
933 $this->assertNotContains($string, $this->currentoutput,
934 'String ' . $string . ' unexpectedly found in ' . $this->currentoutput);
935 }
936
937 protected function check_output_contains_lang_string($identifier, $component = '', $a = null) {
938 $this->check_output_contains(get_string($identifier, $component, $a));
939 }
940
eca230b5
TH
941 protected function get_tag_matcher($tag, $attributes) {
942 return array(
943 'tag' => $tag,
944 'attributes' => $attributes,
945 );
946 }
947
603bd001
PS
948 /**
949 * @param $condition one or more Expectations. (users varargs).
950 */
951 protected function check_current_output() {
952 $html = $this->quba->render_question($this->slot, $this->displayoptions);
953 foreach (func_get_args() as $condition) {
954 $this->assert($condition, $html);
955 }
956 }
957
0d3be6d6
JB
958 /**
959 * Use this function rather than check_current_output for select expectations where
960 * checking the value of the options is required. check_current_output only checks
961 * that the right number of options are available.
962 *
963 * @param question_contains_select_expectation $expectations One or more expectations.
964 */
965 protected function check_output_contains_selectoptions(...$expectations) {
966 $html = $this->quba->render_question($this->slot, $this->displayoptions);
967 foreach ($expectations as $expectation) {
968 $this->assert_select_options($expectation, $html);
969 }
970 }
971
603bd001
PS
972 protected function get_question_attempt() {
973 return $this->quba->get_question_attempt($this->slot);
974 }
975
976 protected function get_step_count() {
977 return $this->get_question_attempt()->get_num_steps();
978 }
979
980 protected function check_step_count($expectednumsteps) {
981 $this->assertEquals($expectednumsteps, $this->get_step_count());
982 }
983
984 protected function get_step($stepnum) {
985 return $this->get_question_attempt()->get_step($stepnum);
986 }
987
988 protected function get_contains_question_text_expectation($question) {
03cefcc9 989 return new question_pattern_expectation('/' . preg_quote($question->questiontext, '/') . '/');
603bd001
PS
990 }
991
992 protected function get_contains_general_feedback_expectation($question) {
03cefcc9 993 return new question_pattern_expectation('/' . preg_quote($question->generalfeedback, '/') . '/');
603bd001
PS
994 }
995
996 protected function get_does_not_contain_correctness_expectation() {
997 return new question_no_pattern_expectation('/class=\"correctness/');
998 }
999
1000 protected function get_contains_correct_expectation() {
03cefcc9 1001 return new question_pattern_expectation('/' . preg_quote(get_string('correct', 'question'), '/') . '/');
603bd001
PS
1002 }
1003
1004 protected function get_contains_partcorrect_expectation() {
1005 return new question_pattern_expectation('/' .
03cefcc9 1006 preg_quote(get_string('partiallycorrect', 'question'), '/') . '/');
603bd001
PS
1007 }
1008
1009 protected function get_contains_incorrect_expectation() {
03cefcc9 1010 return new question_pattern_expectation('/' . preg_quote(get_string('incorrect', 'question'), '/') . '/');
603bd001
PS
1011 }
1012
1013 protected function get_contains_standard_correct_combined_feedback_expectation() {
1014 return new question_pattern_expectation('/' .
03cefcc9 1015 preg_quote(test_question_maker::STANDARD_OVERALL_CORRECT_FEEDBACK, '/') . '/');
603bd001
PS
1016 }
1017
1018 protected function get_contains_standard_partiallycorrect_combined_feedback_expectation() {
1019 return new question_pattern_expectation('/' .
03cefcc9 1020 preg_quote(test_question_maker::STANDARD_OVERALL_PARTIALLYCORRECT_FEEDBACK, '/') . '/');
603bd001
PS
1021 }
1022
1023 protected function get_contains_standard_incorrect_combined_feedback_expectation() {
1024 return new question_pattern_expectation('/' .
03cefcc9 1025 preg_quote(test_question_maker::STANDARD_OVERALL_INCORRECT_FEEDBACK, '/') . '/');
603bd001
PS
1026 }
1027
1028 protected function get_does_not_contain_feedback_expectation() {
1029 return new question_no_pattern_expectation('/class="feedback"/');
1030 }
1031
1032 protected function get_does_not_contain_num_parts_correct() {
1033 return new question_no_pattern_expectation('/class="numpartscorrect"/');
1034 }
1035
1036 protected function get_contains_num_parts_correct($num) {
1037 $a = new stdClass();
1038 $a->num = $num;
1039 return new question_pattern_expectation('/<div class="numpartscorrect">' .
03cefcc9 1040 preg_quote(get_string('yougotnright', 'question', $a), '/') . '/');
603bd001
PS
1041 }
1042
1043 protected function get_does_not_contain_specific_feedback_expectation() {
1044 return new question_no_pattern_expectation('/class="specificfeedback"/');
1045 }
1046
1047 protected function get_contains_validation_error_expectation() {
1048 return new question_contains_tag_with_attribute('div', 'class', 'validationerror');
1049 }
1050
1051 protected function get_does_not_contain_validation_error_expectation() {
1052 return new question_no_pattern_expectation('/class="validationerror"/');
1053 }
1054
1055 protected function get_contains_mark_summary($mark) {
1056 $a = new stdClass();
1057 $a->mark = format_float($mark, $this->displayoptions->markdp);
1058 $a->max = format_float($this->quba->get_question_max_mark($this->slot),
1059 $this->displayoptions->markdp);
1060 return new question_pattern_expectation('/' .
03cefcc9 1061 preg_quote(get_string('markoutofmax', 'question', $a), '/') . '/');
603bd001
PS
1062 }
1063
1064 protected function get_contains_marked_out_of_summary() {
1065 $max = format_float($this->quba->get_question_max_mark($this->slot),
1066 $this->displayoptions->markdp);
1067 return new question_pattern_expectation('/' .
03cefcc9 1068 preg_quote(get_string('markedoutofmax', 'question', $max), '/') . '/');
603bd001
PS
1069 }
1070
1071 protected function get_does_not_contain_mark_summary() {
1072 return new question_no_pattern_expectation('/<div class="grade">/');
1073 }
1074
1075 protected function get_contains_checkbox_expectation($baseattr, $enabled, $checked) {
1076 $expectedattributes = $baseattr;
1077 $forbiddenattributes = array();
1078 $expectedattributes['type'] = 'checkbox';
1079 if ($enabled === true) {
1080 $forbiddenattributes['disabled'] = 'disabled';
1081 } else if ($enabled === false) {
1082 $expectedattributes['disabled'] = 'disabled';
1083 }
1084 if ($checked === true) {
1085 $expectedattributes['checked'] = 'checked';
1086 } else if ($checked === false) {
1087 $forbiddenattributes['checked'] = 'checked';
1088 }
1089 return new question_contains_tag_with_attributes('input', $expectedattributes, $forbiddenattributes);
1090 }
1091
1092 protected function get_contains_mc_checkbox_expectation($index, $enabled = null,
1093 $checked = null) {
1094 return $this->get_contains_checkbox_expectation(array(
1095 'name' => $this->quba->get_field_prefix($this->slot) . $index,
1096 'value' => 1,
1097 ), $enabled, $checked);
1098 }
1099
1100 protected function get_contains_radio_expectation($baseattr, $enabled, $checked) {
1101 $expectedattributes = $baseattr;
1102 $forbiddenattributes = array();
1103 $expectedattributes['type'] = 'radio';
1104 if ($enabled === true) {
1105 $forbiddenattributes['disabled'] = 'disabled';
1106 } else if ($enabled === false) {
1107 $expectedattributes['disabled'] = 'disabled';
1108 }
1109 if ($checked === true) {
1110 $expectedattributes['checked'] = 'checked';
1111 } else if ($checked === false) {
1112 $forbiddenattributes['checked'] = 'checked';
1113 }
1114 return new question_contains_tag_with_attributes('input', $expectedattributes, $forbiddenattributes);
1115 }
1116
1117 protected function get_contains_mc_radio_expectation($index, $enabled = null, $checked = null) {
1118 return $this->get_contains_radio_expectation(array(
1119 'name' => $this->quba->get_field_prefix($this->slot) . 'answer',
1120 'value' => $index,
1121 ), $enabled, $checked);
1122 }
1123
1124 protected function get_contains_hidden_expectation($name, $value = null) {
1125 $expectedattributes = array('type' => 'hidden', 'name' => s($name));
1126 if (!is_null($value)) {
1127 $expectedattributes['value'] = s($value);
1128 }
1129 return new question_contains_tag_with_attributes('input', $expectedattributes);
1130 }
1131
1132 protected function get_does_not_contain_hidden_expectation($name, $value = null) {
1133 $expectedattributes = array('type' => 'hidden', 'name' => s($name));
1134 if (!is_null($value)) {
1135 $expectedattributes['value'] = s($value);
1136 }
1137 return new question_does_not_contain_tag_with_attributes('input', $expectedattributes);
1138 }
1139
1140 protected function get_contains_tf_true_radio_expectation($enabled = null, $checked = null) {
1141 return $this->get_contains_radio_expectation(array(
1142 'name' => $this->quba->get_field_prefix($this->slot) . 'answer',
1143 'value' => 1,
1144 ), $enabled, $checked);
1145 }
1146
1147 protected function get_contains_tf_false_radio_expectation($enabled = null, $checked = null) {
1148 return $this->get_contains_radio_expectation(array(
1149 'name' => $this->quba->get_field_prefix($this->slot) . 'answer',
1150 'value' => 0,
1151 ), $enabled, $checked);
1152 }
1153
1154 protected function get_contains_cbm_radio_expectation($certainty, $enabled = null,
1155 $checked = null) {
1156 return $this->get_contains_radio_expectation(array(
1157 'name' => $this->quba->get_field_prefix($this->slot) . '-certainty',
1158 'value' => $certainty,
1159 ), $enabled, $checked);
1160 }
1161
1162 protected function get_contains_button_expectation($name, $value = null, $enabled = null) {
1163 $expectedattributes = array(
1164 'type' => 'submit',
1165 'name' => $name,
1166 );
1167 $forbiddenattributes = array();
1168 if (!is_null($value)) {
1169 $expectedattributes['value'] = $value;
1170 }
1171 if ($enabled === true) {
1172 $forbiddenattributes['disabled'] = 'disabled';
1173 } else if ($enabled === false) {
1174 $expectedattributes['disabled'] = 'disabled';
1175 }
1176 return new question_contains_tag_with_attributes('input', $expectedattributes, $forbiddenattributes);
1177 }
1178
81e47a35
TH
1179 /**
1180 * Returns an epectation that a string contains the HTML of a button with
1181 * name {question-attempt prefix}-submit, and eiter enabled or not.
1182 * @param bool $enabled if not null, check the enabled/disabled state of the button. True = enabled.
1183 * @return question_contains_tag_with_attributes an expectation for use with check_current_output.
1184 */
603bd001
PS
1185 protected function get_contains_submit_button_expectation($enabled = null) {
1186 return $this->get_contains_button_expectation(
1187 $this->quba->get_field_prefix($this->slot) . '-submit', null, $enabled);
1188 }
1189
81e47a35
TH
1190 /**
1191 * Returns an epectation that a string does not contain the HTML of a button with
1192 * name {question-attempt prefix}-submit.
1193 * @return question_contains_tag_with_attributes an expectation for use with check_current_output.
1194 */
1195 protected function get_does_not_contain_submit_button_expectation() {
1196 return new question_no_pattern_expectation('/name="' .
1197 $this->quba->get_field_prefix($this->slot) . '-submit"/');
1198 }
1199
603bd001
PS
1200 protected function get_tries_remaining_expectation($n) {
1201 return new question_pattern_expectation('/' .
03cefcc9 1202 preg_quote(get_string('triesremaining', 'qbehaviour_interactive', $n), '/') . '/');
603bd001
PS
1203 }
1204
1205 protected function get_invalid_answer_expectation() {
1206 return new question_pattern_expectation('/' .
03cefcc9 1207 preg_quote(get_string('invalidanswer', 'question'), '/') . '/');
603bd001
PS
1208 }
1209
1210 protected function get_contains_try_again_button_expectation($enabled = null) {
1211 $expectedattributes = array(
1212 'type' => 'submit',
1213 'name' => $this->quba->get_field_prefix($this->slot) . '-tryagain',
1214 );
1215 $forbiddenattributes = array();
1216 if ($enabled === true) {
1217 $forbiddenattributes['disabled'] = 'disabled';
1218 } else if ($enabled === false) {
1219 $expectedattributes['disabled'] = 'disabled';
1220 }
1221 return new question_contains_tag_with_attributes('input', $expectedattributes, $forbiddenattributes);
1222 }
1223
1224 protected function get_does_not_contain_try_again_button_expectation() {
1225 return new question_no_pattern_expectation('/name="' .
1226 $this->quba->get_field_prefix($this->slot) . '-tryagain"/');
1227 }
1228
1229 protected function get_contains_select_expectation($name, $choices,
1230 $selected = null, $enabled = null) {
1231 $fullname = $this->quba->get_field_prefix($this->slot) . $name;
1232 return new question_contains_select_expectation($fullname, $choices, $selected, $enabled);
1233 }
1234
1235 protected function get_mc_right_answer_index($mc) {
1236 $order = $mc->get_order($this->get_question_attempt());
1237 foreach ($order as $i => $ansid) {
1238 if ($mc->answers[$ansid]->fraction == 1) {
1239 return $i;
1240 }
1241 }
1242 $this->fail('This multiple choice question does not seem to have a right answer!');
1243 }
1244
1245 protected function get_no_hint_visible_expectation() {
1246 return new question_no_pattern_expectation('/class="hint"/');
1247 }
1248
1249 protected function get_contains_hint_expectation($hinttext) {
1250 // Does not currently verify hint text.
1251 return new question_contains_tag_with_attribute('div', 'class', 'hint');
1252 }
1253}
1254
1255/**
1256 * Simple class that implements the {@link moodle_recordset} API based on an
1257 * array of test data.
1258 *
1259 * See the {@link question_attempt_step_db_test} class in
1260 * question/engine/tests/testquestionattemptstep.php for an example of how
1261 * this is used.
1262 *
1263 * @copyright 2011 The Open University
1264 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1265 */
1266class question_test_recordset extends moodle_recordset {
1267 protected $records;
1268
1269 /**
1270 * Constructor
1271 * @param $table as for {@link testing_db_record_builder::build_db_records()}
1272 * but does not need a unique first column.
1273 */
1274 public function __construct(array $table) {
1275 $columns = array_shift($table);
1276 $this->records = array();
1277 foreach ($table as $row) {
1278 if (count($row) != count($columns)) {
1279 throw new coding_exception("Row contains the wrong number of fields.");
1280 }
1281 $rec = array();
1282 foreach ($columns as $i => $name) {
1283 $rec[$name] = $row[$i];
1284 }
1285 $this->records[] = $rec;
1286 }
1287 reset($this->records);
1288 }
1289
1290 public function __destruct() {
1291 $this->close();
1292 }
1293
1294 public function current() {
1295 return (object) current($this->records);
1296 }
1297
1298 public function key() {
1299 if (is_null(key($this->records))) {
1300 return false;
1301 }
1302 $current = current($this->records);
1303 return reset($current);
1304 }
1305
1306 public function next() {
1307 next($this->records);
1308 }
1309
1310 public function valid() {
1311 return !is_null(key($this->records));
1312 }
1313
1314 public function close() {
1315 $this->records = null;
1316 }
1317}
628b4c86
HN
1318
1319/**
1320 * Helper class for tests that help to test core_question_renderer.
1321 *
1322 * @copyright 2018 Huong Nguyen <huongnv13@gmail.com>
1323 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1324 */
1325class testable_core_question_renderer extends core_question_renderer {
1326
1327 /**
1328 * Test the private number function.
1329 *
1330 * @param null|string $number
1331 * @return HTML
1332 */
1333 public function number($number) {
1334 return parent::number($number);
1335 }
1336}