From 95dcf965597af02a4cdb892a90c657cce96cc84b Mon Sep 17 00:00:00 2001 From: Petr Skoda Date: Tue, 10 Apr 2012 12:13:28 +0200 Subject: [PATCH] MDL-32323 allow mocking of global $DB --- lib/phpunit/lib.php | 13 ++++++++++++- lib/tests/phpunit_test.php | 21 +++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/lib/phpunit/lib.php b/lib/phpunit/lib.php index 9f44e2b6dec..bbe0e7547dc 100644 --- a/lib/phpunit/lib.php +++ b/lib/phpunit/lib.php @@ -420,6 +420,9 @@ class phpunit_util { public static function reset_all_data($logchanges = false) { global $DB, $CFG, $USER, $SITE, $COURSE, $PAGE, $OUTPUT, $SESSION; + // reset global $DB in case somebody mocked it + $DB = self::get_global_backup('DB'); + if ($DB->is_transaction_started()) { // we can not reset inside transaction $DB->force_transaction_rollback(); @@ -515,12 +518,13 @@ class phpunit_util { * @static */ public static function bootstrap_init() { - global $CFG, $SITE; + global $CFG, $SITE, $DB; // backup the globals self::$globals['_SERVER'] = $_SERVER; self::$globals['CFG'] = clone($CFG); self::$globals['SITE'] = clone($SITE); + self::$globals['DB'] = $DB; // refresh data in all tables, clear caches, etc. phpunit_util::reset_all_data(); @@ -533,6 +537,11 @@ class phpunit_util { * @return mixed */ public static function get_global_backup($name) { + if ($name === 'DB') { + // no cloning of database object, + // we just need the original reference, not original state + return self::$globals['DB']; + } if (isset(self::$globals[$name])) { if (is_object(self::$globals[$name])) { $return = clone(self::$globals[$name]); @@ -1056,6 +1065,8 @@ class advanced_testcase extends PHPUnit_Framework_TestCase { try { parent::runBare(); + // set DB reference in case somebody mocked it in test + $DB = phpunit_util::get_global_backup('DB'); } catch (Exception $e) { // cleanup after failed expectation phpunit_util::reset_all_data(); diff --git a/lib/tests/phpunit_test.php b/lib/tests/phpunit_test.php index accd3f29cd6..39f918a3b54 100644 --- a/lib/tests/phpunit_test.php +++ b/lib/tests/phpunit_test.php @@ -324,6 +324,27 @@ class core_phpunit_advanced_testcase extends advanced_testcase { $generator = $this->getDataGenerator(); $this->assertInstanceOf('phpunit_data_generator', $generator); } + + public function test_database_mock1() { + global $DB; + + try { + $DB->get_record('pokus', array()); + $this->fail('Exception expected when accessing non existent table'); + } catch (dml_exception $e) { + $this->assertTrue(true); + } + $DB = $this->getMock(get_class($DB)); + $this->assertNull($DB->get_record('pokus', array())); + // test continues after reset + } + + public function test_database_mock2() { + global $DB; + + // now the database should be back to normal + $this->assertFalse($DB->get_record('user', array('id'=>9999))); + } }