Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1441 ariadna 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 mod_quiz\tests;
18
 
19
use question_engine;
20
use mod_quiz\quiz_settings;
21
use mod_quiz\quiz_attempt;
22
use stdClass;
23
 
24
/**
25
 * Quiz attempt walk through using data from csv file.
26
 *
27
 * @package    mod_quiz
28
 * @category   test
29
 * @copyright  2013 The Open University
30
 * @author     Jamie Pratt <me@jamiep.org>
31
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
32
 */
33
abstract class attempt_walkthrough_testcase extends \advanced_testcase {
34
    use question_helper_test_trait;
35
 
36
    /**
37
     * @var stdClass the quiz record we create.
38
     */
39
    protected $quiz;
40
 
41
    /**
42
     * @var array with slot no => question name => questionid. Question ids of questions created in the same category as random q.
43
     */
44
    protected $randqids;
45
 
46
    /**
47
     * Get the list of files which contain test data.
48
     *
49
     * @return array
50
     */
51
    protected static function get_test_files(): array {
52
        return [];
53
    }
54
 
55
    /**
56
     * Get the component name.
57
     *
58
     * @return string
59
     */
60
    protected static function get_component(): string {
61
        // If the late-static class name is namespaced, use the first part of the namespace.
62
        if (str_contains(static::class, '\\')) {
63
            return explode('\\', static::class)[0];
64
        }
65
 
66
        // Otherwise we have to assume that the test name is correctly frankenstyle named.
67
        return implode(
68
            '_',
69
            array_slice(
70
                explode('_', static::class, 3),
71
                0,
72
                2,
73
            )
74
        );
75
    }
76
 
77
    /**
78
     * Get the full path of the csv file.
79
     *
80
     * @param string $setname
81
     * @param string $test
82
     * @return string
83
     */
84
    protected static function get_full_path_of_csv_file(string $setname, string $test): string {
85
        return static::get_fixture_path(static::get_component(), "{$setname}{$test}.csv");
86
    }
87
 
88
    /**
89
     * The only test in this class. This is run multiple times depending on how many sets of files there are in fixtures/
90
     * directory.
91
     *
92
     * @param array $quizsettings of settings read from csv file quizzes.csv
93
     * @param array $csvdata of data read from csv file "questionsXX.csv", "stepsXX.csv" and "resultsXX.csv".
94
     * // phpcs:ignore moodle.Commenting.ValidTags.Invalid
95
     * @dataProvider get_data_for_walkthrough
96
     */
97
    public function test_walkthrough_from_csv($quizsettings, $csvdata): void {
98
        // CSV data files for these tests were generated using:
99
        // https://github.com/jamiepratt/moodle-quiz-tools/tree/master/responsegenerator.
100
 
101
        $this->create_quiz_simulate_attempts_and_check_results($quizsettings, $csvdata);
102
    }
103
 
104
    /**
105
     * Create a quiz, add questions to it, and simulate attempts on it.
106
     *
107
     * @param array $quizsettings Quiz overrides for this quiz.
108
     * @param array $csvdata Data loaded from csv files for this test.
109
     */
110
    public function create_quiz($quizsettings, $qs) {
111
        global $SITE, $DB;
112
        $this->setAdminUser();
113
 
114
        /** @var core_question_generator $questiongenerator */
115
        $questiongenerator = $this->getDataGenerator()->get_plugin_generator('core_question');
116
        $slots = [];
117
        $qidsbycat = [];
118
        $sumofgrades = 0;
119
        foreach ($qs as $qsrow) {
120
            $q = $this->explode_dot_separated_keys_to_make_subindexs($qsrow);
121
 
122
            $catname = ['name' => $q['cat']];
123
            if (!$cat = $DB->get_record('question_categories', ['name' => $q['cat']])) {
124
                $cat = $questiongenerator->create_question_category($catname);
125
            }
126
            $q['catid'] = $cat->id;
127
            foreach (['which' => null, 'overrides' => []] as $key => $default) {
128
                if (empty($q[$key])) {
129
                    $q[$key] = $default;
130
                }
131
            }
132
 
133
            if ($q['type'] !== 'random') {
134
                // Don't actually create random questions here.
135
                $overrides = ['category' => $cat->id, 'defaultmark' => $q['mark']] + $q['overrides'];
136
                if ($q['type'] === 'truefalse') {
137
                    // True/false question can never have hints, but sometimes we need to put them
138
                    // in the CSV file, to keep it rectangular.
139
                    unset($overrides['hint']);
140
                }
141
                $question = $questiongenerator->create_question($q['type'], $q['which'], $overrides);
142
                $q['id'] = $question->id;
143
 
144
                if (!isset($qidsbycat[$q['cat']])) {
145
                    $qidsbycat[$q['cat']] = [];
146
                }
147
                if (!empty($q['which'])) {
148
                    $name = $q['type'] . '_' . $q['which'];
149
                } else {
150
                    $name = $q['type'];
151
                }
152
                $qidsbycat[$q['catid']][$name] = $q['id'];
153
            }
154
            if (!empty($q['slot'])) {
155
                $slots[$q['slot']] = $q;
156
                $sumofgrades += $q['mark'];
157
            }
158
        }
159
 
160
        ksort($slots);
161
 
162
        // Make a quiz.
163
        $quizgenerator = $this->getDataGenerator()->get_plugin_generator('mod_quiz');
164
 
165
        // Settings from param override defaults.
166
        $aggregratedsettings = $quizsettings + ['course' => $SITE->id,
167
                                                     'questionsperpage' => 0,
168
                                                     'grade' => 100.0,
169
                                                     'sumgrades' => $sumofgrades];
170
 
171
        $this->quiz = $quizgenerator->create_instance($aggregratedsettings);
172
 
173
        $this->randqids = [];
174
        foreach ($slots as $slotno => $slotquestion) {
175
            if ($slotquestion['type'] !== 'random') {
176
                quiz_add_quiz_question($slotquestion['id'], $this->quiz, 0, $slotquestion['mark']);
177
            } else {
178
                $this->add_random_questions($this->quiz->id, 0, $slotquestion['catid'], 1);
179
                $this->randqids[$slotno] = $qidsbycat[$slotquestion['catid']];
180
            }
181
        }
182
    }
183
 
184
    /**
185
     * Create quiz, simulate attempts and check results (if resultsXX.csv exists).
186
     *
187
     * @param array $quizsettings Quiz overrides for this quiz.
188
     * @param array $csvdata Data loaded from csv files for this test.
189
     */
190
    protected function create_quiz_simulate_attempts_and_check_results(array $quizsettings, array $csvdata) {
191
        $this->resetAfterTest();
192
 
193
        $this->create_quiz($quizsettings, $csvdata['questions']);
194
 
195
        $attemptids = $this->walkthrough_attempts($csvdata['steps']);
196
 
197
        if (isset($csvdata['results'])) {
198
            $this->check_attempts_results($csvdata['results'], $attemptids);
199
        }
200
    }
201
 
202
    /**
203
     * Load dataset from CSV file "{$setname}{$test}.csv".
204
     *
205
     * @param string $setname
206
     * @param string $test
207
     * @return array
208
     */
209
    protected static function load_csv_data_file(string $setname, string $test = ''): array {
210
        $files = [$setname => static::get_full_path_of_csv_file($setname, $test)];
211
        return static::dataset_from_files($files)->get_rows([$setname]);
212
    }
213
 
214
    /**
215
     * Break down row of csv data into sub arrays, according to column names.
216
     *
217
     * @param array $row from csv file with field names with parts separate by '.'.
218
     * @return array the row with each part of the field name following a '.' being a separate sub array's index.
219
     */
220
    protected function explode_dot_separated_keys_to_make_subindexs(array $row): array {
221
        $parts = [];
222
        foreach ($row as $columnkey => $value) {
223
            $newkeys = explode('.', trim($columnkey));
224
            $placetoputvalue =& $parts;
225
            foreach ($newkeys as $newkeydepth => $newkey) {
226
                if ($newkeydepth + 1 === count($newkeys)) {
227
                    $placetoputvalue[$newkey] = $value;
228
                } else {
229
                    // Going deeper down.
230
                    if (!isset($placetoputvalue[$newkey])) {
231
                        $placetoputvalue[$newkey] = [];
232
                    }
233
                    $placetoputvalue =& $placetoputvalue[$newkey];
234
                }
235
            }
236
        }
237
        return $parts;
238
    }
239
 
240
    /**
241
     * Data provider method for test_walkthrough_from_csv. Called by PHPUnit.
242
     *
243
     * @return array One array element for each run of the test. Each element contains an array with the params for
244
     *                  test_walkthrough_from_csv.
245
     */
246
    public static function get_data_for_walkthrough(): array {
247
        $quizzes = self::load_csv_data_file('quizzes')['quizzes'];
248
        $datasets = [];
249
        foreach ($quizzes as $quizsettings) {
250
            $dataset = [];
251
            foreach (static::get_test_files() as $file) {
252
                if (file_exists(static::get_full_path_of_csv_file($file, $quizsettings['testnumber']))) {
253
                    $dataset[$file] = self::load_csv_data_file($file, $quizsettings['testnumber'])[$file];
254
                }
255
            }
256
            $datasets[] = [$quizsettings, $dataset];
257
        }
258
        return $datasets;
259
    }
260
 
261
    /**
262
     * Helper to walk through attempts.
263
     *
264
     * @param array $steps the step data from the csv file.
265
     * @return array attempt no as in csv file => the id of the quiz_attempt as stored in the db.
266
     */
267
    protected function walkthrough_attempts(array $steps): array {
268
        global $DB;
269
        $attemptids = [];
270
        foreach ($steps as $steprow) {
271
            $step = $this->explode_dot_separated_keys_to_make_subindexs($steprow);
272
            // Find existing user or make a new user to do the quiz.
273
            $username = ['firstname' => $step['firstname'],
274
                              'lastname'  => $step['lastname']];
275
 
276
            if (!$user = $DB->get_record('user', $username)) {
277
                $user = $this->getDataGenerator()->create_user($username);
278
            }
279
 
280
            if (!isset($attemptids[$step['quizattempt']])) {
281
                // Start the attempt.
282
                $quizobj = quiz_settings::create($this->quiz->id, $user->id);
283
                $quba = question_engine::make_questions_usage_by_activity('mod_quiz', $quizobj->get_context());
284
                $quba->set_preferred_behaviour($quizobj->get_quiz()->preferredbehaviour);
285
 
286
                $prevattempts = quiz_get_user_attempts($this->quiz->id, $user->id, 'all', true);
287
                $attemptnumber = count($prevattempts) + 1;
288
                $timenow = time();
289
                $attempt = quiz_create_attempt($quizobj, $attemptnumber, null, $timenow, false, $user->id);
290
                // Select variant and / or random sub question.
291
                if (!isset($step['variants'])) {
292
                    $step['variants'] = [];
293
                }
294
                if (isset($step['randqs'])) {
295
                    // Replace 'names' with ids.
296
                    foreach ($step['randqs'] as $slotno => $randqname) {
297
                        $step['randqs'][$slotno] = $this->randqids[$slotno][$randqname];
298
                    }
299
                } else {
300
                    $step['randqs'] = [];
301
                }
302
 
303
                quiz_start_new_attempt($quizobj, $quba, $attempt, $attemptnumber, $timenow, $step['randqs'], $step['variants']);
304
                quiz_attempt_save_started($quizobj, $quba, $attempt);
305
                $attemptid = $attemptids[$step['quizattempt']] = $attempt->id;
306
            } else {
307
                $attemptid = $attemptids[$step['quizattempt']];
308
            }
309
 
310
            // Process some responses from the student.
311
            $attemptobj = quiz_attempt::create($attemptid);
312
            $attemptobj->process_submitted_actions($timenow, false, $step['responses']);
313
 
314
            // Finish the attempt.
315
            if (!isset($step['finished']) || ($step['finished'] == 1)) {
316
                $attemptobj = quiz_attempt::create($attemptid);
317
                $attemptobj->process_submit($timenow, false);
318
                $attemptobj->process_grade_submission($timenow);
319
            }
320
        }
321
        return $attemptids;
322
    }
323
 
324
    /**
325
     * Assertion helper to check attempt results.
326
     *
327
     * @param array $results the results data from the csv file.
328
     * @param array $attemptids attempt no as in csv file => the id of the quiz_attempt as stored in the db.
329
     */
330
    protected function check_attempts_results(array $results, array $attemptids) {
331
        foreach ($results as $resultrow) {
332
            $result = $this->explode_dot_separated_keys_to_make_subindexs($resultrow);
333
            // Re-load quiz attempt data.
334
            $attemptobj = quiz_attempt::create($attemptids[$result['quizattempt']]);
335
            $this->check_attempt_results($result, $attemptobj);
336
        }
337
    }
338
 
339
    /**
340
     * Check that attempt results are as specified in $result.
341
     *
342
     * @param array        $result             row of data read from csv file.
343
     * @param quiz_attempt $attemptobj         the attempt object loaded from db.
344
     */
345
    protected function check_attempt_results(array $result, quiz_attempt $attemptobj) {
346
        foreach ($result as $fieldname => $value) {
347
            if ($value === '!NULL!') {
348
                $value = null;
349
            }
350
            switch ($fieldname) {
351
                case 'quizattempt':
352
                    break;
353
                case 'attemptnumber':
354
                    $this->assertEquals($value, $attemptobj->get_attempt_number());
355
                    break;
356
                case 'slots':
357
                    foreach ($value as $slotno => $slottests) {
358
                        foreach ($slottests as $slotfieldname => $slotvalue) {
359
                            switch ($slotfieldname) {
360
                                case 'mark':
361
                                    $this->assertEquals(
362
                                        round($slotvalue, 2),
363
                                        $attemptobj->get_question_mark($slotno),
364
                                        "Mark for slot $slotno of attempt {$result['quizattempt']}."
365
                                    );
366
                                    break;
367
                                default:
368
                                    throw new \coding_exception('Unknown slots sub field column in csv file '
369
                                                               . s($slotfieldname));
370
                            }
371
                        }
372
                    }
373
                    break;
374
                case 'finished':
375
                    $this->assertEquals((bool)$value, $attemptobj->is_finished());
376
                    break;
377
                case 'summarks':
378
                    $this->assertEquals(
379
                        (float)$value,
380
                        $attemptobj->get_sum_marks(),
381
                        "Sum of marks of attempt {$result['quizattempt']}."
382
                    );
383
                    break;
384
                case 'quizgrade':
385
                    // Check quiz grades.
386
                    $grades = quiz_get_user_grades($attemptobj->get_quiz(), $attemptobj->get_userid());
387
                    $grade = array_shift($grades);
388
                    $this->assertEquals($value, $grade->rawgrade, "Quiz grade for attempt {$result['quizattempt']}.");
389
                    break;
390
                case 'gradebookgrade':
391
                    // Check grade book.
392
                    $gradebookgrades = grade_get_grades(
393
                        $attemptobj->get_courseid(),
394
                        'mod',
395
                        'quiz',
396
                        $attemptobj->get_quizid(),
397
                        $attemptobj->get_userid()
398
                    );
399
                    $gradebookitem = array_shift($gradebookgrades->items);
400
                    $gradebookgrade = array_shift($gradebookitem->grades);
401
                    $this->assertEquals($value, $gradebookgrade->grade, "Gradebook grade for attempt {$result['quizattempt']}.");
402
                    break;
403
                default:
404
                    throw new \coding_exception('Unknown column in csv file ' . s($fieldname));
405
            }
406
        }
407
    }
408
}