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 * Edits or creates a page/revision
46 * @param string $pageName Page title
47 * @param string $text Content of the page
48 * @param string $summary Optional summary string for the revision
49 * @param int $defaultNs Optional namespace id
50 * @return array Array as returned by WikiPage::doEditContent()
52 protected function editPage( $pageName, $text, $summary = '', $defaultNs = NS_MAIN
) {
53 $title = Title
::newFromText( $pageName, $defaultNs );
54 $page = WikiPage
::factory( $title );
56 return $page->doEditContent( ContentHandler
::makeContent( $text, $title ), $summary );
60 * Does the API request and returns the result.
62 * The returned value is an array containing
63 * - the result data (array)
64 * - the request (WebRequest)
65 * - the session data of the request (array)
66 * - if $appendModule is true, the Api module $module
68 * @param array $params
69 * @param array|null $session
70 * @param bool $appendModule
71 * @param User|null $user
72 * @param string|null $tokenType Set to a string like 'csrf' to send an
75 * @throws ApiUsageException
78 protected function doApiRequest( array $params, array $session = null,
79 $appendModule = false, User
$user = null, $tokenType = null
81 global $wgRequest, $wgUser;
83 if ( is_null( $session ) ) {
84 // re-use existing global session by default
85 $session = $wgRequest->getSessionArray();
88 $sessionObj = SessionManager
::singleton()->getEmptySession();
90 if ( $session !== null ) {
91 foreach ( $session as $key => $value ) {
92 $sessionObj->set( $key, $value );
96 // set up global environment
101 if ( $tokenType !== null ) {
102 $params['token'] = ApiQueryTokens
::getToken(
103 $wgUser, $sessionObj, ApiQueryTokens
::getTokenTypeSalts()[$tokenType]
107 $wgRequest = new FauxRequest( $params, true, $sessionObj );
108 RequestContext
::getMain()->setRequest( $wgRequest );
109 RequestContext
::getMain()->setUser( $wgUser );
110 MediaWiki\Auth\AuthManager
::resetCache();
112 // set up local environment
113 $context = $this->apiContext
->newTestContext( $wgRequest, $wgUser );
115 $module = new ApiMain( $context, true );
122 $module->getResult()->getResultData( null, [ 'Strip' => 'all' ] ),
123 $context->getRequest(),
124 $context->getRequest()->getSessionArray()
127 if ( $appendModule ) {
128 $results[] = $module;
135 * Convenience function to access the token parameter of doApiRequest()
138 * @param array $params Key-value API params
139 * @param array|null $session Session array
140 * @param User|null $user A User object for the context
141 * @param string $tokenType Which token type to pass
142 * @return array Result of the API call
144 protected function doApiRequestWithToken( array $params, array $session = null,
145 User
$user = null, $tokenType = 'csrf'
147 return $this->doApiRequest( $params, $session, false, $user, $tokenType );
151 * Previously this would do API requests to log in, as well as setting $wgUser and the request
152 * context's user. The API requests are unnecessary, and the global-setting is unwanted, so
153 * this method should not be called. Instead, pass appropriate User values directly to
154 * functions that need them. For functions that still rely on $wgUser, set that directly. If
155 * you just want to log in the test sysop user, don't do anything -- that's the default.
157 * @param TestUser|string $testUser Object, or key to self::$users such as 'sysop' or 'uploader'
158 * @deprecated since 1.31
160 protected function doLogin( $testUser = null ) {
163 if ( $testUser === null ) {
164 $testUser = static::getTestSysop();
165 } elseif ( is_string( $testUser ) && array_key_exists( $testUser, self
::$users ) ) {
166 $testUser = self
::$users[$testUser];
167 } elseif ( !$testUser instanceof TestUser
) {
168 throw new MWException( "Can't log in to undefined user $testUser" );
171 $wgUser = $testUser->getUser();
172 RequestContext
::getMain()->setUser( $wgUser );
175 protected function getTokenList( TestUser
$user, $session = null ) {
176 $data = $this->doApiRequest( [
177 'action' => 'tokens',
178 'type' => 'edit|delete|protect|move|block|unblock|watch'
179 ], $session, false, $user->getUser() );
181 if ( !array_key_exists( 'tokens', $data[0] ) ) {
182 throw new MWException( 'Api failed to return a token list' );
185 return $data[0]['tokens'];
188 protected static function getErrorFormatter() {
189 if ( self
::$errorFormatter === null ) {
190 self
::$errorFormatter = new ApiErrorFormatter(
191 new ApiResult( false ),
192 Language
::factory( 'en' ),
196 return self
::$errorFormatter;
199 public static function apiExceptionHasCode( ApiUsageException
$ex, $code ) {
200 return (bool)array_filter(
201 self
::getErrorFormatter()->arrayFromStatus( $ex->getStatusValue() ),
202 function ( $e ) use ( $code ) {
203 return is_array( $e ) && $e['code'] === $code;
211 public function testApiTestGroup() {
212 $groups = PHPUnit_Util_Test
::getGroups( static::class );
213 $constraint = PHPUnit_Framework_Assert
::logicalOr(
214 $this->contains( 'medium' ),
215 $this->contains( 'large' )
217 $this->assertThat( $groups, $constraint,
218 'ApiTestCase::setUp can be slow, tests must be "medium" or "large"'