8ec184b630f6f3e22ac9e016f7fa01d97287e1c3
[moodle.git] / course / 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 course functions unit tests
19  *
20  * @package    core_course
21  * @category   external
22  * @copyright  2012 Jerome Mouneyrac
23  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24  */
26 defined('MOODLE_INTERNAL') || die();
28 global $CFG;
30 require_once($CFG->dirroot . '/webservice/tests/helpers.php');
32 /**
33  * External course functions unit tests
34  *
35  * @package    core_course
36  * @category   external
37  * @copyright  2012 Jerome Mouneyrac
38  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
39  */
40 class core_course_externallib_testcase extends externallib_advanced_testcase {
42     /**
43      * Tests set up
44      */
45     protected function setUp() {
46         global $CFG;
47         require_once($CFG->dirroot . '/course/externallib.php');
48     }
50     /**
51      * Test create_categories
52      */
53     public function test_create_categories() {
55         global $DB;
57         $this->resetAfterTest(true);
59         // Set the required capabilities by the external function
60         $contextid = context_system::instance()->id;
61         $roleid = $this->assignUserCapability('moodle/category:manage', $contextid);
63         // Create base categories.
64         $category1 = new stdClass();
65         $category1->name = 'Root Test Category 1';
66         $category2 = new stdClass();
67         $category2->name = 'Root Test Category 2';
68         $category2->idnumber = 'rootcattest2';
69         $category2->desc = 'Description for root test category 1';
70         $category2->theme = 'base';
71         $categories = array(
72             array('name' => $category1->name, 'parent' => 0),
73             array('name' => $category2->name, 'parent' => 0, 'idnumber' => $category2->idnumber,
74                 'description' => $category2->desc, 'theme' => $category2->theme)
75         );
77         $createdcats = core_course_external::create_categories($categories);
79         // We need to execute the return values cleaning process to simulate the web service server.
80         $createdcats = external_api::clean_returnvalue(core_course_external::create_categories_returns(), $createdcats);
82         // Initially confirm that base data was inserted correctly.
83         $this->assertEquals($category1->name, $createdcats[0]['name']);
84         $this->assertEquals($category2->name, $createdcats[1]['name']);
86         // Save the ids.
87         $category1->id = $createdcats[0]['id'];
88         $category2->id = $createdcats[1]['id'];
90         // Create on sub category.
91         $category3 = new stdClass();
92         $category3->name = 'Sub Root Test Category 3';
93         $subcategories = array(
94             array('name' => $category3->name, 'parent' => $category1->id)
95         );
97         $createdsubcats = core_course_external::create_categories($subcategories);
99         // We need to execute the return values cleaning process to simulate the web service server.
100         $createdsubcats = external_api::clean_returnvalue(core_course_external::create_categories_returns(), $createdsubcats);
102         // Confirm that sub categories were inserted correctly.
103         $this->assertEquals($category3->name, $createdsubcats[0]['name']);
105         // Save the ids.
106         $category3->id = $createdsubcats[0]['id'];
108         // Calling the ws function should provide a new sortorder to give category1,
109         // category2, category3. New course categories are ordered by id not name.
110         $category1 = $DB->get_record('course_categories', array('id' => $category1->id));
111         $category2 = $DB->get_record('course_categories', array('id' => $category2->id));
112         $category3 = $DB->get_record('course_categories', array('id' => $category3->id));
114         // sortorder sequence (and sortorder) must be:
115         // category 1
116         //   category 3
117         // category 2
118         $this->assertGreaterThan($category1->sortorder, $category3->sortorder);
119         $this->assertGreaterThan($category3->sortorder, $category2->sortorder);
121         // Call without required capability
122         $this->unassignUserCapability('moodle/category:manage', $contextid, $roleid);
123         $this->setExpectedException('required_capability_exception');
124         $createdsubcats = core_course_external::create_categories($subcategories);
126     }
128     /**
129      * Test delete categories
130      */
131     public function test_delete_categories() {
132         global $DB;
134         $this->resetAfterTest(true);
136         // Set the required capabilities by the external function
137         $contextid = context_system::instance()->id;
138         $roleid = $this->assignUserCapability('moodle/category:manage', $contextid);
140         $category1  = self::getDataGenerator()->create_category();
141         $category2  = self::getDataGenerator()->create_category(
142                 array('parent' => $category1->id));
143         $category3  = self::getDataGenerator()->create_category();
144         $category4  = self::getDataGenerator()->create_category(
145                 array('parent' => $category3->id));
146         $category5  = self::getDataGenerator()->create_category(
147                 array('parent' => $category4->id));
149         //delete category 1 and 2 + delete category 4, category 5 moved under category 3
150         core_course_external::delete_categories(array(
151             array('id' => $category1->id, 'recursive' => 1),
152             array('id' => $category4->id)
153         ));
155         //check $category 1 and 2 are deleted
156         $notdeletedcount = $DB->count_records_select('course_categories',
157             'id IN ( ' . $category1->id . ',' . $category2->id . ',' . $category4->id . ')');
158         $this->assertEquals(0, $notdeletedcount);
160         //check that $category5 as $category3 for parent
161         $dbcategory5 = $DB->get_record('course_categories', array('id' => $category5->id));
162         $this->assertEquals($dbcategory5->path, $category3->path . '/' . $category5->id);
164          // Call without required capability
165         $this->unassignUserCapability('moodle/category:manage', $contextid, $roleid);
166         $this->setExpectedException('required_capability_exception');
167         $createdsubcats = core_course_external::delete_categories(
168                 array(array('id' => $category3->id)));
169     }
171     /**
172      * Test get categories
173      */
174     public function test_get_categories() {
175         global $DB;
177         $this->resetAfterTest(true);
179         $generatedcats = array();
180         $category1data['idnumber'] = 'idnumbercat1';
181         $category1data['name'] = 'Category 1 for PHPunit test';
182         $category1data['description'] = 'Category 1 description';
183         $category1data['descriptionformat'] = FORMAT_MOODLE;
184         $category1  = self::getDataGenerator()->create_category($category1data);
185         $generatedcats[$category1->id] = $category1;
186         $category2  = self::getDataGenerator()->create_category(
187                 array('parent' => $category1->id));
188         $generatedcats[$category2->id] = $category2;
189         $category6  = self::getDataGenerator()->create_category(
190                 array('parent' => $category1->id, 'visible' => 0));
191         $generatedcats[$category6->id] = $category6;
192         $category3  = self::getDataGenerator()->create_category();
193         $generatedcats[$category3->id] = $category3;
194         $category4  = self::getDataGenerator()->create_category(
195                 array('parent' => $category3->id));
196         $generatedcats[$category4->id] = $category4;
197         $category5  = self::getDataGenerator()->create_category(
198                 array('parent' => $category4->id));
199         $generatedcats[$category5->id] = $category5;
201         // Set the required capabilities by the external function.
202         $context = context_system::instance();
203         $roleid = $this->assignUserCapability('moodle/category:manage', $context->id);
205         // Retrieve category1 + sub-categories except not visible ones
206         $categories = core_course_external::get_categories(array(
207             array('key' => 'id', 'value' => $category1->id),
208             array('key' => 'visible', 'value' => 1)), 1);
210         // We need to execute the return values cleaning process to simulate the web service server.
211         $categories = external_api::clean_returnvalue(core_course_external::get_categories_returns(), $categories);
213         // Check we retrieve the good total number of categories.
214         $this->assertEquals(2, count($categories));
216         // Check the return values
217         foreach ($categories as $category) {
218             $generatedcat = $generatedcats[$category['id']];
219             $this->assertEquals($category['idnumber'], $generatedcat->idnumber);
220             $this->assertEquals($category['name'], $generatedcat->name);
221             // Description was converted to the HTML format.
222             $this->assertEquals($category['description'], format_text($generatedcat->description, FORMAT_MOODLE, array('para' => false)));
223             $this->assertEquals($category['descriptionformat'], FORMAT_HTML);
224         }
226         // Check different params.
227         $categories = core_course_external::get_categories(array(
228             array('key' => 'id', 'value' => $category1->id),
229             array('key' => 'idnumber', 'value' => $category1->idnumber),
230             array('key' => 'visible', 'value' => 1)), 0);
232         // We need to execute the return values cleaning process to simulate the web service server.
233         $categories = external_api::clean_returnvalue(core_course_external::get_categories_returns(), $categories);
235         $this->assertEquals(1, count($categories));
237         // Retrieve categories from parent.
238         $categories = core_course_external::get_categories(array(
239             array('key' => 'parent', 'value' => $category3->id)), 1);
240         $categories = external_api::clean_returnvalue(core_course_external::get_categories_returns(), $categories);
242         $this->assertEquals(2, count($categories));
244         // Retrieve all categories.
245         $categories = core_course_external::get_categories();
247         // We need to execute the return values cleaning process to simulate the web service server.
248         $categories = external_api::clean_returnvalue(core_course_external::get_categories_returns(), $categories);
250         $this->assertEquals($DB->count_records('course_categories'), count($categories));
252         // Call without required capability (it will fail cause of the search on idnumber).
253         $this->unassignUserCapability('moodle/category:manage', $context->id, $roleid);
254         $this->setExpectedException('moodle_exception');
255         $categories = core_course_external::get_categories(array(
256             array('key' => 'id', 'value' => $category1->id),
257             array('key' => 'idnumber', 'value' => $category1->idnumber),
258             array('key' => 'visible', 'value' => 1)), 0);
259     }
261     /**
262      * Test update_categories
263      */
264     public function test_update_categories() {
265         global $DB;
267         $this->resetAfterTest(true);
269         // Set the required capabilities by the external function
270         $contextid = context_system::instance()->id;
271         $roleid = $this->assignUserCapability('moodle/category:manage', $contextid);
273         // Create base categories.
274         $category1data['idnumber'] = 'idnumbercat1';
275         $category1data['name'] = 'Category 1 for PHPunit test';
276         $category1data['description'] = 'Category 1 description';
277         $category1data['descriptionformat'] = FORMAT_MOODLE;
278         $category1  = self::getDataGenerator()->create_category($category1data);
279         $category2  = self::getDataGenerator()->create_category(
280                 array('parent' => $category1->id));
281         $category3  = self::getDataGenerator()->create_category();
282         $category4  = self::getDataGenerator()->create_category(
283                 array('parent' => $category3->id));
284         $category5  = self::getDataGenerator()->create_category(
285                 array('parent' => $category4->id));
287         // We update all category1 attribut.
288         // Then we move cat4 and cat5 parent: cat3 => cat1
289         $categories = array(
290             array('id' => $category1->id,
291                 'name' => $category1->name . '_updated',
292                 'idnumber' => $category1->idnumber . '_updated',
293                 'description' => $category1->description . '_updated',
294                 'descriptionformat' => FORMAT_HTML,
295                 'theme' => $category1->theme),
296             array('id' => $category4->id, 'parent' => $category1->id));
298         core_course_external::update_categories($categories);
300         // Check the values were updated.
301         $dbcategories = $DB->get_records_select('course_categories',
302                 'id IN (' . $category1->id . ',' . $category2->id . ',' . $category2->id
303                 . ',' . $category3->id . ',' . $category4->id . ',' . $category5->id .')');
304         $this->assertEquals($category1->name . '_updated',
305                 $dbcategories[$category1->id]->name);
306         $this->assertEquals($category1->idnumber . '_updated',
307                 $dbcategories[$category1->id]->idnumber);
308         $this->assertEquals($category1->description . '_updated',
309                 $dbcategories[$category1->id]->description);
310         $this->assertEquals(FORMAT_HTML, $dbcategories[$category1->id]->descriptionformat);
312         // Check that category4 and category5 have been properly moved.
313         $this->assertEquals('/' . $category1->id . '/' . $category4->id,
314                 $dbcategories[$category4->id]->path);
315         $this->assertEquals('/' . $category1->id . '/' . $category4->id . '/' . $category5->id,
316                 $dbcategories[$category5->id]->path);
318         // Call without required capability.
319         $this->unassignUserCapability('moodle/category:manage', $contextid, $roleid);
320         $this->setExpectedException('required_capability_exception');
321         core_course_external::update_categories($categories);
322     }
324     /**
325      * Test create_courses
326      */
327     public function test_create_courses() {
328         global $DB;
330         $this->resetAfterTest(true);
332         // Enable course completion.
333         set_config('enablecompletion', 1);
334         // Enable course themes.
335         set_config('allowcoursethemes', 1);
337         // Set the required capabilities by the external function
338         $contextid = context_system::instance()->id;
339         $roleid = $this->assignUserCapability('moodle/course:create', $contextid);
340         $this->assignUserCapability('moodle/course:visibility', $contextid, $roleid);
342         $category  = self::getDataGenerator()->create_category();
344         // Create base categories.
345         $course1['fullname'] = 'Test course 1';
346         $course1['shortname'] = 'Testcourse1';
347         $course1['categoryid'] = $category->id;
348         $course2['fullname'] = 'Test course 2';
349         $course2['shortname'] = 'Testcourse2';
350         $course2['categoryid'] = $category->id;
351         $course2['idnumber'] = 'testcourse2idnumber';
352         $course2['summary'] = 'Description for course 2';
353         $course2['summaryformat'] = FORMAT_MOODLE;
354         $course2['format'] = 'weeks';
355         $course2['showgrades'] = 1;
356         $course2['newsitems'] = 3;
357         $course2['startdate'] = 1420092000; // 01/01/2015
358         $course2['numsections'] = 4;
359         $course2['maxbytes'] = 100000;
360         $course2['showreports'] = 1;
361         $course2['visible'] = 0;
362         $course2['hiddensections'] = 0;
363         $course2['groupmode'] = 0;
364         $course2['groupmodeforce'] = 0;
365         $course2['defaultgroupingid'] = 0;
366         $course2['enablecompletion'] = 1;
367         $course2['completionnotify'] = 1;
368         $course2['lang'] = 'en';
369         $course2['forcetheme'] = 'base';
370         $course3['fullname'] = 'Test course 3';
371         $course3['shortname'] = 'Testcourse3';
372         $course3['categoryid'] = $category->id;
373         $course3['format'] = 'topics';
374         $course3options = array('numsections' => 8,
375             'hiddensections' => 1,
376             'coursedisplay' => 1);
377         $course3['courseformatoptions'] = array();
378         foreach ($course3options as $key => $value) {
379             $course3['courseformatoptions'][] = array('name' => $key, 'value' => $value);
380         }
381         $courses = array($course1, $course2, $course3);
383         $createdcourses = core_course_external::create_courses($courses);
385         // We need to execute the return values cleaning process to simulate the web service server.
386         $createdcourses = external_api::clean_returnvalue(core_course_external::create_courses_returns(), $createdcourses);
388         // Check that right number of courses were created.
389         $this->assertEquals(3, count($createdcourses));
391         // Check that the courses were correctly created.
392         foreach ($createdcourses as $createdcourse) {
393             $courseinfo = course_get_format($createdcourse['id'])->get_course();
395             if ($createdcourse['shortname'] == $course2['shortname']) {
396                 $this->assertEquals($courseinfo->fullname, $course2['fullname']);
397                 $this->assertEquals($courseinfo->shortname, $course2['shortname']);
398                 $this->assertEquals($courseinfo->category, $course2['categoryid']);
399                 $this->assertEquals($courseinfo->idnumber, $course2['idnumber']);
400                 $this->assertEquals($courseinfo->summary, $course2['summary']);
401                 $this->assertEquals($courseinfo->summaryformat, $course2['summaryformat']);
402                 $this->assertEquals($courseinfo->format, $course2['format']);
403                 $this->assertEquals($courseinfo->showgrades, $course2['showgrades']);
404                 $this->assertEquals($courseinfo->newsitems, $course2['newsitems']);
405                 $this->assertEquals($courseinfo->startdate, $course2['startdate']);
406                 $this->assertEquals($courseinfo->numsections, $course2['numsections']);
407                 $this->assertEquals($courseinfo->maxbytes, $course2['maxbytes']);
408                 $this->assertEquals($courseinfo->showreports, $course2['showreports']);
409                 $this->assertEquals($courseinfo->visible, $course2['visible']);
410                 $this->assertEquals($courseinfo->hiddensections, $course2['hiddensections']);
411                 $this->assertEquals($courseinfo->groupmode, $course2['groupmode']);
412                 $this->assertEquals($courseinfo->groupmodeforce, $course2['groupmodeforce']);
413                 $this->assertEquals($courseinfo->defaultgroupingid, $course2['defaultgroupingid']);
414                 $this->assertEquals($courseinfo->completionnotify, $course2['completionnotify']);
415                 $this->assertEquals($courseinfo->lang, $course2['lang']);
416                 $this->assertEquals($courseinfo->theme, $course2['forcetheme']);
418                 // We enabled completion at the beginning of the test.
419                 $this->assertEquals($courseinfo->enablecompletion, $course2['enablecompletion']);
421             } else if ($createdcourse['shortname'] == $course1['shortname']) {
422                 $courseconfig = get_config('moodlecourse');
423                 $this->assertEquals($courseinfo->fullname, $course1['fullname']);
424                 $this->assertEquals($courseinfo->shortname, $course1['shortname']);
425                 $this->assertEquals($courseinfo->category, $course1['categoryid']);
426                 $this->assertEquals($courseinfo->summaryformat, FORMAT_HTML);
427                 $this->assertEquals($courseinfo->format, $courseconfig->format);
428                 $this->assertEquals($courseinfo->showgrades, $courseconfig->showgrades);
429                 $this->assertEquals($courseinfo->newsitems, $courseconfig->newsitems);
430                 $this->assertEquals($courseinfo->maxbytes, $courseconfig->maxbytes);
431                 $this->assertEquals($courseinfo->showreports, $courseconfig->showreports);
432                 $this->assertEquals($courseinfo->groupmode, $courseconfig->groupmode);
433                 $this->assertEquals($courseinfo->groupmodeforce, $courseconfig->groupmodeforce);
434                 $this->assertEquals($courseinfo->defaultgroupingid, 0);
435             } else if ($createdcourse['shortname'] == $course3['shortname']) {
436                 $this->assertEquals($courseinfo->fullname, $course3['fullname']);
437                 $this->assertEquals($courseinfo->shortname, $course3['shortname']);
438                 $this->assertEquals($courseinfo->category, $course3['categoryid']);
439                 $this->assertEquals($courseinfo->format, $course3['format']);
440                 $this->assertEquals($courseinfo->hiddensections, $course3options['hiddensections']);
441                 $this->assertEquals($courseinfo->numsections, $course3options['numsections']);
442                 $this->assertEquals($courseinfo->coursedisplay, $course3options['coursedisplay']);
443             } else {
444                 throw moodle_exception('Unexpected shortname');
445             }
446         }
448         // Call without required capability
449         $this->unassignUserCapability('moodle/course:create', $contextid, $roleid);
450         $this->setExpectedException('required_capability_exception');
451         $createdsubcats = core_course_external::create_courses($courses);
452     }
454     /**
455      * Test delete_courses
456      */
457     public function test_delete_courses() {
458         global $DB, $USER;
460         $this->resetAfterTest(true);
462         // Admin can delete a course.
463         $this->setAdminUser();
464         // Validate_context() will fail as the email is not set by $this->setAdminUser().
465         $USER->email = 'emailtopass@example.com';
467         $course1  = self::getDataGenerator()->create_course();
468         $course2  = self::getDataGenerator()->create_course();
469         $course3  = self::getDataGenerator()->create_course();
471         // Delete courses.
472         $result = core_course_external::delete_courses(array($course1->id, $course2->id));
473         $result = external_api::clean_returnvalue(core_course_external::delete_courses_returns(), $result);
474         // Check for 0 warnings.
475         $this->assertEquals(0, count($result['warnings']));
477         // Check $course 1 and 2 are deleted.
478         $notdeletedcount = $DB->count_records_select('course',
479             'id IN ( ' . $course1->id . ',' . $course2->id . ')');
480         $this->assertEquals(0, $notdeletedcount);
482         // Try to delete non-existent course.
483         $result = core_course_external::delete_courses(array($course1->id));
484         $result = external_api::clean_returnvalue(core_course_external::delete_courses_returns(), $result);
485         // Check for 1 warnings.
486         $this->assertEquals(1, count($result['warnings']));
488         // Try to delete Frontpage course.
489         $result = core_course_external::delete_courses(array(0));
490         $result = external_api::clean_returnvalue(core_course_external::delete_courses_returns(), $result);
491         // Check for 1 warnings.
492         $this->assertEquals(1, count($result['warnings']));
494          // Fail when the user has access to course (enrolled) but does not have permission or is not admin.
495         $student1 = self::getDataGenerator()->create_user();
496         $studentrole = $DB->get_record('role', array('shortname' => 'student'));
497         $this->getDataGenerator()->enrol_user($student1->id,
498                                               $course3->id,
499                                               $studentrole->id);
500         $this->setUser($student1);
501         $result = core_course_external::delete_courses(array($course3->id));
502         $result = external_api::clean_returnvalue(core_course_external::delete_courses_returns(), $result);
503         // Check for 1 warnings.
504         $this->assertEquals(1, count($result['warnings']));
506          // Fail when the user is not allow to access the course (enrolled) or is not admin.
507         $this->setGuestUser();
508         $this->setExpectedException('require_login_exception');
510         $result = core_course_external::delete_courses(array($course3->id));
511         $result = external_api::clean_returnvalue(core_course_external::delete_courses_returns(), $result);
512     }
514     /**
515      * Test get_courses
516      */
517     public function test_get_courses () {
518         global $DB;
520         $this->resetAfterTest(true);
522         $generatedcourses = array();
523         $coursedata['idnumber'] = 'idnumbercourse1';
524         $coursedata['fullname'] = 'Course 1 for PHPunit test';
525         $coursedata['summary'] = 'Course 1 description';
526         $coursedata['summaryformat'] = FORMAT_MOODLE;
527         $course1  = self::getDataGenerator()->create_course($coursedata);
528         $generatedcourses[$course1->id] = $course1;
529         $course2  = self::getDataGenerator()->create_course();
530         $generatedcourses[$course2->id] = $course2;
531         $course3  = self::getDataGenerator()->create_course(array('format' => 'topics'));
532         $generatedcourses[$course3->id] = $course3;
534         // Set the required capabilities by the external function.
535         $context = context_system::instance();
536         $roleid = $this->assignUserCapability('moodle/course:view', $context->id);
537         $this->assignUserCapability('moodle/course:update',
538                 context_course::instance($course1->id)->id, $roleid);
539         $this->assignUserCapability('moodle/course:update',
540                 context_course::instance($course2->id)->id, $roleid);
541         $this->assignUserCapability('moodle/course:update',
542                 context_course::instance($course3->id)->id, $roleid);
544         $courses = core_course_external::get_courses(array('ids' =>
545             array($course1->id, $course2->id)));
547         // We need to execute the return values cleaning process to simulate the web service server.
548         $courses = external_api::clean_returnvalue(core_course_external::get_courses_returns(), $courses);
550         // Check we retrieve the good total number of categories.
551         $this->assertEquals(2, count($courses));
553         foreach ($courses as $course) {
554             $dbcourse = $generatedcourses[$course['id']];
555             $this->assertEquals($course['idnumber'], $dbcourse->idnumber);
556             $this->assertEquals($course['fullname'], $dbcourse->fullname);
557             $this->assertEquals($course['displayname'], get_course_display_name_for_list($dbcourse));
558             // Summary was converted to the HTML format.
559             $this->assertEquals($course['summary'], format_text($dbcourse->summary, FORMAT_MOODLE, array('para' => false)));
560             $this->assertEquals($course['summaryformat'], FORMAT_HTML);
561             $this->assertEquals($course['shortname'], $dbcourse->shortname);
562             $this->assertEquals($course['categoryid'], $dbcourse->category);
563             $this->assertEquals($course['format'], $dbcourse->format);
564             $this->assertEquals($course['showgrades'], $dbcourse->showgrades);
565             $this->assertEquals($course['newsitems'], $dbcourse->newsitems);
566             $this->assertEquals($course['startdate'], $dbcourse->startdate);
567             $this->assertEquals($course['numsections'], $dbcourse->numsections);
568             $this->assertEquals($course['maxbytes'], $dbcourse->maxbytes);
569             $this->assertEquals($course['showreports'], $dbcourse->showreports);
570             $this->assertEquals($course['visible'], $dbcourse->visible);
571             $this->assertEquals($course['hiddensections'], $dbcourse->hiddensections);
572             $this->assertEquals($course['groupmode'], $dbcourse->groupmode);
573             $this->assertEquals($course['groupmodeforce'], $dbcourse->groupmodeforce);
574             $this->assertEquals($course['defaultgroupingid'], $dbcourse->defaultgroupingid);
575             $this->assertEquals($course['completionnotify'], $dbcourse->completionnotify);
576             $this->assertEquals($course['lang'], $dbcourse->lang);
577             $this->assertEquals($course['forcetheme'], $dbcourse->theme);
578             $this->assertEquals($course['enablecompletion'], $dbcourse->enablecompletion);
579             if ($dbcourse->format === 'topics') {
580                 $this->assertEquals($course['courseformatoptions'], array(
581                     array('name' => 'numsections', 'value' => $dbcourse->numsections),
582                     array('name' => 'hiddensections', 'value' => $dbcourse->hiddensections),
583                     array('name' => 'coursedisplay', 'value' => $dbcourse->coursedisplay),
584                 ));
585             }
586         }
588         // Get all courses in the DB
589         $courses = core_course_external::get_courses(array());
591         // We need to execute the return values cleaning process to simulate the web service server.
592         $courses = external_api::clean_returnvalue(core_course_external::get_courses_returns(), $courses);
594         $this->assertEquals($DB->count_records('course'), count($courses));
595     }
597     /**
598      * Test search_courses
599      */
600     public function test_search_courses () {
602         global $DB;
604         $this->resetAfterTest(true);
605         $this->setAdminUser();
606         $generatedcourses = array();
607         $coursedata1['fullname'] = 'FIRST COURSE';
608         $course1  = self::getDataGenerator()->create_course($coursedata1);
609         $coursedata2['fullname'] = 'SECOND COURSE';
610         $course2  = self::getDataGenerator()->create_course($coursedata2);
611         // Search by name.
612         $results = core_course_external::search_courses('search', 'FIRST');
613         $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
614         $this->assertEquals($coursedata1['fullname'], $results['courses'][0]['fullname']);
615         $this->assertCount(1, $results['courses']);
617         // Create the forum.
618         $record = new stdClass();
619         $record->introformat = FORMAT_HTML;
620         $record->course = $course2->id;
621         // Set Aggregate type = Average of ratings.
622         $forum = self::getDataGenerator()->create_module('forum', $record);
624         // Search by module.
625         $results = core_course_external::search_courses('modulelist', 'forum');
626         $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
627         $this->assertEquals(1, $results['total']);
629         // Enable coursetag option.
630         set_config('block_tags_showcoursetags', true);
631         // Add tag 'TAG-LABEL ON SECOND COURSE' to Course2.
632         core_tag_tag::set_item_tags('core', 'course', $course2->id, context_course::instance($course2->id),
633                 array('TAG-LABEL ON SECOND COURSE'));
634         $taginstance = $DB->get_record('tag_instance',
635                 array('itemtype' => 'course', 'itemid' => $course2->id), '*', MUST_EXIST);
636         // Search by tagid.
637         $results = core_course_external::search_courses('tagid', $taginstance->tagid);
638         $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
639         $this->assertEquals($coursedata2['fullname'], $results['courses'][0]['fullname']);
641         // Search by block (use news_items default block).
642         $blockid = $DB->get_field('block', 'id', array('name' => 'news_items'));
643         $results = core_course_external::search_courses('blocklist', $blockid);
644         $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
645         $this->assertEquals(2, $results['total']);
647         // Now as a normal user.
648         $user = self::getDataGenerator()->create_user();
650         // Add a 3rd, hidden, course we shouldn't see, even when enrolled as student.
651         $coursedata3['fullname'] = 'HIDDEN COURSE';
652         $coursedata3['visible'] = 0;
653         $course3  = self::getDataGenerator()->create_course($coursedata3);
654         $this->getDataGenerator()->enrol_user($user->id, $course3->id, 'student');
656         $this->getDataGenerator()->enrol_user($user->id, $course2->id, 'student');
657         $this->setUser($user);
659         $results = core_course_external::search_courses('search', 'FIRST');
660         $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
661         $this->assertCount(1, $results['courses']);
662         $this->assertEquals(1, $results['total']);
663         $this->assertEquals($coursedata1['fullname'], $results['courses'][0]['fullname']);
665         // Check that we can see both without the limit to enrolled setting.
666         $results = core_course_external::search_courses('search', 'COURSE', 0, 0, array(), 0);
667         $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
668         $this->assertCount(2, $results['courses']);
669         $this->assertEquals(2, $results['total']);
671         // Check that we only see our enrolled course when limiting.
672         $results = core_course_external::search_courses('search', 'COURSE', 0, 0, array(), 1);
673         $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
674         $this->assertCount(1, $results['courses']);
675         $this->assertEquals(1, $results['total']);
676         $this->assertEquals($coursedata2['fullname'], $results['courses'][0]['fullname']);
678         // Search by block (use news_items default block). Should fail (only admins allowed).
679         $this->setExpectedException('required_capability_exception');
680         $results = core_course_external::search_courses('blocklist', $blockid);
682     }
684     /**
685      * Create a course with contents
686      * @return array A list with the course object and course modules objects
687      */
688     private function prepare_get_course_contents_test() {
689         global $DB;
690         $course  = self::getDataGenerator()->create_course();
691         $forumdescription = 'This is the forum description';
692         $forum = $this->getDataGenerator()->create_module('forum',
693             array('course' => $course->id, 'intro' => $forumdescription),
694             array('showdescription' => true));
695         $forumcm = get_coursemodule_from_id('forum', $forum->cmid);
696         $data = $this->getDataGenerator()->create_module('data', array('assessed' => 1, 'scale' => 100, 'course' => $course->id));
697         $datacm = get_coursemodule_from_instance('page', $data->id);
698         $page = $this->getDataGenerator()->create_module('page', array('course' => $course->id));
699         $pagecm = get_coursemodule_from_instance('page', $page->id);
700         $labeldescription = 'This is a very long label to test if more than 50 characters are returned.
701                 So bla bla bla bla <b>bold bold bold</b> bla bla bla bla.';
702         $label = $this->getDataGenerator()->create_module('label', array('course' => $course->id,
703             'intro' => $labeldescription));
704         $labelcm = get_coursemodule_from_instance('label', $label->id);
705         $url = $this->getDataGenerator()->create_module('url', array('course' => $course->id,
706             'name' => 'URL: % & $ ../', 'section' => 2));
707         $urlcm = get_coursemodule_from_instance('url', $url->id);
709         // Set the required capabilities by the external function.
710         $context = context_course::instance($course->id);
711         $roleid = $this->assignUserCapability('moodle/course:view', $context->id);
712         $this->assignUserCapability('moodle/course:update', $context->id, $roleid);
714         $conditions = array('course' => $course->id, 'section' => 2);
715         $DB->set_field('course_sections', 'summary', 'Text with iframe <iframe src="https://moodle.org"></iframe>', $conditions);
716         rebuild_course_cache($course->id, true);
718         return array($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm);
719     }
721     /**
722      * Test get_course_contents
723      */
724     public function test_get_course_contents() {
725         $this->resetAfterTest(true);
727         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
729         $sections = core_course_external::get_course_contents($course->id, array());
730         // We need to execute the return values cleaning process to simulate the web service server.
731         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
733         // Check that forum and label descriptions are correctly returned.
734         $firstsection = array_shift($sections);
735         $lastsection = array_pop($sections);
737         $modinfo = get_fast_modinfo($course);
738         $testexecuted = 0;
739         foreach ($firstsection['modules'] as $module) {
740             if ($module['id'] == $forumcm->id and $module['modname'] == 'forum') {
741                 $cm = $modinfo->cms[$forumcm->id];
742                 $formattedtext = format_text($cm->content, FORMAT_HTML,
743                     array('noclean' => true, 'para' => false, 'filter' => false));
744                 $this->assertEquals($formattedtext, $module['description']);
745                 $this->assertEquals($forumcm->instance, $module['instance']);
746                 $testexecuted = $testexecuted + 1;
747             } else if ($module['id'] == $labelcm->id and $module['modname'] == 'label') {
748                 $cm = $modinfo->cms[$labelcm->id];
749                 $formattedtext = format_text($cm->content, FORMAT_HTML,
750                     array('noclean' => true, 'para' => false, 'filter' => false));
751                 $this->assertEquals($formattedtext, $module['description']);
752                 $this->assertEquals($labelcm->instance, $module['instance']);
753                 $testexecuted = $testexecuted + 1;
754             }
755         }
756         $this->assertEquals(2, $testexecuted);
757         $this->assertEquals(0, $firstsection['section']);
759         // Check that the only return section has the 5 created modules.
760         $this->assertCount(4, $firstsection['modules']);
761         $this->assertCount(1, $lastsection['modules']);
762         $this->assertEquals(2, $lastsection['section']);
763         $this->assertContains('<iframe', $lastsection['summary']);
764         $this->assertContains('</iframe>', $lastsection['summary']);
766         try {
767             $sections = core_course_external::get_course_contents($course->id,
768                                                                     array(array("name" => "invalid", "value" => 1)));
769             $this->fail('Exception expected due to invalid option.');
770         } catch (moodle_exception $e) {
771             $this->assertEquals('errorinvalidparam', $e->errorcode);
772         }
773     }
776     /**
777      * Test get_course_contents excluding modules
778      */
779     public function test_get_course_contents_excluding_modules() {
780         $this->resetAfterTest(true);
782         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
784         // Test exclude modules.
785         $sections = core_course_external::get_course_contents($course->id, array(array("name" => "excludemodules", "value" => 1)));
787         // We need to execute the return values cleaning process to simulate the web service server.
788         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
790         $firstsection = array_shift($sections);
791         $lastsection = array_pop($sections);
793         $this->assertEmpty($firstsection['modules']);
794         $this->assertEmpty($lastsection['modules']);
795     }
797     /**
798      * Test get_course_contents excluding contents
799      */
800     public function test_get_course_contents_excluding_contents() {
801         $this->resetAfterTest(true);
803         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
805         // Test exclude modules.
806         $sections = core_course_external::get_course_contents($course->id, array(array("name" => "excludecontents", "value" => 1)));
808         // We need to execute the return values cleaning process to simulate the web service server.
809         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
811         foreach ($sections as $section) {
812             foreach ($section['modules'] as $module) {
813                 // Only resources return contents.
814                 if (isset($module['contents'])) {
815                     $this->assertEmpty($module['contents']);
816                 }
817             }
818         }
819     }
821     /**
822      * Test get_course_contents filtering by section number
823      */
824     public function test_get_course_contents_section_number() {
825         $this->resetAfterTest(true);
827         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
829         // Test exclude modules.
830         $sections = core_course_external::get_course_contents($course->id, array(array("name" => "sectionnumber", "value" => 0)));
832         // We need to execute the return values cleaning process to simulate the web service server.
833         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
835         $this->assertCount(1, $sections);
836         $this->assertCount(4, $sections[0]['modules']);
837     }
839     /**
840      * Test get_course_contents filtering by cmid
841      */
842     public function test_get_course_contents_cmid() {
843         $this->resetAfterTest(true);
845         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
847         // Test exclude modules.
848         $sections = core_course_external::get_course_contents($course->id, array(array("name" => "cmid", "value" => $forumcm->id)));
850         // We need to execute the return values cleaning process to simulate the web service server.
851         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
853         $this->assertCount(2, $sections);
854         $this->assertCount(1, $sections[0]['modules']);
855         $this->assertEquals($forumcm->id, $sections[0]['modules'][0]["id"]);
856     }
859     /**
860      * Test get_course_contents filtering by cmid and section
861      */
862     public function test_get_course_contents_section_cmid() {
863         $this->resetAfterTest(true);
865         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
867         // Test exclude modules.
868         $sections = core_course_external::get_course_contents($course->id, array(
869                                                                         array("name" => "cmid", "value" => $forumcm->id),
870                                                                         array("name" => "sectionnumber", "value" => 0)
871                                                                         ));
873         // We need to execute the return values cleaning process to simulate the web service server.
874         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
876         $this->assertCount(1, $sections);
877         $this->assertCount(1, $sections[0]['modules']);
878         $this->assertEquals($forumcm->id, $sections[0]['modules'][0]["id"]);
879     }
881     /**
882      * Test get_course_contents filtering by modname
883      */
884     public function test_get_course_contents_modname() {
885         $this->resetAfterTest(true);
887         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
889         // Test exclude modules.
890         $sections = core_course_external::get_course_contents($course->id, array(array("name" => "modname", "value" => "forum")));
892         // We need to execute the return values cleaning process to simulate the web service server.
893         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
895         $this->assertCount(2, $sections);
896         $this->assertCount(1, $sections[0]['modules']);
897         $this->assertEquals($forumcm->id, $sections[0]['modules'][0]["id"]);
898     }
900     /**
901      * Test get_course_contents filtering by modname
902      */
903     public function test_get_course_contents_modid() {
904         $this->resetAfterTest(true);
906         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
908         // Test exclude modules.
909         $sections = core_course_external::get_course_contents($course->id, array(
910                                                                             array("name" => "modname", "value" => "page"),
911                                                                             array("name" => "modid", "value" => $pagecm->instance),
912                                                                             ));
914         // We need to execute the return values cleaning process to simulate the web service server.
915         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
917         $this->assertCount(2, $sections);
918         $this->assertCount(1, $sections[0]['modules']);
919         $this->assertEquals("page", $sections[0]['modules'][0]["modname"]);
920         $this->assertEquals($pagecm->instance, $sections[0]['modules'][0]["instance"]);
921     }
923     /**
924      * Test duplicate_course
925      */
926     public function test_duplicate_course() {
927         $this->resetAfterTest(true);
929         // Create one course with three modules.
930         $course  = self::getDataGenerator()->create_course();
931         $forum = $this->getDataGenerator()->create_module('forum', array('course'=>$course->id));
932         $forumcm = get_coursemodule_from_id('forum', $forum->cmid);
933         $forumcontext = context_module::instance($forum->cmid);
934         $data = $this->getDataGenerator()->create_module('data', array('assessed'=>1, 'scale'=>100, 'course'=>$course->id));
935         $datacontext = context_module::instance($data->cmid);
936         $datacm = get_coursemodule_from_instance('page', $data->id);
937         $page = $this->getDataGenerator()->create_module('page', array('course'=>$course->id));
938         $pagecontext = context_module::instance($page->cmid);
939         $pagecm = get_coursemodule_from_instance('page', $page->id);
941         // Set the required capabilities by the external function.
942         $coursecontext = context_course::instance($course->id);
943         $categorycontext = context_coursecat::instance($course->category);
944         $roleid = $this->assignUserCapability('moodle/course:create', $categorycontext->id);
945         $this->assignUserCapability('moodle/course:view', $categorycontext->id, $roleid);
946         $this->assignUserCapability('moodle/restore:restorecourse', $categorycontext->id, $roleid);
947         $this->assignUserCapability('moodle/backup:backupcourse', $coursecontext->id, $roleid);
948         $this->assignUserCapability('moodle/backup:configure', $coursecontext->id, $roleid);
949         // Optional capabilities to copy user data.
950         $this->assignUserCapability('moodle/backup:userinfo', $coursecontext->id, $roleid);
951         $this->assignUserCapability('moodle/restore:userinfo', $categorycontext->id, $roleid);
953         $newcourse['fullname'] = 'Course duplicate';
954         $newcourse['shortname'] = 'courseduplicate';
955         $newcourse['categoryid'] = $course->category;
956         $newcourse['visible'] = true;
957         $newcourse['options'][] = array('name' => 'users', 'value' => true);
959         $duplicate = core_course_external::duplicate_course($course->id, $newcourse['fullname'],
960                 $newcourse['shortname'], $newcourse['categoryid'], $newcourse['visible'], $newcourse['options']);
962         // We need to execute the return values cleaning process to simulate the web service server.
963         $duplicate = external_api::clean_returnvalue(core_course_external::duplicate_course_returns(), $duplicate);
965         // Check that the course has been duplicated.
966         $this->assertEquals($newcourse['shortname'], $duplicate['shortname']);
967     }
969     /**
970      * Test update_courses
971      */
972     public function test_update_courses() {
973         global $DB, $CFG, $USER, $COURSE;
975         // Get current $COURSE to be able to restore it later (defaults to $SITE). We need this
976         // trick because we are both updating and getting (for testing) course information
977         // in the same request and core_course_external::update_courses()
978         // is overwriting $COURSE all over the time with OLD values, so later
979         // use of get_course() fetches those OLD values instead of the updated ones.
980         // See MDL-39723 for more info.
981         $origcourse = clone($COURSE);
983         $this->resetAfterTest(true);
985         // Set the required capabilities by the external function.
986         $contextid = context_system::instance()->id;
987         $roleid = $this->assignUserCapability('moodle/course:update', $contextid);
988         $this->assignUserCapability('moodle/course:changecategory', $contextid, $roleid);
989         $this->assignUserCapability('moodle/course:changefullname', $contextid, $roleid);
990         $this->assignUserCapability('moodle/course:changeshortname', $contextid, $roleid);
991         $this->assignUserCapability('moodle/course:changeidnumber', $contextid, $roleid);
992         $this->assignUserCapability('moodle/course:changesummary', $contextid, $roleid);
993         $this->assignUserCapability('moodle/course:visibility', $contextid, $roleid);
994         $this->assignUserCapability('moodle/course:viewhiddencourses', $contextid, $roleid);
996         // Create category and course.
997         $category1  = self::getDataGenerator()->create_category();
998         $category2  = self::getDataGenerator()->create_category();
999         $originalcourse1 = self::getDataGenerator()->create_course();
1000         self::getDataGenerator()->enrol_user($USER->id, $originalcourse1->id, $roleid);
1001         $originalcourse2 = self::getDataGenerator()->create_course();
1002         self::getDataGenerator()->enrol_user($USER->id, $originalcourse2->id, $roleid);
1004         // Course values to be updated.
1005         $course1['id'] = $originalcourse1->id;
1006         $course1['fullname'] = 'Updated test course 1';
1007         $course1['shortname'] = 'Udestedtestcourse1';
1008         $course1['categoryid'] = $category1->id;
1009         $course2['id'] = $originalcourse2->id;
1010         $course2['fullname'] = 'Updated test course 2';
1011         $course2['shortname'] = 'Updestedtestcourse2';
1012         $course2['categoryid'] = $category2->id;
1013         $course2['idnumber'] = 'Updatedidnumber2';
1014         $course2['summary'] = 'Updaated description for course 2';
1015         $course2['summaryformat'] = FORMAT_HTML;
1016         $course2['format'] = 'topics';
1017         $course2['showgrades'] = 1;
1018         $course2['newsitems'] = 3;
1019         $course2['startdate'] = 1420092000; // 01/01/2015.
1020         $course2['numsections'] = 4;
1021         $course2['maxbytes'] = 100000;
1022         $course2['showreports'] = 1;
1023         $course2['visible'] = 0;
1024         $course2['hiddensections'] = 0;
1025         $course2['groupmode'] = 0;
1026         $course2['groupmodeforce'] = 0;
1027         $course2['defaultgroupingid'] = 0;
1028         $course2['enablecompletion'] = 1;
1029         $course2['lang'] = 'en';
1030         $course2['forcetheme'] = 'base';
1031         $courses = array($course1, $course2);
1033         $updatedcoursewarnings = core_course_external::update_courses($courses);
1034         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1035                                                                     $updatedcoursewarnings);
1036         $COURSE = $origcourse; // Restore $COURSE. Instead of using the OLD one set by the previous line.
1038         // Check that right number of courses were created.
1039         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1041         // Check that the courses were correctly created.
1042         foreach ($courses as $course) {
1043             $courseinfo = course_get_format($course['id'])->get_course();
1044             if ($course['id'] == $course2['id']) {
1045                 $this->assertEquals($course2['fullname'], $courseinfo->fullname);
1046                 $this->assertEquals($course2['shortname'], $courseinfo->shortname);
1047                 $this->assertEquals($course2['categoryid'], $courseinfo->category);
1048                 $this->assertEquals($course2['idnumber'], $courseinfo->idnumber);
1049                 $this->assertEquals($course2['summary'], $courseinfo->summary);
1050                 $this->assertEquals($course2['summaryformat'], $courseinfo->summaryformat);
1051                 $this->assertEquals($course2['format'], $courseinfo->format);
1052                 $this->assertEquals($course2['showgrades'], $courseinfo->showgrades);
1053                 $this->assertEquals($course2['newsitems'], $courseinfo->newsitems);
1054                 $this->assertEquals($course2['startdate'], $courseinfo->startdate);
1055                 $this->assertEquals($course2['numsections'], $courseinfo->numsections);
1056                 $this->assertEquals($course2['maxbytes'], $courseinfo->maxbytes);
1057                 $this->assertEquals($course2['showreports'], $courseinfo->showreports);
1058                 $this->assertEquals($course2['visible'], $courseinfo->visible);
1059                 $this->assertEquals($course2['hiddensections'], $courseinfo->hiddensections);
1060                 $this->assertEquals($course2['groupmode'], $courseinfo->groupmode);
1061                 $this->assertEquals($course2['groupmodeforce'], $courseinfo->groupmodeforce);
1062                 $this->assertEquals($course2['defaultgroupingid'], $courseinfo->defaultgroupingid);
1063                 $this->assertEquals($course2['lang'], $courseinfo->lang);
1065                 if (!empty($CFG->allowcoursethemes)) {
1066                     $this->assertEquals($course2['forcetheme'], $courseinfo->theme);
1067                 }
1069                 $this->assertEquals($course2['enablecompletion'], $courseinfo->enablecompletion);
1070             } else if ($course['id'] == $course1['id']) {
1071                 $this->assertEquals($course1['fullname'], $courseinfo->fullname);
1072                 $this->assertEquals($course1['shortname'], $courseinfo->shortname);
1073                 $this->assertEquals($course1['categoryid'], $courseinfo->category);
1074                 $this->assertEquals(FORMAT_MOODLE, $courseinfo->summaryformat);
1075                 $this->assertEquals('topics', $courseinfo->format);
1076                 $this->assertEquals(5, $courseinfo->numsections);
1077                 $this->assertEquals(0, $courseinfo->newsitems);
1078                 $this->assertEquals(FORMAT_MOODLE, $courseinfo->summaryformat);
1079             } else {
1080                 throw moodle_exception('Unexpected shortname');
1081             }
1082         }
1084         $courses = array($course1);
1085         // Try update course without update capability.
1086         $user = self::getDataGenerator()->create_user();
1087         $this->setUser($user);
1088         $this->unassignUserCapability('moodle/course:update', $contextid, $roleid);
1089         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1090         $updatedcoursewarnings = core_course_external::update_courses($courses);
1091         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1092                                                                     $updatedcoursewarnings);
1093         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1095         // Try update course category without capability.
1096         $this->assignUserCapability('moodle/course:update', $contextid, $roleid);
1097         $this->unassignUserCapability('moodle/course:changecategory', $contextid, $roleid);
1098         $user = self::getDataGenerator()->create_user();
1099         $this->setUser($user);
1100         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1101         $course1['categoryid'] = $category2->id;
1102         $courses = array($course1);
1103         $updatedcoursewarnings = core_course_external::update_courses($courses);
1104         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1105                                                                     $updatedcoursewarnings);
1106         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1108         // Try update course fullname without capability.
1109         $this->assignUserCapability('moodle/course:changecategory', $contextid, $roleid);
1110         $this->unassignUserCapability('moodle/course:changefullname', $contextid, $roleid);
1111         $user = self::getDataGenerator()->create_user();
1112         $this->setUser($user);
1113         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1114         $updatedcoursewarnings = core_course_external::update_courses($courses);
1115         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1116                                                                     $updatedcoursewarnings);
1117         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1118         $course1['fullname'] = 'Testing fullname without permission';
1119         $courses = array($course1);
1120         $updatedcoursewarnings = core_course_external::update_courses($courses);
1121         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1122                                                                     $updatedcoursewarnings);
1123         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1125         // Try update course shortname without capability.
1126         $this->assignUserCapability('moodle/course:changefullname', $contextid, $roleid);
1127         $this->unassignUserCapability('moodle/course:changeshortname', $contextid, $roleid);
1128         $user = self::getDataGenerator()->create_user();
1129         $this->setUser($user);
1130         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1131         $updatedcoursewarnings = core_course_external::update_courses($courses);
1132         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1133                                                                     $updatedcoursewarnings);
1134         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1135         $course1['shortname'] = 'Testing shortname without permission';
1136         $courses = array($course1);
1137         $updatedcoursewarnings = core_course_external::update_courses($courses);
1138         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1139                                                                     $updatedcoursewarnings);
1140         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1142         // Try update course idnumber without capability.
1143         $this->assignUserCapability('moodle/course:changeshortname', $contextid, $roleid);
1144         $this->unassignUserCapability('moodle/course:changeidnumber', $contextid, $roleid);
1145         $user = self::getDataGenerator()->create_user();
1146         $this->setUser($user);
1147         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1148         $updatedcoursewarnings = core_course_external::update_courses($courses);
1149         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1150                                                                     $updatedcoursewarnings);
1151         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1152         $course1['idnumber'] = 'NEWIDNUMBER';
1153         $courses = array($course1);
1154         $updatedcoursewarnings = core_course_external::update_courses($courses);
1155         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1156                                                                     $updatedcoursewarnings);
1157         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1159         // Try update course summary without capability.
1160         $this->assignUserCapability('moodle/course:changeidnumber', $contextid, $roleid);
1161         $this->unassignUserCapability('moodle/course:changesummary', $contextid, $roleid);
1162         $user = self::getDataGenerator()->create_user();
1163         $this->setUser($user);
1164         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1165         $updatedcoursewarnings = core_course_external::update_courses($courses);
1166         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1167                                                                     $updatedcoursewarnings);
1168         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1169         $course1['summary'] = 'New summary';
1170         $courses = array($course1);
1171         $updatedcoursewarnings = core_course_external::update_courses($courses);
1172         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1173                                                                     $updatedcoursewarnings);
1174         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1176         // Try update course with invalid summary format.
1177         $this->assignUserCapability('moodle/course:changesummary', $contextid, $roleid);
1178         $user = self::getDataGenerator()->create_user();
1179         $this->setUser($user);
1180         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1181         $updatedcoursewarnings = core_course_external::update_courses($courses);
1182         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1183                                                                     $updatedcoursewarnings);
1184         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1185         $course1['summaryformat'] = 10;
1186         $courses = array($course1);
1187         $updatedcoursewarnings = core_course_external::update_courses($courses);
1188         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1189                                                                     $updatedcoursewarnings);
1190         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1192         // Try update course visibility without capability.
1193         $this->unassignUserCapability('moodle/course:visibility', $contextid, $roleid);
1194         $user = self::getDataGenerator()->create_user();
1195         $this->setUser($user);
1196         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1197         $course1['summaryformat'] = FORMAT_MOODLE;
1198         $courses = array($course1);
1199         $updatedcoursewarnings = core_course_external::update_courses($courses);
1200         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1201                                                                     $updatedcoursewarnings);
1202         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1203         $course1['visible'] = 0;
1204         $courses = array($course1);
1205         $updatedcoursewarnings = core_course_external::update_courses($courses);
1206         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1207                                                                     $updatedcoursewarnings);
1208         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1209     }
1211     /**
1212      * Test delete course_module.
1213      */
1214     public function test_delete_modules() {
1215         global $DB;
1217         // Ensure we reset the data after this test.
1218         $this->resetAfterTest(true);
1220         // Create a user.
1221         $user = self::getDataGenerator()->create_user();
1223         // Set the tests to run as the user.
1224         self::setUser($user);
1226         // Create a course to add the modules.
1227         $course = self::getDataGenerator()->create_course();
1229         // Create two test modules.
1230         $record = new stdClass();
1231         $record->course = $course->id;
1232         $module1 = self::getDataGenerator()->create_module('forum', $record);
1233         $module2 = self::getDataGenerator()->create_module('assign', $record);
1235         // Check the forum was correctly created.
1236         $this->assertEquals(1, $DB->count_records('forum', array('id' => $module1->id)));
1238         // Check the assignment was correctly created.
1239         $this->assertEquals(1, $DB->count_records('assign', array('id' => $module2->id)));
1241         // Check data exists in the course modules table.
1242         $this->assertEquals(2, $DB->count_records_select('course_modules', 'id = :module1 OR id = :module2',
1243                 array('module1' => $module1->cmid, 'module2' => $module2->cmid)));
1245         // Enrol the user in the course.
1246         $enrol = enrol_get_plugin('manual');
1247         $enrolinstances = enrol_get_instances($course->id, true);
1248         foreach ($enrolinstances as $courseenrolinstance) {
1249             if ($courseenrolinstance->enrol == "manual") {
1250                 $instance = $courseenrolinstance;
1251                 break;
1252             }
1253         }
1254         $enrol->enrol_user($instance, $user->id);
1256         // Assign capabilities to delete module 1.
1257         $modcontext = context_module::instance($module1->cmid);
1258         $this->assignUserCapability('moodle/course:manageactivities', $modcontext->id);
1260         // Assign capabilities to delete module 2.
1261         $modcontext = context_module::instance($module2->cmid);
1262         $newrole = create_role('Role 2', 'role2', 'Role 2 description');
1263         $this->assignUserCapability('moodle/course:manageactivities', $modcontext->id, $newrole);
1265         // Deleting these module instances.
1266         core_course_external::delete_modules(array($module1->cmid, $module2->cmid));
1268         // Check the forum was deleted.
1269         $this->assertEquals(0, $DB->count_records('forum', array('id' => $module1->id)));
1271         // Check the assignment was deleted.
1272         $this->assertEquals(0, $DB->count_records('assign', array('id' => $module2->id)));
1274         // Check we retrieve no data in the course modules table.
1275         $this->assertEquals(0, $DB->count_records_select('course_modules', 'id = :module1 OR id = :module2',
1276                 array('module1' => $module1->cmid, 'module2' => $module2->cmid)));
1278         // Call with non-existent course module id and ensure exception thrown.
1279         try {
1280             core_course_external::delete_modules(array('1337'));
1281             $this->fail('Exception expected due to missing course module.');
1282         } catch (dml_missing_record_exception $e) {
1283             $this->assertEquals('invalidcoursemodule', $e->errorcode);
1284         }
1286         // Create two modules.
1287         $module1 = self::getDataGenerator()->create_module('forum', $record);
1288         $module2 = self::getDataGenerator()->create_module('assign', $record);
1290         // Since these modules were recreated the user will not have capabilities
1291         // to delete them, ensure exception is thrown if they try.
1292         try {
1293             core_course_external::delete_modules(array($module1->cmid, $module2->cmid));
1294             $this->fail('Exception expected due to missing capability.');
1295         } catch (moodle_exception $e) {
1296             $this->assertEquals('nopermissions', $e->errorcode);
1297         }
1299         // Unenrol user from the course.
1300         $enrol->unenrol_user($instance, $user->id);
1302         // Try and delete modules from the course the user was unenrolled in, make sure exception thrown.
1303         try {
1304             core_course_external::delete_modules(array($module1->cmid, $module2->cmid));
1305             $this->fail('Exception expected due to being unenrolled from the course.');
1306         } catch (moodle_exception $e) {
1307             $this->assertEquals('requireloginerror', $e->errorcode);
1308         }
1309     }
1311     /**
1312      * Test import_course into an empty course
1313      */
1314     public function test_import_course_empty() {
1315         global $USER;
1317         $this->resetAfterTest(true);
1319         $course1  = self::getDataGenerator()->create_course();
1320         $forum = $this->getDataGenerator()->create_module('forum', array('course' => $course1->id, 'name' => 'Forum test'));
1321         $page = $this->getDataGenerator()->create_module('page', array('course' => $course1->id, 'name' => 'Page test'));
1323         $course2  = self::getDataGenerator()->create_course();
1325         $course1cms = get_fast_modinfo($course1->id)->get_cms();
1326         $course2cms = get_fast_modinfo($course2->id)->get_cms();
1328         // Verify the state of the courses before we do the import.
1329         $this->assertCount(2, $course1cms);
1330         $this->assertEmpty($course2cms);
1332         // Setup the user to run the operation (ugly hack because validate_context() will
1333         // fail as the email is not set by $this->setAdminUser()).
1334         $this->setAdminUser();
1335         $USER->email = 'emailtopass@example.com';
1337         // Import from course1 to course2.
1338         core_course_external::import_course($course1->id, $course2->id, 0);
1340         // Verify that now we have two modules in both courses.
1341         $course1cms = get_fast_modinfo($course1->id)->get_cms();
1342         $course2cms = get_fast_modinfo($course2->id)->get_cms();
1343         $this->assertCount(2, $course1cms);
1344         $this->assertCount(2, $course2cms);
1346         // Verify that the names transfered across correctly.
1347         foreach ($course2cms as $cm) {
1348             if ($cm->modname === 'page') {
1349                 $this->assertEquals($cm->name, $page->name);
1350             } else if ($cm->modname === 'forum') {
1351                 $this->assertEquals($cm->name, $forum->name);
1352             } else {
1353                 $this->fail('Unknown CM found.');
1354             }
1355         }
1356     }
1358     /**
1359      * Test import_course into an filled course
1360      */
1361     public function test_import_course_filled() {
1362         global $USER;
1364         $this->resetAfterTest(true);
1366         // Add forum and page to course1.
1367         $course1  = self::getDataGenerator()->create_course();
1368         $forum = $this->getDataGenerator()->create_module('forum', array('course'=>$course1->id, 'name' => 'Forum test'));
1369         $page = $this->getDataGenerator()->create_module('page', array('course'=>$course1->id, 'name' => 'Page test'));
1371         // Add quiz to course 2.
1372         $course2  = self::getDataGenerator()->create_course();
1373         $quiz = $this->getDataGenerator()->create_module('quiz', array('course'=>$course2->id, 'name' => 'Page test'));
1375         $course1cms = get_fast_modinfo($course1->id)->get_cms();
1376         $course2cms = get_fast_modinfo($course2->id)->get_cms();
1378         // Verify the state of the courses before we do the import.
1379         $this->assertCount(2, $course1cms);
1380         $this->assertCount(1, $course2cms);
1382         // Setup the user to run the operation (ugly hack because validate_context() will
1383         // fail as the email is not set by $this->setAdminUser()).
1384         $this->setAdminUser();
1385         $USER->email = 'emailtopass@example.com';
1387         // Import from course1 to course2 without deleting content.
1388         core_course_external::import_course($course1->id, $course2->id, 0);
1390         $course2cms = get_fast_modinfo($course2->id)->get_cms();
1392         // Verify that now we have three modules in course2.
1393         $this->assertCount(3, $course2cms);
1395         // Verify that the names transfered across correctly.
1396         foreach ($course2cms as $cm) {
1397             if ($cm->modname === 'page') {
1398                 $this->assertEquals($cm->name, $page->name);
1399             } else if ($cm->modname === 'forum') {
1400                 $this->assertEquals($cm->name, $forum->name);
1401             } else if ($cm->modname === 'quiz') {
1402                 $this->assertEquals($cm->name, $quiz->name);
1403             } else {
1404                 $this->fail('Unknown CM found.');
1405             }
1406         }
1407     }
1409     /**
1410      * Test import_course with only blocks set to backup
1411      */
1412     public function test_import_course_blocksonly() {
1413         global $USER, $DB;
1415         $this->resetAfterTest(true);
1417         // Add forum and page to course1.
1418         $course1  = self::getDataGenerator()->create_course();
1419         $course1ctx = context_course::instance($course1->id);
1420         $forum = $this->getDataGenerator()->create_module('forum', array('course'=>$course1->id, 'name' => 'Forum test'));
1421         $block = $this->getDataGenerator()->create_block('online_users', array('parentcontextid' => $course1ctx->id));
1423         $course2  = self::getDataGenerator()->create_course();
1424         $course2ctx = context_course::instance($course2->id);
1425         $initialblockcount = $DB->count_records('block_instances', array('parentcontextid' => $course2ctx->id));
1426         $initialcmcount = count(get_fast_modinfo($course2->id)->get_cms());
1428         // Setup the user to run the operation (ugly hack because validate_context() will
1429         // fail as the email is not set by $this->setAdminUser()).
1430         $this->setAdminUser();
1431         $USER->email = 'emailtopass@example.com';
1433         // Import from course1 to course2 without deleting content, but excluding
1434         // activities.
1435         $options = array(
1436             array('name' => 'activities', 'value' => 0),
1437             array('name' => 'blocks', 'value' => 1),
1438             array('name' => 'filters', 'value' => 0),
1439         );
1441         core_course_external::import_course($course1->id, $course2->id, 0, $options);
1443         $newcmcount = count(get_fast_modinfo($course2->id)->get_cms());
1444         $newblockcount = $DB->count_records('block_instances', array('parentcontextid' => $course2ctx->id));
1445         // Check that course modules haven't changed, but that blocks have.
1446         $this->assertEquals($initialcmcount, $newcmcount);
1447         $this->assertEquals(($initialblockcount + 1), $newblockcount);
1448     }
1450     /**
1451      * Test import_course into an filled course, deleting content.
1452      */
1453     public function test_import_course_deletecontent() {
1454         global $USER;
1455         $this->resetAfterTest(true);
1457         // Add forum and page to course1.
1458         $course1  = self::getDataGenerator()->create_course();
1459         $forum = $this->getDataGenerator()->create_module('forum', array('course'=>$course1->id, 'name' => 'Forum test'));
1460         $page = $this->getDataGenerator()->create_module('page', array('course'=>$course1->id, 'name' => 'Page test'));
1462         // Add quiz to course 2.
1463         $course2  = self::getDataGenerator()->create_course();
1464         $quiz = $this->getDataGenerator()->create_module('quiz', array('course'=>$course2->id, 'name' => 'Page test'));
1466         $course1cms = get_fast_modinfo($course1->id)->get_cms();
1467         $course2cms = get_fast_modinfo($course2->id)->get_cms();
1469         // Verify the state of the courses before we do the import.
1470         $this->assertCount(2, $course1cms);
1471         $this->assertCount(1, $course2cms);
1473         // Setup the user to run the operation (ugly hack because validate_context() will
1474         // fail as the email is not set by $this->setAdminUser()).
1475         $this->setAdminUser();
1476         $USER->email = 'emailtopass@example.com';
1478         // Import from course1 to course2,  deleting content.
1479         core_course_external::import_course($course1->id, $course2->id, 1);
1481         $course2cms = get_fast_modinfo($course2->id)->get_cms();
1483         // Verify that now we have two modules in course2.
1484         $this->assertCount(2, $course2cms);
1486         // Verify that the course only contains the imported modules.
1487         foreach ($course2cms as $cm) {
1488             if ($cm->modname === 'page') {
1489                 $this->assertEquals($cm->name, $page->name);
1490             } else if ($cm->modname === 'forum') {
1491                 $this->assertEquals($cm->name, $forum->name);
1492             } else {
1493                 $this->fail('Unknown CM found: '.$cm->name);
1494             }
1495         }
1496     }
1498     /**
1499      * Ensure import_course handles incorrect deletecontent option correctly.
1500      */
1501     public function test_import_course_invalid_deletecontent_option() {
1502         $this->resetAfterTest(true);
1504         $course1  = self::getDataGenerator()->create_course();
1505         $course2  = self::getDataGenerator()->create_course();
1507         $this->setExpectedException('moodle_exception', get_string('invalidextparam', 'webservice', -1));
1508         // Import from course1 to course2, with invalid option
1509         core_course_external::import_course($course1->id, $course2->id, -1);;
1510     }
1512     /**
1513      * Test view_course function
1514      */
1515     public function test_view_course() {
1517         $this->resetAfterTest();
1519         // Course without sections.
1520         $course = $this->getDataGenerator()->create_course(array('numsections' => 5), array('createsections' => true));
1521         $this->setAdminUser();
1523         // Redirect events to the sink, so we can recover them later.
1524         $sink = $this->redirectEvents();
1526         $result = core_course_external::view_course($course->id, 1);
1527         $result = external_api::clean_returnvalue(core_course_external::view_course_returns(), $result);
1528         $events = $sink->get_events();
1529         $event = reset($events);
1531         // Check the event details are correct.
1532         $this->assertInstanceOf('\core\event\course_viewed', $event);
1533         $this->assertEquals(context_course::instance($course->id), $event->get_context());
1534         $this->assertEquals(1, $event->other['coursesectionnumber']);
1536         $result = core_course_external::view_course($course->id);
1537         $result = external_api::clean_returnvalue(core_course_external::view_course_returns(), $result);
1538         $events = $sink->get_events();
1539         $event = array_pop($events);
1540         $sink->close();
1542         // Check the event details are correct.
1543         $this->assertInstanceOf('\core\event\course_viewed', $event);
1544         $this->assertEquals(context_course::instance($course->id), $event->get_context());
1545         $this->assertEmpty($event->other);
1547     }
1549     /**
1550      * Test get_course_module
1551      */
1552     public function test_get_course_module() {
1553         global $DB;
1555         $this->resetAfterTest(true);
1557         $this->setAdminUser();
1558         $course = self::getDataGenerator()->create_course();
1559         $record = array(
1560             'course' => $course->id,
1561             'name' => 'First Chat'
1562         );
1563         $options = array(
1564             'idnumber' => 'ABC',
1565             'visible' => 0
1566         );
1567         // Hidden activity.
1568         $chat = self::getDataGenerator()->create_module('chat', $record, $options);
1570         // Test admin user can see the complete hidden activity.
1571         $result = core_course_external::get_course_module($chat->cmid);
1572         $result = external_api::clean_returnvalue(core_course_external::get_course_module_returns(), $result);
1574         $this->assertCount(0, $result['warnings']);
1575         // Test we retrieve all the fields.
1576         $this->assertCount(22, $result['cm']);
1577         $this->assertEquals($record['name'], $result['cm']['name']);
1578         $this->assertEquals($options['idnumber'], $result['cm']['idnumber']);
1580         $student = $this->getDataGenerator()->create_user();
1581         $studentrole = $DB->get_record('role', array('shortname' => 'student'));
1583         self::getDataGenerator()->enrol_user($student->id,  $course->id, $studentrole->id);
1584         $this->setUser($student);
1586         // The user shouldn't be able to see the activity.
1587         try {
1588             core_course_external::get_course_module($chat->cmid);
1589             $this->fail('Exception expected due to invalid permissions.');
1590         } catch (moodle_exception $e) {
1591             $this->assertEquals('requireloginerror', $e->errorcode);
1592         }
1594         // Make module visible.
1595         set_coursemodule_visible($chat->cmid, 1);
1597         // Test student user.
1598         $result = core_course_external::get_course_module($chat->cmid);
1599         $result = external_api::clean_returnvalue(core_course_external::get_course_module_returns(), $result);
1601         $this->assertCount(0, $result['warnings']);
1602         // Test we retrieve only the few files we can see.
1603         $this->assertCount(11, $result['cm']);
1604         $this->assertEquals($chat->cmid, $result['cm']['id']);
1605         $this->assertEquals($course->id, $result['cm']['course']);
1606         $this->assertEquals('chat', $result['cm']['modname']);
1607         $this->assertEquals($chat->id, $result['cm']['instance']);
1609     }
1611     /**
1612      * Test get_course_module_by_instance
1613      */
1614     public function test_get_course_module_by_instance() {
1615         global $DB;
1617         $this->resetAfterTest(true);
1619         $this->setAdminUser();
1620         $course = self::getDataGenerator()->create_course();
1621         $record = array(
1622             'course' => $course->id,
1623             'name' => 'First Chat'
1624         );
1625         $options = array(
1626             'idnumber' => 'ABC',
1627             'visible' => 0
1628         );
1629         // Hidden activity.
1630         $chat = self::getDataGenerator()->create_module('chat', $record, $options);
1632         // Test admin user can see the complete hidden activity.
1633         $result = core_course_external::get_course_module_by_instance('chat', $chat->id);
1634         $result = external_api::clean_returnvalue(core_course_external::get_course_module_by_instance_returns(), $result);
1636         $this->assertCount(0, $result['warnings']);
1637         // Test we retrieve all the fields.
1638         $this->assertCount(22, $result['cm']);
1639         $this->assertEquals($record['name'], $result['cm']['name']);
1640         $this->assertEquals($options['idnumber'], $result['cm']['idnumber']);
1642         $student = $this->getDataGenerator()->create_user();
1643         $studentrole = $DB->get_record('role', array('shortname' => 'student'));
1645         self::getDataGenerator()->enrol_user($student->id,  $course->id, $studentrole->id);
1646         $this->setUser($student);
1648         // The user shouldn't be able to see the activity.
1649         try {
1650             core_course_external::get_course_module_by_instance('chat', $chat->id);
1651             $this->fail('Exception expected due to invalid permissions.');
1652         } catch (moodle_exception $e) {
1653             $this->assertEquals('requireloginerror', $e->errorcode);
1654         }
1656         // Make module visible.
1657         set_coursemodule_visible($chat->cmid, 1);
1659         // Test student user.
1660         $result = core_course_external::get_course_module_by_instance('chat', $chat->id);
1661         $result = external_api::clean_returnvalue(core_course_external::get_course_module_by_instance_returns(), $result);
1663         $this->assertCount(0, $result['warnings']);
1664         // Test we retrieve only the few files we can see.
1665         $this->assertCount(11, $result['cm']);
1666         $this->assertEquals($chat->cmid, $result['cm']['id']);
1667         $this->assertEquals($course->id, $result['cm']['course']);
1668         $this->assertEquals('chat', $result['cm']['modname']);
1669         $this->assertEquals($chat->id, $result['cm']['instance']);
1671         // Try with an invalid module name.
1672         try {
1673             core_course_external::get_course_module_by_instance('abc', $chat->id);
1674             $this->fail('Exception expected due to invalid module name.');
1675         } catch (dml_read_exception $e) {
1676             $this->assertEquals('dmlreadexception', $e->errorcode);
1677         }
1679     }