Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.11.x will end 14 Nov 2022 (12 months plus 6 months extension).
  • Bug fixes for security issues in 3.11.x will end 13 Nov 2023 (18 months plus 12 months extension).
  • PHP version: minimum PHP 7.3.0 Note: minimum PHP version has increased since Moodle 3.10. PHP 7.4.x is supported too.

Differences Between: [Versions 310 and 311] [Versions 311 and 400] [Versions 311 and 401] [Versions 311 and 402] [Versions 311 and 403] [Versions 39 and 311]

   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;
  18  
  19  use question_bank;
  20  use question_engine;
  21  use quiz;
  22  use quiz_attempt;
  23  
  24  defined('MOODLE_INTERNAL') || die();
  25  
  26  global $CFG;
  27  require_once($CFG->dirroot . '/mod/quiz/locallib.php');
  28  
  29  /**
  30   * Quiz attempt walk through using data from csv file.
  31   *
  32   * @package    mod_quiz
  33   * @category   test
  34   * @copyright  2013 The Open University
  35   * @author     Jamie Pratt <me@jamiep.org>
  36   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  37   */
  38  class attempt_walkthrough_from_csv_test extends \advanced_testcase {
  39  
  40      protected $files = array('questions', 'steps', 'results');
  41  
  42      /**
  43       * @var stdClass the quiz record we create.
  44       */
  45      protected $quiz;
  46  
  47      /**
  48       * @var array with slot no => question name => questionid. Question ids of questions created in the same category as random q.
  49       */
  50      protected $randqids;
  51  
  52      /**
  53       * The only test in this class. This is run multiple times depending on how many sets of files there are in fixtures/
  54       * directory.
  55       *
  56       * @param array $quizsettings of settings read from csv file quizzes.csv
  57       * @param array $csvdata of data read from csv file "questionsXX.csv", "stepsXX.csv" and "resultsXX.csv".
  58       * @dataProvider get_data_for_walkthrough
  59       */
  60      public function test_walkthrough_from_csv($quizsettings, $csvdata) {
  61  
  62          // CSV data files for these tests were generated using :
  63          // https://github.com/jamiepratt/moodle-quiz-tools/tree/master/responsegenerator
  64  
  65          $this->create_quiz_simulate_attempts_and_check_results($quizsettings, $csvdata);
  66      }
  67  
  68      public function create_quiz($quizsettings, $qs) {
  69          global $SITE, $DB;
  70          $this->setAdminUser();
  71  
  72          $questiongenerator = $this->getDataGenerator()->get_plugin_generator('core_question');
  73          $slots = array();
  74          $qidsbycat = array();
  75          $sumofgrades = 0;
  76          foreach ($qs as $qsrow) {
  77              $q = $this->explode_dot_separated_keys_to_make_subindexs($qsrow);
  78  
  79              $catname = array('name' => $q['cat']);
  80              if (!$cat = $DB->get_record('question_categories', array('name' => $q['cat']))) {
  81                  $cat = $questiongenerator->create_question_category($catname);
  82              }
  83              $q['catid'] = $cat->id;
  84              foreach (array('which' => null, 'overrides' => array()) as $key => $default) {
  85                  if (empty($q[$key])) {
  86                      $q[$key] = $default;
  87                  }
  88              }
  89  
  90              if ($q['type'] !== 'random') {
  91                  // Don't actually create random questions here.
  92                  $overrides = array('category' => $cat->id, 'defaultmark' => $q['mark']) + $q['overrides'];
  93                  if ($q['type'] === 'truefalse') {
  94                      // True/false question can never have hints, but sometimes we need to put them
  95                      // in the CSV file, to keep it rectangular.
  96                      unset($overrides['hint']);
  97                  }
  98                  $question = $questiongenerator->create_question($q['type'], $q['which'], $overrides);
  99                  $q['id'] = $question->id;
 100  
 101                  if (!isset($qidsbycat[$q['cat']])) {
 102                      $qidsbycat[$q['cat']] = array();
 103                  }
 104                  if (!empty($q['which'])) {
 105                      $name = $q['type'].'_'.$q['which'];
 106                  } else {
 107                      $name = $q['type'];
 108                  }
 109                  $qidsbycat[$q['catid']][$name] = $q['id'];
 110              }
 111              if (!empty($q['slot'])) {
 112                  $slots[$q['slot']] = $q;
 113                  $sumofgrades += $q['mark'];
 114              }
 115          }
 116  
 117          ksort($slots);
 118  
 119          // Make a quiz.
 120          $quizgenerator = $this->getDataGenerator()->get_plugin_generator('mod_quiz');
 121  
 122          // Settings from param override defaults.
 123          $aggregratedsettings = $quizsettings + array('course' => $SITE->id,
 124                                                       'questionsperpage' => 0,
 125                                                       'grade' => 100.0,
 126                                                       'sumgrades' => $sumofgrades);
 127  
 128          $this->quiz = $quizgenerator->create_instance($aggregratedsettings);
 129  
 130          $this->randqids = array();
 131          foreach ($slots as $slotno => $slotquestion) {
 132              if ($slotquestion['type'] !== 'random') {
 133                  quiz_add_quiz_question($slotquestion['id'], $this->quiz, 0, $slotquestion['mark']);
 134              } else {
 135                  quiz_add_random_questions($this->quiz, 0, $slotquestion['catid'], 1, 0);
 136                  $this->randqids[$slotno] = $qidsbycat[$slotquestion['catid']];
 137              }
 138          }
 139      }
 140  
 141      /**
 142       * Create quiz, simulate attempts and check results (if resultsXX.csv exists).
 143       *
 144       * @param array $quizsettings Quiz overrides for this quiz.
 145       * @param array $csvdata Data loaded from csv files for this test.
 146       */
 147      protected function create_quiz_simulate_attempts_and_check_results($quizsettings, $csvdata) {
 148          $this->resetAfterTest(true);
 149          question_bank::get_qtype('random')->clear_caches_before_testing();
 150  
 151          $this->create_quiz($quizsettings, $csvdata['questions']);
 152  
 153          $attemptids = $this->walkthrough_attempts($csvdata['steps']);
 154  
 155          if (isset($csvdata['results'])) {
 156              $this->check_attempts_results($csvdata['results'], $attemptids);
 157          }
 158      }
 159  
 160      /**
 161       * Get full path of CSV file.
 162       *
 163       * @param string $setname
 164       * @param string $test
 165       * @return string full path of file.
 166       */
 167      protected function get_full_path_of_csv_file($setname, $test) {
 168          return  __DIR__."/fixtures/{$setname}{$test}.csv";
 169      }
 170  
 171      /**
 172       * Load dataset from CSV file "{$setname}{$test}.csv".
 173       *
 174       * @param string $setname
 175       * @param string $test
 176       * @return array
 177       */
 178      protected function load_csv_data_file($setname, $test='') {
 179          $files = array($setname => $this->get_full_path_of_csv_file($setname, $test));
 180          return $this->dataset_from_files($files)->get_rows([$setname]);
 181      }
 182  
 183      /**
 184       * Break down row of csv data into sub arrays, according to column names.
 185       *
 186       * @param array $row from csv file with field names with parts separate by '.'.
 187       * @return array the row with each part of the field name following a '.' being a separate sub array's index.
 188       */
 189      protected function explode_dot_separated_keys_to_make_subindexs(array $row) {
 190          $parts = array();
 191          foreach ($row as $columnkey => $value) {
 192              $newkeys = explode('.', trim($columnkey));
 193              $placetoputvalue =& $parts;
 194              foreach ($newkeys as $newkeydepth => $newkey) {
 195                  if ($newkeydepth + 1 === count($newkeys)) {
 196                      $placetoputvalue[$newkey] = $value;
 197                  } else {
 198                      // Going deeper down.
 199                      if (!isset($placetoputvalue[$newkey])) {
 200                          $placetoputvalue[$newkey] = array();
 201                      }
 202                      $placetoputvalue =& $placetoputvalue[$newkey];
 203                  }
 204              }
 205          }
 206          return $parts;
 207      }
 208  
 209      /**
 210       * Data provider method for test_walkthrough_from_csv. Called by PHPUnit.
 211       *
 212       * @return array One array element for each run of the test. Each element contains an array with the params for
 213       *                  test_walkthrough_from_csv.
 214       */
 215      public function get_data_for_walkthrough() {
 216          $quizzes = $this->load_csv_data_file('quizzes')['quizzes'];
 217          $datasets = array();
 218          foreach ($quizzes as $quizsettings) {
 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'])[$file];
 223                  }
 224              }
 225              $datasets[] = array($quizsettings, $dataset);
 226          }
 227          return $datasets;
 228      }
 229  
 230      /**
 231       * @param $steps array 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          foreach ($steps as $steprow) {
 238  
 239              $step = $this->explode_dot_separated_keys_to_make_subindexs($steprow);
 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 array 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          foreach ($results as $resultrow) {
 297              $result = $this->explode_dot_separated_keys_to_make_subindexs($resultrow);
 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((float)$value, $attemptobj->get_sum_marks(),
 342                          "Sum of marks of attempt {$result['quizattempt']}.");
 343                      break;
 344                  case 'quizgrade' :
 345                      // Check quiz grades.
 346                      $grades = quiz_get_user_grades($attemptobj->get_quiz(), $attemptobj->get_userid());
 347                      $grade = array_shift($grades);
 348                      $this->assertEquals($value, $grade->rawgrade, "Quiz grade for attempt {$result['quizattempt']}.");
 349                      break;
 350                  case 'gradebookgrade' :
 351                      // Check grade book.
 352                      $gradebookgrades = grade_get_grades($attemptobj->get_courseid(),
 353                                                          'mod', 'quiz',
 354                                                          $attemptobj->get_quizid(),
 355                                                          $attemptobj->get_userid());
 356                      $gradebookitem = array_shift($gradebookgrades->items);
 357                      $gradebookgrade = array_shift($gradebookitem->grades);
 358                      $this->assertEquals($value, $gradebookgrade->grade, "Gradebook grade for attempt {$result['quizattempt']}.");
 359                      break;
 360                  default :
 361                      throw new \coding_exception('Unknown column in csv file '.s($fieldname));
 362              }
 363          }
 364      }
 365  }