From daf9b24b6a8e76ecd71116bb4e9f2da72361245a Mon Sep 17 00:00:00 2001 From: Andrew Nicols Date: Thu, 8 Jul 2021 12:20:50 +0800 Subject: [PATCH] MDL-72125 testing: Add helper to run generators as a user --- .../generator/component_generator_base.php | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/lib/testing/generator/component_generator_base.php b/lib/testing/generator/component_generator_base.php index bdcdb113402..cd3f2194f03 100644 --- a/lib/testing/generator/component_generator_base.php +++ b/lib/testing/generator/component_generator_base.php @@ -57,4 +57,33 @@ abstract class component_generator_base { */ public function reset() { } + + /** + * Set the current user during data generation. + * + * This should be avoided wherever possible, but in some situations underlying code will insert data as the current + * user. + * + * @param stdClass $user + */ + protected function set_user(?stdClass $user = null): void { + global $CFG, $DB; + + if ($user === null) { + $user = (object) [ + 'id' => 0, + 'mnethostid' => $CFG->mnet_localhost_id, + ]; + } else { + $user = clone($user); + unset($user->description); + unset($user->access); + unset($user->preference); + } + + // Ensure session is empty, as it may contain caches and user-specific info. + \core\session\manager::init_empty_session(); + + \core\session\manager::set_user($user); + } }