MDL-69823 mod_quiz: Return question options via WS
[moodle.git] / mod / quiz / tests / external_test.php
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 // GNU General Public License for more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
17 /**
18  * Quiz module external functions tests.
19  *
20  * @package    mod_quiz
21  * @category   external
22  * @copyright  2016 Juan Leyva <juan@moodle.com>
23  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24  * @since      Moodle 3.1
25  */
27 defined('MOODLE_INTERNAL') || die();
29 global $CFG;
31 require_once($CFG->dirroot . '/webservice/tests/helpers.php');
33 /**
34  * Silly class to access mod_quiz_external internal methods.
35  *
36  * @package mod_quiz
37  * @copyright 2016 Juan Leyva <juan@moodle.com>
38  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
39  * @since  Moodle 3.1
40  */
41 class testable_mod_quiz_external extends mod_quiz_external {
43     /**
44      * Public accessor.
45      *
46      * @param  array $params Array of parameters including the attemptid and preflight data
47      * @param  bool $checkaccessrules whether to check the quiz access rules or not
48      * @param  bool $failifoverdue whether to return error if the attempt is overdue
49      * @return  array containing the attempt object and access messages
50      */
51     public static function validate_attempt($params, $checkaccessrules = true, $failifoverdue = true) {
52         return parent::validate_attempt($params, $checkaccessrules, $failifoverdue);
53     }
55     /**
56      * Public accessor.
57      *
58      * @param  array $params Array of parameters including the attemptid
59      * @return  array containing the attempt object and display options
60      */
61     public static function validate_attempt_review($params) {
62         return parent::validate_attempt_review($params);
63     }
64 }
66 /**
67  * Quiz module external functions tests
68  *
69  * @package    mod_quiz
70  * @category   external
71  * @copyright  2016 Juan Leyva <juan@moodle.com>
72  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
73  * @since      Moodle 3.1
74  */
75 class mod_quiz_external_testcase extends externallib_advanced_testcase {
77     /**
78      * Set up for every test
79      */
80     public function setUp(): void {
81         global $DB;
82         $this->resetAfterTest();
83         $this->setAdminUser();
85         // Setup test data.
86         $this->course = $this->getDataGenerator()->create_course();
87         $this->quiz = $this->getDataGenerator()->create_module('quiz', array('course' => $this->course->id));
88         $this->context = context_module::instance($this->quiz->cmid);
89         $this->cm = get_coursemodule_from_instance('quiz', $this->quiz->id);
91         // Create users.
92         $this->student = self::getDataGenerator()->create_user();
93         $this->teacher = self::getDataGenerator()->create_user();
95         // Users enrolments.
96         $this->studentrole = $DB->get_record('role', array('shortname' => 'student'));
97         $this->teacherrole = $DB->get_record('role', array('shortname' => 'editingteacher'));
98         // Allow student to receive messages.
99         $coursecontext = context_course::instance($this->course->id);
100         assign_capability('mod/quiz:emailnotifysubmission', CAP_ALLOW, $this->teacherrole->id, $coursecontext, true);
102         $this->getDataGenerator()->enrol_user($this->student->id, $this->course->id, $this->studentrole->id, 'manual');
103         $this->getDataGenerator()->enrol_user($this->teacher->id, $this->course->id, $this->teacherrole->id, 'manual');
104     }
106     /**
107      * Create a quiz with questions including a started or finished attempt optionally
108      *
109      * @param  boolean $startattempt whether to start a new attempt
110      * @param  boolean $finishattempt whether to finish the new attempt
111      * @param  string $behaviour the quiz preferredbehaviour, defaults to 'deferredfeedback'.
112      * @param  boolean $includeqattachments whether to include a question that supports attachments, defaults to false.
113      * @return array array containing the quiz, context and the attempt
114      */
115     private function create_quiz_with_questions($startattempt = false, $finishattempt = false, $behaviour = 'deferredfeedback',
116             $includeqattachments = false) {
118         // Create a new quiz with attempts.
119         $quizgenerator = $this->getDataGenerator()->get_plugin_generator('mod_quiz');
120         $data = array('course' => $this->course->id,
121                       'sumgrades' => 2,
122                       'preferredbehaviour' => $behaviour);
123         $quiz = $quizgenerator->create_instance($data);
124         $context = context_module::instance($quiz->cmid);
126         // Create a couple of questions.
127         $questiongenerator = $this->getDataGenerator()->get_plugin_generator('core_question');
129         $cat = $questiongenerator->create_question_category();
130         $question = $questiongenerator->create_question('numerical', null, array('category' => $cat->id));
131         quiz_add_quiz_question($question->id, $quiz);
132         $question = $questiongenerator->create_question('numerical', null, array('category' => $cat->id));
133         quiz_add_quiz_question($question->id, $quiz);
135         if ($includeqattachments) {
136             $question = $questiongenerator->create_question('essay', null, array('category' => $cat->id, 'attachments' => 1,
137                 'attachmentsrequired' => 1));
138             quiz_add_quiz_question($question->id, $quiz);
139         }
141         $quizobj = quiz::create($quiz->id, $this->student->id);
143         // Set grade to pass.
144         $item = grade_item::fetch(array('courseid' => $this->course->id, 'itemtype' => 'mod',
145                                         'itemmodule' => 'quiz', 'iteminstance' => $quiz->id, 'outcomeid' => null));
146         $item->gradepass = 80;
147         $item->update();
149         if ($startattempt or $finishattempt) {
150             // Now, do one attempt.
151             $quba = question_engine::make_questions_usage_by_activity('mod_quiz', $quizobj->get_context());
152             $quba->set_preferred_behaviour($quizobj->get_quiz()->preferredbehaviour);
154             $timenow = time();
155             $attempt = quiz_create_attempt($quizobj, 1, false, $timenow, false, $this->student->id);
156             quiz_start_new_attempt($quizobj, $quba, $attempt, 1, $timenow);
157             quiz_attempt_save_started($quizobj, $quba, $attempt);
158             $attemptobj = quiz_attempt::create($attempt->id);
160             if ($finishattempt) {
161                 // Process some responses from the student.
162                 $tosubmit = array(1 => array('answer' => '3.14'));
163                 $attemptobj->process_submitted_actions(time(), false, $tosubmit);
165                 // Finish the attempt.
166                 $attemptobj->process_finish(time(), false);
167             }
168             return array($quiz, $context, $quizobj, $attempt, $attemptobj, $quba);
169         } else {
170             return array($quiz, $context, $quizobj);
171         }
173     }
175     /*
176      * Test get quizzes by courses
177      */
178     public function test_mod_quiz_get_quizzes_by_courses() {
179         global $DB;
181         // Create additional course.
182         $course2 = self::getDataGenerator()->create_course();
184         // Second quiz.
185         $record = new stdClass();
186         $record->course = $course2->id;
187         $record->intro = '<button>Test with HTML allowed.</button>';
188         $quiz2 = self::getDataGenerator()->create_module('quiz', $record);
190         // Execute real Moodle enrolment as we'll call unenrol() method on the instance later.
191         $enrol = enrol_get_plugin('manual');
192         $enrolinstances = enrol_get_instances($course2->id, true);
193         foreach ($enrolinstances as $courseenrolinstance) {
194             if ($courseenrolinstance->enrol == "manual") {
195                 $instance2 = $courseenrolinstance;
196                 break;
197             }
198         }
199         $enrol->enrol_user($instance2, $this->student->id, $this->studentrole->id);
201         self::setUser($this->student);
203         $returndescription = mod_quiz_external::get_quizzes_by_courses_returns();
205         // Create what we expect to be returned when querying the two courses.
206         // First for the student user.
207         $allusersfields = array('id', 'coursemodule', 'course', 'name', 'intro', 'introformat', 'introfiles', 'timeopen',
208                                 'timeclose', 'grademethod', 'section', 'visible', 'groupmode', 'groupingid',
209                                 'attempts', 'timelimit', 'grademethod', 'decimalpoints', 'questiondecimalpoints', 'sumgrades',
210                                 'grade', 'preferredbehaviour', 'hasfeedback');
211         $userswithaccessfields = array('attemptonlast', 'reviewattempt', 'reviewcorrectness', 'reviewmarks',
212                                         'reviewspecificfeedback', 'reviewgeneralfeedback', 'reviewrightanswer',
213                                         'reviewoverallfeedback', 'questionsperpage', 'navmethod',
214                                         'browsersecurity', 'delay1', 'delay2', 'showuserpicture', 'showblocks',
215                                         'completionattemptsexhausted', 'completionpass', 'autosaveperiod', 'hasquestions',
216                                         'overduehandling', 'graceperiod', 'canredoquestions', 'allowofflineattempts');
217         $managerfields = array('shuffleanswers', 'timecreated', 'timemodified', 'password', 'subnet');
219         // Add expected coursemodule and other data.
220         $quiz1 = $this->quiz;
221         $quiz1->coursemodule = $quiz1->cmid;
222         $quiz1->introformat = 1;
223         $quiz1->section = 0;
224         $quiz1->visible = true;
225         $quiz1->groupmode = 0;
226         $quiz1->groupingid = 0;
227         $quiz1->hasquestions = 0;
228         $quiz1->hasfeedback = 0;
229         $quiz1->autosaveperiod = get_config('quiz', 'autosaveperiod');
230         $quiz1->introfiles = [];
232         $quiz2->coursemodule = $quiz2->cmid;
233         $quiz2->introformat = 1;
234         $quiz2->section = 0;
235         $quiz2->visible = true;
236         $quiz2->groupmode = 0;
237         $quiz2->groupingid = 0;
238         $quiz2->hasquestions = 0;
239         $quiz2->hasfeedback = 0;
240         $quiz2->autosaveperiod = get_config('quiz', 'autosaveperiod');
241         $quiz2->introfiles = [];
243         foreach (array_merge($allusersfields, $userswithaccessfields) as $field) {
244             $expected1[$field] = $quiz1->{$field};
245             $expected2[$field] = $quiz2->{$field};
246         }
248         $expectedquizzes = array($expected2, $expected1);
250         // Call the external function passing course ids.
251         $result = mod_quiz_external::get_quizzes_by_courses(array($course2->id, $this->course->id));
252         $result = external_api::clean_returnvalue($returndescription, $result);
254         $this->assertEquals($expectedquizzes, $result['quizzes']);
255         $this->assertCount(0, $result['warnings']);
257         // Call the external function without passing course id.
258         $result = mod_quiz_external::get_quizzes_by_courses();
259         $result = external_api::clean_returnvalue($returndescription, $result);
260         $this->assertEquals($expectedquizzes, $result['quizzes']);
261         $this->assertCount(0, $result['warnings']);
263         // Unenrol user from second course and alter expected quizzes.
264         $enrol->unenrol_user($instance2, $this->student->id);
265         array_shift($expectedquizzes);
267         // Call the external function without passing course id.
268         $result = mod_quiz_external::get_quizzes_by_courses();
269         $result = external_api::clean_returnvalue($returndescription, $result);
270         $this->assertEquals($expectedquizzes, $result['quizzes']);
272         // Call for the second course we unenrolled the user from, expected warning.
273         $result = mod_quiz_external::get_quizzes_by_courses(array($course2->id));
274         $this->assertCount(1, $result['warnings']);
275         $this->assertEquals('1', $result['warnings'][0]['warningcode']);
276         $this->assertEquals($course2->id, $result['warnings'][0]['itemid']);
278         // Now, try as a teacher for getting all the additional fields.
279         self::setUser($this->teacher);
281         foreach ($managerfields as $field) {
282             $expectedquizzes[0][$field] = $quiz1->{$field};
283         }
285         $result = mod_quiz_external::get_quizzes_by_courses();
286         $result = external_api::clean_returnvalue($returndescription, $result);
287         $this->assertEquals($expectedquizzes, $result['quizzes']);
289         // Admin also should get all the information.
290         self::setAdminUser();
292         $result = mod_quiz_external::get_quizzes_by_courses(array($this->course->id));
293         $result = external_api::clean_returnvalue($returndescription, $result);
294         $this->assertEquals($expectedquizzes, $result['quizzes']);
296         // Now, prevent access.
297         $enrol->enrol_user($instance2, $this->student->id);
299         self::setUser($this->student);
301         $quiz2->timeclose = time() - DAYSECS;
302         $DB->update_record('quiz', $quiz2);
304         $result = mod_quiz_external::get_quizzes_by_courses();
305         $result = external_api::clean_returnvalue($returndescription, $result);
306         $this->assertCount(2, $result['quizzes']);
307         // We only see a limited set of fields.
308         $this->assertCount(4, $result['quizzes'][0]);
309         $this->assertEquals($quiz2->id, $result['quizzes'][0]['id']);
310         $this->assertEquals($quiz2->coursemodule, $result['quizzes'][0]['coursemodule']);
311         $this->assertEquals($quiz2->course, $result['quizzes'][0]['course']);
312         $this->assertEquals($quiz2->name, $result['quizzes'][0]['name']);
313         $this->assertEquals($quiz2->course, $result['quizzes'][0]['course']);
315         $this->assertFalse(isset($result['quizzes'][0]['timelimit']));
317     }
319     /**
320      * Test test_view_quiz
321      */
322     public function test_view_quiz() {
323         global $DB;
325         // Test invalid instance id.
326         try {
327             mod_quiz_external::view_quiz(0);
328             $this->fail('Exception expected due to invalid mod_quiz instance id.');
329         } catch (moodle_exception $e) {
330             $this->assertEquals('invalidrecord', $e->errorcode);
331         }
333         // Test not-enrolled user.
334         $usernotenrolled = self::getDataGenerator()->create_user();
335         $this->setUser($usernotenrolled);
336         try {
337             mod_quiz_external::view_quiz($this->quiz->id);
338             $this->fail('Exception expected due to not enrolled user.');
339         } catch (moodle_exception $e) {
340             $this->assertEquals('requireloginerror', $e->errorcode);
341         }
343         // Test user with full capabilities.
344         $this->setUser($this->student);
346         // Trigger and capture the event.
347         $sink = $this->redirectEvents();
349         $result = mod_quiz_external::view_quiz($this->quiz->id);
350         $result = external_api::clean_returnvalue(mod_quiz_external::view_quiz_returns(), $result);
351         $this->assertTrue($result['status']);
353         $events = $sink->get_events();
354         $this->assertCount(1, $events);
355         $event = array_shift($events);
357         // Checking that the event contains the expected values.
358         $this->assertInstanceOf('\mod_quiz\event\course_module_viewed', $event);
359         $this->assertEquals($this->context, $event->get_context());
360         $moodlequiz = new \moodle_url('/mod/quiz/view.php', array('id' => $this->cm->id));
361         $this->assertEquals($moodlequiz, $event->get_url());
362         $this->assertEventContextNotUsed($event);
363         $this->assertNotEmpty($event->get_name());
365         // Test user with no capabilities.
366         // We need a explicit prohibit since this capability is only defined in authenticated user and guest roles.
367         assign_capability('mod/quiz:view', CAP_PROHIBIT, $this->studentrole->id, $this->context->id);
368         // Empty all the caches that may be affected  by this change.
369         accesslib_clear_all_caches_for_unit_testing();
370         course_modinfo::clear_instance_cache();
372         try {
373             mod_quiz_external::view_quiz($this->quiz->id);
374             $this->fail('Exception expected due to missing capability.');
375         } catch (moodle_exception $e) {
376             $this->assertEquals('requireloginerror', $e->errorcode);
377         }
379     }
381     /**
382      * Test get_user_attempts
383      */
384     public function test_get_user_attempts() {
386         // Create a quiz with one attempt finished.
387         list($quiz, $context, $quizobj, $attempt, $attemptobj) = $this->create_quiz_with_questions(true, true);
389         $this->setUser($this->student);
390         $result = mod_quiz_external::get_user_attempts($quiz->id);
391         $result = external_api::clean_returnvalue(mod_quiz_external::get_user_attempts_returns(), $result);
393         $this->assertCount(1, $result['attempts']);
394         $this->assertEquals($attempt->id, $result['attempts'][0]['id']);
395         $this->assertEquals($quiz->id, $result['attempts'][0]['quiz']);
396         $this->assertEquals($this->student->id, $result['attempts'][0]['userid']);
397         $this->assertEquals(1, $result['attempts'][0]['attempt']);
399         // Test filters. Only finished.
400         $result = mod_quiz_external::get_user_attempts($quiz->id, 0, 'finished', false);
401         $result = external_api::clean_returnvalue(mod_quiz_external::get_user_attempts_returns(), $result);
403         $this->assertCount(1, $result['attempts']);
404         $this->assertEquals($attempt->id, $result['attempts'][0]['id']);
406         // Test filters. All attempts.
407         $result = mod_quiz_external::get_user_attempts($quiz->id, 0, 'all', false);
408         $result = external_api::clean_returnvalue(mod_quiz_external::get_user_attempts_returns(), $result);
410         $this->assertCount(1, $result['attempts']);
411         $this->assertEquals($attempt->id, $result['attempts'][0]['id']);
413         // Test filters. Unfinished.
414         $result = mod_quiz_external::get_user_attempts($quiz->id, 0, 'unfinished', false);
415         $result = external_api::clean_returnvalue(mod_quiz_external::get_user_attempts_returns(), $result);
417         $this->assertCount(0, $result['attempts']);
419         // Start a new attempt, but not finish it.
420         $timenow = time();
421         $attempt = quiz_create_attempt($quizobj, 2, false, $timenow, false, $this->student->id);
422         $quba = question_engine::make_questions_usage_by_activity('mod_quiz', $quizobj->get_context());
423         $quba->set_preferred_behaviour($quizobj->get_quiz()->preferredbehaviour);
425         quiz_start_new_attempt($quizobj, $quba, $attempt, 1, $timenow);
426         quiz_attempt_save_started($quizobj, $quba, $attempt);
428         // Test filters. All attempts.
429         $result = mod_quiz_external::get_user_attempts($quiz->id, 0, 'all', false);
430         $result = external_api::clean_returnvalue(mod_quiz_external::get_user_attempts_returns(), $result);
432         $this->assertCount(2, $result['attempts']);
434         // Test filters. Unfinished.
435         $result = mod_quiz_external::get_user_attempts($quiz->id, 0, 'unfinished', false);
436         $result = external_api::clean_returnvalue(mod_quiz_external::get_user_attempts_returns(), $result);
438         $this->assertCount(1, $result['attempts']);
440         // Test manager can see user attempts.
441         $this->setUser($this->teacher);
442         $result = mod_quiz_external::get_user_attempts($quiz->id, $this->student->id);
443         $result = external_api::clean_returnvalue(mod_quiz_external::get_user_attempts_returns(), $result);
445         $this->assertCount(1, $result['attempts']);
446         $this->assertEquals($this->student->id, $result['attempts'][0]['userid']);
448         $result = mod_quiz_external::get_user_attempts($quiz->id, $this->student->id, 'all');
449         $result = external_api::clean_returnvalue(mod_quiz_external::get_user_attempts_returns(), $result);
451         $this->assertCount(2, $result['attempts']);
452         $this->assertEquals($this->student->id, $result['attempts'][0]['userid']);
454         // Invalid parameters.
455         try {
456             mod_quiz_external::get_user_attempts($quiz->id, $this->student->id, 'INVALID_PARAMETER');
457             $this->fail('Exception expected due to missing capability.');
458         } catch (invalid_parameter_exception $e) {
459             $this->assertEquals('invalidparameter', $e->errorcode);
460         }
461     }
463     /**
464      * Test get_user_best_grade
465      */
466     public function test_get_user_best_grade() {
467         global $DB;
469         $this->setUser($this->student);
471         $result = mod_quiz_external::get_user_best_grade($this->quiz->id);
472         $result = external_api::clean_returnvalue(mod_quiz_external::get_user_best_grade_returns(), $result);
474         // No grades yet.
475         $this->assertFalse($result['hasgrade']);
476         $this->assertTrue(!isset($result['grade']));
478         $grade = new stdClass();
479         $grade->quiz = $this->quiz->id;
480         $grade->userid = $this->student->id;
481         $grade->grade = 8.9;
482         $grade->timemodified = time();
483         $grade->id = $DB->insert_record('quiz_grades', $grade);
485         $result = mod_quiz_external::get_user_best_grade($this->quiz->id);
486         $result = external_api::clean_returnvalue(mod_quiz_external::get_user_best_grade_returns(), $result);
488         // Now I have grades.
489         $this->assertTrue($result['hasgrade']);
490         $this->assertEquals(8.9, $result['grade']);
492         // We should not see other users grades.
493         $anotherstudent = self::getDataGenerator()->create_user();
494         $this->getDataGenerator()->enrol_user($anotherstudent->id, $this->course->id, $this->studentrole->id, 'manual');
496         try {
497             mod_quiz_external::get_user_best_grade($this->quiz->id, $anotherstudent->id);
498             $this->fail('Exception expected due to missing capability.');
499         } catch (required_capability_exception $e) {
500             $this->assertEquals('nopermissions', $e->errorcode);
501         }
503         // Teacher must be able to see student grades.
504         $this->setUser($this->teacher);
506         $result = mod_quiz_external::get_user_best_grade($this->quiz->id, $this->student->id);
507         $result = external_api::clean_returnvalue(mod_quiz_external::get_user_best_grade_returns(), $result);
509         $this->assertTrue($result['hasgrade']);
510         $this->assertEquals(8.9, $result['grade']);
512         // Invalid user.
513         try {
514             mod_quiz_external::get_user_best_grade($this->quiz->id, -1);
515             $this->fail('Exception expected due to missing capability.');
516         } catch (dml_missing_record_exception $e) {
517             $this->assertEquals('invaliduser', $e->errorcode);
518         }
520         // Remove the created data.
521         $DB->delete_records('quiz_grades', array('id' => $grade->id));
523     }
524     /**
525      * Test get_combined_review_options.
526      * This is a basic test, this is already tested in mod_quiz_display_options_testcase.
527      */
528     public function test_get_combined_review_options() {
529         global $DB;
531         // Create a new quiz with attempts.
532         $quizgenerator = $this->getDataGenerator()->get_plugin_generator('mod_quiz');
533         $data = array('course' => $this->course->id,
534                       'sumgrades' => 1);
535         $quiz = $quizgenerator->create_instance($data);
537         // Create a couple of questions.
538         $questiongenerator = $this->getDataGenerator()->get_plugin_generator('core_question');
540         $cat = $questiongenerator->create_question_category();
541         $question = $questiongenerator->create_question('numerical', null, array('category' => $cat->id));
542         quiz_add_quiz_question($question->id, $quiz);
544         $quizobj = quiz::create($quiz->id, $this->student->id);
546         // Set grade to pass.
547         $item = grade_item::fetch(array('courseid' => $this->course->id, 'itemtype' => 'mod',
548                                         'itemmodule' => 'quiz', 'iteminstance' => $quiz->id, 'outcomeid' => null));
549         $item->gradepass = 80;
550         $item->update();
552         // Start the passing attempt.
553         $quba = question_engine::make_questions_usage_by_activity('mod_quiz', $quizobj->get_context());
554         $quba->set_preferred_behaviour($quizobj->get_quiz()->preferredbehaviour);
556         $timenow = time();
557         $attempt = quiz_create_attempt($quizobj, 1, false, $timenow, false, $this->student->id);
558         quiz_start_new_attempt($quizobj, $quba, $attempt, 1, $timenow);
559         quiz_attempt_save_started($quizobj, $quba, $attempt);
561         $this->setUser($this->student);
563         $result = mod_quiz_external::get_combined_review_options($quiz->id);
564         $result = external_api::clean_returnvalue(mod_quiz_external::get_combined_review_options_returns(), $result);
566         // Expected values.
567         $expected = array(
568             "someoptions" => array(
569                 array("name" => "feedback", "value" => 1),
570                 array("name" => "generalfeedback", "value" => 1),
571                 array("name" => "rightanswer", "value" => 1),
572                 array("name" => "overallfeedback", "value" => 0),
573                 array("name" => "marks", "value" => 2),
574             ),
575             "alloptions" => array(
576                 array("name" => "feedback", "value" => 1),
577                 array("name" => "generalfeedback", "value" => 1),
578                 array("name" => "rightanswer", "value" => 1),
579                 array("name" => "overallfeedback", "value" => 0),
580                 array("name" => "marks", "value" => 2),
581             ),
582             "warnings" => [],
583         );
585         $this->assertEquals($expected, $result);
587         // Now, finish the attempt.
588         $attemptobj = quiz_attempt::create($attempt->id);
589         $attemptobj->process_finish($timenow, false);
591         $expected = array(
592             "someoptions" => array(
593                 array("name" => "feedback", "value" => 1),
594                 array("name" => "generalfeedback", "value" => 1),
595                 array("name" => "rightanswer", "value" => 1),
596                 array("name" => "overallfeedback", "value" => 1),
597                 array("name" => "marks", "value" => 2),
598             ),
599             "alloptions" => array(
600                 array("name" => "feedback", "value" => 1),
601                 array("name" => "generalfeedback", "value" => 1),
602                 array("name" => "rightanswer", "value" => 1),
603                 array("name" => "overallfeedback", "value" => 1),
604                 array("name" => "marks", "value" => 2),
605             ),
606             "warnings" => [],
607         );
609         // We should see now the overall feedback.
610         $result = mod_quiz_external::get_combined_review_options($quiz->id);
611         $result = external_api::clean_returnvalue(mod_quiz_external::get_combined_review_options_returns(), $result);
612         $this->assertEquals($expected, $result);
614         // Start a new attempt, but not finish it.
615         $timenow = time();
616         $attempt = quiz_create_attempt($quizobj, 2, false, $timenow, false, $this->student->id);
617         $quba = question_engine::make_questions_usage_by_activity('mod_quiz', $quizobj->get_context());
618         $quba->set_preferred_behaviour($quizobj->get_quiz()->preferredbehaviour);
619         quiz_start_new_attempt($quizobj, $quba, $attempt, 1, $timenow);
620         quiz_attempt_save_started($quizobj, $quba, $attempt);
622         $expected = array(
623             "someoptions" => array(
624                 array("name" => "feedback", "value" => 1),
625                 array("name" => "generalfeedback", "value" => 1),
626                 array("name" => "rightanswer", "value" => 1),
627                 array("name" => "overallfeedback", "value" => 1),
628                 array("name" => "marks", "value" => 2),
629             ),
630             "alloptions" => array(
631                 array("name" => "feedback", "value" => 1),
632                 array("name" => "generalfeedback", "value" => 1),
633                 array("name" => "rightanswer", "value" => 1),
634                 array("name" => "overallfeedback", "value" => 0),
635                 array("name" => "marks", "value" => 2),
636             ),
637             "warnings" => [],
638         );
640         $result = mod_quiz_external::get_combined_review_options($quiz->id);
641         $result = external_api::clean_returnvalue(mod_quiz_external::get_combined_review_options_returns(), $result);
642         $this->assertEquals($expected, $result);
644         // Teacher, for see student options.
645         $this->setUser($this->teacher);
647         $result = mod_quiz_external::get_combined_review_options($quiz->id, $this->student->id);
648         $result = external_api::clean_returnvalue(mod_quiz_external::get_combined_review_options_returns(), $result);
650         $this->assertEquals($expected, $result);
652         // Invalid user.
653         try {
654             mod_quiz_external::get_combined_review_options($quiz->id, -1);
655             $this->fail('Exception expected due to missing capability.');
656         } catch (dml_missing_record_exception $e) {
657             $this->assertEquals('invaliduser', $e->errorcode);
658         }
659     }
661     /**
662      * Test start_attempt
663      */
664     public function test_start_attempt() {
665         global $DB;
667         // Create a new quiz with questions.
668         list($quiz, $context, $quizobj) = $this->create_quiz_with_questions();
670         $this->setUser($this->student);
672         // Try to open attempt in closed quiz.
673         $quiz->timeopen = time() - WEEKSECS;
674         $quiz->timeclose = time() - DAYSECS;
675         $DB->update_record('quiz', $quiz);
676         $result = mod_quiz_external::start_attempt($quiz->id);
677         $result = external_api::clean_returnvalue(mod_quiz_external::start_attempt_returns(), $result);
679         $this->assertEquals([], $result['attempt']);
680         $this->assertCount(1, $result['warnings']);
682         // Now with a password.
683         $quiz->timeopen = 0;
684         $quiz->timeclose = 0;
685         $quiz->password = 'abc';
686         $DB->update_record('quiz', $quiz);
688         try {
689             mod_quiz_external::start_attempt($quiz->id, array(array("name" => "quizpassword", "value" => 'bad')));
690             $this->fail('Exception expected due to invalid passwod.');
691         } catch (moodle_exception $e) {
692             $this->assertEquals(get_string('passworderror', 'quizaccess_password'), $e->errorcode);
693         }
695         // Now, try everything correct.
696         $result = mod_quiz_external::start_attempt($quiz->id, array(array("name" => "quizpassword", "value" => 'abc')));
697         $result = external_api::clean_returnvalue(mod_quiz_external::start_attempt_returns(), $result);
699         $this->assertEquals(1, $result['attempt']['attempt']);
700         $this->assertEquals($this->student->id, $result['attempt']['userid']);
701         $this->assertEquals($quiz->id, $result['attempt']['quiz']);
702         $this->assertCount(0, $result['warnings']);
703         $attemptid = $result['attempt']['id'];
705         // We are good, try to start a new attempt now.
707         try {
708             mod_quiz_external::start_attempt($quiz->id, array(array("name" => "quizpassword", "value" => 'abc')));
709             $this->fail('Exception expected due to attempt not finished.');
710         } catch (moodle_quiz_exception $e) {
711             $this->assertEquals('attemptstillinprogress', $e->errorcode);
712         }
714         // Finish the started attempt.
716         // Process some responses from the student.
717         $timenow = time();
718         $attemptobj = quiz_attempt::create($attemptid);
719         $tosubmit = array(1 => array('answer' => '3.14'));
720         $attemptobj->process_submitted_actions($timenow, false, $tosubmit);
722         // Finish the attempt.
723         $attemptobj = quiz_attempt::create($attemptid);
724         $this->assertTrue($attemptobj->has_response_to_at_least_one_graded_question());
725         $attemptobj->process_finish($timenow, false);
727         // We should be able to start a new attempt.
728         $result = mod_quiz_external::start_attempt($quiz->id, array(array("name" => "quizpassword", "value" => 'abc')));
729         $result = external_api::clean_returnvalue(mod_quiz_external::start_attempt_returns(), $result);
731         $this->assertEquals(2, $result['attempt']['attempt']);
732         $this->assertEquals($this->student->id, $result['attempt']['userid']);
733         $this->assertEquals($quiz->id, $result['attempt']['quiz']);
734         $this->assertCount(0, $result['warnings']);
736         // Test user with no capabilities.
737         // We need a explicit prohibit since this capability is only defined in authenticated user and guest roles.
738         assign_capability('mod/quiz:attempt', CAP_PROHIBIT, $this->studentrole->id, $context->id);
739         // Empty all the caches that may be affected  by this change.
740         accesslib_clear_all_caches_for_unit_testing();
741         course_modinfo::clear_instance_cache();
743         try {
744             mod_quiz_external::start_attempt($quiz->id);
745             $this->fail('Exception expected due to missing capability.');
746         } catch (required_capability_exception $e) {
747             $this->assertEquals('nopermissions', $e->errorcode);
748         }
750     }
752     /**
753      * Test validate_attempt
754      */
755     public function test_validate_attempt() {
756         global $DB;
758         // Create a new quiz with one attempt started.
759         list($quiz, $context, $quizobj, $attempt, $attemptobj) = $this->create_quiz_with_questions(true);
761         $this->setUser($this->student);
763         // Invalid attempt.
764         try {
765             $params = array('attemptid' => -1, 'page' => 0);
766             testable_mod_quiz_external::validate_attempt($params);
767             $this->fail('Exception expected due to invalid attempt id.');
768         } catch (dml_missing_record_exception $e) {
769             $this->assertEquals('invalidrecord', $e->errorcode);
770         }
772         // Test OK case.
773         $params = array('attemptid' => $attempt->id, 'page' => 0);
774         $result = testable_mod_quiz_external::validate_attempt($params);
775         $this->assertEquals($attempt->id, $result[0]->get_attempt()->id);
776         $this->assertEquals([], $result[1]);
778         // Test with preflight data.
779         $quiz->password = 'abc';
780         $DB->update_record('quiz', $quiz);
782         try {
783             $params = array('attemptid' => $attempt->id, 'page' => 0,
784                             'preflightdata' => array(array("name" => "quizpassword", "value" => 'bad')));
785             testable_mod_quiz_external::validate_attempt($params);
786             $this->fail('Exception expected due to invalid passwod.');
787         } catch (moodle_exception $e) {
788             $this->assertEquals(get_string('passworderror', 'quizaccess_password'), $e->errorcode);
789         }
791         // Now, try everything correct.
792         $params['preflightdata'][0]['value'] = 'abc';
793         $result = testable_mod_quiz_external::validate_attempt($params);
794         $this->assertEquals($attempt->id, $result[0]->get_attempt()->id);
795         $this->assertEquals([], $result[1]);
797         // Page out of range.
798         $DB->update_record('quiz', $quiz);
799         $params['page'] = 4;
800         try {
801             testable_mod_quiz_external::validate_attempt($params);
802             $this->fail('Exception expected due to page out of range.');
803         } catch (moodle_quiz_exception $e) {
804             $this->assertEquals('Invalid page number', $e->errorcode);
805         }
807         $params['page'] = 0;
808         // Try to open attempt in closed quiz.
809         $quiz->timeopen = time() - WEEKSECS;
810         $quiz->timeclose = time() - DAYSECS;
811         $DB->update_record('quiz', $quiz);
813         // This should work, ommit access rules.
814         testable_mod_quiz_external::validate_attempt($params, false);
816         // Get a generic error because prior to checking the dates the attempt is closed.
817         try {
818             testable_mod_quiz_external::validate_attempt($params);
819             $this->fail('Exception expected due to passed dates.');
820         } catch (moodle_quiz_exception $e) {
821             $this->assertEquals('attempterror', $e->errorcode);
822         }
824         // Finish the attempt.
825         $attemptobj = quiz_attempt::create($attempt->id);
826         $attemptobj->process_finish(time(), false);
828         try {
829             testable_mod_quiz_external::validate_attempt($params, false);
830             $this->fail('Exception expected due to attempt finished.');
831         } catch (moodle_quiz_exception $e) {
832             $this->assertEquals('attemptalreadyclosed', $e->errorcode);
833         }
835         // Test user with no capabilities.
836         // We need a explicit prohibit since this capability is only defined in authenticated user and guest roles.
837         assign_capability('mod/quiz:attempt', CAP_PROHIBIT, $this->studentrole->id, $context->id);
838         // Empty all the caches that may be affected  by this change.
839         accesslib_clear_all_caches_for_unit_testing();
840         course_modinfo::clear_instance_cache();
842         try {
843             testable_mod_quiz_external::validate_attempt($params);
844             $this->fail('Exception expected due to missing permissions.');
845         } catch (required_capability_exception $e) {
846             $this->assertEquals('nopermissions', $e->errorcode);
847         }
849         // Now try with a different user.
850         $this->setUser($this->teacher);
852         $params['page'] = 0;
853         try {
854             testable_mod_quiz_external::validate_attempt($params);
855             $this->fail('Exception expected due to not your attempt.');
856         } catch (moodle_quiz_exception $e) {
857             $this->assertEquals('notyourattempt', $e->errorcode);
858         }
859     }
861     /**
862      * Test get_attempt_data
863      */
864     public function test_get_attempt_data() {
865         global $DB;
867         $timenow = time();
868         // Create a new quiz with one attempt started.
869         list($quiz, $context, $quizobj, $attempt, $attemptobj) = $this->create_quiz_with_questions(true);
871         // Set correctness mask so questions state can be fetched only after finishing the attempt.
872         $DB->set_field('quiz', 'reviewcorrectness', mod_quiz_display_options::IMMEDIATELY_AFTER, array('id' => $quiz->id));
874         $quizobj = $attemptobj->get_quizobj();
875         $quizobj->preload_questions();
876         $quizobj->load_questions();
877         $questions = $quizobj->get_questions();
879         $this->setUser($this->student);
881         // We receive one question per page.
882         $result = mod_quiz_external::get_attempt_data($attempt->id, 0);
883         $result = external_api::clean_returnvalue(mod_quiz_external::get_attempt_data_returns(), $result);
885         $this->assertEquals($attempt, (object) $result['attempt']);
886         $this->assertEquals(1, $result['nextpage']);
887         $this->assertCount(0, $result['messages']);
888         $this->assertCount(1, $result['questions']);
889         $this->assertEquals(1, $result['questions'][0]['slot']);
890         $this->assertEquals(1, $result['questions'][0]['number']);
891         $this->assertEquals('numerical', $result['questions'][0]['type']);
892         $this->assertArrayNotHasKey('state', $result['questions'][0]);  // We don't receive the state yet.
893         $this->assertEquals(get_string('notyetanswered', 'question'), $result['questions'][0]['status']);
894         $this->assertFalse($result['questions'][0]['flagged']);
895         $this->assertEquals(0, $result['questions'][0]['page']);
896         $this->assertEmpty($result['questions'][0]['mark']);
897         $this->assertEquals(1, $result['questions'][0]['maxmark']);
898         $this->assertEquals(1, $result['questions'][0]['sequencecheck']);
899         $this->assertGreaterThanOrEqual($timenow, $result['questions'][0]['lastactiontime']);
900         $this->assertEquals(false, $result['questions'][0]['hasautosavedstep']);
902         // Now try the last page.
903         $result = mod_quiz_external::get_attempt_data($attempt->id, 1);
904         $result = external_api::clean_returnvalue(mod_quiz_external::get_attempt_data_returns(), $result);
906         $this->assertEquals($attempt, (object) $result['attempt']);
907         $this->assertEquals(-1, $result['nextpage']);
908         $this->assertCount(0, $result['messages']);
909         $this->assertCount(1, $result['questions']);
910         $this->assertEquals(2, $result['questions'][0]['slot']);
911         $this->assertEquals(2, $result['questions'][0]['number']);
912         $this->assertEquals('numerical', $result['questions'][0]['type']);
913         $this->assertArrayNotHasKey('state', $result['questions'][0]);  // We don't receive the state yet.
914         $this->assertEquals(get_string('notyetanswered', 'question'), $result['questions'][0]['status']);
915         $this->assertFalse($result['questions'][0]['flagged']);
916         $this->assertEquals(1, $result['questions'][0]['page']);
917         $this->assertEquals(1, $result['questions'][0]['sequencecheck']);
918         $this->assertGreaterThanOrEqual($timenow, $result['questions'][0]['lastactiontime']);
919         $this->assertEquals(false, $result['questions'][0]['hasautosavedstep']);
921         // Finish previous attempt.
922         $attemptobj->process_finish(time(), false);
924         // Now we should receive the question state.
925         $result = mod_quiz_external::get_attempt_review($attempt->id, 1);
926         $result = external_api::clean_returnvalue(mod_quiz_external::get_attempt_review_returns(), $result);
927         $this->assertEquals('gaveup', $result['questions'][0]['state']);
929         // Change setting and expect two pages.
930         $quiz->questionsperpage = 4;
931         $DB->update_record('quiz', $quiz);
932         quiz_repaginate_questions($quiz->id, $quiz->questionsperpage);
934         // Start with new attempt with the new layout.
935         $quba = question_engine::make_questions_usage_by_activity('mod_quiz', $quizobj->get_context());
936         $quba->set_preferred_behaviour($quizobj->get_quiz()->preferredbehaviour);
938         $timenow = time();
939         $attempt = quiz_create_attempt($quizobj, 2, false, $timenow, false, $this->student->id);
940         quiz_start_new_attempt($quizobj, $quba, $attempt, 1, $timenow);
941         quiz_attempt_save_started($quizobj, $quba, $attempt);
943         // We receive two questions per page.
944         $result = mod_quiz_external::get_attempt_data($attempt->id, 0);
945         $result = external_api::clean_returnvalue(mod_quiz_external::get_attempt_data_returns(), $result);
946         $this->assertCount(2, $result['questions']);
947         $this->assertEquals(-1, $result['nextpage']);
949         // Check questions looks good.
950         $found = 0;
951         foreach ($questions as $question) {
952             foreach ($result['questions'] as $rquestion) {
953                 if ($rquestion['slot'] == $question->slot) {
954                     $this->assertTrue(strpos($rquestion['html'], "qid=$question->id") !== false);
955                     $found++;
956                 }
957             }
958         }
959         $this->assertEquals(2, $found);
961     }
963     /**
964      * Test get_attempt_data with blocked questions.
965      * @since 3.2
966      */
967     public function test_get_attempt_data_with_blocked_questions() {
968         global $DB;
970         // Create a new quiz with one attempt started and using immediatefeedback.
971         list($quiz, $context, $quizobj, $attempt, $attemptobj) = $this->create_quiz_with_questions(
972                 true, false, 'immediatefeedback');
974         $quizobj = $attemptobj->get_quizobj();
976         // Make second question blocked by the first one.
977         $structure = $quizobj->get_structure();
978         $slots = $structure->get_slots();
979         $structure->update_question_dependency(end($slots)->id, true);
981         $quizobj->preload_questions();
982         $quizobj->load_questions();
983         $questions = $quizobj->get_questions();
985         $this->setUser($this->student);
987         // We receive one question per page.
988         $result = mod_quiz_external::get_attempt_data($attempt->id, 0);
989         $result = external_api::clean_returnvalue(mod_quiz_external::get_attempt_data_returns(), $result);
991         $this->assertEquals($attempt, (object) $result['attempt']);
992         $this->assertCount(1, $result['questions']);
993         $this->assertEquals(1, $result['questions'][0]['slot']);
994         $this->assertEquals(1, $result['questions'][0]['number']);
995         $this->assertEquals(false, $result['questions'][0]['blockedbyprevious']);
997         // Now try the last page.
998         $result = mod_quiz_external::get_attempt_data($attempt->id, 1);
999         $result = external_api::clean_returnvalue(mod_quiz_external::get_attempt_data_returns(), $result);
1001         $this->assertEquals($attempt, (object) $result['attempt']);
1002         $this->assertCount(1, $result['questions']);
1003         $this->assertEquals(2, $result['questions'][0]['slot']);
1004         $this->assertEquals(2, $result['questions'][0]['number']);
1005         $this->assertEquals(true, $result['questions'][0]['blockedbyprevious']);
1006     }
1008     /**
1009      * Test get_attempt_summary
1010      */
1011     public function test_get_attempt_summary() {
1013         $timenow = time();
1014         // Create a new quiz with one attempt started.
1015         list($quiz, $context, $quizobj, $attempt, $attemptobj) = $this->create_quiz_with_questions(true);
1017         $this->setUser($this->student);
1018         $result = mod_quiz_external::get_attempt_summary($attempt->id);
1019         $result = external_api::clean_returnvalue(mod_quiz_external::get_attempt_summary_returns(), $result);
1021         // Check the state, flagged and mark data is correct.
1022         $this->assertEquals('todo', $result['questions'][0]['state']);
1023         $this->assertEquals('todo', $result['questions'][1]['state']);
1024         $this->assertEquals(1, $result['questions'][0]['number']);
1025         $this->assertEquals(2, $result['questions'][1]['number']);
1026         $this->assertFalse($result['questions'][0]['flagged']);
1027         $this->assertFalse($result['questions'][1]['flagged']);
1028         $this->assertEmpty($result['questions'][0]['mark']);
1029         $this->assertEmpty($result['questions'][1]['mark']);
1030         $this->assertEquals(1, $result['questions'][0]['sequencecheck']);
1031         $this->assertEquals(1, $result['questions'][1]['sequencecheck']);
1032         $this->assertGreaterThanOrEqual($timenow, $result['questions'][0]['lastactiontime']);
1033         $this->assertGreaterThanOrEqual($timenow, $result['questions'][1]['lastactiontime']);
1034         $this->assertEquals(false, $result['questions'][0]['hasautosavedstep']);
1035         $this->assertEquals(false, $result['questions'][1]['hasautosavedstep']);
1037         // Check question options.
1038         $this->assertNotEmpty(5, $result['questions'][0]['settings']);
1039         // Check at least some settings returned.
1040         $this->assertCount(4, (array) json_decode($result['questions'][0]['settings']));
1042         // Submit a response for the first question.
1043         $tosubmit = array(1 => array('answer' => '3.14'));
1044         $attemptobj->process_submitted_actions(time(), false, $tosubmit);
1045         $result = mod_quiz_external::get_attempt_summary($attempt->id);
1046         $result = external_api::clean_returnvalue(mod_quiz_external::get_attempt_summary_returns(), $result);
1048         // Check it's marked as completed only the first one.
1049         $this->assertEquals('complete', $result['questions'][0]['state']);
1050         $this->assertEquals('todo', $result['questions'][1]['state']);
1051         $this->assertEquals(1, $result['questions'][0]['number']);
1052         $this->assertEquals(2, $result['questions'][1]['number']);
1053         $this->assertFalse($result['questions'][0]['flagged']);
1054         $this->assertFalse($result['questions'][1]['flagged']);
1055         $this->assertEmpty($result['questions'][0]['mark']);
1056         $this->assertEmpty($result['questions'][1]['mark']);
1057         $this->assertEquals(2, $result['questions'][0]['sequencecheck']);
1058         $this->assertEquals(1, $result['questions'][1]['sequencecheck']);
1059         $this->assertGreaterThanOrEqual($timenow, $result['questions'][0]['lastactiontime']);
1060         $this->assertGreaterThanOrEqual($timenow, $result['questions'][1]['lastactiontime']);
1061         $this->assertEquals(false, $result['questions'][0]['hasautosavedstep']);
1062         $this->assertEquals(false, $result['questions'][1]['hasautosavedstep']);
1064     }
1066     /**
1067      * Test save_attempt
1068      */
1069     public function test_save_attempt() {
1071         $timenow = time();
1072         // Create a new quiz with one attempt started.
1073         list($quiz, $context, $quizobj, $attempt, $attemptobj, $quba) = $this->create_quiz_with_questions(true);
1075         // Response for slot 1.
1076         $prefix = $quba->get_field_prefix(1);
1077         $data = array(
1078             array('name' => 'slots', 'value' => 1),
1079             array('name' => $prefix . ':sequencecheck',
1080                     'value' => $attemptobj->get_question_attempt(1)->get_sequence_check_count()),
1081             array('name' => $prefix . 'answer', 'value' => 1),
1082         );
1084         $this->setUser($this->student);
1086         $result = mod_quiz_external::save_attempt($attempt->id, $data);
1087         $result = external_api::clean_returnvalue(mod_quiz_external::save_attempt_returns(), $result);
1088         $this->assertTrue($result['status']);
1090         // Now, get the summary.
1091         $result = mod_quiz_external::get_attempt_summary($attempt->id);
1092         $result = external_api::clean_returnvalue(mod_quiz_external::get_attempt_summary_returns(), $result);
1094         // Check it's marked as completed only the first one.
1095         $this->assertEquals('complete', $result['questions'][0]['state']);
1096         $this->assertEquals('todo', $result['questions'][1]['state']);
1097         $this->assertEquals(1, $result['questions'][0]['number']);
1098         $this->assertEquals(2, $result['questions'][1]['number']);
1099         $this->assertFalse($result['questions'][0]['flagged']);
1100         $this->assertFalse($result['questions'][1]['flagged']);
1101         $this->assertEmpty($result['questions'][0]['mark']);
1102         $this->assertEmpty($result['questions'][1]['mark']);
1103         $this->assertEquals(1, $result['questions'][0]['sequencecheck']);
1104         $this->assertEquals(1, $result['questions'][1]['sequencecheck']);
1105         $this->assertGreaterThanOrEqual($timenow, $result['questions'][0]['lastactiontime']);
1106         $this->assertGreaterThanOrEqual($timenow, $result['questions'][1]['lastactiontime']);
1107         $this->assertEquals(true, $result['questions'][0]['hasautosavedstep']);
1108         $this->assertEquals(false, $result['questions'][1]['hasautosavedstep']);
1110         // Now, second slot.
1111         $prefix = $quba->get_field_prefix(2);
1112         $data = array(
1113             array('name' => 'slots', 'value' => 2),
1114             array('name' => $prefix . ':sequencecheck',
1115                     'value' => $attemptobj->get_question_attempt(1)->get_sequence_check_count()),
1116             array('name' => $prefix . 'answer', 'value' => 1),
1117         );
1119         $result = mod_quiz_external::save_attempt($attempt->id, $data);
1120         $result = external_api::clean_returnvalue(mod_quiz_external::save_attempt_returns(), $result);
1121         $this->assertTrue($result['status']);
1123         // Now, get the summary.
1124         $result = mod_quiz_external::get_attempt_summary($attempt->id);
1125         $result = external_api::clean_returnvalue(mod_quiz_external::get_attempt_summary_returns(), $result);
1127         // Check it's marked as completed only the first one.
1128         $this->assertEquals('complete', $result['questions'][0]['state']);
1129         $this->assertEquals(1, $result['questions'][0]['sequencecheck']);
1130         $this->assertEquals('complete', $result['questions'][1]['state']);
1131         $this->assertEquals(1, $result['questions'][1]['sequencecheck']);
1133     }
1135     /**
1136      * Test process_attempt
1137      */
1138     public function test_process_attempt() {
1139         global $DB;
1141         $timenow = time();
1142         // Create a new quiz with three questions and one attempt started.
1143         list($quiz, $context, $quizobj, $attempt, $attemptobj, $quba) = $this->create_quiz_with_questions(true, false,
1144             'deferredfeedback', true);
1146         // Response for slot 1.
1147         $prefix = $quba->get_field_prefix(1);
1148         $data = array(
1149             array('name' => 'slots', 'value' => 1),
1150             array('name' => $prefix . ':sequencecheck',
1151                     'value' => $attemptobj->get_question_attempt(1)->get_sequence_check_count()),
1152             array('name' => $prefix . 'answer', 'value' => 1),
1153         );
1155         $this->setUser($this->student);
1157         $result = mod_quiz_external::process_attempt($attempt->id, $data);
1158         $result = external_api::clean_returnvalue(mod_quiz_external::process_attempt_returns(), $result);
1159         $this->assertEquals(quiz_attempt::IN_PROGRESS, $result['state']);
1161         $result = mod_quiz_external::get_attempt_data($attempt->id, 2);
1163         // Now, get the summary.
1164         $result = mod_quiz_external::get_attempt_summary($attempt->id);
1165         $result = external_api::clean_returnvalue(mod_quiz_external::get_attempt_summary_returns(), $result);
1166         $this->assertDebuggingCalled(); // Expect $PAGE->set_url debugging.
1168         // Check it's marked as completed only the first one.
1169         $this->assertEquals('complete', $result['questions'][0]['state']);
1170         $this->assertEquals('todo', $result['questions'][1]['state']);
1171         $this->assertEquals(1, $result['questions'][0]['number']);
1172         $this->assertEquals(2, $result['questions'][1]['number']);
1173         $this->assertFalse($result['questions'][0]['flagged']);
1174         $this->assertFalse($result['questions'][1]['flagged']);
1175         $this->assertEmpty($result['questions'][0]['mark']);
1176         $this->assertEmpty($result['questions'][1]['mark']);
1177         $this->assertEquals(2, $result['questions'][0]['sequencecheck']);
1178         $this->assertEquals(2, $result['questions'][0]['sequencecheck']);
1179         $this->assertGreaterThanOrEqual($timenow, $result['questions'][0]['lastactiontime']);
1180         $this->assertGreaterThanOrEqual($timenow, $result['questions'][0]['lastactiontime']);
1181         $this->assertEquals(false, $result['questions'][0]['hasautosavedstep']);
1182         $this->assertEquals(false, $result['questions'][0]['hasautosavedstep']);
1184         // Now, second slot.
1185         $prefix = $quba->get_field_prefix(2);
1186         $data = array(
1187             array('name' => 'slots', 'value' => 2),
1188             array('name' => $prefix . ':sequencecheck',
1189                     'value' => $attemptobj->get_question_attempt(1)->get_sequence_check_count()),
1190             array('name' => $prefix . 'answer', 'value' => 1),
1191             array('name' => $prefix . ':flagged', 'value' => 1),
1192         );
1194         $result = mod_quiz_external::process_attempt($attempt->id, $data);
1195         $result = external_api::clean_returnvalue(mod_quiz_external::process_attempt_returns(), $result);
1196         $this->assertEquals(quiz_attempt::IN_PROGRESS, $result['state']);
1198         // Now, get the summary.
1199         $result = mod_quiz_external::get_attempt_summary($attempt->id);
1200         $result = external_api::clean_returnvalue(mod_quiz_external::get_attempt_summary_returns(), $result);
1202         // Check it's marked as completed the two first questions.
1203         $this->assertEquals('complete', $result['questions'][0]['state']);
1204         $this->assertEquals('complete', $result['questions'][1]['state']);
1205         $this->assertFalse($result['questions'][0]['flagged']);
1206         $this->assertTrue($result['questions'][1]['flagged']);
1208         // Add files in the attachment response.
1209         $draftitemid = file_get_unused_draft_itemid();
1210         $filerecordinline = array(
1211             'contextid' => context_user::instance($this->student->id)->id,
1212             'component' => 'user',
1213             'filearea'  => 'draft',
1214             'itemid'    => $draftitemid,
1215             'filepath'  => '/',
1216             'filename'  => 'faketxt.txt',
1217         );
1218         $fs = get_file_storage();
1219         $fs->create_file_from_string($filerecordinline, 'fake txt contents 1.');
1221         // Last slot.
1222         $prefix = $quba->get_field_prefix(3);
1223         $data = array(
1224             array('name' => 'slots', 'value' => 3),
1225             array('name' => $prefix . ':sequencecheck',
1226                     'value' => $attemptobj->get_question_attempt(1)->get_sequence_check_count()),
1227             array('name' => $prefix . 'answer', 'value' => 'Some test'),
1228             array('name' => $prefix . 'answerformat', 'value' => FORMAT_HTML),
1229             array('name' => $prefix . 'attachments', 'value' => $draftitemid),
1230         );
1232         $result = mod_quiz_external::process_attempt($attempt->id, $data);
1233         $result = external_api::clean_returnvalue(mod_quiz_external::process_attempt_returns(), $result);
1234         $this->assertEquals(quiz_attempt::IN_PROGRESS, $result['state']);
1236         // Now, get the summary.
1237         $result = mod_quiz_external::get_attempt_summary($attempt->id);
1238         $result = external_api::clean_returnvalue(mod_quiz_external::get_attempt_summary_returns(), $result);
1240         $this->assertEquals('complete', $result['questions'][0]['state']);
1241         $this->assertEquals('complete', $result['questions'][1]['state']);
1242         $this->assertEquals('complete', $result['questions'][2]['state']);
1243         $this->assertFalse($result['questions'][0]['flagged']);
1244         $this->assertTrue($result['questions'][1]['flagged']);
1245         $this->assertFalse($result['questions'][2]['flagged']);
1247         // Check submitted files are there.
1248         $this->assertCount(1, $result['questions'][2]['responsefileareas']);
1249         $this->assertEquals('attachments', $result['questions'][2]['responsefileareas'][0]['area']);
1250         $this->assertCount(1, $result['questions'][2]['responsefileareas'][0]['files']);
1251         $this->assertEquals($filerecordinline['filename'], $result['questions'][2]['responsefileareas'][0]['files'][0]['filename']);
1253         // Finish the attempt.
1254         $sink = $this->redirectMessages();
1255         $result = mod_quiz_external::process_attempt($attempt->id, array(), true);
1256         $result = external_api::clean_returnvalue(mod_quiz_external::process_attempt_returns(), $result);
1257         $this->assertEquals(quiz_attempt::FINISHED, $result['state']);
1258         $messages = $sink->get_messages();
1259         $message = reset($messages);
1260         $sink->close();
1261         // Test customdata.
1262         if (!empty($message->customdata)) {
1263             $customdata = json_decode($message->customdata);
1264             $this->assertEquals($quizobj->get_quizid(), $customdata->instance);
1265             $this->assertEquals($quizobj->get_cmid(), $customdata->cmid);
1266             $this->assertEquals($attempt->id, $customdata->attemptid);
1267             $this->assertObjectHasAttribute('notificationiconurl', $customdata);
1268         }
1270         // Start new attempt.
1271         $quba = question_engine::make_questions_usage_by_activity('mod_quiz', $quizobj->get_context());
1272         $quba->set_preferred_behaviour($quizobj->get_quiz()->preferredbehaviour);
1274         $timenow = time();
1275         $attempt = quiz_create_attempt($quizobj, 2, false, $timenow, false, $this->student->id);
1276         quiz_start_new_attempt($quizobj, $quba, $attempt, 2, $timenow);
1277         quiz_attempt_save_started($quizobj, $quba, $attempt);
1279         // Force grace period, attempt going to overdue.
1280         $quiz->timeclose = $timenow - 10;
1281         $quiz->graceperiod = 60;
1282         $quiz->overduehandling = 'graceperiod';
1283         $DB->update_record('quiz', $quiz);
1285         $result = mod_quiz_external::process_attempt($attempt->id, array());
1286         $result = external_api::clean_returnvalue(mod_quiz_external::process_attempt_returns(), $result);
1287         $this->assertEquals(quiz_attempt::OVERDUE, $result['state']);
1289         // Force grace period for time limit.
1290         $quiz->timeclose = 0;
1291         $quiz->timelimit = 1;
1292         $quiz->graceperiod = 60;
1293         $quiz->overduehandling = 'graceperiod';
1294         $DB->update_record('quiz', $quiz);
1296         $timenow = time();
1297         $quba = question_engine::make_questions_usage_by_activity('mod_quiz', $quizobj->get_context());
1298         $quba->set_preferred_behaviour($quizobj->get_quiz()->preferredbehaviour);
1299         $attempt = quiz_create_attempt($quizobj, 3, 2, $timenow - 10, false, $this->student->id);
1300         quiz_start_new_attempt($quizobj, $quba, $attempt, 2, $timenow - 10);
1301         quiz_attempt_save_started($quizobj, $quba, $attempt);
1303         $result = mod_quiz_external::process_attempt($attempt->id, array());
1304         $result = external_api::clean_returnvalue(mod_quiz_external::process_attempt_returns(), $result);
1305         $this->assertEquals(quiz_attempt::OVERDUE, $result['state']);
1307         // New attempt.
1308         $timenow = time();
1309         $quba = question_engine::make_questions_usage_by_activity('mod_quiz', $quizobj->get_context());
1310         $quba->set_preferred_behaviour($quizobj->get_quiz()->preferredbehaviour);
1311         $attempt = quiz_create_attempt($quizobj, 4, 3, $timenow, false, $this->student->id);
1312         quiz_start_new_attempt($quizobj, $quba, $attempt, 3, $timenow);
1313         quiz_attempt_save_started($quizobj, $quba, $attempt);
1315         // Force abandon.
1316         $quiz->timeclose = $timenow - HOURSECS;
1317         $DB->update_record('quiz', $quiz);
1319         $result = mod_quiz_external::process_attempt($attempt->id, array());
1320         $result = external_api::clean_returnvalue(mod_quiz_external::process_attempt_returns(), $result);
1321         $this->assertEquals(quiz_attempt::ABANDONED, $result['state']);
1323     }
1325     /**
1326      * Test validate_attempt_review
1327      */
1328     public function test_validate_attempt_review() {
1329         global $DB;
1331         // Create a new quiz with one attempt started.
1332         list($quiz, $context, $quizobj, $attempt, $attemptobj) = $this->create_quiz_with_questions(true);
1334         $this->setUser($this->student);
1336         // Invalid attempt, invalid id.
1337         try {
1338             $params = array('attemptid' => -1);
1339             testable_mod_quiz_external::validate_attempt_review($params);
1340             $this->fail('Exception expected due invalid id.');
1341         } catch (dml_missing_record_exception $e) {
1342             $this->assertEquals('invalidrecord', $e->errorcode);
1343         }
1345         // Invalid attempt, not closed.
1346         try {
1347             $params = array('attemptid' => $attempt->id);
1348             testable_mod_quiz_external::validate_attempt_review($params);
1349             $this->fail('Exception expected due not closed attempt.');
1350         } catch (moodle_quiz_exception $e) {
1351             $this->assertEquals('attemptclosed', $e->errorcode);
1352         }
1354         // Test ok case (finished attempt).
1355         list($quiz, $context, $quizobj, $attempt, $attemptobj) = $this->create_quiz_with_questions(true, true);
1357         $params = array('attemptid' => $attempt->id);
1358         testable_mod_quiz_external::validate_attempt_review($params);
1360         // Teacher should be able to view the review of one student's attempt.
1361         $this->setUser($this->teacher);
1362         testable_mod_quiz_external::validate_attempt_review($params);
1364         // We should not see other students attempts.
1365         $anotherstudent = self::getDataGenerator()->create_user();
1366         $this->getDataGenerator()->enrol_user($anotherstudent->id, $this->course->id, $this->studentrole->id, 'manual');
1368         $this->setUser($anotherstudent);
1369         try {
1370             $params = array('attemptid' => $attempt->id);
1371             testable_mod_quiz_external::validate_attempt_review($params);
1372             $this->fail('Exception expected due missing permissions.');
1373         } catch (moodle_quiz_exception $e) {
1374             $this->assertEquals('noreviewattempt', $e->errorcode);
1375         }
1376     }
1379     /**
1380      * Test get_attempt_review
1381      */
1382     public function test_get_attempt_review() {
1383         global $DB;
1385         // Create a new quiz with two questions and one attempt finished.
1386         list($quiz, $context, $quizobj, $attempt, $attemptobj, $quba) = $this->create_quiz_with_questions(true, true);
1388         // Add feedback to the quiz.
1389         $feedback = new stdClass();
1390         $feedback->quizid = $quiz->id;
1391         $feedback->feedbacktext = 'Feedback text 1';
1392         $feedback->feedbacktextformat = 1;
1393         $feedback->mingrade = 49;
1394         $feedback->maxgrade = 100;
1395         $feedback->id = $DB->insert_record('quiz_feedback', $feedback);
1397         $feedback->feedbacktext = 'Feedback text 2';
1398         $feedback->feedbacktextformat = 1;
1399         $feedback->mingrade = 30;
1400         $feedback->maxgrade = 48;
1401         $feedback->id = $DB->insert_record('quiz_feedback', $feedback);
1403         $result = mod_quiz_external::get_attempt_review($attempt->id);
1404         $result = external_api::clean_returnvalue(mod_quiz_external::get_attempt_review_returns(), $result);
1406         // Two questions, one completed and correct, the other gave up.
1407         $this->assertEquals(50, $result['grade']);
1408         $this->assertEquals(1, $result['attempt']['attempt']);
1409         $this->assertEquals('finished', $result['attempt']['state']);
1410         $this->assertEquals(1, $result['attempt']['sumgrades']);
1411         $this->assertCount(2, $result['questions']);
1412         $this->assertEquals('gradedright', $result['questions'][0]['state']);
1413         $this->assertEquals(1, $result['questions'][0]['slot']);
1414         $this->assertEquals('gaveup', $result['questions'][1]['state']);
1415         $this->assertEquals(2, $result['questions'][1]['slot']);
1417         $this->assertCount(1, $result['additionaldata']);
1418         $this->assertEquals('feedback', $result['additionaldata'][0]['id']);
1419         $this->assertEquals('Feedback', $result['additionaldata'][0]['title']);
1420         $this->assertEquals('Feedback text 1', $result['additionaldata'][0]['content']);
1422         // Only first page.
1423         $result = mod_quiz_external::get_attempt_review($attempt->id, 0);
1424         $result = external_api::clean_returnvalue(mod_quiz_external::get_attempt_review_returns(), $result);
1426         $this->assertEquals(50, $result['grade']);
1427         $this->assertEquals(1, $result['attempt']['attempt']);
1428         $this->assertEquals('finished', $result['attempt']['state']);
1429         $this->assertEquals(1, $result['attempt']['sumgrades']);
1430         $this->assertCount(1, $result['questions']);
1431         $this->assertEquals('gradedright', $result['questions'][0]['state']);
1432         $this->assertEquals(1, $result['questions'][0]['slot']);
1434          $this->assertCount(1, $result['additionaldata']);
1435         $this->assertEquals('feedback', $result['additionaldata'][0]['id']);
1436         $this->assertEquals('Feedback', $result['additionaldata'][0]['title']);
1437         $this->assertEquals('Feedback text 1', $result['additionaldata'][0]['content']);
1439     }
1441     /**
1442      * Test test_view_attempt
1443      */
1444     public function test_view_attempt() {
1445         global $DB;
1447         // Create a new quiz with two questions and one attempt started.
1448         list($quiz, $context, $quizobj, $attempt, $attemptobj, $quba) = $this->create_quiz_with_questions(true, false);
1450         // Test user with full capabilities.
1451         $this->setUser($this->student);
1453         // Trigger and capture the event.
1454         $sink = $this->redirectEvents();
1456         $result = mod_quiz_external::view_attempt($attempt->id, 0);
1457         $result = external_api::clean_returnvalue(mod_quiz_external::view_attempt_returns(), $result);
1458         $this->assertTrue($result['status']);
1460         $events = $sink->get_events();
1461         $this->assertCount(1, $events);
1462         $event = array_shift($events);
1464         // Checking that the event contains the expected values.
1465         $this->assertInstanceOf('\mod_quiz\event\attempt_viewed', $event);
1466         $this->assertEquals($context, $event->get_context());
1467         $this->assertEventContextNotUsed($event);
1468         $this->assertNotEmpty($event->get_name());
1470         // Now, force the quiz with QUIZ_NAVMETHOD_SEQ (sequencial) navigation method.
1471         $DB->set_field('quiz', 'navmethod', QUIZ_NAVMETHOD_SEQ, array('id' => $quiz->id));
1472         // Quiz requiring preflightdata.
1473         $DB->set_field('quiz', 'password', 'abcdef', array('id' => $quiz->id));
1474         $preflightdata = array(array("name" => "quizpassword", "value" => 'abcdef'));
1476         // See next page.
1477         $result = mod_quiz_external::view_attempt($attempt->id, 1, $preflightdata);
1478         $result = external_api::clean_returnvalue(mod_quiz_external::view_attempt_returns(), $result);
1479         $this->assertTrue($result['status']);
1481         $events = $sink->get_events();
1482         $this->assertCount(2, $events);
1484         // Try to go to previous page.
1485         try {
1486             mod_quiz_external::view_attempt($attempt->id, 0);
1487             $this->fail('Exception expected due to try to see a previous page.');
1488         } catch (moodle_quiz_exception $e) {
1489             $this->assertEquals('Out of sequence access', $e->errorcode);
1490         }
1492     }
1494     /**
1495      * Test test_view_attempt_summary
1496      */
1497     public function test_view_attempt_summary() {
1498         global $DB;
1500         // Create a new quiz with two questions and one attempt started.
1501         list($quiz, $context, $quizobj, $attempt, $attemptobj, $quba) = $this->create_quiz_with_questions(true, false);
1503         // Test user with full capabilities.
1504         $this->setUser($this->student);
1506         // Trigger and capture the event.
1507         $sink = $this->redirectEvents();
1509         $result = mod_quiz_external::view_attempt_summary($attempt->id);
1510         $result = external_api::clean_returnvalue(mod_quiz_external::view_attempt_summary_returns(), $result);
1511         $this->assertTrue($result['status']);
1513         $events = $sink->get_events();
1514         $this->assertCount(1, $events);
1515         $event = array_shift($events);
1517         // Checking that the event contains the expected values.
1518         $this->assertInstanceOf('\mod_quiz\event\attempt_summary_viewed', $event);
1519         $this->assertEquals($context, $event->get_context());
1520         $moodlequiz = new \moodle_url('/mod/quiz/summary.php', array('attempt' => $attempt->id));
1521         $this->assertEquals($moodlequiz, $event->get_url());
1522         $this->assertEventContextNotUsed($event);
1523         $this->assertNotEmpty($event->get_name());
1525         // Quiz requiring preflightdata.
1526         $DB->set_field('quiz', 'password', 'abcdef', array('id' => $quiz->id));
1527         $preflightdata = array(array("name" => "quizpassword", "value" => 'abcdef'));
1529         $result = mod_quiz_external::view_attempt_summary($attempt->id, $preflightdata);
1530         $result = external_api::clean_returnvalue(mod_quiz_external::view_attempt_summary_returns(), $result);
1531         $this->assertTrue($result['status']);
1533     }
1535     /**
1536      * Test test_view_attempt_summary
1537      */
1538     public function test_view_attempt_review() {
1539         global $DB;
1541         // Create a new quiz with two questions and one attempt finished.
1542         list($quiz, $context, $quizobj, $attempt, $attemptobj, $quba) = $this->create_quiz_with_questions(true, true);
1544         // Test user with full capabilities.
1545         $this->setUser($this->student);
1547         // Trigger and capture the event.
1548         $sink = $this->redirectEvents();
1550         $result = mod_quiz_external::view_attempt_review($attempt->id, 0);
1551         $result = external_api::clean_returnvalue(mod_quiz_external::view_attempt_review_returns(), $result);
1552         $this->assertTrue($result['status']);
1554         $events = $sink->get_events();
1555         $this->assertCount(1, $events);
1556         $event = array_shift($events);
1558         // Checking that the event contains the expected values.
1559         $this->assertInstanceOf('\mod_quiz\event\attempt_reviewed', $event);
1560         $this->assertEquals($context, $event->get_context());
1561         $moodlequiz = new \moodle_url('/mod/quiz/review.php', array('attempt' => $attempt->id));
1562         $this->assertEquals($moodlequiz, $event->get_url());
1563         $this->assertEventContextNotUsed($event);
1564         $this->assertNotEmpty($event->get_name());
1566     }
1568     /**
1569      * Test get_quiz_feedback_for_grade
1570      */
1571     public function test_get_quiz_feedback_for_grade() {
1572         global $DB;
1574         // Add feedback to the quiz.
1575         $feedback = new stdClass();
1576         $feedback->quizid = $this->quiz->id;
1577         $feedback->feedbacktext = 'Feedback text 1';
1578         $feedback->feedbacktextformat = 1;
1579         $feedback->mingrade = 49;
1580         $feedback->maxgrade = 100;
1581         $feedback->id = $DB->insert_record('quiz_feedback', $feedback);
1582         // Add a fake inline image to the feedback text.
1583         $filename = 'shouldbeanimage.jpg';
1584         $filerecordinline = array(
1585             'contextid' => $this->context->id,
1586             'component' => 'mod_quiz',
1587             'filearea'  => 'feedback',
1588             'itemid'    => $feedback->id,
1589             'filepath'  => '/',
1590             'filename'  => $filename,
1591         );
1592         $fs = get_file_storage();
1593         $fs->create_file_from_string($filerecordinline, 'image contents (not really)');
1595         $feedback->feedbacktext = 'Feedback text 2';
1596         $feedback->feedbacktextformat = 1;
1597         $feedback->mingrade = 30;
1598         $feedback->maxgrade = 49;
1599         $feedback->id = $DB->insert_record('quiz_feedback', $feedback);
1601         $result = mod_quiz_external::get_quiz_feedback_for_grade($this->quiz->id, 50);
1602         $result = external_api::clean_returnvalue(mod_quiz_external::get_quiz_feedback_for_grade_returns(), $result);
1603         $this->assertEquals('Feedback text 1', $result['feedbacktext']);
1604         $this->assertEquals($filename, $result['feedbackinlinefiles'][0]['filename']);
1605         $this->assertEquals(FORMAT_HTML, $result['feedbacktextformat']);
1607         $result = mod_quiz_external::get_quiz_feedback_for_grade($this->quiz->id, 30);
1608         $result = external_api::clean_returnvalue(mod_quiz_external::get_quiz_feedback_for_grade_returns(), $result);
1609         $this->assertEquals('Feedback text 2', $result['feedbacktext']);
1610         $this->assertEquals(FORMAT_HTML, $result['feedbacktextformat']);
1612         $result = mod_quiz_external::get_quiz_feedback_for_grade($this->quiz->id, 10);
1613         $result = external_api::clean_returnvalue(mod_quiz_external::get_quiz_feedback_for_grade_returns(), $result);
1614         $this->assertEquals('', $result['feedbacktext']);
1615         $this->assertEquals(FORMAT_MOODLE, $result['feedbacktextformat']);
1616     }
1618     /**
1619      * Test get_quiz_access_information
1620      */
1621     public function test_get_quiz_access_information() {
1622         global $DB;
1624         // Create a new quiz.
1625         $quizgenerator = $this->getDataGenerator()->get_plugin_generator('mod_quiz');
1626         $data = array('course' => $this->course->id);
1627         $quiz = $quizgenerator->create_instance($data);
1629         $this->setUser($this->student);
1631         // Default restrictions (none).
1632         $result = mod_quiz_external::get_quiz_access_information($quiz->id);
1633         $result = external_api::clean_returnvalue(mod_quiz_external::get_quiz_access_information_returns(), $result);
1635         $expected = array(
1636             'canattempt' => true,
1637             'canmanage' => false,
1638             'canpreview' => false,
1639             'canreviewmyattempts' => true,
1640             'canviewreports' => false,
1641             'accessrules' => [],
1642             // This rule is always used, even if the quiz has no open or close date.
1643             'activerulenames' => ['quizaccess_openclosedate'],
1644             'preventaccessreasons' => [],
1645             'warnings' => []
1646         );
1648         $this->assertEquals($expected, $result);
1650         // Now teacher, different privileges.
1651         $this->setUser($this->teacher);
1652         $result = mod_quiz_external::get_quiz_access_information($quiz->id);
1653         $result = external_api::clean_returnvalue(mod_quiz_external::get_quiz_access_information_returns(), $result);
1655         $expected['canmanage'] = true;
1656         $expected['canpreview'] = true;
1657         $expected['canviewreports'] = true;
1658         $expected['canattempt'] = false;
1659         $expected['canreviewmyattempts'] = false;
1661         $this->assertEquals($expected, $result);
1663         $this->setUser($this->student);
1664         // Now add some restrictions.
1665         $quiz->timeopen = time() + DAYSECS;
1666         $quiz->timeclose = time() + WEEKSECS;
1667         $quiz->password = '123456';
1668         $DB->update_record('quiz', $quiz);
1670         $result = mod_quiz_external::get_quiz_access_information($quiz->id);
1671         $result = external_api::clean_returnvalue(mod_quiz_external::get_quiz_access_information_returns(), $result);
1673         // Access limited by time and password.
1674         $this->assertCount(3, $result['accessrules']);
1675         // Two rule names, password and open/close date.
1676         $this->assertCount(2, $result['activerulenames']);
1677         $this->assertCount(1, $result['preventaccessreasons']);
1679     }
1681     /**
1682      * Test get_attempt_access_information
1683      */
1684     public function test_get_attempt_access_information() {
1685         global $DB;
1687         $this->setAdminUser();
1689         // Create a new quiz with attempts.
1690         $quizgenerator = $this->getDataGenerator()->get_plugin_generator('mod_quiz');
1691         $data = array('course' => $this->course->id,
1692                       'sumgrades' => 2);
1693         $quiz = $quizgenerator->create_instance($data);
1695         // Create some questions.
1696         $questiongenerator = $this->getDataGenerator()->get_plugin_generator('core_question');
1698         $cat = $questiongenerator->create_question_category();
1699         $question = $questiongenerator->create_question('numerical', null, array('category' => $cat->id));
1700         quiz_add_quiz_question($question->id, $quiz);
1702         $question = $questiongenerator->create_question('shortanswer', null, array('category' => $cat->id));
1703         quiz_add_quiz_question($question->id, $quiz);
1705         // Add new question types in the category (for the random one).
1706         $question = $questiongenerator->create_question('truefalse', null, array('category' => $cat->id));
1707         $question = $questiongenerator->create_question('essay', null, array('category' => $cat->id));
1709         quiz_add_random_questions($quiz, 0, $cat->id, 1, false);
1711         $quizobj = quiz::create($quiz->id, $this->student->id);
1713         // Set grade to pass.
1714         $item = grade_item::fetch(array('courseid' => $this->course->id, 'itemtype' => 'mod',
1715                                         'itemmodule' => 'quiz', 'iteminstance' => $quiz->id, 'outcomeid' => null));
1716         $item->gradepass = 80;
1717         $item->update();
1719         $this->setUser($this->student);
1721         // Default restrictions (none).
1722         $result = mod_quiz_external::get_attempt_access_information($quiz->id);
1723         $result = external_api::clean_returnvalue(mod_quiz_external::get_attempt_access_information_returns(), $result);
1725         $expected = array(
1726             'isfinished' => false,
1727             'preventnewattemptreasons' => [],
1728             'warnings' => []
1729         );
1731         $this->assertEquals($expected, $result);
1733         // Limited attempts.
1734         $quiz->attempts = 1;
1735         $DB->update_record('quiz', $quiz);
1737         // Now, do one attempt.
1738         $quba = question_engine::make_questions_usage_by_activity('mod_quiz', $quizobj->get_context());
1739         $quba->set_preferred_behaviour($quizobj->get_quiz()->preferredbehaviour);
1741         $timenow = time();
1742         $attempt = quiz_create_attempt($quizobj, 1, false, $timenow, false, $this->student->id);
1743         quiz_start_new_attempt($quizobj, $quba, $attempt, 1, $timenow);
1744         quiz_attempt_save_started($quizobj, $quba, $attempt);
1746         // Process some responses from the student.
1747         $attemptobj = quiz_attempt::create($attempt->id);
1748         $tosubmit = array(1 => array('answer' => '3.14'));
1749         $attemptobj->process_submitted_actions($timenow, false, $tosubmit);
1751         // Finish the attempt.
1752         $attemptobj = quiz_attempt::create($attempt->id);
1753         $this->assertTrue($attemptobj->has_response_to_at_least_one_graded_question());
1754         $attemptobj->process_finish($timenow, false);
1756         // Can we start a new attempt? We shall not!
1757         $result = mod_quiz_external::get_attempt_access_information($quiz->id, $attempt->id);
1758         $result = external_api::clean_returnvalue(mod_quiz_external::get_attempt_access_information_returns(), $result);
1760         // Now new attemps allowed.
1761         $this->assertCount(1, $result['preventnewattemptreasons']);
1762         $this->assertFalse($result['ispreflightcheckrequired']);
1763         $this->assertEquals(get_string('nomoreattempts', 'quiz'), $result['preventnewattemptreasons'][0]);
1765     }
1767     /**
1768      * Test get_quiz_required_qtypes
1769      */
1770     public function test_get_quiz_required_qtypes() {
1771         $this->setAdminUser();
1773         // Create a new quiz.
1774         $quizgenerator = $this->getDataGenerator()->get_plugin_generator('mod_quiz');
1775         $data = array('course' => $this->course->id);
1776         $quiz = $quizgenerator->create_instance($data);
1778         // Create some questions.
1779         $questiongenerator = $this->getDataGenerator()->get_plugin_generator('core_question');
1781         $cat = $questiongenerator->create_question_category();
1782         $question = $questiongenerator->create_question('numerical', null, array('category' => $cat->id));
1783         quiz_add_quiz_question($question->id, $quiz);
1785         $question = $questiongenerator->create_question('shortanswer', null, array('category' => $cat->id));
1786         quiz_add_quiz_question($question->id, $quiz);
1788         // Add new question types in the category (for the random one).
1789         $question = $questiongenerator->create_question('truefalse', null, array('category' => $cat->id));
1790         $question = $questiongenerator->create_question('essay', null, array('category' => $cat->id));
1792         quiz_add_random_questions($quiz, 0, $cat->id, 1, false);
1794         $this->setUser($this->student);
1796         $result = mod_quiz_external::get_quiz_required_qtypes($quiz->id);
1797         $result = external_api::clean_returnvalue(mod_quiz_external::get_quiz_required_qtypes_returns(), $result);
1799         $expected = array(
1800             'questiontypes' => ['essay', 'numerical', 'random', 'shortanswer', 'truefalse'],
1801             'warnings' => []
1802         );
1804         $this->assertEquals($expected, $result);
1806     }