MediaWiki  master
ApiTestCase.php
Go to the documentation of this file.
1 <?php
2 
4 
5 abstract 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  'wgRequest' => new FauxRequest( [] ),
30  'wgUser' => self::$users['sysop']->getUser(),
31  ] );
32 
33  $this->apiContext = new ApiTestContext();
34  }
35 
36  protected function tearDown() {
37  // Avoid leaking session over tests
39 
40  parent::tearDown();
41  }
42 
62  protected function doApiRequest( array $params, array $session = null,
63  $appendModule = false, User $user = null, $tokenType = null
64  ) {
65  global $wgRequest, $wgUser;
66 
67  if ( is_null( $session ) ) {
68  // re-use existing global session by default
69  $session = $wgRequest->getSessionArray();
70  }
71 
72  $sessionObj = SessionManager::singleton()->getEmptySession();
73 
74  if ( $session !== null ) {
75  foreach ( $session as $key => $value ) {
76  $sessionObj->set( $key, $value );
77  }
78  }
79 
80  // set up global environment
81  if ( $user ) {
82  $wgUser = $user;
83  }
84 
85  if ( $tokenType !== null ) {
86  if ( $tokenType === 'auto' ) {
87  $tokenType = ( new ApiMain() )->getModuleManager()
88  ->getModule( $params['action'], 'action' )->needsToken();
89  }
90  $params['token'] = ApiQueryTokens::getToken(
91  $wgUser, $sessionObj, ApiQueryTokens::getTokenTypeSalts()[$tokenType]
92  )->toString();
93  }
94 
95  $wgRequest = new FauxRequest( $params, true, $sessionObj );
96  RequestContext::getMain()->setRequest( $wgRequest );
97  RequestContext::getMain()->setUser( $wgUser );
99 
100  // set up local environment
101  $context = $this->apiContext->newTestContext( $wgRequest, $wgUser );
102 
103  $module = new ApiMain( $context, true );
104 
105  // run it!
106  $module->execute();
107 
108  // construct result
109  $results = [
110  $module->getResult()->getResultData( null, [ 'Strip' => 'all' ] ),
111  $context->getRequest(),
112  $context->getRequest()->getSessionArray()
113  ];
114 
115  if ( $appendModule ) {
116  $results[] = $module;
117  }
118 
119  return $results;
120  }
121 
132  protected function doApiRequestWithToken( array $params, array $session = null,
133  User $user = null, $tokenType = 'auto'
134  ) {
135  return $this->doApiRequest( $params, $session, false, $user, $tokenType );
136  }
137 
148  protected function doLogin( $testUser = null ) {
149  global $wgUser;
150 
151  if ( $testUser === null ) {
152  $testUser = static::getTestSysop();
153  } elseif ( is_string( $testUser ) && array_key_exists( $testUser, self::$users ) ) {
154  $testUser = self::$users[$testUser];
155  } elseif ( !$testUser instanceof TestUser ) {
156  throw new MWException( "Can't log in to undefined user $testUser" );
157  }
158 
159  $wgUser = $testUser->getUser();
160  RequestContext::getMain()->setUser( $wgUser );
161  }
162 
163  protected function getTokenList( TestUser $user, $session = null ) {
164  $data = $this->doApiRequest( [
165  'action' => 'tokens',
166  'type' => 'edit|delete|protect|move|block|unblock|watch'
167  ], $session, false, $user->getUser() );
168 
169  if ( !array_key_exists( 'tokens', $data[0] ) ) {
170  throw new MWException( 'Api failed to return a token list' );
171  }
172 
173  return $data[0]['tokens'];
174  }
175 
176  protected static function getErrorFormatter() {
177  if ( self::$errorFormatter === null ) {
178  self::$errorFormatter = new ApiErrorFormatter(
179  new ApiResult( false ),
180  Language::factory( 'en' ),
181  'none'
182  );
183  }
184  return self::$errorFormatter;
185  }
186 
187  public static function apiExceptionHasCode( ApiUsageException $ex, $code ) {
188  return (bool)array_filter(
189  self::getErrorFormatter()->arrayFromStatus( $ex->getStatusValue() ),
190  function ( $e ) use ( $code ) {
191  return is_array( $e ) && $e['code'] === $code;
192  }
193  );
194  }
195 
199  public function testApiTestGroup() {
200  $groups = PHPUnit_Util_Test::getGroups( static::class );
201  $constraint = PHPUnit_Framework_Assert::logicalOr(
202  $this->contains( 'medium' ),
203  $this->contains( 'large' )
204  );
205  $this->assertThat( $groups, $constraint,
206  'ApiTestCase::setUp can be slow, tests must be "medium" or "large"'
207  );
208  }
209 
216  protected function setExpectedApiException(
217  $msg, $code = null, array $data = null, $httpCode = 0
218  ) {
219  $expected = ApiUsageException::newWithMessage( null, $msg, $code, $data, $httpCode );
220  $this->setExpectedException( ApiUsageException::class, $expected->getMessage() );
221  }
222 }
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
$data
Utility to generate mapping file used in mw.Title (phpCharToUpper.json)
Formats errors and warnings for the API, and add them to the associated ApiResult.
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2159
static newWithMessage(ApiBase $module=null, $msg, $code=null, $data=null, $httpCode=0)
Exception used to abort API execution with an error.
doApiRequest(array $params, array $session=null, $appendModule=false, User $user=null, $tokenType=null)
Does the API request and returns the result.
Definition: ApiTestCase.php:62
$value
doApiRequestWithToken(array $params, array $session=null, User $user=null, $tokenType='auto')
Convenience function to access the token parameter of doApiRequest() more succinctly.
The User object encapsulates all of the user-specific settings (user_id, name, rights, email address, options, last login time).
Definition: User.php:48
wfScript( $script='index')
Get the path to a specified script file, respecting file extensions; this is a wrapper around $wgScri...
static resetCache()
Reset the internal caching for unit testing.
getTokenList(TestUser $user, $session=null)
static getMain()
Get the RequestContext object associated with the main request.
$params
This is the main API class, used for both external and internal processing.
Definition: ApiMain.php:41
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:780
static factory( $code)
Get a cached or new language object for a given language code.
Definition: Language.php:215
This class represents the result of the API operations.
Definition: ApiResult.php:35
static $apiUrl
Definition: ApiTestCase.php:6
setMwGlobals( $pairs, $value=null)
Sets a global, maintaining a stashed version of the previous global to be restored in tearDown...
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not it can be in the form of< username >< more info > e g for bot passwords intended to be added to log contexts Fields it might only if the login was with a bot password 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:780
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
ApiTestContext $apiContext
Definition: ApiTestCase.php:13
static getTokenTypeSalts()
Get the salts for known token types.
static getGlobalSession()
Get the "global" session.
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
Definition: maintenance.txt:52
static getToken(User $user, MediaWiki\Session\Session $session, $salt)
Get a token from a salt.
static getErrorFormatter()
Wraps the user object, so we can also retain full access to properties like password if we log in via...
Definition: TestUser.php:9
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:2633
if(! $wgDBerrorLogTZ) $wgRequest
Definition: Setup.php:728
$wgServer
URL of the server.
doLogin( $testUser=null)
Previously this would do API requests to log in, as well as setting $wgUser and the request context&#39;s...
getStatusValue()
Fetch the error status.
static $errorFormatter
Definition: ApiTestCase.php:8
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 resetTokenCache()
static apiExceptionHasCode(ApiUsageException $ex, $code)
return true to allow those checks to and false if checking is done & $user
Definition: hooks.txt:1473