MDL-41540 remove use of $USER
[moodle.git] / mod / quiz / tests / attempt_walkthrough_from_csv_test.php
CommitLineData
da6bb0c5
JP
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 * Quiz attempt walk through using data from csv file.
19 *
20 * @package mod_quiz
21 * @category phpunit
22 * @copyright 2013 The Open University
23 * @author Jamie Pratt <me@jamiep.org>
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 */
26
27defined('MOODLE_INTERNAL') || die();
28
29global $CFG;
30require_once($CFG->dirroot . '/mod/quiz/editlib.php');
31require_once($CFG->dirroot . '/mod/quiz/locallib.php');
32
33/**
34 * Quiz attempt walk through using data from csv file.
35 *
36 * @package mod_quiz
37 * @category phpunit
38 * @copyright 2013 The Open University
39 * @author Jamie Pratt <me@jamiep.org>
40 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
41 */
42class mod_quiz_attempt_walkthrough_from_csv_testcase extends advanced_testcase {
43
44 /**
45 * @var array postfix number for sets of csv files to load data from.
46 */
47 protected $tests = array('00');
48
3652dddd
JP
49 protected $files = array('questions', 'steps', 'results');
50
da6bb0c5
JP
51 /**
52 * @var stdClass the quiz record we create.
53 */
54 protected $quiz;
55
56 /**
57 * @var array with slot no => question name => questionid. Question ids of questions created in the same category as random q.
58 */
59 protected $randqids;
60
61 public function create_quiz($qs) {
62 global $SITE, $DB;
63 $this->setAdminUser();
64
65 $questiongenerator = $this->getDataGenerator()->get_plugin_generator('core_question');
66 $slots = array();
67 $qidsbycat = array();
68 $sumofgrades = 0;
69 for ($rowno = 0; $rowno < $qs->getRowCount(); $rowno++) {
70 $q = $this->explode_dot_separated_keys_to_make_subindexs($qs->getRow($rowno));
71
72 $catname = array('name' => $q['cat']);
73 if (!$cat = $DB->get_record('question_categories', array('name' => $q['cat']))) {
74 $cat = $questiongenerator->create_question_category($catname);
75 }
76 $q['catid'] = $cat->id;
77 foreach (array('which' => null, 'overrides' => array()) as $key => $default) {
78 if (empty($q[$key])) {
79 $q[$key] = $default;
80 }
81 }
82
83 if ($q['type'] !== 'random') {
84 // Don't actually create random questions here.
85 $overrides = array('category' => $cat->id, 'defaultmark' => $q['mark']) + $q['overrides'];
86 $question = $questiongenerator->create_question($q['type'], $q['which'], $overrides);
87 $q['id'] = $question->id;
88
89 if (!isset($qidsbycat[$q['cat']])) {
90 $qidsbycat[$q['cat']] = array();
91 }
92 if (!empty($q['which'])) {
93 $name = $q['type'].'_'.$q['which'];
94 } else {
95 $name = $q['type'];
96 }
97 $qidsbycat[$q['catid']][$name] = $q['id'];
98 }
99 if (!empty($q['slot'])) {
100 $slots[$q['slot']] = $q;
101 $sumofgrades += $q['mark'];
102 }
103 }
104
105 ksort($slots);
106
107 // Make a quiz.
108 $quizgenerator = $this->getDataGenerator()->get_plugin_generator('mod_quiz');
109 $this->quiz = $quizgenerator->create_instance(array('course'=>$SITE->id,
110 'questionsperpage' => 0,
111 'grade' => 100.0,
112 'sumgrades' => $sumofgrades));
113
114 $this->randqids = array();
115 foreach ($slots as $slotno => $slotquestion) {
116 if ($slotquestion['type'] !== 'random') {
117 quiz_add_quiz_question($slotquestion['id'], $this->quiz, 0);
118 // Setting default mark above does not affect the grade for multi-answer question type (and maybe others??).
119 // Set the mark again just to be sure.
120 quiz_update_question_instance($slotquestion['mark'], $slotquestion['id'], $this->quiz);
121 } else {
122 quiz_add_random_questions($this->quiz, 0, $slotquestion['catid'], 1, 0);
123 $this->randqids[$slotno] = $qidsbycat[$slotquestion['catid']];
124 }
125 }
126 }
127
da6bb0c5
JP
128 /**
129 * Get full path of CSV file.
130 *
131 * @param string $setname
132 * @param string $test
133 * @return string full path of file.
134 */
135 protected function get_full_path_of_csv_file($setname, $test) {
136 return __DIR__."/fixtures/{$setname}{$test}.csv";
137 }
138
139 /**
140 * Load dataset from CSV file "{$setname}{$test}.csv".
141 *
142 * @param string $setname
143 * @param string $test
144 * @return \PHPUnit_Extensions_Database_DataSet_ITable
145 */
146 protected function load_csv_data_file($setname, $test) {
147 $files = array($setname => $this->get_full_path_of_csv_file($setname, $test));
148 return $this->createCsvDataSet($files)->getTable($setname);
149 }
150
e39a2faa
JP
151 /**
152 * Break down row of csv data into sub arrays, according to column names.
153 *
154 * @param array $row from csv file with field names with parts separate by '.'.
155 * @return array the row with each part of the field name following a '.' being a separate sub array's index.
156 */
157 protected function explode_dot_separated_keys_to_make_subindexs(array $row) {
158 $parts = array();
159 foreach ($row as $columnkey => $value) {
160 $newkeys = explode('.', trim($columnkey));
161 $placetoputvalue =& $parts;
162 foreach ($newkeys as $newkeydepth => $newkey) {
163 if ($newkeydepth + 1 === count($newkeys)) {
164 $placetoputvalue[$newkey] = $value;
165 } else {
166 // Going deeper down.
167 if (!isset($placetoputvalue[$newkey])) {
168 $placetoputvalue[$newkey] = array();
169 }
170 $placetoputvalue =& $placetoputvalue[$newkey];
171 }
172 }
173 }
174 return $parts;
175 }
176
3652dddd
JP
177 /**
178 * Data provider method for test_walkthrough_from_csv. Called by PHPUnit.
179 *
180 * @return array One array element for each run of the test. Each element contains an array with the one param for
181 * test_walkthrough_from_csv.
182 */
183 public function get_data_for_walkthrough() {
184 $datasets = array();
185 foreach ($this->tests as $test) {
186 $dataset = array();
187 foreach ($this->files as $file) {
188 $dataset[$file] = $this->load_csv_data_file($file, $test);
189 }
190 $datasets[] = array($dataset);
191 }
192 return $datasets;
193 }
194
da6bb0c5
JP
195 /**
196 * Create a quiz add questions to it, walk through quiz attempts and then check results.
197 *
3652dddd
JP
198 * @param PHPUnit_Extensions_Database_DataSet_ITable[] of data read from csv file "questionsXX.csv",
199 * "stepsXX.csv" and "resultsXX.csv".
da6bb0c5
JP
200 * @dataProvider get_data_for_walkthrough
201 */
3652dddd
JP
202 public function test_walkthrough_from_csv($csvdata) {
203
204 // CSV data files for these tests were generated using :
205 // https://github.com/jamiepratt/moodle-quiz-tools/tree/master/responsegenerator
206
da6bb0c5
JP
207 $this->resetAfterTest(true);
208 question_bank::get_qtype('random')->clear_caches_before_testing();
209
3652dddd
JP
210 $this->create_quiz($csvdata['questions']);
211
212 $attemptids = $this->walkthrough_attempts($csvdata['steps']);
da6bb0c5 213
3652dddd
JP
214 $this->check_attempts_results($csvdata['results'], $attemptids);
215 }
216
217 /**
218 * @param $steps PHPUnit_Extensions_Database_DataSet_ITable the step data from the csv file.
219 * @return array attempt no as in csv file => the id of the quiz_attempt as stored in the db.
220 */
221 protected function walkthrough_attempts($steps) {
222 global $DB;
e39a2faa 223 $attemptids = array();
da6bb0c5
JP
224 for ($rowno = 0; $rowno < $steps->getRowCount(); $rowno++) {
225
226 $step = $this->explode_dot_separated_keys_to_make_subindexs($steps->getRow($rowno));
227 // Find existing user or make a new user to do the quiz.
228 $username = array('firstname' => $step['firstname'],
3652dddd 229 'lastname' => $step['lastname']);
da6bb0c5
JP
230
231 if (!$user = $DB->get_record('user', $username)) {
232 $user = $this->getDataGenerator()->create_user($username);
233 }
da6bb0c5
JP
234 // Start the attempt.
235 $quizobj = quiz::create($this->quiz->id, $user->id);
236 $quba = question_engine::make_questions_usage_by_activity('mod_quiz', $quizobj->get_context());
237 $quba->set_preferred_behaviour($quizobj->get_quiz()->preferredbehaviour);
238
239 $timenow = time();
70782526 240 $attempt = quiz_create_attempt($quizobj, 1, false, $timenow, false, $user->id);
da6bb0c5
JP
241 // Select variant and / or random sub question.
242 if (!isset($step['variants'])) {
243 $step['variants'] = array();
244 }
245 if (isset($step['randqs'])) {
246 // Replace 'names' with ids.
247 foreach ($step['randqs'] as $slotno => $randqname) {
248 $step['randqs'][$slotno] = $this->randqids[$slotno][$randqname];
249 }
250 } else {
251 $step['randqs'] = array();
252 }
253 quiz_start_new_attempt($quizobj, $quba, $attempt, 1, $timenow, $step['randqs'], $step['variants']);
254 quiz_attempt_save_started($quizobj, $quba, $attempt);
255
e39a2faa
JP
256 $attemptids[$step['quizattempt']] = $attempt->id;
257
da6bb0c5
JP
258 // Process some responses from the student.
259 $attemptobj = quiz_attempt::create($attempt->id);
260 $attemptobj->process_submitted_actions($timenow, false, $step['responses']);
261
262 // Finish the attempt.
263 $attemptobj = quiz_attempt::create($attempt->id);
264 $attemptobj->process_finish($timenow, false);
265
e39a2faa 266 }
3652dddd
JP
267 return $attemptids;
268 }
e39a2faa 269
3652dddd
JP
270 /**
271 * @param $results PHPUnit_Extensions_Database_DataSet_ITable the results data from the csv file.
272 * @param $attemptids array attempt no as in csv file => the id of the quiz_attempt as stored in the db.
273 */
274 protected function check_attempts_results($results, $attemptids) {
e39a2faa
JP
275 for ($rowno = 0; $rowno < $results->getRowCount(); $rowno++) {
276 $result = $this->explode_dot_separated_keys_to_make_subindexs($results->getRow($rowno));
da6bb0c5 277 // Re-load quiz attempt data.
e39a2faa
JP
278 $attemptobj = quiz_attempt::create($attemptids[$result['quizattempt']]);
279 $this->check_attempt_results($result, $attemptobj);
da6bb0c5
JP
280 }
281 }
282
283 /**
e39a2faa 284 * Check that attempt results are as specified in $result.
da6bb0c5 285 *
e39a2faa
JP
286 * @param array $result row of data read from csv file.
287 * @param quiz_attempt $attemptobj the attempt object loaded from db.
288 * @throws coding_exception
da6bb0c5 289 */
e39a2faa
JP
290 protected function check_attempt_results($result, $attemptobj) {
291 foreach ($result as $fieldname => $value) {
292 switch ($fieldname) {
293 case 'quizattempt' :
294 break;
295 case 'attemptnumber' :
296 $this->assertEquals($value, $attemptobj->get_attempt_number());
297 break;
298 case 'slots' :
299 foreach ($value as $slotno => $slottests) {
300 foreach ($slottests as $slotfieldname => $slotvalue) {
301 switch ($slotfieldname) {
302 case 'mark' :
303 $this->assertEquals(round($slotvalue, 2), $attemptobj->get_question_mark($slotno),
304 "Mark for slot $slotno of attempt {$result['quizattempt']}.");
305 break;
306 default :
307 throw new coding_exception('Unknown slots sub field column in csv file '
3652dddd 308 .s($slotfieldname));
e39a2faa
JP
309 }
310 }
da6bb0c5 311 }
e39a2faa
JP
312 break;
313 case 'finished' :
314 $this->assertEquals($value, $attemptobj->is_finished());
315 break;
316 case 'summarks' :
317 $this->assertEquals($value, $attemptobj->get_sum_marks(), "Sum of marks of attempt {$result['quizattempt']}.");
318 break;
319 case 'quizgrade' :
320 // Check quiz grades.
321 $grades = quiz_get_user_grades($attemptobj->get_quiz(), $attemptobj->get_userid());
322 $grade = array_shift($grades);
323 $this->assertEquals($value, $grade->rawgrade, "Quiz grade for attempt {$result['quizattempt']}.");
324 break;
325 case 'gradebookgrade' :
326 // Check grade book.
327 $gradebookgrades = grade_get_grades($attemptobj->get_courseid(),
328 'mod', 'quiz',
329 $attemptobj->get_quizid(),
330 $attemptobj->get_userid());
331 $gradebookitem = array_shift($gradebookgrades->items);
332 $gradebookgrade = array_shift($gradebookitem->grades);
333 $this->assertEquals($value, $gradebookgrade->grade, "Gradebook grade for attempt {$result['quizattempt']}.");
334 break;
335 default :
336 throw new coding_exception('Unknown column in csv file '.s($fieldname));
da6bb0c5
JP
337 }
338 }
da6bb0c5
JP
339 }
340}