weekly release 3.8dev
[moodle.git] / lib / tests / behat / behat_data_generators.php
CommitLineData
f0200d14 1<?php
f0200d14
DM
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 generators for acceptance testing.
19 *
20 * @package core
21 * @category test
22 * @copyright 2012 David MonllaĆ³
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 */
25
26// NOTE: no MOODLE_INTERNAL test here, this file may be required by behat before including /config.php.
27
28require_once(__DIR__ . '/../../behat/behat_base.php');
f0200d14
DM
29
30use Behat\Gherkin\Node\TableNode as TableNode;
134494e0 31use Behat\Behat\Tester\Exception\PendingException as PendingException;
f0200d14
DM
32
33/**
34 * Class to set up quickly a Given environment.
35 *
36 * Acceptance tests are block-boxed, so this steps definitions should only
37 * be used to set up the test environment as we are not replicating user steps.
38 *
d2eca4cd 39 * All data generators should be in lib/testing/generator/*, shared between phpunit
f0200d14 40 * and behat and they should be called from here, if possible using the standard
d2eca4cd
DM
41 * 'create_$elementname($options)' and if it's not possible (data generators arguments will not be
42 * always the same) or the element is not suitable to be a data generator, create a
43 * 'process_$elementname($options)' method and use the data generator from there if possible.
f0200d14
DM
44 *
45 * @todo If the available elements list grows too much this class must be split into smaller pieces
46 * @package core
47 * @category test
48 * @copyright 2012 David MonllaĆ³
49 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
50 */
51class behat_data_generators extends behat_base {
52
46ac40cd
DM
53 /**
54 * @var testing_data_generator
55 */
f0200d14
DM
56 protected $datagenerator;
57
58 /**
59 * Each element specifies:
60 * - The data generator sufix used.
61 * - The required fields.
62 * - The mapping between other elements references and database field names.
63 * @var array
64 */
65 protected static $elements = array(
66 'users' => array(
67 'datagenerator' => 'user',
68 'required' => array('username')
69 ),
70 'categories' => array(
71 'datagenerator' => 'category',
72 'required' => array('idnumber'),
73 'switchids' => array('category' => 'parent')
74 ),
75 'courses' => array(
76 'datagenerator' => 'course',
77 'required' => array('shortname'),
78 'switchids' => array('category' => 'category')
79 ),
80 'groups' => array(
81 'datagenerator' => 'group',
82 'required' => array('idnumber', 'course'),
83 'switchids' => array('course' => 'courseid')
84 ),
85 'groupings' => array(
86 'datagenerator' => 'grouping',
87 'required' => array('idnumber', 'course'),
88 'switchids' => array('course' => 'courseid')
89 ),
90 'course enrolments' => array(
91 'datagenerator' => 'enrol_user',
92 'required' => array('user', 'course', 'role'),
93 'switchids' => array('user' => 'userid', 'course' => 'courseid', 'role' => 'roleid')
f0200d14 94 ),
01c10959
DNA
95 'custom field categories' => array(
96 'datagenerator' => 'custom_field_category',
97 'required' => array('name', 'component', 'area', 'itemid'),
98 'switchids' => array()
99 ),
100 'custom fields' => array(
101 'datagenerator' => 'custom_field',
102 'required' => array('name', 'category', 'type', 'shortname'),
103 'switchids' => array()
104 ),
81cd8572
DM
105 'permission overrides' => array(
106 'datagenerator' => 'permission_override',
107 'required' => array('capability', 'permission', 'role', 'contextlevel', 'reference'),
108 'switchids' => array('role' => 'roleid')
109 ),
d2eca4cd 110 'system role assigns' => array(
72ddc05f 111 'datagenerator' => 'system_role_assign',
d2eca4cd
DM
112 'required' => array('user', 'role'),
113 'switchids' => array('user' => 'userid', 'role' => 'roleid')
114 ),
72ddc05f
DM
115 'role assigns' => array(
116 'datagenerator' => 'role_assign',
117 'required' => array('user', 'role', 'contextlevel', 'reference'),
118 'switchids' => array('user' => 'userid', 'role' => 'roleid')
119 ),
a0902967
DM
120 'activities' => array(
121 'datagenerator' => 'activity',
122 'required' => array('activity', 'idnumber', 'course'),
e2b0e62f 123 'switchids' => array('course' => 'course', 'gradecategory' => 'gradecat', 'grouping' => 'groupingid')
a0902967 124 ),
eb3884e4
TH
125 'blocks' => array(
126 'datagenerator' => 'block_instance',
127 'required' => array('blockname', 'contextlevel', 'reference'),
128 ),
f0200d14
DM
129 'group members' => array(
130 'datagenerator' => 'group_member',
131 'required' => array('user', 'group'),
132 'switchids' => array('user' => 'userid', 'group' => 'groupid')
133 ),
134 'grouping groups' => array(
135 'datagenerator' => 'grouping_group',
136 'required' => array('grouping', 'group'),
137 'switchids' => array('grouping' => 'groupingid', 'group' => 'groupid')
23349a73
DM
138 ),
139 'cohorts' => array(
140 'datagenerator' => 'cohort',
141 'required' => array('idnumber')
702851c0 142 ),
9cc66e86
MG
143 'cohort members' => array(
144 'datagenerator' => 'cohort_member',
145 'required' => array('user', 'cohort'),
146 'switchids' => array('user' => 'userid', 'cohort' => 'cohortid')
147 ),
702851c0
DM
148 'roles' => array(
149 'datagenerator' => 'role',
150 'required' => array('shortname')
15ace204
DW
151 ),
152 'grade categories' => array(
153 'datagenerator' => 'grade_category',
154 'required' => array('fullname', 'course'),
155 'switchids' => array('course' => 'courseid', 'gradecategory' => 'parent')
cfa91962
JO
156 ),
157 'grade items' => array(
158 'datagenerator' => 'grade_item',
159 'required' => array('course'),
160 'switchids' => array('scale' => 'scaleid', 'outcome' => 'outcomeid', 'course' => 'courseid',
161 'gradecategory' => 'categoryid')
162 ),
163 'grade outcomes' => array(
164 'datagenerator' => 'grade_outcome',
165 'required' => array('shortname', 'scale'),
166 'switchids' => array('course' => 'courseid', 'gradecategory' => 'categoryid', 'scale' => 'scaleid')
167 ),
168 'scales' => array(
169 'datagenerator' => 'scale',
170 'required' => array('name', 'scale'),
171 'switchids' => array('course' => 'courseid')
0db16e08
TH
172 ),
173 'question categories' => array(
174 'datagenerator' => 'question_category',
175 'required' => array('name', 'contextlevel', 'reference'),
834cc0ed 176 'switchids' => array('questioncategory' => 'parent')
0db16e08
TH
177 ),
178 'questions' => array(
179 'datagenerator' => 'question',
180 'required' => array('qtype', 'questioncategory', 'name'),
181 'switchids' => array('questioncategory' => 'category', 'user' => 'createdby')
182 ),
9a7e3986
MG
183 'tags' => array(
184 'datagenerator' => 'tag',
185 'required' => array('name')
186 ),
fb3c0fc3
AN
187 'events' => array(
188 'datagenerator' => 'event',
189 'required' => array('name', 'eventtype'),
190 'switchids' => array(
191 'user' => 'userid',
192 'course' => 'courseid',
193 'category' => 'categoryid',
194 )
195 ),
029a3e73 196 'message contacts' => array(
197 'datagenerator' => 'message_contacts',
198 'required' => array('user', 'contact'),
199 'switchids' => array('user' => 'userid', 'contact' => 'contactid')
200 ),
173be485
AA
201 'private messages' => array(
202 'datagenerator' => 'private_messages',
203 'required' => array('user', 'contact', 'message'),
204 'switchids' => array('user' => 'userid', 'contact' => 'contactid')
205 ),
206 'favourite conversations' => array(
207 'datagenerator' => 'favourite_conversations',
208 'required' => array('user', 'contact'),
209 'switchids' => array('user' => 'userid', 'contact' => 'contactid')
210 ),
8922d78b
AA
211 'group messages' => array(
212 'datagenerator' => 'group_messages',
213 'required' => array('user', 'group', 'message'),
214 'switchids' => array('user' => 'userid', 'group' => 'groupid')
215 ),
f0e8f0a5
AA
216 'muted group conversations' => array(
217 'datagenerator' => 'mute_group_conversations',
218 'required' => array('user', 'group', 'course'),
219 'switchids' => array('user' => 'userid', 'group' => 'groupid', 'course' => 'courseid')
220 ),
221 'muted private conversations' => array(
222 'datagenerator' => 'mute_private_conversations',
223 'required' => array('user', 'contact'),
224 'switchids' => array('user' => 'userid', 'contact' => 'contactid')
225 ),
4d0ac716
SR
226 'language customisations' => array(
227 'datagenerator' => 'customlang',
228 'required' => array('component', 'stringid', 'value'),
229 ),
a9e58c14
VDF
230 'analytics model' => array (
231 'datagenerator' => 'analytics_model',
232 'required' => array('target', 'indicators', 'timesplitting', 'enabled'),
233 ),
f0200d14
DM
234 );
235
236 /**
d1ac356a
TH
237 * Creates the specified element.
238 *
239 * The most reliable list of what types of thing can be created is the
240 * $elements array defined above.
f0200d14 241 *
c51c3b55 242 * @Given /^the following "(?P<element_string>(?:[^"]|\\")*)" exist:$/
f0200d14
DM
243 *
244 * @throws Exception
245 * @throws PendingException
246 * @param string $elementname The name of the entity to add
247 * @param TableNode $data
248 */
c51c3b55 249 public function the_following_exist($elementname, TableNode $data) {
f0200d14 250
c29e3e24
DM
251 // Now that we need them require the data generators.
252 require_once(__DIR__ . '/../../testing/generator/lib.php');
253
f0200d14
DM
254 if (empty(self::$elements[$elementname])) {
255 throw new PendingException($elementname . ' data generator is not implemented');
256 }
257
258 $this->datagenerator = testing_util::get_data_generator();
259
260 $elementdatagenerator = self::$elements[$elementname]['datagenerator'];
261 $requiredfields = self::$elements[$elementname]['required'];
262 if (!empty(self::$elements[$elementname]['switchids'])) {
263 $switchids = self::$elements[$elementname]['switchids'];
264 }
265
266 foreach ($data->getHash() as $elementdata) {
267
268 // Check if all the required fields are there.
269 foreach ($requiredfields as $requiredfield) {
270 if (!isset($elementdata[$requiredfield])) {
271 throw new Exception($elementname . ' requires the field ' . $requiredfield . ' to be specified');
272 }
273 }
274
275 // Switch from human-friendly references to ids.
276 if (isset($switchids)) {
277 foreach ($switchids as $element => $field) {
278 $methodname = 'get_' . $element . '_id';
279
280 // Not all the switch fields are required, default vars will be assigned by data generators.
48a3a50a 281 if (isset($elementdata[$element])) {
f0200d14
DM
282 // Temp $id var to avoid problems when $element == $field.
283 $id = $this->{$methodname}($elementdata[$element]);
284 unset($elementdata[$element]);
285 $elementdata[$field] = $id;
286 }
287 }
288 }
289
290 // Preprocess the entities that requires a special treatment.
291 if (method_exists($this, 'preprocess_' . $elementdatagenerator)) {
292 $elementdata = $this->{'preprocess_' . $elementdatagenerator}($elementdata);
293 }
294
295 // Creates element.
296 $methodname = 'create_' . $elementdatagenerator;
297 if (method_exists($this->datagenerator, $methodname)) {
298 // Using data generators directly.
299 $this->datagenerator->{$methodname}($elementdata);
300
d2eca4cd
DM
301 } else if (method_exists($this, 'process_' . $elementdatagenerator)) {
302 // Using an alternative to the direct data generator call.
303 $this->{'process_' . $elementdatagenerator}($elementdata);
f0200d14
DM
304 } else {
305 throw new PendingException($elementname . ' data generator is not implemented');
306 }
307 }
308
309 }
310
311 /**
312 * If password is not set it uses the username.
313 * @param array $data
314 * @return array
315 */
316 protected function preprocess_user($data) {
317 if (!isset($data['password'])) {
318 $data['password'] = $data['username'];
319 }
320 return $data;
321 }
322
5f079af4
MG
323 /**
324 * If contextlevel and reference are specified for cohort, transform them to the contextid.
325 *
326 * @param array $data
327 * @return array
328 */
329 protected function preprocess_cohort($data) {
330 if (isset($data['contextlevel'])) {
331 if (!isset($data['reference'])) {
332 throw new Exception('If field contextlevel is specified, field reference must also be present');
333 }
334 $context = $this->get_context($data['contextlevel'], $data['reference']);
335 unset($data['contextlevel']);
336 unset($data['reference']);
337 $data['contextid'] = $context->id;
338 }
339 return $data;
340 }
341
cfa91962
JO
342 /**
343 * Preprocesses the creation of a grade item. Converts gradetype text to a number.
344 * @param array $data
345 * @return array
346 */
347 protected function preprocess_grade_item($data) {
348 global $CFG;
349 require_once("$CFG->libdir/grade/constants.php");
350
351 if (isset($data['gradetype'])) {
352 $data['gradetype'] = constant("GRADE_TYPE_" . strtoupper($data['gradetype']));
353 }
b13afc36
FM
354
355 if (!empty($data['category']) && !empty($data['courseid'])) {
356 $cat = grade_category::fetch(array('fullname' => $data['category'], 'courseid' => $data['courseid']));
357 if (!$cat) {
358 throw new Exception('Could not resolve category with name "' . $data['category'] . '"');
359 }
360 unset($data['category']);
361 $data['categoryid'] = $cat->id;
362 }
363
cfa91962
JO
364 return $data;
365 }
366
a0902967
DM
367 /**
368 * Adapter to modules generator
369 * @throws Exception Custom exception for test writers
370 * @param array $data
371 * @return void
372 */
373 protected function process_activity($data) {
cfa91962 374 global $DB, $CFG;
a0902967
DM
375
376 // The the_following_exists() method checks that the field exists.
377 $activityname = $data['activity'];
378 unset($data['activity']);
379
cfa91962
JO
380 // Convert scale name into scale id (negative number indicates using scale).
381 if (isset($data['grade']) && strlen($data['grade']) && !is_number($data['grade'])) {
382 $data['grade'] = - $this->get_scale_id($data['grade']);
383 require_once("$CFG->libdir/grade/constants.php");
384
385 if (!isset($data['gradetype'])) {
386 $data['gradetype'] = GRADE_TYPE_SCALE;
387 }
388 }
389
041cf62b
DM
390 // We split $data in the activity $record and the course module $options.
391 $cmoptions = array();
392 $cmcolumns = $DB->get_columns('course_modules');
393 foreach ($cmcolumns as $key => $value) {
394 if (isset($data[$key])) {
395 $cmoptions[$key] = $data[$key];
396 }
397 }
398
a0902967
DM
399 // Custom exception.
400 try {
041cf62b 401 $this->datagenerator->create_module($activityname, $data, $cmoptions);
a0902967
DM
402 } catch (coding_exception $e) {
403 throw new Exception('\'' . $activityname . '\' activity can not be added using this step,' .
404 ' use the step \'I add a "ACTIVITY_OR_RESOURCE_NAME_STRING" to section "SECTION_NUMBER"\' instead');
405 }
eb3884e4
TH
406 }
407
408 /**
409 * Add a block to a page.
410 *
411 * @param array $data should mostly match the fields of the block_instances table.
412 * The block type is specified by blockname.
413 * The parentcontextid is set from contextlevel and reference.
414 * Missing values are filled in by testing_block_generator::prepare_record.
415 * $data is passed to create_block as both $record and $options. Normally
416 * the keys are different, so this is a way to let people set values in either place.
417 */
418 protected function process_block_instance($data) {
419
420 if (empty($data['blockname'])) {
421 throw new Exception('\'blocks\' requires the field \'block\' type to be specified');
422 }
423
424 if (empty($data['contextlevel'])) {
425 throw new Exception('\'blocks\' requires the field \'contextlevel\' to be specified');
426 }
427
428 if (!isset($data['reference'])) {
429 throw new Exception('\'blocks\' requires the field \'reference\' to be specified');
430 }
431
432 $context = $this->get_context($data['contextlevel'], $data['reference']);
433 $data['parentcontextid'] = $context->id;
434
435 // Pass $data as both $record and $options. I think that is unlikely to
436 // cause problems since the relevant key names are different.
437 // $options is not used in most blocks I have seen, but where it is, it is necessary.
438 $this->datagenerator->create_block($data['blockname'], $data, $data);
a0902967 439 }
f0200d14 440
4d0ac716
SR
441 /**
442 * Creates language customisation.
443 *
444 * @throws Exception
445 * @throws dml_exception
446 * @param array $data
447 * @return void
448 */
449 protected function process_customlang($data) {
450 global $CFG, $DB, $USER;
451
452 require_once($CFG->dirroot . '/' . $CFG->admin . '/tool/customlang/locallib.php');
453 require_once($CFG->libdir . '/adminlib.php');
454
455 if (empty($data['component'])) {
456 throw new Exception('\'customlang\' requires the field \'component\' type to be specified');
457 }
458
459 if (empty($data['stringid'])) {
460 throw new Exception('\'customlang\' requires the field \'stringid\' to be specified');
461 }
462
463 if (!isset($data['value'])) {
464 throw new Exception('\'customlang\' requires the field \'value\' to be specified');
465 }
466
467 $now = time();
468
469 tool_customlang_utils::checkout($USER->lang);
470
471 $record = $DB->get_record_sql("SELECT s.*
472 FROM {tool_customlang} s
473 JOIN {tool_customlang_components} c ON s.componentid = c.id
474 WHERE c.name = ? AND s.lang = ? AND s.stringid = ?",
475 array($data['component'], $USER->lang, $data['stringid']));
476
477 if (empty($data['value']) && !is_null($record->local)) {
478 $record->local = null;
479 $record->modified = 1;
480 $record->outdated = 0;
481 $record->timecustomized = null;
482 $DB->update_record('tool_customlang', $record);
483 tool_customlang_utils::checkin($USER->lang);
484 }
485
486 if (!empty($data['value']) && $data['value'] != $record->local) {
487 $record->local = $data['value'];
488 $record->modified = 1;
489 $record->outdated = 0;
490 $record->timecustomized = $now;
491 $DB->update_record('tool_customlang', $record);
492 tool_customlang_utils::checkin($USER->lang);
493 }
494 }
495
f0200d14
DM
496 /**
497 * Adapter to enrol_user() data generator.
498 * @throws Exception
d2eca4cd 499 * @param array $data
f0200d14
DM
500 * @return void
501 */
d2eca4cd 502 protected function process_enrol_user($data) {
a8a48495 503 global $SITE;
f0200d14
DM
504
505 if (empty($data['roleid'])) {
506 throw new Exception('\'course enrolments\' requires the field \'role\' to be specified');
507 }
508
509 if (!isset($data['userid'])) {
510 throw new Exception('\'course enrolments\' requires the field \'user\' to be specified');
511 }
512
513 if (!isset($data['courseid'])) {
514 throw new Exception('\'course enrolments\' requires the field \'course\' to be specified');
515 }
516
517 if (!isset($data['enrol'])) {
518 $data['enrol'] = 'manual';
519 }
520
2f29dd62
TB
521 if (!isset($data['timestart'])) {
522 $data['timestart'] = 0;
523 }
524
525 if (!isset($data['timeend'])) {
526 $data['timeend'] = 0;
527 }
528
529 if (!isset($data['status'])) {
530 $data['status'] = null;
531 }
532
a8a48495
DM
533 // If the provided course shortname is the site shortname we consider it a system role assign.
534 if ($data['courseid'] == $SITE->id) {
535 // Frontpage course assign.
536 $context = context_course::instance($data['courseid']);
537 role_assign($data['roleid'], $data['userid'], $context->id);
538
539 } else {
540 // Course assign.
2f29dd62
TB
541 $this->datagenerator->enrol_user($data['userid'], $data['courseid'], $data['roleid'], $data['enrol'],
542 $data['timestart'], $data['timeend'], $data['status']);
a8a48495
DM
543 }
544
f0200d14
DM
545 }
546
81cd8572
DM
547 /**
548 * Allows/denies a capability at the specified context
549 *
550 * @throws Exception
551 * @param array $data
552 * @return void
553 */
554 protected function process_permission_override($data) {
555
556 // Will throw an exception if it does not exist.
557 $context = $this->get_context($data['contextlevel'], $data['reference']);
558
559 switch ($data['permission']) {
a5254141 560 case get_string('allow', 'role'):
81cd8572
DM
561 $permission = CAP_ALLOW;
562 break;
a5254141 563 case get_string('prevent', 'role'):
81cd8572
DM
564 $permission = CAP_PREVENT;
565 break;
a5254141 566 case get_string('prohibit', 'role'):
81cd8572
DM
567 $permission = CAP_PROHIBIT;
568 break;
569 default:
570 throw new Exception('The \'' . $data['permission'] . '\' permission does not exist');
571 break;
572 }
573
574 if (is_null(get_capability_info($data['capability']))) {
575 throw new Exception('The \'' . $data['capability'] . '\' capability does not exist');
576 }
577
578 role_change_permission($data['roleid'], $context, $data['capability'], $permission);
579 }
580
d2eca4cd 581 /**
72ddc05f
DM
582 * Assigns a role to a user at system context
583 *
584 * Used by "system role assigns" can be deleted when
585 * system role assign will be deprecated in favour of
586 * "role assigns"
587 *
d2eca4cd
DM
588 * @throws Exception
589 * @param array $data
590 * @return void
591 */
72ddc05f 592 protected function process_system_role_assign($data) {
d2eca4cd
DM
593
594 if (empty($data['roleid'])) {
595 throw new Exception('\'system role assigns\' requires the field \'role\' to be specified');
596 }
597
598 if (!isset($data['userid'])) {
599 throw new Exception('\'system role assigns\' requires the field \'user\' to be specified');
600 }
601
602 $context = context_system::instance();
72ddc05f
DM
603
604 $this->datagenerator->role_assign($data['roleid'], $data['userid'], $context->id);
605 }
606
607 /**
608 * Assigns a role to a user at the specified context
609 *
610 * @throws Exception
611 * @param array $data
612 * @return void
613 */
614 protected function process_role_assign($data) {
615
616 if (empty($data['roleid'])) {
617 throw new Exception('\'role assigns\' requires the field \'role\' to be specified');
618 }
619
620 if (!isset($data['userid'])) {
621 throw new Exception('\'role assigns\' requires the field \'user\' to be specified');
622 }
623
624 if (empty($data['contextlevel'])) {
625 throw new Exception('\'role assigns\' requires the field \'contextlevel\' to be specified');
626 }
627
628 if (!isset($data['reference'])) {
629 throw new Exception('\'role assigns\' requires the field \'reference\' to be specified');
630 }
631
632 // Getting the context id.
633 $context = $this->get_context($data['contextlevel'], $data['reference']);
634
635 $this->datagenerator->role_assign($data['roleid'], $data['userid'], $context->id);
f0200d14
DM
636 }
637
702851c0
DM
638 /**
639 * Creates a role.
640 *
641 * @param array $data
642 * @return void
643 */
644 protected function process_role($data) {
645
646 // We require the user to fill the role shortname.
647 if (empty($data['shortname'])) {
648 throw new Exception('\'role\' requires the field \'shortname\' to be specified');
649 }
650
651 $this->datagenerator->create_role($data);
652 }
653
9cc66e86
MG
654 /**
655 * Adds members to cohorts
656 *
657 * @param array $data
658 * @return void
659 */
660 protected function process_cohort_member($data) {
661 cohort_add_member($data['cohortid'], $data['userid']);
662 }
663
0db16e08
TH
664 /**
665 * Create a question category.
666 *
667 * @param array $data the row of data from the behat script.
668 */
669 protected function process_question_category($data) {
670 $context = $this->get_context($data['contextlevel'], $data['reference']);
671 $data['contextid'] = $context->id;
672 $this->datagenerator->get_plugin_generator('core_question')->create_question_category($data);
673 }
674
675 /**
676 * Create a question.
677 *
678 * Creating questions relies on the question/type/.../tests/helper.php mechanism.
679 * We start with test_question_maker::get_question_form_data($data['qtype'], $data['template'])
680 * and then overlay the values from any other fields of $data that are set.
681 *
682 * @param array $data the row of data from the behat script.
683 */
684 protected function process_question($data) {
685 if (array_key_exists('questiontext', $data)) {
686 $data['questiontext'] = array(
687 'text' => $data['questiontext'],
688 'format' => FORMAT_HTML,
689 );
690 }
691
692 if (array_key_exists('generalfeedback', $data)) {
693 $data['generalfeedback'] = array(
694 'text' => $data['generalfeedback'],
695 'format' => FORMAT_HTML,
696 );
697 }
698
699 $which = null;
700 if (!empty($data['template'])) {
701 $which = $data['template'];
702 }
703
704 $this->datagenerator->get_plugin_generator('core_question')->create_question($data['qtype'], $which, $data);
705 }
706
15ace204
DW
707 /**
708 * Gets the grade category id from the grade category fullname
709 * @throws Exception
710 * @param string $username
711 * @return int
712 */
713 protected function get_gradecategory_id($fullname) {
714 global $DB;
715
716 if (!$id = $DB->get_field('grade_categories', 'id', array('fullname' => $fullname))) {
717 throw new Exception('The specified grade category with fullname "' . $fullname . '" does not exist');
718 }
719 return $id;
720 }
721
f0200d14
DM
722 /**
723 * Gets the user id from it's username.
724 * @throws Exception
46ac40cd 725 * @param string $username
f0200d14
DM
726 * @return int
727 */
728 protected function get_user_id($username) {
729 global $DB;
730
731 if (!$id = $DB->get_field('user', 'id', array('username' => $username))) {
1f9ffbdb 732 throw new Exception('The specified user with username "' . $username . '" does not exist');
f0200d14
DM
733 }
734 return $id;
735 }
736
737 /**
738 * Gets the role id from it's shortname.
739 * @throws Exception
46ac40cd 740 * @param string $roleshortname
f0200d14
DM
741 * @return int
742 */
743 protected function get_role_id($roleshortname) {
744 global $DB;
745
746 if (!$id = $DB->get_field('role', 'id', array('shortname' => $roleshortname))) {
702851c0 747 throw new Exception('The specified role with shortname "' . $roleshortname . '" does not exist');
f0200d14
DM
748 }
749
750 return $id;
751 }
752
753 /**
754 * Gets the category id from it's idnumber.
755 * @throws Exception
756 * @param string $idnumber
757 * @return int
758 */
759 protected function get_category_id($idnumber) {
760 global $DB;
761
762 // If no category was specified use the data generator one.
763 if ($idnumber == false) {
764 return null;
765 }
766
767 if (!$id = $DB->get_field('course_categories', 'id', array('idnumber' => $idnumber))) {
1f9ffbdb 768 throw new Exception('The specified category with idnumber "' . $idnumber . '" does not exist');
f0200d14
DM
769 }
770
771 return $id;
772 }
773
774 /**
775 * Gets the course id from it's shortname.
776 * @throws Exception
777 * @param string $shortname
778 * @return int
779 */
780 protected function get_course_id($shortname) {
781 global $DB;
782
783 if (!$id = $DB->get_field('course', 'id', array('shortname' => $shortname))) {
702851c0 784 throw new Exception('The specified course with shortname "' . $shortname . '" does not exist');
f0200d14
DM
785 }
786 return $id;
787 }
788
789 /**
790 * Gets the group id from it's idnumber.
791 * @throws Exception
792 * @param string $idnumber
793 * @return int
794 */
795 protected function get_group_id($idnumber) {
796 global $DB;
797
798 if (!$id = $DB->get_field('groups', 'id', array('idnumber' => $idnumber))) {
1f9ffbdb 799 throw new Exception('The specified group with idnumber "' . $idnumber . '" does not exist');
f0200d14
DM
800 }
801 return $id;
802 }
803
804 /**
805 * Gets the grouping id from it's idnumber.
806 * @throws Exception
807 * @param string $idnumber
808 * @return int
809 */
810 protected function get_grouping_id($idnumber) {
811 global $DB;
812
5fb766da
JP
813 // Do not fetch grouping ID for empty grouping idnumber.
814 if (empty($idnumber)) {
815 return null;
816 }
817
f0200d14 818 if (!$id = $DB->get_field('groupings', 'id', array('idnumber' => $idnumber))) {
1f9ffbdb 819 throw new Exception('The specified grouping with idnumber "' . $idnumber . '" does not exist');
f0200d14
DM
820 }
821 return $id;
822 }
72ddc05f 823
9cc66e86
MG
824 /**
825 * Gets the cohort id from it's idnumber.
826 * @throws Exception
827 * @param string $idnumber
828 * @return int
829 */
830 protected function get_cohort_id($idnumber) {
831 global $DB;
832
833 if (!$id = $DB->get_field('cohort', 'id', array('idnumber' => $idnumber))) {
834 throw new Exception('The specified cohort with idnumber "' . $idnumber . '" does not exist');
835 }
836 return $id;
837 }
838
cfa91962
JO
839 /**
840 * Gets the outcome item id from its shortname.
841 * @throws Exception
842 * @param string $shortname
843 * @return int
844 */
845 protected function get_outcome_id($shortname) {
846 global $DB;
847
848 if (!$id = $DB->get_field('grade_outcomes', 'id', array('shortname' => $shortname))) {
849 throw new Exception('The specified outcome with shortname "' . $shortname . '" does not exist');
850 }
851 return $id;
852 }
853
854 /**
0db16e08
TH
855 * Get the id of a named scale.
856 * @param string $name the name of the scale.
857 * @return int the scale id.
cfa91962
JO
858 */
859 protected function get_scale_id($name) {
860 global $DB;
861
862 if (!$id = $DB->get_field('scale', 'id', array('name' => $name))) {
863 throw new Exception('The specified scale with name "' . $name . '" does not exist');
864 }
865 return $id;
866 }
867
0db16e08
TH
868 /**
869 * Get the id of a named question category (must be globally unique).
870 * Note that 'Top' is a special value, used when setting the parent of another
871 * category, meaning top-level.
872 *
873 * @param string $name the question category name.
874 * @return int the question category id.
875 */
876 protected function get_questioncategory_id($name) {
877 global $DB;
878
879 if ($name == 'Top') {
880 return 0;
881 }
882
883 if (!$id = $DB->get_field('question_categories', 'id', array('name' => $name))) {
884 throw new Exception('The specified question category with name "' . $name . '" does not exist');
885 }
886 return $id;
887 }
888
72ddc05f
DM
889 /**
890 * Gets the internal context id from the context reference.
891 *
892 * The context reference changes depending on the context
893 * level, it can be the system, a user, a category, a course or
894 * a module.
895 *
896 * @throws Exception
897 * @param string $levelname The context level string introduced by the test writer
898 * @param string $contextref The context reference introduced by the test writer
899 * @return context
900 */
901 protected function get_context($levelname, $contextref) {
902 global $DB;
903
904 // Getting context levels and names (we will be using the English ones as it is the test site language).
905 $contextlevels = context_helper::get_all_levels();
906 $contextnames = array();
907 foreach ($contextlevels as $level => $classname) {
908 $contextnames[context_helper::get_level_name($level)] = $level;
909 }
910
911 if (empty($contextnames[$levelname])) {
912 throw new Exception('The specified "' . $levelname . '" context level does not exist');
913 }
914 $contextlevel = $contextnames[$levelname];
915
916 // Return it, we don't need to look for other internal ids.
917 if ($contextlevel == CONTEXT_SYSTEM) {
918 return context_system::instance();
919 }
920
921 switch ($contextlevel) {
922
923 case CONTEXT_USER:
924 $instanceid = $DB->get_field('user', 'id', array('username' => $contextref));
925 break;
926
927 case CONTEXT_COURSECAT:
928 $instanceid = $DB->get_field('course_categories', 'id', array('idnumber' => $contextref));
929 break;
930
931 case CONTEXT_COURSE:
932 $instanceid = $DB->get_field('course', 'id', array('shortname' => $contextref));
933 break;
934
935 case CONTEXT_MODULE:
936 $instanceid = $DB->get_field('course_modules', 'id', array('idnumber' => $contextref));
937 break;
938
939 default:
940 break;
941 }
942
943 $contextclass = $contextlevels[$contextlevel];
944 if (!$context = $contextclass::instance($instanceid, IGNORE_MISSING)) {
945 throw new Exception('The specified "' . $contextref . '" context reference does not exist');
946 }
947
948 return $context;
949 }
950
029a3e73 951 /**
952 * Adds user to contacts
953 *
954 * @param array $data
955 * @return void
956 */
957 protected function process_message_contacts($data) {
958 \core_message\api::add_contact($data['userid'], $data['contactid']);
959 }
960
961 /**
962 * Gets the contact id from it's username.
963 * @throws Exception
964 * @param string $username
965 * @return int
966 */
967 protected function get_contact_id($username) {
968 global $DB;
969
970 if (!$id = $DB->get_field('user', 'id', array('username' => $username))) {
971 throw new Exception('The specified user with username "' . $username . '" does not exist');
972 }
973 return $id;
974 }
173be485
AA
975
976 /**
977 * Send a new message from user to contact in a private conversation
978 *
979 * @param array $data
980 * @return void
981 */
982 protected function process_private_messages(array $data) {
8922d78b
AA
983 if (empty($data['format'])) {
984 $data['format'] = 'FORMAT_PLAIN';
985 }
986
173be485
AA
987 if (!$conversationid = \core_message\api::get_conversation_between_users([$data['userid'], $data['contactid']])) {
988 $conversation = \core_message\api::create_conversation(
989 \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
990 [$data['userid'], $data['contactid']]
991 );
992 $conversationid = $conversation->id;
993 }
8922d78b
AA
994 \core_message\api::send_message_to_conversation(
995 $data['userid'],
996 $conversationid,
997 $data['message'],
998 constant($data['format'])
999 );
1000 }
1001
1002 /**
1003 * Send a new message from user to a group conversation
1004 *
1005 * @param array $data
1006 * @return void
1007 */
1008 protected function process_group_messages(array $data) {
1009 global $DB;
1010
1011 if (empty($data['format'])) {
1012 $data['format'] = 'FORMAT_PLAIN';
1013 }
1014
1015 $group = $DB->get_record('groups', ['id' => $data['groupid']]);
1016 $coursecontext = context_course::instance($group->courseid);
1017 if (!$conversation = \core_message\api::get_conversation_by_area('core_group', 'groups', $data['groupid'],
1018 $coursecontext->id)) {
1019 $members = $DB->get_records_menu('groups_members', ['groupid' => $data['groupid']], '', 'userid, id');
1020 $conversation = \core_message\api::create_conversation(
1021 \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
1022 array_keys($members),
1023 $group->name,
1024 \core_message\api::MESSAGE_CONVERSATION_ENABLED,
1025 'core_group',
1026 'groups',
1027 $group->id,
1028 $coursecontext->id);
1029 }
1030 \core_message\api::send_message_to_conversation(
1031 $data['userid'],
1032 $conversation->id,
1033 $data['message'],
1034 constant($data['format'])
1035 );
173be485
AA
1036 }
1037
1038 /**
1039 * Mark a private conversation as favourite for user
1040 *
1041 * @param array $data
1042 * @return void
1043 */
1044 protected function process_favourite_conversations(array $data) {
1045 if (!$conversationid = \core_message\api::get_conversation_between_users([$data['userid'], $data['contactid']])) {
1046 $conversation = \core_message\api::create_conversation(
1047 \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
1048 [$data['userid'], $data['contactid']]
1049 );
1050 $conversationid = $conversation->id;
1051 }
1052 \core_message\api::set_favourite_conversation($conversationid, $data['userid']);
1053 }
f0e8f0a5
AA
1054
1055 /**
1056 * Mute an existing group conversation for user
1057 *
1058 * @param array $data
1059 * @return void
1060 */
1061 protected function process_mute_group_conversations(array $data) {
1062 if (groups_is_member($data['groupid'], $data['userid'])) {
1063 $context = context_course::instance($data['courseid']);
1064 $conversation = \core_message\api::get_conversation_by_area(
1065 'core_group',
1066 'groups',
1067 $data['groupid'],
1068 $context->id
1069 );
1070 if ($conversation) {
1071 \core_message\api::mute_conversation($data['userid'], $conversation->id);
1072 }
1073 }
1074 }
1075
1076 /**
1077 * Mute a private conversation for user
1078 *
1079 * @param array $data
1080 * @return void
1081 */
1082 protected function process_mute_private_conversations(array $data) {
1083 if (!$conversationid = \core_message\api::get_conversation_between_users([$data['userid'], $data['contactid']])) {
1084 $conversation = \core_message\api::create_conversation(
1085 \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
1086 [$data['userid'], $data['contactid']]
1087 );
1088 $conversationid = $conversation->id;
1089 }
1090 \core_message\api::mute_conversation($data['userid'], $conversationid);
1091 }
a9e58c14
VDF
1092
1093 /**
1094 * Transform indicators string into array.
1095 *
1096 * @param array $data
1097 * @return array
1098 */
1099 protected function preprocess_analytics_model($data) {
1100 $data['indicators'] = explode(',', $data['indicators']);
1101 return $data;
1102 }
1103
1104 /**
1105 * Creates an analytics model
1106 *
1107 * @param target $data
1108 * @return void
1109 */
1110 protected function process_analytics_model($data) {
1111 \core_analytics\manager::create_declared_model($data);
1112 }
f0200d14 1113}