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 'wgAuth' => new MediaWiki\Auth\AuthManagerAuthPlugin
,
30 'wgRequest' => new FauxRequest( [] ),
31 'wgUser' => self
::$users['sysop']->getUser(),
34 $this->apiContext
= new ApiTestContext();
37 protected function tearDown() {
38 // Avoid leaking session over tests
39 MediaWiki\Session\SessionManager
::getGlobalSession()->clear();
45 * Does the API request and returns the result.
47 * The returned value is an array containing
48 * - the result data (array)
49 * - the request (WebRequest)
50 * - the session data of the request (array)
51 * - if $appendModule is true, the Api module $module
53 * @param array $params
54 * @param array|null $session
55 * @param bool $appendModule
56 * @param User|null $user
57 * @param string|null $tokenType Set to a string like 'csrf' to send an
60 * @throws ApiUsageException
63 protected function doApiRequest( array $params, array $session = null,
64 $appendModule = false, User
$user = null, $tokenType = null
66 global $wgRequest, $wgUser;
68 if ( is_null( $session ) ) {
69 // re-use existing global session by default
70 $session = $wgRequest->getSessionArray();
73 $sessionObj = SessionManager
::singleton()->getEmptySession();
75 if ( $session !== null ) {
76 foreach ( $session as $key => $value ) {
77 $sessionObj->set( $key, $value );
81 // set up global environment
86 if ( $tokenType !== null ) {
87 if ( $tokenType === 'auto' ) {
88 $tokenType = ( new ApiMain() )->getModuleManager()
89 ->getModule( $params['action'], 'action' )->needsToken();
91 $params['token'] = ApiQueryTokens
::getToken(
92 $wgUser, $sessionObj, ApiQueryTokens
::getTokenTypeSalts()[$tokenType]
96 $wgRequest = new FauxRequest( $params, true, $sessionObj );
97 RequestContext
::getMain()->setRequest( $wgRequest );
98 RequestContext
::getMain()->setUser( $wgUser );
99 MediaWiki\Auth\AuthManager
::resetCache();
101 // set up local environment
102 $context = $this->apiContext
->newTestContext( $wgRequest, $wgUser );
104 $module = new ApiMain( $context, true );
111 $module->getResult()->getResultData( null, [ 'Strip' => 'all' ] ),
112 $context->getRequest(),
113 $context->getRequest()->getSessionArray()
116 if ( $appendModule ) {
117 $results[] = $module;
124 * Convenience function to access the token parameter of doApiRequest()
127 * @param array $params Key-value API params
128 * @param array|null $session Session array
129 * @param User|null $user A User object for the context
130 * @param string $tokenType Which token type to pass
131 * @return array Result of the API call
133 protected function doApiRequestWithToken( array $params, array $session = null,
134 User
$user = null, $tokenType = 'auto'
136 return $this->doApiRequest( $params, $session, false, $user, $tokenType );
140 * Previously this would do API requests to log in, as well as setting $wgUser and the request
141 * context's user. The API requests are unnecessary, and the global-setting is unwanted, so
142 * this method should not be called. Instead, pass appropriate User values directly to
143 * functions that need them. For functions that still rely on $wgUser, set that directly. If
144 * you just want to log in the test sysop user, don't do anything -- that's the default.
146 * @param TestUser|string $testUser Object, or key to self::$users such as 'sysop' or 'uploader'
147 * @deprecated since 1.31
149 protected function doLogin( $testUser = null ) {
152 if ( $testUser === null ) {
153 $testUser = static::getTestSysop();
154 } elseif ( is_string( $testUser ) && array_key_exists( $testUser, self
::$users ) ) {
155 $testUser = self
::$users[$testUser];
156 } elseif ( !$testUser instanceof TestUser
) {
157 throw new MWException( "Can't log in to undefined user $testUser" );
160 $wgUser = $testUser->getUser();
161 RequestContext
::getMain()->setUser( $wgUser );
164 protected function getTokenList( TestUser
$user, $session = null ) {
165 $data = $this->doApiRequest( [
166 'action' => 'tokens',
167 'type' => 'edit|delete|protect|move|block|unblock|watch'
168 ], $session, false, $user->getUser() );
170 if ( !array_key_exists( 'tokens', $data[0] ) ) {
171 throw new MWException( 'Api failed to return a token list' );
174 return $data[0]['tokens'];
177 protected static function getErrorFormatter() {
178 if ( self
::$errorFormatter === null ) {
179 self
::$errorFormatter = new ApiErrorFormatter(
180 new ApiResult( false ),
181 Language
::factory( 'en' ),
185 return self
::$errorFormatter;
188 public static function apiExceptionHasCode( ApiUsageException
$ex, $code ) {
189 return (bool)array_filter(
190 self
::getErrorFormatter()->arrayFromStatus( $ex->getStatusValue() ),
191 function ( $e ) use ( $code ) {
192 return is_array( $e ) && $e['code'] === $code;
200 public function testApiTestGroup() {
201 $groups = PHPUnit_Util_Test
::getGroups( static::class );
202 $constraint = PHPUnit_Framework_Assert
::logicalOr(
203 $this->contains( 'medium' ),
204 $this->contains( 'large' )
206 $this->assertThat( $groups, $constraint,
207 'ApiTestCase::setUp can be slow, tests must be "medium" or "large"'
212 * Expect an ApiUsageException to be thrown with the given parameters, which are the same as
213 * ApiUsageException::newWithMessage()'s parameters. This allows checking for an exception
214 * whose text is given by a message key instead of text, so as not to hard-code the message's
215 * text into test code.
217 protected function setExpectedApiException(
218 $msg, $code = null, array $data = null, $httpCode = 0
220 $expected = ApiUsageException
::newWithMessage( null, $msg, $code, $data, $httpCode );
221 $this->setExpectedException( ApiUsageException
::class, $expected->getMessage() );