MDL-72125 testing: Add helper to run generators as a user

This commit is contained in:
Andrew Nicols 2021-07-08 12:20:50 +08:00
parent 8453fe0ddb
commit daf9b24b6a

View File

@ -57,4 +57,33 @@ abstract class component_generator_base {
*/ */
public function reset() { 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);
}
} }