Proyectos de Subversion Moodle

Rev

Rev 1 | | 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
 */
47
class report_test extends \advanced_testcase {
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
     */
55
    public function report_sql_cases(): array {
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],
112
            [$quiz, $student1, 5, null, quiz_attempt::IN_PROGRESS],
113
            [$quiz, $student2, 1, null, quiz_attempt::ABANDONED],
114
            [$quiz, $student2, 2, null, quiz_attempt::ABANDONED],
115
            [$quiz, $student2, 3, 7.0,  quiz_attempt::FINISHED],
116
            [$quiz, $student2, 4, null, quiz_attempt::ABANDONED],
117
            [$quiz, $student2, 5, null, quiz_attempt::ABANDONED],
118
        ];
119
 
120
        // Load it in to quiz attempts table.
121
        foreach ($attempts as $attemptdata) {
122
            list($quiz, $student, $attemptnumber, $sumgrades, $state) = $attemptdata;
123
            $timestart = $timestamp + $attemptnumber * 3600;
124
 
125
            $quizobj = quiz_settings::create($quiz->id, $student->id);
126
            $quba = question_engine::make_questions_usage_by_activity('mod_quiz', $quizobj->get_context());
127
            $quba->set_preferred_behaviour($quizobj->get_quiz()->preferredbehaviour);
128
 
129
            // Create the new attempt and initialize the question sessions.
130
            $attempt = quiz_create_attempt($quizobj, $attemptnumber, null, $timestart, false, $student->id);
131
 
132
            $attempt = quiz_start_new_attempt($quizobj, $quba, $attempt, $attemptnumber, $timestamp);
133
            $attempt = quiz_attempt_save_started($quizobj, $quba, $attempt);
134
 
135
            // Process some responses from the student.
136
            $attemptobj = quiz_attempt::create($attempt->id);
137
            switch ($state) {
138
                case quiz_attempt::ABANDONED:
139
                    $attemptobj->process_abandon($timestart + 300, false);
140
                    break;
141
 
142
                case quiz_attempt::IN_PROGRESS:
143
                    // Do nothing.
144
                    break;
145
 
146
                case quiz_attempt::FINISHED:
147
                    // Save answer and finish attempt.
148
                    $attemptobj->process_submitted_actions($timestart + 300, false, [
149
                            1 => ['answer' => 'My essay by ' . $student->firstname, 'answerformat' => FORMAT_PLAIN]]);
150
                    $attemptobj->process_finish($timestart + 600, false);
151
 
152
                    // Manually grade it.
153
                    $quba = $attemptobj->get_question_usage();
154
                    $quba->get_question_attempt(1)->manual_grade(
155
                            'Comment', $sumgrades, FORMAT_HTML, $timestart + 1200);
156
                    question_engine::save_questions_usage_by_activity($quba);
157
                    $update = new \stdClass();
158
                    $update->id = $attemptobj->get_attemptid();
159
                    $update->timemodified = $timestart + 1200;
160
                    $update->sumgrades = $quba->get_total_mark();
161
                    $DB->update_record('quiz_attempts', $update);
162
                    $attemptobj->get_quizobj()->get_grade_calculator()->recompute_final_grade($student->id);
163
                    break;
164
            }
165
        }
166
 
167
        // Actually getting the SQL to run is quite hard. Do a minimal set up of
168
        // some objects.
169
        $context = \context_module::instance($quiz->cmid);
170
        $cm = get_coursemodule_from_id('quiz', $quiz->cmid);
171
        $qmsubselect = quiz_report_qm_filter_select($quiz);
172
        $studentsjoins = get_enrolled_with_capabilities_join($context, '',
173
                ['mod/quiz:attempt', 'mod/quiz:reviewmyattempts']);
174
        $empty = new \core\dml\sql_join();
175
 
176
        // Set the options.
177
        $reportoptions = new quiz_overview_options('overview', $quiz, $cm, null);
178
        $reportoptions->attempts = attempts_report::ENROLLED_ALL;
179
        $reportoptions->onlygraded = true;
180
        $reportoptions->states = [quiz_attempt::IN_PROGRESS, quiz_attempt::OVERDUE, quiz_attempt::FINISHED];
181
 
182
        // Now do a minimal set-up of the table class.
183
        $q->slot = 1;
184
        $q->maxmark = 10;
185
        $table = new quiz_overview_table($quiz, $context, $qmsubselect, $reportoptions,
186
                $empty, $studentsjoins, [1 => $q], null);
187
        $table->download = $isdownloading; // Cannot call the is_downloading API, because it gives errors.
188
        $table->define_columns(['fullname']);
189
        $table->sortable(true, 'uniqueid');
190
        $table->define_baseurl(new \moodle_url('/mod/quiz/report.php'));
191
        $table->setup();
192
 
193
        // Run the query.
194
        $table->setup_sql_queries($studentsjoins);
195
        $table->query_db(30, false);
196
 
197
        // Should be 4 rows, matching count($table->rawdata) tested below.
198
        // The count is only done if not downloading.
199
        if (!$isdownloading) {
200
            $this->assertEquals(4, $table->totalrows);
201
        }
202
 
203
        // Verify what was returned: Student 1's best and in progress attempts.
204
        // Student 2's finshed attempt, and Student 3 with no attempt.
205
        // The array key is {student id}#{attempt number}.
206
        $this->assertEquals(4, count($table->rawdata));
207
        $this->assertArrayHasKey($student1->id . '#3', $table->rawdata);
208
        $this->assertEquals(1, $table->rawdata[$student1->id . '#3']->gradedattempt);
209
        $this->assertArrayHasKey($student1->id . '#3', $table->rawdata);
210
        $this->assertEquals(0, $table->rawdata[$student1->id . '#5']->gradedattempt);
211
        $this->assertArrayHasKey($student2->id . '#3', $table->rawdata);
212
        $this->assertEquals(1, $table->rawdata[$student2->id . '#3']->gradedattempt);
213
        $this->assertArrayHasKey($student3->id . '#0', $table->rawdata);
214
        $this->assertEquals(0, $table->rawdata[$student3->id . '#0']->gradedattempt);
215
 
216
        // Check the calculation of averages.
217
        $averagerow = $table->compute_average_row('overallaverage', $studentsjoins);
218
        $this->assertStringContainsString('75.00', $averagerow['sumgrades']);
219
        $this->assertStringContainsString('75.00', $averagerow['qsgrade1']);
220
        if (!$isdownloading) {
221
            $this->assertStringContainsString('(2)', $averagerow['sumgrades']);
222
            $this->assertStringContainsString('(2)', $averagerow['qsgrade1']);
223
        }
224
 
225
        // Ensure that filtering by initial does not break it.
226
        // This involves setting a private properly of the base class, which is
227
        // only really possible using reflection :-(.
228
        $reflectionobject = new \ReflectionObject($table);
229
        while ($parent = $reflectionobject->getParentClass()) {
230
            $reflectionobject = $parent;
231
        }
232
        $prefsproperty = $reflectionobject->getProperty('prefs');
233
        $prefs = $prefsproperty->getValue($table);
234
        $prefs['i_first'] = 'A';
235
        $prefsproperty->setValue($table, $prefs);
236
 
237
        list($fields, $from, $where, $params) = $table->base_sql($studentsjoins);
238
        $table->set_count_sql("SELECT COUNT(1) FROM (SELECT $fields FROM $from WHERE $where) temp WHERE 1 = 1", $params);
239
        $table->set_sql($fields, $from, $where, $params);
240
        $table->query_db(30, false);
241
        // Just verify that this does not cause a fatal error.
242
    }
243
 
244
    /**
245
     * Bands provider.
246
     * @return array
247
     */
248
    public function get_bands_count_and_width_provider(): array {
249
        return [
250
            [10, [20, .5]],
251
            [20, [20, 1]],
252
            [30, [15, 2]],
253
            // TODO MDL-55068 Handle bands better when grade is 50.
254
            // [50, [10, 5]],
255
            [100, [20, 5]],
256
            [200, [20, 10]],
257
        ];
258
    }
259
 
260
    /**
261
     * Test bands.
262
     *
263
     * @dataProvider get_bands_count_and_width_provider
264
     * @param int $grade grade
265
     * @param array $expected
266
     */
267
    public function test_get_bands_count_and_width(int $grade, array $expected): void {
268
        $this->resetAfterTest();
269
        $quizgenerator = $this->getDataGenerator()->get_plugin_generator('mod_quiz');
270
        $quiz = $quizgenerator->create_instance(['course' => SITEID, 'grade' => $grade]);
271
        $this->assertEquals($expected, quiz_overview_report::get_bands_count_and_width($quiz));
272
    }
273
 
274
    /**
275
     * Test delete_selected_attempts function.
276
     */
277
    public function test_delete_selected_attempts(): void {
278
        $this->resetAfterTest();
279
 
280
        $timestamp = 1234567890;
281
        $timestart = $timestamp + 3600;
282
 
283
        // Create a course and a quiz.
284
        $generator = $this->getDataGenerator();
285
        $course = $generator->create_course();
286
        $quizgenerator = $generator->get_plugin_generator('mod_quiz');
287
        $quiz = $quizgenerator->create_instance([
288
                'course' => $course->id,
289
                'grademethod' => QUIZ_GRADEHIGHEST,
290
                'grade' => 100.0,
291
                'sumgrades' => 10.0,
292
                'attempts' => 10
293
        ]);
294
 
295
        // Add one question.
296
        /** @var core_question_generator $questiongenerator */
297
        $questiongenerator = $this->getDataGenerator()->get_plugin_generator('core_question');
298
        $cat = $questiongenerator->create_question_category();
299
        $q = $questiongenerator->create_question('essay', 'plain', ['category' => $cat->id]);
300
        quiz_add_quiz_question($q->id, $quiz, 0 , 10);
301
 
302
        // Create student and enrol them in the course.
303
        // Note: we create two enrolments, to test the problem reported in MDL-67942.
304
        $student = $generator->create_user();
305
        $generator->enrol_user($student->id, $course->id);
306
        $generator->enrol_user($student->id, $course->id, null, 'self');
307
 
308
        $context = \context_module::instance($quiz->cmid);
309
        $cm = get_coursemodule_from_id('quiz', $quiz->cmid);
310
        $allowedjoins = get_enrolled_with_capabilities_join($context, '', ['mod/quiz:attempt', 'mod/quiz:reviewmyattempts']);
311
        $quizattemptsreport = new \testable_quiz_attempts_report();
312
 
313
        // Create the new attempt and initialize the question sessions.
314
        $quizobj = quiz_settings::create($quiz->id, $student->id);
315
        $quba = question_engine::make_questions_usage_by_activity('mod_quiz', $quizobj->get_context());
316
        $quba->set_preferred_behaviour($quizobj->get_quiz()->preferredbehaviour);
317
        $attempt = quiz_create_attempt($quizobj, 1, null, $timestart, false, $student->id);
318
        $attempt = quiz_start_new_attempt($quizobj, $quba, $attempt, 1, $timestamp);
319
        $attempt = quiz_attempt_save_started($quizobj, $quba, $attempt);
320
 
321
        // Delete the student's attempt.
322
        $quizattemptsreport->delete_selected_attempts($quiz, $cm, [$attempt->id], $allowedjoins);
323
    }
324
 
325
    /**
326
     * Test question regrade for selected versions.
327
     *
328
     * @covers ::regrade_question
329
     */
11 efrain 330
    public function test_regrade_question(): void {
1 efrain 331
        global $DB;
332
        $this->resetAfterTest();
333
        $this->setAdminUser();
334
 
335
        $course = $this->getDataGenerator()->create_course();
336
        $quiz = $this->create_test_quiz($course);
337
        $cm = get_fast_modinfo($course->id)->get_cm($quiz->cmid);
338
        $context = \context_module::instance($quiz->cmid);
339
 
340
        /** @var core_question_generator $questiongenerator */
341
        $questiongenerator = $this->getDataGenerator()->get_plugin_generator('core_question');
342
        // Create a couple of questions.
343
        $cat = $questiongenerator->create_question_category(['contextid' => $context->id]);
344
        $q = $questiongenerator->create_question('shortanswer', null,
345
                ['category' => $cat->id, 'name' => 'Toad scores 0.8']);
346
 
347
        // Create a version, the last one draft.
348
        // Sadly, update_question is a bit dodgy, so it can't handle updating the answer score.
349
        $q2 = $questiongenerator->update_question($q, null,
350
                ['name' => 'Toad now scores 1.0']);
351
        $toadanswer = $DB->get_record_select('question_answers',
352
                'question = ? AND ' . $DB->sql_compare_text('answer') . ' = ?',
353
                [$q2->id, 'toad'], '*', MUST_EXIST);
354
        $DB->set_field('question_answers', 'fraction', 1, ['id' => $toadanswer->id]);
355
 
356
        // Add the question to the quiz.
357
        quiz_add_quiz_question($q2->id, $quiz, 0, 10);
358
 
359
        // Attempt the quiz, submitting response 'toad'.
360
        $quizobj = quiz_settings::create($quiz->id);
361
        $attempt = quiz_prepare_and_start_new_attempt($quizobj, 1, null);
362
        $attemptobj = quiz_attempt::create($attempt->id);
363
        $attemptobj->process_submitted_actions(time(), false, [1 => ['answer' => 'toad']]);
364
        $attemptobj->process_finish(time(), false);
365
 
366
        // We should be using 'always latest' version, which is currently v2, so should be right.
367
        $this->assertEquals(10, $attemptobj->get_question_usage()->get_total_mark());
368
 
369
        // Now change the quiz to use fixed version 1.
370
        $slot = $quizobj->get_question($q2->id);
371
        submit_question_version::execute($slot->slotid, 1);
372
 
373
        // Regrade.
374
        $report = new quiz_overview_report();
375
        $report->init('overview', 'quiz_overview_settings_form', $quiz, $cm, $course);
376
        $report->regrade_attempt($attempt);
377
 
378
        // The mark should now be 8.
379
        $attemptobj = quiz_attempt::create($attempt->id);
380
        $this->assertEquals(8, $attemptobj->get_question_usage()->get_total_mark());
381
 
382
        // Now add two more versions, the second of which is draft.
383
        $q3 = $questiongenerator->update_question($q, null,
384
                ['name' => 'Toad now scores 0.5']);
385
        $toadanswer = $DB->get_record_select('question_answers',
386
                'question = ? AND ' . $DB->sql_compare_text('answer') . ' = ?',
387
                [$q3->id, 'toad'], '*', MUST_EXIST);
388
        $DB->set_field('question_answers', 'fraction', 0.5, ['id' => $toadanswer->id]);
389
 
390
        $q4 = $questiongenerator->update_question($q, null,
391
                ['name' => 'Toad now scores 0.3',
392
                    'status' => question_version_status::QUESTION_STATUS_DRAFT]);
393
        $toadanswer = $DB->get_record_select('question_answers',
394
                'question = ? AND ' . $DB->sql_compare_text('answer') . ' = ?',
395
                [$q4->id, 'toad'], '*', MUST_EXIST);
396
        $DB->set_field('question_answers', 'fraction', 0.3, ['id' => $toadanswer->id]);
397
 
398
        // Now change the quiz back to always latest and regrade again.
399
        submit_question_version::execute($slot->slotid, 0);
400
        $report->regrade_attempt($attempt);
401
 
402
        // Score should now be 5, because v3 is the latest non-draft version.
403
        $attemptobj = quiz_attempt::create($attempt->id);
404
        $this->assertEquals(5, $attemptobj->get_question_usage()->get_total_mark());
405
    }
406
}