MediaWiki  1.32.0
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  '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
40 
41  parent::tearDown();
42  }
43 
63  protected function doApiRequest( array $params, array $session = null,
64  $appendModule = false, User $user = null, $tokenType = null
65  ) {
66  global $wgRequest, $wgUser;
67 
68  if ( is_null( $session ) ) {
69  // re-use existing global session by default
70  $session = $wgRequest->getSessionArray();
71  }
72 
73  $sessionObj = SessionManager::singleton()->getEmptySession();
74 
75  if ( $session !== null ) {
76  foreach ( $session as $key => $value ) {
77  $sessionObj->set( $key, $value );
78  }
79  }
80 
81  // set up global environment
82  if ( $user ) {
83  $wgUser = $user;
84  }
85 
86  if ( $tokenType !== null ) {
87  if ( $tokenType === 'auto' ) {
88  $tokenType = ( new ApiMain() )->getModuleManager()
89  ->getModule( $params['action'], 'action' )->needsToken();
90  }
92  $wgUser, $sessionObj, ApiQueryTokens::getTokenTypeSalts()[$tokenType]
93  )->toString();
94  }
95 
96  $wgRequest = new FauxRequest( $params, true, $sessionObj );
97  RequestContext::getMain()->setRequest( $wgRequest );
98  RequestContext::getMain()->setUser( $wgUser );
100 
101  // set up local environment
102  $context = $this->apiContext->newTestContext( $wgRequest, $wgUser );
103 
104  $module = new ApiMain( $context, true );
105 
106  // run it!
107  $module->execute();
108 
109  // construct result
110  $results = [
111  $module->getResult()->getResultData( null, [ 'Strip' => 'all' ] ),
112  $context->getRequest(),
113  $context->getRequest()->getSessionArray()
114  ];
115 
116  if ( $appendModule ) {
117  $results[] = $module;
118  }
119 
120  return $results;
121  }
122 
133  protected function doApiRequestWithToken( array $params, array $session = null,
134  User $user = null, $tokenType = 'auto'
135  ) {
136  return $this->doApiRequest( $params, $session, false, $user, $tokenType );
137  }
138 
149  protected function doLogin( $testUser = null ) {
150  global $wgUser;
151 
152  if ( $testUser === null ) {
153  $testUser = static::getTestSysop();
154  } elseif ( is_string( $testUser ) && array_key_exists( $testUser, self::$users ) ) {
155  $testUser = self::$users[$testUser];
156  } elseif ( !$testUser instanceof TestUser ) {
157  throw new MWException( "Can't log in to undefined user $testUser" );
158  }
159 
160  $wgUser = $testUser->getUser();
161  RequestContext::getMain()->setUser( $wgUser );
162  }
163 
164  protected function getTokenList( TestUser $user, $session = null ) {
165  $data = $this->doApiRequest( [
166  'action' => 'tokens',
167  'type' => 'edit|delete|protect|move|block|unblock|watch'
168  ], $session, false, $user->getUser() );
169 
170  if ( !array_key_exists( 'tokens', $data[0] ) ) {
171  throw new MWException( 'Api failed to return a token list' );
172  }
173 
174  return $data[0]['tokens'];
175  }
176 
177  protected static function getErrorFormatter() {
178  if ( self::$errorFormatter === null ) {
179  self::$errorFormatter = new ApiErrorFormatter(
180  new ApiResult( false ),
181  Language::factory( 'en' ),
182  'none'
183  );
184  }
185  return self::$errorFormatter;
186  }
187 
188  public static function apiExceptionHasCode( ApiUsageException $ex, $code ) {
189  return (bool)array_filter(
190  self::getErrorFormatter()->arrayFromStatus( $ex->getStatusValue() ),
191  function ( $e ) use ( $code ) {
192  return is_array( $e ) && $e['code'] === $code;
193  }
194  );
195  }
196 
200  public function testApiTestGroup() {
201  $groups = PHPUnit_Util_Test::getGroups( static::class );
202  $constraint = PHPUnit_Framework_Assert::logicalOr(
203  $this->contains( 'medium' ),
204  $this->contains( 'large' )
205  );
206  $this->assertThat( $groups, $constraint,
207  'ApiTestCase::setUp can be slow, tests must be "medium" or "large"'
208  );
209  }
210 
217  protected function setExpectedApiException(
218  $msg, $code = null, array $data = null, $httpCode = 0
219  ) {
220  $expected = ApiUsageException::newWithMessage( null, $msg, $code, $data, $httpCode );
221  $this->setExpectedException( ApiUsageException::class, $expected->getMessage() );
222  }
223 }
ApiUsageException\getStatusValue
getStatusValue()
Fetch the error status.
Definition: ApiUsageException.php:101
ApiMain
This is the main API class, used for both external and internal processing.
Definition: ApiMain.php:41
ApiTestCase\$errorFormatter
static $errorFormatter
Definition: ApiTestCase.php:8
$user
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 account $user
Definition: hooks.txt:244
FauxRequest
WebRequest clone which takes values from a provided array.
Definition: FauxRequest.php:33
ApiUsageException
Exception used to abort API execution with an error.
Definition: ApiUsageException.php:28
$context
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:2675
ApiTestCase\tearDown
tearDown()
Definition: ApiTestCase.php:37
ApiQueryInfo\resetTokenCache
static resetTokenCache()
Definition: ApiQueryInfo.php:126
$params
$params
Definition: styleTest.css.php:44
ApiTestCase\testApiTestGroup
testApiTestGroup()
@coversNothing
Definition: ApiTestCase.php:200
ApiUsageException\newWithMessage
static newWithMessage(ApiBase $module=null, $msg, $code=null, $data=null, $httpCode=0)
Definition: ApiUsageException.php:63
php
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
TestUser
Wraps the user object, so we can also retain full access to properties like password if we log in via...
Definition: TestUser.php:9
ApiTestCase\getTokenList
getTokenList(TestUser $user, $session=null)
Definition: ApiTestCase.php:164
ApiTestCase\doApiRequest
doApiRequest(array $params, array $session=null, $appendModule=false, User $user=null, $tokenType=null)
Does the API request and returns the result.
Definition: ApiTestCase.php:63
MWException
MediaWiki exception.
Definition: MWException.php:26
wfScript
wfScript( $script='index')
Get the path to a specified script file, respecting file extensions; this is a wrapper around $wgScri...
Definition: GlobalFunctions.php:2771
ApiResult
This class represents the result of the API operations.
Definition: ApiResult.php:35
ApiTestCase\$apiUrl
static $apiUrl
Definition: ApiTestCase.php:6
MediaWikiTestCase\setMwGlobals
setMwGlobals( $pairs, $value=null)
Sets a global, maintaining a stashed version of the previous global to be restored in tearDown.
Definition: MediaWikiTestCase.php:706
ApiQueryTokens\getTokenTypeSalts
static getTokenTypeSalts()
Get the salts for known token types.
Definition: ApiQueryTokens.php:63
MediaWiki
A helper class for throttling authentication attempts.
ApiTestCase\setUp
setUp()
Definition: ApiTestCase.php:15
use
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:10
$code
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:813
ApiTestCase\doApiRequestWithToken
doApiRequestWithToken(array $params, array $session=null, User $user=null, $tokenType='auto')
Convenience function to access the token parameter of doApiRequest() more succinctly.
Definition: ApiTestCase.php:133
array
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))
MediaWiki\Auth\AuthManager\resetCache
static resetCache()
Reset the internal caching for unit testing.
Definition: AuthManager.php:2449
MediaWiki\Session\SessionManager\getGlobalSession
static getGlobalSession()
Get the "global" session.
Definition: SessionManager.php:107
$e
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2213
ApiTestCase
Definition: ApiTestCase.php:5
$value
$value
Definition: styleTest.css.php:49
ApiTestContext
Definition: ApiTestContext.php:3
$wgServer
$wgServer
URL of the server.
Definition: DefaultSettings.php:105
MediaWiki\Session\SessionManager
This serves as the entry point to the MediaWiki session handling system.
Definition: SessionManager.php:50
MediaWikiLangTestCase
Base class that store and restore the Language objects.
Definition: MediaWikiLangTestCase.php:8
RequestContext\getMain
static getMain()
Get the RequestContext object associated with the main request.
Definition: RequestContext.php:432
ApiErrorFormatter
Formats errors and warnings for the API, and add them to the associated ApiResult.
Definition: ApiErrorFormatter.php:30
ApiTestCase\$apiContext
ApiTestContext $apiContext
Definition: ApiTestCase.php:13
ApiTestCase\setExpectedApiException
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...
Definition: ApiTestCase.php:217
ApiQueryTokens\getToken
static getToken(User $user, MediaWiki\Session\Session $session, $salt)
Get a token from a salt.
Definition: ApiQueryTokens.php:94
ApiTestCase\apiExceptionHasCode
static apiExceptionHasCode(ApiUsageException $ex, $code)
Definition: ApiTestCase.php:188
ApiTestCase\getErrorFormatter
static getErrorFormatter()
Definition: ApiTestCase.php:177
ApiTestCase\doLogin
doLogin( $testUser=null)
Previously this would do API requests to log in, as well as setting $wgUser and the request context's...
Definition: ApiTestCase.php:149
as
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
Language\factory
static factory( $code)
Get a cached or new language object for a given language code.
Definition: Language.php:214
class
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
$wgRequest
if(! $wgDBerrorLogTZ) $wgRequest
Definition: Setup.php:747
contains
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
User
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition: User.php:47