2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
18 * Data generators for acceptance testing.
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 require_once(__DIR__
. '/../../behat/behat_base.php');
30 use Behat\Gherkin\Node\TableNode
as TableNode
;
31 use Behat\Behat\Tester\Exception\PendingException
as PendingException
;
34 * Class to set up quickly a Given environment.
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.
39 * All data generators should be in lib/testing/generator/*, shared between phpunit
40 * and behat and they should be called from here, if possible using the standard
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.
45 * @todo If the available elements list grows too much this class must be split into smaller pieces
48 * @copyright 2012 David MonllaĆ³
49 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
51 class behat_data_generators
extends behat_base
{
54 * @var testing_data_generator
56 protected $datagenerator;
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.
65 protected static $elements = array(
67 'datagenerator' => 'user',
68 'required' => array('username')
70 'categories' => array(
71 'datagenerator' => 'category',
72 'required' => array('idnumber'),
73 'switchids' => array('category' => 'parent')
76 'datagenerator' => 'course',
77 'required' => array('shortname'),
78 'switchids' => array('category' => 'category')
81 'datagenerator' => 'group',
82 'required' => array('idnumber', 'course'),
83 'switchids' => array('course' => 'courseid')
86 'datagenerator' => 'grouping',
87 'required' => array('idnumber', 'course'),
88 'switchids' => array('course' => 'courseid')
90 'course enrolments' => array(
91 'datagenerator' => 'enrol_user',
92 'required' => array('user', 'course', 'role'),
93 'switchids' => array('user' => 'userid', 'course' => 'courseid', 'role' => 'roleid')
95 'permission overrides' => array(
96 'datagenerator' => 'permission_override',
97 'required' => array('capability', 'permission', 'role', 'contextlevel', 'reference'),
98 'switchids' => array('role' => 'roleid')
100 'system role assigns' => array(
101 'datagenerator' => 'system_role_assign',
102 'required' => array('user', 'role'),
103 'switchids' => array('user' => 'userid', 'role' => 'roleid')
105 'role assigns' => array(
106 'datagenerator' => 'role_assign',
107 'required' => array('user', 'role', 'contextlevel', 'reference'),
108 'switchids' => array('user' => 'userid', 'role' => 'roleid')
110 'activities' => array(
111 'datagenerator' => 'activity',
112 'required' => array('activity', 'idnumber', 'course'),
113 'switchids' => array('course' => 'course', 'gradecategory' => 'gradecat')
116 'datagenerator' => 'block_instance',
117 'required' => array('blockname', 'contextlevel', 'reference'),
119 'group members' => array(
120 'datagenerator' => 'group_member',
121 'required' => array('user', 'group'),
122 'switchids' => array('user' => 'userid', 'group' => 'groupid')
124 'grouping groups' => array(
125 'datagenerator' => 'grouping_group',
126 'required' => array('grouping', 'group'),
127 'switchids' => array('grouping' => 'groupingid', 'group' => 'groupid')
130 'datagenerator' => 'cohort',
131 'required' => array('idnumber')
133 'cohort members' => array(
134 'datagenerator' => 'cohort_member',
135 'required' => array('user', 'cohort'),
136 'switchids' => array('user' => 'userid', 'cohort' => 'cohortid')
139 'datagenerator' => 'role',
140 'required' => array('shortname')
142 'grade categories' => array(
143 'datagenerator' => 'grade_category',
144 'required' => array('fullname', 'course'),
145 'switchids' => array('course' => 'courseid', 'gradecategory' => 'parent')
147 'grade items' => array(
148 'datagenerator' => 'grade_item',
149 'required' => array('course'),
150 'switchids' => array('scale' => 'scaleid', 'outcome' => 'outcomeid', 'course' => 'courseid',
151 'gradecategory' => 'categoryid')
153 'grade outcomes' => array(
154 'datagenerator' => 'grade_outcome',
155 'required' => array('shortname', 'scale'),
156 'switchids' => array('course' => 'courseid', 'gradecategory' => 'categoryid', 'scale' => 'scaleid')
159 'datagenerator' => 'scale',
160 'required' => array('name', 'scale'),
161 'switchids' => array('course' => 'courseid')
163 'question categories' => array(
164 'datagenerator' => 'question_category',
165 'required' => array('name', 'contextlevel', 'reference'),
166 'switchids' => array('questioncategory' => 'parent')
168 'questions' => array(
169 'datagenerator' => 'question',
170 'required' => array('qtype', 'questioncategory', 'name'),
171 'switchids' => array('questioncategory' => 'category', 'user' => 'createdby')
174 'datagenerator' => 'tag',
175 'required' => array('name')
178 'datagenerator' => 'event',
179 'required' => array('name', 'eventtype'),
180 'switchids' => array(
182 'course' => 'courseid',
183 'category' => 'categoryid',
189 * Creates the specified element. More info about available elements in http://docs.moodle.org/dev/Acceptance_testing#Fixtures.
191 * @Given /^the following "(?P<element_string>(?:[^"]|\\")*)" exist:$/
194 * @throws PendingException
195 * @param string $elementname The name of the entity to add
196 * @param TableNode $data
198 public function the_following_exist($elementname, TableNode
$data) {
200 // Now that we need them require the data generators.
201 require_once(__DIR__
. '/../../testing/generator/lib.php');
203 if (empty(self
::$elements[$elementname])) {
204 throw new PendingException($elementname . ' data generator is not implemented');
207 $this->datagenerator
= testing_util
::get_data_generator();
209 $elementdatagenerator = self
::$elements[$elementname]['datagenerator'];
210 $requiredfields = self
::$elements[$elementname]['required'];
211 if (!empty(self
::$elements[$elementname]['switchids'])) {
212 $switchids = self
::$elements[$elementname]['switchids'];
215 foreach ($data->getHash() as $elementdata) {
217 // Check if all the required fields are there.
218 foreach ($requiredfields as $requiredfield) {
219 if (!isset($elementdata[$requiredfield])) {
220 throw new Exception($elementname . ' requires the field ' . $requiredfield . ' to be specified');
224 // Switch from human-friendly references to ids.
225 if (isset($switchids)) {
226 foreach ($switchids as $element => $field) {
227 $methodname = 'get_' . $element . '_id';
229 // Not all the switch fields are required, default vars will be assigned by data generators.
230 if (!empty($elementdata[$element])) {
231 // Temp $id var to avoid problems when $element == $field.
232 $id = $this->{$methodname}($elementdata[$element]);
233 unset($elementdata[$element]);
234 $elementdata[$field] = $id;
239 // Preprocess the entities that requires a special treatment.
240 if (method_exists($this, 'preprocess_' . $elementdatagenerator)) {
241 $elementdata = $this->{'preprocess_' . $elementdatagenerator}($elementdata);
245 $methodname = 'create_' . $elementdatagenerator;
246 if (method_exists($this->datagenerator
, $methodname)) {
247 // Using data generators directly.
248 $this->datagenerator
->{$methodname}($elementdata);
250 } else if (method_exists($this, 'process_' . $elementdatagenerator)) {
251 // Using an alternative to the direct data generator call.
252 $this->{'process_' . $elementdatagenerator}($elementdata);
254 throw new PendingException($elementname . ' data generator is not implemented');
261 * If password is not set it uses the username.
265 protected function preprocess_user($data) {
266 if (!isset($data['password'])) {
267 $data['password'] = $data['username'];
273 * If contextlevel and reference are specified for cohort, transform them to the contextid.
278 protected function preprocess_cohort($data) {
279 if (isset($data['contextlevel'])) {
280 if (!isset($data['reference'])) {
281 throw new Exception('If field contextlevel is specified, field reference must also be present');
283 $context = $this->get_context($data['contextlevel'], $data['reference']);
284 unset($data['contextlevel']);
285 unset($data['reference']);
286 $data['contextid'] = $context->id
;
292 * Preprocesses the creation of a grade item. Converts gradetype text to a number.
296 protected function preprocess_grade_item($data) {
298 require_once("$CFG->libdir/grade/constants.php");
300 if (isset($data['gradetype'])) {
301 $data['gradetype'] = constant("GRADE_TYPE_" . strtoupper($data['gradetype']));
304 if (!empty($data['category']) && !empty($data['courseid'])) {
305 $cat = grade_category
::fetch(array('fullname' => $data['category'], 'courseid' => $data['courseid']));
307 throw new Exception('Could not resolve category with name "' . $data['category'] . '"');
309 unset($data['category']);
310 $data['categoryid'] = $cat->id
;
317 * Adapter to modules generator
318 * @throws Exception Custom exception for test writers
322 protected function process_activity($data) {
325 // The the_following_exists() method checks that the field exists.
326 $activityname = $data['activity'];
327 unset($data['activity']);
329 // Convert scale name into scale id (negative number indicates using scale).
330 if (isset($data['grade']) && strlen($data['grade']) && !is_number($data['grade'])) {
331 $data['grade'] = - $this->get_scale_id($data['grade']);
332 require_once("$CFG->libdir/grade/constants.php");
334 if (!isset($data['gradetype'])) {
335 $data['gradetype'] = GRADE_TYPE_SCALE
;
339 // We split $data in the activity $record and the course module $options.
340 $cmoptions = array();
341 $cmcolumns = $DB->get_columns('course_modules');
342 foreach ($cmcolumns as $key => $value) {
343 if (isset($data[$key])) {
344 $cmoptions[$key] = $data[$key];
350 $this->datagenerator
->create_module($activityname, $data, $cmoptions);
351 } catch (coding_exception
$e) {
352 throw new Exception('\'' . $activityname . '\' activity can not be added using this step,' .
353 ' use the step \'I add a "ACTIVITY_OR_RESOURCE_NAME_STRING" to section "SECTION_NUMBER"\' instead');
358 * Add a block to a page.
360 * @param array $data should mostly match the fields of the block_instances table.
361 * The block type is specified by blockname.
362 * The parentcontextid is set from contextlevel and reference.
363 * Missing values are filled in by testing_block_generator::prepare_record.
364 * $data is passed to create_block as both $record and $options. Normally
365 * the keys are different, so this is a way to let people set values in either place.
367 protected function process_block_instance($data) {
369 if (empty($data['blockname'])) {
370 throw new Exception('\'blocks\' requires the field \'block\' type to be specified');
373 if (empty($data['contextlevel'])) {
374 throw new Exception('\'blocks\' requires the field \'contextlevel\' to be specified');
377 if (!isset($data['reference'])) {
378 throw new Exception('\'blocks\' requires the field \'reference\' to be specified');
381 $context = $this->get_context($data['contextlevel'], $data['reference']);
382 $data['parentcontextid'] = $context->id
;
384 // Pass $data as both $record and $options. I think that is unlikely to
385 // cause problems since the relevant key names are different.
386 // $options is not used in most blocks I have seen, but where it is, it is necessary.
387 $this->datagenerator
->create_block($data['blockname'], $data, $data);
391 * Adapter to enrol_user() data generator.
396 protected function process_enrol_user($data) {
399 if (empty($data['roleid'])) {
400 throw new Exception('\'course enrolments\' requires the field \'role\' to be specified');
403 if (!isset($data['userid'])) {
404 throw new Exception('\'course enrolments\' requires the field \'user\' to be specified');
407 if (!isset($data['courseid'])) {
408 throw new Exception('\'course enrolments\' requires the field \'course\' to be specified');
411 if (!isset($data['enrol'])) {
412 $data['enrol'] = 'manual';
415 if (!isset($data['timestart'])) {
416 $data['timestart'] = 0;
419 if (!isset($data['timeend'])) {
420 $data['timeend'] = 0;
423 if (!isset($data['status'])) {
424 $data['status'] = null;
427 // If the provided course shortname is the site shortname we consider it a system role assign.
428 if ($data['courseid'] == $SITE->id
) {
429 // Frontpage course assign.
430 $context = context_course
::instance($data['courseid']);
431 role_assign($data['roleid'], $data['userid'], $context->id
);
435 $this->datagenerator
->enrol_user($data['userid'], $data['courseid'], $data['roleid'], $data['enrol'],
436 $data['timestart'], $data['timeend'], $data['status']);
442 * Allows/denies a capability at the specified context
448 protected function process_permission_override($data) {
450 // Will throw an exception if it does not exist.
451 $context = $this->get_context($data['contextlevel'], $data['reference']);
453 switch ($data['permission']) {
454 case get_string('allow', 'role'):
455 $permission = CAP_ALLOW
;
457 case get_string('prevent', 'role'):
458 $permission = CAP_PREVENT
;
460 case get_string('prohibit', 'role'):
461 $permission = CAP_PROHIBIT
;
464 throw new Exception('The \'' . $data['permission'] . '\' permission does not exist');
468 if (is_null(get_capability_info($data['capability']))) {
469 throw new Exception('The \'' . $data['capability'] . '\' capability does not exist');
472 role_change_permission($data['roleid'], $context, $data['capability'], $permission);
476 * Assigns a role to a user at system context
478 * Used by "system role assigns" can be deleted when
479 * system role assign will be deprecated in favour of
486 protected function process_system_role_assign($data) {
488 if (empty($data['roleid'])) {
489 throw new Exception('\'system role assigns\' requires the field \'role\' to be specified');
492 if (!isset($data['userid'])) {
493 throw new Exception('\'system role assigns\' requires the field \'user\' to be specified');
496 $context = context_system
::instance();
498 $this->datagenerator
->role_assign($data['roleid'], $data['userid'], $context->id
);
502 * Assigns a role to a user at the specified context
508 protected function process_role_assign($data) {
510 if (empty($data['roleid'])) {
511 throw new Exception('\'role assigns\' requires the field \'role\' to be specified');
514 if (!isset($data['userid'])) {
515 throw new Exception('\'role assigns\' requires the field \'user\' to be specified');
518 if (empty($data['contextlevel'])) {
519 throw new Exception('\'role assigns\' requires the field \'contextlevel\' to be specified');
522 if (!isset($data['reference'])) {
523 throw new Exception('\'role assigns\' requires the field \'reference\' to be specified');
526 // Getting the context id.
527 $context = $this->get_context($data['contextlevel'], $data['reference']);
529 $this->datagenerator
->role_assign($data['roleid'], $data['userid'], $context->id
);
538 protected function process_role($data) {
540 // We require the user to fill the role shortname.
541 if (empty($data['shortname'])) {
542 throw new Exception('\'role\' requires the field \'shortname\' to be specified');
545 $this->datagenerator
->create_role($data);
549 * Adds members to cohorts
554 protected function process_cohort_member($data) {
555 cohort_add_member($data['cohortid'], $data['userid']);
559 * Create a question category.
561 * @param array $data the row of data from the behat script.
563 protected function process_question_category($data) {
564 $context = $this->get_context($data['contextlevel'], $data['reference']);
565 $data['contextid'] = $context->id
;
566 $this->datagenerator
->get_plugin_generator('core_question')->create_question_category($data);
572 * Creating questions relies on the question/type/.../tests/helper.php mechanism.
573 * We start with test_question_maker::get_question_form_data($data['qtype'], $data['template'])
574 * and then overlay the values from any other fields of $data that are set.
576 * @param array $data the row of data from the behat script.
578 protected function process_question($data) {
579 if (array_key_exists('questiontext', $data)) {
580 $data['questiontext'] = array(
581 'text' => $data['questiontext'],
582 'format' => FORMAT_HTML
,
586 if (array_key_exists('generalfeedback', $data)) {
587 $data['generalfeedback'] = array(
588 'text' => $data['generalfeedback'],
589 'format' => FORMAT_HTML
,
594 if (!empty($data['template'])) {
595 $which = $data['template'];
598 $this->datagenerator
->get_plugin_generator('core_question')->create_question($data['qtype'], $which, $data);
602 * Gets the grade category id from the grade category fullname
604 * @param string $username
607 protected function get_gradecategory_id($fullname) {
610 if (!$id = $DB->get_field('grade_categories', 'id', array('fullname' => $fullname))) {
611 throw new Exception('The specified grade category with fullname "' . $fullname . '" does not exist');
617 * Gets the user id from it's username.
619 * @param string $username
622 protected function get_user_id($username) {
625 if (!$id = $DB->get_field('user', 'id', array('username' => $username))) {
626 throw new Exception('The specified user with username "' . $username . '" does not exist');
632 * Gets the role id from it's shortname.
634 * @param string $roleshortname
637 protected function get_role_id($roleshortname) {
640 if (!$id = $DB->get_field('role', 'id', array('shortname' => $roleshortname))) {
641 throw new Exception('The specified role with shortname "' . $roleshortname . '" does not exist');
648 * Gets the category id from it's idnumber.
650 * @param string $idnumber
653 protected function get_category_id($idnumber) {
656 // If no category was specified use the data generator one.
657 if ($idnumber == false) {
661 if (!$id = $DB->get_field('course_categories', 'id', array('idnumber' => $idnumber))) {
662 throw new Exception('The specified category with idnumber "' . $idnumber . '" does not exist');
669 * Gets the course id from it's shortname.
671 * @param string $shortname
674 protected function get_course_id($shortname) {
677 if (!$id = $DB->get_field('course', 'id', array('shortname' => $shortname))) {
678 throw new Exception('The specified course with shortname "' . $shortname . '" does not exist');
684 * Gets the group id from it's idnumber.
686 * @param string $idnumber
689 protected function get_group_id($idnumber) {
692 if (!$id = $DB->get_field('groups', 'id', array('idnumber' => $idnumber))) {
693 throw new Exception('The specified group with idnumber "' . $idnumber . '" does not exist');
699 * Gets the grouping id from it's idnumber.
701 * @param string $idnumber
704 protected function get_grouping_id($idnumber) {
707 if (!$id = $DB->get_field('groupings', 'id', array('idnumber' => $idnumber))) {
708 throw new Exception('The specified grouping with idnumber "' . $idnumber . '" does not exist');
714 * Gets the cohort id from it's idnumber.
716 * @param string $idnumber
719 protected function get_cohort_id($idnumber) {
722 if (!$id = $DB->get_field('cohort', 'id', array('idnumber' => $idnumber))) {
723 throw new Exception('The specified cohort with idnumber "' . $idnumber . '" does not exist');
729 * Gets the outcome item id from its shortname.
731 * @param string $shortname
734 protected function get_outcome_id($shortname) {
737 if (!$id = $DB->get_field('grade_outcomes', 'id', array('shortname' => $shortname))) {
738 throw new Exception('The specified outcome with shortname "' . $shortname . '" does not exist');
744 * Get the id of a named scale.
745 * @param string $name the name of the scale.
746 * @return int the scale id.
748 protected function get_scale_id($name) {
751 if (!$id = $DB->get_field('scale', 'id', array('name' => $name))) {
752 throw new Exception('The specified scale with name "' . $name . '" does not exist');
758 * Get the id of a named question category (must be globally unique).
759 * Note that 'Top' is a special value, used when setting the parent of another
760 * category, meaning top-level.
762 * @param string $name the question category name.
763 * @return int the question category id.
765 protected function get_questioncategory_id($name) {
768 if ($name == 'Top') {
772 if (!$id = $DB->get_field('question_categories', 'id', array('name' => $name))) {
773 throw new Exception('The specified question category with name "' . $name . '" does not exist');
779 * Gets the internal context id from the context reference.
781 * The context reference changes depending on the context
782 * level, it can be the system, a user, a category, a course or
786 * @param string $levelname The context level string introduced by the test writer
787 * @param string $contextref The context reference introduced by the test writer
790 protected function get_context($levelname, $contextref) {
793 // Getting context levels and names (we will be using the English ones as it is the test site language).
794 $contextlevels = context_helper
::get_all_levels();
795 $contextnames = array();
796 foreach ($contextlevels as $level => $classname) {
797 $contextnames[context_helper
::get_level_name($level)] = $level;
800 if (empty($contextnames[$levelname])) {
801 throw new Exception('The specified "' . $levelname . '" context level does not exist');
803 $contextlevel = $contextnames[$levelname];
805 // Return it, we don't need to look for other internal ids.
806 if ($contextlevel == CONTEXT_SYSTEM
) {
807 return context_system
::instance();
810 switch ($contextlevel) {
813 $instanceid = $DB->get_field('user', 'id', array('username' => $contextref));
816 case CONTEXT_COURSECAT
:
817 $instanceid = $DB->get_field('course_categories', 'id', array('idnumber' => $contextref));
821 $instanceid = $DB->get_field('course', 'id', array('shortname' => $contextref));
825 $instanceid = $DB->get_field('course_modules', 'id', array('idnumber' => $contextref));
832 $contextclass = $contextlevels[$contextlevel];
833 if (!$context = $contextclass::instance($instanceid, IGNORE_MISSING
)) {
834 throw new Exception('The specified "' . $contextref . '" context reference does not exist');