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