Merge branch 'MDL-67410-37' of https://github.com/felicemcc/moodle into MOODLE_37_STABLE
[moodle.git] / lib / behat / classes / behat_core_generator.php
blob2e626fcab8d913207d3125e2af7fb4c258cd4724
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.
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 for acceptance testing.
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
26 // NOTE: no MOODLE_INTERNAL test here, this file may be required by behat before including /config.php.
28 defined('MOODLE_INTERNAL') || die();
31 /**
32 * Behat data generator class for core entities.
34 * @package core
35 * @category test
36 * @copyright 2012 David MonllaĆ³
37 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
39 class behat_core_generator extends behat_generator_base {
41 protected function get_creatable_entities(): array {
42 return [
43 'users' => [
44 'datagenerator' => 'user',
45 'required' => ['username'],
47 'categories' => [
48 'datagenerator' => 'category',
49 'required' => ['idnumber'],
50 'switchids' => ['category' => 'parent'],
52 'courses' => [
53 'datagenerator' => 'course',
54 'required' => ['shortname'],
55 'switchids' => ['category' => 'category'],
57 'groups' => [
58 'datagenerator' => 'group',
59 'required' => ['idnumber', 'course'],
60 'switchids' => ['course' => 'courseid'],
62 'groupings' => [
63 'datagenerator' => 'grouping',
64 'required' => ['idnumber', 'course'],
65 'switchids' => ['course' => 'courseid'],
67 'course enrolments' => [
68 'datagenerator' => 'enrol_user',
69 'required' => ['user', 'course', 'role'],
70 'switchids' => ['user' => 'userid', 'course' => 'courseid', 'role' => 'roleid'],
72 'custom field categories' => [
73 'datagenerator' => 'custom_field_category',
74 'required' => ['name', 'component', 'area', 'itemid'],
75 'switchids' => [],
77 'custom fields' => [
78 'datagenerator' => 'custom_field',
79 'required' => ['name', 'category', 'type', 'shortname'],
80 'switchids' => [],
82 'permission overrides' => [
83 'datagenerator' => 'permission_override',
84 'required' => ['capability', 'permission', 'role', 'contextlevel', 'reference'],
85 'switchids' => ['role' => 'roleid'],
87 'system role assigns' => [
88 'datagenerator' => 'system_role_assign',
89 'required' => ['user', 'role'],
90 'switchids' => ['user' => 'userid', 'role' => 'roleid'],
92 'role assigns' => [
93 'datagenerator' => 'role_assign',
94 'required' => ['user', 'role', 'contextlevel', 'reference'],
95 'switchids' => ['user' => 'userid', 'role' => 'roleid'],
97 'activities' => [
98 'datagenerator' => 'activity',
99 'required' => ['activity', 'idnumber', 'course'],
100 'switchids' => ['course' => 'course', 'gradecategory' => 'gradecat', 'grouping' => 'groupingid'],
102 'blocks' => [
103 'datagenerator' => 'block_instance',
104 'required' => ['blockname', 'contextlevel', 'reference'],
106 'group members' => [
107 'datagenerator' => 'group_member',
108 'required' => ['user', 'group'],
109 'switchids' => ['user' => 'userid', 'group' => 'groupid'],
111 'grouping groups' => [
112 'datagenerator' => 'grouping_group',
113 'required' => ['grouping', 'group'],
114 'switchids' => ['grouping' => 'groupingid', 'group' => 'groupid'],
116 'cohorts' => [
117 'datagenerator' => 'cohort',
118 'required' => ['idnumber'],
120 'cohort members' => [
121 'datagenerator' => 'cohort_member',
122 'required' => ['user', 'cohort'],
123 'switchids' => ['user' => 'userid', 'cohort' => 'cohortid'],
125 'roles' => [
126 'datagenerator' => 'role',
127 'required' => ['shortname'],
129 'grade categories' => [
130 'datagenerator' => 'grade_category',
131 'required' => ['fullname', 'course'],
132 'switchids' => ['course' => 'courseid', 'gradecategory' => 'parent'],
134 'grade items' => [
135 'datagenerator' => 'grade_item',
136 'required' => ['course'],
137 'switchids' => [
138 'scale' => 'scaleid',
139 'outcome' => 'outcomeid',
140 'course' => 'courseid',
141 'gradecategory' => 'categoryid',
144 'grade outcomes' => [
145 'datagenerator' => 'grade_outcome',
146 'required' => ['shortname', 'scale'],
147 'switchids' => ['course' => 'courseid', 'gradecategory' => 'categoryid', 'scale' => 'scaleid'],
149 'scales' => [
150 'datagenerator' => 'scale',
151 'required' => ['name', 'scale'],
152 'switchids' => ['course' => 'courseid'],
154 'question categories' => [
155 'datagenerator' => 'question_category',
156 'required' => ['name', 'contextlevel', 'reference'],
157 'switchids' => ['questioncategory' => 'parent'],
159 'questions' => [
160 'datagenerator' => 'question',
161 'required' => ['qtype', 'questioncategory', 'name'],
162 'switchids' => ['questioncategory' => 'category', 'user' => 'createdby'],
164 'tags' => [
165 'datagenerator' => 'tag',
166 'required' => ['name'],
168 'events' => [
169 'datagenerator' => 'event',
170 'required' => ['name', 'eventtype'],
171 'switchids' => [
172 'user' => 'userid',
173 'course' => 'courseid',
174 'category' => 'categoryid',
177 'message contacts' => [
178 'datagenerator' => 'message_contacts',
179 'required' => ['user', 'contact'],
180 'switchids' => ['user' => 'userid', 'contact' => 'contactid'],
182 'private messages' => [
183 'datagenerator' => 'private_messages',
184 'required' => ['user', 'contact', 'message'],
185 'switchids' => ['user' => 'userid', 'contact' => 'contactid'],
187 'favourite conversations' => [
188 'datagenerator' => 'favourite_conversations',
189 'required' => ['user', 'contact'],
190 'switchids' => ['user' => 'userid', 'contact' => 'contactid'],
192 'group messages' => [
193 'datagenerator' => 'group_messages',
194 'required' => ['user', 'group', 'message'],
195 'switchids' => ['user' => 'userid', 'group' => 'groupid'],
197 'muted group conversations' => [
198 'datagenerator' => 'mute_group_conversations',
199 'required' => ['user', 'group', 'course'],
200 'switchids' => ['user' => 'userid', 'group' => 'groupid', 'course' => 'courseid'],
202 'muted private conversations' => [
203 'datagenerator' => 'mute_private_conversations',
204 'required' => ['user', 'contact'],
205 'switchids' => ['user' => 'userid', 'contact' => 'contactid'],
207 'language customisations' => [
208 'datagenerator' => 'customlang',
209 'required' => ['component', 'stringid', 'value'],
211 'analytics model' => [
212 'datagenerator' => 'analytics_model',
213 'required' => ['target', 'indicators', 'timesplitting', 'enabled'],
215 'user preferences' => [
216 'datagenerator' => 'user_preferences',
217 'required' => array('user', 'preference', 'value'),
218 'switchids' => array('user' => 'userid')
224 * If password is not set it uses the username.
226 * @param array $data
227 * @return array
229 protected function preprocess_user($data) {
230 if (!isset($data['password'])) {
231 $data['password'] = $data['username'];
233 return $data;
237 * If contextlevel and reference are specified for cohort, transform them to the contextid.
239 * @param array $data
240 * @return array
242 protected function preprocess_cohort($data) {
243 if (isset($data['contextlevel'])) {
244 if (!isset($data['reference'])) {
245 throw new Exception('If field contextlevel is specified, field reference must also be present');
247 $context = $this->get_context($data['contextlevel'], $data['reference']);
248 unset($data['contextlevel']);
249 unset($data['reference']);
250 $data['contextid'] = $context->id;
252 return $data;
256 * Preprocesses the creation of a grade item. Converts gradetype text to a number.
258 * @param array $data
259 * @return array
261 protected function preprocess_grade_item($data) {
262 global $CFG;
263 require_once("$CFG->libdir/grade/constants.php");
265 if (isset($data['gradetype'])) {
266 $data['gradetype'] = constant("GRADE_TYPE_" . strtoupper($data['gradetype']));
269 if (!empty($data['category']) && !empty($data['courseid'])) {
270 $cat = grade_category::fetch(array('fullname' => $data['category'], 'courseid' => $data['courseid']));
271 if (!$cat) {
272 throw new Exception('Could not resolve category with name "' . $data['category'] . '"');
274 unset($data['category']);
275 $data['categoryid'] = $cat->id;
278 return $data;
282 * Adapter to modules generator.
284 * @throws Exception Custom exception for test writers
285 * @param array $data
286 * @return void
288 protected function process_activity($data) {
289 global $DB, $CFG;
291 // The the_following_exists() method checks that the field exists.
292 $activityname = $data['activity'];
293 unset($data['activity']);
295 // Convert scale name into scale id (negative number indicates using scale).
296 if (isset($data['grade']) && strlen($data['grade']) && !is_number($data['grade'])) {
297 $data['grade'] = - $this->get_scale_id($data['grade']);
298 require_once("$CFG->libdir/grade/constants.php");
300 if (!isset($data['gradetype'])) {
301 $data['gradetype'] = GRADE_TYPE_SCALE;
305 // We split $data in the activity $record and the course module $options.
306 $cmoptions = array();
307 $cmcolumns = $DB->get_columns('course_modules');
308 foreach ($cmcolumns as $key => $value) {
309 if (isset($data[$key])) {
310 $cmoptions[$key] = $data[$key];
314 // Custom exception.
315 try {
316 $this->datagenerator->create_module($activityname, $data, $cmoptions);
317 } catch (coding_exception $e) {
318 throw new Exception('\'' . $activityname . '\' activity can not be added using this step,' .
319 ' use the step \'I add a "ACTIVITY_OR_RESOURCE_NAME_STRING" to section "SECTION_NUMBER"\' instead');
324 * Add a block to a page.
326 * @param array $data should mostly match the fields of the block_instances table.
327 * The block type is specified by blockname.
328 * The parentcontextid is set from contextlevel and reference.
329 * Missing values are filled in by testing_block_generator::prepare_record.
330 * $data is passed to create_block as both $record and $options. Normally
331 * the keys are different, so this is a way to let people set values in either place.
333 protected function process_block_instance($data) {
335 if (empty($data['blockname'])) {
336 throw new Exception('\'blocks\' requires the field \'block\' type to be specified');
339 if (empty($data['contextlevel'])) {
340 throw new Exception('\'blocks\' requires the field \'contextlevel\' to be specified');
343 if (!isset($data['reference'])) {
344 throw new Exception('\'blocks\' requires the field \'reference\' to be specified');
347 $context = $this->get_context($data['contextlevel'], $data['reference']);
348 $data['parentcontextid'] = $context->id;
350 // Pass $data as both $record and $options. I think that is unlikely to
351 // cause problems since the relevant key names are different.
352 // $options is not used in most blocks I have seen, but where it is, it is necessary.
353 $this->datagenerator->create_block($data['blockname'], $data, $data);
357 * Creates language customisation.
359 * @throws Exception
360 * @throws dml_exception
361 * @param array $data
362 * @return void
364 protected function process_customlang($data) {
365 global $CFG, $DB, $USER;
367 require_once($CFG->dirroot . '/' . $CFG->admin . '/tool/customlang/locallib.php');
368 require_once($CFG->libdir . '/adminlib.php');
370 if (empty($data['component'])) {
371 throw new Exception('\'customlang\' requires the field \'component\' type to be specified');
374 if (empty($data['stringid'])) {
375 throw new Exception('\'customlang\' requires the field \'stringid\' to be specified');
378 if (!isset($data['value'])) {
379 throw new Exception('\'customlang\' requires the field \'value\' to be specified');
382 $now = time();
384 tool_customlang_utils::checkout($USER->lang);
386 $record = $DB->get_record_sql("SELECT s.*
387 FROM {tool_customlang} s
388 JOIN {tool_customlang_components} c ON s.componentid = c.id
389 WHERE c.name = ? AND s.lang = ? AND s.stringid = ?",
390 array($data['component'], $USER->lang, $data['stringid']));
392 if (empty($data['value']) && !is_null($record->local)) {
393 $record->local = null;
394 $record->modified = 1;
395 $record->outdated = 0;
396 $record->timecustomized = null;
397 $DB->update_record('tool_customlang', $record);
398 tool_customlang_utils::checkin($USER->lang);
401 if (!empty($data['value']) && $data['value'] != $record->local) {
402 $record->local = $data['value'];
403 $record->modified = 1;
404 $record->outdated = 0;
405 $record->timecustomized = $now;
406 $DB->update_record('tool_customlang', $record);
407 tool_customlang_utils::checkin($USER->lang);
412 * Adapter to enrol_user() data generator.
414 * @throws Exception
415 * @param array $data
416 * @return void
418 protected function process_enrol_user($data) {
419 global $SITE;
421 if (empty($data['roleid'])) {
422 throw new Exception('\'course enrolments\' requires the field \'role\' to be specified');
425 if (!isset($data['userid'])) {
426 throw new Exception('\'course enrolments\' requires the field \'user\' to be specified');
429 if (!isset($data['courseid'])) {
430 throw new Exception('\'course enrolments\' requires the field \'course\' to be specified');
433 if (!isset($data['enrol'])) {
434 $data['enrol'] = 'manual';
437 if (!isset($data['timestart'])) {
438 $data['timestart'] = 0;
441 if (!isset($data['timeend'])) {
442 $data['timeend'] = 0;
445 if (!isset($data['status'])) {
446 $data['status'] = null;
449 // If the provided course shortname is the site shortname we consider it a system role assign.
450 if ($data['courseid'] == $SITE->id) {
451 // Frontpage course assign.
452 $context = context_course::instance($data['courseid']);
453 role_assign($data['roleid'], $data['userid'], $context->id);
455 } else {
456 // Course assign.
457 $this->datagenerator->enrol_user($data['userid'], $data['courseid'], $data['roleid'], $data['enrol'],
458 $data['timestart'], $data['timeend'], $data['status']);
464 * Allows/denies a capability at the specified context
466 * @throws Exception
467 * @param array $data
468 * @return void
470 protected function process_permission_override($data) {
472 // Will throw an exception if it does not exist.
473 $context = $this->get_context($data['contextlevel'], $data['reference']);
475 switch ($data['permission']) {
476 case get_string('allow', 'role'):
477 $permission = CAP_ALLOW;
478 break;
479 case get_string('prevent', 'role'):
480 $permission = CAP_PREVENT;
481 break;
482 case get_string('prohibit', 'role'):
483 $permission = CAP_PROHIBIT;
484 break;
485 default:
486 throw new Exception('The \'' . $data['permission'] . '\' permission does not exist');
487 break;
490 if (is_null(get_capability_info($data['capability']))) {
491 throw new Exception('The \'' . $data['capability'] . '\' capability does not exist');
494 role_change_permission($data['roleid'], $context, $data['capability'], $permission);
498 * Assigns a role to a user at system context
500 * Used by "system role assigns" can be deleted when
501 * system role assign will be deprecated in favour of
502 * "role assigns"
504 * @throws Exception
505 * @param array $data
506 * @return void
508 protected function process_system_role_assign($data) {
510 if (empty($data['roleid'])) {
511 throw new Exception('\'system role assigns\' requires the field \'role\' to be specified');
514 if (!isset($data['userid'])) {
515 throw new Exception('\'system role assigns\' requires the field \'user\' to be specified');
518 $context = context_system::instance();
520 $this->datagenerator->role_assign($data['roleid'], $data['userid'], $context->id);
524 * Assigns a role to a user at the specified context
526 * @throws Exception
527 * @param array $data
528 * @return void
530 protected function process_role_assign($data) {
532 if (empty($data['roleid'])) {
533 throw new Exception('\'role assigns\' requires the field \'role\' to be specified');
536 if (!isset($data['userid'])) {
537 throw new Exception('\'role assigns\' requires the field \'user\' to be specified');
540 if (empty($data['contextlevel'])) {
541 throw new Exception('\'role assigns\' requires the field \'contextlevel\' to be specified');
544 if (!isset($data['reference'])) {
545 throw new Exception('\'role assigns\' requires the field \'reference\' to be specified');
548 // Getting the context id.
549 $context = $this->get_context($data['contextlevel'], $data['reference']);
551 $this->datagenerator->role_assign($data['roleid'], $data['userid'], $context->id);
555 * Creates a role.
557 * @param array $data
558 * @return void
560 protected function process_role($data) {
562 // We require the user to fill the role shortname.
563 if (empty($data['shortname'])) {
564 throw new Exception('\'role\' requires the field \'shortname\' to be specified');
567 $this->datagenerator->create_role($data);
571 * Adds members to cohorts
573 * @param array $data
574 * @return void
576 protected function process_cohort_member($data) {
577 cohort_add_member($data['cohortid'], $data['userid']);
581 * Create a question category.
583 * @param array $data the row of data from the behat script.
585 protected function process_question_category($data) {
586 global $DB;
588 $context = $this->get_context($data['contextlevel'], $data['reference']);
590 // The way this class works, we have already looked up the given parent category
591 // name and found a matching category. However, it is possible, particularly
592 // for the 'top' category, for there to be several categories with the
593 // same name. So far one will have been picked at random, but we need
594 // the one from the right context. So, if we have the wrong category, try again.
595 // (Just fixing it here, rather than getting it right first time, is a bit
596 // of a bodge, but in general this class assumes that names are unique,
597 // and normally they are, so this was the easiest fix.)
598 if (!empty($data['parent'])) {
599 $foundparent = $DB->get_record('question_categories', ['id' => $data['parent']], '*', MUST_EXIST);
600 if ($foundparent->contextid != $context->id) {
601 $rightparentid = $DB->get_field('question_categories', 'id',
602 ['contextid' => $context->id, 'name' => $foundparent->name]);
603 if (!$rightparentid) {
604 throw new Exception('The specified question category with name "' . $foundparent->name .
605 '" does not exist in context "' . $context->get_context_name() . '"."');
607 $data['parent'] = $rightparentid;
611 $data['contextid'] = $context->id;
612 $this->datagenerator->get_plugin_generator('core_question')->create_question_category($data);
616 * Create a question.
618 * Creating questions relies on the question/type/.../tests/helper.php mechanism.
619 * We start with test_question_maker::get_question_form_data($data['qtype'], $data['template'])
620 * and then overlay the values from any other fields of $data that are set.
622 * @param array $data the row of data from the behat script.
624 protected function process_question($data) {
625 if (array_key_exists('questiontext', $data)) {
626 $data['questiontext'] = array(
627 'text' => $data['questiontext'],
628 'format' => FORMAT_HTML,
632 if (array_key_exists('generalfeedback', $data)) {
633 $data['generalfeedback'] = array(
634 'text' => $data['generalfeedback'],
635 'format' => FORMAT_HTML,
639 $which = null;
640 if (!empty($data['template'])) {
641 $which = $data['template'];
644 $this->datagenerator->get_plugin_generator('core_question')->create_question($data['qtype'], $which, $data);
648 * Adds user to contacts
650 * @param array $data
651 * @return void
653 protected function process_message_contacts($data) {
654 \core_message\api::add_contact($data['userid'], $data['contactid']);
658 * Send a new message from user to contact in a private conversation
660 * @param array $data
661 * @return void
663 protected function process_private_messages(array $data) {
664 if (empty($data['format'])) {
665 $data['format'] = 'FORMAT_PLAIN';
668 if (!$conversationid = \core_message\api::get_conversation_between_users([$data['userid'], $data['contactid']])) {
669 $conversation = \core_message\api::create_conversation(
670 \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
671 [$data['userid'], $data['contactid']]
673 $conversationid = $conversation->id;
675 \core_message\api::send_message_to_conversation(
676 $data['userid'],
677 $conversationid,
678 $data['message'],
679 constant($data['format'])
684 * Send a new message from user to a group conversation
686 * @param array $data
687 * @return void
689 protected function process_group_messages(array $data) {
690 global $DB;
692 if (empty($data['format'])) {
693 $data['format'] = 'FORMAT_PLAIN';
696 $group = $DB->get_record('groups', ['id' => $data['groupid']]);
697 $coursecontext = context_course::instance($group->courseid);
698 if (!$conversation = \core_message\api::get_conversation_by_area('core_group', 'groups', $data['groupid'],
699 $coursecontext->id)) {
700 $members = $DB->get_records_menu('groups_members', ['groupid' => $data['groupid']], '', 'userid, id');
701 $conversation = \core_message\api::create_conversation(
702 \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
703 array_keys($members),
704 $group->name,
705 \core_message\api::MESSAGE_CONVERSATION_ENABLED,
706 'core_group',
707 'groups',
708 $group->id,
709 $coursecontext->id);
711 \core_message\api::send_message_to_conversation(
712 $data['userid'],
713 $conversation->id,
714 $data['message'],
715 constant($data['format'])
720 * Mark a private conversation as favourite for user
722 * @param array $data
723 * @return void
725 protected function process_favourite_conversations(array $data) {
726 if (!$conversationid = \core_message\api::get_conversation_between_users([$data['userid'], $data['contactid']])) {
727 $conversation = \core_message\api::create_conversation(
728 \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
729 [$data['userid'], $data['contactid']]
731 $conversationid = $conversation->id;
733 \core_message\api::set_favourite_conversation($conversationid, $data['userid']);
737 * Mute an existing group conversation for user
739 * @param array $data
740 * @return void
742 protected function process_mute_group_conversations(array $data) {
743 if (groups_is_member($data['groupid'], $data['userid'])) {
744 $context = context_course::instance($data['courseid']);
745 $conversation = \core_message\api::get_conversation_by_area(
746 'core_group',
747 'groups',
748 $data['groupid'],
749 $context->id
751 if ($conversation) {
752 \core_message\api::mute_conversation($data['userid'], $conversation->id);
758 * Mute a private conversation for user
760 * @param array $data
761 * @return void
763 protected function process_mute_private_conversations(array $data) {
764 if (!$conversationid = \core_message\api::get_conversation_between_users([$data['userid'], $data['contactid']])) {
765 $conversation = \core_message\api::create_conversation(
766 \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
767 [$data['userid'], $data['contactid']]
769 $conversationid = $conversation->id;
771 \core_message\api::mute_conversation($data['userid'], $conversationid);
775 * Set a preference value for user
777 * @param array $data
778 * @return void
780 protected function process_user_preferences(array $data) {
781 set_user_preference($data['preference'], $data['value'], $data['userid']);