MDL-69823 mod_quiz: Return question options via WS
[moodle.git] / mod / quiz / tests / external_test.php
CommitLineData
51e27aac
JL
1<?php
2// This file is part of Moodle - http://moodle.org/
3//
4// Moodle is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// Moodle is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
16
17/**
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 */
26
27defined('MOODLE_INTERNAL') || die();
28
29global $CFG;
30
31require_once($CFG->dirroot . '/webservice/tests/helpers.php');
32
4c08658a
JL
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 */
41class testable_mod_quiz_external extends mod_quiz_external {
42
43 /**
44 * Public accessor.
45 *
46 * @param array $params Array of parameters including the attemptid and preflight data
98e68690
JL
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
4c08658a
JL
49 * @return array containing the attempt object and access messages
50 */
98e68690
JL
51 public static function validate_attempt($params, $checkaccessrules = true, $failifoverdue = true) {
52 return parent::validate_attempt($params, $checkaccessrules, $failifoverdue);
4c08658a 53 }
3589b659
JL
54
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 }
4c08658a
JL
64}
65
51e27aac
JL
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 */
75class mod_quiz_external_testcase extends externallib_advanced_testcase {
76
77 /**
78 * Set up for every test
79 */
d81a9480 80 public function setUp(): void {
51e27aac
JL
81 global $DB;
82 $this->resetAfterTest();
83 $this->setAdminUser();
84
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);
90
91 // Create users.
92 $this->student = self::getDataGenerator()->create_user();
93 $this->teacher = self::getDataGenerator()->create_user();
94
95 // Users enrolments.
96 $this->studentrole = $DB->get_record('role', array('shortname' => 'student'));
97 $this->teacherrole = $DB->get_record('role', array('shortname' => 'editingteacher'));
36fa0ec9
JL
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);
101
51e27aac
JL
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 }
105
4c08658a
JL
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
33ef5cdc 111 * @param string $behaviour the quiz preferredbehaviour, defaults to 'deferredfeedback'.
e49ccc92 112 * @param boolean $includeqattachments whether to include a question that supports attachments, defaults to false.
4c08658a
JL
113 * @return array array containing the quiz, context and the attempt
114 */
e49ccc92
JL
115 private function create_quiz_with_questions($startattempt = false, $finishattempt = false, $behaviour = 'deferredfeedback',
116 $includeqattachments = false) {
4c08658a
JL
117
118 // Create a new quiz with attempts.
119 $quizgenerator = $this->getDataGenerator()->get_plugin_generator('mod_quiz');
120 $data = array('course' => $this->course->id,
33ef5cdc
DP
121 'sumgrades' => 2,
122 'preferredbehaviour' => $behaviour);
4c08658a
JL
123 $quiz = $quizgenerator->create_instance($data);
124 $context = context_module::instance($quiz->cmid);
125
126 // Create a couple of questions.
127 $questiongenerator = $this->getDataGenerator()->get_plugin_generator('core_question');
128
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);
134
e49ccc92
JL
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 }
140
4c08658a
JL
141 $quizobj = quiz::create($quiz->id, $this->student->id);
142
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();
148
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);
153
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);
159
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);
164
165 // Finish the attempt.
166 $attemptobj->process_finish(time(), false);
167 }
96d5607c 168 return array($quiz, $context, $quizobj, $attempt, $attemptobj, $quba);
4c08658a
JL
169 } else {
170 return array($quiz, $context, $quizobj);
171 }
172
173 }
174
51e27aac
JL
175 /*
176 * Test get quizzes by courses
177 */
178 public function test_mod_quiz_get_quizzes_by_courses() {
179 global $DB;
180
181 // Create additional course.
182 $course2 = self::getDataGenerator()->create_course();
183
184 // Second quiz.
185 $record = new stdClass();
186 $record->course = $course2->id;
dfd48815 187 $record->intro = '<button>Test with HTML allowed.</button>';
51e27aac
JL
188 $quiz2 = self::getDataGenerator()->create_module('quiz', $record);
189
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);
200
201 self::setUser($this->student);
202
203 $returndescription = mod_quiz_external::get_quizzes_by_courses_returns();
204
205 // Create what we expect to be returned when querying the two courses.
206 // First for the student user.
7ef49bd3 207 $allusersfields = array('id', 'coursemodule', 'course', 'name', 'intro', 'introformat', 'introfiles', 'timeopen',
bcd6249d
JL
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',
51e27aac 212 'reviewspecificfeedback', 'reviewgeneralfeedback', 'reviewrightanswer',
bcd6249d 213 'reviewoverallfeedback', 'questionsperpage', 'navmethod',
51e27aac
JL
214 'browsersecurity', 'delay1', 'delay2', 'showuserpicture', 'showblocks',
215 'completionattemptsexhausted', 'completionpass', 'autosaveperiod', 'hasquestions',
bcd6249d 216 'overduehandling', 'graceperiod', 'canredoquestions', 'allowofflineattempts');
51e27aac
JL
217 $managerfields = array('shuffleanswers', 'timecreated', 'timemodified', 'password', 'subnet');
218
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');
7ef49bd3 230 $quiz1->introfiles = [];
51e27aac
JL
231
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');
7ef49bd3 241 $quiz2->introfiles = [];
51e27aac
JL
242
243 foreach (array_merge($allusersfields, $userswithaccessfields) as $field) {
244 $expected1[$field] = $quiz1->{$field};
245 $expected2[$field] = $quiz2->{$field};
246 }
247
248 $expectedquizzes = array($expected2, $expected1);
249
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);
253
254 $this->assertEquals($expectedquizzes, $result['quizzes']);
255 $this->assertCount(0, $result['warnings']);
256
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']);
262
263 // Unenrol user from second course and alter expected quizzes.
264 $enrol->unenrol_user($instance2, $this->student->id);
265 array_shift($expectedquizzes);
266
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']);
271
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']);
277
278 // Now, try as a teacher for getting all the additional fields.
279 self::setUser($this->teacher);
280
281 foreach ($managerfields as $field) {
282 $expectedquizzes[0][$field] = $quiz1->{$field};
283 }
284
285 $result = mod_quiz_external::get_quizzes_by_courses();
286 $result = external_api::clean_returnvalue($returndescription, $result);
287 $this->assertEquals($expectedquizzes, $result['quizzes']);
288
289 // Admin also should get all the information.
290 self::setAdminUser();
291
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']);
295
296 // Now, prevent access.
297 $enrol->enrol_user($instance2, $this->student->id);
298
299 self::setUser($this->student);
300
301 $quiz2->timeclose = time() - DAYSECS;
302 $DB->update_record('quiz', $quiz2);
303
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']);
314
315 $this->assertFalse(isset($result['quizzes'][0]['timelimit']));
316
317 }
318
4064dd0e
JL
319 /**
320 * Test test_view_quiz
321 */
322 public function test_view_quiz() {
323 global $DB;
324
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 }
332
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 }
342
343 // Test user with full capabilities.
344 $this->setUser($this->student);
345
346 // Trigger and capture the event.
347 $sink = $this->redirectEvents();
348
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']);
352
353 $events = $sink->get_events();
354 $this->assertCount(1, $events);
355 $event = array_shift($events);
356
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());
364
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();
371
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 }
378
379 }
380
c161ecff
JL
381 /**
382 * Test get_user_attempts
383 */
384 public function test_get_user_attempts() {
385
4c08658a
JL
386 // Create a quiz with one attempt finished.
387 list($quiz, $context, $quizobj, $attempt, $attemptobj) = $this->create_quiz_with_questions(true, true);
c161ecff
JL
388
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);
392
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']);
398
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);
402
403 $this->assertCount(1, $result['attempts']);
404 $this->assertEquals($attempt->id, $result['attempts'][0]['id']);
405
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);
409
410 $this->assertCount(1, $result['attempts']);
411 $this->assertEquals($attempt->id, $result['attempts'][0]['id']);
412
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);
416
417 $this->assertCount(0, $result['attempts']);
418
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);
424
425 quiz_start_new_attempt($quizobj, $quba, $attempt, 1, $timenow);
426 quiz_attempt_save_started($quizobj, $quba, $attempt);
427
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);
431
432 $this->assertCount(2, $result['attempts']);
433
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);
437
438 $this->assertCount(1, $result['attempts']);
439
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);
444
445 $this->assertCount(1, $result['attempts']);
446 $this->assertEquals($this->student->id, $result['attempts'][0]['userid']);
447
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);
450
451 $this->assertCount(2, $result['attempts']);
452 $this->assertEquals($this->student->id, $result['attempts'][0]['userid']);
453
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 }
e73e4581
JL
462
463 /**
464 * Test get_user_best_grade
465 */
466 public function test_get_user_best_grade() {
467 global $DB;
468
469 $this->setUser($this->student);
470
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);
473
474 // No grades yet.
475 $this->assertFalse($result['hasgrade']);
476 $this->assertTrue(!isset($result['grade']));
477
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);
484
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);
487
488 // Now I have grades.
489 $this->assertTrue($result['hasgrade']);
490 $this->assertEquals(8.9, $result['grade']);
491
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');
495
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 }
502
503 // Teacher must be able to see student grades.
504 $this->setUser($this->teacher);
505
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);
508
509 $this->assertTrue($result['hasgrade']);
510 $this->assertEquals(8.9, $result['grade']);
511
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 }
519
520 // Remove the created data.
521 $DB->delete_records('quiz_grades', array('id' => $grade->id));
522
523 }
1f67c0b8
JL
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;
530
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);
536
537 // Create a couple of questions.
538 $questiongenerator = $this->getDataGenerator()->get_plugin_generator('core_question');
539
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);
543
544 $quizobj = quiz::create($quiz->id, $this->student->id);
545
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();
551
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);
555
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);
560
561 $this->setUser($this->student);
562
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);
565
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 );
584
585 $this->assertEquals($expected, $result);
586
587 // Now, finish the attempt.
588 $attemptobj = quiz_attempt::create($attempt->id);
589 $attemptobj->process_finish($timenow, false);
590
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 );
608
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);
613
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);
621
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 );
639
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);
643
644 // Teacher, for see student options.
645 $this->setUser($this->teacher);
646
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);
649
650 $this->assertEquals($expected, $result);
651
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 }
660
b8954440
JL
661 /**
662 * Test start_attempt
663 */
664 public function test_start_attempt() {
665 global $DB;
666
4c08658a
JL
667 // Create a new quiz with questions.
668 list($quiz, $context, $quizobj) = $this->create_quiz_with_questions();
b8954440
JL
669
670 $this->setUser($this->student);
671
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);
678
679 $this->assertEquals([], $result['attempt']);
680 $this->assertCount(1, $result['warnings']);
681
682 // Now with a password.
683 $quiz->timeopen = 0;
684 $quiz->timeclose = 0;
685 $quiz->password = 'abc';
686 $DB->update_record('quiz', $quiz);
687
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 }
694
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);
698
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'];
704
705 // We are good, try to start a new attempt now.
706
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 }
713
714 // Finish the started attempt.
715
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);
721
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);
726
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);
730
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']);
735
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();
742
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 }
749
750 }
751
bc247b0d 752 /**
4c08658a 753 * Test validate_attempt
bc247b0d 754 */
4c08658a
JL
755 public function test_validate_attempt() {
756 global $DB;
bc247b0d 757
4c08658a
JL
758 // Create a new quiz with one attempt started.
759 list($quiz, $context, $quizobj, $attempt, $attemptobj) = $this->create_quiz_with_questions(true);
bc247b0d 760
4c08658a
JL
761 $this->setUser($this->student);
762
763 // Invalid attempt.
bc247b0d 764 try {
4c08658a
JL
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 }
771
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]);
777
778 // Test with preflight data.
779 $quiz->password = 'abc';
780 $DB->update_record('quiz', $quiz);
781
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 }
790
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]);
796
bc9733e7 797 // Page out of range.
4c08658a 798 $DB->update_record('quiz', $quiz);
bc9733e7 799 $params['page'] = 4;
4c08658a
JL
800 try {
801 testable_mod_quiz_external::validate_attempt($params);
bc9733e7 802 $this->fail('Exception expected due to page out of range.');
4c08658a 803 } catch (moodle_quiz_exception $e) {
bc9733e7 804 $this->assertEquals('Invalid page number', $e->errorcode);
4c08658a
JL
805 }
806
bc9733e7
JL
807 $params['page'] = 0;
808 // Try to open attempt in closed quiz.
809 $quiz->timeopen = time() - WEEKSECS;
810 $quiz->timeclose = time() - DAYSECS;
4c08658a 811 $DB->update_record('quiz', $quiz);
98e68690
JL
812
813 // This should work, ommit access rules.
814 testable_mod_quiz_external::validate_attempt($params, false);
815
816 // Get a generic error because prior to checking the dates the attempt is closed.
4c08658a
JL
817 try {
818 testable_mod_quiz_external::validate_attempt($params);
bc9733e7 819 $this->fail('Exception expected due to passed dates.');
4c08658a 820 } catch (moodle_quiz_exception $e) {
98e68690 821 $this->assertEquals('attempterror', $e->errorcode);
4c08658a
JL
822 }
823
824 // Finish the attempt.
825 $attemptobj = quiz_attempt::create($attempt->id);
826 $attemptobj->process_finish(time(), false);
827
828 try {
98e68690 829 testable_mod_quiz_external::validate_attempt($params, false);
4c08658a
JL
830 $this->fail('Exception expected due to attempt finished.');
831 } catch (moodle_quiz_exception $e) {
832 $this->assertEquals('attemptalreadyclosed', $e->errorcode);
833 }
834
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();
841
842 try {
843 testable_mod_quiz_external::validate_attempt($params);
844 $this->fail('Exception expected due to missing permissions.');
bc247b0d
JL
845 } catch (required_capability_exception $e) {
846 $this->assertEquals('nopermissions', $e->errorcode);
847 }
848
4c08658a
JL
849 // Now try with a different user.
850 $this->setUser($this->teacher);
851
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 }
860
861 /**
862 * Test get_attempt_data
863 */
864 public function test_get_attempt_data() {
865 global $DB;
866
74804b57 867 $timenow = time();
4c08658a
JL
868 // Create a new quiz with one attempt started.
869 list($quiz, $context, $quizobj, $attempt, $attemptobj) = $this->create_quiz_with_questions(true);
870
01a79b4e
JL
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));
873
4c08658a
JL
874 $quizobj = $attemptobj->get_quizobj();
875 $quizobj->preload_questions();
876 $quizobj->load_questions();
877 $questions = $quizobj->get_questions();
878
879 $this->setUser($this->student);
880
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);
884
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']);
01a79b4e 892 $this->assertArrayNotHasKey('state', $result['questions'][0]); // We don't receive the state yet.
4c08658a
JL
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']);
74804b57
JL
898 $this->assertEquals(1, $result['questions'][0]['sequencecheck']);
899 $this->assertGreaterThanOrEqual($timenow, $result['questions'][0]['lastactiontime']);
900 $this->assertEquals(false, $result['questions'][0]['hasautosavedstep']);
4c08658a
JL
901
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);
905
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']);
01a79b4e 913 $this->assertArrayNotHasKey('state', $result['questions'][0]); // We don't receive the state yet.
4c08658a
JL
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']);
74804b57
JL
917 $this->assertEquals(1, $result['questions'][0]['sequencecheck']);
918 $this->assertGreaterThanOrEqual($timenow, $result['questions'][0]['lastactiontime']);
919 $this->assertEquals(false, $result['questions'][0]['hasautosavedstep']);
4c08658a
JL
920
921 // Finish previous attempt.
922 $attemptobj->process_finish(time(), false);
923
01a79b4e
JL
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']);
928
4c08658a
JL
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);
933
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);
937
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);
942
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']);
948
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);
960
bc247b0d
JL
961 }
962
33ef5cdc
DP
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;
969
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');
973
974 $quizobj = $attemptobj->get_quizobj();
975
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);
980
981 $quizobj->preload_questions();
982 $quizobj->load_questions();
983 $questions = $quizobj->get_questions();
984
985 $this->setUser($this->student);
986
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);
990
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']);
996
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);
1000
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 }
1007
bc9733e7
JL
1008 /**
1009 * Test get_attempt_summary
1010 */
1011 public function test_get_attempt_summary() {
1012
74804b57 1013 $timenow = time();
bc9733e7
JL
1014 // Create a new quiz with one attempt started.
1015 list($quiz, $context, $quizobj, $attempt, $attemptobj) = $this->create_quiz_with_questions(true);
1016
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);
1020
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']);
74804b57
JL
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']);
bc9733e7 1036
a5dcaee3
JL
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']));
1041
bc9733e7
JL
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);
1047
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']);
74804b57
JL
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']);
bc9733e7
JL
1063
1064 }
1065
96d5607c
JL
1066 /**
1067 * Test save_attempt
1068 */
1069 public function test_save_attempt() {
1070
74804b57 1071 $timenow = time();
96d5607c
JL
1072 // Create a new quiz with one attempt started.
1073 list($quiz, $context, $quizobj, $attempt, $attemptobj, $quba) = $this->create_quiz_with_questions(true);
1074
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 );
1083
1084 $this->setUser($this->student);
1085
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']);
1089
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);
1093
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']);
74804b57
JL
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']);
96d5607c
JL
1109
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 );
1118
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']);
1122
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);
1126
1127 // Check it's marked as completed only the first one.
1128 $this->assertEquals('complete', $result['questions'][0]['state']);
74804b57 1129 $this->assertEquals(1, $result['questions'][0]['sequencecheck']);
96d5607c 1130 $this->assertEquals('complete', $result['questions'][1]['state']);
74804b57 1131 $this->assertEquals(1, $result['questions'][1]['sequencecheck']);
96d5607c
JL
1132
1133 }
1134
98e68690
JL
1135 /**
1136 * Test process_attempt
1137 */
1138 public function test_process_attempt() {
1139 global $DB;
1140
74804b57 1141 $timenow = time();
e49ccc92
JL
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);
98e68690
JL
1145
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 );
1154
1155 $this->setUser($this->student);
1156
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']);
1160
e49ccc92
JL
1161 $result = mod_quiz_external::get_attempt_data($attempt->id, 2);
1162
98e68690
JL
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);
e49ccc92 1166 $this->assertDebuggingCalled(); // Expect $PAGE->set_url debugging.
98e68690
JL
1167
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']);
74804b57
JL
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']);
98e68690
JL
1183
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 );
1193
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']);
1197
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);
1201
e49ccc92
JL
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']);
1207
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.');
1220
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 );
1231
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']);
1235
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);
1239
98e68690
JL
1240 $this->assertEquals('complete', $result['questions'][0]['state']);
1241 $this->assertEquals('complete', $result['questions'][1]['state']);
e49ccc92 1242 $this->assertEquals('complete', $result['questions'][2]['state']);
98e68690
JL
1243 $this->assertFalse($result['questions'][0]['flagged']);
1244 $this->assertTrue($result['questions'][1]['flagged']);
e49ccc92
JL
1245 $this->assertFalse($result['questions'][2]['flagged']);
1246
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']);
98e68690
JL
1252
1253 // Finish the attempt.
36fa0ec9 1254 $sink = $this->redirectMessages();
98e68690
JL
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']);
36fa0ec9 1258 $messages = $sink->get_messages();
2356454f 1259 $message = reset($messages);
36fa0ec9
JL
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 }
98e68690
JL
1269
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);
1273
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);
1278
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);
1284
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']);
1288
904c37c6
JL
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);
1295
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);
1302
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']);
1306
98e68690
JL
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);
904c37c6 1311 $attempt = quiz_create_attempt($quizobj, 4, 3, $timenow, false, $this->student->id);
98e68690
JL
1312 quiz_start_new_attempt($quizobj, $quba, $attempt, 3, $timenow);
1313 quiz_attempt_save_started($quizobj, $quba, $attempt);
1314
1315 // Force abandon.
1316 $quiz->timeclose = $timenow - HOURSECS;
1317 $DB->update_record('quiz', $quiz);
1318
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']);
1322
1323 }
1324
3589b659
JL
1325 /**
1326 * Test validate_attempt_review
1327 */
1328 public function test_validate_attempt_review() {
1329 global $DB;
1330
1331 // Create a new quiz with one attempt started.
1332 list($quiz, $context, $quizobj, $attempt, $attemptobj) = $this->create_quiz_with_questions(true);
1333
1334 $this->setUser($this->student);
1335
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 }
1344
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 }
1353
1354 // Test ok case (finished attempt).
1355 list($quiz, $context, $quizobj, $attempt, $attemptobj) = $this->create_quiz_with_questions(true, true);
1356
1357 $params = array('attemptid' => $attempt->id);
1358 testable_mod_quiz_external::validate_attempt_review($params);
1359
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);
1363
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');
1367
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 }
1377
1378
1379 /**
1380 * Test get_attempt_review
1381 */
1382 public function test_get_attempt_review() {
1383 global $DB;
1384
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);
1387
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);
1396
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);
1402
1403 $result = mod_quiz_external::get_attempt_review($attempt->id);
1404 $result = external_api::clean_returnvalue(mod_quiz_external::get_attempt_review_returns(), $result);
1405
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']);
1416
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']);
1421
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);
1425
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']);
1433
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']);
1438
1439 }
1440
899983ee
JL
1441 /**
1442 * Test test_view_attempt
1443 */
1444 public function test_view_attempt() {
1445 global $DB;
1446
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);
1449
1450 // Test user with full capabilities.
1451 $this->setUser($this->student);
1452
1453 // Trigger and capture the event.
1454 $sink = $this->redirectEvents();
1455
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']);
1459
1460 $events = $sink->get_events();
1461 $this->assertCount(1, $events);
1462 $event = array_shift($events);
1463
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());
1469
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));
9be3072d
JL
1472 // Quiz requiring preflightdata.
1473 $DB->set_field('quiz', 'password', 'abcdef', array('id' => $quiz->id));
1474 $preflightdata = array(array("name" => "quizpassword", "value" => 'abcdef'));
1475
899983ee 1476 // See next page.
9be3072d 1477 $result = mod_quiz_external::view_attempt($attempt->id, 1, $preflightdata);
899983ee
JL
1478 $result = external_api::clean_returnvalue(mod_quiz_external::view_attempt_returns(), $result);
1479 $this->assertTrue($result['status']);
1480
1481 $events = $sink->get_events();
1482 $this->assertCount(2, $events);
1483
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 }
1491
1492 }
1493
d9ef6ae0
JL
1494 /**
1495 * Test test_view_attempt_summary
1496 */
1497 public function test_view_attempt_summary() {
1498 global $DB;
1499
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);
1502
1503 // Test user with full capabilities.
1504 $this->setUser($this->student);
1505
1506 // Trigger and capture the event.
1507 $sink = $this->redirectEvents();
1508
9be3072d 1509 $result = mod_quiz_external::view_attempt_summary($attempt->id);
d9ef6ae0
JL
1510 $result = external_api::clean_returnvalue(mod_quiz_external::view_attempt_summary_returns(), $result);
1511 $this->assertTrue($result['status']);
1512
1513 $events = $sink->get_events();
1514 $this->assertCount(1, $events);
1515 $event = array_shift($events);
1516
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());
1524
9be3072d
JL
1525 // Quiz requiring preflightdata.
1526 $DB->set_field('quiz', 'password', 'abcdef', array('id' => $quiz->id));
1527 $preflightdata = array(array("name" => "quizpassword", "value" => 'abcdef'));
1528
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']);
1532
d9ef6ae0
JL
1533 }
1534
3e5c19a0
JL
1535 /**
1536 * Test test_view_attempt_summary
1537 */
1538 public function test_view_attempt_review() {
1539 global $DB;
1540
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);
1543
1544 // Test user with full capabilities.
1545 $this->setUser($this->student);
1546
1547 // Trigger and capture the event.
1548 $sink = $this->redirectEvents();
1549
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']);
1553
1554 $events = $sink->get_events();
1555 $this->assertCount(1, $events);
1556 $event = array_shift($events);
1557
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());
1565
1566 }
1567
48abca79
JL
1568 /**
1569 * Test get_quiz_feedback_for_grade
1570 */
1571 public function test_get_quiz_feedback_for_grade() {
1572 global $DB;
1573
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);
c8743f62
JL
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)');
48abca79
JL
1594
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);
1600
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']);
c8743f62 1604 $this->assertEquals($filename, $result['feedbackinlinefiles'][0]['filename']);
48abca79
JL
1605 $this->assertEquals(FORMAT_HTML, $result['feedbacktextformat']);
1606
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']);
1611
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 }
1617
a79a6361
JL
1618 /**
1619 * Test get_quiz_access_information
1620 */
1621 public function test_get_quiz_access_information() {
1622 global $DB;
1623
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);
1628
1629 $this->setUser($this->student);
1630
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);
1634
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 );
1647
1648 $this->assertEquals($expected, $result);
1649
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);
1654
1655 $expected['canmanage'] = true;
1656 $expected['canpreview'] = true;
1657 $expected['canviewreports'] = true;
1658 $expected['canattempt'] = false;
1659 $expected['canreviewmyattempts'] = false;
1660
1661 $this->assertEquals($expected, $result);
1662
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);
1669
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);
1672
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']);
1678
1679 }
ff99efcd
JL
1680
1681 /**
1682 * Test get_attempt_access_information
1683 */
1684 public function test_get_attempt_access_information() {
1685 global $DB;
1686
4fa49cc6
SR
1687 $this->setAdminUser();
1688
ff99efcd
JL
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);
1694
1695 // Create some questions.
1696 $questiongenerator = $this->getDataGenerator()->get_plugin_generator('core_question');
1697
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);
1701
1702 $question = $questiongenerator->create_question('shortanswer', null, array('category' => $cat->id));
1703 quiz_add_quiz_question($question->id, $quiz);
1704
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));
1708
4fa49cc6 1709 quiz_add_random_questions($quiz, 0, $cat->id, 1, false);
ff99efcd
JL
1710
1711 $quizobj = quiz::create($quiz->id, $this->student->id);
1712
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();
1718
1719 $this->setUser($this->student);
1720
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);
1724
1725 $expected = array(
1726 'isfinished' => false,
1727 'preventnewattemptreasons' => [],
1728 'warnings' => []
1729 );
1730
1731 $this->assertEquals($expected, $result);
1732
1733 // Limited attempts.
1734 $quiz->attempts = 1;
1735 $DB->update_record('quiz', $quiz);
1736
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);
1740
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);
1745
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);
1750
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);
1755
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);
1759
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]);
1764
1765 }
efca239e
JL
1766
1767 /**
1768 * Test get_quiz_required_qtypes
1769 */
1770 public function test_get_quiz_required_qtypes() {
4fa49cc6 1771 $this->setAdminUser();
efca239e
JL
1772
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);
1777
1778 // Create some questions.
1779 $questiongenerator = $this->getDataGenerator()->get_plugin_generator('core_question');
1780
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);
1784
1785 $question = $questiongenerator->create_question('shortanswer', null, array('category' => $cat->id));
1786 quiz_add_quiz_question($question->id, $quiz);
1787
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));
1791
4fa49cc6 1792 quiz_add_random_questions($quiz, 0, $cat->id, 1, false);
efca239e
JL
1793
1794 $this->setUser($this->student);
1795
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);
1798
1799 $expected = array(
1800 'questiontypes' => ['essay', 'numerical', 'random', 'shortanswer', 'truefalse'],
1801 'warnings' => []
1802 );
1803
1804 $this->assertEquals($expected, $result);
1805
1806 }
51e27aac 1807}