Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.2.x will end 22 April 2024 (12 months).
  • Bug fixes for security issues in 4.2.x will end 7 October 2024 (18 months).
  • PHP version: minimum PHP 8.0.0 Note: minimum PHP version has increased since Moodle 4.1. PHP 8.1.x is supported too.

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

   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 core_external\external_api;
  20  use externallib_advanced_testcase;
  21  use mod_url_external;
  22  
  23  defined('MOODLE_INTERNAL') || die();
  24  
  25  global $CFG;
  26  
  27  require_once($CFG->dirroot . '/webservice/tests/helpers.php');
  28  
  29  /**
  30   * External mod_url functions unit tests
  31   *
  32   * @package    mod_url
  33   * @category   external
  34   * @copyright  2015 Juan Leyva <juan@moodle.com>
  35   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  36   * @since      Moodle 3.0
  37   */
  38  class externallib_test extends externallib_advanced_testcase {
  39  
  40      /**
  41       * Test view_url
  42       */
  43      public function test_view_url() {
  44          global $DB;
  45  
  46          $this->resetAfterTest(true);
  47  
  48          // Setup test data.
  49          $course = $this->getDataGenerator()->create_course();
  50          $url = $this->getDataGenerator()->create_module('url', array('course' => $course->id));
  51          $context = \context_module::instance($url->cmid);
  52          $cm = get_coursemodule_from_instance('url', $url->id);
  53  
  54          // Test invalid instance id.
  55          try {
  56              mod_url_external::view_url(0);
  57              $this->fail('Exception expected due to invalid mod_url 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_url_external::view_url($url->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_url_external::view_url($url->id);
  80          $result = external_api::clean_returnvalue(mod_url_external::view_url_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_url\event\course_module_viewed', $event);
  88          $this->assertEquals($context, $event->get_context());
  89          $moodleurl = new \moodle_url('/mod/url/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/url: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_url_external::view_url($url->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_url_get_urls_by_courses
 112       */
 113      public function test_mod_url_get_urls_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          // First url.
 126          $record = new \stdClass();
 127          $record->course = $course1->id;
 128          $url1 = self::getDataGenerator()->create_module('url', $record);
 129  
 130          // Second url.
 131          $record = new \stdClass();
 132          $record->course = $course2->id;
 133          $url2 = self::getDataGenerator()->create_module('url', $record);
 134  
 135          // Execute real Moodle enrolment as we'll call unenrol() method on the instance later.
 136          $enrol = enrol_get_plugin('manual');
 137          $enrolinstances = enrol_get_instances($course2->id, true);
 138          foreach ($enrolinstances as $courseenrolinstance) {
 139              if ($courseenrolinstance->enrol == "manual") {
 140                  $instance2 = $courseenrolinstance;
 141                  break;
 142              }
 143          }
 144          $enrol->enrol_user($instance2, $student->id, $studentrole->id);
 145  
 146          self::setUser($student);
 147  
 148          $returndescription = mod_url_external::get_urls_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                  'externalurl', 'display', 'displayoptions', 'parameters', 'timemodified', 'section', 'visible', 'groupmode',
 153                  'groupingid');
 154  
 155          // Add expected coursemodule and data.
 156          $url1->coursemodule = $url1->cmid;
 157          $url1->introformat = 1;
 158          $url1->section = 0;
 159          $url1->visible = true;
 160          $url1->groupmode = 0;
 161          $url1->groupingid = 0;
 162          $url1->introfiles = [];
 163          $url1->lang = '';
 164  
 165          $url2->coursemodule = $url2->cmid;
 166          $url2->introformat = 1;
 167          $url2->section = 0;
 168          $url2->visible = true;
 169          $url2->groupmode = 0;
 170          $url2->groupingid = 0;
 171          $url2->introfiles = [];
 172          $url2->lang = '';
 173  
 174          foreach ($expectedfields as $field) {
 175              $expected1[$field] = $url1->{$field};
 176              $expected2[$field] = $url2->{$field};
 177          }
 178  
 179          $expectedurls = array($expected2, $expected1);
 180  
 181          // Call the external function passing course ids.
 182          $result = mod_url_external::get_urls_by_courses(array($course2->id, $course1->id));
 183          $result = external_api::clean_returnvalue($returndescription, $result);
 184  
 185          $this->assertEquals($expectedurls, $result['urls']);
 186          $this->assertCount(0, $result['warnings']);
 187  
 188          // Call the external function without passing course id.
 189          $result = mod_url_external::get_urls_by_courses();
 190          $result = external_api::clean_returnvalue($returndescription, $result);
 191          $this->assertEquals($expectedurls, $result['urls']);
 192          $this->assertCount(0, $result['warnings']);
 193  
 194          // Add a file to the intro.
 195          $filename = "file.txt";
 196          $filerecordinline = array(
 197              'contextid' => \context_module::instance($url2->cmid)->id,
 198              'component' => 'mod_url',
 199              'filearea'  => 'intro',
 200              'itemid'    => 0,
 201              'filepath'  => '/',
 202              'filename'  => $filename,
 203          );
 204          $fs = get_file_storage();
 205          $timepost = time();
 206          $fs->create_file_from_string($filerecordinline, 'image contents (not really)');
 207  
 208          $result = mod_url_external::get_urls_by_courses(array($course2->id, $course1->id));
 209          $result = external_api::clean_returnvalue($returndescription, $result);
 210  
 211          $this->assertCount(1, $result['urls'][0]['introfiles']);
 212          $this->assertEquals($filename, $result['urls'][0]['introfiles'][0]['filename']);
 213  
 214          // Unenrol user from second course and alter expected urls.
 215          $enrol->unenrol_user($instance2, $student->id);
 216          array_shift($expectedurls);
 217  
 218          // Call the external function without passing course id.
 219          $result = mod_url_external::get_urls_by_courses();
 220          $result = external_api::clean_returnvalue($returndescription, $result);
 221          $this->assertEquals($expectedurls, $result['urls']);
 222  
 223          // Call for the second course we unenrolled the user from, expected warning.
 224          $result = mod_url_external::get_urls_by_courses(array($course2->id));
 225          $this->assertCount(1, $result['warnings']);
 226          $this->assertEquals('1', $result['warnings'][0]['warningcode']);
 227          $this->assertEquals($course2->id, $result['warnings'][0]['itemid']);
 228      }
 229  }