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
71 * @throws ApiUsageException
74 protected function doApiRequest( array $params, array $session = null,
75 $appendModule = false, User
$user = null
77 global $wgRequest, $wgUser;
79 if ( is_null( $session ) ) {
80 // re-use existing global session by default
81 $session = $wgRequest->getSessionArray();
84 // set up global environment
89 $wgRequest = new FauxRequest( $params, true, $session );
90 RequestContext
::getMain()->setRequest( $wgRequest );
91 RequestContext
::getMain()->setUser( $wgUser );
92 MediaWiki\Auth\AuthManager
::resetCache();
94 // set up local environment
95 $context = $this->apiContext
->newTestContext( $wgRequest, $wgUser );
97 $module = new ApiMain( $context, true );
104 $module->getResult()->getResultData( null, [ 'Strip' => 'all' ] ),
105 $context->getRequest(),
106 $context->getRequest()->getSessionArray()
109 if ( $appendModule ) {
110 $results[] = $module;
117 * Add an edit token to the API request
118 * This is cheating a bit -- we grab a token in the correct format and then
119 * add it to the pseudo-session and to the request, without actually
120 * requesting a "real" edit token.
122 * @param array $params Key-value API params
123 * @param array|null $session Session array
124 * @param User|null $user A User object for the context
125 * @return array Result of the API call
126 * @throws Exception In case wsToken is not set in the session
128 protected function doApiRequestWithToken( array $params, array $session = null,
133 if ( $session === null ) {
134 $session = $wgRequest->getSessionArray();
137 if ( isset( $session['wsToken'] ) && $session['wsToken'] ) {
138 // @todo Why does this directly mess with the session? Fix that.
139 // add edit token to fake session
140 $session['wsTokenSecrets']['default'] = $session['wsToken'];
141 // add token to request parameters
142 $timestamp = wfTimestamp();
143 $params['token'] = hash_hmac( 'md5', $timestamp, $session['wsToken'] ) .
144 dechex( $timestamp ) .
145 MediaWiki\Session\Token
::SUFFIX
;
147 return $this->doApiRequest( $params, $session, false, $user );
149 throw new Exception( "Session token not available" );
153 protected function doLogin( $testUser = 'sysop' ) {
154 if ( $testUser === null ) {
155 $testUser = static::getTestSysop();
156 } elseif ( is_string( $testUser ) && array_key_exists( $testUser, self
::$users ) ) {
157 $testUser = self
::$users[ $testUser ];
158 } elseif ( !$testUser instanceof TestUser
) {
159 throw new MWException( "Can not log in to undefined user $testUser" );
162 $data = $this->doApiRequest( [
164 'lgname' => $testUser->getUser()->getName(),
165 'lgpassword' => $testUser->getPassword() ] );
167 $token = $data[0]['login']['token'];
169 $data = $this->doApiRequest(
173 'lgname' => $testUser->getUser()->getName(),
174 'lgpassword' => $testUser->getPassword(),
179 if ( $data[0]['login']['result'] === 'Success' ) {
182 $wgUser = $testUser->getUser();
183 RequestContext
::getMain()->setUser( $wgUser );
189 protected function getTokenList( TestUser
$user, $session = null ) {
190 $data = $this->doApiRequest( [
191 'action' => 'tokens',
192 'type' => 'edit|delete|protect|move|block|unblock|watch'
193 ], $session, false, $user->getUser() );
195 if ( !array_key_exists( 'tokens', $data[0] ) ) {
196 throw new MWException( 'Api failed to return a token list' );
199 return $data[0]['tokens'];
202 protected static function getErrorFormatter() {
203 if ( self
::$errorFormatter === null ) {
204 self
::$errorFormatter = new ApiErrorFormatter(
205 new ApiResult( false ),
206 Language
::factory( 'en' ),
210 return self
::$errorFormatter;
213 public static function apiExceptionHasCode( ApiUsageException
$ex, $code ) {
214 return (bool)array_filter(
215 self
::getErrorFormatter()->arrayFromStatus( $ex->getStatusValue() ),
216 function ( $e ) use ( $code ) {
217 return is_array( $e ) && $e['code'] === $code;
225 public function testApiTestGroup() {
226 $groups = PHPUnit_Util_Test
::getGroups( static::class );
227 $constraint = PHPUnit_Framework_Assert
::logicalOr(
228 $this->contains( 'medium' ),
229 $this->contains( 'large' )
231 $this->assertThat( $groups, $constraint,
232 'ApiTestCase::setUp can be slow, tests must be "medium" or "large"'