MDL-52895 webservice: Fix capability checks
[moodle.git] / mod / lti / 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 tool module external functions tests
19  *
20  * @package    mod_lti
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');
32 require_once($CFG->dirroot . '/mod/lti/lib.php');
34 /**
35  * External tool module external functions tests
36  *
37  * @package    mod_lti
38  * @category   external
39  * @copyright  2015 Juan Leyva <juan@moodle.com>
40  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
41  * @since      Moodle 3.0
42  */
43 class mod_lti_external_testcase extends externallib_advanced_testcase {
45     /**
46      * Set up for every test
47      */
48     public function setUp() {
49         global $DB;
50         $this->resetAfterTest();
51         $this->setAdminUser();
53         // Setup test data.
54         $this->course = $this->getDataGenerator()->create_course();
55         $this->lti = $this->getDataGenerator()->create_module('lti', array('course' => $this->course->id));
56         $this->context = context_module::instance($this->lti->cmid);
57         $this->cm = get_coursemodule_from_instance('lti', $this->lti->id);
59         // Create users.
60         $this->student = self::getDataGenerator()->create_user();
61         $this->teacher = self::getDataGenerator()->create_user();
63         // Users enrolments.
64         $this->studentrole = $DB->get_record('role', array('shortname' => 'student'));
65         $this->teacherrole = $DB->get_record('role', array('shortname' => 'editingteacher'));
66         $this->getDataGenerator()->enrol_user($this->student->id, $this->course->id, $this->studentrole->id, 'manual');
67         $this->getDataGenerator()->enrol_user($this->teacher->id, $this->course->id, $this->teacherrole->id, 'manual');
68     }
70     /**
71      * Test view_lti
72      */
73     public function test_get_tool_launch_data() {
74         global $USER;
76         $result = mod_lti_external::get_tool_launch_data($this->lti->id);
77         $result = external_api::clean_returnvalue(mod_lti_external::get_tool_launch_data_returns(), $result);
79         // Basic test, the function returns what it's expected.
80         self::assertEquals($this->lti->toolurl, $result['endpoint']);
81         self::assertCount(35, $result['parameters']);
83         // Check some parameters.
84         $parameters = array();
85         foreach ($result['parameters'] as $param) {
86             $parameters[$param['name']] = $param['value'];
87         }
88         self::assertEquals($this->lti->resourcekey, $parameters['oauth_consumer_key']);
89         self::assertEquals($this->course->fullname, $parameters['context_title']);
90         self::assertEquals($this->course->shortname, $parameters['context_label']);
91         self::assertEquals($USER->id, $parameters['user_id']);
92         self::assertEquals($USER->firstname, $parameters['lis_person_name_given']);
93         self::assertEquals($USER->lastname, $parameters['lis_person_name_family']);
94         self::assertEquals(fullname($USER), $parameters['lis_person_name_full']);
95         self::assertEquals($USER->username, $parameters['ext_user_username']);
97     }
99     /*
100      * Test get ltis by courses
101      */
102     public function test_mod_lti_get_ltis_by_courses() {
103         global $DB;
105         // Create additional course.
106         $course2 = self::getDataGenerator()->create_course();
108         // Second lti.
109         $record = new stdClass();
110         $record->course = $course2->id;
111         $lti2 = self::getDataGenerator()->create_module('lti', $record);
113         // Execute real Moodle enrolment as we'll call unenrol() method on the instance later.
114         $enrol = enrol_get_plugin('manual');
115         $enrolinstances = enrol_get_instances($course2->id, true);
116         foreach ($enrolinstances as $courseenrolinstance) {
117             if ($courseenrolinstance->enrol == "manual") {
118                 $instance2 = $courseenrolinstance;
119                 break;
120             }
121         }
122         $enrol->enrol_user($instance2, $this->student->id, $this->studentrole->id);
124         self::setUser($this->student);
126         $returndescription = mod_lti_external::get_ltis_by_courses_returns();
128         // Create what we expect to be returned when querying the two courses.
129         // First for the student user.
130         $expectedfields = array('id', 'coursemodule', 'course', 'name', 'intro', 'introformat', 'launchcontainer',
131                                 'showtitlelaunch', 'showdescriptionlaunch', 'icon', 'secureicon');
133         // Add expected coursemodule and data.
134         $lti1 = $this->lti;
135         $lti1->coursemodule = $lti1->cmid;
136         $lti1->introformat = 1;
137         $lti1->section = 0;
138         $lti1->visible = true;
139         $lti1->groupmode = 0;
140         $lti1->groupingid = 0;
142         $lti2->coursemodule = $lti2->cmid;
143         $lti2->introformat = 1;
144         $lti2->section = 0;
145         $lti2->visible = true;
146         $lti2->groupmode = 0;
147         $lti2->groupingid = 0;
149         foreach ($expectedfields as $field) {
150                 $expected1[$field] = $lti1->{$field};
151                 $expected2[$field] = $lti2->{$field};
152         }
154         $expectedltis = array($expected2, $expected1);
156         // Call the external function passing course ids.
157         $result = mod_lti_external::get_ltis_by_courses(array($course2->id, $this->course->id));
158         $result = external_api::clean_returnvalue($returndescription, $result);
160         $this->assertEquals($expectedltis, $result['ltis']);
161         $this->assertCount(0, $result['warnings']);
163         // Call the external function without passing course id.
164         $result = mod_lti_external::get_ltis_by_courses();
165         $result = external_api::clean_returnvalue($returndescription, $result);
166         $this->assertEquals($expectedltis, $result['ltis']);
167         $this->assertCount(0, $result['warnings']);
169         // Unenrol user from second course and alter expected ltis.
170         $enrol->unenrol_user($instance2, $this->student->id);
171         array_shift($expectedltis);
173         // Call the external function without passing course id.
174         $result = mod_lti_external::get_ltis_by_courses();
175         $result = external_api::clean_returnvalue($returndescription, $result);
176         $this->assertEquals($expectedltis, $result['ltis']);
178         // Call for the second course we unenrolled the user from, expected warning.
179         $result = mod_lti_external::get_ltis_by_courses(array($course2->id));
180         $this->assertCount(1, $result['warnings']);
181         $this->assertEquals('1', $result['warnings'][0]['warningcode']);
182         $this->assertEquals($course2->id, $result['warnings'][0]['itemid']);
184         // Now, try as a teacher for getting all the additional fields.
185         self::setUser($this->teacher);
187         $additionalfields = array('timecreated', 'timemodified', 'typeid', 'toolurl', 'securetoolurl',
188                         'instructorchoicesendname', 'instructorchoicesendemailaddr', 'instructorchoiceallowroster',
189                         'instructorchoiceallowsetting', 'instructorcustomparameters', 'instructorchoiceacceptgrades', 'grade',
190                         'resourcekey', 'password', 'debuglaunch', 'servicesalt', 'visible', 'groupmode', 'groupingid');
192         foreach ($additionalfields as $field) {
193                 $expectedltis[0][$field] = $lti1->{$field};
194         }
196         $result = mod_lti_external::get_ltis_by_courses();
197         $result = external_api::clean_returnvalue($returndescription, $result);
198         $this->assertEquals($expectedltis, $result['ltis']);
200         // Admin also should get all the information.
201         self::setAdminUser();
203         $result = mod_lti_external::get_ltis_by_courses(array($this->course->id));
204         $result = external_api::clean_returnvalue($returndescription, $result);
205         $this->assertEquals($expectedltis, $result['ltis']);
207         // Now, prohibit capabilities.
208         $this->setUser($this->student);
209         $contextcourse1 = context_course::instance($this->course->id);
210         // Prohibit capability = mod:lti:view on Course1 for students.
211         assign_capability('mod/lti:view', CAP_PROHIBIT, $this->studentrole->id, $contextcourse1->id);
212         // Empty all the caches that may be affected by this change.
213         accesslib_clear_all_caches_for_unit_testing();
214         course_modinfo::clear_instance_cache();
216         $ltis = mod_lti_external::get_ltis_by_courses(array($this->course->id));
217         $ltis = external_api::clean_returnvalue(mod_lti_external::get_ltis_by_courses_returns(), $ltis);
218         $this->assertCount(0, $ltis['ltis']);
219     }
221     /**
222      * Test view_lti
223      */
224     public function test_view_lti() {
225         global $DB;
227         // Test invalid instance id.
228         try {
229             mod_lti_external::view_lti(0);
230             $this->fail('Exception expected due to invalid mod_lti instance id.');
231         } catch (moodle_exception $e) {
232             $this->assertEquals('invalidrecord', $e->errorcode);
233         }
235         // Test not-enrolled user.
236         $usernotenrolled = self::getDataGenerator()->create_user();
237         $this->setUser($usernotenrolled);
238         try {
239             mod_lti_external::view_lti($this->lti->id);
240             $this->fail('Exception expected due to not enrolled user.');
241         } catch (moodle_exception $e) {
242             $this->assertEquals('requireloginerror', $e->errorcode);
243         }
245         // Test user with full capabilities.
246         $this->setUser($this->student);
248         // Trigger and capture the event.
249         $sink = $this->redirectEvents();
251         $result = mod_lti_external::view_lti($this->lti->id);
252         $result = external_api::clean_returnvalue(mod_lti_external::view_lti_returns(), $result);
254         $events = $sink->get_events();
255         $this->assertCount(1, $events);
256         $event = array_shift($events);
258         // Checking that the event contains the expected values.
259         $this->assertInstanceOf('\mod_lti\event\course_module_viewed', $event);
260         $this->assertEquals($this->context, $event->get_context());
261         $moodlelti = new \moodle_url('/mod/lti/view.php', array('id' => $this->cm->id));
262         $this->assertEquals($moodlelti, $event->get_url());
263         $this->assertEventContextNotUsed($event);
264         $this->assertNotEmpty($event->get_name());
266         // Test user with no capabilities.
267         // We need a explicit prohibit since this capability is only defined in authenticated user and guest roles.
268         assign_capability('mod/lti:view', CAP_PROHIBIT, $this->studentrole->id, $this->context->id);
269         // Empty all the caches that may be affected by this change.
270         accesslib_clear_all_caches_for_unit_testing();
271         course_modinfo::clear_instance_cache();
273         try {
274             mod_lti_external::view_lti($this->lti->id);
275             $this->fail('Exception expected due to missing capability.');
276         } catch (moodle_exception $e) {
277             $this->assertEquals('requireloginerror', $e->errorcode);
278         }
280     }