Merge "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 * Revision-deletes a revision.
61 *
62 * @param Revision|int $rev Revision to delete
63 * @param array $value Keys are Revision::DELETED_* flags. Values are 1 to set the bit, 0 to
64 * clear, -1 to leave alone. (All other values also clear the bit.)
65 * @param string $comment Deletion comment
66 */
67 protected function revisionDelete(
68 $rev, array $value = [ Revision::DELETED_TEXT => 1 ], $comment = ''
69 ) {
70 if ( is_int( $rev ) ) {
71 $rev = Revision::newFromId( $rev );
72 }
73 RevisionDeleter::createList(
74 'revision', RequestContext::getMain(), $rev->getTitle(), [ $rev->getId() ]
75 )->setVisibility( [
76 'value' => $value,
77 'comment' => $comment,
78 ] );
79 }
80
81 /**
82 * Does the API request and returns the result.
83 *
84 * The returned value is an array containing
85 * - the result data (array)
86 * - the request (WebRequest)
87 * - the session data of the request (array)
88 * - if $appendModule is true, the Api module $module
89 *
90 * @param array $params
91 * @param array|null $session
92 * @param bool $appendModule
93 * @param User|null $user
94 * @param string|null $tokenType Set to a string like 'csrf' to send an
95 * appropriate token
96 *
97 * @throws ApiUsageException
98 * @return array
99 */
100 protected function doApiRequest( array $params, array $session = null,
101 $appendModule = false, User $user = null, $tokenType = null
102 ) {
103 global $wgRequest, $wgUser;
104
105 if ( is_null( $session ) ) {
106 // re-use existing global session by default
107 $session = $wgRequest->getSessionArray();
108 }
109
110 $sessionObj = SessionManager::singleton()->getEmptySession();
111
112 if ( $session !== null ) {
113 foreach ( $session as $key => $value ) {
114 $sessionObj->set( $key, $value );
115 }
116 }
117
118 // set up global environment
119 if ( $user ) {
120 $wgUser = $user;
121 }
122
123 if ( $tokenType !== null ) {
124 if ( $tokenType === 'auto' ) {
125 $tokenType = ( new ApiMain() )->getModuleManager()
126 ->getModule( $params['action'], 'action' )->needsToken();
127 }
128 $params['token'] = ApiQueryTokens::getToken(
129 $wgUser, $sessionObj, ApiQueryTokens::getTokenTypeSalts()[$tokenType]
130 )->toString();
131 }
132
133 $wgRequest = new FauxRequest( $params, true, $sessionObj );
134 RequestContext::getMain()->setRequest( $wgRequest );
135 RequestContext::getMain()->setUser( $wgUser );
136 MediaWiki\Auth\AuthManager::resetCache();
137
138 // set up local environment
139 $context = $this->apiContext->newTestContext( $wgRequest, $wgUser );
140
141 $module = new ApiMain( $context, true );
142
143 // run it!
144 $module->execute();
145
146 // construct result
147 $results = [
148 $module->getResult()->getResultData( null, [ 'Strip' => 'all' ] ),
149 $context->getRequest(),
150 $context->getRequest()->getSessionArray()
151 ];
152
153 if ( $appendModule ) {
154 $results[] = $module;
155 }
156
157 return $results;
158 }
159
160 /**
161 * Convenience function to access the token parameter of doApiRequest()
162 * more succinctly.
163 *
164 * @param array $params Key-value API params
165 * @param array|null $session Session array
166 * @param User|null $user A User object for the context
167 * @param string $tokenType Which token type to pass
168 * @return array Result of the API call
169 */
170 protected function doApiRequestWithToken( array $params, array $session = null,
171 User $user = null, $tokenType = 'auto'
172 ) {
173 return $this->doApiRequest( $params, $session, false, $user, $tokenType );
174 }
175
176 /**
177 * Previously this would do API requests to log in, as well as setting $wgUser and the request
178 * context's user. The API requests are unnecessary, and the global-setting is unwanted, so
179 * this method should not be called. Instead, pass appropriate User values directly to
180 * functions that need them. For functions that still rely on $wgUser, set that directly. If
181 * you just want to log in the test sysop user, don't do anything -- that's the default.
182 *
183 * @param TestUser|string $testUser Object, or key to self::$users such as 'sysop' or 'uploader'
184 * @deprecated since 1.31
185 */
186 protected function doLogin( $testUser = null ) {
187 global $wgUser;
188
189 if ( $testUser === null ) {
190 $testUser = static::getTestSysop();
191 } elseif ( is_string( $testUser ) && array_key_exists( $testUser, self::$users ) ) {
192 $testUser = self::$users[$testUser];
193 } elseif ( !$testUser instanceof TestUser ) {
194 throw new MWException( "Can't log in to undefined user $testUser" );
195 }
196
197 $wgUser = $testUser->getUser();
198 RequestContext::getMain()->setUser( $wgUser );
199 }
200
201 protected function getTokenList( TestUser $user, $session = null ) {
202 $data = $this->doApiRequest( [
203 'action' => 'tokens',
204 'type' => 'edit|delete|protect|move|block|unblock|watch'
205 ], $session, false, $user->getUser() );
206
207 if ( !array_key_exists( 'tokens', $data[0] ) ) {
208 throw new MWException( 'Api failed to return a token list' );
209 }
210
211 return $data[0]['tokens'];
212 }
213
214 protected static function getErrorFormatter() {
215 if ( self::$errorFormatter === null ) {
216 self::$errorFormatter = new ApiErrorFormatter(
217 new ApiResult( false ),
218 Language::factory( 'en' ),
219 'none'
220 );
221 }
222 return self::$errorFormatter;
223 }
224
225 public static function apiExceptionHasCode( ApiUsageException $ex, $code ) {
226 return (bool)array_filter(
227 self::getErrorFormatter()->arrayFromStatus( $ex->getStatusValue() ),
228 function ( $e ) use ( $code ) {
229 return is_array( $e ) && $e['code'] === $code;
230 }
231 );
232 }
233
234 /**
235 * @coversNothing
236 */
237 public function testApiTestGroup() {
238 $groups = PHPUnit_Util_Test::getGroups( static::class );
239 $constraint = PHPUnit_Framework_Assert::logicalOr(
240 $this->contains( 'medium' ),
241 $this->contains( 'large' )
242 );
243 $this->assertThat( $groups, $constraint,
244 'ApiTestCase::setUp can be slow, tests must be "medium" or "large"'
245 );
246 }
247 }