Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 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
 
27
defined('MOODLE_INTERNAL') || die();
28
 
29
global $CFG;
30
require_once(__DIR__ . '/../lib.php');
31
require_once($CFG->dirroot . '/lib/phpunit/lib.php');
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
 */
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
}
54
 
55
 
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
    }
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
    }
87
 
88
    public function get_metadata_added() {
89
        return $this->metadataadded;
90
    }
91
 
92
    public function get_metadata_modified() {
93
        return $this->metadatamodified;
94
    }
95
}
96
 
97
 
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
 */
104
abstract 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();
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 core_question\local\bank\question_edit_contexts($catcontext);
121
        $dataforformconstructor = new stdClass();
122
        $dataforformconstructor->createdby = $questiondata->createdby;
123
        $dataforformconstructor->qtype = $questiondata->qtype;
124
        $dataforformconstructor->contextid = $questiondata->contextid = $catcontext->id;
125
        $dataforformconstructor->category = $questiondata->category = $cat->id;
126
        $dataforformconstructor->status = $questiondata->status;
127
        $dataforformconstructor->formoptions = new stdClass();
128
        $dataforformconstructor->formoptions->canmove = true;
129
        $dataforformconstructor->formoptions->cansaveasnew = true;
130
        $dataforformconstructor->formoptions->canedit = true;
131
        $dataforformconstructor->formoptions->repeatelements = true;
132
        $qtype = question_bank::get_qtype($questiondata->qtype);
133
        return  $qtype->create_editing_form('question.php', $dataforformconstructor, $cat, $contexts, true);
134
    }
135
}
136
 
137
 
138
/**
139
 * This class creates questions of various types, which can then be used when
140
 * testing.
141
 *
142
 * @copyright  2009 The Open University
143
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
144
 */
145
class test_question_maker {
146
    const STANDARD_OVERALL_CORRECT_FEEDBACK = 'Well done!';
147
    const STANDARD_OVERALL_PARTIALLYCORRECT_FEEDBACK =
148
        'Parts, but only parts, of your response are correct.';
149
    const STANDARD_OVERALL_INCORRECT_FEEDBACK = 'That is not right at all.';
150
 
151
    /** @var array qtype => qtype test helper class. */
152
    protected static $testhelpers = array();
153
 
154
    /**
155
     * Just make a question_attempt at a question. Useful for unit tests that
156
     * need to pass a $qa to methods that call format_text. Probably not safe
157
     * to use for anything beyond that.
158
     * @param question_definition $question a question.
159
     * @param number $maxmark the max mark to set.
160
     * @return question_attempt the question attempt.
161
     */
162
    public static function get_a_qa($question, $maxmark = 3) {
163
        return new question_attempt($question, 13, null, $maxmark);
164
    }
165
 
166
    /**
167
     * Initialise the common fields of a question of any type.
168
     */
169
    public static function initialise_a_question($q) {
170
        global $USER;
171
 
172
        $q->id = 0;
173
        $q->category = 0;
174
        $q->idnumber = null;
175
        $q->parent = 0;
176
        $q->questiontextformat = FORMAT_HTML;
177
        $q->generalfeedbackformat = FORMAT_HTML;
178
        $q->defaultmark = 1;
179
        $q->penalty = 0.3333333;
180
        $q->length = 1;
181
        $q->stamp = make_unique_id_code();
182
        $q->status = \core_question\local\bank\question_version_status::QUESTION_STATUS_READY;
183
        $q->version = 1;
184
        $q->timecreated = time();
185
        $q->timemodified = time();
186
        $q->createdby = $USER->id;
187
        $q->modifiedby = $USER->id;
188
    }
189
 
190
    public static function initialise_question_data($qdata) {
191
        global $USER;
192
 
193
        $qdata->id = 0;
194
        $qdata->category = 0;
195
        $qdata->idnumber = null;
196
        $qdata->contextid = 0;
197
        $qdata->parent = 0;
198
        $qdata->questiontextformat = FORMAT_HTML;
199
        $qdata->generalfeedbackformat = FORMAT_HTML;
200
        $qdata->defaultmark = 1;
201
        $qdata->penalty = 0.3333333;
202
        $qdata->length = 1;
203
        $qdata->stamp = make_unique_id_code();
204
        $qdata->status = \core_question\local\bank\question_version_status::QUESTION_STATUS_READY;
205
        $qdata->version = 1;
206
        $qdata->timecreated = time();
207
        $qdata->timemodified = time();
208
        $qdata->createdby = $USER->id;
209
        $qdata->modifiedby = $USER->id;
210
        $qdata->hints = array();
211
    }
212
 
213
    /**
214
     * Get the test helper class for a particular question type.
215
     * @param $qtype the question type name, e.g. 'multichoice'.
216
     * @return question_test_helper the test helper class.
217
     */
218
    public static function get_test_helper($qtype) {
219
        global $CFG;
220
 
221
        if (array_key_exists($qtype, self::$testhelpers)) {
222
            return self::$testhelpers[$qtype];
223
        }
224
 
225
        $file = core_component::get_plugin_directory('qtype', $qtype) . '/tests/helper.php';
226
        if (!is_readable($file)) {
227
            throw new coding_exception('Question type ' . $qtype .
228
                ' does not have test helper code.');
229
        }
230
        include_once($file);
231
 
232
        $class = 'qtype_' . $qtype . '_test_helper';
233
        if (!class_exists($class)) {
234
            throw new coding_exception('Class ' . $class . ' is not defined in ' . $file);
235
        }
236
 
237
        self::$testhelpers[$qtype] = new $class();
238
        return self::$testhelpers[$qtype];
239
    }
240
 
241
    /**
242
     * Call a method on a qtype_{$qtype}_test_helper class and return the result.
243
     *
244
     * @param string $methodtemplate e.g. 'make_{qtype}_question_{which}';
245
     * @param string $qtype the question type to get a test question for.
246
     * @param string $which one of the names returned by the get_test_questions
247
     *      method of the relevant qtype_{$qtype}_test_helper class.
248
     * @param unknown_type $which
249
     */
250
    protected static function call_question_helper_method($methodtemplate, $qtype, $which = null) {
251
        $helper = self::get_test_helper($qtype);
252
 
253
        $available = $helper->get_test_questions();
254
 
255
        if (is_null($which)) {
256
            $which = reset($available);
257
        } else if (!in_array($which, $available)) {
258
            throw new coding_exception('Example question ' . $which . ' of type ' .
259
                $qtype . ' does not exist.');
260
        }
261
 
262
        $method = str_replace(array('{qtype}', '{which}'),
263
            array($qtype,    $which), $methodtemplate);
264
 
265
        if (!method_exists($helper, $method)) {
266
            throw new coding_exception('Method ' . $method . ' does not exist on the ' .
267
                $qtype . ' question type test helper class.');
268
        }
269
 
270
        return $helper->$method();
271
    }
272
 
273
    /**
274
     * Question types can provide a number of test question defintions.
275
     * They do this by creating a qtype_{$qtype}_test_helper class that extends
276
     * question_test_helper. The get_test_questions method returns the list of
277
     * test questions available for this question type.
278
     *
279
     * @param string $qtype the question type to get a test question for.
280
     * @param string $which one of the names returned by the get_test_questions
281
     *      method of the relevant qtype_{$qtype}_test_helper class.
282
     * @return question_definition the requested question object.
283
     */
284
    public static function make_question($qtype, $which = null) {
285
        return self::call_question_helper_method('make_{qtype}_question_{which}',
286
            $qtype, $which);
287
    }
288
 
289
    /**
290
     * Like {@link make_question()} but returns the datastructure from
291
     * get_question_options instead of the question_definition object.
292
     *
293
     * @param string $qtype the question type to get a test question for.
294
     * @param string $which one of the names returned by the get_test_questions
295
     *      method of the relevant qtype_{$qtype}_test_helper class.
296
     * @return stdClass the requested question object.
297
     */
298
    public static function get_question_data($qtype, $which = null) {
299
        return self::call_question_helper_method('get_{qtype}_question_data_{which}',
300
            $qtype, $which);
301
    }
302
 
303
    /**
304
     * Like {@link make_question()} but returns the data what would be saved from
305
     * the question editing form instead of the question_definition object.
306
     *
307
     * @param string $qtype the question type to get a test question for.
308
     * @param string $which one of the names returned by the get_test_questions
309
     *      method of the relevant qtype_{$qtype}_test_helper class.
310
     * @return stdClass the requested question object.
311
     */
312
    public static function get_question_form_data($qtype, $which = null) {
313
        return self::call_question_helper_method('get_{qtype}_question_form_data_{which}',
314
            $qtype, $which);
315
    }
316
 
317
    /**
318
     * Makes a multichoice question with choices 'A', 'B' and 'C' shuffled. 'A'
319
     * is correct, defaultmark 1.
320
     * @return qtype_multichoice_single_question
321
     */
322
    public static function make_a_multichoice_single_question() {
323
        question_bank::load_question_definition_classes('multichoice');
324
        $mc = new qtype_multichoice_single_question();
325
        self::initialise_a_question($mc);
326
        $mc->name = 'Multi-choice question, single response';
327
        $mc->questiontext = 'The answer is A.';
328
        $mc->generalfeedback = 'You should have selected A.';
329
        $mc->qtype = question_bank::get_qtype('multichoice');
330
 
331
        $mc->shuffleanswers = 1;
332
        $mc->answernumbering = 'abc';
333
        $mc->showstandardinstruction = 0;
334
 
335
        $mc->answers = array(
336
            13 => new question_answer(13, 'A', 1, 'A is right', FORMAT_HTML),
337
            14 => new question_answer(14, 'B', -0.3333333, 'B is wrong', FORMAT_HTML),
338
            15 => new question_answer(15, 'C', -0.3333333, 'C is wrong', FORMAT_HTML),
339
        );
340
 
341
        return $mc;
342
    }
343
 
344
    /**
345
     * Makes a multichoice question with choices 'A', 'B', 'C' and 'D' shuffled.
346
     * 'A' and 'C' is correct, defaultmark 1.
347
     * @return qtype_multichoice_multi_question
348
     */
349
    public static function make_a_multichoice_multi_question() {
350
        question_bank::load_question_definition_classes('multichoice');
351
        $mc = new qtype_multichoice_multi_question();
352
        self::initialise_a_question($mc);
353
        $mc->name = 'Multi-choice question, multiple response';
354
        $mc->questiontext = 'The answer is A and C.';
355
        $mc->generalfeedback = 'You should have selected A and C.';
356
        $mc->qtype = question_bank::get_qtype('multichoice');
357
 
358
        $mc->shuffleanswers = 1;
359
        $mc->answernumbering = 'abc';
360
        $mc->showstandardinstruction = 0;
361
 
362
        self::set_standard_combined_feedback_fields($mc);
363
 
364
        $mc->answers = array(
365
            13 => new question_answer(13, 'A', 0.5, 'A is part of the right answer', FORMAT_HTML),
366
            14 => new question_answer(14, 'B', -1, 'B is wrong', FORMAT_HTML),
367
            15 => new question_answer(15, 'C', 0.5, 'C is part of the right answer', FORMAT_HTML),
368
            16 => new question_answer(16, 'D', -1, 'D is wrong', FORMAT_HTML),
369
        );
370
 
371
        return $mc;
372
    }
373
 
374
    /**
375
     * Makes a matching question to classify 'Dog', 'Frog', 'Toad' and 'Cat' as
376
     * 'Mammal', 'Amphibian' or 'Insect'.
377
     * defaultmark 1. Stems are shuffled by default.
378
     * @return qtype_match_question
379
     */
380
    public static function make_a_matching_question() {
381
        return self::make_question('match');
382
    }
383
 
384
    /**
385
     * Makes a truefalse question with correct ansewer true, defaultmark 1.
386
     * @return qtype_essay_question
387
     */
388
    public static function make_an_essay_question() {
389
        question_bank::load_question_definition_classes('essay');
390
        $essay = new qtype_essay_question();
391
        self::initialise_a_question($essay);
392
        $essay->name = 'Essay question';
393
        $essay->questiontext = 'Write an essay.';
394
        $essay->generalfeedback = 'I hope you wrote an interesting essay.';
395
        $essay->penalty = 0;
396
        $essay->qtype = question_bank::get_qtype('essay');
397
 
398
        $essay->responseformat = 'editor';
399
        $essay->responserequired = 1;
400
        $essay->responsefieldlines = 15;
401
        $essay->attachments = 0;
402
        $essay->attachmentsrequired = 0;
403
        $essay->responsetemplate = '';
404
        $essay->responsetemplateformat = FORMAT_MOODLE;
405
        $essay->graderinfo = '';
406
        $essay->graderinfoformat = FORMAT_MOODLE;
407
 
408
        return $essay;
409
    }
410
 
411
    /**
412
     * Add some standard overall feedback to a question. You need to use these
413
     * specific feedback strings for the corresponding contains_..._feedback
414
     * methods in {@link qbehaviour_walkthrough_test_base} to works.
415
     * @param question_definition|stdClass $q the question to add the feedback to.
416
     */
417
    public static function set_standard_combined_feedback_fields($q) {
418
        $q->correctfeedback = self::STANDARD_OVERALL_CORRECT_FEEDBACK;
419
        $q->correctfeedbackformat = FORMAT_HTML;
420
        $q->partiallycorrectfeedback = self::STANDARD_OVERALL_PARTIALLYCORRECT_FEEDBACK;
421
        $q->partiallycorrectfeedbackformat = FORMAT_HTML;
422
        $q->shownumcorrect = true;
423
        $q->incorrectfeedback = self::STANDARD_OVERALL_INCORRECT_FEEDBACK;
424
        $q->incorrectfeedbackformat = FORMAT_HTML;
425
    }
426
 
427
    /**
428
     * Add some standard overall feedback to a question's form data.
429
     */
430
    public static function set_standard_combined_feedback_form_data($form) {
431
        $form->correctfeedback = array('text' => self::STANDARD_OVERALL_CORRECT_FEEDBACK,
432
                                    'format' => FORMAT_HTML);
433
        $form->partiallycorrectfeedback = array('text' => self::STANDARD_OVERALL_PARTIALLYCORRECT_FEEDBACK,
434
                                             'format' => FORMAT_HTML);
435
        $form->shownumcorrect = true;
436
        $form->incorrectfeedback = array('text' => self::STANDARD_OVERALL_INCORRECT_FEEDBACK,
437
                                    'format' => FORMAT_HTML);
438
    }
439
}
440
 
441
 
442
/**
443
 * Helper for tests that need to simulate records loaded from the database.
444
 *
445
 * @copyright  2009 The Open University
446
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
447
 */
448
abstract class testing_db_record_builder {
449
    public static function build_db_records(array $table) {
450
        $columns = array_shift($table);
451
        $records = array();
452
        foreach ($table as $row) {
453
            if (count($row) != count($columns)) {
454
                throw new coding_exception("Row contains the wrong number of fields.");
455
            }
456
            $rec = new stdClass();
457
            foreach ($columns as $i => $name) {
458
                $rec->$name = $row[$i];
459
            }
460
            $records[] = $rec;
461
        }
462
        return $records;
463
    }
464
}
465
 
466
 
467
/**
468
 * Helper base class for tests that need to simulate records loaded from the
469
 * database.
470
 *
471
 * @copyright  2009 The Open University
472
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
473
 */
474
abstract class data_loading_method_test_base extends advanced_testcase {
475
    public function build_db_records(array $table) {
476
        return testing_db_record_builder::build_db_records($table);
477
    }
478
}
479
 
480
 
481
abstract class question_testcase extends advanced_testcase {
482
 
483
    /**
484
     * Tolerance accepted in some unit tests when float operations are involved.
485
     */
486
    const GRADE_DELTA = 0.00000005;
487
 
488
    public function assert($expectation, $compare, $notused = '') {
489
 
490
        if (get_class($expectation) === 'question_pattern_expectation') {
491
            $this->assertMatchesRegularExpression($expectation->pattern, $compare,
492
                    'Expected regex ' . $expectation->pattern . ' not found in ' . $compare);
493
            return;
494
 
495
        } else if (get_class($expectation) === 'question_no_pattern_expectation') {
496
            $this->assertDoesNotMatchRegularExpression($expectation->pattern, $compare,
497
                    'Unexpected regex ' . $expectation->pattern . ' found in ' . $compare);
498
            return;
499
 
500
        } else if (get_class($expectation) === 'question_contains_tag_with_attributes') {
501
            $this->assertTag(array('tag'=>$expectation->tag, 'attributes'=>$expectation->expectedvalues), $compare,
502
                    'Looking for a ' . $expectation->tag . ' with attributes ' . html_writer::attributes($expectation->expectedvalues) . ' in ' . $compare);
503
            foreach ($expectation->forbiddenvalues as $k=>$v) {
504
                $attr = $expectation->expectedvalues;
505
                $attr[$k] = $v;
506
                $this->assertNotTag(array('tag'=>$expectation->tag, 'attributes'=>$attr), $compare,
507
                        $expectation->tag . ' had a ' . $k . ' attribute that should not be there in ' . $compare);
508
            }
509
            return;
510
 
511
        } else if (get_class($expectation) === 'question_contains_tag_with_attribute') {
512
            $attr = array($expectation->attribute=>$expectation->value);
513
            $this->assertTag(array('tag'=>$expectation->tag, 'attributes'=>$attr), $compare,
514
                    'Looking for a ' . $expectation->tag . ' with attribute ' . html_writer::attributes($attr) . ' in ' . $compare);
515
            return;
516
 
517
        } else if (get_class($expectation) === 'question_does_not_contain_tag_with_attributes') {
518
            $this->assertNotTag(array('tag'=>$expectation->tag, 'attributes'=>$expectation->attributes), $compare,
519
                    'Unexpected ' . $expectation->tag . ' with attributes ' . html_writer::attributes($expectation->attributes) . ' found in ' . $compare);
520
            return;
521
 
522
        } else if (get_class($expectation) === 'question_contains_select_expectation') {
523
            $tag = array('tag'=>'select', 'attributes'=>array('name'=>$expectation->name),
524
                'children'=>array('count'=>count($expectation->choices)));
525
            if ($expectation->enabled === false) {
526
                $tag['attributes']['disabled'] = 'disabled';
527
            } else if ($expectation->enabled === true) {
528
                // TODO
529
            }
530
            foreach(array_keys($expectation->choices) as $value) {
531
                if ($expectation->selected === $value) {
532
                    $tag['child'] = array('tag'=>'option', 'attributes'=>array('value'=>$value, 'selected'=>'selected'));
533
                } else {
534
                    $tag['child'] = array('tag'=>'option', 'attributes'=>array('value'=>$value));
535
                }
536
            }
537
 
538
            $this->assertTag($tag, $compare, 'expected select not found in ' . $compare);
539
            return;
540
 
541
        } else if (get_class($expectation) === 'question_check_specified_fields_expectation') {
542
            $expect = (array)$expectation->expect;
543
            $compare = (array)$compare;
544
            foreach ($expect as $k=>$v) {
545
                if (!array_key_exists($k, $compare)) {
546
                    $this->fail("Property {$k} does not exist");
547
                }
548
                if ($v != $compare[$k]) {
549
                    $this->fail("Property {$k} is different");
550
                }
551
            }
552
            $this->assertTrue(true);
553
            return;
554
 
555
        } else if (get_class($expectation) === 'question_contains_tag_with_contents') {
556
            $this->assertTag(array('tag'=>$expectation->tag, 'content'=>$expectation->content), $compare,
557
                    'Looking for a ' . $expectation->tag . ' with content ' . $expectation->content . ' in ' . $compare);
558
            return;
559
        }
560
 
561
        throw new coding_exception('Unknown expectiontion:'.get_class($expectation));
562
    }
563
 
564
    /**
565
     * Use this function rather than assert when checking the value of options within a select element.
566
     *
567
     * @param question_contains_select_expectation $expectation The select expectation class
568
     * @param string $html The rendered output to check against
569
     */
570
    public function assert_select_options($expectation, $html) {
571
        if (get_class($expectation) !== 'question_contains_select_expectation') {
572
            throw new coding_exception('Unsuitable expectiontion: '.get_class($expectation));
573
        }
574
        $dom = new DOMDocument();
575
        $dom->loadHTML($html);
576
        $selects = $dom->getElementsByTagName('select');
1441 ariadna 577
        $this->assertGreaterThanOrEqual(1, $selects->count(), 'There is no <select> in the output.');
1 efrain 578
        foreach ($selects as $select) {
579
            if ($select->getAttribute('name') == $expectation->name) {
580
                $options = $select->getElementsByTagName('option');
581
                foreach ($options as $key => $option) {
582
                    if ($key == 0) {
583
                        // Check the value of the first option. This is often 'Choose...' or a nbsp.
584
                        // Note it is necessary to pass a nbsp character in the test here and not just ' '.
585
                        // Many tests do not require checking of this option.
586
                        if (isset($expectation->choices[$option->getAttribute('value')])) {
587
                            $this->assertEquals($expectation->choices[$option->getAttribute('value')], $option->textContent);
588
                        }
589
                        continue;
590
                    }
591
                    // Check the value of the options in the select.
592
                    $this->assertEquals($expectation->choices[$option->getAttribute('value')], $option->textContent);
593
                    if ($expectation->selected && $option->getAttribute('value') == $expectation->selected) {
594
                        // Check the right option is selected.
595
                        $this->assertTrue(!empty($option->getAttribute('selected')));
596
                    }
597
                }
598
                if ($expectation->enabled) {
599
                    // Check the select element is enabled.
600
                    $this->assertTrue(!$select->getAttribute('disabled'));
601
                }
602
            }
603
        }
604
        return;
605
    }
606
 
607
    /**
608
     * Check that 2 XML strings are the same, ignoring differences in line endings.
609
     *
610
     * @param string $expectedxml The expected XML string
611
     * @param string $xml The XML string to check
612
     */
613
    public function assert_same_xml($expectedxml, $xml) {
614
        $this->assertEquals(
615
            phpunit_util::normalise_line_endings($expectedxml),
616
            phpunit_util::normalise_line_endings($xml)
617
        );
618
    }
619
}
620
 
621
 
622
class 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
 
635
class 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
 
646
class 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
 
663
class 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
 
676
class 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
 
691
class 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
 
706
class 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
 
717
class 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 question walk-through tests.
730
 *
731
 * The purpose of tests that use this base class is to simulate the entire
732
 * interaction of a student making an attempt at a question. Therefore,
733
 * these are not really unit tests. They would more accurately be described
734
 * as integration tests. However, whether they are unit tests or not,
735
 * it works well to implement them in PHPUnit.
736
 *
737
 * Historically, tests like this were made because Moodle did not have anything
738
 * like Behat for end-to-end testing. Even though we do now have Behat, it makes
739
 * sense to keep these walk-through tests. They run massively faster than Behat
740
 * tests, which gives you a much faster feedback loop while doing development.
741
 * They also make it quite easy to test things like regrading the attempt after
742
 * the question has been edited, which would be possible but very fiddly in Behat.
743
 *
744
 * Ideally, the full set of tests for the question class of a question type would be:
745
 *
746
 * 1. A lot of unit tests for each qtype_myqtype_question class method
747
 *    like grade_response, is_complete_response, is_same_response, ...
748
 *
749
 * 2. Several of these walk-through tests, to test the end-to-end interaction
750
 *    of a student with a question, for example with different behaviours.
751
 *
752
 * 3. Just one Behat test, using question preview, to verify that everything
753
 *    is plugged together correctly and works when used through the UI.
754
 *
755
 * What one would expect to see in one of these walk-through tests is:
756
 *
757
 * // 1. Set up a question: $q.
758
 *
759
 * // 2. A call to $this->start_attempt_at_question($q, ...); with the relevant options.
760
 *
761
 * // 3. Some number of calls to $this->process_submission passing an array of simulated
762
 * //    POST data that matches what would be sent back be submitting a form that contains
763
 * //    the form fields that are output by rendering the question. This is like clicking
764
 * //    the 'Check' button in a question, or navigating to the next page in a quiz.
765
 *
766
 * // 4. A call to $this->finish(); which is the equivalent of clicking
767
 * //    'Submit all and finish' in the quiz.
768
 *
769
 * // 5. After each of steps 2-4 above, one would expect to see a certain amount of
770
 * //    validation of the state of the question and how the question is rendered,
771
 * //    using methods like $this->check_current_state(), $this->check_current_output, etc.
772
 *
773
 * The best way to work out how to write tests like this is probably to look at
774
 * some examples in other question types or question behaviours.
775
 *
776
 * In writing these tests, it is worth noting the following points:
777
 *
778
 * a) The easiest mistake to make is at step 3. You need to ensure that your
779
 *    simulated post data actually matches what gets sent back when the
780
 *    question is submitted in the browser. Try checking it against the
781
 *    HTTP POST requests you see in your browser when the question is submitted.
782
 *    Some question types have a $q->prepare_simulated_post_data() method that
783
 *    can help with this.
784
 *
785
 * b) In the past, tests like these used to contain even more repetitive code,
786
 *    and so they were re-factored to add the helper methods like
787
 *    start_attempt_at_question, process_submission, finish. That change had
788
 *    good effects, like reducing duplicate code. However, there were down-sides.
789
 *    The extra layers of indirection hide what is going on, which means these
790
 *    tests are harder to understand until you know what the helpers are doing.
791
 *    If you want an interesting exercise, take one of the walk-through tests,
792
 *    and inline all the helpers. This might be a good way to understand more about
793
 *    the question engine API. However, having made the everything-inlined code
794
 *    and learned from the process, you should then just throw it away.
795
 *
796
 * c) The way check_current_output works is weird. When these tests were first written
797
 *    Moodle used SimpleTest for unit tests and check_current_output os written in a
798
 *    style that made sense there. When we moved to PHPUnit, a quick and dirty
799
 *    conversion was done. That was a pragmatic move at the time, and we just have
800
 *    to live with the result. Sorry. (And: don't copy that style for new things.)
801
 *
802
 * @copyright  2009 The Open University
803
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
804
 */
805
abstract class qbehaviour_walkthrough_test_base extends question_testcase {
806
    /** @var question_display_options */
807
    protected $displayoptions;
808
 
809
    /** @var question_usage_by_activity */
810
    protected $quba;
811
 
812
    /** @var int The slot number of the question_attempt we are using in $quba. */
813
    protected $slot;
814
 
815
    /**
816
     * @var string after {@link render()} has been called, this contains the
817
     * display of the question in its current state.
818
     */
819
    protected $currentoutput = '';
820
 
821
    protected function setUp(): void {
822
        parent::setUp();
823
        $this->resetAfterTest();
824
        $this->setAdminUser();
825
 
826
        $this->displayoptions = new question_display_options();
827
        $this->quba = question_engine::make_questions_usage_by_activity('unit_test',
828
            context_system::instance());
829
    }
830
 
831
    protected function tearDown(): void {
832
        $this->displayoptions = null;
833
        $this->quba = null;
834
        parent::tearDown();
835
    }
836
 
837
    protected function start_attempt_at_question($question, $preferredbehaviour,
838
                                                 $maxmark = null, $variant = 1) {
839
        $this->quba->set_preferred_behaviour($preferredbehaviour);
840
        $this->slot = $this->quba->add_question($question, $maxmark);
841
        $this->quba->start_question($this->slot, $variant);
842
    }
843
 
844
    /**
845
     * Convert an array of data destined for one question to the equivalent POST data.
846
     * @param array $data the data for the quetsion.
847
     * @return array the complete post data.
848
     */
849
    protected function response_data_to_post($data) {
850
        $prefix = $this->quba->get_field_prefix($this->slot);
851
        $fulldata = array(
852
            'slots' => $this->slot,
853
            $prefix . ':sequencecheck' => $this->get_question_attempt()->get_sequence_check_count(),
854
        );
855
        foreach ($data as $name => $value) {
856
            $fulldata[$prefix . $name] = $value;
857
        }
858
        return $fulldata;
859
    }
860
 
861
    protected function process_submission($data) {
862
        // Backwards compatibility.
863
        reset($data);
864
        if (count($data) == 1 && key($data) === '-finish') {
865
            $this->finish();
866
        }
867
 
868
        $this->quba->process_all_actions(time(), $this->response_data_to_post($data));
869
    }
870
 
871
    protected function process_autosave($data) {
872
        $this->quba->process_all_autosaves(null, $this->response_data_to_post($data));
873
    }
874
 
875
    protected function finish() {
876
        $this->quba->finish_all_questions();
877
    }
878
 
879
    protected function manual_grade($comment, $mark, $commentformat = null) {
880
        $this->quba->manual_grade($this->slot, $comment, $mark, $commentformat);
881
    }
882
 
1441 ariadna 883
    protected function save_quba(?moodle_database $db = null) {
1 efrain 884
        question_engine::save_questions_usage_by_activity($this->quba, $db);
885
    }
886
 
1441 ariadna 887
    protected function load_quba(?moodle_database $db = null) {
1 efrain 888
        $this->quba = question_engine::load_questions_usage_by_activity($this->quba->get_id(), $db);
889
    }
890
 
891
    protected function delete_quba() {
892
        question_engine::delete_questions_usage_by_activity($this->quba->get_id());
893
        $this->quba = null;
894
    }
895
 
896
    /**
897
     * Asserts if the manual comment for the question is equal to the provided arguments.
898
     * @param $comment Comment text
899
     * @param $commentformat Comment format
900
     */
901
    protected function check_comment($comment, $commentformat) {
902
        $actualcomment = $this->quba->get_question_attempt($this->slot)->get_manual_comment();
903
 
904
        $this->assertEquals(
905
                [$comment, $commentformat],
906
                [$actualcomment[0], $actualcomment[1]]
907
        );
908
    }
909
 
910
    protected function check_current_state($state) {
911
        $this->assertEquals($state, $this->quba->get_question_state($this->slot),
912
            'Questions is in the wrong state.');
913
    }
914
 
915
    protected function check_current_mark($mark) {
916
        if (is_null($mark)) {
917
            $this->assertNull($this->quba->get_question_mark($this->slot));
918
        } else {
919
            if ($mark == 0) {
920
                // PHP will think a null mark and a mark of 0 are equal,
921
                // so explicity check not null in this case.
922
                $this->assertNotNull($this->quba->get_question_mark($this->slot));
923
            }
924
            $this->assertEqualsWithDelta($mark, $this->quba->get_question_mark($this->slot),
925
                 0.000001, 'Expected mark and actual mark differ.');
926
        }
927
    }
928
 
929
    /**
930
     * Generate the HTML rendering of the question in its current state in
931
     * $this->currentoutput so that it can be verified.
932
     */
933
    protected function render() {
934
        $this->quba->preload_all_step_users();
935
        $this->currentoutput = $this->quba->render_question($this->slot, $this->displayoptions);
936
    }
937
 
938
    protected function check_output_contains_text_input($name, $value = null, $enabled = true) {
939
        $attributes = array(
940
            'type' => 'text',
941
            'name' => $this->quba->get_field_prefix($this->slot) . $name,
942
        );
943
        if (!is_null($value)) {
944
            $attributes['value'] = $value;
945
        }
946
        if (!$enabled) {
947
            $attributes['readonly'] = 'readonly';
948
        }
949
        $matcher = $this->get_tag_matcher('input', $attributes);
950
        $this->assertTag($matcher, $this->currentoutput,
951
                'Looking for an input with attributes ' . html_writer::attributes($attributes) . ' in ' . $this->currentoutput);
952
 
953
        if ($enabled) {
954
            $matcher['attributes']['readonly'] = 'readonly';
955
            $this->assertNotTag($matcher, $this->currentoutput,
956
                    'input with attributes ' . html_writer::attributes($attributes) .
957
                    ' should not be read-only in ' . $this->currentoutput);
958
        }
959
    }
960
 
961
    protected function check_output_contains_text_input_with_class($name, $class = null) {
962
        $attributes = array(
963
            'type' => 'text',
964
            'name' => $this->quba->get_field_prefix($this->slot) . $name,
965
        );
966
        if (!is_null($class)) {
967
            $attributes['class'] = 'regexp:/\b' . $class . '\b/';
968
        }
969
 
970
        $matcher = $this->get_tag_matcher('input', $attributes);
971
        $this->assertTag($matcher, $this->currentoutput,
972
                'Looking for an input with attributes ' . html_writer::attributes($attributes) . ' in ' . $this->currentoutput);
973
    }
974
 
975
    protected function check_output_does_not_contain_text_input_with_class($name, $class = null) {
976
        $attributes = array(
977
            'type' => 'text',
978
            'name' => $this->quba->get_field_prefix($this->slot) . $name,
979
        );
980
        if (!is_null($class)) {
981
            $attributes['class'] = 'regexp:/\b' . $class . '\b/';
982
        }
983
 
984
        $matcher = $this->get_tag_matcher('input', $attributes);
985
        $this->assertNotTag($matcher, $this->currentoutput,
986
                'Unexpected input with attributes ' . html_writer::attributes($attributes) . ' found in ' . $this->currentoutput);
987
    }
988
 
989
    protected function check_output_contains_hidden_input($name, $value) {
990
        $attributes = array(
991
            'type' => 'hidden',
992
            'name' => $this->quba->get_field_prefix($this->slot) . $name,
993
            'value' => $value,
994
        );
995
        $this->assertTag($this->get_tag_matcher('input', $attributes), $this->currentoutput,
996
                'Looking for a hidden input with attributes ' . html_writer::attributes($attributes) . ' in ' . $this->currentoutput);
997
    }
998
 
999
    protected function check_output_contains($string) {
1000
        $this->render();
1001
        $this->assertStringContainsString($string, $this->currentoutput,
1002
                'Expected string ' . $string . ' not found in ' . $this->currentoutput);
1003
    }
1004
 
1005
    protected function check_output_does_not_contain($string) {
1006
        $this->render();
1007
        $this->assertStringNotContainsString($string, $this->currentoutput,
1008
                'String ' . $string . ' unexpectedly found in ' . $this->currentoutput);
1009
    }
1010
 
1011
    protected function check_output_contains_lang_string($identifier, $component = '', $a = null) {
1012
        $this->check_output_contains(get_string($identifier, $component, $a));
1013
    }
1014
 
1015
    protected function get_tag_matcher($tag, $attributes) {
1016
        return array(
1017
            'tag' => $tag,
1018
            'attributes' => $attributes,
1019
        );
1020
    }
1021
 
1022
    /**
1023
     * @param $condition one or more Expectations. (users varargs).
1024
     */
1025
    protected function check_current_output() {
1026
        $this->render();
1027
        foreach (func_get_args() as $condition) {
1028
            $this->assert($condition, $this->currentoutput);
1029
        }
1030
    }
1031
 
1032
    /**
1033
     * Use this function rather than check_current_output for select expectations where
1034
     * checking the value of the options is required. check_current_output only checks
1035
     * that the right number of options are available.
1036
     *
1037
     * @param question_contains_select_expectation $expectations One or more expectations.
1038
     */
1039
    protected function check_output_contains_selectoptions(...$expectations) {
1040
        $this->render();
1041
        foreach ($expectations as $expectation) {
1042
            $this->assert_select_options($expectation, $this->currentoutput);
1043
        }
1044
    }
1045
 
1046
    protected function get_question_attempt() {
1047
        return $this->quba->get_question_attempt($this->slot);
1048
    }
1049
 
1050
    protected function get_step_count() {
1051
        return $this->get_question_attempt()->get_num_steps();
1052
    }
1053
 
1054
    protected function check_step_count($expectednumsteps) {
1055
        $this->assertEquals($expectednumsteps, $this->get_step_count());
1056
    }
1057
 
1058
    protected function get_step($stepnum) {
1059
        return $this->get_question_attempt()->get_step($stepnum);
1060
    }
1061
 
1062
    protected function get_contains_question_text_expectation($question) {
1063
        return new question_pattern_expectation('/' . preg_quote($question->questiontext, '/') . '/');
1064
    }
1065
 
1066
    protected function get_contains_general_feedback_expectation($question) {
1067
        return new question_pattern_expectation('/' . preg_quote($question->generalfeedback, '/') . '/');
1068
    }
1069
 
1070
    protected function get_does_not_contain_correctness_expectation() {
1071
        return new question_no_pattern_expectation('/class=\"correctness/');
1072
    }
1073
 
1074
    protected function get_contains_correct_expectation() {
1075
        return new question_pattern_expectation('/' . preg_quote(get_string('correct', 'question'), '/') . '/');
1076
    }
1077
 
1078
    protected function get_contains_partcorrect_expectation() {
1079
        return new question_pattern_expectation('/' .
1080
            preg_quote(get_string('partiallycorrect', 'question'), '/') . '/');
1081
    }
1082
 
1083
    protected function get_contains_incorrect_expectation() {
1084
        return new question_pattern_expectation('/' . preg_quote(get_string('incorrect', 'question'), '/') . '/');
1085
    }
1086
 
1087
    protected function get_contains_standard_correct_combined_feedback_expectation() {
1088
        return new question_pattern_expectation('/' .
1089
            preg_quote(test_question_maker::STANDARD_OVERALL_CORRECT_FEEDBACK, '/') . '/');
1090
    }
1091
 
1092
    protected function get_contains_standard_partiallycorrect_combined_feedback_expectation() {
1093
        return new question_pattern_expectation('/' .
1094
            preg_quote(test_question_maker::STANDARD_OVERALL_PARTIALLYCORRECT_FEEDBACK, '/') . '/');
1095
    }
1096
 
1097
    protected function get_contains_standard_incorrect_combined_feedback_expectation() {
1098
        return new question_pattern_expectation('/' .
1099
            preg_quote(test_question_maker::STANDARD_OVERALL_INCORRECT_FEEDBACK, '/') . '/');
1100
    }
1101
 
1102
    protected function get_does_not_contain_feedback_expectation() {
1103
        return new question_no_pattern_expectation('/class="feedback"/');
1104
    }
1105
 
1106
    protected function get_does_not_contain_num_parts_correct() {
1107
        return new question_no_pattern_expectation('/class="numpartscorrect"/');
1108
    }
1109
 
1110
    protected function get_contains_num_parts_correct($num) {
1111
        $a = new stdClass();
1112
        $a->num = $num;
1113
        return new question_pattern_expectation('/<div class="numpartscorrect">' .
1114
            preg_quote(get_string('yougotnright', 'question', $a), '/') . '/');
1115
    }
1116
 
1117
    protected function get_does_not_contain_specific_feedback_expectation() {
1118
        return new question_no_pattern_expectation('/class="specificfeedback"/');
1119
    }
1120
 
1121
    protected function get_contains_validation_error_expectation() {
1122
        return new question_contains_tag_with_attribute('div', 'class', 'validationerror');
1123
    }
1124
 
1125
    protected function get_does_not_contain_validation_error_expectation() {
1126
        return new question_no_pattern_expectation('/class="validationerror"/');
1127
    }
1128
 
1129
    protected function get_contains_mark_summary($mark) {
1130
        $a = new stdClass();
1131
        $a->mark = format_float($mark, $this->displayoptions->markdp);
1132
        $a->max = format_float($this->quba->get_question_max_mark($this->slot),
1133
            $this->displayoptions->markdp);
1134
        return new question_pattern_expectation('/' .
1135
            preg_quote(get_string('markoutofmax', 'question', $a), '/') . '/');
1136
    }
1137
 
1138
    protected function get_contains_marked_out_of_summary() {
1139
        $max = format_float($this->quba->get_question_max_mark($this->slot),
1140
            $this->displayoptions->markdp);
1141
        return new question_pattern_expectation('/' .
1142
            preg_quote(get_string('markedoutofmax', 'question', $max), '/') . '/');
1143
    }
1144
 
1145
    protected function get_does_not_contain_mark_summary() {
1146
        return new question_no_pattern_expectation('/<div class="grade">/');
1147
    }
1148
 
1149
    protected function get_contains_checkbox_expectation($baseattr, $enabled, $checked) {
1150
        $expectedattributes = $baseattr;
1151
        $forbiddenattributes = array();
1152
        $expectedattributes['type'] = 'checkbox';
1153
        if ($enabled === true) {
1154
            $forbiddenattributes['disabled'] = 'disabled';
1155
        } else if ($enabled === false) {
1156
            $expectedattributes['disabled'] = 'disabled';
1157
        }
1158
        if ($checked === true) {
1159
            $expectedattributes['checked'] = 'checked';
1160
        } else if ($checked === false) {
1161
            $forbiddenattributes['checked'] = 'checked';
1162
        }
1163
        return new question_contains_tag_with_attributes('input', $expectedattributes, $forbiddenattributes);
1164
    }
1165
 
1166
    protected function get_contains_mc_checkbox_expectation($index, $enabled = null,
1167
                                                            $checked = null) {
1168
        return $this->get_contains_checkbox_expectation(array(
1169
            'name' => $this->quba->get_field_prefix($this->slot) . $index,
1170
            'value' => 1,
1171
        ), $enabled, $checked);
1172
    }
1173
 
1174
    protected function get_contains_radio_expectation($baseattr, $enabled, $checked) {
1175
        $expectedattributes = $baseattr;
1176
        $forbiddenattributes = array();
1177
        $expectedattributes['type'] = 'radio';
1178
        if ($enabled === true) {
1179
            $forbiddenattributes['disabled'] = 'disabled';
1180
        } else if ($enabled === false) {
1181
            $expectedattributes['disabled'] = 'disabled';
1182
        }
1183
        if ($checked === true) {
1184
            $expectedattributes['checked'] = 'checked';
1185
        } else if ($checked === false) {
1186
            $forbiddenattributes['checked'] = 'checked';
1187
        }
1188
        return new question_contains_tag_with_attributes('input', $expectedattributes, $forbiddenattributes);
1189
    }
1190
 
1191
    protected function get_contains_mc_radio_expectation($index, $enabled = null, $checked = null) {
1192
        return $this->get_contains_radio_expectation(array(
1193
            'name' => $this->quba->get_field_prefix($this->slot) . 'answer',
1194
            'value' => $index,
1195
        ), $enabled, $checked);
1196
    }
1197
 
1198
    protected function get_contains_hidden_expectation($name, $value = null) {
1199
        $expectedattributes = array('type' => 'hidden', 'name' => s($name));
1200
        if (!is_null($value)) {
1201
            $expectedattributes['value'] = s($value);
1202
        }
1203
        return new question_contains_tag_with_attributes('input', $expectedattributes);
1204
    }
1205
 
1206
    protected function get_does_not_contain_hidden_expectation($name, $value = null) {
1207
        $expectedattributes = array('type' => 'hidden', 'name' => s($name));
1208
        if (!is_null($value)) {
1209
            $expectedattributes['value'] = s($value);
1210
        }
1211
        return new question_does_not_contain_tag_with_attributes('input', $expectedattributes);
1212
    }
1213
 
1214
    protected function get_contains_tf_true_radio_expectation($enabled = null, $checked = null) {
1215
        return $this->get_contains_radio_expectation(array(
1216
            'name' => $this->quba->get_field_prefix($this->slot) . 'answer',
1217
            'value' => 1,
1218
        ), $enabled, $checked);
1219
    }
1220
 
1221
    protected function get_contains_tf_false_radio_expectation($enabled = null, $checked = null) {
1222
        return $this->get_contains_radio_expectation(array(
1223
            'name' => $this->quba->get_field_prefix($this->slot) . 'answer',
1224
            'value' => 0,
1225
        ), $enabled, $checked);
1226
    }
1227
 
1228
    protected function get_contains_cbm_radio_expectation($certainty, $enabled = null,
1229
                                                          $checked = null) {
1230
        return $this->get_contains_radio_expectation(array(
1231
            'name' => $this->quba->get_field_prefix($this->slot) . '-certainty',
1232
            'value' => $certainty,
1233
        ), $enabled, $checked);
1234
    }
1235
 
1236
    protected function get_contains_button_expectation($name, $value = null, $enabled = null) {
1237
        $expectedattributes = array(
1238
            'type' => 'submit',
1239
            'name' => $name,
1240
        );
1241
        $forbiddenattributes = array();
1242
        if (!is_null($value)) {
1243
            $expectedattributes['value'] = $value;
1244
        }
1245
        if ($enabled === true) {
1246
            $forbiddenattributes['disabled'] = 'disabled';
1247
        } else if ($enabled === false) {
1248
            $expectedattributes['disabled'] = 'disabled';
1249
        }
1250
        return new question_contains_tag_with_attributes('button', $expectedattributes, $forbiddenattributes);
1251
    }
1252
 
1253
    /**
1254
     * Returns an epectation that a string contains the HTML of a button with
1255
     * name {question-attempt prefix}-submit, and eiter enabled or not.
1256
     * @param bool $enabled if not null, check the enabled/disabled state of the button. True = enabled.
1257
     * @return question_contains_tag_with_attributes an expectation for use with check_current_output.
1258
     */
1259
    protected function get_contains_submit_button_expectation($enabled = null) {
1260
        return $this->get_contains_button_expectation(
1261
            $this->quba->get_field_prefix($this->slot) . '-submit', null, $enabled);
1262
    }
1263
 
1264
    /**
1265
     * Returns an epectation that a string does not contain the HTML of a button with
1266
     * name {question-attempt prefix}-submit.
1267
     * @return question_contains_tag_with_attributes an expectation for use with check_current_output.
1268
     */
1269
    protected function get_does_not_contain_submit_button_expectation() {
1270
        return new question_no_pattern_expectation('/name="' .
1271
                $this->quba->get_field_prefix($this->slot) . '-submit"/');
1272
    }
1273
 
1274
    protected function get_tries_remaining_expectation($n) {
1275
        return new question_pattern_expectation('/' .
1276
            preg_quote(get_string('triesremaining', 'qbehaviour_interactive', $n), '/') . '/');
1277
    }
1278
 
1279
    protected function get_invalid_answer_expectation() {
1280
        return new question_pattern_expectation('/' .
1281
            preg_quote(get_string('invalidanswer', 'question'), '/') . '/');
1282
    }
1283
 
1284
    protected function get_contains_try_again_button_expectation($enabled = null) {
1285
        $expectedattributes = array(
1286
            'type' => 'submit',
1287
            'name' => $this->quba->get_field_prefix($this->slot) . '-tryagain',
1288
        );
1289
        $forbiddenattributes = array();
1290
        if ($enabled === true) {
1291
            $forbiddenattributes['disabled'] = 'disabled';
1292
        } else if ($enabled === false) {
1293
            $expectedattributes['disabled'] = 'disabled';
1294
        }
1295
        return new question_contains_tag_with_attributes('input', $expectedattributes, $forbiddenattributes);
1296
    }
1297
 
1298
    protected function get_does_not_contain_try_again_button_expectation() {
1299
        return new question_no_pattern_expectation('/name="' .
1300
            $this->quba->get_field_prefix($this->slot) . '-tryagain"/');
1301
    }
1302
 
1303
    protected function get_contains_select_expectation($name, $choices,
1304
                                                       $selected = null, $enabled = null) {
1305
        $fullname = $this->quba->get_field_prefix($this->slot) . $name;
1306
        return new question_contains_select_expectation($fullname, $choices, $selected, $enabled);
1307
    }
1308
 
1309
    protected function get_mc_right_answer_index($mc) {
1310
        $order = $mc->get_order($this->get_question_attempt());
1311
        foreach ($order as $i => $ansid) {
1312
            if ($mc->answers[$ansid]->fraction == 1) {
1313
                return $i;
1314
            }
1315
        }
1316
        $this->fail('This multiple choice question does not seem to have a right answer!');
1317
    }
1318
 
1319
    protected function get_no_hint_visible_expectation() {
1320
        return new question_no_pattern_expectation('/class="hint"/');
1321
    }
1322
 
1323
    protected function get_contains_hint_expectation($hinttext) {
1324
        // Does not currently verify hint text.
1325
        return new question_contains_tag_with_attribute('div', 'class', 'hint');
1326
    }
1327
 
1328
    /**
1329
     * Returns an expectation that a string contains a corrupted question notification.
1330
     *
1331
     * @return question_pattern_expectation an expectation for use with check_current_output.
1332
     */
1333
    protected function get_contains_corruption_notification() {
1334
        return new question_pattern_expectation('/' . preg_quote(get_string('corruptedquestion', 'qtype_multianswer'), '/') . '/');
1335
    }
1336
 
1337
    /**
1338
     * Returns an expectation that a string contains a corrupted subquestion message.
1339
     *
1340
     * @return question_pattern_expectation an expectation for use with check_current_output.
1341
     */
1342
    protected function get_contains_corrupted_subquestion_message() {
1343
        return new question_pattern_expectation('/' . preg_quote(get_string('missingsubquestion', 'qtype_multianswer'), '/') . '/');
1344
    }
1345
}
1346
 
1347
/**
1348
 * Simple class that implements the {@link moodle_recordset} API based on an
1349
 * array of test data.
1350
 *
1351
 *  See the {@link question_attempt_step_db_test} class in
1352
 *  question/engine/tests/testquestionattemptstep.php for an example of how
1353
 *  this is used.
1354
 *
1355
 * @copyright  2011 The Open University
1356
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1357
 */
1358
class question_test_recordset extends moodle_recordset {
1359
    protected $records;
1360
 
1361
    /**
1362
     * Constructor
1363
     * @param $table as for {@link testing_db_record_builder::build_db_records()}
1364
     *      but does not need a unique first column.
1365
     */
1366
    public function __construct(array $table) {
1367
        $columns = array_shift($table);
1368
        $this->records = array();
1369
        foreach ($table as $row) {
1370
            if (count($row) != count($columns)) {
1371
                throw new coding_exception("Row contains the wrong number of fields.");
1372
            }
1373
            $rec = array();
1374
            foreach ($columns as $i => $name) {
1375
                $rec[$name] = $row[$i];
1376
            }
1377
            $this->records[] = $rec;
1378
        }
1379
        reset($this->records);
1380
    }
1381
 
1382
    public function __destruct() {
1383
        $this->close();
1384
    }
1385
 
1386
    #[\ReturnTypeWillChange]
1387
    public function current() {
1388
        return (object) current($this->records);
1389
    }
1390
 
1391
    #[\ReturnTypeWillChange]
1392
    public function key() {
1393
        if (is_null(key($this->records))) {
1394
            return false;
1395
        }
1396
        $current = current($this->records);
1397
        return reset($current);
1398
    }
1399
 
1400
    public function next(): void {
1401
        next($this->records);
1402
    }
1403
 
1404
    public function valid(): bool {
1405
        return !is_null(key($this->records));
1406
    }
1407
 
1408
    public function close() {
1409
        $this->records = null;
1410
    }
1411
}
1412
 
1413
/**
1414
 * Provide utility function for random question test
1415
 *
1416
 * @package   core_question
1417
 * @author     Nathan Nguyen <nathannguyen@catalyst-au.net>
1418
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1419
 */
1420
class question_filter_test_helper {
1421
    /**
1422
     * Create filters base on provided values
1423
     *
1424
     * @param array $categoryids question category filter
1425
     * @param bool $recursive subcategories filter
1426
     * @param array $qtagids tags filter
1427
     * @return array
1428
     */
1429
    public static function create_filters(array $categoryids, bool $recursive = false, array $qtagids = []): array {
1430
        $filters = [
1431
            'category' => [
1432
                'jointype' => \qbank_managecategories\category_condition::JOINTYPE_DEFAULT,
1433
                'values' => $categoryids,
1434
                'filteroptions' => ['includesubcategories' => $recursive],
1435
            ],
1436
            'qtagids' => [
1437
                'jointype' => \qbank_tagquestion\tag_condition::JOINTYPE_DEFAULT,
1438
                'values' => $qtagids,
1439
            ],
1440
        ];
1441
        return $filters;
1442
    }
1443
}