3 use MediaWiki\Session\SessionManager
;
5 abstract class ApiTestCase
extends MediaWikiLangTestCase
{
6 protected static $apiUrl;
8 protected static $errorFormatter = null;
13 protected $apiContext;
15 protected function setUp() {
19 self
::$apiUrl = $wgServer . wfScript( 'api' );
21 ApiQueryInfo
::resetTokenCache(); // tokens are invalid because we cleared the session
24 'sysop' => static::getTestSysop(),
25 'uploader' => static::getTestUser(),
28 $this->setMwGlobals( [
29 'wgRequest' => new FauxRequest( [] ),
30 'wgUser' => self
::$users['sysop']->getUser(),
33 $this->apiContext
= new ApiTestContext();
36 protected function tearDown() {
37 // Avoid leaking session over tests
38 MediaWiki\Session\SessionManager
::getGlobalSession()->clear();
44 * Does the API request and returns the result.
46 * The returned value is an array containing
47 * - the result data (array)
48 * - the request (WebRequest)
49 * - the session data of the request (array)
50 * - if $appendModule is true, the Api module $module
52 * @param array $params
53 * @param array|null $session
54 * @param bool $appendModule
55 * @param User|null $user
56 * @param string|null $tokenType Set to a string like 'csrf' to send an
59 * @throws ApiUsageException
62 protected function doApiRequest( array $params, array $session = null,
63 $appendModule = false, User
$user = null, $tokenType = null
65 global $wgRequest, $wgUser;
67 if ( is_null( $session ) ) {
68 // re-use existing global session by default
69 $session = $wgRequest->getSessionArray();
72 $sessionObj = SessionManager
::singleton()->getEmptySession();
74 if ( $session !== null ) {
75 foreach ( $session as $key => $value ) {
76 $sessionObj->set( $key, $value );
80 // set up global environment
85 if ( $tokenType !== null ) {
86 if ( $tokenType === 'auto' ) {
87 $tokenType = ( new ApiMain() )->getModuleManager()
88 ->getModule( $params['action'], 'action' )->needsToken();
90 $params['token'] = ApiQueryTokens
::getToken(
91 $wgUser, $sessionObj, ApiQueryTokens
::getTokenTypeSalts()[$tokenType]
95 $wgRequest = new FauxRequest( $params, true, $sessionObj );
96 RequestContext
::getMain()->setRequest( $wgRequest );
97 RequestContext
::getMain()->setUser( $wgUser );
98 MediaWiki\Auth\AuthManager
::resetCache();
100 // set up local environment
101 $context = $this->apiContext
->newTestContext( $wgRequest, $wgUser );
103 $module = new ApiMain( $context, true );
110 $module->getResult()->getResultData( null, [ 'Strip' => 'all' ] ),
111 $context->getRequest(),
112 $context->getRequest()->getSessionArray()
115 if ( $appendModule ) {
116 $results[] = $module;
123 * Convenience function to access the token parameter of doApiRequest()
126 * @param array $params Key-value API params
127 * @param array|null $session Session array
128 * @param User|null $user A User object for the context
129 * @param string $tokenType Which token type to pass
130 * @return array Result of the API call
132 protected function doApiRequestWithToken( array $params, array $session = null,
133 User
$user = null, $tokenType = 'auto'
135 return $this->doApiRequest( $params, $session, false, $user, $tokenType );
139 * Previously this would do API requests to log in, as well as setting $wgUser and the request
140 * context's user. The API requests are unnecessary, and the global-setting is unwanted, so
141 * this method should not be called. Instead, pass appropriate User values directly to
142 * functions that need them. For functions that still rely on $wgUser, set that directly. If
143 * you just want to log in the test sysop user, don't do anything -- that's the default.
145 * @param TestUser|string $testUser Object, or key to self::$users such as 'sysop' or 'uploader'
146 * @deprecated since 1.31
148 protected function doLogin( $testUser = null ) {
151 if ( $testUser === null ) {
152 $testUser = static::getTestSysop();
153 } elseif ( is_string( $testUser ) && array_key_exists( $testUser, self
::$users ) ) {
154 $testUser = self
::$users[$testUser];
155 } elseif ( !$testUser instanceof TestUser
) {
156 throw new MWException( "Can't log in to undefined user $testUser" );
159 $wgUser = $testUser->getUser();
160 RequestContext
::getMain()->setUser( $wgUser );
163 protected function getTokenList( TestUser
$user, $session = null ) {
164 $data = $this->doApiRequest( [
165 'action' => 'tokens',
166 'type' => 'edit|delete|protect|move|block|unblock|watch'
167 ], $session, false, $user->getUser() );
169 if ( !array_key_exists( 'tokens', $data[0] ) ) {
170 throw new MWException( 'Api failed to return a token list' );
173 return $data[0]['tokens'];
176 protected static function getErrorFormatter() {
177 if ( self
::$errorFormatter === null ) {
178 self
::$errorFormatter = new ApiErrorFormatter(
179 new ApiResult( false ),
180 Language
::factory( 'en' ),
184 return self
::$errorFormatter;
187 public static function apiExceptionHasCode( ApiUsageException
$ex, $code ) {
188 return (bool)array_filter(
189 self
::getErrorFormatter()->arrayFromStatus( $ex->getStatusValue() ),
190 function ( $e ) use ( $code ) {
191 return is_array( $e ) && $e['code'] === $code;
199 public function testApiTestGroup() {
200 $groups = PHPUnit_Util_Test
::getGroups( static::class );
201 $constraint = PHPUnit_Framework_Assert
::logicalOr(
202 $this->contains( 'medium' ),
203 $this->contains( 'large' )
205 $this->assertThat( $groups, $constraint,
206 'ApiTestCase::setUp can be slow, tests must be "medium" or "large"'
211 * Expect an ApiUsageException to be thrown with the given parameters, which are the same as
212 * ApiUsageException::newWithMessage()'s parameters. This allows checking for an exception
213 * whose text is given by a message key instead of text, so as not to hard-code the message's
214 * text into test code.
216 protected function setExpectedApiException(
217 $msg, $code = null, array $data = null, $httpCode = 0
219 $expected = ApiUsageException
::newWithMessage( null, $msg, $code, $data, $httpCode );
220 $this->setExpectedException( ApiUsageException
::class, $expected->getMessage() );