Proyectos de Subversion Moodle

Rev

Rev 11 | | 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
namespace core;
18
 
1441 ariadna 19
use core_question\local\bank\question_bank_helper;
20
use mod_quiz\quiz_settings;
1 efrain 21
use question_bank;
22
 
23
defined('MOODLE_INTERNAL') || die();
24
 
25
global $CFG;
26
 
27
require_once($CFG->libdir . '/questionlib.php');
28
require_once($CFG->dirroot . '/mod/quiz/locallib.php');
29
 
30
// Get the necessary files to perform backup and restore.
31
require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
32
require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
33
 
34
/**
35
 * Unit tests for (some of) ../questionlib.php.
36
 *
37
 * @package    core
38
 * @category   test
39
 * @copyright  2006 The Open University
40
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
41
 */
1441 ariadna 42
final class questionlib_test extends \advanced_testcase {
1 efrain 43
 
44
    /**
45
     * Test set up.
46
     *
47
     * This is executed before running any test in this file.
48
     */
49
    public function setUp(): void {
1441 ariadna 50
        parent::setUp();
1 efrain 51
        $this->resetAfterTest();
52
    }
53
 
54
    /**
1441 ariadna 55
     * Generate a course and question bank module instance for use in test cases, and return the bank context.
56
     * @return \core\context\module
57
     */
58
    protected function create_course_and_question_bank(): \core\context\module {
59
        $course = self::getDataGenerator()->create_course();
60
        $qbank = self::getDataGenerator()->create_module('qbank', ['course' => $course->id]);
61
        return \context_module::instance($qbank->cmid);
62
    }
63
 
64
    /**
1 efrain 65
     * Setup a course, a quiz, a question category and a question for testing.
66
     *
67
     * @return array The created data objects
68
     */
1441 ariadna 69
    public function setup_quiz_and_questions() {
1 efrain 70
        // Create course category.
71
        $category = $this->getDataGenerator()->create_category();
72
 
73
        // Create course.
74
        $course = $this->getDataGenerator()->create_course(array(
75
            'numsections' => 5,
76
            'category' => $category->id
77
        ));
78
 
79
        $options = array(
80
            'course' => $course->id,
81
            'duedate' => time(),
82
        );
83
 
84
        // Generate an assignment with due date (will generate a course event).
85
        $quiz = $this->getDataGenerator()->create_module('quiz', $options);
86
 
87
        /** @var \core_question_generator $qgen */
88
        $qgen = $this->getDataGenerator()->get_plugin_generator('core_question');
89
 
1441 ariadna 90
        $context = \context_module::instance($quiz->cmid);
1 efrain 91
 
92
        $qcat = $qgen->create_question_category(array('contextid' => $context->id));
93
 
94
        $questions = array(
95
                $qgen->create_question('shortanswer', null, array('category' => $qcat->id)),
96
                $qgen->create_question('shortanswer', null, array('category' => $qcat->id)),
97
        );
98
 
99
        quiz_add_quiz_question($questions[0]->id, $quiz);
100
 
101
        return array($category, $course, $quiz, $qcat, $questions);
102
    }
103
 
104
    /**
105
     * Assert that a category contains a specific number of questions.
106
     *
107
     * @param int $categoryid int Category id.
108
     * @param int $numberofquestions Number of question in a category.
109
     * @return void Questions in a category.
110
     */
111
    protected function assert_category_contains_questions(int $categoryid, int $numberofquestions): void {
112
        $questionsid = question_bank::get_finder()->get_questions_from_categories([$categoryid], null);
113
        $this->assertEquals($numberofquestions, count($questionsid));
114
    }
115
 
11 efrain 116
    public function test_question_reorder_qtypes(): void {
1 efrain 117
        $this->assertEquals(
118
            array(0 => 't2', 1 => 't1', 2 => 't3'),
119
            question_reorder_qtypes(array('t1' => '', 't2' => '', 't3' => ''), 't1', +1));
120
        $this->assertEquals(
121
            array(0 => 't1', 1 => 't2', 2 => 't3'),
122
            question_reorder_qtypes(array('t1' => '', 't2' => '', 't3' => ''), 't1', -1));
123
        $this->assertEquals(
124
            array(0 => 't2', 1 => 't1', 2 => 't3'),
125
            question_reorder_qtypes(array('t1' => '', 't2' => '', 't3' => ''), 't2', -1));
126
        $this->assertEquals(
127
            array(0 => 't1', 1 => 't2', 2 => 't3'),
128
            question_reorder_qtypes(array('t1' => '', 't2' => '', 't3' => ''), 't3', +1));
129
        $this->assertEquals(
130
            array(0 => 't1', 1 => 't2', 2 => 't3'),
131
            question_reorder_qtypes(array('t1' => '', 't2' => '', 't3' => ''), 'missing', +1));
132
    }
133
 
11 efrain 134
    public function test_match_grade_options(): void {
1 efrain 135
        $gradeoptions = question_bank::fraction_options_full();
136
 
137
        $this->assertEquals(0.3333333, match_grade_options($gradeoptions, 0.3333333, 'error'));
138
        $this->assertEquals(0.3333333, match_grade_options($gradeoptions, 0.333333, 'error'));
139
        $this->assertEquals(0.3333333, match_grade_options($gradeoptions, 0.33333, 'error'));
140
        $this->assertFalse(match_grade_options($gradeoptions, 0.3333, 'error'));
141
 
142
        $this->assertEquals(0.3333333, match_grade_options($gradeoptions, 0.3333333, 'nearest'));
143
        $this->assertEquals(0.3333333, match_grade_options($gradeoptions, 0.333333, 'nearest'));
144
        $this->assertEquals(0.3333333, match_grade_options($gradeoptions, 0.33333, 'nearest'));
145
        $this->assertEquals(0.3333333, match_grade_options($gradeoptions, 0.33, 'nearest'));
146
 
147
        $this->assertEquals(-0.1428571, match_grade_options($gradeoptions, -0.15, 'nearest'));
148
    }
149
 
150
    /**
151
     * This function tests that the functions responsible for moving questions to
152
     * different contexts also updates the tag instances associated with the questions.
153
     */
11 efrain 154
    public function test_altering_tag_instance_context(): void {
1 efrain 155
        global $CFG, $DB;
156
 
157
        // Set to admin user.
158
        $this->setAdminUser();
159
 
1441 ariadna 160
        // Create 2 qbank instances - we are going to delete one of these later and will expect
161
        // all the questions belonging to the deleted module to be moved.
1 efrain 162
        $coursecat1 = $this->getDataGenerator()->create_category();
1441 ariadna 163
        $course1 = $this->getDataGenerator()->create_course(['category' => $coursecat1->id]);
164
        $modqbank1 = $this->getDataGenerator()->create_module('qbank', ['course' => $course1->id]);
1 efrain 165
        $coursecat2 = $this->getDataGenerator()->create_category();
1441 ariadna 166
        $course2 = $this->getDataGenerator()->create_course(['category' => $coursecat2->id]);
167
        $modqbank2 = $this->getDataGenerator()->create_module('qbank', ['course' => $course2->id]);
1 efrain 168
 
169
        // Create a couple of categories and questions.
1441 ariadna 170
        $context1 = \context_module::instance($modqbank1->cmid);
171
        $context2 = \context_module::instance($modqbank2->cmid);
1 efrain 172
        /** @var \core_question_generator $questiongenerator */
173
        $questiongenerator = $this->getDataGenerator()->get_plugin_generator('core_question');
1441 ariadna 174
        $questioncat1 = question_get_default_category($context1->id);
175
        $questioncat2 = question_get_default_category($context2->id);
176
        $question1 = $questiongenerator->create_question('shortanswer', null, ['category' => $questioncat1->id]);
177
        $question2 = $questiongenerator->create_question('shortanswer', null, ['category' => $questioncat1->id]);
178
        $question3 = $questiongenerator->create_question('shortanswer', null, ['category' => $questioncat2->id]);
179
        $question4 = $questiongenerator->create_question('shortanswer', null, ['category' => $questioncat2->id]);
1 efrain 180
 
181
        // Now lets tag these questions.
1441 ariadna 182
        \core_tag_tag::set_item_tags('core_question', 'question', $question1->id, $context1, ['tag 1', 'tag 2']);
183
        \core_tag_tag::set_item_tags('core_question', 'question', $question2->id, $context1, ['tag 3', 'tag 4']);
184
        \core_tag_tag::set_item_tags('core_question', 'question', $question3->id, $context2, ['tag 5', 'tag 6']);
185
        \core_tag_tag::set_item_tags('core_question', 'question', $question4->id, $context2, ['tag 7', 'tag 8']);
1 efrain 186
 
1441 ariadna 187
        // Test moving a whole question category to another context.
1 efrain 188
        question_move_category_to_context($questioncat1->id, $questioncat1->contextid, $questioncat2->contextid);
189
 
190
        // Test that all tag_instances belong to one context.
1441 ariadna 191
        $this->assertEquals(8, $DB->count_records('tag_instance', ['component' => 'core_question',
192
            'contextid' => $questioncat2->contextid]));
1 efrain 193
 
194
        // Now test moving them back.
195
        question_move_category_to_context($questioncat1->id, $questioncat2->contextid,
1441 ariadna 196
            \context_module::instance($modqbank1->cmid)->id);
1 efrain 197
 
198
        // Test that all tag_instances are now reset to how they were initially.
1441 ariadna 199
        $this->assertEquals(4, $DB->count_records('tag_instance', ['component' => 'core_question',
200
            'contextid' => $questioncat1->contextid]));
201
        $this->assertEquals(4, $DB->count_records('tag_instance', ['component' => 'core_question',
202
            'contextid' => $questioncat2->contextid]));
1 efrain 203
 
204
        // Create a course.
205
        $course = $this->getDataGenerator()->create_course();
1441 ariadna 206
        $modqbank3 = $this->getDataGenerator()->create_module('qbank', ['course' => $course->id]);
1 efrain 207
 
208
        // Create some question categories and questions in this course.
1441 ariadna 209
        $modcontext = \context_module::instance($modqbank3->cmid);
210
        $questioncat = question_get_default_category($modcontext->id);
211
        $question1 = $questiongenerator->create_question('shortanswer', null, ['category' => $questioncat->id]);
212
        $question2 = $questiongenerator->create_question('shortanswer', null, ['category' => $questioncat->id]);
1 efrain 213
 
214
        // Add some tags to these questions.
1441 ariadna 215
        \core_tag_tag::set_item_tags('core_question', 'question', $question1->id, $modcontext, ['tag 1', 'tag 2']);
216
        \core_tag_tag::set_item_tags('core_question', 'question', $question2->id, $modcontext, ['tag 1', 'tag 2']);
1 efrain 217
 
218
        // Create a course that we are going to restore the other course to.
219
        $course2 = $this->getDataGenerator()->create_course();
220
 
221
        // Create backup file and save it to the backup location.
222
        $bc = new \backup_controller(\backup::TYPE_1COURSE, $course->id, \backup::FORMAT_MOODLE,
223
            \backup::INTERACTIVE_NO, \backup::MODE_GENERAL, 2);
224
        $bc->execute_plan();
225
        $results = $bc->get_results();
226
        $file = $results['backup_destination'];
227
        $fp = get_file_packer('application/vnd.moodle.backup');
228
        $filepath = $CFG->dataroot . '/temp/backup/test-restore-course';
229
        $file->extract_to_pathname($fp, $filepath);
230
        $bc->destroy();
231
 
232
        // Now restore the course.
233
        $rc = new \restore_controller('test-restore-course', $course2->id, \backup::INTERACTIVE_NO,
234
            \backup::MODE_GENERAL, 2, \backup::TARGET_NEW_COURSE);
235
        $rc->execute_precheck();
236
        $rc->execute_plan();
237
 
1441 ariadna 238
        $modinfo = get_fast_modinfo($course2);
239
        $qbanks = $modinfo->get_instances_of('qbank');
240
        $qbankids = array_column($qbanks, 'instance');
241
        $qbankrecords = $DB->get_records_list('qbank', 'id', $qbankids, '', 'id, type');
242
        $qbanks = array_filter($qbanks, static function($bank) use ($qbankrecords) {
243
            if (isset($qbankrecords[$bank->instance])) {
244
                return $qbankrecords[$bank->instance]->type === question_bank_helper::TYPE_STANDARD;
245
            }
246
            return false;
247
        });
248
        $qbank = reset($qbanks);
249
 
1 efrain 250
        // Get the created question category.
251
        $restoredcategory = $DB->get_record_select('question_categories', 'contextid = ? AND parent <> 0',
1441 ariadna 252
                [$qbank->context->id, '*', MUST_EXIST]);
1 efrain 253
 
254
        // Check that there are two questions in the restored to course's context.
255
        $this->assertEquals(2, $DB->get_record_sql('SELECT COUNT(q.id) as questioncount
256
                                                               FROM {question} q
257
                                                               JOIN {question_versions} qv
258
                                                                 ON qv.questionid = q.id
259
                                                               JOIN {question_bank_entries} qbe
260
                                                                 ON qbe.id = qv.questionbankentryid
261
                                                              WHERE qbe.questioncategoryid = ?',
262
            [$restoredcategory->id])->questioncount);
263
        $rc->destroy();
264
    }
265
 
266
    /**
267
     * Test that deleting a question from the question bank works in the normal case.
268
     */
11 efrain 269
    public function test_question_delete_question(): void {
1 efrain 270
        global $DB;
271
 
272
        // Setup.
1441 ariadna 273
        $context = $this->create_course_and_question_bank();
1 efrain 274
        /** @var \core_question_generator $qgen */
275
        $qgen = $this->getDataGenerator()->get_plugin_generator('core_question');
276
        $qcat = $qgen->create_question_category(array('contextid' => $context->id));
277
        $q1 = $qgen->create_question('shortanswer', null, array('category' => $qcat->id));
278
        $q2 = $qgen->create_question('shortanswer', null, array('category' => $qcat->id));
279
 
280
        // Do.
281
        question_delete_question($q1->id);
282
 
283
        // Verify.
284
        $this->assertFalse($DB->record_exists('question', ['id' => $q1->id]));
285
        // Check that we did not delete too much.
286
        $this->assertTrue($DB->record_exists('question', ['id' => $q2->id]));
287
    }
288
 
289
    /**
290
     * Test that deleting a broken question from the question bank does not cause fatal errors.
291
     */
11 efrain 292
    public function test_question_delete_question_broken_data(): void {
1 efrain 293
        global $DB;
294
 
295
        // Setup.
1441 ariadna 296
        $context = $this->create_course_and_question_bank();
1 efrain 297
        /** @var \core_question_generator $qgen */
298
        $qgen = $this->getDataGenerator()->get_plugin_generator('core_question');
299
        $qcat = $qgen->create_question_category(array('contextid' => $context->id));
300
        $q1 = $qgen->create_question('shortanswer', null, array('category' => $qcat->id));
301
 
302
        // Now delete the category, to simulate what happens in old sites where
303
        // referential integrity has failed.
304
        $DB->delete_records('question_categories', ['id' => $qcat->id]);
305
 
306
        // Do.
307
        question_delete_question($q1->id);
308
 
309
        // Verify.
310
        $this->assertDebuggingCalled('Deleting question ' . $q1->id .
311
                ' which is no longer linked to a context. Assuming system context ' .
312
                'to avoid errors, but this may mean that some data like ' .
313
                'files, tags, are not cleaned up.');
314
        $this->assertFalse($DB->record_exists('question', ['id' => $q1->id]));
315
    }
316
 
317
    /**
318
     * Test deleting a broken question whose category refers to a missing context
319
     */
11 efrain 320
    public function test_question_delete_question_missing_context(): void {
1 efrain 321
        global $DB;
322
 
1441 ariadna 323
        $context = $this->create_course_and_question_bank();
1 efrain 324
 
325
        /** @var \core_question_generator $generator */
326
        $generator = $this->getDataGenerator()->get_plugin_generator('core_question');
327
        $questioncategory = $generator->create_question_category(['contextid' => $context->id]);
328
        $question = $generator->create_question('shortanswer', null, ['category' => $questioncategory->id]);
329
 
330
        // Now delete the context, to simulate what happens in old sites where
331
        // referential integrity has failed.
332
        $DB->delete_records('context', ['id' => $context->id]);
333
 
334
        question_delete_question($question->id);
335
 
336
        $this->assertDebuggingCalled('Deleting question ' . $question->id .
337
            ' which is no longer linked to a context. Assuming system context ' .
338
            'to avoid errors, but this may mean that some data like ' .
339
            'files, tags, are not cleaned up.');
340
        $this->assertFalse($DB->record_exists('question', ['id' => $question->id]));
341
    }
342
 
343
    /**
1441 ariadna 344
     * Test parameters for calling question_category_delete_safe
345
     *
346
     * @return array
347
     */
348
    public static function delete_category_parameters(): array {
349
        return [
350
            'Delete category' => [
351
                'coursedeletion' => false,
352
            ],
353
            'Delete category with course' => [
354
                'coursedeletion' => true,
355
            ],
356
        ];
357
    }
358
 
359
    /**
1 efrain 360
     * This function tests the question_category_delete_safe function.
1441 ariadna 361
     *
362
     * @param bool $coursedeletion If true, simulate calling question_category_delete_safe as part of deletion of the whole course.
363
     * @dataProvider delete_category_parameters
364
     * @covers ::question_category_delete_safe
1 efrain 365
     */
1441 ariadna 366
    public function test_question_category_delete_safe(bool $coursedeletion): void {
1 efrain 367
        global $DB;
368
        $this->resetAfterTest(true);
369
        $this->setAdminUser();
370
 
1441 ariadna 371
        [, $course, , $qcat, $questions] = $this->setup_quiz_and_questions();
1 efrain 372
 
1441 ariadna 373
        $targetcourseid = $coursedeletion ? SITEID : $course->id;
1 efrain 374
 
1441 ariadna 375
        question_category_delete_safe($qcat, $coursedeletion);
376
 
1 efrain 377
        // Verify category deleted.
1441 ariadna 378
        $criteria = ['id' => $qcat->id];
1 efrain 379
        $this->assertEquals(0, $DB->count_records('question_categories', $criteria));
380
 
381
        // Verify questions deleted or moved.
382
        $this->assert_category_contains_questions($qcat->id, 0);
383
 
384
        // Verify question not deleted.
1441 ariadna 385
        $criteria = ['id' => $questions[0]->id];
386
        $savedquestion = $DB->get_record_sql(
387
            "SELECT q.*, qbe.questioncategoryid
388
               FROM {question} q
389
                    JOIN {question_versions} qv ON qv.questionid = q.id
390
                    JOIN {question_bank_entries} qbe ON qv.questionbankentryid = qbe.id",
391
            $criteria
392
        );
393
        $this->assertNotEmpty($savedquestion);
394
 
395
        // Verify question now sits in a system qbank in the target course.
396
        $this->assertNotEquals($qcat->id, $savedquestion->id);
397
        $newcategory = $DB->get_record('question_categories', ['id' => $savedquestion->questioncategoryid], strictness: MUST_EXIST);
398
        $newcategorycontext = context::instance_by_id($newcategory->contextid);
399
        $this->assertEquals(\context_module::LEVEL, $newcategorycontext->contextlevel);
400
        [$newcourse, $newcm] = get_course_and_cm_from_cmid($newcategorycontext->instanceid);
401
        $this->assertEquals($newcm->modname, 'qbank');
402
        $this->assertEquals(question_bank_helper::TYPE_SYSTEM, $DB->get_field('qbank', 'type', ['id' => $newcm->instance]));
403
        $this->assertEquals($targetcourseid, $newcourse->id);
1 efrain 404
    }
405
 
406
    /**
407
     * This function tests the question_delete_activity function.
408
     */
11 efrain 409
    public function test_question_delete_activity(): void {
1 efrain 410
        global $DB;
411
        $this->resetAfterTest(true);
412
        $this->setAdminUser();
413
 
414
        list($category, $course, $quiz, $qcat, $questions) = $this->setup_quiz_and_questions();
415
 
416
        $cm = get_coursemodule_from_instance('quiz', $quiz->id);
417
 
418
        // Test the deletion.
419
        question_delete_activity($cm);
420
 
421
        // Verify category deleted.
422
        $criteria = array('id' => $qcat->id);
423
        $this->assertEquals(0, $DB->count_records('question_categories', $criteria));
424
 
425
        // Verify questions deleted or moved.
426
        $this->assert_category_contains_questions($qcat->id, 0);
427
    }
428
 
429
    /**
430
     * This function tests the question_delete_context function.
1441 ariadna 431
     *
432
     * @covers ::question_delete_context()
1 efrain 433
     */
11 efrain 434
    public function test_question_delete_context(): void {
1 efrain 435
        global $DB;
436
        $this->resetAfterTest(true);
437
        $this->setAdminUser();
438
 
439
        list($category, $course, $quiz, $qcat, $questions) = $this->setup_quiz_and_questions();
440
 
441
        // Get the module context id.
442
        $result = question_delete_context($qcat->contextid);
443
 
444
        // Verify category deleted.
1441 ariadna 445
        $criteria = ['id' => $qcat->id];
1 efrain 446
        $this->assertEquals(0, $DB->count_records('question_categories', $criteria));
447
 
448
        // Verify questions deleted or moved.
449
        $this->assert_category_contains_questions($qcat->id, 0);
450
    }
451
 
452
    /**
453
     * This function tests the question_save_from_deletion function when it is supposed to make a new category and
454
     * move question categories to that new category.
1441 ariadna 455
     *
456
     * @covers ::question_save_from_deletion()
1 efrain 457
     */
11 efrain 458
    public function test_question_save_from_deletion(): void {
1 efrain 459
        global $DB;
460
        $this->resetAfterTest(true);
461
        $this->setAdminUser();
462
 
1441 ariadna 463
        [$category, $course, $quiz, $qcat, $questions] = $this->setup_quiz_and_questions();
464
        $qbank = self::getDataGenerator()->create_module('qbank', ['course' => $course->id]);
465
        $qbankcontext = \context_module::instance($qbank->cmid);
1 efrain 466
 
467
        $context = \context::instance_by_id($qcat->contextid);
468
 
1441 ariadna 469
        $newcat = question_save_from_deletion(array_column($questions, 'id'), $qbankcontext->id, $context->get_context_name());
1 efrain 470
 
471
        // Verify that the newcat itself is not a tep level category.
472
        $this->assertNotEquals(0, $newcat->parent);
473
 
474
        // Verify there is just a single top-level category.
475
        $this->assertEquals(1, $DB->count_records('question_categories', ['contextid' => $qcat->contextid, 'parent' => 0]));
476
    }
477
 
478
    /**
479
     * This function tests the question_save_from_deletion function when it is supposed to make a new category and
480
     * move question categories to that new category when quiz name is very long but less than 256 characters.
1441 ariadna 481
     *
482
     * @covers ::question_save_from_deletion()
1 efrain 483
     */
11 efrain 484
    public function test_question_save_from_deletion_quiz_with_long_name(): void {
1 efrain 485
        global $DB;
486
        $this->resetAfterTest(true);
487
        $this->setAdminUser();
488
 
1441 ariadna 489
        [$category, $course, $quiz, $qcat, $questions] = $this->setup_quiz_and_questions();
490
        $qbank = self::getDataGenerator()->create_module('qbank', ['course' => $course->id]);
491
        $qbankcontext = \context_module::instance($qbank->cmid);
1 efrain 492
 
493
        // Moodle doesn't allow you to enter a name longer than 255 characters.
494
        $quiz->name = shorten_text(str_repeat('123456789 ', 26), 255);
495
 
496
        $DB->update_record('quiz', $quiz);
497
 
498
        $context = \context::instance_by_id($qcat->contextid);
499
 
1441 ariadna 500
        $newcat = question_save_from_deletion(array_column($questions, 'id'), $qbankcontext->id, $context->get_context_name());
1 efrain 501
 
502
        // Verifying that the inserted record's name is expected or not.
503
        $this->assertEquals($DB->get_record('question_categories', ['id' => $newcat->id])->name, $newcat->name);
504
 
505
        // Verify that the newcat itself is not a top level category.
506
        $this->assertNotEquals(0, $newcat->parent);
507
 
508
        // Verify there is just a single top-level category.
509
        $this->assertEquals(1, $DB->count_records('question_categories', ['contextid' => $qcat->contextid, 'parent' => 0]));
510
    }
511
 
512
    /**
513
     * get_question_options should add the category object to the given question.
1441 ariadna 514
     *
515
     * @covers ::get_question_options()
1 efrain 516
     */
11 efrain 517
    public function test_get_question_options_includes_category_object_single_question(): void {
1441 ariadna 518
        [$category, $course, $quiz, $qcat, $questions] = $this->setup_quiz_and_questions();
1 efrain 519
        $question = array_shift($questions);
520
 
521
        get_question_options($question);
522
 
523
        $this->assertEquals($qcat, $question->categoryobject);
524
    }
525
 
526
    /**
527
     * get_question_options should add the category object to all of the questions in
528
     * the given list.
1441 ariadna 529
     *
530
     * @covers ::get_question_options()
1 efrain 531
     */
11 efrain 532
    public function test_get_question_options_includes_category_object_multiple_questions(): void {
1441 ariadna 533
        [$category, $course, $quiz, $qcat, $questions] = $this->setup_quiz_and_questions();
1 efrain 534
 
535
        get_question_options($questions);
536
 
537
        foreach ($questions as $question) {
538
            $this->assertEquals($qcat, $question->categoryobject);
539
        }
540
    }
541
 
542
    /**
543
     * get_question_options includes the tags for all questions in the list.
1441 ariadna 544
     *
545
     * @covers ::get_question_options()
1 efrain 546
     */
11 efrain 547
    public function test_get_question_options_includes_question_tags(): void {
1441 ariadna 548
        [$category, $course, $quiz, $qcat, $questions] = $this->setup_quiz_and_questions();
1 efrain 549
        $question1 = $questions[0];
550
        $question2 = $questions[1];
551
        $qcontext = \context::instance_by_id($qcat->contextid);
552
 
553
        \core_tag_tag::set_item_tags('core_question', 'question', $question1->id, $qcontext, ['foo', 'bar']);
554
        \core_tag_tag::set_item_tags('core_question', 'question', $question2->id, $qcontext, ['baz', 'bop']);
555
 
556
        get_question_options($questions, true);
557
 
558
        foreach ($questions as $question) {
559
            $tags = \core_tag_tag::get_item_tags('core_question', 'question', $question->id);
560
            $expectedtags = [];
561
            $actualtags = $question->tags;
562
            foreach ($tags as $tag) {
563
                $expectedtags[$tag->id] = $tag->get_display_name();
564
            }
565
 
566
            // The question should have a tags property populated with each tag id
567
            // and display name as a key vale pair.
568
            $this->assertEquals($expectedtags, $actualtags);
569
 
570
            $actualtagobjects = $question->tagobjects;
571
            sort($tags);
572
            sort($actualtagobjects);
573
 
574
            // The question should have a full set of each tag object.
575
            $this->assertEquals($tags, $actualtagobjects);
576
        }
577
    }
578
 
579
    /**
580
     * get_question_options should update the context id to the question category
581
     * context id for any non-course context tag that isn't in the question category
582
     * context.
1441 ariadna 583
     *
584
     * @covers ::get_question_options()
1 efrain 585
     */
11 efrain 586
    public function test_get_question_options_normalises_question_tags(): void {
1441 ariadna 587
        list($category, $course, $quiz, $qcat, $questions) = $this->setup_quiz_and_questions();
1 efrain 588
        $question1 = $questions[0];
589
        $question2 = $questions[1];
590
        $qcontext = \context::instance_by_id($qcat->contextid);
591
        $systemcontext = \context_system::instance();
592
 
593
        \core_tag_tag::set_item_tags('core_question', 'question', $question1->id, $qcontext, ['foo', 'bar']);
594
        \core_tag_tag::set_item_tags('core_question', 'question', $question2->id, $qcontext, ['baz', 'bop']);
595
 
596
        $q1tags = \core_tag_tag::get_item_tags('core_question', 'question', $question1->id);
597
        $q2tags = \core_tag_tag::get_item_tags('core_question', 'question', $question2->id);
598
        $q1tag = array_shift($q1tags);
599
        $q2tag = array_shift($q2tags);
600
 
601
        // Change two of the tag instances to be a different (non-course) context to the
602
        // question tag context. These tags should then be normalised back to the question
603
        // tag context.
604
        \core_tag_tag::change_instances_context([$q1tag->taginstanceid, $q2tag->taginstanceid], $systemcontext);
605
 
606
        get_question_options($questions, true);
607
 
608
        foreach ($questions as $question) {
609
            $tags = \core_tag_tag::get_item_tags('core_question', 'question', $question->id);
610
 
611
            // The database should have been updated with the correct context id.
612
            foreach ($tags as $tag) {
613
                $this->assertEquals($qcontext->id, $tag->taginstancecontextid);
614
            }
615
 
616
            // The tag objects on the question should have been updated with the
617
            // correct context id.
618
            foreach ($question->tagobjects as $tag) {
619
                $this->assertEquals($qcontext->id, $tag->taginstancecontextid);
620
            }
621
        }
622
    }
623
 
624
    /**
1441 ariadna 625
     * When moving all tags from one activity context into another activity context.
626
     *
627
     * @covers ::question_move_question_tags_to_new_context()
1 efrain 628
     */
1441 ariadna 629
    public function test_question_move_question_tags_to_new_context_activity_to_activity_qtags(): void {
630
        [$category, $course, $quiz, $qcat, $questions] = $this->setup_quiz_and_questions();
631
        $qbank = self::getDataGenerator()->create_module('qbank', ['course' => $course->id]);
1 efrain 632
        $question1 = $questions[0];
633
        $question2 = $questions[1];
634
        $qcontext = \context::instance_by_id($qcat->contextid);
1441 ariadna 635
        $newcontext = \context_module::instance($qbank->cmid);
1 efrain 636
 
637
        foreach ($questions as $question) {
638
            $question->contextid = $qcat->contextid;
639
        }
640
 
1441 ariadna 641
        // Create tags in the quiz context.
1 efrain 642
        \core_tag_tag::set_item_tags('core_question', 'question', $question1->id, $qcontext, ['foo']);
643
        \core_tag_tag::set_item_tags('core_question', 'question', $question2->id, $qcontext, ['foo']);
644
 
645
        question_move_question_tags_to_new_context($questions, $newcontext);
646
 
647
        foreach ($questions as $question) {
648
            $tags = \core_tag_tag::get_item_tags('core_question', 'question', $question->id);
649
 
650
            foreach ($tags as $tag) {
651
                $this->assertEquals($newcontext->id, $tag->taginstancecontextid);
652
            }
653
        }
654
    }
655
 
656
    /**
657
     * question_sort_tags() includes the tags for all questions in the list.
658
     */
11 efrain 659
    public function test_question_sort_tags_includes_question_tags(): void {
1 efrain 660
 
1441 ariadna 661
        [$category, $course, $quiz, $qcat, $questions] = $this->setup_quiz_and_questions();
1 efrain 662
        $question1 = $questions[0];
663
        $question2 = $questions[1];
664
        $qcontext = \context::instance_by_id($qcat->contextid);
665
 
666
        \core_tag_tag::set_item_tags('core_question', 'question', $question1->id, $qcontext, ['foo', 'bar']);
667
        \core_tag_tag::set_item_tags('core_question', 'question', $question2->id, $qcontext, ['baz', 'bop']);
668
 
669
        foreach ($questions as $question) {
670
            $tags = \core_tag_tag::get_item_tags('core_question', 'question', $question->id);
671
            $categorycontext = \context::instance_by_id($qcat->contextid);
672
            $tagobjects = question_sort_tags($tags, $categorycontext);
673
            $expectedtags = [];
674
            $actualtags = $tagobjects->tags;
675
            foreach ($tagobjects->tagobjects as $tag) {
676
                $expectedtags[$tag->id] = $tag->name;
677
            }
678
 
679
            // The question should have a tags property populated with each tag id
680
            // and display name as a key vale pair.
681
            $this->assertEquals($expectedtags, $actualtags);
682
 
683
            $actualtagobjects = $tagobjects->tagobjects;
684
            sort($tags);
685
            sort($actualtagobjects);
686
 
687
            // The question should have a full set of each tag object.
688
            $this->assertEquals($tags, $actualtagobjects);
689
        }
690
    }
691
 
692
    /**
693
     * Data provider for tests of question_has_capability_on_context and question_require_capability_on_context.
694
     *
695
     * @return  array
696
     */
1441 ariadna 697
    public static function question_capability_on_question_provider(): array {
1 efrain 698
        return [
699
            'Unrelated capability which is present' => [
700
                'capabilities' => [
701
                    'moodle/question:config' => CAP_ALLOW,
702
                ],
1441 ariadna 703
                'capability' => 'config',
1 efrain 704
                'isowner' => true,
705
                'expect' => true,
706
            ],
707
            'Unrelated capability which is present (not owner)' => [
708
                'capabilities' => [
709
                    'moodle/question:config' => CAP_ALLOW,
710
                ],
1441 ariadna 711
                'capability' => 'config',
1 efrain 712
                'isowner' => false,
713
                'expect' => true,
714
            ],
715
            'Unrelated capability which is not set' => [
716
                'capabilities' => [
717
                ],
1441 ariadna 718
                'capability' => 'config',
1 efrain 719
                'isowner' => true,
720
                'expect' => false,
721
            ],
722
            'Unrelated capability which is not set (not owner)' => [
723
                'capabilities' => [
724
                ],
1441 ariadna 725
                'capability' => 'config',
1 efrain 726
                'isowner' => false,
727
                'expect' => false,
728
            ],
729
            'Unrelated capability which is prevented' => [
730
                'capabilities' => [
731
                    'moodle/question:config' => CAP_PREVENT,
732
                ],
1441 ariadna 733
                'capability' => 'config',
1 efrain 734
                'isowner' => true,
735
                'expect' => false,
736
            ],
737
            'Unrelated capability which is prevented (not owner)' => [
738
                'capabilities' => [
739
                    'moodle/question:config' => CAP_PREVENT,
740
                ],
1441 ariadna 741
                'capability' => 'config',
1 efrain 742
                'isowner' => false,
743
                'expect' => false,
744
            ],
745
            'Related capability which is not set' => [
746
                'capabilities' => [
747
                ],
1441 ariadna 748
                'capability' => 'edit',
1 efrain 749
                'isowner' => true,
750
                'expect' => false,
751
            ],
752
            'Related capability which is not set (not owner)' => [
753
                'capabilities' => [
754
                ],
1441 ariadna 755
                'capability' => 'edit',
1 efrain 756
                'isowner' => false,
757
                'expect' => false,
758
            ],
759
            'Related capability which is allowed at all, unset at mine' => [
760
                'capabilities' => [
761
                    'moodle/question:editall' => CAP_ALLOW,
762
                ],
1441 ariadna 763
                'capability' => 'edit',
1 efrain 764
                'isowner' => true,
765
                'expect' => true,
766
            ],
767
            'Related capability which is allowed at all, unset at mine (not owner)' => [
768
                'capabilities' => [
769
                    'moodle/question:editall' => CAP_ALLOW,
770
                ],
1441 ariadna 771
                'capability' => 'edit',
1 efrain 772
                'isowner' => false,
773
                'expect' => true,
774
            ],
775
            'Related capability which is allowed at all, prevented at mine' => [
776
                'capabilities' => [
777
                    'moodle/question:editall' => CAP_ALLOW,
778
                    'moodle/question:editmine' => CAP_PREVENT,
779
                ],
1441 ariadna 780
                'capability' => 'edit',
1 efrain 781
                'isowner' => true,
782
                'expect' => true,
783
            ],
784
            'Related capability which is allowed at all, prevented at mine (not owner)' => [
785
                'capabilities' => [
786
                    'moodle/question:editall' => CAP_ALLOW,
787
                    'moodle/question:editmine' => CAP_PREVENT,
788
                ],
1441 ariadna 789
                'capability' => 'edit',
1 efrain 790
                'isowner' => false,
791
                'expect' => true,
792
            ],
793
            'Related capability which is unset all, allowed at mine' => [
794
                'capabilities' => [
795
                    'moodle/question:editall' => CAP_PREVENT,
796
                    'moodle/question:editmine' => CAP_ALLOW,
797
                ],
1441 ariadna 798
                'capability' => 'edit',
1 efrain 799
                'isowner' => true,
800
                'expect' => true,
801
            ],
802
            'Related capability which is unset all, allowed at mine (not owner)' => [
803
                'capabilities' => [
804
                    'moodle/question:editall' => CAP_PREVENT,
805
                    'moodle/question:editmine' => CAP_ALLOW,
806
                ],
1441 ariadna 807
                'capability' => 'edit',
1 efrain 808
                'isowner' => false,
809
                'expect' => false,
810
            ],
811
        ];
812
    }
813
 
814
    /**
815
     * Tests that question_has_capability_on does not throw exception on broken questions.
816
     */
11 efrain 817
    public function test_question_has_capability_on_broken_question(): void {
1 efrain 818
        global $DB;
819
 
820
        // Create the test data.
821
        $generator = $this->getDataGenerator();
822
         /** @var \core_question_generator $questiongenerator */
823
         $questiongenerator = $generator->get_plugin_generator('core_question');
824
 
1441 ariadna 825
        $context = $this->create_course_and_question_bank();
1 efrain 826
        $questioncat = $questiongenerator->create_question_category([
827
            'contextid' => $context->id,
828
        ]);
829
 
830
        // Create a cloze question.
1441 ariadna 831
        $question = $questiongenerator->create_question('ddwtos', null, [
1 efrain 832
            'category' => $questioncat->id,
833
        ]);
834
        // Now, break the question.
1441 ariadna 835
        $DB->delete_records('question_ddwtos', ['questionid' => $question->id]);
1 efrain 836
 
837
        $this->setAdminUser();
838
 
839
        $result = question_has_capability_on($question->id, 'tag');
840
        $this->assertTrue($result);
841
 
842
        $this->assertDebuggingCalled();
843
    }
844
 
845
    /**
846
     * Tests for the deprecated question_has_capability_on function when passing a stdClass as parameter.
847
     *
848
     * @dataProvider question_capability_on_question_provider
849
     * @param   array   $capabilities The capability assignments to set.
850
     * @param   string  $capability The capability to test
851
     * @param   bool    $isowner Whether the user to create the question should be the owner or not.
852
     * @param   bool    $expect The expected result.
853
     */
11 efrain 854
    public function test_question_has_capability_on_using_stdClass($capabilities, $capability, $isowner, $expect): void {
1 efrain 855
        $this->resetAfterTest();
856
 
857
        // Create the test data.
858
        $user = $this->getDataGenerator()->create_user();
859
        $otheruser = $this->getDataGenerator()->create_user();
860
        $roleid = $this->getDataGenerator()->create_role();
861
        $category = $this->getDataGenerator()->create_category();
862
        $context = \context_coursecat::instance($category->id);
863
 
864
        // Assign the user to the role.
865
        role_assign($roleid, $user->id, $context->id);
866
 
867
        // Assign the capabilities to the role.
868
        foreach ($capabilities as $capname => $capvalue) {
869
            assign_capability($capname, $capvalue, $roleid, $context->id);
870
        }
871
 
872
        $this->setUser($user);
873
 
874
        // The current fake question we make use of is always a stdClass and typically has no ID.
875
        $fakequestion = (object) [
876
            'contextid' => $context->id,
877
        ];
878
 
879
        if ($isowner) {
880
            $fakequestion->createdby = $user->id;
881
        } else {
882
            $fakequestion->createdby = $otheruser->id;
883
        }
884
 
885
        $result = question_has_capability_on($fakequestion, $capability);
886
        $this->assertEquals($expect, $result);
887
    }
888
 
889
    /**
890
     * Tests for the deprecated question_has_capability_on function when using question definition.
891
     *
892
     * @dataProvider question_capability_on_question_provider
893
     * @param   array   $capabilities The capability assignments to set.
894
     * @param   string  $capability The capability to test
895
     * @param   bool    $isowner Whether the user to create the question should be the owner or not.
896
     * @param   bool    $expect The expected result.
897
     */
11 efrain 898
    public function test_question_has_capability_on_using_question_definition($capabilities, $capability, $isowner, $expect): void {
1 efrain 899
        $this->resetAfterTest();
900
 
901
        // Create the test data.
902
        $generator = $this->getDataGenerator();
903
        /** @var \core_question_generator $questiongenerator */
904
        $questiongenerator = $generator->get_plugin_generator('core_question');
905
        $user = $generator->create_user();
906
        $otheruser = $generator->create_user();
907
        $roleid = $generator->create_role();
1441 ariadna 908
        $context = $this->create_course_and_question_bank();
1 efrain 909
        $questioncat = $questiongenerator->create_question_category([
910
            'contextid' => $context->id,
911
        ]);
912
 
913
        // Assign the user to the role.
914
        role_assign($roleid, $user->id, $context->id);
915
 
916
        // Assign the capabilities to the role.
917
        foreach ($capabilities as $capname => $capvalue) {
918
            assign_capability($capname, $capvalue, $roleid, $context->id);
919
        }
920
 
921
        // Create the question.
922
        $qtype = 'truefalse';
923
        $overrides = [
924
            'category' => $questioncat->id,
925
            'createdby' => ($isowner) ? $user->id : $otheruser->id,
926
        ];
927
 
928
        $question = $questiongenerator->create_question($qtype, null, $overrides);
929
 
930
        $this->setUser($user);
931
        $result = question_has_capability_on($question, $capability);
932
        $this->assertEquals($expect, $result);
933
    }
934
 
935
    /**
936
     * Tests for the deprecated question_has_capability_on function when using a real question id.
937
     *
938
     * @dataProvider question_capability_on_question_provider
939
     * @param   array   $capabilities The capability assignments to set.
940
     * @param   string  $capability The capability to test
941
     * @param   bool    $isowner Whether the user to create the question should be the owner or not.
942
     * @param   bool    $expect The expected result.
943
     */
11 efrain 944
    public function test_question_has_capability_on_using_question_id($capabilities, $capability, $isowner, $expect): void {
1 efrain 945
        $this->resetAfterTest();
946
 
947
        // Create the test data.
948
        $generator = $this->getDataGenerator();
949
        /** @var \core_question_generator $questiongenerator */
950
        $questiongenerator = $generator->get_plugin_generator('core_question');
951
        $user = $generator->create_user();
952
        $otheruser = $generator->create_user();
953
        $roleid = $generator->create_role();
1441 ariadna 954
        $context = $this->create_course_and_question_bank();
1 efrain 955
        $questioncat = $questiongenerator->create_question_category([
956
            'contextid' => $context->id,
957
        ]);
958
 
959
        // Assign the user to the role.
960
        role_assign($roleid, $user->id, $context->id);
961
 
962
        // Assign the capabilities to the role.
963
        foreach ($capabilities as $capname => $capvalue) {
964
            assign_capability($capname, $capvalue, $roleid, $context->id);
965
        }
966
 
967
        // Create the question.
968
        $qtype = 'truefalse';
969
        $overrides = [
970
            'category' => $questioncat->id,
971
            'createdby' => ($isowner) ? $user->id : $otheruser->id,
972
        ];
973
 
974
        $question = $questiongenerator->create_question($qtype, null, $overrides);
975
 
976
        $this->setUser($user);
977
        $result = question_has_capability_on($question->id, $capability);
978
        $this->assertEquals($expect, $result);
979
    }
980
 
981
    /**
982
     * Tests for the deprecated question_has_capability_on function when using a string as question id.
983
     *
984
     * @dataProvider question_capability_on_question_provider
985
     * @param   array   $capabilities The capability assignments to set.
986
     * @param   string  $capability The capability to test
987
     * @param   bool    $isowner Whether the user to create the question should be the owner or not.
988
     * @param   bool    $expect The expected result.
989
     */
11 efrain 990
    public function test_question_has_capability_on_using_question_string_id($capabilities, $capability, $isowner, $expect): void {
1 efrain 991
        $this->resetAfterTest();
992
 
993
        // Create the test data.
994
        $generator = $this->getDataGenerator();
995
        /** @var \core_question_generator $questiongenerator */
996
        $questiongenerator = $generator->get_plugin_generator('core_question');
997
        $user = $generator->create_user();
998
        $otheruser = $generator->create_user();
999
        $roleid = $generator->create_role();
1441 ariadna 1000
        $context = $this->create_course_and_question_bank();
1 efrain 1001
        $questioncat = $questiongenerator->create_question_category([
1002
            'contextid' => $context->id,
1003
        ]);
1004
 
1005
        // Assign the user to the role.
1006
        role_assign($roleid, $user->id, $context->id);
1007
 
1008
        // Assign the capabilities to the role.
1009
        foreach ($capabilities as $capname => $capvalue) {
1010
            assign_capability($capname, $capvalue, $roleid, $context->id);
1011
        }
1012
 
1013
        // Create the question.
1014
        $qtype = 'truefalse';
1015
        $overrides = [
1016
            'category' => $questioncat->id,
1017
            'createdby' => ($isowner) ? $user->id : $otheruser->id,
1018
        ];
1019
 
1020
        $question = $questiongenerator->create_question($qtype, null, $overrides);
1021
 
1022
        $this->setUser($user);
1023
        $result = question_has_capability_on((string) $question->id, $capability);
1024
        $this->assertEquals($expect, $result);
1025
    }
1026
 
1027
    /**
1028
     * Tests for the question_has_capability_on function when using a moved question.
1029
     *
1030
     * @dataProvider question_capability_on_question_provider
1031
     * @param   array   $capabilities The capability assignments to set.
1032
     * @param   string  $capability The capability to test
1033
     * @param   bool    $isowner Whether the user to create the question should be the owner or not.
1034
     * @param   bool    $expect The expected result.
1035
     */
11 efrain 1036
    public function test_question_has_capability_on_using_moved_question($capabilities, $capability, $isowner, $expect): void {
1 efrain 1037
        $this->resetAfterTest();
1038
 
1039
        // Create the test data.
1040
        $generator = $this->getDataGenerator();
1041
        /** @var \core_question_generator $questiongenerator */
1042
        $questiongenerator = $generator->get_plugin_generator('core_question');
1043
        $user = $generator->create_user();
1044
        $otheruser = $generator->create_user();
1045
        $roleid = $generator->create_role();
1441 ariadna 1046
        $context = $this->create_course_and_question_bank();
1047
        $coursecontext = $context->get_course_context();
1 efrain 1048
        $questioncat = $questiongenerator->create_question_category([
1049
            'contextid' => $context->id,
1050
        ]);
1051
 
1441 ariadna 1052
        $qbank2 = $generator->create_module('qbank', ['course' => $coursecontext->instanceid]);
1053
        $newcontext = \context_module::instance($qbank2->cmid);
1 efrain 1054
        $newquestioncat = $questiongenerator->create_question_category([
1055
            'contextid' => $newcontext->id,
1056
        ]);
1057
 
1058
        // Assign the user to the role in the _new_ context..
1059
        role_assign($roleid, $user->id, $newcontext->id);
1060
 
1061
        // Assign the capabilities to the role in the _new_ context.
1062
        foreach ($capabilities as $capname => $capvalue) {
1063
            assign_capability($capname, $capvalue, $roleid, $newcontext->id);
1064
        }
1065
 
1066
        // Create the question.
1067
        $qtype = 'truefalse';
1068
        $overrides = [
1069
            'category' => $questioncat->id,
1070
            'createdby' => ($isowner) ? $user->id : $otheruser->id,
1071
        ];
1072
 
1073
        $question = $questiongenerator->create_question($qtype, null, $overrides);
1074
 
1075
        // Move the question.
1076
        question_move_questions_to_category([$question->id], $newquestioncat->id);
1077
 
1078
        // Test that the capability is correct after the question has been moved.
1079
        $this->setUser($user);
1080
        $result = question_has_capability_on($question->id, $capability);
1081
        $this->assertEquals($expect, $result);
1082
    }
1083
 
1084
    /**
1085
     * Tests for the question_has_capability_on function when using a real question.
1086
     *
1087
     * @dataProvider question_capability_on_question_provider
1088
     * @param   array   $capabilities The capability assignments to set.
1089
     * @param   string  $capability The capability to test
1090
     * @param   bool    $isowner Whether the user to create the question should be the owner or not.
1091
     * @param   bool    $expect The expected result.
1092
     */
11 efrain 1093
    public function test_question_has_capability_on_using_question($capabilities, $capability, $isowner, $expect): void {
1 efrain 1094
        $this->resetAfterTest();
1095
 
1096
        // Create the test data.
1097
        $generator = $this->getDataGenerator();
1098
        /** @var \core_question_generator $questiongenerator */
1099
        $questiongenerator = $generator->get_plugin_generator('core_question');
1100
        $user = $generator->create_user();
1101
        $otheruser = $generator->create_user();
1102
        $roleid = $generator->create_role();
1441 ariadna 1103
        $context = $this->create_course_and_question_bank();
1 efrain 1104
        $questioncat = $questiongenerator->create_question_category([
1105
            'contextid' => $context->id,
1106
        ]);
1107
 
1108
        // Assign the user to the role.
1109
        role_assign($roleid, $user->id, $context->id);
1110
 
1111
        // Assign the capabilities to the role.
1112
        foreach ($capabilities as $capname => $capvalue) {
1113
            assign_capability($capname, $capvalue, $roleid, $context->id);
1114
        }
1115
 
1116
        // Create the question.
1117
        $question = $questiongenerator->create_question('truefalse', null, [
1118
            'category' => $questioncat->id,
1119
            'createdby' => ($isowner) ? $user->id : $otheruser->id,
1120
        ]);
1121
        $question = question_bank::load_question_data($question->id);
1122
 
1123
        $this->setUser($user);
1124
        $result = question_has_capability_on($question, $capability);
1125
        $this->assertEquals($expect, $result);
1126
    }
1127
 
1128
    /**
1129
     * Tests that question_has_capability_on throws an exception for wrong parameter types.
1130
     */
11 efrain 1131
    public function test_question_has_capability_on_wrong_param_type(): void {
1 efrain 1132
        // Create the test data.
1133
        $generator = $this->getDataGenerator();
1134
        /** @var \core_question_generator $questiongenerator */
1135
        $questiongenerator = $generator->get_plugin_generator('core_question');
1136
        $user = $generator->create_user();
1137
 
1441 ariadna 1138
        $context = $this->create_course_and_question_bank();
1 efrain 1139
        $questioncat = $questiongenerator->create_question_category([
1140
            'contextid' => $context->id,
1141
        ]);
1142
 
1143
        // Create the question.
1144
        $question = $questiongenerator->create_question('truefalse', null, [
1145
            'category' => $questioncat->id,
1146
            'createdby' => $user->id,
1147
        ]);
1148
        $question = question_bank::load_question_data($question->id);
1149
 
1150
        $this->setUser($user);
1151
        $result = question_has_capability_on((string)$question->id, 'tag');
1152
        $this->assertFalse($result);
1153
 
1154
        $this->expectException('coding_exception');
1155
        $this->expectExceptionMessage('$questionorid parameter needs to be an integer or an object.');
1156
        question_has_capability_on('one', 'tag');
1157
    }
1158
 
1159
    /**
11 efrain 1160
     * Test question_has_capability_on with an invalid question ID
1161
     */
1162
    public function test_question_has_capability_on_invalid_question(): void {
1163
        try {
1164
            question_has_capability_on(42, 'tag');
1165
            $this->fail('Expected exception');
1166
        } catch (\moodle_exception $exception) {
1167
            $this->assertInstanceOf(\dml_missing_record_exception::class, $exception);
1168
 
1169
            // We also get debugging from initial attempt to load question data.
1170
            $this->assertDebuggingCalled();
1171
        }
1172
    }
1173
 
1174
    /**
1175
     * Test that question_has_capability_on does not fail when passed an object with a null
1176
     * createdby property.
1177
     */
1178
    public function test_question_has_capability_on_object_with_null_createdby(): void {
1179
        $this->resetAfterTest();
1180
        $generator = $this->getDataGenerator();
1181
        $user = $generator->create_user();
1182
        $category = $generator->create_category();
1183
        $context = \context_coursecat::instance($category->id);
1184
 
1185
        $role = $generator->create_role();
1186
        role_assign($role, $user->id, $context->id);
1187
        assign_capability('moodle/question:editmine', CAP_ALLOW, $role, $context->id);
1188
 
1189
        $this->setUser($user);
1190
 
1191
        $fakequestion = (object) [
1192
            'contextid' => $context->id,
1193
            'createdby' => null,
1194
        ];
1195
 
1196
        $this->assertFalse(question_has_capability_on($fakequestion, 'edit'));
1197
 
1198
        $fakequestion->createdby = $user->id;
1199
 
1200
        $this->assertTrue(question_has_capability_on($fakequestion, 'edit'));
1201
    }
1202
 
1203
    /**
1 efrain 1204
     * Test of question_categorylist function.
1205
     *
1206
     * @covers ::question_categorylist()
1207
     */
1208
    public function test_question_categorylist(): void {
1209
        $this->resetAfterTest();
1210
 
1211
        // Create a category tree.
1212
        /** @var \core_question_generator $questiongenerator */
1213
        $questiongenerator = $this->getDataGenerator()->get_plugin_generator('core_question');
1214
        // Create a Course.
1441 ariadna 1215
        $context = $this->create_course_and_question_bank();
1 efrain 1216
 
1441 ariadna 1217
        $top = question_get_top_category($context->id, true);
1218
        $cat1 = question_get_default_category($context->id);
1 efrain 1219
        $sub11 = $questiongenerator->create_question_category(['parent' => $cat1->id]);
1220
        $sub12 = $questiongenerator->create_question_category(['parent' => $cat1->id]);
1221
        $cat2 = $questiongenerator->create_question_category(['parent' => $top->id]);
1222
        $sub22 = $questiongenerator->create_question_category(['parent' => $cat2->id]);
1223
 
1224
        // Test - returned array has keys and values the same.
1225
        $this->assertEquals([$sub22->id], array_keys(question_categorylist($sub22->id)));
1226
        $this->assertEquals([$sub22->id], array_values(question_categorylist($sub22->id)));
1227
        $this->assertEquals([$cat1->id, $sub11->id, $sub12->id], array_keys(question_categorylist($cat1->id)));
1228
        $this->assertEquals([$cat1->id, $sub11->id, $sub12->id], array_values(question_categorylist($cat1->id)));
1229
        $this->assertEquals([$top->id, $cat1->id, $cat2->id, $sub11->id, $sub12->id, $sub22->id],
1230
                array_keys(question_categorylist($top->id)));
1231
        $this->assertEquals([$top->id, $cat1->id, $cat2->id, $sub11->id, $sub12->id, $sub22->id],
1232
                array_values(question_categorylist($top->id)));
1233
    }
1234
 
1235
    /**
1236
     * Test of question_categorylist function when there is bad data, with a category pointing to a parent in another context.
1237
     *
1238
     * This is a situation that should never arise (parents and their children should always belong to the same context)
1239
     * but it does, because bugs, so the code should be robust to it.
1240
     *
1241
     * @covers ::question_categorylist()
1242
     */
1243
    public function test_question_categorylist_bad_data(): void {
1244
        $this->resetAfterTest();
1245
 
1246
        // Create a category tree.
1247
        $course = $this->getDataGenerator()->create_course();
1441 ariadna 1248
        $qbank1 = self::getDataGenerator()->create_module('qbank', ['course' => $course->id]);
1249
        $bank1context = \context_module::instance($qbank1->cmid);
1250
        $qbank2 = self::getDataGenerator()->create_module('qbank', ['course' => $course->id]);
1 efrain 1251
        /** @var \core_question_generator $questiongenerator */
1252
        $questiongenerator = $this->getDataGenerator()->get_plugin_generator('core_question');
1441 ariadna 1253
        $wrongcontext = \context_module::instance($qbank2->cmid);
1 efrain 1254
 
1441 ariadna 1255
        $top = question_get_top_category($bank1context->id, true);
1256
        $cat1 = question_get_default_category($bank1context->id);
1 efrain 1257
        $sub11 = $questiongenerator->create_question_category(['parent' => $cat1->id]);
1258
        $sub12 = $questiongenerator->create_question_category(['parent' => $cat1->id]);
1441 ariadna 1259
        $cat2 = $questiongenerator->create_question_category(['parent' => $top->id, 'contextid' => $wrongcontext->id]);
1 efrain 1260
        $sub22 = $questiongenerator->create_question_category(['parent' => $cat2->id]);
1261
 
1262
        // Test - returned array has keys and values the same.
1263
        $this->assertEquals([$cat2->id, $sub22->id], array_keys(question_categorylist($cat2->id)));
1264
        $this->assertEquals([$top->id, $cat1->id, $sub11->id, $sub12->id],
1265
                array_keys(question_categorylist($top->id)));
1266
    }
1267
 
1268
    /**
1269
     * Test of question_categorylist_parents function.
1270
     *
1271
     * @covers ::question_categorylist_parents()
1272
     */
1273
    public function test_question_categorylist_parents(): void {
1274
        $this->resetAfterTest();
1275
        $generator = $this->getDataGenerator();
1276
        /** @var \core_question_generator $questiongenerator */
1277
        $questiongenerator = $generator->get_plugin_generator('core_question');
1441 ariadna 1278
        $context = $this->create_course_and_question_bank();
1 efrain 1279
        // Create a top category.
1280
        $cat0 = question_get_top_category($context->id, true);
1281
        // Add sub-categories.
1282
        $cat1 = $questiongenerator->create_question_category(['parent' => $cat0->id]);
1283
        $cat2 = $questiongenerator->create_question_category(['parent' => $cat1->id]);
1284
 
1285
        // Test the 'get parents' function.
1286
        $this->assertEquals([$cat0->id, $cat1->id], question_categorylist_parents($cat2->id));
1287
    }
1288
 
1289
    /**
1290
     * Test question_categorylist_parents when there is bad data, with a category pointing to a parent in another context.
1291
     *
1292
     * This is a situation that should never arise (parents and their children should always belong to the same context)
1293
     * but it does, because bugs, so the code should be robust to it.
1294
     *
1295
     * @covers ::question_categorylist_parents()
1296
     */
1297
    public function test_question_categorylist_parents_bad_data(): void {
1298
        $this->resetAfterTest();
1299
        $generator = $this->getDataGenerator();
1300
        /** @var \core_question_generator $questiongenerator */
1301
        $questiongenerator = $generator->get_plugin_generator('core_question');
1441 ariadna 1302
        $bank1context = $this->create_course_and_question_bank();
1303
        $coursecontext = $bank1context->get_course_context();
1304
        $qbank2 = self::getDataGenerator()->create_module('qbank', ['course' => $coursecontext->instanceid]);
1305
        $bank2context = \context_module::instance($qbank2->cmid);
1306
 
1 efrain 1307
        // Create a top category.
1441 ariadna 1308
        $cat0 = question_get_top_category($bank1context->id, true);
1 efrain 1309
        // Add sub-categories - but in a different context.
1310
        $cat1 = $questiongenerator->create_question_category(
1441 ariadna 1311
            ['parent' => $cat0->id, 'contextid' => $bank2context->id]);
1 efrain 1312
        $cat2 = $questiongenerator->create_question_category(
1441 ariadna 1313
            ['parent' => $cat1->id, 'contextid' => $bank2context->id]);
1 efrain 1314
 
1315
        // Test the 'get parents' function only returns categories in the same context.
1316
        $this->assertEquals([$cat1->id], question_categorylist_parents($cat2->id));
1317
    }
1318
 
1319
    /**
1320
     * Get test cases for test_core_question_find_next_unused_idnumber.
1321
     *
1322
     * @return array test cases.
1323
     */
1441 ariadna 1324
    public static function find_next_unused_idnumber_cases(): array {
1 efrain 1325
        return [
1326
            [null, null],
1327
            ['id', null],
1328
            ['id1a', null],
1329
            ['id001', 'id002'],
1330
            ['id9', 'id10'],
1331
            ['id009', 'id010'],
1332
            ['id999', 'id1000'],
1333
            ['0', '1'],
1334
            ['-1', '-2'],
1335
            ['01', '02'],
1336
            ['09', '10'],
1337
            ['1.0E+29', '1.0E+30'], // Idnumbers are strings, not floats.
1338
            ['1.0E-29', '1.0E-30'], // By the way, this is not a sensible idnumber!
1339
            ['10.1', '10.2'],
1340
            ['10.9', '10.10'],
1341
 
1342
        ];
1343
    }
1344
 
1345
    /**
1346
     * Test core_question_find_next_unused_idnumber in the case when there are no other questions.
1347
     *
1348
     * @dataProvider find_next_unused_idnumber_cases
1349
     * @param string|null $oldidnumber value to pass to core_question_find_next_unused_idnumber.
1350
     * @param string|null $expectednewidnumber expected result.
1351
     */
11 efrain 1352
    public function test_core_question_find_next_unused_idnumber(?string $oldidnumber, ?string $expectednewidnumber): void {
1 efrain 1353
        $this->assertSame($expectednewidnumber, core_question_find_next_unused_idnumber($oldidnumber, 0));
1354
    }
1355
 
11 efrain 1356
    public function test_core_question_find_next_unused_idnumber_skips_used(): void {
1 efrain 1357
        $this->resetAfterTest();
1358
 
1359
        /** @var core_question_generator $generator */
1360
        $generator = $this->getDataGenerator()->get_plugin_generator('core_question');
1361
        $category = $generator->create_question_category();
1362
        $othercategory = $generator->create_question_category();
1363
        $generator->create_question('truefalse', null, ['category' => $category->id, 'idnumber' => 'id9']);
1364
        $generator->create_question('truefalse', null, ['category' => $category->id, 'idnumber' => 'id10']);
1365
        // Next one to make sure only idnumbers from the right category are ruled out.
1366
        $generator->create_question('truefalse', null, ['category' => $othercategory->id, 'idnumber' => 'id11']);
1367
 
1368
        $this->assertSame('id11', core_question_find_next_unused_idnumber('id9', $category->id));
1369
        $this->assertSame('id11', core_question_find_next_unused_idnumber('id8', $category->id));
1370
    }
1371
 
1372
    /**
1373
     * Tests for the question_move_questions_to_category function.
1374
     *
1375
     * @covers ::question_move_questions_to_category
1376
     */
11 efrain 1377
    public function test_question_move_questions_to_category(): void {
1 efrain 1378
        $this->resetAfterTest();
1379
 
1380
        // Create the test data.
1381
        list($category1, $course1, $quiz1, $questioncat1, $questions1) = $this->setup_quiz_and_questions();
1382
        list($category2, $course2, $quiz2, $questioncat2, $questions2) = $this->setup_quiz_and_questions();
1383
 
1384
        $this->assertCount(2, $questions1);
1385
        $this->assertCount(2, $questions2);
1386
        $questionsidtomove = [];
1387
        foreach ($questions1 as $question1) {
1388
            $questionsidtomove[] = $question1->id;
1389
        }
1390
 
1391
        // Move the question from quiz 1 to quiz 2.
1392
        question_move_questions_to_category($questionsidtomove, $questioncat2->id);
1393
        $this->assert_category_contains_questions($questioncat2->id, 4);
1394
    }
1395
 
1396
    /**
1397
     * Tests for the idnumber_exist_in_question_category function.
1398
     *
1399
     * @covers ::idnumber_exist_in_question_category
1400
     */
11 efrain 1401
    public function test_idnumber_exist_in_question_category(): void {
1 efrain 1402
        global $DB;
1403
 
1404
        $this->resetAfterTest();
1405
 
1406
        // Create the test data.
1407
        list($category1, $course1, $quiz1, $questioncat1, $questions1) = $this->setup_quiz_and_questions();
1408
        list($category2, $course2, $quiz2, $questioncat2, $questions2) = $this->setup_quiz_and_questions();
1409
 
1410
        $questionbankentry1 = get_question_bank_entry($questions1[0]->id);
1411
        $entry = new \stdClass();
1412
        $entry->id = $questionbankentry1->id;
1413
        $entry->idnumber = 1;
1414
        $DB->update_record('question_bank_entries', $entry);
1415
 
1416
        $questionbankentry2 = get_question_bank_entry($questions2[0]->id);
1417
        $entry2 = new \stdClass();
1418
        $entry2->id = $questionbankentry2->id;
1419
        $entry2->idnumber = 1;
1420
        $DB->update_record('question_bank_entries', $entry2);
1421
 
1422
        $questionbe = $DB->get_record('question_bank_entries', ['id' => $questionbankentry1->id]);
1423
 
1424
        // Validate that a first stage of an idnumber exists (this format: xxxx_x).
1425
        list($response, $record) = idnumber_exist_in_question_category($questionbe->idnumber, $questioncat1->id);
1426
        $this->assertEquals([], $record);
1427
        $this->assertEquals(true, $response);
1428
 
1429
        // Move the question to a category that has a question with the same idnumber.
1430
        question_move_questions_to_category($questions1[0]->id, $questioncat2->id);
1431
 
1432
        // Validate that function return the last record used for the idnumber.
1433
        list($response, $record) = idnumber_exist_in_question_category($questionbe->idnumber, $questioncat2->id);
1434
        $record = reset($record);
1435
        $idnumber = $record->idnumber;
1436
        $this->assertEquals($idnumber, '1_1');
1437
        $this->assertEquals(true, $response);
1438
    }
1439
 
1440
    /**
1441
     * Test method is_latest().
1442
     *
1443
     * @covers ::is_latest
1444
     *
1445
     */
11 efrain 1446
    public function test_is_latest(): void {
1 efrain 1447
        global $DB;
1448
        $this->resetAfterTest();
1449
        /** @var \core_question_generator $generator */
1450
        $generator = $this->getDataGenerator()->get_plugin_generator('core_question');
1451
        $qcat1 = $generator->create_question_category(['name' => 'My category', 'sortorder' => 1, 'idnumber' => 'myqcat']);
1452
        $question = $generator->create_question('shortanswer', null, ['name' => 'q1', 'category' => $qcat1->id]);
1453
        $record = $DB->get_record('question_versions', ['questionid' => $question->id]);
1454
        $firstversion = $record->version;
1455
        $questionbankentryid = $record->questionbankentryid;
1456
        $islatest = is_latest($firstversion, $questionbankentryid);
1457
        $this->assertTrue($islatest);
1458
    }
1459
 
1460
    /**
1461
     * Test question bank entry deletion.
1462
     *
1463
     * @covers ::delete_question_bank_entry
1464
     */
11 efrain 1465
    public function test_delete_question_bank_entry(): void {
1 efrain 1466
        global $DB;
1467
        $this->resetAfterTest();
1468
        // Setup.
1441 ariadna 1469
        $context = $this->create_course_and_question_bank();
1 efrain 1470
        /** @var \core_question_generator $qgen */
1471
        $qgen = $this->getDataGenerator()->get_plugin_generator('core_question');
1472
        $qcat = $qgen->create_question_category(array('contextid' => $context->id));
1473
        $q1 = $qgen->create_question('shortanswer', null, array('category' => $qcat->id));
1474
        // Make sure there is an entry in the entry table.
1475
        $sql = 'SELECT qbe.id as id,
1476
                       qv.id as versionid
1477
                  FROM {question_bank_entries} qbe
1478
                  JOIN {question_versions} qv
1479
                    ON qbe.id = qv.questionbankentryid
1480
                  JOIN {question} q
1481
                    ON qv.questionid = q.id
1482
                 WHERE q.id = ?';
1483
        $records = $DB->get_records_sql($sql, [$q1->id]);
1484
        $this->assertCount(1, $records);
1485
        // Delete the record.
1486
        $record = reset($records);
1487
        delete_question_bank_entry($record->id);
1488
        $records = $DB->get_records('question_bank_entries', ['id' => $record->id]);
1489
        // As the version record exists, it wont delete the data to resolve any errors.
1490
        $this->assertCount(1, $records);
1491
        $DB->delete_records('question_versions', ['id' => $record->versionid]);
1492
        delete_question_bank_entry($record->id);
1493
        $records = $DB->get_records('question_bank_entries', ['id' => $record->id]);
1494
        $this->assertCount(0, $records);
1495
    }
1496
 
1497
    /**
1498
     * Test question bank entry object.
1499
     *
1500
     * @covers ::get_question_bank_entry
1501
     */
11 efrain 1502
    public function test_get_question_bank_entry(): void {
1 efrain 1503
        global $DB;
1504
        $this->resetAfterTest();
1505
        // Setup.
1441 ariadna 1506
        $context = $this->create_course_and_question_bank();
1 efrain 1507
        /** @var \core_question_generator $qgen */
1508
        $qgen = $this->getDataGenerator()->get_plugin_generator('core_question');
1509
        $qcat = $qgen->create_question_category(array('contextid' => $context->id));
1510
        $q1 = $qgen->create_question('shortanswer', null, array('category' => $qcat->id));
1511
        // Make sure there is an entry in the entry table.
1512
        $sql = 'SELECT qbe.id as id,
1513
                       qv.id as versionid
1514
                  FROM {question_bank_entries} qbe
1515
                  JOIN {question_versions} qv
1516
                    ON qbe.id = qv.questionbankentryid
1517
                  JOIN {question} q
1518
                    ON qv.questionid = q.id
1519
                 WHERE q.id = ?';
1520
        $records = $DB->get_records_sql($sql, [$q1->id]);
1521
        $this->assertCount(1, $records);
1522
        $record = reset($records);
1523
        $questionbankentry = get_question_bank_entry($q1->id);
1524
        $this->assertEquals($questionbankentry->id, $record->id);
1525
    }
1526
 
1527
    /**
1528
     * Test the version objects for a question.
1529
     *
1530
     * @covers ::get_question_version
1531
     */
11 efrain 1532
    public function test_get_question_version(): void {
1 efrain 1533
        global $DB;
1534
        $this->resetAfterTest();
1535
        // Setup.
1441 ariadna 1536
        $context = $this->create_course_and_question_bank();
1 efrain 1537
        /** @var \core_question_generator $qgen */
1538
        $qgen = $this->getDataGenerator()->get_plugin_generator('core_question');
1539
        $qcat = $qgen->create_question_category(array('contextid' => $context->id));
1540
        $q1 = $qgen->create_question('shortanswer', null, array('category' => $qcat->id));
1541
        // Make sure there is an entry in the entry table.
1542
        $sql = 'SELECT qbe.id as id,
1543
                       qv.id as versionid
1544
                  FROM {question_bank_entries} qbe
1545
                  JOIN {question_versions} qv
1546
                    ON qbe.id = qv.questionbankentryid
1547
                  JOIN {question} q
1548
                    ON qv.questionid = q.id
1549
                 WHERE q.id = ?';
1550
        $records = $DB->get_records_sql($sql, [$q1->id]);
1551
        $this->assertCount(1, $records);
1552
        $record = reset($records);
1553
        $questionversions = get_question_version($q1->id);
1554
        $questionversion = reset($questionversions);
1555
        $this->assertEquals($questionversion->id, $record->versionid);
1556
    }
1557
 
1558
    /**
1559
     * Test get next version of a question.
1560
     *
1561
     * @covers ::get_next_version
1562
     */
11 efrain 1563
    public function test_get_next_version(): void {
1 efrain 1564
        global $DB;
1565
        $this->resetAfterTest();
1566
        // Setup.
1441 ariadna 1567
        $context = $this->create_course_and_question_bank();
1 efrain 1568
        /** @var \core_question_generator $qgen */
1569
        $qgen = $this->getDataGenerator()->get_plugin_generator('core_question');
1570
        $qcat = $qgen->create_question_category(array('contextid' => $context->id));
1571
        $q1 = $qgen->create_question('shortanswer', null, array('category' => $qcat->id));
1572
        // Make sure there is an entry in the entry table.
1573
        $sql = 'SELECT qbe.id as id,
1574
                       qv.id as versionid,
1575
                       qv.version
1576
                  FROM {question_bank_entries} qbe
1577
                  JOIN {question_versions} qv
1578
                    ON qbe.id = qv.questionbankentryid
1579
                  JOIN {question} q
1580
                    ON qv.questionid = q.id
1581
                 WHERE q.id = ?';
1582
        $records = $DB->get_records_sql($sql, [$q1->id]);
1583
        $this->assertCount(1, $records);
1584
        $record = reset($records);
1585
        $this->assertEquals(1, $record->version);
1586
        $nextversion = get_next_version($record->id);
1587
        $this->assertEquals(2, $nextversion);
1588
    }
1589
 
1441 ariadna 1590
    /**
1591
     * Test moving a question category from one context to another
1592
     *
1593
     * @covers ::question_move_category_to_context
1594
     */
1595
    public function test_question_move_category_to_context(): void {
1596
 
1597
        global $CFG, $DB;
1598
 
1599
        $this->setAdminUser();
1600
 
1601
        // Create a course.
1602
        $course = self::getDataGenerator()->create_course();
1603
 
1604
        // Create a quiz activity to store our question in at the start.
1605
        $quiz1 = $this->getDataGenerator()->create_module('quiz', [
1606
            'course' => $course->id,
1607
        ]);
1608
 
1609
        // And then create another one to move the category to.
1610
        $quiz2 = $this->getDataGenerator()->create_module('quiz', [
1611
            'course' => $course->id,
1612
        ]);
1613
 
1614
        // Get the question generator and the context of the activities.
1615
        $generator = self::getDataGenerator()->get_plugin_generator('core_question');
1616
        $context1 = \context_module::instance($quiz1->cmid);
1617
        $context2 = \context_module::instance($quiz2->cmid);
1618
 
1619
        // Create a question category within our first quiz activity.
1620
        $category = $generator->create_question_category(['contextid' => $context1->id]);
1621
 
1622
        // And create a question within that.
1623
        // We will use `truefalse` but it could be any type.
1624
        $question = $generator->create_question('truefalse', null, ['category' => $category->id]);
1625
 
1626
        $areas = [
1627
            'questiontext' => '1.jpg',
1628
            'generalfeedback' => '2.jpg',
1629
        ];
1630
 
1631
        // Add file records to each of the file areas, for our first quiz activity.
1632
        foreach ($areas as $area => $img) {
1633
            $fs = get_file_storage();
1634
            $filerecord = new \stdClass();
1635
            $filerecord->contextid = $context1->id;
1636
            $filerecord->component = 'question';
1637
            $filerecord->filearea = $area;
1638
            $filerecord->itemid = $question->id;
1639
            $filerecord->filepath = '/';
1640
            $filerecord->filename = $img;
1641
            $fs->create_file_from_pathname($filerecord, $CFG->dirroot .
1642
                '/lib/tests/fixtures/' . $img);
1643
        }
1644
 
1645
        // Firstly, confirm that the file records exist and there were no problems creating them.
1646
        // We don't care in this test about the actual files in the data dir.
1647
        $files = $DB->get_records('files', [
1648
            'component' => 'question',
1649
            'itemid' => $question->id,
1650
            'contextid' => $context1->id,
1651
            'mimetype' => 'image/jpeg',
1652
        ]);
1653
 
1654
        $this->assertCount(2, $files);
1655
 
1656
        // Move the question category to another context.
1657
        question_move_category_to_context(
1658
            $category->id,
1659
            $context1->id,
1660
            $context2->id,
1661
        );
1662
 
1663
        // Now check that the files have been moved to the new category.
1664
        $files = $DB->get_records('files', [
1665
            'component' => 'question',
1666
            'itemid' => $question->id,
1667
            'contextid' => $context2->id,
1668
            'mimetype' => 'image/jpeg',
1669
        ]);
1670
 
1671
        $this->assertCount(2, $files);
1672
 
1673
    }
1674
 
1675
    /**
1676
     * Update the context for a set reference, keeping the original category.
1677
     *
1678
     * @covers ::move_question_set_references()
1679
     */
1680
    public function test_move_question_set_references_context(): void {
1681
        $this->setAdminUser();
1682
        // Create a course with a quiz containing a random question from a qbank context.
1683
        $randomcourse = self::getDataGenerator()->create_course(['shortname' => 'Random']);
1684
        $qbank1 = self::getDataGenerator()->get_plugin_generator('mod_qbank')->create_instance(['course' => $randomcourse->id]);
1685
        $context1 = \context_module::instance($qbank1->cmid);
1686
        $qbank2 = self::getDataGenerator()->get_plugin_generator('mod_qbank')->create_instance(['course' => $randomcourse->id]);
1687
        $context2 = \context_module::instance($qbank2->cmid);
1688
        $topcategory = question_get_top_category($context1->id, true);
1689
        $randomcategory = self::getDataGenerator()->get_plugin_generator('core_question')->create_question_category(
1690
            ['parent' => $topcategory->id],
1691
        );
1692
        $randomquiz = self::getDataGenerator()->get_plugin_generator('mod_quiz')->create_instance(
1693
            [
1694
                'course' => $randomcourse->id,
1695
                'grade' => 100.0,
1696
                'sumgrades' => 2,
1697
                'layout' => '1,0',
1698
            ],
1699
        );
1700
 
1701
        $randomquizsettings = quiz_settings::create($randomquiz->id);
1702
        $structure = $randomquizsettings->get_structure();
1703
 
1704
        $filtercondition = [
1705
            'filter' => [
1706
                'category' => [
1707
                    'jointype' => \core_question\local\bank\condition::JOINTYPE_DEFAULT,
1708
                    'values' => [$randomcategory->id],
1709
                    'filteroptions' => ['includesubcategories' => true],
1710
                ],
1711
            ],
1712
        ];
1713
        $structure->add_random_questions(1, 1, $filtercondition);
1714
        $structure = $randomquizsettings->get_structure();
1715
        $randomquestion = $structure->get_question_in_slot(1);
1716
 
1717
        $this->assertEquals($randomquestion->contextid, $context1->id);
1718
        $this->assertEquals($randomquestion->filtercondition['filter']['category']['values'][0], $randomcategory->id);
1719
 
1720
        move_question_set_references($randomcategory->id, $randomcategory->id, $context1->id, $context2->id);
1721
 
1722
        $structure = $randomquizsettings->get_structure();
1723
        $randomquestion = $structure->get_question_in_slot(1);
1724
 
1725
        $this->assertEquals($randomquestion->contextid, $context2->id);
1726
        $this->assertEquals($randomquestion->filtercondition['filter']['category']['values'][0], $randomcategory->id);
1727
    }
1728
 
1729
    /**
1730
     * Update the context and category for a set reference.
1731
     *
1732
     * @covers ::move_question_set_references()
1733
     */
1734
    public function test_move_question_set_references_category(): void {
1735
        $this->setAdminUser();
1736
        // Create a course with a quiz containing a random question from a qbank context.
1737
        $randomcourse = self::getDataGenerator()->create_course(['shortname' => 'Random']);
1738
        $qbank1 = self::getDataGenerator()->get_plugin_generator('mod_qbank')->create_instance(['course' => $randomcourse->id]);
1739
        $context1 = \context_module::instance($qbank1->cmid);
1740
        $qbank2 = self::getDataGenerator()->get_plugin_generator('mod_qbank')->create_instance(['course' => $randomcourse->id]);
1741
        $context2 = \context_module::instance($qbank2->cmid);
1742
        $topcategory1 = question_get_top_category($context1->id, true);
1743
        $topcategory2 = question_get_top_category($context2->id, true);
1744
        $randomquiz = self::getDataGenerator()->get_plugin_generator('mod_quiz')->create_instance(
1745
            [
1746
                'course' => $randomcourse->id,
1747
                'grade' => 100.0,
1748
                'sumgrades' => 2,
1749
                'layout' => '1,0',
1750
            ],
1751
        );
1752
 
1753
        $randomquizsettings = quiz_settings::create($randomquiz->id);
1754
        $structure = $randomquizsettings->get_structure();
1755
 
1756
        $filtercondition = [
1757
            'filter' => [
1758
                'category' => [
1759
                    'jointype' => \core_question\local\bank\condition::JOINTYPE_DEFAULT,
1760
                    'values' => [$topcategory1->id],
1761
                    'filteroptions' => ['includesubcategories' => true],
1762
                ],
1763
            ],
1764
        ];
1765
        $structure->add_random_questions(1, 1, $filtercondition);
1766
        $structure = $randomquizsettings->get_structure();
1767
        $randomquestion = $structure->get_question_in_slot(1);
1768
 
1769
        $this->assertEquals($randomquestion->contextid, $context1->id);
1770
        $this->assertEquals($randomquestion->filtercondition['filter']['category']['values'][0], $topcategory1->id);
1771
 
1772
        move_question_set_references($topcategory1->id, $topcategory2->id, $context1->id, $context2->id);
1773
 
1774
        $structure = $randomquizsettings->get_structure();
1775
        $randomquestion = $structure->get_question_in_slot(1);
1776
 
1777
        $this->assertEquals($randomquestion->contextid, $context2->id);
1778
        $this->assertEquals($randomquestion->filtercondition['filter']['category']['values'][0], $topcategory2->id);
1779
    }
1 efrain 1780
}