Debian Codegraph @

tests/phpunit/unit/includes/Rest/Handler/HandlerTestTrait.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\Tests\Rest\Handler;
4
5 use MediaWiki\HookContainer\HookContainer;
6 use MediaWiki\Permissions\Authority;
7 use MediaWiki\Rest\Handler;
8 use MediaWiki\Rest\HttpException;
9 use MediaWiki\Rest\Module\Module;
10 use MediaWiki\Rest\RequestInterface;
11 use MediaWiki\Rest\Response;
12 use MediaWiki\Rest\ResponseFactory;
13 use MediaWiki\Rest\ResponseInterface;
14 use MediaWiki\Rest\Router;
15 use MediaWiki\Rest\Validator\Validator;
16 use MediaWiki\Session\Session;
17 use MediaWiki\Tests\Rest\RestTestTrait;
18 use MediaWiki\Tests\Unit\DummyServicesTrait;
19 use MediaWiki\Tests\Unit\Permissions\MockAuthorityTrait;
20 use PHPUnit\Framework\Assert;
21 use PHPUnit\Framework\MockObject\MockObject;
22 use Wikimedia\ObjectFactory\ObjectFactory;
23
24 /**
25 * A trait providing utility functions for testing Handler classes.
26 * This trait is intended to be used on subclasses of MediaWikiUnitTestCase
27 * or MediaWikiIntegrationTestCase.
28 *
29 * @stable to use
30 */
31 trait HandlerTestTrait {
32 use RestTestTrait;
33 use DummyServicesTrait;
34 use MockAuthorityTrait;
35 use SessionHelperTestTrait;
36
37 /**
38 * Calls init() on the Handler, supplying a mock RouteUrlProvider and ResponseFactory.
39 *
40 * @param Handler $handler
41 * @param RequestInterface $request
42 * @param array $config
43 * @param HookContainer|array $hooks Hook container or array of hooks
44 * @param Authority|null $authority
45 * @param Session|null $session Defaults to `$this->getSession( true )`
46 * @param Router|Module|null $routerOrModule
47 *
48 * @internal to the trait
49 */
50 private function initHandler(
51 Handler $handler,
52 RequestInterface $request,
53 $config = [],
54 $hooks = [],
55 ?Authority $authority = null,
56 ?Session $session = null,
57 $routerOrModule = null
58 ) {
59 $formatter = $this->getDummyTextFormatter( true );
60 $responseFactory = new ResponseFactory( [ 'qqx' => $formatter ] );
61
62 $module = null;
63 $router = null;
64
65 if ( $routerOrModule instanceof Module ) {
66 $module = $routerOrModule;
67 $router = $module->getRouter();
68 }
69
70 if ( $routerOrModule instanceof Router ) {
71 $router = $routerOrModule;
72 }
73
74 if ( !$module ) {
75 if ( !$router ) {
76 $router = $this->newRouter();
77 }
78
79 $module = $this->newModule( [ 'router' => $router ] );
80 }
81
82 if ( !$request->hasBody()
83 && in_array( $request->getMethod(), RequestInterface::BODY_METHODS )
84 ) {
85 // Send an empty body if none was provided.
86 $request->setParsedBody( [] );
87 }
88
89 $authority ??= $this->mockAnonUltimateAuthority();
90 $hookContainer =
91 $hooks instanceof HookContainer ? $hooks : $this->createHookContainer( $hooks );
92
93 $session ??= $this->getSession( true );
94 $handler->initContext( $module, $config['path'] ?? 'test', $config );
95 $handler->initServices( $authority, $responseFactory, $hookContainer );
96 $handler->initSession( $session );
97 $handler->initForExecute( $request );
98 }
99
100 /**
101 * @return MockObject&Router
102 */
103 private function newRouter(): Router {
104 $router = $this->createNoOpMock(
105 Router::class,
106 [
107 'getRoutePath',
108 'getRouteUrl',
109 'isRestbaseCompatEnabled'
110 ]
111 );
112 $router->method( 'getRoutePath' )->willReturnCallback(
113 static function ( $route, $path = [], $query = [] ) {
114 foreach ( $path as $param => $value ) {
115 $route = str_replace(
116 '{' . $param . '}',
117 urlencode( (string)$value ),
118 $route
119 );
120 }
121
122 return wfAppendQuery(
123 '/rest' . $route,
124 $query
125 );
126 }
127 );
128 $router->method( 'getRouteUrl' )->willReturnCallback(
129 static function ( $route, $path = [], $query = [] ) use ( $router ) {
130 return 'https://wiki.example.com' . $router->getRoutePath(
131 $route,
132 $path,
133 $query
134 );
135 }
136 );
137 $router->method( 'isRestbaseCompatEnabled' )->willReturnCallback(
138 static function ( RequestInterface $request ) {
139 return $request->getHeaderLine( 'x-restbase-compat' ) === 'true';
140 }
141 );
142
143 return $router;
144 }
145
146 /**
147 * Calls validate() on the Handler, with an appropriate Validator supplied.
148 *
149 * @internal to the trait
150 * @param Handler $handler
151 * @param null|Validator $validator
152 * @throws HttpException
153 */
154 private function validateHandler(
155 Handler $handler,
156 ?Validator $validator = null
157 ) {
158 if ( !$validator ) {
159 $serviceContainer = $this->getServiceContainer();
160 $objectFactory = new ObjectFactory( $serviceContainer );
161 $validator = new Validator( $objectFactory, $handler->getRequest(), $handler->getAuthority() );
162 }
163 $handler->validate( $validator );
164 }
165
166 /**
167 * Creates a mock Validator to bypass actual request query, path, and/or body param validation
168 *
169 * @internal to the trait
170 * @param array $queryPathParams
171 * @param array $bodyParams
172 * @return Validator|MockObject
173 */
174 private function getMockValidator( array $queryPathParams, array $bodyParams ): Validator {
175 $validator = $this->createNoOpMock(
176 Validator::class,
177 [
178 'validateParams',
179 'validateBodyParams',
180 'validateBody',
181 'detectExtraneousBodyFields',
182 ]
183 );
184 $validator->method( 'validateBody' )->willReturn( null );
185 $validator->method( 'validateParams' )->willReturn( $queryPathParams );
186 $validator->method( 'validateBodyParams' )->willReturn( $bodyParams );
187 return $validator;
188 }
189
190 /**
191 * Executes the given Handler on the given request.
192 *
193 * @param Handler $handler
194 * @param RequestInterface $request
195 * @param array $config
196 * @param HookContainer|array $hooks Hook container or array of hooks
197 * @param array $validatedParams Path/query params to return as already valid
198 * @param array $validatedBody Body params to return as already valid
199 * @param Authority|null $authority
200 * @param Session|null $session Defaults to `$this->getSession( true )`
201 * @param Router|Module|null $routerOrModule
202 *
203 * @return ResponseInterface
204 */
205 private function executeHandler(
206 Handler $handler,
207 RequestInterface $request,
208 $config = [],
209 $hooks = [],
210 $validatedParams = [],
211 $validatedBody = [],
212 ?Authority $authority = null,
213 ?Session $session = null,
214 $routerOrModule = null
215 ): ResponseInterface {
216 // supply defaults for required fields in $config
217 $config += [ 'path' => '/test' ];
218
219 $this->initHandler( $handler, $request, $config, $hooks, $authority, $session, $routerOrModule );
220 $validator = null;
221 if ( $validatedParams || $validatedBody ) {
222 /** @var Validator|MockObject $validator */
223 $validator = $this->getMockValidator( $validatedParams, $validatedBody );
224 }
225 $this->validateHandler( $handler, $validator );
226
227 // Check conditional request headers
228 $earlyResponse = $handler->checkPreconditions();
229 if ( $earlyResponse ) {
230 return $earlyResponse;
231 }
232
233 $ret = $handler->execute();
234
235 $response = $ret instanceof Response ? $ret
236 : $handler->getResponseFactory()->createFromReturnValue( $ret );
237
238 // Set Last-Modified and ETag headers in the response if available
239 $handler->applyConditionalResponseHeaders( $response );
240
241 return $response;
242 }
243
244 /**
245 * Executes the given Handler on the given request, parses the response body as JSON,
246 * and returns the result.
247 *
248 * @param Handler $handler
249 * @param RequestInterface $request
250 * @param array $config
251 * @param HookContainer|array $hooks Hook container or array of hooks
252 * @param array $validatedParams
253 * @param array $validatedBody
254 * @param Authority|null $authority
255 * @param Session|null $session Defaults to `$this->getSession( true )`
256 * @return array
257 */
258 private function executeHandlerAndGetBodyData(
259 Handler $handler,
260 RequestInterface $request,
261 $config = [],
262 $hooks = [],
263 $validatedParams = [],
264 $validatedBody = [],
265 ?Authority $authority = null,
266 ?Session $session = null
267 ): array {
268 $response = $this->executeHandler( $handler, $request, $config, $hooks,
269 $validatedParams, $validatedBody, $authority, $session );
270
271 $this->assertGreaterThanOrEqual( 200, $response->getStatusCode() );
272 $this->assertLessThan( 300, $response->getStatusCode() );
273 $this->assertSame( 'application/json', $response->getHeaderLine( 'Content-Type' ) );
274
275 $data = json_decode( $response->getBody(), true );
276 $this->assertIsArray( $data, 'Body must be a JSON array' );
277
278 return $data;
279 }
280
281 /**
282 * Executes the given Handler on the given request, and returns the HttpException thrown.
283 * Fails if no HttpException is thrown.
284 *
285 * @param Handler $handler
286 * @param RequestInterface $request
287 * @param array $config
288 * @param HookContainer|array $hooks Hook container or array of hooks
289 *
290 * @return HttpException
291 */
292 private function executeHandlerAndGetHttpException(
293 Handler $handler,
294 RequestInterface $request,
295 $config = [],
296 $hooks = []
297 ): HttpException {
298 try {
299 $this->executeHandler( $handler, $request, $config, $hooks );
300 Assert::fail( 'Expected a HttpException to be thrown' );
301 } catch ( HttpException $ex ) {
302 return $ex;
303 }
304 }
305
306 }