[ Index ]

PHP Cross Reference of Unnamed Project

title

Body

[close]

/enrol/tests/ -> externallib_test.php (source)

   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  defined('MOODLE_INTERNAL') || die();
  18  
  19  global $CFG;
  20  
  21  require_once($CFG->dirroot . '/webservice/tests/helpers.php');
  22  require_once($CFG->dirroot . '/enrol/externallib.php');
  23  
  24  /**
  25   * Enrol external PHPunit tests
  26   *
  27   * @package    core_enrol
  28   * @category   external
  29   * @copyright  2012 Jerome Mouneyrac
  30   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  31   * @since Moodle 2.4
  32   */
  33  class core_enrol_externallib_testcase extends externallib_advanced_testcase {
  34  
  35      /**
  36       * dataProvider for test_get_enrolled_users_visibility().
  37       */
  38      public function get_enrolled_users_visibility_provider() {
  39          return array(
  40              'Course without groups, default behavior (not filtering by cap, group, active)' =>
  41              array(
  42                  'settings' => array(
  43                      'coursegroupmode' => NOGROUPS,
  44                      'withcapability' => null,
  45                      'groupid' => null,
  46                      'onlyactive' => false,
  47                      'allowedcaps' => array(),
  48                  ),
  49                  'results' => array( // Everybody can view everybody.
  50                      'user0' => array('canview' => array('user0', 'user1', 'user2', 'user2su', 'user31', 'user32', 'userall')),
  51                      'user1' => array('canview' => array('user0', 'user1', 'user2', 'user2su', 'user31', 'user32', 'userall')),
  52                      'user2' => array('canview' => array('user0', 'user1', 'user2', 'user2su', 'user31', 'user32', 'userall')),
  53                      'user31' => array('canview' => array('user0', 'user1', 'user2', 'user2su', 'user31', 'user32', 'userall')),
  54                      'userall' => array('canview' => array('user0', 'user1', 'user2', 'user2su', 'user31', 'user32', 'userall')),
  55                  ),
  56              ),
  57  
  58              'Course with visible groups, default behavior (not filtering by cap, group, active)' =>
  59              array(
  60                  'settings' => array(
  61                      'coursegroupmode' => VISIBLEGROUPS,
  62                      'withcapability' => null,
  63                      'groupid' => null,
  64                      'onlyactive' => false,
  65                      'allowedcaps' => array(),
  66                  ),
  67                  'results' => array( // Everybody can view everybody.
  68                      'user0' => array('canview' => array('user0', 'user1', 'user2', 'user2su', 'user31', 'user32', 'userall')),
  69                      'user1' => array('canview' => array('user0', 'user1', 'user2', 'user2su', 'user31', 'user32', 'userall')),
  70                      'user2' => array('canview' => array('user0', 'user1', 'user2', 'user2su', 'user31', 'user32', 'userall')),
  71                      'user31' => array('canview' => array('user0', 'user1', 'user2', 'user2su', 'user31', 'user32', 'userall')),
  72                      'userall' => array('canview' => array('user0', 'user1', 'user2', 'user2su', 'user31', 'user32', 'userall')),
  73                  ),
  74              ),
  75  
  76              'Course with separate groups, default behavior (not filtering by cap, group, active)' =>
  77              array(
  78                  'settings' => array(
  79                      'coursegroupmode' => SEPARATEGROUPS,
  80                      'withcapability' => null,
  81                      'groupid' => null,
  82                      'onlyactive' => false,
  83                      'allowedcaps' => array(),
  84                  ),
  85                  'results' => array( // Only users from own groups are visible.
  86                      'user0' => array('canview' => array()), // Poor guy, cannot see anybody, himself included.
  87                      'user1' => array('canview' => array('user1', 'userall')),
  88                      'user2' => array('canview' => array('user2', 'user2su', 'userall')),
  89                      'user31' => array('canview' => array('user31', 'user32', 'userall')),
  90                      'userall' => array('canview' => array('user1', 'user2', 'user2su', 'user31', 'user32', 'userall')),
  91                  ),
  92              ),
  93  
  94              'Course with separate groups, default behavior (not filtering but having moodle/site:accessallgroups)' =>
  95              array(
  96                  'settings' => array(
  97                      'coursegroupmode' => VISIBLEGROUPS,
  98                      'withcapability' => null,
  99                      'groupid' => null,
 100                      'onlyactive' => false,
 101                      'allowedcaps' => array('moodle/site:accessallgroups'),
 102                  ),
 103                  'results' => array( // Everybody can view everybody.
 104                      'user0' => array('canview' => array('user0', 'user1', 'user2', 'user2su', 'user31', 'user32', 'userall')),
 105                      'user1' => array('canview' => array('user0', 'user1', 'user2', 'user2su', 'user31', 'user32', 'userall')),
 106                      'user2' => array('canview' => array('user0', 'user1', 'user2', 'user2su', 'user31', 'user32', 'userall')),
 107                      'user31' => array('canview' => array('user0', 'user1', 'user2', 'user2su', 'user31', 'user32', 'userall')),
 108                      'userall' => array('canview' => array('user0', 'user1', 'user2', 'user2su', 'user31', 'user32', 'userall')),
 109                  ),
 110              ),
 111  
 112              'Course with separate groups, filtering onlyactive (missing moodle/course:enrolreview)' =>
 113              array(
 114                  'settings' => array(
 115                      'coursegroupmode' => SEPARATEGROUPS,
 116                      'withcapability' => null,
 117                      'groupid' => null,
 118                      'onlyactive' => true,
 119                      'allowedcaps' => array(),
 120                  ),
 121                  'results' => array( // returns exception, cannot view anybody without the cap.
 122                      'user2' => array('exception' => array(
 123                          'type' => 'required_capability_exception',
 124                          'message' => 'Review course enrolments')),
 125                      'userall' => array('exception' => array(
 126                          'type' => 'required_capability_exception',
 127                          'message' => 'Review course enrolments')),
 128                  ),
 129              ),
 130  
 131              'Course with separate groups, filtering onlyactive (having moodle/course:enrolreview)' =>
 132              array(
 133                  'settings' => array(
 134                      'coursegroupmode' => SEPARATEGROUPS,
 135                      'withcapability' => null,
 136                      'groupid' => null,
 137                      'onlyactive' => true,
 138                      'allowedcaps' => array('moodle/course:enrolreview'),
 139                  ),
 140                  'results' => array( // Suspended are not returned.
 141                      'user2' => array('canview' => array('user2', 'userall')),
 142                      'user31' => array('canview' => array('user31', 'user32', 'userall')),
 143                      'userall' => array('canview' => array('user1', 'user2', 'user31', 'user32', 'userall')),
 144                  ),
 145              ),
 146  
 147              'Course with separate groups, filtering by groupid (not having moodle/site:accessallgroups)' =>
 148              array(
 149                  'settings' => array(
 150                      'coursegroupmode' => SEPARATEGROUPS,
 151                      'withcapability' => null,
 152                      'groupid' => 'group2',
 153                      'onlyactive' => false,
 154                      'allowedcaps' => array(),
 155                  ),
 156                  'results' => array( // Only group 2 members and only for members. Exception for non-members.
 157                      'user0' => array('exception' => array(
 158                          'type' => 'required_capability_exception',
 159                          'message' => 'Access all groups')),
 160                      'user1' => array('exception' => array(
 161                          'type' => 'required_capability_exception',
 162                          'message' => 'Access all groups')),
 163                      'user2' => array('canview' => array('user2', 'user2su', 'userall')),
 164                      'userall' => array('canview' => array('user2', 'user2su', 'userall')),
 165                  ),
 166              ),
 167  
 168              'Course with separate groups, filtering by groupid (having moodle/site:accessallgroups)' =>
 169              array(
 170                  'settings' => array(
 171                      'coursegroupmode' => SEPARATEGROUPS,
 172                      'withcapability' => null,
 173                      'groupid' => 'group2',
 174                      'onlyactive' => false,
 175                      'allowedcaps' => array('moodle/site:accessallgroups'),
 176                  ),
 177                  'results' => array( // All users with 'moodle/site:accessallgroups' can view group 2
 178                      'user0' => array('canview' => array('user2', 'user2su', 'userall')),
 179                      'user1' => array('canview' => array('user2', 'user2su', 'userall')),
 180                      'user2' => array('canview' => array('user2', 'user2su', 'userall')),
 181                      'userall' => array('canview' => array('user2', 'user2su', 'userall')),
 182                  ),
 183              ),
 184  
 185              'Course with separate groups, filtering by withcapability (not having moodle/role:review)' =>
 186              array(
 187                  'settings' => array(
 188                      'coursegroupmode' => SEPARATEGROUPS,
 189                      'withcapability' => 'moodle/course:bulkmessaging',
 190                      'groupid' => null,
 191                      'onlyactive' => false,
 192                      'allowedcaps' => array(),
 193                  ),
 194                  'results' => array( // No user has 'moodle/role:review' so exception.
 195                      'user0' => array('exception' => array(
 196                          'type' => 'required_capability_exception',
 197                          'message' => 'Review permissions for others')),
 198                      'user1' => array('exception' => array(
 199                          'type' => 'required_capability_exception',
 200                          'message' => 'Review permissions for others')),
 201                      'user2' => array('exception' => array(
 202                          'type' => 'required_capability_exception',
 203                          'message' => 'Review permissions for others')),
 204                      'userall' => array('exception' => array(
 205                          'type' => 'required_capability_exception',
 206                          'message' => 'Review permissions for others')),
 207                  ),
 208              ),
 209  
 210              'Course with separate groups, filtering by withcapability (having moodle/role:review)' =>
 211              array(
 212                  'settings' => array(
 213                      'coursegroupmode' => SEPARATEGROUPS,
 214                      'withcapability' => 'moodle/course:bulkmessaging',
 215                      'groupid' => null,
 216                      'onlyactive' => false,
 217                      'allowedcaps' => array('moodle/role:review'),
 218                  ),
 219                  'results' => array( // No user has withcapability, but all have 'moodle/role:review'. Empties.
 220                      'user0' => array('canview' => array()),
 221                      'user1' => array('canview' => array()),
 222                      'user2' => array('canview' => array()),
 223                      'userall' => array('canview' => array()),
 224                  ),
 225              ),
 226  
 227              'Course with separate groups, filtering by withcapability (having moodle/role:review)' =>
 228              array(
 229                  'settings' => array(
 230                      'coursegroupmode' => SEPARATEGROUPS,
 231                      'withcapability' => 'moodle/course:bulkmessaging',
 232                      'groupid' => null,
 233                      'onlyactive' => false,
 234                      'allowedcaps' => array('moodle/role:review', 'moodle/course:bulkmessaging'),
 235                  ),
 236                  'results' => array( // Users (previous) have withcapability, and all have 'moodle/role:review'.
 237                      'user0' => array('canview' => array()),
 238                      'user1' => array('canview' => array('user1')),
 239                      'user2' => array('canview' => array('user2')),
 240                      'userall' => array('canview' => array('user1', 'user2', 'userall')),
 241                  ),
 242              ),
 243          );
 244      }
 245  
 246      /**
 247       * Verify get_enrolled_users() returned users are the expected in every situation.
 248       *
 249       * @dataProvider get_enrolled_users_visibility_provider
 250       */
 251      public function test_get_enrolled_users_visibility($settings, $results) {
 252  
 253          global $USER;
 254  
 255          $this->resetAfterTest();
 256  
 257          // Create the course and the users.
 258          $course = $this->getDataGenerator()->create_course(array('groupmode' => $settings['coursegroupmode']));
 259          $coursecontext = context_course::instance($course->id);
 260          $user0 = $this->getDataGenerator()->create_user(array('username' => 'user0'));     // A user without group.
 261          $user1 = $this->getDataGenerator()->create_user(array('username' => 'user1'));     // User for group 1.
 262          $user2 = $this->getDataGenerator()->create_user(array('username' => 'user2'));     // Two users for group 2.
 263          $user2su = $this->getDataGenerator()->create_user(array('username' => 'user2su')); // (one suspended).
 264          $user31 = $this->getDataGenerator()->create_user(array('username' => 'user31'));   // Two users for group 3.
 265          $user32 = $this->getDataGenerator()->create_user(array('username' => 'user32'));   // (both enabled).
 266          $userall = $this->getDataGenerator()->create_user(array('username' => 'userall')); // A user in all groups.
 267  
 268          // Create utility array of created users, to produce better assertion messages.
 269          $createdusers = array();
 270          foreach (array($user0, $user1, $user2, $user2su, $user31, $user32, $userall) as $createduser) {
 271              $createdusers[$createduser->id] = $createduser->username;
 272          }
 273  
 274          // Enrol the users in the course.
 275          $this->getDataGenerator()->enrol_user($user0->id, $course->id);
 276          $this->getDataGenerator()->enrol_user($user1->id, $course->id);
 277          $this->getDataGenerator()->enrol_user($user2->id, $course->id);
 278          $this->getDataGenerator()->enrol_user($user2su->id, $course->id, null, 'manual', 0, 0, ENROL_USER_SUSPENDED);
 279          $this->getDataGenerator()->enrol_user($user31->id, $course->id);
 280          $this->getDataGenerator()->enrol_user($user32->id, $course->id);
 281          $this->getDataGenerator()->enrol_user($userall->id, $course->id);
 282  
 283          // Create 3 groups.
 284          $group1 = $this->getDataGenerator()->create_group(array('courseid' => $course->id));
 285          $group2 = $this->getDataGenerator()->create_group(array('courseid' => $course->id));
 286          $group3 = $this->getDataGenerator()->create_group(array('courseid' => $course->id));
 287  
 288          // Add the users to the groups.
 289          $this->getDataGenerator()->create_group_member(array('groupid' => $group1->id, 'userid' => $user1->id));
 290          $this->getDataGenerator()->create_group_member(array('groupid' => $group2->id, 'userid' => $user2->id));
 291          $this->getDataGenerator()->create_group_member(array('groupid' => $group2->id, 'userid' => $user2su->id));
 292          $this->getDataGenerator()->create_group_member(array('groupid' => $group3->id, 'userid' => $user31->id));
 293          $this->getDataGenerator()->create_group_member(array('groupid' => $group3->id, 'userid' => $user32->id));
 294          $this->getDataGenerator()->create_group_member(array('groupid' => $group1->id, 'userid' => $userall->id));
 295          $this->getDataGenerator()->create_group_member(array('groupid' => $group2->id, 'userid' => $userall->id));
 296          $this->getDataGenerator()->create_group_member(array('groupid' => $group3->id, 'userid' => $userall->id));
 297  
 298          // Create a role to add the allowedcaps. Users will have this role assigned.
 299          $roleid = $this->getDataGenerator()->create_role();
 300          // Allow the specified capabilities.
 301          if (!empty($settings['allowedcaps'])) {
 302              foreach ($settings['allowedcaps'] as $capability) {
 303                  assign_capability($capability, CAP_ALLOW, $roleid, $coursecontext);
 304              }
 305          }
 306  
 307          // For each of the users, configure everything, perform the call, and assert results.
 308          foreach ($results as $user => $expectations) {
 309              // Convert canview expectations into a nice array of ids for easier handling.
 310              $canview = array();
 311              $exception = null;
 312              // Analyse the expectations.
 313              if (isset($expectations['canview'])) {
 314                  foreach ($expectations['canview'] as $canviewuser) {
 315                      $canview[] = $createdusers[${$canviewuser}->id];
 316                  }
 317              } else if (isset($expectations['exception'])) {
 318                  $exception = $expectations['exception'];
 319                  $this->expectException($exception['type']);
 320                  $this->expectExceptionMessage($exception['message']);
 321              } else {
 322                  // Failed, only canview and exception are supported.
 323                  $this->markTestIncomplete('Incomplete, only canview and exception are supported');
 324              }
 325              // Switch to the user and assign the role.
 326              $this->setUser(${$user});
 327              role_assign($roleid, $USER->id, $coursecontext);
 328  
 329              // Convert groupid to proper id.
 330              $groupid = 0;
 331              if (isset($settings['groupid'])) {
 332                  $groupid = ${$settings['groupid']}->id;
 333              }
 334  
 335              // Call to the function.
 336              $options = array(
 337                  array('name' => 'withcapability', 'value' => $settings['withcapability']),
 338                  array('name' => 'groupid', 'value' => $groupid),
 339                  array('name' => 'onlyactive', 'value' => $settings['onlyactive']),
 340                  array('name' => 'userfields', 'value' => 'id')
 341              );
 342              $enrolledusers = core_enrol_external::get_enrolled_users($course->id, $options);
 343  
 344              // We need to execute the return values cleaning process to simulate the web service server.
 345              $enrolledusers = external_api::clean_returnvalue(core_enrol_external::get_enrolled_users_returns(), $enrolledusers);
 346  
 347              // We are only interested in ids to check visibility.
 348              $viewed = array();
 349              // Verify the user canview the expected users.
 350              foreach ($enrolledusers as $enrolleduser) {
 351                  $viewed[] = $createdusers[$enrolleduser['id']];
 352              }
 353              // Verify viewed matches canview expectation (using canonicalize to ignore ordering).
 354              $this->assertEquals($canview, $viewed, "Problem checking visible users for '{$createdusers[$USER->id]}'", 0, 1, true);
 355          }
 356      }
 357  
 358      /**
 359       * Test get_users_courses
 360       */
 361      public function test_get_users_courses() {
 362          global $USER;
 363  
 364          $this->resetAfterTest(true);
 365  
 366          $coursedata1 = array(
 367              'fullname'         => '<b>Course 1</b>',                // Adding tags here to check that external_format_string works.
 368              'shortname'         => '<b>Course 1</b>',               // Adding tags here to check that external_format_string works.
 369              'summary'          => 'Lightwork Course 1 description',
 370              'summaryformat'    => FORMAT_MOODLE,
 371              'lang'             => 'en',
 372              'enablecompletion' => true,
 373              'showgrades'       => true
 374          );
 375  
 376          $course1 = self::getDataGenerator()->create_course($coursedata1);
 377          $course2 = self::getDataGenerator()->create_course();
 378          $courses = array($course1, $course2);
 379  
 380          // Enrol $USER in the courses.
 381          // We use the manual plugin.
 382          $roleid = null;
 383          $contexts = array();
 384          foreach ($courses as $course) {
 385              $contexts[$course->id] = context_course::instance($course->id);
 386              $roleid = $this->assignUserCapability('moodle/course:viewparticipants',
 387                      $contexts[$course->id]->id, $roleid);
 388  
 389              $this->getDataGenerator()->enrol_user($USER->id, $course->id, $roleid, 'manual');
 390          }
 391  
 392          // Call the external function.
 393          $enrolledincourses = core_enrol_external::get_users_courses($USER->id);
 394  
 395          // We need to execute the return values cleaning process to simulate the web service server.
 396          $enrolledincourses = external_api::clean_returnvalue(core_enrol_external::get_users_courses_returns(), $enrolledincourses);
 397  
 398          // Check we retrieve the good total number of enrolled users.
 399          $this->assertEquals(2, count($enrolledincourses));
 400  
 401          // We need to format summary and summaryformat before to compare them with those values returned by the webservice.
 402          list($course1->summary, $course1->summaryformat) =
 403               external_format_text($course1->summary, $course1->summaryformat, $contexts[$course1->id]->id, 'course', 'summary', 0);
 404  
 405          // Check there are no differences between $course1 properties and course values returned by the webservice
 406          // only for those fields listed in the $coursedata1 array.
 407          $course1->fullname = external_format_string($course1->fullname, $contexts[$course1->id]->id);
 408          $course1->shortname = external_format_string($course1->shortname, $contexts[$course1->id]->id);
 409          foreach ($enrolledincourses as $courseenrol) {
 410              if ($courseenrol['id'] == $course1->id) {
 411                  foreach ($coursedata1 as $fieldname => $value) {
 412                      $this->assertEquals($courseenrol[$fieldname], $course1->$fieldname);
 413                  }
 414              }
 415          }
 416      }
 417  
 418      /**
 419       * Test get_course_enrolment_methods
 420       */
 421      public function test_get_course_enrolment_methods() {
 422          global $DB;
 423  
 424          $this->resetAfterTest(true);
 425  
 426          // Get enrolment plugins.
 427          $selfplugin = enrol_get_plugin('self');
 428          $this->assertNotEmpty($selfplugin);
 429          $manualplugin = enrol_get_plugin('manual');
 430          $this->assertNotEmpty($manualplugin);
 431  
 432          $studentrole = $DB->get_record('role', array('shortname'=>'student'));
 433          $this->assertNotEmpty($studentrole);
 434  
 435          $course1 = self::getDataGenerator()->create_course();
 436          $coursedata = new stdClass();
 437          $coursedata->visible = 0;
 438          $course2 = self::getDataGenerator()->create_course($coursedata);
 439  
 440          // Add enrolment methods for course.
 441          $instanceid1 = $selfplugin->add_instance($course1, array('status' => ENROL_INSTANCE_ENABLED,
 442                                                                  'name' => 'Test instance 1',
 443                                                                  'customint6' => 1,
 444                                                                  'roleid' => $studentrole->id));
 445          $instanceid2 = $selfplugin->add_instance($course1, array('status' => ENROL_INSTANCE_DISABLED,
 446                                                                  'name' => 'Test instance 2',
 447                                                                  'roleid' => $studentrole->id));
 448  
 449          $instanceid3 = $manualplugin->add_instance($course1, array('status' => ENROL_INSTANCE_ENABLED,
 450                                                                  'name' => 'Test instance 3'));
 451  
 452          $enrolmentmethods = $DB->get_records('enrol', array('courseid' => $course1->id, 'status' => ENROL_INSTANCE_ENABLED));
 453          $this->assertCount(2, $enrolmentmethods);
 454  
 455          $this->setAdminUser();
 456  
 457          // Check if information is returned.
 458          $enrolmentmethods = core_enrol_external::get_course_enrolment_methods($course1->id);
 459          $enrolmentmethods = external_api::clean_returnvalue(core_enrol_external::get_course_enrolment_methods_returns(),
 460                                                              $enrolmentmethods);
 461          // Enrolment information is currently returned by self enrolment plugin, so count == 1.
 462          // This should be changed as we implement get_enrol_info() for other enrolment plugins.
 463          $this->assertCount(1, $enrolmentmethods);
 464  
 465          $enrolmentmethod = $enrolmentmethods[0];
 466          $this->assertEquals($course1->id, $enrolmentmethod['courseid']);
 467          $this->assertEquals('self', $enrolmentmethod['type']);
 468          $this->assertTrue($enrolmentmethod['status']);
 469          $this->assertFalse(isset($enrolmentmethod['wsfunction']));
 470  
 471          $instanceid4 = $selfplugin->add_instance($course2, array('status' => ENROL_INSTANCE_ENABLED,
 472                                                                  'name' => 'Test instance 4',
 473                                                                  'roleid' => $studentrole->id,
 474                                                                  'customint6' => 1,
 475                                                                  'password' => 'test'));
 476          $enrolmentmethods = core_enrol_external::get_course_enrolment_methods($course2->id);
 477          $enrolmentmethods = external_api::clean_returnvalue(core_enrol_external::get_course_enrolment_methods_returns(),
 478                                                              $enrolmentmethods);
 479          $this->assertCount(1, $enrolmentmethods);
 480  
 481          $enrolmentmethod = $enrolmentmethods[0];
 482          $this->assertEquals($course2->id, $enrolmentmethod['courseid']);
 483          $this->assertEquals('self', $enrolmentmethod['type']);
 484          $this->assertTrue($enrolmentmethod['status']);
 485          $this->assertEquals('enrol_self_get_instance_info', $enrolmentmethod['wsfunction']);
 486  
 487          // Try to retrieve information using a normal user for a hidden course.
 488          $user = self::getDataGenerator()->create_user();
 489          $this->setUser($user);
 490          try {
 491              core_enrol_external::get_course_enrolment_methods($course2->id);
 492          } catch (moodle_exception $e) {
 493              $this->assertEquals('coursehidden', $e->errorcode);
 494          }
 495      }
 496  
 497      public function get_enrolled_users_setup($capability) {
 498          global $USER;
 499  
 500          $this->resetAfterTest(true);
 501  
 502          $return = new stdClass();
 503  
 504          $return->course = self::getDataGenerator()->create_course();
 505          $return->user1 = self::getDataGenerator()->create_user();
 506          $return->user2 = self::getDataGenerator()->create_user();
 507          $return->user3 = self::getDataGenerator()->create_user();
 508          $this->setUser($return->user3);
 509  
 510          // Set the required capabilities by the external function.
 511          $return->context = context_course::instance($return->course->id);
 512          $return->roleid = $this->assignUserCapability($capability, $return->context->id);
 513          $this->assignUserCapability('moodle/user:viewdetails', $return->context->id, $return->roleid);
 514  
 515          // Enrol the users in the course.
 516          $this->getDataGenerator()->enrol_user($return->user1->id, $return->course->id, $return->roleid, 'manual');
 517          $this->getDataGenerator()->enrol_user($return->user2->id, $return->course->id, $return->roleid, 'manual');
 518          $this->getDataGenerator()->enrol_user($return->user3->id, $return->course->id, $return->roleid, 'manual');
 519  
 520          return $return;
 521      }
 522  
 523      /**
 524       * Test get_enrolled_users from core_enrol_external without additional
 525       * parameters.
 526       */
 527      public function test_get_enrolled_users_without_parameters() {
 528          $capability = 'moodle/course:viewparticipants';
 529          $data = $this->get_enrolled_users_setup($capability);
 530  
 531          // Call the external function.
 532          $enrolledusers = core_enrol_external::get_enrolled_users($data->course->id);
 533  
 534          // We need to execute the return values cleaning process to simulate the web service server.
 535          $enrolledusers = external_api::clean_returnvalue(core_enrol_external::get_enrolled_users_returns(), $enrolledusers);
 536  
 537          // Check the result set.
 538          $this->assertEquals(3, count($enrolledusers));
 539          $this->assertArrayHasKey('email', $enrolledusers[0]);
 540      }
 541  
 542      /**
 543       * Test get_enrolled_users from core_enrol_external with some parameters set.
 544       */
 545      public function test_get_enrolled_users_with_parameters() {
 546          $capability = 'moodle/course:viewparticipants';
 547          $data = $this->get_enrolled_users_setup($capability);
 548  
 549          // Call the function with some parameters set.
 550          $enrolledusers = core_enrol_external::get_enrolled_users($data->course->id, array(
 551              array('name' => 'limitfrom', 'value' => 2),
 552              array('name' => 'limitnumber', 'value' => 1),
 553              array('name' => 'userfields', 'value' => 'id')
 554          ));
 555  
 556          // We need to execute the return values cleaning process to simulate the web service server.
 557          $enrolledusers = external_api::clean_returnvalue(core_enrol_external::get_enrolled_users_returns(), $enrolledusers);
 558  
 559          // Check the result set, we should only get the 3rd result, which is $user3.
 560          $this->assertCount(1, $enrolledusers);
 561          $this->assertEquals($data->user3->id, $enrolledusers[0]['id']);
 562          $this->assertArrayHasKey('id', $enrolledusers[0]);
 563          $this->assertArrayNotHasKey('email', $enrolledusers[0]);
 564      }
 565  
 566      /**
 567       * Test get_enrolled_users from core_enrol_external with capability to
 568       * viewparticipants removed.
 569       *
 570       * @expectedException moodle_exception
 571       */
 572      public function test_get_enrolled_users_without_capability() {
 573          $capability = 'moodle/course:viewparticipants';
 574          $data = $this->get_enrolled_users_setup($capability);
 575  
 576          // Call without required capability.
 577          $this->unassignUserCapability($capability, $data->context->id, $data->roleid);
 578          $categories = core_enrol_external::get_enrolled_users($data->course->id);
 579      }
 580  
 581      public function get_enrolled_users_with_capability_setup($capability) {
 582          global $USER, $DB;
 583  
 584          $this->resetAfterTest(true);
 585  
 586          $return = new stdClass();
 587  
 588          // Create the course and fetch its context.
 589          $return->course = self::getDataGenerator()->create_course();
 590          $context = context_course::instance($return->course->id);
 591  
 592          // Create one teacher, and two students.
 593          $return->teacher = self::getDataGenerator()->create_user();
 594          $return->student1 = self::getDataGenerator()->create_user();
 595          $return->student2 = self::getDataGenerator()->create_user();
 596  
 597          // Create a new student role based on the student archetype but with the capability prohibitted.
 598          $fakestudentroleid = create_role('Fake student role', 'fakestudent', 'Fake student role', 'student');
 599          assign_capability($capability, CAP_PROHIBIT, $fakestudentroleid, $context->id);
 600  
 601          // Enrol all of the users in the course.
 602          // * 'teacher'  is an editing teacher.
 603          // * 'student1' is a standard student.
 604          // * 'student2' is a student with the capability prohibitted.
 605          $editingteacherroleid = $DB->get_field('role', 'id', array('shortname' => 'editingteacher'));
 606          $studentroleid = $DB->get_field('role', 'id', array('shortname' => 'student'));
 607          $this->getDataGenerator()->enrol_user($return->teacher->id, $return->course->id, $editingteacherroleid);
 608          $this->getDataGenerator()->enrol_user($return->student1->id, $return->course->id, $studentroleid);
 609          $this->getDataGenerator()->enrol_user($return->student2->id, $return->course->id, $fakestudentroleid);
 610  
 611          // Log in as the teacher.
 612          $this->setUser($return->teacher);
 613  
 614          // Clear caches.
 615          accesslib_clear_all_caches_for_unit_testing();
 616  
 617          return $return;
 618      }
 619  
 620      /**
 621       * Test get_enrolled_users_with_capability without additional paramaters.
 622       */
 623      public function test_get_enrolled_users_with_capability_without_parameters() {
 624          $capability = 'moodle/course:viewparticipants';
 625          $data = $this->get_enrolled_users_with_capability_setup($capability);
 626  
 627          $result = core_enrol_external::get_enrolled_users_with_capability(
 628              array(
 629                  'coursecapabilities' => array(
 630                      'courseid' => $data->course->id,
 631                      'capabilities' => array(
 632                          $capability,
 633                      ),
 634                  ),
 635              ),
 636              array()
 637          );
 638  
 639          // We need to execute the return values cleaning process to simulate the web service server.
 640          $result = external_api::clean_returnvalue(core_enrol_external::get_enrolled_users_with_capability_returns(), $result);
 641  
 642          // Check an array containing the expected user for the course capability is returned.
 643          $expecteduserlist = $result[0];
 644          $this->assertEquals($data->course->id, $expecteduserlist['courseid']);
 645          $this->assertEquals($capability, $expecteduserlist['capability']);
 646          $this->assertEquals(2, count($expecteduserlist['users']));
 647      }
 648  
 649      /**
 650       * Test get_enrolled_users_with_capability
 651       */
 652      public function test_get_enrolled_users_with_capability_with_parameters () {
 653          $capability = 'moodle/course:viewparticipants';
 654          $data = $this->get_enrolled_users_with_capability_setup($capability);
 655  
 656          $result = core_enrol_external::get_enrolled_users_with_capability(
 657              array(
 658                  'coursecapabilities' => array(
 659                      'courseid' => $data->course->id,
 660                      'capabilities' => array(
 661                          $capability,
 662                      ),
 663                  ),
 664              ),
 665              array(
 666                  array('name' => 'limitfrom', 'value' => 1),
 667                  array('name' => 'limitnumber', 'value' => 1),
 668                  array('name' => 'userfields', 'value' => 'id')
 669              )
 670          );
 671  
 672          // We need to execute the return values cleaning process to simulate the web service server.
 673          $result = external_api::clean_returnvalue(core_enrol_external::get_enrolled_users_with_capability_returns(), $result);
 674  
 675          // Check an array containing the expected user for the course capability is returned.
 676          $expecteduserlist = $result[0]['users'];
 677          $expecteduser = reset($expecteduserlist);
 678          $this->assertEquals(1, count($expecteduserlist));
 679          $this->assertEquals($data->student1->id, $expecteduser['id']);
 680      }
 681  
 682  }


Generated: Thu Aug 11 10:00:09 2016 Cross-referenced by PHPXref 0.7.1