Automatic installer lang files (20110214)
[moodle.git] / lib / simpletestlib.php
blobad3d5c5dc950e660c2933ddb66ed7481b73cb1ae
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();
721 public function tearDown() {
722 $this->automatic_clean_up();
723 parent::tearDown();
726 public function __destruct() {
727 // Should not be necessary thanks to tearDown, but no harm in belt and braces.
728 $this->automatic_clean_up();
732 * Create a test table just like a real one, getting getting the definition from
733 * the specified install.xml file.
734 * @param string $tablename the name of the test table.
735 * @param string $installxmlfile the install.xml file in which this table is defined.
736 * $CFG->dirroot . '/' will be prepended, and '/db/install.xml' appended,
737 * so you need only specify, for example, 'mod/quiz'.
739 protected function create_test_table($tablename, $installxmlfile) {
740 global $CFG;
741 $dbman = $this->testdb->get_manager();
742 if (isset($this->tables[$tablename])) {
743 debugging('You are attempting to create test table ' . $tablename . ' again. It already exists. Please review your code immediately.', DEBUG_DEVELOPER);
744 return;
746 if ($dbman->table_exists($tablename)) {
747 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);
748 $dbman->drop_table(new xmldb_table($tablename));
750 $dbman->install_one_table_from_xmldb_file($CFG->dirroot . '/' . $installxmlfile . '/db/install.xml', $tablename, true); // with structure cache enabled!
751 $this->tables[$tablename] = 1;
755 * Convenience method for calling create_test_table repeatedly.
756 * @param array $tablenames an array of table names.
757 * @param string $installxmlfile the install.xml file in which this table is defined.
758 * $CFG->dirroot . '/' will be prepended, and '/db/install.xml' appended,
759 * so you need only specify, for example, 'mod/quiz'.
761 protected function create_test_tables($tablenames, $installxmlfile) {
762 foreach ($tablenames as $tablename) {
763 $this->create_test_table($tablename, $installxmlfile);
768 * Drop a test table.
769 * @param $tablename the name of the test table.
771 protected function drop_test_table($tablename) {
772 if (!isset($this->tables[$tablename])) {
773 debugging('You are attempting to drop test table ' . $tablename . ' but it does not exist. Please review your code immediately.', DEBUG_DEVELOPER);
774 return;
776 $dbman = $this->testdb->get_manager();
777 $table = new xmldb_table($tablename);
778 $dbman->drop_table($table);
779 unset($this->tables[$tablename]);
783 * Convenience method for calling drop_test_table repeatedly.
784 * @param array $tablenames an array of table names.
786 protected function drop_test_tables($tablenames) {
787 foreach ($tablenames as $tablename) {
788 $this->drop_test_table($tablename);
793 * Load a table with some rows of data. A typical call would look like:
795 * $config = $this->load_test_data('config_plugins',
796 * array('plugin', 'name', 'value'), array(
797 * array('frog', 'numlegs', 2),
798 * array('frog', 'sound', 'croak'),
799 * array('frog', 'action', 'jump'),
800 * ));
802 * @param string $table the table name.
803 * @param array $cols the columns to fill.
804 * @param array $data the data to load.
805 * @return array $objects corresponding to $data.
807 protected function load_test_data($table, array $cols, array $data) {
808 $results = array();
809 foreach ($data as $rowid => $row) {
810 $obj = new stdClass;
811 foreach ($cols as $key => $colname) {
812 $obj->$colname = $row[$key];
814 $obj->id = $this->testdb->insert_record($table, $obj);
815 $results[$rowid] = $obj;
817 return $results;
821 * Clean up data loaded with load_test_data. The call corresponding to the
822 * example load above would be:
824 * $this->delete_test_data('config_plugins', $config);
826 * @param string $table the table name.
827 * @param array $rows the rows to delete. Actually, only $rows[$key]->id is used.
829 protected function delete_test_data($table, array $rows) {
830 $ids = array();
831 foreach ($rows as $row) {
832 $ids[] = $row->id;
834 $this->testdb->delete_records_list($table, 'id', $ids);
840 * @package moodlecore
841 * @subpackage simpletestex
842 * @copyright &copy; 2006 The Open University
843 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
845 class FakeDBUnitTestCase extends UnitTestCase {
846 public $tables = array();
847 public $pkfile;
848 public $cfg;
849 public $DB;
852 * In the constructor, record the max(id) of each test table into a csv file.
853 * If this file already exists, it means that a previous run of unit tests
854 * did not complete, and has left data undeleted in the DB. This data is then
855 * deleted and the file is retained. Otherwise it is created.
857 * throws moodle_exception if CSV file cannot be created
859 public function __construct($label = false) {
860 global $DB, $CFG;
862 if (empty($CFG->unittestprefix)) {
863 return;
866 parent::UnitTestCase($label);
867 // MDL-16483 Get PKs and save data to text file
869 $this->pkfile = $CFG->dataroot.'/testtablespks.csv';
870 $this->cfg = $CFG;
872 UnitTestDB::instantiate();
874 $tables = $DB->get_tables();
876 // The file exists, so use it to truncate tables (tests aborted before test data could be removed)
877 if (file_exists($this->pkfile)) {
878 $this->truncate_test_tables($this->get_table_data($this->pkfile));
880 } else { // Create the file
881 $tabledata = '';
883 foreach ($tables as $table) {
884 if ($table != 'sessions') {
885 if (!$max_id = $DB->get_field_sql("SELECT MAX(id) FROM {$CFG->unittestprefix}{$table}")) {
886 $max_id = 0;
888 $tabledata .= "$table, $max_id\n";
891 if (!file_put_contents($this->pkfile, $tabledata)) {
892 $a = new stdClass();
893 $a->filename = $this->pkfile;
894 throw new moodle_exception('testtablescsvfileunwritable', 'simpletest', '', $a);
900 * 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.
901 * @param array $tabledata
903 private function truncate_test_tables($tabledata) {
904 global $CFG, $DB;
906 if (empty($CFG->unittestprefix)) {
907 return;
910 $tables = $DB->get_tables();
912 foreach ($tables as $table) {
913 if ($table != 'sessions' && isset($tabledata[$table])) {
914 // $DB->delete_records_select($table, "id > ?", array($tabledata[$table]));
920 * Given a filename, opens it and parses the csv contained therein. It expects two fields per line:
921 * 1. Table name
922 * 2. Max id
924 * throws moodle_exception if file doesn't exist
926 * @param string $filename
928 public function get_table_data($filename) {
929 global $CFG;
931 if (empty($CFG->unittestprefix)) {
932 return;
935 if (file_exists($this->pkfile)) {
936 $handle = fopen($this->pkfile, 'r');
937 $tabledata = array();
939 while (($data = fgetcsv($handle, 1000, ",")) !== false) {
940 $tabledata[$data[0]] = $data[1];
942 return $tabledata;
943 } else {
944 $a = new stdClass();
945 $a->filename = $this->pkfile;
946 throw new moodle_exception('testtablescsvfilemissing', 'simpletest', '', $a);
947 return false;
952 * Method called before each test method. Replaces the real $DB with the one configured for unit tests (different prefix, $CFG->unittestprefix).
953 * Also detects if this config setting is properly set, and if the user table exists.
954 * @todo Improve detection of incorrectly built DB test tables (e.g. detect version discrepancy and offer to upgrade/rebuild)
956 public function setUp() {
957 global $DB, $CFG;
959 if (empty($CFG->unittestprefix)) {
960 return;
963 parent::setUp();
964 $this->DB =& $DB;
965 ob_start();
969 * Method called after each test method. Doesn't do anything extraordinary except restore the global $DB to the real one.
971 public function tearDown() {
972 global $DB, $CFG;
974 if (empty($CFG->unittestprefix)) {
975 return;
978 if (empty($DB)) {
979 $DB = $this->DB;
981 $DB->cleanup();
982 parent::tearDown();
984 // Output buffering
985 if (ob_get_length() > 0) {
986 ob_end_flush();
991 * 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
992 * It should also detect if data is missing from the original tables.
994 public function __destruct() {
995 global $CFG, $DB;
997 if (empty($CFG->unittestprefix)) {
998 return;
1001 $CFG = $this->cfg;
1002 $this->tearDown();
1003 UnitTestDB::restore();
1004 fulldelete($this->pkfile);
1008 * Load a table with some rows of data. A typical call would look like:
1010 * $config = $this->load_test_data('config_plugins',
1011 * array('plugin', 'name', 'value'), array(
1012 * array('frog', 'numlegs', 2),
1013 * array('frog', 'sound', 'croak'),
1014 * array('frog', 'action', 'jump'),
1015 * ));
1017 * @param string $table the table name.
1018 * @param array $cols the columns to fill.
1019 * @param array $data the data to load.
1020 * @return array $objects corresponding to $data.
1022 public function load_test_data($table, array $cols, array $data) {
1023 global $CFG, $DB;
1025 if (empty($CFG->unittestprefix)) {
1026 return;
1029 $results = array();
1030 foreach ($data as $rowid => $row) {
1031 $obj = new stdClass;
1032 foreach ($cols as $key => $colname) {
1033 $obj->$colname = $row[$key];
1035 $obj->id = $DB->insert_record($table, $obj);
1036 $results[$rowid] = $obj;
1038 return $results;
1042 * Clean up data loaded with load_test_data. The call corresponding to the
1043 * example load above would be:
1045 * $this->delete_test_data('config_plugins', $config);
1047 * @param string $table the table name.
1048 * @param array $rows the rows to delete. Actually, only $rows[$key]->id is used.
1050 public function delete_test_data($table, array $rows) {
1051 global $CFG, $DB;
1053 if (empty($CFG->unittestprefix)) {
1054 return;
1057 $ids = array();
1058 foreach ($rows as $row) {
1059 $ids[] = $row->id;
1061 $DB->delete_records_list($table, 'id', $ids);
1066 * This is a Database Engine proxy class: It replaces the global object $DB with itself through a call to the
1067 * static instantiate() method, and restores the original global $DB through restore().
1068 * Internally, it routes all calls to $DB to a real instance of the database engine (aggregated as a member variable),
1069 * except those that are defined in this proxy class. This makes it possible to add extra code to the database engine
1070 * without subclassing it.
1072 * @package moodlecore
1073 * @subpackage simpletestex
1074 * @copyright &copy; 2006 The Open University
1075 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1077 class UnitTestDB {
1078 public static $DB;
1079 private static $real_db;
1081 public $table_data = array();
1084 * Call this statically to connect to the DB using the unittest prefix, instantiate
1085 * the unit test db, store it as a member variable, instantiate $this and use it as the new global $DB.
1087 public static function instantiate() {
1088 global $CFG, $DB;
1089 UnitTestDB::$real_db = clone($DB);
1090 if (empty($CFG->unittestprefix)) {
1091 print_error("prefixnotset", 'simpletest');
1094 if (empty(UnitTestDB::$DB)) {
1095 UnitTestDB::$DB = moodle_database::get_driver_instance($CFG->dbtype, $CFG->dblibrary);
1096 UnitTestDB::$DB->connect($CFG->dbhost, $CFG->dbuser, $CFG->dbpass, $CFG->dbname, $CFG->unittestprefix);
1099 $manager = UnitTestDB::$DB->get_manager();
1101 if (!$manager->table_exists('user')) {
1102 print_error('tablesnotsetup', 'simpletest');
1105 $DB = new UnitTestDB();
1108 public function __call($method, $args) {
1109 // Set args to null if they don't exist (up to 10 args should do)
1110 if (!method_exists($this, $method)) {
1111 return call_user_func_array(array(UnitTestDB::$DB, $method), $args);
1112 } else {
1113 call_user_func_array(array($this, $method), $args);
1117 public function __get($variable) {
1118 return UnitTestDB::$DB->$variable;
1121 public function __set($variable, $value) {
1122 UnitTestDB::$DB->$variable = $value;
1125 public function __isset($variable) {
1126 return isset(UnitTestDB::$DB->$variable);
1129 public function __unset($variable) {
1130 unset(UnitTestDB::$DB->$variable);
1134 * Overriding insert_record to keep track of the ids inserted during unit tests, so that they can be deleted afterwards
1136 public function insert_record($table, $dataobject, $returnid=true, $bulk=false) {
1137 global $DB;
1138 $id = UnitTestDB::$DB->insert_record($table, $dataobject, $returnid, $bulk);
1139 $this->table_data[$table][] = $id;
1140 return $id;
1144 * Overriding update_record: If we are updating a record that was NOT inserted by unit tests,
1145 * throw an exception and cancel update.
1147 * throws moodle_exception If trying to update a record not inserted by unit tests.
1149 public function update_record($table, $dataobject, $bulk=false) {
1150 global $DB;
1151 if ((empty($this->table_data[$table]) || !in_array($dataobject->id, $this->table_data[$table])) && !($table == 'course_categories' && $dataobject->id == 1)) {
1152 // return UnitTestDB::$DB->update_record($table, $dataobject, $bulk);
1153 $a = new stdClass();
1154 $a->id = $dataobject->id;
1155 $a->table = $table;
1156 throw new moodle_exception('updatingnoninsertedrecord', 'simpletest', '', $a);
1157 } else {
1158 return UnitTestDB::$DB->update_record($table, $dataobject, $bulk);
1163 * Overriding delete_record: If we are deleting a record that was NOT inserted by unit tests,
1164 * throw an exception and cancel delete.
1166 * throws moodle_exception If trying to delete a record not inserted by unit tests.
1168 public function delete_records($table, array $conditions=array()) {
1169 global $DB;
1170 $tables_to_ignore = array('context_temp');
1172 $a = new stdClass();
1173 $a->table = $table;
1175 // Get ids matching conditions
1176 if (!$ids_to_delete = $DB->get_field($table, 'id', $conditions)) {
1177 return UnitTestDB::$DB->delete_records($table, $conditions);
1180 $proceed_with_delete = true;
1182 if (!is_array($ids_to_delete)) {
1183 $ids_to_delete = array($ids_to_delete);
1186 foreach ($ids_to_delete as $id) {
1187 if (!in_array($table, $tables_to_ignore) && (empty($this->table_data[$table]) || !in_array($id, $this->table_data[$table]))) {
1188 $proceed_with_delete = false;
1189 $a->id = $id;
1190 break;
1194 if ($proceed_with_delete) {
1195 return UnitTestDB::$DB->delete_records($table, $conditions);
1196 } else {
1197 throw new moodle_exception('deletingnoninsertedrecord', 'simpletest', '', $a);
1202 * Overriding delete_records_select: If we are deleting a record that was NOT inserted by unit tests,
1203 * throw an exception and cancel delete.
1205 * throws moodle_exception If trying to delete a record not inserted by unit tests.
1207 public function delete_records_select($table, $select, array $params=null) {
1208 global $DB;
1209 $a = new stdClass();
1210 $a->table = $table;
1212 // Get ids matching conditions
1213 if (!$ids_to_delete = $DB->get_field_select($table, 'id', $select, $params)) {
1214 return UnitTestDB::$DB->delete_records_select($table, $select, $params);
1217 $proceed_with_delete = true;
1219 foreach ($ids_to_delete as $id) {
1220 if (!in_array($id, $this->table_data[$table])) {
1221 $proceed_with_delete = false;
1222 $a->id = $id;
1223 break;
1227 if ($proceed_with_delete) {
1228 return UnitTestDB::$DB->delete_records_select($table, $select, $params);
1229 } else {
1230 throw new moodle_exception('deletingnoninsertedrecord', 'simpletest', '', $a);
1235 * Removes from the test DB all the records that were inserted during unit tests,
1237 public function cleanup() {
1238 global $DB;
1239 foreach ($this->table_data as $table => $ids) {
1240 foreach ($ids as $id) {
1241 $DB->delete_records($table, array('id' => $id));
1247 * Restores the global $DB object.
1249 public static function restore() {
1250 global $DB;
1251 $DB = UnitTestDB::$real_db;
1254 public function get_field($table, $return, array $conditions) {
1255 if (!is_array($conditions)) {
1256 throw new coding_exception('$conditions is not an array.');
1258 return UnitTestDB::$DB->get_field($table, $return, $conditions);