Skip to content

Commit

Permalink
MDL-72125 testing: Add helper to run generators as a user
Browse files Browse the repository at this point in the history
  • Loading branch information
andrewnicols committed Jul 16, 2021
1 parent 8453fe0 commit daf9b24
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions lib/testing/generator/component_generator_base.php
Expand Up @@ -57,4 +57,33 @@ public function __construct(testing_data_generator $datagenerator) {
*/
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);
}
}

0 comments on commit daf9b24

Please sign in to comment.