Yo
', 'format' => FORMAT_HTML); update_module($formdata); $this->assertNull($DB->get_field('course_modules', 'availability', array('id' => $label->cmid))); } /** * Test update_inplace_editable() */ public function test_update_module_name_inplace() { global $CFG, $DB, $PAGE; require_once($CFG->dirroot . '/lib/external/externallib.php'); $this->setUser($this->getDataGenerator()->create_user()); $this->resetAfterTest(true); $course = $this->getDataGenerator()->create_course(); $forum = self::getDataGenerator()->create_module('forum', array('course' => $course->id, 'name' => 'forum name')); // Call service for core_course component without necessary permissions. try { core_external::update_inplace_editable('core_course', 'activityname', $forum->cmid, 'New forum name'); $this->fail('Exception expected'); } catch (moodle_exception $e) { $this->assertEquals('Course or activity not accessible. (Not enrolled)', $e->getMessage()); } // Change to admin user and make sure that cm name can be updated using web service update_inplace_editable(). $this->setAdminUser(); $res = core_external::update_inplace_editable('core_course', 'activityname', $forum->cmid, 'New forum name'); $res = external_api::clean_returnvalue(core_external::update_inplace_editable_returns(), $res); $this->assertEquals('New forum name', $res['value']); $this->assertEquals('New forum name', $DB->get_field('forum', 'name', array('id' => $forum->id))); } /** * Testing function course_get_tagged_course_modules - search tagged course modules */ public function test_course_get_tagged_course_modules() { global $DB; $this->resetAfterTest(); $course3 = $this->getDataGenerator()->create_course(); $course2 = $this->getDataGenerator()->create_course(); $course1 = $this->getDataGenerator()->create_course(); $cm11 = $this->getDataGenerator()->create_module('assign', array('course' => $course1->id, 'tags' => 'Cat, Dog')); $cm12 = $this->getDataGenerator()->create_module('page', array('course' => $course1->id, 'tags' => 'Cat, Mouse', 'visible' => 0)); $cm13 = $this->getDataGenerator()->create_module('page', array('course' => $course1->id, 'tags' => 'Cat, Mouse, Dog')); $cm21 = $this->getDataGenerator()->create_module('forum', array('course' => $course2->id, 'tags' => 'Cat, Mouse')); $cm31 = $this->getDataGenerator()->create_module('forum', array('course' => $course3->id, 'tags' => 'Cat, Mouse')); // Admin is able to view everything. $this->setAdminUser(); $res = course_get_tagged_course_modules(core_tag_tag::get_by_name(0, 'Cat'), /*$exclusivemode = */false, /*$fromctx = */0, /*$ctx = */0, /*$rec = */1, /*$page = */0); $this->assertMatchesRegularExpression('/'.$cm11->name.'/', $res->content); $this->assertMatchesRegularExpression('/'.$cm12->name.'/', $res->content); $this->assertMatchesRegularExpression('/'.$cm13->name.'/', $res->content); $this->assertMatchesRegularExpression('/'.$cm21->name.'/', $res->content); $this->assertMatchesRegularExpression('/'.$cm31->name.'/', $res->content); // Results from course1 are returned before results from course2. $this->assertTrue(strpos($res->content, $cm11->name) < strpos($res->content, $cm21->name)); // Ordinary user is not able to see anything. $user = $this->getDataGenerator()->create_user(); $this->setUser($user); $res = course_get_tagged_course_modules(core_tag_tag::get_by_name(0, 'Cat'), /*$exclusivemode = */false, /*$fromctx = */0, /*$ctx = */0, /*$rec = */1, /*$page = */0); $this->assertNull($res); // Enrol user as student in course1 and course2. $roleids = $DB->get_records_menu('role', null, '', 'shortname, id'); $this->getDataGenerator()->enrol_user($user->id, $course1->id, $roleids['student']); $this->getDataGenerator()->enrol_user($user->id, $course2->id, $roleids['student']); core_tag_index_builder::reset_caches(); // Searching in the course context returns visible modules in this course. $context = context_course::instance($course1->id); $res = course_get_tagged_course_modules(core_tag_tag::get_by_name(0, 'Cat'), /*$exclusivemode = */false, /*$fromctx = */0, /*$ctx = */$context->id, /*$rec = */1, /*$page = */0); $this->assertMatchesRegularExpression('/'.$cm11->name.'/', $res->content); $this->assertDoesNotMatchRegularExpression('/'.$cm12->name.'/', $res->content); $this->assertMatchesRegularExpression('/'.$cm13->name.'/', $res->content); $this->assertDoesNotMatchRegularExpression('/'.$cm21->name.'/', $res->content); $this->assertDoesNotMatchRegularExpression('/'.$cm31->name.'/', $res->content); // Searching FROM the course context returns visible modules in all courses. $context = context_course::instance($course2->id); $res = course_get_tagged_course_modules(core_tag_tag::get_by_name(0, 'Cat'), /*$exclusivemode = */false, /*$fromctx = */$context->id, /*$ctx = */0, /*$rec = */1, /*$page = */0); $this->assertMatchesRegularExpression('/'.$cm11->name.'/', $res->content); $this->assertDoesNotMatchRegularExpression('/'.$cm12->name.'/', $res->content); $this->assertMatchesRegularExpression('/'.$cm13->name.'/', $res->content); $this->assertMatchesRegularExpression('/'.$cm21->name.'/', $res->content); $this->assertDoesNotMatchRegularExpression('/'.$cm31->name.'/', $res->content); // No access to course3. // Results from course2 are returned before results from course1. $this->assertTrue(strpos($res->content, $cm21->name) < strpos($res->content, $cm11->name)); // Enrol user in course1 as a teacher - now he should be able to see hidden module. $this->getDataGenerator()->enrol_user($user->id, $course1->id, $roleids['editingteacher']); get_fast_modinfo(0,0,true); $context = context_course::instance($course1->id); $res = course_get_tagged_course_modules(core_tag_tag::get_by_name(0, 'Cat'), /*$exclusivemode = */false, /*$fromctx = */$context->id, /*$ctx = */0, /*$rec = */1, /*$page = */0); $this->assertMatchesRegularExpression('/'.$cm12->name.'/', $res->content); // Create more modules and try pagination. $cm14 = $this->getDataGenerator()->create_module('assign', array('course' => $course1->id, 'tags' => 'Cat, Dog')); $cm15 = $this->getDataGenerator()->create_module('page', array('course' => $course1->id, 'tags' => 'Cat, Mouse', 'visible' => 0)); $cm16 = $this->getDataGenerator()->create_module('page', array('course' => $course1->id, 'tags' => 'Cat, Mouse, Dog')); $context = context_course::instance($course1->id); $res = course_get_tagged_course_modules(core_tag_tag::get_by_name(0, 'Cat'), /*$exclusivemode = */false, /*$fromctx = */0, /*$ctx = */$context->id, /*$rec = */1, /*$page = */0); $this->assertMatchesRegularExpression('/'.$cm11->name.'/', $res->content); $this->assertMatchesRegularExpression('/'.$cm12->name.'/', $res->content); $this->assertMatchesRegularExpression('/'.$cm13->name.'/', $res->content); $this->assertDoesNotMatchRegularExpression('/'.$cm21->name.'/', $res->content); $this->assertMatchesRegularExpression('/'.$cm14->name.'/', $res->content); $this->assertMatchesRegularExpression('/'.$cm15->name.'/', $res->content); $this->assertDoesNotMatchRegularExpression('/'.$cm16->name.'/', $res->content); $this->assertDoesNotMatchRegularExpression('/'.$cm31->name.'/', $res->content); // No access to course3. $this->assertEmpty($res->prevpageurl); $this->assertNotEmpty($res->nextpageurl); $res = course_get_tagged_course_modules(core_tag_tag::get_by_name(0, 'Cat'), /*$exclusivemode = */false, /*$fromctx = */0, /*$ctx = */$context->id, /*$rec = */1, /*$page = */1); $this->assertDoesNotMatchRegularExpression('/'.$cm11->name.'/', $res->content); $this->assertDoesNotMatchRegularExpression('/'.$cm12->name.'/', $res->content); $this->assertDoesNotMatchRegularExpression('/'.$cm13->name.'/', $res->content); $this->assertDoesNotMatchRegularExpression('/'.$cm21->name.'/', $res->content); $this->assertDoesNotMatchRegularExpression('/'.$cm14->name.'/', $res->content); $this->assertDoesNotMatchRegularExpression('/'.$cm15->name.'/', $res->content); $this->assertMatchesRegularExpression('/'.$cm16->name.'/', $res->content); $this->assertDoesNotMatchRegularExpression('/'.$cm31->name.'/', $res->content); // No access to course3. $this->assertNotEmpty($res->prevpageurl); $this->assertEmpty($res->nextpageurl); } /** * Test course_get_user_navigation_options for frontpage. */ public function test_course_get_user_navigation_options_for_frontpage() { global $CFG, $SITE, $DB; $this->resetAfterTest(); $context = context_system::instance(); $course = clone $SITE; $this->setAdminUser(); $navoptions = course_get_user_navigation_options($context, $course); $this->assertTrue($navoptions->blogs); $this->assertTrue($navoptions->notes); $this->assertTrue($navoptions->participants); $this->assertTrue($navoptions->badges); $this->assertTrue($navoptions->tags); $this->assertFalse($navoptions->search); $this->assertTrue($navoptions->competencies); // Enable global search now. $CFG->enableglobalsearch = 1; $navoptions = course_get_user_navigation_options($context, $course); $this->assertTrue($navoptions->search); // Disable competencies. $oldcompetencies = get_config('core_competency', 'enabled'); set_config('enabled', false, 'core_competency'); $navoptions = course_get_user_navigation_options($context, $course); $this->assertFalse($navoptions->competencies); set_config('enabled', $oldcompetencies, 'core_competency'); // Now try with a standard user. $user = $this->getDataGenerator()->create_user(); $this->setUser($user); $navoptions = course_get_user_navigation_options($context, $course); $this->assertTrue($navoptions->blogs); $this->assertFalse($navoptions->notes); $this->assertFalse($navoptions->participants); $this->assertTrue($navoptions->badges); $this->assertTrue($navoptions->tags); $this->assertTrue($navoptions->search); } /** * Test course_get_user_navigation_options for managers in a normal course. */ public function test_course_get_user_navigation_options_for_managers() { global $CFG; $this->resetAfterTest(); $course = $this->getDataGenerator()->create_course(); $context = context_course::instance($course->id); $this->setAdminUser(); $navoptions = course_get_user_navigation_options($context); $this->assertTrue($navoptions->blogs); $this->assertTrue($navoptions->notes); $this->assertTrue($navoptions->participants); $this->assertTrue($navoptions->badges); } /** * Test course_get_user_navigation_options for students in a normal course. */ public function test_course_get_user_navigation_options_for_students() { global $DB, $CFG; $this->resetAfterTest(); $course = $this->getDataGenerator()->create_course(); $context = context_course::instance($course->id); $user = $this->getDataGenerator()->create_user(); $roleid = $DB->get_field('role', 'id', array('shortname' => 'student')); $this->getDataGenerator()->enrol_user($user->id, $course->id, $roleid); $this->setUser($user); $navoptions = course_get_user_navigation_options($context); $this->assertTrue($navoptions->blogs); $this->assertFalse($navoptions->notes); $this->assertTrue($navoptions->participants); $this->assertFalse($navoptions->badges); // Disable some options. $CFG->badges_allowcoursebadges = 0; $CFG->enableblogs = 0; // Disable view participants capability. assign_capability('moodle/course:viewparticipants', CAP_PROHIBIT, $roleid, $context); $navoptions = course_get_user_navigation_options($context); $this->assertFalse($navoptions->blogs); $this->assertFalse($navoptions->notes); $this->assertFalse($navoptions->participants); $this->assertFalse($navoptions->badges); // Re-enable some options to check badges are displayed as expected. $CFG->badges_allowcoursebadges = 1; assign_capability('moodle/badges:createbadge', CAP_ALLOW, $roleid, $context); $navoptions = course_get_user_navigation_options($context); $this->assertTrue($navoptions->badges); } /** * Test course_get_user_administration_options for frontpage. */ public function test_course_get_user_administration_options_for_frontpage() { global $CFG, $SITE; $this->resetAfterTest(); $course = clone $SITE; $context = context_course::instance($course->id); $this->setAdminUser(); $adminoptions = course_get_user_administration_options($course, $context); $this->assertTrue($adminoptions->update); $this->assertTrue($adminoptions->filters); $this->assertTrue($adminoptions->reports); $this->assertTrue($adminoptions->backup); $this->assertTrue($adminoptions->restore); $this->assertFalse($adminoptions->files); $this->assertFalse($adminoptions->tags); // Now try with a standard user. $user = $this->getDataGenerator()->create_user(); $this->setUser($user); $adminoptions = course_get_user_administration_options($course, $context); $this->assertFalse($adminoptions->update); $this->assertFalse($adminoptions->filters); $this->assertFalse($adminoptions->reports); $this->assertFalse($adminoptions->backup); $this->assertFalse($adminoptions->restore); $this->assertFalse($adminoptions->files); $this->assertFalse($adminoptions->tags); } /** * Test course_get_user_administration_options for managers in a normal course. */ public function test_course_get_user_administration_options_for_managers() { global $CFG; $this->resetAfterTest(); $course = $this->getDataGenerator()->create_course(); $context = context_course::instance($course->id); $this->setAdminUser(); $adminoptions = course_get_user_administration_options($course, $context); $this->assertTrue($adminoptions->update); $this->assertTrue($adminoptions->filters); $this->assertTrue($adminoptions->reports); $this->assertTrue($adminoptions->backup); $this->assertTrue($adminoptions->restore); $this->assertFalse($adminoptions->files); $this->assertTrue($adminoptions->tags); $this->assertTrue($adminoptions->gradebook); $this->assertFalse($adminoptions->outcomes); $this->assertTrue($adminoptions->badges); $this->assertTrue($adminoptions->import); $this->assertTrue($adminoptions->reset); $this->assertTrue($adminoptions->roles); } /** * Test course_get_user_administration_options for students in a normal course. */ public function test_course_get_user_administration_options_for_students() { global $DB, $CFG; $this->resetAfterTest(); $course = $this->getDataGenerator()->create_course(); $context = context_course::instance($course->id); $user = $this->getDataGenerator()->create_user(); $roleid = $DB->get_field('role', 'id', array('shortname' => 'student')); $this->getDataGenerator()->enrol_user($user->id, $course->id, $roleid); $this->setUser($user); $adminoptions = course_get_user_administration_options($course, $context); $this->assertFalse($adminoptions->update); $this->assertFalse($adminoptions->filters); $this->assertFalse($adminoptions->reports); $this->assertFalse($adminoptions->backup); $this->assertFalse($adminoptions->restore); $this->assertFalse($adminoptions->files); $this->assertFalse($adminoptions->tags); $this->assertFalse($adminoptions->gradebook); $this->assertFalse($adminoptions->outcomes); $this->assertTrue($adminoptions->badges); $this->assertFalse($adminoptions->import); $this->assertFalse($adminoptions->reset); $this->assertFalse($adminoptions->roles); $CFG->enablebadges = false; $adminoptions = course_get_user_administration_options($course, $context); $this->assertFalse($adminoptions->badges); } /** * Test test_update_course_frontpage_category. */ public function test_update_course_frontpage_category() { // Fetch front page course. $course = get_course(SITEID); // Test update information on front page course. $course->category = 99; $this->expectException('moodle_exception'); $this->expectExceptionMessage(get_string('invalidcourse', 'error')); update_course($course); } /** * test_course_enddate * * @dataProvider course_enddate_provider * @param int $startdate * @param int $enddate * @param string $errorcode */ public function test_course_enddate($startdate, $enddate, $errorcode) { $this->resetAfterTest(true); $record = array('startdate' => $startdate, 'enddate' => $enddate); try { $course1 = $this->getDataGenerator()->create_course($record); if ($errorcode !== false) { $this->fail('Expected exception with "' . $errorcode . '" error code in create_create'); } } catch (moodle_exception $e) { if ($errorcode === false) { $this->fail('Got "' . $errorcode . '" exception error code and no exception was expected'); } if ($e->errorcode != $errorcode) { $this->fail('Got "' . $e->errorcode. '" exception error code and "' . $errorcode . '" was expected'); } return; } $this->assertEquals($startdate, $course1->startdate); $this->assertEquals($enddate, $course1->enddate); } /** * Provider for test_course_enddate. * * @return array */ public function course_enddate_provider() { // Each provided example contains startdate, enddate and the expected exception error code if there is any. return [ [ 111, 222, false ], [ 222, 111, 'enddatebeforestartdate' ], [ 111, 0, false ], [ 0, 222, 'nostartdatenoenddate' ] ]; } /** * test_course_dates_reset * * @dataProvider course_dates_reset_provider * @param int $startdate * @param int $enddate * @param int $resetstartdate * @param int $resetenddate * @param int $resultingstartdate * @param int $resultingenddate */ public function test_course_dates_reset($startdate, $enddate, $resetstartdate, $resetenddate, $resultingstartdate, $resultingenddate) { global $CFG, $DB; require_once($CFG->dirroot.'/completion/criteria/completion_criteria_date.php'); $this->resetAfterTest(true); $this->setAdminUser(); $CFG->enablecompletion = true; $this->setTimezone('UTC'); $record = array('startdate' => $startdate, 'enddate' => $enddate, 'enablecompletion' => 1); $originalcourse = $this->getDataGenerator()->create_course($record); $coursecriteria = new completion_criteria_date(array('course' => $originalcourse->id, 'timeend' => $startdate + DAYSECS)); $coursecriteria->insert(); $activitycompletiondate = $startdate + DAYSECS; $data = $this->getDataGenerator()->create_module('data', array('course' => $originalcourse->id), array('completion' => 1, 'completionexpected' => $activitycompletiondate)); $resetdata = new stdClass(); $resetdata->id = $originalcourse->id; $resetdata->reset_start_date_old = $originalcourse->startdate; $resetdata->reset_start_date = $resetstartdate; $resetdata->reset_end_date = $resetenddate; $resetdata->reset_end_date_old = $record['enddate']; reset_course_userdata($resetdata); $course = $DB->get_record('course', array('id' => $originalcourse->id)); $this->assertEquals($resultingstartdate, $course->startdate); $this->assertEquals($resultingenddate, $course->enddate); $coursecompletioncriteria = completion_criteria_date::fetch(array('course' => $originalcourse->id)); $this->assertEquals($resultingstartdate + DAYSECS, $coursecompletioncriteria->timeend); $this->assertEquals($resultingstartdate + DAYSECS, $DB->get_field('course_modules', 'completionexpected', array('id' => $data->cmid))); } /** * Provider for test_course_dates_reset. * * @return array */ public function course_dates_reset_provider() { // Each example contains the following: // - course startdate // - course enddate // - startdate to reset to (false if not reset) // - enddate to reset to (false if not reset) // - resulting startdate // - resulting enddate $time = 1445644800; return [ // No date changes. [ $time, $time + DAYSECS, false, false, $time, $time + DAYSECS ], // End date changes to a valid value. [ $time, $time + DAYSECS, false, $time + DAYSECS + 111, $time, $time + DAYSECS + 111 ], // Start date changes to a valid value. End date does not get updated because it does not have value. [ $time, 0, $time + DAYSECS, false, $time + DAYSECS, 0 ], // Start date changes to a valid value. End date gets updated accordingly. [ $time, $time + DAYSECS, $time + WEEKSECS, false, $time + WEEKSECS, $time + WEEKSECS + DAYSECS ], // Start date and end date change to a valid value. [ $time, $time + DAYSECS, $time + WEEKSECS, $time + YEARSECS, $time + WEEKSECS, $time + YEARSECS ] ]; } /** * Test reset_course_userdata() * - with reset_roles_overrides enabled * - with selective role unenrolments */ public function test_course_roles_reset() { global $DB; $this->resetAfterTest(true); $generator = $this->getDataGenerator(); // Create test course and user, enrol one in the other. $course = $generator->create_course(); $user = $generator->create_user(); $roleid = $DB->get_field('role', 'id', array('shortname' => 'student'), MUST_EXIST); $generator->enrol_user($user->id, $course->id, $roleid); // Test case with reset_roles_overrides enabled. // Override course so it does NOT allow students 'mod/forum:viewdiscussion'. $coursecontext = context_course::instance($course->id); assign_capability('mod/forum:viewdiscussion', CAP_PREVENT, $roleid, $coursecontext->id); // Check expected capabilities so far. $this->assertFalse(has_capability('mod/forum:viewdiscussion', $coursecontext, $user)); // Oops, preventing student from viewing forums was a mistake, let's reset the course. $resetdata = new stdClass(); $resetdata->id = $course->id; $resetdata->reset_roles_overrides = true; reset_course_userdata($resetdata); // Check new expected capabilities - override at the course level should be reset. $this->assertTrue(has_capability('mod/forum:viewdiscussion', $coursecontext, $user)); // Test case with selective role unenrolments. $roles = array(); $roles['student'] = $DB->get_field('role', 'id', array('shortname' => 'student'), MUST_EXIST); $roles['teacher'] = $DB->get_field('role', 'id', array('shortname' => 'teacher'), MUST_EXIST); // We enrol a user with student and teacher roles. $generator->enrol_user($user->id, $course->id, $roles['student']); $generator->enrol_user($user->id, $course->id, $roles['teacher']); // When we reset only student role, we expect to keep teacher role. $resetdata = new stdClass(); $resetdata->id = $course->id; $resetdata->unenrol_users = array($roles['student']); reset_course_userdata($resetdata); $usersroles = enrol_get_course_users_roles($course->id); $this->assertArrayHasKey($user->id, $usersroles); $this->assertArrayHasKey($roles['teacher'], $usersroles[$user->id]); $this->assertArrayNotHasKey($roles['student'], $usersroles[$user->id]); $this->assertCount(1, $usersroles[$user->id]); // We reenrol user as student. $generator->enrol_user($user->id, $course->id, $roles['student']); // When we reset student and teacher roles, we expect no roles left. $resetdata = new stdClass(); $resetdata->id = $course->id; $resetdata->unenrol_users = array($roles['student'], $roles['teacher']); reset_course_userdata($resetdata); $usersroles = enrol_get_course_users_roles($course->id); $this->assertEmpty($usersroles); } public function test_course_check_module_updates_since() { global $CFG, $DB, $USER; require_once($CFG->dirroot . '/mod/glossary/lib.php'); require_once($CFG->dirroot . '/rating/lib.php'); require_once($CFG->dirroot . '/comment/lib.php'); $this->resetAfterTest(true); $CFG->enablecompletion = true; $course = $this->getDataGenerator()->create_course(array('enablecompletion' => 1)); $glossary = $this->getDataGenerator()->create_module('glossary', array( 'course' => $course->id, 'completion' => COMPLETION_TRACKING_AUTOMATIC, 'completionview' => 1, 'allowcomments' => 1, 'assessed' => RATING_AGGREGATE_AVERAGE, 'scale' => 100 )); $glossarygenerator = $this->getDataGenerator()->get_plugin_generator('mod_glossary'); $context = context_module::instance($glossary->cmid); $modinfo = get_fast_modinfo($course); $cm = $modinfo->get_cm($glossary->cmid); $user = $this->getDataGenerator()->create_user(); $studentrole = $DB->get_record('role', array('shortname' => 'student')); $this->getDataGenerator()->enrol_user($user->id, $course->id, $studentrole->id); $from = time(); $teacher = $this->getDataGenerator()->create_user(); $teacherrole = $DB->get_record('role', array('shortname' => 'teacher')); $this->getDataGenerator()->enrol_user($teacher->id, $course->id, $teacherrole->id); assign_capability('mod/glossary:viewanyrating', CAP_ALLOW, $studentrole->id, $context->id, true); // Check nothing changed right now. $updates = course_check_module_updates_since($cm, $from); $this->assertFalse($updates->configuration->updated); $this->assertFalse($updates->completion->updated); $this->assertFalse($updates->gradeitems->updated); $this->assertFalse($updates->comments->updated); $this->assertFalse($updates->ratings->updated); $this->assertFalse($updates->introfiles->updated); $this->assertFalse($updates->outcomes->updated); $this->waitForSecond(); // Do some changes. $this->setUser($user); $entry = $glossarygenerator->create_content($glossary); $this->setUser($teacher); // Name. set_coursemodule_name($glossary->cmid, 'New name'); // Add some ratings. $rm = new rating_manager(); $result = $rm->add_rating($cm, $context, 'mod_glossary', 'entry', $entry->id, 100, 50, $user->id, RATING_AGGREGATE_AVERAGE); // Change grades. $glossary->cmidnumber = $glossary->cmid; glossary_update_grades($glossary, $user->id); $this->setUser($user); // Completion status. glossary_view($glossary, $course, $cm, $context, 'letter'); // Add one comment. $args = new stdClass; $args->context = $context; $args->course = $course; $args->cm = $cm; $args->area = 'glossary_entry'; $args->itemid = $entry->id; $args->client_id = 1; $args->component = 'mod_glossary'; $manager = new comment($args); $manager->add('blah blah blah'); // Check upgrade status. $updates = course_check_module_updates_since($cm, $from); $this->assertTrue($updates->configuration->updated); $this->assertTrue($updates->completion->updated); $this->assertTrue($updates->gradeitems->updated); $this->assertTrue($updates->comments->updated); $this->assertTrue($updates->ratings->updated); $this->assertFalse($updates->introfiles->updated); $this->assertFalse($updates->outcomes->updated); } public function test_async_module_deletion_hook_implemented() { // Async module deletion depends on the 'true' being returned by at least one plugin implementing the hook, // 'course_module_adhoc_deletion_recommended'. In core, is implemented by the course recyclebin, which will only return // true if the recyclebin plugin is enabled. To make sure async deletion occurs, this test force-enables the recyclebin. global $DB, $USER; $this->resetAfterTest(true); $this->setAdminUser(); // Ensure recyclebin is enabled. set_config('coursebinenable', true, 'tool_recyclebin'); // Create course, module and context. $course = $this->getDataGenerator()->create_course(['numsections' => 5]); $module = $this->getDataGenerator()->create_module('assign', ['course' => $course->id]); $modcontext = context_module::instance($module->cmid); // Verify context exists. $this->assertInstanceOf('context_module', $modcontext); // Check events generated on the course_delete_module call. $sink = $this->redirectEvents(); // Try to delete the module using the async flag. course_delete_module($module->cmid, true); // Try to delete the module asynchronously. // Verify that no event has been generated yet. $events = $sink->get_events(); $event = array_pop($events); $sink->close(); $this->assertEmpty($event); // Grab the record, in it's final state before hard deletion, for comparison with the event snapshot. // We need to do this because the 'deletioninprogress' flag has changed from '0' to '1'. $cm = $DB->get_record('course_modules', ['id' => $module->cmid], '*', MUST_EXIST); // Verify the course_module is marked as 'deletioninprogress'. $this->assertNotEquals($cm, false); $this->assertEquals($cm->deletioninprogress, '1'); // Verify the context has not yet been removed. $this->assertEquals($modcontext, context_module::instance($module->cmid, IGNORE_MISSING)); // Set up a sink to catch the 'course_module_deleted' event. $sink = $this->redirectEvents(); // Now, run the adhoc task which performs the hard deletion. phpunit_util::run_all_adhoc_tasks(); // Fetch and validate the event data. $events = $sink->get_events(); $event = array_pop($events); $sink->close(); $this->assertInstanceOf('\core\event\course_module_deleted', $event); $this->assertEquals($module->cmid, $event->objectid); $this->assertEquals($USER->id, $event->userid); $this->assertEquals('course_modules', $event->objecttable); $this->assertEquals(null, $event->get_url()); $this->assertEquals($cm, $event->get_record_snapshot('course_modules', $module->cmid)); // Verify the context has been removed. $this->assertFalse(context_module::instance($module->cmid, IGNORE_MISSING)); // Verify the course_module record has been deleted. $cmcount = $DB->count_records('course_modules', ['id' => $module->cmid]); $this->assertEmpty($cmcount); } public function test_async_module_deletion_hook_not_implemented() { // Only proceed if we are sure that no plugin is going to advocate async removal of a module. I.e. no plugin returns // 'true' from the 'course_module_adhoc_deletion_recommended' hook. // In the case of core, only recyclebin implements this hook, and it will only return true if enabled, so disable it. global $DB, $USER; $this->resetAfterTest(true); $this->setAdminUser(); set_config('coursebinenable', false, 'tool_recyclebin'); // Non-core plugins might implement the 'course_module_adhoc_deletion_recommended' hook and spoil this test. // If at least one plugin still returns true, then skip this test. if ($pluginsfunction = get_plugins_with_function('course_module_background_deletion_recommended')) { foreach ($pluginsfunction as $plugintype => $plugins) { foreach ($plugins as $pluginfunction) { if ($pluginfunction()) { $this->markTestSkipped(); } } } } // Create course, module and context. $course = $this->getDataGenerator()->create_course(['numsections' => 5]); $module = $this->getDataGenerator()->create_module('assign', ['course' => $course->id]); $modcontext = context_module::instance($module->cmid); $cm = $DB->get_record('course_modules', ['id' => $module->cmid], '*', MUST_EXIST); // Verify context exists. $this->assertInstanceOf('context_module', $modcontext); // Check events generated on the course_delete_module call. $sink = $this->redirectEvents(); // Try to delete the module using the async flag. course_delete_module($module->cmid, true); // Try to delete the module asynchronously. // Fetch and validate the event data. $events = $sink->get_events(); $event = array_pop($events); $sink->close(); $this->assertInstanceOf('\core\event\course_module_deleted', $event); $this->assertEquals($module->cmid, $event->objectid); $this->assertEquals($USER->id, $event->userid); $this->assertEquals('course_modules', $event->objecttable); $this->assertEquals(null, $event->get_url()); $this->assertEquals($cm, $event->get_record_snapshot('course_modules', $module->cmid)); // Verify the context has been removed. $this->assertFalse(context_module::instance($module->cmid, IGNORE_MISSING)); // Verify the course_module record has been deleted. $cmcount = $DB->count_records('course_modules', ['id' => $module->cmid]); $this->assertEmpty($cmcount); } public function test_async_section_deletion_hook_implemented() { // Async section deletion (provided section contains modules), depends on the 'true' being returned by at least one plugin // implementing the 'course_module_adhoc_deletion_recommended' hook. In core, is implemented by the course recyclebin, // which will only return true if the plugin is enabled. To make sure async deletion occurs, this test enables recyclebin. global $DB, $USER; $this->resetAfterTest(true); $this->setAdminUser(); // Ensure recyclebin is enabled. set_config('coursebinenable', true, 'tool_recyclebin'); // Create course, module and context. $generator = $this->getDataGenerator(); $course = $generator->create_course(['numsections' => 4, 'format' => 'topics'], ['createsections' => true]); $assign0 = $generator->create_module('assign', ['course' => $course, 'section' => 2]); $assign1 = $generator->create_module('assign', ['course' => $course, 'section' => 2]); $assign2 = $generator->create_module('assign', ['course' => $course, 'section' => 2]); $assign3 = $generator->create_module('assign', ['course' => $course, 'section' => 0]); // Delete empty section. No difference from normal, synchronous behaviour. $this->assertTrue(course_delete_section($course, 4, false, true)); $this->assertEquals(3, course_get_format($course)->get_last_section_number()); // Delete a module in section 2 (using async). Need to verify this doesn't generate two tasks when we delete // the section in the next step. course_delete_module($assign2->cmid, true); // Confirm that the module is pending deletion in its current section. $section = $DB->get_record('course_sections', ['course' => $course->id, 'section' => '2']); // For event comparison. $this->assertEquals(true, $DB->record_exists('course_modules', ['id' => $assign2->cmid, 'deletioninprogress' => 1, 'section' => $section->id])); // Now, delete section 2. $this->assertFalse(course_delete_section($course, 2, false, true)); // Non-empty section, no forcedelete, so no change. $sink = $this->redirectEvents(); // To capture the event. $this->assertTrue(course_delete_section($course, 2, true, true)); // Now, confirm that: // a) the section's modules have been flagged for deletion and moved to section 0 and; // b) the section has been deleted and; // c) course_section_deleted event has been fired. The course_module_deleted events will only fire once they have been // removed from section 0 via the adhoc task. // Modules should have been flagged for deletion and moved to section 0. $sectionid = $DB->get_field('course_sections', 'id', ['course' => $course->id, 'section' => 0]); $this->assertEquals(3, $DB->count_records('course_modules', ['section' => $sectionid, 'deletioninprogress' => 1])); // Confirm the section has been deleted. $this->assertEquals(2, course_get_format($course)->get_last_section_number()); // Check event fired. $events = $sink->get_events(); $event = array_pop($events); $sink->close(); $this->assertInstanceOf('\core\event\course_section_deleted', $event); $this->assertEquals($section->id, $event->objectid); $this->assertEquals($USER->id, $event->userid); $this->assertEquals('course_sections', $event->objecttable); $this->assertEquals(null, $event->get_url()); $this->assertEquals($section, $event->get_record_snapshot('course_sections', $section->id)); // Now, run the adhoc task to delete the modules from section 0. $sink = $this->redirectEvents(); // To capture the events. phpunit_util::run_all_adhoc_tasks(); // Confirm the modules have been deleted. list($insql, $assignids) = $DB->get_in_or_equal([$assign0->cmid, $assign1->cmid, $assign2->cmid]); $cmcount = $DB->count_records_select('course_modules', 'id ' . $insql, $assignids); $this->assertEmpty($cmcount); // Confirm other modules in section 0 still remain. $this->assertEquals(1, $DB->count_records('course_modules', ['id' => $assign3->cmid])); // Confirm that events were generated for all 3 of the modules. $events = $sink->get_events(); $sink->close(); $count = 0; while (!empty($events)) { $event = array_pop($events); if ($event instanceof \core\event\course_module_deleted && in_array($event->objectid, [$assign0->cmid, $assign1->cmid, $assign2->cmid])) { $count++; } } $this->assertEquals(3, $count); } public function test_async_section_deletion_hook_not_implemented() { // If no plugins advocate async removal, then normal synchronous removal will take place. // Only proceed if we are sure that no plugin is going to advocate async removal of a module. I.e. no plugin returns // 'true' from the 'course_module_adhoc_deletion_recommended' hook. // In the case of core, only recyclebin implements this hook, and it will only return true if enabled, so disable it. global $DB, $USER; $this->resetAfterTest(true); $this->setAdminUser(); set_config('coursebinenable', false, 'tool_recyclebin'); // Non-core plugins might implement the 'course_module_adhoc_deletion_recommended' hook and spoil this test. // If at least one plugin still returns true, then skip this test. if ($pluginsfunction = get_plugins_with_function('course_module_background_deletion_recommended')) { foreach ($pluginsfunction as $plugintype => $plugins) { foreach ($plugins as $pluginfunction) { if ($pluginfunction()) { $this->markTestSkipped(); } } } } // Create course, module and context. $generator = $this->getDataGenerator(); $course = $generator->create_course(['numsections' => 4, 'format' => 'topics'], ['createsections' => true]); $assign0 = $generator->create_module('assign', ['course' => $course, 'section' => 2]); $assign1 = $generator->create_module('assign', ['course' => $course, 'section' => 2]); // Delete empty section. No difference from normal, synchronous behaviour. $this->assertTrue(course_delete_section($course, 4, false, true)); $this->assertEquals(3, course_get_format($course)->get_last_section_number()); // Delete section in the middle (2). $section = $DB->get_record('course_sections', ['course' => $course->id, 'section' => '2']); // For event comparison. $this->assertFalse(course_delete_section($course, 2, false, true)); // Non-empty section, no forcedelete, so no change. $sink = $this->redirectEvents(); // To capture the event. $this->assertTrue(course_delete_section($course, 2, true, true)); // Now, confirm that: // a) The section's modules have deleted and; // b) the section has been deleted and; // c) course_section_deleted event has been fired and; // d) course_module_deleted events have both been fired. // Confirm modules have been deleted. list($insql, $assignids) = $DB->get_in_or_equal([$assign0->cmid, $assign1->cmid]); $cmcount = $DB->count_records_select('course_modules', 'id ' . $insql, $assignids); $this->assertEmpty($cmcount); // Confirm the section has been deleted. $this->assertEquals(2, course_get_format($course)->get_last_section_number()); // Confirm the course_section_deleted event has been generated. $events = $sink->get_events(); $event = array_pop($events); $sink->close(); $this->assertInstanceOf('\core\event\course_section_deleted', $event); $this->assertEquals($section->id, $event->objectid); $this->assertEquals($USER->id, $event->userid); $this->assertEquals('course_sections', $event->objecttable); $this->assertEquals(null, $event->get_url()); $this->assertEquals($section, $event->get_record_snapshot('course_sections', $section->id)); // Confirm that the course_module_deleted events have both been generated. $count = 0; while (!empty($events)) { $event = array_pop($events); if ($event instanceof \core\event\course_module_deleted && in_array($event->objectid, [$assign0->cmid, $assign1->cmid])) { $count++; } } $this->assertEquals(2, $count); } public function test_classify_course_for_timeline() { global $DB, $CFG; require_once($CFG->dirroot.'/completion/criteria/completion_criteria_self.php'); set_config('enablecompletion', COMPLETION_ENABLED); set_config('coursegraceperiodbefore', 0); set_config('coursegraceperiodafter', 0); $this->resetAfterTest(true); $this->setAdminUser(); // Create courses for testing. $generator = $this->getDataGenerator(); $future = time() + 3600; $past = time() - 3600; $futurecourse = $generator->create_course(['startdate' => $future]); $pastcourse = $generator->create_course(['startdate' => $past - 60, 'enddate' => $past]); $completedcourse = $generator->create_course(['enablecompletion' => COMPLETION_ENABLED]); $inprogresscourse = $generator->create_course(); // Set completion rules. $criteriadata = new stdClass(); $criteriadata->id = $completedcourse->id; // Self completion. $criteriadata->criteria_self = COMPLETION_CRITERIA_TYPE_SELF; $class = 'completion_criteria_self'; $criterion = new $class(); $criterion->update_config($criteriadata); $user = $this->getDataGenerator()->create_user(); $studentrole = $DB->get_record('role', array('shortname' => 'student')); $this->getDataGenerator()->enrol_user($user->id, $futurecourse->id, $studentrole->id); $this->getDataGenerator()->enrol_user($user->id, $pastcourse->id, $studentrole->id); $this->getDataGenerator()->enrol_user($user->id, $completedcourse->id, $studentrole->id); $this->getDataGenerator()->enrol_user($user->id, $inprogresscourse->id, $studentrole->id); $this->setUser($user); core_completion_external::mark_course_self_completed($completedcourse->id); $ccompletion = new completion_completion(array('course' => $completedcourse->id, 'userid' => $user->id)); $ccompletion->mark_complete(); // Aggregate the completions. $this->assertEquals(COURSE_TIMELINE_PAST, course_classify_for_timeline($pastcourse)); $this->assertEquals(COURSE_TIMELINE_FUTURE, course_classify_for_timeline($futurecourse)); $this->assertEquals(COURSE_TIMELINE_PAST, course_classify_for_timeline($completedcourse)); $this->assertEquals(COURSE_TIMELINE_INPROGRESS, course_classify_for_timeline($inprogresscourse)); // Test grace period. set_config('coursegraceperiodafter', 1); set_config('coursegraceperiodbefore', 1); $this->assertEquals(COURSE_TIMELINE_INPROGRESS, course_classify_for_timeline($pastcourse)); $this->assertEquals(COURSE_TIMELINE_INPROGRESS, course_classify_for_timeline($futurecourse)); $this->assertEquals(COURSE_TIMELINE_PAST, course_classify_for_timeline($completedcourse)); $this->assertEquals(COURSE_TIMELINE_INPROGRESS, course_classify_for_timeline($inprogresscourse)); } /** * Test the main function for updating all calendar events for a module. */ public function test_course_module_calendar_event_update_process() { global $DB; $this->resetAfterTest(); $this->setAdminUser(); $completionexpected = time(); $duedate = time(); $course = $this->getDataGenerator()->create_course(['enablecompletion' => COMPLETION_ENABLED]); $assign = $this->getDataGenerator()->create_module('assign', [ 'course' => $course, 'completionexpected' => $completionexpected, 'duedate' => $duedate ]); $cm = get_coursemodule_from_instance('assign', $assign->id, $course->id); $events = $DB->get_records('event', ['courseid' => $course->id, 'instance' => $assign->id]); // Check that both events are using the expected dates. foreach ($events as $event) { if ($event->eventtype == \core_completion\api::COMPLETION_EVENT_TYPE_DATE_COMPLETION_EXPECTED) { $this->assertEquals($completionexpected, $event->timestart); } if ($event->eventtype == ASSIGN_EVENT_TYPE_DUE) { $this->assertEquals($duedate, $event->timestart); } } // We have to manually update the module and the course module. $newcompletionexpected = time() + DAYSECS * 60; $newduedate = time() + DAYSECS * 45; $newmodulename = 'Assign - new name'; $moduleobject = (object)array('id' => $assign->id, 'duedate' => $newduedate, 'name' => $newmodulename); $DB->update_record('assign', $moduleobject); $cmobject = (object)array('id' => $cm->id, 'completionexpected' => $newcompletionexpected); $DB->update_record('course_modules', $cmobject); $assign = $DB->get_record('assign', ['id' => $assign->id]); $cm = get_coursemodule_from_instance('assign', $assign->id, $course->id); course_module_calendar_event_update_process($assign, $cm); $events = $DB->get_records('event', ['courseid' => $course->id, 'instance' => $assign->id]); // Now check that the details have been updated properly from the function. foreach ($events as $event) { if ($event->eventtype == \core_completion\api::COMPLETION_EVENT_TYPE_DATE_COMPLETION_EXPECTED) { $this->assertEquals($newcompletionexpected, $event->timestart); $this->assertEquals(get_string('completionexpectedfor', 'completion', (object)['instancename' => $newmodulename]), $event->name); } if ($event->eventtype == ASSIGN_EVENT_TYPE_DUE) { $this->assertEquals($newduedate, $event->timestart); $this->assertEquals(get_string('calendardue', 'assign', $newmodulename), $event->name); } } } /** * Test the higher level checks for updating calendar events for an instance. */ public function test_course_module_update_calendar_events() { $this->resetAfterTest(); $this->setAdminUser(); $completionexpected = time(); $duedate = time(); $course = $this->getDataGenerator()->create_course(['enablecompletion' => COMPLETION_ENABLED]); $assign = $this->getDataGenerator()->create_module('assign', [ 'course' => $course, 'completionexpected' => $completionexpected, 'duedate' => $duedate ]); $cm = get_coursemodule_from_instance('assign', $assign->id, $course->id); // Both the instance and cm objects are missing. $this->assertFalse(course_module_update_calendar_events('assign')); // Just using the assign instance. $this->assertTrue(course_module_update_calendar_events('assign', $assign)); // Just using the course module object. $this->assertTrue(course_module_update_calendar_events('assign', null, $cm)); // Using both the assign instance and the course module object. $this->assertTrue(course_module_update_calendar_events('assign', $assign, $cm)); } /** * Test the higher level checks for updating calendar events for a module. */ public function test_course_module_bulk_update_calendar_events() { $this->resetAfterTest(); $this->setAdminUser(); $completionexpected = time(); $duedate = time(); $course = $this->getDataGenerator()->create_course(['enablecompletion' => COMPLETION_ENABLED]); $course2 = $this->getDataGenerator()->create_course(['enablecompletion' => COMPLETION_ENABLED]); $assign = $this->getDataGenerator()->create_module('assign', [ 'course' => $course, 'completionexpected' => $completionexpected, 'duedate' => $duedate ]); // No assign instances in this course. $this->assertFalse(course_module_bulk_update_calendar_events('assign', $course2->id)); // No book instances for the site. $this->assertFalse(course_module_bulk_update_calendar_events('book')); // Update all assign instances. $this->assertTrue(course_module_bulk_update_calendar_events('assign')); // Update the assign instances for this course. $this->assertTrue(course_module_bulk_update_calendar_events('assign', $course->id)); } /** * Test that a student can view participants in a course they are enrolled in. */ public function test_course_can_view_participants_as_student() { $this->resetAfterTest(); $course = $this->getDataGenerator()->create_course(); $coursecontext = context_course::instance($course->id); $user = $this->getDataGenerator()->create_user(); $this->getDataGenerator()->enrol_user($user->id, $course->id); $this->setUser($user); $this->assertTrue(course_can_view_participants($coursecontext)); } /** * Test that a student in a course can not view participants on the site. */ public function test_course_can_view_participants_as_student_on_site() { $this->resetAfterTest(); $course = $this->getDataGenerator()->create_course(); $user = $this->getDataGenerator()->create_user(); $this->getDataGenerator()->enrol_user($user->id, $course->id); $this->setUser($user); $this->assertFalse(course_can_view_participants(context_system::instance())); } /** * Test that an admin can view participants on the site. */ public function test_course_can_view_participants_as_admin_on_site() { $this->resetAfterTest(); $this->setAdminUser(); $this->assertTrue(course_can_view_participants(context_system::instance())); } /** * Test teachers can view participants in a course they are enrolled in. */ public function test_course_can_view_participants_as_teacher() { global $DB; $this->resetAfterTest(); $course = $this->getDataGenerator()->create_course(); $coursecontext = context_course::instance($course->id); $user = $this->getDataGenerator()->create_user(); $roleid = $DB->get_field('role', 'id', array('shortname' => 'editingteacher')); $this->getDataGenerator()->enrol_user($user->id, $course->id, $roleid); $this->setUser($user); $this->assertTrue(course_can_view_participants($coursecontext)); } /** * Check the teacher can still view the participants page without the 'viewparticipants' cap. */ public function test_course_can_view_participants_as_teacher_without_view_participants_cap() { global $DB; $this->resetAfterTest(); $course = $this->getDataGenerator()->create_course(); $coursecontext = context_course::instance($course->id); $user = $this->getDataGenerator()->create_user(); $roleid = $DB->get_field('role', 'id', array('shortname' => 'editingteacher')); $this->getDataGenerator()->enrol_user($user->id, $course->id, $roleid); $this->setUser($user); // Disable one of the capabilties. assign_capability('moodle/course:viewparticipants', CAP_PROHIBIT, $roleid, $coursecontext); // Should still be able to view the page as they have the 'moodle/course:enrolreview' cap. $this->assertTrue(course_can_view_participants($coursecontext)); } /** * Check the teacher can still view the participants page without the 'moodle/course:enrolreview' cap. */ public function test_course_can_view_participants_as_teacher_without_enrol_review_cap() { global $DB; $this->resetAfterTest(); $course = $this->getDataGenerator()->create_course(); $coursecontext = context_course::instance($course->id); $user = $this->getDataGenerator()->create_user(); $roleid = $DB->get_field('role', 'id', array('shortname' => 'editingteacher')); $this->getDataGenerator()->enrol_user($user->id, $course->id, $roleid); $this->setUser($user); // Disable one of the capabilties. assign_capability('moodle/course:enrolreview', CAP_PROHIBIT, $roleid, $coursecontext); // Should still be able to view the page as they have the 'moodle/course:viewparticipants' cap. $this->assertTrue(course_can_view_participants($coursecontext)); } /** * Check the teacher can not view the participants page without the required caps. */ public function test_course_can_view_participants_as_teacher_without_required_caps() { global $DB; $this->resetAfterTest(); $course = $this->getDataGenerator()->create_course(); $coursecontext = context_course::instance($course->id); $user = $this->getDataGenerator()->create_user(); $roleid = $DB->get_field('role', 'id', array('shortname' => 'editingteacher')); $this->getDataGenerator()->enrol_user($user->id, $course->id, $roleid); $this->setUser($user); // Disable the capabilities. assign_capability('moodle/course:viewparticipants', CAP_PROHIBIT, $roleid, $coursecontext); assign_capability('moodle/course:enrolreview', CAP_PROHIBIT, $roleid, $coursecontext); $this->assertFalse(course_can_view_participants($coursecontext)); } /** * Check that an exception is not thrown if we can view the participants page. */ public function test_course_require_view_participants() { $this->resetAfterTest(); $course = $this->getDataGenerator()->create_course(); $coursecontext = context_course::instance($course->id); $user = $this->getDataGenerator()->create_user(); $this->getDataGenerator()->enrol_user($user->id, $course->id); $this->setUser($user); course_require_view_participants($coursecontext); } /** * Check that an exception is thrown if we can't view the participants page. */ public function test_course_require_view_participants_as_student_on_site() { $this->resetAfterTest(); $course = $this->getDataGenerator()->create_course(); $user = $this->getDataGenerator()->create_user(); $this->getDataGenerator()->enrol_user($user->id, $course->id); $this->setUser($user); $this->expectException('required_capability_exception'); course_require_view_participants(context_system::instance()); } /** * Testing the can_download_from_backup_filearea fn. */ public function test_can_download_from_backup_filearea() { global $DB; $this->resetAfterTest(); $course = $this->getDataGenerator()->create_course(); $context = context_course::instance($course->id); $user = $this->getDataGenerator()->create_user(); $teacherrole = $DB->get_record('role', array('shortname' => 'teacher')); $this->getDataGenerator()->enrol_user($user->id, $course->id, $teacherrole->id); // The 'automated' backup area. Downloading from this area requires two capabilities. // If the user has only the 'backup:downloadfile' capability. unassign_capability('moodle/restore:userinfo', $teacherrole->id, $context); assign_capability('moodle/backup:downloadfile', CAP_ALLOW, $teacherrole->id, $context); $this->assertFalse(can_download_from_backup_filearea('automated', $context, $user)); // If the user has only the 'restore:userinfo' capability. unassign_capability('moodle/backup:downloadfile', $teacherrole->id, $context); assign_capability('moodle/restore:userinfo', CAP_ALLOW, $teacherrole->id, $context); $this->assertFalse(can_download_from_backup_filearea('automated', $context, $user)); // If the user has both capabilities. assign_capability('moodle/backup:downloadfile', CAP_ALLOW, $teacherrole->id, $context); assign_capability('moodle/restore:userinfo', CAP_ALLOW, $teacherrole->id, $context); $this->assertTrue(can_download_from_backup_filearea('automated', $context, $user)); // Is the user has neither of the capabilities. unassign_capability('moodle/backup:downloadfile', $teacherrole->id, $context); unassign_capability('moodle/restore:userinfo', $teacherrole->id, $context); $this->assertFalse(can_download_from_backup_filearea('automated', $context, $user)); // The 'course ' and 'backup' backup file areas. These are governed by the same download capability. // User has the capability. unassign_capability('moodle/restore:userinfo', $teacherrole->id, $context); assign_capability('moodle/backup:downloadfile', CAP_ALLOW, $teacherrole->id, $context); $this->assertTrue(can_download_from_backup_filearea('course', $context, $user)); $this->assertTrue(can_download_from_backup_filearea('backup', $context, $user)); // User doesn't have the capability. unassign_capability('moodle/backup:downloadfile', $teacherrole->id, $context); $this->assertFalse(can_download_from_backup_filearea('course', $context, $user)); $this->assertFalse(can_download_from_backup_filearea('backup', $context, $user)); // A file area that doesn't exist. No permissions, regardless of capabilities. assign_capability('moodle/backup:downloadfile', CAP_ALLOW, $teacherrole->id, $context); $this->assertFalse(can_download_from_backup_filearea('testing', $context, $user)); } /** * Test cases for the course_classify_courses_for_timeline test. */ public function get_course_classify_courses_for_timeline_test_cases() { $now = time(); $day = 86400; return [ 'no courses' => [ 'coursesdata' => [], 'expected' => [ COURSE_TIMELINE_PAST => [], COURSE_TIMELINE_FUTURE => [], COURSE_TIMELINE_INPROGRESS => [] ] ], 'only past' => [ 'coursesdata' => [ [ 'shortname' => 'past1', 'startdate' => $now - ($day * 2), 'enddate' => $now - $day ], [ 'shortname' => 'past2', 'startdate' => $now - ($day * 2), 'enddate' => $now - $day ] ], 'expected' => [ COURSE_TIMELINE_PAST => ['past1', 'past2'], COURSE_TIMELINE_FUTURE => [], COURSE_TIMELINE_INPROGRESS => [] ] ], 'only in progress' => [ 'coursesdata' => [ [ 'shortname' => 'inprogress1', 'startdate' => $now - $day, 'enddate' => $now + $day ], [ 'shortname' => 'inprogress2', 'startdate' => $now - $day, 'enddate' => $now + $day ] ], 'expected' => [ COURSE_TIMELINE_PAST => [], COURSE_TIMELINE_FUTURE => [], COURSE_TIMELINE_INPROGRESS => ['inprogress1', 'inprogress2'] ] ], 'only future' => [ 'coursesdata' => [ [ 'shortname' => 'future1', 'startdate' => $now + $day ], [ 'shortname' => 'future2', 'startdate' => $now + $day ] ], 'expected' => [ COURSE_TIMELINE_PAST => [], COURSE_TIMELINE_FUTURE => ['future1', 'future2'], COURSE_TIMELINE_INPROGRESS => [] ] ], 'combination' => [ 'coursesdata' => [ [ 'shortname' => 'past1', 'startdate' => $now - ($day * 2), 'enddate' => $now - $day ], [ 'shortname' => 'past2', 'startdate' => $now - ($day * 2), 'enddate' => $now - $day ], [ 'shortname' => 'inprogress1', 'startdate' => $now - $day, 'enddate' => $now + $day ], [ 'shortname' => 'inprogress2', 'startdate' => $now - $day, 'enddate' => $now + $day ], [ 'shortname' => 'future1', 'startdate' => $now + $day ], [ 'shortname' => 'future2', 'startdate' => $now + $day ] ], 'expected' => [ COURSE_TIMELINE_PAST => ['past1', 'past2'], COURSE_TIMELINE_FUTURE => ['future1', 'future2'], COURSE_TIMELINE_INPROGRESS => ['inprogress1', 'inprogress2'] ] ], ]; } /** * Test the course_classify_courses_for_timeline function. * * @dataProvider get_course_classify_courses_for_timeline_test_cases() * @param array $coursesdata Courses to create * @param array $expected Expected test results. */ public function test_course_classify_courses_for_timeline($coursesdata, $expected) { $this->resetAfterTest(); $generator = $this->getDataGenerator(); $courses = array_map(function($coursedata) use ($generator) { return $generator->create_course($coursedata); }, $coursesdata); sort($expected[COURSE_TIMELINE_PAST]); sort($expected[COURSE_TIMELINE_FUTURE]); sort($expected[COURSE_TIMELINE_INPROGRESS]); $results = course_classify_courses_for_timeline($courses); $actualpast = array_map(function($result) { return $result->shortname; }, $results[COURSE_TIMELINE_PAST]); $actualfuture = array_map(function($result) { return $result->shortname; }, $results[COURSE_TIMELINE_FUTURE]); $actualinprogress = array_map(function($result) { return $result->shortname; }, $results[COURSE_TIMELINE_INPROGRESS]); sort($actualpast); sort($actualfuture); sort($actualinprogress); $this->assertEquals($expected[COURSE_TIMELINE_PAST], $actualpast); $this->assertEquals($expected[COURSE_TIMELINE_FUTURE], $actualfuture); $this->assertEquals($expected[COURSE_TIMELINE_INPROGRESS], $actualinprogress); } /** * Test cases for the course_get_enrolled_courses_for_logged_in_user tests. */ public function get_course_get_enrolled_courses_for_logged_in_user_test_cases() { $buildexpectedresult = function($limit, $offset) { $result = []; for ($i = $offset; $i < $offset + $limit; $i++) { $result[] = "testcourse{$i}"; } return $result; }; return [ 'zero records' => [ 'dbquerylimit' => 3, 'totalcourses' => 0, 'limit' => 0, 'offset' => 0, 'expecteddbqueries' => 4, 'expectedresult' => $buildexpectedresult(0, 0) ], 'less than query limit' => [ 'dbquerylimit' => 3, 'totalcourses' => 2, 'limit' => 0, 'offset' => 0, 'expecteddbqueries' => 2, 'expectedresult' => $buildexpectedresult(2, 0) ], 'more than query limit' => [ 'dbquerylimit' => 3, 'totalcourses' => 7, 'limit' => 0, 'offset' => 0, 'expecteddbqueries' => 4, 'expectedresult' => $buildexpectedresult(7, 0) ], 'limit less than query limit' => [ 'dbquerylimit' => 3, 'totalcourses' => 7, 'limit' => 2, 'offset' => 0, 'expecteddbqueries' => 2, 'expectedresult' => $buildexpectedresult(2, 0) ], 'limit less than query limit with offset' => [ 'dbquerylimit' => 3, 'totalcourses' => 7, 'limit' => 2, 'offset' => 2, 'expecteddbqueries' => 2, 'expectedresult' => $buildexpectedresult(2, 2) ], 'limit less than total' => [ 'dbquerylimit' => 3, 'totalcourses' => 9, 'limit' => 6, 'offset' => 0, 'expecteddbqueries' => 3, 'expectedresult' => $buildexpectedresult(6, 0) ], 'less results than limit' => [ 'dbquerylimit' => 4, 'totalcourses' => 9, 'limit' => 20, 'offset' => 0, 'expecteddbqueries' => 4, 'expectedresult' => $buildexpectedresult(9, 0) ], 'less results than limit exact divisible' => [ 'dbquerylimit' => 3, 'totalcourses' => 9, 'limit' => 20, 'offset' => 0, 'expecteddbqueries' => 5, 'expectedresult' => $buildexpectedresult(9, 0) ], 'less results than limit with offset' => [ 'dbquerylimit' => 3, 'totalcourses' => 9, 'limit' => 10, 'offset' => 5, 'expecteddbqueries' => 3, 'expectedresult' => $buildexpectedresult(4, 5) ], ]; } /** * Test the course_get_enrolled_courses_for_logged_in_user function. * * @dataProvider get_course_get_enrolled_courses_for_logged_in_user_test_cases() * @param int $dbquerylimit Number of records to load per DB request * @param int $totalcourses Number of courses to create * @param int $limit Maximum number of results to get. * @param int $offset Skip this number of results from the start of the result set. * @param int $expecteddbqueries The number of DB queries expected during the test. * @param array $expectedresult Expected test results. */ public function test_course_get_enrolled_courses_for_logged_in_user( $dbquerylimit, $totalcourses, $limit, $offset, $expecteddbqueries, $expectedresult ) { global $DB; $this->resetAfterTest(); $generator = $this->getDataGenerator(); $student = $generator->create_user(); for ($i = 0; $i < $totalcourses; $i++) { $shortname = "testcourse{$i}"; $course = $generator->create_course(['shortname' => $shortname]); $generator->enrol_user($student->id, $course->id, 'student'); } $this->setUser($student); $initialquerycount = $DB->perf_get_queries(); $courses = course_get_enrolled_courses_for_logged_in_user($limit, $offset, 'shortname ASC', 'shortname', $dbquerylimit); // Loop over the result set to force the lazy loading to kick in so that we can check the // number of DB queries. $actualresult = array_map(function($course) { return $course->shortname; }, iterator_to_array($courses, false)); sort($expectedresult); $this->assertEquals($expectedresult, $actualresult); $this->assertLessThanOrEqual($expecteddbqueries, $DB->perf_get_queries() - $initialquerycount); } /** * Test cases for the course_filter_courses_by_timeline_classification tests. */ public function get_course_filter_courses_by_timeline_classification_test_cases() { $now = time(); $day = 86400; $coursedata = [ [ 'shortname' => 'apast', 'startdate' => $now - ($day * 2), 'enddate' => $now - $day ], [ 'shortname' => 'bpast', 'startdate' => $now - ($day * 2), 'enddate' => $now - $day ], [ 'shortname' => 'cpast', 'startdate' => $now - ($day * 2), 'enddate' => $now - $day ], [ 'shortname' => 'dpast', 'startdate' => $now - ($day * 2), 'enddate' => $now - $day ], [ 'shortname' => 'epast', 'startdate' => $now - ($day * 2), 'enddate' => $now - $day ], [ 'shortname' => 'ainprogress', 'startdate' => $now - $day, 'enddate' => $now + $day ], [ 'shortname' => 'binprogress', 'startdate' => $now - $day, 'enddate' => $now + $day ], [ 'shortname' => 'cinprogress', 'startdate' => $now - $day, 'enddate' => $now + $day ], [ 'shortname' => 'dinprogress', 'startdate' => $now - $day, 'enddate' => $now + $day ], [ 'shortname' => 'einprogress', 'startdate' => $now - $day, 'enddate' => $now + $day ], [ 'shortname' => 'afuture', 'startdate' => $now + $day ], [ 'shortname' => 'bfuture', 'startdate' => $now + $day ], [ 'shortname' => 'cfuture', 'startdate' => $now + $day ], [ 'shortname' => 'dfuture', 'startdate' => $now + $day ], [ 'shortname' => 'efuture', 'startdate' => $now + $day ] ]; // Raw enrolled courses result set should be returned in this order: // afuture, ainprogress, apast, bfuture, binprogress, bpast, cfuture, cinprogress, cpast, // dfuture, dinprogress, dpast, efuture, einprogress, epast // // By classification the offset values for each record should be: // COURSE_TIMELINE_FUTURE // 0 (afuture), 3 (bfuture), 6 (cfuture), 9 (dfuture), 12 (efuture) // COURSE_TIMELINE_INPROGRESS // 1 (ainprogress), 4 (binprogress), 7 (cinprogress), 10 (dinprogress), 13 (einprogress) // COURSE_TIMELINE_PAST // 2 (apast), 5 (bpast), 8 (cpast), 11 (dpast), 14 (epast). return [ 'empty set' => [ 'coursedata' => [], 'classification' => COURSE_TIMELINE_FUTURE, 'limit' => 2, 'offset' => 0, 'expectedcourses' => [], 'expectedprocessedcount' => 0 ], // COURSE_TIMELINE_FUTURE. 'future not limit no offset' => [ 'coursedata' => $coursedata, 'classification' => COURSE_TIMELINE_FUTURE, 'limit' => 0, 'offset' => 0, 'expectedcourses' => ['afuture', 'bfuture', 'cfuture', 'dfuture', 'efuture'], 'expectedprocessedcount' => 15 ], 'future no offset' => [ 'coursedata' => $coursedata, 'classification' => COURSE_TIMELINE_FUTURE, 'limit' => 2, 'offset' => 0, 'expectedcourses' => ['afuture', 'bfuture'], 'expectedprocessedcount' => 4 ], 'future offset' => [ 'coursedata' => $coursedata, 'classification' => COURSE_TIMELINE_FUTURE, 'limit' => 2, 'offset' => 2, 'expectedcourses' => ['bfuture', 'cfuture'], 'expectedprocessedcount' => 5 ], 'future exact limit' => [ 'coursedata' => $coursedata, 'classification' => COURSE_TIMELINE_FUTURE, 'limit' => 5, 'offset' => 0, 'expectedcourses' => ['afuture', 'bfuture', 'cfuture', 'dfuture', 'efuture'], 'expectedprocessedcount' => 13 ], 'future limit less results' => [ 'coursedata' => $coursedata, 'classification' => COURSE_TIMELINE_FUTURE, 'limit' => 10, 'offset' => 0, 'expectedcourses' => ['afuture', 'bfuture', 'cfuture', 'dfuture', 'efuture'], 'expectedprocessedcount' => 15 ], 'future limit less results with offset' => [ 'coursedata' => $coursedata, 'classification' => COURSE_TIMELINE_FUTURE, 'limit' => 10, 'offset' => 5, 'expectedcourses' => ['cfuture', 'dfuture', 'efuture'], 'expectedprocessedcount' => 10 ], ]; } /** * Test the course_get_enrolled_courses_for_logged_in_user_from_search function. */ public function test_course_get_enrolled_courses_for_logged_in_user_from_search() { global $DB; // Set up. $this->resetAfterTest(); $generator = $this->getDataGenerator(); $student = $generator->create_user(); $cat1 = core_course_category::create(['name' => 'Cat1']); $cat2 = core_course_category::create(['name' => 'Cat2', 'parent' => $cat1->id]); $c1 = $this->getDataGenerator()->create_course(['category' => $cat1->id, 'fullname' => 'Test 3', 'summary' => 'Magic', 'idnumber' => 'ID3']); $c2 = $this->getDataGenerator()->create_course(['category' => $cat1->id, 'fullname' => 'Test 1', 'summary' => 'Magic']); $c3 = $this->getDataGenerator()->create_course(['category' => $cat1->id, 'fullname' => 'Математика', 'summary' => ' Test Magic']); $c4 = $this->getDataGenerator()->create_course(['category' => $cat1->id, 'fullname' => 'Test 4', 'summary' => 'Magic', 'idnumber' => 'ID4']); $c5 = $this->getDataGenerator()->create_course(['category' => $cat2->id, 'fullname' => 'Test 5', 'summary' => 'Magic']); $c6 = $this->getDataGenerator()->create_course(['category' => $cat2->id, 'fullname' => 'Дискретная Математика', 'summary' => 'Magic']); $c7 = $this->getDataGenerator()->create_course(['category' => $cat2->id, 'fullname' => 'Test 7', 'summary' => 'Magic']); $c8 = $this->getDataGenerator()->create_course(['category' => $cat2->id, 'fullname' => 'Test 8', 'summary' => 'Magic']); for ($i = 1; $i < 9; $i++) { $generator->enrol_user($student->id, ${"c$i"}->id, 'student'); } $this->setUser($student); $returnedcourses = course_get_enrolled_courses_for_logged_in_user_from_search( 0, 0, 'id ASC', null, COURSE_DB_QUERY_LIMIT, ['search' => 'test'], ['idonly' => true] ); $actualresult = array_map(function($course) { return $course->id; }, iterator_to_array($returnedcourses, false)); $this->assertEquals([$c1->id, $c2->id, $c3->id, $c4->id, $c5->id, $c7->id, $c8->id], $actualresult); // Test no courses matching the search. $returnedcourses = course_get_enrolled_courses_for_logged_in_user_from_search( 0, 0, 'id ASC', null, COURSE_DB_QUERY_LIMIT, ['search' => 'foobar'], ['idonly' => true] ); $actualresult = array_map(function($course) { return $course->id; }, iterator_to_array($returnedcourses, false)); $this->assertEquals([], $actualresult); // Test returning all courses that have a mutual summary. $returnedcourses = course_get_enrolled_courses_for_logged_in_user_from_search( 0, 0, 'id ASC', null, COURSE_DB_QUERY_LIMIT, ['search' => 'Magic'], ['idonly' => true] ); $actualresult = array_map(function($course) { return $course->id; }, iterator_to_array($returnedcourses, false)); $this->assertEquals([$c1->id, $c2->id, $c3->id, $c4->id, $c5->id, $c6->id, $c7->id, $c8->id], $actualresult); // Test returning a unique course. $returnedcourses = course_get_enrolled_courses_for_logged_in_user_from_search( 0, 0, 'id ASC', null, COURSE_DB_QUERY_LIMIT, ['search' => 'Дискретная'], ['idonly' => true] ); $actualresult = array_map(function($course) { return $course->id; }, iterator_to_array($returnedcourses, false)); $this->assertEquals([$c6->id], $actualresult); } /** * Test the course_filter_courses_by_timeline_classification function. * * @dataProvider get_course_filter_courses_by_timeline_classification_test_cases() * @param array $coursedata Course test data to create. * @param string $classification Timeline classification. * @param int $limit Maximum number of results to return. * @param int $offset Results to skip at the start of the result set. * @param string[] $expectedcourses Expected courses in results. * @param int $expectedprocessedcount Expected number of course records to be processed. */ public function test_course_filter_courses_by_timeline_classification( $coursedata, $classification, $limit, $offset, $expectedcourses, $expectedprocessedcount ) { $this->resetAfterTest(); $generator = $this->getDataGenerator(); $courses = array_map(function($coursedata) use ($generator) { return $generator->create_course($coursedata); }, $coursedata); $student = $generator->create_user(); foreach ($courses as $course) { $generator->enrol_user($student->id, $course->id, 'student'); } $this->setUser($student); $coursesgenerator = course_get_enrolled_courses_for_logged_in_user(0, $offset, 'shortname ASC', 'shortname'); list($result, $processedcount) = course_filter_courses_by_timeline_classification( $coursesgenerator, $classification, $limit ); $actual = array_map(function($course) { return $course->shortname; }, $result); $this->assertEquals($expectedcourses, $actual); $this->assertEquals($expectedprocessedcount, $processedcount); } /** * Test cases for the course_filter_courses_by_timeline_classification tests. */ public function get_course_filter_courses_by_customfield_test_cases() { global $CFG; require_once($CFG->dirroot.'/blocks/myoverview/lib.php'); $coursedata = [ [ 'shortname' => 'C1', 'customfield_checkboxfield' => 1, 'customfield_datefield' => strtotime('2001-02-01T12:00:00Z'), 'customfield_selectfield' => 1, 'customfield_textfield' => 'fish', ], [ 'shortname' => 'C2', 'customfield_checkboxfield' => 0, 'customfield_datefield' => strtotime('1980-08-05T13:00:00Z'), ], [ 'shortname' => 'C3', 'customfield_checkboxfield' => 0, 'customfield_datefield' => strtotime('2001-02-01T12:00:00Z'), 'customfield_selectfield' => 2, 'customfield_textfield' => 'dog', ], [ 'shortname' => 'C4', 'customfield_checkboxfield' => 1, 'customfield_selectfield' => 3, 'customfield_textfield' => 'cat', ], [ 'shortname' => 'C5', 'customfield_datefield' => strtotime('1980-08-06T13:00:00Z'), 'customfield_selectfield' => 2, 'customfield_textfield' => 'fish', ], ]; return [ 'empty set' => [ 'coursedata' => [], 'customfield' => 'checkboxfield', 'customfieldvalue' => 1, 'limit' => 10, 'offset' => 0, 'expectedcourses' => [], 'expectedprocessedcount' => 0 ], 'checkbox yes' => [ 'coursedata' => $coursedata, 'customfield' => 'checkboxfield', 'customfieldvalue' => 1, 'limit' => 10, 'offset' => 0, 'expectedcourses' => ['C1', 'C4'], 'expectedprocessedcount' => 5 ], 'checkbox no' => [ 'coursedata' => $coursedata, 'customfield' => 'checkboxfield', 'customfieldvalue' => BLOCK_MYOVERVIEW_CUSTOMFIELD_EMPTY, 'limit' => 10, 'offset' => 0, 'expectedcourses' => ['C2', 'C3', 'C5'], 'expectedprocessedcount' => 5 ], 'date 1 Feb 2001' => [ 'coursedata' => $coursedata, 'customfield' => 'datefield', 'customfieldvalue' => strtotime('2001-02-01T12:00:00Z'), 'limit' => 10, 'offset' => 0, 'expectedcourses' => ['C1', 'C3'], 'expectedprocessedcount' => 5 ], 'date 6 Aug 1980' => [ 'coursedata' => $coursedata, 'customfield' => 'datefield', 'customfieldvalue' => strtotime('1980-08-06T13:00:00Z'), 'limit' => 10, 'offset' => 0, 'expectedcourses' => ['C5'], 'expectedprocessedcount' => 5 ], 'date no date' => [ 'coursedata' => $coursedata, 'customfield' => 'datefield', 'customfieldvalue' => BLOCK_MYOVERVIEW_CUSTOMFIELD_EMPTY, 'limit' => 10, 'offset' => 0, 'expectedcourses' => ['C4'], 'expectedprocessedcount' => 5 ], 'select Option 1' => [ 'coursedata' => $coursedata, 'customfield' => 'selectfield', 'customfieldvalue' => 1, 'limit' => 10, 'offset' => 0, 'expectedcourses' => ['C1'], 'expectedprocessedcount' => 5 ], 'select Option 2' => [ 'coursedata' => $coursedata, 'customfield' => 'selectfield', 'customfieldvalue' => 2, 'limit' => 10, 'offset' => 0, 'expectedcourses' => ['C3', 'C5'], 'expectedprocessedcount' => 5 ], 'select no select' => [ 'coursedata' => $coursedata, 'customfield' => 'selectfield', 'customfieldvalue' => BLOCK_MYOVERVIEW_CUSTOMFIELD_EMPTY, 'limit' => 10, 'offset' => 0, 'expectedcourses' => ['C2'], 'expectedprocessedcount' => 5 ], 'text fish' => [ 'coursedata' => $coursedata, 'customfield' => 'textfield', 'customfieldvalue' => 'fish', 'limit' => 10, 'offset' => 0, 'expectedcourses' => ['C1', 'C5'], 'expectedprocessedcount' => 5 ], 'text dog' => [ 'coursedata' => $coursedata, 'customfield' => 'textfield', 'customfieldvalue' => 'dog', 'limit' => 10, 'offset' => 0, 'expectedcourses' => ['C3'], 'expectedprocessedcount' => 5 ], 'text no text' => [ 'coursedata' => $coursedata, 'customfield' => 'textfield', 'customfieldvalue' => BLOCK_MYOVERVIEW_CUSTOMFIELD_EMPTY, 'limit' => 10, 'offset' => 0, 'expectedcourses' => ['C2'], 'expectedprocessedcount' => 5 ], 'checkbox limit no' => [ 'coursedata' => $coursedata, 'customfield' => 'checkboxfield', 'customfieldvalue' => BLOCK_MYOVERVIEW_CUSTOMFIELD_EMPTY, 'limit' => 2, 'offset' => 0, 'expectedcourses' => ['C2', 'C3'], 'expectedprocessedcount' => 3 ], 'checkbox limit offset no' => [ 'coursedata' => $coursedata, 'customfield' => 'checkboxfield', 'customfieldvalue' => BLOCK_MYOVERVIEW_CUSTOMFIELD_EMPTY, 'limit' => 2, 'offset' => 3, 'expectedcourses' => ['C5'], 'expectedprocessedcount' => 2 ], ]; } /** * Test the course_filter_courses_by_customfield function. * * @dataProvider get_course_filter_courses_by_customfield_test_cases() * @param array $coursedata Course test data to create. * @param string $customfield Shortname of the customfield. * @param string $customfieldvalue the value to filter by. * @param int $limit Maximum number of results to return. * @param int $offset Results to skip at the start of the result set. * @param string[] $expectedcourses Expected courses in results. * @param int $expectedprocessedcount Expected number of course records to be processed. */ public function test_course_filter_courses_by_customfield( $coursedata, $customfield, $customfieldvalue, $limit, $offset, $expectedcourses, $expectedprocessedcount ) { $this->resetAfterTest(); $generator = $this->getDataGenerator(); // Create the custom fields. $generator->create_custom_field_category([ 'name' => 'Course fields', 'component' => 'core_course', 'area' => 'course', 'itemid' => 0, ]); $generator->create_custom_field([ 'name' => 'Checkbox field', 'category' => 'Course fields', 'type' => 'checkbox', 'shortname' => 'checkboxfield', ]); $generator->create_custom_field([ 'name' => 'Date field', 'category' => 'Course fields', 'type' => 'date', 'shortname' => 'datefield', 'configdata' => '{"mindate":0, "maxdate":0}', ]); $generator->create_custom_field([ 'name' => 'Select field', 'category' => 'Course fields', 'type' => 'select', 'shortname' => 'selectfield', 'configdata' => '{"options":"Option 1\nOption 2\nOption 3\nOption 4"}', ]); $generator->create_custom_field([ 'name' => 'Text field', 'category' => 'Course fields', 'type' => 'text', 'shortname' => 'textfield', ]); $courses = array_map(function($coursedata) use ($generator) { return $generator->create_course($coursedata); }, $coursedata); $student = $generator->create_user(); foreach ($courses as $course) { $generator->enrol_user($student->id, $course->id, 'student'); } $this->setUser($student); $coursesgenerator = course_get_enrolled_courses_for_logged_in_user(0, $offset, 'shortname ASC', 'shortname'); list($result, $processedcount) = course_filter_courses_by_customfield( $coursesgenerator, $customfield, $customfieldvalue, $limit ); $actual = array_map(function($course) { return $course->shortname; }, $result); $this->assertEquals($expectedcourses, $actual); $this->assertEquals($expectedprocessedcount, $processedcount); } /** * Test cases for the course_filter_courses_by_timeline_classification w/ hidden courses tests. */ public function get_course_filter_courses_by_timeline_classification_hidden_courses_test_cases() { $now = time(); $day = 86400; $coursedata = [ [ 'shortname' => 'apast', 'startdate' => $now - ($day * 2), 'enddate' => $now - $day ], [ 'shortname' => 'bpast', 'startdate' => $now - ($day * 2), 'enddate' => $now - $day ], [ 'shortname' => 'cpast', 'startdate' => $now - ($day * 2), 'enddate' => $now - $day ], [ 'shortname' => 'dpast', 'startdate' => $now - ($day * 2), 'enddate' => $now - $day ], [ 'shortname' => 'epast', 'startdate' => $now - ($day * 2), 'enddate' => $now - $day ], [ 'shortname' => 'ainprogress', 'startdate' => $now - $day, 'enddate' => $now + $day ], [ 'shortname' => 'binprogress', 'startdate' => $now - $day, 'enddate' => $now + $day ], [ 'shortname' => 'cinprogress', 'startdate' => $now - $day, 'enddate' => $now + $day ], [ 'shortname' => 'dinprogress', 'startdate' => $now - $day, 'enddate' => $now + $day ], [ 'shortname' => 'einprogress', 'startdate' => $now - $day, 'enddate' => $now + $day ], [ 'shortname' => 'afuture', 'startdate' => $now + $day ], [ 'shortname' => 'bfuture', 'startdate' => $now + $day ], [ 'shortname' => 'cfuture', 'startdate' => $now + $day ], [ 'shortname' => 'dfuture', 'startdate' => $now + $day ], [ 'shortname' => 'efuture', 'startdate' => $now + $day ] ]; // Raw enrolled courses result set should be returned in this order: // afuture, ainprogress, apast, bfuture, binprogress, bpast, cfuture, cinprogress, cpast, // dfuture, dinprogress, dpast, efuture, einprogress, epast // // By classification the offset values for each record should be: // COURSE_TIMELINE_FUTURE // 0 (afuture), 3 (bfuture), 6 (cfuture), 9 (dfuture), 12 (efuture) // COURSE_TIMELINE_INPROGRESS // 1 (ainprogress), 4 (binprogress), 7 (cinprogress), 10 (dinprogress), 13 (einprogress) // COURSE_TIMELINE_PAST // 2 (apast), 5 (bpast), 8 (cpast), 11 (dpast), 14 (epast). return [ 'empty set' => [ 'coursedata' => [], 'classification' => COURSE_TIMELINE_FUTURE, 'limit' => 2, 'offset' => 0, 'expectedcourses' => [], 'expectedprocessedcount' => 0, 'hiddencourse' => '' ], // COURSE_TIMELINE_FUTURE. 'future not limit no offset' => [ 'coursedata' => $coursedata, 'classification' => COURSE_TIMELINE_FUTURE, 'limit' => 0, 'offset' => 0, 'expectedcourses' => ['afuture', 'cfuture', 'dfuture', 'efuture'], 'expectedprocessedcount' => 15, 'hiddencourse' => 'bfuture' ], 'future no offset' => [ 'coursedata' => $coursedata, 'classification' => COURSE_TIMELINE_FUTURE, 'limit' => 2, 'offset' => 0, 'expectedcourses' => ['afuture', 'cfuture'], 'expectedprocessedcount' => 7, 'hiddencourse' => 'bfuture' ], 'future offset' => [ 'coursedata' => $coursedata, 'classification' => COURSE_TIMELINE_FUTURE, 'limit' => 2, 'offset' => 2, 'expectedcourses' => ['bfuture', 'dfuture'], 'expectedprocessedcount' => 8, 'hiddencourse' => 'cfuture' ], 'future exact limit' => [ 'coursedata' => $coursedata, 'classification' => COURSE_TIMELINE_FUTURE, 'limit' => 5, 'offset' => 0, 'expectedcourses' => ['afuture', 'cfuture', 'dfuture', 'efuture'], 'expectedprocessedcount' => 15, 'hiddencourse' => 'bfuture' ], 'future limit less results' => [ 'coursedata' => $coursedata, 'classification' => COURSE_TIMELINE_FUTURE, 'limit' => 10, 'offset' => 0, 'expectedcourses' => ['afuture', 'cfuture', 'dfuture', 'efuture'], 'expectedprocessedcount' => 15, 'hiddencourse' => 'bfuture' ], 'future limit less results with offset' => [ 'coursedata' => $coursedata, 'classification' => COURSE_TIMELINE_FUTURE, 'limit' => 10, 'offset' => 5, 'expectedcourses' => ['cfuture', 'efuture'], 'expectedprocessedcount' => 10, 'hiddencourse' => 'dfuture' ], ]; } /** * Test the course_filter_courses_by_timeline_classification function hidden courses. * * @dataProvider get_course_filter_courses_by_timeline_classification_hidden_courses_test_cases() * @param array $coursedata Course test data to create. * @param string $classification Timeline classification. * @param int $limit Maximum number of results to return. * @param int $offset Results to skip at the start of the result set. * @param string[] $expectedcourses Expected courses in results. * @param int $expectedprocessedcount Expected number of course records to be processed. * @param int $hiddencourse The course to hide as part of this process */ public function test_course_filter_courses_by_timeline_classification_with_hidden_courses( $coursedata, $classification, $limit, $offset, $expectedcourses, $expectedprocessedcount, $hiddencourse ) { $this->resetAfterTest(); $generator = $this->getDataGenerator(); $student = $generator->create_user(); $this->setUser($student); $courses = array_map(function($coursedata) use ($generator, $hiddencourse) { $course = $generator->create_course($coursedata); if ($course->shortname == $hiddencourse) { set_user_preference('block_myoverview_hidden_course_' . $course->id, true); } return $course; }, $coursedata); foreach ($courses as $course) { $generator->enrol_user($student->id, $course->id, 'student'); } $coursesgenerator = course_get_enrolled_courses_for_logged_in_user(0, $offset, 'shortname ASC', 'shortname'); list($result, $processedcount) = course_filter_courses_by_timeline_classification( $coursesgenerator, $classification, $limit ); $actual = array_map(function($course) { return $course->shortname; }, $result); $this->assertEquals($expectedcourses, $actual); $this->assertEquals($expectedprocessedcount, $processedcount); } /** * Testing core_course_core_calendar_get_valid_event_timestart_range when the course has no end date. */ public function test_core_course_core_calendar_get_valid_event_timestart_range_no_enddate() { global $CFG; require_once($CFG->dirroot . "/calendar/lib.php"); $this->resetAfterTest(true); $this->setAdminUser(); $generator = $this->getDataGenerator(); $now = time(); $course = $generator->create_course(['startdate' => $now - 86400]); // Create a course event. $event = new \calendar_event([ 'name' => 'Test course event', 'eventtype' => 'course', 'courseid' => $course->id, ]); list ($min, $max) = core_course_core_calendar_get_valid_event_timestart_range($event, $course); $this->assertEquals($course->startdate, $min[0]); $this->assertNull($max); } /** * Testing core_course_core_calendar_get_valid_event_timestart_range when the course has end date. */ public function test_core_course_core_calendar_get_valid_event_timestart_range_with_enddate() { global $CFG; require_once($CFG->dirroot . "/calendar/lib.php"); $this->resetAfterTest(true); $this->setAdminUser(); $generator = $this->getDataGenerator(); $now = time(); $course = $generator->create_course(['startdate' => $now - 86400, 'enddate' => $now + 86400]); // Create a course event. $event = new \calendar_event([ 'name' => 'Test course event', 'eventtype' => 'course', 'courseid' => $course->id, ]); list ($min, $max) = core_course_core_calendar_get_valid_event_timestart_range($event, $course); $this->assertEquals($course->startdate, $min[0]); $this->assertNull($max); } /** * Test the course_get_recent_courses function. */ public function test_course_get_recent_courses() { global $DB; $this->resetAfterTest(); $generator = $this->getDataGenerator(); $courses = array(); for ($i = 1; $i < 4; $i++) { $courses[] = $generator->create_course(); }; $student = $generator->create_user(); foreach ($courses as $course) { $generator->enrol_user($student->id, $course->id, 'student'); } $this->setUser($student); $result = course_get_recent_courses($student->id); // No course accessed. $this->assertCount(0, $result); $time = time(); foreach ($courses as $course) { $context = context_course::instance($course->id); course_view($context); $DB->set_field('user_lastaccess', 'timeaccess', $time, [ 'userid' => $student->id, 'courseid' => $course->id, ]); $time++; } // Every course accessed. $result = course_get_recent_courses($student->id); $this->assertCount(3, $result); // Every course accessed, result limited to 2 courses. $result = course_get_recent_courses($student->id, 2); $this->assertCount(2, $result); // Every course accessed, with limit and offset should return the first course. $result = course_get_recent_courses($student->id, 3, 2); $this->assertCount(1, $result); $this->assertArrayHasKey($courses[0]->id, $result); // Every course accessed, order by shortname DESC. The last create course ($course[2]) should have the greater shortname. $result = course_get_recent_courses($student->id, 0, 0, 'shortname DESC'); $this->assertCount(3, $result); $this->assertEquals($courses[2]->id, array_values($result)[0]->id); $this->assertEquals($courses[1]->id, array_values($result)[1]->id); $this->assertEquals($courses[0]->id, array_values($result)[2]->id); // Every course accessed, order by shortname ASC. $result = course_get_recent_courses($student->id, 0, 0, 'shortname ASC'); $this->assertCount(3, $result); $this->assertEquals($courses[0]->id, array_values($result)[0]->id); $this->assertEquals($courses[1]->id, array_values($result)[1]->id); $this->assertEquals($courses[2]->id, array_values($result)[2]->id); $guestcourse = $generator->create_course( (object)array('shortname' => 'guestcourse', 'enrol_guest_status_0' => ENROL_INSTANCE_ENABLED, 'enrol_guest_password_0' => '')); $context = context_course::instance($guestcourse->id); course_view($context); // Every course accessed, even the not enrolled one. $result = course_get_recent_courses($student->id); $this->assertCount(4, $result); // Suspended student. $this->getDataGenerator()->enrol_user($student->id, $courses[0]->id, 'student', 'manual', 0, 0, ENROL_USER_SUSPENDED); // The course with suspended enrolment is not returned by the function. $result = course_get_recent_courses($student->id); $this->assertCount(3, $result); $this->assertArrayNotHasKey($courses[0]->id, $result); } /** * Test the validation of the sort value in course_get_recent_courses(). * * @dataProvider course_get_recent_courses_sort_validation_provider * @param string $sort The sort value * @param string $expectedexceptionmsg The expected exception message */ public function test_course_get_recent_courses_sort_validation(string $sort, string $expectedexceptionmsg) { $this->resetAfterTest(); $user = $this->getDataGenerator()->create_user(); if (!empty($expectedexceptionmsg)) { $this->expectException('invalid_parameter_exception'); $this->expectExceptionMessage($expectedexceptionmsg); } course_get_recent_courses($user->id, 0, 0, $sort); } /** * Data provider for test_course_get_recent_courses_sort_validation(). * * @return array */ function course_get_recent_courses_sort_validation_provider() { return [ 'Invalid sort format (SQL injection attempt)' => [ 'shortname DESC LIMIT 1--', 'Invalid structure of the sort parameter, allowed structure: fieldname [ASC|DESC].', ], 'Sort uses \'sort by\' field that does not exist' => [ 'shortname DESC, xyz ASC', 'Invalid field in the sort parameter, allowed fields: id, idnumber, summary, summaryformat, ' . 'startdate, enddate, category, shortname, fullname, timeaccess, component, visible, ' . 'showactivitydates, showcompletionconditions.', ], 'Sort uses invalid value for the sorting direction' => [ 'shortname xyz, lastaccess', 'Invalid sort direction in the sort parameter, allowed values: asc, desc.', ], 'Valid sort format' => [ 'shortname asc, timeaccess', '' ] ]; } /** * Test the course_get_recent_courses function. */ public function test_course_get_recent_courses_with_guest() { global $DB; $this->resetAfterTest(true); $student = $this->getDataGenerator()->create_user(); // Course 1 with guest access and no direct enrolment. $course1 = $this->getDataGenerator()->create_course(); $context1 = context_course::instance($course1->id); $record = $DB->get_record('enrol', ['courseid' => $course1->id, 'enrol' => 'guest']); enrol_get_plugin('guest')->update_status($record, ENROL_INSTANCE_ENABLED); // Course 2 where student is enrolled with two enrolment methods. $course2 = $this->getDataGenerator()->create_course(); $context2 = context_course::instance($course2->id); $record = $DB->get_record('enrol', ['courseid' => $course2->id, 'enrol' => 'self']); enrol_get_plugin('guest')->update_status($record, ENROL_INSTANCE_ENABLED); $this->getDataGenerator()->enrol_user($student->id, $course2->id, 'student', 'manual', 0, 0, ENROL_USER_ACTIVE); $this->getDataGenerator()->enrol_user($student->id, $course2->id, 'student', 'self', 0, 0, ENROL_USER_ACTIVE); // Course 3. $course3 = $this->getDataGenerator()->create_course(); $context3 = context_course::instance($course3->id); // Student visits first two courses, course_get_recent_courses returns two courses. $this->setUser($student); course_view($context1); course_view($context2); $result = course_get_recent_courses($student->id); $this->assertEqualsCanonicalizing([$course2->id, $course1->id], array_column($result, 'id')); // Admin visits all three courses. Only the one with guest access is returned. $this->setAdminUser(); course_view($context1); course_view($context2); course_view($context3); $result = course_get_recent_courses(get_admin()->id); $this->assertEqualsCanonicalizing([$course1->id], array_column($result, 'id')); } /** * Test cases for the course_get_course_dates_for_user_ids tests. */ public function get_course_get_course_dates_for_user_ids_test_cases() { $now = time(); $pastcoursestart = $now - 100; $futurecoursestart = $now + 100; return [ 'future course start fixed no users enrolled' => [ 'relativedatemode' => false, 'coursestart' => $futurecoursestart, 'usercount' => 2, 'enrolmentmethods' => [ ['manual', ENROL_INSTANCE_ENABLED], ['self', ENROL_INSTANCE_ENABLED] ], 'enrolled' => [[], []], 'expected' => [ [ 'start' => $futurecoursestart, 'startoffset' => 0 ], [ 'start' => $futurecoursestart, 'startoffset' => 0 ] ] ], 'future course start fixed 1 users enrolled future' => [ 'relativedatemode' => false, 'coursestart' => $futurecoursestart, 'usercount' => 2, 'enrolmentmethods' => [ ['manual', ENROL_INSTANCE_ENABLED], ['self', ENROL_INSTANCE_ENABLED] ], 'enrolled' => [ // User 1. ['manual' => [$futurecoursestart + 10, ENROL_USER_ACTIVE]], // User 2. [] ], 'expected' => [ [ 'start' => $futurecoursestart, 'startoffset' => 0 ], [ 'start' => $futurecoursestart, 'startoffset' => 0 ] ] ], 'future course start fixed 1 users enrolled past' => [ 'relativedatemode' => false, 'coursestart' => $futurecoursestart, 'usercount' => 2, 'enrolmentmethods' => [ ['manual', ENROL_INSTANCE_ENABLED], ['self', ENROL_INSTANCE_ENABLED] ], 'enrolled' => [ // User 1. ['manual' => [$futurecoursestart - 10, ENROL_USER_ACTIVE]], // User 2. [] ], 'expected' => [ [ 'start' => $futurecoursestart, 'startoffset' => 0 ], [ 'start' => $futurecoursestart, 'startoffset' => 0 ] ] ], 'future course start fixed 2 users enrolled future' => [ 'relativedatemode' => false, 'coursestart' => $futurecoursestart, 'usercount' => 2, 'enrolmentmethods' => [ ['manual', ENROL_INSTANCE_ENABLED], ['self', ENROL_INSTANCE_ENABLED] ], 'enrolled' => [ // User 1. ['manual' => [$futurecoursestart + 10, ENROL_USER_ACTIVE]], // User 2. ['manual' => [$futurecoursestart + 20, ENROL_USER_ACTIVE]] ], 'expected' => [ [ 'start' => $futurecoursestart, 'startoffset' => 0 ], [ 'start' => $futurecoursestart, 'startoffset' => 0 ] ] ], 'future course start fixed 2 users enrolled past' => [ 'relativedatemode' => false, 'coursestart' => $futurecoursestart, 'usercount' => 2, 'enrolmentmethods' => [ ['manual', ENROL_INSTANCE_ENABLED], ['self', ENROL_INSTANCE_ENABLED] ], 'enrolled' => [ // User 1. ['manual' => [$futurecoursestart - 10, ENROL_USER_ACTIVE]], // User 2. ['manual' => [$futurecoursestart - 20, ENROL_USER_ACTIVE]] ], 'expected' => [ [ 'start' => $futurecoursestart, 'startoffset' => 0 ], [ 'start' => $futurecoursestart, 'startoffset' => 0 ] ] ], 'future course start fixed 2 users enrolled mixed' => [ 'relativedatemode' => false, 'coursestart' => $futurecoursestart, 'usercount' => 2, 'enrolmentmethods' => [ ['manual', ENROL_INSTANCE_ENABLED], ['self', ENROL_INSTANCE_ENABLED] ], 'enrolled' => [ // User 1. ['manual' => [$futurecoursestart + 10, ENROL_USER_ACTIVE]], // User 2. ['manual' => [$futurecoursestart - 20, ENROL_USER_ACTIVE]] ], 'expected' => [ [ 'start' => $futurecoursestart, 'startoffset' => 0 ], [ 'start' => $futurecoursestart, 'startoffset' => 0 ] ] ], 'future course start fixed 2 users enrolled 2 methods' => [ 'relativedatemode' => false, 'coursestart' => $futurecoursestart, 'usercount' => 2, 'enrolmentmethods' => [ ['manual', ENROL_INSTANCE_ENABLED], ['self', ENROL_INSTANCE_ENABLED] ], 'enrolled' => [ // User 1. [ 'manual' => [$futurecoursestart + 10, ENROL_USER_ACTIVE], 'self' => [$futurecoursestart + 20, ENROL_USER_ACTIVE] ], // User 2. [ 'manual' => [$futurecoursestart + 20, ENROL_USER_ACTIVE], 'self' => [$futurecoursestart + 10, ENROL_USER_ACTIVE] ] ], 'expected' => [ [ 'start' => $futurecoursestart, 'startoffset' => 0 ], [ 'start' => $futurecoursestart, 'startoffset' => 0 ] ] ], 'future course start fixed 2 users enrolled 2 methods 1 disabled' => [ 'relativedatemode' => false, 'coursestart' => $futurecoursestart, 'usercount' => 2, 'enrolmentmethods' => [ ['manual', ENROL_INSTANCE_DISABLED], ['self', ENROL_INSTANCE_ENABLED] ], 'enrolled' => [ // User 1. [ 'manual' => [$futurecoursestart + 10, ENROL_USER_ACTIVE], 'self' => [$futurecoursestart + 20, ENROL_USER_ACTIVE] ], // User 2. [ 'manual' => [$futurecoursestart + 20, ENROL_USER_ACTIVE], 'self' => [$futurecoursestart + 10, ENROL_USER_ACTIVE] ] ], 'expected' => [ [ 'start' => $futurecoursestart, 'startoffset' => 0 ], [ 'start' => $futurecoursestart, 'startoffset' => 0 ] ] ], 'future course start fixed 2 users enrolled 2 methods 2 disabled' => [ 'relativedatemode' => false, 'coursestart' => $futurecoursestart, 'usercount' => 2, 'enrolmentmethods' => [ ['manual', ENROL_INSTANCE_DISABLED], ['self', ENROL_INSTANCE_DISABLED] ], 'enrolled' => [ // User 1. [ 'manual' => [$futurecoursestart + 10, ENROL_USER_ACTIVE], 'self' => [$futurecoursestart + 20, ENROL_USER_ACTIVE] ], // User 2. [ 'manual' => [$futurecoursestart + 20, ENROL_USER_ACTIVE], 'self' => [$futurecoursestart + 10, ENROL_USER_ACTIVE] ] ], 'expected' => [ [ 'start' => $futurecoursestart, 'startoffset' => 0 ], [ 'start' => $futurecoursestart, 'startoffset' => 0 ] ] ], 'future course start fixed 2 users enrolled 2 methods 0 disabled 1 user suspended' => [ 'relativedatemode' => false, 'coursestart' => $futurecoursestart, 'usercount' => 2, 'enrolmentmethods' => [ ['manual', ENROL_INSTANCE_ENABLED], ['self', ENROL_INSTANCE_ENABLED] ], 'enrolled' => [ // User 1. [ 'manual' => [$futurecoursestart + 10, ENROL_USER_SUSPENDED], 'self' => [$futurecoursestart + 20, ENROL_USER_ACTIVE] ], // User 2. [ 'manual' => [$futurecoursestart + 20, ENROL_USER_SUSPENDED], 'self' => [$futurecoursestart + 10, ENROL_USER_ACTIVE] ] ], 'expected' => [ [ 'start' => $futurecoursestart, 'startoffset' => 0 ], [ 'start' => $futurecoursestart, 'startoffset' => 0 ] ] ], 'future course start fixed 2 users enrolled 2 methods 0 disabled 2 user suspended' => [ 'relativedatemode' => false, 'coursestart' => $futurecoursestart, 'usercount' => 2, 'enrolmentmethods' => [ ['manual', ENROL_INSTANCE_ENABLED], ['self', ENROL_INSTANCE_ENABLED] ], 'enrolled' => [ // User 1. [ 'manual' => [$futurecoursestart + 10, ENROL_USER_SUSPENDED], 'self' => [$futurecoursestart + 20, ENROL_USER_SUSPENDED] ], // User 2. [ 'manual' => [$futurecoursestart + 20, ENROL_USER_SUSPENDED], 'self' => [$futurecoursestart + 10, ENROL_USER_SUSPENDED] ] ], 'expected' => [ [ 'start' => $futurecoursestart, 'startoffset' => 0 ], [ 'start' => $futurecoursestart, 'startoffset' => 0 ] ] ], 'future course start relative no users enrolled' => [ 'relativedatemode' => true, 'coursestart' => $futurecoursestart, 'usercount' => 2, 'enrolmentmethods' => [ ['manual', ENROL_INSTANCE_ENABLED], ['self', ENROL_INSTANCE_ENABLED] ], 'enrolled' => [[], []], 'expected' => [ [ 'start' => $futurecoursestart, 'startoffset' => 0 ], [ 'start' => $futurecoursestart, 'startoffset' => 0 ] ] ], 'future course start relative 1 users enrolled future' => [ 'relativedatemode' => true, 'coursestart' => $futurecoursestart, 'usercount' => 2, 'enrolmentmethods' => [ ['manual', ENROL_INSTANCE_ENABLED], ['self', ENROL_INSTANCE_ENABLED] ], 'enrolled' => [ // User 1. ['manual' => [$futurecoursestart + 10, ENROL_USER_ACTIVE]], // User 2. [] ], 'expected' => [ [ 'start' => $futurecoursestart + 10, 'startoffset' => 10 ], [ 'start' => $futurecoursestart, 'startoffset' => 0 ] ] ], 'future course start relative 1 users enrolled past' => [ 'relativedatemode' => true, 'coursestart' => $futurecoursestart, 'usercount' => 2, 'enrolmentmethods' => [ ['manual', ENROL_INSTANCE_ENABLED], ['self', ENROL_INSTANCE_ENABLED] ], 'enrolled' => [ // User 1. ['manual' => [$futurecoursestart - 10, ENROL_USER_ACTIVE]], // User 2. [] ], 'expected' => [ [ 'start' => $futurecoursestart, 'startoffset' => 0 ], [ 'start' => $futurecoursestart, 'startoffset' => 0 ] ] ], 'future course start relative 2 users enrolled future' => [ 'relativedatemode' => true, 'coursestart' => $futurecoursestart, 'usercount' => 2, 'enrolmentmethods' => [ ['manual', ENROL_INSTANCE_ENABLED], ['self', ENROL_INSTANCE_ENABLED] ], 'enrolled' => [ // User 1. ['manual' => [$futurecoursestart + 10, ENROL_USER_ACTIVE]], // User 2. ['manual' => [$futurecoursestart + 20, ENROL_USER_ACTIVE]] ], 'expected' => [ [ 'start' => $futurecoursestart + 10, 'startoffset' => 10 ], [ 'start' => $futurecoursestart + 20, 'startoffset' => 20 ] ] ], 'future course start relative 2 users enrolled past' => [ 'relativedatemode' => true, 'coursestart' => $futurecoursestart, 'usercount' => 2, 'enrolmentmethods' => [ ['manual', ENROL_INSTANCE_ENABLED], ['self', ENROL_INSTANCE_ENABLED] ], 'enrolled' => [ // User 1. ['manual' => [$futurecoursestart - 10, ENROL_USER_ACTIVE]], // User 2. ['manual' => [$futurecoursestart - 20, ENROL_USER_ACTIVE]] ], 'expected' => [ [ 'start' => $futurecoursestart, 'startoffset' => 0 ], [ 'start' => $futurecoursestart, 'startoffset' => 0 ] ] ], 'future course start relative 2 users enrolled mixed' => [ 'relativedatemode' => true, 'coursestart' => $futurecoursestart, 'usercount' => 2, 'enrolmentmethods' => [ ['manual', ENROL_INSTANCE_ENABLED], ['self', ENROL_INSTANCE_ENABLED] ], 'enrolled' => [ // User 1. ['manual' => [$futurecoursestart + 10, ENROL_USER_ACTIVE]], // User 2. ['manual' => [$futurecoursestart - 20, ENROL_USER_ACTIVE]] ], 'expected' => [ [ 'start' => $futurecoursestart + 10, 'startoffset' => 10 ], [ 'start' => $futurecoursestart, 'startoffset' => 0 ] ] ], 'future course start relative 2 users enrolled 2 methods' => [ 'relativedatemode' => true, 'coursestart' => $futurecoursestart, 'usercount' => 2, 'enrolmentmethods' => [ ['manual', ENROL_INSTANCE_ENABLED], ['self', ENROL_INSTANCE_ENABLED] ], 'enrolled' => [ // User 1. [ 'manual' => [$futurecoursestart + 10, ENROL_USER_ACTIVE], 'self' => [$futurecoursestart + 20, ENROL_USER_ACTIVE] ], // User 2. [ 'manual' => [$futurecoursestart + 20, ENROL_USER_ACTIVE], 'self' => [$futurecoursestart + 10, ENROL_USER_ACTIVE] ] ], 'expected' => [ [ 'start' => $futurecoursestart + 10, 'startoffset' => 10 ], [ 'start' => $futurecoursestart + 10, 'startoffset' => 10 ] ] ], 'future course start relative 2 users enrolled 2 methods 1 disabled' => [ 'relativedatemode' => true, 'coursestart' => $futurecoursestart, 'usercount' => 2, 'enrolmentmethods' => [ ['manual', ENROL_INSTANCE_DISABLED], ['self', ENROL_INSTANCE_ENABLED] ], 'enrolled' => [ // User 1. [ 'manual' => [$futurecoursestart + 10, ENROL_USER_ACTIVE], 'self' => [$futurecoursestart + 20, ENROL_USER_ACTIVE] ], // User 2. [ 'manual' => [$futurecoursestart + 20, ENROL_USER_ACTIVE], 'self' => [$futurecoursestart + 10, ENROL_USER_ACTIVE] ] ], 'expected' => [ [ 'start' => $futurecoursestart + 20, 'startoffset' => 20 ], [ 'start' => $futurecoursestart + 10, 'startoffset' => 10 ] ] ], 'future course start relative 2 users enrolled 2 methods 2 disabled' => [ 'relativedatemode' => true, 'coursestart' => $futurecoursestart, 'usercount' => 2, 'enrolmentmethods' => [ ['manual', ENROL_INSTANCE_DISABLED], ['self', ENROL_INSTANCE_DISABLED] ], 'enrolled' => [ // User 1. [ 'manual' => [$futurecoursestart + 10, ENROL_USER_ACTIVE], 'self' => [$futurecoursestart + 20, ENROL_USER_ACTIVE] ], // User 2. [ 'manual' => [$futurecoursestart + 20, ENROL_USER_ACTIVE], 'self' => [$futurecoursestart + 10, ENROL_USER_ACTIVE] ] ], 'expected' => [ [ 'start' => $futurecoursestart, 'startoffset' => 0 ], [ 'start' => $futurecoursestart, 'startoffset' => 0 ] ] ], 'future course start relative 2 users enrolled 2 methods 0 disabled 1 user suspended' => [ 'relativedatemode' => true, 'coursestart' => $futurecoursestart, 'usercount' => 2, 'enrolmentmethods' => [ ['manual', ENROL_INSTANCE_ENABLED], ['self', ENROL_INSTANCE_ENABLED] ], 'enrolled' => [ // User 1. [ 'manual' => [$futurecoursestart + 10, ENROL_USER_SUSPENDED], 'self' => [$futurecoursestart + 20, ENROL_USER_ACTIVE] ], // User 2. [ 'manual' => [$futurecoursestart + 20, ENROL_USER_SUSPENDED], 'self' => [$futurecoursestart + 10, ENROL_USER_ACTIVE] ] ], 'expected' => [ [ 'start' => $futurecoursestart + 20, 'startoffset' => 20 ], [ 'start' => $futurecoursestart + 10, 'startoffset' => 10 ] ] ], 'future course start relative 2 users enrolled 2 methods 0 disabled 2 user suspended' => [ 'relativedatemode' => true, 'coursestart' => $futurecoursestart, 'usercount' => 2, 'enrolmentmethods' => [ ['manual', ENROL_INSTANCE_ENABLED], ['self', ENROL_INSTANCE_ENABLED] ], 'enrolled' => [ // User 1. [ 'manual' => [$futurecoursestart + 10, ENROL_USER_SUSPENDED], 'self' => [$futurecoursestart + 20, ENROL_USER_SUSPENDED] ], // User 2. [ 'manual' => [$futurecoursestart + 20, ENROL_USER_SUSPENDED], 'self' => [$futurecoursestart + 10, ENROL_USER_SUSPENDED] ] ], 'expected' => [ [ 'start' => $futurecoursestart, 'startoffset' => 0 ], [ 'start' => $futurecoursestart, 'startoffset' => 0 ] ] ], // Course start date in the past. 'past course start fixed no users enrolled' => [ 'relativedatemode' => false, 'coursestart' => $pastcoursestart, 'usercount' => 2, 'enrolmentmethods' => [ ['manual', ENROL_INSTANCE_ENABLED], ['self', ENROL_INSTANCE_ENABLED] ], 'enrolled' => [[], []], 'expected' => [ [ 'start' => $pastcoursestart, 'startoffset' => 0 ], [ 'start' => $pastcoursestart, 'startoffset' => 0 ] ] ], 'past course start fixed 1 users enrolled future' => [ 'relativedatemode' => false, 'coursestart' => $pastcoursestart, 'usercount' => 2, 'enrolmentmethods' => [ ['manual', ENROL_INSTANCE_ENABLED], ['self', ENROL_INSTANCE_ENABLED] ], 'enrolled' => [ // User 1. ['manual' => [$pastcoursestart + 10, ENROL_USER_ACTIVE]], // User 2. [] ], 'expected' => [ [ 'start' => $pastcoursestart, 'startoffset' => 0 ], [ 'start' => $pastcoursestart, 'startoffset' => 0 ] ] ], 'past course start fixed 1 users enrolled past' => [ 'relativedatemode' => false, 'coursestart' => $pastcoursestart, 'usercount' => 2, 'enrolmentmethods' => [ ['manual', ENROL_INSTANCE_ENABLED], ['self', ENROL_INSTANCE_ENABLED] ], 'enrolled' => [ // User 1. ['manual' => [$pastcoursestart - 10, ENROL_USER_ACTIVE]], // User 2. [] ], 'expected' => [ [ 'start' => $pastcoursestart, 'startoffset' => 0 ], [ 'start' => $pastcoursestart, 'startoffset' => 0 ] ] ], 'past course start fixed 2 users enrolled future' => [ 'relativedatemode' => false, 'coursestart' => $pastcoursestart, 'usercount' => 2, 'enrolmentmethods' => [ ['manual', ENROL_INSTANCE_ENABLED], ['self', ENROL_INSTANCE_ENABLED] ], 'enrolled' => [ // User 1. ['manual' => [$pastcoursestart + 10, ENROL_USER_ACTIVE]], // User 2. ['manual' => [$pastcoursestart + 20, ENROL_USER_ACTIVE]] ], 'expected' => [ [ 'start' => $pastcoursestart, 'startoffset' => 0 ], [ 'start' => $pastcoursestart, 'startoffset' => 0 ] ] ], 'past course start fixed 2 users enrolled past' => [ 'relativedatemode' => false, 'coursestart' => $pastcoursestart, 'usercount' => 2, 'enrolmentmethods' => [ ['manual', ENROL_INSTANCE_ENABLED], ['self', ENROL_INSTANCE_ENABLED] ], 'enrolled' => [ // User 1. ['manual' => [$pastcoursestart - 10, ENROL_USER_ACTIVE]], // User 2. ['manual' => [$pastcoursestart - 20, ENROL_USER_ACTIVE]] ], 'expected' => [ [ 'start' => $pastcoursestart, 'startoffset' => 0 ], [ 'start' => $pastcoursestart, 'startoffset' => 0 ] ] ], 'past course start fixed 2 users enrolled mixed' => [ 'relativedatemode' => false, 'coursestart' => $pastcoursestart, 'usercount' => 2, 'enrolmentmethods' => [ ['manual', ENROL_INSTANCE_ENABLED], ['self', ENROL_INSTANCE_ENABLED] ], 'enrolled' => [ // User 1. ['manual' => [$pastcoursestart + 10, ENROL_USER_ACTIVE]], // User 2. ['manual' => [$pastcoursestart - 20, ENROL_USER_ACTIVE]] ], 'expected' => [ [ 'start' => $pastcoursestart, 'startoffset' => 0 ], [ 'start' => $pastcoursestart, 'startoffset' => 0 ] ] ], 'past course start fixed 2 users enrolled 2 methods' => [ 'relativedatemode' => false, 'coursestart' => $pastcoursestart, 'usercount' => 2, 'enrolmentmethods' => [ ['manual', ENROL_INSTANCE_ENABLED], ['self', ENROL_INSTANCE_ENABLED] ], 'enrolled' => [ // User 1. [ 'manual' => [$pastcoursestart + 10, ENROL_USER_ACTIVE], 'self' => [$pastcoursestart + 20, ENROL_USER_ACTIVE] ], // User 2. [ 'manual' => [$pastcoursestart + 20, ENROL_USER_ACTIVE], 'self' => [$pastcoursestart + 10, ENROL_USER_ACTIVE] ] ], 'expected' => [ [ 'start' => $pastcoursestart, 'startoffset' => 0 ], [ 'start' => $pastcoursestart, 'startoffset' => 0 ] ] ], 'past course start fixed 2 users enrolled 2 methods 1 disabled' => [ 'relativedatemode' => false, 'coursestart' => $pastcoursestart, 'usercount' => 2, 'enrolmentmethods' => [ ['manual', ENROL_INSTANCE_DISABLED], ['self', ENROL_INSTANCE_ENABLED] ], 'enrolled' => [ // User 1. [ 'manual' => [$pastcoursestart + 10, ENROL_USER_ACTIVE], 'self' => [$pastcoursestart + 20, ENROL_USER_ACTIVE] ], // User 2. [ 'manual' => [$pastcoursestart + 20, ENROL_USER_ACTIVE], 'self' => [$pastcoursestart + 10, ENROL_USER_ACTIVE] ] ], 'expected' => [ [ 'start' => $pastcoursestart, 'startoffset' => 0 ], [ 'start' => $pastcoursestart, 'startoffset' => 0 ] ] ], 'past course start fixed 2 users enrolled 2 methods 2 disabled' => [ 'relativedatemode' => false, 'coursestart' => $pastcoursestart, 'usercount' => 2, 'enrolmentmethods' => [ ['manual', ENROL_INSTANCE_DISABLED], ['self', ENROL_INSTANCE_DISABLED] ], 'enrolled' => [ // User 1. [ 'manual' => [$pastcoursestart + 10, ENROL_USER_ACTIVE], 'self' => [$pastcoursestart + 20, ENROL_USER_ACTIVE] ], // User 2. [ 'manual' => [$pastcoursestart + 20, ENROL_USER_ACTIVE], 'self' => [$pastcoursestart + 10, ENROL_USER_ACTIVE] ] ], 'expected' => [ [ 'start' => $pastcoursestart, 'startoffset' => 0 ], [ 'start' => $pastcoursestart, 'startoffset' => 0 ] ] ], 'past course start fixed 2 users enrolled 2 methods 0 disabled 1 user suspended' => [ 'relativedatemode' => false, 'coursestart' => $pastcoursestart, 'usercount' => 2, 'enrolmentmethods' => [ ['manual', ENROL_INSTANCE_ENABLED], ['self', ENROL_INSTANCE_ENABLED] ], 'enrolled' => [ // User 1. [ 'manual' => [$pastcoursestart + 10, ENROL_USER_SUSPENDED], 'self' => [$pastcoursestart + 20, ENROL_USER_ACTIVE] ], // User 2. [ 'manual' => [$pastcoursestart + 20, ENROL_USER_SUSPENDED], 'self' => [$pastcoursestart + 10, ENROL_USER_ACTIVE] ] ], 'expected' => [ [ 'start' => $pastcoursestart, 'startoffset' => 0 ], [ 'start' => $pastcoursestart, 'startoffset' => 0 ] ] ], 'past course start fixed 2 users enrolled 2 methods 0 disabled 2 user suspended' => [ 'relativedatemode' => false, 'coursestart' => $pastcoursestart, 'usercount' => 2, 'enrolmentmethods' => [ ['manual', ENROL_INSTANCE_ENABLED], ['self', ENROL_INSTANCE_ENABLED] ], 'enrolled' => [ // User 1. [ 'manual' => [$pastcoursestart + 10, ENROL_USER_SUSPENDED], 'self' => [$pastcoursestart + 20, ENROL_USER_SUSPENDED] ], // User 2. [ 'manual' => [$pastcoursestart + 20, ENROL_USER_SUSPENDED], 'self' => [$pastcoursestart + 10, ENROL_USER_SUSPENDED] ] ], 'expected' => [ [ 'start' => $pastcoursestart, 'startoffset' => 0 ], [ 'start' => $pastcoursestart, 'startoffset' => 0 ] ] ], 'past course start relative no users enrolled' => [ 'relativedatemode' => true, 'coursestart' => $pastcoursestart, 'usercount' => 2, 'enrolmentmethods' => [ ['manual', ENROL_INSTANCE_ENABLED], ['self', ENROL_INSTANCE_ENABLED] ], 'enrolled' => [[], []], 'expected' => [ [ 'start' => $pastcoursestart, 'startoffset' => 0 ], [ 'start' => $pastcoursestart, 'startoffset' => 0 ] ] ], 'past course start relative 1 users enrolled future' => [ 'relativedatemode' => true, 'coursestart' => $pastcoursestart, 'usercount' => 2, 'enrolmentmethods' => [ ['manual', ENROL_INSTANCE_ENABLED], ['self', ENROL_INSTANCE_ENABLED] ], 'enrolled' => [ // User 1. ['manual' => [$pastcoursestart + 10, ENROL_USER_ACTIVE]], // User 2. [] ], 'expected' => [ [ 'start' => $pastcoursestart + 10, 'startoffset' => 10 ], [ 'start' => $pastcoursestart, 'startoffset' => 0 ] ] ], 'past course start relative 1 users enrolled past' => [ 'relativedatemode' => true, 'coursestart' => $pastcoursestart, 'usercount' => 2, 'enrolmentmethods' => [ ['manual', ENROL_INSTANCE_ENABLED], ['self', ENROL_INSTANCE_ENABLED] ], 'enrolled' => [ // User 1. ['manual' => [$pastcoursestart - 10, ENROL_USER_ACTIVE]], // User 2. [] ], 'expected' => [ [ 'start' => $pastcoursestart, 'startoffset' => 0 ], [ 'start' => $pastcoursestart, 'startoffset' => 0 ] ] ], 'past course start relative 2 users enrolled future' => [ 'relativedatemode' => true, 'coursestart' => $pastcoursestart, 'usercount' => 2, 'enrolmentmethods' => [ ['manual', ENROL_INSTANCE_ENABLED], ['self', ENROL_INSTANCE_ENABLED] ], 'enrolled' => [ // User 1. ['manual' => [$pastcoursestart + 10, ENROL_USER_ACTIVE]], // User 2. ['manual' => [$pastcoursestart + 20, ENROL_USER_ACTIVE]] ], 'expected' => [ [ 'start' => $pastcoursestart + 10, 'startoffset' => 10 ], [ 'start' => $pastcoursestart + 20, 'startoffset' => 20 ] ] ], 'past course start relative 2 users enrolled past' => [ 'relativedatemode' => true, 'coursestart' => $pastcoursestart, 'usercount' => 2, 'enrolmentmethods' => [ ['manual', ENROL_INSTANCE_ENABLED], ['self', ENROL_INSTANCE_ENABLED] ], 'enrolled' => [ // User 1. ['manual' => [$pastcoursestart - 10, ENROL_USER_ACTIVE]], // User 2. ['manual' => [$pastcoursestart - 20, ENROL_USER_ACTIVE]] ], 'expected' => [ [ 'start' => $pastcoursestart, 'startoffset' => 0 ], [ 'start' => $pastcoursestart, 'startoffset' => 0 ] ] ], 'past course start relative 2 users enrolled mixed' => [ 'relativedatemode' => true, 'coursestart' => $pastcoursestart, 'usercount' => 2, 'enrolmentmethods' => [ ['manual', ENROL_INSTANCE_ENABLED], ['self', ENROL_INSTANCE_ENABLED] ], 'enrolled' => [ // User 1. ['manual' => [$pastcoursestart + 10, ENROL_USER_ACTIVE]], // User 2. ['manual' => [$pastcoursestart - 20, ENROL_USER_ACTIVE]] ], 'expected' => [ [ 'start' => $pastcoursestart + 10, 'startoffset' => 10 ], [ 'start' => $pastcoursestart, 'startoffset' => 0 ] ] ], 'past course start relative 2 users enrolled 2 methods' => [ 'relativedatemode' => true, 'coursestart' => $pastcoursestart, 'usercount' => 2, 'enrolmentmethods' => [ ['manual', ENROL_INSTANCE_ENABLED], ['self', ENROL_INSTANCE_ENABLED] ], 'enrolled' => [ // User 1. [ 'manual' => [$pastcoursestart + 10, ENROL_USER_ACTIVE], 'self' => [$pastcoursestart + 20, ENROL_USER_ACTIVE] ], // User 2. [ 'manual' => [$pastcoursestart + 20, ENROL_USER_ACTIVE], 'self' => [$pastcoursestart + 10, ENROL_USER_ACTIVE] ] ], 'expected' => [ [ 'start' => $pastcoursestart + 10, 'startoffset' => 10 ], [ 'start' => $pastcoursestart + 10, 'startoffset' => 10 ] ] ], 'past course start relative 2 users enrolled 2 methods 1 disabled' => [ 'relativedatemode' => true, 'coursestart' => $pastcoursestart, 'usercount' => 2, 'enrolmentmethods' => [ ['manual', ENROL_INSTANCE_DISABLED], ['self', ENROL_INSTANCE_ENABLED] ], 'enrolled' => [ // User 1. [ 'manual' => [$pastcoursestart + 10, ENROL_USER_ACTIVE], 'self' => [$pastcoursestart + 20, ENROL_USER_ACTIVE] ], // User 2. [ 'manual' => [$pastcoursestart + 20, ENROL_USER_ACTIVE], 'self' => [$pastcoursestart + 10, ENROL_USER_ACTIVE] ] ], 'expected' => [ [ 'start' => $pastcoursestart + 20, 'startoffset' => 20 ], [ 'start' => $pastcoursestart + 10, 'startoffset' => 10 ] ] ], 'past course start relative 2 users enrolled 2 methods 2 disabled' => [ 'relativedatemode' => true, 'coursestart' => $pastcoursestart, 'usercount' => 2, 'enrolmentmethods' => [ ['manual', ENROL_INSTANCE_DISABLED], ['self', ENROL_INSTANCE_DISABLED] ], 'enrolled' => [ // User 1. [ 'manual' => [$pastcoursestart + 10, ENROL_USER_ACTIVE], 'self' => [$pastcoursestart + 20, ENROL_USER_ACTIVE] ], // User 2. [ 'manual' => [$pastcoursestart + 20, ENROL_USER_ACTIVE], 'self' => [$pastcoursestart + 10, ENROL_USER_ACTIVE] ] ], 'expected' => [ [ 'start' => $pastcoursestart, 'startoffset' => 0 ], [ 'start' => $pastcoursestart, 'startoffset' => 0 ] ] ], 'past course start relative 2 users enrolled 2 methods 0 disabled 1 user suspended' => [ 'relativedatemode' => true, 'coursestart' => $pastcoursestart, 'usercount' => 2, 'enrolmentmethods' => [ ['manual', ENROL_INSTANCE_ENABLED], ['self', ENROL_INSTANCE_ENABLED] ], 'enrolled' => [ // User 1. [ 'manual' => [$pastcoursestart + 10, ENROL_USER_SUSPENDED], 'self' => [$pastcoursestart + 20, ENROL_USER_ACTIVE] ], // User 2. [ 'manual' => [$pastcoursestart + 20, ENROL_USER_SUSPENDED], 'self' => [$pastcoursestart + 10, ENROL_USER_ACTIVE] ] ], 'expected' => [ [ 'start' => $pastcoursestart + 20, 'startoffset' => 20 ], [ 'start' => $pastcoursestart + 10, 'startoffset' => 10 ] ] ], 'past course start relative 2 users enrolled 2 methods 0 disabled 2 user suspended' => [ 'relativedatemode' => true, 'coursestart' => $pastcoursestart, 'usercount' => 2, 'enrolmentmethods' => [ ['manual', ENROL_INSTANCE_ENABLED], ['self', ENROL_INSTANCE_ENABLED] ], 'enrolled' => [ // User 1. [ 'manual' => [$pastcoursestart + 10, ENROL_USER_SUSPENDED], 'self' => [$pastcoursestart + 20, ENROL_USER_SUSPENDED] ], // User 2. [ 'manual' => [$pastcoursestart + 20, ENROL_USER_SUSPENDED], 'self' => [$pastcoursestart + 10, ENROL_USER_SUSPENDED] ] ], 'expected' => [ [ 'start' => $pastcoursestart, 'startoffset' => 0 ], [ 'start' => $pastcoursestart, 'startoffset' => 0 ] ] ] ]; } /** * Test the course_get_course_dates_for_user_ids function. * * @dataProvider get_course_get_course_dates_for_user_ids_test_cases() * @param bool $relativedatemode Set the course to relative dates mode * @param int $coursestart Course start date * @param int $usercount Number of users to create * @param array $enrolmentmethods Enrolment methods to set for the course * @param array $enrolled Enrolment config for to set for the users * @param array $expected Expected output */ public function test_course_get_course_dates_for_user_ids( $relativedatemode, $coursestart, $usercount, $enrolmentmethods, $enrolled, $expected ) { global $DB; $this->resetAfterTest(); $generator = $this->getDataGenerator(); $course = $generator->create_course(['startdate' => $coursestart]); $course->relativedatesmode = $relativedatemode; $users = []; for ($i = 0; $i < $usercount; $i++) { $users[] = $generator->create_user(); } foreach ($enrolmentmethods as [$type, $status]) { $record = $DB->get_record('enrol', ['courseid' => $course->id, 'enrol' => $type]); $plugin = enrol_get_plugin($type); if ($record->status != $status) { $plugin->update_status($record, $status); } } foreach ($enrolled as $index => $enrolconfig) { $user = $users[$index]; foreach ($enrolconfig as $type => [$starttime, $status]) { $generator->enrol_user($user->id, $course->id, 'student', $type, $starttime, 0, $status); } } $userids = array_map(function($user) { return $user->id; }, $users); $actual = course_get_course_dates_for_user_ids($course, $userids); foreach ($expected as $index => $exp) { $userid = $userids[$index]; $act = $actual[$userid]; $this->assertEquals($exp['start'], $act['start']); $this->assertEquals($exp['startoffset'], $act['startoffset']); } } /** * Test that calling course_get_course_dates_for_user_ids multiple times in the * same request fill fetch the correct data for the user. */ public function test_course_get_course_dates_for_user_ids_multiple_calls() { $this->resetAfterTest(); $generator = $this->getDataGenerator(); $now = time(); $coursestart = $now - 1000; $course = $generator->create_course(['startdate' => $coursestart]); $course->relativedatesmode = true; $user1 = $generator->create_user(); $user2 = $generator->create_user(); $user1start = $coursestart + 100; $user2start = $coursestart + 200; $generator->enrol_user($user1->id, $course->id, 'student', 'manual', $user1start); $generator->enrol_user($user2->id, $course->id, 'student', 'manual', $user2start); $result = course_get_course_dates_for_user_ids($course, [$user1->id]); $this->assertEquals($user1start, $result[$user1->id]['start']); $result = course_get_course_dates_for_user_ids($course, [$user1->id, $user2->id]); $this->assertEquals($user1start, $result[$user1->id]['start']); $this->assertEquals($user2start, $result[$user2->id]['start']); $result = course_get_course_dates_for_user_ids($course, [$user2->id]); $this->assertEquals($user2start, $result[$user2->id]['start']); } /** * Data provider for test_course_modules_pending_deletion. * * @return array An array of arrays contain test data */ public function provider_course_modules_pending_deletion() { return [ 'Non-gradable activity, check all' => [['forum'], 0, false, true], 'Gradable activity, check all' => [['assign'], 0, false, true], 'Non-gradable activity, check gradables' => [['forum'], 0, true, false], 'Gradable activity, check gradables' => [['assign'], 0, true, true], 'Non-gradable within multiple, check all' => [['quiz', 'forum', 'assign'], 1, false, true], 'Non-gradable within multiple, check gradables' => [['quiz', 'forum', 'assign'], 1, true, false], 'Gradable within multiple, check all' => [['quiz', 'forum', 'assign'], 2, false, true], 'Gradable within multiple, check gradables' => [['quiz', 'forum', 'assign'], 2, true, true], ]; } /** * Tests the function course_modules_pending_deletion. * * @param string[] $modules A complete list aff all available modules before deletion * @param int $indextodelete The index of the module in the $modules array that we want to test with * @param bool $gradable The value to pass to the gradable argument of the course_modules_pending_deletion function * @param bool $expected The expected result * @dataProvider provider_course_modules_pending_deletion */ public function test_course_modules_pending_deletion(array $modules, int $indextodelete, bool $gradable, bool $expected) { $this->resetAfterTest(); // Ensure recyclebin is enabled. set_config('coursebinenable', true, 'tool_recyclebin'); // Create course and modules. $generator = $this->getDataGenerator(); $course = $generator->create_course(); $moduleinstances = []; foreach ($modules as $module) { $moduleinstances[] = $generator->create_module($module, array('course' => $course->id)); } course_delete_module($moduleinstances[$indextodelete]->cmid, true); // Try to delete the instance asynchronously. $this->assertEquals($expected, course_modules_pending_deletion($course->id, $gradable)); } /** * Tests for the course_request::can_request */ public function test_can_request_course() { global $CFG, $DB; $this->resetAfterTest(); $user = $this->getDataGenerator()->create_user(); $cat1 = $CFG->defaultrequestcategory; $cat2 = $this->getDataGenerator()->create_category()->id; $cat3 = $this->getDataGenerator()->create_category()->id; $context1 = context_coursecat::instance($cat1); $context2 = context_coursecat::instance($cat2); $context3 = context_coursecat::instance($cat3); $this->setUser($user); // By default users don't have capability to request courses. $this->assertFalse(course_request::can_request(context_system::instance())); $this->assertFalse(course_request::can_request($context1)); $this->assertFalse(course_request::can_request($context2)); $this->assertFalse(course_request::can_request($context3)); // Allow for the 'user' role the capability to request courses. $userroleid = $DB->get_field('role', 'id', ['shortname' => 'user']); assign_capability('moodle/course:request', CAP_ALLOW, $userroleid, context_system::instance()->id); accesslib_clear_all_caches_for_unit_testing(); // Lock category selection. $CFG->lockrequestcategory = 1; // Now user can only request course in the default category or in system context. $this->assertTrue(course_request::can_request(context_system::instance())); $this->assertTrue(course_request::can_request($context1)); $this->assertFalse(course_request::can_request($context2)); $this->assertFalse(course_request::can_request($context3)); // Enable category selection. User can request course anywhere. $CFG->lockrequestcategory = 0; $this->assertTrue(course_request::can_request(context_system::instance())); $this->assertTrue(course_request::can_request($context1)); $this->assertTrue(course_request::can_request($context2)); $this->assertTrue(course_request::can_request($context3)); // Remove cap from cat2. $roleid = create_role('Test role', 'testrole', 'Test role description'); assign_capability('moodle/course:request', CAP_PROHIBIT, $roleid, $context2->id, true); role_assign($roleid, $user->id, $context2->id); accesslib_clear_all_caches_for_unit_testing(); $this->assertTrue(course_request::can_request(context_system::instance())); $this->assertTrue(course_request::can_request($context1)); $this->assertFalse(course_request::can_request($context2)); $this->assertTrue(course_request::can_request($context3)); // Disable course request functionality. $CFG->enablecourserequests = false; $this->assertFalse(course_request::can_request(context_system::instance())); $this->assertFalse(course_request::can_request($context1)); $this->assertFalse(course_request::can_request($context2)); $this->assertFalse(course_request::can_request($context3)); } /** * Tests for the course_request::can_approve */ public function test_can_approve_course_request() { global $CFG; $this->resetAfterTest(); $requestor = $this->getDataGenerator()->create_user(); $user = $this->getDataGenerator()->create_user(); $cat1 = $CFG->defaultrequestcategory; $cat2 = $this->getDataGenerator()->create_category()->id; $cat3 = $this->getDataGenerator()->create_category()->id; // Enable course requests. Default 'user' role has capability to request courses. $CFG->enablecourserequests = true; $CFG->lockrequestcategory = 0; $this->setUser($requestor); $requestdata = ['summary_editor' => ['text' => '', 'format' => 0], 'name' => 'Req', 'reason' => 'test']; $request1 = course_request::create((object)($requestdata)); $request2 = course_request::create((object)($requestdata + ['category' => $cat2])); $request3 = course_request::create((object)($requestdata + ['category' => $cat3])); $this->setUser($user); // Add capability to approve courses. $roleid = create_role('Test role', 'testrole', 'Test role description'); assign_capability('moodle/site:approvecourse', CAP_ALLOW, $roleid, context_system::instance()->id, true); role_assign($roleid, $user->id, context_coursecat::instance($cat2)->id); accesslib_clear_all_caches_for_unit_testing(); $this->assertFalse($request1->can_approve()); $this->assertTrue($request2->can_approve()); $this->assertFalse($request3->can_approve()); // Delete category where course was requested. Now only site-wide manager can approve it. core_course_category::get($cat2, MUST_EXIST, true)->delete_full(false); $this->assertFalse($request2->can_approve()); $this->setAdminUser(); $this->assertTrue($request2->can_approve()); } /** * Test the course allowed module method. */ public function test_course_allowed_module() { $this->resetAfterTest(); global $DB; $course = $this->getDataGenerator()->create_course(); $teacher = $this->getDataGenerator()->create_and_enrol($course, 'editingteacher'); $manager = $this->getDataGenerator()->create_and_enrol($course, 'manager'); $teacherrole = $DB->get_record('role', array('shortname' => 'editingteacher')); assign_capability('mod/assign:addinstance', CAP_PROHIBIT, $teacherrole->id, \context_course::instance($course->id)); // Global user (teacher) has no permissions in this course. $this->setUser($teacher); $this->assertFalse(course_allowed_module($course, 'assign')); // Manager has permissions. $this->assertTrue(course_allowed_module($course, 'assign', $manager)); } /** * Test the {@link average_number_of_participants()} function. */ public function test_average_number_of_participants() { global $DB; $this->resetAfterTest(true); $generator = $this->getDataGenerator(); $now = time(); // If there are no courses, expect zero number of participants per course. $this->assertEquals(0, average_number_of_participants()); $c1 = $generator->create_course(); $c2 = $generator->create_course(); // If there are no users, expect zero number of participants per course. $this->assertEquals(0, average_number_of_participants()); $t1 = $generator->create_user(['lastlogin' => $now]); $s1 = $generator->create_user(['lastlogin' => $now]); $s2 = $generator->create_user(['lastlogin' => $now - WEEKSECS]); $s3 = $generator->create_user(['lastlogin' => $now - WEEKSECS]); $s4 = $generator->create_user(['lastlogin' => $now - YEARSECS]); // We have courses, we have users, but no enrolments yet. $this->assertEquals(0, average_number_of_participants()); // Front page enrolments are ignored. $generator->enrol_user($t1->id, SITEID, 'teacher'); $this->assertEquals(0, average_number_of_participants()); // The teacher enrolled into one of the two courses. $generator->enrol_user($t1->id, $c1->id, 'editingteacher'); $this->assertEquals(0.5, average_number_of_participants()); // The teacher enrolled into both courses. $generator->enrol_user($t1->id, $c2->id, 'editingteacher'); $this->assertEquals(1, average_number_of_participants()); // Student 1 enrolled in the Course 1 only. $generator->enrol_user($s1->id, $c1->id, 'student'); $this->assertEquals(1.5, average_number_of_participants()); // Student 2 enrolled in both courses, but the enrolment in the Course 2 not active yet (enrolment starts in the future). $generator->enrol_user($s2->id, $c1->id, 'student'); $generator->enrol_user($s2->id, $c2->id, 'student', 'manual', $now + WEEKSECS); $this->assertEquals(2.5, average_number_of_participants()); $this->assertEquals(2, average_number_of_participants(true)); // Student 3 enrolled in the Course 1, but the enrolment already expired. $generator->enrol_user($s3->id, $c1->id, 'student', 'manual', 0, $now - YEARSECS); $this->assertEquals(3, average_number_of_participants()); $this->assertEquals(2, average_number_of_participants(true)); // Student 4 enrolled in both courses, but the enrolment has been suspended. $generator->enrol_user($s4->id, $c1->id, 'student', 'manual', 0, 0, ENROL_USER_SUSPENDED); $generator->enrol_user($s4->id, $c2->id, 'student', 'manual', $now - DAYSECS, $now + YEARSECS, ENROL_USER_SUSPENDED); $this->assertEquals(4, average_number_of_participants()); $this->assertEquals(2, average_number_of_participants(true)); // Consider only t1 and s1 who logged in recently. $this->assertEquals(1.5, average_number_of_participants(false, $now - DAYSECS)); // Consider only t1, s1, s2 and s3 who logged in in recent weeks. $this->assertEquals(3, average_number_of_participants(false, $now - 4 * WEEKSECS)); // Hidden courses are excluded from stats. $DB->set_field('course', 'visible', 0, ['id' => $c1->id]); $this->assertEquals(3, average_number_of_participants()); $this->assertEquals(1, average_number_of_participants(true)); } /** * Test the set_downloadcontent() function. */ public function test_set_downloadcontent() { $this->resetAfterTest(); $generator = $this->getDataGenerator(); $course = $generator->create_course(); $page = $generator->create_module('page', ['course' => $course]); // Test the module 'downloadcontent' field is set to enabled. set_downloadcontent($page->cmid, DOWNLOAD_COURSE_CONTENT_ENABLED); $modinfo = get_fast_modinfo($course)->get_cm($page->cmid); $this->assertEquals(DOWNLOAD_COURSE_CONTENT_ENABLED, $modinfo->downloadcontent); // Now let's test the 'downloadcontent' value is updated to disabled. set_downloadcontent($page->cmid, DOWNLOAD_COURSE_CONTENT_DISABLED); $modinfo = get_fast_modinfo($course)->get_cm($page->cmid); $this->assertEquals(DOWNLOAD_COURSE_CONTENT_DISABLED, $modinfo->downloadcontent); // Nothing to update, the download course content value is the same, it should return false. $this->assertFalse(set_downloadcontent($page->cmid, DOWNLOAD_COURSE_CONTENT_DISABLED)); // The download course content value has changed, it should return true in this case. $this->assertTrue(set_downloadcontent($page->cmid, DOWNLOAD_COURSE_CONTENT_ENABLED)); } }