3 namespace MediaWiki\Tests\Api
;
11 use 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
;
30 protected static $apiUrl;
32 protected static $errorFormatter = null;
37 protected $apiContext;
39 protected function setUp(): void
{
43 self
::$apiUrl = $wgServer . wfScript( 'api' );
45 // HACK: Avoid creating test users in the DB if the test may not need them.
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();
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
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,
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();
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;
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(
159 ApiQueryTokens
::getTokenTypeSalts()[$tokenType]
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 );
187 $module->getResult()->getResultData( null, [ 'Strip' => 'all' ] ),
188 $context->getRequest(),
189 $context->getRequest()->getSessionArray()
192 if ( $appendModule ) {
193 $results[] = $module;
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()
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' ),
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.
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.
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
) {
303 $errors = $other->getStatusValue()->getMessages();
304 if ( count( $errors ) === 0 ) {
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 {
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 );
331 * Adds support for expectApiErrorCode().
333 protected function runTest() {
335 $testResult = parent
::runTest();
337 } catch ( ApiUsageException
$exception ) {
338 if ( !isset( $this->expectedApiErrorCode
) ) {
342 $this->assertApiErrorCode( $this->expectedApiErrorCode
, $exception );
347 if ( !isset( $this->expectedApiErrorCode
) ) {
351 throw new AssertionFailedError(
353 'Failed asserting that exception with API error code "%s" is thrown',
354 $this->expectedApiErrorCode
360 class_alias( ApiTestCase
::class, 'ApiTestCase' );