3 namespace MediaWiki\Tests\Api
;
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
;
27 abstract class ApiTestCase
extends MediaWikiLangTestCase
{
28 use MockAuthorityTrait
;
31 protected static $apiUrl;
33 /** @var ApiErrorFormatter|null */
34 protected static $errorFormatter = null;
39 protected $apiContext;
41 protected function setUp(): void
{
45 self
::$apiUrl = $wgServer . wfScript( 'api' );
47 // HACK: Avoid creating test users in the DB if the test may not need them.
49 'sysop' => fn () => $this->getTestSysop(),
50 'uploader' => fn () => $this->getTestUser(),
52 $fakeUserArray = new class ( $getters ) implements ArrayAccess
{
53 private array $getters;
54 private array $extraUsers = [];
56 public function __construct( array $getters ) {
57 $this->getters
= $getters;
60 public function offsetExists( $offset ): bool {
61 return isset( $this->getters
[$offset] ) ||
isset( $this->extraUsers
[$offset] );
64 #[ReturnTypeWillChange]
65 public function offsetGet( $offset ) {
66 if ( isset( $this->getters
[$offset] ) ) {
67 return ( $this->getters
[$offset] )();
69 if ( isset( $this->extraUsers
[$offset] ) ) {
70 return $this->extraUsers
[$offset];
72 throw new LogicException( "Requested unknown user $offset" );
75 public function offsetSet( $offset, $value ): void
{
76 $this->extraUsers
[$offset] = $value;
79 public function offsetUnset( $offset ): void
{
80 unset( $this->getters
[$offset] );
81 unset( $this->extraUsers
[$offset] );
85 self
::$users = $fakeUserArray;
87 $this->setRequest( new FauxRequest( [] ) );
89 $this->apiContext
= new ApiTestContext();
92 protected function tearDown(): void
{
93 // Avoid leaking session over tests
94 SessionManager
::getGlobalSession()->clear();
96 ApiBase
::clearCacheForTest();
102 * Does the API request and returns the result.
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
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
118 protected function doApiRequest( array $params, ?
array $session = null,
119 $appendModule = false, ?Authority
$performer = null, $tokenType = null,
124 // re-use existing global session by default
125 $session ??
= $wgRequest->getSessionArray();
127 $sessionObj = SessionManager
::singleton()->getEmptySession();
129 if ( $session !== null ) {
130 foreach ( $session as $key => $value ) {
131 $sessionObj->set( $key, $value );
135 // set up global environment
136 if ( !$performer && !$this->needsDB() ) {
137 $performer = $this->mockRegisteredUltimateAuthority();
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;
146 $contextUser = $this->getTestSysop()->getUser();
147 $performer = $contextUser;
148 $sessionUser = $contextUser;
151 $sessionObj->setUser( $sessionUser );
152 if ( $tokenType !== null ) {
153 if ( $tokenType === 'auto' ) {
154 $tokenType = ( new ApiMain() )->getModuleManager()
155 ->getModule( $params['action'], 'action' )->needsToken();
157 if ( $tokenType !== false ) {
158 $params['token'] = ApiQueryTokens
::getToken(
161 ApiQueryTokens
::getTokenTypeSalts()[$tokenType]
166 // prepend parameters with prefix
167 if ( $paramPrefix !== null && $paramPrefix !== '' ) {
168 $prefixedParams = [];
169 foreach ( $params as $key => $value ) {
170 $prefixedParams[$paramPrefix . $key] = $value;
172 $params = $prefixedParams;
175 $wgRequest = $this->buildFauxRequest( $params, $sessionObj );
176 RequestContext
::getMain()->setRequest( $wgRequest );
177 RequestContext
::getMain()->setAuthority( $performer );
178 RequestContext
::getMain()->setUser( $sessionUser );
180 // set up local environment
181 $context = $this->apiContext
->newTestContext( $wgRequest, $performer );
183 $module = new ApiMain( $context, true );
190 $module->getResult()->getResultData( null, [ 'Strip' => 'all' ] ),
191 $context->getRequest(),
192 $context->getRequest()->getSessionArray()
195 if ( $appendModule ) {
196 $results[] = $module;
204 * @param array $params
205 * @param Session|array|null $session
206 * @return FauxRequest
208 protected function buildFauxRequest( $params, $session ) {
209 return new FauxRequest( $params, true, $session );
213 * Convenience function to access the token parameter of doApiRequest()
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
223 protected function doApiRequestWithToken( array $params, ?
array $session = null,
224 ?Authority
$performer = null, $tokenType = 'auto', $paramPrefix = null
226 return $this->doApiRequest( $params, $session, false, $performer, $tokenType, $paramPrefix );
229 protected static function getErrorFormatter() {
230 self
::$errorFormatter ??
= new ApiErrorFormatter(
231 new ApiResult( false ),
232 MediaWikiServices
::getInstance()->getLanguageFactory()->getLanguage( 'en' ),
235 return self
::$errorFormatter;
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;
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.
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
259 protected function setExpectedApiException(
260 $msg, $code = null, ?
array $data = null, $httpCode = 0
262 $expected = ApiUsageException
::newWithMessage( null, $msg, $code, $data, $httpCode );
263 $this->expectException( ApiUsageException
::class );
264 $this->expectExceptionMessage( $expected->getMessage() );
267 private ?
string $expectedApiErrorCode;
270 * Expect an ApiUsageException that results in the given API error code to be thrown.
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.
276 * @param string $expectedCode
278 protected function expectApiErrorCode( string $expectedCode ) {
279 $this->expectedApiErrorCode
= $expectedCode;
283 * Assert that an ApiUsageException will result in the given API error code being outputted.
286 * @param string $expectedCode
287 * @param ApiUsageException $exception
288 * @param string $message
290 protected function assertApiErrorCode( string $expectedCode, ApiUsageException
$exception, string $message = '' ) {
291 $constraint = new class( $expectedCode ) extends Constraint
{
292 private string $expectedApiErrorCode;
294 public function __construct( string $expected ) {
295 $this->expectedApiErrorCode
= $expected;
298 public function toString(): string {
299 return 'API error code is ';
302 private function getApiErrorCode( $other ) {
303 if ( !$other instanceof ApiUsageException
) {
306 $errors = $other->getStatusValue()->getMessages();
307 if ( count( $errors ) === 0 ) {
309 } elseif ( count( $errors ) > 1 ) {
310 return '(multiple errors)';
312 return ApiMessage
::create( $errors[0] )->getApiCode();
315 protected function matches( $other ): bool {
316 return $this->getApiErrorCode( $other ) === $this->expectedApiErrorCode
;
319 protected function failureDescription( $other ): string {
321 '%s is equal to expected API error code %s',
322 $this->exporter()->export( $this->getApiErrorCode( $other ) ),
323 $this->exporter()->export( $this->expectedApiErrorCode
)
328 $this->assertThat( $exception, $constraint, $message );
334 * Adds support for expectApiErrorCode().
336 protected function runTest() {
338 $testResult = parent
::runTest();
340 } catch ( ApiUsageException
$exception ) {
341 if ( !isset( $this->expectedApiErrorCode
) ) {
345 $this->assertApiErrorCode( $this->expectedApiErrorCode
, $exception );
350 if ( !isset( $this->expectedApiErrorCode
) ) {
354 throw new AssertionFailedError(
356 'Failed asserting that exception with API error code "%s" is thrown',
357 $this->expectedApiErrorCode
363 /** @deprecated class alias since 1.42 */
364 class_alias( ApiTestCase
::class, 'ApiTestCase' );