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 400 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 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', 'lang',
 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          $resource1->lang = '';
 166  
 167          $resource2->coursemodule = $resource2->cmid;
 168          $resource2->introformat = 1;
 169          $resource2->contentformat = 1;
 170          $resource2->section = 0;
 171          $resource2->visible = true;
 172          $resource2->groupmode = 0;
 173          $resource2->groupingid = 0;
 174          $resource2->introfiles = [];
 175          $resource2->contentfiles = [];
 176          $resource2->lang = '';
 177  
 178          foreach ($expectedfields as $field) {
 179              $expected1[$field] = $resource1->{$field};
 180              $expected2[$field] = $resource2->{$field};
 181          }
 182  
 183          $expectedresources = array($expected2, $expected1);
 184  
 185          // Call the external function passing course ids.
 186          $result = mod_resource_external::get_resources_by_courses(array($course2->id, $course1->id));
 187          $result = \external_api::clean_returnvalue($returndescription, $result);
 188  
 189          // Remove the contentfiles (to be checked bellow).
 190          $result['resources'][0]['contentfiles'] = [];
 191          $result['resources'][1]['contentfiles'] = [];
 192  
 193          // Now, check that we retrieve the same data we created.
 194          $this->assertEquals($expectedresources, $result['resources']);
 195          $this->assertCount(0, $result['warnings']);
 196  
 197          // Call the external function without passing course id.
 198          $result = mod_resource_external::get_resources_by_courses();
 199          $result = \external_api::clean_returnvalue($returndescription, $result);
 200  
 201          // Remove the contentfiles (to be checked bellow).
 202          $result['resources'][0]['contentfiles'] = [];
 203          $result['resources'][1]['contentfiles'] = [];
 204  
 205          // Check that without course ids we still get the correct data.
 206          $this->assertEquals($expectedresources, $result['resources']);
 207          $this->assertCount(0, $result['warnings']);
 208  
 209          // Add a file to the intro.
 210          $fileintroname = "fileintro.txt";
 211          $filerecordinline = array(
 212              'contextid' => \context_module::instance($resource2->cmid)->id,
 213              'component' => 'mod_resource',
 214              'filearea'  => 'intro',
 215              'itemid'    => 0,
 216              'filepath'  => '/',
 217              'filename'  => $fileintroname,
 218          );
 219          $fs = get_file_storage();
 220          $timepost = time();
 221          $fs->create_file_from_string($filerecordinline, 'image contents (not really)');
 222  
 223          $result = mod_resource_external::get_resources_by_courses(array($course2->id, $course1->id));
 224          $result = \external_api::clean_returnvalue($returndescription, $result);
 225  
 226          // Check that we receive correctly the files.
 227          $this->assertCount(1, $result['resources'][0]['introfiles']);
 228          $this->assertEquals($fileintroname, $result['resources'][0]['introfiles'][0]['filename']);
 229          $this->assertCount(1, $result['resources'][0]['contentfiles']);
 230          $this->assertCount(1, $result['resources'][1]['contentfiles']);
 231          // Test autogenerated resource.
 232          $this->assertEquals('resource2.txt', $result['resources'][0]['contentfiles'][0]['filename']);
 233          $this->assertEquals('resource1.txt', $result['resources'][1]['contentfiles'][0]['filename']);
 234  
 235          // Unenrol user from second course.
 236          $enrol->unenrol_user($instance2, $student->id);
 237          array_shift($expectedresources);
 238  
 239          // Call the external function without passing course id.
 240          $result = mod_resource_external::get_resources_by_courses();
 241          $result = \external_api::clean_returnvalue($returndescription, $result);
 242  
 243          // Remove the contentfiles (to be checked bellow).
 244          $result['resources'][0]['contentfiles'] = [];
 245          $this->assertEquals($expectedresources, $result['resources']);
 246  
 247          // Call for the second course we unenrolled the user from, expected warning.
 248          $result = mod_resource_external::get_resources_by_courses(array($course2->id));
 249          $this->assertCount(1, $result['warnings']);
 250          $this->assertEquals('1', $result['warnings'][0]['warningcode']);
 251          $this->assertEquals($course2->id, $result['warnings'][0]['itemid']);
 252      }
 253  }