MDL-52252 Tags: Add tags to modules (Resources and Activities)
[moodle.git] / lib / testing / tests / generator_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  * Data generators 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();
29 /**
30  * Test data generator
31  *
32  * @package    core
33  * @category   phpunit
34  * @copyright  2012 Petr Skoda {@link http://skodak.org}
35  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
36  */
37 class core_test_generator_testcase extends advanced_testcase {
38     public function test_get_plugin_generator_good_case() {
39         $generator = $this->getDataGenerator()->get_plugin_generator('core_question');
40         $this->assertInstanceOf('core_question_generator', $generator);
41     }
43     public function test_get_plugin_generator_sloppy_name() {
44         $generator = $this->getDataGenerator()->get_plugin_generator('quiz');
45         $this->assertDebuggingCalled('Please specify the component you want a generator for as ' .
46                     'mod_quiz, not quiz.', DEBUG_DEVELOPER);
47         $this->assertInstanceOf('mod_quiz_generator', $generator);
48     }
50     public function test_get_plugin_generator_no_component_dir() {
51         $this->setExpectedException('coding_exception', 'Component core_completion does not support ' .
52                     'generators yet. Missing tests/generator/lib.php.');
53         $generator = $this->getDataGenerator()->get_plugin_generator('core_completion');
54     }
56     public function test_create_user() {
57         global $DB, $CFG;
58         require_once($CFG->dirroot.'/user/lib.php');
60         $this->resetAfterTest(true);
61         $generator = $this->getDataGenerator();
63         $count = $DB->count_records('user');
64         $this->setCurrentTimeStart();
65         $user = $generator->create_user();
66         $this->assertEquals($count + 1, $DB->count_records('user'));
67         $this->assertSame($user->username, clean_param($user->username, PARAM_USERNAME));
68         $this->assertSame($user->email, clean_param($user->email, PARAM_EMAIL));
69         $this->assertSame(AUTH_PASSWORD_NOT_CACHED, $user->password);
70         $this->assertNotEmpty($user->firstnamephonetic);
71         $this->assertNotEmpty($user->lastnamephonetic);
72         $this->assertNotEmpty($user->alternatename);
73         $this->assertNotEmpty($user->middlename);
74         $this->assertSame('manual', $user->auth);
75         $this->assertSame('en', $user->lang);
76         $this->assertSame('1', $user->confirmed);
77         $this->assertSame('0', $user->deleted);
78         $this->assertTimeCurrent($user->timecreated);
79         $this->assertSame($user->timecreated, $user->timemodified);
80         $this->assertSame('0.0.0.0', $user->lastip);
82         $record = array(
83             'auth' => 'email',
84             'firstname' => 'Žluťoučký',
85             'lastname' => 'Koníček',
86             'firstnamephonetic' => 'Zhlutyoucky',
87             'lastnamephonetic' => 'Koniiczek',
88             'middlename' => 'Hopper',
89             'alternatename' => 'horse',
90             'idnumber' => 'abc1',
91             'mnethostid' => (string)$CFG->mnet_localhost_id,
92             'username' => 'konic666',
93             'password' => 'password1',
94             'email' => 'email@example.com',
95             'confirmed' => '1',
96             'lang' => 'cs',
97             'maildisplay' => '1',
98             'mailformat' => '0',
99             'maildigest' => '1',
100             'autosubscribe' => '0',
101             'trackforums' => '0',
102             'deleted' => '0',
103             'timecreated' => '666',
104         );
105         $user = $generator->create_user($record);
106         $this->assertEquals($count + 2, $DB->count_records('user'));
107         foreach ($record as $k => $v) {
108             if ($k === 'password') {
109                 $this->assertTrue(password_verify($v, $user->password));
110             } else {
111                 $this->assertSame($v, $user->{$k});
112             }
113         }
115         $record = array(
116             'firstname' => 'Some',
117             'lastname' => 'User',
118             'idnumber' => 'def',
119             'username' => 'user666',
120             'email' => 'email666@example.com',
121             'deleted' => '1',
122         );
123         $user = $generator->create_user($record);
124         $this->assertEquals($count + 3, $DB->count_records('user'));
125         $this->assertSame('', $user->idnumber);
126         $this->assertSame(md5($record['username']), $user->email);
127         $this->assertFalse(context_user::instance($user->id, IGNORE_MISSING));
129         // Test generating user with interests.
130         $user = $generator->create_user(array('interests' => 'Cats, Dogs'));
131         $userdetails = user_get_user_details($user);
132         $this->assertSame('Cats, Dogs', $userdetails['interests']);
133     }
135     public function test_create() {
136         global $DB;
138         $this->resetAfterTest(true);
139         $generator = $this->getDataGenerator();
141         $count = $DB->count_records('course_categories');
142         $category = $generator->create_category();
143         $this->assertEquals($count+1, $DB->count_records('course_categories'));
144         $this->assertRegExp('/^Course category \d/', $category->name);
145         $this->assertSame('', $category->idnumber);
146         $this->assertRegExp('/^Test course category \d/', $category->description);
147         $this->assertSame(FORMAT_MOODLE, $category->descriptionformat);
149         $count = $DB->count_records('cohort');
150         $cohort = $generator->create_cohort();
151         $this->assertEquals($count+1, $DB->count_records('cohort'));
152         $this->assertEquals(context_system::instance()->id, $cohort->contextid);
153         $this->assertRegExp('/^Cohort \d/', $cohort->name);
154         $this->assertSame('', $cohort->idnumber);
155         $this->assertRegExp('/^Test cohort \d/', $cohort->description);
156         $this->assertSame(FORMAT_MOODLE, $cohort->descriptionformat);
157         $this->assertSame('', $cohort->component);
158         $this->assertLessThanOrEqual(time(), $cohort->timecreated);
159         $this->assertSame($cohort->timecreated, $cohort->timemodified);
161         $count = $DB->count_records('course');
162         $course = $generator->create_course();
163         $this->assertEquals($count+1, $DB->count_records('course'));
164         $this->assertRegExp('/^Test course \d/', $course->fullname);
165         $this->assertRegExp('/^tc_\d/', $course->shortname);
166         $this->assertSame('', $course->idnumber);
167         $this->assertSame('topics', $course->format);
168         $this->assertEquals(0, $course->newsitems);
169         $this->assertEquals(5, $course->numsections);
170         $this->assertRegExp('/^Test course \d/', $course->summary);
171         $this->assertSame(FORMAT_MOODLE, $course->summaryformat);
173         $section = $generator->create_course_section(array('course'=>$course->id, 'section'=>3));
174         $this->assertEquals($course->id, $section->course);
176         $course = $generator->create_course(array('tags' => 'Cat, Dog'));
177         $this->assertEquals(array('Cat', 'Dog'), array_values(core_tag_tag::get_item_tags_array('core', 'course', $course->id)));
179         $scale = $generator->create_scale();
180         $this->assertNotEmpty($scale);
181     }
183     public function test_create_module() {
184         global $CFG, $SITE, $DB;
185         if (!file_exists("$CFG->dirroot/mod/page/")) {
186             $this->markTestSkipped('Can not find standard Page module');
187         }
189         $this->resetAfterTest(true);
190         $generator = $this->getDataGenerator();
192         $page = $generator->create_module('page', array('course'=>$SITE->id));
193         $this->assertNotEmpty($page);
194         $cm = get_coursemodule_from_instance('page', $page->id, $SITE->id, true);
195         $this->assertEquals(0, $cm->sectionnum);
197         $page = $generator->create_module('page', array('course'=>$SITE->id), array('section'=>3));
198         $this->assertNotEmpty($page);
199         $cm = get_coursemodule_from_instance('page', $page->id, $SITE->id, true);
200         $this->assertEquals(3, $cm->sectionnum);
202         $page = $generator->create_module('page', array('course' => $SITE->id, 'tags' => 'Cat, Dog'));
203         $this->assertEquals(array('Cat', 'Dog'),
204             array_values(core_tag_tag::get_item_tags_array('core', 'course_modules', $page->cmid)));
206         // Prepare environment to generate modules with all possible options.
208         // Enable advanced functionality.
209         $CFG->enablecompletion = 1;
210         $CFG->enableavailability = 1;
211         $CFG->enableoutcomes = 1;
212         require_once($CFG->libdir.'/gradelib.php');
213         require_once($CFG->libdir.'/completionlib.php');
214         require_once($CFG->dirroot.'/rating/lib.php');
216         // Create a course with enabled completion.
217         $course = $generator->create_course(array('enablecompletion' => true));
219         // Create new grading category in this course.
220         $grade_category = new grade_category();
221         $grade_category->courseid = $course->id;
222         $grade_category->fullname = 'Grade category';
223         $grade_category->insert();
225         // Create group and grouping.
226         $group = $generator->create_group(array('courseid' => $course->id));
227         $grouping = $generator->create_grouping(array('courseid' => $course->id));
228         $generator->create_grouping_group(array('groupid' => $group->id, 'groupingid' => $grouping->id));
230         // Prepare arrays with properties that we can both use for creating modules and asserting the data in created modules.
232         // General properties.
233         $optionsgeneral = array(
234             'visible' => 0, // Note: 'visibleold' will always be set to the same value as 'visible'.
235             'section' => 3, // Note: section will be created if does not exist.
236             // Module supports FEATURE_IDNUMBER.
237             'cmidnumber' => 'IDNUM', // Note: alternatively can have key 'idnumber'.
238             // Module supports FEATURE_GROUPS;
239             'groupmode' => SEPARATEGROUPS, // Note: will be reset to 0 if course groupmodeforce is set.
240             // Module supports FEATURE_GROUPINGS.
241             'groupingid' => $grouping->id,
242         );
244         // In case completion is enabled on site and for course every module can have manual completion.
245         $featurecompletionmanual = array(
246             'completion' => COMPLETION_TRACKING_MANUAL, // "Students can manually mark activity as completed."
247             'completionexpected' => time() + 7 * DAYSECS,
248         );
250         // Automatic completion is possible if module supports FEATURE_COMPLETION_TRACKS_VIEWS or FEATURE_GRADE_HAS_GRADE.
251         // Note: completionusegrade is stored in DB and can be found in cm_info as 'completiongradeitemnumber' - either NULL or 0.
252         // Note: module can have more autocompletion rules as defined in moodleform_mod::add_completion_rules().
253         $featurecompletionautomatic = array(
254             'completion' => COMPLETION_TRACKING_AUTOMATIC, // "Show activity as complete when conditions are met."
255             'completionview' => 1, // "Student must view this activity to complete it"
256             'completionusegrade' => 1, // "Student must receive a grade to complete this activity"
257         );
259         // Module supports FEATURE_RATE:
260         $featurerate = array(
261             'assessed' => RATING_AGGREGATE_AVERAGE, // "Aggregate type"
262             'scale' => 100, // Either max grade or negative number for scale id.
263             'ratingtime' => 1, // "Restrict ratings to items with dates in this range".
264             'assesstimestart' => time() - DAYSECS, // Note: Will be ignored if neither 'assessed' nor 'ratingtime' is set.
265             'assesstimefinish' => time() + DAYSECS, // Note: Will be ignored if neither 'assessed' nor 'ratingtime' is set.
266         );
268         // Module supports FEATURE_GRADE_HAS_GRADE:
269         $featuregrade = array(
270             'grade' => 10,
271             'gradecat' => $grade_category->id, // Note: if $CFG->enableoutcomes is set, this can be set to -1 to automatically create new grade category.
272         );
274         // Now let's create several modules with different options.
275         $m1 = $generator->create_module('assign',
276             array('course' => $course->id) +
277             $optionsgeneral);
278         $m2 = $generator->create_module('data',
279             array('course' => $course->id) +
280             $featurecompletionmanual +
281             $featurerate);
282         $m3 = $generator->create_module('assign',
283             array('course' => $course->id) +
284             $featurecompletionautomatic +
285             $featuregrade);
287         // We need id of the grading item for the second module to create availability dependency in the 3rd module.
288         $gradingitem = grade_item::fetch(array('courseid'=>$course->id, 'itemtype'=>'mod', 'itemmodule' => 'assign', 'iteminstance' => $m3->id));
290         // Now prepare option to create the 4th module with an availability condition.
291         $optionsavailability = array(
292             'availability' => '{"op":"&","showc":[true],"c":[' .
293                 '{"type":"date","d":">=","t":' . (time() - WEEKSECS) . '}]}',
294         );
296         // Create module with conditional availability.
297         $m4 = $generator->create_module('assign',
298                 array('course' => $course->id) +
299                 $optionsavailability
300         );
302         // Verifying that everything is generated correctly.
303         $modinfo = get_fast_modinfo($course->id);
304         $cm1 = $modinfo->cms[$m1->cmid];
305         $this->assertEquals($optionsgeneral['visible'], $cm1->visible);
306         $this->assertEquals($optionsgeneral['section'], $cm1->sectionnum); // Note difference in key.
307         $this->assertEquals($optionsgeneral['cmidnumber'], $cm1->idnumber); // Note difference in key.
308         $this->assertEquals($optionsgeneral['groupmode'], $cm1->groupmode);
309         $this->assertEquals($optionsgeneral['groupingid'], $cm1->groupingid);
311         $cm2 = $modinfo->cms[$m2->cmid];
312         $this->assertEquals($featurecompletionmanual['completion'], $cm2->completion);
313         $this->assertEquals($featurecompletionmanual['completionexpected'], $cm2->completionexpected);
314         $this->assertEquals(null, $cm2->completiongradeitemnumber);
315         // Rating info is stored in the module's table (in our test {data}).
316         $data = $DB->get_record('data', array('id' => $m2->id));
317         $this->assertEquals($featurerate['assessed'], $data->assessed);
318         $this->assertEquals($featurerate['scale'], $data->scale);
319         $this->assertEquals($featurerate['assesstimestart'], $data->assesstimestart);
320         $this->assertEquals($featurerate['assesstimefinish'], $data->assesstimefinish);
321         // No validation for 'ratingtime'. It is only used in to enable/disable assesstime* when adding module.
323         $cm3 = $modinfo->cms[$m3->cmid];
324         $this->assertEquals($featurecompletionautomatic['completion'], $cm3->completion);
325         $this->assertEquals($featurecompletionautomatic['completionview'], $cm3->completionview);
326         $this->assertEquals(0, $cm3->completiongradeitemnumber); // Zero instead of default null since 'completionusegrade' was set.
327         $gradingitem = grade_item::fetch(array('courseid'=>$course->id, 'itemtype'=>'mod', 'itemmodule' => 'assign', 'iteminstance' => $m3->id));
328         $this->assertEquals(0, $gradingitem->grademin);
329         $this->assertEquals($featuregrade['grade'], $gradingitem->grademax);
330         $this->assertEquals($featuregrade['gradecat'], $gradingitem->categoryid);
332         $cm4 = $modinfo->cms[$m4->cmid];
333         $this->assertEquals($optionsavailability['availability'], $cm4->availability);
334     }
336     public function test_create_block() {
337         global $CFG;
338         if (!file_exists("$CFG->dirroot/blocks/online_users/")) {
339             $this->markTestSkipped('Can not find standard Online users block');
340         }
342         $this->resetAfterTest(true);
343         $generator = $this->getDataGenerator();
345         $page = $generator->create_block('online_users');
346         $this->assertNotEmpty($page);
347     }
349     public function test_enrol_user() {
350         global $DB;
352         $this->resetAfterTest();
354         $selfplugin = enrol_get_plugin('self');
355         $this->assertNotEmpty($selfplugin);
357         $manualplugin = enrol_get_plugin('manual');
358         $this->assertNotEmpty($manualplugin);
360         // Prepare some data.
362         $studentrole = $DB->get_record('role', array('shortname'=>'student'));
363         $this->assertNotEmpty($studentrole);
364         $teacherrole = $DB->get_record('role', array('shortname'=>'teacher'));
365         $this->assertNotEmpty($teacherrole);
367         $course1 = $this->getDataGenerator()->create_course();
368         $course2 = $this->getDataGenerator()->create_course();
369         $course3 = $this->getDataGenerator()->create_course();
371         $context1 = context_course::instance($course1->id);
372         $context2 = context_course::instance($course2->id);
373         $context3 = context_course::instance($course3->id);
375         $user1 = $this->getDataGenerator()->create_user();
376         $user2 = $this->getDataGenerator()->create_user();
377         $user3 = $this->getDataGenerator()->create_user();
378         $user4 = $this->getDataGenerator()->create_user();
380         $this->assertEquals(3, $DB->count_records('enrol', array('enrol'=>'self')));
381         $instance1 = $DB->get_record('enrol', array('courseid'=>$course1->id, 'enrol'=>'self'), '*', MUST_EXIST);
382         $instance2 = $DB->get_record('enrol', array('courseid'=>$course2->id, 'enrol'=>'self'), '*', MUST_EXIST);
383         $instance3 = $DB->get_record('enrol', array('courseid'=>$course3->id, 'enrol'=>'self'), '*', MUST_EXIST);
385         $this->assertEquals($studentrole->id, $instance1->roleid);
386         $this->assertEquals($studentrole->id, $instance2->roleid);
387         $this->assertEquals($studentrole->id, $instance3->roleid);
389         $this->assertEquals(3, $DB->count_records('enrol', array('enrol'=>'manual')));
390         $maninstance1 = $DB->get_record('enrol', array('courseid'=>$course1->id, 'enrol'=>'manual'), '*', MUST_EXIST);
391         $maninstance2 = $DB->get_record('enrol', array('courseid'=>$course2->id, 'enrol'=>'manual'), '*', MUST_EXIST);
392         $maninstance3 = $DB->get_record('enrol', array('courseid'=>$course3->id, 'enrol'=>'manual'), '*', MUST_EXIST);
393         $maninstance3->roleid = $teacherrole->id;
394         $DB->update_record('enrol', $maninstance3, array('id'=>$maninstance3->id));
396         $this->assertEquals($studentrole->id, $maninstance1->roleid);
397         $this->assertEquals($studentrole->id, $maninstance2->roleid);
398         $this->assertEquals($teacherrole->id, $maninstance3->roleid);
400         $result = $this->getDataGenerator()->enrol_user($user1->id, $course1->id);
401         $this->assertTrue($result);
402         $this->assertTrue($DB->record_exists('user_enrolments', array('enrolid'=>$maninstance1->id, 'userid'=>$user1->id)));
403         $this->assertTrue($DB->record_exists('role_assignments', array('contextid'=>$context1->id, 'userid'=>$user1->id, 'roleid'=>$studentrole->id)));
405         $result = $this->getDataGenerator()->enrol_user($user1->id, $course2->id, $teacherrole->id, 'manual');
406         $this->assertTrue($result);
407         $this->assertTrue($DB->record_exists('user_enrolments', array('enrolid'=>$maninstance2->id, 'userid'=>$user1->id)));
408         $this->assertTrue($DB->record_exists('role_assignments', array('contextid'=>$context2->id, 'userid'=>$user1->id, 'roleid'=>$teacherrole->id)));
410         $result = $this->getDataGenerator()->enrol_user($user4->id, $course2->id, 'teacher', 'manual');
411         $this->assertTrue($result);
412         $this->assertTrue($DB->record_exists('user_enrolments',
413                 array('enrolid' => $maninstance2->id, 'userid' => $user4->id)));
414         $this->assertTrue($DB->record_exists('role_assignments',
415                 array('contextid' => $context2->id, 'userid' => $user4->id, 'roleid' => $teacherrole->id)));
417         $result = $this->getDataGenerator()->enrol_user($user1->id, $course3->id, 0, 'manual');
418         $this->assertTrue($result);
419         $this->assertTrue($DB->record_exists('user_enrolments', array('enrolid'=>$maninstance3->id, 'userid'=>$user1->id)));
420         $this->assertFalse($DB->record_exists('role_assignments', array('contextid'=>$context3->id, 'userid'=>$user1->id)));
422         $result = $this->getDataGenerator()->enrol_user($user2->id, $course1->id, null, 'self');
423         $this->assertTrue($result);
424         $this->assertTrue($DB->record_exists('user_enrolments', array('enrolid'=>$instance1->id, 'userid'=>$user2->id)));
425         $this->assertTrue($DB->record_exists('role_assignments', array('contextid'=>$context1->id, 'userid'=>$user2->id, 'roleid'=>$studentrole->id)));
427         $selfplugin->add_instance($course2, array('status'=>ENROL_INSTANCE_ENABLED, 'roleid'=>$teacherrole->id));
428         $result = $this->getDataGenerator()->enrol_user($user2->id, $course2->id, null, 'self');
429         $this->assertFalse($result);
431         $DB->delete_records('enrol', array('enrol'=>'self', 'courseid'=>$course3->id));
432         $result = $this->getDataGenerator()->enrol_user($user2->id, $course3->id, null, 'self');
433         $this->assertFalse($result);
434     }
436     public function test_create_grade_category() {
437         global $DB, $CFG;
438         require_once $CFG->libdir . '/grade/constants.php';
440         $this->resetAfterTest(true);
441         $generator = $this->getDataGenerator();
442         $course = $generator->create_course();
444         // Generate category and make sure number of records in DB table increases.
445         // Note we only count grade cats with depth > 1 because the course grade category
446         // is lazily created.
447         $count = $DB->count_records_select('grade_categories', 'depth <> 1');
448         $gradecategory = $generator->create_grade_category(array('courseid'=>$course->id));
449         $this->assertEquals($count+1, $DB->count_records_select('grade_categories', 'depth <> 1'));
450         $this->assertEquals(2, $gradecategory->depth);
451         $this->assertEquals($course->id, $gradecategory->courseid);
452         $this->assertEquals('Grade category 1', $gradecategory->fullname);
454         // Generate category and make sure aggregation is set.
455         $gradecategory = $generator->create_grade_category(
456                 array('courseid' => $course->id, 'aggregation' => GRADE_AGGREGATE_MEDIAN));
457         $this->assertEquals(GRADE_AGGREGATE_MEDIAN, $gradecategory->aggregation);
459         // Generate category and make sure parent is set.
460         $gradecategory2 = $generator->create_grade_category(
461                 array('courseid' => $course->id,
462                     'parent' => $gradecategory->id));
463         $this->assertEquals($gradecategory->id, $gradecategory2->parent);
464     }