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.
This commit is contained in:
Andrew Nicols 2024-02-07 21:04:57 +08:00
parent 4197e50fec
commit 6cd08cc382
No known key found for this signature in database
GPG Key ID: 6D1E3157C8CFBF14

View File

@ -57,7 +57,7 @@ abstract class advanced_testcase extends base_testcase {
* Runs the bare test sequence.
*/
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.
@ -70,20 +70,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)) {
@ -92,6 +89,13 @@ abstract class advanced_testcase extends base_testcase {
throw $e;
}
// 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;
}