MDL-27639 restore of attempt data from 2.0 - first attempt.
[moodle.git] / lib / simpletestlib.php
blobd056060fbc9324d8ddc36d4da13594f06e6ef56f
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * Utility functions to make unit testing easier.
21 * These functions, particularly the the database ones, are quick and
22 * dirty methods for getting things done in test cases. None of these
23 * methods should be used outside test code.
25 * Major Contirbutors
26 * - T.J.Hunt@open.ac.uk
28 * @package core
29 * @subpackage simpletestex
30 * @copyright &copy; 2006 The Open University
31 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
34 defined('MOODLE_INTERNAL') || die();
36 /**
37 * Includes
39 require_once(dirname(__FILE__) . '/../config.php');
40 require_once($CFG->libdir . '/simpletestlib/simpletest.php');
41 require_once($CFG->libdir . '/simpletestlib/unit_tester.php');
42 require_once($CFG->libdir . '/simpletestlib/expectation.php');
43 require_once($CFG->libdir . '/simpletestlib/reporter.php');
44 require_once($CFG->libdir . '/simpletestlib/web_tester.php');
45 require_once($CFG->libdir . '/simpletestlib/mock_objects.php');
47 /**
48 * Recursively visit all the files in the source tree. Calls the callback
49 * function with the pathname of each file found.
51 * @param $path the folder to start searching from.
52 * @param $callback the function to call with the name of each file found.
53 * @param $fileregexp a regexp used to filter the search (optional).
54 * @param $exclude If true, pathnames that match the regexp will be ingored. If false,
55 * only files that match the regexp will be included. (default false).
56 * @param array $ignorefolders will not go into any of these folders (optional).
58 function recurseFolders($path, $callback, $fileregexp = '/.*/', $exclude = false, $ignorefolders = array()) {
59 $files = scandir($path);
61 foreach ($files as $file) {
62 $filepath = $path .'/'. $file;
63 if (strpos($file, '.') === 0) {
64 /// Don't check hidden files.
65 continue;
66 } else if (is_dir($filepath)) {
67 if (!in_array($filepath, $ignorefolders)) {
68 recurseFolders($filepath, $callback, $fileregexp, $exclude, $ignorefolders);
70 } else if ($exclude xor preg_match($fileregexp, $filepath)) {
71 call_user_func($callback, $filepath);
76 /**
77 * An expectation for comparing strings ignoring whitespace.
79 * @package moodlecore
80 * @subpackage simpletestex
81 * @copyright &copy; 2006 The Open University
82 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
84 class IgnoreWhitespaceExpectation extends SimpleExpectation {
85 var $expect;
87 function IgnoreWhitespaceExpectation($content, $message = '%s') {
88 $this->SimpleExpectation($message);
89 $this->expect=$this->normalise($content);
92 function test($ip) {
93 return $this->normalise($ip)==$this->expect;
96 function normalise($text) {
97 return preg_replace('/\s+/m',' ',trim($text));
100 function testMessage($ip) {
101 return "Input string [$ip] doesn't match the required value.";
106 * An Expectation that two arrays contain the same list of values.
108 * @package moodlecore
109 * @subpackage simpletestex
110 * @copyright &copy; 2006 The Open University
111 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
113 class ArraysHaveSameValuesExpectation extends SimpleExpectation {
114 var $expect;
116 function ArraysHaveSameValuesExpectation($expected, $message = '%s') {
117 $this->SimpleExpectation($message);
118 if (!is_array($expected)) {
119 trigger_error('Attempt to create an ArraysHaveSameValuesExpectation ' .
120 'with an expected value that is not an array.');
122 $this->expect = $this->normalise($expected);
125 function test($actual) {
126 return $this->normalise($actual) == $this->expect;
129 function normalise($array) {
130 sort($array);
131 return $array;
134 function testMessage($actual) {
135 return 'Array [' . implode(', ', $actual) .
136 '] does not contain the expected list of values [' . implode(', ', $this->expect) . '].';
142 * An Expectation that compares to objects, and ensures that for every field in the
143 * expected object, there is a key of the same name in the actual object, with
144 * the same value. (The actual object may have other fields to, but we ignore them.)
146 * @package moodlecore
147 * @subpackage simpletestex
148 * @copyright &copy; 2006 The Open University
149 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
151 class CheckSpecifiedFieldsExpectation extends SimpleExpectation {
152 var $expect;
154 function CheckSpecifiedFieldsExpectation($expected, $message = '%s') {
155 $this->SimpleExpectation($message);
156 if (!is_object($expected)) {
157 trigger_error('Attempt to create a CheckSpecifiedFieldsExpectation ' .
158 'with an expected value that is not an object.');
160 $this->expect = $expected;
163 function test($actual) {
164 foreach ($this->expect as $key => $value) {
165 if (isset($value) && isset($actual->$key) && $actual->$key == $value) {
166 // OK
167 } else if (is_null($value) && is_null($actual->$key)) {
168 // OK
169 } else {
170 return false;
173 return true;
176 function testMessage($actual) {
177 $mismatches = array();
178 foreach ($this->expect as $key => $value) {
179 if (isset($value) && isset($actual->$key) && $actual->$key == $value) {
180 // OK
181 } else if (is_null($value) && is_null($actual->$key)) {
182 // OK
183 } else if (!isset($actual->$key)) {
184 $mismatches[] = $key . ' (expected [' . $value . '] but was missing.';
185 } else {
186 $mismatches[] = $key . ' (expected [' . $value . '] got [' . $actual->$key . '].';
189 return 'Actual object does not have all the same fields with the same values as the expected object (' .
190 implode(', ', $mismatches) . ').';
194 abstract class XMLStructureExpectation extends SimpleExpectation {
196 * Parse a string as XML and return a DOMDocument;
197 * @param $html
198 * @return unknown_type
200 protected function load_xml($html) {
201 $prevsetting = libxml_use_internal_errors(true);
202 $parser = new DOMDocument();
203 if (!$parser->loadXML('<html>' . $html . '</html>')) {
204 $parser = new DOMDocument();
206 libxml_clear_errors();
207 libxml_use_internal_errors($prevsetting);
208 return $parser;
211 function testMessage($html) {
212 $parsererrors = $this->load_xml($html);
213 if (is_array($parsererrors)) {
214 foreach ($parsererrors as $key => $message) {
215 $parsererrors[$key] = $message->message;
217 return 'Could not parse XML [' . $html . '] errors were [' .
218 implode('], [', $parsererrors) . ']';
220 return $this->customMessage($html);
224 * An Expectation that looks to see whether some HMTL contains a tag with a certain attribute.
226 * @copyright 2009 Tim Hunt
227 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
229 class ContainsTagWithAttribute extends XMLStructureExpectation {
230 protected $tag;
231 protected $attribute;
232 protected $value;
234 function __construct($tag, $attribute, $value, $message = '%s') {
235 parent::__construct($message);
236 $this->tag = $tag;
237 $this->attribute = $attribute;
238 $this->value = $value;
241 function test($html) {
242 $parser = $this->load_xml($html);
243 if (is_array($parser)) {
244 return false;
246 $list = $parser->getElementsByTagName($this->tag);
248 foreach ($list as $node) {
249 if ($node->attributes->getNamedItem($this->attribute)->nodeValue === (string) $this->value) {
250 return true;
253 return false;
256 function customMessage($html) {
257 return 'Content [' . $html . '] does not contain the tag [' .
258 $this->tag . '] with attribute [' . $this->attribute . '="' . $this->value . '"].';
263 * An Expectation that looks to see whether some HMTL contains a tag with an array of attributes.
264 * All attributes must be present and their values must match the expected values.
265 * A third parameter can be used to specify attribute=>value pairs which must not be present in a positive match.
267 * @copyright 2009 Nicolas Connault
268 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
270 class ContainsTagWithAttributes extends XMLStructureExpectation {
272 * @var string $tag The name of the Tag to search
274 protected $tag;
276 * @var array $expectedvalues An associative array of parameters, all of which must be matched
278 protected $expectedvalues = array();
280 * @var array $forbiddenvalues An associative array of parameters, none of which must be matched
282 protected $forbiddenvalues = array();
284 * @var string $failurereason The reason why the test failed: nomatch or forbiddenmatch
286 protected $failurereason = 'nomatch';
288 function __construct($tag, $expectedvalues, $forbiddenvalues=array(), $message = '%s') {
289 parent::__construct($message);
290 $this->tag = $tag;
291 $this->expectedvalues = $expectedvalues;
292 $this->forbiddenvalues = $forbiddenvalues;
295 function test($html) {
296 $parser = $this->load_xml($html);
297 if (is_array($parser)) {
298 return false;
301 $list = $parser->getElementsByTagName($this->tag);
302 $foundamatch = false;
304 // Iterating through inputs
305 foreach ($list as $node) {
306 if (empty($node->attributes) || !is_a($node->attributes, 'DOMNamedNodeMap')) {
307 continue;
310 // For the current expected attribute under consideration, check that values match
311 $allattributesmatch = true;
313 foreach ($this->expectedvalues as $expectedattribute => $expectedvalue) {
314 if ($node->getAttribute($expectedattribute) === '' && $expectedvalue !== '') {
315 $this->failurereason = 'nomatch';
316 continue 2; // Skip this tag, it doesn't have all the expected attributes
318 if ($node->getAttribute($expectedattribute) !== (string) $expectedvalue) {
319 $allattributesmatch = false;
320 $this->failurereason = 'nomatch';
324 if ($allattributesmatch) {
325 $foundamatch = true;
327 // Now make sure this node doesn't have any of the forbidden attributes either
328 $nodeattrlist = $node->attributes;
330 foreach ($nodeattrlist as $domattrname => $domattr) {
331 if (array_key_exists($domattrname, $this->forbiddenvalues) && $node->getAttribute($domattrname) === (string) $this->forbiddenvalues[$domattrname]) {
332 $this->failurereason = "forbiddenmatch:$domattrname:" . $node->getAttribute($domattrname);
333 $foundamatch = false;
339 return $foundamatch;
342 function customMessage($html) {
343 $output = 'Content [' . $html . '] ';
345 if (preg_match('/forbiddenmatch:(.*):(.*)/', $this->failurereason, $matches)) {
346 $output .= "contains the tag $this->tag with the forbidden attribute=>value pair: [$matches[1]=>$matches[2]]";
347 } else if ($this->failurereason == 'nomatch') {
348 $output .= 'does not contain the tag [' . $this->tag . '] with attributes [';
349 foreach ($this->expectedvalues as $var => $val) {
350 $output .= "$var=\"$val\" ";
352 $output = rtrim($output);
353 $output .= '].';
356 return $output;
361 * An Expectation that looks to see whether some HMTL contains a tag with an array of attributes.
362 * All attributes must be present and their values must match the expected values.
363 * A third parameter can be used to specify attribute=>value pairs which must not be present in a positive match.
365 * @copyright 2010 The Open University
366 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
368 class ContainsSelectExpectation extends XMLStructureExpectation {
370 * @var string $tag The name of the Tag to search
372 protected $name;
374 * @var array $expectedvalues An associative array of parameters, all of which must be matched
376 protected $choices;
378 * @var array $forbiddenvalues An associative array of parameters, none of which must be matched
380 protected $selected;
382 * @var string $failurereason The reason why the test failed: nomatch or forbiddenmatch
384 protected $enabled;
386 function __construct($name, $choices, $selected = null, $enabled = null, $message = '%s') {
387 parent::__construct($message);
388 $this->name = $name;
389 $this->choices = $choices;
390 $this->selected = $selected;
391 $this->enabled = $enabled;
394 function test($html) {
395 $parser = $this->load_xml($html);
396 if (is_array($parser)) {
397 return false;
400 $list = $parser->getElementsByTagName('select');
402 // Iterating through inputs
403 foreach ($list as $node) {
404 if (empty($node->attributes) || !is_a($node->attributes, 'DOMNamedNodeMap')) {
405 continue;
408 if ($node->getAttribute('name') != $this->name) {
409 continue;
412 if ($this->enabled === true && $node->getAttribute('disabled')) {
413 continue;
414 } else if ($this->enabled === false && $node->getAttribute('disabled') != 'disabled') {
415 continue;
418 $options = $node->getElementsByTagName('option');
419 reset($this->choices);
420 foreach ($options as $option) {
421 if ($option->getAttribute('value') != key($this->choices)) {
422 continue 2;
424 if ($option->firstChild->wholeText != current($this->choices)) {
425 continue 2;
427 if ($option->getAttribute('value') === $this->selected &&
428 !$option->hasAttribute('selected')) {
429 continue 2;
431 next($this->choices);
433 if (current($this->choices) !== false) {
434 // The HTML did not contain all the choices.
435 return false;
437 return true;
439 return false;
442 function customMessage($html) {
443 if ($this->enabled === true) {
444 $state = 'an enabled';
445 } else if ($this->enabled === false) {
446 $state = 'a disabled';
447 } else {
448 $state = 'a';
450 $output = 'Content [' . $html . '] does not contain ' . $state .
451 ' <select> with name ' . $this->name . ' and choices ' .
452 implode(', ', $this->choices);
453 if ($this->selected) {
454 $output .= ' with ' . $this->selected . ' selected).';
457 return $output;
462 * The opposite of {@link ContainsTagWithAttributes}. The test passes only if
463 * the HTML does not contain a tag with the given attributes.
465 * @copyright 2010 The Open University
466 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
468 class DoesNotContainTagWithAttributes extends ContainsTagWithAttributes {
469 function __construct($tag, $expectedvalues, $message = '%s') {
470 parent::__construct($tag, $expectedvalues, array(), $message);
472 function test($html) {
473 return !parent::test($html);
475 function customMessage($html) {
476 $output = 'Content [' . $html . '] ';
478 $output .= 'contains the tag [' . $this->tag . '] with attributes [';
479 foreach ($this->expectedvalues as $var => $val) {
480 $output .= "$var=\"$val\" ";
482 $output = rtrim($output);
483 $output .= '].';
485 return $output;
490 * An Expectation that looks to see whether some HMTL contains a tag with a certain text inside it.
492 * @copyright 2009 Tim Hunt
493 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
495 class ContainsTagWithContents extends XMLStructureExpectation {
496 protected $tag;
497 protected $content;
499 function __construct($tag, $content, $message = '%s') {
500 parent::__construct($message);
501 $this->tag = $tag;
502 $this->content = $content;
505 function test($html) {
506 $parser = $this->load_xml($html);
507 $list = $parser->getElementsByTagName($this->tag);
509 foreach ($list as $node) {
510 if ($node->textContent == $this->content) {
511 return true;
515 return false;
518 function testMessage($html) {
519 return 'Content [' . $html . '] does not contain the tag [' .
520 $this->tag . '] with contents [' . $this->content . '].';
525 * An Expectation that looks to see whether some HMTL contains an empty tag of a specific type.
527 * @copyright 2009 Nicolas Connault
528 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
530 class ContainsEmptyTag extends XMLStructureExpectation {
531 protected $tag;
533 function __construct($tag, $message = '%s') {
534 parent::__construct($message);
535 $this->tag = $tag;
538 function test($html) {
539 $parser = $this->load_xml($html);
540 $list = $parser->getElementsByTagName($this->tag);
542 foreach ($list as $node) {
543 if (!$node->hasAttributes() && !$node->hasChildNodes()) {
544 return true;
548 return false;
551 function testMessage($html) {
552 return 'Content ['.$html.'] does not contain the empty tag ['.$this->tag.'].';
558 * This class lets you write unit tests that access a separate set of test
559 * tables with a different prefix. Only those tables you explicitly ask to
560 * be created will be.
562 * This class has failities for flipping $USER->id.
564 * The tear-down method for this class should automatically revert any changes
565 * you make during test set-up using the metods defined here. That is, it will
566 * drop tables for you automatically and revert to the real $DB and $USER->id.
568 * @package moodlecore
569 * @subpackage simpletestex
570 * @copyright &copy; 2006 The Open University
571 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
573 class UnitTestCaseUsingDatabase extends UnitTestCase {
574 private $realdb;
575 protected $testdb;
576 private $realuserid = null;
577 private $tables = array();
579 private $realcfg;
580 protected $testcfg;
582 public function __construct($label = false) {
583 global $DB, $CFG;
585 // Complain if we get this far and $CFG->unittestprefix is not set.
586 if (empty($CFG->unittestprefix)) {
587 throw new coding_exception('You cannot use UnitTestCaseUsingDatabase unless you set $CFG->unittestprefix.');
590 // Only do this after the above text.
591 parent::UnitTestCase($label);
593 // Create the test DB instance.
594 $this->realdb = $DB;
595 $this->testdb = moodle_database::get_driver_instance($CFG->dbtype, $CFG->dblibrary);
596 $this->testdb->connect($CFG->dbhost, $CFG->dbuser, $CFG->dbpass, $CFG->dbname, $CFG->unittestprefix);
598 // Set up test config
599 $this->testcfg = (object)array(
600 'testcfg' => true, // Marker that this is a test config
601 'libdir' => $CFG->libdir, // Must use real one so require_once works
602 'dirroot' => $CFG->dirroot, // Must use real one
603 'dataroot' => $CFG->dataroot, // Use real one for now (maybe this should change?)
604 'ostype' => $CFG->ostype, // Real one
605 'wwwroot' => 'http://www.example.org', // Use fixed url
606 'siteadmins' => '0', // No admins
607 'siteguest' => '0' // No guest
609 $this->realcfg = $CFG;
613 * Switch to using the test database for all queries until further notice.
615 protected function switch_to_test_db() {
616 global $DB;
617 if ($DB === $this->testdb) {
618 debugging('switch_to_test_db called when the test DB was already selected. This suggest you are doing something wrong and dangerous. Please review your code immediately.', DEBUG_DEVELOPER);
620 $DB = $this->testdb;
624 * Revert to using the test database for all future queries.
626 protected function revert_to_real_db() {
627 global $DB;
628 if ($DB !== $this->testdb) {
629 debugging('revert_to_real_db called when the test DB was not already selected. This suggest you are doing something wrong and dangerous. Please review your code immediately.', DEBUG_DEVELOPER);
631 $DB = $this->realdb;
635 * Switch to using the test $CFG for all queries until further notice.
637 protected function switch_to_test_cfg() {
638 global $CFG;
639 if (isset($CFG->testcfg)) {
640 debugging('switch_to_test_cfg called when the test CFG was already selected. This suggest you are doing something wrong and dangerous. Please review your code immediately.', DEBUG_DEVELOPER);
642 $CFG = $this->testcfg;
646 * Revert to using the real $CFG for all future queries.
648 protected function revert_to_real_cfg() {
649 global $CFG;
650 if (!isset($CFG->testcfg)) {
651 debugging('revert_to_real_cfg called when the test CFG was not already selected. This suggest you are doing something wrong and dangerous. Please review your code immediately.', DEBUG_DEVELOPER);
653 $CFG = $this->realcfg;
657 * Switch $USER->id to a test value.
659 * It might be worth making this method do more robuse $USER switching in future,
660 * however, this is sufficient for my needs at present.
662 protected function switch_global_user_id($userid) {
663 global $USER;
664 if (!is_null($this->realuserid)) {
665 debugging('switch_global_user_id called when $USER->id was already switched to a different value. This suggest you are doing something wrong and dangerous. Please review your code immediately.', DEBUG_DEVELOPER);
666 } else {
667 $this->realuserid = $USER->id;
669 $USER->id = $userid;
673 * Revert $USER->id to the real value.
675 protected function revert_global_user_id() {
676 global $USER;
677 if (is_null($this->realuserid)) {
678 debugging('revert_global_user_id called without switch_global_user_id having been called first. This suggest you are doing something wrong and dangerous. Please review your code immediately.', DEBUG_DEVELOPER);
679 } else {
680 $USER->id = $this->realuserid;
681 $this->realuserid = null;
686 * Check that the user has not forgotten to clean anything up, and if they
687 * have, display a rude message and clean it up for them.
689 private function automatic_clean_up() {
690 global $DB, $CFG;
691 $cleanmore = false;
693 // Drop any test tables that were created.
694 foreach ($this->tables as $tablename => $notused) {
695 $this->drop_test_table($tablename);
698 // Switch back to the real DB if necessary.
699 if ($DB !== $this->realdb) {
700 $this->revert_to_real_db();
701 $cleanmore = true;
704 // Switch back to the real CFG if necessary.
705 if (isset($CFG->testcfg)) {
706 $this->revert_to_real_cfg();
707 $cleanmore = true;
710 // revert_global_user_id if necessary.
711 if (!is_null($this->realuserid)) {
712 $this->revert_global_user_id();
713 $cleanmore = true;
716 if ($cleanmore) {
717 accesslib_clear_all_caches_for_unit_testing();
718 $course = 'reset';
719 get_fast_modinfo($course);
723 public function tearDown() {
724 $this->automatic_clean_up();
725 parent::tearDown();
728 public function __destruct() {
729 // Should not be necessary thanks to tearDown, but no harm in belt and braces.
730 $this->automatic_clean_up();
734 * Create a test table just like a real one, getting getting the definition from
735 * the specified install.xml file.
736 * @param string $tablename the name of the test table.
737 * @param string $installxmlfile the install.xml file in which this table is defined.
738 * $CFG->dirroot . '/' will be prepended, and '/db/install.xml' appended,
739 * so you need only specify, for example, 'mod/quiz'.
741 protected function create_test_table($tablename, $installxmlfile) {
742 global $CFG;
743 $dbman = $this->testdb->get_manager();
744 if (isset($this->tables[$tablename])) {
745 debugging('You are attempting to create test table ' . $tablename . ' again. It already exists. Please review your code immediately.', DEBUG_DEVELOPER);
746 return;
748 if ($dbman->table_exists($tablename)) {
749 debugging('This table ' . $tablename . ' already exists from a previous execution. If the error persists you will need to review your code to ensure it is being created only once.', DEBUG_DEVELOPER);
750 $dbman->drop_table(new xmldb_table($tablename));
752 $dbman->install_one_table_from_xmldb_file($CFG->dirroot . '/' . $installxmlfile . '/db/install.xml', $tablename, true); // with structure cache enabled!
753 $this->tables[$tablename] = 1;
757 * Convenience method for calling create_test_table repeatedly.
758 * @param array $tablenames an array of table names.
759 * @param string $installxmlfile the install.xml file in which this table is defined.
760 * $CFG->dirroot . '/' will be prepended, and '/db/install.xml' appended,
761 * so you need only specify, for example, 'mod/quiz'.
763 protected function create_test_tables($tablenames, $installxmlfile) {
764 foreach ($tablenames as $tablename) {
765 $this->create_test_table($tablename, $installxmlfile);
770 * Drop a test table.
771 * @param $tablename the name of the test table.
773 protected function drop_test_table($tablename) {
774 if (!isset($this->tables[$tablename])) {
775 debugging('You are attempting to drop test table ' . $tablename . ' but it does not exist. Please review your code immediately.', DEBUG_DEVELOPER);
776 return;
778 $dbman = $this->testdb->get_manager();
779 $table = new xmldb_table($tablename);
780 $dbman->drop_table($table);
781 unset($this->tables[$tablename]);
785 * Convenience method for calling drop_test_table repeatedly.
786 * @param array $tablenames an array of table names.
788 protected function drop_test_tables($tablenames) {
789 foreach ($tablenames as $tablename) {
790 $this->drop_test_table($tablename);
795 * Load a table with some rows of data. A typical call would look like:
797 * $config = $this->load_test_data('config_plugins',
798 * array('plugin', 'name', 'value'), array(
799 * array('frog', 'numlegs', 2),
800 * array('frog', 'sound', 'croak'),
801 * array('frog', 'action', 'jump'),
802 * ));
804 * @param string $table the table name.
805 * @param array $cols the columns to fill.
806 * @param array $data the data to load.
807 * @return array $objects corresponding to $data.
809 protected function load_test_data($table, array $cols, array $data) {
810 $results = array();
811 foreach ($data as $rowid => $row) {
812 $obj = new stdClass;
813 foreach ($cols as $key => $colname) {
814 $obj->$colname = $row[$key];
816 $obj->id = $this->testdb->insert_record($table, $obj);
817 $results[$rowid] = $obj;
819 return $results;
823 * Clean up data loaded with load_test_data. The call corresponding to the
824 * example load above would be:
826 * $this->delete_test_data('config_plugins', $config);
828 * @param string $table the table name.
829 * @param array $rows the rows to delete. Actually, only $rows[$key]->id is used.
831 protected function delete_test_data($table, array $rows) {
832 $ids = array();
833 foreach ($rows as $row) {
834 $ids[] = $row->id;
836 $this->testdb->delete_records_list($table, 'id', $ids);
842 * @package moodlecore
843 * @subpackage simpletestex
844 * @copyright &copy; 2006 The Open University
845 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
847 class FakeDBUnitTestCase extends UnitTestCase {
848 public $tables = array();
849 public $pkfile;
850 public $cfg;
851 public $DB;
854 * In the constructor, record the max(id) of each test table into a csv file.
855 * If this file already exists, it means that a previous run of unit tests
856 * did not complete, and has left data undeleted in the DB. This data is then
857 * deleted and the file is retained. Otherwise it is created.
859 * throws moodle_exception if CSV file cannot be created
861 public function __construct($label = false) {
862 global $DB, $CFG;
864 if (empty($CFG->unittestprefix)) {
865 return;
868 parent::UnitTestCase($label);
869 // MDL-16483 Get PKs and save data to text file
871 $this->pkfile = $CFG->dataroot.'/testtablespks.csv';
872 $this->cfg = $CFG;
874 UnitTestDB::instantiate();
876 $tables = $DB->get_tables();
878 // The file exists, so use it to truncate tables (tests aborted before test data could be removed)
879 if (file_exists($this->pkfile)) {
880 $this->truncate_test_tables($this->get_table_data($this->pkfile));
882 } else { // Create the file
883 $tabledata = '';
885 foreach ($tables as $table) {
886 if ($table != 'sessions') {
887 if (!$max_id = $DB->get_field_sql("SELECT MAX(id) FROM {$CFG->unittestprefix}{$table}")) {
888 $max_id = 0;
890 $tabledata .= "$table, $max_id\n";
893 if (!file_put_contents($this->pkfile, $tabledata)) {
894 $a = new stdClass();
895 $a->filename = $this->pkfile;
896 throw new moodle_exception('testtablescsvfileunwritable', 'simpletest', '', $a);
902 * Given an array of tables and their max id, truncates all test table records whose id is higher than the ones in the $tabledata array.
903 * @param array $tabledata
905 private function truncate_test_tables($tabledata) {
906 global $CFG, $DB;
908 if (empty($CFG->unittestprefix)) {
909 return;
912 $tables = $DB->get_tables();
914 foreach ($tables as $table) {
915 if ($table != 'sessions' && isset($tabledata[$table])) {
916 // $DB->delete_records_select($table, "id > ?", array($tabledata[$table]));
922 * Given a filename, opens it and parses the csv contained therein. It expects two fields per line:
923 * 1. Table name
924 * 2. Max id
926 * throws moodle_exception if file doesn't exist
928 * @param string $filename
930 public function get_table_data($filename) {
931 global $CFG;
933 if (empty($CFG->unittestprefix)) {
934 return;
937 if (file_exists($this->pkfile)) {
938 $handle = fopen($this->pkfile, 'r');
939 $tabledata = array();
941 while (($data = fgetcsv($handle, 1000, ",")) !== false) {
942 $tabledata[$data[0]] = $data[1];
944 return $tabledata;
945 } else {
946 $a = new stdClass();
947 $a->filename = $this->pkfile;
948 throw new moodle_exception('testtablescsvfilemissing', 'simpletest', '', $a);
949 return false;
954 * Method called before each test method. Replaces the real $DB with the one configured for unit tests (different prefix, $CFG->unittestprefix).
955 * Also detects if this config setting is properly set, and if the user table exists.
956 * @todo Improve detection of incorrectly built DB test tables (e.g. detect version discrepancy and offer to upgrade/rebuild)
958 public function setUp() {
959 global $DB, $CFG;
961 if (empty($CFG->unittestprefix)) {
962 return;
965 parent::setUp();
966 $this->DB =& $DB;
967 ob_start();
971 * Method called after each test method. Doesn't do anything extraordinary except restore the global $DB to the real one.
973 public function tearDown() {
974 global $DB, $CFG;
976 if (empty($CFG->unittestprefix)) {
977 return;
980 if (empty($DB)) {
981 $DB = $this->DB;
983 $DB->cleanup();
984 parent::tearDown();
986 // Output buffering
987 if (ob_get_length() > 0) {
988 ob_end_flush();
993 * This will execute once all the tests have been run. It should delete the text file holding info about database contents prior to the tests
994 * It should also detect if data is missing from the original tables.
996 public function __destruct() {
997 global $CFG, $DB;
999 if (empty($CFG->unittestprefix)) {
1000 return;
1003 $CFG = $this->cfg;
1004 $this->tearDown();
1005 UnitTestDB::restore();
1006 fulldelete($this->pkfile);
1010 * Load a table with some rows of data. A typical call would look like:
1012 * $config = $this->load_test_data('config_plugins',
1013 * array('plugin', 'name', 'value'), array(
1014 * array('frog', 'numlegs', 2),
1015 * array('frog', 'sound', 'croak'),
1016 * array('frog', 'action', 'jump'),
1017 * ));
1019 * @param string $table the table name.
1020 * @param array $cols the columns to fill.
1021 * @param array $data the data to load.
1022 * @return array $objects corresponding to $data.
1024 public function load_test_data($table, array $cols, array $data) {
1025 global $CFG, $DB;
1027 if (empty($CFG->unittestprefix)) {
1028 return;
1031 $results = array();
1032 foreach ($data as $rowid => $row) {
1033 $obj = new stdClass;
1034 foreach ($cols as $key => $colname) {
1035 $obj->$colname = $row[$key];
1037 $obj->id = $DB->insert_record($table, $obj);
1038 $results[$rowid] = $obj;
1040 return $results;
1044 * Clean up data loaded with load_test_data. The call corresponding to the
1045 * example load above would be:
1047 * $this->delete_test_data('config_plugins', $config);
1049 * @param string $table the table name.
1050 * @param array $rows the rows to delete. Actually, only $rows[$key]->id is used.
1052 public function delete_test_data($table, array $rows) {
1053 global $CFG, $DB;
1055 if (empty($CFG->unittestprefix)) {
1056 return;
1059 $ids = array();
1060 foreach ($rows as $row) {
1061 $ids[] = $row->id;
1063 $DB->delete_records_list($table, 'id', $ids);
1068 * This is a Database Engine proxy class: It replaces the global object $DB with itself through a call to the
1069 * static instantiate() method, and restores the original global $DB through restore().
1070 * Internally, it routes all calls to $DB to a real instance of the database engine (aggregated as a member variable),
1071 * except those that are defined in this proxy class. This makes it possible to add extra code to the database engine
1072 * without subclassing it.
1074 * @package moodlecore
1075 * @subpackage simpletestex
1076 * @copyright &copy; 2006 The Open University
1077 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1079 class UnitTestDB {
1080 public static $DB;
1081 private static $real_db;
1083 public $table_data = array();
1086 * Call this statically to connect to the DB using the unittest prefix, instantiate
1087 * the unit test db, store it as a member variable, instantiate $this and use it as the new global $DB.
1089 public static function instantiate() {
1090 global $CFG, $DB;
1091 UnitTestDB::$real_db = clone($DB);
1092 if (empty($CFG->unittestprefix)) {
1093 print_error("prefixnotset", 'simpletest');
1096 if (empty(UnitTestDB::$DB)) {
1097 UnitTestDB::$DB = moodle_database::get_driver_instance($CFG->dbtype, $CFG->dblibrary);
1098 UnitTestDB::$DB->connect($CFG->dbhost, $CFG->dbuser, $CFG->dbpass, $CFG->dbname, $CFG->unittestprefix);
1101 $manager = UnitTestDB::$DB->get_manager();
1103 if (!$manager->table_exists('user')) {
1104 print_error('tablesnotsetup', 'simpletest');
1107 $DB = new UnitTestDB();
1110 public function __call($method, $args) {
1111 // Set args to null if they don't exist (up to 10 args should do)
1112 if (!method_exists($this, $method)) {
1113 return call_user_func_array(array(UnitTestDB::$DB, $method), $args);
1114 } else {
1115 call_user_func_array(array($this, $method), $args);
1119 public function __get($variable) {
1120 return UnitTestDB::$DB->$variable;
1123 public function __set($variable, $value) {
1124 UnitTestDB::$DB->$variable = $value;
1127 public function __isset($variable) {
1128 return isset(UnitTestDB::$DB->$variable);
1131 public function __unset($variable) {
1132 unset(UnitTestDB::$DB->$variable);
1136 * Overriding insert_record to keep track of the ids inserted during unit tests, so that they can be deleted afterwards
1138 public function insert_record($table, $dataobject, $returnid=true, $bulk=false) {
1139 global $DB;
1140 $id = UnitTestDB::$DB->insert_record($table, $dataobject, $returnid, $bulk);
1141 $this->table_data[$table][] = $id;
1142 return $id;
1146 * Overriding update_record: If we are updating a record that was NOT inserted by unit tests,
1147 * throw an exception and cancel update.
1149 * throws moodle_exception If trying to update a record not inserted by unit tests.
1151 public function update_record($table, $dataobject, $bulk=false) {
1152 global $DB;
1153 if ((empty($this->table_data[$table]) || !in_array($dataobject->id, $this->table_data[$table])) && !($table == 'course_categories' && $dataobject->id == 1)) {
1154 // return UnitTestDB::$DB->update_record($table, $dataobject, $bulk);
1155 $a = new stdClass();
1156 $a->id = $dataobject->id;
1157 $a->table = $table;
1158 throw new moodle_exception('updatingnoninsertedrecord', 'simpletest', '', $a);
1159 } else {
1160 return UnitTestDB::$DB->update_record($table, $dataobject, $bulk);
1165 * Overriding delete_record: If we are deleting a record that was NOT inserted by unit tests,
1166 * throw an exception and cancel delete.
1168 * throws moodle_exception If trying to delete a record not inserted by unit tests.
1170 public function delete_records($table, array $conditions=array()) {
1171 global $DB;
1172 $tables_to_ignore = array('context_temp');
1174 $a = new stdClass();
1175 $a->table = $table;
1177 // Get ids matching conditions
1178 if (!$ids_to_delete = $DB->get_field($table, 'id', $conditions)) {
1179 return UnitTestDB::$DB->delete_records($table, $conditions);
1182 $proceed_with_delete = true;
1184 if (!is_array($ids_to_delete)) {
1185 $ids_to_delete = array($ids_to_delete);
1188 foreach ($ids_to_delete as $id) {
1189 if (!in_array($table, $tables_to_ignore) && (empty($this->table_data[$table]) || !in_array($id, $this->table_data[$table]))) {
1190 $proceed_with_delete = false;
1191 $a->id = $id;
1192 break;
1196 if ($proceed_with_delete) {
1197 return UnitTestDB::$DB->delete_records($table, $conditions);
1198 } else {
1199 throw new moodle_exception('deletingnoninsertedrecord', 'simpletest', '', $a);
1204 * Overriding delete_records_select: If we are deleting a record that was NOT inserted by unit tests,
1205 * throw an exception and cancel delete.
1207 * throws moodle_exception If trying to delete a record not inserted by unit tests.
1209 public function delete_records_select($table, $select, array $params=null) {
1210 global $DB;
1211 $a = new stdClass();
1212 $a->table = $table;
1214 // Get ids matching conditions
1215 if (!$ids_to_delete = $DB->get_field_select($table, 'id', $select, $params)) {
1216 return UnitTestDB::$DB->delete_records_select($table, $select, $params);
1219 $proceed_with_delete = true;
1221 foreach ($ids_to_delete as $id) {
1222 if (!in_array($id, $this->table_data[$table])) {
1223 $proceed_with_delete = false;
1224 $a->id = $id;
1225 break;
1229 if ($proceed_with_delete) {
1230 return UnitTestDB::$DB->delete_records_select($table, $select, $params);
1231 } else {
1232 throw new moodle_exception('deletingnoninsertedrecord', 'simpletest', '', $a);
1237 * Removes from the test DB all the records that were inserted during unit tests,
1239 public function cleanup() {
1240 global $DB;
1241 foreach ($this->table_data as $table => $ids) {
1242 foreach ($ids as $id) {
1243 $DB->delete_records($table, array('id' => $id));
1249 * Restores the global $DB object.
1251 public static function restore() {
1252 global $DB;
1253 $DB = UnitTestDB::$real_db;
1256 public function get_field($table, $return, array $conditions) {
1257 if (!is_array($conditions)) {
1258 throw new coding_exception('$conditions is not an array.');
1260 return UnitTestDB::$DB->get_field($table, $return, $conditions);