Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 4.1.x will end 13 November 2023 (12 months).
  • Bug fixes for security issues in 4.1.x will end 10 November 2025 (36 months).
  • PHP version: minimum PHP 7.4.0 Note: minimum PHP version has increased since Moodle 4.0. PHP 8.0.x is supported too.

Differences Between: [Versions 310 and 401] [Versions 311 and 401] [Versions 39 and 401] [Versions 401 and 402] [Versions 401 and 403]

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