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