MediaWiki  1.28.1
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 
11  protected function setUp() {
13 
14  parent::setUp();
15  self::$apiUrl = $wgServer . wfScript( 'api' );
16 
17  ApiQueryInfo::resetTokenCache(); // tokens are invalid because we cleared the session
18 
19  self::$users = [
20  'sysop' => static::getTestSysop(),
21  'uploader' => static::getTestUser(),
22  ];
23 
24  $this->setMwGlobals( [
25  'wgAuth' => new MediaWiki\Auth\AuthManagerAuthPlugin,
26  'wgRequest' => new FauxRequest( [] ),
27  'wgUser' => self::$users['sysop']->getUser(),
28  ] );
29 
30  $this->apiContext = new ApiTestContext();
31  }
32 
33  protected function tearDown() {
34  // Avoid leaking session over tests
36 
37  parent::tearDown();
38  }
39 
48  protected function editPage( $pageName, $text, $summary = '', $defaultNs = NS_MAIN ) {
49  $title = Title::newFromText( $pageName, $defaultNs );
51 
52  return $page->doEditContent( ContentHandler::makeContent( $text, $title ), $summary );
53  }
54 
71  protected function doApiRequest( array $params, array $session = null,
72  $appendModule = false, User $user = null
73  ) {
75 
76  if ( is_null( $session ) ) {
77  // re-use existing global session by default
78  $session = $wgRequest->getSessionArray();
79  }
80 
81  // set up global environment
82  if ( $user ) {
83  $wgUser = $user;
84  }
85 
86  $wgRequest = new FauxRequest( $params, true, $session );
87  RequestContext::getMain()->setRequest( $wgRequest );
88  RequestContext::getMain()->setUser( $wgUser );
90 
91  // set up local environment
92  $context = $this->apiContext->newTestContext( $wgRequest, $wgUser );
93 
94  $module = new ApiMain( $context, true );
95 
96  // run it!
97  $module->execute();
98 
99  // construct result
100  $results = [
101  $module->getResult()->getResultData( null, [ 'Strip' => 'all' ] ),
102  $context->getRequest(),
103  $context->getRequest()->getSessionArray()
104  ];
105 
106  if ( $appendModule ) {
107  $results[] = $module;
108  }
109 
110  return $results;
111  }
112 
125  protected function doApiRequestWithToken( array $params, array $session = null,
126  User $user = null
127  ) {
129 
130  if ( $session === null ) {
131  $session = $wgRequest->getSessionArray();
132  }
133 
134  if ( isset( $session['wsToken'] ) && $session['wsToken'] ) {
135  // @todo Why does this directly mess with the session? Fix that.
136  // add edit token to fake session
137  $session['wsTokenSecrets']['default'] = $session['wsToken'];
138  // add token to request parameters
140  $params['token'] = hash_hmac( 'md5', $timestamp, $session['wsToken'] ) .
141  dechex( $timestamp ) .
143 
144  return $this->doApiRequest( $params, $session, false, $user );
145  } else {
146  throw new Exception( "Session token not available" );
147  }
148  }
149 
150  protected function doLogin( $testUser = 'sysop' ) {
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 not log in to undefined user $testUser" );
157  }
158 
159  $data = $this->doApiRequest( [
160  'action' => 'login',
161  'lgname' => $testUser->getUser()->getName(),
162  'lgpassword' => $testUser->getPassword() ] );
163 
164  $token = $data[0]['login']['token'];
165 
166  $data = $this->doApiRequest(
167  [
168  'action' => 'login',
169  'lgtoken' => $token,
170  'lgname' => $testUser->getUser()->getName(),
171  'lgpassword' => $testUser->getPassword(),
172  ],
173  $data[2]
174  );
175 
176  if ( $data[0]['login']['result'] === 'Success' ) {
177  // DWIM
178  global $wgUser;
179  $wgUser = $testUser->getUser();
180  RequestContext::getMain()->setUser( $wgUser );
181  }
182 
183  return $data;
184  }
185 
186  protected function getTokenList( TestUser $user, $session = null ) {
187  $data = $this->doApiRequest( [
188  'action' => 'tokens',
189  'type' => 'edit|delete|protect|move|block|unblock|watch'
190  ], $session, false, $user->getUser() );
191 
192  if ( !array_key_exists( 'tokens', $data[0] ) ) {
193  throw new MWException( 'Api failed to return a token list' );
194  }
195 
196  return $data[0]['tokens'];
197  }
198 
199  public function testApiTestGroup() {
200  $groups = PHPUnit_Util_Test::getGroups( get_class( $this ) );
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 }
static factory(Title $title)
Create a WikiPage object of the appropriate class for the given title.
Definition: WikiPage.php:115
the array() calling protocol came about after MediaWiki 1.4rc1.
$context
Definition: load.php:50
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:56
if(!$wgDBerrorLogTZ) $wgRequest
Definition: Setup.php:664
static newFromText($text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:262
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.
static resetCache()
Reset the internal caching for unit testing.
getTokenList(TestUser $user, $session=null)
static getMain()
Static methods.
if($limit) $timestamp
doLogin($testUser= 'sysop')
$summary
$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:43
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:953
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:71
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:48
$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()
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:2491
$wgUser
Definition: Setup.php:806