MDL-43236 behat: Deprecate old steps
[moodle.git] / lib / tests / behat / behat_data_generators.php
blob0a18e4bbd8690f267ff6ab864d2ac38ab5532b0b
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 require_once(__DIR__ . '/../../behat/behat_base.php');
30 use Behat\Gherkin\Node\TableNode as TableNode;
31 use Behat\Behat\Exception\PendingException as PendingException;
33 /**
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
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
51 class behat_data_generators extends behat_base {
53 /**
54 * @var testing_data_generator
56 protected $datagenerator;
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
65 protected static $elements = array(
66 'users' => array(
67 'datagenerator' => 'user',
68 'required' => array('username')
70 'categories' => array(
71 'datagenerator' => 'category',
72 'required' => array('idnumber'),
73 'switchids' => array('category' => 'parent')
75 'courses' => array(
76 'datagenerator' => 'course',
77 'required' => array('shortname'),
78 'switchids' => array('category' => 'category')
80 'groups' => array(
81 'datagenerator' => 'group',
82 'required' => array('idnumber', 'course'),
83 'switchids' => array('course' => 'courseid')
85 'groupings' => array(
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')
96 'permission overrides' => array(
97 'datagenerator' => 'permission_override',
98 'required' => array('capability', 'permission', 'role', 'contextlevel', 'reference'),
99 'switchids' => array('role' => 'roleid')
101 'system role assigns' => array(
102 'datagenerator' => 'system_role_assign',
103 'required' => array('user', 'role'),
104 'switchids' => array('user' => 'userid', 'role' => 'roleid')
106 'role assigns' => array(
107 'datagenerator' => 'role_assign',
108 'required' => array('user', 'role', 'contextlevel', 'reference'),
109 'switchids' => array('user' => 'userid', 'role' => 'roleid')
111 'activities' => array(
112 'datagenerator' => 'activity',
113 'required' => array('activity', 'idnumber', 'course'),
114 'switchids' => array('course' => 'course')
116 'group members' => array(
117 'datagenerator' => 'group_member',
118 'required' => array('user', 'group'),
119 'switchids' => array('user' => 'userid', 'group' => 'groupid')
121 'grouping groups' => array(
122 'datagenerator' => 'grouping_group',
123 'required' => array('grouping', 'group'),
124 'switchids' => array('grouping' => 'groupingid', 'group' => 'groupid')
126 'cohorts' => array(
127 'datagenerator' => 'cohort',
128 'required' => array('idnumber')
130 'roles' => array(
131 'datagenerator' => 'role',
132 'required' => array('shortname')
137 * Creates the specified element. More info about available elements in http://docs.moodle.org/dev/Acceptance_testing#Fixtures.
139 * @Given /^the following "(?P<element_string>(?:[^"]|\\")*)" exist:$/
141 * @throws Exception
142 * @throws PendingException
143 * @param string $elementname The name of the entity to add
144 * @param TableNode $data
146 public function the_following_exist($elementname, TableNode $data) {
148 // Now that we need them require the data generators.
149 require_once(__DIR__ . '/../../testing/generator/lib.php');
151 if (empty(self::$elements[$elementname])) {
152 throw new PendingException($elementname . ' data generator is not implemented');
155 $this->datagenerator = testing_util::get_data_generator();
157 $elementdatagenerator = self::$elements[$elementname]['datagenerator'];
158 $requiredfields = self::$elements[$elementname]['required'];
159 if (!empty(self::$elements[$elementname]['switchids'])) {
160 $switchids = self::$elements[$elementname]['switchids'];
163 foreach ($data->getHash() as $elementdata) {
165 // Check if all the required fields are there.
166 foreach ($requiredfields as $requiredfield) {
167 if (!isset($elementdata[$requiredfield])) {
168 throw new Exception($elementname . ' requires the field ' . $requiredfield . ' to be specified');
172 // Switch from human-friendly references to ids.
173 if (isset($switchids)) {
174 foreach ($switchids as $element => $field) {
175 $methodname = 'get_' . $element . '_id';
177 // Not all the switch fields are required, default vars will be assigned by data generators.
178 if (isset($elementdata[$element])) {
179 // Temp $id var to avoid problems when $element == $field.
180 $id = $this->{$methodname}($elementdata[$element]);
181 unset($elementdata[$element]);
182 $elementdata[$field] = $id;
187 // Preprocess the entities that requires a special treatment.
188 if (method_exists($this, 'preprocess_' . $elementdatagenerator)) {
189 $elementdata = $this->{'preprocess_' . $elementdatagenerator}($elementdata);
192 // Creates element.
193 $methodname = 'create_' . $elementdatagenerator;
194 if (method_exists($this->datagenerator, $methodname)) {
195 // Using data generators directly.
196 $this->datagenerator->{$methodname}($elementdata);
198 } else if (method_exists($this, 'process_' . $elementdatagenerator)) {
199 // Using an alternative to the direct data generator call.
200 $this->{'process_' . $elementdatagenerator}($elementdata);
201 } else {
202 throw new PendingException($elementname . ' data generator is not implemented');
209 * If password is not set it uses the username.
210 * @param array $data
211 * @return array
213 protected function preprocess_user($data) {
214 if (!isset($data['password'])) {
215 $data['password'] = $data['username'];
217 return $data;
221 * Adapter to modules generator
222 * @throws Exception Custom exception for test writers
223 * @param array $data
224 * @return void
226 protected function process_activity($data) {
227 global $DB;
229 // The the_following_exists() method checks that the field exists.
230 $activityname = $data['activity'];
231 unset($data['activity']);
233 // We split $data in the activity $record and the course module $options.
234 $cmoptions = array();
235 $cmcolumns = $DB->get_columns('course_modules');
236 foreach ($cmcolumns as $key => $value) {
237 if (isset($data[$key])) {
238 $cmoptions[$key] = $data[$key];
242 // Custom exception.
243 try {
244 $this->datagenerator->create_module($activityname, $data, $cmoptions);
245 } catch (coding_exception $e) {
246 throw new Exception('\'' . $activityname . '\' activity can not be added using this step,' .
247 ' use the step \'I add a "ACTIVITY_OR_RESOURCE_NAME_STRING" to section "SECTION_NUMBER"\' instead');
252 * Adapter to enrol_user() data generator.
253 * @throws Exception
254 * @param array $data
255 * @return void
257 protected function process_enrol_user($data) {
258 global $SITE;
260 if (empty($data['roleid'])) {
261 throw new Exception('\'course enrolments\' requires the field \'role\' to be specified');
264 if (!isset($data['userid'])) {
265 throw new Exception('\'course enrolments\' requires the field \'user\' to be specified');
268 if (!isset($data['courseid'])) {
269 throw new Exception('\'course enrolments\' requires the field \'course\' to be specified');
272 if (!isset($data['enrol'])) {
273 $data['enrol'] = 'manual';
276 // If the provided course shortname is the site shortname we consider it a system role assign.
277 if ($data['courseid'] == $SITE->id) {
278 // Frontpage course assign.
279 $context = context_course::instance($data['courseid']);
280 role_assign($data['roleid'], $data['userid'], $context->id);
282 } else {
283 // Course assign.
284 $this->datagenerator->enrol_user($data['userid'], $data['courseid'], $data['roleid'], $data['enrol']);
290 * Allows/denies a capability at the specified context
292 * @throws Exception
293 * @param array $data
294 * @return void
296 protected function process_permission_override($data) {
298 // Will throw an exception if it does not exist.
299 $context = $this->get_context($data['contextlevel'], $data['reference']);
301 switch ($data['permission']) {
302 case get_string('allow', 'role'):
303 $permission = CAP_ALLOW;
304 break;
305 case get_string('prevent', 'role'):
306 $permission = CAP_PREVENT;
307 break;
308 case get_string('prohibit', 'role'):
309 $permission = CAP_PROHIBIT;
310 break;
311 default:
312 throw new Exception('The \'' . $data['permission'] . '\' permission does not exist');
313 break;
316 if (is_null(get_capability_info($data['capability']))) {
317 throw new Exception('The \'' . $data['capability'] . '\' capability does not exist');
320 role_change_permission($data['roleid'], $context, $data['capability'], $permission);
324 * Assigns a role to a user at system context
326 * Used by "system role assigns" can be deleted when
327 * system role assign will be deprecated in favour of
328 * "role assigns"
330 * @throws Exception
331 * @param array $data
332 * @return void
334 protected function process_system_role_assign($data) {
336 if (empty($data['roleid'])) {
337 throw new Exception('\'system role assigns\' requires the field \'role\' to be specified');
340 if (!isset($data['userid'])) {
341 throw new Exception('\'system role assigns\' requires the field \'user\' to be specified');
344 $context = context_system::instance();
346 $this->datagenerator->role_assign($data['roleid'], $data['userid'], $context->id);
350 * Assigns a role to a user at the specified context
352 * @throws Exception
353 * @param array $data
354 * @return void
356 protected function process_role_assign($data) {
358 if (empty($data['roleid'])) {
359 throw new Exception('\'role assigns\' requires the field \'role\' to be specified');
362 if (!isset($data['userid'])) {
363 throw new Exception('\'role assigns\' requires the field \'user\' to be specified');
366 if (empty($data['contextlevel'])) {
367 throw new Exception('\'role assigns\' requires the field \'contextlevel\' to be specified');
370 if (!isset($data['reference'])) {
371 throw new Exception('\'role assigns\' requires the field \'reference\' to be specified');
374 // Getting the context id.
375 $context = $this->get_context($data['contextlevel'], $data['reference']);
377 $this->datagenerator->role_assign($data['roleid'], $data['userid'], $context->id);
381 * Creates a role.
383 * @param array $data
384 * @return void
386 protected function process_role($data) {
388 // We require the user to fill the role shortname.
389 if (empty($data['shortname'])) {
390 throw new Exception('\'role\' requires the field \'shortname\' to be specified');
393 $this->datagenerator->create_role($data);
397 * Gets the user id from it's username.
398 * @throws Exception
399 * @param string $username
400 * @return int
402 protected function get_user_id($username) {
403 global $DB;
405 if (!$id = $DB->get_field('user', 'id', array('username' => $username))) {
406 throw new Exception('The specified user with username "' . $username . '" does not exist');
408 return $id;
412 * Gets the role id from it's shortname.
413 * @throws Exception
414 * @param string $roleshortname
415 * @return int
417 protected function get_role_id($roleshortname) {
418 global $DB;
420 if (!$id = $DB->get_field('role', 'id', array('shortname' => $roleshortname))) {
421 throw new Exception('The specified role with shortname "' . $roleshortname . '" does not exist');
424 return $id;
428 * Gets the category id from it's idnumber.
429 * @throws Exception
430 * @param string $idnumber
431 * @return int
433 protected function get_category_id($idnumber) {
434 global $DB;
436 // If no category was specified use the data generator one.
437 if ($idnumber == false) {
438 return null;
441 if (!$id = $DB->get_field('course_categories', 'id', array('idnumber' => $idnumber))) {
442 throw new Exception('The specified category with idnumber "' . $idnumber . '" does not exist');
445 return $id;
449 * Gets the course id from it's shortname.
450 * @throws Exception
451 * @param string $shortname
452 * @return int
454 protected function get_course_id($shortname) {
455 global $DB;
457 if (!$id = $DB->get_field('course', 'id', array('shortname' => $shortname))) {
458 throw new Exception('The specified course with shortname "' . $shortname . '" does not exist');
460 return $id;
464 * Gets the group id from it's idnumber.
465 * @throws Exception
466 * @param string $idnumber
467 * @return int
469 protected function get_group_id($idnumber) {
470 global $DB;
472 if (!$id = $DB->get_field('groups', 'id', array('idnumber' => $idnumber))) {
473 throw new Exception('The specified group with idnumber "' . $idnumber . '" does not exist');
475 return $id;
479 * Gets the grouping id from it's idnumber.
480 * @throws Exception
481 * @param string $idnumber
482 * @return int
484 protected function get_grouping_id($idnumber) {
485 global $DB;
487 if (!$id = $DB->get_field('groupings', 'id', array('idnumber' => $idnumber))) {
488 throw new Exception('The specified grouping with idnumber "' . $idnumber . '" does not exist');
490 return $id;
494 * Gets the internal context id from the context reference.
496 * The context reference changes depending on the context
497 * level, it can be the system, a user, a category, a course or
498 * a module.
500 * @throws Exception
501 * @param string $levelname The context level string introduced by the test writer
502 * @param string $contextref The context reference introduced by the test writer
503 * @return context
505 protected function get_context($levelname, $contextref) {
506 global $DB;
508 // Getting context levels and names (we will be using the English ones as it is the test site language).
509 $contextlevels = context_helper::get_all_levels();
510 $contextnames = array();
511 foreach ($contextlevels as $level => $classname) {
512 $contextnames[context_helper::get_level_name($level)] = $level;
515 if (empty($contextnames[$levelname])) {
516 throw new Exception('The specified "' . $levelname . '" context level does not exist');
518 $contextlevel = $contextnames[$levelname];
520 // Return it, we don't need to look for other internal ids.
521 if ($contextlevel == CONTEXT_SYSTEM) {
522 return context_system::instance();
525 switch ($contextlevel) {
527 case CONTEXT_USER:
528 $instanceid = $DB->get_field('user', 'id', array('username' => $contextref));
529 break;
531 case CONTEXT_COURSECAT:
532 $instanceid = $DB->get_field('course_categories', 'id', array('idnumber' => $contextref));
533 break;
535 case CONTEXT_COURSE:
536 $instanceid = $DB->get_field('course', 'id', array('shortname' => $contextref));
537 break;
539 case CONTEXT_MODULE:
540 $instanceid = $DB->get_field('course_modules', 'id', array('idnumber' => $contextref));
541 break;
543 default:
544 break;
547 $contextclass = $contextlevels[$contextlevel];
548 if (!$context = $contextclass::instance($instanceid, IGNORE_MISSING)) {
549 throw new Exception('The specified "' . $contextref . '" context reference does not exist');
552 return $context;