5fdbd41a9c8eead9dab79574d49c5e8b85250656
[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_external_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             $this->assertEquals($category['description'], $generatedcat->description);
222             $this->assertEquals($category['descriptionformat'], FORMAT_HTML);
223         }
225         // Check different params.
226         $categories = core_course_external::get_categories(array(
227             array('key' => 'id', 'value' => $category1->id),
228             array('key' => 'idnumber', 'value' => $category1->idnumber),
229             array('key' => 'visible', 'value' => 1)), 0);
231         // We need to execute the return values cleaning process to simulate the web service server.
232         $categories = external_api::clean_returnvalue(core_course_external::get_categories_returns(), $categories);
234         $this->assertEquals(1, count($categories));
236         // Retrieve categories from parent.
237         $categories = core_course_external::get_categories(array(
238             array('key' => 'parent', 'value' => $category3->id)), 1);
239         $this->assertEquals(2, count($categories));
241         // Retrieve all categories.
242         $categories = core_course_external::get_categories();
244         // We need to execute the return values cleaning process to simulate the web service server.
245         $categories = external_api::clean_returnvalue(core_course_external::get_categories_returns(), $categories);
247         $this->assertEquals($DB->count_records('course_categories'), count($categories));
249         // Call without required capability (it will fail cause of the search on idnumber).
250         $this->unassignUserCapability('moodle/category:manage', $context->id, $roleid);
251         $this->setExpectedException('moodle_exception');
252         $categories = core_course_external::get_categories(array(
253             array('key' => 'id', 'value' => $category1->id),
254             array('key' => 'idnumber', 'value' => $category1->idnumber),
255             array('key' => 'visible', 'value' => 1)), 0);
256     }
258     /**
259      * Test update_categories
260      */
261     public function test_update_categories() {
262         global $DB;
264         $this->resetAfterTest(true);
266         // Set the required capabilities by the external function
267         $contextid = context_system::instance()->id;
268         $roleid = $this->assignUserCapability('moodle/category:manage', $contextid);
270         // Create base categories.
271         $category1data['idnumber'] = 'idnumbercat1';
272         $category1data['name'] = 'Category 1 for PHPunit test';
273         $category1data['description'] = 'Category 1 description';
274         $category1data['descriptionformat'] = FORMAT_MOODLE;
275         $category1  = self::getDataGenerator()->create_category($category1data);
276         $category2  = self::getDataGenerator()->create_category(
277                 array('parent' => $category1->id));
278         $category3  = self::getDataGenerator()->create_category();
279         $category4  = self::getDataGenerator()->create_category(
280                 array('parent' => $category3->id));
281         $category5  = self::getDataGenerator()->create_category(
282                 array('parent' => $category4->id));
284         // We update all category1 attribut.
285         // Then we move cat4 and cat5 parent: cat3 => cat1
286         $categories = array(
287             array('id' => $category1->id,
288                 'name' => $category1->name . '_updated',
289                 'idnumber' => $category1->idnumber . '_updated',
290                 'description' => $category1->description . '_updated',
291                 'descriptionformat' => FORMAT_HTML,
292                 'theme' => $category1->theme),
293             array('id' => $category4->id, 'parent' => $category1->id));
295         core_course_external::update_categories($categories);
297         // Check the values were updated.
298         $dbcategories = $DB->get_records_select('course_categories',
299                 'id IN (' . $category1->id . ',' . $category2->id . ',' . $category2->id
300                 . ',' . $category3->id . ',' . $category4->id . ',' . $category5->id .')');
301         $this->assertEquals($category1->name . '_updated',
302                 $dbcategories[$category1->id]->name);
303         $this->assertEquals($category1->idnumber . '_updated',
304                 $dbcategories[$category1->id]->idnumber);
305         $this->assertEquals($category1->description . '_updated',
306                 $dbcategories[$category1->id]->description);
307         $this->assertEquals(FORMAT_HTML, $dbcategories[$category1->id]->descriptionformat);
309         // Check that category4 and category5 have been properly moved.
310         $this->assertEquals('/' . $category1->id . '/' . $category4->id,
311                 $dbcategories[$category4->id]->path);
312         $this->assertEquals('/' . $category1->id . '/' . $category4->id . '/' . $category5->id,
313                 $dbcategories[$category5->id]->path);
315         // Call without required capability.
316         $this->unassignUserCapability('moodle/category:manage', $contextid, $roleid);
317         $this->setExpectedException('required_capability_exception');
318         core_course_external::update_categories($categories);
319     }
321     /**
322      * Test create_courses
323      */
324     public function test_create_courses() {
325         global $DB;
327         $this->resetAfterTest(true);
329         // Enable course completion.
330         set_config('enablecompletion', 1);
332         // Set the required capabilities by the external function
333         $contextid = context_system::instance()->id;
334         $roleid = $this->assignUserCapability('moodle/course:create', $contextid);
335         $this->assignUserCapability('moodle/course:visibility', $contextid, $roleid);
337         $category  = self::getDataGenerator()->create_category();
339         // Create base categories.
340         $course1['fullname'] = 'Test course 1';
341         $course1['shortname'] = 'Testcourse1';
342         $course1['categoryid'] = $category->id;
343         $course2['fullname'] = 'Test course 2';
344         $course2['shortname'] = 'Testcourse2';
345         $course2['categoryid'] = $category->id;
346         $course2['idnumber'] = 'testcourse2idnumber';
347         $course2['summary'] = 'Description for course 2';
348         $course2['summaryformat'] = FORMAT_MOODLE;
349         $course2['format'] = 'weeks';
350         $course2['showgrades'] = 1;
351         $course2['newsitems'] = 3;
352         $course2['startdate'] = 1420092000; // 01/01/2015
353         $course2['numsections'] = 4;
354         $course2['maxbytes'] = 100000;
355         $course2['showreports'] = 1;
356         $course2['visible'] = 0;
357         $course2['hiddensections'] = 0;
358         $course2['groupmode'] = 0;
359         $course2['groupmodeforce'] = 0;
360         $course2['defaultgroupingid'] = 0;
361         $course2['enablecompletion'] = 1;
362         $course2['completionnotify'] = 1;
363         $course2['lang'] = 'en';
364         $course2['forcetheme'] = 'base';
365         $course3['fullname'] = 'Test course 3';
366         $course3['shortname'] = 'Testcourse3';
367         $course3['categoryid'] = $category->id;
368         $course3['format'] = 'topics';
369         $course3options = array('numsections' => 8,
370             'hiddensections' => 1,
371             'coursedisplay' => 1);
372         $course3['courseformatoptions'] = array();
373         foreach ($course3options as $key => $value) {
374             $course3['courseformatoptions'][] = array('name' => $key, 'value' => $value);
375         }
376         $courses = array($course1, $course2, $course3);
378         $createdcourses = core_course_external::create_courses($courses);
380         // We need to execute the return values cleaning process to simulate the web service server.
381         $createdcourses = external_api::clean_returnvalue(core_course_external::create_courses_returns(), $createdcourses);
383         // Check that right number of courses were created.
384         $this->assertEquals(3, count($createdcourses));
386         // Check that the courses were correctly created.
387         foreach ($createdcourses as $createdcourse) {
388             $courseinfo = course_get_format($createdcourse['id'])->get_course();
390             if ($createdcourse['shortname'] == $course2['shortname']) {
391                 $this->assertEquals($courseinfo->fullname, $course2['fullname']);
392                 $this->assertEquals($courseinfo->shortname, $course2['shortname']);
393                 $this->assertEquals($courseinfo->category, $course2['categoryid']);
394                 $this->assertEquals($courseinfo->idnumber, $course2['idnumber']);
395                 $this->assertEquals($courseinfo->summary, $course2['summary']);
396                 $this->assertEquals($courseinfo->summaryformat, $course2['summaryformat']);
397                 $this->assertEquals($courseinfo->format, $course2['format']);
398                 $this->assertEquals($courseinfo->showgrades, $course2['showgrades']);
399                 $this->assertEquals($courseinfo->newsitems, $course2['newsitems']);
400                 $this->assertEquals($courseinfo->startdate, $course2['startdate']);
401                 $this->assertEquals($courseinfo->numsections, $course2['numsections']);
402                 $this->assertEquals($courseinfo->maxbytes, $course2['maxbytes']);
403                 $this->assertEquals($courseinfo->showreports, $course2['showreports']);
404                 $this->assertEquals($courseinfo->visible, $course2['visible']);
405                 $this->assertEquals($courseinfo->hiddensections, $course2['hiddensections']);
406                 $this->assertEquals($courseinfo->groupmode, $course2['groupmode']);
407                 $this->assertEquals($courseinfo->groupmodeforce, $course2['groupmodeforce']);
408                 $this->assertEquals($courseinfo->defaultgroupingid, $course2['defaultgroupingid']);
409                 $this->assertEquals($courseinfo->completionnotify, $course2['completionnotify']);
410                 $this->assertEquals($courseinfo->lang, $course2['lang']);
412                 if (!empty($CFG->allowcoursethemes)) {
413                     $this->assertEquals($courseinfo->theme, $course2['forcetheme']);
414                 }
416                 // We enabled completion at the beginning of the test.
417                 $this->assertEquals($courseinfo->enablecompletion, $course2['enablecompletion']);
419             } else if ($createdcourse['shortname'] == $course1['shortname']) {
420                 $courseconfig = get_config('moodlecourse');
421                 $this->assertEquals($courseinfo->fullname, $course1['fullname']);
422                 $this->assertEquals($courseinfo->shortname, $course1['shortname']);
423                 $this->assertEquals($courseinfo->category, $course1['categoryid']);
424                 $this->assertEquals($courseinfo->summaryformat, FORMAT_HTML);
425                 $this->assertEquals($courseinfo->format, $courseconfig->format);
426                 $this->assertEquals($courseinfo->showgrades, $courseconfig->showgrades);
427                 $this->assertEquals($courseinfo->newsitems, $courseconfig->newsitems);
428                 $this->assertEquals($courseinfo->maxbytes, $courseconfig->maxbytes);
429                 $this->assertEquals($courseinfo->showreports, $courseconfig->showreports);
430                 $this->assertEquals($courseinfo->groupmode, $courseconfig->groupmode);
431                 $this->assertEquals($courseinfo->groupmodeforce, $courseconfig->groupmodeforce);
432                 $this->assertEquals($courseinfo->defaultgroupingid, 0);
433             } else if ($createdcourse['shortname'] == $course3['shortname']) {
434                 $this->assertEquals($courseinfo->fullname, $course3['fullname']);
435                 $this->assertEquals($courseinfo->shortname, $course3['shortname']);
436                 $this->assertEquals($courseinfo->category, $course3['categoryid']);
437                 $this->assertEquals($courseinfo->format, $course3['format']);
438                 $this->assertEquals($courseinfo->hiddensections, $course3options['hiddensections']);
439                 $this->assertEquals($courseinfo->numsections, $course3options['numsections']);
440                 $this->assertEquals($courseinfo->coursedisplay, $course3options['coursedisplay']);
441             } else {
442                 throw moodle_exception('Unexpected shortname');
443             }
444         }
446         // Call without required capability
447         $this->unassignUserCapability('moodle/course:create', $contextid, $roleid);
448         $this->setExpectedException('required_capability_exception');
449         $createdsubcats = core_course_external::create_courses($courses);
450     }
452     /**
453      * Test delete_courses
454      */
455     public function test_delete_courses() {
456         global $DB, $USER;
458         $this->resetAfterTest(true);
460         // Admin can delete a course.
461         $this->setAdminUser();
462         // Validate_context() will fail as the email is not set by $this->setAdminUser().
463         $USER->email = 'emailtopass@contextvalidation.me';
465         $course1  = self::getDataGenerator()->create_course();
466         $course2  = self::getDataGenerator()->create_course();
467         $course3  = self::getDataGenerator()->create_course();
469         // Delete courses.
470         core_course_external::delete_courses(array($course1->id, $course2->id));
472         // Check $course 1 and 2 are deleted.
473         $notdeletedcount = $DB->count_records_select('course',
474             'id IN ( ' . $course1->id . ',' . $course2->id . ')');
475         $this->assertEquals(0, $notdeletedcount);
477          // Fail when the user is not allow to access the course (enrolled) or is not admin.
478         $this->setGuestUser();
479         $this->setExpectedException('require_login_exception');
480         $createdsubcats = core_course_external::delete_courses(array($course3->id));
481     }
483     /**
484      * Test get_courses
485      */
486     public function test_get_courses () {
487         global $DB;
489         $this->resetAfterTest(true);
491         $generatedcourses = array();
492         $coursedata['idnumber'] = 'idnumbercourse1';
493         $coursedata['fullname'] = 'Course 1 for PHPunit test';
494         $coursedata['summary'] = 'Course 1 description';
495         $coursedata['summaryformat'] = FORMAT_MOODLE;
496         $course1  = self::getDataGenerator()->create_course($coursedata);
497         $generatedcourses[$course1->id] = $course1;
498         $course2  = self::getDataGenerator()->create_course();
499         $generatedcourses[$course2->id] = $course2;
500         $course3  = self::getDataGenerator()->create_course(array('format' => 'topics'));
501         $generatedcourses[$course3->id] = $course3;
503         // Set the required capabilities by the external function.
504         $context = context_system::instance();
505         $roleid = $this->assignUserCapability('moodle/course:view', $context->id);
506         $this->assignUserCapability('moodle/course:update',
507                 context_course::instance($course1->id)->id, $roleid);
508         $this->assignUserCapability('moodle/course:update',
509                 context_course::instance($course2->id)->id, $roleid);
510         $this->assignUserCapability('moodle/course:update',
511                 context_course::instance($course3->id)->id, $roleid);
513         $courses = core_course_external::get_courses(array('ids' =>
514             array($course1->id, $course2->id)));
516         // We need to execute the return values cleaning process to simulate the web service server.
517         $courses = external_api::clean_returnvalue(core_course_external::get_courses_returns(), $courses);
519         // Check we retrieve the good total number of categories.
520         $this->assertEquals(2, count($courses));
522         foreach ($courses as $course) {
523             $dbcourse = $generatedcourses[$course['id']];
524             $this->assertEquals($course['idnumber'], $dbcourse->idnumber);
525             $this->assertEquals($course['fullname'], $dbcourse->fullname);
526             $this->assertEquals($course['summary'], $dbcourse->summary);
527             $this->assertEquals($course['summaryformat'], FORMAT_HTML);
528             $this->assertEquals($course['shortname'], $dbcourse->shortname);
529             $this->assertEquals($course['categoryid'], $dbcourse->category);
530             $this->assertEquals($course['format'], $dbcourse->format);
531             $this->assertEquals($course['showgrades'], $dbcourse->showgrades);
532             $this->assertEquals($course['newsitems'], $dbcourse->newsitems);
533             $this->assertEquals($course['startdate'], $dbcourse->startdate);
534             $this->assertEquals($course['numsections'], $dbcourse->numsections);
535             $this->assertEquals($course['maxbytes'], $dbcourse->maxbytes);
536             $this->assertEquals($course['showreports'], $dbcourse->showreports);
537             $this->assertEquals($course['visible'], $dbcourse->visible);
538             $this->assertEquals($course['hiddensections'], $dbcourse->hiddensections);
539             $this->assertEquals($course['groupmode'], $dbcourse->groupmode);
540             $this->assertEquals($course['groupmodeforce'], $dbcourse->groupmodeforce);
541             $this->assertEquals($course['defaultgroupingid'], $dbcourse->defaultgroupingid);
542             $this->assertEquals($course['completionnotify'], $dbcourse->completionnotify);
543             $this->assertEquals($course['lang'], $dbcourse->lang);
544             $this->assertEquals($course['forcetheme'], $dbcourse->theme);
545             $this->assertEquals($course['enablecompletion'], $dbcourse->enablecompletion);
546             if ($dbcourse->format === 'topics') {
547                 $this->assertEquals($course['courseformatoptions'], array(
548                     array('name' => 'numsections', 'value' => $dbcourse->numsections),
549                     array('name' => 'hiddensections', 'value' => $dbcourse->hiddensections),
550                     array('name' => 'coursedisplay', 'value' => $dbcourse->coursedisplay),
551                 ));
552             }
553         }
555         // Get all courses in the DB
556         $courses = core_course_external::get_courses(array());
558         // We need to execute the return values cleaning process to simulate the web service server.
559         $courses = external_api::clean_returnvalue(core_course_external::get_courses_returns(), $courses);
561         $this->assertEquals($DB->count_records('course'), count($courses));
562     }
564     /**
565      * Test get_course_contents
566      */
567     public function test_get_course_contents() {
568         $this->resetAfterTest(true);
570         $course  = self::getDataGenerator()->create_course();
571         $forumdescription = 'This is the forum description';
572         $forum = $this->getDataGenerator()->create_module('forum',
573             array('course'=>$course->id, 'intro' => $forumdescription),
574             array('showdescription' => true));
575         $forumcm = get_coursemodule_from_id('forum', $forum->cmid);
576         $data = $this->getDataGenerator()->create_module('data', array('assessed'=>1, 'scale'=>100, 'course'=>$course->id));
577         $datacm = get_coursemodule_from_instance('page', $data->id);
578         $page = $this->getDataGenerator()->create_module('page', array('course'=>$course->id));
579         $pagecm = get_coursemodule_from_instance('page', $page->id);
580         $labeldescription = 'This is a very long label to test if more than 50 characters are returned.
581                 So bla bla bla bla <b>bold bold bold</b> bla bla bla bla.';
582         $label = $this->getDataGenerator()->create_module('label', array('course' => $course->id,
583             'intro' => $labeldescription));
584         $labelcm = get_coursemodule_from_instance('label', $label->id);
586         // Set the required capabilities by the external function.
587         $context = context_course::instance($course->id);
588         $roleid = $this->assignUserCapability('moodle/course:view', $context->id);
589         $this->assignUserCapability('moodle/course:update', $context->id, $roleid);
591         $sections = core_course_external::get_course_contents($course->id, array());
593         // We need to execute the return values cleaning process to simulate the web service server.
594         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
596         // Check that forum and label descriptions are correctly returned.
597         $firstsection = array_pop($sections);
598         $modinfo = get_fast_modinfo($course);
599         $testexecuted = 0;
600         foreach($firstsection['modules'] as $module) {
601             if ($module['id'] == $forumcm->id and $module['modname'] == 'forum') {
602                 $cm = $modinfo->cms[$forumcm->id];
603                 $formattedtext = format_text($cm->get_content(), FORMAT_HTML,
604                     array('noclean' => true, 'para' => false, 'filter' => false));
605                 $this->assertEquals($formattedtext, $module['description']);
606                 $testexecuted = $testexecuted + 1;
607             } else if ($module['id'] == $labelcm->id and $module['modname'] == 'label') {
608                 $cm = $modinfo->cms[$labelcm->id];
609                 $formattedtext = format_text($cm->get_content(), FORMAT_HTML,
610                     array('noclean' => true, 'para' => false, 'filter' => false));
611                 $this->assertEquals($formattedtext, $module['description']);
612                 $testexecuted = $testexecuted + 1;
613             }
614         }
615         $this->assertEquals(2, $testexecuted);
617         // Check that the only return section has the 4 created modules
618         $this->assertEquals(4, count($firstsection['modules']));
619     }
621     /**
622      * Test duplicate_course
623      */
624     public function test_duplicate_course() {
625         $this->resetAfterTest(true);
627         // Create one course with three modules.
628         $course  = self::getDataGenerator()->create_course();
629         $forum = $this->getDataGenerator()->create_module('forum', array('course'=>$course->id));
630         $forumcm = get_coursemodule_from_id('forum', $forum->cmid);
631         $forumcontext = context_module::instance($forum->cmid);
632         $data = $this->getDataGenerator()->create_module('data', array('assessed'=>1, 'scale'=>100, 'course'=>$course->id));
633         $datacontext = context_module::instance($data->cmid);
634         $datacm = get_coursemodule_from_instance('page', $data->id);
635         $page = $this->getDataGenerator()->create_module('page', array('course'=>$course->id));
636         $pagecontext = context_module::instance($page->cmid);
637         $pagecm = get_coursemodule_from_instance('page', $page->id);
639         // Set the required capabilities by the external function.
640         $coursecontext = context_course::instance($course->id);
641         $categorycontext = context_coursecat::instance($course->category);
642         $roleid = $this->assignUserCapability('moodle/course:create', $categorycontext->id);
643         $this->assignUserCapability('moodle/course:view', $categorycontext->id, $roleid);
644         $this->assignUserCapability('moodle/restore:restorecourse', $categorycontext->id, $roleid);
645         $this->assignUserCapability('moodle/backup:backupcourse', $coursecontext->id, $roleid);
646         $this->assignUserCapability('moodle/backup:configure', $coursecontext->id, $roleid);
647         // Optional capabilities to copy user data.
648         $this->assignUserCapability('moodle/backup:userinfo', $coursecontext->id, $roleid);
649         $this->assignUserCapability('moodle/restore:userinfo', $categorycontext->id, $roleid);
651         $newcourse['fullname'] = 'Course duplicate';
652         $newcourse['shortname'] = 'courseduplicate';
653         $newcourse['categoryid'] = $course->category;
654         $newcourse['visible'] = true;
655         $newcourse['options'][] = array('name' => 'users', 'value' => true);
657         $duplicate = core_course_external::duplicate_course($course->id, $newcourse['fullname'],
658                 $newcourse['shortname'], $newcourse['categoryid'], $newcourse['visible'], $newcourse['options']);
660         // We need to execute the return values cleaning process to simulate the web service server.
661         $duplicate = external_api::clean_returnvalue(core_course_external::duplicate_course_returns(), $duplicate);
663         // Check that the course has been duplicated.
664         $this->assertEquals($newcourse['shortname'], $duplicate['shortname']);
666         // Reset the timeouts.
667         set_time_limit(0);
668     }
670     /**
671      * Test update_courses
672      */
673     public function test_update_courses() {
674         global $DB, $CFG, $USER, $COURSE;
676         // Get current $COURSE to be able to restore it later (defaults to $SITE). We need this
677         // trick because we are both updating and getting (for testing) course information
678         // in the same request and core_course_external::update_courses()
679         // is overwriting $COURSE all over the time with OLD values, so later
680         // use of get_course() fetches those OLD values instead of the updated ones.
681         // See MDL-39723 for more info.
682         $origcourse = clone($COURSE);
684         $this->resetAfterTest(true);
686         // Set the required capabilities by the external function.
687         $contextid = context_system::instance()->id;
688         $roleid = $this->assignUserCapability('moodle/course:update', $contextid);
689         $this->assignUserCapability('moodle/course:changecategory', $contextid, $roleid);
690         $this->assignUserCapability('moodle/course:changefullname', $contextid, $roleid);
691         $this->assignUserCapability('moodle/course:changeshortname', $contextid, $roleid);
692         $this->assignUserCapability('moodle/course:changeidnumber', $contextid, $roleid);
693         $this->assignUserCapability('moodle/course:changesummary', $contextid, $roleid);
694         $this->assignUserCapability('moodle/course:visibility', $contextid, $roleid);
695         $this->assignUserCapability('moodle/course:viewhiddencourses', $contextid, $roleid);
697         // Create category and course.
698         $category1  = self::getDataGenerator()->create_category();
699         $category2  = self::getDataGenerator()->create_category();
700         $originalcourse1 = self::getDataGenerator()->create_course();
701         self::getDataGenerator()->enrol_user($USER->id, $originalcourse1->id, $roleid);
702         $originalcourse2 = self::getDataGenerator()->create_course();
703         self::getDataGenerator()->enrol_user($USER->id, $originalcourse2->id, $roleid);
705         // Course values to be updated.
706         $course1['id'] = $originalcourse1->id;
707         $course1['fullname'] = 'Updated test course 1';
708         $course1['shortname'] = 'Udestedtestcourse1';
709         $course1['categoryid'] = $category1->id;
710         $course2['id'] = $originalcourse2->id;
711         $course2['fullname'] = 'Updated test course 2';
712         $course2['shortname'] = 'Updestedtestcourse2';
713         $course2['categoryid'] = $category2->id;
714         $course2['idnumber'] = 'Updatedidnumber2';
715         $course2['summary'] = 'Updaated description for course 2';
716         $course2['summaryformat'] = FORMAT_HTML;
717         $course2['format'] = 'topics';
718         $course2['showgrades'] = 1;
719         $course2['newsitems'] = 3;
720         $course2['startdate'] = 1420092000; // 01/01/2015.
721         $course2['numsections'] = 4;
722         $course2['maxbytes'] = 100000;
723         $course2['showreports'] = 1;
724         $course2['visible'] = 0;
725         $course2['hiddensections'] = 0;
726         $course2['groupmode'] = 0;
727         $course2['groupmodeforce'] = 0;
728         $course2['defaultgroupingid'] = 0;
729         $course2['enablecompletion'] = 1;
730         $course2['lang'] = 'en';
731         $course2['forcetheme'] = 'base';
732         $courses = array($course1, $course2);
734         $updatedcoursewarnings = core_course_external::update_courses($courses);
735         $COURSE = $origcourse; // Restore $COURSE. Instead of using the OLD one set by the previous line.
737         // Check that right number of courses were created.
738         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
740         // Check that the courses were correctly created.
741         foreach ($courses as $course) {
742             $courseinfo = course_get_format($course['id'])->get_course();
743             if ($course['id'] == $course2['id']) {
744                 $this->assertEquals($course2['fullname'], $courseinfo->fullname);
745                 $this->assertEquals($course2['shortname'], $courseinfo->shortname);
746                 $this->assertEquals($course2['categoryid'], $courseinfo->category);
747                 $this->assertEquals($course2['idnumber'], $courseinfo->idnumber);
748                 $this->assertEquals($course2['summary'], $courseinfo->summary);
749                 $this->assertEquals($course2['summaryformat'], $courseinfo->summaryformat);
750                 $this->assertEquals($course2['format'], $courseinfo->format);
751                 $this->assertEquals($course2['showgrades'], $courseinfo->showgrades);
752                 $this->assertEquals($course2['newsitems'], $courseinfo->newsitems);
753                 $this->assertEquals($course2['startdate'], $courseinfo->startdate);
754                 $this->assertEquals($course2['numsections'], $courseinfo->numsections);
755                 $this->assertEquals($course2['maxbytes'], $courseinfo->maxbytes);
756                 $this->assertEquals($course2['showreports'], $courseinfo->showreports);
757                 $this->assertEquals($course2['visible'], $courseinfo->visible);
758                 $this->assertEquals($course2['hiddensections'], $courseinfo->hiddensections);
759                 $this->assertEquals($course2['groupmode'], $courseinfo->groupmode);
760                 $this->assertEquals($course2['groupmodeforce'], $courseinfo->groupmodeforce);
761                 $this->assertEquals($course2['defaultgroupingid'], $courseinfo->defaultgroupingid);
762                 $this->assertEquals($course2['lang'], $courseinfo->lang);
764                 if (!empty($CFG->allowcoursethemes)) {
765                     $this->assertEquals($course2['forcetheme'], $courseinfo->theme);
766                 }
768                 if (completion_info::is_enabled_for_site()) {
769                     $this->assertEquals($course2['enabledcompletion'], $courseinfo->enablecompletion);
770                 }
771             } else if ($course['id'] == $course1['id']) {
772                 $this->assertEquals($course1['fullname'], $courseinfo->fullname);
773                 $this->assertEquals($course1['shortname'], $courseinfo->shortname);
774                 $this->assertEquals($course1['categoryid'], $courseinfo->category);
775                 $this->assertEquals(FORMAT_MOODLE, $courseinfo->summaryformat);
776                 $this->assertEquals('topics', $courseinfo->format);
777                 $this->assertEquals(5, $courseinfo->numsections);
778                 $this->assertEquals(0, $courseinfo->newsitems);
779                 $this->assertEquals(FORMAT_MOODLE, $courseinfo->summaryformat);
780             } else {
781                 throw moodle_exception('Unexpected shortname');
782             }
783         }
785         $courses = array($course1);
786         // Try update course without update capability.
787         $user = self::getDataGenerator()->create_user();
788         $this->setUser($user);
789         $this->unassignUserCapability('moodle/course:update', $contextid, $roleid);
790         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
791         $updatedcoursewarnings = core_course_external::update_courses($courses);
792         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
794         // Try update course category without capability.
795         $this->assignUserCapability('moodle/course:update', $contextid, $roleid);
796         $this->unassignUserCapability('moodle/course:changecategory', $contextid, $roleid);
797         $user = self::getDataGenerator()->create_user();
798         $this->setUser($user);
799         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
800         $course1['categoryid'] = $category2->id;
801         $courses = array($course1);
802         $updatedcoursewarnings = core_course_external::update_courses($courses);
803         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
805         // Try update course fullname without capability.
806         $this->assignUserCapability('moodle/course:changecategory', $contextid, $roleid);
807         $this->unassignUserCapability('moodle/course:changefullname', $contextid, $roleid);
808         $user = self::getDataGenerator()->create_user();
809         $this->setUser($user);
810         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
811         $updatedcoursewarnings = core_course_external::update_courses($courses);
812         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
813         $course1['fullname'] = 'Testing fullname without permission';
814         $courses = array($course1);
815         $updatedcoursewarnings = core_course_external::update_courses($courses);
816         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
818         // Try update course shortname without capability.
819         $this->assignUserCapability('moodle/course:changefullname', $contextid, $roleid);
820         $this->unassignUserCapability('moodle/course:changeshortname', $contextid, $roleid);
821         $user = self::getDataGenerator()->create_user();
822         $this->setUser($user);
823         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
824         $updatedcoursewarnings = core_course_external::update_courses($courses);
825         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
826         $course1['shortname'] = 'Testing shortname without permission';
827         $courses = array($course1);
828         $updatedcoursewarnings = core_course_external::update_courses($courses);
829         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
831         // Try update course idnumber without capability.
832         $this->assignUserCapability('moodle/course:changeshortname', $contextid, $roleid);
833         $this->unassignUserCapability('moodle/course:changeidnumber', $contextid, $roleid);
834         $user = self::getDataGenerator()->create_user();
835         $this->setUser($user);
836         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
837         $updatedcoursewarnings = core_course_external::update_courses($courses);
838         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
839         $course1['idnumber'] = 'NEWIDNUMBER';
840         $courses = array($course1);
841         $updatedcoursewarnings = core_course_external::update_courses($courses);
842         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
844         // Try update course summary without capability.
845         $this->assignUserCapability('moodle/course:changeidnumber', $contextid, $roleid);
846         $this->unassignUserCapability('moodle/course:changesummary', $contextid, $roleid);
847         $user = self::getDataGenerator()->create_user();
848         $this->setUser($user);
849         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
850         $updatedcoursewarnings = core_course_external::update_courses($courses);
851         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
852         $course1['summary'] = 'New summary';
853         $courses = array($course1);
854         $updatedcoursewarnings = core_course_external::update_courses($courses);
855         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
857         // Try update course with invalid summary format.
858         $this->assignUserCapability('moodle/course:changesummary', $contextid, $roleid);
859         $user = self::getDataGenerator()->create_user();
860         $this->setUser($user);
861         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
862         $updatedcoursewarnings = core_course_external::update_courses($courses);
863         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
864         $course1['summaryformat'] = 10;
865         $courses = array($course1);
866         $updatedcoursewarnings = core_course_external::update_courses($courses);
867         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
869         // Try update course visibility without capability.
870         $this->unassignUserCapability('moodle/course:visibility', $contextid, $roleid);
871         $user = self::getDataGenerator()->create_user();
872         $this->setUser($user);
873         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
874         $course1['summaryformat'] = FORMAT_MOODLE;
875         $courses = array($course1);
876         $updatedcoursewarnings = core_course_external::update_courses($courses);
877         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
878         $course1['visible'] = 0;
879         $courses = array($course1);
880         $updatedcoursewarnings = core_course_external::update_courses($courses);
881         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
882     }
884     /**
885      * Test delete course_module.
886      */
887     public function test_delete_modules() {
888         global $DB;
890         // Ensure we reset the data after this test.
891         $this->resetAfterTest(true);
893         // Create a user.
894         $user = self::getDataGenerator()->create_user();
896         // Set the tests to run as the user.
897         self::setUser($user);
899         // Create a course to add the modules.
900         $course = self::getDataGenerator()->create_course();
902         // Create two test modules.
903         $record = new stdClass();
904         $record->course = $course->id;
905         $module1 = self::getDataGenerator()->create_module('forum', $record);
906         $module2 = self::getDataGenerator()->create_module('assignment', $record);
908         // Check the forum was correctly created.
909         $this->assertEquals(1, $DB->count_records('forum', array('id' => $module1->id)));
911         // Check the assignment was correctly created.
912         $this->assertEquals(1, $DB->count_records('assignment', array('id' => $module2->id)));
914         // Check data exists in the course modules table.
915         $this->assertEquals(2, $DB->count_records_select('course_modules', 'id = :module1 OR id = :module2',
916                 array('module1' => $module1->cmid, 'module2' => $module2->cmid)));
918         // Enrol the user in the course.
919         $enrol = enrol_get_plugin('manual');
920         $enrolinstances = enrol_get_instances($course->id, true);
921         foreach ($enrolinstances as $courseenrolinstance) {
922             if ($courseenrolinstance->enrol == "manual") {
923                 $instance = $courseenrolinstance;
924                 break;
925             }
926         }
927         $enrol->enrol_user($instance, $user->id);
929         // Assign capabilities to delete module 1.
930         $modcontext = context_module::instance($module1->cmid);
931         $this->assignUserCapability('moodle/course:manageactivities', $modcontext->id);
933         // Assign capabilities to delete module 2.
934         $modcontext = context_module::instance($module2->cmid);
935         $newrole = create_role('Role 2', 'role2', 'Role 2 description');
936         $this->assignUserCapability('moodle/course:manageactivities', $modcontext->id, $newrole);
938         // Deleting these module instances.
939         core_course_external::delete_modules(array($module1->cmid, $module2->cmid));
941         // Check the forum was deleted.
942         $this->assertEquals(0, $DB->count_records('forum', array('id' => $module1->id)));
944         // Check the assignment was deleted.
945         $this->assertEquals(0, $DB->count_records('assignment', array('id' => $module2->id)));
947         // Check we retrieve no data in the course modules table.
948         $this->assertEquals(0, $DB->count_records_select('course_modules', 'id = :module1 OR id = :module2',
949                 array('module1' => $module1->cmid, 'module2' => $module2->cmid)));
951         // Call with non-existent course module id and ensure exception thrown.
952         try {
953             core_course_external::delete_modules(array('1337'));
954             $this->fail('Exception expected due to missing course module.');
955         } catch (dml_missing_record_exception $e) {
956             $this->assertEquals('invalidrecord', $e->errorcode);
957         }
959         // Create two modules.
960         $module1 = self::getDataGenerator()->create_module('forum', $record);
961         $module2 = self::getDataGenerator()->create_module('assignment', $record);
963         // Since these modules were recreated the user will not have capabilities
964         // to delete them, ensure exception is thrown if they try.
965         try {
966             core_course_external::delete_modules(array($module1->cmid, $module2->cmid));
967             $this->fail('Exception expected due to missing capability.');
968         } catch (moodle_exception $e) {
969             $this->assertEquals('nopermissions', $e->errorcode);
970         }
972         // Unenrol user from the course.
973         $enrol->unenrol_user($instance, $user->id);
975         // Try and delete modules from the course the user was unenrolled in, make sure exception thrown.
976         try {
977             core_course_external::delete_modules(array($module1->cmid, $module2->cmid));
978             $this->fail('Exception expected due to being unenrolled from the course.');
979         } catch (moodle_exception $e) {
980             $this->assertEquals('requireloginerror', $e->errorcode);
981         }
982     }