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