Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.11.x will end 14 Nov 2022 (12 months plus 6 months extension).
  • Bug fixes for security issues in 3.11.x will end 13 Nov 2023 (18 months plus 12 months extension).
  • PHP version: minimum PHP 7.3.0 Note: minimum PHP version has increased since Moodle 3.10. PHP 7.4.x is supported too.

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

   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 mod_resource;
  18  
  19  use externallib_advanced_testcase;
  20  use mod_resource_external;
  21  
  22  defined('MOODLE_INTERNAL') || die();
  23  
  24  global $CFG;
  25  
  26  require_once($CFG->dirroot . '/webservice/tests/helpers.php');
  27  
  28  /**
  29   * External mod_resource functions unit tests
  30   *
  31   * @package    mod_resource
  32   * @category   external
  33   * @copyright  2015 Juan Leyva <juan@moodle.com>
  34   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  35   * @since      Moodle 3.0
  36   */
  37  class externallib_test extends externallib_advanced_testcase {
  38  
  39      /**
  40       * Test view_resource
  41       */
  42      public function test_view_resource() {
  43          global $DB;
  44  
  45          $this->resetAfterTest(true);
  46  
  47          $this->setAdminUser();
  48          // Setup test data.
  49          $course = $this->getDataGenerator()->create_course();
  50          $resource = $this->getDataGenerator()->create_module('resource', array('course' => $course->id));
  51          $context = \context_module::instance($resource->cmid);
  52          $cm = get_coursemodule_from_instance('resource', $resource->id);
  53  
  54          // Test invalid instance id.
  55          try {
  56              mod_resource_external::view_resource(0);
  57              $this->fail('Exception expected due to invalid mod_resource instance id.');
  58          } catch (\moodle_exception $e) {
  59              $this->assertEquals('invalidrecord', $e->errorcode);
  60          }
  61  
  62          // Test not-enrolled user.
  63          $user = self::getDataGenerator()->create_user();
  64          $this->setUser($user);
  65          try {
  66              mod_resource_external::view_resource($resource->id);
  67              $this->fail('Exception expected due to not enrolled user.');
  68          } catch (\moodle_exception $e) {
  69              $this->assertEquals('requireloginerror', $e->errorcode);
  70          }
  71  
  72          // Test user with full capabilities.
  73          $studentrole = $DB->get_record('role', array('shortname' => 'student'));
  74          $this->getDataGenerator()->enrol_user($user->id, $course->id, $studentrole->id);
  75  
  76          // Trigger and capture the event.
  77          $sink = $this->redirectEvents();
  78  
  79          $result = mod_resource_external::view_resource($resource->id);
  80          $result = \external_api::clean_returnvalue(mod_resource_external::view_resource_returns(), $result);
  81  
  82          $events = $sink->get_events();
  83          $this->assertCount(1, $events);
  84          $event = array_shift($events);
  85  
  86          // Checking that the event contains the expected values.
  87          $this->assertInstanceOf('\mod_resource\event\course_module_viewed', $event);
  88          $this->assertEquals($context, $event->get_context());
  89          $moodleurl = new \moodle_url('/mod/resource/view.php', array('id' => $cm->id));
  90          $this->assertEquals($moodleurl, $event->get_url());
  91          $this->assertEventContextNotUsed($event);
  92          $this->assertNotEmpty($event->get_name());
  93  
  94          // Test user with no capabilities.
  95          // We need a explicit prohibit since this capability is only defined in authenticated user and guest roles.
  96          assign_capability('mod/resource:view', CAP_PROHIBIT, $studentrole->id, $context->id);
  97          // Empty all the caches that may be affected by this change.
  98          accesslib_clear_all_caches_for_unit_testing();
  99          \course_modinfo::clear_instance_cache();
 100  
 101          try {
 102              mod_resource_external::view_resource($resource->id);
 103              $this->fail('Exception expected due to missing capability.');
 104          } catch (\moodle_exception $e) {
 105              $this->assertEquals('requireloginerror', $e->errorcode);
 106          }
 107  
 108      }
 109  
 110      /**
 111       * Test test_mod_resource_get_resources_by_courses
 112       */
 113      public function test_mod_resource_get_resources_by_courses() {
 114          global $DB;
 115  
 116          $this->resetAfterTest(true);
 117  
 118          $course1 = self::getDataGenerator()->create_course();
 119          $course2 = self::getDataGenerator()->create_course();
 120  
 121          $student = self::getDataGenerator()->create_user();
 122          $studentrole = $DB->get_record('role', array('shortname' => 'student'));
 123          $this->getDataGenerator()->enrol_user($student->id, $course1->id, $studentrole->id);
 124  
 125          self::setUser($student);
 126  
 127          // First resource.
 128          $record = new \stdClass();
 129          $record->course = $course1->id;
 130          $resource1 = self::getDataGenerator()->create_module('resource', $record);
 131  
 132          // Second resource.
 133          $record = new \stdClass();
 134          $record->course = $course2->id;
 135          $resource2 = self::getDataGenerator()->create_module('resource', $record);
 136  
 137          // Execute real Moodle enrolment as we'll call unenrol() method on the instance later.
 138          $enrol = enrol_get_plugin('manual');
 139          $enrolinstances = enrol_get_instances($course2->id, true);
 140          foreach ($enrolinstances as $courseenrolinstance) {
 141              if ($courseenrolinstance->enrol == "manual") {
 142                  $instance2 = $courseenrolinstance;
 143                  break;
 144              }
 145          }
 146          $enrol->enrol_user($instance2, $student->id, $studentrole->id);
 147  
 148          $returndescription = mod_resource_external::get_resources_by_courses_returns();
 149  
 150          // Create what we expect to be returned when querying the two courses.
 151          $expectedfields = array('id', 'coursemodule', 'course', 'name', 'intro', 'introformat', 'introfiles',
 152                                  'contentfiles', 'tobemigrated', 'legacyfiles', 'legacyfileslast', 'display', 'displayoptions',
 153                                  'filterfiles', 'revision', 'timemodified', 'section', 'visible', 'groupmode', 'groupingid');
 154  
 155          // Add expected coursemodule and data.
 156          $resource1->coursemodule = $resource1->cmid;
 157          $resource1->introformat = 1;
 158          $resource1->contentformat = 1;
 159          $resource1->section = 0;
 160          $resource1->visible = true;
 161          $resource1->groupmode = 0;
 162          $resource1->groupingid = 0;
 163          $resource1->introfiles = [];
 164          $resource1->contentfiles = [];
 165  
 166          $resource2->coursemodule = $resource2->cmid;
 167          $resource2->introformat = 1;
 168          $resource2->contentformat = 1;
 169          $resource2->section = 0;
 170          $resource2->visible = true;
 171          $resource2->groupmode = 0;
 172          $resource2->groupingid = 0;
 173          $resource2->introfiles = [];
 174          $resource2->contentfiles = [];
 175  
 176          foreach ($expectedfields as $field) {
 177              $expected1[$field] = $resource1->{$field};
 178              $expected2[$field] = $resource2->{$field};
 179          }
 180  
 181          $expectedresources = array($expected2, $expected1);
 182  
 183          // Call the external function passing course ids.
 184          $result = mod_resource_external::get_resources_by_courses(array($course2->id, $course1->id));
 185          $result = \external_api::clean_returnvalue($returndescription, $result);
 186  
 187          // Remove the contentfiles (to be checked bellow).
 188          $result['resources'][0]['contentfiles'] = [];
 189          $result['resources'][1]['contentfiles'] = [];
 190  
 191          // Now, check that we retrieve the same data we created.
 192          $this->assertEquals($expectedresources, $result['resources']);
 193          $this->assertCount(0, $result['warnings']);
 194  
 195          // Call the external function without passing course id.
 196          $result = mod_resource_external::get_resources_by_courses();
 197          $result = \external_api::clean_returnvalue($returndescription, $result);
 198  
 199          // Remove the contentfiles (to be checked bellow).
 200          $result['resources'][0]['contentfiles'] = [];
 201          $result['resources'][1]['contentfiles'] = [];
 202  
 203          // Check that without course ids we still get the correct data.
 204          $this->assertEquals($expectedresources, $result['resources']);
 205          $this->assertCount(0, $result['warnings']);
 206  
 207          // Add a file to the intro.
 208          $fileintroname = "fileintro.txt";
 209          $filerecordinline = array(
 210              'contextid' => \context_module::instance($resource2->cmid)->id,
 211              'component' => 'mod_resource',
 212              'filearea'  => 'intro',
 213              'itemid'    => 0,
 214              'filepath'  => '/',
 215              'filename'  => $fileintroname,
 216          );
 217          $fs = get_file_storage();
 218          $timepost = time();
 219          $fs->create_file_from_string($filerecordinline, 'image contents (not really)');
 220  
 221          $result = mod_resource_external::get_resources_by_courses(array($course2->id, $course1->id));
 222          $result = \external_api::clean_returnvalue($returndescription, $result);
 223  
 224          // Check that we receive correctly the files.
 225          $this->assertCount(1, $result['resources'][0]['introfiles']);
 226          $this->assertEquals($fileintroname, $result['resources'][0]['introfiles'][0]['filename']);
 227          $this->assertCount(1, $result['resources'][0]['contentfiles']);
 228          $this->assertCount(1, $result['resources'][1]['contentfiles']);
 229          // Test autogenerated resource.
 230          $this->assertEquals('resource2.txt', $result['resources'][0]['contentfiles'][0]['filename']);
 231          $this->assertEquals('resource1.txt', $result['resources'][1]['contentfiles'][0]['filename']);
 232  
 233          // Unenrol user from second course.
 234          $enrol->unenrol_user($instance2, $student->id);
 235          array_shift($expectedresources);
 236  
 237          // Call the external function without passing course id.
 238          $result = mod_resource_external::get_resources_by_courses();
 239          $result = \external_api::clean_returnvalue($returndescription, $result);
 240  
 241          // Remove the contentfiles (to be checked bellow).
 242          $result['resources'][0]['contentfiles'] = [];
 243          $this->assertEquals($expectedresources, $result['resources']);
 244  
 245          // Call for the second course we unenrolled the user from, expected warning.
 246          $result = mod_resource_external::get_resources_by_courses(array($course2->id));
 247          $this->assertCount(1, $result['warnings']);
 248          $this->assertEquals('1', $result['warnings'][0]['warningcode']);
 249          $this->assertEquals($course2->id, $result['warnings'][0]['itemid']);
 250      }
 251  }