6 class TestUserRegistry
{
8 /** @var TestUser[] (group key => TestUser) */
9 private static $testUsers = [];
11 /** @var int Count of users that have been generated */
12 private static $counter = 0;
14 /** @var int Random int, included in IDs */
15 private static $randInt;
17 public static function getNextId() {
18 if ( !self
::$randInt ) {
19 self
::$randInt = mt_rand( 1, 0xFFFFFF );
21 return sprintf( '%06x.%03x', self
::$randInt, ++self
::$counter );
25 * Get a TestUser object that the caller may modify.
29 * @param string $testName Caller's __CLASS__. Used to generate the
31 * @param string[] $groups Groups the test user should be added to.
34 public static function getMutableTestUser( $testName, $groups = [] ) {
35 $id = self
::getNextId();
36 $password = wfRandomString( 20 );
37 $testUser = new TestUser(
38 "TestUser $testName $id", // username
39 "Name $id", // real name
40 "$id@mediawiki.test", // e-mail
44 $testUser->getUser()->clearInstanceCache();
49 * Get a TestUser object that the caller may not modify.
51 * Whenever possible, unit tests should use immutable users, because
52 * immutable users can be reused in multiple tests, which helps keep
53 * the unit tests fast.
57 * @param string[] $groups Groups the test user should be added to.
60 public static function getImmutableTestUser( $groups = [] ) {
61 $groups = array_unique( $groups );
63 $key = implode( ',', $groups );
65 $testUser = isset( self
::$testUsers[$key] )
66 ? self
::$testUsers[$key]
69 if ( !$testUser ||
!$testUser->getUser()->isLoggedIn() ) {
70 $id = self
::getNextId();
71 // Hack! If this is the primary sysop account, make the username
72 // be 'UTSysop', for back-compat, and for the sake of PHPUnit data
73 // provider methods, which are executed before the test database
74 // is set up. See T136348.
75 if ( $groups === [ 'bureaucrat', 'sysop' ] ) {
76 $username = 'UTSysop';
77 $password = 'UTSysopPassword';
79 $username = "TestUser $id";
80 $password = wfRandomString( 20 );
82 self
::$testUsers[$key] = $testUser = new TestUser(
83 $username, // username
84 "Name $id", // real name
85 "$id@mediawiki.test", // e-mail
91 $testUser->getUser()->clearInstanceCache();
92 return self
::$testUsers[$key];
98 * TestUsers created by this class will not be deleted, but any handles
99 * to existing immutable TestUsers will be deleted, ensuring these users
100 * are not reused. We don't reset the counter or random string by design.
104 * @param string[] $groups Groups the test user should be added to.
107 public static function clear() {
108 self
::$testUsers = [];