3 * Utility functions to make unit testing easier.
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 © 2006 The Open University
10 * @author T.J.Hunt@open.ac.uk
11 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
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');
20 require_once($CFG->libdir
. '/simpletestlib/reporter.php');
21 require_once($CFG->libdir
. '/simpletestlib/web_tester.php');
24 * Recursively visit all the files in the source tree. Calls the callback
25 * function with the pathname of each file found.
27 * @param $path the folder to start searching from.
28 * @param $callback the function to call with the name of each file found.
29 * @param $fileregexp a regexp used to filter the search (optional).
30 * @param $exclude If true, pathnames that match the regexp will be ingored. If false,
31 * only files that match the regexp will be included. (default false).
32 * @param array $ignorefolders will not go into any of these folders (optional).
34 function recurseFolders($path, $callback, $fileregexp = '/.*/', $exclude = false, $ignorefolders = array()) {
35 $files = scandir($path);
37 foreach ($files as $file) {
38 $filepath = $path .'/'. $file;
39 if ($file == '.' ||
$file == '..') {
41 } else if (is_dir($filepath)) {
42 if (!in_array($filepath, $ignorefolders)) {
43 recurseFolders($filepath, $callback, $fileregexp, $exclude, $ignorefolders);
45 } else if ($exclude xor preg_match($fileregexp, $filepath)) {
46 call_user_func($callback, $filepath);
52 * An expectation for comparing strings ignoring whitespace.
54 class IgnoreWhitespaceExpectation
extends SimpleExpectation
{
57 function IgnoreWhitespaceExpectation($content, $message = '%s') {
58 $this->SimpleExpectation($message);
59 $this->expect
=$this->normalise($content);
63 return $this->normalise($ip)==$this->expect
;
66 function normalise($text) {
67 return preg_replace('/\s+/m',' ',trim($text));
70 function testMessage($ip) {
71 return "Input string [$ip] doesn't match the required value.";
76 * An Expectation that two arrays contain the same list of values.
78 class ArraysHaveSameValuesExpectation
extends SimpleExpectation
{
81 function ArraysHaveSameValuesExpectation($expected, $message = '%s') {
82 $this->SimpleExpectation($message);
83 if (!is_array($expected)) {
84 trigger_error('Attempt to create an ArraysHaveSameValuesExpectation ' .
85 'with an expected value that is not an array.');
87 $this->expect
= $this->normalise($expected);
90 function test($actual) {
91 return $this->normalise($actual) == $this->expect
;
94 function normalise($array) {
99 function testMessage($actual) {
100 return 'Array [' . implode(', ', $actual) .
101 '] does not contain the expected list of values [' . implode(', ', $this->expect
) . '].';
106 * An Expectation that compares to objects, and ensures that for every field in the
107 * expected object, there is a key of the same name in the actual object, with
108 * the same value. (The actual object may have other fields to, but we ignore them.)
110 class CheckSpecifiedFieldsExpectation
extends SimpleExpectation
{
113 function CheckSpecifiedFieldsExpectation($expected, $message = '%s') {
114 $this->SimpleExpectation($message);
115 if (!is_object($expected)) {
116 trigger_error('Attempt to create a CheckSpecifiedFieldsExpectation ' .
117 'with an expected value that is not an object.');
119 $this->expect
= $expected;
122 function test($actual) {
123 foreach ($this->expect
as $key => $value) {
124 if (isset($value) && isset($actual->$key) && $actual->$key == $value) {
126 } else if (is_null($value) && is_null($actual->$key)) {
135 function testMessage($actual) {
136 $mismatches = array();
137 foreach ($this->expect
as $key => $value) {
138 if (isset($value) && isset($actual->$key) && $actual->$key == $value) {
140 } else if (is_null($value) && is_null($actual->$key)) {
143 $mismatches[] = $key;
146 return 'Actual object does not have all the same fields with the same values as the expected object (' .
147 implode(', ', $mismatches) . ').';
152 * Given a table name, a two-dimensional array of data, and a database connection,
153 * creates a table in the database. The array of data should look something like this.
156 * array('id', 'username', 'firstname', 'lastname', 'email'),
157 * array(1, 'u1', 'user', 'one', 'u1@example.com'),
158 * array(2, 'u2', 'user', 'two', 'u2@example.com'),
159 * array(3, 'u3', 'user', 'three', 'u3@example.com'),
160 * array(4, 'u4', 'user', 'four', 'u4@example.com'),
161 * array(5, 'u5', 'user', 'five', 'u5@example.com'),
164 * The first 'row' of the test data gives the column names. The type of each column
165 * is set to either INT or VARCHAR($strlen), guessed by inspecting the first row of
166 * data. Unless the col name is 'id' in which case the col type will be SERIAL.
167 * The remaining 'rows' of the data array are values loaded into the table. All columns
168 * are created with a default of 0xdefa or 'Default' as appropriate.
170 * This function should not be used in real code. Only for testing and debugging.
172 * @param string $tablename the name of the table to create. E.g. 'mdl_unittest_user'.
173 * @param array $data a two-dimensional array of data, in the format described above.
174 * @param object $db an AdoDB database connection.
175 * @param int $strlen the width to use for string fields.
177 function load_test_table($tablename, $data, $db = null, $strlen = 255) {
178 $colnames = array_shift($data);
180 foreach (array_combine($colnames, $data[0]) as $colname => $value) {
181 if ($colname == 'id') {
183 } else if (is_int($value)) {
184 $type = 'INTEGER DEFAULT 57082'; // 0xdefa
186 $type = "VARCHAR($strlen) DEFAULT 'Default'";
188 $coldefs[] = "$colname $type";
190 _private_execute_sql("CREATE TABLE $tablename (" . join(',', $coldefs) . ');', $db);
192 array_unshift($data, $colnames);
193 load_test_data($tablename, $data, $db);
197 * Given a table name, a two-dimensional array of data, and a database connection,
198 * adds data to the database table. The array should have the same format as for
199 * load_test_table(), with the first 'row' giving column names.
201 * This function should not be used in real code. Only for testing and debugging.
203 * @param string $tablename the name of the table to populate. E.g. 'mdl_unittest_user'.
204 * @param array $data a two-dimensional array of data, in the format described.
205 * @param object $localdb an AdoDB database connection.
207 function load_test_data($tablename, $data, $localdb = null) {
210 if (null == $localdb) {
214 $colnames = array_shift($data);
215 $idcol = array_search('id', $colnames);
217 foreach ($data as $row) {
218 _private_execute_sql($localdb->GetInsertSQL($tablename, array_combine($colnames, $row)), $localdb);
219 if ($idcol !== false && $row[$idcol] > $maxid) {
220 $maxid = $row[$idcol];
223 if ($CFG->dbfamily
== 'postgres' && $idcol !== false) {
225 _private_execute_sql("ALTER SEQUENCE {$tablename}_id_seq RESTART WITH $maxid;", $localdb);
230 * Make multiple tables that are the same as a real table but empty.
232 * This function should not be used in real code. Only for testing and debugging.
234 * @param mixed $tablename Array of strings containing the names of the table to populate (without prefix).
235 * @param string $realprefix the prefix used for real tables. E.g. 'mdl_'.
236 * @param string $testprefix the prefix used for test tables. E.g. 'mdl_unittest_'.
237 * @param object $db an AdoDB database connection.
239 function make_test_tables_like_real_one($tablenames, $realprefix, $testprefix, $db,$dropconstraints=false) {
240 foreach($tablenames as $individual) {
241 make_test_table_like_real_one($individual,$realprefix,$testprefix,$db,$dropconstraints);
246 * Make a test table that has all the same columns as a real moodle table,
247 * but which is empty.
249 * This function should not be used in real code. Only for testing and debugging.
251 * @param string $tablename Name of the table to populate. E.g. 'user'.
252 * @param string $realprefix the prefix used for real tables. E.g. 'mdl_'.
253 * @param string $testprefix the prefix used for test tables. E.g. 'mdl_unittest_'.
254 * @param object $db an AdoDB database connection.
256 function make_test_table_like_real_one($tablename, $realprefix, $testprefix, $db, $dropconstraints=false) {
257 _private_execute_sql("CREATE TABLE $testprefix$tablename (LIKE $realprefix$tablename INCLUDING DEFAULTS);", $db);
258 if (_private_has_id_column($testprefix . $tablename, $db)) {
259 _private_execute_sql("CREATE SEQUENCE $testprefix{$tablename}_id_seq;", $db);
260 _private_execute_sql("ALTER TABLE $testprefix$tablename ALTER COLUMN id SET DEFAULT nextval('{$testprefix}{$tablename}_id_seq'::regclass);", $db);
261 _private_execute_sql("ALTER TABLE $testprefix$tablename ADD PRIMARY KEY (id);", $db);
263 if($dropconstraints) {
264 $cols=$db->MetaColumnNames($testprefix.$tablename);
265 foreach($cols as $col) {
266 $rs=_private_execute_sql(
267 "SELECT constraint_name FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE table_name='$testprefix$tablename'",$db);
269 $constraintname=$rs->fields
['constraint_name'];
270 _private_execute_sql("ALTER TABLE $testprefix$tablename DROP CONSTRAINT $constraintname",$db);
274 _private_execute_sql("ALTER TABLE $testprefix$tablename ALTER COLUMN $col DROP NOT NULL",$db);
280 * Drops a table from the database pointed to by the database connection.
281 * This undoes the create performed by load_test_table().
283 * This function should not be used in real code. Only for testing and debugging.
285 * @param string $tablename the name of the table to populate. E.g. 'mdl_unittest_user'.
286 * @param object $db an AdoDB database connection.
287 * @param bool $cascade If true, also drop tables that depend on this one, e.g. through
288 * foreign key constraints.
290 function remove_test_table($tablename, $db, $cascade = false) {
292 _private_execute_sql('DROP TABLE ' . $tablename . ($cascade ?
' CASCADE' : '') . ';', $db);
294 if ($CFG->dbfamily
== 'postgres') {
295 $rs = $db->Execute("SELECT relname FROM pg_class WHERE relname = '{$tablename}_id_seq' AND relkind = 'S';");
296 if ($rs && $rs->RecordCount()) {
297 _private_execute_sql("DROP SEQUENCE {$tablename}_id_seq;", $db);
303 * Drops all the tables with a particular prefix from the database pointed to by the database connection.
304 * Useful for cleaning up after a unit test run has crashed leaving the DB full of junk.
306 * This function should not be used in real code. Only for testing and debugging.
308 * @param string $prefix the prfix of tables to drop 'mdl_unittest_'.
309 * @param object $db an AdoDB database connection.
311 function wipe_tables($prefix, $db) {
312 if (strpos($prefix, 'test') === false) {
313 notice('The wipe_tables function should only be used to wipe test tables.');
316 $tables = $db->Metatables('TABLES', false, "$prefix%");
317 foreach ($tables as $table) {
318 _private_execute_sql("DROP TABLE $table CASCADE", $db);
323 * Drops all the sequences with a particular prefix from the database pointed to by the database connection.
324 * Useful for cleaning up after a unit test run has crashed leaving the DB full of junk.
326 * This function should not be used in real code. Only for testing and debugging.
328 * @param string $prefix the prfix of sequences to drop 'mdl_unittest_'.
329 * @param object $db an AdoDB database connection.
331 function wipe_sequences($prefix, $db) {
334 if ($CFG->dbfamily
== 'postgres') {
335 $sequences = $db->GetCol("SELECT relname FROM pg_class WHERE relname LIKE '$prefix%_id_seq' AND relkind = 'S';");
337 foreach ($sequences as $sequence) {
338 _private_execute_sql("DROP SEQUENCE $sequence CASCADE", $db);
344 function _private_has_id_column($table, $db) {
345 return in_array('id', $db->MetaColumnNames($table));
348 function _private_execute_sql($sql, $localdb = null) {
350 if (null == $localdb) {
354 if (!$rs = $localdb->Execute($sql)) {
355 echo '<p>SQL ERROR: ', $localdb->ErrorMsg(), ". STATEMENT: $sql</p>";
361 * Base class for testcases that want a different DB prefix.
363 * That is, when you need to load test data into the database for
364 * unit testing, instead of messing with the real mdl_course table,
365 * we will temporarily change $CFG->prefix from (say) mdl_ to mdl_unittest_
366 * and create a table called mdl_unittest_course to hold the test data.
368 class prefix_changing_test_case
extends UnitTestCase
{
371 function change_prefix() {
373 $this->old_prefix
= $CFG->prefix
;
374 $CFG->prefix
= $CFG->prefix
. 'unittest_';
377 function change_prefix_back() {
379 $CFG->prefix
= $this->old_prefix
;
383 $this->change_prefix();
386 function tearDown() {
387 $this->change_prefix_back();