forum cron MDL-24843 fix typo in mtrace message.
[moodle.git] / lib / simpletestlib.php
CommitLineData
b37eac91 1<?php
2
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.
14//
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/>.
17
3ef8c936 18/**
19 * Utility functions to make unit testing easier.
b9c639d6 20 *
3ef8c936 21 * These functions, particularly the the database ones, are quick and
b9c639d6 22 * dirty methods for getting things done in test cases. None of these
3ef8c936 23 * methods should be used outside test code.
24 *
b37eac91 25 * Major Contirbutors
26 * - T.J.Hunt@open.ac.uk
27 *
78bfb562 28 * @package core
b37eac91 29 * @subpackage simpletestex
78bfb562
PS
30 * @copyright &copy; 2006 The Open University
31 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3ef8c936 32 */
33
78bfb562
PS
34defined('MOODLE_INTERNAL') || die();
35
b37eac91 36/**
37 * Includes
38 */
3ef8c936 39require_once(dirname(__FILE__) . '/../config.php');
40require_once($CFG->libdir . '/simpletestlib/simpletest.php');
41require_once($CFG->libdir . '/simpletestlib/unit_tester.php');
42require_once($CFG->libdir . '/simpletestlib/expectation.php');
4309bd17 43require_once($CFG->libdir . '/simpletestlib/reporter.php');
a205dcdc 44require_once($CFG->libdir . '/simpletestlib/web_tester.php');
76144765 45require_once($CFG->libdir . '/simpletestlib/mock_objects.php');
3ef8c936 46
47/**
48 * Recursively visit all the files in the source tree. Calls the callback
b9c639d6 49 * function with the pathname of each file found.
50 *
51 * @param $path the folder to start searching from.
3ef8c936 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).
b9c639d6 54 * @param $exclude If true, pathnames that match the regexp will be ingored. If false,
3ef8c936 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).
b9c639d6 57 */
3ef8c936 58function recurseFolders($path, $callback, $fileregexp = '/.*/', $exclude = false, $ignorefolders = array()) {
59 $files = scandir($path);
60
61 foreach ($files as $file) {
62 $filepath = $path .'/'. $file;
2e710be8 63 if (strpos($file, '.') === 0) {
64 /// Don't check hidden files.
3ef8c936 65 continue;
66 } else if (is_dir($filepath)) {
67 if (!in_array($filepath, $ignorefolders)) {
68 recurseFolders($filepath, $callback, $fileregexp, $exclude, $ignorefolders);
69 }
70 } else if ($exclude xor preg_match($fileregexp, $filepath)) {
71 call_user_func($callback, $filepath);
72 }
73 }
74}
75
76/**
77 * An expectation for comparing strings ignoring whitespace.
b37eac91 78 *
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
3ef8c936 83 */
84class IgnoreWhitespaceExpectation extends SimpleExpectation {
85 var $expect;
86
87 function IgnoreWhitespaceExpectation($content, $message = '%s') {
88 $this->SimpleExpectation($message);
89 $this->expect=$this->normalise($content);
90 }
91
92 function test($ip) {
93 return $this->normalise($ip)==$this->expect;
94 }
95
96 function normalise($text) {
97 return preg_replace('/\s+/m',' ',trim($text));
98 }
99
100 function testMessage($ip) {
101 return "Input string [$ip] doesn't match the required value.";
102 }
103}
104
105/**
106 * An Expectation that two arrays contain the same list of values.
b37eac91 107 *
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
3ef8c936 112 */
113class ArraysHaveSameValuesExpectation extends SimpleExpectation {
114 var $expect;
115
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.');
121 }
122 $this->expect = $this->normalise($expected);
123 }
124
125 function test($actual) {
126 return $this->normalise($actual) == $this->expect;
127 }
128
129 function normalise($array) {
130 sort($array);
131 return $array;
132 }
133
134 function testMessage($actual) {
135 return 'Array [' . implode(', ', $actual) .
136 '] does not contain the expected list of values [' . implode(', ', $this->expect) . '].';
137 }
138}
139
8954245a 140
3ef8c936 141/**
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.)
b37eac91 145 *
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
3ef8c936 150 */
151class CheckSpecifiedFieldsExpectation extends SimpleExpectation {
152 var $expect;
153
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.');
159 }
160 $this->expect = $expected;
161 }
162
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;
171 }
172 }
173 return true;
174 }
175
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 {
3efb762e 184 $mismatches[] = $key . ' (expected [' . $value . '] got [' . $actual->$key . '].';
3ef8c936 185 }
186 }
187 return 'Actual object does not have all the same fields with the same values as the expected object (' .
188 implode(', ', $mismatches) . ').';
189 }
190}
191
d4bc6be7 192abstract class XMLStructureExpectation extends SimpleExpectation {
4454447d
PS
193 /**
194 * Parse a string as XML and return a DOMDocument;
195 * @param $html
196 * @return unknown_type
197 */
d4bc6be7 198 protected function load_xml($html) {
4454447d
PS
199 $prevsetting = libxml_use_internal_errors(true);
200 $parser = new DOMDocument();
201 if (!$parser->loadXML('<html>' . $html . '</html>')) {
202 $parser = new DOMDocument();
203 }
3d39d775 204 libxml_clear_errors();
4454447d
PS
205 libxml_use_internal_errors($prevsetting);
206 return $parser;
d4bc6be7 207 }
208}
8954245a 209/**
210 * An Expectation that looks to see whether some HMTL contains a tag with a certain attribute.
211 *
212 * @copyright 2009 Tim Hunt
213 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
214 */
d4bc6be7 215class ContainsTagWithAttribute extends XMLStructureExpectation {
8954245a 216 protected $tag;
217 protected $attribute;
218 protected $value;
219
220 function __construct($tag, $attribute, $value, $message = '%s') {
d4bc6be7 221 parent::__construct($message);
8954245a 222 $this->tag = $tag;
223 $this->attribute = $attribute;
224 $this->value = $value;
225 }
226
227 function test($html) {
d4bc6be7 228 $parser = $this->load_xml($html);
6a923128 229 $list = $parser->getElementsByTagName($this->tag);
117bd748 230
6a923128 231 foreach ($list as $node) {
d5bbc449 232 if ($node->attributes->getNamedItem($this->attribute)->nodeValue === (string) $this->value) {
6a923128 233 return true;
234 }
235 }
236 return false;
8954245a 237 }
238
239 function testMessage($html) {
240 return 'Content [' . $html . '] does not contain the tag [' .
241 $this->tag . '] with attribute [' . $this->attribute . '="' . $this->value . '"].';
242 }
243}
244
6a923128 245/**
246 * An Expectation that looks to see whether some HMTL contains a tag with an array of attributes.
247 * All attributes must be present and their values must match the expected values.
f8065dd2 248 * A third parameter can be used to specify attribute=>value pairs which must not be present in a positive match.
6a923128 249 *
250 * @copyright 2009 Nicolas Connault
251 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
252 */
d4bc6be7 253class ContainsTagWithAttributes extends XMLStructureExpectation {
f8065dd2 254 /**
255 * @var string $tag The name of the Tag to search
256 */
6a923128 257 protected $tag;
f8065dd2 258 /**
259 * @var array $expectedvalues An associative array of parameters, all of which must be matched
260 */
261 protected $expectedvalues = array();
262 /**
263 * @var array $forbiddenvalues An associative array of parameters, none of which must be matched
264 */
265 protected $forbiddenvalues = array();
266 /**
267 * @var string $failurereason The reason why the test failed: nomatch or forbiddenmatch
268 */
269 protected $failurereason = 'nomatch';
270
271 function __construct($tag, $expectedvalues, $forbiddenvalues=array(), $message = '%s') {
d4bc6be7 272 parent::__construct($message);
6a923128 273 $this->tag = $tag;
f8065dd2 274 $this->expectedvalues = $expectedvalues;
275 $this->forbiddenvalues = $forbiddenvalues;
6a923128 276 }
f8065dd2 277
6a923128 278 function test($html) {
d4bc6be7 279 $parser = $this->load_xml($html);
6a923128 280 $list = $parser->getElementsByTagName($this->tag);
f8065dd2 281
282 $foundamatch = false;
283
6a923128 284 // Iterating through inputs
285 foreach ($list as $node) {
286 if (empty($node->attributes) || !is_a($node->attributes, 'DOMNamedNodeMap')) {
287 continue;
288 }
289
f8065dd2 290 // For the current expected attribute under consideration, check that values match
291 $allattributesmatch = true;
6a923128 292
f8065dd2 293 foreach ($this->expectedvalues as $expectedattribute => $expectedvalue) {
d5bbc449 294 if ($node->getAttribute($expectedattribute) === '' && $expectedvalue !== '') {
f8065dd2 295 $this->failurereason = 'nomatch';
296 continue 2; // Skip this tag, it doesn't have all the expected attributes
6a923128 297 }
d5bbc449 298 if ($node->getAttribute($expectedattribute) !== (string) $expectedvalue) {
f8065dd2 299 $allattributesmatch = false;
300 $this->failurereason = 'nomatch';
6a923128 301 }
302 }
303
f8065dd2 304 if ($allattributesmatch) {
305 $foundamatch = true;
306
307 // Now make sure this node doesn't have any of the forbidden attributes either
308 $nodeattrlist = $node->attributes;
309
310 foreach ($nodeattrlist as $domattrname => $domattr) {
d5bbc449 311 if (array_key_exists($domattrname, $this->forbiddenvalues) && $node->getAttribute($domattrname) === (string) $this->forbiddenvalues[$domattrname]) {
f8065dd2 312 $this->failurereason = "forbiddenmatch:$domattrname:" . $node->getAttribute($domattrname);
313 $foundamatch = false;
314 }
315 }
6a923128 316 }
6a923128 317 }
f8065dd2 318
319 return $foundamatch;
6a923128 320 }
f8065dd2 321
6a923128 322 function testMessage($html) {
f8065dd2 323 $output = 'Content [' . $html . '] ';
324
325 if (preg_match('/forbiddenmatch:(.*):(.*)/', $this->failurereason, $matches)) {
326 $output .= "contains the tag $this->tag with the forbidden attribute=>value pair: [$matches[1]=>$matches[2]]";
327 } else if ($this->failurereason == 'nomatch') {
328 $output .= 'does not contain the tag [' . $this->tag . '] with attributes [';
329 foreach ($this->expectedvalues as $var => $val) {
330 $output .= "$var=\"$val\" ";
331 }
332 $output = rtrim($output);
333 $output .= '].';
6a923128 334 }
f8065dd2 335
6a923128 336 return $output;
337 }
338}
8954245a 339
340/**
341 * An Expectation that looks to see whether some HMTL contains a tag with a certain text inside it.
342 *
343 * @copyright 2009 Tim Hunt
344 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
345 */
d4bc6be7 346class ContainsTagWithContents extends XMLStructureExpectation {
8954245a 347 protected $tag;
348 protected $content;
349
350 function __construct($tag, $content, $message = '%s') {
d4bc6be7 351 parent::__construct($message);
8954245a 352 $this->tag = $tag;
353 $this->content = $content;
354 }
355
356 function test($html) {
d4bc6be7 357 $parser = $this->load_xml($html);
6a923128 358 $list = $parser->getElementsByTagName($this->tag);
359
360 foreach ($list as $node) {
361 if ($node->textContent == $this->content) {
362 return true;
363 }
364 }
117bd748 365
6a923128 366 return false;
8954245a 367 }
368
369 function testMessage($html) {
370 return 'Content [' . $html . '] does not contain the tag [' .
371 $this->tag . '] with contents [' . $this->content . '].';
6a923128 372 }
373}
374
375/**
376 * An Expectation that looks to see whether some HMTL contains an empty tag of a specific type.
377 *
378 * @copyright 2009 Nicolas Connault
379 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
380 */
d4bc6be7 381class ContainsEmptyTag extends XMLStructureExpectation {
6a923128 382 protected $tag;
383
384 function __construct($tag, $message = '%s') {
d4bc6be7 385 parent::__construct($message);
6a923128 386 $this->tag = $tag;
387 }
388
389 function test($html) {
d4bc6be7 390 $parser = $this->load_xml($html);
6a923128 391 $list = $parser->getElementsByTagName($this->tag);
392
393 foreach ($list as $node) {
394 if (!$node->hasAttributes() && !$node->hasChildNodes()) {
395 return true;
396 }
397 }
117bd748 398
6a923128 399 return false;
400 }
401
402 function testMessage($html) {
403 return 'Content ['.$html.'] does not contain the empty tag ['.$this->tag.'].';
8954245a 404 }
405}
406
407
f68cb08b 408/**
409 * This class lets you write unit tests that access a separate set of test
410 * tables with a different prefix. Only those tables you explicitly ask to
411 * be created will be.
240be1d7 412 *
413 * This class has failities for flipping $USER->id.
414 *
415 * The tear-down method for this class should automatically revert any changes
416 * you make during test set-up using the metods defined here. That is, it will
417 * drop tables for you automatically and revert to the real $DB and $USER->id.
b37eac91 418 *
419 * @package moodlecore
420 * @subpackage simpletestex
421 * @copyright &copy; 2006 The Open University
422 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
f68cb08b 423 */
424class UnitTestCaseUsingDatabase extends UnitTestCase {
425 private $realdb;
426 protected $testdb;
82701e24 427 private $realuserid = null;
f68cb08b 428 private $tables = array();
429
f68cb08b 430 public function __construct($label = false) {
431 global $DB, $CFG;
432
82701e24 433 // Complain if we get this far and $CFG->unittestprefix is not set.
f68cb08b 434 if (empty($CFG->unittestprefix)) {
435 throw new coding_exception('You cannot use UnitTestCaseUsingDatabase unless you set $CFG->unittestprefix.');
436 }
82701e24 437
438 // Only do this after the above text.
f68cb08b 439 parent::UnitTestCase($label);
440
82701e24 441 // Create the test DB instance.
f68cb08b 442 $this->realdb = $DB;
443 $this->testdb = moodle_database::get_driver_instance($CFG->dbtype, $CFG->dblibrary);
444 $this->testdb->connect($CFG->dbhost, $CFG->dbuser, $CFG->dbpass, $CFG->dbname, $CFG->unittestprefix);
445 }
446
447 /**
448 * Switch to using the test database for all queries until further notice.
f68cb08b 449 */
450 protected function switch_to_test_db() {
451 global $DB;
452 if ($DB === $this->testdb) {
453 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);
454 }
455 $DB = $this->testdb;
456 }
457
458 /**
459 * Revert to using the test database for all future queries.
460 */
461 protected function revert_to_real_db() {
462 global $DB;
463 if ($DB !== $this->testdb) {
7fa95ef1 464 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);
f68cb08b 465 }
466 $DB = $this->realdb;
467 }
468
82701e24 469 /**
470 * Switch $USER->id to a test value.
82701e24 471 *
472 * It might be worth making this method do more robuse $USER switching in future,
473 * however, this is sufficient for my needs at present.
474 */
475 protected function switch_global_user_id($userid) {
476 global $USER;
477 if (!is_null($this->realuserid)) {
478 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);
479 } else {
480 $this->realuserid = $USER->id;
481 }
482 $USER->id = $userid;
483 }
484
485 /**
486 * Revert $USER->id to the real value.
487 */
488 protected function revert_global_user_id() {
489 global $USER;
490 if (is_null($this->realuserid)) {
491 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);
492 } else {
493 $USER->id = $this->realuserid;
494 $this->realuserid = null;
495 }
496 }
497
f68cb08b 498 /**
499 * Check that the user has not forgotten to clean anything up, and if they
500 * have, display a rude message and clean it up for them.
501 */
240be1d7 502 private function automatic_clean_up() {
f68cb08b 503 global $DB;
82701e24 504 $cleanmore = false;
f68cb08b 505
240be1d7 506 // Drop any test tables that were created.
f68cb08b 507 foreach ($this->tables as $tablename => $notused) {
508 $this->drop_test_table($tablename);
509 }
510
240be1d7 511 // Switch back to the real DB if necessary.
f68cb08b 512 if ($DB !== $this->realdb) {
f68cb08b 513 $this->revert_to_real_db();
82701e24 514 $cleanmore = true;
515 }
516
240be1d7 517 // revert_global_user_id if necessary.
82701e24 518 if (!is_null($this->realuserid)) {
82701e24 519 $this->revert_global_user_id();
520 $cleanmore = true;
521 }
522
523 if ($cleanmore) {
524 accesslib_clear_all_caches_for_unit_testing();
f68cb08b 525 }
526 }
527
528 public function tearDown() {
240be1d7 529 $this->automatic_clean_up();
f68cb08b 530 parent::tearDown();
531 }
532
533 public function __destruct() {
240be1d7 534 // Should not be necessary thanks to tearDown, but no harm in belt and braces.
535 $this->automatic_clean_up();
f68cb08b 536 }
537
538 /**
539 * Create a test table just like a real one, getting getting the definition from
540 * the specified install.xml file.
541 * @param string $tablename the name of the test table.
542 * @param string $installxmlfile the install.xml file in which this table is defined.
543 * $CFG->dirroot . '/' will be prepended, and '/db/install.xml' appended,
544 * so you need only specify, for example, 'mod/quiz'.
545 */
546 protected function create_test_table($tablename, $installxmlfile) {
547 global $CFG;
04aa2fd6 548 $dbman = $this->testdb->get_manager();
f68cb08b 549 if (isset($this->tables[$tablename])) {
c39a4607 550 debugging('You are attempting to create test table ' . $tablename . ' again. It already exists. Please review your code immediately.', DEBUG_DEVELOPER);
f68cb08b 551 return;
552 }
04aa2fd6
EL
553 if ($dbman->table_exists($tablename)) {
554 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);
555 $dbman->drop_table(new xmldb_table($tablename));
556 }
c6adec25 557 $dbman->install_one_table_from_xmldb_file($CFG->dirroot . '/' . $installxmlfile . '/db/install.xml', $tablename, true); // with structure cache enabled!
f68cb08b 558 $this->tables[$tablename] = 1;
559 }
560
561 /**
562 * Convenience method for calling create_test_table repeatedly.
563 * @param array $tablenames an array of table names.
564 * @param string $installxmlfile the install.xml file in which this table is defined.
565 * $CFG->dirroot . '/' will be prepended, and '/db/install.xml' appended,
566 * so you need only specify, for example, 'mod/quiz'.
567 */
568 protected function create_test_tables($tablenames, $installxmlfile) {
569 foreach ($tablenames as $tablename) {
570 $this->create_test_table($tablename, $installxmlfile);
571 }
572 }
573
574 /**
575 * Drop a test table.
576 * @param $tablename the name of the test table.
577 */
578 protected function drop_test_table($tablename) {
579 if (!isset($this->tables[$tablename])) {
580 debugging('You are attempting to drop test table ' . $tablename . ' but it does not exist. Please review your code immediately.', DEBUG_DEVELOPER);
581 return;
582 }
583 $dbman = $this->testdb->get_manager();
584 $table = new xmldb_table($tablename);
585 $dbman->drop_table($table);
586 unset($this->tables[$tablename]);
587 }
588
589 /**
590 * Convenience method for calling drop_test_table repeatedly.
591 * @param array $tablenames an array of table names.
592 */
593 protected function drop_test_tables($tablenames) {
594 foreach ($tablenames as $tablename) {
595 $this->drop_test_table($tablename);
596 }
597 }
598
599 /**
600 * Load a table with some rows of data. A typical call would look like:
601 *
602 * $config = $this->load_test_data('config_plugins',
603 * array('plugin', 'name', 'value'), array(
604 * array('frog', 'numlegs', 2),
605 * array('frog', 'sound', 'croak'),
606 * array('frog', 'action', 'jump'),
607 * ));
608 *
609 * @param string $table the table name.
610 * @param array $cols the columns to fill.
611 * @param array $data the data to load.
612 * @return array $objects corresponding to $data.
613 */
614 protected function load_test_data($table, array $cols, array $data) {
615 $results = array();
616 foreach ($data as $rowid => $row) {
617 $obj = new stdClass;
618 foreach ($cols as $key => $colname) {
619 $obj->$colname = $row[$key];
620 }
621 $obj->id = $this->testdb->insert_record($table, $obj);
622 $results[$rowid] = $obj;
623 }
624 return $results;
625 }
626
627 /**
628 * Clean up data loaded with load_test_data. The call corresponding to the
629 * example load above would be:
630 *
631 * $this->delete_test_data('config_plugins', $config);
632 *
633 * @param string $table the table name.
634 * @param array $rows the rows to delete. Actually, only $rows[$key]->id is used.
635 */
636 protected function delete_test_data($table, array $rows) {
637 $ids = array();
638 foreach ($rows as $row) {
639 $ids[] = $row->id;
640 }
641 $this->testdb->delete_records_list($table, 'id', $ids);
642 }
643}
644
8954245a 645
b37eac91 646/**
647 * @package moodlecore
648 * @subpackage simpletestex
649 * @copyright &copy; 2006 The Open University
650 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
651 */
58fa5d6f 652class FakeDBUnitTestCase extends UnitTestCase {
356e0010 653 public $tables = array();
90997d6d 654 public $pkfile;
655 public $cfg;
274e2947 656 public $DB;
356e0010 657
90997d6d 658 /**
659 * In the constructor, record the max(id) of each test table into a csv file.
660 * If this file already exists, it means that a previous run of unit tests
661 * did not complete, and has left data undeleted in the DB. This data is then
662 * deleted and the file is retained. Otherwise it is created.
b37eac91 663 *
664 * throws moodle_exception if CSV file cannot be created
90997d6d 665 */
b9c639d6 666 public function __construct($label = false) {
84ebf08d 667 global $DB, $CFG;
668
669 if (empty($CFG->unittestprefix)) {
670 return;
671 }
672
b9c639d6 673 parent::UnitTestCase($label);
90997d6d 674 // MDL-16483 Get PKs and save data to text file
84ebf08d 675
90997d6d 676 $this->pkfile = $CFG->dataroot.'/testtablespks.csv';
677 $this->cfg = $CFG;
274e2947 678
679 UnitTestDB::instantiate();
90997d6d 680
681 $tables = $DB->get_tables();
682
683 // The file exists, so use it to truncate tables (tests aborted before test data could be removed)
684 if (file_exists($this->pkfile)) {
685 $this->truncate_test_tables($this->get_table_data($this->pkfile));
686
687 } else { // Create the file
688 $tabledata = '';
689
690 foreach ($tables as $table) {
58fa5d6f 691 if ($table != 'sessions') {
90997d6d 692 if (!$max_id = $DB->get_field_sql("SELECT MAX(id) FROM {$CFG->unittestprefix}{$table}")) {
693 $max_id = 0;
694 }
695 $tabledata .= "$table, $max_id\n";
696 }
697 }
698 if (!file_put_contents($this->pkfile, $tabledata)) {
5d1381c2 699 $a = new stdClass();
700 $a->filename = $this->pkfile;
701 throw new moodle_exception('testtablescsvfileunwritable', 'simpletest', '', $a);
90997d6d 702 }
703 }
704 }
705
706 /**
707 * 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.
708 * @param array $tabledata
709 */
710 private function truncate_test_tables($tabledata) {
711 global $CFG, $DB;
712
84ebf08d 713 if (empty($CFG->unittestprefix)) {
714 return;
715 }
716
90997d6d 717 $tables = $DB->get_tables();
718
719 foreach ($tables as $table) {
3f57bd45 720 if ($table != 'sessions' && isset($tabledata[$table])) {
5d1381c2 721 // $DB->delete_records_select($table, "id > ?", array($tabledata[$table]));
90997d6d 722 }
723 }
356e0010 724 }
725
90997d6d 726 /**
727 * Given a filename, opens it and parses the csv contained therein. It expects two fields per line:
728 * 1. Table name
729 * 2. Max id
b37eac91 730 *
731 * throws moodle_exception if file doesn't exist
732 *
90997d6d 733 * @param string $filename
90997d6d 734 */
735 public function get_table_data($filename) {
84ebf08d 736 global $CFG;
737
738 if (empty($CFG->unittestprefix)) {
739 return;
740 }
741
90997d6d 742 if (file_exists($this->pkfile)) {
743 $handle = fopen($this->pkfile, 'r');
744 $tabledata = array();
745
746 while (($data = fgetcsv($handle, 1000, ",")) !== false) {
747 $tabledata[$data[0]] = $data[1];
748 }
749 return $tabledata;
750 } else {
5d1381c2 751 $a = new stdClass();
752 $a->filename = $this->pkfile;
5d1381c2 753 throw new moodle_exception('testtablescsvfilemissing', 'simpletest', '', $a);
90997d6d 754 return false;
755 }
756 }
757
758 /**
759 * Method called before each test method. Replaces the real $DB with the one configured for unit tests (different prefix, $CFG->unittestprefix).
760 * Also detects if this config setting is properly set, and if the user table exists.
b37eac91 761 * @todo Improve detection of incorrectly built DB test tables (e.g. detect version discrepancy and offer to upgrade/rebuild)
90997d6d 762 */
356e0010 763 public function setUp() {
84ebf08d 764 global $DB, $CFG;
765
766 if (empty($CFG->unittestprefix)) {
767 return;
768 }
769
356e0010 770 parent::setUp();
274e2947 771 $this->DB =& $DB;
915d745f 772 ob_start();
5d1381c2 773 }
774
775 /**
776 * Method called after each test method. Doesn't do anything extraordinary except restore the global $DB to the real one.
777 */
778 public function tearDown() {
84ebf08d 779 global $DB, $CFG;
780
781 if (empty($CFG->unittestprefix)) {
782 return;
783 }
784
274e2947 785 if (empty($DB)) {
786 $DB = $this->DB;
787 }
5d1381c2 788 $DB->cleanup();
789 parent::tearDown();
747f4a4c 790
791 // Output buffering
915d745f 792 if (ob_get_length() > 0) {
793 ob_end_flush();
794 }
5d1381c2 795 }
796
797 /**
798 * 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
799 * It should also detect if data is missing from the original tables.
800 */
801 public function __destruct() {
802 global $CFG, $DB;
803
84ebf08d 804 if (empty($CFG->unittestprefix)) {
805 return;
806 }
807
5d1381c2 808 $CFG = $this->cfg;
809 $this->tearDown();
810 UnitTestDB::restore();
811 fulldelete($this->pkfile);
812 }
821e4ecf 813
814 /**
815 * Load a table with some rows of data. A typical call would look like:
816 *
817 * $config = $this->load_test_data('config_plugins',
818 * array('plugin', 'name', 'value'), array(
819 * array('frog', 'numlegs', 2),
820 * array('frog', 'sound', 'croak'),
821 * array('frog', 'action', 'jump'),
822 * ));
823 *
824 * @param string $table the table name.
825 * @param array $cols the columns to fill.
826 * @param array $data the data to load.
827 * @return array $objects corresponding to $data.
828 */
829 public function load_test_data($table, array $cols, array $data) {
84ebf08d 830 global $CFG, $DB;
831
832 if (empty($CFG->unittestprefix)) {
833 return;
834 }
835
821e4ecf 836 $results = array();
837 foreach ($data as $rowid => $row) {
838 $obj = new stdClass;
839 foreach ($cols as $key => $colname) {
840 $obj->$colname = $row[$key];
841 }
842 $obj->id = $DB->insert_record($table, $obj);
843 $results[$rowid] = $obj;
844 }
845 return $results;
846 }
847
848 /**
849 * Clean up data loaded with load_test_data. The call corresponding to the
850 * example load above would be:
851 *
852 * $this->delete_test_data('config_plugins', $config);
853 *
854 * @param string $table the table name.
855 * @param array $rows the rows to delete. Actually, only $rows[$key]->id is used.
856 */
857 public function delete_test_data($table, array $rows) {
84ebf08d 858 global $CFG, $DB;
859
860 if (empty($CFG->unittestprefix)) {
861 return;
862 }
863
821e4ecf 864 $ids = array();
865 foreach ($rows as $row) {
866 $ids[] = $row->id;
867 }
868 $DB->delete_records_list($table, 'id', $ids);
869 }
5d1381c2 870}
871
872/**
873 * This is a Database Engine proxy class: It replaces the global object $DB with itself through a call to the
874 * static instantiate() method, and restores the original global $DB through restore().
875 * Internally, it routes all calls to $DB to a real instance of the database engine (aggregated as a member variable),
876 * except those that are defined in this proxy class. This makes it possible to add extra code to the database engine
877 * without subclassing it.
b37eac91 878 *
879 * @package moodlecore
880 * @subpackage simpletestex
881 * @copyright &copy; 2006 The Open University
882 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5d1381c2 883 */
884class UnitTestDB {
885 public static $DB;
886 private static $real_db;
356e0010 887
5d1381c2 888 public $table_data = array();
889
5d1381c2 890 /**
891 * Call this statically to connect to the DB using the unittest prefix, instantiate
892 * the unit test db, store it as a member variable, instantiate $this and use it as the new global $DB.
893 */
894 public static function instantiate() {
895 global $CFG, $DB;
896 UnitTestDB::$real_db = clone($DB);
90997d6d 897 if (empty($CFG->unittestprefix)) {
b9c639d6 898 print_error("prefixnotset", 'simpletest');
899 }
900
274e2947 901 if (empty(UnitTestDB::$DB)) {
902 UnitTestDB::$DB = moodle_database::get_driver_instance($CFG->dbtype, $CFG->dblibrary);
beaa43db 903 UnitTestDB::$DB->connect($CFG->dbhost, $CFG->dbuser, $CFG->dbpass, $CFG->dbname, $CFG->unittestprefix);
274e2947 904 }
905
5d1381c2 906 $manager = UnitTestDB::$DB->get_manager();
356e0010 907
908 if (!$manager->table_exists('user')) {
b9c639d6 909 print_error('tablesnotsetup', 'simpletest');
910 }
5d1381c2 911
912 $DB = new UnitTestDB();
913 }
914
915 public function __call($method, $args) {
916 // Set args to null if they don't exist (up to 10 args should do)
917 if (!method_exists($this, $method)) {
918 return call_user_func_array(array(UnitTestDB::$DB, $method), $args);
919 } else {
920 call_user_func_array(array($this, $method), $args);
921 }
922 }
923
924 public function __get($variable) {
925 return UnitTestDB::$DB->$variable;
926 }
927
928 public function __set($variable, $value) {
929 UnitTestDB::$DB->$variable = $value;
930 }
931
932 public function __isset($variable) {
933 return isset(UnitTestDB::$DB->$variable);
934 }
935
936 public function __unset($variable) {
937 unset(UnitTestDB::$DB->$variable);
b9c639d6 938 }
939
90997d6d 940 /**
5d1381c2 941 * Overriding insert_record to keep track of the ids inserted during unit tests, so that they can be deleted afterwards
90997d6d 942 */
5d1381c2 943 public function insert_record($table, $dataobject, $returnid=true, $bulk=false) {
356e0010 944 global $DB;
5d1381c2 945 $id = UnitTestDB::$DB->insert_record($table, $dataobject, $returnid, $bulk);
946 $this->table_data[$table][] = $id;
947 return $id;
948 }
356e0010 949
5d1381c2 950 /**
951 * Overriding update_record: If we are updating a record that was NOT inserted by unit tests,
952 * throw an exception and cancel update.
117bd748 953 *
b37eac91 954 * throws moodle_exception If trying to update a record not inserted by unit tests.
5d1381c2 955 */
956 public function update_record($table, $dataobject, $bulk=false) {
957 global $DB;
747f4a4c 958 if ((empty($this->table_data[$table]) || !in_array($dataobject->id, $this->table_data[$table])) && !($table == 'course_categories' && $dataobject->id == 1)) {
274e2947 959 // return UnitTestDB::$DB->update_record($table, $dataobject, $bulk);
960 $a = new stdClass();
961 $a->id = $dataobject->id;
962 $a->table = $table;
274e2947 963 throw new moodle_exception('updatingnoninsertedrecord', 'simpletest', '', $a);
5d1381c2 964 } else {
965 return UnitTestDB::$DB->update_record($table, $dataobject, $bulk);
966 }
b9c639d6 967 }
968
969 /**
5d1381c2 970 * Overriding delete_record: If we are deleting a record that was NOT inserted by unit tests,
971 * throw an exception and cancel delete.
b37eac91 972 *
973 * throws moodle_exception If trying to delete a record not inserted by unit tests.
b9c639d6 974 */
274e2947 975 public function delete_records($table, array $conditions=array()) {
5d1381c2 976 global $DB;
747f4a4c 977 $tables_to_ignore = array('context_temp');
978
5d1381c2 979 $a = new stdClass();
980 $a->table = $table;
981
982 // Get ids matching conditions
983 if (!$ids_to_delete = $DB->get_field($table, 'id', $conditions)) {
984 return UnitTestDB::$DB->delete_records($table, $conditions);
985 }
986
987 $proceed_with_delete = true;
988
989 if (!is_array($ids_to_delete)) {
990 $ids_to_delete = array($ids_to_delete);
991 }
992
993 foreach ($ids_to_delete as $id) {
747f4a4c 994 if (!in_array($table, $tables_to_ignore) && (empty($this->table_data[$table]) || !in_array($id, $this->table_data[$table]))) {
5d1381c2 995 $proceed_with_delete = false;
996 $a->id = $id;
997 break;
998 }
999 }
1000
1001 if ($proceed_with_delete) {
1002 return UnitTestDB::$DB->delete_records($table, $conditions);
1003 } else {
5d1381c2 1004 throw new moodle_exception('deletingnoninsertedrecord', 'simpletest', '', $a);
1005 }
b9c639d6 1006 }
b9c639d6 1007
5d1381c2 1008 /**
1009 * Overriding delete_records_select: If we are deleting a record that was NOT inserted by unit tests,
1010 * throw an exception and cancel delete.
b37eac91 1011 *
1012 * throws moodle_exception If trying to delete a record not inserted by unit tests.
5d1381c2 1013 */
1014 public function delete_records_select($table, $select, array $params=null) {
1015 global $DB;
1016 $a = new stdClass();
1017 $a->table = $table;
1018
1019 // Get ids matching conditions
1020 if (!$ids_to_delete = $DB->get_field_select($table, 'id', $select, $params)) {
1021 return UnitTestDB::$DB->delete_records_select($table, $select, $params);
1022 }
1023
1024 $proceed_with_delete = true;
1025
1026 foreach ($ids_to_delete as $id) {
1027 if (!in_array($id, $this->table_data[$table])) {
1028 $proceed_with_delete = false;
1029 $a->id = $id;
1030 break;
1031 }
1032 }
1033
1034 if ($proceed_with_delete) {
1035 return UnitTestDB::$DB->delete_records_select($table, $select, $params);
1036 } else {
5d1381c2 1037 throw new moodle_exception('deletingnoninsertedrecord', 'simpletest', '', $a);
1038 }
1039 }
1040
1041 /**
1042 * Removes from the test DB all the records that were inserted during unit tests,
1043 */
1044 public function cleanup() {
1045 global $DB;
1046 foreach ($this->table_data as $table => $ids) {
1047 foreach ($ids as $id) {
1048 $DB->delete_records($table, array('id' => $id));
1049 }
1050 }
1051 }
1052
1053 /**
1054 * Restores the global $DB object.
1055 */
1056 public static function restore() {
1057 global $DB;
1058 $DB = UnitTestDB::$real_db;
1059 }
1060
1061 public function get_field($table, $return, array $conditions) {
1062 if (!is_array($conditions)) {
fa98e6d1 1063 throw new coding_exception('$conditions is not an array.');
5d1381c2 1064 }
1065 return UnitTestDB::$DB->get_field($table, $return, $conditions);
1066 }
1067}