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  /**
  18   * This file contains helper classes for testing the question engine.
  19   *
  20   * @package    moodlecore
  21   * @subpackage questionengine
  22   * @copyright  2009 The Open University
  23   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  24   */
  25  
  26  
  27  defined('MOODLE_INTERNAL') || die();
  28  
  29  global $CFG;
  30  require_once (__DIR__ . '/../lib.php');
  31  require_once($CFG->dirroot . '/lib/phpunit/lib.php');
  32  
  33  
  34  /**
  35   * Makes some protected methods of question_attempt public to facilitate testing.
  36   *
  37   * @copyright  2009 The Open University
  38   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  39   */
  40  class testable_question_attempt extends question_attempt {
  41      public function add_step(question_attempt_step $step) {
  42          parent::add_step($step);
  43      }
  44      public function set_min_fraction($fraction) {
  45          $this->minfraction = $fraction;
  46      }
  47      public function set_max_fraction($fraction) {
  48          $this->maxfraction = $fraction;
  49      }
  50      public function set_behaviour(question_behaviour $behaviour) {
  51          $this->behaviour = $behaviour;
  52      }
  53  }
  54  
  55  
  56  /**
  57   * Test subclass to allow access to some protected data so that the correct
  58   * behaviour can be verified.
  59   *
  60   * @copyright  2012 The Open University
  61   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  62   */
  63  class testable_question_engine_unit_of_work extends question_engine_unit_of_work {
  64      public function get_modified() {
  65          return $this->modified;
  66      }
  67  
  68      public function get_attempts_added() {
  69          return $this->attemptsadded;
  70      }
  71  
  72      public function get_attempts_modified() {
  73          return $this->attemptsmodified;
  74      }
  75  
  76      public function get_steps_added() {
  77          return $this->stepsadded;
  78      }
  79  
  80      public function get_steps_modified() {
  81          return $this->stepsmodified;
  82      }
  83  
  84      public function get_steps_deleted() {
  85          return $this->stepsdeleted;
  86      }
  87  
  88      public function get_metadata_added() {
  89          return $this->metadataadded;
  90      }
  91  
  92      public function get_metadata_modified() {
  93          return $this->metadatamodified;
  94      }
  95  }
  96  
  97  
  98  /**
  99   * Base class for question type test helpers.
 100   *
 101   * @copyright  2011 The Open University
 102   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 103   */
 104  abstract class question_test_helper {
 105      /**
 106       * @return array of example question names that can be passed as the $which
 107       * argument of {@link test_question_maker::make_question} when $qtype is
 108       * this question type.
 109       */
 110      abstract public function get_test_questions();
 111  
 112      /**
 113       * Set up a form to create a question in $cat. This method also sets cat and contextid on $questiondata object.
 114       * @param object $cat the category
 115       * @param object $questiondata form initialisation requires question data.
 116       * @return moodleform
 117       */
 118      public static function get_question_editing_form($cat, $questiondata) {
 119          $catcontext = context::instance_by_id($cat->contextid, MUST_EXIST);
 120          $contexts = new question_edit_contexts($catcontext);
 121          $dataforformconstructor = new stdClass();
 122          $dataforformconstructor->createdby = $questiondata->createdby;
 123          $dataforformconstructor->qtype = $questiondata->qtype;
 124          $dataforformconstructor->contextid = $questiondata->contextid = $catcontext->id;
 125          $dataforformconstructor->category = $questiondata->category = $cat->id;
 126          $dataforformconstructor->formoptions = new stdClass();
 127          $dataforformconstructor->formoptions->canmove = true;
 128          $dataforformconstructor->formoptions->cansaveasnew = true;
 129          $dataforformconstructor->formoptions->canedit = true;
 130          $dataforformconstructor->formoptions->repeatelements = true;
 131          $qtype = question_bank::get_qtype($questiondata->qtype);
 132          return  $qtype->create_editing_form('question.php', $dataforformconstructor, $cat, $contexts, true);
 133      }
 134  }
 135  
 136  
 137  /**
 138   * This class creates questions of various types, which can then be used when
 139   * testing.
 140   *
 141   * @copyright  2009 The Open University
 142   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 143   */
 144  class test_question_maker {
 145      const STANDARD_OVERALL_CORRECT_FEEDBACK = 'Well done!';
 146      const STANDARD_OVERALL_PARTIALLYCORRECT_FEEDBACK =
 147          'Parts, but only parts, of your response are correct.';
 148      const STANDARD_OVERALL_INCORRECT_FEEDBACK = 'That is not right at all.';
 149  
 150      /** @var array qtype => qtype test helper class. */
 151      protected static $testhelpers = array();
 152  
 153      /**
 154       * Just make a question_attempt at a question. Useful for unit tests that
 155       * need to pass a $qa to methods that call format_text. Probably not safe
 156       * to use for anything beyond that.
 157       * @param question_definition $question a question.
 158       * @param number $maxmark the max mark to set.
 159       * @return question_attempt the question attempt.
 160       */
 161      public static function get_a_qa($question, $maxmark = 3) {
 162          return new question_attempt($question, 13, null, $maxmark);
 163      }
 164  
 165      /**
 166       * Initialise the common fields of a question of any type.
 167       */
 168      public static function initialise_a_question($q) {
 169          global $USER;
 170  
 171          $q->id = 0;
 172          $q->category = 0;
 173          $q->idnumber = null;
 174          $q->parent = 0;
 175          $q->questiontextformat = FORMAT_HTML;
 176          $q->generalfeedbackformat = FORMAT_HTML;
 177          $q->defaultmark = 1;
 178          $q->penalty = 0.3333333;
 179          $q->length = 1;
 180          $q->stamp = make_unique_id_code();
 181          $q->version = make_unique_id_code();
 182          $q->hidden = 0;
 183          $q->timecreated = time();
 184          $q->timemodified = time();
 185          $q->createdby = $USER->id;
 186          $q->modifiedby = $USER->id;
 187      }
 188  
 189      public static function initialise_question_data($qdata) {
 190          global $USER;
 191  
 192          $qdata->id = 0;
 193          $qdata->category = 0;
 194          $qdata->idnumber = null;
 195          $qdata->contextid = 0;
 196          $qdata->parent = 0;
 197          $qdata->questiontextformat = FORMAT_HTML;
 198          $qdata->generalfeedbackformat = FORMAT_HTML;
 199          $qdata->defaultmark = 1;
 200          $qdata->penalty = 0.3333333;
 201          $qdata->length = 1;
 202          $qdata->stamp = make_unique_id_code();
 203          $qdata->version = make_unique_id_code();
 204          $qdata->hidden = 0;
 205          $qdata->timecreated = time();
 206          $qdata->timemodified = time();
 207          $qdata->createdby = $USER->id;
 208          $qdata->modifiedby = $USER->id;
 209          $qdata->hints = array();
 210      }
 211  
 212      /**
 213       * Get the test helper class for a particular question type.
 214       * @param $qtype the question type name, e.g. 'multichoice'.
 215       * @return question_test_helper the test helper class.
 216       */
 217      public static function get_test_helper($qtype) {
 218          global $CFG;
 219  
 220          if (array_key_exists($qtype, self::$testhelpers)) {
 221              return self::$testhelpers[$qtype];
 222          }
 223  
 224          $file = core_component::get_plugin_directory('qtype', $qtype) . '/tests/helper.php';
 225          if (!is_readable($file)) {
 226              throw new coding_exception('Question type ' . $qtype .
 227                  ' does not have test helper code.');
 228          }
 229          include_once($file);
 230  
 231          $class = 'qtype_' . $qtype . '_test_helper';
 232          if (!class_exists($class)) {
 233              throw new coding_exception('Class ' . $class . ' is not defined in ' . $file);
 234          }
 235  
 236          self::$testhelpers[$qtype] = new $class();
 237          return self::$testhelpers[$qtype];
 238      }
 239  
 240      /**
 241       * Call a method on a qtype_{$qtype}_test_helper class and return the result.
 242       *
 243       * @param string $methodtemplate e.g. 'make_{qtype}_question_{which}';
 244       * @param string $qtype the question type to get a test question for.
 245       * @param string $which one of the names returned by the get_test_questions
 246       *      method of the relevant qtype_{$qtype}_test_helper class.
 247       * @param unknown_type $which
 248       */
 249      protected static function call_question_helper_method($methodtemplate, $qtype, $which = null) {
 250          $helper = self::get_test_helper($qtype);
 251  
 252          $available = $helper->get_test_questions();
 253  
 254          if (is_null($which)) {
 255              $which = reset($available);
 256          } else if (!in_array($which, $available)) {
 257              throw new coding_exception('Example question ' . $which . ' of type ' .
 258                  $qtype . ' does not exist.');
 259          }
 260  
 261          $method = str_replace(array('{qtype}', '{which}'),
 262              array($qtype,    $which), $methodtemplate);
 263  
 264          if (!method_exists($helper, $method)) {
 265              throw new coding_exception('Method ' . $method . ' does not exist on the ' .
 266                  $qtype . ' question type test helper class.');
 267          }
 268  
 269          return $helper->$method();
 270      }
 271  
 272      /**
 273       * Question types can provide a number of test question defintions.
 274       * They do this by creating a qtype_{$qtype}_test_helper class that extends
 275       * question_test_helper. The get_test_questions method returns the list of
 276       * test questions available for this question type.
 277       *
 278       * @param string $qtype the question type to get a test question for.
 279       * @param string $which one of the names returned by the get_test_questions
 280       *      method of the relevant qtype_{$qtype}_test_helper class.
 281       * @return question_definition the requested question object.
 282       */
 283      public static function make_question($qtype, $which = null) {
 284          return self::call_question_helper_method('make_{qtype}_question_{which}',
 285              $qtype, $which);
 286      }
 287  
 288      /**
 289       * Like {@link make_question()} but returns the datastructure from
 290       * get_question_options instead of the question_definition object.
 291       *
 292       * @param string $qtype the question type to get a test question for.
 293       * @param string $which one of the names returned by the get_test_questions
 294       *      method of the relevant qtype_{$qtype}_test_helper class.
 295       * @return stdClass the requested question object.
 296       */
 297      public static function get_question_data($qtype, $which = null) {
 298          return self::call_question_helper_method('get_{qtype}_question_data_{which}',
 299              $qtype, $which);
 300      }
 301  
 302      /**
 303       * Like {@link make_question()} but returns the data what would be saved from
 304       * the question editing form instead of the question_definition object.
 305       *
 306       * @param string $qtype the question type to get a test question for.
 307       * @param string $which one of the names returned by the get_test_questions
 308       *      method of the relevant qtype_{$qtype}_test_helper class.
 309       * @return stdClass the requested question object.
 310       */
 311      public static function get_question_form_data($qtype, $which = null) {
 312          return self::call_question_helper_method('get_{qtype}_question_form_data_{which}',
 313              $qtype, $which);
 314      }
 315  
 316      /**
 317       * Makes a multichoice question with choices 'A', 'B' and 'C' shuffled. 'A'
 318       * is correct, defaultmark 1.
 319       * @return qtype_multichoice_single_question
 320       */
 321      public static function make_a_multichoice_single_question() {
 322          question_bank::load_question_definition_classes('multichoice');
 323          $mc = new qtype_multichoice_single_question();
 324          self::initialise_a_question($mc);
 325          $mc->name = 'Multi-choice question, single response';
 326          $mc->questiontext = 'The answer is A.';
 327          $mc->generalfeedback = 'You should have selected A.';
 328          $mc->qtype = question_bank::get_qtype('multichoice');
 329  
 330          $mc->shuffleanswers = 1;
 331          $mc->answernumbering = 'abc';
 332          $mc->showstandardinstruction = 0;
 333  
 334          $mc->answers = array(
 335              13 => new question_answer(13, 'A', 1, 'A is right', FORMAT_HTML),
 336              14 => new question_answer(14, 'B', -0.3333333, 'B is wrong', FORMAT_HTML),
 337              15 => new question_answer(15, 'C', -0.3333333, 'C is wrong', FORMAT_HTML),
 338          );
 339  
 340          return $mc;
 341      }
 342  
 343      /**
 344       * Makes a multichoice question with choices 'A', 'B', 'C' and 'D' shuffled.
 345       * 'A' and 'C' is correct, defaultmark 1.
 346       * @return qtype_multichoice_multi_question
 347       */
 348      public static function make_a_multichoice_multi_question() {
 349          question_bank::load_question_definition_classes('multichoice');
 350          $mc = new qtype_multichoice_multi_question();
 351          self::initialise_a_question($mc);
 352          $mc->name = 'Multi-choice question, multiple response';
 353          $mc->questiontext = 'The answer is A and C.';
 354          $mc->generalfeedback = 'You should have selected A and C.';
 355          $mc->qtype = question_bank::get_qtype('multichoice');
 356  
 357          $mc->shuffleanswers = 1;
 358          $mc->answernumbering = 'abc';
 359          $mc->showstandardinstruction = 0;
 360  
 361          self::set_standard_combined_feedback_fields($mc);
 362  
 363          $mc->answers = array(
 364              13 => new question_answer(13, 'A', 0.5, 'A is part of the right answer', FORMAT_HTML),
 365              14 => new question_answer(14, 'B', -1, 'B is wrong', FORMAT_HTML),
 366              15 => new question_answer(15, 'C', 0.5, 'C is part of the right answer', FORMAT_HTML),
 367              16 => new question_answer(16, 'D', -1, 'D is wrong', FORMAT_HTML),
 368          );
 369  
 370          return $mc;
 371      }
 372  
 373      /**
 374       * Makes a matching question to classify 'Dog', 'Frog', 'Toad' and 'Cat' as
 375       * 'Mammal', 'Amphibian' or 'Insect'.
 376       * defaultmark 1. Stems are shuffled by default.
 377       * @return qtype_match_question
 378       */
 379      public static function make_a_matching_question() {
 380          return self::make_question('match');
 381      }
 382  
 383      /**
 384       * Makes a truefalse question with correct ansewer true, defaultmark 1.
 385       * @return qtype_essay_question
 386       */
 387      public static function make_an_essay_question() {
 388          question_bank::load_question_definition_classes('essay');
 389          $essay = new qtype_essay_question();
 390          self::initialise_a_question($essay);
 391          $essay->name = 'Essay question';
 392          $essay->questiontext = 'Write an essay.';
 393          $essay->generalfeedback = 'I hope you wrote an interesting essay.';
 394          $essay->penalty = 0;
 395          $essay->qtype = question_bank::get_qtype('essay');
 396  
 397          $essay->responseformat = 'editor';
 398          $essay->responserequired = 1;
 399          $essay->responsefieldlines = 15;
 400          $essay->attachments = 0;
 401          $essay->attachmentsrequired = 0;
 402          $essay->responsetemplate = '';
 403          $essay->responsetemplateformat = FORMAT_MOODLE;
 404          $essay->graderinfo = '';
 405          $essay->graderinfoformat = FORMAT_MOODLE;
 406  
 407          return $essay;
 408      }
 409  
 410      /**
 411       * Add some standard overall feedback to a question. You need to use these
 412       * specific feedback strings for the corresponding contains_..._feedback
 413       * methods in {@link qbehaviour_walkthrough_test_base} to works.
 414       * @param question_definition|stdClass $q the question to add the feedback to.
 415       */
 416      public static function set_standard_combined_feedback_fields($q) {
 417          $q->correctfeedback = self::STANDARD_OVERALL_CORRECT_FEEDBACK;
 418          $q->correctfeedbackformat = FORMAT_HTML;
 419          $q->partiallycorrectfeedback = self::STANDARD_OVERALL_PARTIALLYCORRECT_FEEDBACK;
 420          $q->partiallycorrectfeedbackformat = FORMAT_HTML;
 421          $q->shownumcorrect = true;
 422          $q->incorrectfeedback = self::STANDARD_OVERALL_INCORRECT_FEEDBACK;
 423          $q->incorrectfeedbackformat = FORMAT_HTML;
 424      }
 425  
 426      /**
 427       * Add some standard overall feedback to a question's form data.
 428       */
 429      public static function set_standard_combined_feedback_form_data($form) {
 430          $form->correctfeedback = array('text' => self::STANDARD_OVERALL_CORRECT_FEEDBACK,
 431                                      'format' => FORMAT_HTML);
 432          $form->partiallycorrectfeedback = array('text' => self::STANDARD_OVERALL_PARTIALLYCORRECT_FEEDBACK,
 433                                               'format' => FORMAT_HTML);
 434          $form->shownumcorrect = true;
 435          $form->incorrectfeedback = array('text' => self::STANDARD_OVERALL_INCORRECT_FEEDBACK,
 436                                      'format' => FORMAT_HTML);
 437      }
 438  }
 439  
 440  
 441  /**
 442   * Helper for tests that need to simulate records loaded from the database.
 443   *
 444   * @copyright  2009 The Open University
 445   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 446   */
 447  abstract class testing_db_record_builder {
 448      public static function build_db_records(array $table) {
 449          $columns = array_shift($table);
 450          $records = array();
 451          foreach ($table as $row) {
 452              if (count($row) != count($columns)) {
 453                  throw new coding_exception("Row contains the wrong number of fields.");
 454              }
 455              $rec = new stdClass();
 456              foreach ($columns as $i => $name) {
 457                  $rec->$name = $row[$i];
 458              }
 459              $records[] = $rec;
 460          }
 461          return $records;
 462      }
 463  }
 464  
 465  
 466  /**
 467   * Helper base class for tests that need to simulate records loaded from the
 468   * database.
 469   *
 470   * @copyright  2009 The Open University
 471   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 472   */
 473  abstract class data_loading_method_test_base extends advanced_testcase {
 474      public function build_db_records(array $table) {
 475          return testing_db_record_builder::build_db_records($table);
 476      }
 477  }
 478  
 479  
 480  abstract class question_testcase extends advanced_testcase {
 481  
 482      /**
 483       * Tolerance accepted in some unit tests when float operations are involved.
 484       */
 485      const GRADE_DELTA = 0.00000005;
 486  
 487      public function assert($expectation, $compare, $notused = '') {
 488  
 489          if (get_class($expectation) === 'question_pattern_expectation') {
 490              $this->assertMatchesRegularExpression($expectation->pattern, $compare,
 491                      'Expected regex ' . $expectation->pattern . ' not found in ' . $compare);
 492              return;
 493  
 494          } else if (get_class($expectation) === 'question_no_pattern_expectation') {
 495              $this->assertDoesNotMatchRegularExpression($expectation->pattern, $compare,
 496                      'Unexpected regex ' . $expectation->pattern . ' found in ' . $compare);
 497              return;
 498  
 499          } else if (get_class($expectation) === 'question_contains_tag_with_attributes') {
 500              $this->assertTag(array('tag'=>$expectation->tag, 'attributes'=>$expectation->expectedvalues), $compare,
 501                      'Looking for a ' . $expectation->tag . ' with attributes ' . html_writer::attributes($expectation->expectedvalues) . ' in ' . $compare);
 502              foreach ($expectation->forbiddenvalues as $k=>$v) {
 503                  $attr = $expectation->expectedvalues;
 504                  $attr[$k] = $v;
 505                  $this->assertNotTag(array('tag'=>$expectation->tag, 'attributes'=>$attr), $compare,
 506                          $expectation->tag . ' had a ' . $k . ' attribute that should not be there in ' . $compare);
 507              }
 508              return;
 509  
 510          } else if (get_class($expectation) === 'question_contains_tag_with_attribute') {
 511              $attr = array($expectation->attribute=>$expectation->value);
 512              $this->assertTag(array('tag'=>$expectation->tag, 'attributes'=>$attr), $compare,
 513                      'Looking for a ' . $expectation->tag . ' with attribute ' . html_writer::attributes($attr) . ' in ' . $compare);
 514              return;
 515  
 516          } else if (get_class($expectation) === 'question_does_not_contain_tag_with_attributes') {
 517              $this->assertNotTag(array('tag'=>$expectation->tag, 'attributes'=>$expectation->attributes), $compare,
 518                      'Unexpected ' . $expectation->tag . ' with attributes ' . html_writer::attributes($expectation->attributes) . ' found in ' . $compare);
 519              return;
 520  
 521          } else if (get_class($expectation) === 'question_contains_select_expectation') {
 522              $tag = array('tag'=>'select', 'attributes'=>array('name'=>$expectation->name),
 523                  'children'=>array('count'=>count($expectation->choices)));
 524              if ($expectation->enabled === false) {
 525                  $tag['attributes']['disabled'] = 'disabled';
 526              } else if ($expectation->enabled === true) {
 527                  // TODO
 528              }
 529              foreach(array_keys($expectation->choices) as $value) {
 530                  if ($expectation->selected === $value) {
 531                      $tag['child'] = array('tag'=>'option', 'attributes'=>array('value'=>$value, 'selected'=>'selected'));
 532                  } else {
 533                      $tag['child'] = array('tag'=>'option', 'attributes'=>array('value'=>$value));
 534                  }
 535              }
 536  
 537              $this->assertTag($tag, $compare, 'expected select not found in ' . $compare);
 538              return;
 539  
 540          } else if (get_class($expectation) === 'question_check_specified_fields_expectation') {
 541              $expect = (array)$expectation->expect;
 542              $compare = (array)$compare;
 543              foreach ($expect as $k=>$v) {
 544                  if (!array_key_exists($k, $compare)) {
 545                      $this->fail("Property {$k} does not exist");
 546                  }
 547                  if ($v != $compare[$k]) {
 548                      $this->fail("Property {$k} is different");
 549                  }
 550              }
 551              $this->assertTrue(true);
 552              return;
 553  
 554          } else if (get_class($expectation) === 'question_contains_tag_with_contents') {
 555              $this->assertTag(array('tag'=>$expectation->tag, 'content'=>$expectation->content), $compare,
 556                      'Looking for a ' . $expectation->tag . ' with content ' . $expectation->content . ' in ' . $compare);
 557              return;
 558          }
 559  
 560          throw new coding_exception('Unknown expectiontion:'.get_class($expectation));
 561      }
 562  
 563      /**
 564       * Use this function rather than assert when checking the value of options within a select element.
 565       *
 566       * @param question_contains_select_expectation $expectation The select expectation class
 567       * @param string $html The rendered output to check against
 568       */
 569      public function assert_select_options($expectation, $html) {
 570          if (get_class($expectation) !== 'question_contains_select_expectation') {
 571              throw new coding_exception('Unsuitable expectiontion: '.get_class($expectation));
 572          }
 573          $dom = new DOMDocument();
 574          $dom->loadHTML($html);
 575          $selects = $dom->getElementsByTagName('select');
 576          foreach ($selects as $select) {
 577              if ($select->getAttribute('name') == $expectation->name) {
 578                  $options = $select->getElementsByTagName('option');
 579                  foreach ($options as $key => $option) {
 580                      if ($key == 0) {
 581                          // Check the value of the first option. This is often 'Choose...' or a nbsp.
 582                          // Note it is necessary to pass a nbsp character in the test here and not just ' '.
 583                          // Many tests do not require checking of this option.
 584                          if (isset($expectation->choices[$option->getAttribute('value')])) {
 585                              $this->assertEquals($expectation->choices[$option->getAttribute('value')], $option->textContent);
 586                          }
 587                          continue;
 588                      }
 589                      // Check the value of the options in the select.
 590                      $this->assertEquals($expectation->choices[$option->getAttribute('value')], $option->textContent);
 591                      if ($expectation->selected && $option->getAttribute('value') == $expectation->selected) {
 592                          // Check the right option is selected.
 593                          $this->assertTrue(!empty($option->getAttribute('selected')));
 594                      }
 595                  }
 596                  if ($expectation->enabled) {
 597                      // Check the select element is enabled.
 598                      $this->assertTrue(!$select->getAttribute('disabled'));
 599                  }
 600              }
 601          }
 602          return;
 603      }
 604  }
 605  
 606  
 607  class question_contains_tag_with_contents {
 608      public $tag;
 609      public $content;
 610      public $message;
 611  
 612      public function __construct($tag, $content, $message = '') {
 613          $this->tag = $tag;
 614          $this->content = $content;
 615          $this->message = $message;
 616      }
 617  
 618  }
 619  
 620  class question_check_specified_fields_expectation {
 621      public $expect;
 622      public $message;
 623  
 624      function __construct($expected, $message = '') {
 625          $this->expect = $expected;
 626          $this->message = $message;
 627      }
 628  }
 629  
 630  
 631  class question_contains_select_expectation {
 632      public $name;
 633      public $choices;
 634      public $selected;
 635      public $enabled;
 636      public $message;
 637  
 638      public function __construct($name, $choices, $selected = null, $enabled = null, $message = '') {
 639          $this->name = $name;
 640          $this->choices = $choices;
 641          $this->selected = $selected;
 642          $this->enabled = $enabled;
 643          $this->message = $message;
 644      }
 645  }
 646  
 647  
 648  class question_does_not_contain_tag_with_attributes {
 649      public $tag;
 650      public $attributes;
 651      public $message;
 652  
 653      public function __construct($tag, $attributes, $message = '') {
 654          $this->tag = $tag;
 655          $this->attributes = $attributes;
 656          $this->message = $message;
 657      }
 658  }
 659  
 660  
 661  class question_contains_tag_with_attribute {
 662      public $tag;
 663      public $attribute;
 664      public $value;
 665      public $message;
 666  
 667      public function __construct($tag, $attribute, $value, $message = '') {
 668          $this->tag = $tag;
 669          $this->attribute = $attribute;
 670          $this->value = $value;
 671          $this->message = $message;
 672      }
 673  }
 674  
 675  
 676  class question_contains_tag_with_attributes {
 677      public $tag;
 678      public $expectedvalues = array();
 679      public $forbiddenvalues = array();
 680      public $message;
 681  
 682      public function __construct($tag, $expectedvalues, $forbiddenvalues=array(), $message = '') {
 683          $this->tag = $tag;
 684          $this->expectedvalues = $expectedvalues;
 685          $this->forbiddenvalues = $forbiddenvalues;
 686          $this->message = $message;
 687      }
 688  }
 689  
 690  
 691  class question_pattern_expectation {
 692      public $pattern;
 693      public $message;
 694  
 695      public function __construct($pattern, $message = '') {
 696          $this->pattern = $pattern;
 697          $this->message = $message;
 698      }
 699  }
 700  
 701  
 702  class question_no_pattern_expectation {
 703      public $pattern;
 704      public $message;
 705  
 706      public function __construct($pattern, $message = '') {
 707          $this->pattern = $pattern;
 708          $this->message = $message;
 709      }
 710  }
 711  
 712  
 713  /**
 714   * Helper base class for question walk-through tests.
 715   *
 716   * The purpose of tests that use this base class is to simulate the entire
 717   * interaction of a student making an attempt at a question. Therefore,
 718   * these are not really unit tests. They would more accurately be described
 719   * as integration tests. However, whether they are unit tests or not,
 720   * it works well to implement them in PHPUnit.
 721   *
 722   * Historically, tests like this were made because Moodle did not have anything
 723   * like Behat for end-to-end testing. Even though we do now have Behat, it makes
 724   * sense to keep these walk-through tests. They run massively faster than Behat
 725   * tests, which gives you a much faster feedback loop while doing development.
 726   * They also make it quite easy to test things like regrading the attempt after
 727   * the question has been edited, which would be possible but very fiddly in Behat.
 728   *
 729   * Ideally, the full set of tests for the question class of a question type would be:
 730   *
 731   * 1. A lot of unit tests for each qtype_myqtype_question class method
 732   *    like grade_response, is_complete_response, is_same_response, ...
 733   *
 734   * 2. Several of these walk-through tests, to test the end-to-end interaction
 735   *    of a student with a question, for example with different behaviours.
 736   *
 737   * 3. Just one Behat test, using question preview, to verify that everything
 738   *    is plugged together correctly and works when used through the UI.
 739   *
 740   * What one would expect to see in one of these walk-through tests is:
 741   *
 742   * // 1. Set up a question: $q.
 743   *
 744   * // 2. A call to $this->start_attempt_at_question($q, ...); with the relevant options.
 745   *
 746   * // 3. Some number of calls to $this->process_submission passing an array of simulated
 747   * //    POST data that matches what would be sent back be submitting a form that contains
 748   * //    the form fields that are output by rendering the question. This is like clicking
 749   * //    the 'Check' button in a question, or navigating to the next page in a quiz.
 750   *
 751   * // 4. A call to $this->finish(); which is the equivalent of clicking
 752   * //    'Submit all and finish' in the quiz.
 753   *
 754   * // 5. After each of steps 2-4 above, one would expect to see a certain amount of
 755   * //    validation of the state of the question and how the question is rendered,
 756   * //    using methods like $this->check_current_state(), $this->check_current_output, etc.
 757   *
 758   * The best way to work out how to write tests like this is probably to look at
 759   * some examples in other question types or question behaviours.
 760   *
 761   * In writing these tests, it is worth noting the following points:
 762   *
 763   * a) The easiest mistake to make is at step 3. You need to ensure that your
 764   *    simulated post data actually matches what gets sent back when the
 765   *    question is submitted in the browser. Try checking it against the
 766   *    HTTP POST requests you see in your browser when the question is submitted.
 767   *    Some question types have a $q->prepare_simulated_post_data() method that
 768   *    can help with this.
 769   *
 770   * b) In the past, tests like these used to contain even more repetitive code,
 771   *    and so they were re-factored to add the helper methods like
 772   *    start_attempt_at_question, process_submission, finish. That change had
 773   *    good effects, like reducing duplicate code. However, there were down-sides.
 774   *    The extra layers of indirection hide what is going on, which means these
 775   *    tests are harder to understand until you know what the helpers are doing.
 776   *    If you want an interesting exercise, take one of the walk-through tests,
 777   *    and inline all the helpers. This might be a good way to understand more about
 778   *    the question engine API. However, having made the everything-inlined code
 779   *    and learned from the process, you should then just throw it away.
 780   *
 781   * c) The way check_current_output works is weird. When these tests were first written
 782   *    Moodle used SimpleTest for unit tests and check_current_output os written in a
 783   *    style that made sense there. When we moved to PHPUnit, a quick and dirty
 784   *    conversion was done. That was a pragmatic move at the time, and we just have
 785   *    to live with the result. Sorry. (And: don't copy that style for new things.)
 786   *
 787   * @copyright  2009 The Open University
 788   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 789   */
 790  abstract class qbehaviour_walkthrough_test_base extends question_testcase {
 791      /** @var question_display_options */
 792      protected $displayoptions;
 793      /** @var question_usage_by_activity */
 794      protected $quba;
 795      /** @var integer */
 796  
 797      protected $slot;
 798      /**
 799       * @var string after {@link render()} has been called, this contains the
 800       * display of the question in its current state.
 801       */
 802      protected $currentoutput = '';
 803  
 804      protected function setUp(): void {
 805          parent::setUp();
 806          $this->resetAfterTest(true);
 807  
 808          $this->displayoptions = new question_display_options();
 809          $this->quba = question_engine::make_questions_usage_by_activity('unit_test',
 810              context_system::instance());
 811      }
 812  
 813      protected function tearDown(): void {
 814          $this->displayoptions = null;
 815          $this->quba = null;
 816          parent::tearDown();
 817      }
 818  
 819      protected function start_attempt_at_question($question, $preferredbehaviour,
 820                                                   $maxmark = null, $variant = 1) {
 821          $this->quba->set_preferred_behaviour($preferredbehaviour);
 822          $this->slot = $this->quba->add_question($question, $maxmark);
 823          $this->quba->start_question($this->slot, $variant);
 824      }
 825  
 826      /**
 827       * Convert an array of data destined for one question to the equivalent POST data.
 828       * @param array $data the data for the quetsion.
 829       * @return array the complete post data.
 830       */
 831      protected function response_data_to_post($data) {
 832          $prefix = $this->quba->get_field_prefix($this->slot);
 833          $fulldata = array(
 834              'slots' => $this->slot,
 835              $prefix . ':sequencecheck' => $this->get_question_attempt()->get_sequence_check_count(),
 836          );
 837          foreach ($data as $name => $value) {
 838              $fulldata[$prefix . $name] = $value;
 839          }
 840          return $fulldata;
 841      }
 842  
 843      protected function process_submission($data) {
 844          // Backwards compatibility.
 845          reset($data);
 846          if (count($data) == 1 && key($data) === '-finish') {
 847              $this->finish();
 848          }
 849  
 850          $this->quba->process_all_actions(time(), $this->response_data_to_post($data));
 851      }
 852  
 853      protected function process_autosave($data) {
 854          $this->quba->process_all_autosaves(null, $this->response_data_to_post($data));
 855      }
 856  
 857      protected function finish() {
 858          $this->quba->finish_all_questions();
 859      }
 860  
 861      protected function manual_grade($comment, $mark, $commentformat = null) {
 862          $this->quba->manual_grade($this->slot, $comment, $mark, $commentformat);
 863      }
 864  
 865      protected function save_quba(moodle_database $db = null) {
 866          question_engine::save_questions_usage_by_activity($this->quba, $db);
 867      }
 868  
 869      protected function load_quba(moodle_database $db = null) {
 870          $this->quba = question_engine::load_questions_usage_by_activity($this->quba->get_id(), $db);
 871      }
 872  
 873      protected function delete_quba() {
 874          question_engine::delete_questions_usage_by_activity($this->quba->get_id());
 875          $this->quba = null;
 876      }
 877  
 878      /**
 879       * Asserts if the manual comment for the question is equal to the provided arguments.
 880       * @param $comment Comment text
 881       * @param $commentformat Comment format
 882       */
 883      protected function check_comment($comment, $commentformat) {
 884          $actualcomment = $this->quba->get_question_attempt($this->slot)->get_manual_comment();
 885  
 886          $this->assertEquals(
 887                  [$comment, $commentformat],
 888                  [$actualcomment[0], $actualcomment[1]]
 889          );
 890      }
 891  
 892      protected function check_current_state($state) {
 893          $this->assertEquals($state, $this->quba->get_question_state($this->slot),
 894              'Questions is in the wrong state.');
 895      }
 896  
 897      protected function check_current_mark($mark) {
 898          if (is_null($mark)) {
 899              $this->assertNull($this->quba->get_question_mark($this->slot));
 900          } else {
 901              if ($mark == 0) {
 902                  // PHP will think a null mark and a mark of 0 are equal,
 903                  // so explicity check not null in this case.
 904                  $this->assertNotNull($this->quba->get_question_mark($this->slot));
 905              }
 906              $this->assertEqualsWithDelta($mark, $this->quba->get_question_mark($this->slot),
 907                   0.000001, 'Expected mark and actual mark differ.');
 908          }
 909      }
 910  
 911      /**
 912       * Generate the HTML rendering of the question in its current state in
 913       * $this->currentoutput so that it can be verified.
 914       */
 915      protected function render() {
 916          $this->currentoutput = $this->quba->render_question($this->slot, $this->displayoptions);
 917      }
 918  
 919      protected function check_output_contains_text_input($name, $value = null, $enabled = true) {
 920          $attributes = array(
 921              'type' => 'text',
 922              'name' => $this->quba->get_field_prefix($this->slot) . $name,
 923          );
 924          if (!is_null($value)) {
 925              $attributes['value'] = $value;
 926          }
 927          if (!$enabled) {
 928              $attributes['readonly'] = 'readonly';
 929          }
 930          $matcher = $this->get_tag_matcher('input', $attributes);
 931          $this->assertTag($matcher, $this->currentoutput,
 932                  'Looking for an input with attributes ' . html_writer::attributes($attributes) . ' in ' . $this->currentoutput);
 933  
 934          if ($enabled) {
 935              $matcher['attributes']['readonly'] = 'readonly';
 936              $this->assertNotTag($matcher, $this->currentoutput,
 937                      'input with attributes ' . html_writer::attributes($attributes) .
 938                      ' should not be read-only in ' . $this->currentoutput);
 939          }
 940      }
 941  
 942      protected function check_output_contains_text_input_with_class($name, $class = null) {
 943          $attributes = array(
 944              'type' => 'text',
 945              'name' => $this->quba->get_field_prefix($this->slot) . $name,
 946          );
 947          if (!is_null($class)) {
 948              $attributes['class'] = 'regexp:/\b' . $class . '\b/';
 949          }
 950  
 951          $matcher = $this->get_tag_matcher('input', $attributes);
 952          $this->assertTag($matcher, $this->currentoutput,
 953                  'Looking for an input with attributes ' . html_writer::attributes($attributes) . ' in ' . $this->currentoutput);
 954      }
 955  
 956      protected function check_output_does_not_contain_text_input_with_class($name, $class = null) {
 957          $attributes = array(
 958              'type' => 'text',
 959              'name' => $this->quba->get_field_prefix($this->slot) . $name,
 960          );
 961          if (!is_null($class)) {
 962              $attributes['class'] = 'regexp:/\b' . $class . '\b/';
 963          }
 964  
 965          $matcher = $this->get_tag_matcher('input', $attributes);
 966          $this->assertNotTag($matcher, $this->currentoutput,
 967                  'Unexpected input with attributes ' . html_writer::attributes($attributes) . ' found in ' . $this->currentoutput);
 968      }
 969  
 970      protected function check_output_contains_hidden_input($name, $value) {
 971          $attributes = array(
 972              'type' => 'hidden',
 973              'name' => $this->quba->get_field_prefix($this->slot) . $name,
 974              'value' => $value,
 975          );
 976          $this->assertTag($this->get_tag_matcher('input', $attributes), $this->currentoutput,
 977                  'Looking for a hidden input with attributes ' . html_writer::attributes($attributes) . ' in ' . $this->currentoutput);
 978      }
 979  
 980      protected function check_output_contains($string) {
 981          $this->render();
 982          $this->assertStringContainsString($string, $this->currentoutput,
 983                  'Expected string ' . $string . ' not found in ' . $this->currentoutput);
 984      }
 985  
 986      protected function check_output_does_not_contain($string) {
 987          $this->render();
 988          $this->assertStringNotContainsString($string, $this->currentoutput,
 989                  'String ' . $string . ' unexpectedly found in ' . $this->currentoutput);
 990      }
 991  
 992      protected function check_output_contains_lang_string($identifier, $component = '', $a = null) {
 993          $this->check_output_contains(get_string($identifier, $component, $a));
 994      }
 995  
 996      protected function get_tag_matcher($tag, $attributes) {
 997          return array(
 998              'tag' => $tag,
 999              'attributes' => $attributes,
1000          );
1001      }
1002  
1003      /**
1004       * @param $condition one or more Expectations. (users varargs).
1005       */
1006      protected function check_current_output() {
1007          $html = $this->quba->render_question($this->slot, $this->displayoptions);
1008          foreach (func_get_args() as $condition) {
1009              $this->assert($condition, $html);
1010          }
1011      }
1012  
1013      /**
1014       * Use this function rather than check_current_output for select expectations where
1015       * checking the value of the options is required. check_current_output only checks
1016       * that the right number of options are available.
1017       *
1018       * @param question_contains_select_expectation $expectations One or more expectations.
1019       */
1020      protected function check_output_contains_selectoptions(...$expectations) {
1021          $html = $this->quba->render_question($this->slot, $this->displayoptions);
1022          foreach ($expectations as $expectation) {
1023              $this->assert_select_options($expectation, $html);
1024          }
1025      }
1026  
1027      protected function get_question_attempt() {
1028          return $this->quba->get_question_attempt($this->slot);
1029      }
1030  
1031      protected function get_step_count() {
1032          return $this->get_question_attempt()->get_num_steps();
1033      }
1034  
1035      protected function check_step_count($expectednumsteps) {
1036          $this->assertEquals($expectednumsteps, $this->get_step_count());
1037      }
1038  
1039      protected function get_step($stepnum) {
1040          return $this->get_question_attempt()->get_step($stepnum);
1041      }
1042  
1043      protected function get_contains_question_text_expectation($question) {
1044          return new question_pattern_expectation('/' . preg_quote($question->questiontext, '/') . '/');
1045      }
1046  
1047      protected function get_contains_general_feedback_expectation($question) {
1048          return new question_pattern_expectation('/' . preg_quote($question->generalfeedback, '/') . '/');
1049      }
1050  
1051      protected function get_does_not_contain_correctness_expectation() {
1052          return new question_no_pattern_expectation('/class=\"correctness/');
1053      }
1054  
1055      protected function get_contains_correct_expectation() {
1056          return new question_pattern_expectation('/' . preg_quote(get_string('correct', 'question'), '/') . '/');
1057      }
1058  
1059      protected function get_contains_partcorrect_expectation() {
1060          return new question_pattern_expectation('/' .
1061              preg_quote(get_string('partiallycorrect', 'question'), '/') . '/');
1062      }
1063  
1064      protected function get_contains_incorrect_expectation() {
1065          return new question_pattern_expectation('/' . preg_quote(get_string('incorrect', 'question'), '/') . '/');
1066      }
1067  
1068      protected function get_contains_standard_correct_combined_feedback_expectation() {
1069          return new question_pattern_expectation('/' .
1070              preg_quote(test_question_maker::STANDARD_OVERALL_CORRECT_FEEDBACK, '/') . '/');
1071      }
1072  
1073      protected function get_contains_standard_partiallycorrect_combined_feedback_expectation() {
1074          return new question_pattern_expectation('/' .
1075              preg_quote(test_question_maker::STANDARD_OVERALL_PARTIALLYCORRECT_FEEDBACK, '/') . '/');
1076      }
1077  
1078      protected function get_contains_standard_incorrect_combined_feedback_expectation() {
1079          return new question_pattern_expectation('/' .
1080              preg_quote(test_question_maker::STANDARD_OVERALL_INCORRECT_FEEDBACK, '/') . '/');
1081      }
1082  
1083      protected function get_does_not_contain_feedback_expectation() {
1084          return new question_no_pattern_expectation('/class="feedback"/');
1085      }
1086  
1087      protected function get_does_not_contain_num_parts_correct() {
1088          return new question_no_pattern_expectation('/class="numpartscorrect"/');
1089      }
1090  
1091      protected function get_contains_num_parts_correct($num) {
1092          $a = new stdClass();
1093          $a->num = $num;
1094          return new question_pattern_expectation('/<div class="numpartscorrect">' .
1095              preg_quote(get_string('yougotnright', 'question', $a), '/') . '/');
1096      }
1097  
1098      protected function get_does_not_contain_specific_feedback_expectation() {
1099          return new question_no_pattern_expectation('/class="specificfeedback"/');
1100      }
1101  
1102      protected function get_contains_validation_error_expectation() {
1103          return new question_contains_tag_with_attribute('div', 'class', 'validationerror');
1104      }
1105  
1106      protected function get_does_not_contain_validation_error_expectation() {
1107          return new question_no_pattern_expectation('/class="validationerror"/');
1108      }
1109  
1110      protected function get_contains_mark_summary($mark) {
1111          $a = new stdClass();
1112          $a->mark = format_float($mark, $this->displayoptions->markdp);
1113          $a->max = format_float($this->quba->get_question_max_mark($this->slot),
1114              $this->displayoptions->markdp);
1115          return new question_pattern_expectation('/' .
1116              preg_quote(get_string('markoutofmax', 'question', $a), '/') . '/');
1117      }
1118  
1119      protected function get_contains_marked_out_of_summary() {
1120          $max = format_float($this->quba->get_question_max_mark($this->slot),
1121              $this->displayoptions->markdp);
1122          return new question_pattern_expectation('/' .
1123              preg_quote(get_string('markedoutofmax', 'question', $max), '/') . '/');
1124      }
1125  
1126      protected function get_does_not_contain_mark_summary() {
1127          return new question_no_pattern_expectation('/<div class="grade">/');
1128      }
1129  
1130      protected function get_contains_checkbox_expectation($baseattr, $enabled, $checked) {
1131          $expectedattributes = $baseattr;
1132          $forbiddenattributes = array();
1133          $expectedattributes['type'] = 'checkbox';
1134          if ($enabled === true) {
1135              $forbiddenattributes['disabled'] = 'disabled';
1136          } else if ($enabled === false) {
1137              $expectedattributes['disabled'] = 'disabled';
1138          }
1139          if ($checked === true) {
1140              $expectedattributes['checked'] = 'checked';
1141          } else if ($checked === false) {
1142              $forbiddenattributes['checked'] = 'checked';
1143          }
1144          return new question_contains_tag_with_attributes('input', $expectedattributes, $forbiddenattributes);
1145      }
1146  
1147      protected function get_contains_mc_checkbox_expectation($index, $enabled = null,
1148                                                              $checked = null) {
1149          return $this->get_contains_checkbox_expectation(array(
1150              'name' => $this->quba->get_field_prefix($this->slot) . $index,
1151              'value' => 1,
1152          ), $enabled, $checked);
1153      }
1154  
1155      protected function get_contains_radio_expectation($baseattr, $enabled, $checked) {
1156          $expectedattributes = $baseattr;
1157          $forbiddenattributes = array();
1158          $expectedattributes['type'] = 'radio';
1159          if ($enabled === true) {
1160              $forbiddenattributes['disabled'] = 'disabled';
1161          } else if ($enabled === false) {
1162              $expectedattributes['disabled'] = 'disabled';
1163          }
1164          if ($checked === true) {
1165              $expectedattributes['checked'] = 'checked';
1166          } else if ($checked === false) {
1167              $forbiddenattributes['checked'] = 'checked';
1168          }
1169          return new question_contains_tag_with_attributes('input', $expectedattributes, $forbiddenattributes);
1170      }
1171  
1172      protected function get_contains_mc_radio_expectation($index, $enabled = null, $checked = null) {
1173          return $this->get_contains_radio_expectation(array(
1174              'name' => $this->quba->get_field_prefix($this->slot) . 'answer',
1175              'value' => $index,
1176          ), $enabled, $checked);
1177      }
1178  
1179      protected function get_contains_hidden_expectation($name, $value = null) {
1180          $expectedattributes = array('type' => 'hidden', 'name' => s($name));
1181          if (!is_null($value)) {
1182              $expectedattributes['value'] = s($value);
1183          }
1184          return new question_contains_tag_with_attributes('input', $expectedattributes);
1185      }
1186  
1187      protected function get_does_not_contain_hidden_expectation($name, $value = null) {
1188          $expectedattributes = array('type' => 'hidden', 'name' => s($name));
1189          if (!is_null($value)) {
1190              $expectedattributes['value'] = s($value);
1191          }
1192          return new question_does_not_contain_tag_with_attributes('input', $expectedattributes);
1193      }
1194  
1195      protected function get_contains_tf_true_radio_expectation($enabled = null, $checked = null) {
1196          return $this->get_contains_radio_expectation(array(
1197              'name' => $this->quba->get_field_prefix($this->slot) . 'answer',
1198              'value' => 1,
1199          ), $enabled, $checked);
1200      }
1201  
1202      protected function get_contains_tf_false_radio_expectation($enabled = null, $checked = null) {
1203          return $this->get_contains_radio_expectation(array(
1204              'name' => $this->quba->get_field_prefix($this->slot) . 'answer',
1205              'value' => 0,
1206          ), $enabled, $checked);
1207      }
1208  
1209      protected function get_contains_cbm_radio_expectation($certainty, $enabled = null,
1210                                                            $checked = null) {
1211          return $this->get_contains_radio_expectation(array(
1212              'name' => $this->quba->get_field_prefix($this->slot) . '-certainty',
1213              'value' => $certainty,
1214          ), $enabled, $checked);
1215      }
1216  
1217      protected function get_contains_button_expectation($name, $value = null, $enabled = null) {
1218          $expectedattributes = array(
1219              'type' => 'submit',
1220              'name' => $name,
1221          );
1222          $forbiddenattributes = array();
1223          if (!is_null($value)) {
1224              $expectedattributes['value'] = $value;
1225          }
1226          if ($enabled === true) {
1227              $forbiddenattributes['disabled'] = 'disabled';
1228          } else if ($enabled === false) {
1229              $expectedattributes['disabled'] = 'disabled';
1230          }
1231          return new question_contains_tag_with_attributes('input', $expectedattributes, $forbiddenattributes);
1232      }
1233  
1234      /**
1235       * Returns an epectation that a string contains the HTML of a button with
1236       * name {question-attempt prefix}-submit, and eiter enabled or not.
1237       * @param bool $enabled if not null, check the enabled/disabled state of the button. True = enabled.
1238       * @return question_contains_tag_with_attributes an expectation for use with check_current_output.
1239       */
1240      protected function get_contains_submit_button_expectation($enabled = null) {
1241          return $this->get_contains_button_expectation(
1242              $this->quba->get_field_prefix($this->slot) . '-submit', null, $enabled);
1243      }
1244  
1245      /**
1246       * Returns an epectation that a string does not contain the HTML of a button with
1247       * name {question-attempt prefix}-submit.
1248       * @return question_contains_tag_with_attributes an expectation for use with check_current_output.
1249       */
1250      protected function get_does_not_contain_submit_button_expectation() {
1251          return new question_no_pattern_expectation('/name="' .
1252                  $this->quba->get_field_prefix($this->slot) . '-submit"/');
1253      }
1254  
1255      protected function get_tries_remaining_expectation($n) {
1256          return new question_pattern_expectation('/' .
1257              preg_quote(get_string('triesremaining', 'qbehaviour_interactive', $n), '/') . '/');
1258      }
1259  
1260      protected function get_invalid_answer_expectation() {
1261          return new question_pattern_expectation('/' .
1262              preg_quote(get_string('invalidanswer', 'question'), '/') . '/');
1263      }
1264  
1265      protected function get_contains_try_again_button_expectation($enabled = null) {
1266          $expectedattributes = array(
1267              'type' => 'submit',
1268              'name' => $this->quba->get_field_prefix($this->slot) . '-tryagain',
1269          );
1270          $forbiddenattributes = array();
1271          if ($enabled === true) {
1272              $forbiddenattributes['disabled'] = 'disabled';
1273          } else if ($enabled === false) {
1274              $expectedattributes['disabled'] = 'disabled';
1275          }
1276          return new question_contains_tag_with_attributes('input', $expectedattributes, $forbiddenattributes);
1277      }
1278  
1279      protected function get_does_not_contain_try_again_button_expectation() {
1280          return new question_no_pattern_expectation('/name="' .
1281              $this->quba->get_field_prefix($this->slot) . '-tryagain"/');
1282      }
1283  
1284      protected function get_contains_select_expectation($name, $choices,
1285                                                         $selected = null, $enabled = null) {
1286          $fullname = $this->quba->get_field_prefix($this->slot) . $name;
1287          return new question_contains_select_expectation($fullname, $choices, $selected, $enabled);
1288      }
1289  
1290      protected function get_mc_right_answer_index($mc) {
1291          $order = $mc->get_order($this->get_question_attempt());
1292          foreach ($order as $i => $ansid) {
1293              if ($mc->answers[$ansid]->fraction == 1) {
1294                  return $i;
1295              }
1296          }
1297          $this->fail('This multiple choice question does not seem to have a right answer!');
1298      }
1299  
1300      protected function get_no_hint_visible_expectation() {
1301          return new question_no_pattern_expectation('/class="hint"/');
1302      }
1303  
1304      protected function get_contains_hint_expectation($hinttext) {
1305          // Does not currently verify hint text.
1306          return new question_contains_tag_with_attribute('div', 'class', 'hint');
1307      }
1308  
1309      /**
1310       * Returns an expectation that a string contains a corrupted question notification.
1311       *
1312       * @return question_pattern_expectation an expectation for use with check_current_output.
1313       */
1314      protected function get_contains_corruption_notification() {
1315          return new question_pattern_expectation('/' . preg_quote(get_string('corruptedquestion', 'qtype_multianswer'), '/') . '/');
1316      }
1317  
1318      /**
1319       * Returns an expectation that a string contains a corrupted subquestion message.
1320       *
1321       * @return question_pattern_expectation an expectation for use with check_current_output.
1322       */
1323      protected function get_contains_corrupted_subquestion_message() {
1324          return new question_pattern_expectation('/' . preg_quote(get_string('missingsubquestion', 'qtype_multianswer'), '/') . '/');
1325      }
1326  }
1327  
1328  /**
1329   * Simple class that implements the {@link moodle_recordset} API based on an
1330   * array of test data.
1331   *
1332   *  See the {@link question_attempt_step_db_test} class in
1333   *  question/engine/tests/testquestionattemptstep.php for an example of how
1334   *  this is used.
1335   *
1336   * @copyright  2011 The Open University
1337   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1338   */
1339  class question_test_recordset extends moodle_recordset {
1340      protected $records;
1341  
1342      /**
1343       * Constructor
1344       * @param $table as for {@link testing_db_record_builder::build_db_records()}
1345       *      but does not need a unique first column.
1346       */
1347      public function __construct(array $table) {
1348          $columns = array_shift($table);
1349          $this->records = array();
1350          foreach ($table as $row) {
1351              if (count($row) != count($columns)) {
1352                  throw new coding_exception("Row contains the wrong number of fields.");
1353              }
1354              $rec = array();
1355              foreach ($columns as $i => $name) {
1356                  $rec[$name] = $row[$i];
1357              }
1358              $this->records[] = $rec;
1359          }
1360          reset($this->records);
1361      }
1362  
1363      public function __destruct() {
1364          $this->close();
1365      }
1366  
1367      public function current() {
1368          return (object) current($this->records);
1369      }
1370  
1371      public function key() {
1372          if (is_null(key($this->records))) {
1373              return false;
1374          }
1375          $current = current($this->records);
1376          return reset($current);
1377      }
1378  
1379      public function next() {
1380          next($this->records);
1381      }
1382  
1383      public function valid() {
1384          return !is_null(key($this->records));
1385      }
1386  
1387      public function close() {
1388          $this->records = null;
1389      }
1390  }
1391  
1392  /**
1393   * Helper class for tests that help to test core_question_renderer.
1394   *
1395   * @copyright  2018 Huong Nguyen <huongnv13@gmail.com>
1396   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1397   */
1398  class testable_core_question_renderer extends core_question_renderer {
1399  
1400      /**
1401       * Test the private number function.
1402       *
1403       * @param null|string $number
1404       * @return HTML
1405       */
1406      public function number($number) {
1407          return parent::number($number);
1408      }
1409  }