3 use Wikimedia\TestingAccessWrapper
;
6 * @author Matthew Flaschen
11 class OutputPageTest
extends MediaWikiTestCase
{
12 const SCREEN_MEDIA_QUERY
= 'screen and (min-width: 982px)';
13 const SCREEN_ONLY_MEDIA_QUERY
= 'only screen and (min-width: 982px)';
15 // @codingStandardsIgnoreStart Generic.Files.LineLength
16 const RSS_RC_LINK
= '<link rel="alternate" type="application/rss+xml" title=" RSS feed" href="/w/index.php?title=Special:RecentChanges&feed=rss"/>';
17 const ATOM_RC_LINK
= '<link rel="alternate" type="application/atom+xml" title=" Atom feed" href="/w/index.php?title=Special:RecentChanges&feed=atom"/>';
19 const RSS_TEST_LINK
= '<link rel="alternate" type="application/rss+xml" title=""Test" RSS feed" href="fake-link"/>';
20 const ATOM_TEST_LINK
= '<link rel="alternate" type="application/atom+xml" title=""Test" Atom feed" href="fake-link"/>';
21 // @codingStandardsIgnoreEnd
23 // Ensure that we don't affect the global ResourceLoader state.
24 protected function setUp() {
26 ResourceLoader
::clearCache();
29 protected function tearDown() {
31 ResourceLoader
::clearCache();
35 * @dataProvider provideRedirect
37 * @covers OutputPage::__construct
38 * @covers OutputPage::redirect
39 * @covers OutputPage::getRedirect
41 public function testRedirect( $url, $code = null ) {
42 $op = $this->newInstance();
43 if ( isset( $code ) ) {
44 $op->redirect( $url, $code );
46 $op->redirect( $url );
48 $expectedUrl = str_replace( "\n", '', $url );
49 $this->assertSame( $expectedUrl, $op->getRedirect() );
50 $this->assertSame( $expectedUrl, $op->mRedirect
);
51 $this->assertSame( $code ??
'302', $op->mRedirectCode
);
54 public function provideRedirect() {
56 [ 'http://example.com' ],
57 [ 'http://example.com', '400' ],
58 [ 'http://example.com', 'squirrels!!!' ],
63 private function setupFeedLinks( $feed, $types ) {
64 $outputPage = $this->newInstance( [
65 'AdvertisedFeedTypes' => $types,
67 'OverrideSiteFeed' => false,
71 $outputPage->setTitle( Title
::makeTitle( NS_MAIN
, 'Test' ) );
72 $this->setMwGlobals( [
73 'wgScript' => '/w/index.php',
78 private function assertFeedLinks( $outputPage, $message, $present, $non_present ) {
79 $links = $outputPage->getHeadLinksArray();
80 foreach ( $present as $link ) {
81 $this->assertContains( $link, $links, $message );
83 foreach ( $non_present as $link ) {
84 $this->assertNotContains( $link, $links, $message );
88 private function assertFeedUILinks( $outputPage, $ui_links ) {
90 $this->assertTrue( $outputPage->isSyndicated(), 'Syndication should be offered' );
91 $this->assertGreaterThan( 0, count( $outputPage->getSyndicationLinks() ),
92 'Some syndication links should be there' );
94 $this->assertFalse( $outputPage->isSyndicated(), 'No syndication should be offered' );
95 $this->assertEquals( 0, count( $outputPage->getSyndicationLinks() ),
96 'No syndication links should be there' );
100 public static function provideFeedLinkData() {
103 true, [ 'rss' ], 'Only RSS RC link should be offerred',
104 [ self
::RSS_RC_LINK
], [ self
::ATOM_RC_LINK
]
107 true, [ 'atom' ], 'Only Atom RC link should be offerred',
108 [ self
::ATOM_RC_LINK
], [ self
::RSS_RC_LINK
]
111 true, [], 'No RC feed formats should be offerred',
112 [], [ self
::ATOM_RC_LINK
, self
::RSS_RC_LINK
]
115 false, [ 'atom' ], 'No RC feeds should be offerred',
116 [], [ self
::ATOM_RC_LINK
, self
::RSS_RC_LINK
]
122 * @covers OutputPage::setCopyrightUrl
123 * @covers OutputPage::getHeadLinksArray
125 public function testSetCopyrightUrl() {
126 $op = $this->newInstance();
127 $op->setCopyrightUrl( 'http://example.com' );
130 Html
::element( 'link', [ 'rel' => 'license', 'href' => 'http://example.com' ] ),
131 $op->getHeadLinksArray()['copyright']
136 * @dataProvider provideFeedLinkData
137 * @covers OutputPage::getHeadLinksArray
139 public function testRecentChangesFeed( $feed, $advertised_feed_types,
140 $message, $present, $non_present ) {
141 $outputPage = $this->setupFeedLinks( $feed, $advertised_feed_types );
142 $this->assertFeedLinks( $outputPage, $message, $present, $non_present );
145 public static function provideAdditionalFeedData() {
148 true, [ 'atom' ], 'Additional Atom feed should be offered',
150 [ self
::ATOM_TEST_LINK
, self
::ATOM_RC_LINK
],
151 [ self
::RSS_TEST_LINK
, self
::RSS_RC_LINK
],
155 true, [ 'rss' ], 'Additional RSS feed should be offered',
157 [ self
::RSS_TEST_LINK
, self
::RSS_RC_LINK
],
158 [ self
::ATOM_TEST_LINK
, self
::ATOM_RC_LINK
],
162 true, [ 'rss' ], 'Additional Atom feed should NOT be offered with RSS enabled',
164 [ self
::RSS_RC_LINK
],
165 [ self
::RSS_TEST_LINK
, self
::ATOM_TEST_LINK
, self
::ATOM_RC_LINK
],
169 false, [ 'atom' ], 'Additional Atom feed should NOT be offered, all feeds disabled',
173 self
::RSS_TEST_LINK
, self
::ATOM_TEST_LINK
,
174 self
::ATOM_RC_LINK
, self
::ATOM_RC_LINK
,
182 * @dataProvider provideAdditionalFeedData
183 * @covers OutputPage::getHeadLinksArray
184 * @covers OutputPage::addFeedLink
185 * @covers OutputPage::getSyndicationLinks
186 * @covers OutputPage::isSyndicated
188 public function testAdditionalFeeds( $feed, $advertised_feed_types, $message,
189 $additional_feed_type, $present, $non_present, $any_ui_links ) {
190 $outputPage = $this->setupFeedLinks( $feed, $advertised_feed_types );
191 $outputPage->addFeedLink( $additional_feed_type, 'fake-link' );
192 $this->assertFeedLinks( $outputPage, $message, $present, $non_present );
193 $this->assertFeedUILinks( $outputPage, $any_ui_links );
196 // @todo How to test setStatusCode?
199 * @covers OutputPage::addMeta
200 * @covers OutputPage::getMetaTags
201 * @covers OutputPage::getHeadLinksArray
203 public function testMetaTags() {
204 $op = $this->newInstance();
205 $op->addMeta( 'http:expires', '0' );
206 $op->addMeta( 'keywords', 'first' );
207 $op->addMeta( 'keywords', 'second' );
208 $op->addMeta( 'og:title', 'Ta-duh' );
211 [ 'http:expires', '0' ],
212 [ 'keywords', 'first' ],
213 [ 'keywords', 'second' ],
214 [ 'og:title', 'Ta-duh' ],
216 $this->assertSame( $expected, $op->getMetaTags() );
218 $links = $op->getHeadLinksArray();
219 $this->assertContains( '<meta http-equiv="expires" content="0"/>', $links );
220 $this->assertContains( '<meta name="keywords" content="first"/>', $links );
221 $this->assertContains( '<meta name="keywords" content="second"/>', $links );
222 $this->assertContains( '<meta property="og:title" content="Ta-duh"/>', $links );
223 $this->assertArrayNotHasKey( 'meta-robots', $links );
227 * @covers OutputPage::addLink
228 * @covers OutputPage::getLinkTags
229 * @covers OutputPage::getHeadLinksArray
231 public function testAddLink() {
232 $op = $this->newInstance();
236 [ 'rel' => 'foo', 'href' => 'http://example.com' ],
239 foreach ( $links as $link ) {
240 $op->addLink( $link );
243 $this->assertSame( $links, $op->getLinkTags() );
245 $result = $op->getHeadLinksArray();
247 foreach ( $links as $link ) {
248 $this->assertContains( Html
::element( 'link', $link ), $result );
253 * @covers OutputPage::setCanonicalUrl
254 * @covers OutputPage::getCanonicalUrl
255 * @covers OutputPage::getHeadLinksArray
257 public function testSetCanonicalUrl() {
258 $op = $this->newInstance();
259 $op->setCanonicalUrl( 'http://example.comm' );
260 $op->setCanonicalUrl( 'http://example.com' );
262 $this->assertSame( 'http://example.com', $op->getCanonicalUrl() );
264 $headLinks = $op->getHeadLinksArray();
266 $this->assertContains( Html
::element( 'link', [
267 'rel' => 'canonical', 'href' => 'http://example.com'
270 $this->assertNotContains( Html
::element( 'link', [
271 'rel' => 'canonical', 'href' => 'http://example.comm'
276 * @covers OutputPage::addScript
278 public function testAddScript() {
279 $op = $this->newInstance();
280 $op->addScript( 'some random string' );
282 $this->assertContains( "\nsome random string\n", "\n" . $op->getBottomScripts() . "\n" );
286 * @covers OutputPage::addScriptFile
288 public function testAddScriptFile() {
289 $op = $this->newInstance();
290 $op->addScriptFile( '/somescript.js' );
291 $op->addScriptFile( '//example.com/somescript.js' );
293 $this->assertContains(
294 "\n" . Html
::linkedScript( '/somescript.js', $op->getCSPNonce() ) .
295 Html
::linkedScript( '//example.com/somescript.js', $op->getCSPNonce() ) . "\n",
296 "\n" . $op->getBottomScripts() . "\n"
301 * Test that addScriptFile() throws due to deprecation.
303 * @covers OutputPage::addScriptFile
305 public function testAddDeprecatedScriptFileWarning() {
306 $this->setExpectedException( PHPUnit_Framework_Error_Deprecated
::class,
307 'Use of OutputPage::addScriptFile was deprecated in MediaWiki 1.24.' );
309 $op = $this->newInstance();
310 $op->addScriptFile( 'ignored-script.js' );
314 * Test the actual behavior of the method (in the case where it doesn't throw, e.g., in
317 * @covers OutputPage::addScriptFile
319 public function testAddDeprecatedScriptFileNoOp() {
320 $this->hideDeprecated( 'OutputPage::addScriptFile' );
321 $op = $this->newInstance();
322 $op->addScriptFile( 'ignored-script.js' );
324 $this->assertNotContains( 'ignored-script.js', '' . $op->getBottomScripts() );
328 * @covers OutputPage::addInlineScript
330 public function testAddInlineScript() {
331 $op = $this->newInstance();
332 $op->addInlineScript( 'let foo = "bar";' );
333 $op->addInlineScript( 'alert( foo );' );
335 $this->assertContains(
336 "\n" . Html
::inlineScript( "\nlet foo = \"bar\";\n", $op->getCSPNonce() ) . "\n" .
337 Html
::inlineScript( "\nalert( foo );\n", $op->getCSPNonce() ) . "\n",
338 "\n" . $op->getBottomScripts() . "\n"
342 // @todo How to test filterModules(), warnModuleTargetFilter(), getModules(), etc.?
345 * @covers OutputPage::getTarget
346 * @covers OutputPage::setTarget
348 public function testSetTarget() {
349 $op = $this->newInstance();
350 $op->setTarget( 'foo' );
352 $this->assertSame( 'foo', $op->getTarget() );
353 // @todo What else? Test some actual effect?
356 // @todo How to test addContentOverride(Callback)?
359 * @covers OutputPage::getHeadItemsArray
360 * @covers OutputPage::addHeadItem
361 * @covers OutputPage::addHeadItems
362 * @covers OutputPage::hasHeadItem
364 public function testHeadItems() {
365 $op = $this->newInstance();
366 $op->addHeadItem( 'a', 'b' );
367 $op->addHeadItems( [ 'c' => '<d>&', 'e' => 'f', 'a' => 'q' ] );
368 $op->addHeadItem( 'e', 'g' );
369 $op->addHeadItems( 'x' );
371 $this->assertSame( [ 'a' => 'q', 'c' => '<d>&', 'e' => 'g', 'x' ],
372 $op->getHeadItemsArray() );
374 $this->assertTrue( $op->hasHeadItem( 'a' ) );
375 $this->assertTrue( $op->hasHeadItem( 'c' ) );
376 $this->assertTrue( $op->hasHeadItem( 'e' ) );
377 $this->assertTrue( $op->hasHeadItem( '0' ) );
379 $this->assertContains( "\nq\n<d>&\ng\nx\n",
380 '' . $op->headElement( $op->getContext()->getSkin() ) );
384 * @covers OutputPage::getHeadItemsArray
385 * @covers OutputPage::addParserOutputMetadata
386 * @covers OutputPage::addParserOutput
388 public function testHeadItemsParserOutput() {
389 $op = $this->newInstance();
390 $stubPO1 = $this->createParserOutputStub( 'getHeadItems', [ 'a' => 'b' ] );
391 $op->addParserOutputMetadata( $stubPO1 );
392 $stubPO2 = $this->createParserOutputStub( 'getHeadItems',
393 [ 'c' => '<d>&', 'e' => 'f', 'a' => 'q' ] );
394 $op->addParserOutputMetadata( $stubPO2 );
395 $stubPO3 = $this->createParserOutputStub( 'getHeadItems', [ 'e' => 'g' ] );
396 $op->addParserOutput( $stubPO3 );
397 $stubPO4 = $this->createParserOutputStub( 'getHeadItems', [ 'x' ] );
398 $op->addParserOutputMetadata( $stubPO4 );
400 $this->assertSame( [ 'a' => 'q', 'c' => '<d>&', 'e' => 'g', 'x' ],
401 $op->getHeadItemsArray() );
403 $this->assertTrue( $op->hasHeadItem( 'a' ) );
404 $this->assertTrue( $op->hasHeadItem( 'c' ) );
405 $this->assertTrue( $op->hasHeadItem( 'e' ) );
406 $this->assertTrue( $op->hasHeadItem( '0' ) );
407 $this->assertFalse( $op->hasHeadItem( 'b' ) );
409 $this->assertContains( "\nq\n<d>&\ng\nx\n",
410 '' . $op->headElement( $op->getContext()->getSkin() ) );
414 * @covers OutputPage::addBodyClasses
416 public function testAddBodyClasses() {
417 $op = $this->newInstance();
418 $op->addBodyClasses( 'a' );
419 $op->addBodyClasses( 'mediawiki' );
420 $op->addBodyClasses( 'b c' );
421 $op->addBodyClasses( [ 'd', 'e' ] );
422 $op->addBodyClasses( 'a' );
424 $this->assertContains( '"a mediawiki b c d e ltr',
425 '' . $op->headElement( $op->getContext()->getSkin() ) );
429 * @covers OutputPage::setArticleBodyOnly
430 * @covers OutputPage::getArticleBodyOnly
432 public function testArticleBodyOnly() {
433 $op = $this->newInstance();
434 $this->assertFalse( $op->getArticleBodyOnly() );
436 $op->setArticleBodyOnly( true );
437 $this->assertTrue( $op->getArticleBodyOnly() );
439 $op->addHTML( '<b>a</b>' );
441 $this->assertSame( '<b>a</b>', $op->output( true ) );
445 * @covers OutputPage::setProperty
446 * @covers OutputPage::getProperty
448 public function testProperties() {
449 $op = $this->newInstance();
451 $this->assertNull( $op->getProperty( 'foo' ) );
453 $op->setProperty( 'foo', 'bar' );
454 $op->setProperty( 'baz', 'quz' );
456 $this->assertSame( 'bar', $op->getProperty( 'foo' ) );
457 $this->assertSame( 'quz', $op->getProperty( 'baz' ) );
461 * @dataProvider provideCheckLastModified
463 * @covers OutputPage::checkLastModified
464 * @covers OutputPage::getCdnCacheEpoch
466 public function testCheckLastModified(
467 $timestamp, $ifModifiedSince, $expected, $config = [], $callback = null
469 $request = new FauxRequest();
470 if ( $ifModifiedSince ) {
471 if ( is_numeric( $ifModifiedSince ) ) {
473 $ifModifiedSince = date( 'D, d M Y H:i:s', $ifModifiedSince ) . ' GMT';
475 $request->setHeader( 'If-Modified-Since', $ifModifiedSince );
478 if ( !isset( $config['CacheEpoch'] ) ) {
479 // Make sure it's not too recent
480 $config['CacheEpoch'] = '20000101000000';
483 $op = $this->newInstance( $config, $request );
486 $callback( $op, $this );
489 // Avoid a complaint about not being able to disable compression
490 Wikimedia\
suppressWarnings();
492 $this->assertEquals( $expected, $op->checkLastModified( $timestamp ) );
494 Wikimedia\restoreWarnings
();
498 public function provideCheckLastModified() {
499 $lastModified = time() - 3600;
502 [ '0', $lastModified, false ],
503 'Timestamp Unix epoch' =>
504 [ '19700101000000', $lastModified, false ],
505 'Timestamp same as If-Modified-Since' =>
506 [ $lastModified, $lastModified, true ],
507 'Timestamp one second after If-Modified-Since' =>
508 [ $lastModified +
1, $lastModified, false ],
509 'No If-Modified-Since' =>
510 [ $lastModified +
1, null, false ],
511 'Malformed If-Modified-Since' =>
512 [ $lastModified +
1, 'GIBBERING WOMBATS !!!', false ],
513 'Non-standard IE-style If-Modified-Since' =>
514 [ $lastModified, date( 'D, d M Y H:i:s', $lastModified ) . ' GMT; length=5202',
516 // @todo Should we fix this behavior to match the spec? Probably no reason to.
517 'If-Modified-Since not per spec but we accept it anyway because strtotime does' =>
518 [ $lastModified, "@$lastModified", true ],
519 '$wgCachePages = false' =>
520 [ $lastModified, $lastModified, false, [ 'CachePages' => false ] ],
522 [ $lastModified, $lastModified, false,
523 [ 'CacheEpoch' => wfTimestamp( TS_MW
, $lastModified +
1 ) ] ],
524 'Recently-touched user' =>
525 [ $lastModified, $lastModified, false, [],
527 $op->getContext()->setUser( $this->getTestUser()->getUser() );
529 'After Squid expiry' =>
530 [ $lastModified, $lastModified, false,
531 [ 'UseSquid' => true, 'SquidMaxage' => 3599 ] ],
532 'Hook allows cache use' =>
533 [ $lastModified +
1, $lastModified, true, [],
534 function ( $op, $that ) {
535 $that->setTemporaryHook( 'OutputPageCheckLastModified',
536 function ( &$modifiedTimes ) {
537 $modifiedTimes = [ 1 ];
541 'Hooks prohibits cache use' =>
542 [ $lastModified, $lastModified, false, [],
543 function ( $op, $that ) {
544 $that->setTemporaryHook( 'OutputPageCheckLastModified',
545 function ( &$modifiedTimes ) {
546 $modifiedTimes = [ max( $modifiedTimes ) +
1 ];
554 * @dataProvider provideCdnCacheEpoch
556 * @covers OutputPage::getCdnCacheEpoch
558 public function testCdnCacheEpoch( $params ) {
559 $out = TestingAccessWrapper
::newFromObject( $this->newInstance() );
560 $reqTime = strtotime( $params['reqTime'] );
561 $pageTime = strtotime( $params['pageTime'] );
562 $actual = max( $pageTime, $out->getCdnCacheEpoch( $reqTime, $params['maxAge'] ) );
566 gmdate( DateTime
::ATOM
, $actual ),
571 public static function provideCdnCacheEpoch() {
573 'pageTime' => '2011-04-01T12:00:00+00:00',
574 'maxAge' => 24 * 3600,
577 'after 1s' => [ $base +
[
578 'reqTime' => '2011-04-01T12:00:01+00:00',
579 'expect' => '2011-04-01T12:00:00+00:00',
581 'after 23h' => [ $base +
[
582 'reqTime' => '2011-04-02T11:00:00+00:00',
583 'expect' => '2011-04-01T12:00:00+00:00',
585 'after 24h and a bit' => [ $base +
[
586 'reqTime' => '2011-04-02T12:34:56+00:00',
587 'expect' => '2011-04-01T12:34:56+00:00',
589 'after a year' => [ $base +
[
590 'reqTime' => '2012-05-06T00:12:07+00:00',
591 'expect' => '2012-05-05T00:12:07+00:00',
596 // @todo How to test setLastModified?
599 * @covers OutputPage::setRobotPolicy
600 * @covers OutputPage::getHeadLinksArray
602 public function testSetRobotPolicy() {
603 $op = $this->newInstance();
604 $op->setRobotPolicy( 'noindex, nofollow' );
606 $links = $op->getHeadLinksArray();
607 $this->assertContains( '<meta name="robots" content="noindex,nofollow"/>', $links );
611 * @covers OutputPage::setIndexPolicy
612 * @covers OutputPage::setFollowPolicy
613 * @covers OutputPage::getHeadLinksArray
615 public function testSetIndexFollowPolicies() {
616 $op = $this->newInstance();
617 $op->setIndexPolicy( 'noindex' );
618 $op->setFollowPolicy( 'nofollow' );
620 $links = $op->getHeadLinksArray();
621 $this->assertContains( '<meta name="robots" content="noindex,nofollow"/>', $links );
624 private function extractHTMLTitle( OutputPage
$op ) {
625 $html = $op->headElement( $op->getContext()->getSkin() );
627 // OutputPage should always output the title in a nice format such that regexes will work
628 // fine. If it doesn't, we'll fail the tests.
629 preg_match_all( '!<title>(.*?)</title>!', $html, $matches );
631 $this->assertLessThanOrEqual( 1, count( $matches[1] ), 'More than one <title>!' );
633 if ( !count( $matches[1] ) ) {
637 return $matches[1][0];
641 * Shorthand for getting the text of a message, in content language.
643 private static function getMsgText( $op, ...$msgParams ) {
644 return $op->msg( ...$msgParams )->inContentLanguage()->text();
648 * @covers OutputPage::setHTMLTitle
649 * @covers OutputPage::getHTMLTitle
651 public function testHTMLTitle() {
652 $op = $this->newInstance();
655 $this->assertSame( '', $op->getHTMLTitle() );
656 $this->assertSame( '', $op->getPageTitle() );
658 $this->getMsgText( $op, 'pagetitle', '' ),
659 $this->extractHTMLTitle( $op )
663 $op->setHTMLTitle( 'Potatoes will eat me' );
665 $this->assertSame( 'Potatoes will eat me', $op->getHTMLTitle() );
666 $this->assertSame( 'Potatoes will eat me', $this->extractHTMLTitle( $op ) );
667 // Shouldn't have changed the page title
668 $this->assertSame( '', $op->getPageTitle() );
671 $msg = $op->msg( 'mainpage' );
673 $op->setHTMLTitle( $msg );
674 $this->assertSame( $msg->text(), $op->getHTMLTitle() );
675 $this->assertSame( $msg->text(), $this->extractHTMLTitle( $op ) );
676 $this->assertSame( '', $op->getPageTitle() );
680 * @covers OutputPage::setRedirectedFrom
682 public function testSetRedirectedFrom() {
683 $op = $this->newInstance();
685 $op->setRedirectedFrom( Title
::newFromText( 'Talk:Some page' ) );
686 $this->assertSame( 'Talk:Some_page', $op->getJSVars()['wgRedirectedFrom'] );
690 * @covers OutputPage::setPageTitle
691 * @covers OutputPage::getPageTitle
693 public function testPageTitle() {
694 // We don't test the actual HTML output anywhere, because that's up to the skin.
695 $op = $this->newInstance();
698 $this->assertSame( '', $op->getPageTitle() );
699 $this->assertSame( '', $op->getHTMLTitle() );
701 // Test set to plain text
702 $op->setPageTitle( 'foobar' );
704 $this->assertSame( 'foobar', $op->getPageTitle() );
705 // HTML title should change as well
706 $this->assertSame( $this->getMsgText( $op, 'pagetitle', 'foobar' ), $op->getHTMLTitle() );
708 // Test set to text with good and bad HTML. We don't try to be comprehensive here, that
709 // belongs in Sanitizer tests.
710 $op->setPageTitle( '<script>a</script>&<i>b</i>' );
712 $this->assertSame( '<script>a</script>&<i>b</i>', $op->getPageTitle() );
714 $this->getMsgText( $op, 'pagetitle', '<script>a</script>&b' ),
718 // Test set to message
719 $text = $this->getMsgText( $op, 'mainpage' );
721 $op->setPageTitle( $op->msg( 'mainpage' )->inContentLanguage() );
722 $this->assertSame( $text, $op->getPageTitle() );
723 $this->assertSame( $this->getMsgText( $op, 'pagetitle', $text ), $op->getHTMLTitle() );
727 * @covers OutputPage::setTitle
729 public function testSetTitle() {
730 $op = $this->newInstance();
732 $this->assertSame( 'My test page', $op->getTitle()->getPrefixedText() );
734 $op->setTitle( Title
::newFromText( 'Another test page' ) );
736 $this->assertSame( 'Another test page', $op->getTitle()->getPrefixedText() );
740 * @covers OutputPage::setSubtitle
741 * @covers OutputPage::clearSubtitle
742 * @covers OutputPage::addSubtitle
743 * @covers OutputPage::getSubtitle
745 public function testSubtitle() {
746 $op = $this->newInstance();
748 $this->assertSame( '', $op->getSubtitle() );
750 $op->addSubtitle( '<b>foo</b>' );
752 $this->assertSame( '<b>foo</b>', $op->getSubtitle() );
754 $op->addSubtitle( $op->msg( 'mainpage' )->inContentLanguage() );
757 "<b>foo</b><br />\n\t\t\t\t" . $this->getMsgText( $op, 'mainpage' ),
761 $op->setSubtitle( 'There can be only one' );
763 $this->assertSame( 'There can be only one', $op->getSubtitle() );
765 $op->clearSubtitle();
767 $this->assertSame( '', $op->getSubtitle() );
771 * @dataProvider provideBacklinkSubtitle
773 * @covers OutputPage::buildBacklinkSubtitle
775 public function testBuildBacklinkSubtitle( $titles, $queries, $contains, $notContains ) {
776 if ( count( $titles ) > 1 ) {
778 $this->assertTrue( true );
782 $title = Title
::newFromText( $titles[0] );
783 $query = $queries[0];
785 $this->editPage( 'Page 1', '' );
786 $this->editPage( 'Page 2', '#REDIRECT [[Page 1]]' );
788 $str = OutputPage
::buildBacklinkSubtitle( $title, $query )->text();
790 foreach ( $contains as $substr ) {
791 $this->assertContains( $substr, $str );
794 foreach ( $notContains as $substr ) {
795 $this->assertNotContains( $substr, $str );
800 * @dataProvider provideBacklinkSubtitle
802 * @covers OutputPage::addBacklinkSubtitle
803 * @covers OutputPage::getSubtitle
805 public function testAddBacklinkSubtitle( $titles, $queries, $contains, $notContains ) {
806 $this->editPage( 'Page 1', '' );
807 $this->editPage( 'Page 2', '#REDIRECT [[Page 1]]' );
809 $op = $this->newInstance();
810 foreach ( $titles as $i => $unused ) {
811 $op->addBacklinkSubtitle( Title
::newFromText( $titles[$i] ), $queries[$i] );
814 $str = $op->getSubtitle();
816 foreach ( $contains as $substr ) {
817 $this->assertContains( $substr, $str );
820 foreach ( $notContains as $substr ) {
821 $this->assertNotContains( $substr, $str );
825 public function provideBacklinkSubtitle() {
831 [ 'redirect', 'Page 2' ],
841 [ [ 'action' => 'edit' ] ],
846 [ 'Page 1', 'Page 2' ],
848 [ 'Page 1', 'Page 2', "<br />\n\t\t\t\t" ],
851 // @todo Anything else to test?
856 * @covers OutputPage::setPrintable
857 * @covers OutputPage::isPrintable
859 public function testPrintable() {
860 $op = $this->newInstance();
862 $this->assertFalse( $op->isPrintable() );
866 $this->assertTrue( $op->isPrintable() );
870 * @covers OutputPage::disable
871 * @covers OutputPage::isDisabled
873 public function testDisable() {
874 $op = $this->newInstance();
876 $this->assertFalse( $op->isDisabled() );
877 $this->assertNotSame( '', $op->output( true ) );
881 $this->assertTrue( $op->isDisabled() );
882 $this->assertSame( '', $op->output( true ) );
886 * @covers OutputPage::showNewSectionLink
887 * @covers OutputPage::addParserOutputMetadata
888 * @covers OutputPage::addParserOutput
890 public function testShowNewSectionLink() {
891 $op = $this->newInstance();
893 $this->assertFalse( $op->showNewSectionLink() );
895 $pOut1 = $this->createParserOutputStub( 'getNewSection', true );
896 $op->addParserOutputMetadata( $pOut1 );
897 $this->assertTrue( $op->showNewSectionLink() );
899 $pOut2 = $this->createParserOutputStub( 'getNewSection', false );
900 $op->addParserOutput( $pOut2 );
901 $this->assertFalse( $op->showNewSectionLink() );
905 * @covers OutputPage::forceHideNewSectionLink
906 * @covers OutputPage::addParserOutputMetadata
907 * @covers OutputPage::addParserOutput
909 public function testForceHideNewSectionLink() {
910 $op = $this->newInstance();
912 $this->assertFalse( $op->forceHideNewSectionLink() );
914 $pOut1 = $this->createParserOutputStub( 'getHideNewSection', true );
915 $op->addParserOutputMetadata( $pOut1 );
916 $this->assertTrue( $op->forceHideNewSectionLink() );
918 $pOut2 = $this->createParserOutputStub( 'getHideNewSection', false );
919 $op->addParserOutput( $pOut2 );
920 $this->assertFalse( $op->forceHideNewSectionLink() );
924 * @covers OutputPage::setSyndicated
925 * @covers OutputPage::isSyndicated
927 public function testSetSyndicated() {
928 $op = $this->newInstance( [ 'Feed' => true ] );
929 $this->assertFalse( $op->isSyndicated() );
931 $op->setSyndicated();
932 $this->assertTrue( $op->isSyndicated() );
934 $op->setSyndicated( false );
935 $this->assertFalse( $op->isSyndicated() );
937 $op = $this->newInstance(); // Feed => false by default
938 $this->assertFalse( $op->isSyndicated() );
940 $op->setSyndicated();
941 $this->assertFalse( $op->isSyndicated() );
945 * @covers OutputPage::isSyndicated
946 * @covers OutputPage::setFeedAppendQuery
947 * @covers OutputPage::addFeedLink
948 * @covers OutputPage::getSyndicationLinks()
950 public function testFeedLinks() {
951 $op = $this->newInstance( [ 'Feed' => true ] );
952 $this->assertSame( [], $op->getSyndicationLinks() );
954 $op->addFeedLink( 'not a supported format', 'abc' );
955 $this->assertFalse( $op->isSyndicated() );
956 $this->assertSame( [], $op->getSyndicationLinks() );
958 $feedTypes = $op->getConfig()->get( 'AdvertisedFeedTypes' );
960 $op->addFeedLink( $feedTypes[0], 'def' );
961 $this->assertTrue( $op->isSyndicated() );
962 $this->assertSame( [ $feedTypes[0] => 'def' ], $op->getSyndicationLinks() );
964 $op->setFeedAppendQuery( false );
966 foreach ( $feedTypes as $type ) {
967 $expected[$type] = $op->getTitle()->getLocalURL( "feed=$type" );
969 $this->assertSame( $expected, $op->getSyndicationLinks() );
971 $op->setFeedAppendQuery( 'apples=oranges' );
972 foreach ( $feedTypes as $type ) {
973 $expected[$type] = $op->getTitle()->getLocalURL( "feed=$type&apples=oranges" );
975 $this->assertSame( $expected, $op->getSyndicationLinks() );
977 $op = $this->newInstance(); // Feed => false by default
978 $this->assertSame( [], $op->getSyndicationLinks() );
980 $op->addFeedLink( $feedTypes[0], 'def' );
981 $this->assertFalse( $op->isSyndicated() );
982 $this->assertSame( [], $op->getSyndicationLinks() );
986 * @covers OutputPage::setArticleFlag
987 * @covers OutputPage::isArticle
988 * @covers OutputPage::setArticleRelated
989 * @covers OutputPage::isArticleRelated
991 function testArticleFlags() {
992 $op = $this->newInstance();
993 $this->assertFalse( $op->isArticle() );
994 $this->assertTrue( $op->isArticleRelated() );
996 $op->setArticleRelated( false );
997 $this->assertFalse( $op->isArticle() );
998 $this->assertFalse( $op->isArticleRelated() );
1000 $op->setArticleFlag( true );
1001 $this->assertTrue( $op->isArticle() );
1002 $this->assertTrue( $op->isArticleRelated() );
1004 $op->setArticleFlag( false );
1005 $this->assertFalse( $op->isArticle() );
1006 $this->assertTrue( $op->isArticleRelated() );
1008 $op->setArticleFlag( true );
1009 $op->setArticleRelated( false );
1010 $this->assertFalse( $op->isArticle() );
1011 $this->assertFalse( $op->isArticleRelated() );
1015 * @covers OutputPage::addLanguageLinks
1016 * @covers OutputPage::setLanguageLinks
1017 * @covers OutputPage::getLanguageLinks
1018 * @covers OutputPage::addParserOutputMetadata
1019 * @covers OutputPage::addParserOutput
1021 function testLanguageLinks() {
1022 $op = $this->newInstance();
1023 $this->assertSame( [], $op->getLanguageLinks() );
1025 $op->addLanguageLinks( [ 'fr:A', 'it:B' ] );
1026 $this->assertSame( [ 'fr:A', 'it:B' ], $op->getLanguageLinks() );
1028 $op->addLanguageLinks( [ 'de:C', 'es:D' ] );
1029 $this->assertSame( [ 'fr:A', 'it:B', 'de:C', 'es:D' ], $op->getLanguageLinks() );
1031 $op->setLanguageLinks( [ 'pt:E' ] );
1032 $this->assertSame( [ 'pt:E' ], $op->getLanguageLinks() );
1034 $pOut1 = $this->createParserOutputStub( 'getLanguageLinks', [ 'he:F', 'ar:G' ] );
1035 $op->addParserOutputMetadata( $pOut1 );
1036 $this->assertSame( [ 'pt:E', 'he:F', 'ar:G' ], $op->getLanguageLinks() );
1038 $pOut2 = $this->createParserOutputStub( 'getLanguageLinks', [ 'pt:H' ] );
1039 $op->addParserOutput( $pOut2 );
1040 $this->assertSame( [ 'pt:E', 'he:F', 'ar:G', 'pt:H' ], $op->getLanguageLinks() );
1043 // @todo Are these category links tests too abstract and complicated for what they test? Would
1044 // it make sense to just write out all the tests by hand with maybe some copy-and-paste?
1047 * @dataProvider provideGetCategories
1049 * @covers OutputPage::addCategoryLinks
1050 * @covers OutputPage::getCategories
1051 * @covers OutputPage::getCategoryLinks
1053 * @param array $args Array of form [ category name => sort key ]
1054 * @param array $fakeResults Array of form [ category name => value to return from mocked
1056 * @param callable $variantLinkCallback Callback to replace findVariantLink() call
1057 * @param array $expectedNormal Expected return value of getCategoryLinks['normal']
1058 * @param array $expectedHidden Expected return value of getCategoryLinks['hidden']
1060 public function testAddCategoryLinks(
1061 array $args, array $fakeResults, callable
$variantLinkCallback = null,
1062 array $expectedNormal, array $expectedHidden
1064 $expectedNormal = $this->extractExpectedCategories( $expectedNormal, 'add' );
1065 $expectedHidden = $this->extractExpectedCategories( $expectedHidden, 'add' );
1067 $op = $this->setupCategoryTests( $fakeResults, $variantLinkCallback );
1069 $op->addCategoryLinks( $args );
1071 $this->doCategoryAsserts( $op, $expectedNormal, $expectedHidden );
1072 $this->doCategoryLinkAsserts( $op, $expectedNormal, $expectedHidden );
1076 * @dataProvider provideGetCategories
1078 * @covers OutputPage::addCategoryLinks
1079 * @covers OutputPage::getCategories
1080 * @covers OutputPage::getCategoryLinks
1082 public function testAddCategoryLinksOneByOne(
1083 array $args, array $fakeResults, callable
$variantLinkCallback = null,
1084 array $expectedNormal, array $expectedHidden
1086 if ( count( $args ) <= 1 ) {
1087 // @todo Should this be skipped instead of passed?
1088 $this->assertTrue( true );
1092 $expectedNormal = $this->extractExpectedCategories( $expectedNormal, 'onebyone' );
1093 $expectedHidden = $this->extractExpectedCategories( $expectedHidden, 'onebyone' );
1095 $op = $this->setupCategoryTests( $fakeResults, $variantLinkCallback );
1097 foreach ( $args as $key => $val ) {
1098 $op->addCategoryLinks( [ $key => $val ] );
1101 $this->doCategoryAsserts( $op, $expectedNormal, $expectedHidden );
1102 $this->doCategoryLinkAsserts( $op, $expectedNormal, $expectedHidden );
1106 * @dataProvider provideGetCategories
1108 * @covers OutputPage::setCategoryLinks
1109 * @covers OutputPage::getCategories
1110 * @covers OutputPage::getCategoryLinks
1112 public function testSetCategoryLinks(
1113 array $args, array $fakeResults, callable
$variantLinkCallback = null,
1114 array $expectedNormal, array $expectedHidden
1116 $expectedNormal = $this->extractExpectedCategories( $expectedNormal, 'set' );
1117 $expectedHidden = $this->extractExpectedCategories( $expectedHidden, 'set' );
1119 $op = $this->setupCategoryTests( $fakeResults, $variantLinkCallback );
1121 $op->setCategoryLinks( [ 'Initial page' => 'Initial page' ] );
1122 $op->setCategoryLinks( $args );
1124 // We don't reset the categories, for some reason, only the links
1125 $expectedNormalCats = array_merge( [ 'Initial page' ], $expectedNormal );
1126 $expectedCats = array_merge( $expectedHidden, $expectedNormalCats );
1128 $this->doCategoryAsserts( $op, $expectedNormalCats, $expectedHidden );
1129 $this->doCategoryLinkAsserts( $op, $expectedNormal, $expectedHidden );
1133 * @dataProvider provideGetCategories
1135 * @covers OutputPage::addParserOutputMetadata
1136 * @covers OutputPage::addParserOutput
1137 * @covers OutputPage::getCategories
1138 * @covers OutputPage::getCategoryLinks
1140 public function testParserOutputCategoryLinks(
1141 array $args, array $fakeResults, callable
$variantLinkCallback = null,
1142 array $expectedNormal, array $expectedHidden
1144 $expectedNormal = $this->extractExpectedCategories( $expectedNormal, 'pout' );
1145 $expectedHidden = $this->extractExpectedCategories( $expectedHidden, 'pout' );
1147 $op = $this->setupCategoryTests( $fakeResults, $variantLinkCallback );
1149 $stubPO = $this->createParserOutputStub( 'getCategories', $args );
1151 // addParserOutput and addParserOutputMetadata should behave identically for us, so
1152 // alternate to get coverage for both without adding extra tests
1155 $method = [ 'addParserOutputMetadata', 'addParserOutput' ][$idx %
2];
1156 $op->$method( $stubPO );
1158 $this->doCategoryAsserts( $op, $expectedNormal, $expectedHidden );
1159 $this->doCategoryLinkAsserts( $op, $expectedNormal, $expectedHidden );
1163 * We allow different expectations for different tests as an associative array, like
1164 * [ 'set' => [ ... ], 'default' => [ ... ] ] if setCategoryLinks() will give a different
1167 private function extractExpectedCategories( array $expected, $key ) {
1168 if ( !$expected ||
isset( $expected[0] ) ) {
1171 return $expected[$key] ??
$expected['default'];
1174 private function setupCategoryTests(
1175 array $fakeResults, callable
$variantLinkCallback = null
1177 $this->setMwGlobals( 'wgUsePigLatinVariant', true );
1179 $op = $this->getMockBuilder( OutputPage
::class )
1180 ->setConstructorArgs( [ new RequestContext() ] )
1181 ->setMethods( [ 'addCategoryLinksToLBAndGetResult', 'getTitle' ] )
1184 $title = Title
::newFromText( 'My test page' );
1185 $op->expects( $this->any() )
1186 ->method( 'getTitle' )
1187 ->will( $this->returnValue( $title ) );
1189 $op->expects( $this->any() )
1190 ->method( 'addCategoryLinksToLBAndGetResult' )
1191 ->will( $this->returnCallback( function ( array $categories ) use ( $fakeResults ) {
1193 foreach ( $categories as $category => $unused ) {
1194 if ( isset( $fakeResults[$category] ) ) {
1195 $return[] = $fakeResults[$category];
1198 return new FakeResultWrapper( $return );
1201 if ( $variantLinkCallback ) {
1202 $mockContLang = $this->getMockBuilder( Language
::class )
1203 ->setConstructorArgs( [ 'en' ] )
1204 ->setMethods( [ 'findVariantLink' ] )
1206 $mockContLang->expects( $this->any() )
1207 ->method( 'findVariantLink' )
1208 ->will( $this->returnCallback( $variantLinkCallback ) );
1209 $this->setContentLang( $mockContLang );
1212 $this->assertSame( [], $op->getCategories() );
1217 private function doCategoryAsserts( $op, $expectedNormal, $expectedHidden ) {
1218 $this->assertSame( array_merge( $expectedHidden, $expectedNormal ), $op->getCategories() );
1219 $this->assertSame( $expectedNormal, $op->getCategories( 'normal' ) );
1220 $this->assertSame( $expectedHidden, $op->getCategories( 'hidden' ) );
1223 private function doCategoryLinkAsserts( $op, $expectedNormal, $expectedHidden ) {
1224 $catLinks = $op->getCategoryLinks();
1225 $this->assertSame( (bool)$expectedNormal +
(bool)$expectedHidden, count( $catLinks ) );
1226 if ( $expectedNormal ) {
1227 $this->assertSame( count( $expectedNormal ), count( $catLinks['normal'] ) );
1229 if ( $expectedHidden ) {
1230 $this->assertSame( count( $expectedHidden ), count( $catLinks['hidden'] ) );
1233 foreach ( $expectedNormal as $i => $name ) {
1234 $this->assertContains( $name, $catLinks['normal'][$i] );
1236 foreach ( $expectedHidden as $i => $name ) {
1237 $this->assertContains( $name, $catLinks['hidden'][$i] );
1241 public function provideGetCategories() {
1243 'No categories' => [ [], [], null, [], [] ],
1245 [ 'Test1' => 'Some sortkey', 'Test2' => 'A different sortkey' ],
1246 [ 'Test1' => (object)[ 'pp_value' => 1, 'page_title' => 'Test1' ],
1247 'Test2' => (object)[ 'page_title' => 'Test2' ] ],
1252 'Invalid title' => [
1253 [ '[' => '[', 'Test' => 'Test' ],
1254 [ 'Test' => (object)[ 'page_title' => 'Test' ] ],
1260 [ 'Test' => 'Test', 'Estay' => 'Estay' ],
1261 [ 'Test' => (object)[ 'page_title' => 'Test' ] ],
1262 function ( &$link, &$title ) {
1263 if ( $link === 'Estay' ) {
1265 $title = Title
::makeTitleSafe( NS_CATEGORY
, $link );
1268 // For adding one by one, the variant gets added as well as the original category,
1269 // but if you add them all together the second time gets skipped.
1270 [ 'onebyone' => [ 'Test', 'Test' ], 'default' => [ 'Test' ] ],
1277 * @covers OutputPage::getCategories
1279 public function testGetCategoriesInvalid() {
1280 $this->setExpectedException( InvalidArgumentException
::class,
1281 'Invalid category type given: hiddne' );
1283 $op = $this->newInstance();
1284 $op->getCategories( 'hiddne' );
1287 // @todo Should we test addCategoryLinksToLBAndGetResult? If so, how? Insert some test rows in
1291 * @covers OutputPage::setIndicators
1292 * @covers OutputPage::getIndicators
1293 * @covers OutputPage::addParserOutputMetadata
1294 * @covers OutputPage::addParserOutput
1296 public function testIndicators() {
1297 $op = $this->newInstance();
1298 $this->assertSame( [], $op->getIndicators() );
1300 $op->setIndicators( [] );
1301 $this->assertSame( [], $op->getIndicators() );
1303 // Test sorting alphabetically
1304 $op->setIndicators( [ 'b' => 'x', 'a' => 'y' ] );
1305 $this->assertSame( [ 'a' => 'y', 'b' => 'x' ], $op->getIndicators() );
1307 // Test overwriting existing keys
1308 $op->setIndicators( [ 'c' => 'z', 'a' => 'w' ] );
1309 $this->assertSame( [ 'a' => 'w', 'b' => 'x', 'c' => 'z' ], $op->getIndicators() );
1311 // Test with addParserOutputMetadata
1312 $pOut1 = $this->createParserOutputStub( 'getIndicators', [ 'c' => 'u', 'd' => 'v' ] );
1313 $op->addParserOutputMetadata( $pOut1 );
1314 $this->assertSame( [ 'a' => 'w', 'b' => 'x', 'c' => 'u', 'd' => 'v' ],
1315 $op->getIndicators() );
1317 // Test with addParserOutput
1318 $pOut2 = $this->createParserOutputStub( 'getIndicators', [ 'a' => '!!!' ] );
1319 $op->addParserOutput( $pOut2 );
1320 $this->assertSame( [ 'a' => '!!!', 'b' => 'x', 'c' => 'u', 'd' => 'v' ],
1321 $op->getIndicators() );
1325 * @covers OutputPage::addHelpLink
1326 * @covers OutputPage::getIndicators
1328 public function testAddHelpLink() {
1329 $op = $this->newInstance();
1331 $op->addHelpLink( 'Manual:PHP unit testing' );
1332 $indicators = $op->getIndicators();
1333 $this->assertSame( [ 'mw-helplink' ], array_keys( $indicators ) );
1334 $this->assertContains( 'Manual:PHP_unit_testing', $indicators['mw-helplink'] );
1336 $op->addHelpLink( 'https://phpunit.de', true );
1337 $indicators = $op->getIndicators();
1338 $this->assertSame( [ 'mw-helplink' ], array_keys( $indicators ) );
1339 $this->assertContains( 'https://phpunit.de', $indicators['mw-helplink'] );
1340 $this->assertNotContains( 'mediawiki', $indicators['mw-helplink'] );
1341 $this->assertNotContains( 'Manual:PHP', $indicators['mw-helplink'] );
1345 * @covers OutputPage::prependHTML
1346 * @covers OutputPage::addHTML
1347 * @covers OutputPage::addElement
1348 * @covers OutputPage::clearHTML
1349 * @covers OutputPage::getHTML
1351 public function testBodyHTML() {
1352 $op = $this->newInstance();
1353 $this->assertSame( '', $op->getHTML() );
1355 $op->addHTML( 'a' );
1356 $this->assertSame( 'a', $op->getHTML() );
1358 $op->addHTML( 'b' );
1359 $this->assertSame( 'ab', $op->getHTML() );
1361 $op->prependHTML( 'c' );
1362 $this->assertSame( 'cab', $op->getHTML() );
1364 $op->addElement( 'p', [ 'id' => 'foo' ], 'd' );
1365 $this->assertSame( 'cab<p id="foo">d</p>', $op->getHTML() );
1368 $this->assertSame( '', $op->getHTML() );
1372 * @dataProvider provideRevisionId
1373 * @covers OutputPage::setRevisionId
1374 * @covers OutputPage::getRevisionId
1376 public function testRevisionId( $newVal, $expected ) {
1377 $op = $this->newInstance();
1379 $this->assertNull( $op->setRevisionId( $newVal ) );
1380 $this->assertSame( $expected, $op->getRevisionId() );
1381 $this->assertSame( $expected, $op->setRevisionId( null ) );
1382 $this->assertNull( $op->getRevisionId() );
1385 public function provideRevisionId() {
1392 [ '32% finished', 32 ],
1398 * @covers OutputPage::setRevisionTimestamp
1399 * @covers OutputPage::getRevisionTimestamp
1401 public function testRevisionTimestamp() {
1402 $op = $this->newInstance();
1403 $this->assertNull( $op->getRevisionTimestamp() );
1405 $this->assertNull( $op->setRevisionTimestamp( 'abc' ) );
1406 $this->assertSame( 'abc', $op->getRevisionTimestamp() );
1407 $this->assertSame( 'abc', $op->setRevisionTimestamp( null ) );
1408 $this->assertNull( $op->getRevisionTimestamp() );
1412 * @covers OutputPage::setFileVersion
1413 * @covers OutputPage::getFileVersion
1415 public function testFileVersion() {
1416 $op = $this->newInstance();
1417 $this->assertNull( $op->getFileVersion() );
1419 $stubFile = $this->createMock( File
::class );
1420 $stubFile->method( 'exists' )->willReturn( true );
1421 $stubFile->method( 'getTimestamp' )->willReturn( '12211221123321' );
1422 $stubFile->method( 'getSha1' )->willReturn( 'bf3ffa7047dc080f5855377a4f83cd18887e3b05' );
1424 $op->setFileVersion( $stubFile );
1426 $this->assertEquals(
1427 [ 'time' => '12211221123321', 'sha1' => 'bf3ffa7047dc080f5855377a4f83cd18887e3b05' ],
1428 $op->getFileVersion()
1431 $stubMissingFile = $this->createMock( File
::class );
1432 $stubMissingFile->method( 'exists' )->willReturn( false );
1434 $op->setFileVersion( $stubMissingFile );
1435 $this->assertNull( $op->getFileVersion() );
1437 $op->setFileVersion( $stubFile );
1438 $this->assertNotNull( $op->getFileVersion() );
1440 $op->setFileVersion( null );
1441 $this->assertNull( $op->getFileVersion() );
1445 * Call either with arguments $methodName, $returnValue; or an array
1446 * [ $methodName => $returnValue, $methodName => $returnValue, ... ]
1448 private function createParserOutputStub( ...$args ) {
1449 if ( count( $args ) === 0 ) {
1451 } elseif ( count( $args ) === 1 ) {
1452 $retVals = $args[0];
1453 } elseif ( count( $args ) === 2 ) {
1454 $retVals = [ $args[0] => $args[1] ];
1456 $pOut = $this->getMock( ParserOutput
::class );
1457 foreach ( $retVals as $method => $retVal ) {
1458 $pOut->method( $method )->willReturn( $retVal );
1461 $arrayReturningMethods = [
1463 'getFileSearchOptions',
1471 foreach ( $arrayReturningMethods as $method ) {
1472 $pOut->method( $method )->willReturn( [] );
1479 * @covers OutputPage::getTemplateIds
1480 * @covers OutputPage::addParserOutputMetadata
1481 * @covers OutputPage::addParserOutput
1483 public function testTemplateIds() {
1484 $op = $this->newInstance();
1485 $this->assertSame( [], $op->getTemplateIds() );
1487 // Test with no template id's
1488 $stubPOEmpty = $this->createParserOutputStub();
1489 $op->addParserOutputMetadata( $stubPOEmpty );
1490 $this->assertSame( [], $op->getTemplateIds() );
1492 // Test with some arbitrary template id's
1494 NS_MAIN
=> [ 'A' => 3, 'B' => 17 ],
1495 NS_TALK
=> [ 'C' => 31 ],
1496 NS_MEDIA
=> [ 'D' => -1 ],
1499 $stubPO1 = $this->createParserOutputStub( 'getTemplateIds', $ids );
1501 $op->addParserOutputMetadata( $stubPO1 );
1502 $this->assertSame( $ids, $op->getTemplateIds() );
1504 // Test merging with a second set of id's
1505 $stubPO2 = $this->createParserOutputStub( 'getTemplateIds', [
1506 NS_MAIN
=> [ 'E' => 1234 ],
1507 NS_PROJECT
=> [ 'F' => 5678 ],
1511 NS_MAIN
=> [ 'E' => 1234, 'A' => 3, 'B' => 17 ],
1512 NS_TALK
=> [ 'C' => 31 ],
1513 NS_MEDIA
=> [ 'D' => -1 ],
1514 NS_PROJECT
=> [ 'F' => 5678 ],
1517 $op->addParserOutput( $stubPO2 );
1518 $this->assertSame( $finalIds, $op->getTemplateIds() );
1520 // Test merging with an empty set of id's
1521 $op->addParserOutputMetadata( $stubPOEmpty );
1522 $this->assertSame( $finalIds, $op->getTemplateIds() );
1526 * @covers OutputPage::getFileSearchOptions
1527 * @covers OutputPage::addParserOutputMetadata
1528 * @covers OutputPage::addParserOutput
1530 public function testFileSearchOptions() {
1531 $op = $this->newInstance();
1532 $this->assertSame( [], $op->getFileSearchOptions() );
1534 // Test with no files
1535 $stubPOEmpty = $this->createParserOutputStub();
1537 $op->addParserOutputMetadata( $stubPOEmpty );
1538 $this->assertSame( [], $op->getFileSearchOptions() );
1540 // Test with some arbitrary files
1542 'A' => [ 'time' => null, 'sha1' => '' ],
1544 'time' => '12211221123321',
1545 'sha1' => 'bf3ffa7047dc080f5855377a4f83cd18887e3b05',
1549 $stubPO1 = $this->createParserOutputStub( 'getFileSearchOptions', $files1 );
1551 $op->addParserOutput( $stubPO1 );
1552 $this->assertSame( $files1, $op->getFileSearchOptions() );
1554 // Test merging with a second set of files
1556 'C' => [ 'time' => null, 'sha1' => '' ],
1557 'B' => [ 'time' => null, 'sha1' => '' ],
1560 $stubPO2 = $this->createParserOutputStub( 'getFileSearchOptions', $files2 );
1562 $op->addParserOutputMetadata( $stubPO2 );
1563 $this->assertSame( array_merge( $files1, $files2 ), $op->getFileSearchOptions() );
1565 // Test merging with an empty set of files
1566 $op->addParserOutput( $stubPOEmpty );
1567 $this->assertSame( array_merge( $files1, $files2 ), $op->getFileSearchOptions() );
1571 * @dataProvider provideAddWikiText
1572 * @covers OutputPage::addWikiText
1573 * @covers OutputPage::addWikiTextAsInterface
1574 * @covers OutputPage::wrapWikiTextAsInterface
1575 * @covers OutputPage::addWikiTextAsContent
1576 * @covers OutputPage::addWikiTextWithTitle
1577 * @covers OutputPage::addWikiTextTitle
1578 * @covers OutputPage::addWikiTextTidy
1579 * @covers OutputPage::addWikiTextTitleTidy
1580 * @covers OutputPage::getHTML
1582 public function testAddWikiText( $method, array $args, $expected ) {
1583 $op = $this->newInstance();
1584 $this->assertSame( '', $op->getHTML() );
1586 $this->hideDeprecated( 'OutputPage::addWikiText' );
1587 $this->hideDeprecated( 'OutputPage::addWikiTextTitle' );
1588 $this->hideDeprecated( 'OutputPage::addWikiTextWithTitle' );
1589 $this->hideDeprecated( 'OutputPage::addWikiTextTidy' );
1590 $this->hideDeprecated( 'OutputPage::addWikiTextTitleTidy' );
1591 $this->hideDeprecated( 'disabling tidy' );
1595 [ 'addWikiTextWithTitle', 'addWikiTextTitleTidy', 'addWikiTextTitle' ]
1596 ) && count( $args ) >= 2 && $args[1] === null ) {
1597 // Special placeholder because we can't get the actual title in the provider
1598 $args[1] = $op->getTitle();
1602 [ 'addWikiTextAsInterface', 'addWikiTextAsContent' ]
1603 ) && count( $args ) >= 3 && $args[2] === null ) {
1604 // Special placeholder because we can't get the actual title in the provider
1605 $args[2] = $op->getTitle();
1608 $op->$method( ...$args );
1609 $this->assertSame( $expected, $op->getHTML() );
1612 public function provideAddWikiText() {
1615 // Not tidied; this API is deprecated.
1616 'Simple wikitext' => [
1618 "<p><b>Bold</b>\n</p>",
1619 ], 'List at start' => [
1621 "<ul><li>List</li></ul>\n",
1622 ], 'List not at start' => [
1623 [ '* Not a list', false ],
1625 ], 'Non-interface' => [
1626 [ "'''Bold'''", true, false ],
1627 "<p><b>Bold</b>\n</p>",
1628 ], 'No section edit links' => [
1630 "<h2><span class=\"mw-headline\" id=\"Title\">Title</span></h2>",
1633 'addWikiTextWithTitle' => [
1634 // Untidied; this API is deprecated
1635 'With title at start' => [
1636 [ '* {{PAGENAME}}', Title
::newFromText( 'Talk:Some page' ) ],
1637 "<ul><li>Some page</li></ul>\n",
1638 ], 'With title at start' => [
1639 [ '* {{PAGENAME}}', Title
::newFromText( 'Talk:Some page' ), false ],
1643 'addWikiTextAsInterface' => [
1644 // Preferred interface: output is tidied
1645 'Simple wikitext' => [
1647 "<p><b>Bold</b>\n</p>",
1648 ], 'Untidy wikitext' => [
1650 "<p><b>Bold\n</b></p>",
1651 ], 'List at start' => [
1653 "<ul><li>List</li></ul>\n",
1654 ], 'List not at start' => [
1655 [ '* Not a list', false ],
1656 '<p>* Not a list</p>',
1657 ], 'No section edit links' => [
1659 "<h2><span class=\"mw-headline\" id=\"Title\">Title</span></h2>",
1660 ], 'With title at start' => [
1661 [ '* {{PAGENAME}}', true, Title
::newFromText( 'Talk:Some page' ) ],
1662 "<ul><li>Some page</li></ul>\n",
1663 ], 'With title at start' => [
1664 [ '* {{PAGENAME}}', false, Title
::newFromText( 'Talk:Some page' ), false ],
1665 "<p>* Some page</p>",
1666 ], 'Untidy input' => [
1667 [ '<b>{{PAGENAME}}', true, Title
::newFromText( 'Talk:Some page' ) ],
1668 "<p><b>Some page\n</b></p>",
1671 'addWikiTextAsContent' => [
1672 // Preferred interface: output is tidied
1673 'SpecialNewimages' => [
1674 [ "<p lang='en' dir='ltr'>\nMy message" ],
1675 '<p lang="en" dir="ltr">' . "\nMy message</p>"
1676 ], 'List at start' => [
1678 "<ul><li>List</li></ul>",
1679 ], 'List not at start' => [
1680 [ '* <b>Not a list', false ],
1681 '<p>* <b>Not a list</b></p>',
1682 ], 'With title at start' => [
1683 [ '* {{PAGENAME}}', true, Title
::newFromText( 'Talk:Some page' ) ],
1684 "<ul><li>Some page</li></ul>\n",
1685 ], 'With title at start' => [
1686 [ '* {{PAGENAME}}', false, Title
::newFromText( 'Talk:Some page' ), false ],
1687 "<p>* Some page</p>",
1689 [ "<div class='mw-editintro'>{{PAGENAME}}", true, Title
::newFromText( 'Talk:Some page' ) ],
1690 '<div class="mw-editintro">' . "Some page</div>"
1693 'wrapWikiTextAsInterface' => [
1695 [ 'wrapperClass', 'text' ],
1696 "<div class=\"wrapperClass\"><p>text\n</p></div>"
1697 ], 'Spurious </div>' => [
1698 [ 'wrapperClass', 'text</div><div>more' ],
1699 "<div class=\"wrapperClass\"><p>text</p><div>more</div></div>"
1700 ], 'Extra newlines would break <p> wrappers' => [
1701 [ 'two classes', "1\n\n2\n\n3" ],
1702 "<div class=\"two classes\"><p>1\n</p><p>2\n</p><p>3\n</p></div>"
1703 ], 'Other unclosed tags' => [
1704 [ 'error', 'a<b>c<i>d' ],
1705 "<div class=\"error\"><p>a<b>c<i>d\n</i></b></p></div>"
1710 // Test all the others on addWikiTextTitle as well
1711 foreach ( $tests['addWikiText'] as $key => $val ) {
1712 $args = [ $val[0][0], null, $val[0][1] ??
true, false, $val[0][2] ??
true ];
1713 $tests['addWikiTextTitle']["$key (addWikiTextTitle)"] =
1714 array_merge( [ $args ], array_slice( $val, 1 ) );
1716 foreach ( $tests['addWikiTextWithTitle'] as $key => $val ) {
1717 $args = [ $val[0][0], $val[0][1], $val[0][2] ??
true ];
1718 $tests['addWikiTextTitle']["$key (addWikiTextTitle)"] =
1719 array_merge( [ $args ], array_slice( $val, 1 ) );
1721 foreach ( $tests['addWikiTextAsInterface'] as $key => $val ) {
1722 $args = [ $val[0][0], $val[0][2] ??
null, $val[0][1] ??
true, true, true ];
1723 $tests['addWikiTextTitle']["$key (addWikiTextTitle)"] =
1724 array_merge( [ $args ], array_slice( $val, 1 ) );
1726 foreach ( $tests['addWikiTextAsContent'] as $key => $val ) {
1727 $args = [ $val[0][0], $val[0][2] ??
null, $val[0][1] ??
true, true, false ];
1728 $tests['addWikiTextTitle']["$key (addWikiTextTitle)"] =
1729 array_merge( [ $args ], array_slice( $val, 1 ) );
1731 // addWikiTextTidy / addWikiTextTitleTidy were old aliases of
1732 // addWikiTextAsContent
1733 foreach ( $tests['addWikiTextAsContent'] as $key => $val ) {
1734 if ( count( $val[0] ) > 2 ) {
1735 $args = [ $val[0][0], $val[0][2], $val[0][1] ??
true ];
1736 $tests['addWikiTextTitleTidy']["$key (addWikiTextTitleTidy)"] =
1737 array_merge( [ $args ], array_slice( $val, 1 ) );
1739 $args = [ $val[0][0], $val[0][1] ??
true ];
1740 $tests['addWikiTextTidy']["$key (addWikiTextTidy)"] =
1741 array_merge( [ $args ], array_slice( $val, 1 ) );
1745 // We have to reformat our array to match what PHPUnit wants
1747 foreach ( $tests as $key => $subarray ) {
1748 foreach ( $subarray as $subkey => $val ) {
1749 $val = array_merge( [ $key ], $val );
1750 $ret[$subkey] = $val;
1758 * @covers OutputPage::addWikiText
1760 public function testAddWikiTextNoTitle() {
1761 $this->hideDeprecated( 'OutputPage::addWikiText' );
1762 $this->setExpectedException( MWException
::class, 'Title is null' );
1764 $op = $this->newInstance( [], null, 'notitle' );
1765 $op->addWikiText( 'a' );
1769 * @covers OutputPage::addWikiTextAsInterface
1771 public function testAddWikiTextAsInterfaceNoTitle() {
1772 $this->setExpectedException( MWException
::class, 'Title is null' );
1774 $op = $this->newInstance( [], null, 'notitle' );
1775 $op->addWikiTextAsInterface( 'a' );
1779 * @covers OutputPage::addWikiTextAsContent
1781 public function testAddWikiTextAsContentNoTitle() {
1782 $this->setExpectedException( MWException
::class, 'Title is null' );
1784 $op = $this->newInstance( [], null, 'notitle' );
1785 $op->addWikiTextAsContent( 'a' );
1789 * @covers OutputPage::addWikiMsg
1791 public function testAddWikiMsg() {
1792 $msg = wfMessage( 'parentheses' );
1793 $this->assertSame( '(a)', $msg->rawParams( 'a' )->plain() );
1795 $op = $this->newInstance();
1796 $this->assertSame( '', $op->getHTML() );
1797 $op->addWikiMsg( 'parentheses', "<b>a" );
1798 // The input is bad unbalanced HTML, but the output is tidied
1799 $this->assertSame( "<p>(<b>a)\n</b></p>", $op->getHTML() );
1803 * @covers OutputPage::wrapWikiMsg
1805 public function testWrapWikiMsg() {
1806 $msg = wfMessage( 'parentheses' );
1807 $this->assertSame( '(a)', $msg->rawParams( 'a' )->plain() );
1809 $op = $this->newInstance();
1810 $this->assertSame( '', $op->getHTML() );
1811 $op->wrapWikiMsg( '[$1]', [ 'parentheses', "<b>a" ] );
1812 // The input is bad unbalanced HTML, but the output is tidied
1813 $this->assertSame( "<p>[(<b>a)]\n</b></p>", $op->getHTML() );
1817 * @covers OutputPage::addParserOutputMetadata
1818 * @covers OutputPage::addParserOutput
1820 public function testNoGallery() {
1821 $op = $this->newInstance();
1822 $this->assertFalse( $op->mNoGallery
);
1824 $stubPO1 = $this->createParserOutputStub( 'getNoGallery', true );
1825 $op->addParserOutputMetadata( $stubPO1 );
1826 $this->assertTrue( $op->mNoGallery
);
1828 $stubPO2 = $this->createParserOutputStub( 'getNoGallery', false );
1829 $op->addParserOutput( $stubPO2 );
1830 $this->assertFalse( $op->mNoGallery
);
1833 private static $parserOutputHookCalled;
1836 * @covers OutputPage::addParserOutputMetadata
1838 public function testParserOutputHooks() {
1839 $op = $this->newInstance();
1840 $pOut = $this->createParserOutputStub( 'getOutputHooks', [
1841 [ 'myhook', 'banana' ],
1842 [ 'yourhook', 'kumquat' ],
1843 [ 'theirhook', 'hippopotamus' ],
1846 self
::$parserOutputHookCalled = [];
1848 $this->setMwGlobals( 'wgParserOutputHooks', [
1849 'myhook' => function ( OutputPage
$innerOp, ParserOutput
$innerPOut, $data )
1850 use ( $op, $pOut ) {
1851 $this->assertSame( $op, $innerOp );
1852 $this->assertSame( $pOut, $innerPOut );
1853 $this->assertSame( 'banana', $data );
1854 self
::$parserOutputHookCalled[] = 'closure';
1856 'yourhook' => [ $this, 'parserOutputHookCallback' ],
1857 'theirhook' => [ __CLASS__
, 'parserOutputHookCallbackStatic' ],
1858 'uncalled' => function () {
1859 $this->assertTrue( false );
1863 $op->addParserOutputMetadata( $pOut );
1865 $this->assertSame( [ 'closure', 'callback', 'static' ], self
::$parserOutputHookCalled );
1868 public function parserOutputHookCallback(
1869 OutputPage
$op, ParserOutput
$pOut, $data
1871 $this->assertSame( 'kumquat', $data );
1873 self
::$parserOutputHookCalled[] = 'callback';
1876 public static function parserOutputHookCallbackStatic(
1877 OutputPage
$op, ParserOutput
$pOut, $data
1879 // All the assert methods are actually static, who knew!
1880 self
::assertSame( 'hippopotamus', $data );
1882 self
::$parserOutputHookCalled[] = 'static';
1885 // @todo Make sure to test the following in addParserOutputMetadata() as well when we add tests
1888 // * addModuleStyles()
1889 // * addJsConfigVars()
1891 // Otherwise those lines of addParserOutputMetadata() will be reported as covered, but we won't
1892 // be testing they actually work.
1895 * @covers OutputPage::addParserOutputText
1897 public function testAddParserOutputText() {
1898 $op = $this->newInstance();
1899 $this->assertSame( '', $op->getHTML() );
1901 $pOut = $this->createParserOutputStub( 'getText', '<some text>' );
1903 $op->addParserOutputMetadata( $pOut );
1904 $this->assertSame( '', $op->getHTML() );
1906 $op->addParserOutputText( $pOut );
1907 $this->assertSame( '<some text>', $op->getHTML() );
1911 * @covers OutputPage::addParserOutput
1913 public function testAddParserOutput() {
1914 $op = $this->newInstance();
1915 $this->assertSame( '', $op->getHTML() );
1916 $this->assertFalse( $op->showNewSectionLink() );
1918 $pOut = $this->createParserOutputStub( [
1919 'getText' => '<some text>',
1920 'getNewSection' => true,
1923 $op->addParserOutput( $pOut );
1924 $this->assertSame( '<some text>', $op->getHTML() );
1925 $this->assertTrue( $op->showNewSectionLink() );
1929 * @covers OutputPage::addTemplate
1931 public function testAddTemplate() {
1932 $template = $this->getMock( QuickTemplate
::class );
1933 $template->method( 'getHTML' )->willReturn( '<abc>&def;' );
1935 $op = $this->newInstance();
1936 $op->addTemplate( $template );
1938 $this->assertSame( '<abc>&def;', $op->getHTML() );
1942 * @dataProvider provideParse
1943 * @covers OutputPage::parse
1944 * @param array $args To pass to parse()
1945 * @param string $expectedHTML Expected return value for parse()
1946 * @param string $expectedHTML Expected return value for parseInline(), if different
1948 public function testParse( array $args, $expectedHTML ) {
1949 $this->hideDeprecated( 'OutputPage::parse' );
1950 $op = $this->newInstance();
1951 $this->assertSame( $expectedHTML, $op->parse( ...$args ) );
1955 * @dataProvider provideParse
1956 * @covers OutputPage::parseInline
1958 public function testParseInline( array $args, $expectedHTML, $expectedHTMLInline = null ) {
1959 if ( count( $args ) > 3 ) {
1960 // $language param not supported
1961 $this->assertTrue( true );
1964 $this->hideDeprecated( 'OutputPage::parseInline' );
1965 $op = $this->newInstance();
1966 $this->assertSame( $expectedHTMLInline ??
$expectedHTML, $op->parseInline( ...$args ) );
1969 public function provideParse() {
1971 'List at start of line (content)' => [
1972 [ '* List', true, false ],
1973 "<div class=\"mw-parser-output\"><ul><li>List</li></ul></div>",
1974 "<ul><li>List</li></ul>",
1976 'List at start of line (interface)' => [
1977 [ '* List', true, true ],
1978 "<ul><li>List</li></ul>",
1980 'List not at start (content)' => [
1981 [ "* ''Not'' list", false, false ],
1982 '<div class="mw-parser-output">* <i>Not</i> list</div>',
1983 '* <i>Not</i> list',
1985 'List not at start (interface)' => [
1986 [ "* ''Not'' list", false, true ],
1987 '* <i>Not</i> list',
1989 'Interface message' => [
1990 [ "''Italic''", true, true ],
1991 "<p><i>Italic</i>\n</p>",
1994 'formatnum (content)' => [
1995 [ '{{formatnum:123456.789}}', true, false ],
1996 "<div class=\"mw-parser-output\"><p>123,456.789\n</p></div>",
1999 'formatnum (interface)' => [
2000 [ '{{formatnum:123456.789}}', true, true ],
2001 "<p>123,456.789\n</p>",
2004 'Language (content)' => [
2005 [ '{{formatnum:123456.789}}', true, false, Language
::factory( 'is' ) ],
2006 "<div class=\"mw-parser-output\"><p>123.456,789\n</p></div>",
2008 'Language (interface)' => [
2009 [ '{{formatnum:123456.789}}', true, true, Language
::factory( 'is' ) ],
2010 "<p>123.456,789\n</p>",
2013 'No section edit links' => [
2015 '<div class="mw-parser-output"><h2><span class="mw-headline" id="Header">' .
2016 "Header</span></h2></div>",
2017 '<h2><span class="mw-headline" id="Header">Header</span></h2>',
2023 * @dataProvider provideParseAs
2024 * @covers OutputPage::parseAsContent
2025 * @param array $args To pass to parse()
2026 * @param string $expectedHTML Expected return value for parseAsContent()
2027 * @param string $expectedHTML Expected return value for parseInlineAsInterface(), if different
2029 public function testParseAsContent(
2030 array $args, $expectedHTML, $expectedHTMLInline = null
2032 $op = $this->newInstance();
2033 $this->assertSame( $expectedHTML, $op->parseAsContent( ...$args ) );
2037 * @dataProvider provideParseAs
2038 * @covers OutputPage::parseAsInterface
2039 * @param array $args To pass to parse()
2040 * @param string $expectedHTML Expected return value for parseAsInterface()
2041 * @param string $expectedHTML Expected return value for parseInlineAsInterface(), if different
2043 public function testParseAsInterface(
2044 array $args, $expectedHTML, $expectedHTMLInline = null
2046 $op = $this->newInstance();
2047 $this->assertSame( $expectedHTML, $op->parseAsInterface( ...$args ) );
2051 * @dataProvider provideParseAs
2052 * @covers OutputPage::parseInlineAsInterface
2054 public function testParseInlineAsInterface(
2055 array $args, $expectedHTML, $expectedHTMLInline = null
2057 $op = $this->newInstance();
2059 $expectedHTMLInline ??
$expectedHTML,
2060 $op->parseInlineAsInterface( ...$args )
2064 public function provideParseAs() {
2066 'List at start of line' => [
2068 "<ul><li>List</li></ul>",
2070 'List not at start' => [
2071 [ "* ''Not'' list", false ],
2072 '<p>* <i>Not</i> list</p>',
2073 '* <i>Not</i> list',
2076 [ "''Italic''", true ],
2077 "<p><i>Italic</i>\n</p>",
2081 [ '{{formatnum:123456.789}}', true ],
2082 "<p>123,456.789\n</p>",
2085 'No section edit links' => [
2087 '<h2><span class="mw-headline" id="Header">Header</span></h2>',
2093 * @covers OutputPage::parse
2095 public function testParseNullTitle() {
2096 $this->hideDeprecated( 'OutputPage::parse' );
2097 $this->setExpectedException( MWException
::class, 'Empty $mTitle in OutputPage::parseInternal' );
2098 $op = $this->newInstance( [], null, 'notitle' );
2103 * @covers OutputPage::parseInline
2105 public function testParseInlineNullTitle() {
2106 $this->hideDeprecated( 'OutputPage::parseInline' );
2107 $this->setExpectedException( MWException
::class, 'Empty $mTitle in OutputPage::parseInternal' );
2108 $op = $this->newInstance( [], null, 'notitle' );
2109 $op->parseInline( '' );
2113 * @covers OutputPage::parseAsContent
2115 public function testParseAsContentNullTitle() {
2116 $this->setExpectedException( MWException
::class, 'Empty $mTitle in OutputPage::parseInternal' );
2117 $op = $this->newInstance( [], null, 'notitle' );
2118 $op->parseAsContent( '' );
2122 * @covers OutputPage::parseAsInterface
2124 public function testParseAsInterfaceNullTitle() {
2125 $this->setExpectedException( MWException
::class, 'Empty $mTitle in OutputPage::parseInternal' );
2126 $op = $this->newInstance( [], null, 'notitle' );
2127 $op->parseAsInterface( '' );
2131 * @covers OutputPage::parseInlineAsInterface
2133 public function testParseInlineAsInterfaceNullTitle() {
2134 $this->setExpectedException( MWException
::class, 'Empty $mTitle in OutputPage::parseInternal' );
2135 $op = $this->newInstance( [], null, 'notitle' );
2136 $op->parseInlineAsInterface( '' );
2140 * @covers OutputPage::setCdnMaxage
2141 * @covers OutputPage::lowerCdnMaxage
2143 public function testCdnMaxage() {
2144 $op = $this->newInstance();
2145 $wrapper = TestingAccessWrapper
::newFromObject( $op );
2146 $this->assertSame( 0, $wrapper->mCdnMaxage
);
2148 $op->setCdnMaxage( -1 );
2149 $this->assertSame( -1, $wrapper->mCdnMaxage
);
2151 $op->setCdnMaxage( 120 );
2152 $this->assertSame( 120, $wrapper->mCdnMaxage
);
2154 $op->setCdnMaxage( 60 );
2155 $this->assertSame( 60, $wrapper->mCdnMaxage
);
2157 $op->setCdnMaxage( 180 );
2158 $this->assertSame( 180, $wrapper->mCdnMaxage
);
2160 $op->lowerCdnMaxage( 240 );
2161 $this->assertSame( 180, $wrapper->mCdnMaxage
);
2163 $op->setCdnMaxage( 300 );
2164 $this->assertSame( 240, $wrapper->mCdnMaxage
);
2166 $op->lowerCdnMaxage( 120 );
2167 $this->assertSame( 120, $wrapper->mCdnMaxage
);
2169 $op->setCdnMaxage( 180 );
2170 $this->assertSame( 120, $wrapper->mCdnMaxage
);
2172 $op->setCdnMaxage( 60 );
2173 $this->assertSame( 60, $wrapper->mCdnMaxage
);
2175 $op->setCdnMaxage( 240 );
2176 $this->assertSame( 120, $wrapper->mCdnMaxage
);
2179 /** @var int Faked time to set for tests that need it */
2180 private static $fakeTime;
2183 * @dataProvider provideAdaptCdnTTL
2184 * @covers OutputPage::adaptCdnTTL
2185 * @param array $args To pass to adaptCdnTTL()
2186 * @param int $expected Expected new value of mCdnMaxageLimit
2187 * @param array $options Associative array:
2188 * initialMaxage => Maxage to set before calling adaptCdnTTL() (default 86400)
2190 public function testAdaptCdnTTL( array $args, $expected, array $options = [] ) {
2192 MWTimestamp
::setFakeTime( self
::$fakeTime );
2194 $op = $this->newInstance();
2195 // Set a high maxage so that it will get reduced by adaptCdnTTL(). The default maxage
2196 // is 0, so adaptCdnTTL() won't mutate the object at all.
2197 $initial = $options['initialMaxage'] ??
86400;
2198 $op->setCdnMaxage( $initial );
2200 $op->adaptCdnTTL( ...$args );
2202 MWTimestamp
::setFakeTime( false );
2205 $wrapper = TestingAccessWrapper
::newFromObject( $op );
2207 // Special rules for false/null
2208 if ( $args[0] === null ||
$args[0] === false ) {
2209 $this->assertSame( $initial, $wrapper->mCdnMaxage
, 'member value' );
2210 $op->setCdnMaxage( $expected +
1 );
2211 $this->assertSame( $expected +
1, $wrapper->mCdnMaxage
, 'member value after new set' );
2215 $this->assertSame( $expected, $wrapper->mCdnMaxageLimit
, 'limit value' );
2217 if ( $initial >= $expected ) {
2218 $this->assertSame( $expected, $wrapper->mCdnMaxage
, 'member value' );
2220 $this->assertSame( $initial, $wrapper->mCdnMaxage
, 'member value' );
2223 $op->setCdnMaxage( $expected +
1 );
2224 $this->assertSame( $expected, $wrapper->mCdnMaxage
, 'member value after new set' );
2227 public function provideAdaptCdnTTL() {
2228 global $wgSquidMaxage;
2230 self
::$fakeTime = $now;
2232 'Five minutes ago' => [ [ $now - 300 ], 270 ],
2233 'Now' => [ [ +
0 ], IExpiringStore
::TTL_MINUTE
],
2234 'Five minutes from now' => [ [ $now +
300 ], IExpiringStore
::TTL_MINUTE
],
2235 'Five minutes ago, initial maxage four minutes' =>
2236 [ [ $now - 300 ], 270, [ 'initialMaxage' => 240 ] ],
2237 'A very long time ago' => [ [ $now - 1000000000 ], $wgSquidMaxage ],
2238 'Initial maxage zero' => [ [ $now - 300 ], 270, [ 'initialMaxage' => 0 ] ],
2240 'false' => [ [ false ], IExpiringStore
::TTL_MINUTE
],
2241 'null' => [ [ null ], IExpiringStore
::TTL_MINUTE
],
2242 "'0'" => [ [ '0' ], IExpiringStore
::TTL_MINUTE
],
2243 'Empty string' => [ [ '' ], IExpiringStore
::TTL_MINUTE
],
2244 // @todo These give incorrect results due to timezones, how to test?
2245 //"'now'" => [ [ 'now' ], IExpiringStore::TTL_MINUTE ],
2246 //"'parse error'" => [ [ 'parse error' ], IExpiringStore::TTL_MINUTE ],
2248 'Now, minTTL 0' => [ [ $now, 0 ], IExpiringStore
::TTL_MINUTE
],
2249 'Now, minTTL 0.000001' => [ [ $now, 0.000001 ], 0 ],
2250 'A very long time ago, maxTTL even longer' =>
2251 [ [ $now - 1000000000, 0, 1000000001 ], 900000000 ],
2256 * @covers OutputPage::enableClientCache
2257 * @covers OutputPage::addParserOutputMetadata
2258 * @covers OutputPage::addParserOutput
2260 public function testClientCache() {
2261 $op = $this->newInstance();
2263 // Test initial value
2264 $this->assertSame( true, $op->enableClientCache( null ) );
2265 // Test that calling with null doesn't change the value
2266 $this->assertSame( true, $op->enableClientCache( null ) );
2268 // Test setting to false
2269 $this->assertSame( true, $op->enableClientCache( false ) );
2270 $this->assertSame( false, $op->enableClientCache( null ) );
2271 // Test that calling with null doesn't change the value
2272 $this->assertSame( false, $op->enableClientCache( null ) );
2274 // Test that a cacheable ParserOutput doesn't set to true
2275 $pOutCacheable = $this->createParserOutputStub( 'isCacheable', true );
2276 $op->addParserOutputMetadata( $pOutCacheable );
2277 $this->assertSame( false, $op->enableClientCache( null ) );
2279 // Test setting back to true
2280 $this->assertSame( false, $op->enableClientCache( true ) );
2281 $this->assertSame( true, $op->enableClientCache( null ) );
2283 // Test that an uncacheable ParserOutput does set to false
2284 $pOutUncacheable = $this->createParserOutputStub( 'isCacheable', false );
2285 $op->addParserOutput( $pOutUncacheable );
2286 $this->assertSame( false, $op->enableClientCache( null ) );
2290 * @covers OutputPage::getCacheVaryCookies
2292 public function testGetCacheVaryCookies() {
2293 global $wgCookiePrefix, $wgDBname;
2294 $op = $this->newInstance();
2295 $prefix = $wgCookiePrefix !== false ?
$wgCookiePrefix : $wgDBname;
2296 $expectedCookies = [
2298 "{$prefix}LoggedOut",
2299 "{$prefix}_session",
2305 // We have to reset the cookies because getCacheVaryCookies may have already been called
2306 TestingAccessWrapper
::newFromClass( OutputPage
::class )->cacheVaryCookies
= null;
2308 $this->setMwGlobals( 'wgCacheVaryCookies', [ 'cookie1' ] );
2309 $this->setTemporaryHook( 'GetCacheVaryCookies',
2310 function ( $innerOP, &$cookies ) use ( $op, $expectedCookies ) {
2311 $this->assertSame( $op, $innerOP );
2312 $cookies[] = 'cookie2';
2313 $this->assertSame( $expectedCookies, $cookies );
2317 $this->assertSame( $expectedCookies, $op->getCacheVaryCookies() );
2321 * @covers OutputPage::haveCacheVaryCookies
2323 public function testHaveCacheVaryCookies() {
2324 $request = new FauxRequest();
2325 $op = $this->newInstance( [], $request );
2327 // No cookies are set.
2328 $this->assertFalse( $op->haveCacheVaryCookies() );
2330 // 'Token' is present but empty, so it shouldn't count.
2331 $request->setCookie( 'Token', '' );
2332 $this->assertFalse( $op->haveCacheVaryCookies() );
2334 // 'Token' present and nonempty.
2335 $request->setCookie( 'Token', '123' );
2336 $this->assertTrue( $op->haveCacheVaryCookies() );
2340 * @dataProvider provideVaryHeaders
2342 * @covers OutputPage::addVaryHeader
2343 * @covers OutputPage::getVaryHeader
2344 * @covers OutputPage::getKeyHeader
2346 * @param array[] $calls For each array, call addVaryHeader() with those arguments
2347 * @param string[] $cookies Array of cookie names to vary on
2348 * @param string $vary Text of expected Vary header (including the 'Vary: ')
2349 * @param string $key Text of expected Key header (including the 'Key: ')
2351 public function testVaryHeaders( array $calls, array $cookies, $vary, $key ) {
2352 // Get rid of default Vary fields
2353 $op = $this->getMockBuilder( OutputPage
::class )
2354 ->setConstructorArgs( [ new RequestContext() ] )
2355 ->setMethods( [ 'getCacheVaryCookies' ] )
2357 $op->expects( $this->any() )
2358 ->method( 'getCacheVaryCookies' )
2359 ->will( $this->returnValue( $cookies ) );
2360 TestingAccessWrapper
::newFromObject( $op )->mVaryHeader
= [];
2362 $this->hideDeprecated( '$wgUseKeyHeader' );
2363 foreach ( $calls as $call ) {
2364 $op->addVaryHeader( ...$call );
2366 $this->assertEquals( $vary, $op->getVaryHeader(), 'Vary:' );
2367 $this->assertEquals( $key, $op->getKeyHeader(), 'Key:' );
2370 public function provideVaryHeaders() {
2371 // note: getKeyHeader() automatically adds Vary: Cookie
2379 'Single header' => [
2387 'Non-unique headers' => [
2390 [ 'Accept-Language' ],
2394 'Vary: Cookie, Accept-Language',
2395 'Key: Cookie,Accept-Language',
2397 'Two headers with single options' => [
2399 [ 'Cookie', [ 'param=phpsessid' ] ],
2400 [ 'Accept-Language', [ 'substr=en' ] ],
2403 'Vary: Cookie, Accept-Language',
2404 'Key: Cookie;param=phpsessid,Accept-Language;substr=en',
2406 'One header with multiple options' => [
2408 [ 'Cookie', [ 'param=phpsessid', 'param=userId' ] ],
2412 'Key: Cookie;param=phpsessid;param=userId',
2414 'Duplicate option' => [
2416 [ 'Cookie', [ 'param=phpsessid' ] ],
2417 [ 'Cookie', [ 'param=phpsessid' ] ],
2418 [ 'Accept-Language', [ 'substr=en', 'substr=en' ] ],
2421 'Vary: Cookie, Accept-Language',
2422 'Key: Cookie;param=phpsessid,Accept-Language;substr=en',
2424 'Same header, different options' => [
2426 [ 'Cookie', [ 'param=phpsessid' ] ],
2427 [ 'Cookie', [ 'param=userId' ] ],
2431 'Key: Cookie;param=phpsessid;param=userId',
2433 'No header, vary cookies' => [
2435 [ 'cookie1', 'cookie2' ],
2437 'Key: Cookie;param=cookie1;param=cookie2',
2439 'Cookie header with option plus vary cookies' => [
2441 [ 'Cookie', [ 'param=cookie1' ] ],
2443 [ 'cookie2', 'cookie3' ],
2445 'Key: Cookie;param=cookie1;param=cookie2;param=cookie3',
2447 'Non-cookie header plus vary cookies' => [
2449 [ 'Accept-Language' ],
2452 'Vary: Accept-Language, Cookie',
2453 'Key: Accept-Language,Cookie;param=cookie',
2455 'Cookie and non-cookie headers plus vary cookies' => [
2457 [ 'Cookie', [ 'param=cookie1' ] ],
2458 [ 'Accept-Language' ],
2461 'Vary: Cookie, Accept-Language',
2462 'Key: Cookie;param=cookie1;param=cookie2,Accept-Language',
2468 * @covers OutputPage::getVaryHeader
2470 public function testVaryHeaderDefault() {
2471 $op = $this->newInstance();
2472 $this->assertSame( 'Vary: Accept-Encoding, Cookie', $op->getVaryHeader() );
2476 * @dataProvider provideLinkHeaders
2478 * @covers OutputPage::addLinkHeader
2479 * @covers OutputPage::getLinkHeader
2481 public function testLinkHeaders( array $headers, $result ) {
2482 $op = $this->newInstance();
2484 foreach ( $headers as $header ) {
2485 $op->addLinkHeader( $header );
2488 $this->assertEquals( $result, $op->getLinkHeader() );
2491 public function provideLinkHeaders() {
2498 [ '<https://foo/bar.jpg>;rel=preload;as=image' ],
2499 'Link: <https://foo/bar.jpg>;rel=preload;as=image',
2503 '<https://foo/bar.jpg>;rel=preload;as=image',
2504 '<https://foo/baz.jpg>;rel=preload;as=image'
2506 'Link: <https://foo/bar.jpg>;rel=preload;as=image,<https://foo/baz.jpg>;' .
2507 'rel=preload;as=image',
2513 * @dataProvider provideAddAcceptLanguage
2514 * @covers OutputPage::addAcceptLanguage
2515 * @covers OutputPage::getKeyHeader
2517 public function testAddAcceptLanguage(
2518 $code, array $variants, array $expected, array $options = []
2520 $req = new FauxRequest( in_array( 'varianturl', $options ) ?
[ 'variant' => 'x' ] : [] );
2521 $op = $this->newInstance( [], $req, in_array( 'notitle', $options ) ?
'notitle' : null );
2523 if ( !in_array( 'notitle', $options ) ) {
2524 $mockLang = $this->getMock( Language
::class );
2526 if ( in_array( 'varianturl', $options ) ) {
2527 $mockLang->expects( $this->never() )->method( $this->anything() );
2529 $mockLang->method( 'hasVariants' )->willReturn( count( $variants ) > 1 );
2530 $mockLang->method( 'getVariants' )->willReturn( $variants );
2531 $mockLang->method( 'getCode' )->willReturn( $code );
2534 $mockTitle = $this->getMock( Title
::class );
2535 $mockTitle->method( 'getPageLanguage' )->willReturn( $mockLang );
2537 $op->setTitle( $mockTitle );
2540 // This will run addAcceptLanguage()
2541 $op->sendCacheControl();
2543 $this->hideDeprecated( '$wgUseKeyHeader' );
2544 $keyHeader = $op->getKeyHeader();
2547 $this->assertFalse( strpos( 'Accept-Language', $keyHeader ) );
2551 $keyHeader = explode( ' ', $keyHeader, 2 )[1];
2552 $keyHeader = explode( ',', $keyHeader );
2554 $acceptLanguage = null;
2555 foreach ( $keyHeader as $item ) {
2556 if ( strpos( $item, 'Accept-Language;' ) === 0 ) {
2557 $acceptLanguage = $item;
2562 $expectedString = 'Accept-Language;substr=' . implode( ';substr=', $expected );
2563 $this->assertSame( $expectedString, $acceptLanguage );
2566 public function provideAddAcceptLanguage() {
2568 'No variants' => [ 'en', [ 'en' ], [] ],
2569 'One simple variant' => [ 'en', [ 'en', 'en-x-piglatin' ], [ 'en-x-piglatin' ] ],
2570 'Multiple variants with BCP47 alternatives' => [
2572 [ 'zh', 'zh-hans', 'zh-cn', 'zh-tw' ],
2573 [ 'zh-hans', 'zh-Hans', 'zh-cn', 'zh-Hans-CN', 'zh-tw', 'zh-Hant-TW' ],
2575 'No title' => [ 'en', [ 'en', 'en-x-piglatin' ], [], [ 'notitle' ] ],
2576 'Variant in URL' => [ 'en', [ 'en', 'en-x-piglatin' ], [], [ 'varianturl' ] ],
2581 * @covers OutputPage::preventClickjacking
2582 * @covers OutputPage::allowClickjacking
2583 * @covers OutputPage::getPreventClickjacking
2584 * @covers OutputPage::addParserOutputMetadata
2585 * @covers OutputPage::addParserOutput
2587 public function testClickjacking() {
2588 $op = $this->newInstance();
2589 $this->assertTrue( $op->getPreventClickjacking() );
2591 $op->allowClickjacking();
2592 $this->assertFalse( $op->getPreventClickjacking() );
2594 $op->preventClickjacking();
2595 $this->assertTrue( $op->getPreventClickjacking() );
2597 $op->preventClickjacking( false );
2598 $this->assertFalse( $op->getPreventClickjacking() );
2600 $pOut1 = $this->createParserOutputStub( 'preventClickjacking', true );
2601 $op->addParserOutputMetadata( $pOut1 );
2602 $this->assertTrue( $op->getPreventClickjacking() );
2604 // The ParserOutput can't allow, only prevent
2605 $pOut2 = $this->createParserOutputStub( 'preventClickjacking', false );
2606 $op->addParserOutputMetadata( $pOut2 );
2607 $this->assertTrue( $op->getPreventClickjacking() );
2609 // Reset to test with addParserOutput()
2610 $op->allowClickjacking();
2611 $this->assertFalse( $op->getPreventClickjacking() );
2613 $op->addParserOutput( $pOut1 );
2614 $this->assertTrue( $op->getPreventClickjacking() );
2616 $op->addParserOutput( $pOut2 );
2617 $this->assertTrue( $op->getPreventClickjacking() );
2621 * @dataProvider provideGetFrameOptions
2622 * @covers OutputPage::getFrameOptions
2623 * @covers OutputPage::preventClickjacking
2625 public function testGetFrameOptions(
2626 $breakFrames, $preventClickjacking, $editPageFrameOptions, $expected
2628 $op = $this->newInstance( [
2629 'BreakFrames' => $breakFrames,
2630 'EditPageFrameOptions' => $editPageFrameOptions,
2632 $op->preventClickjacking( $preventClickjacking );
2634 $this->assertSame( $expected, $op->getFrameOptions() );
2637 public function provideGetFrameOptions() {
2639 'BreakFrames true' => [ true, false, false, 'DENY' ],
2640 'Allow clickjacking locally' => [ false, false, 'DENY', false ],
2641 'Allow clickjacking globally' => [ false, true, false, false ],
2642 'DENY globally' => [ false, true, 'DENY', 'DENY' ],
2643 'SAMEORIGIN' => [ false, true, 'SAMEORIGIN', 'SAMEORIGIN' ],
2644 'BreakFrames with SAMEORIGIN' => [ true, true, 'SAMEORIGIN', 'DENY' ],
2649 * See ResourceLoaderClientHtmlTest for full coverage.
2651 * @dataProvider provideMakeResourceLoaderLink
2653 * @covers OutputPage::makeResourceLoaderLink
2655 public function testMakeResourceLoaderLink( $args, $expectedHtml ) {
2656 $this->setMwGlobals( [
2657 'wgResourceLoaderDebug' => false,
2658 'wgLoadScript' => 'http://127.0.0.1:8080/w/load.php',
2659 'wgCSPReportOnlyHeader' => true,
2661 $class = new ReflectionClass( OutputPage
::class );
2662 $method = $class->getMethod( 'makeResourceLoaderLink' );
2663 $method->setAccessible( true );
2664 $ctx = new RequestContext();
2665 $ctx->setSkin( SkinFactory
::getDefaultInstance()->makeSkin( 'fallback' ) );
2666 $ctx->setLanguage( 'en' );
2667 $out = new OutputPage( $ctx );
2668 $nonce = $class->getProperty( 'CSPNonce' );
2669 $nonce->setAccessible( true );
2670 $nonce->setValue( $out, 'secret' );
2671 $rl = $out->getResourceLoader();
2672 $rl->setMessageBlobStore( $this->createMock( MessageBlobStore
::class ) );
2674 'test.foo' => new ResourceLoaderTestModule( [
2675 'script' => 'mw.test.foo( { a: true } );',
2676 'styles' => '.mw-test-foo { content: "style"; }',
2678 'test.bar' => new ResourceLoaderTestModule( [
2679 'script' => 'mw.test.bar( { a: true } );',
2680 'styles' => '.mw-test-bar { content: "style"; }',
2682 'test.baz' => new ResourceLoaderTestModule( [
2683 'script' => 'mw.test.baz( { a: true } );',
2684 'styles' => '.mw-test-baz { content: "style"; }',
2686 'test.quux' => new ResourceLoaderTestModule( [
2687 'script' => 'mw.test.baz( { token: 123 } );',
2688 'styles' => '/* pref-animate=off */ .mw-icon { transition: none; }',
2689 'group' => 'private',
2691 'test.noscript' => new ResourceLoaderTestModule( [
2692 'styles' => '.stuff { color: red; }',
2693 'group' => 'noscript',
2695 'test.group.foo' => new ResourceLoaderTestModule( [
2696 'script' => 'mw.doStuff( "foo" );',
2699 'test.group.bar' => new ResourceLoaderTestModule( [
2700 'script' => 'mw.doStuff( "bar" );',
2704 $links = $method->invokeArgs( $out, $args );
2705 $actualHtml = strval( $links );
2706 $this->assertEquals( $expectedHtml, $actualHtml );
2709 public static function provideMakeResourceLoaderLink() {
2710 // phpcs:disable Generic.Files.LineLength
2712 // Single only=scripts load
2714 [ 'test.foo', ResourceLoaderModule
::TYPE_SCRIPTS
],
2715 "<script nonce=\"secret\">(RLQ=window.RLQ||[]).push(function(){"
2716 . 'mw.loader.load("http://127.0.0.1:8080/w/load.php?lang=en\u0026modules=test.foo\u0026only=scripts\u0026skin=fallback");'
2719 // Multiple only=styles load
2721 [ [ 'test.baz', 'test.foo', 'test.bar' ], ResourceLoaderModule
::TYPE_STYLES
],
2723 '<link rel="stylesheet" href="http://127.0.0.1:8080/w/load.php?lang=en&modules=test.bar%2Cbaz%2Cfoo&only=styles&skin=fallback"/>'
2725 // Private embed (only=scripts)
2727 [ 'test.quux', ResourceLoaderModule
::TYPE_SCRIPTS
],
2728 "<script nonce=\"secret\">(RLQ=window.RLQ||[]).push(function(){"
2729 . "mw.test.baz({token:123});\nmw.loader.state({\"test.quux\":\"ready\"});"
2732 // Load private module (combined)
2734 [ 'test.quux', ResourceLoaderModule
::TYPE_COMBINED
],
2735 "<script nonce=\"secret\">(RLQ=window.RLQ||[]).push(function(){"
2736 . "mw.loader.implement(\"test.quux@1ev0ijv\",function($,jQuery,require,module){"
2737 . "mw.test.baz({token:123});},{\"css\":[\".mw-icon{transition:none}"
2738 . "\"]});});</script>"
2742 [ [], ResourceLoaderModule
::TYPE_COMBINED
],
2747 [ 'test.noscript', ResourceLoaderModule
::TYPE_STYLES
],
2748 '<noscript><link rel="stylesheet" href="http://127.0.0.1:8080/w/load.php?lang=en&modules=test.noscript&only=styles&skin=fallback"/></noscript>'
2750 // Load two modules in separate groups
2752 [ [ 'test.group.foo', 'test.group.bar' ], ResourceLoaderModule
::TYPE_COMBINED
],
2753 "<script nonce=\"secret\">(RLQ=window.RLQ||[]).push(function(){"
2754 . 'mw.loader.load("http://127.0.0.1:8080/w/load.php?lang=en\u0026modules=test.group.bar\u0026skin=fallback");'
2755 . 'mw.loader.load("http://127.0.0.1:8080/w/load.php?lang=en\u0026modules=test.group.foo\u0026skin=fallback");'
2763 * @dataProvider provideBuildExemptModules
2765 * @covers OutputPage::buildExemptModules
2767 public function testBuildExemptModules( array $exemptStyleModules, $expect ) {
2768 $this->setMwGlobals( [
2769 'wgResourceLoaderDebug' => false,
2770 'wgLoadScript' => '/w/load.php',
2771 // Stub wgCacheEpoch as it influences getVersionHash used for the
2772 // urls in the expected HTML
2773 'wgCacheEpoch' => '20140101000000',
2777 $ctx = new RequestContext();
2778 $ctx->setSkin( SkinFactory
::getDefaultInstance()->makeSkin( 'fallback' ) );
2779 $ctx->setLanguage( 'en' );
2780 $op = $this->getMockBuilder( OutputPage
::class )
2781 ->setConstructorArgs( [ $ctx ] )
2782 ->setMethods( [ 'buildCssLinksArray' ] )
2784 $op->expects( $this->any() )
2785 ->method( 'buildCssLinksArray' )
2787 $rl = $op->getResourceLoader();
2788 $rl->setMessageBlobStore( $this->createMock( MessageBlobStore
::class ) );
2790 // Register custom modules
2792 'example.site.a' => new ResourceLoaderTestModule( [ 'group' => 'site' ] ),
2793 'example.site.b' => new ResourceLoaderTestModule( [ 'group' => 'site' ] ),
2794 'example.user' => new ResourceLoaderTestModule( [ 'group' => 'user' ] ),
2797 $op = TestingAccessWrapper
::newFromObject( $op );
2798 $op->rlExemptStyleModules
= $exemptStyleModules;
2799 $this->assertEquals(
2801 strval( $op->buildExemptModules() )
2805 public static function provideBuildExemptModules() {
2806 // phpcs:disable Generic.Files.LineLength
2809 'exemptStyleModules' => [],
2810 '<meta name="ResourceLoaderDynamicStyles" content=""/>',
2813 'exemptStyleModules' => [ 'site' => [], 'noscript' => [], 'private' => [], 'user' => [] ],
2814 '<meta name="ResourceLoaderDynamicStyles" content=""/>',
2816 'default logged-out' => [
2817 'exemptStyleModules' => [ 'site' => [ 'site.styles' ] ],
2818 '<meta name="ResourceLoaderDynamicStyles" content=""/>' . "\n" .
2819 '<link rel="stylesheet" href="/w/load.php?lang=en&modules=site.styles&only=styles&skin=fallback"/>',
2821 'default logged-in' => [
2822 'exemptStyleModules' => [ 'site' => [ 'site.styles' ], 'user' => [ 'user.styles' ] ],
2823 '<meta name="ResourceLoaderDynamicStyles" content=""/>' . "\n" .
2824 '<link rel="stylesheet" href="/w/load.php?lang=en&modules=site.styles&only=styles&skin=fallback"/>' . "\n" .
2825 '<link rel="stylesheet" href="/w/load.php?lang=en&modules=user.styles&only=styles&skin=fallback&version=1ai9g6t"/>',
2827 'custom modules' => [
2828 'exemptStyleModules' => [
2829 'site' => [ 'site.styles', 'example.site.a', 'example.site.b' ],
2830 'user' => [ 'user.styles', 'example.user' ],
2832 '<meta name="ResourceLoaderDynamicStyles" content=""/>' . "\n" .
2833 '<link rel="stylesheet" href="/w/load.php?lang=en&modules=example.site.a%2Cb&only=styles&skin=fallback"/>' . "\n" .
2834 '<link rel="stylesheet" href="/w/load.php?lang=en&modules=site.styles&only=styles&skin=fallback"/>' . "\n" .
2835 '<link rel="stylesheet" href="/w/load.php?lang=en&modules=example.user&only=styles&skin=fallback&version=0a56zyi"/>' . "\n" .
2836 '<link rel="stylesheet" href="/w/load.php?lang=en&modules=user.styles&only=styles&skin=fallback&version=1ai9g6t"/>',
2843 * @dataProvider provideTransformFilePath
2844 * @covers OutputPage::transformFilePath
2845 * @covers OutputPage::transformResourcePath
2847 public function testTransformResourcePath( $baseDir, $basePath, $uploadDir = null,
2848 $uploadPath = null, $path = null, $expected = null
2850 if ( $path === null ) {
2851 // Skip optional $uploadDir and $uploadPath
2853 $expected = $uploadPath;
2854 $uploadDir = "$baseDir/images";
2855 $uploadPath = "$basePath/images";
2857 $this->setMwGlobals( 'IP', $baseDir );
2858 $conf = new HashConfig( [
2859 'ResourceBasePath' => $basePath,
2860 'UploadDirectory' => $uploadDir,
2861 'UploadPath' => $uploadPath,
2864 // Some of these paths don't exist and will cause warnings
2865 Wikimedia\
suppressWarnings();
2866 $actual = OutputPage
::transformResourcePath( $conf, $path );
2867 Wikimedia\restoreWarnings
();
2869 $this->assertEquals( $expected ?
: $path, $actual );
2872 public static function provideTransformFilePath() {
2873 $baseDir = dirname( __DIR__
) . '/data/media';
2875 // File that matches basePath, and exists. Hash found and appended.
2877 'baseDir' => $baseDir, 'basePath' => '/w',
2881 // File that matches basePath, but not found on disk. Empty query.
2883 'baseDir' => $baseDir, 'basePath' => '/w',
2887 // File not matching basePath. Ignored.
2889 'baseDir' => $baseDir, 'basePath' => '/w',
2892 // Empty string. Ignored.
2894 'baseDir' => $baseDir, 'basePath' => '/w',
2898 // Similar path, but with domain component. Ignored.
2900 'baseDir' => $baseDir, 'basePath' => '/w',
2901 '//example.org/w/test.jpg'
2904 'baseDir' => $baseDir, 'basePath' => '/w',
2905 'https://example.org/w/test.jpg'
2907 // Unrelated path with domain component. Ignored.
2909 'baseDir' => $baseDir, 'basePath' => '/w',
2910 'https://example.org/files/test.jpg'
2913 'baseDir' => $baseDir, 'basePath' => '/w',
2914 '//example.org/files/test.jpg'
2916 // Unrelated path with domain, and empty base path (root mw install). Ignored.
2918 'baseDir' => $baseDir, 'basePath' => '',
2919 'https://example.org/files/test.jpg'
2922 'baseDir' => $baseDir, 'basePath' => '',
2924 '//example.org/files/test.jpg'
2926 // Check UploadPath before ResourceBasePath (T155146)
2928 'baseDir' => dirname( $baseDir ), 'basePath' => '',
2929 'uploadDir' => $baseDir, 'uploadPath' => '/images',
2931 '/images/test.jpg?edcf2'
2937 * Tests a particular case of transformCssMedia, using the given input, globals,
2938 * expected return, and message
2940 * Asserts that $expectedReturn is returned.
2942 * options['printableQuery'] - value of query string for printable, or omitted for none
2943 * options['handheldQuery'] - value of query string for handheld, or omitted for none
2944 * options['media'] - passed into the method under the same name
2945 * options['expectedReturn'] - expected return value
2946 * options['message'] - PHPUnit message for assertion
2948 * @param array $args Key-value array of arguments as shown above
2950 protected function assertTransformCssMediaCase( $args ) {
2952 if ( isset( $args['printableQuery'] ) ) {
2953 $queryData['printable'] = $args['printableQuery'];
2956 if ( isset( $args['handheldQuery'] ) ) {
2957 $queryData['handheld'] = $args['handheldQuery'];
2960 $fauxRequest = new FauxRequest( $queryData, false );
2961 $this->setMwGlobals( [
2962 'wgRequest' => $fauxRequest,
2965 $actualReturn = OutputPage
::transformCssMedia( $args['media'] );
2966 $this->assertSame( $args['expectedReturn'], $actualReturn, $args['message'] );
2970 * Tests print requests
2972 * @covers OutputPage::transformCssMedia
2974 public function testPrintRequests() {
2975 $this->assertTransformCssMediaCase( [
2976 'printableQuery' => '1',
2977 'media' => 'screen',
2978 'expectedReturn' => null,
2979 'message' => 'On printable request, screen returns null'
2982 $this->assertTransformCssMediaCase( [
2983 'printableQuery' => '1',
2984 'media' => self
::SCREEN_MEDIA_QUERY
,
2985 'expectedReturn' => null,
2986 'message' => 'On printable request, screen media query returns null'
2989 $this->assertTransformCssMediaCase( [
2990 'printableQuery' => '1',
2991 'media' => self
::SCREEN_ONLY_MEDIA_QUERY
,
2992 'expectedReturn' => null,
2993 'message' => 'On printable request, screen media query with only returns null'
2996 $this->assertTransformCssMediaCase( [
2997 'printableQuery' => '1',
2999 'expectedReturn' => '',
3000 'message' => 'On printable request, media print returns empty string'
3005 * Tests screen requests, without either query parameter set
3007 * @covers OutputPage::transformCssMedia
3009 public function testScreenRequests() {
3010 $this->assertTransformCssMediaCase( [
3011 'media' => 'screen',
3012 'expectedReturn' => 'screen',
3013 'message' => 'On screen request, screen media type is preserved'
3016 $this->assertTransformCssMediaCase( [
3017 'media' => 'handheld',
3018 'expectedReturn' => 'handheld',
3019 'message' => 'On screen request, handheld media type is preserved'
3022 $this->assertTransformCssMediaCase( [
3023 'media' => self
::SCREEN_MEDIA_QUERY
,
3024 'expectedReturn' => self
::SCREEN_MEDIA_QUERY
,
3025 'message' => 'On screen request, screen media query is preserved.'
3028 $this->assertTransformCssMediaCase( [
3029 'media' => self
::SCREEN_ONLY_MEDIA_QUERY
,
3030 'expectedReturn' => self
::SCREEN_ONLY_MEDIA_QUERY
,
3031 'message' => 'On screen request, screen media query with only is preserved.'
3034 $this->assertTransformCssMediaCase( [
3036 'expectedReturn' => 'print',
3037 'message' => 'On screen request, print media type is preserved'
3042 * Tests handheld behavior
3044 * @covers OutputPage::transformCssMedia
3046 public function testHandheld() {
3047 $this->assertTransformCssMediaCase( [
3048 'handheldQuery' => '1',
3049 'media' => 'handheld',
3050 'expectedReturn' => '',
3051 'message' => 'On request with handheld querystring and media is handheld, returns empty string'
3054 $this->assertTransformCssMediaCase( [
3055 'handheldQuery' => '1',
3056 'media' => 'screen',
3057 'expectedReturn' => null,
3058 'message' => 'On request with handheld querystring and media is screen, returns null'
3063 * @covers OutputPage::isTOCEnabled
3064 * @covers OutputPage::addParserOutputMetadata
3065 * @covers OutputPage::addParserOutput
3067 public function testIsTOCEnabled() {
3068 $op = $this->newInstance();
3069 $this->assertFalse( $op->isTOCEnabled() );
3071 $pOut1 = $this->createParserOutputStub( 'getTOCHTML', false );
3072 $op->addParserOutputMetadata( $pOut1 );
3073 $this->assertFalse( $op->isTOCEnabled() );
3075 $pOut2 = $this->createParserOutputStub( 'getTOCHTML', true );
3076 $op->addParserOutput( $pOut2 );
3077 $this->assertTrue( $op->isTOCEnabled() );
3079 // The parser output doesn't disable the TOC after it was enabled
3080 $op->addParserOutputMetadata( $pOut1 );
3081 $this->assertTrue( $op->isTOCEnabled() );
3085 * @dataProvider providePreloadLinkHeaders
3086 * @covers ResourceLoaderSkinModule::getPreloadLinks
3087 * @covers ResourceLoaderSkinModule::getLogoPreloadlinks
3089 public function testPreloadLinkHeaders( $config, $result ) {
3090 $this->setMwGlobals( $config );
3091 $ctx = $this->getMockBuilder( ResourceLoaderContext
::class )
3092 ->disableOriginalConstructor()->getMock();
3093 $module = new ResourceLoaderSkinModule();
3095 $this->assertEquals( [ $result ], $module->getHeaders( $ctx ) );
3098 public function providePreloadLinkHeaders() {
3102 'wgResourceBasePath' => '/w',
3103 'wgLogo' => '/img/default.png',
3105 '1.5x' => '/img/one-point-five.png',
3106 '2x' => '/img/two-x.png',
3109 'Link: </img/default.png>;rel=preload;as=image;media=' .
3110 'not all and (min-resolution: 1.5dppx),' .
3111 '</img/one-point-five.png>;rel=preload;as=image;media=' .
3112 '(min-resolution: 1.5dppx) and (max-resolution: 1.999999dppx),' .
3113 '</img/two-x.png>;rel=preload;as=image;media=(min-resolution: 2dppx)'
3117 'wgResourceBasePath' => '/w',
3118 'wgLogo' => '/img/default.png',
3119 'wgLogoHD' => false,
3121 'Link: </img/default.png>;rel=preload;as=image'
3125 'wgResourceBasePath' => '/w',
3126 'wgLogo' => '/img/default.png',
3128 '2x' => '/img/two-x.png',
3131 'Link: </img/default.png>;rel=preload;as=image;media=' .
3132 'not all and (min-resolution: 2dppx),' .
3133 '</img/two-x.png>;rel=preload;as=image;media=(min-resolution: 2dppx)'
3137 'wgResourceBasePath' => '/w',
3138 'wgLogo' => '/img/default.png',
3140 'svg' => '/img/vector.svg',
3143 'Link: </img/vector.svg>;rel=preload;as=image'
3148 'wgResourceBasePath' => '/w',
3149 'wgLogo' => '/w/test.jpg',
3150 'wgLogoHD' => false,
3151 'wgUploadPath' => '/w/images',
3152 'IP' => dirname( __DIR__
) . '/data/media',
3154 'Link: </w/test.jpg?edcf2>;rel=preload;as=image',
3160 * @return OutputPage
3162 private function newInstance( $config = [], WebRequest
$request = null, $options = [] ) {
3163 $context = new RequestContext();
3165 $context->setConfig( new MultiConfig( [
3166 new HashConfig( $config +
[
3167 'AppleTouchIcon' => false,
3168 'DisableLangConversion' => true,
3169 'EnableCanonicalServerLink' => false,
3172 'LanguageCode' => false,
3173 'ReferrerPolicy' => false,
3174 'RightsPage' => false,
3175 'RightsUrl' => false,
3176 'UniversalEditButton' => false,
3178 $context->getConfig()
3181 if ( !in_array( 'notitle', (array)$options ) ) {
3182 $context->setTitle( Title
::newFromText( 'My test page' ) );
3186 $context->setRequest( $request );
3189 return new OutputPage( $context );