Debian Codegraph @

tests/phpunit/includes/page/ParserOutputAccessTest.php

raw symbols SCIP
1 <?php
2
3 use MediaWiki\Content\WikitextContent;
4 use MediaWiki\Json\JsonCodec;
5 use MediaWiki\Logger\LoggerFactory;
6 use MediaWiki\Logger\Spi as LoggerSpi;
7 use MediaWiki\MainConfigNames;
8 use MediaWiki\MediaWikiServices;
9 use MediaWiki\Page\Hook\OpportunisticLinksUpdateHook;
10 use MediaWiki\Page\PageRecord;
11 use MediaWiki\Page\ParserOutputAccess;
12 use MediaWiki\Page\WikiPageFactory;
13 use MediaWiki\Parser\ParserCache;
14 use MediaWiki\Parser\ParserCacheFactory;
15 use MediaWiki\Parser\ParserOptions;
16 use MediaWiki\Parser\ParserOutput;
17 use MediaWiki\Parser\RevisionOutputCache;
18 use MediaWiki\PoolCounter\PoolCounter;
19 use MediaWiki\PoolCounter\PoolCounterWork;
20 use MediaWiki\Revision\MutableRevisionRecord;
21 use MediaWiki\Revision\RevisionLookup;
22 use MediaWiki\Revision\RevisionRecord;
23 use MediaWiki\Revision\RevisionRenderer;
24 use MediaWiki\Revision\RevisionStore;
25 use MediaWiki\Revision\SlotRecord;
26 use MediaWiki\Status\Status;
27 use MediaWiki\Title\TitleFormatter;
28 use MediaWiki\Utils\MWTimestamp;
29 use Psr\Log\NullLogger;
30 use Wikimedia\ObjectCache\EmptyBagOStuff;
31 use Wikimedia\ObjectCache\HashBagOStuff;
32 use Wikimedia\ObjectCache\WANObjectCache;
33 use Wikimedia\Rdbms\ChronologyProtector;
34 use Wikimedia\Rdbms\ILBFactory;
35 use Wikimedia\Stats\StatsFactory;
36 use Wikimedia\TestingAccessWrapper;
37
38 /**
39 * @covers \MediaWiki\Page\ParserOutputAccess
40 * @group Database
41 */
42 class ParserOutputAccessTest extends MediaWikiIntegrationTestCase {
43
44 public int $actualCallsToPoolWorkArticleView = 0;
45 public int $expectedCallsToPoolWorkArticleView = 0;
46
47 public function tearDown(): void {
48 $this->assertSame(
49 $this->expectedCallsToPoolWorkArticleView,
50 $this->actualCallsToPoolWorkArticleView,
51 'Calls to newPoolWorkArticleView'
52 );
53
54 parent::tearDown();
55 }
56
57 private function getHtml( $value ) {
58 if ( $value instanceof StatusValue ) {
59 $value = $value->getValue();
60 }
61
62 if ( $value instanceof ParserOutput ) {
63 $pipeline = MediaWikiServices::getInstance()->getDefaultOutputPipeline();
64 $value = $pipeline->run( $value, $this->getParserOptions(), [] )->getContentHolderText();
65 }
66
67 $html = preg_replace( '/<!--.*?-->/s', '', $value );
68 $html = trim( preg_replace( '/[\r\n]{2,}/', "\n", $html ) );
69 $html = trim( preg_replace( '/\s{2,}/', ' ', $html ) );
70 return $html;
71 }
72
73 private function assertContainsHtml( $needle, $actual, $msg = '' ) {
74 $this->assertNotNull( $actual );
75
76 if ( $actual instanceof StatusValue ) {
77 $this->assertStatusOK( $actual, 'isOK' );
78 }
79
80 $this->assertStringContainsString( $needle, $this->getHtml( $actual ), $msg );
81 }
82
83 private function assertSameHtml( $expected, $actual, $msg = '' ) {
84 $this->assertNotNull( $actual );
85
86 if ( $actual instanceof StatusValue ) {
87 $this->assertStatusOK( $actual, 'isOK' );
88 }
89
90 $this->assertSame( $this->getHtml( $expected ), $this->getHtml( $actual ), $msg );
91 }
92
93 private function assertNotSameHtml( $expected, $actual, $msg = '' ) {
94 $this->assertNotNull( $actual );
95
96 if ( $actual instanceof StatusValue ) {
97 $this->assertStatusOK( $actual, 'isOK' );
98 }
99
100 $this->assertNotSame( $this->getHtml( $expected ), $this->getHtml( $actual ), $msg );
101 }
102
103 private function getParserCache( $bag = null ) {
104 $parserCache = new ParserCache(
105 'test',
106 $bag ?: new HashBagOStuff(),
107 '19900220000000',
108 $this->getServiceContainer()->getHookContainer(),
109 new JsonCodec( $this->getServiceContainer() ),
110 StatsFactory::newNull(),
111 new NullLogger(),
112 $this->getServiceContainer()->getTitleFactory(),
113 $this->getServiceContainer()->getWikiPageFactory(),
114 $this->getServiceContainer()->getGlobalIdGenerator()
115 );
116
117 return $parserCache;
118 }
119
120 private function getRevisionOutputCache( $bag = null, $expiry = 3600 ) {
121 $wanCache = new WANObjectCache( [ 'cache' => $bag ?: new HashBagOStuff() ] );
122 $revisionOutputCache = new RevisionOutputCache(
123 'test',
124 $wanCache,
125 $expiry,
126 '19900220000000',
127 new JsonCodec( $this->getServiceContainer() ),
128 StatsFactory::newNull(),
129 new NullLogger(),
130 $this->getServiceContainer()->getGlobalIdGenerator()
131 );
132
133 return $revisionOutputCache;
134 }
135
136 /**
137 * @param ParserCache|null $parserCache
138 * @param RevisionOutputCache|null $revisionOutputCache
139 * @param int|bool $maxRenderCalls
140 *
141 * @return ParserOutputAccess
142 * @throws Exception
143 */
144 private function getParserOutputAccessWithCache(
145 $parserCache = null,
146 $revisionOutputCache = null,
147 $maxRenderCalls = false
148 ): ParserOutputAccess {
149 return $this->getParserOutputAccess( [
150 'parserCache' => $parserCache ?? new HashBagOStuff(),
151 'revisionOutputCache' => $revisionOutputCache ?? new HashBagOStuff(),
152 'maxRenderCalls' => $maxRenderCalls
153 ] );
154 }
155
156 /**
157 * @param array $options
158 *
159 * @return ParserOutputAccess
160 * @throws Exception
161 */
162 private function getParserOutputAccess( array $options = [] ): ParserOutputAccess {
163 $parserCacheFactory = $options['parserCacheFactory'] ?? null;
164 $maxRenderCalls = $options['maxRenderCalls'] ?? null;
165 $parserCache = $options['parserCache'] ?? null;
166 $revisionOutputCache = $options['revisionOutputCache'] ?? null;
167 $expectPoolCounterCalls = $options['expectPoolCounterCalls'] ?? 0;
168
169 if ( !$parserCacheFactory ) {
170 if ( !$parserCache instanceof ParserCache ) {
171 $parserCache = $this->getParserCache(
172 $parserCache ?? new EmptyBagOStuff()
173 );
174 }
175
176 if ( !$revisionOutputCache instanceof RevisionOutputCache ) {
177 $revisionOutputCache = $this->getRevisionOutputCache(
178 $revisionOutputCache ?? new EmptyBagOStuff()
179 );
180 }
181
182 $parserCacheFactory = $this->createMock( ParserCacheFactory::class );
183
184 $parserCacheFactory->method( 'getParserCache' )
185 ->willReturn( $parserCache );
186
187 $parserCacheFactory->method( 'getRevisionOutputCache' )
188 ->willReturn( $revisionOutputCache );
189 }
190
191 $revRenderer = $this->getServiceContainer()->getRevisionRenderer();
192 if ( $maxRenderCalls ) {
193 $realRevRenderer = $revRenderer;
194
195 $revRenderer =
196 $this->createNoOpMock( RevisionRenderer::class, [ 'getRenderedRevision' ] );
197
198 $revRenderer->expects( $this->atMost( $maxRenderCalls ) )
199 ->method( 'getRenderedRevision' )
200 ->willReturnCallback( [ $realRevRenderer, 'getRenderedRevision' ] );
201 }
202
203 $mock = new class (
204 $parserCacheFactory,
205 $this->getServiceContainer()->getRevisionLookup(),
206 $revRenderer,
207 $this->getServiceContainer()->getStatsFactory(),
208 $this->getServiceContainer()->getDBLoadBalancerFactory(),
209 $this->getServiceContainer()->getChronologyProtector(),
210 LoggerFactory::getProvider(),
211 $this->getServiceContainer()->getWikiPageFactory(),
212 $this->getServiceContainer()->getTitleFormatter(),
213 $this
214 ) extends ParserOutputAccess {
215 private ParserOutputAccessTest $test;
216
217 public function __construct(
218 ParserCacheFactory $parserCacheFactory,
219 RevisionLookup $revisionLookup,
220 RevisionRenderer $revisionRenderer,
221 StatsFactory $statsFactory,
222 ILBFactory $lbFactory,
223 ChronologyProtector $chronologyProtector,
224 LoggerSpi $loggerSpi,
225 WikiPageFactory $wikiPageFactory,
226 TitleFormatter $titleFormatter,
227 ParserOutputAccessTest $test
228 ) {
229 parent::__construct(
230 $parserCacheFactory,
231 $revisionLookup,
232 $revisionRenderer,
233 $statsFactory,
234 $lbFactory,
235 $chronologyProtector,
236 $loggerSpi,
237 $wikiPageFactory,
238 $titleFormatter
239 );
240
241 $this->test = $test;
242 }
243
244 protected function newPoolWorkArticleView(
245 PageRecord $page,
246 ParserOptions $parserOptions,
247 RevisionRecord $revision,
248 int $options
249 ): PoolCounterWork {
250 $this->test->actualCallsToPoolWorkArticleView++;
251 return parent::newPoolWorkArticleView( $page, $parserOptions, $revision, $options );
252 }
253 };
254
255 $this->expectedCallsToPoolWorkArticleView += $expectPoolCounterCalls;
256
257 return $mock;
258 }
259
260 /**
261 * @param WikiPage $page
262 * @param string $text
263 *
264 * @return RevisionRecord
265 */
266 private function makeFakeRevision( WikiPage $page, $text ) {
267 // construct fake revision with no ID
268 $content = new WikitextContent( $text );
269 $rev = new MutableRevisionRecord( $page->getTitle() );
270 $rev->setPageId( $page->getId() );
271 $rev->setContent( SlotRecord::MAIN, $content );
272
273 return $rev;
274 }
275
276 /**
277 * @return ParserOptions
278 */
279 private function getParserOptions() {
280 return ParserOptions::newFromAnon();
281 }
282
283 /**
284 * Install OpportunisticLinksUpdateHook to inspect whether WikiPage::triggerOpportunisticLinksUpdate
285 * is called or not, the hook implementation will return false disabling the
286 * WikiPage::triggerOpportunisticLinksUpdate to proceed completely.
287 * @param bool $called whether WikiPage::triggerOpportunisticLinksUpdate is expected to be called or not
288 * @return void
289 */
290 private function installOpportunisticUpdateHook( bool $called ): void {
291 $opportunisticUpdateHook =
292 $this->createMock( OpportunisticLinksUpdateHook::class );
293 // WikiPage::triggerOpportunisticLinksUpdate is not called by default
294 $opportunisticUpdateHook->expects( $this->exactly( $called ? 1 : 0 ) )
295 ->method( 'onOpportunisticLinksUpdate' )
296 ->willReturn( false );
297 $this->setTemporaryHook( 'OpportunisticLinksUpdate', $opportunisticUpdateHook );
298 }
299
300 /**
301 * Tests that we can get rendered output for the latest revision.
302 */
303 public function testOutputForLatestRevision() {
304 $access = $this->getParserOutputAccess( [
305 'parserCache' => new HashBagOStuff()
306 ] );
307
308 $page = $this->getNonexistingTestPage( __METHOD__ );
309 $this->editPage( $page, 'Hello \'\'World\'\'!' );
310
311 $parserOptions = $this->getParserOptions();
312 // WikiPage::triggerOpportunisticLinksUpdate is not called by default
313 $this->installOpportunisticUpdateHook( false );
314 $status = $access->getParserOutput( $page, $parserOptions );
315 $this->assertContainsHtml( 'Hello <i>World</i>!', $status );
316
317 $this->assertNotNull( $access->getCachedParserOutput( $page, $parserOptions ) );
318 }
319
320 /**
321 * Tests that we can get rendered output for the latest revision.
322 */
323 public function testOutputForLatestRevisionUsingPoolCounter() {
324 $access = $this->getParserOutputAccess( [
325 'expectPoolCounterCalls' => 1
326 ] );
327
328 $page = $this->getNonexistingTestPage( __METHOD__ );
329 $this->editPage( $page, 'Hello \'\'World\'\'!' );
330
331 $parserOptions = $this->getParserOptions();
332
333 // WikiPage::triggerOpportunisticLinksUpdate is not called by default
334 $this->installOpportunisticUpdateHook( false );
335
336 $status = $access->getParserOutput(
337 $page,
338 $parserOptions,
339 null,
340 ParserOutputAccess::OPT_FOR_ARTICLE_VIEW
341 );
342 $this->assertContainsHtml( 'Hello <i>World</i>!', $status );
343 }
344
345 /**
346 * Tests that we can get rendered output for the latest revision.
347 */
348 public function testOutputForLatestRevisionWithLinksUpdate() {
349 $access = $this->getParserOutputAccess();
350
351 $page = $this->getNonexistingTestPage( __METHOD__ );
352 $this->editPage( $page, 'Hello \'\'World\'\'!' );
353
354 $parserOptions = $this->getParserOptions();
355 // With ParserOutputAccess::OPT_LINKS_UPDATE WikiPage::triggerOpportunisticLinksUpdate can be called
356 $this->installOpportunisticUpdateHook( true );
357 $status = $access->getParserOutput( $page, $parserOptions, null, ParserOutputAccess::OPT_LINKS_UPDATE );
358 $this->assertContainsHtml( 'Hello <i>World</i>!', $status );
359 }
360
361 /**
362 * Tests that we can get rendered output for the latest revision.
363 */
364 public function testOutputForLatestRevisionWithLinksUpdateWithPoolCounter() {
365 $access = $this->getParserOutputAccess( [
366 'expectPoolCounterCalls' => 1
367 ] );
368
369 $page = $this->getNonexistingTestPage( __METHOD__ );
370 $this->editPage( $page, 'Hello \'\'World\'\'!' );
371
372 $parserOptions = $this->getParserOptions();
373 // With ParserOutputAccess::OPT_LINKS_UPDATE WikiPage::triggerOpportunisticLinksUpdate can be called
374 $this->installOpportunisticUpdateHook( true );
375
376 $status = $access->getParserOutput(
377 $page,
378 $parserOptions,
379 null,
380 ParserOutputAccess::OPT_LINKS_UPDATE | ParserOutputAccess::OPT_FOR_ARTICLE_VIEW
381 );
382 $this->assertContainsHtml( 'Hello <i>World</i>!', $status );
383 }
384
385 /**
386 * Tests that cached output in the ParserCache will be used for the latest revision.
387 */
388 public function testLatestRevisionUseCached() {
389 // Allow only one render call, use default caches
390 $access = $this->getParserOutputAccessWithCache( null, null, 1 );
391
392 $parserOptions = $this->getParserOptions();
393 $page = $this->getNonexistingTestPage( __METHOD__ );
394 $this->editPage( $page, 'Hello \'\'World\'\'!' );
395
396 $access->getParserOutput( $page, $parserOptions );
397
398 // The second call should use cached output
399 $status = $access->getParserOutput( $page, $parserOptions );
400 $this->assertContainsHtml( 'Hello <i>World</i>!', $status );
401 }
402
403 /**
404 * Tests that cached output in the ParserCache will not be used
405 * for the latest revision if the FORCE_PARSE option is given.
406 */
407 public function testLatestRevisionForceParse() {
408 $parserCache = $this->getParserCache( new HashBagOStuff() );
409 $access = $this->getParserOutputAccessWithCache( $parserCache );
410
411 $parserOptions = ParserOptions::newFromAnon();
412 $page = $this->getNonexistingTestPage( __METHOD__ );
413 $this->editPage( $page, 'Hello \'\'World\'\'!' );
414
415 // Put something else into the cache, so we'd notice if it got used
416 $cachedOutput = new ParserOutput( 'Cached Text' );
417 $parserCache->save( $cachedOutput, $page, $parserOptions );
418
419 $status = $access->getParserOutput(
420 $page,
421 $parserOptions,
422 null,
423 ParserOutputAccess::OPT_FORCE_PARSE
424 );
425 $this->assertNotSameHtml( $cachedOutput, $status );
426 $this->assertContainsHtml( 'Hello <i>World</i>!', $status );
427 }
428
429 /**
430 * Tests that an error is reported if the latest revision cannot be loaded.
431 */
432 public function testLatestRevisionCantLoad() {
433 $page = $this->getNonexistingTestPage( __METHOD__ );
434 $this->editPage( $page, 'Hello \'\'World\'\'!' );
435
436 $revisionStore = $this->createNoOpMock(
437 RevisionStore::class,
438 [ 'getRevisionByTitle', 'getKnownCurrentRevision', 'getRevisionById' ]
439 );
440 $revisionStore->method( 'getRevisionById' )->willReturn( null );
441 $revisionStore->method( 'getRevisionByTitle' )->willReturn( null );
442 $revisionStore->method( 'getKnownCurrentRevision' )->willReturn( false );
443 $this->setService( 'RevisionStore', $revisionStore );
444 $this->setService( 'RevisionLookup', $revisionStore );
445
446 $page->clear();
447
448 $access = $this->getParserOutputAccess();
449
450 $parserOptions = $this->getParserOptions();
451 $status = $access->getParserOutput( $page, $parserOptions );
452 $this->assertStatusError( 'missing-revision', $status );
453 }
454
455 /**
456 * Tests that getCachedParserOutput() will return previously generated output.
457 */
458 public function testGetCachedParserOutput() {
459 $access = $this->getParserOutputAccessWithCache();
460 $parserOptions = $this->getParserOptions();
461
462 $page = $this->getNonexistingTestPage( __METHOD__ );
463
464 $output = $access->getCachedParserOutput( $page, $parserOptions );
465 $this->assertNull( $output );
466
467 $this->editPage( $page, 'Hello \'\'World\'\'!' );
468 $access->getParserOutput( $page, $parserOptions );
469
470 $output = $access->getCachedParserOutput( $page, $parserOptions );
471 $this->assertNotNull( $output );
472 $this->assertContainsHtml( 'Hello <i>World</i>!', $output );
473 }
474
475 /**
476 * Tests that getCachedParserOutput() will not return output for current revision when
477 * a fake revision with no ID is supplied.
478 */
479 public function testGetCachedParserOutputForFakeRevision() {
480 $access = $this->getParserOutputAccessWithCache();
481
482 $page = $this->getNonexistingTestPage( __METHOD__ );
483 $this->editPage( $page, 'Hello \'\'World\'\'!' );
484
485 $parserOptions = $this->getParserOptions();
486 $access->getParserOutput( $page, $parserOptions );
487
488 $rev = $this->makeFakeRevision( $page, 'fake text' );
489
490 $output = $access->getCachedParserOutput( $page, $parserOptions, $rev );
491 $this->assertNull( $output );
492 }
493
494 /**
495 * Tests that getPageOutput() will place the generated output for the latest revision
496 * in the parser cache.
497 */
498 public function testLatestRevisionIsCached() {
499 $access = $this->getParserOutputAccessWithCache();
500
501 $page = $this->getNonexistingTestPage( __METHOD__ );
502 $this->editPage( $page, 'Hello \'\'World\'\'!' );
503
504 $parserOptions = $this->getParserOptions();
505 $access->getParserOutput( $page, $parserOptions );
506
507 $cachedOutput = $access->getCachedParserOutput( $page, $parserOptions );
508 $this->assertContainsHtml( 'World', $cachedOutput );
509 }
510
511 /**
512 * Tests that the cache for the current revision is split on parser options.
513 */
514 public function testLatestRevisionCacheSplit() {
515 $access = $this->getParserOutputAccessWithCache();
516
517 $frenchOptions = ParserOptions::newFromAnon();
518 $frenchOptions->setUserLang( 'fr' );
519
520 $tongaOptions = ParserOptions::newFromAnon();
521 $tongaOptions->setUserLang( 'to' );
522
523 $page = $this->getNonexistingTestPage( __METHOD__ );
524 $this->editPage( $page, 'Test {{int:ok}}!' );
525
526 $frenchResult = $access->getParserOutput( $page, $frenchOptions );
527 $this->assertContainsHtml( 'Test', $frenchResult );
528
529 // Check that French output was cached
530 $cachedFrenchOutput =
531 $access->getCachedParserOutput( $page, $frenchOptions );
532 $this->assertNotNull( $cachedFrenchOutput, 'French output should be in the cache' );
533
534 // check that we don't get the French output when asking for Tonga
535 $cachedTongaOutput =
536 $access->getCachedParserOutput( $page, $tongaOptions );
537 $this->assertNull( $cachedTongaOutput, 'Tonga output should not be in the cache yet' );
538
539 // check that we can generate the Tonga output, and it's different from French
540 $tongaResult = $access->getParserOutput( $page, $tongaOptions );
541 $this->assertContainsHtml( 'Test', $tongaResult );
542 $this->assertNotSameHtml(
543 $frenchResult,
544 $tongaResult,
545 'Tonga output should be different from French'
546 );
547
548 // check that the Tonga output is cached
549 $cachedTongaOutput =
550 $access->getCachedParserOutput( $page, $tongaOptions );
551 $this->assertNotNull( $cachedTongaOutput, 'Tonga output should be in the cache' );
552 }
553
554 /**
555 * Tests that getPageOutput() will place the generated output in the parser cache if the
556 * latest revision is passed explicitly. In other words, thins ensures that the current
557 * revision won't get treated like an old revision.
558 */
559 public function testLatestRevisionIsDetectedAndCached() {
560 $access = $this->getParserOutputAccessWithCache();
561
562 $page = $this->getNonexistingTestPage( __METHOD__ );
563 $rev = $this->editPage( $page, 'Hello \'\'World\'\'!' )->getNewRevision();
564
565 // When $rev is passed, it should be detected to be the latest revision.
566 $parserOptions = $this->getParserOptions();
567 $access->getParserOutput( $page, $parserOptions, $rev );
568
569 $cachedOutput = $access->getCachedParserOutput( $page, $parserOptions );
570 $this->assertContainsHtml( 'World', $cachedOutput );
571 }
572
573 /**
574 * Tests that getPageOutput() will generate output for an old revision, and
575 * that we still have the output for the current revision cached afterwards.
576 */
577 public function testOutputForOldRevision() {
578 $access = $this->getParserOutputAccessWithCache();
579
580 $page = $this->getNonexistingTestPage( __METHOD__ );
581 $firstRev = $this->editPage( $page, 'First' )->getNewRevision();
582 $secondRev = $this->editPage( $page, 'Second' )->getNewRevision();
583
584 // output is for the second revision (write to ParserCache)
585 $parserOptions = $this->getParserOptions();
586 $status = $access->getParserOutput( $page, $parserOptions );
587 $this->assertContainsHtml( 'Second', $status );
588
589 // output is for the first revision (not written to ParserCache)
590 $status = $access->getParserOutput( $page, $parserOptions, $firstRev );
591 $this->assertContainsHtml( 'First', $status );
592
593 // Latest revision is still the one in the ParserCache
594 $output = $access->getCachedParserOutput( $page, $parserOptions );
595 $this->assertContainsHtml( 'Second', $output );
596 }
597
598 /**
599 * Tests that getPageOutput() will generate output for an old revision, and
600 * that we still have the output for the current revision cached afterwards.
601 */
602 public function testOutputForOldRevisionUsingPoolCounter() {
603 $access = $this->getParserOutputAccess( [
604 'expectPoolCounterCalls' => 2,
605 'parserCache' => new HashBagOStuff(),
606 'revisionOutputCache' => new HashBagOStuff()
607 ] );
608
609 $page = $this->getNonexistingTestPage( __METHOD__ );
610 $firstRev = $this->editPage( $page, 'First' )->getNewRevision();
611 $secondRev = $this->editPage( $page, 'Second' )->getNewRevision();
612
613 // output is for the second revision (write to ParserCache)
614 $parserOptions = $this->getParserOptions();
615 $status = $access->getParserOutput(
616 $page,
617 $parserOptions,
618 null,
619 ParserOutputAccess::OPT_FOR_ARTICLE_VIEW
620 );
621 $this->assertContainsHtml( 'Second', $status );
622
623 // output is for the first revision (not written to ParserCache)
624 $status = $access->getParserOutput(
625 $page,
626 $parserOptions,
627 $firstRev,
628 ParserOutputAccess::OPT_FOR_ARTICLE_VIEW
629 );
630 $this->assertContainsHtml( 'First', $status );
631
632 // Latest revision is still the one in the ParserCache
633 $output = $access->getCachedParserOutput( $page, $parserOptions );
634 $this->assertContainsHtml( 'Second', $output );
635 }
636
637 /**
638 * Tests that trying to get output for a suppressed old revision is denied.
639 */
640 public function testOldRevisionSuppressedDenied() {
641 $access = $this->getParserOutputAccess();
642
643 $page = $this->getNonexistingTestPage( __METHOD__ );
644 $firstRev = $this->editPage( $page, 'First' )->getNewRevision();
645 $secondRev = $this->editPage( $page, 'Second' )->getNewRevision();
646
647 $this->revisionDelete( $firstRev );
648 $firstRev =
649 $this->getServiceContainer()->getRevisionStore()->getRevisionById( $firstRev->getId() );
650
651 // output is for the first revision denied
652 $parserOptions = $this->getParserOptions();
653 $status = $access->getParserOutput( $page, $parserOptions, $firstRev );
654 $this->assertStatusError( 'missing-revision-permission', $status );
655 // TODO: Once PoolWorkArticleView properly reports errors, check that the correct error
656 // is propagated.
657 }
658
659 /**
660 * Tests that getting output for a suppressed old revision is possible when NO_AUDIENCE_CHECK
661 * is set.
662 */
663 public function testOldRevisionSuppressedAllowed() {
664 $access = $this->getParserOutputAccess();
665
666 $page = $this->getNonexistingTestPage( __METHOD__ );
667 $firstRev = $this->editPage( $page, 'First' )->getNewRevision();
668 $secondRev = $this->editPage( $page, 'Second' )->getNewRevision();
669
670 $this->revisionDelete( $firstRev );
671 $firstRev =
672 $this->getServiceContainer()->getRevisionStore()->getRevisionById( $firstRev->getId() );
673
674 // output is for the first revision (even though it's suppressed)
675 $parserOptions = $this->getParserOptions();
676 $status = $access->getParserOutput(
677 $page,
678 $parserOptions,
679 $firstRev,
680 ParserOutputAccess::OPT_NO_AUDIENCE_CHECK
681 );
682 $this->assertContainsHtml( 'First', $status );
683
684 // even though the output was generated, it wasn't cached, since it's not public
685 $cachedOutput = $access->getCachedParserOutput( $page, $parserOptions, $firstRev );
686 $this->assertNull( $cachedOutput );
687 }
688
689 /**
690 * Tests that output for an old revision is fetched from the secondary parser cache if possible.
691 */
692 public function testOldRevisionUseCached() {
693 // Allow only one render call, use default caches
694 $access = $this->getParserOutputAccessWithCache( null, null, 1 );
695
696 $parserOptions = $this->getParserOptions();
697 $page = $this->getNonexistingTestPage( __METHOD__ );
698 $this->editPage( $page, 'First' );
699 $oldRev = $page->getRevisionRecord();
700
701 $this->editPage( $page, 'Second' );
702
703 $firstStatus = $access->getParserOutput( $page, $parserOptions, $oldRev );
704
705 // The second call should use cached output
706 $secondStatus = $access->getParserOutput( $page, $parserOptions, $oldRev );
707 $this->assertSameHtml( $firstStatus, $secondStatus );
708 }
709
710 /**
711 * Tests that output for an old revision is fetched from the secondary parser cache if possible.
712 */
713 public function testOldRevisionDisableCached() {
714 // Use default caches, but expiry 0 for the secondary cache
715 $access = $this->getParserOutputAccessWithCache(
716 null,
717 $this->getRevisionOutputCache( null, 0 )
718 );
719
720 $parserOptions = $this->getParserOptions();
721 $page = $this->getNonexistingTestPage( __METHOD__ );
722 $this->editPage( $page, 'First' );
723 $oldRev = $page->getRevisionRecord();
724
725 $this->editPage( $page, 'Second' );
726 $access->getParserOutput( $page, $parserOptions, $oldRev );
727
728 // Should not be cached!
729 $cachedOutput = $access->getCachedParserOutput( $page, $parserOptions, $oldRev );
730 $this->assertNull( $cachedOutput );
731 }
732
733 /**
734 * Tests that the secondary cache for output for old revisions is split on parser options.
735 */
736 public function testOldRevisionCacheSplit() {
737 $access = $this->getParserOutputAccessWithCache();
738
739 $frenchOptions = ParserOptions::newFromAnon();
740 $frenchOptions->setUserLang( 'fr' );
741
742 $tongaOptions = ParserOptions::newFromAnon();
743 $tongaOptions->setUserLang( 'to' );
744
745 $page = $this->getNonexistingTestPage( __METHOD__ );
746 $this->editPage( $page, 'Test {{int:ok}}!' );
747 $oldRev = $page->getRevisionRecord();
748
749 $this->editPage( $page, 'Latest Test' );
750
751 $frenchResult = $access->getParserOutput( $page, $frenchOptions, $oldRev );
752 $this->assertContainsHtml( 'Test', $frenchResult );
753
754 // Check that French output was cached
755 $cachedFrenchOutput =
756 $access->getCachedParserOutput( $page, $frenchOptions, $oldRev );
757 $this->assertNotNull( $cachedFrenchOutput, 'French output should be in the cache' );
758
759 // check that we don't get the French output when asking for Tonga
760 $cachedTongaOutput =
761 $access->getCachedParserOutput( $page, $tongaOptions, $oldRev );
762 $this->assertNull( $cachedTongaOutput, 'Tonga output should not be in the cache yet' );
763
764 // check that we can generate the Tonga output, and it's different from French
765 $tongaResult = $access->getParserOutput( $page, $tongaOptions, $oldRev );
766 $this->assertContainsHtml( 'Test', $tongaResult );
767 $this->assertNotSameHtml(
768 $frenchResult,
769 $tongaResult,
770 'Tonga output should be different from French'
771 );
772
773 // check that the Tonga output is cached
774 $cachedTongaOutput =
775 $access->getCachedParserOutput( $page, $tongaOptions, $oldRev );
776 $this->assertNotNull( $cachedTongaOutput, 'Tonga output should be in the cache' );
777 }
778
779 /**
780 * Tests that a RevisionRecord with no ID can be rendered if OPT_NO_CACHE is set.
781 */
782 public function testFakeRevisionNoCache() {
783 $access = $this->getParserOutputAccessWithCache();
784
785 $page = $this->getExistingTestPage( __METHOD__ );
786 $rev = $this->makeFakeRevision( $page, 'fake text' );
787
788 // Render fake
789 $parserOptions = $this->getParserOptions();
790 $fakeResult = $access->getParserOutput(
791 $page,
792 $parserOptions,
793 $rev,
794 ParserOutputAccess::OPT_NO_CACHE
795 );
796 $this->assertContainsHtml( 'fake text', $fakeResult );
797
798 // check that fake output isn't cached
799 $cachedOutput = $access->getCachedParserOutput( $page, $parserOptions );
800 if ( $cachedOutput ) {
801 // we may have a cache entry for original edit
802 $this->assertNotSameHtml( $fakeResult, $cachedOutput );
803 }
804 }
805
806 /**
807 * Tests that a RevisionRecord with no ID cannot be rendered if OPT_NO_CACHE is not set.
808 */
809 public function testFakeRevisionError() {
810 $access = $this->getParserOutputAccess();
811 $parserOptions = $this->getParserOptions();
812
813 $page = $this->getExistingTestPage( __METHOD__ );
814 $rev = $this->makeFakeRevision( $page, 'fake text' );
815
816 // Render should fail
817 $this->expectException( InvalidArgumentException::class );
818 $access->getParserOutput( $page, $parserOptions, $rev );
819 }
820
821 /**
822 * Tests that trying to render a RevisionRecord for another page will throw an exception.
823 */
824 public function testPageIdMismatchError() {
825 $access = $this->getParserOutputAccess();
826 $parserOptions = $this->getParserOptions();
827
828 $page1 = $this->getExistingTestPage( __METHOD__ . '-1' );
829 $page2 = $this->getExistingTestPage( __METHOD__ . '-2' );
830
831 $this->expectException( InvalidArgumentException::class );
832 $access->getParserOutput( $page1, $parserOptions, $page2->getRevisionRecord() );
833 }
834
835 /**
836 * Tests that trying to render a non-existing page will be reported as an error.
837 */
838 public function testNonExistingPage() {
839 $access = $this->getParserOutputAccess();
840
841 $page = $this->getNonexistingTestPage( __METHOD__ );
842
843 $parserOptions = $this->getParserOptions();
844 $status = $access->getParserOutput( $page, $parserOptions );
845 $this->assertStatusError( 'nopagetext', $status );
846 }
847
848 /**
849 * @param Status $status
850 * @param bool $fastStale
851 */
852 private function setPoolCounterFactory( $status, $fastStale = false ) {
853 $this->overrideConfigValue( MainConfigNames::PoolCounterConf, [
854 'ArticleView' => [
855 'class' => MockPoolCounterFailing::class,
856 'fastStale' => $fastStale,
857 'mockAcquire' => $status,
858 'mockRelease' => Status::newGood( PoolCounter::RELEASED ),
859 ],
860 ] );
861 }
862
863 public static function providePoolWorkDirty() {
864 yield [ Status::newGood( PoolCounter::QUEUE_FULL ), false, 'view-pool-overload' ];
865 yield [ Status::newGood( PoolCounter::TIMEOUT ), false, 'view-pool-overload' ];
866 yield [ Status::newGood( PoolCounter::TIMEOUT ), true, 'view-pool-contention' ];
867 }
868
869 /**
870 * Tests that under some circumstances, stale cache entries will be returned, but get
871 * flagged as "dirty".
872 *
873 * @dataProvider providePoolWorkDirty
874 */
875 public function testPoolWorkDirty( $status, $fastStale, $expectedMessage ) {
876 $this->overrideConfigValues( [
877 MainConfigNames::ParserCacheExpireTime => 60,
878 ] );
879 $this->setPoolCounterFactory( Status::newGood( PoolCounter::LOCKED ), $fastStale );
880 MWTimestamp::setFakeTime( '2020-04-04T01:02:03' );
881
882 $access = $this->getParserOutputAccess( [
883 'expectPoolCounterCalls' => 2,
884 'parserCache' => new HashBagOStuff()
885 ] );
886
887 $page = $this->getNonexistingTestPage( __METHOD__ );
888 $this->editPage( $page, 'Hello \'\'World\'\'!' );
889
890 $parserOptions = $this->getParserOptions();
891 $result = $access->getParserOutput(
892 $page,
893 $parserOptions,
894 null,
895 ParserOutputAccess::OPT_FOR_ARTICLE_VIEW
896 );
897 $this->assertContainsHtml( 'World', $result, 'fresh result' );
898
899 $testingAccess = TestingAccessWrapper::newFromObject( $access );
900 $testingAccess->localCache->clear();
901
902 $this->setPoolCounterFactory( $status, $fastStale );
903
904 // expire parser cache
905 MWTimestamp::setFakeTime( '2020-05-05T01:02:03' );
906
907 $parserOptions = $this->getParserOptions();
908 $cachedResult = $access->getParserOutput(
909 $page,
910 $parserOptions,
911 null,
912 ParserOutputAccess::OPT_FOR_ARTICLE_VIEW
913 );
914 $this->assertContainsHtml( 'World', $cachedResult, 'cached result' );
915
916 $this->assertStatusWarning( $expectedMessage, $cachedResult );
917 $this->assertStatusWarning( 'view-pool-dirty-output', $cachedResult );
918 }
919
920 /**
921 * Tests that a failure to acquire a work lock will be reported as an error if no
922 * stale output can be returned.
923 */
924 public function testPoolWorkTimeout() {
925 $this->overrideConfigValues( [
926 MainConfigNames::ParserCacheExpireTime => 60,
927 ] );
928 $this->setPoolCounterFactory( Status::newGood( PoolCounter::TIMEOUT ) );
929
930 $access = $this->getParserOutputAccess( [
931 'expectPoolCounterCalls' => 1
932 ] );
933
934 $page = $this->getNonexistingTestPage( __METHOD__ );
935 $this->editPage( $page, 'Hello \'\'World\'\'!' );
936
937 $parserOptions = $this->getParserOptions();
938 $result = $access->getParserOutput(
939 $page,
940 $parserOptions,
941 null,
942 ParserOutputAccess::OPT_FOR_ARTICLE_VIEW
943 );
944 $this->assertStatusError( 'pool-timeout', $result );
945 }
946
947 /**
948 * Tests that a PoolCounter error does not prevent output from being generated.
949 */
950 public function testPoolWorkError() {
951 $this->overrideConfigValues( [
952 MainConfigNames::ParserCacheExpireTime => 60,
953 ] );
954 $this->setPoolCounterFactory( Status::newFatal( 'some-error' ) );
955
956 $access = $this->getParserOutputAccess();
957
958 $page = $this->getNonexistingTestPage( __METHOD__ );
959 $this->editPage( $page, 'Hello \'\'World\'\'!' );
960
961 $parserOptions = $this->getParserOptions();
962 $result = $access->getParserOutput( $page, $parserOptions );
963 $this->assertContainsHtml( 'World', $result );
964 }
965
966 public function testParsoidCacheSplit() {
967 $parserCacheFactory = $this->createMock( ParserCacheFactory::class );
968 $revisionOutputCache = $this->getRevisionOutputCache( new HashBagOStuff() );
969 $caches = [
970 $this->getParserCache( new HashBagOStuff() ),
971 $this->getParserCache( new HashBagOStuff() ),
972 ];
973 $calls = [];
974 $parserCacheFactory
975 ->method( 'getParserCache' )
976 ->willReturnCallback( static function ( $cacheName ) use ( &$calls, $caches ) {
977 static $cacheList = [];
978 $calls[] = $cacheName;
979 $which = array_search( $cacheName, $cacheList );
980 if ( $which === false ) {
981 $which = count( $cacheList );
982 $cacheList[] = $cacheName;
983 }
984 return $caches[$which];
985 } );
986 $parserCacheFactory
987 ->method( 'getRevisionOutputCache' )
988 ->willReturn( $revisionOutputCache );
989
990 $access = $this->getParserOutputAccess( [
991 'parserCacheFactory' => $parserCacheFactory
992 ] );
993 $parserOptions0 = $this->getParserOptions();
994 $page = $this->getNonexistingTestPage( __METHOD__ );
995 $output = $access->getCachedParserOutput( $page, $parserOptions0 );
996 $this->assertNull( $output );
997 // $calls[0] will remember what cache name we used.
998 $this->assertCount( 1, $calls );
999
1000 $parserOptions1 = $this->getParserOptions();
1001 $parserOptions1->setUseParsoid();
1002 $output = $access->getCachedParserOutput( $page, $parserOptions1 );
1003 $this->assertNull( $output );
1004 $this->assertCount( 2, $calls );
1005 // Check that we used a different cache name this time.
1006 $this->assertNotEquals( $calls[1], $calls[0], "Should use different caches" );
1007
1008 // Try this again, with actual content.
1009 $calls = [];
1010 $this->editPage( $page, "__NOTOC__" );
1011 $status0 = $access->getParserOutput( $page, $parserOptions0 );
1012 $this->assertContainsHtml( '<div class="mw-content-ltr mw-parser-output" lang="en" dir="ltr"></div>', $status0 );
1013 $status1 = $access->getParserOutput( $page, $parserOptions1 );
1014 $this->assertContainsHtml( '<meta property="mw:PageProp/notoc"', $status1 );
1015 $this->assertNotSameHtml( $status0, $status1 );
1016 }
1017
1018 public function testParsoidRevisionCacheSplit() {
1019 $parserCacheFactory = $this->createMock( ParserCacheFactory::class );
1020 $parserCache = $this->getParserCache( new HashBagOStuff() );
1021 $caches = [
1022 $this->getRevisionOutputCache( new HashBagOStuff() ),
1023 $this->getRevisionOutputCache( new HashBagOStuff() ),
1024 ];
1025 $calls = [];
1026 $parserCacheFactory
1027 ->method( 'getParserCache' )
1028 ->willReturn( $parserCache );
1029 $parserCacheFactory
1030 ->method( 'getRevisionOutputCache' )
1031 ->willReturnCallback( static function ( $cacheName ) use ( &$calls, $caches ) {
1032 static $cacheList = [];
1033 $calls[] = $cacheName;
1034 $which = array_search( $cacheName, $cacheList );
1035 if ( $which === false ) {
1036 $which = count( $cacheList );
1037 $cacheList[] = $cacheName;
1038 }
1039 return $caches[$which];
1040 } );
1041
1042 $access = $this->getParserOutputAccess( [
1043 'parserCacheFactory' => $parserCacheFactory
1044 ] );
1045 $page = $this->getNonexistingTestPage( __METHOD__ );
1046 $firstRev = $this->editPage( $page, 'First __NOTOC__' )->getNewRevision();
1047 $secondRev = $this->editPage( $page, 'Second __NOTOC__' )->getNewRevision();
1048
1049 $parserOptions0 = $this->getParserOptions();
1050 $status = $access->getParserOutput( $page, $parserOptions0, $firstRev );
1051 $this->assertContainsHtml( 'First', $status );
1052 // Check that we used the "not parsoid" revision cache
1053 $this->assertNotEmpty( $calls );
1054 $notParsoid = $calls[0];
1055 $this->assertEquals( array_fill( 0, count( $calls ), $notParsoid ), $calls );
1056
1057 $calls = [];
1058 $parserOptions1 = $this->getParserOptions();
1059 $parserOptions1->setUseParsoid();
1060 $status = $access->getParserOutput( $page, $parserOptions1, $firstRev );
1061 $this->assertContainsHtml( 'First', $status );
1062 $this->assertContainsHtml( '<meta property="mw:PageProp/notoc"', $status );
1063 $this->assertNotEmpty( $calls );
1064 $parsoid = $calls[0];
1065 $this->assertNotEquals( $notParsoid, $parsoid, "Should use different caches" );
1066 $this->assertEquals( array_fill( 0, count( $calls ), $parsoid ), $calls );
1067 }
1068 }