MediaWiki  1.27.2
ApiTestCase.php
Go to the documentation of this file.
1 <?php
2 
3 abstract class ApiTestCase extends MediaWikiLangTestCase {
4  protected static $apiUrl;
5 
9  protected $apiContext;
10 
14  protected $tablesUsed = [ 'user', 'user_groups', 'user_properties' ];
15 
16  protected function setUp() {
18 
19  parent::setUp();
20  self::$apiUrl = $wgServer . wfScript( 'api' );
21 
22  ApiQueryInfo::resetTokenCache(); // tokens are invalid because we cleared the session
23 
24  self::$users = [
25  'sysop' => new TestUser(
26  'Apitestsysop',
27  'Api Test Sysop',
28  'api_test_sysop@example.com',
29  [ 'sysop' ]
30  ),
31  'uploader' => new TestUser(
32  'Apitestuser',
33  'Api Test User',
34  'api_test_user@example.com',
35  []
36  )
37  ];
38 
39  $this->setMwGlobals( [
40  'wgAuth' => new MediaWiki\Auth\AuthManagerAuthPlugin,
41  'wgRequest' => new FauxRequest( [] ),
42  'wgUser' => self::$users['sysop']->user,
43  ] );
44 
45  $this->apiContext = new ApiTestContext();
46  }
47 
48  protected function tearDown() {
49  // Avoid leaking session over tests
51 
52  parent::tearDown();
53  }
54 
63  protected function editPage( $pageName, $text, $summary = '', $defaultNs = NS_MAIN ) {
64  $title = Title::newFromText( $pageName, $defaultNs );
66 
67  return $page->doEditContent( ContentHandler::makeContent( $text, $title ), $summary );
68  }
69 
86  protected function doApiRequest( array $params, array $session = null,
87  $appendModule = false, User $user = null
88  ) {
90 
91  if ( is_null( $session ) ) {
92  // re-use existing global session by default
93  $session = $wgRequest->getSessionArray();
94  }
95 
96  // set up global environment
97  if ( $user ) {
98  $wgUser = $user;
99  }
100 
101  $wgRequest = new FauxRequest( $params, true, $session );
102  RequestContext::getMain()->setRequest( $wgRequest );
103  RequestContext::getMain()->setUser( $wgUser );
105 
106  // set up local environment
107  $context = $this->apiContext->newTestContext( $wgRequest, $wgUser );
108 
109  $module = new ApiMain( $context, true );
110 
111  // run it!
112  $module->execute();
113 
114  // construct result
115  $results = [
116  $module->getResult()->getResultData( null, [ 'Strip' => 'all' ] ),
117  $context->getRequest(),
118  $context->getRequest()->getSessionArray()
119  ];
120 
121  if ( $appendModule ) {
122  $results[] = $module;
123  }
124 
125  return $results;
126  }
127 
140  protected function doApiRequestWithToken( array $params, array $session = null,
141  User $user = null
142  ) {
144 
145  if ( $session === null ) {
146  $session = $wgRequest->getSessionArray();
147  }
148 
149  if ( isset( $session['wsToken'] ) && $session['wsToken'] ) {
150  // @todo Why does this directly mess with the session? Fix that.
151  // add edit token to fake session
152  $session['wsTokenSecrets']['default'] = $session['wsToken'];
153  // add token to request parameters
155  $params['token'] = hash_hmac( 'md5', $timestamp, $session['wsToken'] ) .
156  dechex( $timestamp ) .
158 
159  return $this->doApiRequest( $params, $session, false, $user );
160  } else {
161  throw new Exception( "Session token not available" );
162  }
163  }
164 
165  protected function doLogin( $user = 'sysop' ) {
166  if ( !array_key_exists( $user, self::$users ) ) {
167  throw new MWException( "Can not log in to undefined user $user" );
168  }
169 
170  $data = $this->doApiRequest( [
171  'action' => 'login',
172  'lgname' => self::$users[$user]->username,
173  'lgpassword' => self::$users[$user]->password ] );
174 
175  $token = $data[0]['login']['token'];
176 
177  $data = $this->doApiRequest(
178  [
179  'action' => 'login',
180  'lgtoken' => $token,
181  'lgname' => self::$users[$user]->username,
182  'lgpassword' => self::$users[$user]->password,
183  ],
184  $data[2]
185  );
186 
187  if ( $data[0]['login']['result'] === 'Success' ) {
188  // DWIM
189  global $wgUser;
190  $wgUser = self::$users[$user]->getUser();
191  RequestContext::getMain()->setUser( $wgUser );
192  }
193 
194  return $data;
195  }
196 
197  protected function getTokenList( $user, $session = null ) {
198  $data = $this->doApiRequest( [
199  'action' => 'tokens',
200  'type' => 'edit|delete|protect|move|block|unblock|watch'
201  ], $session, false, $user->user );
202 
203  if ( !array_key_exists( 'tokens', $data[0] ) ) {
204  throw new MWException( 'Api failed to return a token list' );
205  }
206 
207  return $data[0]['tokens'];
208  }
209 
210  public function testApiTestGroup() {
211  $groups = PHPUnit_Util_Test::getGroups( get_class( $this ) );
212  $constraint = PHPUnit_Framework_Assert::logicalOr(
213  $this->contains( 'medium' ),
214  $this->contains( 'large' )
215  );
216  $this->assertThat( $groups, $constraint,
217  'ApiTestCase::setUp can be slow, tests must be "medium" or "large"'
218  );
219  }
220 }
static factory(Title $title)
Create a WikiPage object of the appropriate class for the given title.
Definition: WikiPage.php:99
the array() calling protocol came about after MediaWiki 1.4rc1.
$context
Definition: load.php:44
wfScript($script= 'index')
Get the path to a specified script file, respecting file extensions; this is a wrapper around $wgScri...
const SUFFIX
CSRF token suffix.
Definition: Token.php:35
const NS_MAIN
Definition: Defines.php:69
static newFromText($text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:277
A helper class for throttling authentication attempts.
when a variable name is used in a it is silently declared as a new local masking the global
Definition: design.txt:93
wfTimestamp($outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
getTokenList($user, $session=null)
static resetCache()
Reset the internal caching for unit testing.
static getMain()
Static methods.
if($limit) $timestamp
$summary
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 and we might be restricted by PHP settings such as safe mode or open_basedir We cannot assume that the software even has read access anywhere useful Many shared hosts run all users web applications under the same user
Wikitext formatted, in the key only.
Definition: distributors.txt:9
$params
Base class that store and restore the Language objects.
This is the main API class, used for both external and internal processing.
Definition: ApiMain.php:41
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:912
doLogin($user= 'sysop')
static makeContent($text, Title $title=null, $modelId=null, $format=null)
Convenience function for creating a Content object from a given textual representation.
static $apiUrl
Definition: ApiTestCase.php:4
ApiTestContext $apiContext
Definition: ApiTestCase.php:9
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:242
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
doApiRequest(array $params, array $session=null, $appendModule=false, User $user=null)
Does the API request and returns the result.
Definition: ApiTestCase.php:86
array $tablesUsed
Definition: ApiTestCase.php:14
Wraps the user object, so we can also retain full access to properties like password if we log in via...
Definition: TestUser.php:7
editPage($pageName, $text, $summary= '', $defaultNs=NS_MAIN)
Edits or creates a page/revision.
Definition: ApiTestCase.php:63
$wgServer
URL of the server.
setMwGlobals($pairs, $value=null)
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 ...
static resetTokenCache()
if(is_null($wgLocalTZoffset)) if(!$wgDBerrorLogTZ) $wgRequest
Definition: Setup.php:657
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:2338
$wgUser
Definition: Setup.php:794