Rename JsonUnserial… to JsonDeserial…
[mediawiki.git] / tests / phpunit / includes / api / ApiTestCase.php
blobc1a562e01832e24f81eb8323775c8335e222a1ad
1 <?php
3 namespace MediaWiki\Tests\Api;
5 use ApiBase;
6 use ApiErrorFormatter;
7 use ApiMain;
8 use ApiMessage;
9 use ApiQueryTokens;
10 use ApiResult;
11 use ApiUsageException;
12 use ArrayAccess;
13 use LogicException;
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;
27 abstract class ApiTestCase extends MediaWikiLangTestCase {
28 use MockAuthorityTrait;
30 protected static $apiUrl;
32 protected static $errorFormatter = null;
34 /**
35 * @var ApiTestContext
37 protected $apiContext;
39 protected function setUp(): void {
40 global $wgServer;
42 parent::setUp();
43 self::$apiUrl = $wgServer . wfScript( 'api' );
45 // HACK: Avoid creating test users in the DB if the test may not need them.
46 $getters = [
47 'sysop' => fn () => $this->getTestSysop(),
48 'uploader' => fn () => $this->getTestUser(),
50 $fakeUserArray = new class ( $getters ) implements ArrayAccess {
51 private array $getters;
52 private array $extraUsers = [];
54 public function __construct( array $getters ) {
55 $this->getters = $getters;
58 public function offsetExists( $offset ): bool {
59 return isset( $this->getters[$offset] ) || isset( $this->extraUsers[$offset] );
62 #[ReturnTypeWillChange]
63 public function offsetGet( $offset ) {
64 if ( isset( $this->getters[$offset] ) ) {
65 return ( $this->getters[$offset] )();
67 if ( isset( $this->extraUsers[$offset] ) ) {
68 return $this->extraUsers[$offset];
70 throw new LogicException( "Requested unknown user $offset" );
73 public function offsetSet( $offset, $value ): void {
74 $this->extraUsers[$offset] = $value;
77 public function offsetUnset( $offset ): void {
78 unset( $this->getters[$offset] );
79 unset( $this->extraUsers[$offset] );
83 self::$users = $fakeUserArray;
85 $this->setRequest( new FauxRequest( [] ) );
87 $this->apiContext = new ApiTestContext();
90 protected function tearDown(): void {
91 // Avoid leaking session over tests
92 SessionManager::getGlobalSession()->clear();
94 ApiBase::clearCacheForTest();
96 parent::tearDown();
99 /**
100 * Does the API request and returns the result.
102 * @param array $params
103 * @param array|null $session
104 * @param bool $appendModule
105 * @param Authority|null $performer
106 * @param string|null $tokenType Set to a string like 'csrf' to send an
107 * appropriate token
108 * @param string|null $paramPrefix Prefix to prepend to parameters
109 * @return array List of:
110 * - the result data (array)
111 * - the request (WebRequest)
112 * - the session data of the request (array)
113 * - if $appendModule is true, the Api module $module
114 * @throws ApiUsageException
116 protected function doApiRequest( array $params, array $session = null,
117 $appendModule = false, Authority $performer = null, $tokenType = null,
118 $paramPrefix = null
120 global $wgRequest;
122 // re-use existing global session by default
123 $session ??= $wgRequest->getSessionArray();
125 $sessionObj = SessionManager::singleton()->getEmptySession();
127 if ( $session !== null ) {
128 foreach ( $session as $key => $value ) {
129 $sessionObj->set( $key, $value );
133 // set up global environment
134 if ( !$performer && !$this->needsDB() ) {
135 $performer = $this->mockRegisteredUltimateAuthority();
137 if ( $performer ) {
138 $legacyUser = $this->getServiceContainer()->getUserFactory()->newFromAuthority( $performer );
139 $contextUser = $legacyUser;
140 // Clone the user object, because something in Session code will replace its user with "Unknown user"
141 // if it doesn't exist. But that'll also change $contextUser, and the token won't match (T341953).
142 $sessionUser = clone $contextUser;
143 } else {
144 $contextUser = $this->getTestSysop()->getUser();
145 $performer = $contextUser;
146 $sessionUser = $contextUser;
149 $sessionObj->setUser( $sessionUser );
150 if ( $tokenType !== null ) {
151 if ( $tokenType === 'auto' ) {
152 $tokenType = ( new ApiMain() )->getModuleManager()
153 ->getModule( $params['action'], 'action' )->needsToken();
155 if ( $tokenType !== false ) {
156 $params['token'] = ApiQueryTokens::getToken(
157 $contextUser,
158 $sessionObj,
159 ApiQueryTokens::getTokenTypeSalts()[$tokenType]
160 )->toString();
164 // prepend parameters with prefix
165 if ( $paramPrefix !== null && $paramPrefix !== '' ) {
166 $prefixedParams = [];
167 foreach ( $params as $key => $value ) {
168 $prefixedParams[$paramPrefix . $key] = $value;
170 $params = $prefixedParams;
173 $wgRequest = $this->buildFauxRequest( $params, $sessionObj );
174 RequestContext::getMain()->setRequest( $wgRequest );
175 RequestContext::getMain()->setAuthority( $performer );
177 // set up local environment
178 $context = $this->apiContext->newTestContext( $wgRequest, $performer );
180 $module = new ApiMain( $context, true );
182 // run it!
183 $module->execute();
185 // construct result
186 $results = [
187 $module->getResult()->getResultData( null, [ 'Strip' => 'all' ] ),
188 $context->getRequest(),
189 $context->getRequest()->getSessionArray()
192 if ( $appendModule ) {
193 $results[] = $module;
196 return $results;
200 * @since 1.37
201 * @param array $params
202 * @param Session|array|null $session
203 * @return FauxRequest
205 protected function buildFauxRequest( $params, $session ) {
206 return new FauxRequest( $params, true, $session );
210 * Convenience function to access the token parameter of doApiRequest()
211 * more succinctly.
213 * @param array $params Key-value API params
214 * @param array|null $session Session array
215 * @param Authority|null $performer A User object for the context
216 * @param string $tokenType Which token type to pass
217 * @param string|null $paramPrefix Prefix to prepend to parameters
218 * @return array Result of the API call
220 protected function doApiRequestWithToken( array $params, array $session = null,
221 Authority $performer = null, $tokenType = 'auto', $paramPrefix = null
223 return $this->doApiRequest( $params, $session, false, $performer, $tokenType, $paramPrefix );
226 protected static function getErrorFormatter() {
227 self::$errorFormatter ??= new ApiErrorFormatter(
228 new ApiResult( false ),
229 MediaWikiServices::getInstance()->getLanguageFactory()->getLanguage( 'en' ),
230 'none'
232 return self::$errorFormatter;
235 public static function apiExceptionHasCode( ApiUsageException $ex, $code ) {
236 return (bool)array_filter(
237 self::getErrorFormatter()->arrayFromStatus( $ex->getStatusValue() ),
238 static function ( $e ) use ( $code ) {
239 return is_array( $e ) && $e['code'] === $code;
245 * Expect an ApiUsageException to be thrown with the given parameters, which are the same as
246 * ApiUsageException::newWithMessage()'s parameters. This allows checking for an exception
247 * whose text is given by a message key instead of text, so as not to hard-code the message's
248 * text into test code.
250 * @deprecated since 1.43; use expectApiErrorCode() instead, it's better to test error codes than messages
251 * @param string|array|Message $msg
252 * @param string|null $code
253 * @param array|null $data
254 * @param int $httpCode
256 protected function setExpectedApiException(
257 $msg, $code = null, array $data = null, $httpCode = 0
259 $expected = ApiUsageException::newWithMessage( null, $msg, $code, $data, $httpCode );
260 $this->expectException( ApiUsageException::class );
261 $this->expectExceptionMessage( $expected->getMessage() );
264 private ?string $expectedApiErrorCode;
267 * Expect an ApiUsageException that results in the given API error code to be thrown.
269 * Note that you can't mix this method with standard PHPUnit expectException() methods,
270 * as PHPUnit will catch the exception and prevent us from testing it.
272 * @since 1.41
273 * @param string $expectedCode
275 protected function expectApiErrorCode( string $expectedCode ) {
276 $this->expectedApiErrorCode = $expectedCode;
280 * Assert that an ApiUsageException will result in the given API error code being outputted.
282 * @since 1.41
283 * @param string $expectedCode
284 * @param ApiUsageException $exception
285 * @param string $message
287 protected function assertApiErrorCode( string $expectedCode, ApiUsageException $exception, string $message = '' ) {
288 $constraint = new class( $expectedCode ) extends Constraint {
289 private string $expectedApiErrorCode;
291 public function __construct( string $expected ) {
292 $this->expectedApiErrorCode = $expected;
295 public function toString(): string {
296 return 'API error code is ';
299 private function getApiErrorCode( $other ) {
300 if ( !$other instanceof ApiUsageException ) {
301 return null;
303 $errors = $other->getStatusValue()->getMessages();
304 if ( count( $errors ) === 0 ) {
305 return '(no error)';
306 } elseif ( count( $errors ) > 1 ) {
307 return '(multiple errors)';
309 return ApiMessage::create( $errors[0] )->getApiCode();
312 protected function matches( $other ): bool {
313 return $this->getApiErrorCode( $other ) === $this->expectedApiErrorCode;
316 protected function failureDescription( $other ): string {
317 return sprintf(
318 '%s is equal to expected API error code %s',
319 $this->exporter()->export( $this->getApiErrorCode( $other ) ),
320 $this->exporter()->export( $this->expectedApiErrorCode )
325 $this->assertThat( $exception, $constraint, $message );
329 * @inheritDoc
331 * Adds support for expectApiErrorCode().
333 protected function runTest() {
334 try {
335 $testResult = parent::runTest();
337 } catch ( ApiUsageException $exception ) {
338 if ( !isset( $this->expectedApiErrorCode ) ) {
339 throw $exception;
342 $this->assertApiErrorCode( $this->expectedApiErrorCode, $exception );
344 return null;
347 if ( !isset( $this->expectedApiErrorCode ) ) {
348 return $testResult;
351 throw new AssertionFailedError(
352 sprintf(
353 'Failed asserting that exception with API error code "%s" is thrown',
354 $this->expectedApiErrorCode
360 class_alias( ApiTestCase::class, 'ApiTestCase' );