Test ApiUserrights
[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 if ( $tokenType === 'auto' ) {
103 $tokenType = ( new ApiMain() )->getModuleManager()
104 ->getModule( $params['action'], 'action' )->needsToken();
105 }
106 $params['token'] = ApiQueryTokens::getToken(
107 $wgUser, $sessionObj, ApiQueryTokens::getTokenTypeSalts()[$tokenType]
108 )->toString();
109 }
110
111 $wgRequest = new FauxRequest( $params, true, $sessionObj );
112 RequestContext::getMain()->setRequest( $wgRequest );
113 RequestContext::getMain()->setUser( $wgUser );
114 MediaWiki\Auth\AuthManager::resetCache();
115
116 // set up local environment
117 $context = $this->apiContext->newTestContext( $wgRequest, $wgUser );
118
119 $module = new ApiMain( $context, true );
120
121 // run it!
122 $module->execute();
123
124 // construct result
125 $results = [
126 $module->getResult()->getResultData( null, [ 'Strip' => 'all' ] ),
127 $context->getRequest(),
128 $context->getRequest()->getSessionArray()
129 ];
130
131 if ( $appendModule ) {
132 $results[] = $module;
133 }
134
135 return $results;
136 }
137
138 /**
139 * Convenience function to access the token parameter of doApiRequest()
140 * more succinctly.
141 *
142 * @param array $params Key-value API params
143 * @param array|null $session Session array
144 * @param User|null $user A User object for the context
145 * @param string $tokenType Which token type to pass
146 * @return array Result of the API call
147 */
148 protected function doApiRequestWithToken( array $params, array $session = null,
149 User $user = null, $tokenType = 'auto'
150 ) {
151 return $this->doApiRequest( $params, $session, false, $user, $tokenType );
152 }
153
154 protected function doLogin( $testUser = 'sysop' ) {
155 if ( $testUser === null ) {
156 $testUser = static::getTestSysop();
157 } elseif ( is_string( $testUser ) && array_key_exists( $testUser, self::$users ) ) {
158 $testUser = self::$users[ $testUser ];
159 } elseif ( !$testUser instanceof TestUser ) {
160 throw new MWException( "Can not log in to undefined user $testUser" );
161 }
162
163 $data = $this->doApiRequest( [
164 'action' => 'login',
165 'lgname' => $testUser->getUser()->getName(),
166 'lgpassword' => $testUser->getPassword() ] );
167
168 $token = $data[0]['login']['token'];
169
170 $data = $this->doApiRequest(
171 [
172 'action' => 'login',
173 'lgtoken' => $token,
174 'lgname' => $testUser->getUser()->getName(),
175 'lgpassword' => $testUser->getPassword(),
176 ],
177 $data[2]
178 );
179
180 if ( $data[0]['login']['result'] === 'Success' ) {
181 // DWIM
182 global $wgUser;
183 $wgUser = $testUser->getUser();
184 RequestContext::getMain()->setUser( $wgUser );
185 }
186
187 return $data;
188 }
189
190 protected function getTokenList( TestUser $user, $session = null ) {
191 $data = $this->doApiRequest( [
192 'action' => 'tokens',
193 'type' => 'edit|delete|protect|move|block|unblock|watch'
194 ], $session, false, $user->getUser() );
195
196 if ( !array_key_exists( 'tokens', $data[0] ) ) {
197 throw new MWException( 'Api failed to return a token list' );
198 }
199
200 return $data[0]['tokens'];
201 }
202
203 protected static function getErrorFormatter() {
204 if ( self::$errorFormatter === null ) {
205 self::$errorFormatter = new ApiErrorFormatter(
206 new ApiResult( false ),
207 Language::factory( 'en' ),
208 'none'
209 );
210 }
211 return self::$errorFormatter;
212 }
213
214 public static function apiExceptionHasCode( ApiUsageException $ex, $code ) {
215 return (bool)array_filter(
216 self::getErrorFormatter()->arrayFromStatus( $ex->getStatusValue() ),
217 function ( $e ) use ( $code ) {
218 return is_array( $e ) && $e['code'] === $code;
219 }
220 );
221 }
222
223 /**
224 * @coversNothing
225 */
226 public function testApiTestGroup() {
227 $groups = PHPUnit_Util_Test::getGroups( static::class );
228 $constraint = PHPUnit_Framework_Assert::logicalOr(
229 $this->contains( 'medium' ),
230 $this->contains( 'large' )
231 );
232 $this->assertThat( $groups, $constraint,
233 'ApiTestCase::setUp can be slow, tests must be "medium" or "large"'
234 );
235 }
236 }