weekly release 2.3dev
[moodle.git] / lib / phpunit / lib.php
CommitLineData
5bd40408
PS
1<?php
2// This file is part of Moodle - http://moodle.org/
3//
4// Moodle is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// Moodle is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
16
17/**
18 * Various PHPUnit classes and functions
19 *
7aea08e1 20 * @package core
5bd40408
PS
21 * @category phpunit
22 * @copyright 2012 Petr Skoda {@link http://skodak.org}
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 */
25
7aea08e1 26require_once 'PHPUnit/Autoload.php';
e396e8ed 27require_once 'PHPUnit/Extensions/Database/Autoload.php';
5bd40408
PS
28
29
30/**
31 * Collection of utility methods.
32 *
7aea08e1
SH
33 * @package core
34 * @category phpunit
5bd40408
PS
35 * @copyright 2012 Petr Skoda {@link http://skodak.org}
36 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
37 */
38class phpunit_util {
589376d3
PS
39 /** @var string current version hash from php files */
40 protected static $versionhash = null;
41
42 /** @var array original content of all database tables*/
5bd40408
PS
43 protected static $tabledata = null;
44
589376d3 45 /** @var array original structure of all database tables */
0b9251e3
PS
46 protected static $tablestructure = null;
47
589376d3 48 /** @var array An array of original globals, restored after each test */
5bd40408
PS
49 protected static $globals = array();
50
589376d3 51 /** @var int last value of db writes counter, used for db resetting */
50be93d1 52 public static $lastdbwrites = null;
a3d5830a 53
589376d3 54 /** @var phpunit_data_generator */
a3d5830a
PS
55 protected static $generator = null;
56
589376d3 57 /** @var resource used for prevention of parallel test execution */
4be2ad36
PS
58 protected static $lockhandle = null;
59
60 /**
920f4efe 61 * Prevent parallel test execution - this can not work in Moodle because we modify database and dataroot.
4be2ad36
PS
62 *
63 * Note: do not call manually!
64 *
920f4efe 65 * @internal
4be2ad36
PS
66 * @static
67 * @return void
68 */
69 public static function acquire_test_lock() {
70 global $CFG;
6c583c75
PS
71 if (!file_exists("$CFG->phpunit_dataroot/phpunit")) {
72 // dataroot not initialised yet
73 return;
74 }
4be2ad36
PS
75 if (!file_exists("$CFG->phpunit_dataroot/phpunit/lock")) {
76 file_put_contents("$CFG->phpunit_dataroot/phpunit/lock", 'This file prevents concurrent execution of Moodle PHPUnit tests');
77 phpunit_boostrap_fix_file_permissions("$CFG->phpunit_dataroot/phpunit/lock");
78 }
79 if (self::$lockhandle = fopen("$CFG->phpunit_dataroot/phpunit/lock", 'r')) {
80 $wouldblock = null;
81 $locked = flock(self::$lockhandle, (LOCK_EX | LOCK_NB), $wouldblock);
e3701541
PS
82 if (!$locked) {
83 if ($wouldblock) {
84 echo "Waiting for other test execution to complete...\n";
85 }
4be2ad36
PS
86 $locked = flock(self::$lockhandle, LOCK_EX);
87 }
88 if (!$locked) {
89 fclose(self::$lockhandle);
90 self::$lockhandle = null;
91 }
92 }
93 register_shutdown_function(array('phpunit_util', 'release_test_lock'));
94 }
95
96 /**
97 * Note: do not call manually!
920f4efe 98 * @internal
4be2ad36
PS
99 * @static
100 * @return void
101 */
102 public static function release_test_lock() {
103 if (self::$lockhandle) {
104 flock(self::$lockhandle, LOCK_UN);
105 fclose(self::$lockhandle);
106 self::$lockhandle = null;
107 }
108 }
109
589376d3
PS
110 /**
111 * Load global $CFG;
112 * @internal
113 * @static
114 * @return void
115 */
116 public static function initialise_cfg() {
117 global $DB;
118 $dbhash = false;
119 try {
120 $dbhash = $DB->get_field('config', 'value', array('name'=>'phpunittest'));
121 } catch (Exception $e) {
122 // not installed yet
123 initialise_cfg();
124 return;
125 }
126 if ($dbhash !== phpunit_util::get_version_hash()) {
127 // do not set CFG - the only way forward is to drop and reinstall
128 return;
129 }
130 // standard CFG init
131 initialise_cfg();
132 }
133
a3d5830a
PS
134 /**
135 * Get data generator
136 * @static
137 * @return phpunit_data_generator
138 */
139 public static function get_data_generator() {
140 if (is_null(self::$generator)) {
141 require_once(__DIR__.'/generatorlib.php');
142 self::$generator = new phpunit_data_generator();
143 }
144 return self::$generator;
145 }
146
5bd40408
PS
147 /**
148 * Returns contents of all tables right after installation.
149 * @static
150 * @return array $table=>$records
151 */
152 protected static function get_tabledata() {
153 global $CFG;
154
a3d5830a
PS
155 if (!file_exists("$CFG->dataroot/phpunit/tabledata.ser")) {
156 // not initialised yet
157 return array();
158 }
159
5bd40408
PS
160 if (!isset(self::$tabledata)) {
161 $data = file_get_contents("$CFG->dataroot/phpunit/tabledata.ser");
162 self::$tabledata = unserialize($data);
163 }
164
165 if (!is_array(self::$tabledata)) {
7b0ff213 166 phpunit_bootstrap_error(1, 'Can not read dataroot/phpunit/tabledata.ser or invalid format, reinitialize test database.');
5bd40408
PS
167 }
168
169 return self::$tabledata;
170 }
171
0b9251e3
PS
172 /**
173 * Returns structure of all tables right after installation.
174 * @static
175 * @return array $table=>$records
176 */
e396e8ed 177 public static function get_tablestructure() {
0b9251e3
PS
178 global $CFG;
179
180 if (!file_exists("$CFG->dataroot/phpunit/tablestructure.ser")) {
181 // not initialised yet
182 return array();
183 }
184
185 if (!isset(self::$tablestructure)) {
186 $data = file_get_contents("$CFG->dataroot/phpunit/tablestructure.ser");
187 self::$tablestructure = unserialize($data);
188 }
189
190 if (!is_array(self::$tablestructure)) {
191 phpunit_bootstrap_error(1, 'Can not read dataroot/phpunit/tablestructure.ser or invalid format, reinitialize test database.');
192 }
193
194 return self::$tablestructure;
195 }
196
e10736b3
PS
197 /**
198 * Returns list of tables that are unmodified and empty.
199 *
200 * @static
201 * @return array of table names, empty if unknown
202 */
203 protected static function guess_unmodified_empty_tables() {
204 global $DB;
205
206 $dbfamily = $DB->get_dbfamily();
207
208 if ($dbfamily === 'mysql') {
209 $empties = array();
210 $prefix = $DB->get_prefix();
211 $rs = $DB->get_recordset_sql("SHOW TABLE STATUS LIKE ?", array($prefix.'%'));
212 foreach ($rs as $info) {
213 $table = strtolower($info->name);
214 if (strpos($table, $prefix) !== 0) {
215 // incorrect table match caused by _
216 continue;
217 }
218 if (!is_null($info->auto_increment)) {
219 $table = preg_replace('/^'.preg_quote($prefix, '/').'/', '', $table);
220 if ($info->auto_increment == 1) {
221 $empties[$table] = $table;
222 }
223 }
224 }
225 $rs->close();
226 return $empties;
227
5a798e7e
PS
228 } else if ($dbfamily === 'mssql') {
229 $empties = array();
230 $prefix = $DB->get_prefix();
231 $sql = "SELECT t.name
232 FROM sys.identity_columns i
233 JOIN sys.tables t ON t.object_id = i.object_id
234 WHERE t.name LIKE ?
235 AND i.name = 'id'
236 AND i.last_value IS NULL";
237 $rs = $DB->get_recordset_sql($sql, array($prefix.'%'));
238 foreach ($rs as $info) {
239 $table = strtolower($info->name);
240 if (strpos($table, $prefix) !== 0) {
241 // incorrect table match caused by _
242 continue;
243 }
244 $table = preg_replace('/^'.preg_quote($prefix, '/').'/', '', $table);
245 $empties[$table] = $table;
246 }
247 $rs->close();
248 return $empties;
249
e10736b3
PS
250 } else {
251 return array();
252 }
253 }
254
8b5413cc 255 /**
ab483c0a
PS
256 * Reset all database sequences to initial values.
257 *
8b5413cc 258 * @static
e10736b3 259 * @param array $empties tables that are known to be unmodified and empty
8b5413cc
PS
260 * @return void
261 */
e10736b3 262 public static function reset_all_database_sequences(array $empties = null) {
8b5413cc
PS
263 global $DB;
264
8b5413cc
PS
265 if (!$data = self::get_tabledata()) {
266 // not initialised yet
ab483c0a 267 return;
8b5413cc
PS
268 }
269 if (!$structure = self::get_tablestructure()) {
270 // not initialised yet
ab483c0a 271 return;
8b5413cc
PS
272 }
273
274 $dbfamily = $DB->get_dbfamily();
275 if ($dbfamily === 'postgres') {
276 $queries = array();
277 $prefix = $DB->get_prefix();
278 foreach ($data as $table=>$records) {
ab483c0a 279 if (isset($structure[$table]['id']) and $structure[$table]['id']->auto_increment) {
8b5413cc
PS
280 if (empty($records)) {
281 $nextid = 1;
282 } else {
283 $lastrecord = end($records);
284 $nextid = $lastrecord->id + 1;
285 }
286 $queries[] = "ALTER SEQUENCE {$prefix}{$table}_id_seq RESTART WITH $nextid";
287 }
288 }
289 if ($queries) {
290 $DB->change_database_structure(implode(';', $queries));
291 }
8b5413cc 292
ab483c0a
PS
293 } else if ($dbfamily === 'mysql') {
294 $sequences = array();
8b5413cc
PS
295 $prefix = $DB->get_prefix();
296 $rs = $DB->get_recordset_sql("SHOW TABLE STATUS LIKE ?", array($prefix.'%'));
297 foreach ($rs as $info) {
298 $table = strtolower($info->name);
299 if (strpos($table, $prefix) !== 0) {
300 // incorrect table match caused by _
301 continue;
302 }
303 if (!is_null($info->auto_increment)) {
e10736b3 304 $table = preg_replace('/^'.preg_quote($prefix, '/').'/', '', $table);
8b5413cc
PS
305 $sequences[$table] = $info->auto_increment;
306 }
307 }
308 $rs->close();
ab483c0a
PS
309 foreach ($data as $table=>$records) {
310 if (isset($structure[$table]['id']) and $structure[$table]['id']->auto_increment) {
311 if (isset($sequences[$table])) {
312 if (empty($records)) {
313 $lastid = 0;
314 } else {
315 $lastrecord = end($records);
316 $lastid = $lastrecord->id;
317 }
318 if ($sequences[$table] != $lastid +1) {
319 $DB->get_manager()->reset_sequence($table);
320 }
8b5413cc 321
8b5413cc 322 } else {
8b5413cc
PS
323 $DB->get_manager()->reset_sequence($table);
324 }
ab483c0a
PS
325 }
326 }
8b5413cc 327
ab483c0a
PS
328 } else {
329 // note: does mssql and oracle support any kind of faster reset?
e10736b3
PS
330 if (is_null($empties)) {
331 $empties = self::guess_unmodified_empty_tables();
332 }
ab483c0a 333 foreach ($data as $table=>$records) {
e10736b3
PS
334 if (isset($empties[$table])) {
335 continue;
336 }
ab483c0a 337 if (isset($structure[$table]['id']) and $structure[$table]['id']->auto_increment) {
8b5413cc
PS
338 $DB->get_manager()->reset_sequence($table);
339 }
340 }
341 }
342 }
343
5bd40408 344 /**
a3d5830a 345 * Reset all database tables to default values.
5bd40408 346 * @static
a3d5830a 347 * @return bool true if reset done, false if skipped
5bd40408 348 */
7b0ff213 349 public static function reset_database() {
a3d5830a
PS
350 global $DB;
351
a3d5830a
PS
352 $tables = $DB->get_tables(false);
353 if (!$tables or empty($tables['config'])) {
354 // not installed yet
fe35ccaf 355 return false;
5bd40408
PS
356 }
357
fe35ccaf
PS
358 if (!is_null(self::$lastdbwrites) and self::$lastdbwrites == $DB->perf_get_writes()) {
359 return false;
360 }
361 if (!$data = self::get_tabledata()) {
362 // not initialised yet
363 return false;
364 }
0b9251e3
PS
365 if (!$structure = self::get_tablestructure()) {
366 // not initialised yet
367 return false;
368 }
728eadac 369
e10736b3
PS
370 $empties = self::guess_unmodified_empty_tables();
371
fe35ccaf
PS
372 foreach ($data as $table=>$records) {
373 if (empty($records)) {
e10736b3
PS
374 if (isset($empties[$table])) {
375 // table was not modified and is empty
376 } else {
377 $DB->delete_records($table, array());
378 }
fe35ccaf
PS
379 continue;
380 }
381
ab483c0a 382 if (isset($structure[$table]['id']) and $structure[$table]['id']->auto_increment) {
714f3998
PS
383 $currentrecords = $DB->get_records($table, array(), 'id ASC');
384 $changed = false;
385 foreach ($records as $id=>$record) {
386 if (!isset($currentrecords[$id])) {
387 $changed = true;
388 break;
389 }
390 if ((array)$record != (array)$currentrecords[$id]) {
391 $changed = true;
392 break;
728eadac 393 }
714f3998
PS
394 unset($currentrecords[$id]);
395 }
396 if (!$changed) {
397 if ($currentrecords) {
398 $lastrecord = end($records);
399 $DB->delete_records_select($table, "id > ?", array($lastrecord->id));
400 continue;
401 } else {
402 continue;
a3d5830a 403 }
a3d5830a 404 }
fe35ccaf 405 }
728eadac 406
fe35ccaf 407 $DB->delete_records($table, array());
fe35ccaf
PS
408 foreach ($records as $record) {
409 $DB->import_record($table, $record, false, true);
410 }
411 }
714f3998 412
8b5413cc 413 // reset all next record ids - aka sequences
e10736b3 414 self::reset_all_database_sequences($empties);
728eadac 415
fe35ccaf 416 // remove extra tables
714f3998
PS
417 foreach ($tables as $table) {
418 if (!isset($data[$table])) {
419 $DB->get_manager()->drop_table(new xmldb_table($table));
5bd40408 420 }
5bd40408 421 }
a3d5830a
PS
422
423 self::$lastdbwrites = $DB->perf_get_writes();
424
fe35ccaf 425 return true;
5bd40408
PS
426 }
427
728eadac 428 /**
920f4efe 429 * Purge dataroot directory
728eadac
PS
430 * @static
431 * @return void
432 */
433 public static function reset_dataroot() {
434 global $CFG;
435
436 $handle = opendir($CFG->dataroot);
437 $skip = array('.', '..', 'phpunittestdir.txt', 'phpunit', '.htaccess');
438 while (false !== ($item = readdir($handle))) {
439 if (in_array($item, $skip)) {
440 continue;
441 }
442 if (is_dir("$CFG->dataroot/$item")) {
443 remove_dir("$CFG->dataroot/$item", false);
444 } else {
445 unlink("$CFG->dataroot/$item");
446 }
447 }
448 closedir($handle);
449 make_temp_directory('');
450 make_cache_directory('');
451 make_cache_directory('htmlpurifier');
452 }
453
5bd40408
PS
454 /**
455 * Reset contents of all database tables to initial values, reset caches, etc.
456 *
457 * Note: this is relatively slow (cca 2 seconds for pg and 7 for mysql) - please use with care!
458 *
920f4efe 459 * @static
a3d5830a 460 * @param bool $logchanges log changes in global state and database in error log
a3d5830a 461 * @return void
5bd40408 462 */
7b0ff213 463 public static function reset_all_data($logchanges = false) {
458b3386 464 global $DB, $CFG, $USER, $SITE, $COURSE, $PAGE, $OUTPUT, $SESSION;
5bd40408 465
95dcf965
PS
466 // reset global $DB in case somebody mocked it
467 $DB = self::get_global_backup('DB');
468
ce9f3beb
PS
469 if ($DB->is_transaction_started()) {
470 // we can not reset inside transaction
471 $DB->force_transaction_rollback();
472 }
473
fe35ccaf 474 $resetdb = self::reset_database();
7b0ff213 475 $warnings = array();
5bd40408 476
a3d5830a 477 if ($logchanges) {
fe35ccaf 478 if ($resetdb) {
6e2cff2d 479 $warnings[] = 'Warning: unexpected database modification, resetting DB state';
a3d5830a
PS
480 }
481
482 $oldcfg = self::get_global_backup('CFG');
458b3386 483 $oldsite = self::get_global_backup('SITE');
a3d5830a
PS
484 foreach($CFG as $k=>$v) {
485 if (!property_exists($oldcfg, $k)) {
6e2cff2d 486 $warnings[] = 'Warning: unexpected new $CFG->'.$k.' value';
a3d5830a 487 } else if ($oldcfg->$k !== $CFG->$k) {
6e2cff2d 488 $warnings[] = 'Warning: unexpected change of $CFG->'.$k.' value';
a3d5830a
PS
489 }
490 unset($oldcfg->$k);
491
492 }
493 if ($oldcfg) {
494 foreach($oldcfg as $k=>$v) {
6e2cff2d 495 $warnings[] = 'Warning: unexpected removal of $CFG->'.$k;
5bd40408 496 }
5bd40408 497 }
a3d5830a
PS
498
499 if ($USER->id != 0) {
6e2cff2d 500 $warnings[] = 'Warning: unexpected change of $USER';
5bd40408 501 }
458b3386
PS
502
503 if ($COURSE->id != $oldsite->id) {
6e2cff2d 504 $warnings[] = 'Warning: unexpected change of $COURSE';
458b3386 505 }
5bd40408 506 }
5bd40408 507
920f4efe 508 // restore original globals
6e2cff2d 509 $_SERVER = self::get_global_backup('_SERVER');
a3d5830a 510 $CFG = self::get_global_backup('CFG');
458b3386
PS
511 $SITE = self::get_global_backup('SITE');
512 $COURSE = $SITE;
513
920f4efe 514 // reinitialise following globals
458b3386
PS
515 $OUTPUT = new bootstrap_renderer();
516 $PAGE = new moodle_page();
517 $FULLME = null;
518 $ME = null;
519 $SCRIPT = null;
520 $SESSION = new stdClass();
521 $_SESSION['SESSION'] =& $SESSION;
5bd40408 522
920f4efe 523 // set fresh new not-logged-in user
5bd40408
PS
524 $user = new stdClass();
525 $user->id = 0;
5bd40408
PS
526 $user->mnethostid = $CFG->mnet_localhost_id;
527 session_set_user($user);
a3d5830a
PS
528
529 // reset all static caches
530 accesslib_clear_all_caches(true);
531 get_string_manager()->reset_caches();
812013b1 532 events_get_handlers('reset');
a3d5830a
PS
533 //TODO: add more resets here and probably refactor them to new core function
534
920f4efe 535 // purge dataroot directory
728eadac 536 self::reset_dataroot();
a3d5830a 537
920f4efe 538 // restore original config once more in case resetting of caches changed CFG
a3d5830a
PS
539 $CFG = self::get_global_backup('CFG');
540
a3d5830a
PS
541 // inform data generator
542 self::get_data_generator()->reset();
543
544 // fix PHP settings
545 error_reporting($CFG->debug);
7b0ff213 546
8b5413cc
PS
547 // verify db writes just in case something goes wrong in reset
548 if (self::$lastdbwrites != $DB->perf_get_writes()) {
920f4efe 549 error_log('Unexpected DB writes in phpunit_util::reset_all_data()');
8b5413cc
PS
550 self::$lastdbwrites = $DB->perf_get_writes();
551 }
552
7b0ff213
PS
553 if ($warnings) {
554 $warnings = implode("\n", $warnings);
555 trigger_error($warnings, E_USER_WARNING);
556 }
5bd40408
PS
557 }
558
559 /**
560 * Called during bootstrap only!
920f4efe 561 * @internal
5bd40408 562 * @static
920f4efe 563 * @return void
5bd40408 564 */
a3d5830a 565 public static function bootstrap_init() {
95dcf965 566 global $CFG, $SITE, $DB;
5bd40408 567
a3d5830a 568 // backup the globals
6e2cff2d 569 self::$globals['_SERVER'] = $_SERVER;
5bd40408 570 self::$globals['CFG'] = clone($CFG);
458b3386 571 self::$globals['SITE'] = clone($SITE);
95dcf965 572 self::$globals['DB'] = $DB;
a3d5830a
PS
573
574 // refresh data in all tables, clear caches, etc.
575 phpunit_util::reset_all_data();
5bd40408
PS
576 }
577
578 /**
579 * Returns original state of global variable.
580 * @static
581 * @param string $name
582 * @return mixed
583 */
584 public static function get_global_backup($name) {
95dcf965
PS
585 if ($name === 'DB') {
586 // no cloning of database object,
587 // we just need the original reference, not original state
588 return self::$globals['DB'];
589 }
5bd40408
PS
590 if (isset(self::$globals[$name])) {
591 if (is_object(self::$globals[$name])) {
592 $return = clone(self::$globals[$name]);
593 return $return;
594 } else {
595 return self::$globals[$name];
596 }
597 }
598 return null;
599 }
600
601 /**
602 * Does this site (db and dataroot) appear to be used for production?
603 * We try very hard to prevent accidental damage done to production servers!!
604 *
605 * @static
606 * @return bool
607 */
608 public static function is_test_site() {
609 global $DB, $CFG;
610
611 if (!file_exists("$CFG->dataroot/phpunittestdir.txt")) {
612 // this is already tested in bootstrap script,
a3d5830a 613 // but anyway presence of this file means the dataroot is for testing
5bd40408
PS
614 return false;
615 }
616
617 $tables = $DB->get_tables(false);
618 if ($tables) {
619 if (!$DB->get_manager()->table_exists('config')) {
620 return false;
621 }
622 if (!get_config('core', 'phpunittest')) {
623 return false;
624 }
625 }
626
627 return true;
628 }
629
630 /**
631 * Is this site initialised to run unit tests?
632 *
633 * @static
7b0ff213 634 * @return int array errorcode=>message, 0 means ok
5bd40408 635 */
a3d5830a 636 public static function testing_ready_problem() {
7b0ff213 637 global $CFG, $DB;
5bd40408 638
7b0ff213 639 $tables = $DB->get_tables(false);
5bd40408 640
7b0ff213
PS
641 if (!self::is_test_site()) {
642 // dataroot was verified in bootstrap, so it must be DB
0d8e51a6 643 return array(PHPUNIT_EXITCODE_CONFIGERROR, 'Can not use database for testing, try different prefix');
5bd40408
PS
644 }
645
de3d1590 646 if (empty($tables)) {
0d8e51a6 647 return array(PHPUNIT_EXITCODE_INSTALL, '');
de3d1590
PS
648 }
649
0b9251e3 650 if (!file_exists("$CFG->dataroot/phpunit/tabledata.ser") or !file_exists("$CFG->dataroot/phpunit/tablestructure.ser")) {
0d8e51a6 651 return array(PHPUNIT_EXITCODE_REINSTALL, '');
5bd40408
PS
652 }
653
654 if (!file_exists("$CFG->dataroot/phpunit/versionshash.txt")) {
0d8e51a6 655 return array(PHPUNIT_EXITCODE_REINSTALL, '');
5bd40408
PS
656 }
657
658 $hash = phpunit_util::get_version_hash();
659 $oldhash = file_get_contents("$CFG->dataroot/phpunit/versionshash.txt");
660
661 if ($hash !== $oldhash) {
0d8e51a6 662 return array(PHPUNIT_EXITCODE_REINSTALL, '');
5bd40408
PS
663 }
664
e2b8630b
PS
665 $dbhash = get_config('core', 'phpunittest');
666 if ($hash !== $dbhash) {
0d8e51a6 667 return array(PHPUNIT_EXITCODE_REINSTALL, '');
e2b8630b
PS
668 }
669
7b0ff213 670 return array(0, '');
5bd40408
PS
671 }
672
673 /**
674 * Drop all test site data.
675 *
676 * Note: To be used from CLI scripts only.
677 *
678 * @static
7aea08e1 679 * @return void may terminate execution with exit code
5bd40408
PS
680 */
681 public static function drop_site() {
682 global $DB, $CFG;
683
684 if (!self::is_test_site()) {
0d8e51a6 685 phpunit_bootstrap_error(PHPUNIT_EXITCODE_CONFIGERROR, 'Can not drop non-test site!!');
5bd40408
PS
686 }
687
4be2ad36 688 // purge dataroot
728eadac 689 self::reset_dataroot();
5bd40408 690 phpunit_bootstrap_initdataroot($CFG->dataroot);
4be2ad36
PS
691 $keep = array('.', '..', 'lock', 'webrunner.xml');
692 $files = scandir("$CFG->dataroot/phpunit");
693 foreach ($files as $file) {
694 if (in_array($file, $keep)) {
695 continue;
696 }
697 $path = "$CFG->dataroot/phpunit/$file";
698 if (is_dir($path)) {
699 remove_dir($path, false);
700 } else {
701 unlink($path);
702 }
703 }
5bd40408
PS
704
705 // drop all tables
5bd40408 706 $tables = $DB->get_tables(false);
728eadac
PS
707 if (isset($tables['config'])) {
708 // config always last to prevent problems with interrupted drops!
709 unset($tables['config']);
710 $tables['config'] = 'config';
5bd40408 711 }
5bd40408
PS
712 foreach ($tables as $tablename) {
713 $table = new xmldb_table($tablename);
714 $DB->get_manager()->drop_table($table);
715 }
716 }
717
718 /**
719 * Perform a fresh test site installation
720 *
721 * Note: To be used from CLI scripts only.
722 *
723 * @static
7aea08e1 724 * @return void may terminate execution with exit code
5bd40408
PS
725 */
726 public static function install_site() {
727 global $DB, $CFG;
728
729 if (!self::is_test_site()) {
0d8e51a6 730 phpunit_bootstrap_error(PHPUNIT_EXITCODE_CONFIGERROR, 'Can not install on non-test site!!');
5bd40408
PS
731 }
732
733 if ($DB->get_tables()) {
219d1a4e
PS
734 list($errorcode, $message) = phpunit_util::testing_ready_problem();
735 if ($errorcode) {
0d8e51a6 736 phpunit_bootstrap_error(PHPUNIT_EXITCODE_REINSTALL, 'Database tables already present, Moodle PHPUnit test environment can not be initialised');
219d1a4e 737 } else {
b6b8a193 738 phpunit_bootstrap_error(0, 'Moodle PHPUnit test environment is already initialised');
219d1a4e 739 }
5bd40408
PS
740 }
741
742 $options = array();
6e2cff2d 743 $options['adminpass'] = 'admin';
5bd40408
PS
744 $options['shortname'] = 'phpunit';
745 $options['fullname'] = 'PHPUnit test site';
746
747 install_cli_database($options, false);
748
a3d5830a
PS
749 // install timezone info
750 $timezones = get_records_csv($CFG->libdir.'/timezone.txt', 'timezone');
751 update_timezone_records($timezones);
5bd40408
PS
752
753 // add test db flag
e2b8630b
PS
754 $hash = phpunit_util::get_version_hash();
755 set_config('phpunittest', $hash);
5bd40408
PS
756
757 // store data for all tables
758 $data = array();
0b9251e3 759 $structure = array();
5bd40408
PS
760 $tables = $DB->get_tables();
761 foreach ($tables as $table) {
728eadac 762 $columns = $DB->get_columns($table);
0b9251e3 763 $structure[$table] = $columns;
ab483c0a 764 if (isset($columns['id']) and $columns['id']->auto_increment) {
728eadac
PS
765 $data[$table] = $DB->get_records($table, array(), 'id ASC');
766 } else {
767 // there should not be many of these
768 $data[$table] = $DB->get_records($table, array());
769 }
5bd40408
PS
770 }
771 $data = serialize($data);
5bd40408 772 file_put_contents("$CFG->dataroot/phpunit/tabledata.ser", $data);
6e2cff2d 773 phpunit_boostrap_fix_file_permissions("$CFG->dataroot/phpunit/tabledata.ser");
5bd40408 774
0b9251e3
PS
775 $structure = serialize($structure);
776 file_put_contents("$CFG->dataroot/phpunit/tablestructure.ser", $structure);
777 phpunit_boostrap_fix_file_permissions("$CFG->dataroot/phpunit/tablestructure.ser");
778
5bd40408 779 // hash all plugin versions - helps with very fast detection of db structure changes
5bd40408 780 file_put_contents("$CFG->dataroot/phpunit/versionshash.txt", $hash);
6e2cff2d 781 phpunit_boostrap_fix_file_permissions("$CFG->dataroot/phpunit/versionshash.txt", $hash);
5bd40408
PS
782 }
783
784 /**
920f4efe 785 * Calculate unique version hash for all plugins and core.
5bd40408
PS
786 * @static
787 * @return string sha1 hash
788 */
789 public static function get_version_hash() {
790 global $CFG;
791
589376d3
PS
792 if (self::$versionhash) {
793 return self::$versionhash;
794 }
795
5bd40408
PS
796 $versions = array();
797
798 // main version first
799 $version = null;
800 include($CFG->dirroot.'/version.php');
801 $versions['core'] = $version;
802
803 // modules
804 $mods = get_plugin_list('mod');
805 ksort($mods);
806 foreach ($mods as $mod => $fullmod) {
807 $module = new stdClass();
808 $module->version = null;
809 include($fullmod.'/version.php');
810 $versions[$mod] = $module->version;
811 }
812
813 // now the rest of plugins
814 $plugintypes = get_plugin_types();
815 unset($plugintypes['mod']);
816 ksort($plugintypes);
817 foreach ($plugintypes as $type=>$unused) {
818 $plugs = get_plugin_list($type);
819 ksort($plugs);
820 foreach ($plugs as $plug=>$fullplug) {
821 $plugin = new stdClass();
822 $plugin->version = null;
823 @include($fullplug.'/version.php');
824 $versions[$plug] = $plugin->version;
825 }
826 }
827
589376d3 828 self::$versionhash = sha1(serialize($versions));
5bd40408 829
589376d3 830 return self::$versionhash;
5bd40408
PS
831 }
832
833 /**
920f4efe 834 * Builds dirroot/phpunit.xml and dataroot/phpunit/webrunner.xml files using defaults from /phpunit.xml.dist
5bd40408 835 * @static
7b0ff213 836 * @return bool true means main config file created, false means only dataroot file created
5bd40408
PS
837 */
838 public static function build_config_file() {
839 global $CFG;
840
841 $template = '
5bd40408
PS
842 <testsuite name="@component@">
843 <directory suffix="_test.php">@dir@</directory>
a3d5830a 844 </testsuite>';
5bd40408
PS
845 $data = file_get_contents("$CFG->dirroot/phpunit.xml.dist");
846
847 $suites = '';
848
849 $plugintypes = get_plugin_types();
850 ksort($plugintypes);
851 foreach ($plugintypes as $type=>$unused) {
852 $plugs = get_plugin_list($type);
853 ksort($plugs);
854 foreach ($plugs as $plug=>$fullplug) {
855 if (!file_exists("$fullplug/tests/")) {
856 continue;
857 }
322cf284 858 $dir = substr($fullplug, strlen($CFG->dirroot)+1);
5bd40408
PS
859 $dir .= '/tests';
860 $component = $type.'_'.$plug;
861
862 $suite = str_replace('@component@', $component, $template);
863 $suite = str_replace('@dir@', $dir, $suite);
864
865 $suites .= $suite;
866 }
867 }
868
7aea08e1 869 $data = preg_replace('|<!--@plugin_suites_start@-->.*<!--@plugin_suites_end@-->|s', $suites, $data, 1);
5bd40408 870
7b0ff213
PS
871 $result = false;
872 if (is_writable($CFG->dirroot)) {
873 if ($result = file_put_contents("$CFG->dirroot/phpunit.xml", $data)) {
6e2cff2d 874 phpunit_boostrap_fix_file_permissions("$CFG->dirroot/phpunit.xml");
7b0ff213
PS
875 }
876 }
322cf284 877
6e2cff2d 878 // relink - it seems that xml:base does not work in phpunit xml files, remove this nasty hack if you find a way to set xml base for relative refs
322cf284
PS
879 $data = str_replace('lib/phpunit/', $CFG->dirroot.DIRECTORY_SEPARATOR.'lib'.DIRECTORY_SEPARATOR.'phpunit'.DIRECTORY_SEPARATOR, $data);
880 $data = preg_replace('|<directory suffix="_test.php">([^<]+)</directory>|',
881 '<directory suffix="_test.php">'.$CFG->dirroot.(DIRECTORY_SEPARATOR === '\\' ? '\\\\' : DIRECTORY_SEPARATOR).'$1</directory>',
882 $data);
7b0ff213 883 file_put_contents("$CFG->dataroot/phpunit/webrunner.xml", $data);
6e2cff2d 884 phpunit_boostrap_fix_file_permissions("$CFG->dataroot/phpunit/webrunner.xml");
7b0ff213
PS
885
886 return (bool)$result;
5bd40408
PS
887 }
888}
889
890
891/**
892 * Simplified emulation test case for legacy SimpleTest.
893 *
894 * Note: this is supposed to work for very simple tests only.
895 *
7aea08e1
SH
896 * @deprecated since 2.3
897 * @package core
898 * @category phpunit
5bd40408
PS
899 * @author Petr Skoda
900 * @copyright 2012 Petr Skoda {@link http://skodak.org}
901 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
902 */
d2999716 903abstract class UnitTestCase extends PHPUnit_Framework_TestCase {
5bd40408
PS
904
905 /**
7aea08e1 906 * @deprecated since 2.3
5bd40408
PS
907 * @param bool $expected
908 * @param string $message
a3d5830a 909 * @return void
5bd40408
PS
910 */
911 public function expectException($expected, $message = '') {
920f4efe 912 // alternatively use phpdocs: @expectedException ExceptionClassName
5bd40408
PS
913 if (!$expected) {
914 return;
915 }
916 $this->setExpectedException('moodle_exception', $message);
917 }
918
919 /**
7aea08e1 920 * @deprecated since 2.3
5bd40408
PS
921 * @param bool $expected
922 * @param string $message
a3d5830a 923 * @return void
5bd40408
PS
924 */
925 public static function expectError($expected = false, $message = '') {
926 // not available in PHPUnit
927 if (!$expected) {
928 return;
929 }
930 self::skipIf(true);
931 }
932
933 /**
7aea08e1 934 * @deprecated since 2.3
5bd40408
PS
935 * @static
936 * @param mixed $actual
937 * @param string $messages
a3d5830a 938 * @return void
5bd40408
PS
939 */
940 public static function assertTrue($actual, $messages = '') {
941 parent::assertTrue((bool)$actual, $messages);
942 }
943
944 /**
7aea08e1 945 * @deprecated since 2.3
5bd40408
PS
946 * @static
947 * @param mixed $actual
948 * @param string $messages
a3d5830a 949 * @return void
5bd40408
PS
950 */
951 public static function assertFalse($actual, $messages = '') {
952 parent::assertFalse((bool)$actual, $messages);
953 }
954
955 /**
7aea08e1 956 * @deprecated since 2.3
5bd40408
PS
957 * @static
958 * @param mixed $expected
959 * @param mixed $actual
960 * @param string $message
a3d5830a 961 * @return void
5bd40408
PS
962 */
963 public static function assertEqual($expected, $actual, $message = '') {
964 parent::assertEquals($expected, $actual, $message);
965 }
966
967 /**
7aea08e1 968 * @deprecated since 2.3
5bd40408
PS
969 * @static
970 * @param mixed $expected
971 * @param mixed $actual
972 * @param string $message
a3d5830a 973 * @return void
5bd40408
PS
974 */
975 public static function assertNotEqual($expected, $actual, $message = '') {
976 parent::assertNotEquals($expected, $actual, $message);
977 }
978
979 /**
7aea08e1 980 * @deprecated since 2.3
5bd40408
PS
981 * @static
982 * @param mixed $expected
983 * @param mixed $actual
984 * @param string $message
a3d5830a 985 * @return void
5bd40408
PS
986 */
987 public static function assertIdentical($expected, $actual, $message = '') {
988 parent::assertSame($expected, $actual, $message);
989 }
990
991 /**
7aea08e1 992 * @deprecated since 2.3
5bd40408
PS
993 * @static
994 * @param mixed $expected
995 * @param mixed $actual
996 * @param string $message
a3d5830a 997 * @return void
5bd40408
PS
998 */
999 public static function assertNotIdentical($expected, $actual, $message = '') {
1000 parent::assertNotSame($expected, $actual, $message);
1001 }
1002
1003 /**
7aea08e1 1004 * @deprecated since 2.3
5bd40408
PS
1005 * @static
1006 * @param mixed $actual
1007 * @param mixed $expected
1008 * @param string $message
a3d5830a 1009 * @return void
5bd40408
PS
1010 */
1011 public static function assertIsA($actual, $expected, $message = '') {
6e2cff2d
PS
1012 if ($expected === 'array') {
1013 parent::assertEquals(gettype($actual), 'array', $message);
1014 } else {
1015 parent::assertInstanceOf($expected, $actual, $message);
1016 }
5bd40408
PS
1017 }
1018}
1019
1020
1021/**
7aea08e1
SH
1022 * The simplest PHPUnit test case customised for Moodle
1023 *
a3d5830a 1024 * It is intended for isolated tests that do not modify database or any globals.
5bd40408 1025 *
7aea08e1
SH
1026 * @package core
1027 * @category phpunit
5bd40408
PS
1028 * @copyright 2012 Petr Skoda {@link http://skodak.org}
1029 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1030 */
d2999716 1031abstract class basic_testcase extends PHPUnit_Framework_TestCase {
5bd40408
PS
1032
1033 /**
1034 * Constructs a test case with the given name.
1035 *
920f4efe 1036 * Note: use setUp() or setUpBeforeClass() in your test cases.
b0e980d7 1037 *
7aea08e1
SH
1038 * @param string $name
1039 * @param array $data
1040 * @param string $dataName
5bd40408 1041 */
b0e980d7 1042 final public function __construct($name = null, array $data = array(), $dataName = '') {
5bd40408
PS
1043 parent::__construct($name, $data, $dataName);
1044
1045 $this->setBackupGlobals(false);
1046 $this->setBackupStaticAttributes(false);
1047 $this->setRunTestInSeparateProcess(false);
5bd40408
PS
1048 }
1049
1050 /**
a3d5830a 1051 * Runs the bare test sequence and log any changes in global state or database.
5bd40408
PS
1052 * @return void
1053 */
39e2e9c4 1054 final public function runBare() {
7620602c
PS
1055 global $DB;
1056
713d2091
PS
1057 try {
1058 parent::runBare();
1059 } catch (Exception $e) {
1060 // cleanup after failed expectation
1061 phpunit_util::reset_all_data();
1062 throw $e;
1063 }
7620602c
PS
1064
1065 if ($DB->is_transaction_started()) {
7620602c
PS
1066 phpunit_util::reset_all_data();
1067 throw new coding_exception('basic_testcase '.$this->getName().' is not supposed to use database transactions!');
1068 }
1069
7b0ff213 1070 phpunit_util::reset_all_data(true);
a3d5830a
PS
1071 }
1072}
5bd40408 1073
a3d5830a
PS
1074
1075/**
1076 * Advanced PHPUnit test case customised for Moodle.
1077 *
1078 * @package core
1079 * @category phpunit
1080 * @copyright 2012 Petr Skoda {@link http://skodak.org}
1081 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1082 */
d2999716 1083abstract class advanced_testcase extends PHPUnit_Framework_TestCase {
458b3386 1084 /** @var bool automatically reset everything? null means log changes */
a0c5affe 1085 private $resetAfterTest;
a3d5830a 1086
50be93d1 1087 /** @var moodle_transaction */
a0c5affe 1088 private $testdbtransaction;
50be93d1 1089
a3d5830a
PS
1090 /**
1091 * Constructs a test case with the given name.
1092 *
920f4efe 1093 * Note: use setUp() or setUpBeforeClass() in your test cases.
b0e980d7 1094 *
a3d5830a
PS
1095 * @param string $name
1096 * @param array $data
1097 * @param string $dataName
1098 */
b0e980d7 1099 final public function __construct($name = null, array $data = array(), $dataName = '') {
a3d5830a
PS
1100 parent::__construct($name, $data, $dataName);
1101
1102 $this->setBackupGlobals(false);
1103 $this->setBackupStaticAttributes(false);
1104 $this->setRunTestInSeparateProcess(false);
1105 }
1106
1107 /**
1108 * Runs the bare test sequence.
1109 * @return void
1110 */
39e2e9c4 1111 final public function runBare() {
50be93d1
PS
1112 global $DB;
1113
8b5413cc
PS
1114 if (phpunit_util::$lastdbwrites != $DB->perf_get_writes()) {
1115 // this happens when previous test does not reset, we can not use transactions
1116 $this->testdbtransaction = null;
1117
5a798e7e 1118 } else if ($DB->get_dbfamily() === 'postgres' or $DB->get_dbfamily() === 'mssql') {
50be93d1
PS
1119 // database must allow rollback of DDL, so no mysql here
1120 $this->testdbtransaction = $DB->start_delegated_transaction();
1121 }
1122
713d2091
PS
1123 try {
1124 parent::runBare();
95dcf965
PS
1125 // set DB reference in case somebody mocked it in test
1126 $DB = phpunit_util::get_global_backup('DB');
713d2091
PS
1127 } catch (Exception $e) {
1128 // cleanup after failed expectation
713d2091
PS
1129 phpunit_util::reset_all_data();
1130 throw $e;
1131 }
5bd40408 1132
50be93d1
PS
1133 if (!$this->testdbtransaction or $this->testdbtransaction->is_disposed()) {
1134 $this->testdbtransaction = null;
1135 }
50be93d1 1136
a3d5830a 1137 if ($this->resetAfterTest === true) {
8b5413cc 1138 if ($this->testdbtransaction) {
50be93d1 1139 $DB->force_transaction_rollback();
8b5413cc 1140 phpunit_util::reset_all_database_sequences();
50be93d1
PS
1141 phpunit_util::$lastdbwrites = $DB->perf_get_writes(); // no db reset necessary
1142 }
714f3998 1143 phpunit_util::reset_all_data();
8b5413cc 1144
a3d5830a 1145 } else if ($this->resetAfterTest === false) {
8b5413cc
PS
1146 if ($this->testdbtransaction) {
1147 $this->testdbtransaction->allow_commit();
50be93d1 1148 }
a3d5830a 1149 // keep all data untouched for other tests
8b5413cc 1150
a3d5830a
PS
1151 } else {
1152 // reset but log what changed
8b5413cc 1153 if ($this->testdbtransaction) {
7620602c
PS
1154 try {
1155 $this->testdbtransaction->allow_commit();
1156 } catch (dml_transaction_exception $e) {
7620602c
PS
1157 phpunit_util::reset_all_data();
1158 throw new coding_exception('Invalid transaction state detected in test '.$this->getName());
1159 }
50be93d1 1160 }
7b0ff213 1161 phpunit_util::reset_all_data(true);
a3d5830a 1162 }
7620602c
PS
1163
1164 // make sure test did not forget to close transaction
1165 if ($DB->is_transaction_started()) {
7620602c
PS
1166 phpunit_util::reset_all_data();
1167 if ($this->getStatus() == PHPUnit_Runner_BaseTestRunner::STATUS_PASSED
1168 or $this->getStatus() == PHPUnit_Runner_BaseTestRunner::STATUS_SKIPPED
1169 or $this->getStatus() == PHPUnit_Runner_BaseTestRunner::STATUS_INCOMPLETE) {
1170 throw new coding_exception('Test '.$this->getName().' did not close database transaction');
1171 }
1172 }
a3d5830a
PS
1173 }
1174
e396e8ed
PS
1175 /**
1176 * Creates a new FlatXmlDataSet with the given $xmlFile. (absolute path.)
1177 *
1178 * @param string $xmlFile
1179 * @return PHPUnit_Extensions_Database_DataSet_FlatXmlDataSet
1180 */
1181 protected function createFlatXMLDataSet($xmlFile) {
1182 return new PHPUnit_Extensions_Database_DataSet_FlatXmlDataSet($xmlFile);
1183 }
1184
1185 /**
1186 * Creates a new XMLDataSet with the given $xmlFile. (absolute path.)
1187 *
1188 * @param string $xmlFile
1189 * @return PHPUnit_Extensions_Database_DataSet_XmlDataSet
1190 */
1191 protected function createXMLDataSet($xmlFile) {
1192 return new PHPUnit_Extensions_Database_DataSet_XmlDataSet($xmlFile);
1193 }
1194
1195 /**
c691274b 1196 * Creates a new CsvDataSet from the given array of csv files. (absolute paths.)
e396e8ed
PS
1197 *
1198 * @param array $files array tablename=>cvsfile
1199 * @param string $delimiter
1200 * @param string $enclosure
1201 * @param string $escape
1202 * @return PHPUnit_Extensions_Database_DataSet_CsvDataSet
1203 */
c691274b 1204 protected function createCsvDataSet($files, $delimiter = ',', $enclosure = '"', $escape = '"') {
e396e8ed
PS
1205 $dataSet = new PHPUnit_Extensions_Database_DataSet_CsvDataSet($delimiter, $enclosure, $escape);
1206 foreach($files as $table=>$file) {
1207 $dataSet->addTable($table, $file);
1208 }
1209 return $dataSet;
1210 }
1211
1212 /**
1213 * Creates new ArrayDataSet from given array
1214 *
1215 * @param array $data array of tables, first row in each table is columns
1216 * @return phpunit_ArrayDataSet
1217 */
1218 protected function createArrayDataSet(array $data) {
1219 return new phpunit_ArrayDataSet($data);
1220 }
1221
1222 /**
1223 * Load date into moodle database tables from standard PHPUnit data set.
1224 *
1225 * Note: it is usually better to use data generators
1226 *
1227 * @param PHPUnit_Extensions_Database_DataSet_IDataSet $dataset
1228 * @return void
1229 */
1230 protected function loadDataSet(PHPUnit_Extensions_Database_DataSet_IDataSet $dataset) {
1231 global $DB;
1232
1233 $structure = phpunit_util::get_tablestructure();
1234
1235 foreach($dataset->getTableNames() as $tablename) {
1236 $table = $dataset->getTable($tablename);
1237 $metadata = $dataset->getTableMetaData($tablename);
1238 $columns = $metadata->getColumns();
1239
1240 $doimport = false;
1241 if (isset($structure[$tablename]['id']) and $structure[$tablename]['id']->auto_increment) {
1242 $doimport = in_array('id', $columns);
1243 }
1244
1245 for($r=0; $r<$table->getRowCount(); $r++) {
1246 $record = $table->getRow($r);
1247 if ($doimport) {
1248 $DB->import_record($tablename, $record);
1249 } else {
1250 $DB->insert_record($tablename, $record);
1251 }
1252 }
1253 if ($doimport) {
1254 $DB->get_manager()->reset_sequence(new xmldb_table($tablename));
1255 }
1256 }
1257 }
1258
8b5413cc
PS
1259 /**
1260 * Call this method from test if you want to make sure that
1261 * the resetting of database is done the slow way without transaction
1262 * rollback.
920f4efe
PS
1263 *
1264 * This is useful especially when testing stuff that is not compatible with transactions.
1265 *
8b5413cc
PS
1266 * @return void
1267 */
1268 public function preventResetByRollback() {
1269 if ($this->testdbtransaction and !$this->testdbtransaction->is_disposed()) {
1270 $this->testdbtransaction->allow_commit();
1271 $this->testdbtransaction = null;
1272 }
1273 }
1274
a3d5830a
PS
1275 /**
1276 * Reset everything after current test.
1277 * @param bool $reset true means reset state back, false means keep all data for the next test,
1278 * null means reset state and show warnings if anything changed
1279 * @return void
1280 */
1281 public function resetAfterTest($reset = true) {
1282 $this->resetAfterTest = $reset;
1283 }
1284
1285 /**
1286 * Cleanup after all tests are executed.
1287 *
1288 * Note: do not forget to call this if overridden...
1289 *
1290 * @static
1291 * @return void
1292 */
1293 public static function tearDownAfterClass() {
1294 phpunit_util::reset_all_data();
1295 }
1296
1297 /**
1298 * Reset all database tables, restore global state and clear caches and optionally purge dataroot dir.
1299 * @static
1300 * @return void
1301 */
1302 public static function resetAllData() {
1303 phpunit_util::reset_all_data();
1304 }
1305
458b3386
PS
1306 /**
1307 * Set current $USER, reset access cache.
1308 * @static
e72ea4a5 1309 * @param null|int|stdClass $user user record, null means non-logged-in, integer means userid
458b3386
PS
1310 * @return void
1311 */
e72ea4a5
PS
1312 public static function setUser($user = null) {
1313 global $CFG, $DB;
458b3386 1314
e72ea4a5
PS
1315 if (is_object($user)) {
1316 $user = clone($user);
1317 } else if (!$user) {
458b3386
PS
1318 $user = new stdClass();
1319 $user->id = 0;
1320 $user->mnethostid = $CFG->mnet_localhost_id;
1321 } else {
e72ea4a5 1322 $user = $DB->get_record('user', array('id'=>$user));
458b3386
PS
1323 }
1324 unset($user->description);
1325 unset($user->access);
1326
1327 session_set_user($user);
1328 }
1329
a3d5830a
PS
1330 /**
1331 * Get data generator
1332 * @static
1333 * @return phpunit_data_generator
1334 */
1335 public static function getDataGenerator() {
1336 return phpunit_util::get_data_generator();
1337 }
1338
1339 /**
1340 * Recursively visit all the files in the source tree. Calls the callback
1341 * function with the pathname of each file found.
1342 *
6e2cff2d
PS
1343 * @param string $path the folder to start searching from.
1344 * @param string $callback the method of this class to call with the name of each file found.
1345 * @param string $fileregexp a regexp used to filter the search (optional).
1346 * @param bool $exclude If true, pathnames that match the regexp will be ignored. If false,
a3d5830a
PS
1347 * only files that match the regexp will be included. (default false).
1348 * @param array $ignorefolders will not go into any of these folders (optional).
1349 * @return void
1350 */
1351 public function recurseFolders($path, $callback, $fileregexp = '/.*/', $exclude = false, $ignorefolders = array()) {
1352 $files = scandir($path);
1353
1354 foreach ($files as $file) {
1355 $filepath = $path .'/'. $file;
1356 if (strpos($file, '.') === 0) {
1357 /// Don't check hidden files.
1358 continue;
1359 } else if (is_dir($filepath)) {
1360 if (!in_array($filepath, $ignorefolders)) {
1361 $this->recurseFolders($filepath, $callback, $fileregexp, $exclude, $ignorefolders);
1362 }
1363 } else if ($exclude xor preg_match($fileregexp, $filepath)) {
1364 $this->$callback($filepath);
5bd40408 1365 }
a3d5830a
PS
1366 }
1367 }
1368}
5bd40408 1369
a3d5830a 1370
e396e8ed
PS
1371/**
1372 * based on array iterator code from PHPUnit documentation by Sebastian Bergmann
1373 * and added new constructor parameter for different array types.
1374 */
1375class phpunit_ArrayDataSet extends PHPUnit_Extensions_Database_DataSet_AbstractDataSet {
1376 /**
1377 * @var array
1378 */
1379 protected $tables = array();
1380
1381 /**
1382 * @param array $data
1383 */
1384 public function __construct(array $data) {
1385 foreach ($data AS $tableName => $rows) {
1386 $firstrow = reset($rows);
1387
1388 if (array_key_exists(0, $firstrow)) {
1389 // columns in first row
1390 $columnsInFirstRow = true;
1391 $columns = $firstrow;
1392 $key = key($rows);
1393 unset($rows[$key]);
1394 } else {
1395 // column name is in each row as key
1396 $columnsInFirstRow = false;
1397 $columns = array_keys($firstrow);
1398 }
1399
1400 $metaData = new PHPUnit_Extensions_Database_DataSet_DefaultTableMetaData($tableName, $columns);
1401 $table = new PHPUnit_Extensions_Database_DataSet_DefaultTable($metaData);
1402
1403 foreach ($rows AS $row) {
1404 if ($columnsInFirstRow) {
1405 $row = array_combine($columns, $row);
1406 }
1407 $table->addRow($row);
1408 }
1409 $this->tables[$tableName] = $table;
1410 }
1411 }
1412
1413 protected function createIterator($reverse = FALSE) {
1414 return new PHPUnit_Extensions_Database_DataSet_DefaultTableIterator($this->tables, $reverse);
1415 }
1416
1417 public function getTable($tableName) {
1418 if (!isset($this->tables[$tableName])) {
1419 throw new InvalidArgumentException("$tableName is not a table in the current database.");
1420 }
1421
1422 return $this->tables[$tableName];
1423 }
1424}
1425
1426
a3d5830a 1427/**
458b3386
PS
1428 * Special test case for testing of DML drivers and DDL layer.
1429 *
c06563c8
PS
1430 * Note: Use only 'test_table*' names when creating new tables.
1431 *
1432 * For DML/DDL developers: you can add following settings to config.php if you want to test different driver than the main one,
1433 * the reason is to allow testing of incomplete drivers that do not allow full PHPUnit environment
1434 * initialisation (the database can be empty).
1435 * $CFG->phpunit_extra_drivers = array(
1436 * 1=>array('dbtype'=>'mysqli', 'dbhost'=>'localhost', 'dbname'=>'moodle', 'dbuser'=>'root', 'dbpass'=>'', 'prefix'=>'phpu2_'),
1437 * 2=>array('dbtype'=>'pgsql', 'dbhost'=>'localhost', 'dbname'=>'moodle', 'dbuser'=>'postgres', 'dbpass'=>'', 'prefix'=>'phpu2_'),
1438 * 3=>array('dbtype'=>'sqlsrv', 'dbhost'=>'127.0.0.1', 'dbname'=>'moodle', 'dbuser'=>'sa', 'dbpass'=>'', 'prefix'=>'phpu2_'),
1439 * 4=>array('dbtype'=>'oci', 'dbhost'=>'127.0.0.1', 'dbname'=>'XE', 'dbuser'=>'sa', 'dbpass'=>'', 'prefix'=>'t_'),
1440 * );
1441 * define('PHPUNIT_TEST_DRIVER')=1; //number is index in the previous array
a3d5830a
PS
1442 *
1443 * @package core
1444 * @category phpunit
1445 * @copyright 2012 Petr Skoda {@link http://skodak.org}
1446 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1447 */
d2999716 1448abstract class database_driver_testcase extends PHPUnit_Framework_TestCase {
6e2cff2d 1449 /** @var moodle_database connection to extra database */
a0c5affe 1450 private static $extradb = null;
a3d5830a 1451
6e2cff2d 1452 /** @var moodle_database used in these tests*/
a3d5830a
PS
1453 protected $tdb;
1454
1455 /**
1456 * Constructs a test case with the given name.
1457 *
1458 * @param string $name
1459 * @param array $data
1460 * @param string $dataName
1461 */
b0e980d7 1462 final public function __construct($name = null, array $data = array(), $dataName = '') {
a3d5830a
PS
1463 parent::__construct($name, $data, $dataName);
1464
1465 $this->setBackupGlobals(false);
1466 $this->setBackupStaticAttributes(false);
1467 $this->setRunTestInSeparateProcess(false);
1468 }
1469
1470 public static function setUpBeforeClass() {
1471 global $CFG;
6e2cff2d 1472 parent::setUpBeforeClass();
a3d5830a
PS
1473
1474 if (!defined('PHPUNIT_TEST_DRIVER')) {
1475 // use normal $DB
1476 return;
5bd40408 1477 }
a3d5830a
PS
1478
1479 if (!isset($CFG->phpunit_extra_drivers[PHPUNIT_TEST_DRIVER])) {
1480 throw new exception('Can not find driver configuration options with index: '.PHPUNIT_TEST_DRIVER);
1481 }
1482
1483 $dblibrary = empty($CFG->phpunit_extra_drivers[PHPUNIT_TEST_DRIVER]['dblibrary']) ? 'native' : $CFG->phpunit_extra_drivers[PHPUNIT_TEST_DRIVER]['dblibrary'];
1484 $dbtype = $CFG->phpunit_extra_drivers[PHPUNIT_TEST_DRIVER]['dbtype'];
1485 $dbhost = $CFG->phpunit_extra_drivers[PHPUNIT_TEST_DRIVER]['dbhost'];
1486 $dbname = $CFG->phpunit_extra_drivers[PHPUNIT_TEST_DRIVER]['dbname'];
1487 $dbuser = $CFG->phpunit_extra_drivers[PHPUNIT_TEST_DRIVER]['dbuser'];
1488 $dbpass = $CFG->phpunit_extra_drivers[PHPUNIT_TEST_DRIVER]['dbpass'];
1489 $prefix = $CFG->phpunit_extra_drivers[PHPUNIT_TEST_DRIVER]['prefix'];
1490 $dboptions = empty($CFG->phpunit_extra_drivers[PHPUNIT_TEST_DRIVER]['dboptions']) ? array() : $CFG->phpunit_extra_drivers[PHPUNIT_TEST_DRIVER]['dboptions'];
1491
1492 $classname = "{$dbtype}_{$dblibrary}_moodle_database";
1493 require_once("$CFG->libdir/dml/$classname.php");
1494 $d = new $classname();
1495 if (!$d->driver_installed()) {
1496 throw new exception('Database driver for '.$classname.' is not installed');
1497 }
1498
1499 $d->connect($dbhost, $dbuser, $dbpass, $dbname, $prefix, $dboptions);
1500
1501 self::$extradb = $d;
1502 }
1503
1cbf2a20 1504 protected function setUp() {
a3d5830a 1505 global $DB;
6e2cff2d 1506 parent::setUp();
5bd40408 1507
a3d5830a
PS
1508 if (self::$extradb) {
1509 $this->tdb = self::$extradb;
1510 } else {
1511 $this->tdb = $DB;
5bd40408 1512 }
a3d5830a 1513 }
5bd40408 1514
1cbf2a20 1515 protected function tearDown() {
a3d5830a
PS
1516 // delete all test tables
1517 $dbman = $this->tdb->get_manager();
1518 $tables = $this->tdb->get_tables(false);
1519 foreach($tables as $tablename) {
1520 if (strpos($tablename, 'test_table') === 0) {
1521 $table = new xmldb_table($tablename);
1522 $dbman->drop_table($table);
1523 }
5bd40408 1524 }
6e2cff2d 1525 parent::tearDown();
a3d5830a 1526 }
5bd40408 1527
a3d5830a
PS
1528 public static function tearDownAfterClass() {
1529 if (self::$extradb) {
1530 self::$extradb->dispose();
1531 self::$extradb = null;
1532 }
1533 phpunit_util::reset_all_data();
6e2cff2d 1534 parent::tearDownAfterClass();
5bd40408 1535 }
a3d5830a 1536}