/** * Test view_choice */ public function test_view_choice() { global $DB; $this->resetAfterTest(true); // Setup test data. $course = $this->getDataGenerator()->create_course(); $choice = $this->getDataGenerator()->create_module('choice', array('course' => $course->id)); $context = context_module::instance($choice->cmid); $cm = get_coursemodule_from_instance('choice', $choice->id); // Test invalid instance id. try { mod_choice_external::view_choice(0); $this->fail('Exception expected due to invalid mod_choice instance id.'); } catch (moodle_exception $e) { $this->assertEquals('invalidcoursemodule', $e->errorcode); } // Test not-enrolled user. $user = self::getDataGenerator()->create_user(); $this->setUser($user); try { mod_choice_external::view_choice($choice->id); $this->fail('Exception expected due to not enrolled user.'); } catch (moodle_exception $e) { $this->assertEquals('requireloginerror', $e->errorcode); } // Test user with full capabilities. $studentrole = $DB->get_record('role', array('shortname' => 'student')); $this->getDataGenerator()->enrol_user($user->id, $course->id, $studentrole->id); // Trigger and capture the event. $sink = $this->redirectEvents(); $result = mod_choice_external::view_choice($choice->id); $result = external_api::clean_returnvalue(mod_choice_external::view_choice_returns(), $result); $events = $sink->get_events(); $this->assertCount(1, $events); $event = array_shift($events); // Checking that the event contains the expected values. $this->assertInstanceOf('\\mod_choice\\event\\course_module_viewed', $event); $this->assertEquals($context, $event->get_context()); $moodlechoice = new \moodle_url('/mod/choice/view.php', array('id' => $cm->id)); $this->assertEquals($moodlechoice, $event->get_url()); $this->assertEventContextNotUsed($event); $this->assertNotEmpty($event->get_name()); }