PageRenderTime 49ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/tests/behat/behat_data_generators.php

https://bitbucket.org/synergylearning/campusconnect
PHP | 575 lines | 303 code | 82 blank | 190 comment | 42 complexity | edb129941d6026c1bd7600b313e1ea8e MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception, LGPL-3.0, GPL-3.0, LGPL-2.1, Apache-2.0, BSD-3-Clause, AGPL-3.0
  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.
  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. * Data generators for acceptance testing.
  18. *
  19. * @package core
  20. * @category test
  21. * @copyright 2012 David Monllaรณ
  22. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  23. */
  24. // NOTE: no MOODLE_INTERNAL test here, this file may be required by behat before including /config.php.
  25. require_once(__DIR__ . '/../../behat/behat_base.php');
  26. use Behat\Gherkin\Node\TableNode as TableNode;
  27. use Behat\Behat\Exception\PendingException as PendingException;
  28. /**
  29. * Class to set up quickly a Given environment.
  30. *
  31. * Acceptance tests are block-boxed, so this steps definitions should only
  32. * be used to set up the test environment as we are not replicating user steps.
  33. *
  34. * All data generators should be in lib/testing/generator/*, shared between phpunit
  35. * and behat and they should be called from here, if possible using the standard
  36. * 'create_$elementname($options)' and if it's not possible (data generators arguments will not be
  37. * always the same) or the element is not suitable to be a data generator, create a
  38. * 'process_$elementname($options)' method and use the data generator from there if possible.
  39. *
  40. * @todo If the available elements list grows too much this class must be split into smaller pieces
  41. * @package core
  42. * @category test
  43. * @copyright 2012 David Monllaรณ
  44. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  45. */
  46. class behat_data_generators extends behat_base {
  47. const cap_allow = 'Allow';
  48. const cap_prevent = 'Prevent';
  49. const cap_prohibit = 'Prohibit';
  50. /**
  51. * @var testing_data_generator
  52. */
  53. protected $datagenerator;
  54. /**
  55. * Each element specifies:
  56. * - The data generator sufix used.
  57. * - The required fields.
  58. * - The mapping between other elements references and database field names.
  59. * @var array
  60. */
  61. protected static $elements = array(
  62. 'users' => array(
  63. 'datagenerator' => 'user',
  64. 'required' => array('username')
  65. ),
  66. 'categories' => array(
  67. 'datagenerator' => 'category',
  68. 'required' => array('idnumber'),
  69. 'switchids' => array('category' => 'parent')
  70. ),
  71. 'courses' => array(
  72. 'datagenerator' => 'course',
  73. 'required' => array('shortname'),
  74. 'switchids' => array('category' => 'category')
  75. ),
  76. 'groups' => array(
  77. 'datagenerator' => 'group',
  78. 'required' => array('idnumber', 'course'),
  79. 'switchids' => array('course' => 'courseid')
  80. ),
  81. 'groupings' => array(
  82. 'datagenerator' => 'grouping',
  83. 'required' => array('idnumber', 'course'),
  84. 'switchids' => array('course' => 'courseid')
  85. ),
  86. 'course enrolments' => array(
  87. 'datagenerator' => 'enrol_user',
  88. 'required' => array('user', 'course', 'role'),
  89. 'switchids' => array('user' => 'userid', 'course' => 'courseid', 'role' => 'roleid')
  90. ),
  91. 'permission overrides' => array(
  92. 'datagenerator' => 'permission_override',
  93. 'required' => array('capability', 'permission', 'role', 'contextlevel', 'reference'),
  94. 'switchids' => array('role' => 'roleid')
  95. ),
  96. 'system role assigns' => array(
  97. 'datagenerator' => 'system_role_assign',
  98. 'required' => array('user', 'role'),
  99. 'switchids' => array('user' => 'userid', 'role' => 'roleid')
  100. ),
  101. 'role assigns' => array(
  102. 'datagenerator' => 'role_assign',
  103. 'required' => array('user', 'role', 'contextlevel', 'reference'),
  104. 'switchids' => array('user' => 'userid', 'role' => 'roleid')
  105. ),
  106. 'activities' => array(
  107. 'datagenerator' => 'activity',
  108. 'required' => array('activity', 'idnumber', 'course'),
  109. 'switchids' => array('course' => 'course')
  110. ),
  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')
  120. ),
  121. 'cohorts' => array(
  122. 'datagenerator' => 'cohort',
  123. 'required' => array('idnumber')
  124. )
  125. );
  126. /**
  127. * Creates the specified element. More info about available elements in http://docs.moodle.org/dev/Acceptance_testing#Fixtures.
  128. *
  129. * This method has been introduced in 2.7 and replaces self::the_following_exists(),
  130. * it has been added here to make backports easier and to help 3rd parties working on new
  131. * scenarios so they don't need to update their scenarios when they upgrade to 2.7.
  132. *
  133. * @Given /^the following "(?P<element_string>(?:[^"]|\\")*)" exist:$/
  134. *
  135. * @param string $elementname The name of the entity to add
  136. * @param TableNode $data
  137. */
  138. public function the_following_exist($elementname, TableNode $data) {
  139. // Forwarding it.
  140. $this->the_following_exists($elementname, $data);
  141. }
  142. /**
  143. * Creates the specified element. More info about available elements in http://docs.moodle.org/dev/Acceptance_testing#Fixtures. This step will be deprecated in Moodle 2.7 in favour of 'the following "ELEMENT_STRING" exist:'.
  144. *
  145. * @Given /^the following "(?P<element_string>(?:[^"]|\\")*)" exists:$/
  146. *
  147. * @throws Exception
  148. * @throws PendingException
  149. * @param string $elementname The name of the entity to add
  150. * @param TableNode $data
  151. */
  152. public function the_following_exists($elementname, TableNode $data) {
  153. // Now that we need them require the data generators.
  154. require_once(__DIR__ . '/../../testing/generator/lib.php');
  155. if (empty(self::$elements[$elementname])) {
  156. throw new PendingException($elementname . ' data generator is not implemented');
  157. }
  158. $this->datagenerator = testing_util::get_data_generator();
  159. $elementdatagenerator = self::$elements[$elementname]['datagenerator'];
  160. $requiredfields = self::$elements[$elementname]['required'];
  161. if (!empty(self::$elements[$elementname]['switchids'])) {
  162. $switchids = self::$elements[$elementname]['switchids'];
  163. }
  164. 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');
  169. }
  170. }
  171. // Switch from human-friendly references to ids.
  172. if (isset($switchids)) {
  173. foreach ($switchids as $element => $field) {
  174. $methodname = 'get_' . $element . '_id';
  175. // Not all the switch fields are required, default vars will be assigned by data generators.
  176. if (isset($elementdata[$element])) {
  177. // Temp $id var to avoid problems when $element == $field.
  178. $id = $this->{$methodname}($elementdata[$element]);
  179. unset($elementdata[$element]);
  180. $elementdata[$field] = $id;
  181. }
  182. }
  183. }
  184. // Preprocess the entities that requires a special treatment.
  185. if (method_exists($this, 'preprocess_' . $elementdatagenerator)) {
  186. $elementdata = $this->{'preprocess_' . $elementdatagenerator}($elementdata);
  187. }
  188. // Creates element.
  189. $methodname = 'create_' . $elementdatagenerator;
  190. if (method_exists($this->datagenerator, $methodname)) {
  191. // Using data generators directly.
  192. $this->datagenerator->{$methodname}($elementdata);
  193. } else if (method_exists($this, 'process_' . $elementdatagenerator)) {
  194. // Using an alternative to the direct data generator call.
  195. $this->{'process_' . $elementdatagenerator}($elementdata);
  196. } else {
  197. throw new PendingException($elementname . ' data generator is not implemented');
  198. }
  199. }
  200. }
  201. /**
  202. * If password is not set it uses the username.
  203. * @param array $data
  204. * @return array
  205. */
  206. protected function preprocess_user($data) {
  207. if (!isset($data['password'])) {
  208. $data['password'] = $data['username'];
  209. }
  210. return $data;
  211. }
  212. /**
  213. * If contextlevel and reference are specified for cohort, transform them to the contextid.
  214. *
  215. * @param array $data
  216. * @return array
  217. */
  218. protected function preprocess_cohort($data) {
  219. if (isset($data['contextlevel'])) {
  220. if (!isset($data['reference'])) {
  221. throw new Exception('If field contextlevel is specified, field reference must also be present');
  222. }
  223. $context = $this->get_context($data['contextlevel'], $data['reference']);
  224. unset($data['contextlevel']);
  225. unset($data['reference']);
  226. $data['contextid'] = $context->id;
  227. }
  228. return $data;
  229. }
  230. /**
  231. * Adapter to modules generator
  232. * @throws Exception Custom exception for test writers
  233. * @param array $data
  234. * @return void
  235. */
  236. protected function process_activity($data) {
  237. global $DB;
  238. // The the_following_exists() method checks that the field exists.
  239. $activityname = $data['activity'];
  240. unset($data['activity']);
  241. // We split $data in the activity $record and the course module $options.
  242. $cmoptions = array();
  243. $cmcolumns = $DB->get_columns('course_modules');
  244. foreach ($cmcolumns as $key => $value) {
  245. if (isset($data[$key])) {
  246. $cmoptions[$key] = $data[$key];
  247. }
  248. }
  249. // Custom exception.
  250. try {
  251. $this->datagenerator->create_module($activityname, $data, $cmoptions);
  252. } catch (coding_exception $e) {
  253. throw new Exception('\'' . $activityname . '\' activity can not be added using this step,' .
  254. ' use the step \'I add a "ACTIVITY_OR_RESOURCE_NAME_STRING" to section "SECTION_NUMBER"\' instead');
  255. }
  256. }
  257. /**
  258. * Adapter to enrol_user() data generator.
  259. * @throws Exception
  260. * @param array $data
  261. * @return void
  262. */
  263. protected function process_enrol_user($data) {
  264. global $SITE;
  265. if (empty($data['roleid'])) {
  266. throw new Exception('\'course enrolments\' requires the field \'role\' to be specified');
  267. }
  268. if (!isset($data['userid'])) {
  269. throw new Exception('\'course enrolments\' requires the field \'user\' to be specified');
  270. }
  271. if (!isset($data['courseid'])) {
  272. throw new Exception('\'course enrolments\' requires the field \'course\' to be specified');
  273. }
  274. if (!isset($data['enrol'])) {
  275. $data['enrol'] = 'manual';
  276. }
  277. // If the provided course shortname is the site shortname we consider it a system role assign.
  278. if ($data['courseid'] == $SITE->id) {
  279. // Frontpage course assign.
  280. $context = context_course::instance($data['courseid']);
  281. 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']);
  285. }
  286. }
  287. /**
  288. * Allows/denies a capability at the specified context
  289. *
  290. * @throws Exception
  291. * @param array $data
  292. * @return void
  293. */
  294. protected function process_permission_override($data) {
  295. // Will throw an exception if it does not exist.
  296. $context = $this->get_context($data['contextlevel'], $data['reference']);
  297. switch ($data['permission']) {
  298. case get_string('allow', 'role'):
  299. $permission = CAP_ALLOW;
  300. break;
  301. case get_string('prevent', 'role'):
  302. $permission = CAP_PREVENT;
  303. break;
  304. case get_string('prohibit', 'role'):
  305. $permission = CAP_PROHIBIT;
  306. break;
  307. default:
  308. throw new Exception('The \'' . $data['permission'] . '\' permission does not exist');
  309. break;
  310. }
  311. if (is_null(get_capability_info($data['capability']))) {
  312. throw new Exception('The \'' . $data['capability'] . '\' capability does not exist');
  313. }
  314. role_change_permission($data['roleid'], $context, $data['capability'], $permission);
  315. }
  316. /**
  317. * Assigns a role to a user at system context
  318. *
  319. * Used by "system role assigns" can be deleted when
  320. * system role assign will be deprecated in favour of
  321. * "role assigns"
  322. *
  323. * @throws Exception
  324. * @param array $data
  325. * @return void
  326. */
  327. protected function process_system_role_assign($data) {
  328. if (empty($data['roleid'])) {
  329. throw new Exception('\'system role assigns\' requires the field \'role\' to be specified');
  330. }
  331. if (!isset($data['userid'])) {
  332. throw new Exception('\'system role assigns\' requires the field \'user\' to be specified');
  333. }
  334. $context = context_system::instance();
  335. $this->datagenerator->role_assign($data['roleid'], $data['userid'], $context->id);
  336. }
  337. /**
  338. * Assigns a role to a user at the specified context
  339. *
  340. * @throws Exception
  341. * @param array $data
  342. * @return void
  343. */
  344. protected function process_role_assign($data) {
  345. if (empty($data['roleid'])) {
  346. throw new Exception('\'role assigns\' requires the field \'role\' to be specified');
  347. }
  348. if (!isset($data['userid'])) {
  349. throw new Exception('\'role assigns\' requires the field \'user\' to be specified');
  350. }
  351. if (empty($data['contextlevel'])) {
  352. throw new Exception('\'role assigns\' requires the field \'contextlevel\' to be specified');
  353. }
  354. if (!isset($data['reference'])) {
  355. throw new Exception('\'role assigns\' requires the field \'reference\' to be specified');
  356. }
  357. // Getting the context id.
  358. $context = $this->get_context($data['contextlevel'], $data['reference']);
  359. $this->datagenerator->role_assign($data['roleid'], $data['userid'], $context->id);
  360. }
  361. /**
  362. * Gets the user id from it's username.
  363. * @throws Exception
  364. * @param string $username
  365. * @return int
  366. */
  367. protected function get_user_id($username) {
  368. global $DB;
  369. if (!$id = $DB->get_field('user', 'id', array('username' => $username))) {
  370. throw new Exception('The specified user with username "' . $username . '" does not exist');
  371. }
  372. return $id;
  373. }
  374. /**
  375. * Gets the role id from it's shortname.
  376. * @throws Exception
  377. * @param string $roleshortname
  378. * @return int
  379. */
  380. protected function get_role_id($roleshortname) {
  381. global $DB;
  382. if (!$id = $DB->get_field('role', 'id', array('shortname' => $roleshortname))) {
  383. throw new Exception('The specified role with shortname"' . $roleshortname . '" does not exist');
  384. }
  385. return $id;
  386. }
  387. /**
  388. * Gets the category id from it's idnumber.
  389. * @throws Exception
  390. * @param string $idnumber
  391. * @return int
  392. */
  393. protected function get_category_id($idnumber) {
  394. global $DB;
  395. // If no category was specified use the data generator one.
  396. if ($idnumber == false) {
  397. return null;
  398. }
  399. if (!$id = $DB->get_field('course_categories', 'id', array('idnumber' => $idnumber))) {
  400. throw new Exception('The specified category with idnumber "' . $idnumber . '" does not exist');
  401. }
  402. return $id;
  403. }
  404. /**
  405. * Gets the course id from it's shortname.
  406. * @throws Exception
  407. * @param string $shortname
  408. * @return int
  409. */
  410. protected function get_course_id($shortname) {
  411. global $DB;
  412. if (!$id = $DB->get_field('course', 'id', array('shortname' => $shortname))) {
  413. throw new Exception('The specified course with shortname"' . $shortname . '" does not exist');
  414. }
  415. return $id;
  416. }
  417. /**
  418. * Gets the group id from it's idnumber.
  419. * @throws Exception
  420. * @param string $idnumber
  421. * @return int
  422. */
  423. protected function get_group_id($idnumber) {
  424. global $DB;
  425. if (!$id = $DB->get_field('groups', 'id', array('idnumber' => $idnumber))) {
  426. throw new Exception('The specified group with idnumber "' . $idnumber . '" does not exist');
  427. }
  428. return $id;
  429. }
  430. /**
  431. * Gets the grouping id from it's idnumber.
  432. * @throws Exception
  433. * @param string $idnumber
  434. * @return int
  435. */
  436. protected function get_grouping_id($idnumber) {
  437. global $DB;
  438. if (!$id = $DB->get_field('groupings', 'id', array('idnumber' => $idnumber))) {
  439. throw new Exception('The specified grouping with idnumber "' . $idnumber . '" does not exist');
  440. }
  441. return $id;
  442. }
  443. /**
  444. * Gets the internal context id from the context reference.
  445. *
  446. * The context reference changes depending on the context
  447. * level, it can be the system, a user, a category, a course or
  448. * a module.
  449. *
  450. * @throws Exception
  451. * @param string $levelname The context level string introduced by the test writer
  452. * @param string $contextref The context reference introduced by the test writer
  453. * @return context
  454. */
  455. protected function get_context($levelname, $contextref) {
  456. global $DB;
  457. // Getting context levels and names (we will be using the English ones as it is the test site language).
  458. $contextlevels = context_helper::get_all_levels();
  459. $contextnames = array();
  460. foreach ($contextlevels as $level => $classname) {
  461. $contextnames[context_helper::get_level_name($level)] = $level;
  462. }
  463. if (empty($contextnames[$levelname])) {
  464. throw new Exception('The specified "' . $levelname . '" context level does not exist');
  465. }
  466. $contextlevel = $contextnames[$levelname];
  467. // Return it, we don't need to look for other internal ids.
  468. if ($contextlevel == CONTEXT_SYSTEM) {
  469. return context_system::instance();
  470. }
  471. switch ($contextlevel) {
  472. case CONTEXT_USER:
  473. $instanceid = $DB->get_field('user', 'id', array('username' => $contextref));
  474. break;
  475. case CONTEXT_COURSECAT:
  476. $instanceid = $DB->get_field('course_categories', 'id', array('idnumber' => $contextref));
  477. break;
  478. case CONTEXT_COURSE:
  479. $instanceid = $DB->get_field('course', 'id', array('shortname' => $contextref));
  480. break;
  481. case CONTEXT_MODULE:
  482. $instanceid = $DB->get_field('course_modules', 'id', array('idnumber' => $contextref));
  483. break;
  484. default:
  485. break;
  486. }
  487. $contextclass = $contextlevels[$contextlevel];
  488. if (!$context = $contextclass::instance($instanceid, IGNORE_MISSING)) {
  489. throw new Exception('The specified "' . $contextref . '" context reference does not exist');
  490. }
  491. return $context;
  492. }
  493. }