Debian Codegraph @

tests/phpunit/includes/api/ApiTestCase.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\Tests\Api;
4
5 use ArrayAccess;
6 use LogicException;
7 use MediaWiki\Api\ApiBase;
8 use MediaWiki\Api\ApiErrorFormatter;
9 use MediaWiki\Api\ApiMain;
10 use MediaWiki\Api\ApiMessage;
11 use MediaWiki\Api\ApiQueryTokens;
12 use MediaWiki\Api\ApiResult;
13 use MediaWiki\Api\ApiUsageException;
14 use MediaWiki\Context\RequestContext;
15 use MediaWiki\MediaWikiServices;
16 use MediaWiki\Message\Message;
17 use MediaWiki\Permissions\Authority;
18 use MediaWiki\Request\FauxRequest;
19 use MediaWiki\Session\Session;
20 use MediaWiki\Session\SessionManager;
21 use MediaWiki\Tests\Unit\Permissions\MockAuthorityTrait;
22 use MediaWikiLangTestCase;
23 use PHPUnit\Framework\AssertionFailedError;
24 use PHPUnit\Framework\Constraint\Constraint;
25 use ReturnTypeWillChange;
26
27 abstract class ApiTestCase extends MediaWikiLangTestCase {
28 use MockAuthorityTrait;
29
30 /** @var string */
31 protected static $apiUrl;
32
33 /** @var ApiErrorFormatter|null */
34 protected static $errorFormatter = null;
35
36 /**
37 * @var ApiTestContext
38 */
39 protected $apiContext;
40
41 protected function setUp(): void {
42 global $wgServer;
43
44 parent::setUp();
45 self::$apiUrl = $wgServer . wfScript( 'api' );
46
47 // HACK: Avoid creating test users in the DB if the test may not need them.
48 $getters = [
49 'sysop' => fn () => $this->getTestSysop(),
50 'uploader' => fn () => $this->getTestUser(),
51 ];
52 $fakeUserArray = new class ( $getters ) implements ArrayAccess {
53 private array $getters;
54 private array $extraUsers = [];
55
56 public function __construct( array $getters ) {
57 $this->getters = $getters;
58 }
59
60 public function offsetExists( $offset ): bool {
61 return isset( $this->getters[$offset] ) || isset( $this->extraUsers[$offset] );
62 }
63
64 #[ReturnTypeWillChange]
65 public function offsetGet( $offset ) {
66 if ( isset( $this->getters[$offset] ) ) {
67 return ( $this->getters[$offset] )();
68 }
69 if ( isset( $this->extraUsers[$offset] ) ) {
70 return $this->extraUsers[$offset];
71 }
72 throw new LogicException( "Requested unknown user $offset" );
73 }
74
75 public function offsetSet( $offset, $value ): void {
76 $this->extraUsers[$offset] = $value;
77 }
78
79 public function offsetUnset( $offset ): void {
80 unset( $this->getters[$offset] );
81 unset( $this->extraUsers[$offset] );
82 }
83 };
84
85 self::$users = $fakeUserArray;
86
87 $this->setRequest( new FauxRequest( [] ) );
88
89 $this->apiContext = new ApiTestContext();
90 }
91
92 protected function tearDown(): void {
93 // Avoid leaking session over tests
94 SessionManager::getGlobalSession()->clear();
95
96 ApiBase::clearCacheForTest();
97
98 parent::tearDown();
99 }
100
101 /**
102 * Does the API request and returns the result.
103 *
104 * @param array $params
105 * @param array|null $session
106 * @param bool $appendModule
107 * @param Authority|null $performer
108 * @param string|null $tokenType Set to a string like 'csrf' to send an
109 * appropriate token
110 * @param string|null $paramPrefix Prefix to prepend to parameters
111 * @return array List of:
112 * - the result data (array)
113 * - the request (WebRequest)
114 * - the session data of the request (array)
115 * - if $appendModule is true, the Api module $module
116 * @throws ApiUsageException
117 */
118 protected function doApiRequest( array $params, ?array $session = null,
119 $appendModule = false, ?Authority $performer = null, $tokenType = null,
120 $paramPrefix = null
121 ) {
122 global $wgRequest;
123
124 // re-use existing global session by default
125 $session ??= $wgRequest->getSessionArray();
126
127 $sessionObj = SessionManager::singleton()->getEmptySession();
128
129 if ( $session !== null ) {
130 foreach ( $session as $key => $value ) {
131 $sessionObj->set( $key, $value );
132 }
133 }
134
135 // set up global environment
136 if ( !$performer && !$this->needsDB() ) {
137 $performer = $this->mockRegisteredUltimateAuthority();
138 }
139 if ( $performer ) {
140 $legacyUser = $this->getServiceContainer()->getUserFactory()->newFromAuthority( $performer );
141 $contextUser = $legacyUser;
142 // Clone the user object, because something in Session code will replace its user with "Unknown user"
143 // if it doesn't exist. But that'll also change $contextUser, and the token won't match (T341953).
144 $sessionUser = clone $contextUser;
145 } else {
146 $contextUser = $this->getTestSysop()->getUser();
147 $performer = $contextUser;
148 $sessionUser = $contextUser;
149 }
150
151 $sessionObj->setUser( $sessionUser );
152 if ( $tokenType !== null ) {
153 if ( $tokenType === 'auto' ) {
154 $tokenType = ( new ApiMain() )->getModuleManager()
155 ->getModule( $params['action'], 'action' )->needsToken();
156 }
157 if ( $tokenType !== false ) {
158 $params['token'] = ApiQueryTokens::getToken(
159 $contextUser,
160 $sessionObj,
161 ApiQueryTokens::getTokenTypeSalts()[$tokenType]
162 )->toString();
163 }
164 }
165
166 // prepend parameters with prefix
167 if ( $paramPrefix !== null && $paramPrefix !== '' ) {
168 $prefixedParams = [];
169 foreach ( $params as $key => $value ) {
170 $prefixedParams[$paramPrefix . $key] = $value;
171 }
172 $params = $prefixedParams;
173 }
174
175 $wgRequest = $this->buildFauxRequest( $params, $sessionObj );
176 RequestContext::getMain()->setRequest( $wgRequest );
177 RequestContext::getMain()->setAuthority( $performer );
178 RequestContext::getMain()->setUser( $sessionUser );
179
180 // set up local environment
181 $context = $this->apiContext->newTestContext( $wgRequest, $performer );
182
183 $module = new ApiMain( $context, true );
184
185 // run it!
186 $module->execute();
187
188 // construct result
189 $results = [
190 $module->getResult()->getResultData( null, [ 'Strip' => 'all' ] ),
191 $context->getRequest(),
192 $context->getRequest()->getSessionArray()
193 ];
194
195 if ( $appendModule ) {
196 $results[] = $module;
197 }
198
199 return $results;
200 }
201
202 /**
203 * @since 1.37
204 * @param array $params
205 * @param Session|array|null $session
206 * @return FauxRequest
207 */
208 protected function buildFauxRequest( $params, $session ) {
209 return new FauxRequest( $params, true, $session );
210 }
211
212 /**
213 * Convenience function to access the token parameter of doApiRequest()
214 * more succinctly.
215 *
216 * @param array $params Key-value API params
217 * @param array|null $session Session array
218 * @param Authority|null $performer A User object for the context
219 * @param string $tokenType Which token type to pass
220 * @param string|null $paramPrefix Prefix to prepend to parameters
221 * @return array Result of the API call
222 */
223 protected function doApiRequestWithToken( array $params, ?array $session = null,
224 ?Authority $performer = null, $tokenType = 'auto', $paramPrefix = null
225 ) {
226 return $this->doApiRequest( $params, $session, false, $performer, $tokenType, $paramPrefix );
227 }
228
229 protected static function getErrorFormatter() {
230 self::$errorFormatter ??= new ApiErrorFormatter(
231 new ApiResult( false ),
232 MediaWikiServices::getInstance()->getLanguageFactory()->getLanguage( 'en' ),
233 'none'
234 );
235 return self::$errorFormatter;
236 }
237
238 public static function apiExceptionHasCode( ApiUsageException $ex, $code ) {
239 return (bool)array_filter(
240 self::getErrorFormatter()->arrayFromStatus( $ex->getStatusValue() ),
241 static function ( $e ) use ( $code ) {
242 return is_array( $e ) && $e['code'] === $code;
243 }
244 );
245 }
246
247 /**
248 * Expect an ApiUsageException to be thrown with the given parameters, which are the same as
249 * ApiUsageException::newWithMessage()'s parameters. This allows checking for an exception
250 * whose text is given by a message key instead of text, so as not to hard-code the message's
251 * text into test code.
252 *
253 * @deprecated since 1.43; use expectApiErrorCode() instead, it's better to test error codes than messages
254 * @param string|array|Message $msg
255 * @param string|null $code
256 * @param array|null $data
257 * @param int $httpCode
258 */
259 protected function setExpectedApiException(
260 $msg, $code = null, ?array $data = null, $httpCode = 0
261 ) {
262 $expected = ApiUsageException::newWithMessage( null, $msg, $code, $data, $httpCode );
263 $this->expectException( ApiUsageException::class );
264 $this->expectExceptionMessage( $expected->getMessage() );
265 }
266
267 private ?string $expectedApiErrorCode;
268
269 /**
270 * Expect an ApiUsageException that results in the given API error code to be thrown.
271 *
272 * Note that you can't mix this method with standard PHPUnit expectException() methods,
273 * as PHPUnit will catch the exception and prevent us from testing it.
274 *
275 * @since 1.41
276 * @param string $expectedCode
277 */
278 protected function expectApiErrorCode( string $expectedCode ) {
279 $this->expectedApiErrorCode = $expectedCode;
280 }
281
282 /**
283 * Assert that an ApiUsageException will result in the given API error code being outputted.
284 *
285 * @since 1.41
286 * @param string $expectedCode
287 * @param ApiUsageException $exception
288 * @param string $message
289 */
290 protected function assertApiErrorCode( string $expectedCode, ApiUsageException $exception, string $message = '' ) {
291 $constraint = new class( $expectedCode ) extends Constraint {
292 private string $expectedApiErrorCode;
293
294 public function __construct( string $expected ) {
295 $this->expectedApiErrorCode = $expected;
296 }
297
298 public function toString(): string {
299 return 'API error code is ';
300 }
301
302 private function getApiErrorCode( $other ) {
303 if ( !$other instanceof ApiUsageException ) {
304 return null;
305 }
306 $errors = $other->getStatusValue()->getMessages();
307 if ( count( $errors ) === 0 ) {
308 return '(no error)';
309 } elseif ( count( $errors ) > 1 ) {
310 return '(multiple errors)';
311 }
312 return ApiMessage::create( $errors[0] )->getApiCode();
313 }
314
315 protected function matches( $other ): bool {
316 return $this->getApiErrorCode( $other ) === $this->expectedApiErrorCode;
317 }
318
319 protected function failureDescription( $other ): string {
320 return sprintf(
321 '%s is equal to expected API error code %s',
322 $this->exporter()->export( $this->getApiErrorCode( $other ) ),
323 $this->exporter()->export( $this->expectedApiErrorCode )
324 );
325 }
326 };
327
328 $this->assertThat( $exception, $constraint, $message );
329 }
330
331 /**
332 * @inheritDoc
333 *
334 * Adds support for expectApiErrorCode().
335 */
336 protected function runTest() {
337 try {
338 $testResult = parent::runTest();
339
340 } catch ( ApiUsageException $exception ) {
341 if ( !isset( $this->expectedApiErrorCode ) ) {
342 throw $exception;
343 }
344
345 $this->assertApiErrorCode( $this->expectedApiErrorCode, $exception );
346
347 return null;
348 }
349
350 if ( !isset( $this->expectedApiErrorCode ) ) {
351 return $testResult;
352 }
353
354 throw new AssertionFailedError(
355 sprintf(
356 'Failed asserting that exception with API error code "%s" is thrown',
357 $this->expectedApiErrorCode
358 )
359 );
360 }
361 }
362
363 /** @deprecated class alias since 1.42 */
364 class_alias( ApiTestCase::class, 'ApiTestCase' );