Proyectos de Subversion Moodle

Rev

Rev 11 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 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
namespace quiz_overview;
18
 
19
use core_question\local\bank\question_version_status;
20
use mod_quiz\external\submit_question_version;
21
use mod_quiz\quiz_attempt;
22
use question_engine;
23
use mod_quiz\quiz_settings;
24
use mod_quiz\local\reports\attempts_report;
25
use quiz_overview_options;
26
use quiz_overview_report;
27
use quiz_overview_table;
28
 
29
defined('MOODLE_INTERNAL') || die();
30
 
31
global $CFG;
32
require_once($CFG->dirroot . '/mod/quiz/locallib.php');
33
require_once($CFG->dirroot . '/mod/quiz/report/reportlib.php');
34
require_once($CFG->dirroot . '/mod/quiz/report/overview/report.php');
35
require_once($CFG->dirroot . '/mod/quiz/report/overview/overview_form.php');
36
require_once($CFG->dirroot . '/mod/quiz/report/overview/tests/helpers.php');
37
require_once($CFG->dirroot . '/mod/quiz/tests/quiz_question_helper_test_trait.php');
38
 
39
 
40
/**
41
 * Tests for the quiz overview report.
42
 *
43
 * @package    quiz_overview
44
 * @copyright  2014 The Open University
45
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
46
 */
1441 ariadna 47
final class report_test extends \advanced_testcase {
1 efrain 48
    use \quiz_question_helper_test_trait;
49
 
50
    /**
51
     * Data provider for test_report_sql.
52
     *
53
     * @return array the data for the test sub-cases.
54
     */
1441 ariadna 55
    public static function report_sql_cases(): array {
1 efrain 56
        return [[null], ['csv']]; // Only need to test on or off, not all download types.
57
    }
58
 
59
    /**
60
     * Test how the report queries the database.
61
     *
62
     * @param string|null $isdownloading a download type, or null.
63
     * @dataProvider report_sql_cases
64
     */
65
    public function test_report_sql(?string $isdownloading): void {
66
        global $DB;
67
        $this->resetAfterTest();
68
 
69
        // Create a course and a quiz.
70
        $generator = $this->getDataGenerator();
71
        $course = $generator->create_course();
72
        $quizgenerator = $generator->get_plugin_generator('mod_quiz');
73
        $quiz = $quizgenerator->create_instance(['course' => $course->id,
74
                'grademethod' => QUIZ_GRADEHIGHEST, 'grade' => 100.0, 'sumgrades' => 10.0,
75
                'attempts' => 10]);
76
 
77
        // Add one question.
78
        /** @var core_question_generator $questiongenerator */
79
        $questiongenerator = $this->getDataGenerator()->get_plugin_generator('core_question');
80
        $cat = $questiongenerator->create_question_category();
81
        $q = $questiongenerator->create_question('essay', 'plain', ['category' => $cat->id]);
82
        quiz_add_quiz_question($q->id, $quiz, 0 , 10);
83
 
84
        // Create some students and enrol them in the course.
85
        $student1 = $generator->create_user();
86
        $student2 = $generator->create_user();
87
        $student3 = $generator->create_user();
88
        $generator->enrol_user($student1->id, $course->id);
89
        $generator->enrol_user($student2->id, $course->id);
90
        $generator->enrol_user($student3->id, $course->id);
91
        // This line is not really necessary for the test asserts below,
92
        // but what it does is add an extra user row returned by
93
        // get_enrolled_with_capabilities_join because of a second enrolment.
94
        // The extra row returned used to make $table->query_db complain
95
        // about duplicate records. So this is really a test that an extra
96
        // student enrolment does not cause duplicate records in this query.
97
        $generator->enrol_user($student2->id, $course->id, null, 'self');
98
 
99
        // Also create a user who should not appear in the reports,
100
        // because they have a role with neither 'mod/quiz:attempt'
101
        // nor 'mod/quiz:reviewmyattempts'.
102
        $tutor = $generator->create_user();
103
        $generator->enrol_user($tutor->id, $course->id, 'teacher');
104
 
105
        // The test data.
106
        $timestamp = 1234567890;
107
        $attempts = [
108
            [$quiz, $student1, 1, 0.0,  quiz_attempt::FINISHED],
109
            [$quiz, $student1, 2, 5.0,  quiz_attempt::FINISHED],
110
            [$quiz, $student1, 3, 8.0,  quiz_attempt::FINISHED],
111
            [$quiz, $student1, 4, null, quiz_attempt::ABANDONED],
1441 ariadna 112
            [$quiz, $student1, 5, null, quiz_attempt::SUBMITTED],
113
            [$quiz, $student1, 6, null, quiz_attempt::IN_PROGRESS],
1 efrain 114
            [$quiz, $student2, 1, null, quiz_attempt::ABANDONED],
115
            [$quiz, $student2, 2, null, quiz_attempt::ABANDONED],
116
            [$quiz, $student2, 3, 7.0,  quiz_attempt::FINISHED],
117
            [$quiz, $student2, 4, null, quiz_attempt::ABANDONED],
118
            [$quiz, $student2, 5, null, quiz_attempt::ABANDONED],
119
        ];
120
 
121
        // Load it in to quiz attempts table.
122
        foreach ($attempts as $attemptdata) {
123
            list($quiz, $student, $attemptnumber, $sumgrades, $state) = $attemptdata;
124
            $timestart = $timestamp + $attemptnumber * 3600;
125
 
126
            $quizobj = quiz_settings::create($quiz->id, $student->id);
127
            $quba = question_engine::make_questions_usage_by_activity('mod_quiz', $quizobj->get_context());
128
            $quba->set_preferred_behaviour($quizobj->get_quiz()->preferredbehaviour);
129
 
130
            // Create the new attempt and initialize the question sessions.
131
            $attempt = quiz_create_attempt($quizobj, $attemptnumber, null, $timestart, false, $student->id);
132
 
133
            $attempt = quiz_start_new_attempt($quizobj, $quba, $attempt, $attemptnumber, $timestamp);
134
            $attempt = quiz_attempt_save_started($quizobj, $quba, $attempt);
135
 
136
            // Process some responses from the student.
137
            $attemptobj = quiz_attempt::create($attempt->id);
138
            switch ($state) {
139
                case quiz_attempt::ABANDONED:
140
                    $attemptobj->process_abandon($timestart + 300, false);
141
                    break;
142
 
143
                case quiz_attempt::IN_PROGRESS:
144
                    // Do nothing.
145
                    break;
146
 
1441 ariadna 147
                case quiz_attempt::SUBMITTED:
148
                    // Save answers but do not grade attempt.
149
                    $attemptobj->process_submitted_actions(
150
                        $timestart + 300,
151
                        false,
152
                        [
153
                            1 => ['answer' => 'My essay by ' . $student->firstname, 'answerformat' => FORMAT_PLAIN],
154
                        ]
155
                    );
156
                    $attemptobj->process_submit($timestart + 600, false);
157
                    break;
158
 
1 efrain 159
                case quiz_attempt::FINISHED:
160
                    // Save answer and finish attempt.
1441 ariadna 161
                    $attemptobj->process_submitted_actions(
162
                        $timestart + 300,
163
                        false,
164
                        [
165
                            1 => ['answer' => 'My essay by ' . $student->firstname, 'answerformat' => FORMAT_PLAIN],
166
                        ]
167
                    );
168
                    $attemptobj->process_submit($timestart + 600, false);
169
                    $attemptobj->process_grade_submission($timestart + 600);
1 efrain 170
 
171
                    // Manually grade it.
172
                    $quba = $attemptobj->get_question_usage();
173
                    $quba->get_question_attempt(1)->manual_grade(
174
                            'Comment', $sumgrades, FORMAT_HTML, $timestart + 1200);
175
                    question_engine::save_questions_usage_by_activity($quba);
176
                    $update = new \stdClass();
177
                    $update->id = $attemptobj->get_attemptid();
178
                    $update->timemodified = $timestart + 1200;
179
                    $update->sumgrades = $quba->get_total_mark();
180
                    $DB->update_record('quiz_attempts', $update);
181
                    $attemptobj->get_quizobj()->get_grade_calculator()->recompute_final_grade($student->id);
182
                    break;
183
            }
184
        }
185
 
186
        // Actually getting the SQL to run is quite hard. Do a minimal set up of
187
        // some objects.
188
        $context = \context_module::instance($quiz->cmid);
189
        $cm = get_coursemodule_from_id('quiz', $quiz->cmid);
190
        $qmsubselect = quiz_report_qm_filter_select($quiz);
191
        $studentsjoins = get_enrolled_with_capabilities_join($context, '',
192
                ['mod/quiz:attempt', 'mod/quiz:reviewmyattempts']);
193
        $empty = new \core\dml\sql_join();
194
 
195
        // Set the options.
196
        $reportoptions = new quiz_overview_options('overview', $quiz, $cm, null);
197
        $reportoptions->attempts = attempts_report::ENROLLED_ALL;
198
        $reportoptions->onlygraded = true;
199
        $reportoptions->states = [quiz_attempt::IN_PROGRESS, quiz_attempt::OVERDUE, quiz_attempt::FINISHED];
200
 
201
        // Now do a minimal set-up of the table class.
202
        $q->slot = 1;
203
        $q->maxmark = 10;
204
        $table = new quiz_overview_table($quiz, $context, $qmsubselect, $reportoptions,
205
                $empty, $studentsjoins, [1 => $q], null);
206
        $table->download = $isdownloading; // Cannot call the is_downloading API, because it gives errors.
207
        $table->define_columns(['fullname']);
208
        $table->sortable(true, 'uniqueid');
209
        $table->define_baseurl(new \moodle_url('/mod/quiz/report.php'));
210
        $table->setup();
211
 
212
        // Run the query.
213
        $table->setup_sql_queries($studentsjoins);
214
        $table->query_db(30, false);
215
 
216
        // Should be 4 rows, matching count($table->rawdata) tested below.
217
        // The count is only done if not downloading.
218
        if (!$isdownloading) {
219
            $this->assertEquals(4, $table->totalrows);
220
        }
221
 
222
        // Verify what was returned: Student 1's best and in progress attempts.
223
        // Student 2's finshed attempt, and Student 3 with no attempt.
224
        // The array key is {student id}#{attempt number}.
225
        $this->assertEquals(4, count($table->rawdata));
226
        $this->assertArrayHasKey($student1->id . '#3', $table->rawdata);
227
        $this->assertEquals(1, $table->rawdata[$student1->id . '#3']->gradedattempt);
228
        $this->assertArrayHasKey($student1->id . '#3', $table->rawdata);
1441 ariadna 229
        $this->assertEquals(0, $table->rawdata[$student1->id . '#6']->gradedattempt);
1 efrain 230
        $this->assertArrayHasKey($student2->id . '#3', $table->rawdata);
231
        $this->assertEquals(1, $table->rawdata[$student2->id . '#3']->gradedattempt);
232
        $this->assertArrayHasKey($student3->id . '#0', $table->rawdata);
233
        $this->assertEquals(0, $table->rawdata[$student3->id . '#0']->gradedattempt);
234
 
235
        // Check the calculation of averages.
236
        $averagerow = $table->compute_average_row('overallaverage', $studentsjoins);
237
        $this->assertStringContainsString('75.00', $averagerow['sumgrades']);
238
        $this->assertStringContainsString('75.00', $averagerow['qsgrade1']);
239
        if (!$isdownloading) {
240
            $this->assertStringContainsString('(2)', $averagerow['sumgrades']);
241
            $this->assertStringContainsString('(2)', $averagerow['qsgrade1']);
242
        }
243
 
244
        // Ensure that filtering by initial does not break it.
245
        // This involves setting a private properly of the base class, which is
246
        // only really possible using reflection :-(.
247
        $reflectionobject = new \ReflectionObject($table);
248
        while ($parent = $reflectionobject->getParentClass()) {
249
            $reflectionobject = $parent;
250
        }
251
        $prefsproperty = $reflectionobject->getProperty('prefs');
252
        $prefs = $prefsproperty->getValue($table);
253
        $prefs['i_first'] = 'A';
254
        $prefsproperty->setValue($table, $prefs);
255
 
256
        list($fields, $from, $where, $params) = $table->base_sql($studentsjoins);
257
        $table->set_count_sql("SELECT COUNT(1) FROM (SELECT $fields FROM $from WHERE $where) temp WHERE 1 = 1", $params);
258
        $table->set_sql($fields, $from, $where, $params);
259
        $table->query_db(30, false);
260
        // Just verify that this does not cause a fatal error.
261
    }
262
 
263
    /**
264
     * Bands provider.
265
     * @return array
266
     */
1441 ariadna 267
    public static function get_bands_count_and_width_provider(): array {
1 efrain 268
        return [
269
            [10, [20, .5]],
270
            [20, [20, 1]],
271
            [30, [15, 2]],
272
            // TODO MDL-55068 Handle bands better when grade is 50.
273
            // [50, [10, 5]],
274
            [100, [20, 5]],
275
            [200, [20, 10]],
276
        ];
277
    }
278
 
279
    /**
280
     * Test bands.
281
     *
282
     * @dataProvider get_bands_count_and_width_provider
283
     * @param int $grade grade
284
     * @param array $expected
285
     */
286
    public function test_get_bands_count_and_width(int $grade, array $expected): void {
287
        $this->resetAfterTest();
288
        $quizgenerator = $this->getDataGenerator()->get_plugin_generator('mod_quiz');
289
        $quiz = $quizgenerator->create_instance(['course' => SITEID, 'grade' => $grade]);
290
        $this->assertEquals($expected, quiz_overview_report::get_bands_count_and_width($quiz));
291
    }
292
 
293
    /**
294
     * Test delete_selected_attempts function.
295
     */
296
    public function test_delete_selected_attempts(): void {
297
        $this->resetAfterTest();
298
 
299
        $timestamp = 1234567890;
300
        $timestart = $timestamp + 3600;
301
 
302
        // Create a course and a quiz.
303
        $generator = $this->getDataGenerator();
304
        $course = $generator->create_course();
305
        $quizgenerator = $generator->get_plugin_generator('mod_quiz');
306
        $quiz = $quizgenerator->create_instance([
307
                'course' => $course->id,
308
                'grademethod' => QUIZ_GRADEHIGHEST,
309
                'grade' => 100.0,
310
                'sumgrades' => 10.0,
311
                'attempts' => 10
312
        ]);
313
 
314
        // Add one question.
315
        /** @var core_question_generator $questiongenerator */
316
        $questiongenerator = $this->getDataGenerator()->get_plugin_generator('core_question');
317
        $cat = $questiongenerator->create_question_category();
318
        $q = $questiongenerator->create_question('essay', 'plain', ['category' => $cat->id]);
319
        quiz_add_quiz_question($q->id, $quiz, 0 , 10);
320
 
321
        // Create student and enrol them in the course.
322
        // Note: we create two enrolments, to test the problem reported in MDL-67942.
323
        $student = $generator->create_user();
324
        $generator->enrol_user($student->id, $course->id);
325
        $generator->enrol_user($student->id, $course->id, null, 'self');
326
 
327
        $context = \context_module::instance($quiz->cmid);
328
        $cm = get_coursemodule_from_id('quiz', $quiz->cmid);
329
        $allowedjoins = get_enrolled_with_capabilities_join($context, '', ['mod/quiz:attempt', 'mod/quiz:reviewmyattempts']);
330
        $quizattemptsreport = new \testable_quiz_attempts_report();
331
 
332
        // Create the new attempt and initialize the question sessions.
333
        $quizobj = quiz_settings::create($quiz->id, $student->id);
334
        $quba = question_engine::make_questions_usage_by_activity('mod_quiz', $quizobj->get_context());
335
        $quba->set_preferred_behaviour($quizobj->get_quiz()->preferredbehaviour);
336
        $attempt = quiz_create_attempt($quizobj, 1, null, $timestart, false, $student->id);
337
        $attempt = quiz_start_new_attempt($quizobj, $quba, $attempt, 1, $timestamp);
338
        $attempt = quiz_attempt_save_started($quizobj, $quba, $attempt);
339
 
340
        // Delete the student's attempt.
341
        $quizattemptsreport->delete_selected_attempts($quiz, $cm, [$attempt->id], $allowedjoins);
342
    }
343
 
344
    /**
345
     * Test question regrade for selected versions.
346
     *
347
     * @covers ::regrade_question
348
     */
11 efrain 349
    public function test_regrade_question(): void {
1 efrain 350
        global $DB;
351
        $this->resetAfterTest();
352
        $this->setAdminUser();
353
 
354
        $course = $this->getDataGenerator()->create_course();
355
        $quiz = $this->create_test_quiz($course);
356
        $cm = get_fast_modinfo($course->id)->get_cm($quiz->cmid);
357
        $context = \context_module::instance($quiz->cmid);
358
 
359
        /** @var core_question_generator $questiongenerator */
360
        $questiongenerator = $this->getDataGenerator()->get_plugin_generator('core_question');
361
        // Create a couple of questions.
362
        $cat = $questiongenerator->create_question_category(['contextid' => $context->id]);
363
        $q = $questiongenerator->create_question('shortanswer', null,
364
                ['category' => $cat->id, 'name' => 'Toad scores 0.8']);
365
 
366
        // Create a version, the last one draft.
367
        // Sadly, update_question is a bit dodgy, so it can't handle updating the answer score.
368
        $q2 = $questiongenerator->update_question($q, null,
369
                ['name' => 'Toad now scores 1.0']);
370
        $toadanswer = $DB->get_record_select('question_answers',
371
                'question = ? AND ' . $DB->sql_compare_text('answer') . ' = ?',
372
                [$q2->id, 'toad'], '*', MUST_EXIST);
373
        $DB->set_field('question_answers', 'fraction', 1, ['id' => $toadanswer->id]);
374
 
375
        // Add the question to the quiz.
376
        quiz_add_quiz_question($q2->id, $quiz, 0, 10);
377
 
378
        // Attempt the quiz, submitting response 'toad'.
379
        $quizobj = quiz_settings::create($quiz->id);
380
        $attempt = quiz_prepare_and_start_new_attempt($quizobj, 1, null);
381
        $attemptobj = quiz_attempt::create($attempt->id);
382
        $attemptobj->process_submitted_actions(time(), false, [1 => ['answer' => 'toad']]);
1441 ariadna 383
        $attemptobj->process_submit(time(), false);
384
        $attemptobj->process_grade_submission(time());
1 efrain 385
 
386
        // We should be using 'always latest' version, which is currently v2, so should be right.
387
        $this->assertEquals(10, $attemptobj->get_question_usage()->get_total_mark());
388
 
389
        // Now change the quiz to use fixed version 1.
390
        $slot = $quizobj->get_question($q2->id);
391
        submit_question_version::execute($slot->slotid, 1);
392
 
393
        // Regrade.
394
        $report = new quiz_overview_report();
395
        $report->init('overview', 'quiz_overview_settings_form', $quiz, $cm, $course);
396
        $report->regrade_attempt($attempt);
397
 
398
        // The mark should now be 8.
399
        $attemptobj = quiz_attempt::create($attempt->id);
400
        $this->assertEquals(8, $attemptobj->get_question_usage()->get_total_mark());
401
 
402
        // Now add two more versions, the second of which is draft.
403
        $q3 = $questiongenerator->update_question($q, null,
404
                ['name' => 'Toad now scores 0.5']);
405
        $toadanswer = $DB->get_record_select('question_answers',
406
                'question = ? AND ' . $DB->sql_compare_text('answer') . ' = ?',
407
                [$q3->id, 'toad'], '*', MUST_EXIST);
408
        $DB->set_field('question_answers', 'fraction', 0.5, ['id' => $toadanswer->id]);
409
 
410
        $q4 = $questiongenerator->update_question($q, null,
411
                ['name' => 'Toad now scores 0.3',
412
                    'status' => question_version_status::QUESTION_STATUS_DRAFT]);
413
        $toadanswer = $DB->get_record_select('question_answers',
414
                'question = ? AND ' . $DB->sql_compare_text('answer') . ' = ?',
415
                [$q4->id, 'toad'], '*', MUST_EXIST);
416
        $DB->set_field('question_answers', 'fraction', 0.3, ['id' => $toadanswer->id]);
417
 
418
        // Now change the quiz back to always latest and regrade again.
419
        submit_question_version::execute($slot->slotid, 0);
420
        $report->regrade_attempt($attempt);
421
 
422
        // Score should now be 5, because v3 is the latest non-draft version.
423
        $attemptobj = quiz_attempt::create($attempt->id);
424
        $this->assertEquals(5, $attemptobj->get_question_usage()->get_total_mark());
425
    }
426
}