wiki.techinc.nl/tests/phpunit/includes/api/ApiTestCase.php

217 lines
5.6 KiB
PHP
Raw Normal View History

<?php
2011-05-01 23:02:27 +00:00
abstract class ApiTestCase extends MediaWikiLangTestCase {
protected static $apiUrl;
2011-10-27 01:06:50 +00:00
/**
* @var ApiTestContext
*/
protected $apiContext;
/**
* @var array
*/
protected $tablesUsed = array( 'user', 'user_groups', 'user_properties' );
Clean and repair many phpunit tests (+ fix implied configuration) This commit depends on the introduction of MediaWikiTestCase::setMwGlobals in change Iccf6ea81f4. Various tests already set their globals, but forgot to restore them afterwards, or forgot to call the parent setUp, tearDown... Either way they won't have to anymore with setMwGlobals. Consistent use of function characteristics: * protected function setUp * protected function tearDown * public static function (provide..) (Matching the function signature with PHPUnit/Framework/TestCase.php) Replaces: * public function (setUp|tearDown)\( * protected function $1( * \tfunction (setUp|tearDown)\( * \tprotected function $1( * \tfunction (data|provide)\( * \tpublic static function $1\( Also renamed a few "data#", "provider#" and "provides#" functions to "provide#" for consistency. This also removes confusion where the /media tests had a few private methods called dataFile(), which were sometimes expected to be data providers. Fixes: TimestampTest often failed due to a previous test setting a different language (it tests "1 hour ago" so need to make sure it is set to English). MWNamespaceTest became a lot cleaner now that it executes with a known context. Though the now-redundant code that was removed didn't work anyway because wgContentNamespaces isn't keyed by namespace id, it had them was values... FileBackendTest: * Fixed: "PHP Fatal: Using $this when not in object context" HttpTest * Added comment about: "PHP Fatal: Call to protected MWHttpRequest::__construct()" (too much unrelated code to fix in this commit) ExternalStoreTest * Add an assertTrue as well, without it the test is useless because regardless of whether wgExternalStores is true or false it only uses it if it is an array. Change-Id: I9d2b148e57bada64afeb7d5a99bec0e58f8e1561
2012-10-08 10:56:20 +00:00
protected function setUp() {
global $wgServer;
2011-05-01 23:02:27 +00:00
parent::setUp();
self::$apiUrl = $wgServer . wfScript( 'api' );
ApiQueryInfo::resetTokenCache(); // tokens are invalid because we cleared the session
self::$users = array(
'sysop' => new TestUser(
'Apitestsysop',
'Api Test Sysop',
'api_test_sysop@example.com',
array( 'sysop' )
),
'uploader' => new TestUser(
'Apitestuser',
'Api Test User',
'api_test_user@example.com',
array()
)
);
$this->setMwGlobals( array(
'wgMemc' => new EmptyBagOStuff(),
'wgAuth' => new StubObject( 'wgAuth', 'AuthPlugin' ),
'wgRequest' => new FauxRequest( array() ),
'wgUser' => self::$users['sysop']->user,
) );
2011-10-27 01:06:50 +00:00
$this->apiContext = new ApiTestContext();
}
protected function tearDown() {
// Avoid leaking session over tests
if ( session_id() != '' ) {
global $wgUser;
$wgUser->logout();
session_destroy();
}
parent::tearDown();
}
/**
* Edits or creates a page/revision
* @param string $pageName Page title
* @param string $text Content of the page
* @param string $summary Optional summary string for the revision
* @param int $defaultNs Optional namespace id
* @return array Array as returned by WikiPage::doEditContent()
*/
protected function editPage( $pageName, $text, $summary = '', $defaultNs = NS_MAIN ) {
$title = Title::newFromText( $pageName, $defaultNs );
$page = WikiPage::factory( $title );
return $page->doEditContent( ContentHandler::makeContent( $text, $title ), $summary );
}
/**
* Does the API request and returns the result.
*
* The returned value is an array containing
* - the result data (array)
* - the request (WebRequest)
* - the session data of the request (array)
* - if $appendModule is true, the Api module $module
*
* @param array $params
* @param array|null $session
* @param bool $appendModule
* @param User|null $user
*
* @return array
*/
protected function doApiRequest( array $params, array $session = null,
$appendModule = false, User $user = null
) {
global $wgRequest, $wgUser;
if ( is_null( $session ) ) {
// re-use existing global session by default
$session = $wgRequest->getSessionArray();
}
// set up global environment
if ( $user ) {
$wgUser = $user;
}
$wgRequest = new FauxRequest( $params, true, $session );
RequestContext::getMain()->setRequest( $wgRequest );
// set up local environment
$context = $this->apiContext->newTestContext( $wgRequest, $wgUser );
2011-10-27 01:06:50 +00:00
$module = new ApiMain( $context, true );
// run it!
$module->execute();
// construct result
2011-10-27 01:06:50 +00:00
$results = array(
API: Overhaul ApiResult, make format=xml not throw, and add json formatversion ApiResult was a mess: some methods could only be used with an array reference instead of manipulating the stored data, methods that had both array-ref and internal-data versions had names that didn't at all correspond, some methods that worked on an array reference were annoyingly non-static, and then the whole mess with setIndexedTagName. ApiFormatXml is also entirely annoying to deal with, as it liked to throw exceptions if certain metadata wasn't provided that no other formatter required. Its legacy also means we have this silly convention of using empty-string rather than boolean true, annoying restrictions on keys (leading to things that should be hashes being arrays of key-value object instead), '*' used as a key all over the place, and so on. So, changes here: * ApiResult is no longer an ApiBase or a ContextSource. * Wherever sensible, ApiResult provides a static method working on an arrayref and a non-static method working on internal data. * Metadata is now always added to ApiResult's internal data structure. Formatters are responsible for stripping it if necessary. "raw mode" is deprecated. * New metadata to replace the '*' key, solve the array() => '[]' vs '{}' question, and so on. * New class for formatting warnings and errors using i18n messages, and support for multiple errors and a more machine-readable format for warnings. For the moment, though, the actual output will not be changing yet (see T47843 for future plans). * New formatversion parameter for format=json and format=php, to select between BC mode and the modern output. * In BC mode, booleans will be converted to empty-string presence style; modules currently returning booleans will need to use ApiResult::META_BC_BOOLS to preserve their current output. Actual changes to the API modules' output (e.g. actually returning booleans for the new formatversion) beyond the use of ApiResult::setContentValue() are left for a future change. Bug: T76728 Bug: T57371 Bug: T33629 Change-Id: I7b37295e8862b188d1f3b0cd07f66ac34629678f
2014-12-03 22:14:22 +00:00
$module->getResult()->getResultData( null, array( 'Strip' => 'all' ) ),
2011-10-27 01:06:50 +00:00
$context->getRequest(),
$context->getRequest()->getSessionArray()
);
if ( $appendModule ) {
$results[] = $module;
}
2011-08-13 14:00:22 +00:00
return $results;
}
/**
* Add an edit token to the API request
* This is cheating a bit -- we grab a token in the correct format and then
* add it to the pseudo-session and to the request, without actually
* requesting a "real" edit token.
*
* @param array $params Key-value API params
* @param array|null $session Session array
* @param User|null $user A User object for the context
* @return array Result of the API call
* @throws Exception In case wsToken is not set in the session
*/
protected function doApiRequestWithToken( array $params, array $session = null,
User $user = null
) {
global $wgRequest;
if ( $session === null ) {
$session = $wgRequest->getSessionArray();
}
if ( isset( $session['wsToken'] ) && $session['wsToken'] ) {
// @todo Why does this directly mess with the session? Fix that.
// add edit token to fake session
$session['wsEditToken'] = $session['wsToken'];
// add token to request parameters
$timestamp = wfTimestamp();
$params['token'] = hash_hmac( 'md5', $timestamp, $session['wsToken'] ) .
dechex( $timestamp ) .
User::EDIT_TOKEN_SUFFIX;
return $this->doApiRequest( $params, $session, false, $user );
} else {
throw new Exception( "Session token not available" );
}
}
protected function doLogin( $user = 'sysop' ) {
if ( !array_key_exists( $user, self::$users ) ) {
throw new MWException( "Can not log in to undefined user $user" );
}
$data = $this->doApiRequest( array(
'action' => 'login',
'lgname' => self::$users[$user]->username,
'lgpassword' => self::$users[$user]->password ) );
$token = $data[0]['login']['token'];
$data = $this->doApiRequest(
array(
'action' => 'login',
'lgtoken' => $token,
'lgname' => self::$users[$user]->username,
'lgpassword' => self::$users[$user]->password,
),
$data[2]
);
return $data;
}
protected function getTokenList( $user, $session = null ) {
$data = $this->doApiRequest( array(
'action' => 'tokens',
'type' => 'edit|delete|protect|move|block|unblock|watch'
), $session, false, $user->user );
if ( !array_key_exists( 'tokens', $data[0] ) ) {
throw new MWException( 'Api failed to return a token list' );
}
return $data[0]['tokens'];
}
public function testApiTestGroup() {
$groups = PHPUnit_Util_Test::getGroups( get_class( $this ) );
$constraint = PHPUnit_Framework_Assert::logicalOr(
$this->contains( 'medium' ),
$this->contains( 'large' )
);
$this->assertThat( $groups, $constraint,
'ApiTestCase::setUp can be slow, tests must be "medium" or "large"'
);
}
}