MediaWiki REL1_31
ApiTestCase.php
Go to the documentation of this file.
1<?php
2
4
5abstract class ApiTestCase extends MediaWikiLangTestCase {
6 protected static $apiUrl;
7
8 protected static $errorFormatter = null;
9
13 protected $apiContext;
14
15 protected function setUp() {
16 global $wgServer;
17
18 parent::setUp();
19 self::$apiUrl = $wgServer . wfScript( 'api' );
20
21 ApiQueryInfo::resetTokenCache(); // tokens are invalid because we cleared the session
22
23 self::$users = [
24 'sysop' => static::getTestSysop(),
25 'uploader' => static::getTestUser(),
26 ];
27
28 $this->setMwGlobals( [
29 'wgAuth' => new MediaWiki\Auth\AuthManagerAuthPlugin,
30 'wgRequest' => new FauxRequest( [] ),
31 'wgUser' => self::$users['sysop']->getUser(),
32 ] );
33
34 $this->apiContext = new ApiTestContext();
35 }
36
37 protected function tearDown() {
38 // Avoid leaking session over tests
39 MediaWiki\Session\SessionManager::getGlobalSession()->clear();
40
41 parent::tearDown();
42 }
43
52 protected function editPage( $pageName, $text, $summary = '', $defaultNs = NS_MAIN ) {
53 $title = Title::newFromText( $pageName, $defaultNs );
54 $page = WikiPage::factory( $title );
55
56 return $page->doEditContent( ContentHandler::makeContent( $text, $title ), $summary );
57 }
58
67 protected function revisionDelete(
68 $rev, array $value = [ Revision::DELETED_TEXT => 1 ], $comment = ''
69 ) {
70 if ( is_int( $rev ) ) {
71 $rev = Revision::newFromId( $rev );
72 }
74 'revision', RequestContext::getMain(), $rev->getTitle(), [ $rev->getId() ]
75 )->setVisibility( [
76 'value' => $value,
77 'comment' => $comment,
78 ] );
79 }
80
100 protected function doApiRequest( array $params, array $session = null,
101 $appendModule = false, User $user = null, $tokenType = null
102 ) {
103 global $wgRequest, $wgUser;
104
105 if ( is_null( $session ) ) {
106 // re-use existing global session by default
107 $session = $wgRequest->getSessionArray();
108 }
109
110 $sessionObj = SessionManager::singleton()->getEmptySession();
111
112 if ( $session !== null ) {
113 foreach ( $session as $key => $value ) {
114 $sessionObj->set( $key, $value );
115 }
116 }
117
118 // set up global environment
119 if ( $user ) {
120 $wgUser = $user;
121 }
122
123 if ( $tokenType !== null ) {
124 if ( $tokenType === 'auto' ) {
125 $tokenType = ( new ApiMain() )->getModuleManager()
126 ->getModule( $params['action'], 'action' )->needsToken();
127 }
129 $wgUser, $sessionObj, ApiQueryTokens::getTokenTypeSalts()[$tokenType]
130 )->toString();
131 }
132
133 $wgRequest = new FauxRequest( $params, true, $sessionObj );
134 RequestContext::getMain()->setRequest( $wgRequest );
135 RequestContext::getMain()->setUser( $wgUser );
136 MediaWiki\Auth\AuthManager::resetCache();
137
138 // set up local environment
139 $context = $this->apiContext->newTestContext( $wgRequest, $wgUser );
140
141 $module = new ApiMain( $context, true );
142
143 // run it!
144 $module->execute();
145
146 // construct result
147 $results = [
148 $module->getResult()->getResultData( null, [ 'Strip' => 'all' ] ),
149 $context->getRequest(),
150 $context->getRequest()->getSessionArray()
151 ];
152
153 if ( $appendModule ) {
154 $results[] = $module;
155 }
156
157 return $results;
158 }
159
170 protected function doApiRequestWithToken( array $params, array $session = null,
171 User $user = null, $tokenType = 'auto'
172 ) {
173 return $this->doApiRequest( $params, $session, false, $user, $tokenType );
174 }
175
186 protected function doLogin( $testUser = null ) {
187 global $wgUser;
188
189 if ( $testUser === null ) {
190 $testUser = static::getTestSysop();
191 } elseif ( is_string( $testUser ) && array_key_exists( $testUser, self::$users ) ) {
192 $testUser = self::$users[$testUser];
193 } elseif ( !$testUser instanceof TestUser ) {
194 throw new MWException( "Can't log in to undefined user $testUser" );
195 }
196
197 $wgUser = $testUser->getUser();
198 RequestContext::getMain()->setUser( $wgUser );
199 }
200
201 protected function getTokenList( TestUser $user, $session = null ) {
202 $data = $this->doApiRequest( [
203 'action' => 'tokens',
204 'type' => 'edit|delete|protect|move|block|unblock|watch'
205 ], $session, false, $user->getUser() );
206
207 if ( !array_key_exists( 'tokens', $data[0] ) ) {
208 throw new MWException( 'Api failed to return a token list' );
209 }
210
211 return $data[0]['tokens'];
212 }
213
214 protected static function getErrorFormatter() {
215 if ( self::$errorFormatter === null ) {
216 self::$errorFormatter = new ApiErrorFormatter(
217 new ApiResult( false ),
218 Language::factory( 'en' ),
219 'none'
220 );
221 }
223 }
224
225 public static function apiExceptionHasCode( ApiUsageException $ex, $code ) {
226 return (bool)array_filter(
227 self::getErrorFormatter()->arrayFromStatus( $ex->getStatusValue() ),
228 function ( $e ) use ( $code ) {
229 return is_array( $e ) && $e['code'] === $code;
230 }
231 );
232 }
233
237 public function testApiTestGroup() {
238 $groups = PHPUnit_Util_Test::getGroups( static::class );
239 $constraint = PHPUnit_Framework_Assert::logicalOr(
240 $this->contains( 'medium' ),
241 $this->contains( 'large' )
242 );
243 $this->assertThat( $groups, $constraint,
244 'ApiTestCase::setUp can be slow, tests must be "medium" or "large"'
245 );
246 }
247
254 protected function setExpectedApiException(
255 $msg, $code = null, array $data = null, $httpCode = 0
256 ) {
257 $expected = ApiUsageException::newWithMessage( null, $msg, $code, $data, $httpCode );
258 $this->setExpectedException( ApiUsageException::class, $expected->getMessage() );
259 }
260}
c Accompany it with the information you received as to the offer to distribute corresponding source complete source code means all the source code for all modules it contains
Definition COPYING.txt:157
$wgServer
URL of the server.
wfScript( $script='index')
Get the path to a specified script file, respecting file extensions; this is a wrapper around $wgScri...
$wgUser
Definition Setup.php:902
if(! $wgDBerrorLogTZ) $wgRequest
Definition Setup.php:737
Formats errors and warnings for the API, and add them to the associated ApiResult.
This is the main API class, used for both external and internal processing.
Definition ApiMain.php:43
static resetTokenCache()
static getTokenTypeSalts()
Get the salts for known token types.
static getToken(User $user, MediaWiki\Session\Session $session, $salt)
Get a token from a salt.
This class represents the result of the API operations.
Definition ApiResult.php:33
revisionDelete( $rev, array $value=[Revision::DELETED_TEXT=> 1], $comment='')
Revision-deletes a revision.
editPage( $pageName, $text, $summary='', $defaultNs=NS_MAIN)
Edits or creates a page/revision.
testApiTestGroup()
@coversNothing
static $errorFormatter
doApiRequestWithToken(array $params, array $session=null, User $user=null, $tokenType='auto')
Convenience function to access the token parameter of doApiRequest() more succinctly.
static $apiUrl
getTokenList(TestUser $user, $session=null)
doLogin( $testUser=null)
Previously this would do API requests to log in, as well as setting $wgUser and the request context's...
setExpectedApiException( $msg, $code=null, array $data=null, $httpCode=0)
Expect an ApiUsageException to be thrown with the given parameters, which are the same as ApiUsageExc...
static apiExceptionHasCode(ApiUsageException $ex, $code)
doApiRequest(array $params, array $session=null, $appendModule=false, User $user=null, $tokenType=null)
Does the API request and returns the result.
static getErrorFormatter()
ApiTestContext $apiContext
Exception used to abort API execution with an error.
static newWithMessage(ApiBase $module=null, $msg, $code=null, $data=null, $httpCode=0)
WebRequest clone which takes values from a provided array.
MediaWiki exception.
Base class that store and restore the Language objects.
setMwGlobals( $pairs, $value=null)
Sets a global, maintaining a stashed version of the previous global to be restored in tearDown.
This serves as the entry point to the MediaWiki session handling system.
static getMain()
Get the RequestContext object associated with the main request.
static createList( $typeName, IContextSource $context, Title $title, array $ids)
Instantiate the appropriate list class for a given list of IDs.
Wraps the user object, so we can also retain full access to properties like password if we log in via...
Definition TestUser.php:7
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition User.php:53
when a variable name is used in a function
Definition design.txt:94
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable & $code
Definition hooks.txt:865
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on and they can depend only on the ResourceLoaderContext $context
Definition hooks.txt:2811
presenting them properly to the user as errors is done by the caller return true use this to change the list i e etc $rev
Definition hooks.txt:1777
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a local account $user
Definition hooks.txt:247
returning false will NOT prevent logging $e
Definition hooks.txt:2176
const NS_MAIN
Definition Defines.php:74
A helper class for throttling authentication attempts.
$params