Refactor ApiTestCase to get token from ApiQueryTokens
[lhc/web/wiklou.git] / tests / phpunit / includes / api / ApiTestCase.php
1 <?php
2
3 use MediaWiki\Session\SessionManager;
4
5 abstract class ApiTestCase extends MediaWikiLangTestCase {
6 protected static $apiUrl;
7
8 protected static $errorFormatter = null;
9
10 /**
11 * @var ApiTestContext
12 */
13 protected $apiContext;
14
15 protected function setUp() {
16 global $wgServer;
17
18 parent::setUp();
19 self::$apiUrl = $wgServer . wfScript( 'api' );
20
21 ApiQueryInfo::resetTokenCache(); // tokens are invalid because we cleared the session
22
23 self::$users = [
24 'sysop' => static::getTestSysop(),
25 'uploader' => static::getTestUser(),
26 ];
27
28 $this->setMwGlobals( [
29 'wgAuth' => new MediaWiki\Auth\AuthManagerAuthPlugin,
30 'wgRequest' => new FauxRequest( [] ),
31 'wgUser' => self::$users['sysop']->getUser(),
32 ] );
33
34 $this->apiContext = new ApiTestContext();
35 }
36
37 protected function tearDown() {
38 // Avoid leaking session over tests
39 MediaWiki\Session\SessionManager::getGlobalSession()->clear();
40
41 parent::tearDown();
42 }
43
44 /**
45 * Edits or creates a page/revision
46 * @param string $pageName Page title
47 * @param string $text Content of the page
48 * @param string $summary Optional summary string for the revision
49 * @param int $defaultNs Optional namespace id
50 * @return array Array as returned by WikiPage::doEditContent()
51 */
52 protected function editPage( $pageName, $text, $summary = '', $defaultNs = NS_MAIN ) {
53 $title = Title::newFromText( $pageName, $defaultNs );
54 $page = WikiPage::factory( $title );
55
56 return $page->doEditContent( ContentHandler::makeContent( $text, $title ), $summary );
57 }
58
59 /**
60 * Does the API request and returns the result.
61 *
62 * The returned value is an array containing
63 * - the result data (array)
64 * - the request (WebRequest)
65 * - the session data of the request (array)
66 * - if $appendModule is true, the Api module $module
67 *
68 * @param array $params
69 * @param array|null $session
70 * @param bool $appendModule
71 * @param User|null $user
72 * @param string|null $tokenType Set to a string like 'csrf' to send an
73 * appropriate token
74 *
75 * @return array
76 */
77 protected function doApiRequest( array $params, array $session = null,
78 $appendModule = false, User $user = null, $tokenType = null
79 ) {
80 global $wgRequest, $wgUser;
81
82 if ( is_null( $session ) ) {
83 // re-use existing global session by default
84 $session = $wgRequest->getSessionArray();
85 }
86
87 $sessionObj = SessionManager::singleton()->getEmptySession();
88
89 if ( $session !== null ) {
90 foreach ( $session as $key => $value ) {
91 $sessionObj->set( $key, $value );
92 }
93 }
94
95 // set up global environment
96 if ( $user ) {
97 $wgUser = $user;
98 }
99
100 if ( $tokenType !== null ) {
101 $params['token'] = ApiQueryTokens::getToken(
102 $wgUser, $sessionObj, ApiQueryTokens::getTokenTypeSalts()[$tokenType]
103 )->toString();
104 }
105
106 $wgRequest = new FauxRequest( $params, true, $sessionObj );
107 RequestContext::getMain()->setRequest( $wgRequest );
108 RequestContext::getMain()->setUser( $wgUser );
109 MediaWiki\Auth\AuthManager::resetCache();
110
111 // set up local environment
112 $context = $this->apiContext->newTestContext( $wgRequest, $wgUser );
113
114 $module = new ApiMain( $context, true );
115
116 // run it!
117 $module->execute();
118
119 // construct result
120 $results = [
121 $module->getResult()->getResultData( null, [ 'Strip' => 'all' ] ),
122 $context->getRequest(),
123 $context->getRequest()->getSessionArray()
124 ];
125
126 if ( $appendModule ) {
127 $results[] = $module;
128 }
129
130 return $results;
131 }
132
133 /**
134 * Convenience function to access the token parameter of doApiRequest()
135 * more succinctly.
136 *
137 * @param array $params Key-value API params
138 * @param array|null $session Session array
139 * @param User|null $user A User object for the context
140 * @param string $tokenType Which token type to pass
141 * @return array Result of the API call
142 */
143 protected function doApiRequestWithToken( array $params, array $session = null,
144 User $user = null, $tokenType = 'csrf'
145 ) {
146 return $this->doApiRequest( $params, $session, false, $user, $tokenType );
147 }
148
149 protected function doLogin( $testUser = 'sysop' ) {
150 if ( $testUser === null ) {
151 $testUser = static::getTestSysop();
152 } elseif ( is_string( $testUser ) && array_key_exists( $testUser, self::$users ) ) {
153 $testUser = self::$users[ $testUser ];
154 } elseif ( !$testUser instanceof TestUser ) {
155 throw new MWException( "Can not log in to undefined user $testUser" );
156 }
157
158 $data = $this->doApiRequest( [
159 'action' => 'login',
160 'lgname' => $testUser->getUser()->getName(),
161 'lgpassword' => $testUser->getPassword() ] );
162
163 $token = $data[0]['login']['token'];
164
165 $data = $this->doApiRequest(
166 [
167 'action' => 'login',
168 'lgtoken' => $token,
169 'lgname' => $testUser->getUser()->getName(),
170 'lgpassword' => $testUser->getPassword(),
171 ],
172 $data[2]
173 );
174
175 if ( $data[0]['login']['result'] === 'Success' ) {
176 // DWIM
177 global $wgUser;
178 $wgUser = $testUser->getUser();
179 RequestContext::getMain()->setUser( $wgUser );
180 }
181
182 return $data;
183 }
184
185 protected function getTokenList( TestUser $user, $session = null ) {
186 $data = $this->doApiRequest( [
187 'action' => 'tokens',
188 'type' => 'edit|delete|protect|move|block|unblock|watch'
189 ], $session, false, $user->getUser() );
190
191 if ( !array_key_exists( 'tokens', $data[0] ) ) {
192 throw new MWException( 'Api failed to return a token list' );
193 }
194
195 return $data[0]['tokens'];
196 }
197
198 protected static function getErrorFormatter() {
199 if ( self::$errorFormatter === null ) {
200 self::$errorFormatter = new ApiErrorFormatter(
201 new ApiResult( false ),
202 Language::factory( 'en' ),
203 'none'
204 );
205 }
206 return self::$errorFormatter;
207 }
208
209 public static function apiExceptionHasCode( ApiUsageException $ex, $code ) {
210 return (bool)array_filter(
211 self::getErrorFormatter()->arrayFromStatus( $ex->getStatusValue() ),
212 function ( $e ) use ( $code ) {
213 return is_array( $e ) && $e['code'] === $code;
214 }
215 );
216 }
217
218 /**
219 * @coversNothing
220 */
221 public function testApiTestGroup() {
222 $groups = PHPUnit_Util_Test::getGroups( static::class );
223 $constraint = PHPUnit_Framework_Assert::logicalOr(
224 $this->contains( 'medium' ),
225 $this->contains( 'large' )
226 );
227 $this->assertThat( $groups, $constraint,
228 'ApiTestCase::setUp can be slow, tests must be "medium" or "large"'
229 );
230 }
231 }