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_url;
  18  
  19  use externallib_advanced_testcase;
  20  use mod_url_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_url functions unit tests
  30   *
  31   * @package    mod_url
  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_url
  41       */
  42      public function test_view_url() {
  43          global $DB;
  44  
  45          $this->resetAfterTest(true);
  46  
  47          // Setup test data.
  48          $course = $this->getDataGenerator()->create_course();
  49          $url = $this->getDataGenerator()->create_module('url', array('course' => $course->id));
  50          $context = \context_module::instance($url->cmid);
  51          $cm = get_coursemodule_from_instance('url', $url->id);
  52  
  53          // Test invalid instance id.
  54          try {
  55              mod_url_external::view_url(0);
  56              $this->fail('Exception expected due to invalid mod_url instance id.');
  57          } catch (\moodle_exception $e) {
  58              $this->assertEquals('invalidrecord', $e->errorcode);
  59          }
  60  
  61          // Test not-enrolled user.
  62          $user = self::getDataGenerator()->create_user();
  63          $this->setUser($user);
  64          try {
  65              mod_url_external::view_url($url->id);
  66              $this->fail('Exception expected due to not enrolled user.');
  67          } catch (\moodle_exception $e) {
  68              $this->assertEquals('requireloginerror', $e->errorcode);
  69          }
  70  
  71          // Test user with full capabilities.
  72          $studentrole = $DB->get_record('role', array('shortname' => 'student'));
  73          $this->getDataGenerator()->enrol_user($user->id, $course->id, $studentrole->id);
  74  
  75          // Trigger and capture the event.
  76          $sink = $this->redirectEvents();
  77  
  78          $result = mod_url_external::view_url($url->id);
  79          $result = \external_api::clean_returnvalue(mod_url_external::view_url_returns(), $result);
  80  
  81          $events = $sink->get_events();
  82          $this->assertCount(1, $events);
  83          $event = array_shift($events);
  84  
  85          // Checking that the event contains the expected values.
  86          $this->assertInstanceOf('\mod_url\event\course_module_viewed', $event);
  87          $this->assertEquals($context, $event->get_context());
  88          $moodleurl = new \moodle_url('/mod/url/view.php', array('id' => $cm->id));
  89          $this->assertEquals($moodleurl, $event->get_url());
  90          $this->assertEventContextNotUsed($event);
  91          $this->assertNotEmpty($event->get_name());
  92  
  93          // Test user with no capabilities.
  94          // We need a explicit prohibit since this capability is only defined in authenticated user and guest roles.
  95          assign_capability('mod/url:view', CAP_PROHIBIT, $studentrole->id, $context->id);
  96          // Empty all the caches that may be affected by this change.
  97          accesslib_clear_all_caches_for_unit_testing();
  98          \course_modinfo::clear_instance_cache();
  99  
 100          try {
 101              mod_url_external::view_url($url->id);
 102              $this->fail('Exception expected due to missing capability.');
 103          } catch (\moodle_exception $e) {
 104              $this->assertEquals('requireloginerror', $e->errorcode);
 105          }
 106  
 107      }
 108  
 109      /**
 110       * Test test_mod_url_get_urls_by_courses
 111       */
 112      public function test_mod_url_get_urls_by_courses() {
 113          global $DB;
 114  
 115          $this->resetAfterTest(true);
 116  
 117          $course1 = self::getDataGenerator()->create_course();
 118          $course2 = self::getDataGenerator()->create_course();
 119  
 120          $student = self::getDataGenerator()->create_user();
 121          $studentrole = $DB->get_record('role', array('shortname' => 'student'));
 122          $this->getDataGenerator()->enrol_user($student->id, $course1->id, $studentrole->id);
 123  
 124          // First url.
 125          $record = new \stdClass();
 126          $record->course = $course1->id;
 127          $url1 = self::getDataGenerator()->create_module('url', $record);
 128  
 129          // Second url.
 130          $record = new \stdClass();
 131          $record->course = $course2->id;
 132          $url2 = self::getDataGenerator()->create_module('url', $record);
 133  
 134          // Execute real Moodle enrolment as we'll call unenrol() method on the instance later.
 135          $enrol = enrol_get_plugin('manual');
 136          $enrolinstances = enrol_get_instances($course2->id, true);
 137          foreach ($enrolinstances as $courseenrolinstance) {
 138              if ($courseenrolinstance->enrol == "manual") {
 139                  $instance2 = $courseenrolinstance;
 140                  break;
 141              }
 142          }
 143          $enrol->enrol_user($instance2, $student->id, $studentrole->id);
 144  
 145          self::setUser($student);
 146  
 147          $returndescription = mod_url_external::get_urls_by_courses_returns();
 148  
 149          // Create what we expect to be returned when querying the two courses.
 150          $expectedfields = array('id', 'coursemodule', 'course', 'name', 'intro', 'introformat', 'introfiles', 'lang',
 151                  'externalurl', 'display', 'displayoptions', 'parameters', 'timemodified', 'section', 'visible', 'groupmode',
 152                  'groupingid');
 153  
 154          // Add expected coursemodule and data.
 155          $url1->coursemodule = $url1->cmid;
 156          $url1->introformat = 1;
 157          $url1->section = 0;
 158          $url1->visible = true;
 159          $url1->groupmode = 0;
 160          $url1->groupingid = 0;
 161          $url1->introfiles = [];
 162          $url1->lang = '';
 163  
 164          $url2->coursemodule = $url2->cmid;
 165          $url2->introformat = 1;
 166          $url2->section = 0;
 167          $url2->visible = true;
 168          $url2->groupmode = 0;
 169          $url2->groupingid = 0;
 170          $url2->introfiles = [];
 171          $url2->lang = '';
 172  
 173          foreach ($expectedfields as $field) {
 174              $expected1[$field] = $url1->{$field};
 175              $expected2[$field] = $url2->{$field};
 176          }
 177  
 178          $expectedurls = array($expected2, $expected1);
 179  
 180          // Call the external function passing course ids.
 181          $result = mod_url_external::get_urls_by_courses(array($course2->id, $course1->id));
 182          $result = \external_api::clean_returnvalue($returndescription, $result);
 183  
 184          $this->assertEquals($expectedurls, $result['urls']);
 185          $this->assertCount(0, $result['warnings']);
 186  
 187          // Call the external function without passing course id.
 188          $result = mod_url_external::get_urls_by_courses();
 189          $result = \external_api::clean_returnvalue($returndescription, $result);
 190          $this->assertEquals($expectedurls, $result['urls']);
 191          $this->assertCount(0, $result['warnings']);
 192  
 193          // Add a file to the intro.
 194          $filename = "file.txt";
 195          $filerecordinline = array(
 196              'contextid' => \context_module::instance($url2->cmid)->id,
 197              'component' => 'mod_url',
 198              'filearea'  => 'intro',
 199              'itemid'    => 0,
 200              'filepath'  => '/',
 201              'filename'  => $filename,
 202          );
 203          $fs = get_file_storage();
 204          $timepost = time();
 205          $fs->create_file_from_string($filerecordinline, 'image contents (not really)');
 206  
 207          $result = mod_url_external::get_urls_by_courses(array($course2->id, $course1->id));
 208          $result = \external_api::clean_returnvalue($returndescription, $result);
 209  
 210          $this->assertCount(1, $result['urls'][0]['introfiles']);
 211          $this->assertEquals($filename, $result['urls'][0]['introfiles'][0]['filename']);
 212  
 213          // Unenrol user from second course and alter expected urls.
 214          $enrol->unenrol_user($instance2, $student->id);
 215          array_shift($expectedurls);
 216  
 217          // Call the external function without passing course id.
 218          $result = mod_url_external::get_urls_by_courses();
 219          $result = \external_api::clean_returnvalue($returndescription, $result);
 220          $this->assertEquals($expectedurls, $result['urls']);
 221  
 222          // Call for the second course we unenrolled the user from, expected warning.
 223          $result = mod_url_external::get_urls_by_courses(array($course2->id));
 224          $this->assertCount(1, $result['warnings']);
 225          $this->assertEquals('1', $result['warnings'][0]['warningcode']);
 226          $this->assertEquals($course2->id, $result['warnings'][0]['itemid']);
 227      }
 228  }