3 abstract class ApiTestCase
extends MediaWikiLangTestCase
{
4 protected static $apiUrl;
6 protected static $errorFormatter = null;
11 protected $apiContext;
13 protected function setUp() {
17 self
::$apiUrl = $wgServer . wfScript( 'api' );
19 ApiQueryInfo
::resetTokenCache(); // tokens are invalid because we cleared the session
22 'sysop' => static::getTestSysop(),
23 'uploader' => static::getTestUser(),
26 $this->setMwGlobals( [
27 'wgAuth' => new MediaWiki\Auth\AuthManagerAuthPlugin
,
28 'wgRequest' => new FauxRequest( [] ),
29 'wgUser' => self
::$users['sysop']->getUser(),
32 $this->apiContext
= new ApiTestContext();
35 protected function tearDown() {
36 // Avoid leaking session over tests
37 MediaWiki\Session\SessionManager
::getGlobalSession()->clear();
43 * Edits or creates a page/revision
44 * @param string $pageName Page title
45 * @param string $text Content of the page
46 * @param string $summary Optional summary string for the revision
47 * @param int $defaultNs Optional namespace id
48 * @return array Array as returned by WikiPage::doEditContent()
50 protected function editPage( $pageName, $text, $summary = '', $defaultNs = NS_MAIN
) {
51 $title = Title
::newFromText( $pageName, $defaultNs );
52 $page = WikiPage
::factory( $title );
54 return $page->doEditContent( ContentHandler
::makeContent( $text, $title ), $summary );
58 * Does the API request and returns the result.
60 * The returned value is an array containing
61 * - the result data (array)
62 * - the request (WebRequest)
63 * - the session data of the request (array)
64 * - if $appendModule is true, the Api module $module
66 * @param array $params
67 * @param array|null $session
68 * @param bool $appendModule
69 * @param User|null $user
73 protected function doApiRequest( array $params, array $session = null,
74 $appendModule = false, User
$user = null
76 global $wgRequest, $wgUser;
78 if ( is_null( $session ) ) {
79 // re-use existing global session by default
80 $session = $wgRequest->getSessionArray();
83 // set up global environment
88 $wgRequest = new FauxRequest( $params, true, $session );
89 RequestContext
::getMain()->setRequest( $wgRequest );
90 RequestContext
::getMain()->setUser( $wgUser );
91 MediaWiki\Auth\AuthManager
::resetCache();
93 // set up local environment
94 $context = $this->apiContext
->newTestContext( $wgRequest, $wgUser );
96 $module = new ApiMain( $context, true );
103 $module->getResult()->getResultData( null, [ 'Strip' => 'all' ] ),
104 $context->getRequest(),
105 $context->getRequest()->getSessionArray()
108 if ( $appendModule ) {
109 $results[] = $module;
116 * Add an edit token to the API request
117 * This is cheating a bit -- we grab a token in the correct format and then
118 * add it to the pseudo-session and to the request, without actually
119 * requesting a "real" edit token.
121 * @param array $params Key-value API params
122 * @param array|null $session Session array
123 * @param User|null $user A User object for the context
124 * @return array Result of the API call
125 * @throws Exception In case wsToken is not set in the session
127 protected function doApiRequestWithToken( array $params, array $session = null,
132 if ( $session === null ) {
133 $session = $wgRequest->getSessionArray();
136 if ( isset( $session['wsToken'] ) && $session['wsToken'] ) {
137 // @todo Why does this directly mess with the session? Fix that.
138 // add edit token to fake session
139 $session['wsTokenSecrets']['default'] = $session['wsToken'];
140 // add token to request parameters
141 $timestamp = wfTimestamp();
142 $params['token'] = hash_hmac( 'md5', $timestamp, $session['wsToken'] ) .
143 dechex( $timestamp ) .
144 MediaWiki\Session\Token
::SUFFIX
;
146 return $this->doApiRequest( $params, $session, false, $user );
148 throw new Exception( "Session token not available" );
152 protected function doLogin( $testUser = 'sysop' ) {
153 if ( $testUser === null ) {
154 $testUser = static::getTestSysop();
155 } elseif ( is_string( $testUser ) && array_key_exists( $testUser, self
::$users ) ) {
156 $testUser = self
::$users[ $testUser ];
157 } elseif ( !$testUser instanceof TestUser
) {
158 throw new MWException( "Can not log in to undefined user $testUser" );
161 $data = $this->doApiRequest( [
163 'lgname' => $testUser->getUser()->getName(),
164 'lgpassword' => $testUser->getPassword() ] );
166 $token = $data[0]['login']['token'];
168 $data = $this->doApiRequest(
172 'lgname' => $testUser->getUser()->getName(),
173 'lgpassword' => $testUser->getPassword(),
178 if ( $data[0]['login']['result'] === 'Success' ) {
181 $wgUser = $testUser->getUser();
182 RequestContext
::getMain()->setUser( $wgUser );
188 protected function getTokenList( TestUser
$user, $session = null ) {
189 $data = $this->doApiRequest( [
190 'action' => 'tokens',
191 'type' => 'edit|delete|protect|move|block|unblock|watch'
192 ], $session, false, $user->getUser() );
194 if ( !array_key_exists( 'tokens', $data[0] ) ) {
195 throw new MWException( 'Api failed to return a token list' );
198 return $data[0]['tokens'];
201 protected static function getErrorFormatter() {
202 if ( self
::$errorFormatter === null ) {
203 self
::$errorFormatter = new ApiErrorFormatter(
204 new ApiResult( false ),
205 Language
::factory( 'en' ),
209 return self
::$errorFormatter;
212 public static function apiExceptionHasCode( ApiUsageException
$ex, $code ) {
213 return (bool)array_filter(
214 self
::getErrorFormatter()->arrayFromStatus( $ex->getStatusValue() ),
215 function ( $e ) use ( $code ) {
216 return is_array( $e ) && $e['code'] === $code;
221 public function testApiTestGroup() {
222 $groups = PHPUnit_Util_Test
::getGroups( get_class( $this ) );
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"'