Skip to content
Browse files

MDL-33916 Add unit tests to ensure that is_enrolled returns correctly

  • Loading branch information...
1 parent a386e6e commit 9b128ba39cf66b9bbe71bf80b3f27025eec419f9 @andrewnicols andrewnicols committed
Showing with 53 additions and 0 deletions.
  1. +53 −0 lib/tests/accesslib_test.php
View
53 lib/tests/accesslib_test.php
@@ -148,6 +148,59 @@ public function test_is_siteadmin() {
}
/**
+ * Test if user is enrolled in a course
+ * @return void
+ */
+ public function test_is_enrolled() {
+ global $DB;
+
+ // Generate data
+ $user = $this->getDataGenerator()->create_user();
+ $course = $this->getDataGenerator()->create_course();
+ $coursecontext = context_course::instance($course->id);
+ $role = $DB->get_record('role', array('shortname'=>'student'));
+
+ // There should be a manual enrolment as part of the default install
+ $plugin = enrol_get_plugin('manual');
+ $instance = $DB->get_record('enrol', array(
+ 'courseid' => $course->id,
+ 'enrol' => 'manual',
+ ));
+ $this->assertNotEquals($instance, false);
+
+ // Enrol the user in the course
+ $plugin->enrol_user($instance, $user->id, $role->id);
+
+ // We'll test with the mod/assign:submit capability
+ $capability= 'mod/assign:submit';
+ $this->assertTrue($DB->record_exists('capabilities', array('name' => $capability)));
+
+ // Switch to our user
+ $this->setUser($user);
+
+ // Ensure that the user has the capability first
+ $this->assertTrue(has_capability($capability, $coursecontext, $user->id));
+
+ // We first test whether the user is enrolled on the course as this
+ // seeds the cache, then we test for the capability
+ $this->assertTrue(is_enrolled($coursecontext, $user, '', true));
+ $this->assertTrue(is_enrolled($coursecontext, $user, $capability));
+
+ // Prevent the capability for this user role
+ assign_capability($capability, CAP_PROHIBIT, $role->id, $coursecontext);
+ $coursecontext->mark_dirty();
+ $this->assertFalse(has_capability($capability, $coursecontext, $user->id));
+
+ // Again, we seed the cache first by checking initial enrolment,
+ // and then we test the actual capability
+ $this->assertTrue(is_enrolled($coursecontext, $user, '', true));
+ $this->assertFalse(is_enrolled($coursecontext, $user, $capability));
+
+ // We need variable states to be reset for the next test
+ $this->resetAfterTest(true);
+ }
+
+ /**
* Test logged in test.
* @return void
*/

0 comments on commit 9b128ba

Please sign in to comment.
Something went wrong with that request. Please try again.