2020-02-27 22:00:28 +00:00
|
|
|
<?php
|
|
|
|
|
|
|
|
|
|
namespace MediaWiki\Tests\Rest\Handler;
|
|
|
|
|
|
2022-08-31 14:51:57 +00:00
|
|
|
use MediaWiki\HookContainer\HookContainer;
|
2021-01-06 18:10:15 +00:00
|
|
|
use MediaWiki\Permissions\Authority;
|
2020-02-27 22:00:28 +00:00
|
|
|
use MediaWiki\Rest\Handler;
|
2020-03-02 12:28:10 +00:00
|
|
|
use MediaWiki\Rest\HttpException;
|
2023-10-30 16:04:41 +00:00
|
|
|
use MediaWiki\Rest\Module\Module;
|
2020-02-27 22:00:28 +00:00
|
|
|
use MediaWiki\Rest\RequestInterface;
|
|
|
|
|
use MediaWiki\Rest\Response;
|
|
|
|
|
use MediaWiki\Rest\ResponseFactory;
|
2020-03-16 20:52:39 +00:00
|
|
|
use MediaWiki\Rest\ResponseInterface;
|
2020-02-27 22:00:28 +00:00
|
|
|
use MediaWiki\Rest\Router;
|
|
|
|
|
use MediaWiki\Rest\Validator\Validator;
|
Make it possible to override the session in REST API tests
The current signature of the various execute methods only takes a
boolean parameter to determine if the session should be safe against
CSRF, but that does not give callers fine-grained control over the
Session object, including setting a specific token.
Also, do not use createNoOpMock in getSession(), since it implies
strong assertions on what methods are called. This way, getSession
can also be used to get a simple mock session that tests may further
manipulate.
Make $csrfSafe parameter of SessionHelperTestTrait::getSession
mandatory. This way, callers are forced to think what makes sense in
each use case. The various methods in HandlerTestTrait now default to
a session that is safe against CSRF. This assumes that most REST
handlers don't care about the session, and that any handler that does
care about the session and where someone needs to test the behaviour
in case of bad/missing token will explicitly provide a Session that
is NOT safe against CSRF.
Typehint the return value of Session(Backend)::getUser so that PHPUnit
will automatically make it return a mock User object even if the method
is not explicitly mocked. Remove a useless PHPUnit assertion -- setting
the return value to be X and then veryfing that is equal to X is a
tautology, and can only fail if the test itself is flawed (as was the
case, since it was using stdClass as the return type for all
methods). Remove the getUser test case altogether, there's no way to
make it work given the DummySessionBackend, and the test isn't that
helpful anyway. More and more methods will have the same issue as soon
as their return value is typehinted.
Follow-up: I2a9215bf909b83564247ded95ecdb4ead0615150
Change-Id: Ic51dc3e7bf47c81f2ac4705308bb9ecd8275bbaf
2023-02-06 15:18:00 +00:00
|
|
|
use MediaWiki\Session\Session;
|
2023-10-30 16:04:41 +00:00
|
|
|
use MediaWiki\Tests\Rest\RestTestTrait;
|
2024-01-09 13:04:26 +00:00
|
|
|
use MediaWiki\Tests\Unit\DummyServicesTrait;
|
2021-01-22 00:20:44 +00:00
|
|
|
use MediaWiki\Tests\Unit\Permissions\MockAuthorityTrait;
|
2020-03-02 12:28:10 +00:00
|
|
|
use PHPUnit\Framework\Assert;
|
2020-02-27 22:00:28 +00:00
|
|
|
use PHPUnit\Framework\MockObject\MockObject;
|
2022-03-09 22:16:22 +00:00
|
|
|
use Wikimedia\ObjectFactory\ObjectFactory;
|
2020-02-27 22:00:28 +00:00
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* A trait providing utility functions for testing Handler classes.
|
|
|
|
|
* This trait is intended to be used on subclasses of MediaWikiUnitTestCase
|
|
|
|
|
* or MediaWikiIntegrationTestCase.
|
|
|
|
|
*
|
2021-01-13 17:34:01 +00:00
|
|
|
* @stable to use
|
2020-02-27 22:00:28 +00:00
|
|
|
*/
|
|
|
|
|
trait HandlerTestTrait {
|
2023-10-30 16:04:41 +00:00
|
|
|
use RestTestTrait;
|
2024-01-09 13:04:26 +00:00
|
|
|
use DummyServicesTrait;
|
2021-01-22 00:20:44 +00:00
|
|
|
use MockAuthorityTrait;
|
2022-05-04 16:29:51 +00:00
|
|
|
use SessionHelperTestTrait;
|
2020-02-27 22:00:28 +00:00
|
|
|
|
|
|
|
|
/**
|
2023-10-30 16:04:41 +00:00
|
|
|
* Calls init() on the Handler, supplying a mock RouteUrlProvider and ResponseFactory.
|
2020-02-27 22:00:28 +00:00
|
|
|
*
|
|
|
|
|
* @param Handler $handler
|
|
|
|
|
* @param RequestInterface $request
|
|
|
|
|
* @param array $config
|
2022-08-31 14:51:57 +00:00
|
|
|
* @param HookContainer|array $hooks Hook container or array of hooks
|
2021-01-06 18:10:15 +00:00
|
|
|
* @param Authority|null $authority
|
Make it possible to override the session in REST API tests
The current signature of the various execute methods only takes a
boolean parameter to determine if the session should be safe against
CSRF, but that does not give callers fine-grained control over the
Session object, including setting a specific token.
Also, do not use createNoOpMock in getSession(), since it implies
strong assertions on what methods are called. This way, getSession
can also be used to get a simple mock session that tests may further
manipulate.
Make $csrfSafe parameter of SessionHelperTestTrait::getSession
mandatory. This way, callers are forced to think what makes sense in
each use case. The various methods in HandlerTestTrait now default to
a session that is safe against CSRF. This assumes that most REST
handlers don't care about the session, and that any handler that does
care about the session and where someone needs to test the behaviour
in case of bad/missing token will explicitly provide a Session that
is NOT safe against CSRF.
Typehint the return value of Session(Backend)::getUser so that PHPUnit
will automatically make it return a mock User object even if the method
is not explicitly mocked. Remove a useless PHPUnit assertion -- setting
the return value to be X and then veryfing that is equal to X is a
tautology, and can only fail if the test itself is flawed (as was the
case, since it was using stdClass as the return type for all
methods). Remove the getUser test case altogether, there's no way to
make it work given the DummySessionBackend, and the test isn't that
helpful anyway. More and more methods will have the same issue as soon
as their return value is typehinted.
Follow-up: I2a9215bf909b83564247ded95ecdb4ead0615150
Change-Id: Ic51dc3e7bf47c81f2ac4705308bb9ecd8275bbaf
2023-02-06 15:18:00 +00:00
|
|
|
* @param Session|null $session Defaults to `$this->getSession( true )`
|
2023-10-30 16:04:41 +00:00
|
|
|
* @param Router|Module|null $routerOrModule
|
2023-12-04 22:21:07 +00:00
|
|
|
*
|
|
|
|
|
* @internal to the trait
|
2020-02-27 22:00:28 +00:00
|
|
|
*/
|
2021-01-06 18:10:15 +00:00
|
|
|
private function initHandler(
|
|
|
|
|
Handler $handler,
|
|
|
|
|
RequestInterface $request,
|
|
|
|
|
$config = [],
|
|
|
|
|
$hooks = [],
|
2022-05-04 16:29:51 +00:00
|
|
|
Authority $authority = null,
|
2023-12-04 22:21:07 +00:00
|
|
|
Session $session = null,
|
2023-10-30 16:04:41 +00:00
|
|
|
$routerOrModule = null
|
Hooks::run() call site migration
Migrate all callers of Hooks::run() to use the new
HookContainer/HookRunner system.
General principles:
* Use DI if it is already used. We're not changing the way state is
managed in this patch.
* HookContainer is always injected, not HookRunner. HookContainer
is a service, it's a more generic interface, it is the only
thing that provides isRegistered() which is needed in some cases,
and a HookRunner can be efficiently constructed from it
(confirmed by benchmark). Because HookContainer is needed
for object construction, it is also needed by all factories.
* "Ask your friendly local base class". Big hierarchies like
SpecialPage and ApiBase have getHookContainer() and getHookRunner()
methods in the base class, and classes that extend that base class
are not expected to know or care where the base class gets its
HookContainer from.
* ProtectedHookAccessorTrait provides protected getHookContainer() and
getHookRunner() methods, getting them from the global service
container. The point of this is to ease migration to DI by ensuring
that call sites ask their local friendly base class rather than
getting a HookRunner from the service container directly.
* Private $this->hookRunner. In some smaller classes where accessor
methods did not seem warranted, there is a private HookRunner property
which is accessed directly. Very rarely (two cases), there is a
protected property, for consistency with code that conventionally
assumes protected=private, but in cases where the class might actually
be overridden, a protected accessor is preferred over a protected
property.
* The last resort: Hooks::runner(). Mostly for static, file-scope and
global code. In a few cases it was used for objects with broken
construction schemes, out of horror or laziness.
Constructors with new required arguments:
* AuthManager
* BadFileLookup
* BlockManager
* ClassicInterwikiLookup
* ContentHandlerFactory
* ContentSecurityPolicy
* DefaultOptionsManager
* DerivedPageDataUpdater
* FullSearchResultWidget
* HtmlCacheUpdater
* LanguageFactory
* LanguageNameUtils
* LinkRenderer
* LinkRendererFactory
* LocalisationCache
* MagicWordFactory
* MessageCache
* NamespaceInfo
* PageEditStash
* PageHandlerFactory
* PageUpdater
* ParserFactory
* PermissionManager
* RevisionStore
* RevisionStoreFactory
* SearchEngineConfig
* SearchEngineFactory
* SearchFormWidget
* SearchNearMatcher
* SessionBackend
* SpecialPageFactory
* UserNameUtils
* UserOptionsManager
* WatchedItemQueryService
* WatchedItemStore
Constructors with new optional arguments:
* DefaultPreferencesFactory
* Language
* LinkHolderArray
* MovePage
* Parser
* ParserCache
* PasswordReset
* Router
setHookContainer() now required after construction:
* AuthenticationProvider
* ResourceLoaderModule
* SearchEngine
Change-Id: Id442b0dbe43aba84bd5cf801d86dedc768b082c7
2020-03-19 02:42:09 +00:00
|
|
|
) {
|
2024-01-09 13:04:26 +00:00
|
|
|
$formatter = $this->getDummyTextFormatter( true );
|
2020-02-27 22:00:28 +00:00
|
|
|
$responseFactory = new ResponseFactory( [ 'qqx' => $formatter ] );
|
|
|
|
|
|
2023-10-30 16:04:41 +00:00
|
|
|
$module = null;
|
|
|
|
|
$router = null;
|
|
|
|
|
|
|
|
|
|
if ( $routerOrModule instanceof Module ) {
|
|
|
|
|
$module = $routerOrModule;
|
|
|
|
|
$router = $module->getRouter();
|
2023-12-04 22:21:07 +00:00
|
|
|
}
|
2020-05-25 19:14:26 +00:00
|
|
|
|
2023-10-30 16:04:41 +00:00
|
|
|
if ( $routerOrModule instanceof Router ) {
|
|
|
|
|
$router = $routerOrModule;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if ( !$module ) {
|
|
|
|
|
if ( !$router ) {
|
|
|
|
|
$router = $this->newRouter();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
$module = $this->newModule( [ 'router' => $router ] );
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if ( !$request->hasBody()
|
|
|
|
|
&& in_array( $request->getMethod(), RequestInterface::BODY_METHODS )
|
|
|
|
|
) {
|
|
|
|
|
// Send an empty body if none was provided.
|
|
|
|
|
$request->setParsedBody( [] );
|
2024-03-12 11:24:15 +00:00
|
|
|
}
|
|
|
|
|
|
Make it possible to override the session in REST API tests
The current signature of the various execute methods only takes a
boolean parameter to determine if the session should be safe against
CSRF, but that does not give callers fine-grained control over the
Session object, including setting a specific token.
Also, do not use createNoOpMock in getSession(), since it implies
strong assertions on what methods are called. This way, getSession
can also be used to get a simple mock session that tests may further
manipulate.
Make $csrfSafe parameter of SessionHelperTestTrait::getSession
mandatory. This way, callers are forced to think what makes sense in
each use case. The various methods in HandlerTestTrait now default to
a session that is safe against CSRF. This assumes that most REST
handlers don't care about the session, and that any handler that does
care about the session and where someone needs to test the behaviour
in case of bad/missing token will explicitly provide a Session that
is NOT safe against CSRF.
Typehint the return value of Session(Backend)::getUser so that PHPUnit
will automatically make it return a mock User object even if the method
is not explicitly mocked. Remove a useless PHPUnit assertion -- setting
the return value to be X and then veryfing that is equal to X is a
tautology, and can only fail if the test itself is flawed (as was the
case, since it was using stdClass as the return type for all
methods). Remove the getUser test case altogether, there's no way to
make it work given the DummySessionBackend, and the test isn't that
helpful anyway. More and more methods will have the same issue as soon
as their return value is typehinted.
Follow-up: I2a9215bf909b83564247ded95ecdb4ead0615150
Change-Id: Ic51dc3e7bf47c81f2ac4705308bb9ecd8275bbaf
2023-02-06 15:18:00 +00:00
|
|
|
$authority ??= $this->mockAnonUltimateAuthority();
|
2023-10-30 16:04:41 +00:00
|
|
|
$hookContainer =
|
|
|
|
|
$hooks instanceof HookContainer ? $hooks : $this->createHookContainer( $hooks );
|
Hooks::run() call site migration
Migrate all callers of Hooks::run() to use the new
HookContainer/HookRunner system.
General principles:
* Use DI if it is already used. We're not changing the way state is
managed in this patch.
* HookContainer is always injected, not HookRunner. HookContainer
is a service, it's a more generic interface, it is the only
thing that provides isRegistered() which is needed in some cases,
and a HookRunner can be efficiently constructed from it
(confirmed by benchmark). Because HookContainer is needed
for object construction, it is also needed by all factories.
* "Ask your friendly local base class". Big hierarchies like
SpecialPage and ApiBase have getHookContainer() and getHookRunner()
methods in the base class, and classes that extend that base class
are not expected to know or care where the base class gets its
HookContainer from.
* ProtectedHookAccessorTrait provides protected getHookContainer() and
getHookRunner() methods, getting them from the global service
container. The point of this is to ease migration to DI by ensuring
that call sites ask their local friendly base class rather than
getting a HookRunner from the service container directly.
* Private $this->hookRunner. In some smaller classes where accessor
methods did not seem warranted, there is a private HookRunner property
which is accessed directly. Very rarely (two cases), there is a
protected property, for consistency with code that conventionally
assumes protected=private, but in cases where the class might actually
be overridden, a protected accessor is preferred over a protected
property.
* The last resort: Hooks::runner(). Mostly for static, file-scope and
global code. In a few cases it was used for objects with broken
construction schemes, out of horror or laziness.
Constructors with new required arguments:
* AuthManager
* BadFileLookup
* BlockManager
* ClassicInterwikiLookup
* ContentHandlerFactory
* ContentSecurityPolicy
* DefaultOptionsManager
* DerivedPageDataUpdater
* FullSearchResultWidget
* HtmlCacheUpdater
* LanguageFactory
* LanguageNameUtils
* LinkRenderer
* LinkRendererFactory
* LocalisationCache
* MagicWordFactory
* MessageCache
* NamespaceInfo
* PageEditStash
* PageHandlerFactory
* PageUpdater
* ParserFactory
* PermissionManager
* RevisionStore
* RevisionStoreFactory
* SearchEngineConfig
* SearchEngineFactory
* SearchFormWidget
* SearchNearMatcher
* SessionBackend
* SpecialPageFactory
* UserNameUtils
* UserOptionsManager
* WatchedItemQueryService
* WatchedItemStore
Constructors with new optional arguments:
* DefaultPreferencesFactory
* Language
* LinkHolderArray
* MovePage
* Parser
* ParserCache
* PasswordReset
* Router
setHookContainer() now required after construction:
* AuthenticationProvider
* ResourceLoaderModule
* SearchEngine
Change-Id: Id442b0dbe43aba84bd5cf801d86dedc768b082c7
2020-03-19 02:42:09 +00:00
|
|
|
|
Make it possible to override the session in REST API tests
The current signature of the various execute methods only takes a
boolean parameter to determine if the session should be safe against
CSRF, but that does not give callers fine-grained control over the
Session object, including setting a specific token.
Also, do not use createNoOpMock in getSession(), since it implies
strong assertions on what methods are called. This way, getSession
can also be used to get a simple mock session that tests may further
manipulate.
Make $csrfSafe parameter of SessionHelperTestTrait::getSession
mandatory. This way, callers are forced to think what makes sense in
each use case. The various methods in HandlerTestTrait now default to
a session that is safe against CSRF. This assumes that most REST
handlers don't care about the session, and that any handler that does
care about the session and where someone needs to test the behaviour
in case of bad/missing token will explicitly provide a Session that
is NOT safe against CSRF.
Typehint the return value of Session(Backend)::getUser so that PHPUnit
will automatically make it return a mock User object even if the method
is not explicitly mocked. Remove a useless PHPUnit assertion -- setting
the return value to be X and then veryfing that is equal to X is a
tautology, and can only fail if the test itself is flawed (as was the
case, since it was using stdClass as the return type for all
methods). Remove the getUser test case altogether, there's no way to
make it work given the DummySessionBackend, and the test isn't that
helpful anyway. More and more methods will have the same issue as soon
as their return value is typehinted.
Follow-up: I2a9215bf909b83564247ded95ecdb4ead0615150
Change-Id: Ic51dc3e7bf47c81f2ac4705308bb9ecd8275bbaf
2023-02-06 15:18:00 +00:00
|
|
|
$session ??= $this->getSession( true );
|
2024-02-21 20:51:29 +00:00
|
|
|
$handler->initContext( $module, $config['path'] ?? 'test', $config );
|
2023-10-30 16:04:41 +00:00
|
|
|
$handler->initServices( $authority, $responseFactory, $hookContainer );
|
|
|
|
|
$handler->initSession( $session );
|
|
|
|
|
$handler->initForExecute( $request );
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* @return MockObject&Router
|
|
|
|
|
*/
|
|
|
|
|
private function newRouter(): Router {
|
|
|
|
|
$router = $this->createNoOpMock(
|
|
|
|
|
Router::class,
|
|
|
|
|
[
|
|
|
|
|
'getRoutePath',
|
|
|
|
|
'getRouteUrl'
|
|
|
|
|
]
|
|
|
|
|
);
|
|
|
|
|
$router->method( 'getRoutePath' )->willReturnCallback(
|
|
|
|
|
static function ( $route, $path = [], $query = [] ) {
|
|
|
|
|
foreach ( $path as $param => $value ) {
|
|
|
|
|
$route = str_replace(
|
|
|
|
|
'{' . $param . '}',
|
|
|
|
|
urlencode( (string)$value ),
|
|
|
|
|
$route
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return wfAppendQuery(
|
|
|
|
|
'/rest' . $route,
|
|
|
|
|
$query
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
);
|
|
|
|
|
$router->method( 'getRouteUrl' )->willReturnCallback(
|
|
|
|
|
static function ( $route, $path = [], $query = [] ) use ( $router ) {
|
|
|
|
|
return 'https://wiki.example.com' . $router->getRoutePath(
|
|
|
|
|
$route,
|
|
|
|
|
$path,
|
|
|
|
|
$query
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
return $router;
|
2020-05-25 19:14:26 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Calls validate() on the Handler, with an appropriate Validator supplied.
|
|
|
|
|
*
|
2021-01-13 17:34:01 +00:00
|
|
|
* @internal to the trait
|
2020-05-25 19:14:26 +00:00
|
|
|
* @param Handler $handler
|
2020-07-29 19:43:11 +00:00
|
|
|
* @param null|Validator $validator
|
|
|
|
|
* @throws HttpException
|
2020-05-25 19:14:26 +00:00
|
|
|
*/
|
2021-01-19 17:51:18 +00:00
|
|
|
private function validateHandler(
|
|
|
|
|
Handler $handler,
|
2021-01-06 18:10:15 +00:00
|
|
|
Validator $validator = null
|
2021-01-19 17:51:18 +00:00
|
|
|
) {
|
2020-07-29 19:43:11 +00:00
|
|
|
if ( !$validator ) {
|
2024-04-24 15:48:19 +00:00
|
|
|
$serviceContainer = $this->getServiceContainer();
|
2020-07-29 19:43:11 +00:00
|
|
|
$objectFactory = new ObjectFactory( $serviceContainer );
|
2021-01-06 18:10:15 +00:00
|
|
|
$validator = new Validator( $objectFactory, $handler->getRequest(), $handler->getAuthority() );
|
2020-07-29 19:43:11 +00:00
|
|
|
}
|
2020-02-27 22:00:28 +00:00
|
|
|
$handler->validate( $validator );
|
2020-05-25 19:14:26 +00:00
|
|
|
}
|
|
|
|
|
|
2020-07-29 19:43:11 +00:00
|
|
|
/**
|
|
|
|
|
* Creates a mock Validator to bypass actual request query, path, and/or body param validation
|
|
|
|
|
*
|
2021-01-13 17:34:01 +00:00
|
|
|
* @internal to the trait
|
2020-07-29 19:43:11 +00:00
|
|
|
* @param array $queryPathParams
|
|
|
|
|
* @param array $bodyParams
|
|
|
|
|
* @return Validator|MockObject
|
|
|
|
|
*/
|
2021-01-22 00:20:44 +00:00
|
|
|
private function getMockValidator( array $queryPathParams, array $bodyParams ): Validator {
|
2024-05-27 20:37:26 +00:00
|
|
|
$validator = $this->createNoOpMock(
|
|
|
|
|
Validator::class,
|
|
|
|
|
[
|
|
|
|
|
'validateParams',
|
|
|
|
|
'validateBodyParams',
|
|
|
|
|
'validateBody',
|
|
|
|
|
'detectExtraneousBodyFields',
|
|
|
|
|
]
|
|
|
|
|
);
|
|
|
|
|
$validator->method( 'validateBody' )->willReturn( null );
|
2023-09-05 14:33:12 +00:00
|
|
|
$validator->method( 'validateParams' )->willReturn( $queryPathParams );
|
2024-05-27 20:37:26 +00:00
|
|
|
$validator->method( 'validateBodyParams' )->willReturn( $bodyParams );
|
2020-07-29 19:43:11 +00:00
|
|
|
return $validator;
|
|
|
|
|
}
|
|
|
|
|
|
2020-05-25 19:14:26 +00:00
|
|
|
/**
|
|
|
|
|
* Executes the given Handler on the given request.
|
|
|
|
|
*
|
|
|
|
|
* @param Handler $handler
|
|
|
|
|
* @param RequestInterface $request
|
|
|
|
|
* @param array $config
|
2022-08-31 14:51:57 +00:00
|
|
|
* @param HookContainer|array $hooks Hook container or array of hooks
|
2020-07-29 19:43:11 +00:00
|
|
|
* @param array $validatedParams Path/query params to return as already valid
|
|
|
|
|
* @param array $validatedBody Body params to return as already valid
|
2021-01-06 18:10:15 +00:00
|
|
|
* @param Authority|null $authority
|
Make it possible to override the session in REST API tests
The current signature of the various execute methods only takes a
boolean parameter to determine if the session should be safe against
CSRF, but that does not give callers fine-grained control over the
Session object, including setting a specific token.
Also, do not use createNoOpMock in getSession(), since it implies
strong assertions on what methods are called. This way, getSession
can also be used to get a simple mock session that tests may further
manipulate.
Make $csrfSafe parameter of SessionHelperTestTrait::getSession
mandatory. This way, callers are forced to think what makes sense in
each use case. The various methods in HandlerTestTrait now default to
a session that is safe against CSRF. This assumes that most REST
handlers don't care about the session, and that any handler that does
care about the session and where someone needs to test the behaviour
in case of bad/missing token will explicitly provide a Session that
is NOT safe against CSRF.
Typehint the return value of Session(Backend)::getUser so that PHPUnit
will automatically make it return a mock User object even if the method
is not explicitly mocked. Remove a useless PHPUnit assertion -- setting
the return value to be X and then veryfing that is equal to X is a
tautology, and can only fail if the test itself is flawed (as was the
case, since it was using stdClass as the return type for all
methods). Remove the getUser test case altogether, there's no way to
make it work given the DummySessionBackend, and the test isn't that
helpful anyway. More and more methods will have the same issue as soon
as their return value is typehinted.
Follow-up: I2a9215bf909b83564247ded95ecdb4ead0615150
Change-Id: Ic51dc3e7bf47c81f2ac4705308bb9ecd8275bbaf
2023-02-06 15:18:00 +00:00
|
|
|
* @param Session|null $session Defaults to `$this->getSession( true )`
|
2023-10-30 16:04:41 +00:00
|
|
|
* @param Router|Module|null $routerOrModule
|
2023-12-04 22:21:07 +00:00
|
|
|
*
|
2020-05-25 19:14:26 +00:00
|
|
|
* @return ResponseInterface
|
|
|
|
|
*/
|
2021-01-19 17:51:18 +00:00
|
|
|
private function executeHandler(
|
|
|
|
|
Handler $handler,
|
|
|
|
|
RequestInterface $request,
|
|
|
|
|
$config = [],
|
|
|
|
|
$hooks = [],
|
|
|
|
|
$validatedParams = [],
|
|
|
|
|
$validatedBody = [],
|
2022-05-04 16:29:51 +00:00
|
|
|
Authority $authority = null,
|
2023-12-04 22:21:07 +00:00
|
|
|
Session $session = null,
|
2023-10-30 16:04:41 +00:00
|
|
|
$routerOrModule = null
|
2021-01-22 00:20:44 +00:00
|
|
|
): ResponseInterface {
|
2020-05-12 18:28:43 +00:00
|
|
|
// supply defaults for required fields in $config
|
|
|
|
|
$config += [ 'path' => '/test' ];
|
|
|
|
|
|
2023-10-30 16:04:41 +00:00
|
|
|
$this->initHandler( $handler, $request, $config, $hooks, $authority, $session, $routerOrModule );
|
2020-07-29 19:43:11 +00:00
|
|
|
$validator = null;
|
|
|
|
|
if ( $validatedParams || $validatedBody ) {
|
|
|
|
|
/** @var Validator|MockObject $validator */
|
|
|
|
|
$validator = $this->getMockValidator( $validatedParams, $validatedBody );
|
|
|
|
|
}
|
2021-01-06 18:10:15 +00:00
|
|
|
$this->validateHandler( $handler, $validator );
|
2020-03-16 20:52:39 +00:00
|
|
|
|
|
|
|
|
// Check conditional request headers
|
|
|
|
|
$earlyResponse = $handler->checkPreconditions();
|
|
|
|
|
if ( $earlyResponse ) {
|
|
|
|
|
return $earlyResponse;
|
|
|
|
|
}
|
|
|
|
|
|
2020-02-27 22:00:28 +00:00
|
|
|
$ret = $handler->execute();
|
|
|
|
|
|
|
|
|
|
$response = $ret instanceof Response ? $ret
|
2020-05-25 19:14:26 +00:00
|
|
|
: $handler->getResponseFactory()->createFromReturnValue( $ret );
|
2020-02-27 22:00:28 +00:00
|
|
|
|
2020-03-16 20:52:39 +00:00
|
|
|
// Set Last-Modified and ETag headers in the response if available
|
|
|
|
|
$handler->applyConditionalResponseHeaders( $response );
|
|
|
|
|
|
2020-02-27 22:00:28 +00:00
|
|
|
return $response;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Executes the given Handler on the given request, parses the response body as JSON,
|
|
|
|
|
* and returns the result.
|
|
|
|
|
*
|
|
|
|
|
* @param Handler $handler
|
|
|
|
|
* @param RequestInterface $request
|
|
|
|
|
* @param array $config
|
2022-08-31 14:51:57 +00:00
|
|
|
* @param HookContainer|array $hooks Hook container or array of hooks
|
2021-01-06 18:10:15 +00:00
|
|
|
* @param array $validatedParams
|
|
|
|
|
* @param array $validatedBody
|
|
|
|
|
* @param Authority|null $authority
|
Make it possible to override the session in REST API tests
The current signature of the various execute methods only takes a
boolean parameter to determine if the session should be safe against
CSRF, but that does not give callers fine-grained control over the
Session object, including setting a specific token.
Also, do not use createNoOpMock in getSession(), since it implies
strong assertions on what methods are called. This way, getSession
can also be used to get a simple mock session that tests may further
manipulate.
Make $csrfSafe parameter of SessionHelperTestTrait::getSession
mandatory. This way, callers are forced to think what makes sense in
each use case. The various methods in HandlerTestTrait now default to
a session that is safe against CSRF. This assumes that most REST
handlers don't care about the session, and that any handler that does
care about the session and where someone needs to test the behaviour
in case of bad/missing token will explicitly provide a Session that
is NOT safe against CSRF.
Typehint the return value of Session(Backend)::getUser so that PHPUnit
will automatically make it return a mock User object even if the method
is not explicitly mocked. Remove a useless PHPUnit assertion -- setting
the return value to be X and then veryfing that is equal to X is a
tautology, and can only fail if the test itself is flawed (as was the
case, since it was using stdClass as the return type for all
methods). Remove the getUser test case altogether, there's no way to
make it work given the DummySessionBackend, and the test isn't that
helpful anyway. More and more methods will have the same issue as soon
as their return value is typehinted.
Follow-up: I2a9215bf909b83564247ded95ecdb4ead0615150
Change-Id: Ic51dc3e7bf47c81f2ac4705308bb9ecd8275bbaf
2023-02-06 15:18:00 +00:00
|
|
|
* @param Session|null $session Defaults to `$this->getSession( true )`
|
2020-02-27 22:00:28 +00:00
|
|
|
* @return array
|
|
|
|
|
*/
|
|
|
|
|
private function executeHandlerAndGetBodyData(
|
|
|
|
|
Handler $handler,
|
|
|
|
|
RequestInterface $request,
|
Hooks::run() call site migration
Migrate all callers of Hooks::run() to use the new
HookContainer/HookRunner system.
General principles:
* Use DI if it is already used. We're not changing the way state is
managed in this patch.
* HookContainer is always injected, not HookRunner. HookContainer
is a service, it's a more generic interface, it is the only
thing that provides isRegistered() which is needed in some cases,
and a HookRunner can be efficiently constructed from it
(confirmed by benchmark). Because HookContainer is needed
for object construction, it is also needed by all factories.
* "Ask your friendly local base class". Big hierarchies like
SpecialPage and ApiBase have getHookContainer() and getHookRunner()
methods in the base class, and classes that extend that base class
are not expected to know or care where the base class gets its
HookContainer from.
* ProtectedHookAccessorTrait provides protected getHookContainer() and
getHookRunner() methods, getting them from the global service
container. The point of this is to ease migration to DI by ensuring
that call sites ask their local friendly base class rather than
getting a HookRunner from the service container directly.
* Private $this->hookRunner. In some smaller classes where accessor
methods did not seem warranted, there is a private HookRunner property
which is accessed directly. Very rarely (two cases), there is a
protected property, for consistency with code that conventionally
assumes protected=private, but in cases where the class might actually
be overridden, a protected accessor is preferred over a protected
property.
* The last resort: Hooks::runner(). Mostly for static, file-scope and
global code. In a few cases it was used for objects with broken
construction schemes, out of horror or laziness.
Constructors with new required arguments:
* AuthManager
* BadFileLookup
* BlockManager
* ClassicInterwikiLookup
* ContentHandlerFactory
* ContentSecurityPolicy
* DefaultOptionsManager
* DerivedPageDataUpdater
* FullSearchResultWidget
* HtmlCacheUpdater
* LanguageFactory
* LanguageNameUtils
* LinkRenderer
* LinkRendererFactory
* LocalisationCache
* MagicWordFactory
* MessageCache
* NamespaceInfo
* PageEditStash
* PageHandlerFactory
* PageUpdater
* ParserFactory
* PermissionManager
* RevisionStore
* RevisionStoreFactory
* SearchEngineConfig
* SearchEngineFactory
* SearchFormWidget
* SearchNearMatcher
* SessionBackend
* SpecialPageFactory
* UserNameUtils
* UserOptionsManager
* WatchedItemQueryService
* WatchedItemStore
Constructors with new optional arguments:
* DefaultPreferencesFactory
* Language
* LinkHolderArray
* MovePage
* Parser
* ParserCache
* PasswordReset
* Router
setHookContainer() now required after construction:
* AuthenticationProvider
* ResourceLoaderModule
* SearchEngine
Change-Id: Id442b0dbe43aba84bd5cf801d86dedc768b082c7
2020-03-19 02:42:09 +00:00
|
|
|
$config = [],
|
2020-07-29 19:43:11 +00:00
|
|
|
$hooks = [],
|
|
|
|
|
$validatedParams = [],
|
2021-01-19 17:51:18 +00:00
|
|
|
$validatedBody = [],
|
2022-05-04 16:29:51 +00:00
|
|
|
Authority $authority = null,
|
Make it possible to override the session in REST API tests
The current signature of the various execute methods only takes a
boolean parameter to determine if the session should be safe against
CSRF, but that does not give callers fine-grained control over the
Session object, including setting a specific token.
Also, do not use createNoOpMock in getSession(), since it implies
strong assertions on what methods are called. This way, getSession
can also be used to get a simple mock session that tests may further
manipulate.
Make $csrfSafe parameter of SessionHelperTestTrait::getSession
mandatory. This way, callers are forced to think what makes sense in
each use case. The various methods in HandlerTestTrait now default to
a session that is safe against CSRF. This assumes that most REST
handlers don't care about the session, and that any handler that does
care about the session and where someone needs to test the behaviour
in case of bad/missing token will explicitly provide a Session that
is NOT safe against CSRF.
Typehint the return value of Session(Backend)::getUser so that PHPUnit
will automatically make it return a mock User object even if the method
is not explicitly mocked. Remove a useless PHPUnit assertion -- setting
the return value to be X and then veryfing that is equal to X is a
tautology, and can only fail if the test itself is flawed (as was the
case, since it was using stdClass as the return type for all
methods). Remove the getUser test case altogether, there's no way to
make it work given the DummySessionBackend, and the test isn't that
helpful anyway. More and more methods will have the same issue as soon
as their return value is typehinted.
Follow-up: I2a9215bf909b83564247ded95ecdb4ead0615150
Change-Id: Ic51dc3e7bf47c81f2ac4705308bb9ecd8275bbaf
2023-02-06 15:18:00 +00:00
|
|
|
Session $session = null
|
2021-01-22 00:20:44 +00:00
|
|
|
): array {
|
2021-01-06 18:10:15 +00:00
|
|
|
$response = $this->executeHandler( $handler, $request, $config, $hooks,
|
Make it possible to override the session in REST API tests
The current signature of the various execute methods only takes a
boolean parameter to determine if the session should be safe against
CSRF, but that does not give callers fine-grained control over the
Session object, including setting a specific token.
Also, do not use createNoOpMock in getSession(), since it implies
strong assertions on what methods are called. This way, getSession
can also be used to get a simple mock session that tests may further
manipulate.
Make $csrfSafe parameter of SessionHelperTestTrait::getSession
mandatory. This way, callers are forced to think what makes sense in
each use case. The various methods in HandlerTestTrait now default to
a session that is safe against CSRF. This assumes that most REST
handlers don't care about the session, and that any handler that does
care about the session and where someone needs to test the behaviour
in case of bad/missing token will explicitly provide a Session that
is NOT safe against CSRF.
Typehint the return value of Session(Backend)::getUser so that PHPUnit
will automatically make it return a mock User object even if the method
is not explicitly mocked. Remove a useless PHPUnit assertion -- setting
the return value to be X and then veryfing that is equal to X is a
tautology, and can only fail if the test itself is flawed (as was the
case, since it was using stdClass as the return type for all
methods). Remove the getUser test case altogether, there's no way to
make it work given the DummySessionBackend, and the test isn't that
helpful anyway. More and more methods will have the same issue as soon
as their return value is typehinted.
Follow-up: I2a9215bf909b83564247ded95ecdb4ead0615150
Change-Id: Ic51dc3e7bf47c81f2ac4705308bb9ecd8275bbaf
2023-02-06 15:18:00 +00:00
|
|
|
$validatedParams, $validatedBody, $authority, $session );
|
2020-02-27 22:00:28 +00:00
|
|
|
|
2023-07-03 14:13:58 +00:00
|
|
|
$this->assertGreaterThanOrEqual( 200, $response->getStatusCode() );
|
|
|
|
|
$this->assertLessThan( 300, $response->getStatusCode() );
|
2020-02-27 22:00:28 +00:00
|
|
|
$this->assertSame( 'application/json', $response->getHeaderLine( 'Content-Type' ) );
|
|
|
|
|
|
|
|
|
|
$data = json_decode( $response->getBody(), true );
|
|
|
|
|
$this->assertIsArray( $data, 'Body must be a JSON array' );
|
|
|
|
|
|
|
|
|
|
return $data;
|
|
|
|
|
}
|
|
|
|
|
|
2020-03-02 12:28:10 +00:00
|
|
|
/**
|
|
|
|
|
* Executes the given Handler on the given request, and returns the HttpException thrown.
|
|
|
|
|
* Fails if no HttpException is thrown.
|
|
|
|
|
*
|
|
|
|
|
* @param Handler $handler
|
|
|
|
|
* @param RequestInterface $request
|
|
|
|
|
* @param array $config
|
2022-08-31 14:51:57 +00:00
|
|
|
* @param HookContainer|array $hooks Hook container or array of hooks
|
2020-03-02 12:28:10 +00:00
|
|
|
*
|
|
|
|
|
* @return HttpException
|
|
|
|
|
*/
|
|
|
|
|
private function executeHandlerAndGetHttpException(
|
|
|
|
|
Handler $handler,
|
|
|
|
|
RequestInterface $request,
|
Hooks::run() call site migration
Migrate all callers of Hooks::run() to use the new
HookContainer/HookRunner system.
General principles:
* Use DI if it is already used. We're not changing the way state is
managed in this patch.
* HookContainer is always injected, not HookRunner. HookContainer
is a service, it's a more generic interface, it is the only
thing that provides isRegistered() which is needed in some cases,
and a HookRunner can be efficiently constructed from it
(confirmed by benchmark). Because HookContainer is needed
for object construction, it is also needed by all factories.
* "Ask your friendly local base class". Big hierarchies like
SpecialPage and ApiBase have getHookContainer() and getHookRunner()
methods in the base class, and classes that extend that base class
are not expected to know or care where the base class gets its
HookContainer from.
* ProtectedHookAccessorTrait provides protected getHookContainer() and
getHookRunner() methods, getting them from the global service
container. The point of this is to ease migration to DI by ensuring
that call sites ask their local friendly base class rather than
getting a HookRunner from the service container directly.
* Private $this->hookRunner. In some smaller classes where accessor
methods did not seem warranted, there is a private HookRunner property
which is accessed directly. Very rarely (two cases), there is a
protected property, for consistency with code that conventionally
assumes protected=private, but in cases where the class might actually
be overridden, a protected accessor is preferred over a protected
property.
* The last resort: Hooks::runner(). Mostly for static, file-scope and
global code. In a few cases it was used for objects with broken
construction schemes, out of horror or laziness.
Constructors with new required arguments:
* AuthManager
* BadFileLookup
* BlockManager
* ClassicInterwikiLookup
* ContentHandlerFactory
* ContentSecurityPolicy
* DefaultOptionsManager
* DerivedPageDataUpdater
* FullSearchResultWidget
* HtmlCacheUpdater
* LanguageFactory
* LanguageNameUtils
* LinkRenderer
* LinkRendererFactory
* LocalisationCache
* MagicWordFactory
* MessageCache
* NamespaceInfo
* PageEditStash
* PageHandlerFactory
* PageUpdater
* ParserFactory
* PermissionManager
* RevisionStore
* RevisionStoreFactory
* SearchEngineConfig
* SearchEngineFactory
* SearchFormWidget
* SearchNearMatcher
* SessionBackend
* SpecialPageFactory
* UserNameUtils
* UserOptionsManager
* WatchedItemQueryService
* WatchedItemStore
Constructors with new optional arguments:
* DefaultPreferencesFactory
* Language
* LinkHolderArray
* MovePage
* Parser
* ParserCache
* PasswordReset
* Router
setHookContainer() now required after construction:
* AuthenticationProvider
* ResourceLoaderModule
* SearchEngine
Change-Id: Id442b0dbe43aba84bd5cf801d86dedc768b082c7
2020-03-19 02:42:09 +00:00
|
|
|
$config = [],
|
|
|
|
|
$hooks = []
|
2021-01-22 00:20:44 +00:00
|
|
|
): HttpException {
|
2020-03-02 12:28:10 +00:00
|
|
|
try {
|
Hooks::run() call site migration
Migrate all callers of Hooks::run() to use the new
HookContainer/HookRunner system.
General principles:
* Use DI if it is already used. We're not changing the way state is
managed in this patch.
* HookContainer is always injected, not HookRunner. HookContainer
is a service, it's a more generic interface, it is the only
thing that provides isRegistered() which is needed in some cases,
and a HookRunner can be efficiently constructed from it
(confirmed by benchmark). Because HookContainer is needed
for object construction, it is also needed by all factories.
* "Ask your friendly local base class". Big hierarchies like
SpecialPage and ApiBase have getHookContainer() and getHookRunner()
methods in the base class, and classes that extend that base class
are not expected to know or care where the base class gets its
HookContainer from.
* ProtectedHookAccessorTrait provides protected getHookContainer() and
getHookRunner() methods, getting them from the global service
container. The point of this is to ease migration to DI by ensuring
that call sites ask their local friendly base class rather than
getting a HookRunner from the service container directly.
* Private $this->hookRunner. In some smaller classes where accessor
methods did not seem warranted, there is a private HookRunner property
which is accessed directly. Very rarely (two cases), there is a
protected property, for consistency with code that conventionally
assumes protected=private, but in cases where the class might actually
be overridden, a protected accessor is preferred over a protected
property.
* The last resort: Hooks::runner(). Mostly for static, file-scope and
global code. In a few cases it was used for objects with broken
construction schemes, out of horror or laziness.
Constructors with new required arguments:
* AuthManager
* BadFileLookup
* BlockManager
* ClassicInterwikiLookup
* ContentHandlerFactory
* ContentSecurityPolicy
* DefaultOptionsManager
* DerivedPageDataUpdater
* FullSearchResultWidget
* HtmlCacheUpdater
* LanguageFactory
* LanguageNameUtils
* LinkRenderer
* LinkRendererFactory
* LocalisationCache
* MagicWordFactory
* MessageCache
* NamespaceInfo
* PageEditStash
* PageHandlerFactory
* PageUpdater
* ParserFactory
* PermissionManager
* RevisionStore
* RevisionStoreFactory
* SearchEngineConfig
* SearchEngineFactory
* SearchFormWidget
* SearchNearMatcher
* SessionBackend
* SpecialPageFactory
* UserNameUtils
* UserOptionsManager
* WatchedItemQueryService
* WatchedItemStore
Constructors with new optional arguments:
* DefaultPreferencesFactory
* Language
* LinkHolderArray
* MovePage
* Parser
* ParserCache
* PasswordReset
* Router
setHookContainer() now required after construction:
* AuthenticationProvider
* ResourceLoaderModule
* SearchEngine
Change-Id: Id442b0dbe43aba84bd5cf801d86dedc768b082c7
2020-03-19 02:42:09 +00:00
|
|
|
$this->executeHandler( $handler, $request, $config, $hooks );
|
2020-03-02 12:28:10 +00:00
|
|
|
Assert::fail( 'Expected a HttpException to be thrown' );
|
|
|
|
|
} catch ( HttpException $ex ) {
|
|
|
|
|
return $ex;
|
|
|
|
|
}
|
|
|
|
|
}
|
2022-11-16 19:08:58 +00:00
|
|
|
|
2020-02-27 22:00:28 +00:00
|
|
|
}
|