weekly release 2.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;
31use Behat\Behat\Exception\PendingException as PendingException;
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')
94
95 ),
81cd8572
DM
96 'permission overrides' => array(
97 'datagenerator' => 'permission_override',
98 'required' => array('capability', 'permission', 'role', 'contextlevel', 'reference'),
99 'switchids' => array('role' => 'roleid')
100 ),
d2eca4cd 101 'system role assigns' => array(
72ddc05f 102 'datagenerator' => 'system_role_assign',
d2eca4cd
DM
103 'required' => array('user', 'role'),
104 'switchids' => array('user' => 'userid', 'role' => 'roleid')
105 ),
72ddc05f
DM
106 'role assigns' => array(
107 'datagenerator' => 'role_assign',
108 'required' => array('user', 'role', 'contextlevel', 'reference'),
109 'switchids' => array('user' => 'userid', 'role' => 'roleid')
110 ),
a0902967
DM
111 'activities' => array(
112 'datagenerator' => 'activity',
113 'required' => array('activity', 'idnumber', 'course'),
114 'switchids' => array('course' => 'course')
115 ),
f0200d14
DM
116 'group members' => array(
117 'datagenerator' => 'group_member',
118 'required' => array('user', 'group'),
119 'switchids' => array('user' => 'userid', 'group' => 'groupid')
120 ),
121 'grouping groups' => array(
122 'datagenerator' => 'grouping_group',
123 'required' => array('grouping', 'group'),
124 'switchids' => array('grouping' => 'groupingid', 'group' => 'groupid')
23349a73
DM
125 ),
126 'cohorts' => array(
127 'datagenerator' => 'cohort',
128 'required' => array('idnumber')
702851c0
DM
129 ),
130 'roles' => array(
131 'datagenerator' => 'role',
132 'required' => array('shortname')
f0200d14
DM
133 )
134 );
135
136 /**
137 * Creates the specified element. More info about available elements in http://docs.moodle.org/dev/Acceptance_testing#Fixtures.
138 *
c51c3b55 139 * @Given /^the following "(?P<element_string>(?:[^"]|\\")*)" exist:$/
f0200d14
DM
140 *
141 * @throws Exception
142 * @throws PendingException
143 * @param string $elementname The name of the entity to add
144 * @param TableNode $data
145 */
c51c3b55 146 public function the_following_exist($elementname, TableNode $data) {
f0200d14 147
c29e3e24
DM
148 // Now that we need them require the data generators.
149 require_once(__DIR__ . '/../../testing/generator/lib.php');
150
f0200d14
DM
151 if (empty(self::$elements[$elementname])) {
152 throw new PendingException($elementname . ' data generator is not implemented');
153 }
154
155 $this->datagenerator = testing_util::get_data_generator();
156
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'];
161 }
162
163 foreach ($data->getHash() as $elementdata) {
164
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');
169 }
170 }
171
172 // Switch from human-friendly references to ids.
173 if (isset($switchids)) {
174 foreach ($switchids as $element => $field) {
175 $methodname = 'get_' . $element . '_id';
176
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;
183 }
184 }
185 }
186
187 // Preprocess the entities that requires a special treatment.
188 if (method_exists($this, 'preprocess_' . $elementdatagenerator)) {
189 $elementdata = $this->{'preprocess_' . $elementdatagenerator}($elementdata);
190 }
191
192 // Creates element.
193 $methodname = 'create_' . $elementdatagenerator;
194 if (method_exists($this->datagenerator, $methodname)) {
195 // Using data generators directly.
196 $this->datagenerator->{$methodname}($elementdata);
197
d2eca4cd
DM
198 } else if (method_exists($this, 'process_' . $elementdatagenerator)) {
199 // Using an alternative to the direct data generator call.
200 $this->{'process_' . $elementdatagenerator}($elementdata);
f0200d14
DM
201 } else {
202 throw new PendingException($elementname . ' data generator is not implemented');
203 }
204 }
205
206 }
207
208 /**
209 * If password is not set it uses the username.
210 * @param array $data
211 * @return array
212 */
213 protected function preprocess_user($data) {
214 if (!isset($data['password'])) {
215 $data['password'] = $data['username'];
216 }
217 return $data;
218 }
219
5f079af4
MG
220 /**
221 * If contextlevel and reference are specified for cohort, transform them to the contextid.
222 *
223 * @param array $data
224 * @return array
225 */
226 protected function preprocess_cohort($data) {
227 if (isset($data['contextlevel'])) {
228 if (!isset($data['reference'])) {
229 throw new Exception('If field contextlevel is specified, field reference must also be present');
230 }
231 $context = $this->get_context($data['contextlevel'], $data['reference']);
232 unset($data['contextlevel']);
233 unset($data['reference']);
234 $data['contextid'] = $context->id;
235 }
236 return $data;
237 }
238
a0902967
DM
239 /**
240 * Adapter to modules generator
241 * @throws Exception Custom exception for test writers
242 * @param array $data
243 * @return void
244 */
245 protected function process_activity($data) {
041cf62b 246 global $DB;
a0902967
DM
247
248 // The the_following_exists() method checks that the field exists.
249 $activityname = $data['activity'];
250 unset($data['activity']);
251
041cf62b
DM
252 // We split $data in the activity $record and the course module $options.
253 $cmoptions = array();
254 $cmcolumns = $DB->get_columns('course_modules');
255 foreach ($cmcolumns as $key => $value) {
256 if (isset($data[$key])) {
257 $cmoptions[$key] = $data[$key];
258 }
259 }
260
a0902967
DM
261 // Custom exception.
262 try {
041cf62b 263 $this->datagenerator->create_module($activityname, $data, $cmoptions);
a0902967
DM
264 } catch (coding_exception $e) {
265 throw new Exception('\'' . $activityname . '\' activity can not be added using this step,' .
266 ' use the step \'I add a "ACTIVITY_OR_RESOURCE_NAME_STRING" to section "SECTION_NUMBER"\' instead');
267 }
268 }
f0200d14
DM
269
270 /**
271 * Adapter to enrol_user() data generator.
272 * @throws Exception
d2eca4cd 273 * @param array $data
f0200d14
DM
274 * @return void
275 */
d2eca4cd 276 protected function process_enrol_user($data) {
a8a48495 277 global $SITE;
f0200d14
DM
278
279 if (empty($data['roleid'])) {
280 throw new Exception('\'course enrolments\' requires the field \'role\' to be specified');
281 }
282
283 if (!isset($data['userid'])) {
284 throw new Exception('\'course enrolments\' requires the field \'user\' to be specified');
285 }
286
287 if (!isset($data['courseid'])) {
288 throw new Exception('\'course enrolments\' requires the field \'course\' to be specified');
289 }
290
291 if (!isset($data['enrol'])) {
292 $data['enrol'] = 'manual';
293 }
294
a8a48495
DM
295 // If the provided course shortname is the site shortname we consider it a system role assign.
296 if ($data['courseid'] == $SITE->id) {
297 // Frontpage course assign.
298 $context = context_course::instance($data['courseid']);
299 role_assign($data['roleid'], $data['userid'], $context->id);
300
301 } else {
302 // Course assign.
303 $this->datagenerator->enrol_user($data['userid'], $data['courseid'], $data['roleid'], $data['enrol']);
304 }
305
f0200d14
DM
306 }
307
81cd8572
DM
308 /**
309 * Allows/denies a capability at the specified context
310 *
311 * @throws Exception
312 * @param array $data
313 * @return void
314 */
315 protected function process_permission_override($data) {
316
317 // Will throw an exception if it does not exist.
318 $context = $this->get_context($data['contextlevel'], $data['reference']);
319
320 switch ($data['permission']) {
a5254141 321 case get_string('allow', 'role'):
81cd8572
DM
322 $permission = CAP_ALLOW;
323 break;
a5254141 324 case get_string('prevent', 'role'):
81cd8572
DM
325 $permission = CAP_PREVENT;
326 break;
a5254141 327 case get_string('prohibit', 'role'):
81cd8572
DM
328 $permission = CAP_PROHIBIT;
329 break;
330 default:
331 throw new Exception('The \'' . $data['permission'] . '\' permission does not exist');
332 break;
333 }
334
335 if (is_null(get_capability_info($data['capability']))) {
336 throw new Exception('The \'' . $data['capability'] . '\' capability does not exist');
337 }
338
339 role_change_permission($data['roleid'], $context, $data['capability'], $permission);
340 }
341
d2eca4cd 342 /**
72ddc05f
DM
343 * Assigns a role to a user at system context
344 *
345 * Used by "system role assigns" can be deleted when
346 * system role assign will be deprecated in favour of
347 * "role assigns"
348 *
d2eca4cd
DM
349 * @throws Exception
350 * @param array $data
351 * @return void
352 */
72ddc05f 353 protected function process_system_role_assign($data) {
d2eca4cd
DM
354
355 if (empty($data['roleid'])) {
356 throw new Exception('\'system role assigns\' requires the field \'role\' to be specified');
357 }
358
359 if (!isset($data['userid'])) {
360 throw new Exception('\'system role assigns\' requires the field \'user\' to be specified');
361 }
362
363 $context = context_system::instance();
72ddc05f
DM
364
365 $this->datagenerator->role_assign($data['roleid'], $data['userid'], $context->id);
366 }
367
368 /**
369 * Assigns a role to a user at the specified context
370 *
371 * @throws Exception
372 * @param array $data
373 * @return void
374 */
375 protected function process_role_assign($data) {
376
377 if (empty($data['roleid'])) {
378 throw new Exception('\'role assigns\' requires the field \'role\' to be specified');
379 }
380
381 if (!isset($data['userid'])) {
382 throw new Exception('\'role assigns\' requires the field \'user\' to be specified');
383 }
384
385 if (empty($data['contextlevel'])) {
386 throw new Exception('\'role assigns\' requires the field \'contextlevel\' to be specified');
387 }
388
389 if (!isset($data['reference'])) {
390 throw new Exception('\'role assigns\' requires the field \'reference\' to be specified');
391 }
392
393 // Getting the context id.
394 $context = $this->get_context($data['contextlevel'], $data['reference']);
395
396 $this->datagenerator->role_assign($data['roleid'], $data['userid'], $context->id);
f0200d14
DM
397 }
398
702851c0
DM
399 /**
400 * Creates a role.
401 *
402 * @param array $data
403 * @return void
404 */
405 protected function process_role($data) {
406
407 // We require the user to fill the role shortname.
408 if (empty($data['shortname'])) {
409 throw new Exception('\'role\' requires the field \'shortname\' to be specified');
410 }
411
412 $this->datagenerator->create_role($data);
413 }
414
f0200d14
DM
415 /**
416 * Gets the user id from it's username.
417 * @throws Exception
46ac40cd 418 * @param string $username
f0200d14
DM
419 * @return int
420 */
421 protected function get_user_id($username) {
422 global $DB;
423
424 if (!$id = $DB->get_field('user', 'id', array('username' => $username))) {
1f9ffbdb 425 throw new Exception('The specified user with username "' . $username . '" does not exist');
f0200d14
DM
426 }
427 return $id;
428 }
429
430 /**
431 * Gets the role id from it's shortname.
432 * @throws Exception
46ac40cd 433 * @param string $roleshortname
f0200d14
DM
434 * @return int
435 */
436 protected function get_role_id($roleshortname) {
437 global $DB;
438
439 if (!$id = $DB->get_field('role', 'id', array('shortname' => $roleshortname))) {
702851c0 440 throw new Exception('The specified role with shortname "' . $roleshortname . '" does not exist');
f0200d14
DM
441 }
442
443 return $id;
444 }
445
446 /**
447 * Gets the category id from it's idnumber.
448 * @throws Exception
449 * @param string $idnumber
450 * @return int
451 */
452 protected function get_category_id($idnumber) {
453 global $DB;
454
455 // If no category was specified use the data generator one.
456 if ($idnumber == false) {
457 return null;
458 }
459
460 if (!$id = $DB->get_field('course_categories', 'id', array('idnumber' => $idnumber))) {
1f9ffbdb 461 throw new Exception('The specified category with idnumber "' . $idnumber . '" does not exist');
f0200d14
DM
462 }
463
464 return $id;
465 }
466
467 /**
468 * Gets the course id from it's shortname.
469 * @throws Exception
470 * @param string $shortname
471 * @return int
472 */
473 protected function get_course_id($shortname) {
474 global $DB;
475
476 if (!$id = $DB->get_field('course', 'id', array('shortname' => $shortname))) {
702851c0 477 throw new Exception('The specified course with shortname "' . $shortname . '" does not exist');
f0200d14
DM
478 }
479 return $id;
480 }
481
482 /**
483 * Gets the group id from it's idnumber.
484 * @throws Exception
485 * @param string $idnumber
486 * @return int
487 */
488 protected function get_group_id($idnumber) {
489 global $DB;
490
491 if (!$id = $DB->get_field('groups', 'id', array('idnumber' => $idnumber))) {
1f9ffbdb 492 throw new Exception('The specified group with idnumber "' . $idnumber . '" does not exist');
f0200d14
DM
493 }
494 return $id;
495 }
496
497 /**
498 * Gets the grouping id from it's idnumber.
499 * @throws Exception
500 * @param string $idnumber
501 * @return int
502 */
503 protected function get_grouping_id($idnumber) {
504 global $DB;
505
506 if (!$id = $DB->get_field('groupings', 'id', array('idnumber' => $idnumber))) {
1f9ffbdb 507 throw new Exception('The specified grouping with idnumber "' . $idnumber . '" does not exist');
f0200d14
DM
508 }
509 return $id;
510 }
72ddc05f
DM
511
512 /**
513 * Gets the internal context id from the context reference.
514 *
515 * The context reference changes depending on the context
516 * level, it can be the system, a user, a category, a course or
517 * a module.
518 *
519 * @throws Exception
520 * @param string $levelname The context level string introduced by the test writer
521 * @param string $contextref The context reference introduced by the test writer
522 * @return context
523 */
524 protected function get_context($levelname, $contextref) {
525 global $DB;
526
527 // Getting context levels and names (we will be using the English ones as it is the test site language).
528 $contextlevels = context_helper::get_all_levels();
529 $contextnames = array();
530 foreach ($contextlevels as $level => $classname) {
531 $contextnames[context_helper::get_level_name($level)] = $level;
532 }
533
534 if (empty($contextnames[$levelname])) {
535 throw new Exception('The specified "' . $levelname . '" context level does not exist');
536 }
537 $contextlevel = $contextnames[$levelname];
538
539 // Return it, we don't need to look for other internal ids.
540 if ($contextlevel == CONTEXT_SYSTEM) {
541 return context_system::instance();
542 }
543
544 switch ($contextlevel) {
545
546 case CONTEXT_USER:
547 $instanceid = $DB->get_field('user', 'id', array('username' => $contextref));
548 break;
549
550 case CONTEXT_COURSECAT:
551 $instanceid = $DB->get_field('course_categories', 'id', array('idnumber' => $contextref));
552 break;
553
554 case CONTEXT_COURSE:
555 $instanceid = $DB->get_field('course', 'id', array('shortname' => $contextref));
556 break;
557
558 case CONTEXT_MODULE:
559 $instanceid = $DB->get_field('course_modules', 'id', array('idnumber' => $contextref));
560 break;
561
562 default:
563 break;
564 }
565
566 $contextclass = $contextlevels[$contextlevel];
567 if (!$context = $contextclass::instance($instanceid, IGNORE_MISSING)) {
568 throw new Exception('The specified "' . $contextref . '" context reference does not exist');
569 }
570
571 return $context;
572 }
573
f0200d14 574}