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
77 protected function doApiRequest( array $params, array $session = null,
78 $appendModule = false, User
$user = null, $tokenType = null
80 global $wgRequest, $wgUser;
82 if ( is_null( $session ) ) {
83 // re-use existing global session by default
84 $session = $wgRequest->getSessionArray();
87 $sessionObj = SessionManager
::singleton()->getEmptySession();
89 if ( $session !== null ) {
90 foreach ( $session as $key => $value ) {
91 $sessionObj->set( $key, $value );
95 // set up global environment
100 if ( $tokenType !== null ) {
101 $params['token'] = ApiQueryTokens
::getToken(
102 $wgUser, $sessionObj, ApiQueryTokens
::getTokenTypeSalts()[$tokenType]
106 $wgRequest = new FauxRequest( $params, true, $sessionObj );
107 RequestContext
::getMain()->setRequest( $wgRequest );
108 RequestContext
::getMain()->setUser( $wgUser );
109 MediaWiki\Auth\AuthManager
::resetCache();
111 // set up local environment
112 $context = $this->apiContext
->newTestContext( $wgRequest, $wgUser );
114 $module = new ApiMain( $context, true );
121 $module->getResult()->getResultData( null, [ 'Strip' => 'all' ] ),
122 $context->getRequest(),
123 $context->getRequest()->getSessionArray()
126 if ( $appendModule ) {
127 $results[] = $module;
134 * Convenience function to access the token parameter of doApiRequest()
137 * @param array $params Key-value API params
138 * @param array|null $session Session array
139 * @param User|null $user A User object for the context
140 * @param string $tokenType Which token type to pass
141 * @return array Result of the API call
143 protected function doApiRequestWithToken( array $params, array $session = null,
144 User
$user = null, $tokenType = 'csrf'
146 return $this->doApiRequest( $params, $session, false, $user, $tokenType );
149 protected function doLogin( $testUser = 'sysop' ) {
150 if ( $testUser === null ) {
151 $testUser = static::getTestSysop();
152 } elseif ( is_string( $testUser ) && array_key_exists( $testUser, self
::$users ) ) {
153 $testUser = self
::$users[ $testUser ];
154 } elseif ( !$testUser instanceof TestUser
) {
155 throw new MWException( "Can not log in to undefined user $testUser" );
158 $data = $this->doApiRequest( [
160 'lgname' => $testUser->getUser()->getName(),
161 'lgpassword' => $testUser->getPassword() ] );
163 $token = $data[0]['login']['token'];
165 $data = $this->doApiRequest(
169 'lgname' => $testUser->getUser()->getName(),
170 'lgpassword' => $testUser->getPassword(),
175 if ( $data[0]['login']['result'] === 'Success' ) {
178 $wgUser = $testUser->getUser();
179 RequestContext
::getMain()->setUser( $wgUser );
185 protected function getTokenList( TestUser
$user, $session = null ) {
186 $data = $this->doApiRequest( [
187 'action' => 'tokens',
188 'type' => 'edit|delete|protect|move|block|unblock|watch'
189 ], $session, false, $user->getUser() );
191 if ( !array_key_exists( 'tokens', $data[0] ) ) {
192 throw new MWException( 'Api failed to return a token list' );
195 return $data[0]['tokens'];
198 protected static function getErrorFormatter() {
199 if ( self
::$errorFormatter === null ) {
200 self
::$errorFormatter = new ApiErrorFormatter(
201 new ApiResult( false ),
202 Language
::factory( 'en' ),
206 return self
::$errorFormatter;
209 public static function apiExceptionHasCode( ApiUsageException
$ex, $code ) {
210 return (bool)array_filter(
211 self
::getErrorFormatter()->arrayFromStatus( $ex->getStatusValue() ),
212 function ( $e ) use ( $code ) {
213 return is_array( $e ) && $e['code'] === $code;
221 public function testApiTestGroup() {
222 $groups = PHPUnit_Util_Test
::getGroups( static::class );
223 $constraint = PHPUnit_Framework_Assert
::logicalOr(
224 $this->contains( 'medium' ),
225 $this->contains( 'large' )
227 $this->assertThat( $groups, $constraint,
228 'ApiTestCase::setUp can be slow, tests must be "medium" or "large"'