weekly release 2.5dev
[moodle.git] / lib / testing / generator / data_generator.php
CommitLineData
7e7cfe7a
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/**
18 * Data generator.
19 *
20 * @package core
6b219869 21 * @category test
7e7cfe7a
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
26
27/**
6b219869 28 * Data generator class for unit tests and other tools that need to create fake test sites.
7e7cfe7a
PS
29 *
30 * @package core
6b219869 31 * @category test
7e7cfe7a
PS
32 * @copyright 2012 Petr Skoda {@link http://skodak.org}
33 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
34 */
5c3c2c81 35class testing_data_generator {
7e7cfe7a
PS
36 protected $usercounter = 0;
37 protected $categorycount = 0;
4729332b 38 protected $cohortcount = 0;
7e7cfe7a
PS
39 protected $coursecount = 0;
40 protected $scalecount = 0;
41 protected $groupcount = 0;
42 protected $groupingcount = 0;
43
a9a0cb69
MN
44 /**
45 * @var int keep track of how many forum discussions have been created.
46 */
47 protected $forumdiscussioncount = 0;
48
49 /**
50 * @var int keep track of how many forum posts have been created.
51 */
52 protected $forumpostcount = 0;
53
7e7cfe7a
PS
54 /** @var array list of plugin generators */
55 protected $generators = array();
56
57 /** @var array lis of common last names */
58 public $lastnames = array(
59 'Smith', 'Johnson', 'Williams', 'Brown', 'Jones', 'Miller', 'Davis', 'García', 'Rodríguez', 'Wilson',
60 'Müller', 'Schmidt', 'Schneider', 'Fischer', 'Meyer', 'Weber', 'Schulz', 'Wagner', 'Becker', 'Hoffmann',
61 'Novák', 'Svoboda', 'Novotný', 'Dvořák', 'Černý', 'Procházková', 'Kučerová', 'Veselá', 'Horáková', 'Němcová',
62 'Смирнов', 'Иванов', 'Кузнецов', 'Соколов', 'Попов', 'Лебедева', 'Козлова', 'Новикова', 'Морозова', 'Петрова',
63 '王', '李', '张', '刘', '陈', '楊', '黃', '趙', '吳', '周',
64 '佐藤', '鈴木', '高橋', '田中', '渡辺', '伊藤', '山本', '中村', '小林', '斎藤',
65 );
66
67 /** @var array lis of common first names */
68 public $firstnames = array(
69 'Jacob', 'Ethan', 'Michael', 'Jayden', 'William', 'Isabella', 'Sophia', 'Emma', 'Olivia', 'Ava',
70 'Lukas', 'Leon', 'Luca', 'Timm', 'Paul', 'Leonie', 'Leah', 'Lena', 'Hanna', 'Laura',
71 'Jakub', 'Jan', 'Tomáš', 'Lukáš', 'Matěj', 'Tereza', 'Eliška', 'Anna', 'Adéla', 'Karolína',
72 'Даниил', 'Максим', 'Артем', 'Иван', 'Александр', 'София', 'Анастасия', 'Дарья', 'Мария', 'Полина',
73 '伟', '伟', '芳', '伟', '秀英', '秀英', '娜', '秀英', '伟', '敏',
74 '翔', '大翔', '拓海', '翔太', '颯太', '陽菜', 'さくら', '美咲', '葵', '美羽',
75 );
76
77 public $loremipsum = <<<EOD
78Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nulla non arcu lacinia neque faucibus fringilla. Vivamus porttitor turpis ac leo. Integer in sapien. Nullam eget nisl. Aliquam erat volutpat. Cras elementum. Mauris suscipit, ligula sit amet pharetra semper, nibh ante cursus purus, vel sagittis velit mauris vel metus. Integer malesuada. Nullam lectus justo, vulputate eget mollis sed, tempor sed magna. Mauris elementum mauris vitae tortor. Aliquam erat volutpat.
79Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Pellentesque ipsum. Cras pede libero, dapibus nec, pretium sit amet, tempor quis. Aliquam ante. Proin in tellus sit amet nibh dignissim sagittis. Vivamus porttitor turpis ac leo. Duis bibendum, lectus ut viverra rhoncus, dolor nunc faucibus libero, eget facilisis enim ipsum id lacus. In sem justo, commodo ut, suscipit at, pharetra vitae, orci. Aliquam erat volutpat. Nulla est.
80Vivamus luctus egestas leo. Aenean fermentum risus id tortor. Mauris dictum facilisis augue. Aliquam erat volutpat. Aliquam ornare wisi eu metus. Aliquam id dolor. Duis condimentum augue id magna semper rutrum. Donec iaculis gravida nulla. Pellentesque ipsum. Etiam dictum tincidunt diam. Quisque tincidunt scelerisque libero. Etiam egestas wisi a erat.
81Integer lacinia. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Mauris tincidunt sem sed arcu. Nullam feugiat, turpis at pulvinar vulputate, erat libero tristique tellus, nec bibendum odio risus sit amet ante. Aliquam id dolor. Maecenas sollicitudin. Et harum quidem rerum facilis est et expedita distinctio. Mauris suscipit, ligula sit amet pharetra semper, nibh ante cursus purus, vel sagittis velit mauris vel metus. Nullam dapibus fermentum ipsum. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Pellentesque sapien. Duis risus. Mauris elementum mauris vitae tortor. Suspendisse nisl. Integer rutrum, orci vestibulum ullamcorper ultricies, lacus quam ultricies odio, vitae placerat pede sem sit amet enim.
82In laoreet, magna id viverra tincidunt, sem odio bibendum justo, vel imperdiet sapien wisi sed libero. Proin pede metus, vulputate nec, fermentum fringilla, vehicula vitae, justo. Nullam justo enim, consectetuer nec, ullamcorper ac, vestibulum in, elit. Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur? Maecenas lorem. Etiam posuere lacus quis dolor. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Curabitur ligula sapien, pulvinar a vestibulum quis, facilisis vel sapien. Nam sed tellus id magna elementum tincidunt. Suspendisse nisl. Vivamus luctus egestas leo. Nulla non arcu lacinia neque faucibus fringilla. Etiam dui sem, fermentum vitae, sagittis id, malesuada in, quam. Etiam dictum tincidunt diam. Etiam commodo dui eget wisi. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Proin pede metus, vulputate nec, fermentum fringilla, vehicula vitae, justo. Duis ante orci, molestie vitae vehicula venenatis, tincidunt ac pede. Pellentesque sapien.
83EOD;
84
85 /**
86 * To be called from data reset code only,
87 * do not use in tests.
88 * @return void
89 */
90 public function reset() {
91 $this->usercounter = 0;
92 $this->categorycount = 0;
93 $this->coursecount = 0;
94 $this->scalecount = 0;
a9a0cb69
MN
95 $this->forumdiscussioncount = 0;
96 $this->forumpostcount = 0;
7e7cfe7a 97
5c3c2c81 98 foreach ($this->generators as $generator) {
7e7cfe7a
PS
99 $generator->reset();
100 }
101 }
102
103 /**
104 * Return generator for given plugin
105 * @param string $component
106 * @return mixed plugin data generator
107 */
108 public function get_plugin_generator($component) {
109 list($type, $plugin) = normalize_component($component);
110
111 if ($type !== 'mod' and $type !== 'block') {
112 throw new coding_exception("Plugin type $type does not support generators yet");
113 }
114
115 $dir = get_plugin_directory($type, $plugin);
116
117 if (!isset($this->generators[$type.'_'.$plugin])) {
118 $lib = "$dir/tests/generator/lib.php";
119 if (!include_once($lib)) {
120 throw new coding_exception("Plugin $component does not support data generator, missing tests/generator/lib");
121 }
122 $classname = $type.'_'.$plugin.'_generator';
123 $this->generators[$type.'_'.$plugin] = new $classname($this);
124 }
125
126 return $this->generators[$type.'_'.$plugin];
127 }
128
129 /**
130 * Create a test user
131 * @param array|stdClass $record
132 * @param array $options
133 * @return stdClass user record
134 */
135 public function create_user($record=null, array $options=null) {
136 global $DB, $CFG;
137
138 $this->usercounter++;
139 $i = $this->usercounter;
140
141 $record = (array)$record;
142
143 if (!isset($record['auth'])) {
144 $record['auth'] = 'manual';
145 }
146
147 if (!isset($record['firstname']) and !isset($record['lastname'])) {
148 $country = rand(0, 5);
149 $firstname = rand(0, 4);
150 $lastname = rand(0, 4);
151 $female = rand(0, 1);
152 $record['firstname'] = $this->firstnames[($country*10) + $firstname + ($female*5)];
153 $record['lastname'] = $this->lastnames[($country*10) + $lastname + ($female*5)];
154
155 } else if (!isset($record['firstname'])) {
156 $record['firstname'] = 'Firstname'.$i;
157
158 } else if (!isset($record['lastname'])) {
159 $record['lastname'] = 'Lastname'.$i;
160 }
161
162 if (!isset($record['idnumber'])) {
163 $record['idnumber'] = '';
164 }
165
166 if (!isset($record['mnethostid'])) {
167 $record['mnethostid'] = $CFG->mnet_localhost_id;
168 }
169
170 if (!isset($record['username'])) {
fe67134e
PS
171 $record['username'] = 'username'.$i;
172 $j = 2;
7e7cfe7a 173 while ($DB->record_exists('user', array('username'=>$record['username'], 'mnethostid'=>$record['mnethostid']))) {
fe67134e
PS
174 $record['username'] = 'username'.$i.'_'.$j;
175 $j++;
7e7cfe7a
PS
176 }
177 }
178
dbf60a04
PS
179 if (isset($record['password'])) {
180 $record['password'] = hash_internal_user_password($record['password']);
181 } else {
182 // The auth plugin may not fully support this,
183 // but it is still better/faster than hashing random stuff.
184 $record['password'] = AUTH_PASSWORD_NOT_CACHED;
7e7cfe7a
PS
185 }
186
187 if (!isset($record['email'])) {
188 $record['email'] = $record['username'].'@example.com';
189 }
190
191 if (!isset($record['confirmed'])) {
192 $record['confirmed'] = 1;
193 }
194
195 if (!isset($record['lang'])) {
196 $record['lang'] = 'en';
197 }
198
199 if (!isset($record['maildisplay'])) {
200 $record['maildisplay'] = 1;
201 }
202
203 if (!isset($record['deleted'])) {
204 $record['deleted'] = 0;
205 }
206
207 $record['timecreated'] = time();
208 $record['timemodified'] = $record['timecreated'];
209 $record['lastip'] = '0.0.0.0';
210
7e7cfe7a
PS
211 if ($record['deleted']) {
212 $delname = $record['email'].'.'.time();
213 while ($DB->record_exists('user', array('username'=>$delname))) {
214 $delname++;
215 }
216 $record['idnumber'] = '';
217 $record['email'] = md5($record['username']);
218 $record['username'] = $delname;
219 $record['picture'] = 0;
220 }
221
222 $userid = $DB->insert_record('user', $record);
223
224 if (!$record['deleted']) {
225 context_user::instance($userid);
226 }
227
228 return $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
229 }
230
231 /**
232 * Create a test course category
233 * @param array|stdClass $record
234 * @param array $options
235 * @return stdClass course category record
236 */
4729332b 237 public function create_category($record=null, array $options=null) {
7e7cfe7a
PS
238 global $DB, $CFG;
239 require_once("$CFG->dirroot/course/lib.php");
240
241 $this->categorycount++;
242 $i = $this->categorycount;
243
244 $record = (array)$record;
245
246 if (!isset($record['name'])) {
247 $record['name'] = 'Course category '.$i;
248 }
249
250 if (!isset($record['idnumber'])) {
251 $record['idnumber'] = '';
252 }
253
254 if (!isset($record['description'])) {
255 $record['description'] = "Test course category $i\n$this->loremipsum";
256 }
257
258 if (!isset($record['descriptionformat'])) {
4a38e659 259 $record['descriptionformat'] = FORMAT_MOODLE;
7e7cfe7a
PS
260 }
261
262 if (!isset($record['parent'])) {
4a38e659 263 $record['parent'] = 0;
7e7cfe7a
PS
264 }
265
266 if (empty($record['parent'])) {
267 $parent = new stdClass();
268 $parent->path = '';
269 $parent->depth = 0;
270 } else {
271 $parent = $DB->get_record('course_categories', array('id'=>$record['parent']), '*', MUST_EXIST);
272 }
273 $record['depth'] = $parent->depth+1;
274
275 $record['sortorder'] = 0;
276 $record['timemodified'] = time();
277 $record['timecreated'] = $record['timemodified'];
278
279 $catid = $DB->insert_record('course_categories', $record);
280 $path = $parent->path . '/' . $catid;
281 $DB->set_field('course_categories', 'path', $path, array('id'=>$catid));
282 context_coursecat::instance($catid);
283
284 fix_course_sortorder();
285
286 return $DB->get_record('course_categories', array('id'=>$catid), '*', MUST_EXIST);
287 }
288
4729332b
PS
289 /**
290 * Create test cohort.
291 * @param array|stdClass $record
292 * @param array $options
293 * @return stdClass cohort record
294 */
295 public function create_cohort($record=null, array $options=null) {
296 global $DB, $CFG;
297 require_once("$CFG->dirroot/cohort/lib.php");
298
299 $this->cohortcount++;
300 $i = $this->cohortcount;
301
302 $record = (array)$record;
303
304 if (!isset($record['contextid'])) {
305 $record['contextid'] = context_system::instance()->id;
306 }
307
308 if (!isset($record['name'])) {
309 $record['name'] = 'Cohort '.$i;
310 }
311
312 if (!isset($record['idnumber'])) {
313 $record['idnumber'] = '';
314 }
315
316 if (!isset($record['description'])) {
317 $record['description'] = "Test cohort $i\n$this->loremipsum";
318 }
319
320 if (!isset($record['descriptionformat'])) {
321 $record['descriptionformat'] = FORMAT_MOODLE;
322 }
323
324 if (!isset($record['component'])) {
325 $record['component'] = '';
326 }
327
328 $id = cohort_add_cohort((object)$record);
329
330 return $DB->get_record('cohort', array('id'=>$id), '*', MUST_EXIST);
331 }
332
7e7cfe7a
PS
333 /**
334 * Create a test course
335 * @param array|stdClass $record
336 * @param array $options with keys:
337 * 'createsections'=>bool precreate all sections
338 * @return stdClass course record
339 */
4729332b 340 public function create_course($record=null, array $options=null) {
7e7cfe7a
PS
341 global $DB, $CFG;
342 require_once("$CFG->dirroot/course/lib.php");
343
344 $this->coursecount++;
345 $i = $this->coursecount;
346
347 $record = (array)$record;
348
349 if (!isset($record['fullname'])) {
350 $record['fullname'] = 'Test course '.$i;
351 }
352
353 if (!isset($record['shortname'])) {
354 $record['shortname'] = 'tc_'.$i;
355 }
356
357 if (!isset($record['idnumber'])) {
358 $record['idnumber'] = '';
359 }
360
361 if (!isset($record['format'])) {
362 $record['format'] = 'topics';
363 }
364
365 if (!isset($record['newsitems'])) {
366 $record['newsitems'] = 0;
367 }
368
369 if (!isset($record['numsections'])) {
370 $record['numsections'] = 5;
371 }
372
4a38e659
PS
373 if (!isset($record['summary'])) {
374 $record['summary'] = "Test course $i\n$this->loremipsum";
7e7cfe7a
PS
375 }
376
4a38e659
PS
377 if (!isset($record['summaryformat'])) {
378 $record['summaryformat'] = FORMAT_MOODLE;
7e7cfe7a
PS
379 }
380
381 if (!isset($record['category'])) {
382 $record['category'] = $DB->get_field_select('course_categories', "MIN(id)", "parent=0");
383 }
384
385 $course = create_course((object)$record);
386 context_course::instance($course->id);
7e7cfe7a 387 if (!empty($options['createsections'])) {
384c3510
MG
388 if (isset($course->numsections)) {
389 course_create_sections_if_missing($course, range(0, $course->numsections));
390 } else {
391 course_create_sections_if_missing($course, 0);
7e7cfe7a
PS
392 }
393 }
394
395 return $course;
396 }
397
398 /**
399 * Create course section if does not exist yet
384c3510 400 * @param array|stdClass $record must contain 'course' and 'section' attributes
7e7cfe7a
PS
401 * @param array|null $options
402 * @return stdClass
403 * @throws coding_exception
404 */
405 public function create_course_section($record = null, array $options = null) {
406 global $DB;
407
408 $record = (array)$record;
409
410 if (empty($record['course'])) {
5c3c2c81 411 throw new coding_exception('course must be present in testing_data_generator::create_course_section() $record');
7e7cfe7a
PS
412 }
413
414 if (!isset($record['section'])) {
5c3c2c81 415 throw new coding_exception('section must be present in testing_data_generator::create_course_section() $record');
7e7cfe7a
PS
416 }
417
b46be6ad
MG
418 course_create_sections_if_missing($record['course'], $record['section']);
419 return get_fast_modinfo($record['course'])->get_section_info($record['section']);
7e7cfe7a
PS
420 }
421
422 /**
423 * Create a test block
424 * @param string $blockname
425 * @param array|stdClass $record
426 * @param array $options
427 * @return stdClass block instance record
428 */
429 public function create_block($blockname, $record=null, array $options=null) {
430 $generator = $this->get_plugin_generator('block_'.$blockname);
431 return $generator->create_instance($record, $options);
432 }
433
434 /**
435 * Create a test module
436 * @param string $modulename
437 * @param array|stdClass $record
438 * @param array $options
439 * @return stdClass activity record
440 */
441 public function create_module($modulename, $record=null, array $options=null) {
442 $generator = $this->get_plugin_generator('mod_'.$modulename);
443 return $generator->create_instance($record, $options);
444 }
445
446 /**
447 * Create a test group for the specified course
448 *
449 * $record should be either an array or a stdClass containing infomation about the group to create.
450 * At the very least it needs to contain courseid.
451 * Default values are added for name, description, and descriptionformat if they are not present.
452 *
6b219869
DM
453 * This function calls groups_create_group() to create the group within the database.
454 * @see groups_create_group
7e7cfe7a
PS
455 * @param array|stdClass $record
456 * @return stdClass group record
457 */
458 public function create_group($record) {
459 global $DB, $CFG;
460
461 require_once($CFG->dirroot . '/group/lib.php');
462
463 $this->groupcount++;
464 $i = $this->groupcount;
465
466 $record = (array)$record;
467
468 if (empty($record['courseid'])) {
5c3c2c81 469 throw new coding_exception('courseid must be present in testing_data_generator::create_group() $record');
7e7cfe7a
PS
470 }
471
472 if (!isset($record['name'])) {
473 $record['name'] = 'group-' . $i;
474 }
475
476 if (!isset($record['description'])) {
477 $record['description'] = "Test Group $i\n{$this->loremipsum}";
478 }
479
480 if (!isset($record['descriptionformat'])) {
481 $record['descriptionformat'] = FORMAT_MOODLE;
482 }
483
484 $id = groups_create_group((object)$record);
485
486 return $DB->get_record('groups', array('id'=>$id));
487 }
488
87bb583c
DM
489 /**
490 * Create a test group member
491 * @param array|stdClass $record
492 * @throws coding_exception
493 * @return boolean
494 */
495 public function create_group_member($record) {
496 global $DB, $CFG;
497
498 require_once($CFG->dirroot . '/group/lib.php');
499
500 $record = (array)$record;
501
502 if (empty($record['userid'])) {
503 throw new coding_exception('user must be present in testing_util::create_group_member() $record');
504 }
505
506 if (!isset($record['groupid'])) {
507 throw new coding_exception('group must be present in testing_util::create_group_member() $record');
508 }
509
510 if (!isset($record['component'])) {
511 $record['component'] = null;
512 }
513 if (!isset($record['itemid'])) {
514 $record['itemid'] = 0;
515 }
516
517 return groups_add_member($record['groupid'], $record['userid'], $record['component'], $record['itemid']);
518 }
519
7e7cfe7a
PS
520 /**
521 * Create a test grouping for the specified course
522 *
523 * $record should be either an array or a stdClass containing infomation about the grouping to create.
524 * At the very least it needs to contain courseid.
525 * Default values are added for name, description, and descriptionformat if they are not present.
526 *
6b219869
DM
527 * This function calls groups_create_grouping() to create the grouping within the database.
528 * @see groups_create_grouping
7e7cfe7a
PS
529 * @param array|stdClass $record
530 * @return stdClass grouping record
531 */
532 public function create_grouping($record) {
533 global $DB, $CFG;
534
535 require_once($CFG->dirroot . '/group/lib.php');
536
537 $this->groupingcount++;
538 $i = $this->groupingcount;
539
540 $record = (array)$record;
541
542 if (empty($record['courseid'])) {
5c3c2c81 543 throw new coding_exception('courseid must be present in testing_data_generator::create_grouping() $record');
7e7cfe7a
PS
544 }
545
546 if (!isset($record['name'])) {
547 $record['name'] = 'grouping-' . $i;
548 }
549
550 if (!isset($record['description'])) {
551 $record['description'] = "Test Grouping $i\n{$this->loremipsum}";
552 }
553
554 if (!isset($record['descriptionformat'])) {
555 $record['descriptionformat'] = FORMAT_MOODLE;
556 }
557
558 $id = groups_create_grouping((object)$record);
559
560 return $DB->get_record('groupings', array('id'=>$id));
561 }
562
87bb583c
DM
563 /**
564 * Create a test grouping group
565 * @param array|stdClass $record
566 * @throws coding_exception
567 * @return boolean
568 */
569 public function create_grouping_group($record) {
570 global $DB, $CFG;
571
572 require_once($CFG->dirroot . '/group/lib.php');
573
574 $record = (array)$record;
575
576 if (empty($record['groupingid'])) {
577 throw new coding_exception('grouping must be present in testing::create_grouping_group() $record');
578 }
579
580 if (!isset($record['groupid'])) {
581 throw new coding_exception('group must be present in testing_util::create_grouping_group() $record');
582 }
583
584 return groups_assign_grouping($record['groupingid'], $record['groupid']);
585 }
586
7e7cfe7a
PS
587 /**
588 * Create a test scale
589 * @param array|stdClass $record
590 * @param array $options
591 * @return stdClass block instance record
592 */
593 public function create_scale($record=null, array $options=null) {
594 global $DB;
595
596 $this->scalecount++;
597 $i = $this->scalecount;
598
599 $record = (array)$record;
600
601 if (!isset($record['name'])) {
602 $record['name'] = 'Test scale '.$i;
603 }
604
605 if (!isset($record['scale'])) {
606 $record['scale'] = 'A,B,C,D,F';
607 }
608
609 if (!isset($record['courseid'])) {
610 $record['courseid'] = 0;
611 }
612
613 if (!isset($record['userid'])) {
614 $record['userid'] = 0;
615 }
616
617 if (!isset($record['description'])) {
618 $record['description'] = 'Test scale description '.$i;
619 }
620
621 if (!isset($record['descriptionformat'])) {
622 $record['descriptionformat'] = FORMAT_MOODLE;
623 }
624
625 $record['timemodified'] = time();
626
627 if (isset($record['id'])) {
628 $DB->import_record('scale', $record);
629 $DB->get_manager()->reset_sequence('scale');
630 $id = $record['id'];
631 } else {
632 $id = $DB->insert_record('scale', $record);
633 }
634
635 return $DB->get_record('scale', array('id'=>$id), '*', MUST_EXIST);
636 }
4f5789ea
PS
637
638 /**
639 * Simplified enrolment of user to course using default options.
640 *
641 * It is strongly recommended to use only this method for 'manual' and 'self' plugins only!!!
642 *
643 * @param int $userid
644 * @param int $courseid
645 * @param int $roleid optional role id, use only with manual plugin
646 * @param string $enrol name of enrol plugin,
647 * there must be exactly one instance in course,
648 * it must support enrol_user() method.
649 * @return bool success
650 */
651 public function enrol_user($userid, $courseid, $roleid = null, $enrol = 'manual') {
652 global $DB;
653
654 if (!$plugin = enrol_get_plugin($enrol)) {
655 return false;
656 }
657
658 $instances = $DB->get_records('enrol', array('courseid'=>$courseid, 'enrol'=>$enrol));
659 if (count($instances) != 1) {
660 return false;
661 }
662 $instance = reset($instances);
663
664 if (is_null($roleid) and $instance->roleid) {
665 $roleid = $instance->roleid;
666 }
667
668 $plugin->enrol_user($instance, $userid, $roleid);
669
670 return true;
671 }
a9a0cb69
MN
672
673 /**
674 * Function to create a dummy discussion.
675 *
676 * @param array|stdClass $record
677 * @return stdClass the discussion object
678 */
679 public function create_forum_discussion($record = null) {
680 global $DB;
681
682 // Increment the forum discussion count.
683 $this->forumdiscussioncount++;
684
685 $record = (array) $record;
686
687 if (!isset($record['course'])) {
688 throw new coding_exception('course must be present in phpunit_util::create_forum_discussion() $record');
689 }
690
691 if (!isset($record['forum'])) {
692 throw new coding_exception('forum must be present in phpunit_util::create_forum_discussion() $record');
693 }
694
695 if (!isset($record['userid'])) {
696 throw new coding_exception('userid must be present in phpunit_util::create_forum_discussion() $record');
697 }
698
699 if (!isset($record['name'])) {
700 $record['name'] = "Discussion " . $this->forumdiscussioncount;
701 }
702
703 if (!isset($record['subject'])) {
704 $record['subject'] = "Subject for discussion " . $this->forumdiscussioncount;
705 }
706
707 if (!isset($record['message'])) {
708 $record['message'] = html_writer::tag('p', 'Message for discussion ' . $this->forumdiscussioncount);
709 }
710
711 if (!isset($record['messageformat'])) {
712 $record['messageformat'] = editors_get_preferred_format();
713 }
714
715 if (!isset($record['messagetrust'])) {
716 $record['messagetrust'] = "";
717 }
718
719 if (!isset($record['assessed'])) {
720 $record['assessed'] = '1';
721 }
722
723 if (!isset($record['groupid'])) {
724 $record['groupid'] = "-1";
725 }
726
727 if (!isset($record['timestart'])) {
728 $record['timestart'] = "0";
729 }
730
731 if (!isset($record['timeend'])) {
732 $record['timeend'] = "0";
733 }
734
735 if (!isset($record['mailnow'])) {
736 $record['mailnow'] = "0";
737 }
738
739 $record = (object) $record;
740
741 // Add the discussion.
742 $record->id = forum_add_discussion($record, null, null, $record->userid);
743
744 return $record;
745 }
746
747 /**
748 * Function to create a dummy post.
749 *
750 * @param array|stdClass $record
751 * @return stdClass the post object
752 */
753 public function create_forum_post($record = null) {
754 global $DB;
755
756 // Increment the forum post count.
757 $this->forumpostcount++;
758
759 // Variable to store time.
760 $time = time() + $this->forumpostcount;
761
762 $record = (array) $record;
763
764 if (!isset($record['discussion'])) {
765 throw new coding_exception('discussion must be present in phpunit_util::create_forum_post() $record');
766 }
767
768 if (!isset($record['userid'])) {
769 throw new coding_exception('userid must be present in phpunit_util::create_forum_post() $record');
770 }
771
772 if (!isset($record['parent'])) {
773 $record['parent'] = 0;
774 }
775
776 if (!isset($record['subject'])) {
777 $record['subject'] = 'Forum post subject ' . $this->forumpostcount;
778 }
779
780 if (!isset($record['message'])) {
781 $record['message'] = html_writer::tag('p', 'Forum message post ' . $this->forumpostcount);
782 }
783
784 if (!isset($record['created'])) {
785 $record['created'] = $time;
786 }
787
788 if (!isset($record['modified'])) {
789 $record['modified'] = $time;
790 }
791
792 $record = (object) $record;
793
794 // Add the post.
795 $record->id = $DB->insert_record('forum_posts', $record);
796
797 // Update the last post.
798 forum_discussion_update_last_post($record->discussion);
799
800 return $record;
801 }
7e7cfe7a 802}
6b219869
DM
803
804/**
805 * Deprecated in favour of testing_data_generator
806 *
807 * @deprecated since Moodle 2.5 MDL-37457 - please do not use this function any more.
808 * @todo MDL-37517 This will be deleted in Moodle 2.7
809 * @see testing_data_generator
810 * @package core
811 * @category test
812 * @copyright 2012 David Monllaó
813 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
814 */
815class phpunit_data_generator extends testing_data_generator {
816
817 /**
818 * Dumb constructor to throw the deprecated notification
819 */
820 public function __construct() {
821 debugging('Class phpunit_data_generator is deprecated, please use class testing_module_generator instead', DEBUG_DEVELOPER);
822 }
823}