MDL-66946 quiz reports: incorrectly show teachers sometimes
[moodle.git] / mod / quiz / report / overview / tests / report_test.php
CommitLineData
750757cf
TH
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 * Tests for the quiz overview report.
19 *
20 * @package quiz_overview
21 * @copyright 2014 The Open University
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 */
24
25defined('MOODLE_INTERNAL') || die();
26
27global $CFG;
28require_once($CFG->dirroot . '/mod/quiz/locallib.php');
29require_once($CFG->dirroot . '/mod/quiz/report/reportlib.php');
30require_once($CFG->dirroot . '/mod/quiz/report/default.php');
31require_once($CFG->dirroot . '/mod/quiz/report/overview/report.php');
32
33
34/**
35 * Tests for the quiz overview report.
36 *
37 * @copyright 2014 The Open University
38 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
39 */
40class quiz_overview_report_testcase extends advanced_testcase {
41
ff456b59
TH
42 /**
43 * Data provider for test_report_sql.
44 *
45 * @return array the data for the test sub-cases.
46 */
47 public function report_sql_cases() {
48 return [[null], ['csv']]; // Only need to test on or off, not all download types.
49 }
50
51 /**
52 * Test how the report queries the database.
53 *
54 * @param bool $isdownloading a download type, or null.
55 * @dataProvider report_sql_cases
56 */
57 public function test_report_sql($isdownloading) {
10c4fce5 58 global $DB;
750757cf
TH
59 $this->resetAfterTest(true);
60
ff456b59 61 // Create a course and a quiz.
750757cf 62 $generator = $this->getDataGenerator();
10c4fce5 63 $course = $generator->create_course();
750757cf 64 $quizgenerator = $generator->get_plugin_generator('mod_quiz');
10c4fce5 65 $quiz = $quizgenerator->create_instance(array('course' => $course->id,
750757cf
TH
66 'grademethod' => QUIZ_GRADEHIGHEST, 'grade' => 100.0, 'sumgrades' => 10.0,
67 'attempts' => 10));
68
ff456b59
TH
69 // Add one question.
70 $questiongenerator = $this->getDataGenerator()->get_plugin_generator('core_question');
71 $cat = $questiongenerator->create_question_category();
72 $q = $questiongenerator->create_question('essay', 'plain', ['category' => $cat->id]);
73 quiz_add_quiz_question($q->id, $quiz, 0 , 10);
74
75 // Create some students and enrol them in the course.
750757cf
TH
76 $student1 = $generator->create_user();
77 $student2 = $generator->create_user();
78 $student3 = $generator->create_user();
10c4fce5
JB
79 $generator->enrol_user($student1->id, $course->id);
80 $generator->enrol_user($student2->id, $course->id);
81 $generator->enrol_user($student3->id, $course->id);
ff456b59
TH
82 // This line is not really necessary for the test asserts below,
83 // but what it does is add an extra user row returned by
84 // get_enrolled_with_capabilities_join because of a second enrolment.
85 // The extra row returned used to make $table->query_db complain
86 // about duplicate records. So this is really a test that an extra
87 // student enrolment does not cause duplicate records in this query.
88 $generator->enrol_user($student2->id, $course->id, null, 'self');
750757cf 89
4d325589
TH
90 // Also create a user who should not appear in the reports,
91 // because they have a role with neither 'mod/quiz:attempt'
92 // nor 'mod/quiz:reviewmyattempts'.
93 $tutor = $generator->create_user();
94 $generator->enrol_user($tutor->id, $course->id, 'teacher');
95
750757cf 96 // The test data.
ff456b59 97 $timestamp = 1234567890;
750757cf 98 $attempts = array(
ff456b59
TH
99 array($quiz, $student1, 1, 0.0, quiz_attempt::FINISHED),
100 array($quiz, $student1, 2, 5.0, quiz_attempt::FINISHED),
101 array($quiz, $student1, 3, 8.0, quiz_attempt::FINISHED),
102 array($quiz, $student1, 4, null, quiz_attempt::ABANDONED),
103 array($quiz, $student1, 5, null, quiz_attempt::IN_PROGRESS),
104 array($quiz, $student2, 1, null, quiz_attempt::ABANDONED),
105 array($quiz, $student2, 2, null, quiz_attempt::ABANDONED),
106 array($quiz, $student2, 3, 7.0, quiz_attempt::FINISHED),
107 array($quiz, $student2, 4, null, quiz_attempt::ABANDONED),
108 array($quiz, $student2, 5, null, quiz_attempt::ABANDONED),
750757cf
TH
109 );
110
111 // Load it in to quiz attempts table.
ff456b59
TH
112 foreach ($attempts as $attemptdata) {
113 list($quiz, $student, $attemptnumber, $sumgrades, $state) = $attemptdata;
114 $timestart = $timestamp + $attemptnumber * 3600;
115
116 $quizobj = quiz::create($quiz->id, $student->id);
117 $quba = question_engine::make_questions_usage_by_activity('mod_quiz', $quizobj->get_context());
118 $quba->set_preferred_behaviour($quizobj->get_quiz()->preferredbehaviour);
119
120 // Create the new attempt and initialize the question sessions.
121 $attempt = quiz_create_attempt($quizobj, $attemptnumber, null, $timestart, false, $student->id);
122
123 $attempt = quiz_start_new_attempt($quizobj, $quba, $attempt, $attemptnumber, $timestamp);
124 $attempt = quiz_attempt_save_started($quizobj, $quba, $attempt);
125
126 // Process some responses from the student.
127 $attemptobj = quiz_attempt::create($attempt->id);
128 switch ($state) {
129 case quiz_attempt::ABANDONED:
130 $attemptobj->process_abandon($timestart + 300, false);
131 break;
132
133 case quiz_attempt::IN_PROGRESS:
134 // Do nothing.
135 break;
136
137 case quiz_attempt::FINISHED:
138 // Save answer and finish attempt.
139 $attemptobj->process_submitted_actions($timestart + 300, false, [
140 1 => ['answer' => 'My essay by ' . $student->firstname, 'answerformat' => FORMAT_PLAIN]]);
141 $attemptobj->process_finish($timestart + 600, false);
142
143 // Manually grade it.
144 $quba = $attemptobj->get_question_usage();
145 $quba->get_question_attempt(1)->manual_grade(
146 'Comment', $sumgrades, FORMAT_HTML, $timestart + 1200);
147 question_engine::save_questions_usage_by_activity($quba);
148 $update = new stdClass();
149 $update->id = $attemptobj->get_attemptid();
150 $update->timemodified = $timestart + 1200;
151 $update->sumgrades = $quba->get_total_mark();
152 $DB->update_record('quiz_attempts', $update);
153 quiz_save_best_grade($attemptobj->get_quiz(), $student->id);
154 break;
750757cf 155 }
750757cf
TH
156 }
157
10c4fce5 158 // Actually getting the SQL to run is quite hard. Do a minimal set up of
750757cf
TH
159 // some objects.
160 $context = context_module::instance($quiz->cmid);
161 $cm = get_coursemodule_from_id('quiz', $quiz->cmid);
162 $qmsubselect = quiz_report_qm_filter_select($quiz);
4d325589
TH
163 $studentsjoins = get_enrolled_with_capabilities_join($context, '',
164 array('mod/quiz:attempt', 'mod/quiz:reviewmyattempts'));
10c4fce5 165 $empty = new \core\dml\sql_join();
750757cf
TH
166
167 // Set the options.
168 $reportoptions = new quiz_overview_options('overview', $quiz, $cm, null);
169 $reportoptions->attempts = quiz_attempts_report::ENROLLED_ALL;
170 $reportoptions->onlygraded = true;
171 $reportoptions->states = array(quiz_attempt::IN_PROGRESS, quiz_attempt::OVERDUE, quiz_attempt::FINISHED);
172
173 // Now do a minimal set-up of the table class.
e37c1fe2
TH
174 $q->slot = 1;
175 $q->maxmark = 10;
750757cf 176 $table = new quiz_overview_table($quiz, $context, $qmsubselect, $reportoptions,
ff456b59
TH
177 $empty, $studentsjoins, array(1 => $q), null);
178 $table->download = $isdownloading; // Cannot call the is_downloading API, because it gives errors.
32250b88 179 $table->define_columns(array('fullname'));
750757cf
TH
180 $table->sortable(true, 'uniqueid');
181 $table->define_baseurl(new moodle_url('/mod/quiz/report.php'));
182 $table->setup();
183
184 // Run the query.
c282157f 185 $table->setup_sql_queries($studentsjoins);
750757cf
TH
186 $table->query_db(30, false);
187
ff456b59
TH
188 // Should be 4 rows, matching count($table->rawdata) tested below.
189 // The count is only done if not downloading.
190 if (!$isdownloading) {
191 $this->assertEquals(4, $table->totalrows);
192 }
193
750757cf 194 // Verify what was returned: Student 1's best and in progress attempts.
10c4fce5 195 // Student 2's finshed attempt, and Student 3 with no attempt.
750757cf
TH
196 // The array key is {student id}#{attempt number}.
197 $this->assertEquals(4, count($table->rawdata));
198 $this->assertArrayHasKey($student1->id . '#3', $table->rawdata);
199 $this->assertEquals(1, $table->rawdata[$student1->id . '#3']->gradedattempt);
200 $this->assertArrayHasKey($student1->id . '#3', $table->rawdata);
201 $this->assertEquals(0, $table->rawdata[$student1->id . '#5']->gradedattempt);
202 $this->assertArrayHasKey($student2->id . '#3', $table->rawdata);
203 $this->assertEquals(1, $table->rawdata[$student2->id . '#3']->gradedattempt);
204 $this->assertArrayHasKey($student3->id . '#0', $table->rawdata);
205 $this->assertEquals(0, $table->rawdata[$student3->id . '#0']->gradedattempt);
32250b88 206
e37c1fe2
TH
207 // Check the calculation of averages.
208 $averagerow = $table->compute_average_row('overallaverage', $studentsjoins);
209 $this->assertContains('75.00', $averagerow['sumgrades']);
210 $this->assertContains('75.00', $averagerow['qsgrade1']);
211 if (!$isdownloading) {
212 $this->assertContains('(2)', $averagerow['sumgrades']);
213 $this->assertContains('(2)', $averagerow['qsgrade1']);
214 }
215
216 // Ensure that filtering by initial does not break it.
32250b88
TH
217 // This involves setting a private properly of the base class, which is
218 // only really possible using reflection :-(.
219 $reflectionobject = new ReflectionObject($table);
220 while ($parent = $reflectionobject->getParentClass()) {
221 $reflectionobject = $parent;
222 }
223 $prefsproperty = $reflectionobject->getProperty('prefs');
224 $prefsproperty->setAccessible(true);
225 $prefs = $prefsproperty->getValue($table);
226 $prefs['i_first'] = 'A';
227 $prefsproperty->setValue($table, $prefs);
228
229 list($fields, $from, $where, $params) = $table->base_sql($studentsjoins);
230 $table->set_count_sql("SELECT COUNT(1) FROM (SELECT $fields FROM $from WHERE $where) temp WHERE 1 = 1", $params);
231 $table->set_sql($fields, $from, $where, $params);
232 $table->query_db(30, false);
233 // Just verify that this does not cause a fatal error.
750757cf 234 }
ec882623
FM
235
236 /**
237 * Bands provider.
238 * @return array
239 */
240 public function get_bands_count_and_width_provider() {
241 return [
242 [10, [20, .5]],
243 [20, [20, 1]],
244 [30, [15, 2]],
245 // TODO MDL-55068 Handle bands better when grade is 50.
246 // [50, [10, 5]],
247 [100, [20, 5]],
248 [200, [20, 10]],
249 ];
250 }
251
252 /**
253 * Test bands.
ce323331 254 *
ec882623 255 * @dataProvider get_bands_count_and_width_provider
ce323331
DP
256 * @param int $grade grade
257 * @param array $expected
ec882623
FM
258 */
259 public function test_get_bands_count_and_width($grade, $expected) {
260 $this->resetAfterTest(true);
261 $quizgenerator = $this->getDataGenerator()->get_plugin_generator('mod_quiz');
262 $quiz = $quizgenerator->create_instance(['course' => SITEID, 'grade' => $grade]);
263 $this->assertEquals($expected, quiz_overview_report::get_bands_count_and_width($quiz));
264 }
265
750757cf 266}