weekly release 2.7dev
[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
81cd8572
DM
53 const cap_allow = 'Allow';
54 const cap_prevent = 'Prevent';
55 const cap_prohibit = 'Prohibit';
56
46ac40cd
DM
57 /**
58 * @var testing_data_generator
59 */
f0200d14
DM
60 protected $datagenerator;
61
62 /**
63 * Each element specifies:
64 * - The data generator sufix used.
65 * - The required fields.
66 * - The mapping between other elements references and database field names.
67 * @var array
68 */
69 protected static $elements = array(
70 'users' => array(
71 'datagenerator' => 'user',
72 'required' => array('username')
73 ),
74 'categories' => array(
75 'datagenerator' => 'category',
76 'required' => array('idnumber'),
77 'switchids' => array('category' => 'parent')
78 ),
79 'courses' => array(
80 'datagenerator' => 'course',
81 'required' => array('shortname'),
82 'switchids' => array('category' => 'category')
83 ),
84 'groups' => array(
85 'datagenerator' => 'group',
86 'required' => array('idnumber', 'course'),
87 'switchids' => array('course' => 'courseid')
88 ),
89 'groupings' => array(
90 'datagenerator' => 'grouping',
91 'required' => array('idnumber', 'course'),
92 'switchids' => array('course' => 'courseid')
93 ),
94 'course enrolments' => array(
95 'datagenerator' => 'enrol_user',
96 'required' => array('user', 'course', 'role'),
97 'switchids' => array('user' => 'userid', 'course' => 'courseid', 'role' => 'roleid')
98
99 ),
81cd8572
DM
100 'permission overrides' => array(
101 'datagenerator' => 'permission_override',
102 'required' => array('capability', 'permission', 'role', 'contextlevel', 'reference'),
103 'switchids' => array('role' => 'roleid')
104 ),
d2eca4cd 105 'system role assigns' => array(
72ddc05f 106 'datagenerator' => 'system_role_assign',
d2eca4cd
DM
107 'required' => array('user', 'role'),
108 'switchids' => array('user' => 'userid', 'role' => 'roleid')
109 ),
72ddc05f
DM
110 'role assigns' => array(
111 'datagenerator' => 'role_assign',
112 'required' => array('user', 'role', 'contextlevel', 'reference'),
113 'switchids' => array('user' => 'userid', 'role' => 'roleid')
114 ),
a0902967
DM
115 'activities' => array(
116 'datagenerator' => 'activity',
117 'required' => array('activity', 'idnumber', 'course'),
118 'switchids' => array('course' => 'course')
119 ),
f0200d14
DM
120 'group members' => array(
121 'datagenerator' => 'group_member',
122 'required' => array('user', 'group'),
123 'switchids' => array('user' => 'userid', 'group' => 'groupid')
124 ),
125 'grouping groups' => array(
126 'datagenerator' => 'grouping_group',
127 'required' => array('grouping', 'group'),
128 'switchids' => array('grouping' => 'groupingid', 'group' => 'groupid')
23349a73
DM
129 ),
130 'cohorts' => array(
131 'datagenerator' => 'cohort',
132 'required' => array('idnumber')
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 *
139 * @Given /^the following "(?P<element_string>(?:[^"]|\\")*)" exists:$/
140 *
141 * @throws Exception
142 * @throws PendingException
143 * @param string $elementname The name of the entity to add
144 * @param TableNode $data
145 */
146 public function the_following_exists($elementname, TableNode $data) {
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
a0902967
DM
220 /**
221 * Adapter to modules generator
222 * @throws Exception Custom exception for test writers
223 * @param array $data
224 * @return void
225 */
226 protected function process_activity($data) {
041cf62b 227 global $DB;
a0902967
DM
228
229 // The the_following_exists() method checks that the field exists.
230 $activityname = $data['activity'];
231 unset($data['activity']);
232
041cf62b
DM
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];
239 }
240 }
241
a0902967
DM
242 // Custom exception.
243 try {
041cf62b 244 $this->datagenerator->create_module($activityname, $data, $cmoptions);
a0902967
DM
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');
248 }
249 }
f0200d14
DM
250
251 /**
252 * Adapter to enrol_user() data generator.
253 * @throws Exception
d2eca4cd 254 * @param array $data
f0200d14
DM
255 * @return void
256 */
d2eca4cd 257 protected function process_enrol_user($data) {
a8a48495 258 global $SITE;
f0200d14
DM
259
260 if (empty($data['roleid'])) {
261 throw new Exception('\'course enrolments\' requires the field \'role\' to be specified');
262 }
263
264 if (!isset($data['userid'])) {
265 throw new Exception('\'course enrolments\' requires the field \'user\' to be specified');
266 }
267
268 if (!isset($data['courseid'])) {
269 throw new Exception('\'course enrolments\' requires the field \'course\' to be specified');
270 }
271
272 if (!isset($data['enrol'])) {
273 $data['enrol'] = 'manual';
274 }
275
a8a48495
DM
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);
281
282 } else {
283 // Course assign.
284 $this->datagenerator->enrol_user($data['userid'], $data['courseid'], $data['roleid'], $data['enrol']);
285 }
286
f0200d14
DM
287 }
288
81cd8572
DM
289 /**
290 * Allows/denies a capability at the specified context
291 *
292 * @throws Exception
293 * @param array $data
294 * @return void
295 */
296 protected function process_permission_override($data) {
297
298 // Will throw an exception if it does not exist.
299 $context = $this->get_context($data['contextlevel'], $data['reference']);
300
301 switch ($data['permission']) {
302 case self::cap_allow:
303 $permission = CAP_ALLOW;
304 break;
305 case self::cap_prevent:
306 $permission = CAP_PREVENT;
307 break;
308 case self::cap_prohibit:
309 $permission = CAP_PROHIBIT;
310 break;
311 default:
312 throw new Exception('The \'' . $data['permission'] . '\' permission does not exist');
313 break;
314 }
315
316 if (is_null(get_capability_info($data['capability']))) {
317 throw new Exception('The \'' . $data['capability'] . '\' capability does not exist');
318 }
319
320 role_change_permission($data['roleid'], $context, $data['capability'], $permission);
321 }
322
d2eca4cd 323 /**
72ddc05f
DM
324 * Assigns a role to a user at system context
325 *
326 * Used by "system role assigns" can be deleted when
327 * system role assign will be deprecated in favour of
328 * "role assigns"
329 *
d2eca4cd
DM
330 * @throws Exception
331 * @param array $data
332 * @return void
333 */
72ddc05f 334 protected function process_system_role_assign($data) {
d2eca4cd
DM
335
336 if (empty($data['roleid'])) {
337 throw new Exception('\'system role assigns\' requires the field \'role\' to be specified');
338 }
339
340 if (!isset($data['userid'])) {
341 throw new Exception('\'system role assigns\' requires the field \'user\' to be specified');
342 }
343
344 $context = context_system::instance();
72ddc05f
DM
345
346 $this->datagenerator->role_assign($data['roleid'], $data['userid'], $context->id);
347 }
348
349 /**
350 * Assigns a role to a user at the specified context
351 *
352 * @throws Exception
353 * @param array $data
354 * @return void
355 */
356 protected function process_role_assign($data) {
357
358 if (empty($data['roleid'])) {
359 throw new Exception('\'role assigns\' requires the field \'role\' to be specified');
360 }
361
362 if (!isset($data['userid'])) {
363 throw new Exception('\'role assigns\' requires the field \'user\' to be specified');
364 }
365
366 if (empty($data['contextlevel'])) {
367 throw new Exception('\'role assigns\' requires the field \'contextlevel\' to be specified');
368 }
369
370 if (!isset($data['reference'])) {
371 throw new Exception('\'role assigns\' requires the field \'reference\' to be specified');
372 }
373
374 // Getting the context id.
375 $context = $this->get_context($data['contextlevel'], $data['reference']);
376
377 $this->datagenerator->role_assign($data['roleid'], $data['userid'], $context->id);
f0200d14
DM
378 }
379
380 /**
381 * Gets the user id from it's username.
382 * @throws Exception
46ac40cd 383 * @param string $username
f0200d14
DM
384 * @return int
385 */
386 protected function get_user_id($username) {
387 global $DB;
388
389 if (!$id = $DB->get_field('user', 'id', array('username' => $username))) {
1f9ffbdb 390 throw new Exception('The specified user with username "' . $username . '" does not exist');
f0200d14
DM
391 }
392 return $id;
393 }
394
395 /**
396 * Gets the role id from it's shortname.
397 * @throws Exception
46ac40cd 398 * @param string $roleshortname
f0200d14
DM
399 * @return int
400 */
401 protected function get_role_id($roleshortname) {
402 global $DB;
403
404 if (!$id = $DB->get_field('role', 'id', array('shortname' => $roleshortname))) {
1f9ffbdb 405 throw new Exception('The specified role with shortname"' . $roleshortname . '" does not exist');
f0200d14
DM
406 }
407
408 return $id;
409 }
410
411 /**
412 * Gets the category id from it's idnumber.
413 * @throws Exception
414 * @param string $idnumber
415 * @return int
416 */
417 protected function get_category_id($idnumber) {
418 global $DB;
419
420 // If no category was specified use the data generator one.
421 if ($idnumber == false) {
422 return null;
423 }
424
425 if (!$id = $DB->get_field('course_categories', 'id', array('idnumber' => $idnumber))) {
1f9ffbdb 426 throw new Exception('The specified category with idnumber "' . $idnumber . '" does not exist');
f0200d14
DM
427 }
428
429 return $id;
430 }
431
432 /**
433 * Gets the course id from it's shortname.
434 * @throws Exception
435 * @param string $shortname
436 * @return int
437 */
438 protected function get_course_id($shortname) {
439 global $DB;
440
441 if (!$id = $DB->get_field('course', 'id', array('shortname' => $shortname))) {
1f9ffbdb 442 throw new Exception('The specified course with shortname"' . $shortname . '" does not exist');
f0200d14
DM
443 }
444 return $id;
445 }
446
447 /**
448 * Gets the group id from it's idnumber.
449 * @throws Exception
450 * @param string $idnumber
451 * @return int
452 */
453 protected function get_group_id($idnumber) {
454 global $DB;
455
456 if (!$id = $DB->get_field('groups', 'id', array('idnumber' => $idnumber))) {
1f9ffbdb 457 throw new Exception('The specified group with idnumber "' . $idnumber . '" does not exist');
f0200d14
DM
458 }
459 return $id;
460 }
461
462 /**
463 * Gets the grouping id from it's idnumber.
464 * @throws Exception
465 * @param string $idnumber
466 * @return int
467 */
468 protected function get_grouping_id($idnumber) {
469 global $DB;
470
471 if (!$id = $DB->get_field('groupings', 'id', array('idnumber' => $idnumber))) {
1f9ffbdb 472 throw new Exception('The specified grouping with idnumber "' . $idnumber . '" does not exist');
f0200d14
DM
473 }
474 return $id;
475 }
72ddc05f
DM
476
477 /**
478 * Gets the internal context id from the context reference.
479 *
480 * The context reference changes depending on the context
481 * level, it can be the system, a user, a category, a course or
482 * a module.
483 *
484 * @throws Exception
485 * @param string $levelname The context level string introduced by the test writer
486 * @param string $contextref The context reference introduced by the test writer
487 * @return context
488 */
489 protected function get_context($levelname, $contextref) {
490 global $DB;
491
492 // Getting context levels and names (we will be using the English ones as it is the test site language).
493 $contextlevels = context_helper::get_all_levels();
494 $contextnames = array();
495 foreach ($contextlevels as $level => $classname) {
496 $contextnames[context_helper::get_level_name($level)] = $level;
497 }
498
499 if (empty($contextnames[$levelname])) {
500 throw new Exception('The specified "' . $levelname . '" context level does not exist');
501 }
502 $contextlevel = $contextnames[$levelname];
503
504 // Return it, we don't need to look for other internal ids.
505 if ($contextlevel == CONTEXT_SYSTEM) {
506 return context_system::instance();
507 }
508
509 switch ($contextlevel) {
510
511 case CONTEXT_USER:
512 $instanceid = $DB->get_field('user', 'id', array('username' => $contextref));
513 break;
514
515 case CONTEXT_COURSECAT:
516 $instanceid = $DB->get_field('course_categories', 'id', array('idnumber' => $contextref));
517 break;
518
519 case CONTEXT_COURSE:
520 $instanceid = $DB->get_field('course', 'id', array('shortname' => $contextref));
521 break;
522
523 case CONTEXT_MODULE:
524 $instanceid = $DB->get_field('course_modules', 'id', array('idnumber' => $contextref));
525 break;
526
527 default:
528 break;
529 }
530
531 $contextclass = $contextlevels[$contextlevel];
532 if (!$context = $contextclass::instance($instanceid, IGNORE_MISSING)) {
533 throw new Exception('The specified "' . $contextref . '" context reference does not exist');
534 }
535
536 return $context;
537 }
538
f0200d14 539}