Merge "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 * @throws ApiUsageException
76 * @return array
77 */
78 protected function doApiRequest( array $params, array $session = null,
79 $appendModule = false, User $user = null, $tokenType = null
80 ) {
81 global $wgRequest, $wgUser;
82
83 if ( is_null( $session ) ) {
84 // re-use existing global session by default
85 $session = $wgRequest->getSessionArray();
86 }
87
88 $sessionObj = SessionManager::singleton()->getEmptySession();
89
90 if ( $session !== null ) {
91 foreach ( $session as $key => $value ) {
92 $sessionObj->set( $key, $value );
93 }
94 }
95
96 // set up global environment
97 if ( $user ) {
98 $wgUser = $user;
99 }
100
101 if ( $tokenType !== null ) {
102 $params['token'] = ApiQueryTokens::getToken(
103 $wgUser, $sessionObj, ApiQueryTokens::getTokenTypeSalts()[$tokenType]
104 )->toString();
105 }
106
107 $wgRequest = new FauxRequest( $params, true, $sessionObj );
108 RequestContext::getMain()->setRequest( $wgRequest );
109 RequestContext::getMain()->setUser( $wgUser );
110 MediaWiki\Auth\AuthManager::resetCache();
111
112 // set up local environment
113 $context = $this->apiContext->newTestContext( $wgRequest, $wgUser );
114
115 $module = new ApiMain( $context, true );
116
117 // run it!
118 $module->execute();
119
120 // construct result
121 $results = [
122 $module->getResult()->getResultData( null, [ 'Strip' => 'all' ] ),
123 $context->getRequest(),
124 $context->getRequest()->getSessionArray()
125 ];
126
127 if ( $appendModule ) {
128 $results[] = $module;
129 }
130
131 return $results;
132 }
133
134 /**
135 * Convenience function to access the token parameter of doApiRequest()
136 * more succinctly.
137 *
138 * @param array $params Key-value API params
139 * @param array|null $session Session array
140 * @param User|null $user A User object for the context
141 * @param string $tokenType Which token type to pass
142 * @return array Result of the API call
143 */
144 protected function doApiRequestWithToken( array $params, array $session = null,
145 User $user = null, $tokenType = 'csrf'
146 ) {
147 return $this->doApiRequest( $params, $session, false, $user, $tokenType );
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->getUser()->getName(),
162 'lgpassword' => $testUser->getPassword() ] );
163
164 $token = $data[0]['login']['token'];
165
166 $data = $this->doApiRequest(
167 [
168 'action' => 'login',
169 'lgtoken' => $token,
170 'lgname' => $testUser->getUser()->getName(),
171 'lgpassword' => $testUser->getPassword(),
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( TestUser $user, $session = null ) {
187 $data = $this->doApiRequest( [
188 'action' => 'tokens',
189 'type' => 'edit|delete|protect|move|block|unblock|watch'
190 ], $session, false, $user->getUser() );
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 protected static function getErrorFormatter() {
200 if ( self::$errorFormatter === null ) {
201 self::$errorFormatter = new ApiErrorFormatter(
202 new ApiResult( false ),
203 Language::factory( 'en' ),
204 'none'
205 );
206 }
207 return self::$errorFormatter;
208 }
209
210 public static function apiExceptionHasCode( ApiUsageException $ex, $code ) {
211 return (bool)array_filter(
212 self::getErrorFormatter()->arrayFromStatus( $ex->getStatusValue() ),
213 function ( $e ) use ( $code ) {
214 return is_array( $e ) && $e['code'] === $code;
215 }
216 );
217 }
218
219 /**
220 * @coversNothing
221 */
222 public function testApiTestGroup() {
223 $groups = PHPUnit_Util_Test::getGroups( static::class );
224 $constraint = PHPUnit_Framework_Assert::logicalOr(
225 $this->contains( 'medium' ),
226 $this->contains( 'large' )
227 );
228 $this->assertThat( $groups, $constraint,
229 'ApiTestCase::setUp can be slow, tests must be "medium" or "large"'
230 );
231 }
232 }