Merge "AuthManager fixups around the login→RESTART→create flow"
[lhc/web/wiklou.git] / tests / phpunit / includes / api / ApiTestCase.php
1 <?php
2
3 abstract class ApiTestCase extends MediaWikiLangTestCase {
4 protected static $apiUrl;
5
6 /**
7 * @var ApiTestContext
8 */
9 protected $apiContext;
10
11 protected function setUp() {
12 global $wgServer, $wgDisableAuthManager;
13
14 parent::setUp();
15 self::$apiUrl = $wgServer . wfScript( 'api' );
16
17 ApiQueryInfo::resetTokenCache(); // tokens are invalid because we cleared the session
18
19 self::$users = [
20 'sysop' => static::getTestSysop(),
21 'uploader' => static::getTestUser(),
22 ];
23
24 $this->setMwGlobals( [
25 'wgAuth' => $wgDisableAuthManager ? new AuthPlugin : new MediaWiki\Auth\AuthManagerAuthPlugin,
26 'wgRequest' => new FauxRequest( [] ),
27 'wgUser' => self::$users['sysop']->user,
28 ] );
29
30 $this->apiContext = new ApiTestContext();
31 }
32
33 protected function tearDown() {
34 // Avoid leaking session over tests
35 MediaWiki\Session\SessionManager::getGlobalSession()->clear();
36
37 parent::tearDown();
38 }
39
40 /**
41 * Edits or creates a page/revision
42 * @param string $pageName Page title
43 * @param string $text Content of the page
44 * @param string $summary Optional summary string for the revision
45 * @param int $defaultNs Optional namespace id
46 * @return array Array as returned by WikiPage::doEditContent()
47 */
48 protected function editPage( $pageName, $text, $summary = '', $defaultNs = NS_MAIN ) {
49 $title = Title::newFromText( $pageName, $defaultNs );
50 $page = WikiPage::factory( $title );
51
52 return $page->doEditContent( ContentHandler::makeContent( $text, $title ), $summary );
53 }
54
55 /**
56 * Does the API request and returns the result.
57 *
58 * The returned value is an array containing
59 * - the result data (array)
60 * - the request (WebRequest)
61 * - the session data of the request (array)
62 * - if $appendModule is true, the Api module $module
63 *
64 * @param array $params
65 * @param array|null $session
66 * @param bool $appendModule
67 * @param User|null $user
68 *
69 * @return array
70 */
71 protected function doApiRequest( array $params, array $session = null,
72 $appendModule = false, User $user = null
73 ) {
74 global $wgRequest, $wgUser;
75
76 if ( is_null( $session ) ) {
77 // re-use existing global session by default
78 $session = $wgRequest->getSessionArray();
79 }
80
81 // set up global environment
82 if ( $user ) {
83 $wgUser = $user;
84 }
85
86 $wgRequest = new FauxRequest( $params, true, $session );
87 RequestContext::getMain()->setRequest( $wgRequest );
88 RequestContext::getMain()->setUser( $wgUser );
89 MediaWiki\Auth\AuthManager::resetCache();
90
91 // set up local environment
92 $context = $this->apiContext->newTestContext( $wgRequest, $wgUser );
93
94 $module = new ApiMain( $context, true );
95
96 // run it!
97 $module->execute();
98
99 // construct result
100 $results = [
101 $module->getResult()->getResultData( null, [ 'Strip' => 'all' ] ),
102 $context->getRequest(),
103 $context->getRequest()->getSessionArray()
104 ];
105
106 if ( $appendModule ) {
107 $results[] = $module;
108 }
109
110 return $results;
111 }
112
113 /**
114 * Add an edit token to the API request
115 * This is cheating a bit -- we grab a token in the correct format and then
116 * add it to the pseudo-session and to the request, without actually
117 * requesting a "real" edit token.
118 *
119 * @param array $params Key-value API params
120 * @param array|null $session Session array
121 * @param User|null $user A User object for the context
122 * @return array Result of the API call
123 * @throws Exception In case wsToken is not set in the session
124 */
125 protected function doApiRequestWithToken( array $params, array $session = null,
126 User $user = null
127 ) {
128 global $wgRequest;
129
130 if ( $session === null ) {
131 $session = $wgRequest->getSessionArray();
132 }
133
134 if ( isset( $session['wsToken'] ) && $session['wsToken'] ) {
135 // @todo Why does this directly mess with the session? Fix that.
136 // add edit token to fake session
137 $session['wsTokenSecrets']['default'] = $session['wsToken'];
138 // add token to request parameters
139 $timestamp = wfTimestamp();
140 $params['token'] = hash_hmac( 'md5', $timestamp, $session['wsToken'] ) .
141 dechex( $timestamp ) .
142 MediaWiki\Session\Token::SUFFIX;
143
144 return $this->doApiRequest( $params, $session, false, $user );
145 } else {
146 throw new Exception( "Session token not available" );
147 }
148 }
149
150 protected function doLogin( $testUser = 'sysop' ) {
151 if ( $testUser === null ) {
152 $testUser = static::getTestSysop();
153 } elseif ( is_string( $testUser ) && array_key_exists( $testUser, self::$users ) ) {
154 $testUser = self::$users[ $testUser ];
155 } elseif ( !$testUser instanceof TestUser ) {
156 throw new MWException( "Can not log in to undefined user $testUser" );
157 }
158
159 $data = $this->doApiRequest( [
160 'action' => 'login',
161 'lgname' => $testUser->username,
162 'lgpassword' => $testUser->password ] );
163
164 $token = $data[0]['login']['token'];
165
166 $data = $this->doApiRequest(
167 [
168 'action' => 'login',
169 'lgtoken' => $token,
170 'lgname' => $testUser->username,
171 'lgpassword' => $testUser->password,
172 ],
173 $data[2]
174 );
175
176 if ( $data[0]['login']['result'] === 'Success' ) {
177 // DWIM
178 global $wgUser;
179 $wgUser = $testUser->getUser();
180 RequestContext::getMain()->setUser( $wgUser );
181 }
182
183 return $data;
184 }
185
186 protected function getTokenList( $user, $session = null ) {
187 $data = $this->doApiRequest( [
188 'action' => 'tokens',
189 'type' => 'edit|delete|protect|move|block|unblock|watch'
190 ], $session, false, $user->user );
191
192 if ( !array_key_exists( 'tokens', $data[0] ) ) {
193 throw new MWException( 'Api failed to return a token list' );
194 }
195
196 return $data[0]['tokens'];
197 }
198
199 public function testApiTestGroup() {
200 $groups = PHPUnit_Util_Test::getGroups( get_class( $this ) );
201 $constraint = PHPUnit_Framework_Assert::logicalOr(
202 $this->contains( 'medium' ),
203 $this->contains( 'large' )
204 );
205 $this->assertThat( $groups, $constraint,
206 'ApiTestCase::setUp can be slow, tests must be "medium" or "large"'
207 );
208 }
209 }