Merge branch 'MDL-73457-master-2' of https://github.com/HuongNV13/moodle
[moodle.git] / question / tests / externallib_test.php
blob71a597e30912667beb0e09330071f02c3a4a52e2
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.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Question external functions tests.
20 * @package core_question
21 * @category external
22 * @copyright 2016 Pau Ferrer <pau@moodle.com>
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 * @since Moodle 3.1
27 namespace core_question;
29 use core_question_external;
30 use externallib_advanced_testcase;
32 defined('MOODLE_INTERNAL') || die();
34 global $CFG;
36 require_once($CFG->dirroot . '/webservice/tests/helpers.php');
37 require_once($CFG->dirroot . '/question/engine/tests/helpers.php');
39 /**
40 * Question external functions tests
42 * @package core_question
43 * @category external
44 * @copyright 2016 Pau Ferrer <pau@moodle.com>
45 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
46 * @since Moodle 3.1
48 class externallib_test extends externallib_advanced_testcase {
50 /**
51 * Set up for every test
53 public function setUp(): void {
54 global $DB;
55 $this->resetAfterTest();
56 $this->setAdminUser();
58 // Setup test data.
59 $this->course = $this->getDataGenerator()->create_course();
61 // Create users.
62 $this->student = self::getDataGenerator()->create_user();
64 // Users enrolments.
65 $this->studentrole = $DB->get_record('role', ['shortname' => 'student']);
66 $this->getDataGenerator()->enrol_user($this->student->id, $this->course->id, $this->studentrole->id, 'manual');
69 /**
70 * Test update question flag
72 public function test_core_question_update_flag() {
74 $questiongenerator = $this->getDataGenerator()->get_plugin_generator('core_question');
76 // Create a question category.
77 $cat = $questiongenerator->create_question_category();
79 $quba = \question_engine::make_questions_usage_by_activity('core_question_update_flag', \context_system::instance());
80 $quba->set_preferred_behaviour('deferredfeedback');
81 $questiondata = $questiongenerator->create_question('numerical', null, ['category' => $cat->id]);
82 $question = \question_bank::load_question($questiondata->id);
83 $slot = $quba->add_question($question);
84 $qa = $quba->get_question_attempt($slot);
86 self::setUser($this->student);
88 $quba->start_all_questions();
89 \question_engine::save_questions_usage_by_activity($quba);
91 $qubaid = $quba->get_id();
92 $questionid = $question->id;
93 $qaid = $qa->get_database_id();
94 $checksum = md5($qubaid . "_" . $this->student->secret . "_" . $questionid . "_" . $qaid . "_" . $slot);
96 $flag = core_question_external::update_flag($qubaid, $questionid, $qaid, $slot, $checksum, true);
97 $this->assertTrue($flag['status']);
99 // Test invalid checksum.
100 try {
101 // Using random_string to force failing.
102 $checksum = md5($qubaid . "_" . random_string(11) . "_" . $questionid . "_" . $qaid . "_" . $slot);
104 core_question_external::update_flag($qubaid, $questionid, $qaid, $slot, $checksum, true);
105 $this->fail('Exception expected due to invalid checksum.');
106 } catch (\moodle_exception $e) {
107 $this->assertEquals('errorsavingflags', $e->errorcode);
112 * Data provider for the get_random_question_summaries test.
114 public function get_random_question_summaries_test_cases() {
115 return [
116 'empty category' => [
117 'categoryindex' => 'emptycat',
118 'includesubcategories' => false,
119 'usetagnames' => [],
120 'expectedquestionindexes' => []
122 'single category' => [
123 'categoryindex' => 'cat1',
124 'includesubcategories' => false,
125 'usetagnames' => [],
126 'expectedquestionindexes' => ['cat1q1', 'cat1q2']
128 'include sub category' => [
129 'categoryindex' => 'cat1',
130 'includesubcategories' => true,
131 'usetagnames' => [],
132 'expectedquestionindexes' => ['cat1q1', 'cat1q2', 'subcatq1', 'subcatq2']
134 'single category with tags' => [
135 'categoryindex' => 'cat1',
136 'includesubcategories' => false,
137 'usetagnames' => ['cat1'],
138 'expectedquestionindexes' => ['cat1q1']
140 'include sub category with tag on parent' => [
141 'categoryindex' => 'cat1',
142 'includesubcategories' => true,
143 'usetagnames' => ['cat1'],
144 'expectedquestionindexes' => ['cat1q1']
146 'include sub category with tag on sub' => [
147 'categoryindex' => 'cat1',
148 'includesubcategories' => true,
149 'usetagnames' => ['subcat'],
150 'expectedquestionindexes' => ['subcatq1']
152 'include sub category with same tag on parent and sub' => [
153 'categoryindex' => 'cat1',
154 'includesubcategories' => true,
155 'usetagnames' => ['foo'],
156 'expectedquestionindexes' => ['cat1q1', 'subcatq1']
158 'include sub category with tag not matching' => [
159 'categoryindex' => 'cat1',
160 'includesubcategories' => true,
161 'usetagnames' => ['cat1', 'cat2'],
162 'expectedquestionindexes' => []
168 * Test the get_random_question_summaries function with various parameter combinations.
170 * This function creates a data set as follows:
171 * Category: cat1
172 * Question: cat1q1
173 * Tags: 'cat1', 'foo'
174 * Question: cat1q2
175 * Category: cat2
176 * Question: cat2q1
177 * Tags: 'cat2', 'foo'
178 * Question: cat2q2
179 * Category: subcat
180 * Question: subcatq1
181 * Tags: 'subcat', 'foo'
182 * Question: subcatq2
183 * Parent: cat1
184 * Category: emptycat
186 * @dataProvider get_random_question_summaries_test_cases()
187 * @param string $categoryindex The named index for the category to use
188 * @param bool $includesubcategories If the search should include subcategories
189 * @param string[] $usetagnames The tag names to include in the search
190 * @param string[] $expectedquestionindexes The questions expected in the result
192 public function test_get_random_question_summaries_variations(
193 $categoryindex,
194 $includesubcategories,
195 $usetagnames,
196 $expectedquestionindexes
198 $this->resetAfterTest();
200 $context = \context_system::instance();
201 $categories = [];
202 $questions = [];
203 $tagnames = [
204 'cat1',
205 'cat2',
206 'subcat',
207 'foo'
209 $collid = \core_tag_collection::get_default();
210 $tags = \core_tag_tag::create_if_missing($collid, $tagnames);
211 $generator = $this->getDataGenerator()->get_plugin_generator('core_question');
213 // First category and questions.
214 list($category, $categoryquestions) = $this->create_category_and_questions(2, ['cat1', 'foo']);
215 $categories['cat1'] = $category;
216 $questions['cat1q1'] = $categoryquestions[0];
217 $questions['cat1q2'] = $categoryquestions[1];
218 // Second category and questions.
219 list($category, $categoryquestions) = $this->create_category_and_questions(2, ['cat2', 'foo']);
220 $categories['cat2'] = $category;
221 $questions['cat2q1'] = $categoryquestions[0];
222 $questions['cat2q2'] = $categoryquestions[1];
223 // Sub category and questions.
224 list($category, $categoryquestions) = $this->create_category_and_questions(2, ['subcat', 'foo'], $categories['cat1']);
225 $categories['subcat'] = $category;
226 $questions['subcatq1'] = $categoryquestions[0];
227 $questions['subcatq2'] = $categoryquestions[1];
228 // Empty category.
229 list($category, $categoryquestions) = $this->create_category_and_questions(0);
230 $categories['emptycat'] = $category;
232 // Generate the arguments for the get_questions function.
233 $category = $categories[$categoryindex];
234 $tagids = array_map(function($tagname) use ($tags) {
235 return $tags[$tagname]->id;
236 }, $usetagnames);
238 $result = core_question_external::get_random_question_summaries($category->id, $includesubcategories, $tagids, $context->id);
239 $resultquestions = $result['questions'];
240 $resulttotalcount = $result['totalcount'];
241 // Generate the expected question set.
242 $expectedquestions = array_map(function($index) use ($questions) {
243 return $questions[$index];
244 }, $expectedquestionindexes);
246 // Ensure the resultquestions matches what was expected.
247 $this->assertCount(count($expectedquestions), $resultquestions);
248 $this->assertEquals(count($expectedquestions), $resulttotalcount);
249 foreach ($expectedquestions as $question) {
250 $this->assertEquals($resultquestions[$question->id]->id, $question->id);
251 $this->assertEquals($resultquestions[$question->id]->category, $question->category);
256 * get_random_question_summaries should throw an invalid_parameter_exception if not
257 * given an integer for the category id.
259 public function test_get_random_question_summaries_invalid_category_id_param() {
260 $this->resetAfterTest();
262 $context = \context_system::instance();
263 $this->expectException('\invalid_parameter_exception');
264 core_question_external::get_random_question_summaries('invalid value', false, [], $context->id);
268 * get_random_question_summaries should throw an invalid_parameter_exception if not
269 * given a boolean for the $includesubcategories parameter.
271 public function test_get_random_question_summaries_invalid_includesubcategories_param() {
272 $this->resetAfterTest();
274 $context = \context_system::instance();
275 $this->expectException('\invalid_parameter_exception');
276 core_question_external::get_random_question_summaries(1, 'invalid value', [], $context->id);
280 * get_random_question_summaries should throw an invalid_parameter_exception if not
281 * given an array of integers for the tag ids parameter.
283 public function test_get_random_question_summaries_invalid_tagids_param() {
284 $this->resetAfterTest();
286 $context = \context_system::instance();
287 $this->expectException('\invalid_parameter_exception');
288 core_question_external::get_random_question_summaries(1, false, ['invalid', 'values'], $context->id);
292 * get_random_question_summaries should throw an invalid_parameter_exception if not
293 * given a context.
295 public function test_get_random_question_summaries_invalid_context() {
296 $this->resetAfterTest();
298 $this->expectException('\invalid_parameter_exception');
299 core_question_external::get_random_question_summaries(1, false, [1, 2], 'context');
303 * get_random_question_summaries should throw an restricted_context_exception
304 * if the given context is outside of the set of restricted contexts the user
305 * is allowed to call external functions in.
307 public function test_get_random_question_summaries_restricted_context() {
308 $this->resetAfterTest();
310 $course = $this->getDataGenerator()->create_course();
311 $coursecontext = \context_course::instance($course->id);
312 $systemcontext = \context_system::instance();
313 // Restrict access to external functions for the logged in user to only
314 // the course we just created. External functions should not be allowed
315 // to execute in any contexts above the course context.
316 core_question_external::set_context_restriction($coursecontext);
318 // An exception should be thrown when we try to execute at the system context
319 // since we're restricted to the course context.
320 try {
321 // Do this in a try/catch statement to allow the context restriction
322 // to be reset afterwards.
323 core_question_external::get_random_question_summaries(1, false, [], $systemcontext->id);
324 } catch (\Exception $e) {
325 $this->assertInstanceOf('restricted_context_exception', $e);
327 // Reset the restriction so that other tests don't fail aftwards.
328 core_question_external::set_context_restriction($systemcontext);
332 * get_random_question_summaries should return a question that is formatted correctly.
334 public function test_get_random_question_summaries_formats_returned_questions() {
335 $this->resetAfterTest();
337 list($category, $questions) = $this->create_category_and_questions(1);
338 $context = \context_system::instance();
339 $question = $questions[0];
340 $expected = (object) [
341 'id' => $question->id,
342 'category' => $question->category,
343 'parent' => $question->parent,
344 'name' => $question->name,
345 'qtype' => $question->qtype
348 $result = core_question_external::get_random_question_summaries($category->id, false, [], $context->id);
349 $actual = $result['questions'][$question->id];
351 $this->assertEquals($expected->id, $actual->id);
352 $this->assertEquals($expected->category, $actual->category);
353 $this->assertEquals($expected->parent, $actual->parent);
354 $this->assertEquals($expected->name, $actual->name);
355 $this->assertEquals($expected->qtype, $actual->qtype);
356 // These values are added by the formatting. It doesn't matter what the
357 // exact values are just that they are returned.
358 $this->assertObjectHasAttribute('icon', $actual);
359 $this->assertObjectHasAttribute('key', $actual->icon);
360 $this->assertObjectHasAttribute('component', $actual->icon);
361 $this->assertObjectHasAttribute('alttext', $actual->icon);
365 * get_random_question_summaries should allow limiting and offsetting of the result set.
367 public function test_get_random_question_summaries_with_limit_and_offset() {
368 $this->resetAfterTest();
369 $numberofquestions = 5;
370 $includesubcategories = false;
371 $tagids = [];
372 $limit = 1;
373 $offset = 0;
374 $context = \context_system::instance();
375 list($category, $questions) = $this->create_category_and_questions($numberofquestions);
377 // Sort the questions by id to match the ordering of the result.
378 usort($questions, function($a, $b) {
379 $aid = $a->id;
380 $bid = $b->id;
382 if ($aid == $bid) {
383 return 0;
385 return $aid < $bid ? -1 : 1;
388 for ($i = 0; $i < $numberofquestions; $i++) {
389 $result = core_question_external::get_random_question_summaries(
390 $category->id,
391 $includesubcategories,
392 $tagids,
393 $context->id,
394 $limit,
395 $offset
398 $resultquestions = $result['questions'];
399 $totalcount = $result['totalcount'];
401 $this->assertCount($limit, $resultquestions);
402 $this->assertEquals($numberofquestions, $totalcount);
403 $actual = array_shift($resultquestions);
404 $expected = $questions[$i];
405 $this->assertEquals($expected->id, $actual->id);
406 $offset++;
411 * get_random_question_summaries should throw an exception if the user doesn't
412 * have the capability to use the questions in the requested category.
414 public function test_get_random_question_summaries_without_capability() {
415 $this->resetAfterTest();
416 $generator = $this->getDataGenerator();
417 $user = $generator->create_user();
418 $roleid = $generator->create_role();
419 $systemcontext = \context_system::instance();
420 $numberofquestions = 5;
421 $includesubcategories = false;
422 $tagids = [];
423 $context = \context_system::instance();
424 list($category, $questions) = $this->create_category_and_questions($numberofquestions);
425 $categorycontext = \context::instance_by_id($category->contextid);
427 $generator->role_assign($roleid, $user->id, $systemcontext->id);
428 // Prohibit all of the tag capabilities.
429 assign_capability('moodle/question:viewall', CAP_PROHIBIT, $roleid, $categorycontext->id);
431 $this->setUser($user);
432 $this->expectException('moodle_exception');
433 core_question_external::get_random_question_summaries(
434 $category->id,
435 $includesubcategories,
436 $tagids,
437 $context->id
442 * Create a question category and create questions in that category. Tag
443 * the first question in each category with the given tags.
445 * @param int $questioncount How many questions to create.
446 * @param string[] $tagnames The list of tags to use.
447 * @param stdClass|null $parentcategory The category to set as the parent of the created category.
448 * @return array The category and questions.
450 protected function create_category_and_questions($questioncount, $tagnames = [], $parentcategory = null) {
451 $generator = $this->getDataGenerator()->get_plugin_generator('core_question');
453 if ($parentcategory) {
454 $catparams = ['parent' => $parentcategory->id];
455 } else {
456 $catparams = [];
459 $category = $generator->create_question_category($catparams);
460 $questions = [];
462 for ($i = 0; $i < $questioncount; $i++) {
463 $questions[] = $generator->create_question('shortanswer', null, ['category' => $category->id]);
466 if (!empty($tagnames) && !empty($questions)) {
467 $context = \context::instance_by_id($category->contextid);
468 \core_tag_tag::set_item_tags('core_question', 'question', $questions[0]->id, $context, $tagnames);
471 return [$category, $questions];