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 if ( $tokenType === 'auto' ) {
103 $tokenType = ( new ApiMain() )->getModuleManager()
104 ->getModule( $params['action'], 'action' )->needsToken();
106 $params['token'] = ApiQueryTokens
::getToken(
107 $wgUser, $sessionObj, ApiQueryTokens
::getTokenTypeSalts()[$tokenType]
111 $wgRequest = new FauxRequest( $params, true, $sessionObj );
112 RequestContext
::getMain()->setRequest( $wgRequest );
113 RequestContext
::getMain()->setUser( $wgUser );
114 MediaWiki\Auth\AuthManager
::resetCache();
116 // set up local environment
117 $context = $this->apiContext
->newTestContext( $wgRequest, $wgUser );
119 $module = new ApiMain( $context, true );
126 $module->getResult()->getResultData( null, [ 'Strip' => 'all' ] ),
127 $context->getRequest(),
128 $context->getRequest()->getSessionArray()
131 if ( $appendModule ) {
132 $results[] = $module;
139 * Convenience function to access the token parameter of doApiRequest()
142 * @param array $params Key-value API params
143 * @param array|null $session Session array
144 * @param User|null $user A User object for the context
145 * @param string $tokenType Which token type to pass
146 * @return array Result of the API call
148 protected function doApiRequestWithToken( array $params, array $session = null,
149 User
$user = null, $tokenType = 'auto'
151 return $this->doApiRequest( $params, $session, false, $user, $tokenType );
154 protected function doLogin( $testUser = 'sysop' ) {
155 if ( $testUser === null ) {
156 $testUser = static::getTestSysop();
157 } elseif ( is_string( $testUser ) && array_key_exists( $testUser, self
::$users ) ) {
158 $testUser = self
::$users[ $testUser ];
159 } elseif ( !$testUser instanceof TestUser
) {
160 throw new MWException( "Can not log in to undefined user $testUser" );
163 $data = $this->doApiRequest( [
165 'lgname' => $testUser->getUser()->getName(),
166 'lgpassword' => $testUser->getPassword() ] );
168 $token = $data[0]['login']['token'];
170 $data = $this->doApiRequest(
174 'lgname' => $testUser->getUser()->getName(),
175 'lgpassword' => $testUser->getPassword(),
180 if ( $data[0]['login']['result'] === 'Success' ) {
183 $wgUser = $testUser->getUser();
184 RequestContext
::getMain()->setUser( $wgUser );
190 protected function getTokenList( TestUser
$user, $session = null ) {
191 $data = $this->doApiRequest( [
192 'action' => 'tokens',
193 'type' => 'edit|delete|protect|move|block|unblock|watch'
194 ], $session, false, $user->getUser() );
196 if ( !array_key_exists( 'tokens', $data[0] ) ) {
197 throw new MWException( 'Api failed to return a token list' );
200 return $data[0]['tokens'];
203 protected static function getErrorFormatter() {
204 if ( self
::$errorFormatter === null ) {
205 self
::$errorFormatter = new ApiErrorFormatter(
206 new ApiResult( false ),
207 Language
::factory( 'en' ),
211 return self
::$errorFormatter;
214 public static function apiExceptionHasCode( ApiUsageException
$ex, $code ) {
215 return (bool)array_filter(
216 self
::getErrorFormatter()->arrayFromStatus( $ex->getStatusValue() ),
217 function ( $e ) use ( $code ) {
218 return is_array( $e ) && $e['code'] === $code;
226 public function testApiTestGroup() {
227 $groups = PHPUnit_Util_Test
::getGroups( static::class );
228 $constraint = PHPUnit_Framework_Assert
::logicalOr(
229 $this->contains( 'medium' ),
230 $this->contains( 'large' )
232 $this->assertThat( $groups, $constraint,
233 'ApiTestCase::setUp can be slow, tests must be "medium" or "large"'