Debian Codegraph @

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

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\Tests\Rest\Handler;
4
5 use Exception;
6 use MediaWiki\Deferred\DeferredUpdates;
7 use MediaWiki\Hook\ParserLogLinterDataHook;
8 use MediaWiki\MainConfigNames;
9 use MediaWiki\Rest\Handler\PageHTMLHandler;
10 use MediaWiki\Rest\LocalizedHttpException;
11 use MediaWiki\Rest\RequestData;
12 use MediaWiki\Title\Title;
13 use MediaWiki\Utils\MWTimestamp;
14 use MediaWikiIntegrationTestCase;
15 use PHPUnit\Framework\MockObject\MockObject;
16 use Psr\Http\Message\StreamInterface;
17 use Wikimedia\Message\MessageValue;
18 use Wikimedia\ObjectCache\HashBagOStuff;
19 use Wikimedia\Parsoid\Core\ClientError;
20 use Wikimedia\Parsoid\Core\ResourceLimitExceededException;
21 use Wikimedia\Parsoid\Parsoid;
22 use Wikimedia\Parsoid\Utils\ContentUtils;
23 use Wikimedia\Parsoid\Utils\DOMUtils;
24 use WikiPage;
25
26 /**
27 * @covers \MediaWiki\Rest\Handler\PageHTMLHandler
28 * @group Database
29 */
30 class PageHTMLHandlerTest extends MediaWikiIntegrationTestCase {
31 use HandlerTestTrait;
32 use PageHandlerTestTrait;
33 use HTMLHandlerTestTrait;
34
35 private const WIKITEXT = 'Hello \'\'\'World\'\'\'';
36
37 private const HTML = '>World</';
38
39 private HashBagOStuff $parserCacheBagOStuff;
40
41 protected function setUp(): void {
42 parent::setUp();
43
44 $this->parserCacheBagOStuff = new HashBagOStuff();
45 // Protect the ObjectCacheFactory from the service container reset,
46 // so the emulated parser cache persists between calls to executeHandler().
47 $objectCacheFactory = $this->getServiceContainer()->getObjectCacheFactory();
48 $this->setService( 'ObjectCacheFactory', $objectCacheFactory );
49 }
50
51 /**
52 * @param Parsoid|MockObject|null $parsoid
53 *
54 * @return PageHTMLHandler
55 */
56 private function newHandler( ?Parsoid $parsoid = null ): PageHTMLHandler {
57 if ( $parsoid ) {
58 $this->resetServicesWithMockedParsoid( $parsoid );
59 } else {
60 // ParserOutputAccess has a localCache which can return stale content.
61 // Resetting ensures that ParsoidCachePrewarmJob gets a fresh copy
62 // of ParserOutputAccess without these problems!
63 $this->resetServices();
64 }
65
66 return $this->newPageHtmlHandler();
67 }
68
69 public function testExecuteWithHtml() {
70 $page = $this->getExistingTestPage( 'HtmlEndpointTestPage/with/slashes' );
71 $this->assertStatusGood( $this->editPage( $page, self::WIKITEXT ),
72 'Edited a page'
73 );
74
75 $request = new RequestData(
76 [ 'pathParams' => [ 'title' => $page->getTitle()->getPrefixedText() ] ]
77 );
78
79 $handler = $this->newHandler();
80 $data = $this->executeHandlerAndGetBodyData( $handler, $request, [
81 'format' => 'with_html'
82 ] );
83
84 $this->assertResponseData( $page, $data );
85 $this->assertStringContainsString( '<!DOCTYPE html>', $data['html'] );
86 $this->assertStringContainsString( '<html', $data['html'] );
87 $this->assertStringContainsString( self::HTML, $data['html'] );
88 }
89
90 public function testExecuteWillLint() {
91 $this->overrideConfigValue( MainConfigNames::ParsoidSettings, [
92 'linting' => true
93 ] );
94
95 $mockHandler = $this->createMock( ParserLogLinterDataHook::class );
96 $mockHandler->expects( $this->once() ) // this is the critical assertion in this test case!
97 ->method( 'onParserLogLinterData' );
98
99 $this->setTemporaryHook(
100 'ParserLogLinterData',
101 $mockHandler
102 );
103
104 $page = $this->getExistingTestPage( 'HtmlEndpointTestPage/with/slashes' );
105
106 $request = new RequestData(
107 [ 'pathParams' => [ 'title' => $page->getTitle()->getPrefixedText() ] ]
108 );
109
110 $handler = $this->newHandler();
111 $this->executeHandlerAndGetBodyData( $handler, $request, [
112 'format' => 'with_html'
113 ] );
114 }
115
116 public function testExecuteWithHtmlForSystemMessagePage() {
117 $title = Title::newFromText( 'MediaWiki:Logouttext' );
118 $page = $this->getNonexistingTestPage( $title );
119
120 $request = new RequestData(
121 [ 'pathParams' => [ 'title' => $page->getTitle()->getPrefixedText() ] ]
122 );
123
124 $handler = $this->newHandler();
125 $data = $this->executeHandlerAndGetBodyData( $handler, $request, [
126 'format' => 'with_html'
127 ] );
128
129 // Let's create and test on a full HTML document since system message pages
130 // will not return a full HTML document by default.
131 $data['html'] = ContentUtils::toXML( DOMUtils::parseHTML( $data['html'] ) );
132
133 $this->assertSame( $title->getPrefixedDBkey(), $data['key'] );
134 $this->assertSame( $title->getPrefixedText(), $data['title'] );
135 $this->assertStringContainsString( '<!DOCTYPE html>', $data['html'] );
136 $this->assertStringContainsString( '<html', $data['html'] );
137 $this->assertStringContainsString( '<meta http-equiv', $data['html'] );
138 $this->assertStringContainsString( 'content="en"', $data['html'] );
139
140 $msg = wfMessage( 'logouttext' )->inLanguage( 'en' )->useDatabase( false );
141 $this->assertStringContainsString( $msg->parse(), $data['html'] );
142 }
143
144 public function testExecuteHtmlOnly() {
145 $page = $this->getExistingTestPage( 'HtmlEndpointTestPage/with/slashes' );
146 $this->assertStatusGood( $this->editPage( $page, self::WIKITEXT ),
147 'Edited a page'
148 );
149
150 $request = new RequestData(
151 [ 'pathParams' => [ 'title' => $page->getTitle()->getPrefixedText() ] ]
152 );
153
154 $handler = $this->newHandler();
155 $response = $this->executeHandler( $handler, $request, [
156 'format' => 'html'
157 ] );
158
159 $htmlResponse = (string)$response->getBody();
160 $this->assertStringContainsString( '<!DOCTYPE html>', $htmlResponse );
161 $this->assertStringContainsString( '<html', $htmlResponse );
162 $this->assertStringContainsString( self::HTML, $htmlResponse );
163 }
164
165 public function testExecuteHtmlOnlyForSystemMessagePage() {
166 $title = Title::newFromText( 'MediaWiki:Logouttext/de' );
167 $page = $this->getNonexistingTestPage( $title );
168
169 $request = new RequestData(
170 [ 'pathParams' => [ 'title' => $page->getTitle()->getPrefixedText() ] ]
171 );
172
173 $handler = $this->newHandler();
174 $response = $this->executeHandler( $handler, $request, [
175 'format' => 'html'
176 ] );
177
178 $htmlResponse = (string)$response->getBody();
179 // Let's create and test on a full HTML document since system message pages
180 // will not return a full HTML document by default.
181 $htmlResponse = ContentUtils::toXML( DOMUtils::parseHTML( $htmlResponse ) );
182
183 $this->assertStringContainsString( '<!DOCTYPE html>', $htmlResponse );
184 $this->assertStringContainsString( '<html', $htmlResponse );
185 $this->assertStringContainsString( '<meta http-equiv', $htmlResponse );
186 $this->assertStringContainsString( 'content="de"', $htmlResponse );
187
188 $msg = wfMessage( 'logouttext' )->inLanguage( 'de' )->useDatabase( false );
189 $this->assertStringContainsString( $msg->parse(), $htmlResponse );
190 }
191
192 /**
193 * Assert that we return a 404 even if an associated remote file description
194 * page exists (T353688).
195 */
196 public function testRemoteDescriptionWithNonexistentFilePage() {
197 $name = 'JustSomeSillyFile.png';
198
199 $this->installMockFileRepo( $name );
200
201 $page = $this->getNonexistingTestPage( "File:$name" );
202
203 $request = new RequestData(
204 [ 'pathParams' => [ 'title' => $page->getTitle()->getPrefixedDBkey() ] ]
205 );
206 $handler = $this->newHandler();
207 $exception = $this->executeHandlerAndGetHttpException( $handler, $request, [
208 'format' => 'with_html'
209 ] );
210
211 $this->assertSame( 404, $exception->getCode() );
212 }
213
214 /**
215 * Assert that we return the local page content even if an associated remote
216 * file description page exists (T353688).
217 */
218 public function testRemoteDescriptionWithExistingFilePage() {
219 $name = 'JustSomeSillyFile.png';
220
221 $this->installMockFileRepo( $name );
222
223 $pageName = "File:$name";
224 $this->editPage( $pageName, 'Local content' );
225
226 $request = new RequestData(
227 [ 'pathParams' => [ 'title' => $pageName ] ]
228 );
229 $handler = $this->newHandler();
230 $data = $this->executeHandlerAndGetBodyData( $handler, $request, [
231 'format' => 'with_html'
232 ] );
233
234 $this->assertSame( $pageName, $data['key'] );
235 $this->assertSame( $pageName, $data['title'] );
236
237 $this->assertStringContainsString( '<html', $data['html'] );
238 $this->assertStringContainsString( 'Local content', $data['html'] );
239 }
240
241 /**
242 * @dataProvider provideExecuteWithVariant
243 */
244 public function testExecuteWithVariant(
245 string $format,
246 callable $bodyHtmlHandler,
247 string $expectedContentLanguage,
248 string $expectedVaryHeader
249 ) {
250 $this->overrideConfigValue( MainConfigNames::UsePigLatinVariant, true );
251 $page = $this->getExistingTestPage( 'HtmlVariantConversion' );
252 $this->assertStatusGood( $this->editPage( $page, '<p>test language conversion</p>' ),
253 'Edited a page'
254 );
255
256 $acceptLanguage = 'en-x-piglatin';
257 $request = new RequestData(
258 [
259 'pathParams' => [ 'title' => $page->getTitle()->getPrefixedText() ],
260 'headers' => [
261 'Accept-Language' => $acceptLanguage
262 ]
263 ]
264 );
265
266 $handler = $this->newHandler();
267 $response = $this->executeHandler( $handler, $request, [
268 'format' => $format
269 ] );
270
271 $htmlBody = $bodyHtmlHandler( $response->getBody() );
272 $contentLanguageHeader = $response->getHeaderLine( 'Content-Language' );
273 $varyHeader = $response->getHeaderLine( 'Vary' );
274
275 $this->assertStringContainsString( '>esttay anguagelay onversioncay<', $htmlBody );
276 $this->assertEquals( $expectedContentLanguage, $contentLanguageHeader );
277 $this->assertStringContainsStringIgnoringCase( $expectedVaryHeader, $varyHeader );
278 $this->assertStringContainsString( $acceptLanguage, $response->getHeaderLine( 'ETag' ) );
279 }
280
281 public static function provideExecuteWithVariant() {
282 yield 'with_html request should contain accept language but not content language' => [
283 'with_html',
284 static function ( StreamInterface $response ) {
285 return json_decode( $response->getContents(), true )['html'];
286 },
287 '',
288 'accept-language'
289 ];
290
291 yield 'html request should contain accept and content language' => [
292 'html',
293 static function ( StreamInterface $response ) {
294 return $response->getContents();
295 },
296 'en-x-piglatin',
297 'accept-language'
298 ];
299 }
300
301 public function testEtagLastModified() {
302 $time = time();
303 MWTimestamp::setFakeTime( $time );
304
305 $page = $this->getExistingTestPage( 'HtmlEndpointTestPage/with/slashes' );
306 $request = new RequestData(
307 [ 'pathParams' => [ 'title' => $page->getTitle()->getPrefixedText() ] ]
308 );
309
310 // First, test it works if nothing was cached yet.
311 // Make some time pass since page was created:
312 $time += 10;
313 MWTimestamp::setFakeTime( $time );
314 $handler = $this->newHandler();
315 $response = $this->executeHandler( $handler, $request, [
316 'format' => 'html'
317 ] );
318 $this->assertArrayHasKey( 'ETag', $response->getHeaders() );
319 $etag = $response->getHeaderLine( 'ETag' );
320 $this->assertStringMatchesFormat( '"' . $page->getLatest() . '/%x-%x-%x-%x-%x/%s"', $etag );
321 $this->assertArrayHasKey( 'Last-Modified', $response->getHeaders() );
322 $this->assertSame( MWTimestamp::convert( TS_RFC2822, $time ),
323 $response->getHeaderLine( 'Last-Modified' ) );
324
325 // Now, test that headers work when getting from cache too.
326 $handler = $this->newHandler();
327 $response = $this->executeHandler( $handler, $request, [
328 'format' => 'html'
329 ] );
330 $this->assertArrayHasKey( 'ETag', $response->getHeaders() );
331 $this->assertSame( $etag, $response->getHeaderLine( 'ETag' ) );
332 $etag = $response->getHeaderLine( 'ETag' );
333 $this->assertStringMatchesFormat( '"' . $page->getLatest() . '/%x-%x-%x-%x-%x/%s"', $etag );
334 $this->assertArrayHasKey( 'Last-Modified', $response->getHeaders() );
335 $this->assertSame( MWTimestamp::convert( TS_RFC2822, $time ),
336 $response->getHeaderLine( 'Last-Modified' ) );
337
338 // Now, expire the cache
339 $time += 1000;
340 MWTimestamp::setFakeTime( $time );
341 $this->assertTrue(
342 $page->getTitle()->invalidateCache( MWTimestamp::convert( TS_MW, $time ) ),
343 'Can invalidate cache'
344 );
345 DeferredUpdates::doUpdates();
346
347 $handler = $this->newHandler();
348 $response = $this->executeHandler( $handler, $request, [
349 'format' => 'html'
350 ] );
351 $this->assertArrayHasKey( 'ETag', $response->getHeaders() );
352 $this->assertNotSame( $etag, $response->getHeaderLine( 'ETag' ) );
353 $etag = $response->getHeaderLine( 'ETag' );
354 $this->assertStringMatchesFormat( '"' . $page->getLatest() . '/%x-%x-%x-%x-%x/%s"', $etag );
355 $this->assertArrayHasKey( 'Last-Modified', $response->getHeaders() );
356 $this->assertSame( MWTimestamp::convert( TS_RFC2822, $time ),
357 $response->getHeaderLine( 'Last-Modified' ) );
358 }
359
360 public static function provideHandlesParsoidError() {
361 yield 'ClientError' => [
362 new ClientError( 'TEST_TEST' ),
363 new LocalizedHttpException(
364 new MessageValue( 'rest-html-backend-error' ),
365 400,
366 [
367 'reason' => 'TEST_TEST'
368 ]
369 )
370 ];
371 yield 'ResourceLimitExceededException' => [
372 new ResourceLimitExceededException( 'TEST_TEST' ),
373 new LocalizedHttpException(
374 new MessageValue( 'rest-resource-limit-exceeded' ),
375 413,
376 [
377 'reason' => 'TEST_TEST'
378 ]
379 )
380 ];
381 }
382
383 /**
384 * @dataProvider provideHandlesParsoidError
385 */
386 public function testHandlesParsoidError(
387 Exception $parsoidException,
388 Exception $expectedException
389 ) {
390 $page = $this->getExistingTestPage( 'HtmlEndpointTestPage/with/slashes' );
391 $request = new RequestData(
392 [ 'pathParams' => [ 'title' => $page->getTitle()->getPrefixedText() ] ]
393 );
394
395 $parsoid = $this->createNoOpMock( Parsoid::class, [ 'wikitext2html' ] );
396 $parsoid->expects( $this->once() )
397 ->method( 'wikitext2html' )
398 ->willThrowException( $parsoidException );
399
400 $handler = $this->newHandler( $parsoid );
401 $this->expectExceptionObject( $expectedException );
402 $this->executeHandler( $handler, $request, [
403 'format' => 'html'
404 ] );
405 }
406
407 public function testExecute_missingparam() {
408 $request = new RequestData();
409
410 $this->expectExceptionObject(
411 new LocalizedHttpException(
412 new MessageValue( "paramvalidator-missingparam", [ 'title' ] ),
413 400
414 )
415 );
416
417 $handler = $this->newHandler();
418 $this->executeHandler( $handler, $request );
419 }
420
421 public function testExecute_error() {
422 $request = new RequestData( [ 'pathParams' => [ 'title' => 'DoesNotExist8237456assda1234' ] ] );
423
424 $this->expectExceptionObject(
425 new LocalizedHttpException(
426 new MessageValue( "rest-nonexistent-title", [ 'testing' ] ),
427 404
428 )
429 );
430
431 $handler = $this->newHandler();
432 $this->executeHandler( $handler, $request, [ 'format' => 'html' ] );
433 }
434
435 /**
436 * @param WikiPage $page
437 * @param array $data
438 */
439 private function assertResponseData( WikiPage $page, array $data ): void {
440 $this->assertSame( $page->getId(), $data['id'] );
441 $this->assertSame( $page->getTitle()->getPrefixedDBkey(), $data['key'] );
442 $this->assertSame( $page->getTitle()->getPrefixedText(), $data['title'] );
443 $this->assertSame( $page->getLatest(), $data['latest']['id'] );
444 $this->assertSame(
445 wfTimestampOrNull( TS_ISO_8601, $page->getTimestamp() ),
446 $data['latest']['timestamp']
447 );
448 $this->assertSame( CONTENT_MODEL_WIKITEXT, $data['content_model'] );
449 $this->assertSame( 'https://example.com/rights', $data['license']['url'] );
450 $this->assertSame( 'some rights', $data['license']['title'] );
451 }
452
453 /**
454 * Request One:
455 *
456 * When a request is made with no stash entries in the stash and stashing
457 * is set to false, don't stash anything. At this point, the stash is empty.
458 *
459 * Request Two:
460 *
461 * Once a request is made with stashing option set to true, we should have
462 * one entry in parsoid stash. So at this point, the stash is no longer empty
463 * as before.
464 *
465 * Request Three:
466 *
467 * Upon the third request, there is already a stash entry and if the 3rd request's
468 * stashing option is set to false, we're not invalidating the stash entries that
469 * exiting with the UUID. So, if we request a parsoid stashed object from the stash
470 * with a given UUID that exist, we should have a hit.
471 */
472 public function testExecuteStashParsoidOutput() {
473 $page = $this->getExistingTestPage();
474 $outputStash = $this->getParsoidOutputStash();
475
476 [ /* $html1 */, $etag1, $stashKey1 ] = $this->executePageHTMLRequest( $page );
477 $this->assertNull( $outputStash->get( $stashKey1 ) );
478
479 [ /* $html2 */, $etag2, $stashKey2 ] = $this->executePageHTMLRequest( $page, [ 'stash' => true ] );
480 $this->assertNotNull( $outputStash->get( $stashKey2 ) );
481
482 [ /* $html3 */, $etag3, $stashKey3 ] = $this->executePageHTMLRequest( $page );
483 /**
484 * The stash for the previous request should still live at this point.
485 */
486 $this->assertNotNull( $outputStash->get( $stashKey2 ) );
487 $this->assertNotNull( $outputStash->get( $stashKey3 ) );
488 $this->assertSame( $etag1, $etag3 );
489 $this->assertNotSame( $etag1, $etag2 );
490
491 // Make sure the output for stashed and unstashed doesn't have the same tag,
492 // since it will actually be different!
493 // FIXME: implement flavors and write test cases for them.
494 }
495
496 public function testETagVariesOnFormat() {
497 $page = $this->getExistingTestPage();
498
499 [ /* $html1 */, $etag1 ] =
500 $this->executePageHTMLRequest( $page, [], [ 'format' => 'html' ] );
501
502 [ /* $html2 */, $etag2 ] =
503 $this->executePageHTMLRequest( $page, [], [ 'format' => 'with_html' ] );
504
505 $this->assertNotSame( $etag1, $etag2 );
506 }
507
508 public function testStashingWithRateLimitExceeded() {
509 // Set the rate limit to 1 request per minute
510 $this->overrideConfigValue(
511 MainConfigNames::RateLimits, [
512 'stashbasehtml' => [
513 '&can-bypass' => false,
514 'ip' => [ 1, 60 ],
515 'newbie' => [ 1, 60 ]
516 ]
517 ]
518 );
519
520 $page = $this->getExistingTestPage();
521 $authority = $this->getAuthority();
522
523 $this->executePageHTMLRequest( $page, [ 'stash' => true ], [], $authority );
524 // In this request, the rate limit has been exceeded, so it should throw.
525 $this->expectException( LocalizedHttpException::class );
526 $this->expectExceptionCode( 429 );
527 $this->executePageHTMLRequest( $page, [ 'stash' => true ], [], $authority );
528 }
529
530 }