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