afd8ca99fe6a054f7855f720bebb28cca59a3dfc
[moodle.git] / course / tests / courselib_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  * Course related unit tests
19  *
20  * @package    core
21  * @category   phpunit
22  * @copyright  2012 Petr Skoda {@link http://skodak.org}
23  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24  */
26 defined('MOODLE_INTERNAL') || die();
28 global $CFG;
29 require_once($CFG->dirroot.'/course/lib.php');
31 class courselib_testcase extends advanced_testcase {
33     /**
34      * Set forum specific test values for calling create_module().
35      *
36      * @param object $moduleinfo - the moduleinfo to add some specific values - passed in reference.
37      */
38     private function forum_create_set_values(&$moduleinfo) {
39         // Completion specific to forum - optional.
40         $moduleinfo->completionposts = 3;
41         $moduleinfo->completiondiscussions = 1;
42         $moduleinfo->completionreplies = 2;
44         // Specific values to the Forum module.
45         $moduleinfo->forcesubscribe = FORUM_INITIALSUBSCRIBE;
46         $moduleinfo->type = 'single';
47         $moduleinfo->trackingtype = FORUM_TRACKING_ON;
48         $moduleinfo->maxbytes = 10240;
49         $moduleinfo->maxattachments = 2;
51         // Post threshold for blocking - specific to forum.
52         $moduleinfo->blockperiod = 60*60*24;
53         $moduleinfo->blockafter = 10;
54         $moduleinfo->warnafter = 5;
55     }
57     /**
58      * Execute test asserts on the saved DB data by create_module($forum).
59      *
60      * @param object $moduleinfo - the specific forum values that were used to create a forum.
61      * @param object $dbmodinstance - the DB values of the created forum.
62      */
63     private function forum_create_run_asserts($moduleinfo, $dbmodinstance) {
64         // Compare values specific to forums.
65         $this->assertEquals($moduleinfo->forcesubscribe, $dbmodinstance->forcesubscribe);
66         $this->assertEquals($moduleinfo->type, $dbmodinstance->type);
67         $this->assertEquals($moduleinfo->assessed, $dbmodinstance->assessed);
68         $this->assertEquals($moduleinfo->completionposts, $dbmodinstance->completionposts);
69         $this->assertEquals($moduleinfo->completiondiscussions, $dbmodinstance->completiondiscussions);
70         $this->assertEquals($moduleinfo->completionreplies, $dbmodinstance->completionreplies);
71         $this->assertEquals($moduleinfo->scale, $dbmodinstance->scale);
72         $this->assertEquals($moduleinfo->assesstimestart, $dbmodinstance->assesstimestart);
73         $this->assertEquals($moduleinfo->assesstimefinish, $dbmodinstance->assesstimefinish);
74         $this->assertEquals($moduleinfo->rsstype, $dbmodinstance->rsstype);
75         $this->assertEquals($moduleinfo->rssarticles, $dbmodinstance->rssarticles);
76         $this->assertEquals($moduleinfo->trackingtype, $dbmodinstance->trackingtype);
77         $this->assertEquals($moduleinfo->maxbytes, $dbmodinstance->maxbytes);
78         $this->assertEquals($moduleinfo->maxattachments, $dbmodinstance->maxattachments);
79         $this->assertEquals($moduleinfo->blockperiod, $dbmodinstance->blockperiod);
80         $this->assertEquals($moduleinfo->blockafter, $dbmodinstance->blockafter);
81         $this->assertEquals($moduleinfo->warnafter, $dbmodinstance->warnafter);
82     }
84     /**
85      * Set assign module specific test values for calling create_module().
86      *
87      * @param object $moduleinfo - the moduleinfo to add some specific values - passed in reference.
88      */
89     private function assign_create_set_values(&$moduleinfo) {
90         // Specific values to the Assign module.
91         $moduleinfo->alwaysshowdescription = true;
92         $moduleinfo->submissiondrafts = true;
93         $moduleinfo->requiresubmissionstatement = true;
94         $moduleinfo->sendnotifications = true;
95         $moduleinfo->sendlatenotifications = true;
96         $moduleinfo->duedate = time() + (7 * 24 * 3600);
97         $moduleinfo->cutoffdate = time() + (7 * 24 * 3600);
98         $moduleinfo->allowsubmissionsfromdate = time();
99         $moduleinfo->teamsubmission = true;
100         $moduleinfo->requireallteammemberssubmit = true;
101         $moduleinfo->teamsubmissiongroupingid = true;
102         $moduleinfo->blindmarking = true;
103         $moduleinfo->assignsubmission_onlinetext_enabled = true;
104         $moduleinfo->assignsubmission_file_enabled = true;
105         $moduleinfo->assignsubmission_file_maxfiles = 1;
106         $moduleinfo->assignsubmission_file_maxsizebytes = 1000000;
107         $moduleinfo->assignsubmission_comments_enabled = true;
108         $moduleinfo->assignfeedback_comments_enabled = true;
109         $moduleinfo->assignfeedback_offline_enabled = true;
110         $moduleinfo->assignfeedback_file_enabled = true;
112         // Advanced grading.
113         $gradingmethods = grading_manager::available_methods();
114         $moduleinfo->advancedgradingmethod_submissions = current(array_keys($gradingmethods));
115     }
117     /**
118      * Execute test asserts on the saved DB data by create_module($assign).
119      *
120      * @param object $moduleinfo - the specific assign module values that were used to create an assign module.
121      * @param object $dbmodinstance - the DB values of the created assign module.
122      */
123     private function assign_create_run_asserts($moduleinfo, $dbmodinstance) {
124         global $DB;
126         $this->assertEquals($moduleinfo->alwaysshowdescription, $dbmodinstance->alwaysshowdescription);
127         $this->assertEquals($moduleinfo->submissiondrafts, $dbmodinstance->submissiondrafts);
128         $this->assertEquals($moduleinfo->requiresubmissionstatement, $dbmodinstance->requiresubmissionstatement);
129         $this->assertEquals($moduleinfo->sendnotifications, $dbmodinstance->sendnotifications);
130         $this->assertEquals($moduleinfo->duedate, $dbmodinstance->duedate);
131         $this->assertEquals($moduleinfo->cutoffdate, $dbmodinstance->cutoffdate);
132         $this->assertEquals($moduleinfo->allowsubmissionsfromdate, $dbmodinstance->allowsubmissionsfromdate);
133         $this->assertEquals($moduleinfo->teamsubmission, $dbmodinstance->teamsubmission);
134         $this->assertEquals($moduleinfo->requireallteammemberssubmit, $dbmodinstance->requireallteammemberssubmit);
135         $this->assertEquals($moduleinfo->teamsubmissiongroupingid, $dbmodinstance->teamsubmissiongroupingid);
136         $this->assertEquals($moduleinfo->blindmarking, $dbmodinstance->blindmarking);
137         // The goal not being to fully test assign_add_instance() we'll stop here for the assign tests - to avoid too many DB queries.
139         // Advanced grading.
140         $contextmodule = context_module::instance($dbmodinstance->id);
141         $advancedgradingmethod = $DB->get_record('grading_areas',
142             array('contextid' => $contextmodule->id,
143                 'activemethod' => $moduleinfo->advancedgradingmethod_submissions));
144         $this->assertEquals($moduleinfo->advancedgradingmethod_submissions, $advancedgradingmethod);
145     }
147     /**
148      * Run some asserts test for a specific module for the function create_module().
149      *
150      * The function has been created (and is called) for $this->test_create_module().
151      * Note that the call to MODULE_create_set_values and MODULE_create_run_asserts are done after the common set values/run asserts.
152      * So if you want, you can overwrite the default values/asserts in the respective functions.
153      * @param string $modulename Name of the module ('forum', 'assign', 'book'...).
154      */
155     private function create_specific_module_test($modulename) {
156         global $DB, $CFG;
158         $this->resetAfterTest(true);
160         $this->setAdminUser();
162         // Warnings: you'll need to change this line if ever you come to test a module not following Moodle standard.
163         require_once($CFG->dirroot.'/mod/'. $modulename .'/lib.php');
165         // Enable avaibility.
166         // If not enabled all conditional fields will be ignored.
167         set_config('enableavailability', 1);
169         // Enable course completion.
170         // If not enabled all completion settings will be ignored.
171         set_config('enablecompletion', COMPLETION_ENABLED);
173         // Enable forum RSS feeds.
174         set_config('enablerssfeeds', 1);
175         set_config('forum_enablerssfeeds', 1);
177         $course = $this->getDataGenerator()->create_course(array('numsections'=>1, 'enablecompletion' => COMPLETION_ENABLED),
178            array('createsections'=>true));
180         $grouping = $this->getDataGenerator()->create_grouping(array('courseid' => $course->id));
182         // Create assign module instance for test.
183         $generator = $this->getDataGenerator()->get_plugin_generator('mod_assign');
184         $params['course'] = $course->id;
185         $instance = $generator->create_instance($params);
186         $assigncm = get_coursemodule_from_instance('assign', $instance->id);
188         // Module test values.
189         $moduleinfo = new stdClass();
191         // Always mandatory generic values to any module.
192         $moduleinfo->modulename = $modulename;
193         $moduleinfo->section = 1; // This is the section number in the course. Not the section id in the database.
194         $moduleinfo->course = $course->id;
195         $moduleinfo->groupingid = $grouping->id;
196         $moduleinfo->groupmembersonly = 0;
197         $moduleinfo->visible = true;
199         // Sometimes optional generic values for some modules.
200         $moduleinfo->name = 'My test module';
201         $moduleinfo->showdescription = 1; // standard boolean
202         require_once($CFG->libdir . '/gradelib.php');
203         $gradecats = grade_get_categories_menu($moduleinfo->course, false);
204         $gradecatid = current(array_keys($gradecats)); // Retrieve the first key of $gradecats
205         $moduleinfo->gradecat = $gradecatid;
206         $moduleinfo->groupmode = VISIBLEGROUPS;
207         $moduleinfo->cmidnumber = 'idnumber_XXX';
209         // Completion common to all module.
210         $moduleinfo->completion = COMPLETION_TRACKING_AUTOMATIC;
211         $moduleinfo->completionview = COMPLETION_VIEW_REQUIRED;
212         $moduleinfo->completiongradeitemnumber = 1;
213         $moduleinfo->completionexpected = time() + (7 * 24 * 3600);
215         // Conditional activity.
216         $moduleinfo->availablefrom = time();
217         $moduleinfo->availableuntil = time() + (7 * 24 * 3600);
218         $moduleinfo->showavailability = CONDITION_STUDENTVIEW_SHOW;
219         $coursegradeitem = grade_item::fetch_course_item($moduleinfo->course); //the activity will become available only when the user reach some grade into the course itself.
220         $moduleinfo->conditiongradegroup = array(array('conditiongradeitemid' => $coursegradeitem->id, 'conditiongrademin' => 10, 'conditiongrademax' => 80));
221         $moduleinfo->conditionfieldgroup = array(array('conditionfield' => 'email', 'conditionfieldoperator' => OP_CONTAINS, 'conditionfieldvalue' => '@'));
222         $moduleinfo->conditioncompletiongroup = array(array('conditionsourcecmid' => $assigncm->id, 'conditionrequiredcompletion' => COMPLETION_COMPLETE)); // "conditionsourcecmid == 0" => none
224         // Grading and Advanced grading.
225         require_once($CFG->dirroot . '/rating/lib.php');
226         $moduleinfo->assessed = RATING_AGGREGATE_AVERAGE;
227         $moduleinfo->scale = 10; // Note: it could be minus (for specific course scale). It is a signed number.
228         $moduleinfo->assesstimestart = time();
229         $moduleinfo->assesstimefinish = time() + (7 * 24 * 3600);
231         // RSS.
232         $moduleinfo->rsstype = 2;
233         $moduleinfo->rssarticles = 10;
235         // Optional intro editor (depends of module).
236         $draftid_editor = 0;
237         file_prepare_draft_area($draftid_editor, null, null, null, null);
238         $moduleinfo->introeditor = array('text' => 'This is a module', 'format' => FORMAT_HTML, 'itemid' => $draftid_editor);
240         // Following is the advanced grading method area called 'submissions' for the 'assign' module.
241         if (plugin_supports('mod', $modulename, FEATURE_GRADE_HAS_GRADE, false) && !plugin_supports('mod', $modulename, FEATURE_RATE, false)) {
242             $moduleinfo->grade = 100;
243         }
245         // Plagiarism form values.
246         // No plagiarism plugin installed by default. Use this space to make your own test.
248         // Values specific to the module.
249         $modulesetvalues = $modulename.'_create_set_values';
250         $this->$modulesetvalues($moduleinfo);
252         // Create the module.
253         $result = create_module($moduleinfo);
255         // Retrieve the module info.
256         $dbmodinstance = $DB->get_record($moduleinfo->modulename, array('id' => $result->instance));
257         $dbcm = get_coursemodule_from_instance($moduleinfo->modulename, $result->instance);
258         // We passed the course section number to create_courses but $dbcm contain the section id.
259         // We need to retrieve the db course section number.
260         $section = $DB->get_record('course_sections', array('course' => $dbcm->course, 'id' => $dbcm->section));
261         // Retrieve the grade item.
262         $gradeitem = $DB->get_record('grade_items', array('courseid' => $moduleinfo->course,
263             'iteminstance' => $dbmodinstance->id, 'itemmodule' => $moduleinfo->modulename));
265         // Compare the values common to all module instances.
266         $this->assertEquals($moduleinfo->modulename, $dbcm->modname);
267         $this->assertEquals($moduleinfo->section, $section->section);
268         $this->assertEquals($moduleinfo->course, $dbcm->course);
269         $this->assertEquals($moduleinfo->groupingid, $dbcm->groupingid);
270         $this->assertEquals($moduleinfo->groupmembersonly, $dbcm->groupmembersonly);
271         $this->assertEquals($moduleinfo->visible, $dbcm->visible);
272         $this->assertEquals($moduleinfo->completion, $dbcm->completion);
273         $this->assertEquals($moduleinfo->completionview, $dbcm->completionview);
274         $this->assertEquals($moduleinfo->completiongradeitemnumber, $dbcm->completiongradeitemnumber);
275         $this->assertEquals($moduleinfo->completionexpected, $dbcm->completionexpected);
276         $this->assertEquals($moduleinfo->availablefrom, $dbcm->availablefrom);
277         $this->assertEquals($moduleinfo->availableuntil, $dbcm->availableuntil);
278         $this->assertEquals($moduleinfo->showavailability, $dbcm->showavailability);
279         $this->assertEquals($moduleinfo->showdescription, $dbcm->showdescription);
280         $this->assertEquals($moduleinfo->groupmode, $dbcm->groupmode);
281         $this->assertEquals($moduleinfo->cmidnumber, $dbcm->idnumber);
282         $this->assertEquals($moduleinfo->gradecat, $gradeitem->categoryid);
284         // Optional grade testing.
285         if (plugin_supports('mod', $modulename, FEATURE_GRADE_HAS_GRADE, false) && !plugin_supports('mod', $modulename, FEATURE_RATE, false)) {
286             $this->assertEquals($moduleinfo->grade, $dbmodinstance->grade);
287         }
289         // Some optional (but quite common) to some module.
290         $this->assertEquals($moduleinfo->name, $dbmodinstance->name);
291         $this->assertEquals($moduleinfo->intro, $dbmodinstance->intro);
292         $this->assertEquals($moduleinfo->introformat, $dbmodinstance->introformat);
294         // Common values when conditional activity is enabled.
295         foreach ($moduleinfo->conditionfieldgroup as $fieldgroup) {
296             $isfieldgroupsaved = $DB->count_records('course_modules_avail_fields', array('coursemoduleid' => $dbcm->id,
297                 'userfield' => $fieldgroup['conditionfield'], 'operator' => $fieldgroup['conditionfieldoperator'],
298                 'value' => $fieldgroup['conditionfieldvalue']));
299             $this->assertEquals(1, $isfieldgroupsaved);
300         }
301         foreach ($moduleinfo->conditiongradegroup as $gradegroup) {
302             $isgradegroupsaved = $DB->count_records('course_modules_availability', array('coursemoduleid' => $dbcm->id,
303                 'grademin' => $gradegroup['conditiongrademin'], 'grademax' => $gradegroup['conditiongrademax'],
304                 'gradeitemid' => $gradegroup['conditiongradeitemid']));
305             $this->assertEquals(1, $isgradegroupsaved);
306         }
307         foreach ($moduleinfo->conditioncompletiongroup as $completiongroup) {
308             $iscompletiongroupsaved = $DB->count_records('course_modules_availability', array('coursemoduleid' => $dbcm->id,
309                 'sourcecmid' => $completiongroup['conditionsourcecmid'], 'requiredcompletion' => $completiongroup['conditionrequiredcompletion']));
310             $this->assertEquals(1, $iscompletiongroupsaved);
311         }
313         // Test specific to the module.
314         $modulerunasserts = $modulename.'_create_run_asserts';
315         $this->$modulerunasserts($moduleinfo, $dbmodinstance);
316     }
318     /**
319      * Test create_module() for multiple modules defined in the $modules array (first declaration of the function).
320      */
321     public function test_create_module() {
322         // Add the module name you want to test here.
323         // Create the match MODULENAME_create_set_values() and MODULENAME_create_run_asserts().
324         $modules = array('forum', 'assign');
325         // Run all tests.
326         foreach ($modules as $modulename) {
327             $this->create_specific_module_test($modulename);
328         }
329     }
331     /**
332      * Test update_module() for multiple modules defined in the $modules array (first declaration of the function).
333      */
334     public function test_update_module() {
335         // Add the module name you want to test here.
336         // Create the match MODULENAME_update_set_values() and MODULENAME_update_run_asserts().
337         $modules = array('forum');
338         // Run all tests.
339         foreach ($modules as $modulename) {
340             $this->update_specific_module_test($modulename);
341         }
342     }
344     /**
345      * Set forum specific test values for calling update_module().
346      *
347      * @param object $moduleinfo - the moduleinfo to add some specific values - passed in reference.
348      */
349     private function forum_update_set_values(&$moduleinfo) {
350         // Completion specific to forum - optional.
351         $moduleinfo->completionposts = 3;
352         $moduleinfo->completiondiscussions = 1;
353         $moduleinfo->completionreplies = 2;
355         // Specific values to the Forum module.
356         $moduleinfo->forcesubscribe = FORUM_INITIALSUBSCRIBE;
357         $moduleinfo->type = 'single';
358         $moduleinfo->trackingtype = FORUM_TRACKING_ON;
359         $moduleinfo->maxbytes = 10240;
360         $moduleinfo->maxattachments = 2;
362         // Post threshold for blocking - specific to forum.
363         $moduleinfo->blockperiod = 60*60*24;
364         $moduleinfo->blockafter = 10;
365         $moduleinfo->warnafter = 5;
366     }
368     /**
369      * Execute test asserts on the saved DB data by update_module($forum).
370      *
371      * @param object $moduleinfo - the specific forum values that were used to update a forum.
372      * @param object $dbmodinstance - the DB values of the updated forum.
373      */
374     private function forum_update_run_asserts($moduleinfo, $dbmodinstance) {
375         // Compare values specific to forums.
376         $this->assertEquals($moduleinfo->forcesubscribe, $dbmodinstance->forcesubscribe);
377         $this->assertEquals($moduleinfo->type, $dbmodinstance->type);
378         $this->assertEquals($moduleinfo->assessed, $dbmodinstance->assessed);
379         $this->assertEquals($moduleinfo->completionposts, $dbmodinstance->completionposts);
380         $this->assertEquals($moduleinfo->completiondiscussions, $dbmodinstance->completiondiscussions);
381         $this->assertEquals($moduleinfo->completionreplies, $dbmodinstance->completionreplies);
382         $this->assertEquals($moduleinfo->scale, $dbmodinstance->scale);
383         $this->assertEquals($moduleinfo->assesstimestart, $dbmodinstance->assesstimestart);
384         $this->assertEquals($moduleinfo->assesstimefinish, $dbmodinstance->assesstimefinish);
385         $this->assertEquals($moduleinfo->rsstype, $dbmodinstance->rsstype);
386         $this->assertEquals($moduleinfo->rssarticles, $dbmodinstance->rssarticles);
387         $this->assertEquals($moduleinfo->trackingtype, $dbmodinstance->trackingtype);
388         $this->assertEquals($moduleinfo->maxbytes, $dbmodinstance->maxbytes);
389         $this->assertEquals($moduleinfo->maxattachments, $dbmodinstance->maxattachments);
390         $this->assertEquals($moduleinfo->blockperiod, $dbmodinstance->blockperiod);
391         $this->assertEquals($moduleinfo->blockafter, $dbmodinstance->blockafter);
392         $this->assertEquals($moduleinfo->warnafter, $dbmodinstance->warnafter);
393     }
397     /**
398      * Test a specific type of module.
399      *
400      * @param string $modulename - the module name to test
401      */
402     private function update_specific_module_test($modulename) {
403         global $DB, $CFG;
405         $this->resetAfterTest(true);
407         $this->setAdminUser();
409         // Warnings: you'll need to change this line if ever you come to test a module not following Moodle standard.
410         require_once($CFG->dirroot.'/mod/'. $modulename .'/lib.php');
412         // Enable avaibility.
413         // If not enabled all conditional fields will be ignored.
414         set_config('enableavailability', 1);
416         // Enable course completion.
417         // If not enabled all completion settings will be ignored.
418         set_config('enablecompletion', COMPLETION_ENABLED);
420         // Enable forum RSS feeds.
421         set_config('enablerssfeeds', 1);
422         set_config('forum_enablerssfeeds', 1);
424         $course = $this->getDataGenerator()->create_course(array('numsections'=>1, 'enablecompletion' => COMPLETION_ENABLED),
425            array('createsections'=>true));
427         $grouping = $this->getDataGenerator()->create_grouping(array('courseid' => $course->id));
429         // Create assign module instance for testing gradeitem.
430         $generator = $this->getDataGenerator()->get_plugin_generator('mod_assign');
431         $params['course'] = $course->id;
432         $instance = $generator->create_instance($params);
433         $assigncm = get_coursemodule_from_instance('assign', $instance->id);
435         // Create the test forum to update.
436         $initvalues = new stdClass();
437         $initvalues->introformat = FORMAT_HTML;
438         $initvalues->course = $course->id;
439         $forum = self::getDataGenerator()->create_module('forum', $initvalues);
441         // Retrieve course module.
442         $cm = get_coursemodule_from_instance('forum', $forum->id);
444         // Module test values.
445         $moduleinfo = new stdClass();
447         // Always mandatory generic values to any module.
448         $moduleinfo->coursemodule = $cm->id;
449         $moduleinfo->modulename = $modulename;
450         $moduleinfo->course = $course->id;
451         $moduleinfo->groupingid = $grouping->id;
452         $moduleinfo->groupmembersonly = 0;
453         $moduleinfo->visible = true;
455         // Sometimes optional generic values for some modules.
456         $moduleinfo->name = 'My test module';
457         $moduleinfo->showdescription = 1; // standard boolean
458         require_once($CFG->libdir . '/gradelib.php');
459         $gradecats = grade_get_categories_menu($moduleinfo->course, false);
460         $gradecatid = current(array_keys($gradecats)); // Retrieve the first key of $gradecats
461         $moduleinfo->gradecat = $gradecatid;
462         $moduleinfo->groupmode = VISIBLEGROUPS;
463         $moduleinfo->cmidnumber = 'idnumber_XXX';
465         // Completion common to all module.
466         $moduleinfo->completion = COMPLETION_TRACKING_AUTOMATIC;
467         $moduleinfo->completionview = COMPLETION_VIEW_REQUIRED;
468         $moduleinfo->completiongradeitemnumber = 1;
469         $moduleinfo->completionexpected = time() + (7 * 24 * 3600);
470         $moduleinfo->completionunlocked = 1;
472         // Conditional activity.
473         $moduleinfo->availablefrom = time();
474         $moduleinfo->availableuntil = time() + (7 * 24 * 3600);
475         $moduleinfo->showavailability = CONDITION_STUDENTVIEW_SHOW;
476         $coursegradeitem = grade_item::fetch_course_item($moduleinfo->course); //the activity will become available only when the user reach some grade into the course itself.
477         $moduleinfo->conditiongradegroup = array(array('conditiongradeitemid' => $coursegradeitem->id, 'conditiongrademin' => 10, 'conditiongrademax' => 80));
478         $moduleinfo->conditionfieldgroup = array(array('conditionfield' => 'email', 'conditionfieldoperator' => OP_CONTAINS, 'conditionfieldvalue' => '@'));
479         $moduleinfo->conditioncompletiongroup = array(array('conditionsourcecmid' => $assigncm->id, 'conditionrequiredcompletion' => COMPLETION_COMPLETE)); // "conditionsourcecmid == 0" => none
481         // Grading and Advanced grading.
482         require_once($CFG->dirroot . '/rating/lib.php');
483         $moduleinfo->assessed = RATING_AGGREGATE_AVERAGE;
484         $moduleinfo->scale = 10; // Note: it could be minus (for specific course scale). It is a signed number.
485         $moduleinfo->assesstimestart = time();
486         $moduleinfo->assesstimefinish = time() + (7 * 24 * 3600);
488         // RSS.
489         $moduleinfo->rsstype = 2;
490         $moduleinfo->rssarticles = 10;
492         // Optional intro editor (depends of module).
493         $draftid_editor = 0;
494         file_prepare_draft_area($draftid_editor, null, null, null, null);
495         $moduleinfo->introeditor = array('text' => 'This is a module', 'format' => FORMAT_HTML, 'itemid' => $draftid_editor);
497         // Following is the advanced grading method area called 'submissions' for the 'assign' module.
498         if (plugin_supports('mod', $modulename, FEATURE_GRADE_HAS_GRADE, false) && !plugin_supports('mod', $modulename, FEATURE_RATE, false)) {
499             $moduleinfo->grade = 100;
500         }
501         // Plagiarism form values.
502         // No plagiarism plugin installed by default. Use this space to make your own test.
504         // Values specific to the module.
505         $modulesetvalues = $modulename.'_update_set_values';
506         $this->$modulesetvalues($moduleinfo);
508         // Create the module.
509         $result = update_module($moduleinfo);
511         // Retrieve the module info.
512         $dbmodinstance = $DB->get_record($moduleinfo->modulename, array('id' => $result->instance));
513         $dbcm = get_coursemodule_from_instance($moduleinfo->modulename, $result->instance);
514         // Retrieve the grade item.
515         $gradeitem = $DB->get_record('grade_items', array('courseid' => $moduleinfo->course,
516             'iteminstance' => $dbmodinstance->id, 'itemmodule' => $moduleinfo->modulename));
518         // Compare the values common to all module instances.
519         $this->assertEquals($moduleinfo->modulename, $dbcm->modname);
520         $this->assertEquals($moduleinfo->course, $dbcm->course);
521         $this->assertEquals($moduleinfo->groupingid, $dbcm->groupingid);
522         $this->assertEquals($moduleinfo->groupmembersonly, $dbcm->groupmembersonly);
523         $this->assertEquals($moduleinfo->visible, $dbcm->visible);
524         $this->assertEquals($moduleinfo->completion, $dbcm->completion);
525         $this->assertEquals($moduleinfo->completionview, $dbcm->completionview);
526         $this->assertEquals($moduleinfo->completiongradeitemnumber, $dbcm->completiongradeitemnumber);
527         $this->assertEquals($moduleinfo->completionexpected, $dbcm->completionexpected);
528         $this->assertEquals($moduleinfo->availablefrom, $dbcm->availablefrom);
529         $this->assertEquals($moduleinfo->availableuntil, $dbcm->availableuntil);
530         $this->assertEquals($moduleinfo->showavailability, $dbcm->showavailability);
531         $this->assertEquals($moduleinfo->showdescription, $dbcm->showdescription);
532         $this->assertEquals($moduleinfo->groupmode, $dbcm->groupmode);
533         $this->assertEquals($moduleinfo->cmidnumber, $dbcm->idnumber);
534         $this->assertEquals($moduleinfo->gradecat, $gradeitem->categoryid);
536         // Optional grade testing.
537         if (plugin_supports('mod', $modulename, FEATURE_GRADE_HAS_GRADE, false) && !plugin_supports('mod', $modulename, FEATURE_RATE, false)) {
538             $this->assertEquals($moduleinfo->grade, $dbmodinstance->grade);
539         }
541         // Some optional (but quite common) to some module.
542         $this->assertEquals($moduleinfo->name, $dbmodinstance->name);
543         $this->assertEquals($moduleinfo->intro, $dbmodinstance->intro);
544         $this->assertEquals($moduleinfo->introformat, $dbmodinstance->introformat);
546         // Common values when conditional activity is enabled.
547         foreach ($moduleinfo->conditionfieldgroup as $fieldgroup) {
548             $isfieldgroupsaved = $DB->count_records('course_modules_avail_fields', array('coursemoduleid' => $dbcm->id,
549                 'userfield' => $fieldgroup['conditionfield'], 'operator' => $fieldgroup['conditionfieldoperator'],
550                 'value' => $fieldgroup['conditionfieldvalue']));
551             $this->assertEquals(1, $isfieldgroupsaved);
552         }
553         foreach ($moduleinfo->conditiongradegroup as $gradegroup) {
554             $isgradegroupsaved = $DB->count_records('course_modules_availability', array('coursemoduleid' => $dbcm->id,
555                 'grademin' => $gradegroup['conditiongrademin'], 'grademax' => $gradegroup['conditiongrademax'],
556                 'gradeitemid' => $gradegroup['conditiongradeitemid']));
557             $this->assertEquals(1, $isgradegroupsaved);
558         }
559         foreach ($moduleinfo->conditioncompletiongroup as $completiongroup) {
560             $iscompletiongroupsaved = $DB->count_records('course_modules_availability', array('coursemoduleid' => $dbcm->id,
561                 'sourcecmid' => $completiongroup['conditionsourcecmid'], 'requiredcompletion' => $completiongroup['conditionrequiredcompletion']));
562             $this->assertEquals(1, $iscompletiongroupsaved);
563         }
565         // Test specific to the module.
566         $modulerunasserts = $modulename.'_update_run_asserts';
567         $this->$modulerunasserts($moduleinfo, $dbmodinstance);
568    }
571     public function test_create_course() {
572         global $DB;
573         $this->resetAfterTest(true);
574         $defaultcategory = $DB->get_field_select('course_categories', "MIN(id)", "parent=0");
576         $course = new stdClass();
577         $course->fullname = 'Apu loves Unit Təsts';
578         $course->shortname = 'Spread the lŭve';
579         $course->idnumber = '123';
580         $course->summary = 'Awesome!';
581         $course->summaryformat = FORMAT_PLAIN;
582         $course->format = 'topics';
583         $course->newsitems = 0;
584         $course->numsections = 5;
585         $course->category = $defaultcategory;
586         $original = (array) $course;
588         $created = create_course($course);
589         $context = context_course::instance($created->id);
591         // Compare original and created.
592         $this->assertEquals($original, array_intersect_key((array) $created, $original));
594         // Ensure default section is created.
595         $sectioncreated = $DB->record_exists('course_sections', array('course' => $created->id, 'section' => 0));
596         $this->assertTrue($sectioncreated);
598         // Ensure blocks have been associated to the course.
599         $blockcount = $DB->count_records('block_instances', array('parentcontextid' => $context->id));
600         $this->assertGreaterThan(0, $blockcount);
601     }
603     public function test_create_course_with_generator() {
604         global $DB;
605         $this->resetAfterTest(true);
606         $course = $this->getDataGenerator()->create_course();
608         // Ensure default section is created.
609         $sectioncreated = $DB->record_exists('course_sections', array('course' => $course->id, 'section' => 0));
610         $this->assertTrue($sectioncreated);
611     }
613     public function test_create_course_sections() {
614         global $DB;
615         $this->resetAfterTest(true);
617         $course = $this->getDataGenerator()->create_course(
618                 array('shortname' => 'GrowingCourse',
619                     'fullname' => 'Growing Course',
620                     'numsections' => 5),
621                 array('createsections' => true));
623         // Ensure all 6 (0-5) sections were created and modinfo/sectioninfo cache works properly
624         $sectionscreated = array_keys(get_fast_modinfo($course)->get_section_info_all());
625         $this->assertEquals(range(0, $course->numsections), $sectionscreated);
627         // this will do nothing, section already exists
628         $this->assertFalse(course_create_sections_if_missing($course, $course->numsections));
630         // this will create new section
631         $this->assertTrue(course_create_sections_if_missing($course, $course->numsections + 1));
633         // Ensure all 7 (0-6) sections were created and modinfo/sectioninfo cache works properly
634         $sectionscreated = array_keys(get_fast_modinfo($course)->get_section_info_all());
635         $this->assertEquals(range(0, $course->numsections + 1), $sectionscreated);
636     }
638     public function test_reorder_sections() {
639         global $DB;
640         $this->resetAfterTest(true);
642         $this->getDataGenerator()->create_course(array('numsections'=>5), array('createsections'=>true));
643         $course = $this->getDataGenerator()->create_course(array('numsections'=>10), array('createsections'=>true));
644         $oldsections = array();
645         $sections = array();
646         foreach ($DB->get_records('course_sections', array('course'=>$course->id), 'id') as $section) {
647             $oldsections[$section->section] = $section->id;
648             $sections[$section->id] = $section->section;
649         }
650         ksort($oldsections);
652         $neworder = reorder_sections($sections, 2, 4);
653         $neworder = array_keys($neworder);
654         $this->assertEquals($oldsections[0], $neworder[0]);
655         $this->assertEquals($oldsections[1], $neworder[1]);
656         $this->assertEquals($oldsections[2], $neworder[4]);
657         $this->assertEquals($oldsections[3], $neworder[2]);
658         $this->assertEquals($oldsections[4], $neworder[3]);
659         $this->assertEquals($oldsections[5], $neworder[5]);
660         $this->assertEquals($oldsections[6], $neworder[6]);
662         $neworder = reorder_sections($sections, 4, 2);
663         $neworder = array_keys($neworder);
664         $this->assertEquals($oldsections[0], $neworder[0]);
665         $this->assertEquals($oldsections[1], $neworder[1]);
666         $this->assertEquals($oldsections[2], $neworder[3]);
667         $this->assertEquals($oldsections[3], $neworder[4]);
668         $this->assertEquals($oldsections[4], $neworder[2]);
669         $this->assertEquals($oldsections[5], $neworder[5]);
670         $this->assertEquals($oldsections[6], $neworder[6]);
672         $neworder = reorder_sections(1, 2, 4);
673         $this->assertFalse($neworder);
674     }
676     public function test_move_section_down() {
677         global $DB;
678         $this->resetAfterTest(true);
680         $this->getDataGenerator()->create_course(array('numsections'=>5), array('createsections'=>true));
681         $course = $this->getDataGenerator()->create_course(array('numsections'=>10), array('createsections'=>true));
682         $oldsections = array();
683         foreach ($DB->get_records('course_sections', array('course'=>$course->id)) as $section) {
684             $oldsections[$section->section] = $section->id;
685         }
686         ksort($oldsections);
688         // Test move section down..
689         move_section_to($course, 2, 4);
690         $sections = array();
691         foreach ($DB->get_records('course_sections', array('course'=>$course->id)) as $section) {
692             $sections[$section->section] = $section->id;
693         }
694         ksort($sections);
696         $this->assertEquals($oldsections[0], $sections[0]);
697         $this->assertEquals($oldsections[1], $sections[1]);
698         $this->assertEquals($oldsections[2], $sections[4]);
699         $this->assertEquals($oldsections[3], $sections[2]);
700         $this->assertEquals($oldsections[4], $sections[3]);
701         $this->assertEquals($oldsections[5], $sections[5]);
702         $this->assertEquals($oldsections[6], $sections[6]);
703     }
705     public function test_move_section_up() {
706         global $DB;
707         $this->resetAfterTest(true);
709         $this->getDataGenerator()->create_course(array('numsections'=>5), array('createsections'=>true));
710         $course = $this->getDataGenerator()->create_course(array('numsections'=>10), array('createsections'=>true));
711         $oldsections = array();
712         foreach ($DB->get_records('course_sections', array('course'=>$course->id)) as $section) {
713             $oldsections[$section->section] = $section->id;
714         }
715         ksort($oldsections);
717         // Test move section up..
718         move_section_to($course, 6, 4);
719         $sections = array();
720         foreach ($DB->get_records('course_sections', array('course'=>$course->id)) as $section) {
721             $sections[$section->section] = $section->id;
722         }
723         ksort($sections);
725         $this->assertEquals($oldsections[0], $sections[0]);
726         $this->assertEquals($oldsections[1], $sections[1]);
727         $this->assertEquals($oldsections[2], $sections[2]);
728         $this->assertEquals($oldsections[3], $sections[3]);
729         $this->assertEquals($oldsections[4], $sections[5]);
730         $this->assertEquals($oldsections[5], $sections[6]);
731         $this->assertEquals($oldsections[6], $sections[4]);
732     }
734     public function test_move_section_marker() {
735         global $DB;
736         $this->resetAfterTest(true);
738         $this->getDataGenerator()->create_course(array('numsections'=>5), array('createsections'=>true));
739         $course = $this->getDataGenerator()->create_course(array('numsections'=>10), array('createsections'=>true));
741         // Set course marker to the section we are going to move..
742         course_set_marker($course->id, 2);
743         // Verify that the course marker is set correctly.
744         $course = $DB->get_record('course', array('id' => $course->id));
745         $this->assertEquals(2, $course->marker);
747         // Test move the marked section down..
748         move_section_to($course, 2, 4);
750         // Verify that the coruse marker has been moved along with the section..
751         $course = $DB->get_record('course', array('id' => $course->id));
752         $this->assertEquals(4, $course->marker);
754         // Test move the marked section up..
755         move_section_to($course, 4, 3);
757         // Verify that the course marker has been moved along with the section..
758         $course = $DB->get_record('course', array('id' => $course->id));
759         $this->assertEquals(3, $course->marker);
761         // Test moving a non-marked section above the marked section..
762         move_section_to($course, 4, 2);
764         // Verify that the course marker has been moved down to accomodate..
765         $course = $DB->get_record('course', array('id' => $course->id));
766         $this->assertEquals(4, $course->marker);
768         // Test moving a non-marked section below the marked section..
769         move_section_to($course, 3, 6);
771         // Verify that the course marker has been up to accomodate..
772         $course = $DB->get_record('course', array('id' => $course->id));
773         $this->assertEquals(3, $course->marker);
774     }
776     public function test_get_course_display_name_for_list() {
777         global $CFG;
778         $this->resetAfterTest(true);
780         $course = $this->getDataGenerator()->create_course(array('shortname' => 'FROG101', 'fullname' => 'Introduction to pond life'));
782         $CFG->courselistshortnames = 0;
783         $this->assertEquals('Introduction to pond life', get_course_display_name_for_list($course));
785         $CFG->courselistshortnames = 1;
786         $this->assertEquals('FROG101 Introduction to pond life', get_course_display_name_for_list($course));
787     }
789     public function test_move_module_in_course() {
790         global $DB;
792         $this->resetAfterTest(true);
793         // Setup fixture
794         $course = $this->getDataGenerator()->create_course(array('numsections'=>5), array('createsections' => true));
795         $forum = $this->getDataGenerator()->create_module('forum', array('course'=>$course->id));
797         $cms = get_fast_modinfo($course)->get_cms();
798         $cm = reset($cms);
800         $newsection = get_fast_modinfo($course)->get_section_info(3);
801         $oldsectionid = $cm->section;
803         // Perform the move
804         moveto_module($cm, $newsection);
806         // reset of get_fast_modinfo is usually called the code calling moveto_module so call it here
807         get_fast_modinfo(0, 0, true);
808         $cms = get_fast_modinfo($course)->get_cms();
809         $cm = reset($cms);
811         // Check that the cached modinfo contains the correct section info
812         $modinfo = get_fast_modinfo($course);
813         $this->assertTrue(empty($modinfo->sections[0]));
814         $this->assertFalse(empty($modinfo->sections[3]));
816         // Check that the old section's sequence no longer contains this ID
817         $oldsection = $DB->get_record('course_sections', array('id' => $oldsectionid));
818         $oldsequences = explode(',', $newsection->sequence);
819         $this->assertFalse(in_array($cm->id, $oldsequences));
821         // Check that the new section's sequence now contains this ID
822         $newsection = $DB->get_record('course_sections', array('id' => $newsection->id));
823         $newsequences = explode(',', $newsection->sequence);
824         $this->assertTrue(in_array($cm->id, $newsequences));
826         // Check that the section number has been changed in the cm
827         $this->assertEquals($newsection->id, $cm->section);
830         // Perform a second move as some issues were only seen on the second move
831         $newsection = get_fast_modinfo($course)->get_section_info(2);
832         $oldsectionid = $cm->section;
833         $result = moveto_module($cm, $newsection);
834         $this->assertTrue($result);
836         // reset of get_fast_modinfo is usually called the code calling moveto_module so call it here
837         get_fast_modinfo(0, 0, true);
838         $cms = get_fast_modinfo($course)->get_cms();
839         $cm = reset($cms);
841         // Check that the cached modinfo contains the correct section info
842         $modinfo = get_fast_modinfo($course);
843         $this->assertTrue(empty($modinfo->sections[0]));
844         $this->assertFalse(empty($modinfo->sections[2]));
846         // Check that the old section's sequence no longer contains this ID
847         $oldsection = $DB->get_record('course_sections', array('id' => $oldsectionid));
848         $oldsequences = explode(',', $newsection->sequence);
849         $this->assertFalse(in_array($cm->id, $oldsequences));
851         // Check that the new section's sequence now contains this ID
852         $newsection = $DB->get_record('course_sections', array('id' => $newsection->id));
853         $newsequences = explode(',', $newsection->sequence);
854         $this->assertTrue(in_array($cm->id, $newsequences));
855     }
857     public function test_module_visibility() {
858         $this->setAdminUser();
859         $this->resetAfterTest(true);
861         // Create course and modules.
862         $course = $this->getDataGenerator()->create_course(array('numsections' => 5));
863         $forum = $this->getDataGenerator()->create_module('forum', array('course' => $course->id));
864         $assign = $this->getDataGenerator()->create_module('assign', array('duedate' => time(), 'course' => $course->id));
865         $modules = compact('forum', 'assign');
867         // Hiding the modules.
868         foreach ($modules as $mod) {
869             set_coursemodule_visible($mod->cmid, 0);
870             $this->check_module_visibility($mod, 0, 0);
871         }
873         // Showing the modules.
874         foreach ($modules as $mod) {
875             set_coursemodule_visible($mod->cmid, 1);
876             $this->check_module_visibility($mod, 1, 1);
877         }
878     }
880     public function test_section_visibility() {
881         $this->setAdminUser();
882         $this->resetAfterTest(true);
884         // Create course.
885         $course = $this->getDataGenerator()->create_course(array('numsections' => 3), array('createsections' => true));
887         // Testing an empty section.
888         $sectionnumber = 1;
889         set_section_visible($course->id, $sectionnumber, 0);
890         $section_info = get_fast_modinfo($course->id)->get_section_info($sectionnumber);
891         $this->assertEquals($section_info->visible, 0);
892         set_section_visible($course->id, $sectionnumber, 1);
893         $section_info = get_fast_modinfo($course->id)->get_section_info($sectionnumber);
894         $this->assertEquals($section_info->visible, 1);
896         // Testing a section with visible modules.
897         $sectionnumber = 2;
898         $forum = $this->getDataGenerator()->create_module('forum', array('course' => $course->id),
899                 array('section' => $sectionnumber));
900         $assign = $this->getDataGenerator()->create_module('assign', array('duedate' => time(),
901                 'course' => $course->id), array('section' => $sectionnumber));
902         $modules = compact('forum', 'assign');
903         set_section_visible($course->id, $sectionnumber, 0);
904         $section_info = get_fast_modinfo($course->id)->get_section_info($sectionnumber);
905         $this->assertEquals($section_info->visible, 0);
906         foreach ($modules as $mod) {
907             $this->check_module_visibility($mod, 0, 1);
908         }
909         set_section_visible($course->id, $sectionnumber, 1);
910         $section_info = get_fast_modinfo($course->id)->get_section_info($sectionnumber);
911         $this->assertEquals($section_info->visible, 1);
912         foreach ($modules as $mod) {
913             $this->check_module_visibility($mod, 1, 1);
914         }
916         // Testing a section with hidden modules, which should stay hidden.
917         $sectionnumber = 3;
918         $forum = $this->getDataGenerator()->create_module('forum', array('course' => $course->id),
919                 array('section' => $sectionnumber));
920         $assign = $this->getDataGenerator()->create_module('assign', array('duedate' => time(),
921                 'course' => $course->id), array('section' => $sectionnumber));
922         $modules = compact('forum', 'assign');
923         foreach ($modules as $mod) {
924             set_coursemodule_visible($mod->cmid, 0);
925             $this->check_module_visibility($mod, 0, 0);
926         }
927         set_section_visible($course->id, $sectionnumber, 0);
928         $section_info = get_fast_modinfo($course->id)->get_section_info($sectionnumber);
929         $this->assertEquals($section_info->visible, 0);
930         foreach ($modules as $mod) {
931             $this->check_module_visibility($mod, 0, 0);
932         }
933         set_section_visible($course->id, $sectionnumber, 1);
934         $section_info = get_fast_modinfo($course->id)->get_section_info($sectionnumber);
935         $this->assertEquals($section_info->visible, 1);
936         foreach ($modules as $mod) {
937             $this->check_module_visibility($mod, 0, 0);
938         }
939     }
941     /**
942      * Helper function to assert that a module has correctly been made visible, or hidden.
943      *
944      * @param stdClass $mod module information
945      * @param int $visibility the current state of the module
946      * @param int $visibleold the current state of the visibleold property
947      * @return void
948      */
949     public function check_module_visibility($mod, $visibility, $visibleold) {
950         global $DB;
951         $cm = get_fast_modinfo($mod->course)->get_cm($mod->cmid);
952         $this->assertEquals($visibility, $cm->visible);
953         $this->assertEquals($visibleold, $cm->visibleold);
955         // Check the module grade items.
956         $grade_items = grade_item::fetch_all(array('itemtype' => 'mod', 'itemmodule' => $cm->modname,
957                 'iteminstance' => $cm->instance, 'courseid' => $cm->course));
958         if ($grade_items) {
959             foreach ($grade_items as $grade_item) {
960                 if ($visibility) {
961                     $this->assertFalse($grade_item->is_hidden(), "$cm->modname grade_item not visible");
962                 } else {
963                     $this->assertTrue($grade_item->is_hidden(), "$cm->modname grade_item not hidden");
964                 }
965             }
966         }
968         // Check the events visibility.
969         if ($events = $DB->get_records('event', array('instance' => $cm->instance, 'modulename' => $cm->modname))) {
970             foreach ($events as $event) {
971                 $calevent = new calendar_event($event);
972                 $this->assertEquals($visibility, $calevent->visible, "$cm->modname calendar_event visibility");
973             }
974         }
975     }
977     public function test_course_page_type_list() {
978         global $DB;
979         $this->resetAfterTest(true);
981         // Create a category.
982         $category = new stdClass();
983         $category->name = 'Test Category';
985         $testcategory = $this->getDataGenerator()->create_category($category);
987         // Create a course.
988         $course = new stdClass();
989         $course->fullname = 'Apu loves Unit Təsts';
990         $course->shortname = 'Spread the lŭve';
991         $course->idnumber = '123';
992         $course->summary = 'Awesome!';
993         $course->summaryformat = FORMAT_PLAIN;
994         $course->format = 'topics';
995         $course->newsitems = 0;
996         $course->numsections = 5;
997         $course->category = $testcategory->id;
999         $testcourse = $this->getDataGenerator()->create_course($course);
1001         // Create contexts.
1002         $coursecontext = context_course::instance($testcourse->id);
1003         $parentcontext = $coursecontext->get_parent_context(); // Not actually used.
1004         $pagetype = 'page-course-x'; // Not used either.
1005         $pagetypelist = course_page_type_list($pagetype, $parentcontext, $coursecontext);
1007         // Page type lists for normal courses.
1008         $testpagetypelist1 = array();
1009         $testpagetypelist1['*'] = 'Any page';
1010         $testpagetypelist1['course-*'] = 'Any course page';
1011         $testpagetypelist1['course-view-*'] = 'Any type of course main page';
1013         $this->assertEquals($testpagetypelist1, $pagetypelist);
1015         // Get the context for the front page course.
1016         $sitecoursecontext = context_course::instance(SITEID);
1017         $pagetypelist = course_page_type_list($pagetype, $parentcontext, $sitecoursecontext);
1019         // Page type list for the front page course.
1020         $testpagetypelist2 = array('*' => 'Any page');
1021         $this->assertEquals($testpagetypelist2, $pagetypelist);
1023         // Make sure that providing no current context to the function doesn't result in an error.
1024         // Calls made from generate_page_type_patterns() may provide null values.
1025         $pagetypelist = course_page_type_list($pagetype, null, null);
1026         $this->assertEquals($pagetypelist, $testpagetypelist1);
1027     }
1029     public function test_compare_activities_by_time_desc() {
1031         // Let's create some test data.
1032         $activitiesivities = array();
1033         $x = new stdClass();
1034         $x->timestamp = null;
1035         $activities[] = $x;
1037         $x = new stdClass();
1038         $x->timestamp = 1;
1039         $activities[] = $x;
1041         $x = new stdClass();
1042         $x->timestamp = 3;
1043         $activities[] = $x;
1045         $x = new stdClass();
1046         $x->timestamp = 0;
1047         $activities[] = $x;
1049         $x = new stdClass();
1050         $x->timestamp = 5;
1051         $activities[] = $x;
1053         $x = new stdClass();
1054         $activities[] = $x;
1056         $x = new stdClass();
1057         $x->timestamp = 5;
1058         $activities[] = $x;
1060         // Do the sorting.
1061         usort($activities, 'compare_activities_by_time_desc');
1063         // Let's check the result.
1064         $last = 10;
1065         foreach($activities as $activity) {
1066             if (empty($activity->timestamp)) {
1067                 $activity->timestamp = 0;
1068             }
1069             $this->assertLessThanOrEqual($last, $activity->timestamp);
1070         }
1071     }
1073     public function test_compare_activities_by_time_asc() {
1075         // Let's create some test data.
1076         $activities = array();
1077         $x = new stdClass();
1078         $x->timestamp = null;
1079         $activities[] = $x;
1081         $x = new stdClass();
1082         $x->timestamp = 1;
1083         $activities[] = $x;
1085         $x = new stdClass();
1086         $x->timestamp = 3;
1087         $activities[] = $x;
1089         $x = new stdClass();
1090         $x->timestamp = 0;
1091         $activities[] = $x;
1093         $x = new stdClass();
1094         $x->timestamp = 5;
1095         $activities[] = $x;
1097         $x = new stdClass();
1098         $activities[] = $x;
1100         $x = new stdClass();
1101         $x->timestamp = 5;
1102         $activities[] = $x;
1104         // Do the sorting.
1105         usort($activities, 'compare_activities_by_time_asc');
1107         // Let's check the result.
1108         $last = 0;
1109         foreach($activities as $activity) {
1110             if (empty($activity->timestamp)) {
1111                 $activity->timestamp = 0;
1112             }
1113             $this->assertGreaterThanOrEqual($last, $activity->timestamp);
1114         }
1115     }
1117     /**
1118      * Tests moving a module between hidden/visible sections and
1119      * verifies that the course/module visiblity seettings are
1120      * retained.
1121      */
1122     public function test_moveto_module_between_hidden_sections() {
1123         global $DB;
1125         $this->resetAfterTest(true);
1127         $course = $this->getDataGenerator()->create_course(array('numsections' => 4), array('createsections' => true));
1128         $forum = $this->getDataGenerator()->create_module('forum', array('course' => $course->id));
1129         $page = $this->getDataGenerator()->create_module('page', array('course' => $course->id));
1130         $quiz= $this->getDataGenerator()->create_module('quiz', array('course' => $course->id));
1132         // Set the page as hidden
1133         set_coursemodule_visible($page->cmid, 0);
1135         // Set sections 3 as hidden.
1136         set_section_visible($course->id, 3, 0);
1138         $modinfo = get_fast_modinfo($course);
1140         $hiddensection = $modinfo->get_section_info(3);
1141         // New section is definitely not visible:
1142         $this->assertEquals($hiddensection->visible, 0);
1144         $forumcm = $modinfo->cms[$forum->cmid];
1145         $pagecm = $modinfo->cms[$page->cmid];
1147         // Move the forum and the page to a hidden section.
1148         moveto_module($forumcm, $hiddensection);
1149         moveto_module($pagecm, $hiddensection);
1151         // Reset modinfo cache.
1152         get_fast_modinfo(0, 0, true);
1154         $modinfo = get_fast_modinfo($course);
1156         // Verify that forum and page have been moved to the hidden section and quiz has not.
1157         $this->assertContains($forum->cmid, $modinfo->sections[3]);
1158         $this->assertContains($page->cmid, $modinfo->sections[3]);
1159         $this->assertNotContains($quiz->cmid, $modinfo->sections[3]);
1161         // Verify that forum has been made invisible.
1162         $forumcm = $modinfo->cms[$forum->cmid];
1163         $this->assertEquals($forumcm->visible, 0);
1164         // Verify that old state has been retained.
1165         $this->assertEquals($forumcm->visibleold, 1);
1167         // Verify that page has stayed invisible.
1168         $pagecm = $modinfo->cms[$page->cmid];
1169         $this->assertEquals($pagecm->visible, 0);
1170         // Verify that old state has been retained.
1171         $this->assertEquals($pagecm->visibleold, 0);
1173         // Verify that quiz has been unaffected.
1174         $quizcm = $modinfo->cms[$quiz->cmid];
1175         $this->assertEquals($quizcm->visible, 1);
1177         // Move forum and page back to visible section.
1178         $visiblesection = $modinfo->get_section_info(2);
1179         moveto_module($forumcm, $visiblesection);
1180         moveto_module($pagecm, $visiblesection);
1182         // Reset modinfo cache.
1183         get_fast_modinfo(0, 0, true);
1184         $modinfo = get_fast_modinfo($course);
1186         // Verify that forum has been made visible.
1187         $forumcm = $modinfo->cms[$forum->cmid];
1188         $this->assertEquals($forumcm->visible, 1);
1190         // Verify that page has stayed invisible.
1191         $pagecm = $modinfo->cms[$page->cmid];
1192         $this->assertEquals($pagecm->visible, 0);
1194         // Move the page in the same section (this is what mod duplicate does_
1195         moveto_module($pagecm, $visiblesection, $forumcm);
1197         // Reset modinfo cache.
1198         get_fast_modinfo(0, 0, true);
1200         // Verify that the the page is still hidden
1201         $modinfo = get_fast_modinfo($course);
1202         $pagecm = $modinfo->cms[$page->cmid];
1203         $this->assertEquals($pagecm->visible, 0);
1204     }
1206     /**
1207      * Tests moving a module around in the same section. moveto_module()
1208      * is called this way in modduplicate.
1209      */
1210     public function test_moveto_module_in_same_section() {
1211         global $DB;
1213         $this->resetAfterTest(true);
1215         $course = $this->getDataGenerator()->create_course(array('numsections' => 3), array('createsections' => true));
1216         $page = $this->getDataGenerator()->create_module('page', array('course' => $course->id));
1217         $forum = $this->getDataGenerator()->create_module('forum', array('course' => $course->id));
1219         // Simulate inconsistent visible/visibleold values (MDL-38713).
1220         $cm = $DB->get_record('course_modules', array('id' => $page->cmid), '*', MUST_EXIST);
1221         $cm->visible = 0;
1222         $cm->visibleold = 1;
1223         $DB->update_record('course_modules', $cm);
1225         $modinfo = get_fast_modinfo($course);
1226         $forumcm = $modinfo->cms[$forum->cmid];
1227         $pagecm = $modinfo->cms[$page->cmid];
1229         // Verify that page is hidden.
1230         $this->assertEquals($pagecm->visible, 0);
1232         // Verify section 0 is where all mods added.
1233         $section = $modinfo->get_section_info(0);
1234         $this->assertEquals($section->id, $forumcm->section);
1235         $this->assertEquals($section->id, $pagecm->section);
1238         // Move the forum and the page to a hidden section.
1239         moveto_module($pagecm, $section, $forumcm);
1241         // Reset modinfo cache.
1242         get_fast_modinfo(0, 0, true);
1244         // Verify that the the page is still hidden
1245         $modinfo = get_fast_modinfo($course);
1246         $pagecm = $modinfo->cms[$page->cmid];
1247         $this->assertEquals($pagecm->visible, 0);
1248     }