Merge "Add DeleteUnknownPreferences hook"
[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 * @throws ApiUsageException
72 * @return array
73 */
74 protected function doApiRequest( array $params, array $session = null,
75 $appendModule = false, User $user = null
76 ) {
77 global $wgRequest, $wgUser;
78
79 if ( is_null( $session ) ) {
80 // re-use existing global session by default
81 $session = $wgRequest->getSessionArray();
82 }
83
84 // set up global environment
85 if ( $user ) {
86 $wgUser = $user;
87 }
88
89 $wgRequest = new FauxRequest( $params, true, $session );
90 RequestContext::getMain()->setRequest( $wgRequest );
91 RequestContext::getMain()->setUser( $wgUser );
92 MediaWiki\Auth\AuthManager::resetCache();
93
94 // set up local environment
95 $context = $this->apiContext->newTestContext( $wgRequest, $wgUser );
96
97 $module = new ApiMain( $context, true );
98
99 // run it!
100 $module->execute();
101
102 // construct result
103 $results = [
104 $module->getResult()->getResultData( null, [ 'Strip' => 'all' ] ),
105 $context->getRequest(),
106 $context->getRequest()->getSessionArray()
107 ];
108
109 if ( $appendModule ) {
110 $results[] = $module;
111 }
112
113 return $results;
114 }
115
116 /**
117 * Add an edit token to the API request
118 * This is cheating a bit -- we grab a token in the correct format and then
119 * add it to the pseudo-session and to the request, without actually
120 * requesting a "real" edit token.
121 *
122 * @param array $params Key-value API params
123 * @param array|null $session Session array
124 * @param User|null $user A User object for the context
125 * @return array Result of the API call
126 * @throws Exception In case wsToken is not set in the session
127 */
128 protected function doApiRequestWithToken( array $params, array $session = null,
129 User $user = null
130 ) {
131 global $wgRequest;
132
133 if ( $session === null ) {
134 $session = $wgRequest->getSessionArray();
135 }
136
137 if ( isset( $session['wsToken'] ) && $session['wsToken'] ) {
138 // @todo Why does this directly mess with the session? Fix that.
139 // add edit token to fake session
140 $session['wsTokenSecrets']['default'] = $session['wsToken'];
141 // add token to request parameters
142 $timestamp = wfTimestamp();
143 $params['token'] = hash_hmac( 'md5', $timestamp, $session['wsToken'] ) .
144 dechex( $timestamp ) .
145 MediaWiki\Session\Token::SUFFIX;
146
147 return $this->doApiRequest( $params, $session, false, $user );
148 } else {
149 throw new Exception( "Session token not available" );
150 }
151 }
152
153 protected function doLogin( $testUser = 'sysop' ) {
154 if ( $testUser === null ) {
155 $testUser = static::getTestSysop();
156 } elseif ( is_string( $testUser ) && array_key_exists( $testUser, self::$users ) ) {
157 $testUser = self::$users[ $testUser ];
158 } elseif ( !$testUser instanceof TestUser ) {
159 throw new MWException( "Can not log in to undefined user $testUser" );
160 }
161
162 $data = $this->doApiRequest( [
163 'action' => 'login',
164 'lgname' => $testUser->getUser()->getName(),
165 'lgpassword' => $testUser->getPassword() ] );
166
167 $token = $data[0]['login']['token'];
168
169 $data = $this->doApiRequest(
170 [
171 'action' => 'login',
172 'lgtoken' => $token,
173 'lgname' => $testUser->getUser()->getName(),
174 'lgpassword' => $testUser->getPassword(),
175 ],
176 $data[2]
177 );
178
179 if ( $data[0]['login']['result'] === 'Success' ) {
180 // DWIM
181 global $wgUser;
182 $wgUser = $testUser->getUser();
183 RequestContext::getMain()->setUser( $wgUser );
184 }
185
186 return $data;
187 }
188
189 protected function getTokenList( TestUser $user, $session = null ) {
190 $data = $this->doApiRequest( [
191 'action' => 'tokens',
192 'type' => 'edit|delete|protect|move|block|unblock|watch'
193 ], $session, false, $user->getUser() );
194
195 if ( !array_key_exists( 'tokens', $data[0] ) ) {
196 throw new MWException( 'Api failed to return a token list' );
197 }
198
199 return $data[0]['tokens'];
200 }
201
202 protected static function getErrorFormatter() {
203 if ( self::$errorFormatter === null ) {
204 self::$errorFormatter = new ApiErrorFormatter(
205 new ApiResult( false ),
206 Language::factory( 'en' ),
207 'none'
208 );
209 }
210 return self::$errorFormatter;
211 }
212
213 public static function apiExceptionHasCode( ApiUsageException $ex, $code ) {
214 return (bool)array_filter(
215 self::getErrorFormatter()->arrayFromStatus( $ex->getStatusValue() ),
216 function ( $e ) use ( $code ) {
217 return is_array( $e ) && $e['code'] === $code;
218 }
219 );
220 }
221
222 /**
223 * @coversNothing
224 */
225 public function testApiTestGroup() {
226 $groups = PHPUnit_Util_Test::getGroups( static::class );
227 $constraint = PHPUnit_Framework_Assert::logicalOr(
228 $this->contains( 'medium' ),
229 $this->contains( 'large' )
230 );
231 $this->assertThat( $groups, $constraint,
232 'ApiTestCase::setUp can be slow, tests must be "medium" or "large"'
233 );
234 }
235 }