Added ability to specify destination category within GIFT file.
[moodle-linuxchix.git] / lib / simpletestlib.php
blobd6cdc509aa3cf27059fc7ad1daae498407fe2bf6
1 <?php
2 /**
3 * Utility functions to make unit testing easier.
4 *
5 * These functions, particularly the the database ones, are quick and
6 * dirty methods for getting things done in test cases. None of these
7 * methods should be used outside test code.
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
16 require_once(dirname(__FILE__) . '/../config.php');
17 require_once($CFG->libdir . '/simpletestlib/simpletest.php');
18 require_once($CFG->libdir . '/simpletestlib/unit_tester.php');
19 require_once($CFG->libdir . '/simpletestlib/expectation.php');
21 /**
22 * Recursively visit all the files in the source tree. Calls the callback
23 * function with the pathname of each file found.
25 * @param $path the folder to start searching from.
26 * @param $callback the function to call with the name of each file found.
27 * @param $fileregexp a regexp used to filter the search (optional).
28 * @param $exclude If true, pathnames that match the regexp will be ingored. If false,
29 * only files that match the regexp will be included. (default false).
30 * @param array $ignorefolders will not go into any of these folders (optional).
31 */
32 function recurseFolders($path, $callback, $fileregexp = '/.*/', $exclude = false, $ignorefolders = array()) {
33 $files = scandir($path);
35 foreach ($files as $file) {
36 $filepath = $path .'/'. $file;
37 if ($file == '.' || $file == '..') {
38 continue;
39 } else if (is_dir($filepath)) {
40 if (!in_array($filepath, $ignorefolders)) {
41 recurseFolders($filepath, $callback, $fileregexp, $exclude, $ignorefolders);
43 } else if ($exclude xor preg_match($fileregexp, $filepath)) {
44 call_user_func($callback, $filepath);
49 /**
50 * An expectation for comparing strings ignoring whitespace.
52 class IgnoreWhitespaceExpectation extends SimpleExpectation {
53 var $expect;
55 function IgnoreWhitespaceExpectation($content, $message = '%s') {
56 $this->SimpleExpectation($message);
57 $this->expect=$this->normalise($content);
60 function test($ip) {
61 return $this->normalise($ip)==$this->expect;
64 function normalise($text) {
65 return preg_replace('/\s+/m',' ',trim($text));
68 function testMessage($ip) {
69 return "Input string [$ip] doesn't match the required value.";
73 /**
74 * An Expectation that two arrays contain the same list of values.
76 class ArraysHaveSameValuesExpectation extends SimpleExpectation {
77 var $expect;
79 function ArraysHaveSameValuesExpectation($expected, $message = '%s') {
80 $this->SimpleExpectation($message);
81 if (!is_array($expected)) {
82 trigger_error('Attempt to create an ArraysHaveSameValuesExpectation ' .
83 'with an expected value that is not an array.');
85 $this->expect = $this->normalise($expected);
88 function test($actual) {
89 return $this->normalise($actual) == $this->expect;
92 function normalise($array) {
93 sort($array);
94 return $array;
97 function testMessage($actual) {
98 return 'Array [' . implode(', ', $actual) .
99 '] does not contain the expected list of values [' . implode(', ', $this->expect) . '].';
104 * An Expectation that compares to objects, and ensures that for every field in the
105 * expected object, there is a key of the same name in the actual object, with
106 * the same value. (The actual object may have other fields to, but we ignore them.)
108 class CheckSpecifiedFieldsExpectation extends SimpleExpectation {
109 var $expect;
111 function CheckSpecifiedFieldsExpectation($expected, $message = '%s') {
112 $this->SimpleExpectation($message);
113 if (!is_object($expected)) {
114 trigger_error('Attempt to create a CheckSpecifiedFieldsExpectation ' .
115 'with an expected value that is not an object.');
117 $this->expect = $expected;
120 function test($actual) {
121 foreach ($this->expect as $key => $value) {
122 if (isset($value) && isset($actual->$key) && $actual->$key == $value) {
123 // OK
124 } else if (is_null($value) && is_null($actual->$key)) {
125 // OK
126 } else {
127 return false;
130 return true;
133 function testMessage($actual) {
134 $mismatches = array();
135 foreach ($this->expect as $key => $value) {
136 if (isset($value) && isset($actual->$key) && $actual->$key == $value) {
137 // OK
138 } else if (is_null($value) && is_null($actual->$key)) {
139 // OK
140 } else {
141 $mismatches[] = $key;
144 return 'Actual object does not have all the same fields with the same values as the expected object (' .
145 implode(', ', $mismatches) . ').';
150 * Given a table name, a two-dimensional array of data, and a database connection,
151 * creates a table in the database. The array of data should look something like this.
153 * $testdata = array(
154 * array('id', 'username', 'firstname', 'lastname', 'email'),
155 * array(1, 'u1', 'user', 'one', 'u1@example.com'),
156 * array(2, 'u2', 'user', 'two', 'u2@example.com'),
157 * array(3, 'u3', 'user', 'three', 'u3@example.com'),
158 * array(4, 'u4', 'user', 'four', 'u4@example.com'),
159 * array(5, 'u5', 'user', 'five', 'u5@example.com'),
160 * );
162 * The first 'row' of the test data gives the column names. The type of each column
163 * is set to either INT or VARCHAR($strlen), guessed by inspecting the first row of
164 * data. Unless the col name is 'id' in which case the col type will be SERIAL.
165 * The remaining 'rows' of the data array are values loaded into the table. All columns
166 * are created with a default of 0xdefa or 'Default' as appropriate.
168 * This function should not be used in real code. Only for testing and debugging.
170 * @param string $tablename the name of the table to create. E.g. 'mdl_unittest_user'.
171 * @param array $data a two-dimensional array of data, in the format described above.
172 * @param object $db an AdoDB database connection.
173 * @param int $strlen the width to use for string fields.
175 function load_test_table($tablename, $data, $db = null, $strlen = 255) {
176 $colnames = array_shift($data);
177 $coldefs = array();
178 foreach (array_combine($colnames, $data[0]) as $colname => $value) {
179 if ($colname == 'id') {
180 $type = 'SERIAL';
181 } else if (is_int($value)) {
182 $type = 'INTEGER DEFAULT 57082'; // 0xdefa
183 } else {
184 $type = "VARCHAR($strlen) DEFAULT 'Default'";
186 $coldefs[] = "$colname $type";
188 _private_execute_sql("CREATE TABLE $tablename (" . join(',', $coldefs) . ');', $db);
190 array_unshift($data, $colnames);
191 load_test_data($tablename, $data, $db);
195 * Given a table name, a two-dimensional array of data, and a database connection,
196 * adds data to the database table. The array should have the same format as for
197 * load_test_table(), with the first 'row' giving column names.
199 * This function should not be used in real code. Only for testing and debugging.
201 * @param string $tablename the name of the table to populate. E.g. 'mdl_unittest_user'.
202 * @param array $data a two-dimensional array of data, in the format described.
203 * @param object $localdb an AdoDB database connection.
205 function load_test_data($tablename, $data, $localdb = null) {
206 global $CFG;
208 if (null == $localdb) {
209 global $db;
210 $localdb = $db;
212 $colnames = array_shift($data);
213 $idcol = array_search('id', $colnames);
214 $maxid = -1;
215 foreach ($data as $row) {
216 _private_execute_sql($localdb->GetInsertSQL($tablename, array_combine($colnames, $row)), $localdb);
217 if ($idcol !== false && $row[$idcol] > $maxid) {
218 $maxid = $row[$idcol];
221 if ($CFG->dbtype == 'postgres7' && $idcol !== false) {
222 $maxid += 1;
223 _private_execute_sql("ALTER SEQUENCE {$tablename}_id_seq RESTART WITH $maxid;", $localdb);
228 * Make multiple tables that are the same as a real table but empty.
230 * This function should not be used in real code. Only for testing and debugging.
232 * @param mixed $tablename Array of strings containing the names of the table to populate (without prefix).
233 * @param string $realprefix the prefix used for real tables. E.g. 'mdl_'.
234 * @param string $testprefix the prefix used for test tables. E.g. 'mdl_unittest_'.
235 * @param object $db an AdoDB database connection.
237 function make_test_tables_like_real_one($tablenames, $realprefix, $testprefix, $db,$dropconstraints=false) {
238 foreach($tablenames as $individual) {
239 make_test_table_like_real_one($individual,$realprefix,$testprefix,$db,$dropconstraints);
244 * Make a test table that has all the same columns as a real moodle table,
245 * but which is empty.
247 * This function should not be used in real code. Only for testing and debugging.
249 * @param string $tablename Name of the table to populate. E.g. 'user'.
250 * @param string $realprefix the prefix used for real tables. E.g. 'mdl_'.
251 * @param string $testprefix the prefix used for test tables. E.g. 'mdl_unittest_'.
252 * @param object $db an AdoDB database connection.
254 function make_test_table_like_real_one($tablename, $realprefix, $testprefix, $db, $dropconstraints=false) {
255 _private_execute_sql("CREATE TABLE $testprefix$tablename (LIKE $realprefix$tablename INCLUDING DEFAULTS);", $db);
256 if (_private_has_id_column($testprefix . $tablename, $db)) {
257 _private_execute_sql("CREATE SEQUENCE $testprefix{$tablename}_id_seq;", $db);
258 _private_execute_sql("ALTER TABLE $testprefix$tablename ALTER COLUMN id SET DEFAULT nextval('{$testprefix}{$tablename}_id_seq'::regclass);", $db);
259 _private_execute_sql("ALTER TABLE $testprefix$tablename ADD PRIMARY KEY (id);", $db);
261 if($dropconstraints) {
262 $cols=$db->MetaColumnNames($testprefix.$tablename);
263 foreach($cols as $col) {
264 $rs=_private_execute_sql(
265 "SELECT constraint_name FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE table_name='$testprefix$tablename'",$db);
266 while(!$rs->EOF) {
267 $constraintname=$rs->fields['constraint_name'];
268 _private_execute_sql("ALTER TABLE $testprefix$tablename DROP CONSTRAINT $constraintname",$db);
269 $rs->MoveNext();
272 _private_execute_sql("ALTER TABLE $testprefix$tablename ALTER COLUMN $col DROP NOT NULL",$db);
278 * Drops a table from the database pointed to by the database connection.
279 * This undoes the create performed by load_test_table().
281 * This function should not be used in real code. Only for testing and debugging.
283 * @param string $tablename the name of the table to populate. E.g. 'mdl_unittest_user'.
284 * @param object $db an AdoDB database connection.
285 * @param bool $cascade If true, also drop tables that depend on this one, e.g. through
286 * foreign key constraints.
288 function remove_test_table($tablename, $db, $cascade = false) {
289 global $CFG;
290 _private_execute_sql('DROP TABLE ' . $tablename . ($cascade ? ' CASCADE' : '') . ';', $db);
292 if ($CFG->dbtype == 'postgres7') {
293 $rs = $db->Execute("SELECT relname FROM pg_class WHERE relname = '{$tablename}_id_seq' AND relkind = 'S';");
294 if ($rs && $rs->RecordCount()) {
295 _private_execute_sql("DROP SEQUENCE {$tablename}_id_seq;", $db);
301 * Drops all the tables with a particular prefix from the database pointed to by the database connection.
302 * Useful for cleaning up after a unit test run has crashed leaving the DB full of junk.
304 * This function should not be used in real code. Only for testing and debugging.
306 * @param string $prefix the prfix of tables to drop 'mdl_unittest_'.
307 * @param object $db an AdoDB database connection.
309 function wipe_tables($prefix, $db) {
310 if (strpos($prefix, 'test') === false) {
311 notice('The wipe_tables function should only be used to wipe test tables.');
312 return;
314 $tables = $db->Metatables('TABLES', false, "$prefix%");
315 foreach ($tables as $table) {
316 _private_execute_sql("DROP TABLE $table CASCADE", $db);
321 * Drops all the sequences with a particular prefix from the database pointed to by the database connection.
322 * Useful for cleaning up after a unit test run has crashed leaving the DB full of junk.
324 * This function should not be used in real code. Only for testing and debugging.
326 * @param string $prefix the prfix of sequences to drop 'mdl_unittest_'.
327 * @param object $db an AdoDB database connection.
329 function wipe_sequences($prefix, $db) {
330 global $CFG;
332 if ($CFG->dbtype == 'postgres7') {
333 $sequences = $db->GetCol("SELECT relname FROM pg_class WHERE relname LIKE '$prefix%_id_seq' AND relkind = 'S';");
334 if ($sequences) {
335 foreach ($sequences as $sequence) {
336 _private_execute_sql("DROP SEQUENCE $sequence CASCADE", $db);
342 function _private_has_id_column($table, $db) {
343 return in_array('id', $db->MetaColumnNames($table));
346 function _private_execute_sql($sql, $localdb = null) {
348 if (null == $localdb) {
349 global $db;
350 $localdb = $db;
352 if (!$rs = $localdb->Execute($sql)) {
353 echo '<p>SQL ERROR: ', $localdb->ErrorMsg(), ". STATEMENT: $sql</p>";
355 return $rs;
359 * Base class for testcases that want a different DB prefix.
361 * That is, when you need to load test data into the database for
362 * unit testing, instead of messing with the real mdl_course table,
363 * we will temporarily change $CFG->prefix from (say) mdl_ to mdl_unittest_
364 * and create a table called mdl_unittest_course to hold the test data.
366 class prefix_changing_test_case extends UnitTestCase {
367 var $old_prefix;
369 function change_prefix() {
370 global $CFG;
371 $this->old_prefix = $CFG->prefix;
372 $CFG->prefix = $CFG->prefix . 'unittest_';
375 function change_prefix_back() {
376 global $CFG;
377 $CFG->prefix = $this->old_prefix;
380 function setUp() {
381 $this->change_prefix();
384 function tearDown() {
385 $this->change_prefix_back();