PageRenderTime 141ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/question/engine/tests/helpers.php

http://github.com/moodle/moodle
PHP | 1384 lines | 881 code | 183 blank | 320 comment | 81 complexity | 20c4a4f30a6929de23e03cf2d1426a2b MD5 | raw file
Possible License(s): MIT, AGPL-3.0, MPL-2.0-no-copyleft-exception, LGPL-3.0, GPL-3.0, Apache-2.0, LGPL-2.1, BSD-3-Clause

Large files files are truncated, but you can click here to view the full file

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

Large files files are truncated, but you can click here to view the full file