wiki.techinc.nl/tests/phpunit/unit/includes/Rest/Handler/HandlerTestTrait.php

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

301 lines
8.4 KiB
PHP
Raw Normal View History

<?php
namespace MediaWiki\Tests\Rest\Handler;
Introduce SearchResultThumbnailProvider & move hook + NS_FILE thumbs in What was previously a REST API-only feature (the thumbnails hook allowing for thumbnails for non-file pages via the PageImages extension) is now also being adopted in the main search page. That hook will now be called with NS_FILE result thumbnails pre-filled, which was not the case previously. PageImages essentially duplicated NS_FILE thumbnail logic that was already present in Special:Search, so that can (and will in a follow-up patch) then be removed there. Special:Search will then simply take whatever is produced from the provider (which will include both NS_FILE thumbs - which it handled already - as well as whatever else it receives from the hook), as will the REST API (which already received both) Since thumbnails can now come in for multiple namespaces & having some of those results with & others without a thumbnail can be quite jarring, it was decided that we'd display placeholder images (for certain namespaces). This is now controlled by $wgThumbnailNamespaces. I also split up a few things in FullSearchResultWidget:: generateFileHtml for more clarity. Meanwhile also updated mediawiki.special.search.styles.less to use variables for known colors. Also implemented a 'transform' (required for testing this change properly) and 'getDisplayWidthHeight' (it became needed after implementing transform) callback function for mock Files, and updated some existing tests in response to these changes. And some more Rest test files have been updated to allow passing around a HookContainer instead of only an array of hooks (from which a new HookContainer would then be created) to allow the same container to be used across all relevant objects, who may have it injected as dependency. Bug: T306883 Change-Id: I2a679b51758020d3e822da01a1bde1ae632b0b0a
2022-08-31 14:51:57 +00:00
use MediaWiki\HookContainer\HookContainer;
use MediaWiki\Permissions\Authority;
use MediaWiki\Rest\Handler;
use MediaWiki\Rest\HttpException;
use MediaWiki\Rest\Module\Module;
use MediaWiki\Rest\RequestInterface;
use MediaWiki\Rest\Response;
use MediaWiki\Rest\ResponseFactory;
use MediaWiki\Rest\ResponseInterface;
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;
use MediaWiki\Tests\Rest\RestTestTrait;
use MediaWiki\Tests\Unit\DummyServicesTrait;
use MediaWiki\Tests\Unit\Permissions\MockAuthorityTrait;
use PHPUnit\Framework\Assert;
use PHPUnit\Framework\MockObject\MockObject;
use Wikimedia\ObjectFactory\ObjectFactory;
/**
* A trait providing utility functions for testing Handler classes.
* This trait is intended to be used on subclasses of MediaWikiUnitTestCase
* or MediaWikiIntegrationTestCase.
*
* @stable to use
*/
trait HandlerTestTrait {
use RestTestTrait;
use DummyServicesTrait;
use MockAuthorityTrait;
use SessionHelperTestTrait;
/**
* Calls init() on the Handler, supplying a mock RouteUrlProvider and ResponseFactory.
*
* @param Handler $handler
* @param RequestInterface $request
* @param array $config
Introduce SearchResultThumbnailProvider & move hook + NS_FILE thumbs in What was previously a REST API-only feature (the thumbnails hook allowing for thumbnails for non-file pages via the PageImages extension) is now also being adopted in the main search page. That hook will now be called with NS_FILE result thumbnails pre-filled, which was not the case previously. PageImages essentially duplicated NS_FILE thumbnail logic that was already present in Special:Search, so that can (and will in a follow-up patch) then be removed there. Special:Search will then simply take whatever is produced from the provider (which will include both NS_FILE thumbs - which it handled already - as well as whatever else it receives from the hook), as will the REST API (which already received both) Since thumbnails can now come in for multiple namespaces & having some of those results with & others without a thumbnail can be quite jarring, it was decided that we'd display placeholder images (for certain namespaces). This is now controlled by $wgThumbnailNamespaces. I also split up a few things in FullSearchResultWidget:: generateFileHtml for more clarity. Meanwhile also updated mediawiki.special.search.styles.less to use variables for known colors. Also implemented a 'transform' (required for testing this change properly) and 'getDisplayWidthHeight' (it became needed after implementing transform) callback function for mock Files, and updated some existing tests in response to these changes. And some more Rest test files have been updated to allow passing around a HookContainer instead of only an array of hooks (from which a new HookContainer would then be created) to allow the same container to be used across all relevant objects, who may have it injected as dependency. Bug: T306883 Change-Id: I2a679b51758020d3e822da01a1bde1ae632b0b0a
2022-08-31 14:51:57 +00:00
* @param HookContainer|array $hooks Hook container or array of hooks
* @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 )`
* @param Router|Module|null $routerOrModule
*
* @internal to the trait
*/
private function initHandler(
Handler $handler,
RequestInterface $request,
$config = [],
$hooks = [],
Authority $authority = null,
Session $session = null,
$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
) {
$formatter = $this->getDummyTextFormatter( true );
$responseFactory = new ResponseFactory( [ 'qqx' => $formatter ] );
$module = null;
$router = null;
if ( $routerOrModule instanceof Module ) {
$module = $routerOrModule;
$router = $module->getRouter();
}
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( [] );
}
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();
$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 );
$handler->initContext( $module, $config['path'] ?? 'test', $config );
$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;
}
/**
* Calls validate() on the Handler, with an appropriate Validator supplied.
*
* @internal to the trait
* @param Handler $handler
* @param null|Validator $validator
* @throws HttpException
*/
private function validateHandler(
Handler $handler,
Validator $validator = null
) {
if ( !$validator ) {
$serviceContainer = $this->getServiceContainer();
$objectFactory = new ObjectFactory( $serviceContainer );
$validator = new Validator( $objectFactory, $handler->getRequest(), $handler->getAuthority() );
}
$handler->validate( $validator );
}
/**
* Creates a mock Validator to bypass actual request query, path, and/or body param validation
*
* @internal to the trait
* @param array $queryPathParams
* @param array $bodyParams
* @return Validator|MockObject
*/
private function getMockValidator( array $queryPathParams, array $bodyParams ): Validator {
$validator = $this->createNoOpMock(
Validator::class,
[
'validateParams',
'validateBodyParams',
'validateBody',
'detectExtraneousBodyFields',
]
);
$validator->method( 'validateBody' )->willReturn( null );
$validator->method( 'validateParams' )->willReturn( $queryPathParams );
$validator->method( 'validateBodyParams' )->willReturn( $bodyParams );
return $validator;
}
/**
* Executes the given Handler on the given request.
*
* @param Handler $handler
* @param RequestInterface $request
* @param array $config
Introduce SearchResultThumbnailProvider & move hook + NS_FILE thumbs in What was previously a REST API-only feature (the thumbnails hook allowing for thumbnails for non-file pages via the PageImages extension) is now also being adopted in the main search page. That hook will now be called with NS_FILE result thumbnails pre-filled, which was not the case previously. PageImages essentially duplicated NS_FILE thumbnail logic that was already present in Special:Search, so that can (and will in a follow-up patch) then be removed there. Special:Search will then simply take whatever is produced from the provider (which will include both NS_FILE thumbs - which it handled already - as well as whatever else it receives from the hook), as will the REST API (which already received both) Since thumbnails can now come in for multiple namespaces & having some of those results with & others without a thumbnail can be quite jarring, it was decided that we'd display placeholder images (for certain namespaces). This is now controlled by $wgThumbnailNamespaces. I also split up a few things in FullSearchResultWidget:: generateFileHtml for more clarity. Meanwhile also updated mediawiki.special.search.styles.less to use variables for known colors. Also implemented a 'transform' (required for testing this change properly) and 'getDisplayWidthHeight' (it became needed after implementing transform) callback function for mock Files, and updated some existing tests in response to these changes. And some more Rest test files have been updated to allow passing around a HookContainer instead of only an array of hooks (from which a new HookContainer would then be created) to allow the same container to be used across all relevant objects, who may have it injected as dependency. Bug: T306883 Change-Id: I2a679b51758020d3e822da01a1bde1ae632b0b0a
2022-08-31 14:51:57 +00:00
* @param HookContainer|array $hooks Hook container or array of hooks
* @param array $validatedParams Path/query params to return as already valid
* @param array $validatedBody Body params to return as already valid
* @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 )`
* @param Router|Module|null $routerOrModule
*
* @return ResponseInterface
*/
private function executeHandler(
Handler $handler,
RequestInterface $request,
$config = [],
$hooks = [],
$validatedParams = [],
$validatedBody = [],
Authority $authority = null,
Session $session = null,
$routerOrModule = null
): ResponseInterface {
// supply defaults for required fields in $config
$config += [ 'path' => '/test' ];
$this->initHandler( $handler, $request, $config, $hooks, $authority, $session, $routerOrModule );
$validator = null;
if ( $validatedParams || $validatedBody ) {
/** @var Validator|MockObject $validator */
$validator = $this->getMockValidator( $validatedParams, $validatedBody );
}
$this->validateHandler( $handler, $validator );
// Check conditional request headers
$earlyResponse = $handler->checkPreconditions();
if ( $earlyResponse ) {
return $earlyResponse;
}
$ret = $handler->execute();
$response = $ret instanceof Response ? $ret
: $handler->getResponseFactory()->createFromReturnValue( $ret );
// Set Last-Modified and ETag headers in the response if available
$handler->applyConditionalResponseHeaders( $response );
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
Introduce SearchResultThumbnailProvider & move hook + NS_FILE thumbs in What was previously a REST API-only feature (the thumbnails hook allowing for thumbnails for non-file pages via the PageImages extension) is now also being adopted in the main search page. That hook will now be called with NS_FILE result thumbnails pre-filled, which was not the case previously. PageImages essentially duplicated NS_FILE thumbnail logic that was already present in Special:Search, so that can (and will in a follow-up patch) then be removed there. Special:Search will then simply take whatever is produced from the provider (which will include both NS_FILE thumbs - which it handled already - as well as whatever else it receives from the hook), as will the REST API (which already received both) Since thumbnails can now come in for multiple namespaces & having some of those results with & others without a thumbnail can be quite jarring, it was decided that we'd display placeholder images (for certain namespaces). This is now controlled by $wgThumbnailNamespaces. I also split up a few things in FullSearchResultWidget:: generateFileHtml for more clarity. Meanwhile also updated mediawiki.special.search.styles.less to use variables for known colors. Also implemented a 'transform' (required for testing this change properly) and 'getDisplayWidthHeight' (it became needed after implementing transform) callback function for mock Files, and updated some existing tests in response to these changes. And some more Rest test files have been updated to allow passing around a HookContainer instead of only an array of hooks (from which a new HookContainer would then be created) to allow the same container to be used across all relevant objects, who may have it injected as dependency. Bug: T306883 Change-Id: I2a679b51758020d3e822da01a1bde1ae632b0b0a
2022-08-31 14:51:57 +00:00
* @param HookContainer|array $hooks Hook container or array of hooks
* @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 )`
* @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 = [],
$hooks = [],
$validatedParams = [],
$validatedBody = [],
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
): array {
$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 );
$this->assertGreaterThanOrEqual( 200, $response->getStatusCode() );
$this->assertLessThan( 300, $response->getStatusCode() );
$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;
}
/**
* 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
Introduce SearchResultThumbnailProvider & move hook + NS_FILE thumbs in What was previously a REST API-only feature (the thumbnails hook allowing for thumbnails for non-file pages via the PageImages extension) is now also being adopted in the main search page. That hook will now be called with NS_FILE result thumbnails pre-filled, which was not the case previously. PageImages essentially duplicated NS_FILE thumbnail logic that was already present in Special:Search, so that can (and will in a follow-up patch) then be removed there. Special:Search will then simply take whatever is produced from the provider (which will include both NS_FILE thumbs - which it handled already - as well as whatever else it receives from the hook), as will the REST API (which already received both) Since thumbnails can now come in for multiple namespaces & having some of those results with & others without a thumbnail can be quite jarring, it was decided that we'd display placeholder images (for certain namespaces). This is now controlled by $wgThumbnailNamespaces. I also split up a few things in FullSearchResultWidget:: generateFileHtml for more clarity. Meanwhile also updated mediawiki.special.search.styles.less to use variables for known colors. Also implemented a 'transform' (required for testing this change properly) and 'getDisplayWidthHeight' (it became needed after implementing transform) callback function for mock Files, and updated some existing tests in response to these changes. And some more Rest test files have been updated to allow passing around a HookContainer instead of only an array of hooks (from which a new HookContainer would then be created) to allow the same container to be used across all relevant objects, who may have it injected as dependency. Bug: T306883 Change-Id: I2a679b51758020d3e822da01a1bde1ae632b0b0a
2022-08-31 14:51:57 +00:00
* @param HookContainer|array $hooks Hook container or array of hooks
*
* @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 = []
): HttpException {
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 );
Assert::fail( 'Expected a HttpException to be thrown' );
} catch ( HttpException $ex ) {
return $ex;
}
}
}