54606daa649dc26a612799d787ca3eb31f1a8643
[moodle.git] / mod / quiz / report / overview / tests / report_test.php
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 // GNU General Public License for more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
17 /**
18  * 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  */
25 defined('MOODLE_INTERNAL') || die();
27 global $CFG;
28 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
29 require_once($CFG->dirroot . '/mod/quiz/report/reportlib.php');
30 require_once($CFG->dirroot . '/mod/quiz/report/default.php');
31 require_once($CFG->dirroot . '/mod/quiz/report/overview/report.php');
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  */
40 class quiz_overview_report_testcase extends advanced_testcase {
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     }
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) {
58         global $DB;
59         $this->resetAfterTest(true);
61         // Create a course and a quiz.
62         $generator = $this->getDataGenerator();
63         $course = $generator->create_course();
64         $quizgenerator = $generator->get_plugin_generator('mod_quiz');
65         $quiz = $quizgenerator->create_instance(array('course' => $course->id,
66                 'grademethod' => QUIZ_GRADEHIGHEST, 'grade' => 100.0, 'sumgrades' => 10.0,
67                 'attempts' => 10));
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);
75         // Create some students and enrol them in the course.
76         $student1 = $generator->create_user();
77         $student2 = $generator->create_user();
78         $student3 = $generator->create_user();
79         $generator->enrol_user($student1->id, $course->id);
80         $generator->enrol_user($student2->id, $course->id);
81         $generator->enrol_user($student3->id, $course->id);
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');
90         // The test data.
91         $timestamp = 1234567890;
92         $attempts = array(
93             array($quiz, $student1, 1, 0.0,  quiz_attempt::FINISHED),
94             array($quiz, $student1, 2, 5.0,  quiz_attempt::FINISHED),
95             array($quiz, $student1, 3, 8.0,  quiz_attempt::FINISHED),
96             array($quiz, $student1, 4, null, quiz_attempt::ABANDONED),
97             array($quiz, $student1, 5, null, quiz_attempt::IN_PROGRESS),
98             array($quiz, $student2, 1, null, quiz_attempt::ABANDONED),
99             array($quiz, $student2, 2, null, quiz_attempt::ABANDONED),
100             array($quiz, $student2, 3, 7.0,  quiz_attempt::FINISHED),
101             array($quiz, $student2, 4, null, quiz_attempt::ABANDONED),
102             array($quiz, $student2, 5, null, quiz_attempt::ABANDONED),
103         );
105         // Load it in to quiz attempts table.
106         foreach ($attempts as $attemptdata) {
107             list($quiz, $student, $attemptnumber, $sumgrades, $state) = $attemptdata;
108             $timestart = $timestamp + $attemptnumber * 3600;
110             $quizobj = quiz::create($quiz->id, $student->id);
111             $quba = question_engine::make_questions_usage_by_activity('mod_quiz', $quizobj->get_context());
112             $quba->set_preferred_behaviour($quizobj->get_quiz()->preferredbehaviour);
114             // Create the new attempt and initialize the question sessions.
115             $attempt = quiz_create_attempt($quizobj, $attemptnumber, null, $timestart, false, $student->id);
117             $attempt = quiz_start_new_attempt($quizobj, $quba, $attempt, $attemptnumber, $timestamp);
118             $attempt = quiz_attempt_save_started($quizobj, $quba, $attempt);
120             // Process some responses from the student.
121             $attemptobj = quiz_attempt::create($attempt->id);
122             switch ($state) {
123                 case quiz_attempt::ABANDONED:
124                     $attemptobj->process_abandon($timestart + 300, false);
125                     break;
127                 case quiz_attempt::IN_PROGRESS:
128                     // Do nothing.
129                     break;
131                 case quiz_attempt::FINISHED:
132                     // Save answer and finish attempt.
133                     $attemptobj->process_submitted_actions($timestart + 300, false, [
134                             1 => ['answer' => 'My essay by ' . $student->firstname, 'answerformat' => FORMAT_PLAIN]]);
135                     $attemptobj->process_finish($timestart + 600, false);
137                     // Manually grade it.
138                     $quba = $attemptobj->get_question_usage();
139                     $quba->get_question_attempt(1)->manual_grade(
140                             'Comment', $sumgrades, FORMAT_HTML, $timestart + 1200);
141                     question_engine::save_questions_usage_by_activity($quba);
142                     $update = new stdClass();
143                     $update->id = $attemptobj->get_attemptid();
144                     $update->timemodified = $timestart + 1200;
145                     $update->sumgrades = $quba->get_total_mark();
146                     $DB->update_record('quiz_attempts', $update);
147                     quiz_save_best_grade($attemptobj->get_quiz(), $student->id);
148                     break;
149             }
150         }
152         // Actually getting the SQL to run is quite hard. Do a minimal set up of
153         // some objects.
154         $context = context_module::instance($quiz->cmid);
155         $cm = get_coursemodule_from_id('quiz', $quiz->cmid);
156         $qmsubselect = quiz_report_qm_filter_select($quiz);
157         $studentsjoins = get_enrolled_with_capabilities_join($context);
158         $empty = new \core\dml\sql_join();
160         // Set the options.
161         $reportoptions = new quiz_overview_options('overview', $quiz, $cm, null);
162         $reportoptions->attempts = quiz_attempts_report::ENROLLED_ALL;
163         $reportoptions->onlygraded = true;
164         $reportoptions->states = array(quiz_attempt::IN_PROGRESS, quiz_attempt::OVERDUE, quiz_attempt::FINISHED);
166         // Now do a minimal set-up of the table class.
167         $q->slot = 1;
168         $q->maxmark = 10;
169         $table = new quiz_overview_table($quiz, $context, $qmsubselect, $reportoptions,
170                 $empty, $studentsjoins, array(1 => $q), null);
171         $table->download = $isdownloading; // Cannot call the is_downloading API, because it gives errors.
172         $table->define_columns(array('fullname'));
173         $table->sortable(true, 'uniqueid');
174         $table->define_baseurl(new moodle_url('/mod/quiz/report.php'));
175         $table->setup();
177         // Run the query.
178         $table->setup_sql_queries($studentsjoins);
179         $table->query_db(30, false);
181         // Should be 4 rows, matching count($table->rawdata) tested below.
182         // The count is only done if not downloading.
183         if (!$isdownloading) {
184             $this->assertEquals(4, $table->totalrows);
185         }
187         // Verify what was returned: Student 1's best and in progress attempts.
188         // Student 2's finshed attempt, and Student 3 with no attempt.
189         // The array key is {student id}#{attempt number}.
190         $this->assertEquals(4, count($table->rawdata));
191         $this->assertArrayHasKey($student1->id . '#3', $table->rawdata);
192         $this->assertEquals(1, $table->rawdata[$student1->id . '#3']->gradedattempt);
193         $this->assertArrayHasKey($student1->id . '#3', $table->rawdata);
194         $this->assertEquals(0, $table->rawdata[$student1->id . '#5']->gradedattempt);
195         $this->assertArrayHasKey($student2->id . '#3', $table->rawdata);
196         $this->assertEquals(1, $table->rawdata[$student2->id . '#3']->gradedattempt);
197         $this->assertArrayHasKey($student3->id . '#0', $table->rawdata);
198         $this->assertEquals(0, $table->rawdata[$student3->id . '#0']->gradedattempt);
200         // Check the calculation of averages.
201         $averagerow = $table->compute_average_row('overallaverage', $studentsjoins);
202         $this->assertContains('75.00', $averagerow['sumgrades']);
203         $this->assertContains('75.00', $averagerow['qsgrade1']);
204         if (!$isdownloading) {
205             $this->assertContains('(2)', $averagerow['sumgrades']);
206             $this->assertContains('(2)', $averagerow['qsgrade1']);
207         }
209         // Ensure that filtering by initial does not break it.
210         // This involves setting a private properly of the base class, which is
211         // only really possible using reflection :-(.
212         $reflectionobject = new ReflectionObject($table);
213         while ($parent = $reflectionobject->getParentClass()) {
214             $reflectionobject = $parent;
215         }
216         $prefsproperty = $reflectionobject->getProperty('prefs');
217         $prefsproperty->setAccessible(true);
218         $prefs = $prefsproperty->getValue($table);
219         $prefs['i_first'] = 'A';
220         $prefsproperty->setValue($table, $prefs);
222         list($fields, $from, $where, $params) = $table->base_sql($studentsjoins);
223         $table->set_count_sql("SELECT COUNT(1) FROM (SELECT $fields FROM $from WHERE $where) temp WHERE 1 = 1", $params);
224         $table->set_sql($fields, $from, $where, $params);
225         $table->query_db(30, false);
226         // Just verify that this does not cause a fatal error.
227     }
229     /**
230      * Bands provider.
231      * @return array
232      */
233     public function get_bands_count_and_width_provider() {
234         return [
235             [10, [20, .5]],
236             [20, [20, 1]],
237             [30, [15, 2]],
238             // TODO MDL-55068 Handle bands better when grade is 50.
239             // [50, [10, 5]],
240             [100, [20, 5]],
241             [200, [20, 10]],
242         ];
243     }
245     /**
246      * Test bands.
247      *
248      * @dataProvider get_bands_count_and_width_provider
249      * @param int $grade grade
250      * @param array $expected
251      */
252     public function test_get_bands_count_and_width($grade, $expected) {
253         $this->resetAfterTest(true);
254         $quizgenerator = $this->getDataGenerator()->get_plugin_generator('mod_quiz');
255         $quiz = $quizgenerator->create_instance(['course' => SITEID, 'grade' => $grade]);
256         $this->assertEquals($expected, quiz_overview_report::get_bands_count_and_width($quiz));
257     }