Improve test coverage for ApiParse
[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 $params['token'] = ApiQueryTokens::getToken(
125 $wgUser, $sessionObj, ApiQueryTokens::getTokenTypeSalts()[$tokenType]
126 )->toString();
127 }
128
129 $wgRequest = new FauxRequest( $params, true, $sessionObj );
130 RequestContext::getMain()->setRequest( $wgRequest );
131 RequestContext::getMain()->setUser( $wgUser );
132 MediaWiki\Auth\AuthManager::resetCache();
133
134 // set up local environment
135 $context = $this->apiContext->newTestContext( $wgRequest, $wgUser );
136
137 $module = new ApiMain( $context, true );
138
139 // run it!
140 $module->execute();
141
142 // construct result
143 $results = [
144 $module->getResult()->getResultData( null, [ 'Strip' => 'all' ] ),
145 $context->getRequest(),
146 $context->getRequest()->getSessionArray()
147 ];
148
149 if ( $appendModule ) {
150 $results[] = $module;
151 }
152
153 return $results;
154 }
155
156 /**
157 * Convenience function to access the token parameter of doApiRequest()
158 * more succinctly.
159 *
160 * @param array $params Key-value API params
161 * @param array|null $session Session array
162 * @param User|null $user A User object for the context
163 * @param string $tokenType Which token type to pass
164 * @return array Result of the API call
165 */
166 protected function doApiRequestWithToken( array $params, array $session = null,
167 User $user = null, $tokenType = 'csrf'
168 ) {
169 return $this->doApiRequest( $params, $session, false, $user, $tokenType );
170 }
171
172 /**
173 * Previously this would do API requests to log in, as well as setting $wgUser and the request
174 * context's user. The API requests are unnecessary, and the global-setting is unwanted, so
175 * this method should not be called. Instead, pass appropriate User values directly to
176 * functions that need them. For functions that still rely on $wgUser, set that directly. If
177 * you just want to log in the test sysop user, don't do anything -- that's the default.
178 *
179 * @param TestUser|string $testUser Object, or key to self::$users such as 'sysop' or 'uploader'
180 * @deprecated since 1.31
181 */
182 protected function doLogin( $testUser = null ) {
183 global $wgUser;
184
185 if ( $testUser === null ) {
186 $testUser = static::getTestSysop();
187 } elseif ( is_string( $testUser ) && array_key_exists( $testUser, self::$users ) ) {
188 $testUser = self::$users[$testUser];
189 } elseif ( !$testUser instanceof TestUser ) {
190 throw new MWException( "Can't log in to undefined user $testUser" );
191 }
192
193 $wgUser = $testUser->getUser();
194 RequestContext::getMain()->setUser( $wgUser );
195 }
196
197 protected function getTokenList( TestUser $user, $session = null ) {
198 $data = $this->doApiRequest( [
199 'action' => 'tokens',
200 'type' => 'edit|delete|protect|move|block|unblock|watch'
201 ], $session, false, $user->getUser() );
202
203 if ( !array_key_exists( 'tokens', $data[0] ) ) {
204 throw new MWException( 'Api failed to return a token list' );
205 }
206
207 return $data[0]['tokens'];
208 }
209
210 protected static function getErrorFormatter() {
211 if ( self::$errorFormatter === null ) {
212 self::$errorFormatter = new ApiErrorFormatter(
213 new ApiResult( false ),
214 Language::factory( 'en' ),
215 'none'
216 );
217 }
218 return self::$errorFormatter;
219 }
220
221 public static function apiExceptionHasCode( ApiUsageException $ex, $code ) {
222 return (bool)array_filter(
223 self::getErrorFormatter()->arrayFromStatus( $ex->getStatusValue() ),
224 function ( $e ) use ( $code ) {
225 return is_array( $e ) && $e['code'] === $code;
226 }
227 );
228 }
229
230 /**
231 * @coversNothing
232 */
233 public function testApiTestGroup() {
234 $groups = PHPUnit_Util_Test::getGroups( static::class );
235 $constraint = PHPUnit_Framework_Assert::logicalOr(
236 $this->contains( 'medium' ),
237 $this->contains( 'large' )
238 );
239 $this->assertThat( $groups, $constraint,
240 'ApiTestCase::setUp can be slow, tests must be "medium" or "large"'
241 );
242 }
243 }