From 4cee58fa336ded01f9462617e2f3856f2bbbd82a Mon Sep 17 00:00:00 2001 From: Andrew Nicols Date: Wed, 7 Feb 2024 21:04:57 +0800 Subject: [PATCH] MDL-66903 testing: Reset CFG and component after test This change moves the reset of global test state to the finally section rather than doing it only if the test passes. Previously if a test which modifies the `core_component` internals failed, it would not reset the internal state and impact subsequent tests. --- lib/phpunit/classes/advanced_testcase.php | 27 +++++++++++++---------- 1 file changed, 15 insertions(+), 12 deletions(-) diff --git a/lib/phpunit/classes/advanced_testcase.php b/lib/phpunit/classes/advanced_testcase.php index 185ba2ebe37..5b8262f863b 100644 --- a/lib/phpunit/classes/advanced_testcase.php +++ b/lib/phpunit/classes/advanced_testcase.php @@ -65,7 +65,7 @@ abstract class advanced_testcase extends base_testcase { * @return void */ final public function runBare(): void { - global $DB; + global $CFG, $DB; if (phpunit_util::$lastdbwrites != $DB->perf_get_writes()) { // this happens when previous test does not reset, we can not use transactions @@ -79,21 +79,17 @@ abstract class advanced_testcase extends base_testcase { try { $this->setCurrentTimeStart(); parent::runBare(); - // set DB reference in case somebody mocked it in test - $DB = phpunit_util::get_global_backup('DB'); - - // Deal with any debugging messages. - $debugerror = phpunit_util::display_debugging_messages(true); - $this->resetDebugging(); - if (!empty($debugerror)) { - trigger_error('Unexpected debugging() call detected.'."\n".$debugerror, E_USER_NOTICE); - } - } catch (Exception $ex) { $e = $ex; } catch (Throwable $ex) { // Engine errors in PHP7 throw exceptions of type Throwable (this "catch" will be ignored in PHP5). $e = $ex; + } finally { + // Reset global state after test and test failure. + $CFG = phpunit_util::get_global_backup('CFG'); + $DB = phpunit_util::get_global_backup('DB'); + // This is _hacky_. We need to reset the autoloader, and this is the only way to do so right now. + (new ReflectionProperty(\core_component::class, 'plugintypes'))->setValue(null, null); } if (isset($e)) { @@ -102,7 +98,14 @@ abstract class advanced_testcase extends base_testcase { throw $e; } - if (!$this->testdbtransaction or $this->testdbtransaction->is_disposed()) { + // Deal with any debugging messages. + $debugerror = phpunit_util::display_debugging_messages(true); + $this->resetDebugging(); + if (!empty($debugerror)) { + trigger_error('Unexpected debugging() call detected.' . "\n" . $debugerror, E_USER_NOTICE); + } + + if (!$this->testdbtransaction || $this->testdbtransaction->is_disposed()) { $this->testdbtransaction = null; }