3 // This file is part of Moodle - http://moodle.org/
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.
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/>.
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.
26 * - T.J.Hunt@open.ac.uk
29 * @subpackage simpletestex
30 * @copyright © 2006 The Open University
31 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
34 defined('MOODLE_INTERNAL') ||
die();
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');
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.
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);
77 * An expectation for comparing strings ignoring whitespace.
80 * @subpackage simpletestex
81 * @copyright © 2006 The Open University
82 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
84 class IgnoreWhitespaceExpectation
extends SimpleExpectation
{
87 function IgnoreWhitespaceExpectation($content, $message = '%s') {
88 $this->SimpleExpectation($message);
89 $this->expect
=$this->normalise($content);
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 © 2006 The Open University
111 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
113 class ArraysHaveSameValuesExpectation
extends SimpleExpectation
{
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) {
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 © 2006 The Open University
149 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
151 class CheckSpecifiedFieldsExpectation
extends SimpleExpectation
{
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) {
167 } else if (is_null($value) && is_null($actual->$key)) {
176 function testMessage($actual) {
177 $mismatches = array();
178 foreach ($this->expect
as $key => $value) {
179 if (isset($value) && isset($actual->$key) && $actual->$key == $value) {
181 } else if (is_null($value) && is_null($actual->$key)) {
183 } else if (!isset($actual->$key)) {
184 $mismatches[] = $key . ' (expected [' . $value . '] but was missing.';
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;
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);
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
{
231 protected $attribute;
234 function __construct($tag, $attribute, $value, $message = '%s') {
235 parent
::__construct($message);
237 $this->attribute
= $attribute;
238 $this->value
= $value;
241 function test($html) {
242 $parser = $this->load_xml($html);
243 if (is_array($parser)) {
246 $list = $parser->getElementsByTagName($this->tag
);
248 foreach ($list as $node) {
249 if ($node->attributes
->getNamedItem($this->attribute
)->nodeValue
=== (string) $this->value
) {
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
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);
291 $this->expectedvalues
= $expectedvalues;
292 $this->forbiddenvalues
= $forbiddenvalues;
295 function test($html) {
296 $parser = $this->load_xml($html);
297 if (is_array($parser)) {
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')) {
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) {
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;
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);
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
374 * @var array $expectedvalues An associative array of parameters, all of which must be matched
378 * @var array $forbiddenvalues An associative array of parameters, none of which must be matched
382 * @var string $failurereason The reason why the test failed: nomatch or forbiddenmatch
386 function __construct($name, $choices, $selected = null, $enabled = null, $message = '%s') {
387 parent
::__construct($message);
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)) {
400 $list = $parser->getElementsByTagName('select');
402 // Iterating through inputs
403 foreach ($list as $node) {
404 if (empty($node->attributes
) ||
!is_a($node->attributes
, 'DOMNamedNodeMap')) {
408 if ($node->getAttribute('name') != $this->name
) {
412 if ($this->enabled
=== true && $node->getAttribute('disabled')) {
414 } else if ($this->enabled
=== false && $node->getAttribute('disabled') != 'disabled') {
418 $options = $node->getElementsByTagName('option');
419 reset($this->choices
);
420 foreach ($options as $option) {
421 if ($option->getAttribute('value') != key($this->choices
)) {
424 if ($option->firstChild
->wholeText
!= current($this->choices
)) {
427 if ($option->getAttribute('value') === $this->selected
&&
428 !$option->hasAttribute('selected')) {
431 next($this->choices
);
433 if (current($this->choices
) !== false) {
434 // The HTML did not contain all the choices.
442 function customMessage($html) {
443 if ($this->enabled
=== true) {
444 $state = 'an enabled';
445 } else if ($this->enabled
=== false) {
446 $state = 'a disabled';
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).';
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);
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
{
499 function __construct($tag, $content, $message = '%s') {
500 parent
::__construct($message);
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
) {
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
{
533 function __construct($tag, $message = '%s') {
534 parent
::__construct($message);
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()) {
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 © 2006 The Open University
571 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
573 class UnitTestCaseUsingDatabase
extends UnitTestCase
{
576 private $realuserid = null;
577 private $tables = array();
582 public function __construct($label = false) {
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.
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() {
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
);
624 * Revert to using the test database for all future queries.
626 protected function revert_to_real_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
);
635 * Switch to using the test $CFG for all queries until further notice.
637 protected function switch_to_test_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() {
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) {
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
);
667 $this->realuserid
= $USER->id
;
673 * Revert $USER->id to the real value.
675 protected function revert_global_user_id() {
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
);
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() {
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();
704 // Switch back to the real CFG if necessary.
705 if (isset($CFG->testcfg
)) {
706 $this->revert_to_real_cfg();
710 // revert_global_user_id if necessary.
711 if (!is_null($this->realuserid
)) {
712 $this->revert_global_user_id();
717 accesslib_clear_all_caches_for_unit_testing();
719 get_fast_modinfo($course);
723 public function tearDown() {
724 $this->automatic_clean_up();
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) {
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
);
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);
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
);
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'),
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) {
811 foreach ($data as $rowid => $row) {
813 foreach ($cols as $key => $colname) {
814 $obj->$colname = $row[$key];
816 $obj->id
= $this->testdb
->insert_record($table, $obj);
817 $results[$rowid] = $obj;
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) {
833 foreach ($rows as $row) {
836 $this->testdb
->delete_records_list($table, 'id', $ids);
842 * @package moodlecore
843 * @subpackage simpletestex
844 * @copyright © 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();
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) {
864 if (empty($CFG->unittestprefix
)) {
868 parent
::UnitTestCase($label);
869 // MDL-16483 Get PKs and save data to text file
871 $this->pkfile
= $CFG->dataroot
.'/testtablespks.csv';
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
885 foreach ($tables as $table) {
886 if ($table != 'sessions') {
887 if (!$max_id = $DB->get_field_sql("SELECT MAX(id) FROM {$CFG->unittestprefix}{$table}")) {
890 $tabledata .= "$table, $max_id\n";
893 if (!file_put_contents($this->pkfile
, $tabledata)) {
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) {
908 if (empty($CFG->unittestprefix
)) {
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:
926 * throws moodle_exception if file doesn't exist
928 * @param string $filename
930 public function get_table_data($filename) {
933 if (empty($CFG->unittestprefix
)) {
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];
947 $a->filename
= $this->pkfile
;
948 throw new moodle_exception('testtablescsvfilemissing', 'simpletest', '', $a);
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() {
961 if (empty($CFG->unittestprefix
)) {
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() {
976 if (empty($CFG->unittestprefix
)) {
987 if (ob_get_length() > 0) {
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() {
999 if (empty($CFG->unittestprefix
)) {
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'),
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) {
1027 if (empty($CFG->unittestprefix
)) {
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;
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) {
1055 if (empty($CFG->unittestprefix
)) {
1060 foreach ($rows as $row) {
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 © 2006 The Open University
1077 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
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() {
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);
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) {
1140 $id = UnitTestDB
::$DB->insert_record($table, $dataobject, $returnid, $bulk);
1141 $this->table_data
[$table][] = $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) {
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
;
1158 throw new moodle_exception('updatingnoninsertedrecord', 'simpletest', '', $a);
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()) {
1172 $tables_to_ignore = array('context_temp');
1174 $a = new stdClass();
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;
1196 if ($proceed_with_delete) {
1197 return UnitTestDB
::$DB->delete_records($table, $conditions);
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) {
1211 $a = new stdClass();
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;
1229 if ($proceed_with_delete) {
1230 return UnitTestDB
::$DB->delete_records_select($table, $select, $params);
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() {
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() {
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);