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