"MDL-15488, fix preview URL"
[moodle.git] / lib / simpletestlib.php
CommitLineData
56768525 1<?php // $Id$
3ef8c936 2/**
3 * Utility functions to make unit testing easier.
b9c639d6 4 *
3ef8c936 5 * These functions, particularly the the database ones, are quick and
b9c639d6 6 * dirty methods for getting things done in test cases. None of these
3ef8c936 7 * methods should be used outside test code.
8 *
9 * @copyright &copy; 2006 The Open University
10 * @author T.J.Hunt@open.ac.uk
11 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
12 * @version $Id$
13 * @package SimpleTestEx
14 */
15
16require_once(dirname(__FILE__) . '/../config.php');
17require_once($CFG->libdir . '/simpletestlib/simpletest.php');
18require_once($CFG->libdir . '/simpletestlib/unit_tester.php');
19require_once($CFG->libdir . '/simpletestlib/expectation.php');
4309bd17 20require_once($CFG->libdir . '/simpletestlib/reporter.php');
a205dcdc 21require_once($CFG->libdir . '/simpletestlib/web_tester.php');
76144765 22require_once($CFG->libdir . '/simpletestlib/mock_objects.php');
3ef8c936 23
24/**
25 * Recursively visit all the files in the source tree. Calls the callback
b9c639d6 26 * function with the pathname of each file found.
27 *
28 * @param $path the folder to start searching from.
3ef8c936 29 * @param $callback the function to call with the name of each file found.
30 * @param $fileregexp a regexp used to filter the search (optional).
b9c639d6 31 * @param $exclude If true, pathnames that match the regexp will be ingored. If false,
3ef8c936 32 * only files that match the regexp will be included. (default false).
33 * @param array $ignorefolders will not go into any of these folders (optional).
b9c639d6 34 */
3ef8c936 35function recurseFolders($path, $callback, $fileregexp = '/.*/', $exclude = false, $ignorefolders = array()) {
36 $files = scandir($path);
37
38 foreach ($files as $file) {
39 $filepath = $path .'/'. $file;
40 if ($file == '.' || $file == '..') {
41 continue;
42 } else if (is_dir($filepath)) {
43 if (!in_array($filepath, $ignorefolders)) {
44 recurseFolders($filepath, $callback, $fileregexp, $exclude, $ignorefolders);
45 }
46 } else if ($exclude xor preg_match($fileregexp, $filepath)) {
47 call_user_func($callback, $filepath);
48 }
49 }
50}
51
52/**
53 * An expectation for comparing strings ignoring whitespace.
54 */
55class IgnoreWhitespaceExpectation extends SimpleExpectation {
56 var $expect;
57
58 function IgnoreWhitespaceExpectation($content, $message = '%s') {
59 $this->SimpleExpectation($message);
60 $this->expect=$this->normalise($content);
61 }
62
63 function test($ip) {
64 return $this->normalise($ip)==$this->expect;
65 }
66
67 function normalise($text) {
68 return preg_replace('/\s+/m',' ',trim($text));
69 }
70
71 function testMessage($ip) {
72 return "Input string [$ip] doesn't match the required value.";
73 }
74}
75
76/**
77 * An Expectation that two arrays contain the same list of values.
78 */
79class ArraysHaveSameValuesExpectation extends SimpleExpectation {
80 var $expect;
81
82 function ArraysHaveSameValuesExpectation($expected, $message = '%s') {
83 $this->SimpleExpectation($message);
84 if (!is_array($expected)) {
85 trigger_error('Attempt to create an ArraysHaveSameValuesExpectation ' .
86 'with an expected value that is not an array.');
87 }
88 $this->expect = $this->normalise($expected);
89 }
90
91 function test($actual) {
92 return $this->normalise($actual) == $this->expect;
93 }
94
95 function normalise($array) {
96 sort($array);
97 return $array;
98 }
99
100 function testMessage($actual) {
101 return 'Array [' . implode(', ', $actual) .
102 '] does not contain the expected list of values [' . implode(', ', $this->expect) . '].';
103 }
104}
105
106/**
107 * An Expectation that compares to objects, and ensures that for every field in the
108 * expected object, there is a key of the same name in the actual object, with
109 * the same value. (The actual object may have other fields to, but we ignore them.)
110 */
111class CheckSpecifiedFieldsExpectation extends SimpleExpectation {
112 var $expect;
113
114 function CheckSpecifiedFieldsExpectation($expected, $message = '%s') {
115 $this->SimpleExpectation($message);
116 if (!is_object($expected)) {
117 trigger_error('Attempt to create a CheckSpecifiedFieldsExpectation ' .
118 'with an expected value that is not an object.');
119 }
120 $this->expect = $expected;
121 }
122
123 function test($actual) {
124 foreach ($this->expect as $key => $value) {
125 if (isset($value) && isset($actual->$key) && $actual->$key == $value) {
126 // OK
127 } else if (is_null($value) && is_null($actual->$key)) {
128 // OK
129 } else {
130 return false;
131 }
132 }
133 return true;
134 }
135
136 function testMessage($actual) {
137 $mismatches = array();
138 foreach ($this->expect as $key => $value) {
139 if (isset($value) && isset($actual->$key) && $actual->$key == $value) {
140 // OK
141 } else if (is_null($value) && is_null($actual->$key)) {
142 // OK
143 } else {
144 $mismatches[] = $key;
145 }
146 }
147 return 'Actual object does not have all the same fields with the same values as the expected object (' .
148 implode(', ', $mismatches) . ').';
149 }
150}
151
b9c639d6 152class MoodleUnitTestCase extends UnitTestCase {
356e0010 153 public $tables = array();
90997d6d 154 public $pkfile;
155 public $cfg;
356e0010 156
90997d6d 157 /**
158 * In the constructor, record the max(id) of each test table into a csv file.
159 * If this file already exists, it means that a previous run of unit tests
160 * did not complete, and has left data undeleted in the DB. This data is then
161 * deleted and the file is retained. Otherwise it is created.
162 * @throws moodle_exception if CSV file cannot be created
163 */
b9c639d6 164 public function __construct($label = false) {
165 parent::UnitTestCase($label);
356e0010 166
90997d6d 167 // MDL-16483 Get PKs and save data to text file
168 global $DB, $CFG;
169 $this->pkfile = $CFG->dataroot.'/testtablespks.csv';
170 $this->cfg = $CFG;
cb352449 171 $this->setup();
90997d6d 172
173 $tables = $DB->get_tables();
174
175 // The file exists, so use it to truncate tables (tests aborted before test data could be removed)
176 if (file_exists($this->pkfile)) {
177 $this->truncate_test_tables($this->get_table_data($this->pkfile));
178
179 } else { // Create the file
180 $tabledata = '';
181
182 foreach ($tables as $table) {
183 if ($table != 'sessions2') {
184 if (!$max_id = $DB->get_field_sql("SELECT MAX(id) FROM {$CFG->unittestprefix}{$table}")) {
185 $max_id = 0;
186 }
187 $tabledata .= "$table, $max_id\n";
188 }
189 }
190 if (!file_put_contents($this->pkfile, $tabledata)) {
5d1381c2 191 $a = new stdClass();
192 $a->filename = $this->pkfile;
193 throw new moodle_exception('testtablescsvfileunwritable', 'simpletest', '', $a);
90997d6d 194 }
195 }
196 }
197
198 /**
199 * 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.
200 * @param array $tabledata
201 */
202 private function truncate_test_tables($tabledata) {
203 global $CFG, $DB;
204
205 $tables = $DB->get_tables();
206
207 foreach ($tables as $table) {
208 if ($table != 'sessions2' && isset($tabledata[$table])) {
5d1381c2 209 // $DB->delete_records_select($table, "id > ?", array($tabledata[$table]));
90997d6d 210 }
211 }
356e0010 212 }
213
90997d6d 214 /**
215 * Given a filename, opens it and parses the csv contained therein. It expects two fields per line:
216 * 1. Table name
217 * 2. Max id
218 * @param string $filename
219 * @throws moodle_exception if file doesn't exist
220 */
221 public function get_table_data($filename) {
222 if (file_exists($this->pkfile)) {
223 $handle = fopen($this->pkfile, 'r');
224 $tabledata = array();
225
226 while (($data = fgetcsv($handle, 1000, ",")) !== false) {
227 $tabledata[$data[0]] = $data[1];
228 }
229 return $tabledata;
230 } else {
5d1381c2 231 $a = new stdClass();
232 $a->filename = $this->pkfile;
233 debug_print_backtrace();
234 throw new moodle_exception('testtablescsvfilemissing', 'simpletest', '', $a);
90997d6d 235 return false;
236 }
237 }
238
239 /**
240 * Method called before each test method. Replaces the real $DB with the one configured for unit tests (different prefix, $CFG->unittestprefix).
241 * Also detects if this config setting is properly set, and if the user table exists.
242 * TODO Improve detection of incorrectly built DB test tables (e.g. detect version discrepancy and offer to upgrade/rebuild)
243 */
356e0010 244 public function setUp() {
356e0010 245 parent::setUp();
5d1381c2 246 UnitTestDB::instantiate();
247 }
248
249 /**
250 * Method called after each test method. Doesn't do anything extraordinary except restore the global $DB to the real one.
251 */
252 public function tearDown() {
253 global $DB;
254 $DB->cleanup();
255 parent::tearDown();
256 }
257
258 /**
259 * 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
260 * It should also detect if data is missing from the original tables.
261 */
262 public function __destruct() {
263 global $CFG, $DB;
264
265 $CFG = $this->cfg;
266 $this->tearDown();
267 UnitTestDB::restore();
268 fulldelete($this->pkfile);
269 }
270}
271
272/**
273 * This is a Database Engine proxy class: It replaces the global object $DB with itself through a call to the
274 * static instantiate() method, and restores the original global $DB through restore().
275 * Internally, it routes all calls to $DB to a real instance of the database engine (aggregated as a member variable),
276 * except those that are defined in this proxy class. This makes it possible to add extra code to the database engine
277 * without subclassing it.
278 */
279class UnitTestDB {
280 public static $DB;
281 private static $real_db;
356e0010 282
5d1381c2 283 public $table_data = array();
284
285 public function __construct() {
286
287 }
288
289 /**
290 * Call this statically to connect to the DB using the unittest prefix, instantiate
291 * the unit test db, store it as a member variable, instantiate $this and use it as the new global $DB.
292 */
293 public static function instantiate() {
294 global $CFG, $DB;
295 UnitTestDB::$real_db = clone($DB);
b9c639d6 296
90997d6d 297 if (empty($CFG->unittestprefix)) {
b9c639d6 298 print_error("prefixnotset", 'simpletest');
299 }
300
5d1381c2 301 UnitTestDB::$DB = moodle_database::get_driver_instance($CFG->dbtype, $CFG->dblibrary);
302 UnitTestDB::$DB->connect($CFG->dbhost, $CFG->dbuser, $CFG->dbpass, $CFG->dbname, $CFG->dbpersist, $CFG->unittestprefix);
303 $manager = UnitTestDB::$DB->get_manager();
356e0010 304
305 if (!$manager->table_exists('user')) {
b9c639d6 306 print_error('tablesnotsetup', 'simpletest');
307 }
5d1381c2 308
309 $DB = new UnitTestDB();
310 }
311
312 public function __call($method, $args) {
313 // Set args to null if they don't exist (up to 10 args should do)
314 if (!method_exists($this, $method)) {
315 return call_user_func_array(array(UnitTestDB::$DB, $method), $args);
316 } else {
317 call_user_func_array(array($this, $method), $args);
318 }
319 }
320
321 public function __get($variable) {
322 return UnitTestDB::$DB->$variable;
323 }
324
325 public function __set($variable, $value) {
326 UnitTestDB::$DB->$variable = $value;
327 }
328
329 public function __isset($variable) {
330 return isset(UnitTestDB::$DB->$variable);
331 }
332
333 public function __unset($variable) {
334 unset(UnitTestDB::$DB->$variable);
b9c639d6 335 }
336
90997d6d 337 /**
5d1381c2 338 * Overriding insert_record to keep track of the ids inserted during unit tests, so that they can be deleted afterwards
90997d6d 339 */
5d1381c2 340 public function insert_record($table, $dataobject, $returnid=true, $bulk=false) {
356e0010 341 global $DB;
5d1381c2 342 $id = UnitTestDB::$DB->insert_record($table, $dataobject, $returnid, $bulk);
343 $this->table_data[$table][] = $id;
344 return $id;
345 }
356e0010 346
5d1381c2 347 /**
348 * Overriding update_record: If we are updating a record that was NOT inserted by unit tests,
349 * throw an exception and cancel update.
350 * @throws moodle_exception If trying to update a record not inserted by unit tests.
351 */
352 public function update_record($table, $dataobject, $bulk=false) {
353 global $DB;
354 if (empty($this->table_data[$table]) || !in_array($dataobject->id, $this->table_data[$table])) {
355 return UnitTestDB::$DB->update_record($table, $dataobject, $bulk);
356 // $a = new stdClass();
357 // $a->id = $dataobject->id;
358 // $a->table = $table;
359 // debug_print_backtrace();
360 // throw new moodle_exception('updatingnoninsertedrecord', 'simpletest', '', $a);
361 } else {
362 return UnitTestDB::$DB->update_record($table, $dataobject, $bulk);
363 }
b9c639d6 364 }
365
366 /**
5d1381c2 367 * Overriding delete_record: If we are deleting a record that was NOT inserted by unit tests,
368 * throw an exception and cancel delete.
369 * @throws moodle_exception If trying to delete a record not inserted by unit tests.
b9c639d6 370 */
5d1381c2 371 public function delete_records($table, array $conditions=null) {
372 global $DB;
373 $a = new stdClass();
374 $a->table = $table;
375
376 // Get ids matching conditions
377 if (!$ids_to_delete = $DB->get_field($table, 'id', $conditions)) {
378 return UnitTestDB::$DB->delete_records($table, $conditions);
379 }
380
381 $proceed_with_delete = true;
382
383 if (!is_array($ids_to_delete)) {
384 $ids_to_delete = array($ids_to_delete);
385 }
386
387 foreach ($ids_to_delete as $id) {
388 if (!in_array($id, $this->table_data[$table])) {
389 $proceed_with_delete = false;
390 $a->id = $id;
391 break;
392 }
393 }
394
395 if ($proceed_with_delete) {
396 return UnitTestDB::$DB->delete_records($table, $conditions);
397 } else {
398 debug_print_backtrace();
399 throw new moodle_exception('deletingnoninsertedrecord', 'simpletest', '', $a);
400 }
b9c639d6 401 }
b9c639d6 402
5d1381c2 403 /**
404 * Overriding delete_records_select: If we are deleting a record that was NOT inserted by unit tests,
405 * throw an exception and cancel delete.
406 * @throws moodle_exception If trying to delete a record not inserted by unit tests.
407 */
408 public function delete_records_select($table, $select, array $params=null) {
409 global $DB;
410 $a = new stdClass();
411 $a->table = $table;
412
413 // Get ids matching conditions
414 if (!$ids_to_delete = $DB->get_field_select($table, 'id', $select, $params)) {
415 return UnitTestDB::$DB->delete_records_select($table, $select, $params);
416 }
417
418 $proceed_with_delete = true;
419
420 foreach ($ids_to_delete as $id) {
421 if (!in_array($id, $this->table_data[$table])) {
422 $proceed_with_delete = false;
423 $a->id = $id;
424 break;
425 }
426 }
427
428 if ($proceed_with_delete) {
429 return UnitTestDB::$DB->delete_records_select($table, $select, $params);
430 } else {
431 debug_print_backtrace();
432 throw new moodle_exception('deletingnoninsertedrecord', 'simpletest', '', $a);
433 }
434 }
435
436 /**
437 * Removes from the test DB all the records that were inserted during unit tests,
438 */
439 public function cleanup() {
440 global $DB;
441 foreach ($this->table_data as $table => $ids) {
442 foreach ($ids as $id) {
443 $DB->delete_records($table, array('id' => $id));
444 }
445 }
446 }
447
448 /**
449 * Restores the global $DB object.
450 */
451 public static function restore() {
452 global $DB;
453 $DB = UnitTestDB::$real_db;
454 }
455
456 public function get_field($table, $return, array $conditions) {
457 if (!is_array($conditions)) {
458 debug_print_backtrace();
459 }
460 return UnitTestDB::$DB->get_field($table, $return, $conditions);
461 }
462}
bb48a537 463?>