Sanitize TestUser
[lhc/web/wiklou.git] / tests / phpunit / includes / TestUser.php
1 <?php
2
3 /**
4 * Wraps the user object, so we can also retain full access to properties
5 * like password if we log in via the API.
6 */
7 class TestUser {
8 /**
9 * @deprecated Since 1.25. Use TestUser::getUser()->getName()
10 * @private
11 * @var string
12 */
13 public $username;
14
15 /**
16 * @deprecated Since 1.25. Use TestUser::getPassword()
17 * @private
18 * @var string
19 */
20 public $password;
21
22 /**
23 * @deprecated Since 1.25. Use TestUser::getUser()
24 * @private
25 * @var User
26 */
27 public $user;
28
29 private function assertNotReal() {
30 global $wgDBprefix;
31 if( $wgDBprefix !== MediaWikiTestCase::DB_PREFIX && $wgDBprefix !== MediaWikiTestCase::ORA_DB_PREFIX ) {
32 throw new MWException( "Can't create user on real database" );
33 }
34 }
35
36 public function __construct( $username, $realname = 'Real Name',
37 $email = 'sample@example.com', $groups = array()
38 ) {
39 $this->assertNotReal();
40
41 $this->username = $username;
42 $this->password = 'TestUser';
43
44 $this->user = User::newFromName( $this->username );
45 $this->user->load();
46
47 // In an ideal world we'd have a new wiki (or mock data store) for every single test.
48 // But for now, we just need to create or update the user with the desired properties.
49 // we particularly need the new password, since we just generated it randomly.
50 // In core MediaWiki, there is no functionality to delete users, so this is the best we can do.
51 if ( !$this->user->isLoggedIn() ) {
52 // create the user
53 $this->user = User::createNew(
54 $this->username, array(
55 "email" => $email,
56 "real_name" => $realname
57 )
58 );
59
60 if ( !$this->user ) {
61 throw new MWException( "Error creating TestUser " . $username );
62 }
63 }
64
65 // Update the user to use the password and other details
66 $this->user->setPassword( $this->password );
67 $this->user->setEmail( $email );
68 $this->user->setRealName( $realname );
69
70 // Adjust groups by adding any missing ones and removing any extras
71 $currentGroups = $this->user->getGroups();
72 foreach ( array_diff( $groups, $currentGroups ) as $group ) {
73 $this->user->addGroup( $group );
74 }
75 foreach ( array_diff( $currentGroups, $groups ) as $group ) {
76 $this->user->removeGroup( $group );
77 }
78 $this->user->saveSettings();
79 }
80
81 /**
82 * @return User
83 */
84 public function getUser() {
85 return $this->user;
86 }
87
88 /**
89 * @return string
90 */
91 public function getPassword() {
92 return $this->password;
93 }
94 }