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

211 lines
5.8 KiB
PHP
Raw Normal View History

<?php
use MediaWiki\Session\SessionManager;
2011-05-01 23:02:27 +00:00
abstract class ApiTestCase extends MediaWikiLangTestCase {
protected static $apiUrl;
protected static $errorFormatter = null;
2011-10-27 01:06:50 +00:00
/**
* @var ApiTestContext
*/
protected $apiContext;
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 = [
'sysop' => static::getTestSysop(),
'uploader' => static::getTestUser(),
];
$this->setMwGlobals( [
'wgAuth' => new MediaWiki\Auth\AuthManagerAuthPlugin,
'wgRequest' => new FauxRequest( [] ),
'wgUser' => self::$users['sysop']->getUser(),
] );
2011-10-27 01:06:50 +00:00
$this->apiContext = new ApiTestContext();
}
protected function tearDown() {
// Avoid leaking session over tests
MediaWiki\Session\SessionManager::getGlobalSession()->clear();
parent::tearDown();
}
/**
* 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
* @param string|null $tokenType Set to a string like 'csrf' to send an
* appropriate token
*
* @throws ApiUsageException
* @return array
*/
protected function doApiRequest( array $params, array $session = null,
$appendModule = false, User $user = null, $tokenType = null
) {
global $wgRequest, $wgUser;
if ( is_null( $session ) ) {
// re-use existing global session by default
$session = $wgRequest->getSessionArray();
}
$sessionObj = SessionManager::singleton()->getEmptySession();
if ( $session !== null ) {
foreach ( $session as $key => $value ) {
$sessionObj->set( $key, $value );
}
}
// set up global environment
if ( $user ) {
$wgUser = $user;
}
if ( $tokenType !== null ) {
if ( $tokenType === 'auto' ) {
$tokenType = ( new ApiMain() )->getModuleManager()
->getModule( $params['action'], 'action' )->needsToken();
}
$params['token'] = ApiQueryTokens::getToken(
$wgUser, $sessionObj, ApiQueryTokens::getTokenTypeSalts()[$tokenType]
)->toString();
}
$wgRequest = new FauxRequest( $params, true, $sessionObj );
RequestContext::getMain()->setRequest( $wgRequest );
RequestContext::getMain()->setUser( $wgUser );
MediaWiki\Auth\AuthManager::resetCache();
// 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
$results = [
$module->getResult()->getResultData( null, [ '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;
}
/**
* Convenience function to access the token parameter of doApiRequest()
* more succinctly.
*
* @param array $params Key-value API params
* @param array|null $session Session array
* @param User|null $user A User object for the context
* @param string $tokenType Which token type to pass
* @return array Result of the API call
*/
protected function doApiRequestWithToken( array $params, array $session = null,
User $user = null, $tokenType = 'auto'
) {
return $this->doApiRequest( $params, $session, false, $user, $tokenType );
}
/**
* Previously this would do API requests to log in, as well as setting $wgUser and the request
* context's user. The API requests are unnecessary, and the global-setting is unwanted, so
* this method should not be called. Instead, pass appropriate User values directly to
* functions that need them. For functions that still rely on $wgUser, set that directly. If
* you just want to log in the test sysop user, don't do anything -- that's the default.
*
* @param TestUser|string $testUser Object, or key to self::$users such as 'sysop' or 'uploader'
* @deprecated since 1.31
*/
protected function doLogin( $testUser = null ) {
global $wgUser;
if ( $testUser === null ) {
$testUser = static::getTestSysop();
} elseif ( is_string( $testUser ) && array_key_exists( $testUser, self::$users ) ) {
$testUser = self::$users[$testUser];
} elseif ( !$testUser instanceof TestUser ) {
throw new MWException( "Can't log in to undefined user $testUser" );
}
$wgUser = $testUser->getUser();
RequestContext::getMain()->setUser( $wgUser );
}
protected function getTokenList( TestUser $user, $session = null ) {
$data = $this->doApiRequest( [
'action' => 'tokens',
'type' => 'edit|delete|protect|move|block|unblock|watch'
], $session, false, $user->getUser() );
if ( !array_key_exists( 'tokens', $data[0] ) ) {
throw new MWException( 'Api failed to return a token list' );
}
return $data[0]['tokens'];
}
protected static function getErrorFormatter() {
if ( self::$errorFormatter === null ) {
self::$errorFormatter = new ApiErrorFormatter(
new ApiResult( false ),
Language::factory( 'en' ),
'none'
);
}
return self::$errorFormatter;
}
public static function apiExceptionHasCode( ApiUsageException $ex, $code ) {
return (bool)array_filter(
self::getErrorFormatter()->arrayFromStatus( $ex->getStatusValue() ),
function ( $e ) use ( $code ) {
return is_array( $e ) && $e['code'] === $code;
}
);
}
/**
* @coversNothing
*/
public function testApiTestGroup() {
$groups = PHPUnit_Util_Test::getGroups( static::class );
$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"'
);
}
}