mirrored from git://git.moodle.org/moodle.git
/
external_test.php
1744 lines (1413 loc) · 77 KB
/
external_test.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Quiz module external functions tests.
*
* @package mod_quiz
* @category external
* @copyright 2016 Juan Leyva <juan@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @since Moodle 3.1
*/
defined('MOODLE_INTERNAL') || die();
global $CFG;
require_once($CFG->dirroot . '/webservice/tests/helpers.php');
/**
* Silly class to access mod_quiz_external internal methods.
*
* @package mod_quiz
* @copyright 2016 Juan Leyva <juan@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @since Moodle 3.1
*/
class testable_mod_quiz_external extends mod_quiz_external {
/**
* Public accessor.
*
* @param array $params Array of parameters including the attemptid and preflight data
* @param bool $checkaccessrules whether to check the quiz access rules or not
* @param bool $failifoverdue whether to return error if the attempt is overdue
* @return array containing the attempt object and access messages
*/
public static function validate_attempt($params, $checkaccessrules = true, $failifoverdue = true) {
return parent::validate_attempt($params, $checkaccessrules, $failifoverdue);
}
/**
* Public accessor.
*
* @param array $params Array of parameters including the attemptid
* @return array containing the attempt object and display options
*/
public static function validate_attempt_review($params) {
return parent::validate_attempt_review($params);
}
}
/**
* Quiz module external functions tests
*
* @package mod_quiz
* @category external
* @copyright 2016 Juan Leyva <juan@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @since Moodle 3.1
*/
class mod_quiz_external_testcase extends externallib_advanced_testcase {
/**
* Set up for every test
*/
public function setUp() {
global $DB;
$this->resetAfterTest();
$this->setAdminUser();
// Setup test data.
$this->course = $this->getDataGenerator()->create_course();
$this->quiz = $this->getDataGenerator()->create_module('quiz', array('course' => $this->course->id));
$this->context = context_module::instance($this->quiz->cmid);
$this->cm = get_coursemodule_from_instance('quiz', $this->quiz->id);
// Create users.
$this->student = self::getDataGenerator()->create_user();
$this->teacher = self::getDataGenerator()->create_user();
// Users enrolments.
$this->studentrole = $DB->get_record('role', array('shortname' => 'student'));
$this->teacherrole = $DB->get_record('role', array('shortname' => 'editingteacher'));
// Allow student to receive messages.
$coursecontext = context_course::instance($this->course->id);
assign_capability('mod/quiz:emailnotifysubmission', CAP_ALLOW, $this->teacherrole->id, $coursecontext, true);
$this->getDataGenerator()->enrol_user($this->student->id, $this->course->id, $this->studentrole->id, 'manual');
$this->getDataGenerator()->enrol_user($this->teacher->id, $this->course->id, $this->teacherrole->id, 'manual');
}
/**
* Create a quiz with questions including a started or finished attempt optionally
*
* @param boolean $startattempt whether to start a new attempt
* @param boolean $finishattempt whether to finish the new attempt
* @param string $behaviour the quiz preferredbehaviour, defaults to 'deferredfeedback'.
* @return array array containing the quiz, context and the attempt
*/
private function create_quiz_with_questions($startattempt = false, $finishattempt = false, $behaviour = 'deferredfeedback') {
// Create a new quiz with attempts.
$quizgenerator = $this->getDataGenerator()->get_plugin_generator('mod_quiz');
$data = array('course' => $this->course->id,
'sumgrades' => 2,
'preferredbehaviour' => $behaviour);
$quiz = $quizgenerator->create_instance($data);
$context = context_module::instance($quiz->cmid);
// Create a couple of questions.
$questiongenerator = $this->getDataGenerator()->get_plugin_generator('core_question');
$cat = $questiongenerator->create_question_category();
$question = $questiongenerator->create_question('numerical', null, array('category' => $cat->id));
quiz_add_quiz_question($question->id, $quiz);
$question = $questiongenerator->create_question('numerical', null, array('category' => $cat->id));
quiz_add_quiz_question($question->id, $quiz);
$quizobj = quiz::create($quiz->id, $this->student->id);
// Set grade to pass.
$item = grade_item::fetch(array('courseid' => $this->course->id, 'itemtype' => 'mod',
'itemmodule' => 'quiz', 'iteminstance' => $quiz->id, 'outcomeid' => null));
$item->gradepass = 80;
$item->update();
if ($startattempt or $finishattempt) {
// Now, do one attempt.
$quba = question_engine::make_questions_usage_by_activity('mod_quiz', $quizobj->get_context());
$quba->set_preferred_behaviour($quizobj->get_quiz()->preferredbehaviour);
$timenow = time();
$attempt = quiz_create_attempt($quizobj, 1, false, $timenow, false, $this->student->id);
quiz_start_new_attempt($quizobj, $quba, $attempt, 1, $timenow);
quiz_attempt_save_started($quizobj, $quba, $attempt);
$attemptobj = quiz_attempt::create($attempt->id);
if ($finishattempt) {
// Process some responses from the student.
$tosubmit = array(1 => array('answer' => '3.14'));
$attemptobj->process_submitted_actions(time(), false, $tosubmit);
// Finish the attempt.
$attemptobj->process_finish(time(), false);
}
return array($quiz, $context, $quizobj, $attempt, $attemptobj, $quba);
} else {
return array($quiz, $context, $quizobj);
}
}
/*
* Test get quizzes by courses
*/
public function test_mod_quiz_get_quizzes_by_courses() {
global $DB;
// Create additional course.
$course2 = self::getDataGenerator()->create_course();
// Second quiz.
$record = new stdClass();
$record->course = $course2->id;
$quiz2 = self::getDataGenerator()->create_module('quiz', $record);
// Execute real Moodle enrolment as we'll call unenrol() method on the instance later.
$enrol = enrol_get_plugin('manual');
$enrolinstances = enrol_get_instances($course2->id, true);
foreach ($enrolinstances as $courseenrolinstance) {
if ($courseenrolinstance->enrol == "manual") {
$instance2 = $courseenrolinstance;
break;
}
}
$enrol->enrol_user($instance2, $this->student->id, $this->studentrole->id);
self::setUser($this->student);
$returndescription = mod_quiz_external::get_quizzes_by_courses_returns();
// Create what we expect to be returned when querying the two courses.
// First for the student user.
$allusersfields = array('id', 'coursemodule', 'course', 'name', 'intro', 'introformat', 'introfiles', 'timeopen',
'timeclose', 'grademethod', 'section', 'visible', 'groupmode', 'groupingid',
'attempts', 'timelimit', 'grademethod', 'decimalpoints', 'questiondecimalpoints', 'sumgrades',
'grade', 'preferredbehaviour', 'hasfeedback');
$userswithaccessfields = array('attemptonlast', 'reviewattempt', 'reviewcorrectness', 'reviewmarks',
'reviewspecificfeedback', 'reviewgeneralfeedback', 'reviewrightanswer',
'reviewoverallfeedback', 'questionsperpage', 'navmethod',
'browsersecurity', 'delay1', 'delay2', 'showuserpicture', 'showblocks',
'completionattemptsexhausted', 'completionpass', 'autosaveperiod', 'hasquestions',
'overduehandling', 'graceperiod', 'canredoquestions', 'allowofflineattempts');
$managerfields = array('shuffleanswers', 'timecreated', 'timemodified', 'password', 'subnet');
// Add expected coursemodule and other data.
$quiz1 = $this->quiz;
$quiz1->coursemodule = $quiz1->cmid;
$quiz1->introformat = 1;
$quiz1->section = 0;
$quiz1->visible = true;
$quiz1->groupmode = 0;
$quiz1->groupingid = 0;
$quiz1->hasquestions = 0;
$quiz1->hasfeedback = 0;
$quiz1->autosaveperiod = get_config('quiz', 'autosaveperiod');
$quiz1->introfiles = [];
$quiz2->coursemodule = $quiz2->cmid;
$quiz2->introformat = 1;
$quiz2->section = 0;
$quiz2->visible = true;
$quiz2->groupmode = 0;
$quiz2->groupingid = 0;
$quiz2->hasquestions = 0;
$quiz2->hasfeedback = 0;
$quiz2->autosaveperiod = get_config('quiz', 'autosaveperiod');
$quiz2->introfiles = [];
foreach (array_merge($allusersfields, $userswithaccessfields) as $field) {
$expected1[$field] = $quiz1->{$field};
$expected2[$field] = $quiz2->{$field};
}
$expectedquizzes = array($expected2, $expected1);
// Call the external function passing course ids.
$result = mod_quiz_external::get_quizzes_by_courses(array($course2->id, $this->course->id));
$result = external_api::clean_returnvalue($returndescription, $result);
$this->assertEquals($expectedquizzes, $result['quizzes']);
$this->assertCount(0, $result['warnings']);
// Call the external function without passing course id.
$result = mod_quiz_external::get_quizzes_by_courses();
$result = external_api::clean_returnvalue($returndescription, $result);
$this->assertEquals($expectedquizzes, $result['quizzes']);
$this->assertCount(0, $result['warnings']);
// Unenrol user from second course and alter expected quizzes.
$enrol->unenrol_user($instance2, $this->student->id);
array_shift($expectedquizzes);
// Call the external function without passing course id.
$result = mod_quiz_external::get_quizzes_by_courses();
$result = external_api::clean_returnvalue($returndescription, $result);
$this->assertEquals($expectedquizzes, $result['quizzes']);
// Call for the second course we unenrolled the user from, expected warning.
$result = mod_quiz_external::get_quizzes_by_courses(array($course2->id));
$this->assertCount(1, $result['warnings']);
$this->assertEquals('1', $result['warnings'][0]['warningcode']);
$this->assertEquals($course2->id, $result['warnings'][0]['itemid']);
// Now, try as a teacher for getting all the additional fields.
self::setUser($this->teacher);
foreach ($managerfields as $field) {
$expectedquizzes[0][$field] = $quiz1->{$field};
}
$result = mod_quiz_external::get_quizzes_by_courses();
$result = external_api::clean_returnvalue($returndescription, $result);
$this->assertEquals($expectedquizzes, $result['quizzes']);
// Admin also should get all the information.
self::setAdminUser();
$result = mod_quiz_external::get_quizzes_by_courses(array($this->course->id));
$result = external_api::clean_returnvalue($returndescription, $result);
$this->assertEquals($expectedquizzes, $result['quizzes']);
// Now, prevent access.
$enrol->enrol_user($instance2, $this->student->id);
self::setUser($this->student);
$quiz2->timeclose = time() - DAYSECS;
$DB->update_record('quiz', $quiz2);
$result = mod_quiz_external::get_quizzes_by_courses();
$result = external_api::clean_returnvalue($returndescription, $result);
$this->assertCount(2, $result['quizzes']);
// We only see a limited set of fields.
$this->assertCount(4, $result['quizzes'][0]);
$this->assertEquals($quiz2->id, $result['quizzes'][0]['id']);
$this->assertEquals($quiz2->coursemodule, $result['quizzes'][0]['coursemodule']);
$this->assertEquals($quiz2->course, $result['quizzes'][0]['course']);
$this->assertEquals($quiz2->name, $result['quizzes'][0]['name']);
$this->assertEquals($quiz2->course, $result['quizzes'][0]['course']);
$this->assertFalse(isset($result['quizzes'][0]['timelimit']));
}
/**
* Test test_view_quiz
*/
public function test_view_quiz() {
global $DB;
// Test invalid instance id.
try {
mod_quiz_external::view_quiz(0);
$this->fail('Exception expected due to invalid mod_quiz instance id.');
} catch (moodle_exception $e) {
$this->assertEquals('invalidrecord', $e->errorcode);
}
// Test not-enrolled user.
$usernotenrolled = self::getDataGenerator()->create_user();
$this->setUser($usernotenrolled);
try {
mod_quiz_external::view_quiz($this->quiz->id);
$this->fail('Exception expected due to not enrolled user.');
} catch (moodle_exception $e) {
$this->assertEquals('requireloginerror', $e->errorcode);
}
// Test user with full capabilities.
$this->setUser($this->student);
// Trigger and capture the event.
$sink = $this->redirectEvents();
$result = mod_quiz_external::view_quiz($this->quiz->id);
$result = external_api::clean_returnvalue(mod_quiz_external::view_quiz_returns(), $result);
$this->assertTrue($result['status']);
$events = $sink->get_events();
$this->assertCount(1, $events);
$event = array_shift($events);
// Checking that the event contains the expected values.
$this->assertInstanceOf('\mod_quiz\event\course_module_viewed', $event);
$this->assertEquals($this->context, $event->get_context());
$moodlequiz = new \moodle_url('/mod/quiz/view.php', array('id' => $this->cm->id));
$this->assertEquals($moodlequiz, $event->get_url());
$this->assertEventContextNotUsed($event);
$this->assertNotEmpty($event->get_name());
// Test user with no capabilities.
// We need a explicit prohibit since this capability is only defined in authenticated user and guest roles.
assign_capability('mod/quiz:view', CAP_PROHIBIT, $this->studentrole->id, $this->context->id);
// Empty all the caches that may be affected by this change.
accesslib_clear_all_caches_for_unit_testing();
course_modinfo::clear_instance_cache();
try {
mod_quiz_external::view_quiz($this->quiz->id);
$this->fail('Exception expected due to missing capability.');
} catch (moodle_exception $e) {
$this->assertEquals('requireloginerror', $e->errorcode);
}
}
/**
* Test get_user_attempts
*/
public function test_get_user_attempts() {
// Create a quiz with one attempt finished.
list($quiz, $context, $quizobj, $attempt, $attemptobj) = $this->create_quiz_with_questions(true, true);
$this->setUser($this->student);
$result = mod_quiz_external::get_user_attempts($quiz->id);
$result = external_api::clean_returnvalue(mod_quiz_external::get_user_attempts_returns(), $result);
$this->assertCount(1, $result['attempts']);
$this->assertEquals($attempt->id, $result['attempts'][0]['id']);
$this->assertEquals($quiz->id, $result['attempts'][0]['quiz']);
$this->assertEquals($this->student->id, $result['attempts'][0]['userid']);
$this->assertEquals(1, $result['attempts'][0]['attempt']);
// Test filters. Only finished.
$result = mod_quiz_external::get_user_attempts($quiz->id, 0, 'finished', false);
$result = external_api::clean_returnvalue(mod_quiz_external::get_user_attempts_returns(), $result);
$this->assertCount(1, $result['attempts']);
$this->assertEquals($attempt->id, $result['attempts'][0]['id']);
// Test filters. All attempts.
$result = mod_quiz_external::get_user_attempts($quiz->id, 0, 'all', false);
$result = external_api::clean_returnvalue(mod_quiz_external::get_user_attempts_returns(), $result);
$this->assertCount(1, $result['attempts']);
$this->assertEquals($attempt->id, $result['attempts'][0]['id']);
// Test filters. Unfinished.
$result = mod_quiz_external::get_user_attempts($quiz->id, 0, 'unfinished', false);
$result = external_api::clean_returnvalue(mod_quiz_external::get_user_attempts_returns(), $result);
$this->assertCount(0, $result['attempts']);
// Start a new attempt, but not finish it.
$timenow = time();
$attempt = quiz_create_attempt($quizobj, 2, false, $timenow, false, $this->student->id);
$quba = question_engine::make_questions_usage_by_activity('mod_quiz', $quizobj->get_context());
$quba->set_preferred_behaviour($quizobj->get_quiz()->preferredbehaviour);
quiz_start_new_attempt($quizobj, $quba, $attempt, 1, $timenow);
quiz_attempt_save_started($quizobj, $quba, $attempt);
// Test filters. All attempts.
$result = mod_quiz_external::get_user_attempts($quiz->id, 0, 'all', false);
$result = external_api::clean_returnvalue(mod_quiz_external::get_user_attempts_returns(), $result);
$this->assertCount(2, $result['attempts']);
// Test filters. Unfinished.
$result = mod_quiz_external::get_user_attempts($quiz->id, 0, 'unfinished', false);
$result = external_api::clean_returnvalue(mod_quiz_external::get_user_attempts_returns(), $result);
$this->assertCount(1, $result['attempts']);
// Test manager can see user attempts.
$this->setUser($this->teacher);
$result = mod_quiz_external::get_user_attempts($quiz->id, $this->student->id);
$result = external_api::clean_returnvalue(mod_quiz_external::get_user_attempts_returns(), $result);
$this->assertCount(1, $result['attempts']);
$this->assertEquals($this->student->id, $result['attempts'][0]['userid']);
$result = mod_quiz_external::get_user_attempts($quiz->id, $this->student->id, 'all');
$result = external_api::clean_returnvalue(mod_quiz_external::get_user_attempts_returns(), $result);
$this->assertCount(2, $result['attempts']);
$this->assertEquals($this->student->id, $result['attempts'][0]['userid']);
// Invalid parameters.
try {
mod_quiz_external::get_user_attempts($quiz->id, $this->student->id, 'INVALID_PARAMETER');
$this->fail('Exception expected due to missing capability.');
} catch (invalid_parameter_exception $e) {
$this->assertEquals('invalidparameter', $e->errorcode);
}
}
/**
* Test get_user_best_grade
*/
public function test_get_user_best_grade() {
global $DB;
$this->setUser($this->student);
$result = mod_quiz_external::get_user_best_grade($this->quiz->id);
$result = external_api::clean_returnvalue(mod_quiz_external::get_user_best_grade_returns(), $result);
// No grades yet.
$this->assertFalse($result['hasgrade']);
$this->assertTrue(!isset($result['grade']));
$grade = new stdClass();
$grade->quiz = $this->quiz->id;
$grade->userid = $this->student->id;
$grade->grade = 8.9;
$grade->timemodified = time();
$grade->id = $DB->insert_record('quiz_grades', $grade);
$result = mod_quiz_external::get_user_best_grade($this->quiz->id);
$result = external_api::clean_returnvalue(mod_quiz_external::get_user_best_grade_returns(), $result);
// Now I have grades.
$this->assertTrue($result['hasgrade']);
$this->assertEquals(8.9, $result['grade']);
// We should not see other users grades.
$anotherstudent = self::getDataGenerator()->create_user();
$this->getDataGenerator()->enrol_user($anotherstudent->id, $this->course->id, $this->studentrole->id, 'manual');
try {
mod_quiz_external::get_user_best_grade($this->quiz->id, $anotherstudent->id);
$this->fail('Exception expected due to missing capability.');
} catch (required_capability_exception $e) {
$this->assertEquals('nopermissions', $e->errorcode);
}
// Teacher must be able to see student grades.
$this->setUser($this->teacher);
$result = mod_quiz_external::get_user_best_grade($this->quiz->id, $this->student->id);
$result = external_api::clean_returnvalue(mod_quiz_external::get_user_best_grade_returns(), $result);
$this->assertTrue($result['hasgrade']);
$this->assertEquals(8.9, $result['grade']);
// Invalid user.
try {
mod_quiz_external::get_user_best_grade($this->quiz->id, -1);
$this->fail('Exception expected due to missing capability.');
} catch (dml_missing_record_exception $e) {
$this->assertEquals('invaliduser', $e->errorcode);
}
// Remove the created data.
$DB->delete_records('quiz_grades', array('id' => $grade->id));
}
/**
* Test get_combined_review_options.
* This is a basic test, this is already tested in mod_quiz_display_options_testcase.
*/
public function test_get_combined_review_options() {
global $DB;
// Create a new quiz with attempts.
$quizgenerator = $this->getDataGenerator()->get_plugin_generator('mod_quiz');
$data = array('course' => $this->course->id,
'sumgrades' => 1);
$quiz = $quizgenerator->create_instance($data);
// Create a couple of questions.
$questiongenerator = $this->getDataGenerator()->get_plugin_generator('core_question');
$cat = $questiongenerator->create_question_category();
$question = $questiongenerator->create_question('numerical', null, array('category' => $cat->id));
quiz_add_quiz_question($question->id, $quiz);
$quizobj = quiz::create($quiz->id, $this->student->id);
// Set grade to pass.
$item = grade_item::fetch(array('courseid' => $this->course->id, 'itemtype' => 'mod',
'itemmodule' => 'quiz', 'iteminstance' => $quiz->id, 'outcomeid' => null));
$item->gradepass = 80;
$item->update();
// Start the passing attempt.
$quba = question_engine::make_questions_usage_by_activity('mod_quiz', $quizobj->get_context());
$quba->set_preferred_behaviour($quizobj->get_quiz()->preferredbehaviour);
$timenow = time();
$attempt = quiz_create_attempt($quizobj, 1, false, $timenow, false, $this->student->id);
quiz_start_new_attempt($quizobj, $quba, $attempt, 1, $timenow);
quiz_attempt_save_started($quizobj, $quba, $attempt);
$this->setUser($this->student);
$result = mod_quiz_external::get_combined_review_options($quiz->id);
$result = external_api::clean_returnvalue(mod_quiz_external::get_combined_review_options_returns(), $result);
// Expected values.
$expected = array(
"someoptions" => array(
array("name" => "feedback", "value" => 1),
array("name" => "generalfeedback", "value" => 1),
array("name" => "rightanswer", "value" => 1),
array("name" => "overallfeedback", "value" => 0),
array("name" => "marks", "value" => 2),
),
"alloptions" => array(
array("name" => "feedback", "value" => 1),
array("name" => "generalfeedback", "value" => 1),
array("name" => "rightanswer", "value" => 1),
array("name" => "overallfeedback", "value" => 0),
array("name" => "marks", "value" => 2),
),
"warnings" => [],
);
$this->assertEquals($expected, $result);
// Now, finish the attempt.
$attemptobj = quiz_attempt::create($attempt->id);
$attemptobj->process_finish($timenow, false);
$expected = array(
"someoptions" => array(
array("name" => "feedback", "value" => 1),
array("name" => "generalfeedback", "value" => 1),
array("name" => "rightanswer", "value" => 1),
array("name" => "overallfeedback", "value" => 1),
array("name" => "marks", "value" => 2),
),
"alloptions" => array(
array("name" => "feedback", "value" => 1),
array("name" => "generalfeedback", "value" => 1),
array("name" => "rightanswer", "value" => 1),
array("name" => "overallfeedback", "value" => 1),
array("name" => "marks", "value" => 2),
),
"warnings" => [],
);
// We should see now the overall feedback.
$result = mod_quiz_external::get_combined_review_options($quiz->id);
$result = external_api::clean_returnvalue(mod_quiz_external::get_combined_review_options_returns(), $result);
$this->assertEquals($expected, $result);
// Start a new attempt, but not finish it.
$timenow = time();
$attempt = quiz_create_attempt($quizobj, 2, false, $timenow, false, $this->student->id);
$quba = question_engine::make_questions_usage_by_activity('mod_quiz', $quizobj->get_context());
$quba->set_preferred_behaviour($quizobj->get_quiz()->preferredbehaviour);
quiz_start_new_attempt($quizobj, $quba, $attempt, 1, $timenow);
quiz_attempt_save_started($quizobj, $quba, $attempt);
$expected = array(
"someoptions" => array(
array("name" => "feedback", "value" => 1),
array("name" => "generalfeedback", "value" => 1),
array("name" => "rightanswer", "value" => 1),
array("name" => "overallfeedback", "value" => 1),
array("name" => "marks", "value" => 2),
),
"alloptions" => array(
array("name" => "feedback", "value" => 1),
array("name" => "generalfeedback", "value" => 1),
array("name" => "rightanswer", "value" => 1),
array("name" => "overallfeedback", "value" => 0),
array("name" => "marks", "value" => 2),
),
"warnings" => [],
);
$result = mod_quiz_external::get_combined_review_options($quiz->id);
$result = external_api::clean_returnvalue(mod_quiz_external::get_combined_review_options_returns(), $result);
$this->assertEquals($expected, $result);
// Teacher, for see student options.
$this->setUser($this->teacher);
$result = mod_quiz_external::get_combined_review_options($quiz->id, $this->student->id);
$result = external_api::clean_returnvalue(mod_quiz_external::get_combined_review_options_returns(), $result);
$this->assertEquals($expected, $result);
// Invalid user.
try {
mod_quiz_external::get_combined_review_options($quiz->id, -1);
$this->fail('Exception expected due to missing capability.');
} catch (dml_missing_record_exception $e) {
$this->assertEquals('invaliduser', $e->errorcode);
}
}
/**
* Test start_attempt
*/
public function test_start_attempt() {
global $DB;
// Create a new quiz with questions.
list($quiz, $context, $quizobj) = $this->create_quiz_with_questions();
$this->setUser($this->student);
// Try to open attempt in closed quiz.
$quiz->timeopen = time() - WEEKSECS;
$quiz->timeclose = time() - DAYSECS;
$DB->update_record('quiz', $quiz);
$result = mod_quiz_external::start_attempt($quiz->id);
$result = external_api::clean_returnvalue(mod_quiz_external::start_attempt_returns(), $result);
$this->assertEquals([], $result['attempt']);
$this->assertCount(1, $result['warnings']);
// Now with a password.
$quiz->timeopen = 0;
$quiz->timeclose = 0;
$quiz->password = 'abc';
$DB->update_record('quiz', $quiz);
try {
mod_quiz_external::start_attempt($quiz->id, array(array("name" => "quizpassword", "value" => 'bad')));
$this->fail('Exception expected due to invalid passwod.');
} catch (moodle_exception $e) {
$this->assertEquals(get_string('passworderror', 'quizaccess_password'), $e->errorcode);
}
// Now, try everything correct.
$result = mod_quiz_external::start_attempt($quiz->id, array(array("name" => "quizpassword", "value" => 'abc')));
$result = external_api::clean_returnvalue(mod_quiz_external::start_attempt_returns(), $result);
$this->assertEquals(1, $result['attempt']['attempt']);
$this->assertEquals($this->student->id, $result['attempt']['userid']);
$this->assertEquals($quiz->id, $result['attempt']['quiz']);
$this->assertCount(0, $result['warnings']);
$attemptid = $result['attempt']['id'];
// We are good, try to start a new attempt now.
try {
mod_quiz_external::start_attempt($quiz->id, array(array("name" => "quizpassword", "value" => 'abc')));
$this->fail('Exception expected due to attempt not finished.');
} catch (moodle_quiz_exception $e) {
$this->assertEquals('attemptstillinprogress', $e->errorcode);
}
// Finish the started attempt.
// Process some responses from the student.
$timenow = time();
$attemptobj = quiz_attempt::create($attemptid);
$tosubmit = array(1 => array('answer' => '3.14'));
$attemptobj->process_submitted_actions($timenow, false, $tosubmit);
// Finish the attempt.
$attemptobj = quiz_attempt::create($attemptid);
$this->assertTrue($attemptobj->has_response_to_at_least_one_graded_question());
$attemptobj->process_finish($timenow, false);
// We should be able to start a new attempt.
$result = mod_quiz_external::start_attempt($quiz->id, array(array("name" => "quizpassword", "value" => 'abc')));
$result = external_api::clean_returnvalue(mod_quiz_external::start_attempt_returns(), $result);
$this->assertEquals(2, $result['attempt']['attempt']);
$this->assertEquals($this->student->id, $result['attempt']['userid']);
$this->assertEquals($quiz->id, $result['attempt']['quiz']);
$this->assertCount(0, $result['warnings']);
// Test user with no capabilities.
// We need a explicit prohibit since this capability is only defined in authenticated user and guest roles.
assign_capability('mod/quiz:attempt', CAP_PROHIBIT, $this->studentrole->id, $context->id);
// Empty all the caches that may be affected by this change.
accesslib_clear_all_caches_for_unit_testing();
course_modinfo::clear_instance_cache();
try {
mod_quiz_external::start_attempt($quiz->id);
$this->fail('Exception expected due to missing capability.');
} catch (required_capability_exception $e) {
$this->assertEquals('nopermissions', $e->errorcode);
}
}
/**
* Test validate_attempt
*/
public function test_validate_attempt() {
global $DB;
// Create a new quiz with one attempt started.
list($quiz, $context, $quizobj, $attempt, $attemptobj) = $this->create_quiz_with_questions(true);
$this->setUser($this->student);
// Invalid attempt.
try {
$params = array('attemptid' => -1, 'page' => 0);
testable_mod_quiz_external::validate_attempt($params);
$this->fail('Exception expected due to invalid attempt id.');
} catch (dml_missing_record_exception $e) {
$this->assertEquals('invalidrecord', $e->errorcode);
}
// Test OK case.
$params = array('attemptid' => $attempt->id, 'page' => 0);
$result = testable_mod_quiz_external::validate_attempt($params);
$this->assertEquals($attempt->id, $result[0]->get_attempt()->id);
$this->assertEquals([], $result[1]);
// Test with preflight data.
$quiz->password = 'abc';
$DB->update_record('quiz', $quiz);
try {
$params = array('attemptid' => $attempt->id, 'page' => 0,
'preflightdata' => array(array("name" => "quizpassword", "value" => 'bad')));
testable_mod_quiz_external::validate_attempt($params);
$this->fail('Exception expected due to invalid passwod.');
} catch (moodle_exception $e) {
$this->assertEquals(get_string('passworderror', 'quizaccess_password'), $e->errorcode);
}
// Now, try everything correct.
$params['preflightdata'][0]['value'] = 'abc';
$result = testable_mod_quiz_external::validate_attempt($params);
$this->assertEquals($attempt->id, $result[0]->get_attempt()->id);
$this->assertEquals([], $result[1]);
// Page out of range.
$DB->update_record('quiz', $quiz);
$params['page'] = 4;
try {
testable_mod_quiz_external::validate_attempt($params);
$this->fail('Exception expected due to page out of range.');
} catch (moodle_quiz_exception $e) {
$this->assertEquals('Invalid page number', $e->errorcode);
}
$params['page'] = 0;
// Try to open attempt in closed quiz.
$quiz->timeopen = time() - WEEKSECS;
$quiz->timeclose = time() - DAYSECS;
$DB->update_record('quiz', $quiz);
// This should work, ommit access rules.
testable_mod_quiz_external::validate_attempt($params, false);
// Get a generic error because prior to checking the dates the attempt is closed.
try {
testable_mod_quiz_external::validate_attempt($params);
$this->fail('Exception expected due to passed dates.');
} catch (moodle_quiz_exception $e) {
$this->assertEquals('attempterror', $e->errorcode);
}
// Finish the attempt.
$attemptobj = quiz_attempt::create($attempt->id);
$attemptobj->process_finish(time(), false);
try {
testable_mod_quiz_external::validate_attempt($params, false);
$this->fail('Exception expected due to attempt finished.');
} catch (moodle_quiz_exception $e) {
$this->assertEquals('attemptalreadyclosed', $e->errorcode);
}
// Test user with no capabilities.
// We need a explicit prohibit since this capability is only defined in authenticated user and guest roles.
assign_capability('mod/quiz:attempt', CAP_PROHIBIT, $this->studentrole->id, $context->id);
// Empty all the caches that may be affected by this change.
accesslib_clear_all_caches_for_unit_testing();
course_modinfo::clear_instance_cache();
try {
testable_mod_quiz_external::validate_attempt($params);
$this->fail('Exception expected due to missing permissions.');
} catch (required_capability_exception $e) {
$this->assertEquals('nopermissions', $e->errorcode);
}
// Now try with a different user.
$this->setUser($this->teacher);
$params['page'] = 0;
try {
testable_mod_quiz_external::validate_attempt($params);
$this->fail('Exception expected due to not your attempt.');
} catch (moodle_quiz_exception $e) {
$this->assertEquals('notyourattempt', $e->errorcode);
}
}
/**
* Test get_attempt_data
*/
public function test_get_attempt_data() {
global $DB;
$timenow = time();
// Create a new quiz with one attempt started.
list($quiz, $context, $quizobj, $attempt, $attemptobj) = $this->create_quiz_with_questions(true);
// Set correctness mask so questions state can be fetched only after finishing the attempt.
$DB->set_field('quiz', 'reviewcorrectness', mod_quiz_display_options::IMMEDIATELY_AFTER, array('id' => $quiz->id));
$quizobj = $attemptobj->get_quizobj();
$quizobj->preload_questions();
$quizobj->load_questions();
$questions = $quizobj->get_questions();
$this->setUser($this->student);
// We receive one question per page.
$result = mod_quiz_external::get_attempt_data($attempt->id, 0);
$result = external_api::clean_returnvalue(mod_quiz_external::get_attempt_data_returns(), $result);
$this->assertEquals($attempt, (object) $result['attempt']);
$this->assertEquals(1, $result['nextpage']);
$this->assertCount(0, $result['messages']);
$this->assertCount(1, $result['questions']);
$this->assertEquals(1, $result['questions'][0]['slot']);
$this->assertEquals(1, $result['questions'][0]['number']);
$this->assertEquals('numerical', $result['questions'][0]['type']);
$this->assertArrayNotHasKey('state', $result['questions'][0]); // We don't receive the state yet.
$this->assertEquals(get_string('notyetanswered', 'question'), $result['questions'][0]['status']);
$this->assertFalse($result['questions'][0]['flagged']);
$this->assertEquals(0, $result['questions'][0]['page']);
$this->assertEmpty($result['questions'][0]['mark']);
$this->assertEquals(1, $result['questions'][0]['maxmark']);
$this->assertEquals(1, $result['questions'][0]['sequencecheck']);
$this->assertGreaterThanOrEqual($timenow, $result['questions'][0]['lastactiontime']);
$this->assertEquals(false, $result['questions'][0]['hasautosavedstep']);
// Now try the last page.
$result = mod_quiz_external::get_attempt_data($attempt->id, 1);
$result = external_api::clean_returnvalue(mod_quiz_external::get_attempt_data_returns(), $result);
$this->assertEquals($attempt, (object) $result['attempt']);
$this->assertEquals(-1, $result['nextpage']);
$this->assertCount(0, $result['messages']);
$this->assertCount(1, $result['questions']);
$this->assertEquals(2, $result['questions'][0]['slot']);
$this->assertEquals(2, $result['questions'][0]['number']);
$this->assertEquals('numerical', $result['questions'][0]['type']);
$this->assertArrayNotHasKey('state', $result['questions'][0]); // We don't receive the state yet.
$this->assertEquals(get_string('notyetanswered', 'question'), $result['questions'][0]['status']);
$this->assertFalse($result['questions'][0]['flagged']);
$this->assertEquals(1, $result['questions'][0]['page']);
$this->assertEquals(1, $result['questions'][0]['sequencecheck']);
$this->assertGreaterThanOrEqual($timenow, $result['questions'][0]['lastactiontime']);
$this->assertEquals(false, $result['questions'][0]['hasautosavedstep']);
// Finish previous attempt.
$attemptobj->process_finish(time(), false);
// Now we should receive the question state.
$result = mod_quiz_external::get_attempt_review($attempt->id, 1);
$result = external_api::clean_returnvalue(mod_quiz_external::get_attempt_review_returns(), $result);
$this->assertEquals('gaveup', $result['questions'][0]['state']);
// Change setting and expect two pages.
$quiz->questionsperpage = 4;
$DB->update_record('quiz', $quiz);
quiz_repaginate_questions($quiz->id, $quiz->questionsperpage);
// Start with new attempt with the new layout.
$quba = question_engine::make_questions_usage_by_activity('mod_quiz', $quizobj->get_context());
$quba->set_preferred_behaviour($quizobj->get_quiz()->preferredbehaviour);
$timenow = time();
$attempt = quiz_create_attempt($quizobj, 2, false, $timenow, false, $this->student->id);
quiz_start_new_attempt($quizobj, $quba, $attempt, 1, $timenow);
quiz_attempt_save_started($quizobj, $quba, $attempt);
// We receive two questions per page.
$result = mod_quiz_external::get_attempt_data($attempt->id, 0);
$result = external_api::clean_returnvalue(mod_quiz_external::get_attempt_data_returns(), $result);
$this->assertCount(2, $result['questions']);
$this->assertEquals(-1, $result['nextpage']);
// Check questions looks good.
$found = 0;
foreach ($questions as $question) {
foreach ($result['questions'] as $rquestion) {
if ($rquestion['slot'] == $question->slot) {
$this->assertTrue(strpos($rquestion['html'], "qid=$question->id") !== false);
$found++;
}
}
}
$this->assertEquals(2, $found);
}
/**
* Test get_attempt_data with blocked questions.
* @since 3.2
*/
public function test_get_attempt_data_with_blocked_questions() {
global $DB;
// Create a new quiz with one attempt started and using immediatefeedback.
list($quiz, $context, $quizobj, $attempt, $attemptobj) = $this->create_quiz_with_questions(
true, false, 'immediatefeedback');
$quizobj = $attemptobj->get_quizobj();
// Make second question blocked by the first one.
$structure = $quizobj->get_structure();
$slots = $structure->get_slots();
$structure->update_question_dependency(end($slots)->id, true);
$quizobj->preload_questions();
$quizobj->load_questions();
$questions = $quizobj->get_questions();
$this->setUser($this->student);
// We receive one question per page.
$result = mod_quiz_external::get_attempt_data($attempt->id, 0);
$result = external_api::clean_returnvalue(mod_quiz_external::get_attempt_data_returns(), $result);
$this->assertEquals($attempt, (object) $result['attempt']);
$this->assertCount(1, $result['questions']);
$this->assertEquals(1, $result['questions'][0]['slot']);
$this->assertEquals(1, $result['questions'][0]['number']);
$this->assertEquals(false, $result['questions'][0]['blockedbyprevious']);
// Now try the last page.
$result = mod_quiz_external::get_attempt_data($attempt->id, 1);
$result = external_api::clean_returnvalue(mod_quiz_external::get_attempt_data_returns(), $result);
$this->assertEquals($attempt, (object) $result['attempt']);
$this->assertCount(1, $result['questions']);
$this->assertEquals(2, $result['questions'][0]['slot']);
$this->assertEquals(2, $result['questions'][0]['number']);
$this->assertEquals(true, $result['questions'][0]['blockedbyprevious']);
}
/**
* Test get_attempt_summary