Debian Codegraph @

tests/phpunit/integration/includes/Rest/Handler/CreationHandlerTest.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\Tests\Rest\Handler;
4
5 use MediaWiki\Api\ApiUsageException;
6 use MediaWiki\Config\HashConfig;
7 use MediaWiki\Content\WikitextContent;
8 use MediaWiki\MainConfigNames;
9 use MediaWiki\Message\Message;
10 use MediaWiki\Rest\Handler\CreationHandler;
11 use MediaWiki\Rest\LocalizedHttpException;
12 use MediaWiki\Rest\RequestData;
13 use MediaWiki\Revision\MutableRevisionRecord;
14 use MediaWiki\Revision\RevisionLookup;
15 use MediaWiki\Revision\SlotRecord;
16 use MediaWiki\Session\Token;
17 use MediaWiki\Status\Status;
18 use MediaWiki\Tests\Unit\DummyServicesTrait;
19 use MediaWikiIntegrationTestCase;
20 use MockTitleTrait;
21 use PHPUnit\Framework\MockObject\MockObject;
22 use Wikimedia\Message\DataMessageValue;
23 use Wikimedia\Message\MessageValue;
24 use Wikimedia\Message\ParamType;
25 use Wikimedia\Message\ScalarParam;
26
27 /**
28 * @covers \MediaWiki\Rest\Handler\CreationHandler
29 */
30 class CreationHandlerTest extends MediaWikiIntegrationTestCase {
31 use ActionModuleBasedHandlerTestTrait;
32 use DummyServicesTrait;
33 use MockTitleTrait;
34
35 private function newHandler( $resultData, $throwException = null, $csrfSafe = false ) {
36 $config = new HashConfig( [
37 MainConfigNames::RightsUrl => 'https://creativecommons.org/licenses/by-sa/4.0/',
38 MainConfigNames::RightsText => 'CC-BY-SA 4.0'
39 ] );
40
41 // Claims that wikitext and plaintext are defined, but trying to get the actual
42 // content handlers would break
43 $contentHandlerFactory = $this->getDummyContentHandlerFactory( [
44 CONTENT_MODEL_WIKITEXT => true,
45 CONTENT_MODEL_TEXT => true,
46 ] );
47
48 $titleCodec = $this->getDummyMediaWikiTitleCodec();
49
50 /** @var RevisionLookup|MockObject $revisionLookup */
51 $revisionLookup = $this->createNoOpMock( RevisionLookup::class, [ 'getRevisionById' ] );
52 $revisionLookup->method( 'getRevisionById' )
53 ->willReturnCallback( function ( $id ) {
54 $title = $this->makeMockTitle( __CLASS__ );
55 $rev = new MutableRevisionRecord( $title );
56 $rev->setId( $id );
57 $rev->setContent( SlotRecord::MAIN, new WikitextContent( "Content of revision $id" ) );
58 return $rev;
59 } );
60
61 $handler = new CreationHandler(
62 $config,
63 $contentHandlerFactory,
64 $titleCodec,
65 $titleCodec,
66 $revisionLookup
67 );
68
69 $apiMain = $this->getApiMain( $csrfSafe );
70 $dummyModule = $this->getDummyApiModule( $apiMain, 'edit', $resultData, $throwException );
71
72 $handler->setApiMain( $apiMain );
73 $handler->overrideActionModule(
74 'edit',
75 'action',
76 $dummyModule
77 );
78
79 return $handler;
80 }
81
82 public static function provideExecute() {
83 // NOTE: Prefix hard coded in a fake for Router::getRouteUrl() in HandlerTestTrait
84 $baseUrl = 'https://wiki.example.com/rest/v1/page/';
85 $token = strval( new Token( 'TOKEN', '' ) );
86
87 yield "create with token" => [
88 [ // Request data received by CreationHandler
89 'method' => 'POST',
90 'headers' => [
91 'Content-Type' => 'application/json',
92 ],
93 'bodyContents' => json_encode( [
94 'token' => $token,
95 'title' => 'Foo',
96 'source' => 'Lorem Ipsum',
97 'comment' => 'Testing'
98 ] ),
99 ],
100 [ // Fake request expected to be passed into ApiEditPage
101 'title' => 'Foo',
102 'text' => 'Lorem Ipsum',
103 'summary' => 'Testing',
104 'createonly' => '1',
105 ],
106 [ // Mock response returned by ApiEditPage
107 "edit" => [
108 "new" => true,
109 "result" => "Success",
110 "pageid" => 94542,
111 "title" => "Foo",
112 "contentmodel" => "wikitext",
113 "oldrevid" => 0,
114 "newrevid" => 371707,
115 "newtimestamp" => "2018-12-18T16:59:42Z",
116 ]
117 ],
118 [ // Response expected to be generated by CreationHandler
119 'id' => 94542,
120 'title' => 'Foo',
121 'key' => 'Foo',
122 'content_model' => 'wikitext',
123 'latest' => [
124 'id' => 371707,
125 'timestamp' => "2018-12-18T16:59:42Z"
126 ],
127 'license' => [
128 'url' => 'https://creativecommons.org/licenses/by-sa/4.0/',
129 'title' => 'CC-BY-SA 4.0'
130 ],
131 'source' => 'Content of revision 371707'
132 ],
133 $baseUrl . 'Foo',
134 false,
135 true,
136 ];
137
138 yield "create with model" => [
139 [ // Request data received by CreationHandler
140 'method' => 'POST',
141 'headers' => [
142 'Content-Type' => 'application/json',
143 ],
144 'bodyContents' => json_encode( [
145 'title' => 'Talk:Foo',
146 'source' => 'Lorem Ipsum',
147 'comment' => 'Testing',
148 'content_model' => CONTENT_MODEL_TEXT,
149 ] ),
150 ],
151 [ // Fake request expected to be passed into ApiEditPage
152 'title' => 'Talk:Foo',
153 'text' => 'Lorem Ipsum',
154 'summary' => 'Testing',
155 'contentmodel' => CONTENT_MODEL_TEXT,
156 'createonly' => '1',
157 'token' => '+\\',
158 ],
159 [ // Mock response returned by ApiEditPage
160 "edit" => [
161 "new" => true,
162 "result" => "Success",
163 "pageid" => 94542,
164 "title" => "Talk:Foo",
165 "contentmodel" => CONTENT_MODEL_TEXT,
166 "oldrevid" => 0,
167 "newrevid" => 371707,
168 "newtimestamp" => "2018-12-18T16:59:42Z",
169 ]
170 ],
171 [ // Response expected to be generated by CreationHandler
172 'id' => 94542,
173 'title' => 'Talk:Foo',
174 'key' => 'Talk:Foo',
175 'content_model' => CONTENT_MODEL_TEXT,
176 'latest' => [
177 'id' => 371707,
178 'timestamp' => "2018-12-18T16:59:42Z"
179 ],
180 'license' => [
181 'url' => 'https://creativecommons.org/licenses/by-sa/4.0/',
182 'title' => 'CC-BY-SA 4.0'
183 ],
184 'source' => 'Content of revision 371707'
185 ],
186 $baseUrl . 'Talk:Foo',
187 true,
188 false,
189 ];
190
191 yield "create without token" => [
192 [ // Request data received by CreationHandler
193 'method' => 'POST',
194 'headers' => [
195 'Content-Type' => 'application/json',
196 ],
197 'bodyContents' => json_encode( [
198 'title' => 'foo/bar',
199 'source' => 'Lorem Ipsum',
200 'comment' => 'Testing',
201 'content_model' => CONTENT_MODEL_WIKITEXT,
202 ] ),
203 ],
204 [ // Fake request expected to be passed into ApiEditPage
205 'title' => 'foo/bar',
206 'text' => 'Lorem Ipsum',
207 'summary' => 'Testing',
208 'contentmodel' => 'wikitext',
209 'createonly' => '1',
210 'token' => '+\\', // use known-good token for current user (anon)
211 ],
212 [ // Mock response returned by ApiEditPage
213 "edit" => [
214 "new" => true,
215 "result" => "Success",
216 "pageid" => 94542,
217 "title" => "Foo/bar",
218 "contentmodel" => "wikitext",
219 "oldrevid" => 0,
220 "newrevid" => 371707,
221 "newtimestamp" => "2018-12-18T16:59:42Z",
222 ]
223 ],
224 [ // Response expected to be generated by CreationHandler
225 'id' => 94542,
226 'title' => 'Foo/bar',
227 'key' => 'Foo/bar',
228 'content_model' => 'wikitext',
229 'latest' => [
230 'id' => 371707,
231 'timestamp' => "2018-12-18T16:59:42Z"
232 ],
233 'license' => [
234 'url' => 'https://creativecommons.org/licenses/by-sa/4.0/',
235 'title' => 'CC-BY-SA 4.0'
236 ],
237 'source' => 'Content of revision 371707'
238 ],
239 $baseUrl . 'Foo%2Fbar',
240 true,
241 false,
242 ];
243
244 yield "create with space" => [
245 [ // Request data received by CreationHandler
246 'method' => 'POST',
247 'headers' => [
248 'Content-Type' => 'application/json',
249 ],
250 'bodyContents' => json_encode( [
251 'title' => 'foo (ba+r)',
252 'source' => 'Lorem Ipsum',
253 'comment' => 'Testing'
254 ] ),
255 ],
256 [ // Fake request expected to be passed into ApiEditPage
257 'title' => 'foo (ba+r)',
258 'text' => 'Lorem Ipsum',
259 'summary' => 'Testing',
260 'createonly' => '1',
261 'token' => '+\\', // use known-good token for current user (anon)
262 ],
263 [ // Mock response returned by ApiEditPage
264 "edit" => [
265 "new" => true,
266 "result" => "Success",
267 "pageid" => 94542,
268 "title" => "Foo (ba+r)",
269 "contentmodel" => "wikitext",
270 "oldrevid" => 0,
271 "newrevid" => 371707,
272 "newtimestamp" => "2018-12-18T16:59:42Z",
273 ]
274 ],
275 [ // Response expected to be generated by CreationHandler
276 'id' => 94542,
277 'title' => 'Foo (ba+r)',
278 'key' => 'Foo_(ba+r)',
279 'content_model' => 'wikitext',
280 'latest' => [
281 'id' => 371707,
282 'timestamp' => "2018-12-18T16:59:42Z"
283 ],
284 'license' => [
285 'url' => 'https://creativecommons.org/licenses/by-sa/4.0/',
286 'title' => 'CC-BY-SA 4.0'
287 ],
288 'source' => 'Content of revision 371707'
289 ],
290 $baseUrl . 'Foo_(ba%2Br)',
291 true,
292 false
293 ];
294 }
295
296 /**
297 * @dataProvider provideExecute
298 */
299 public function testExecute(
300 $requestData,
301 $expectedActionParams,
302 $actionResult,
303 $expectedResponse,
304 $expectedRedirect,
305 $csrfSafe,
306 $hasToken
307 ) {
308 $request = new RequestData( $requestData );
309
310 $handler = $this->newHandler( $actionResult, null, $csrfSafe );
311
312 $session = $this->getSession( $csrfSafe );
313
314 $session->method( 'hasToken' )->willReturn( $hasToken );
315
316 $session->method( 'getToken' )->willReturn( new Token( 'TOKEN', '' ) );
317
318 $response = $this->executeHandler( $handler, $request, [], [], [], [], null, $session );
319
320 $this->assertSame( 201, $response->getStatusCode() );
321 $this->assertSame(
322 $expectedRedirect,
323 $response->getHeaderLine( 'Location' )
324 );
325 $this->assertSame( 'application/json', $response->getHeaderLine( 'Content-Type' ) );
326
327 $responseData = json_decode( $response->getBody(), true );
328 $this->assertIsArray( $responseData, 'Body must be a JSON array' );
329
330 // Check parameters passed to ApiEditPage by CreationHandler based on $requestData
331 foreach ( $expectedActionParams as $key => $value ) {
332 $this->assertSame(
333 $value,
334 $handler->getApiMain()->getVal( $key ),
335 "ApiEditPage param: $key"
336 );
337 }
338
339 // Check response that CreationHandler created after receiving $actionResult from ApiEditPage
340 foreach ( $expectedResponse as $key => $value ) {
341 $this->assertArrayHasKey( $key, $responseData );
342 $this->assertSame(
343 $value,
344 $responseData[ $key ],
345 "CreationHandler response field: $key"
346 );
347 }
348 }
349
350 public static function provideBodyValidation() {
351 yield "missing source field" => [
352 [ // Request data received by CreationHandler
353 'method' => 'POST',
354 'headers' => [
355 'Content-Type' => 'application/json',
356 ],
357 'bodyContents' => json_encode( [
358 'token' => 'TOKEN',
359 'title' => 'Foo',
360 'comment' => 'Testing',
361 'content_model' => CONTENT_MODEL_WIKITEXT,
362 ] ),
363 ],
364 MessageValue::new( 'rest-body-validation-error', [
365 DataMessageValue::new( 'paramvalidator-missingparam', [], 'missingparam' )
366 ->plaintextParams( 'source' )
367 ] ),
368 ];
369 yield "missing comment field" => [
370 [ // Request data received by CreationHandler
371 'method' => 'POST',
372 'headers' => [
373 'Content-Type' => 'application/json',
374 ],
375 'bodyContents' => json_encode( [
376 'token' => 'TOKEN',
377 'title' => 'Foo',
378 'source' => 'Lorem Ipsum',
379 'content_model' => CONTENT_MODEL_WIKITEXT,
380 ] ),
381 ],
382 MessageValue::new( 'rest-body-validation-error', [
383 DataMessageValue::new( 'paramvalidator-missingparam', [], 'missingparam' )
384 ->plaintextParams( 'comment' )
385 ] ),
386 ];
387 yield "missing title field" => [
388 [ // Request data received by CreationHandler
389 'method' => 'POST',
390 'headers' => [
391 'Content-Type' => 'application/json',
392 ],
393 'bodyContents' => json_encode( [
394 'token' => 'TOKEN',
395 'comment' => 'Testing',
396 'source' => 'Lorem Ipsum',
397 'content_model' => CONTENT_MODEL_WIKITEXT,
398 ] ),
399 ],
400 MessageValue::new( 'rest-body-validation-error', [
401 DataMessageValue::new( 'paramvalidator-missingparam', [], 'missingparam' )
402 ->plaintextParams( 'title' )
403 ] ),
404 ];
405 }
406
407 /**
408 * @dataProvider provideBodyValidation
409 */
410 public function testBodyValidation( array $requestData, MessageValue $expectedMessage ) {
411 $request = new RequestData( $requestData );
412
413 $handler = $this->newHandler( [] );
414
415 $exception = $this->executeHandlerAndGetHttpException( $handler, $request );
416
417 $this->assertSame( 400, $exception->getCode(), 'HTTP status' );
418 $this->assertInstanceOf( LocalizedHttpException::class, $exception );
419
420 /** @var LocalizedHttpException $exception */
421 $this->assertEquals( $expectedMessage, $exception->getMessageValue() );
422 }
423
424 public static function provideHeaderValidation() {
425 yield "bad content type" => [
426 [ // Request data received by CreationHandler
427 'method' => 'POST',
428 'headers' => [
429 'Content-Type' => 'text/plain',
430 ],
431 'bodyContents' => json_encode( [
432 'title' => 'Foo',
433 'source' => 'Lorem Ipsum',
434 'comment' => 'Testing',
435 'content_model' => CONTENT_MODEL_WIKITEXT,
436 ] ),
437 ],
438 415
439 ];
440 }
441
442 /**
443 * @dataProvider provideHeaderValidation
444 */
445 public function testHeaderValidation( array $requestData, $expectedStatus ) {
446 $request = new RequestData( $requestData );
447
448 $handler = $this->newHandler( [] );
449
450 $exception = $this->executeHandlerAndGetHttpException( $handler, $request );
451
452 $this->assertSame( $expectedStatus, $exception->getCode(), 'HTTP status' );
453 }
454
455 /*
456 * FIXME: Status::newFatal invokes MediaWikiServices, which is not allowed in a dataProvider.
457 */
458 public static function provideErrorMapping() {
459 yield "missingtitle" => [
460 new ApiUsageException( null, Status::newFatal( 'apierror-missingtitle' ) ),
461 new LocalizedHttpException( new MessageValue( 'apierror-missingtitle' ), 404 ),
462 ];
463 yield "protectedpage" => [
464 new ApiUsageException( null, Status::newFatal( 'apierror-protectedpage' ) ),
465 new LocalizedHttpException( new MessageValue( 'apierror-protectedpage' ), 403 ),
466 ];
467 yield "articleexists" => [
468 new ApiUsageException( null, Status::newFatal( 'apierror-articleexists' ) ),
469 new LocalizedHttpException( new MessageValue( 'apierror-articleexists' ), 409 ),
470 ];
471 yield "editconflict" => [
472 new ApiUsageException( null, Status::newFatal( 'apierror-editconflict' ) ),
473 new LocalizedHttpException( new MessageValue( 'apierror-editconflict' ), 409 ),
474 ];
475 yield "ratelimited" => [
476 new ApiUsageException( null, Status::newFatal( 'apierror-ratelimited' ) ),
477 new LocalizedHttpException( new MessageValue( 'apierror-ratelimited' ), 429 ),
478 ];
479 yield "badtoken" => [
480 new ApiUsageException(
481 null,
482 Status::newFatal( 'apierror-badtoken', Message::plaintextParam( 'BAD' ) )
483 ),
484 new LocalizedHttpException(
485 new MessageValue(
486 'apierror-badtoken',
487 [ new ScalarParam( ParamType::PLAINTEXT, 'BAD' ) ]
488 ), 403
489 ),
490 ];
491
492 // Unmapped errors should be passed through with a status 400.
493 yield "no-direct-editing" => [
494 new ApiUsageException( null, Status::newFatal( 'apierror-no-direct-editing' ) ),
495 new LocalizedHttpException( new MessageValue( 'apierror-no-direct-editing' ), 400 ),
496 ];
497 yield "badformat" => [
498 new ApiUsageException( null, Status::newFatal( 'apierror-badformat' ) ),
499 new LocalizedHttpException( new MessageValue( 'apierror-badformat' ), 400 ),
500 ];
501 yield "emptypage" => [
502 new ApiUsageException( null, Status::newFatal( 'apierror-emptypage' ) ),
503 new LocalizedHttpException( new MessageValue( 'apierror-emptypage' ), 400 ),
504 ];
505 }
506
507 public function testErrorMapping() {
508 $provideErrorMapping = $this->provideErrorMapping();
509 foreach ( $provideErrorMapping as $expected ) {
510 $apiUsageException = $expected[0];
511 $expectedHttpException = $expected[1];
512 $requestData = [ // Request data received by CreationHandler
513 'method' => 'POST',
514 'headers' => [
515 'Content-Type' => 'application/json',
516 ],
517 'bodyContents' => json_encode( [
518 'title' => 'Foo',
519 'source' => 'Lorem Ipsum',
520 'comment' => 'Testing',
521 'content_model' => CONTENT_MODEL_WIKITEXT,
522 ] ),
523 ];
524 $request = new RequestData( $requestData );
525
526 $handler = $this->newHandler( [], $apiUsageException );
527
528 $exception = $this->executeHandlerAndGetHttpException( $handler, $request );
529
530 $this->assertSame( $expectedHttpException->getMessage(), $exception->getMessage() );
531 $this->assertSame( $expectedHttpException->getCode(), $exception->getCode(), 'HTTP status' );
532
533 $errorData = $exception->getErrorData();
534 if ( $expectedHttpException->getErrorData() ) {
535 foreach ( $expectedHttpException->getErrorData() as $key => $value ) {
536 $this->assertSame( $value, $errorData[$key], 'Error data key $key' );
537 }
538 }
539
540 if ( $expectedHttpException instanceof LocalizedHttpException ) {
541 /** @var LocalizedHttpException $exception */
542 $this->assertEquals(
543 $expectedHttpException->getMessageValue(),
544 $exception->getMessageValue()
545 );
546 }
547 }
548 }
549
550 }