externallib_test.php 22.1 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

/**
 * External tool module external functions tests
 *
 * @package    mod_lti
 * @category   external
 * @copyright  2015 Juan Leyva <juan@moodle.com>
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 * @since      Moodle 3.0
 */

defined('MOODLE_INTERNAL') || die();

global $CFG;

require_once($CFG->dirroot . '/webservice/tests/helpers.php');
require_once($CFG->dirroot . '/mod/lti/lib.php');

/**
 * External tool module external functions tests
 *
 * @package    mod_lti
 * @category   external
 * @copyright  2015 Juan Leyva <juan@moodle.com>
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 * @since      Moodle 3.0
 */
class mod_lti_external_testcase extends externallib_advanced_testcase {

    /**
     * Set up for every test
     */
    public function setUp() {
        $this->resetAfterTest();
50
51
52
53
54
55
56
57
    }

    /**
     * Sets up some basic test data including course, users, roles, and an lti instance, for use in some tests.
     * @return array
     */
    protected function setup_test_data() {
        global $DB;
58
59
60
        $this->setAdminUser();

        // Setup test data.
61
62
63
64
65
66
67
        $course = $this->getDataGenerator()->create_course();
        $lti = $this->getDataGenerator()->create_module(
            'lti',
            ['course' => $course->id, 'toolurl' => 'http://localhost/not/real/tool.php']
        );
        $context = context_module::instance($lti->cmid);
        $cm = get_coursemodule_from_instance('lti', $lti->id);
68
69

        // Create users.
70
71
        $student = self::getDataGenerator()->create_user();
        $teacher = self::getDataGenerator()->create_user();
72
73

        // Users enrolments.
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
        $studentrole = $DB->get_record('role', array('shortname' => 'student'));
        $teacherrole = $DB->get_record('role', array('shortname' => 'editingteacher'));
        $this->getDataGenerator()->enrol_user($student->id, $course->id, $studentrole->id, 'manual');
        $this->getDataGenerator()->enrol_user($teacher->id, $course->id, $teacherrole->id, 'manual');

        return [
            'course' => $course,
            'lti' => $lti,
            'context' => $context,
            'cm' => $cm,
            'student' => $student,
            'teacher' => $teacher,
            'studentrole' => $studentrole,
            'teacherrole' => $teacherrole
        ];
89
90
91
92
93
94
    }

    /**
     * Test view_lti
     */
    public function test_get_tool_launch_data() {
95
        global $USER;
96

97
98
99
100
101
102
        [
            'course' => $course,
            'lti' => $lti
        ] = $this->setup_test_data();

        $result = mod_lti_external::get_tool_launch_data($lti->id);
103
104
105
        $result = external_api::clean_returnvalue(mod_lti_external::get_tool_launch_data_returns(), $result);

        // Basic test, the function returns what it's expected.
106
        self::assertEquals($lti->toolurl, $result['endpoint']);
107
        self::assertCount(36, $result['parameters']);
108
109
110
111
112
113

        // Check some parameters.
        $parameters = array();
        foreach ($result['parameters'] as $param) {
            $parameters[$param['name']] = $param['value'];
        }
114
115
116
        self::assertEquals($lti->resourcekey, $parameters['oauth_consumer_key']);
        self::assertEquals($course->fullname, $parameters['context_title']);
        self::assertEquals($course->shortname, $parameters['context_label']);
117
118
119
120
121
        self::assertEquals($USER->id, $parameters['user_id']);
        self::assertEquals($USER->firstname, $parameters['lis_person_name_given']);
        self::assertEquals($USER->lastname, $parameters['lis_person_name_family']);
        self::assertEquals(fullname($USER), $parameters['lis_person_name_full']);
        self::assertEquals($USER->username, $parameters['ext_user_username']);
122
123
        self::assertEquals("phpunit", $parameters['tool_consumer_instance_name']);
        self::assertEquals("PHPUnit test site", $parameters['tool_consumer_instance_description']);
124
125
126

    }

127
128
129
130
    /*
     * Test get ltis by courses
     */
    public function test_mod_lti_get_ltis_by_courses() {
131
132
133
134
135
136
137
138
        [
            'course' => $course,
            'lti' => $lti,
            'student' => $student,
            'teacher' => $teacher,
            'studentrole' => $studentrole,
        ] = $this->setup_test_data();

139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
        // Create additional course.
        $course2 = self::getDataGenerator()->create_course();

        // Second lti.
        $record = new stdClass();
        $record->course = $course2->id;
        $lti2 = self::getDataGenerator()->create_module('lti', $record);

        // Execute real Moodle enrolment as we'll call unenrol() method on the instance later.
        $enrol = enrol_get_plugin('manual');
        $enrolinstances = enrol_get_instances($course2->id, true);
        foreach ($enrolinstances as $courseenrolinstance) {
            if ($courseenrolinstance->enrol == "manual") {
                $instance2 = $courseenrolinstance;
                break;
            }
        }
156
        $enrol->enrol_user($instance2, $student->id, $studentrole->id);
157

158
        self::setUser($student);
159
160
161
162
163

        $returndescription = mod_lti_external::get_ltis_by_courses_returns();

        // Create what we expect to be returned when querying the two courses.
        // First for the student user.
164
        $expectedfields = array('id', 'coursemodule', 'course', 'name', 'intro', 'introformat', 'introfiles', 'launchcontainer',
165
166
167
                                'showtitlelaunch', 'showdescriptionlaunch', 'icon', 'secureicon');

        // Add expected coursemodule and data.
168
        $lti1 = $lti;
169
170
171
172
173
174
        $lti1->coursemodule = $lti1->cmid;
        $lti1->introformat = 1;
        $lti1->section = 0;
        $lti1->visible = true;
        $lti1->groupmode = 0;
        $lti1->groupingid = 0;
175
        $lti1->introfiles = [];
176
177
178
179
180
181
182

        $lti2->coursemodule = $lti2->cmid;
        $lti2->introformat = 1;
        $lti2->section = 0;
        $lti2->visible = true;
        $lti2->groupmode = 0;
        $lti2->groupingid = 0;
183
        $lti2->introfiles = [];
184
185
186
187
188
189
190
191
192

        foreach ($expectedfields as $field) {
                $expected1[$field] = $lti1->{$field};
                $expected2[$field] = $lti2->{$field};
        }

        $expectedltis = array($expected2, $expected1);

        // Call the external function passing course ids.
193
        $result = mod_lti_external::get_ltis_by_courses(array($course2->id, $course->id));
194
195
196
197
198
199
200
201
202
203
204
205
        $result = external_api::clean_returnvalue($returndescription, $result);

        $this->assertEquals($expectedltis, $result['ltis']);
        $this->assertCount(0, $result['warnings']);

        // Call the external function without passing course id.
        $result = mod_lti_external::get_ltis_by_courses();
        $result = external_api::clean_returnvalue($returndescription, $result);
        $this->assertEquals($expectedltis, $result['ltis']);
        $this->assertCount(0, $result['warnings']);

        // Unenrol user from second course and alter expected ltis.
206
        $enrol->unenrol_user($instance2, $student->id);
207
208
209
210
211
212
213
214
215
        array_shift($expectedltis);

        // Call the external function without passing course id.
        $result = mod_lti_external::get_ltis_by_courses();
        $result = external_api::clean_returnvalue($returndescription, $result);
        $this->assertEquals($expectedltis, $result['ltis']);

        // Call for the second course we unenrolled the user from, expected warning.
        $result = mod_lti_external::get_ltis_by_courses(array($course2->id));
216
        $result = external_api::clean_returnvalue($returndescription, $result);
217
218
219
220
221
        $this->assertCount(1, $result['warnings']);
        $this->assertEquals('1', $result['warnings'][0]['warningcode']);
        $this->assertEquals($course2->id, $result['warnings'][0]['itemid']);

        // Now, try as a teacher for getting all the additional fields.
222
        self::setUser($teacher);
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239

        $additionalfields = array('timecreated', 'timemodified', 'typeid', 'toolurl', 'securetoolurl',
                        'instructorchoicesendname', 'instructorchoicesendemailaddr', 'instructorchoiceallowroster',
                        'instructorchoiceallowsetting', 'instructorcustomparameters', 'instructorchoiceacceptgrades', 'grade',
                        'resourcekey', 'password', 'debuglaunch', 'servicesalt', 'visible', 'groupmode', 'groupingid');

        foreach ($additionalfields as $field) {
                $expectedltis[0][$field] = $lti1->{$field};
        }

        $result = mod_lti_external::get_ltis_by_courses();
        $result = external_api::clean_returnvalue($returndescription, $result);
        $this->assertEquals($expectedltis, $result['ltis']);

        // Admin also should get all the information.
        self::setAdminUser();

240
        $result = mod_lti_external::get_ltis_by_courses(array($course->id));
241
242
243
244
        $result = external_api::clean_returnvalue($returndescription, $result);
        $this->assertEquals($expectedltis, $result['ltis']);

        // Now, prohibit capabilities.
245
246
        $this->setUser($student);
        $contextcourse1 = context_course::instance($course->id);
247
        // Prohibit capability = mod:lti:view on Course1 for students.
248
        assign_capability('mod/lti:view', CAP_PROHIBIT, $studentrole->id, $contextcourse1->id);
249
        // Empty all the caches that may be affected by this change.
250
        accesslib_clear_all_caches_for_unit_testing();
251
        course_modinfo::clear_instance_cache();
252

253
        $ltis = mod_lti_external::get_ltis_by_courses(array($course->id));
254
        $ltis = external_api::clean_returnvalue(mod_lti_external::get_ltis_by_courses_returns(), $ltis);
255
        $this->assertCount(0, $ltis['ltis']);
256
257
    }

258
259
260
261
    /**
     * Test view_lti
     */
    public function test_view_lti() {
262
263
264
265
266
267
268
269
        [
            'lti' => $lti,
            'context' => $context,
            'cm' => $cm,
            'student' => $student,
            'studentrole' => $studentrole,
        ] = $this->setup_test_data();

270
271
272
273
274
275
276
277
278
279
280
281
        // Test invalid instance id.
        try {
            mod_lti_external::view_lti(0);
            $this->fail('Exception expected due to invalid mod_lti instance id.');
        } catch (moodle_exception $e) {
            $this->assertEquals('invalidrecord', $e->errorcode);
        }

        // Test not-enrolled user.
        $usernotenrolled = self::getDataGenerator()->create_user();
        $this->setUser($usernotenrolled);
        try {
282
            mod_lti_external::view_lti($lti->id);
283
284
285
286
287
288
            $this->fail('Exception expected due to not enrolled user.');
        } catch (moodle_exception $e) {
            $this->assertEquals('requireloginerror', $e->errorcode);
        }

        // Test user with full capabilities.
289
        $this->setUser($student);
290
291
292
293

        // Trigger and capture the event.
        $sink = $this->redirectEvents();

294
        $result = mod_lti_external::view_lti($lti->id);
295
296
        // The value of the result isn't needed but validation is.
        external_api::clean_returnvalue(mod_lti_external::view_lti_returns(), $result);
297
298
299
300
301
302
303

        $events = $sink->get_events();
        $this->assertCount(1, $events);
        $event = array_shift($events);

        // Checking that the event contains the expected values.
        $this->assertInstanceOf('\mod_lti\event\course_module_viewed', $event);
304
305
        $this->assertEquals($context, $event->get_context());
        $moodlelti = new \moodle_url('/mod/lti/view.php', array('id' => $cm->id));
306
307
308
309
310
311
        $this->assertEquals($moodlelti, $event->get_url());
        $this->assertEventContextNotUsed($event);
        $this->assertNotEmpty($event->get_name());

        // Test user with no capabilities.
        // We need a explicit prohibit since this capability is only defined in authenticated user and guest roles.
312
        assign_capability('mod/lti:view', CAP_PROHIBIT, $studentrole->id, $context->id);
313
        // Empty all the caches that may be affected by this change.
314
        accesslib_clear_all_caches_for_unit_testing();
315
        course_modinfo::clear_instance_cache();
316
317

        try {
318
            mod_lti_external::view_lti($lti->id);
319
320
            $this->fail('Exception expected due to missing capability.');
        } catch (moodle_exception $e) {
321
            $this->assertEquals('requireloginerror', $e->errorcode);
322
323
324
325
        }

    }

326
327
328
329
    /*
     * Test create tool proxy
     */
    public function test_mod_lti_create_tool_proxy() {
330
        $this->setAdminUser();
331
332
        $capabilities = ['AA', 'BB'];
        $proxy = mod_lti_external::create_tool_proxy('Test proxy', $this->getExternalTestFileUrl('/test.html'), $capabilities, []);
333
334
        $proxy = (object) external_api::clean_returnvalue(mod_lti_external::create_tool_proxy_returns(), $proxy);

335
336
337
        $this->assertEquals('Test proxy', $proxy->name);
        $this->assertEquals($this->getExternalTestFileUrl('/test.html'), $proxy->regurl);
        $this->assertEquals(LTI_TOOL_PROXY_STATE_PENDING, $proxy->state);
338
        $this->assertEquals(implode("\n", $capabilities), $proxy->capabilityoffered);
339
340
341
342
343
344
    }

    /*
     * Test create tool proxy with duplicate url
     */
    public function test_mod_lti_create_tool_proxy_duplicateurl() {
345
        $this->setAdminUser();
346
        $this->expectException('moodle_exception');
347
348
        mod_lti_external::create_tool_proxy('Test proxy 1', $this->getExternalTestFileUrl('/test.html'), array(), array());
        mod_lti_external::create_tool_proxy('Test proxy 2', $this->getExternalTestFileUrl('/test.html'), array(), array());
349
350
351
352
353
354
    }

    /*
     * Test create tool proxy without sufficient capability
     */
    public function test_mod_lti_create_tool_proxy_without_capability() {
355
356
357
        $course = $this->getDataGenerator()->create_course();
        $teacher = $this->getDataGenerator()->create_and_enrol($course, 'editingteacher');
        $this->setUser($teacher);
358
        $this->expectException('required_capability_exception');
359
        mod_lti_external::create_tool_proxy('Test proxy', $this->getExternalTestFileUrl('/test.html'), array(), array());
360
361
362
363
364
365
    }

    /*
     * Test delete tool proxy
     */
    public function test_mod_lti_delete_tool_proxy() {
366
        $this->setAdminUser();
367
        $proxy = mod_lti_external::create_tool_proxy('Test proxy', $this->getExternalTestFileUrl('/test.html'), array(), array());
368
        $proxy = (object) external_api::clean_returnvalue(mod_lti_external::create_tool_proxy_returns(), $proxy);
369
370
371
        $this->assertNotEmpty(lti_get_tool_proxy($proxy->id));

        $proxy = mod_lti_external::delete_tool_proxy($proxy->id);
372
373
        $proxy = (object) external_api::clean_returnvalue(mod_lti_external::delete_tool_proxy_returns(), $proxy);

374
375
376
377
378
379
380
381
382
383
        $this->assertEquals('Test proxy', $proxy->name);
        $this->assertEquals($this->getExternalTestFileUrl('/test.html'), $proxy->regurl);
        $this->assertEquals(LTI_TOOL_PROXY_STATE_PENDING, $proxy->state);
        $this->assertEmpty(lti_get_tool_proxy($proxy->id));
    }

    /*
     * Test get tool proxy registration request
     */
    public function test_mod_lti_get_tool_proxy_registration_request() {
384
        $this->setAdminUser();
385
        $proxy = mod_lti_external::create_tool_proxy('Test proxy', $this->getExternalTestFileUrl('/test.html'), array(), array());
386
387
        $proxy = (object) external_api::clean_returnvalue(mod_lti_external::create_tool_proxy_returns(), $proxy);

388
        $request = mod_lti_external::get_tool_proxy_registration_request($proxy->id);
389
390
391
        $request = external_api::clean_returnvalue(mod_lti_external::get_tool_proxy_registration_request_returns(),
            $request);

392
393
394
395
396
397
398
399
400
        $this->assertEquals('ToolProxyRegistrationRequest', $request['lti_message_type']);
        $this->assertEquals('LTI-2p0', $request['lti_version']);
    }

    /*
     * Test get tool types
     */
    public function test_mod_lti_get_tool_types() {
        // Create a tool proxy.
401
        $this->setAdminUser();
402
        $proxy = mod_lti_external::create_tool_proxy('Test proxy', $this->getExternalTestFileUrl('/test.html'), array(), array());
403
        $proxy = (object) external_api::clean_returnvalue(mod_lti_external::create_tool_proxy_returns(), $proxy);
404
405
406
407
408
409
410
411
412

        // Create a tool type, associated with that proxy.
        $type = new stdClass();
        $data = new stdClass();
        $type->state = LTI_TOOL_STATE_CONFIGURED;
        $type->name = "Test tool";
        $type->description = "Example description";
        $type->toolproxyid = $proxy->id;
        $type->baseurl = $this->getExternalTestFileUrl('/test.html');
413
        lti_add_type($type, $data);
414
415

        $types = mod_lti_external::get_tool_types($proxy->id);
416
417
        $types = external_api::clean_returnvalue(mod_lti_external::get_tool_types_returns(), $types);

418
419
420
421
422
423
424
425
426
427
        $this->assertEquals(1, count($types));
        $type = $types[0];
        $this->assertEquals('Test tool', $type['name']);
        $this->assertEquals('Example description', $type['description']);
    }

    /*
     * Test create tool type
     */
    public function test_mod_lti_create_tool_type() {
428
        $this->setAdminUser();
429
        $type = mod_lti_external::create_tool_type($this->getExternalTestFileUrl('/ims_cartridge_basic_lti_link.xml'), '', '');
430
431
        $type = external_api::clean_returnvalue(mod_lti_external::create_tool_type_returns(), $type);

432
433
        $this->assertEquals('Example tool', $type['name']);
        $this->assertEquals('Example tool description', $type['description']);
434
        $this->assertEquals('https://download.moodle.org/unittest/test.jpg', $type['urls']['icon']);
435
436
437
438
439
440
441
442
443
444
445
446
447
        $typeentry = lti_get_type($type['id']);
        $this->assertEquals('http://www.example.com/lti/provider.php', $typeentry->baseurl);
        $config = lti_get_type_config($type['id']);
        $this->assertTrue(isset($config['sendname']));
        $this->assertTrue(isset($config['sendemailaddr']));
        $this->assertTrue(isset($config['acceptgrades']));
        $this->assertTrue(isset($config['forcessl']));
    }

    /*
     * Test create tool type failure from non existant file
     */
    public function test_mod_lti_create_tool_type_nonexistant_file() {
448
        $this->expectException('moodle_exception');
449
        mod_lti_external::create_tool_type($this->getExternalTestFileUrl('/doesntexist.xml'), '', '');
450
451
452
453
454
455
    }

    /*
     * Test create tool type failure from xml that is not a cartridge
     */
    public function test_mod_lti_create_tool_type_bad_file() {
456
        $this->expectException('moodle_exception');
457
        mod_lti_external::create_tool_type($this->getExternalTestFileUrl('/rsstest.xml'), '', '');
458
459
460
461
462
463
    }

    /*
     * Test creating of tool types without sufficient capability
     */
    public function test_mod_lti_create_tool_type_without_capability() {
464
465
466
        $course = $this->getDataGenerator()->create_course();
        $teacher = $this->getDataGenerator()->create_and_enrol($course, 'editingteacher');
        $this->setUser($teacher);
467
        $this->expectException('required_capability_exception');
468
        mod_lti_external::create_tool_type($this->getExternalTestFileUrl('/ims_cartridge_basic_lti_link.xml'), '', '');
469
470
471
472
473
474
    }

    /*
     * Test update tool type
     */
    public function test_mod_lti_update_tool_type() {
475
        $this->setAdminUser();
476
        $type = mod_lti_external::create_tool_type($this->getExternalTestFileUrl('/ims_cartridge_basic_lti_link.xml'), '', '');
477
478
        $type = external_api::clean_returnvalue(mod_lti_external::create_tool_type_returns(), $type);

479
        $type = mod_lti_external::update_tool_type($type['id'], 'New name', 'New description', LTI_TOOL_STATE_PENDING);
480
481
        $type = external_api::clean_returnvalue(mod_lti_external::update_tool_type_returns(), $type);

482
483
484
485
486
487
488
489
490
        $this->assertEquals('New name', $type['name']);
        $this->assertEquals('New description', $type['description']);
        $this->assertEquals('Pending', $type['state']['text']);
    }

    /*
     * Test delete tool type
     */
    public function test_mod_lti_delete_tool_type() {
491
        $this->setAdminUser();
492
        $type = mod_lti_external::create_tool_type($this->getExternalTestFileUrl('/ims_cartridge_basic_lti_link.xml'), '', '');
493
        $type = external_api::clean_returnvalue(mod_lti_external::create_tool_type_returns(), $type);
494
        $this->assertNotEmpty(lti_get_type($type['id']));
495

496
        $type = mod_lti_external::delete_tool_type($type['id']);
497
        $type = external_api::clean_returnvalue(mod_lti_external::delete_tool_type_returns(), $type);
498
499
500
501
502
503
504
        $this->assertEmpty(lti_get_type($type['id']));
    }

    /*
     * Test delete tool type without sufficient capability
     */
    public function test_mod_lti_delete_tool_type_without_capability() {
505
        $this->setAdminUser();
506
        $type = mod_lti_external::create_tool_type($this->getExternalTestFileUrl('/ims_cartridge_basic_lti_link.xml'), '', '');
507
        $type = external_api::clean_returnvalue(mod_lti_external::create_tool_type_returns(), $type);
508
        $this->assertNotEmpty(lti_get_type($type['id']));
509
        $this->expectException('required_capability_exception');
510
511
512
        $course = $this->getDataGenerator()->create_course();
        $teacher = $this->getDataGenerator()->create_and_enrol($course, 'editingteacher');
        $this->setUser($teacher);
513
        mod_lti_external::delete_tool_type($type['id']);
514
515
516
517
518
519
    }

    /*
     * Test is cartridge
     */
    public function test_mod_lti_is_cartridge() {
520
        $this->setAdminUser();
521
        $result = mod_lti_external::is_cartridge($this->getExternalTestFileUrl('/ims_cartridge_basic_lti_link.xml'));
522
        $result = external_api::clean_returnvalue(mod_lti_external::is_cartridge_returns(), $result);
523
        $this->assertTrue($result['iscartridge']);
524

525
        $result = mod_lti_external::is_cartridge($this->getExternalTestFileUrl('/test.html'));
526
        $result = external_api::clean_returnvalue(mod_lti_external::is_cartridge_returns(), $result);
527
528
        $this->assertFalse($result['iscartridge']);
    }
529
}