MediaWiki  1.29.2
ApiTestCase.php
Go to the documentation of this file.
1 <?php
2 
3 abstract class ApiTestCase extends MediaWikiLangTestCase {
4  protected static $apiUrl;
5 
6  protected static $errorFormatter = null;
7 
11  protected $apiContext;
12 
13  protected function setUp() {
15 
16  parent::setUp();
17  self::$apiUrl = $wgServer . wfScript( 'api' );
18 
19  ApiQueryInfo::resetTokenCache(); // tokens are invalid because we cleared the session
20 
21  self::$users = [
22  'sysop' => static::getTestSysop(),
23  'uploader' => static::getTestUser(),
24  ];
25 
26  $this->setMwGlobals( [
27  'wgAuth' => new MediaWiki\Auth\AuthManagerAuthPlugin,
28  'wgRequest' => new FauxRequest( [] ),
29  'wgUser' => self::$users['sysop']->getUser(),
30  ] );
31 
32  $this->apiContext = new ApiTestContext();
33  }
34 
35  protected function tearDown() {
36  // Avoid leaking session over tests
38 
39  parent::tearDown();
40  }
41 
50  protected function editPage( $pageName, $text, $summary = '', $defaultNs = NS_MAIN ) {
51  $title = Title::newFromText( $pageName, $defaultNs );
53 
54  return $page->doEditContent( ContentHandler::makeContent( $text, $title ), $summary );
55  }
56 
73  protected function doApiRequest( array $params, array $session = null,
74  $appendModule = false, User $user = null
75  ) {
77 
78  if ( is_null( $session ) ) {
79  // re-use existing global session by default
80  $session = $wgRequest->getSessionArray();
81  }
82 
83  // set up global environment
84  if ( $user ) {
85  $wgUser = $user;
86  }
87 
88  $wgRequest = new FauxRequest( $params, true, $session );
89  RequestContext::getMain()->setRequest( $wgRequest );
90  RequestContext::getMain()->setUser( $wgUser );
92 
93  // set up local environment
94  $context = $this->apiContext->newTestContext( $wgRequest, $wgUser );
95 
96  $module = new ApiMain( $context, true );
97 
98  // run it!
99  $module->execute();
100 
101  // construct result
102  $results = [
103  $module->getResult()->getResultData( null, [ 'Strip' => 'all' ] ),
104  $context->getRequest(),
105  $context->getRequest()->getSessionArray()
106  ];
107 
108  if ( $appendModule ) {
109  $results[] = $module;
110  }
111 
112  return $results;
113  }
114 
127  protected function doApiRequestWithToken( array $params, array $session = null,
128  User $user = null
129  ) {
131 
132  if ( $session === null ) {
133  $session = $wgRequest->getSessionArray();
134  }
135 
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 ) .
145 
146  return $this->doApiRequest( $params, $session, false, $user );
147  } else {
148  throw new Exception( "Session token not available" );
149  }
150  }
151 
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" );
159  }
160 
161  $data = $this->doApiRequest( [
162  'action' => 'login',
163  'lgname' => $testUser->getUser()->getName(),
164  'lgpassword' => $testUser->getPassword() ] );
165 
166  $token = $data[0]['login']['token'];
167 
168  $data = $this->doApiRequest(
169  [
170  'action' => 'login',
171  'lgtoken' => $token,
172  'lgname' => $testUser->getUser()->getName(),
173  'lgpassword' => $testUser->getPassword(),
174  ],
175  $data[2]
176  );
177 
178  if ( $data[0]['login']['result'] === 'Success' ) {
179  // DWIM
180  global $wgUser;
181  $wgUser = $testUser->getUser();
182  RequestContext::getMain()->setUser( $wgUser );
183  }
184 
185  return $data;
186  }
187 
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() );
193 
194  if ( !array_key_exists( 'tokens', $data[0] ) ) {
195  throw new MWException( 'Api failed to return a token list' );
196  }
197 
198  return $data[0]['tokens'];
199  }
200 
201  protected static function getErrorFormatter() {
202  if ( self::$errorFormatter === null ) {
203  self::$errorFormatter = new ApiErrorFormatter(
204  new ApiResult( false ),
205  Language::factory( 'en' ),
206  'none'
207  );
208  }
209  return self::$errorFormatter;
210  }
211 
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;
217  }
218  );
219  }
220 
221  public function testApiTestGroup() {
222  $groups = PHPUnit_Util_Test::getGroups( static::class );
223  $constraint = PHPUnit_Framework_Assert::logicalOr(
224  $this->contains( 'medium' ),
225  $this->contains( 'large' )
226  );
227  $this->assertThat( $groups, $constraint,
228  'ApiTestCase::setUp can be slow, tests must be "medium" or "large"'
229  );
230  }
231 }
ApiUsageException\getStatusValue
getStatusValue()
Fetch the error status.
Definition: ApiUsageException.php:176
ApiMain
This is the main API class, used for both external and internal processing.
Definition: ApiMain.php:45
ApiTestCase\$errorFormatter
static $errorFormatter
Definition: ApiTestCase.php:6
$wgUser
$wgUser
Definition: Setup.php:781
$context
error also a ContextSource you ll probably need to make sure the header is varied on and they can depend only on the ResourceLoaderContext $context
Definition: hooks.txt:2612
FauxRequest
WebRequest clone which takes values from a provided array.
Definition: FauxRequest.php:33
Title\newFromText
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:265
ApiUsageException
Exception used to abort API execution with an error.
Definition: ApiUsageException.php:98
ApiTestCase\tearDown
tearDown()
Definition: ApiTestCase.php:35
ApiQueryInfo\resetTokenCache
static resetTokenCache()
Definition: ApiQueryInfo.php:130
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1994
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
$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:246
$params
$params
Definition: styleTest.css.php:40
ContextSource\getRequest
getRequest()
Get the WebRequest object.
Definition: ContextSource.php:78
ApiTestCase\testApiTestGroup
testApiTestGroup()
Definition: ApiTestCase.php:221
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:7
NS_MAIN
const NS_MAIN
Definition: Defines.php:62
ApiTestCase\getTokenList
getTokenList(TestUser $user, $session=null)
Definition: ApiTestCase.php:188
MWException
MediaWiki exception.
Definition: MWException.php:26
$title
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:934
WikiPage\factory
static factory(Title $title)
Create a WikiPage object of the appropriate class for the given title.
Definition: WikiPage.php:120
wfScript
wfScript( $script='index')
Get the path to a specified script file, respecting file extensions; this is a wrapper around $wgScri...
Definition: GlobalFunctions.php:3138
ApiResult
This class represents the result of the API operations.
Definition: ApiResult.php:33
ApiTestCase\$apiUrl
static $apiUrl
Definition: ApiTestCase.php:4
MediaWikiTestCase\setMwGlobals
setMwGlobals( $pairs, $value=null)
Definition: MediaWikiTestCase.php:658
$page
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached $page
Definition: hooks.txt:2536
MediaWiki
A helper class for throttling authentication attempts.
ApiTestCase\setUp
setUp()
Definition: ApiTestCase.php:13
global
when a variable name is used in a it is silently declared as a new masking the global
Definition: design.txt:93
MediaWiki\Auth\AuthManager\resetCache
static resetCache()
Reset the internal caching for unit testing.
Definition: AuthManager.php:2433
ContentHandler\makeContent
static makeContent( $text, Title $title=null, $modelId=null, $format=null)
Convenience function for creating a Content object from a given textual representation.
Definition: ContentHandler.php:129
ApiTestCase\doLogin
doLogin( $testUser='sysop')
Definition: ApiTestCase.php:152
MediaWiki\Session\SessionManager\getGlobalSession
static getGlobalSession()
Get the "global" session.
Definition: SessionManager.php:106
$e
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2122
ApiTestCase
Definition: ApiTestCase.php:3
ApiTestCase\editPage
editPage( $pageName, $text, $summary='', $defaultNs=NS_MAIN)
Edits or creates a page/revision.
Definition: ApiTestCase.php:50
ApiTestContext
Definition: ApiTestContext.php:3
$wgServer
$wgServer
URL of the server.
Definition: DefaultSettings.php:109
MediaWikiLangTestCase
Base class that store and restore the Language objects.
Definition: MediaWikiLangTestCase.php:6
RequestContext\getMain
static getMain()
Static methods.
Definition: RequestContext.php:468
ApiErrorFormatter
Formats errors and warnings for the API, and add them to the associated ApiResult.
Definition: ApiErrorFormatter.php:30
ApiTestCase\doApiRequest
doApiRequest(array $params, array $session=null, $appendModule=false, User $user=null)
Does the API request and returns the result.
Definition: ApiTestCase.php:73
MediaWiki\Session\Token\SUFFIX
const SUFFIX
CSRF token suffix.
Definition: Token.php:35
ApiTestCase\$apiContext
ApiTestContext $apiContext
Definition: ApiTestCase.php:11
ApiTestCase\apiExceptionHasCode
static apiExceptionHasCode(ApiUsageException $ex, $code)
Definition: ApiTestCase.php:212
$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:783
ApiTestCase\getErrorFormatter
static getErrorFormatter()
Definition: ApiTestCase.php:201
Language\factory
static factory( $code)
Get a cached or new language object for a given language code.
Definition: Language.php:183
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
ApiTestCase\doApiRequestWithToken
doApiRequestWithToken(array $params, array $session=null, User $user=null)
Add an edit token to the API request This is cheating a bit – we grab a token in the correct format a...
Definition: ApiTestCase.php:127
$wgRequest
if(! $wgDBerrorLogTZ) $wgRequest
Definition: Setup.php:639
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:50
array
the array() calling protocol came about after MediaWiki 1.4rc1.