3 use MediaWiki\MediaWikiServices
;
4 use Wikimedia\TestingAccessWrapper
;
7 * @author Matthew Flaschen
12 class OutputPageTest
extends MediaWikiTestCase
{
13 const SCREEN_MEDIA_QUERY
= 'screen and (min-width: 982px)';
14 const SCREEN_ONLY_MEDIA_QUERY
= 'only screen and (min-width: 982px)';
16 // @codingStandardsIgnoreStart Generic.Files.LineLength
17 const RSS_RC_LINK
= '<link rel="alternate" type="application/rss+xml" title=" RSS feed" href="/w/index.php?title=Special:RecentChanges&feed=rss"/>';
18 const ATOM_RC_LINK
= '<link rel="alternate" type="application/atom+xml" title=" Atom feed" href="/w/index.php?title=Special:RecentChanges&feed=atom"/>';
20 const RSS_TEST_LINK
= '<link rel="alternate" type="application/rss+xml" title=""Test" RSS feed" href="fake-link"/>';
21 const ATOM_TEST_LINK
= '<link rel="alternate" type="application/atom+xml" title=""Test" Atom feed" href="fake-link"/>';
22 // @codingStandardsIgnoreEnd
24 // Ensure that we don't affect the global ResourceLoader state.
25 protected function setUp() {
27 ResourceLoader
::clearCache();
30 protected function tearDown() {
32 ResourceLoader
::clearCache();
36 * @dataProvider provideRedirect
38 * @covers OutputPage::__construct
39 * @covers OutputPage::redirect
40 * @covers OutputPage::getRedirect
42 public function testRedirect( $url, $code = null ) {
43 $op = $this->newInstance();
44 if ( isset( $code ) ) {
45 $op->redirect( $url, $code );
47 $op->redirect( $url );
49 $expectedUrl = str_replace( "\n", '', $url );
50 $this->assertSame( $expectedUrl, $op->getRedirect() );
51 $this->assertSame( $expectedUrl, $op->mRedirect
);
52 $this->assertSame( $code ??
'302', $op->mRedirectCode
);
55 public function provideRedirect() {
57 [ 'http://example.com' ],
58 [ 'http://example.com', '400' ],
59 [ 'http://example.com', 'squirrels!!!' ],
64 private function setupFeedLinks( $feed, $types ) {
65 $outputPage = $this->newInstance( [
66 'AdvertisedFeedTypes' => $types,
68 'OverrideSiteFeed' => false,
72 $outputPage->setTitle( Title
::makeTitle( NS_MAIN
, 'Test' ) );
73 $this->setMwGlobals( [
74 'wgScript' => '/w/index.php',
79 private function assertFeedLinks( $outputPage, $message, $present, $non_present ) {
80 $links = $outputPage->getHeadLinksArray();
81 foreach ( $present as $link ) {
82 $this->assertContains( $link, $links, $message );
84 foreach ( $non_present as $link ) {
85 $this->assertNotContains( $link, $links, $message );
89 private function assertFeedUILinks( $outputPage, $ui_links ) {
91 $this->assertTrue( $outputPage->isSyndicated(), 'Syndication should be offered' );
92 $this->assertGreaterThan( 0, count( $outputPage->getSyndicationLinks() ),
93 'Some syndication links should be there' );
95 $this->assertFalse( $outputPage->isSyndicated(), 'No syndication should be offered' );
96 $this->assertEquals( 0, count( $outputPage->getSyndicationLinks() ),
97 'No syndication links should be there' );
101 public static function provideFeedLinkData() {
104 true, [ 'rss' ], 'Only RSS RC link should be offerred',
105 [ self
::RSS_RC_LINK
], [ self
::ATOM_RC_LINK
]
108 true, [ 'atom' ], 'Only Atom RC link should be offerred',
109 [ self
::ATOM_RC_LINK
], [ self
::RSS_RC_LINK
]
112 true, [], 'No RC feed formats should be offerred',
113 [], [ self
::ATOM_RC_LINK
, self
::RSS_RC_LINK
]
116 false, [ 'atom' ], 'No RC feeds should be offerred',
117 [], [ self
::ATOM_RC_LINK
, self
::RSS_RC_LINK
]
123 * @covers OutputPage::setCopyrightUrl
124 * @covers OutputPage::getHeadLinksArray
126 public function testSetCopyrightUrl() {
127 $op = $this->newInstance();
128 $op->setCopyrightUrl( 'http://example.com' );
131 Html
::element( 'link', [ 'rel' => 'license', 'href' => 'http://example.com' ] ),
132 $op->getHeadLinksArray()['copyright']
137 * @dataProvider provideFeedLinkData
138 * @covers OutputPage::getHeadLinksArray
140 public function testRecentChangesFeed( $feed, $advertised_feed_types,
141 $message, $present, $non_present ) {
142 $outputPage = $this->setupFeedLinks( $feed, $advertised_feed_types );
143 $this->assertFeedLinks( $outputPage, $message, $present, $non_present );
146 public static function provideAdditionalFeedData() {
149 true, [ 'atom' ], 'Additional Atom feed should be offered',
151 [ self
::ATOM_TEST_LINK
, self
::ATOM_RC_LINK
],
152 [ self
::RSS_TEST_LINK
, self
::RSS_RC_LINK
],
156 true, [ 'rss' ], 'Additional RSS feed should be offered',
158 [ self
::RSS_TEST_LINK
, self
::RSS_RC_LINK
],
159 [ self
::ATOM_TEST_LINK
, self
::ATOM_RC_LINK
],
163 true, [ 'rss' ], 'Additional Atom feed should NOT be offered with RSS enabled',
165 [ self
::RSS_RC_LINK
],
166 [ self
::RSS_TEST_LINK
, self
::ATOM_TEST_LINK
, self
::ATOM_RC_LINK
],
170 false, [ 'atom' ], 'Additional Atom feed should NOT be offered, all feeds disabled',
174 self
::RSS_TEST_LINK
, self
::ATOM_TEST_LINK
,
175 self
::ATOM_RC_LINK
, self
::ATOM_RC_LINK
,
183 * @dataProvider provideAdditionalFeedData
184 * @covers OutputPage::getHeadLinksArray
185 * @covers OutputPage::addFeedLink
186 * @covers OutputPage::getSyndicationLinks
187 * @covers OutputPage::isSyndicated
189 public function testAdditionalFeeds( $feed, $advertised_feed_types, $message,
190 $additional_feed_type, $present, $non_present, $any_ui_links ) {
191 $outputPage = $this->setupFeedLinks( $feed, $advertised_feed_types );
192 $outputPage->addFeedLink( $additional_feed_type, 'fake-link' );
193 $this->assertFeedLinks( $outputPage, $message, $present, $non_present );
194 $this->assertFeedUILinks( $outputPage, $any_ui_links );
197 // @todo How to test setStatusCode?
200 * @covers OutputPage::addMeta
201 * @covers OutputPage::getMetaTags
202 * @covers OutputPage::getHeadLinksArray
204 public function testMetaTags() {
205 $op = $this->newInstance();
206 $op->addMeta( 'http:expires', '0' );
207 $op->addMeta( 'keywords', 'first' );
208 $op->addMeta( 'keywords', 'second' );
209 $op->addMeta( 'og:title', 'Ta-duh' );
212 [ 'http:expires', '0' ],
213 [ 'keywords', 'first' ],
214 [ 'keywords', 'second' ],
215 [ 'og:title', 'Ta-duh' ],
217 $this->assertSame( $expected, $op->getMetaTags() );
219 $links = $op->getHeadLinksArray();
220 $this->assertContains( '<meta http-equiv="expires" content="0"/>', $links );
221 $this->assertContains( '<meta name="keywords" content="first"/>', $links );
222 $this->assertContains( '<meta name="keywords" content="second"/>', $links );
223 $this->assertContains( '<meta property="og:title" content="Ta-duh"/>', $links );
224 $this->assertArrayNotHasKey( 'meta-robots', $links );
228 * @covers OutputPage::addLink
229 * @covers OutputPage::getLinkTags
230 * @covers OutputPage::getHeadLinksArray
232 public function testAddLink() {
233 $op = $this->newInstance();
237 [ 'rel' => 'foo', 'href' => 'http://example.com' ],
240 foreach ( $links as $link ) {
241 $op->addLink( $link );
244 $this->assertSame( $links, $op->getLinkTags() );
246 $result = $op->getHeadLinksArray();
248 foreach ( $links as $link ) {
249 $this->assertContains( Html
::element( 'link', $link ), $result );
254 * @covers OutputPage::setCanonicalUrl
255 * @covers OutputPage::getCanonicalUrl
256 * @covers OutputPage::getHeadLinksArray
258 public function testSetCanonicalUrl() {
259 $op = $this->newInstance();
260 $op->setCanonicalUrl( 'http://example.comm' );
261 $op->setCanonicalUrl( 'http://example.com' );
263 $this->assertSame( 'http://example.com', $op->getCanonicalUrl() );
265 $headLinks = $op->getHeadLinksArray();
267 $this->assertContains( Html
::element( 'link', [
268 'rel' => 'canonical', 'href' => 'http://example.com'
271 $this->assertNotContains( Html
::element( 'link', [
272 'rel' => 'canonical', 'href' => 'http://example.comm'
277 * @covers OutputPage::addScript
279 public function testAddScript() {
280 $op = $this->newInstance();
281 $op->addScript( 'some random string' );
283 $this->assertContains( "\nsome random string\n", "\n" . $op->getBottomScripts() . "\n" );
287 * @covers OutputPage::addScriptFile
289 public function testAddScriptFile() {
290 $op = $this->newInstance();
291 $op->addScriptFile( '/somescript.js' );
292 $op->addScriptFile( '//example.com/somescript.js' );
294 $this->assertContains(
295 "\n" . Html
::linkedScript( '/somescript.js', $op->getCSPNonce() ) .
296 Html
::linkedScript( '//example.com/somescript.js', $op->getCSPNonce() ) . "\n",
297 "\n" . $op->getBottomScripts() . "\n"
302 * Test that addScriptFile() throws due to deprecation.
304 * @covers OutputPage::addScriptFile
306 public function testAddDeprecatedScriptFileWarning() {
307 $this->setExpectedException( PHPUnit_Framework_Error_Deprecated
::class,
308 'Use of OutputPage::addScriptFile was deprecated in MediaWiki 1.24.' );
310 $op = $this->newInstance();
311 $op->addScriptFile( 'ignored-script.js' );
315 * Test the actual behavior of the method (in the case where it doesn't throw, e.g., in
318 * @covers OutputPage::addScriptFile
320 public function testAddDeprecatedScriptFileNoOp() {
321 $this->hideDeprecated( 'OutputPage::addScriptFile' );
322 $op = $this->newInstance();
323 $op->addScriptFile( 'ignored-script.js' );
325 $this->assertNotContains( 'ignored-script.js', '' . $op->getBottomScripts() );
329 * @covers OutputPage::addInlineScript
331 public function testAddInlineScript() {
332 $op = $this->newInstance();
333 $op->addInlineScript( 'let foo = "bar";' );
334 $op->addInlineScript( 'alert( foo );' );
336 $this->assertContains(
337 "\n" . Html
::inlineScript( "\nlet foo = \"bar\";\n", $op->getCSPNonce() ) . "\n" .
338 Html
::inlineScript( "\nalert( foo );\n", $op->getCSPNonce() ) . "\n",
339 "\n" . $op->getBottomScripts() . "\n"
343 // @todo How to test filterModules(), warnModuleTargetFilter(), getModules(), etc.?
346 * @covers OutputPage::getTarget
347 * @covers OutputPage::setTarget
349 public function testSetTarget() {
350 $op = $this->newInstance();
351 $op->setTarget( 'foo' );
353 $this->assertSame( 'foo', $op->getTarget() );
354 // @todo What else? Test some actual effect?
357 // @todo How to test addContentOverride(Callback)?
360 * @covers OutputPage::getHeadItemsArray
361 * @covers OutputPage::addHeadItem
362 * @covers OutputPage::addHeadItems
363 * @covers OutputPage::hasHeadItem
365 public function testHeadItems() {
366 $op = $this->newInstance();
367 $op->addHeadItem( 'a', 'b' );
368 $op->addHeadItems( [ 'c' => '<d>&', 'e' => 'f', 'a' => 'q' ] );
369 $op->addHeadItem( 'e', 'g' );
370 $op->addHeadItems( 'x' );
372 $this->assertSame( [ 'a' => 'q', 'c' => '<d>&', 'e' => 'g', 'x' ],
373 $op->getHeadItemsArray() );
375 $this->assertTrue( $op->hasHeadItem( 'a' ) );
376 $this->assertTrue( $op->hasHeadItem( 'c' ) );
377 $this->assertTrue( $op->hasHeadItem( 'e' ) );
378 $this->assertTrue( $op->hasHeadItem( '0' ) );
380 $this->assertContains( "\nq\n<d>&\ng\nx\n",
381 '' . $op->headElement( $op->getContext()->getSkin() ) );
385 * @covers OutputPage::getHeadItemsArray
386 * @covers OutputPage::addParserOutputMetadata
387 * @covers OutputPage::addParserOutput
389 public function testHeadItemsParserOutput() {
390 $op = $this->newInstance();
391 $stubPO1 = $this->createParserOutputStub( 'getHeadItems', [ 'a' => 'b' ] );
392 $op->addParserOutputMetadata( $stubPO1 );
393 $stubPO2 = $this->createParserOutputStub( 'getHeadItems',
394 [ 'c' => '<d>&', 'e' => 'f', 'a' => 'q' ] );
395 $op->addParserOutputMetadata( $stubPO2 );
396 $stubPO3 = $this->createParserOutputStub( 'getHeadItems', [ 'e' => 'g' ] );
397 $op->addParserOutput( $stubPO3 );
398 $stubPO4 = $this->createParserOutputStub( 'getHeadItems', [ 'x' ] );
399 $op->addParserOutputMetadata( $stubPO4 );
401 $this->assertSame( [ 'a' => 'q', 'c' => '<d>&', 'e' => 'g', 'x' ],
402 $op->getHeadItemsArray() );
404 $this->assertTrue( $op->hasHeadItem( 'a' ) );
405 $this->assertTrue( $op->hasHeadItem( 'c' ) );
406 $this->assertTrue( $op->hasHeadItem( 'e' ) );
407 $this->assertTrue( $op->hasHeadItem( '0' ) );
408 $this->assertFalse( $op->hasHeadItem( 'b' ) );
410 $this->assertContains( "\nq\n<d>&\ng\nx\n",
411 '' . $op->headElement( $op->getContext()->getSkin() ) );
415 * @covers OutputPage::addBodyClasses
417 public function testAddBodyClasses() {
418 $op = $this->newInstance();
419 $op->addBodyClasses( 'a' );
420 $op->addBodyClasses( 'mediawiki' );
421 $op->addBodyClasses( 'b c' );
422 $op->addBodyClasses( [ 'd', 'e' ] );
423 $op->addBodyClasses( 'a' );
425 $this->assertContains( '"a mediawiki b c d e ltr',
426 '' . $op->headElement( $op->getContext()->getSkin() ) );
430 * @covers OutputPage::setArticleBodyOnly
431 * @covers OutputPage::getArticleBodyOnly
433 public function testArticleBodyOnly() {
434 $op = $this->newInstance();
435 $this->assertFalse( $op->getArticleBodyOnly() );
437 $op->setArticleBodyOnly( true );
438 $this->assertTrue( $op->getArticleBodyOnly() );
440 $op->addHTML( '<b>a</b>' );
442 $this->assertSame( '<b>a</b>', $op->output( true ) );
446 * @covers OutputPage::setProperty
447 * @covers OutputPage::getProperty
449 public function testProperties() {
450 $op = $this->newInstance();
452 $this->assertNull( $op->getProperty( 'foo' ) );
454 $op->setProperty( 'foo', 'bar' );
455 $op->setProperty( 'baz', 'quz' );
457 $this->assertSame( 'bar', $op->getProperty( 'foo' ) );
458 $this->assertSame( 'quz', $op->getProperty( 'baz' ) );
462 * @dataProvider provideCheckLastModified
464 * @covers OutputPage::checkLastModified
465 * @covers OutputPage::getCdnCacheEpoch
467 public function testCheckLastModified(
468 $timestamp, $ifModifiedSince, $expected, $config = [], $callback = null
470 $request = new FauxRequest();
471 if ( $ifModifiedSince ) {
472 if ( is_numeric( $ifModifiedSince ) ) {
474 $ifModifiedSince = date( 'D, d M Y H:i:s', $ifModifiedSince ) . ' GMT';
476 $request->setHeader( 'If-Modified-Since', $ifModifiedSince );
479 if ( !isset( $config['CacheEpoch'] ) ) {
480 // Make sure it's not too recent
481 $config['CacheEpoch'] = '20000101000000';
484 $op = $this->newInstance( $config, $request );
487 $callback( $op, $this );
490 // Avoid a complaint about not being able to disable compression
491 Wikimedia\
suppressWarnings();
493 $this->assertEquals( $expected, $op->checkLastModified( $timestamp ) );
495 Wikimedia\restoreWarnings
();
499 public function provideCheckLastModified() {
500 $lastModified = time() - 3600;
503 [ '0', $lastModified, false ],
504 'Timestamp Unix epoch' =>
505 [ '19700101000000', $lastModified, false ],
506 'Timestamp same as If-Modified-Since' =>
507 [ $lastModified, $lastModified, true ],
508 'Timestamp one second after If-Modified-Since' =>
509 [ $lastModified +
1, $lastModified, false ],
510 'No If-Modified-Since' =>
511 [ $lastModified +
1, null, false ],
512 'Malformed If-Modified-Since' =>
513 [ $lastModified +
1, 'GIBBERING WOMBATS !!!', false ],
514 'Non-standard IE-style If-Modified-Since' =>
515 [ $lastModified, date( 'D, d M Y H:i:s', $lastModified ) . ' GMT; length=5202',
517 // @todo Should we fix this behavior to match the spec? Probably no reason to.
518 'If-Modified-Since not per spec but we accept it anyway because strtotime does' =>
519 [ $lastModified, "@$lastModified", true ],
520 '$wgCachePages = false' =>
521 [ $lastModified, $lastModified, false, [ 'CachePages' => false ] ],
523 [ $lastModified, $lastModified, false,
524 [ 'CacheEpoch' => wfTimestamp( TS_MW
, $lastModified +
1 ) ] ],
525 'Recently-touched user' =>
526 [ $lastModified, $lastModified, false, [],
528 $op->getContext()->setUser( $this->getTestUser()->getUser() );
530 'After CDN expiry' =>
531 [ $lastModified, $lastModified, false,
532 [ 'UseCdn' => true, 'CdnMaxAge' => 3599 ] ],
533 'Hook allows cache use' =>
534 [ $lastModified +
1, $lastModified, true, [],
535 function ( $op, $that ) {
536 $that->setTemporaryHook( 'OutputPageCheckLastModified',
537 function ( &$modifiedTimes ) {
538 $modifiedTimes = [ 1 ];
542 'Hooks prohibits cache use' =>
543 [ $lastModified, $lastModified, false, [],
544 function ( $op, $that ) {
545 $that->setTemporaryHook( 'OutputPageCheckLastModified',
546 function ( &$modifiedTimes ) {
547 $modifiedTimes = [ max( $modifiedTimes ) +
1 ];
555 * @dataProvider provideCdnCacheEpoch
557 * @covers OutputPage::getCdnCacheEpoch
559 public function testCdnCacheEpoch( $params ) {
560 $out = TestingAccessWrapper
::newFromObject( $this->newInstance() );
561 $reqTime = strtotime( $params['reqTime'] );
562 $pageTime = strtotime( $params['pageTime'] );
563 $actual = max( $pageTime, $out->getCdnCacheEpoch( $reqTime, $params['maxAge'] ) );
567 gmdate( DateTime
::ATOM
, $actual ),
572 public static function provideCdnCacheEpoch() {
574 'pageTime' => '2011-04-01T12:00:00+00:00',
575 'maxAge' => 24 * 3600,
578 'after 1s' => [ $base +
[
579 'reqTime' => '2011-04-01T12:00:01+00:00',
580 'expect' => '2011-04-01T12:00:00+00:00',
582 'after 23h' => [ $base +
[
583 'reqTime' => '2011-04-02T11:00:00+00:00',
584 'expect' => '2011-04-01T12:00:00+00:00',
586 'after 24h and a bit' => [ $base +
[
587 'reqTime' => '2011-04-02T12:34:56+00:00',
588 'expect' => '2011-04-01T12:34:56+00:00',
590 'after a year' => [ $base +
[
591 'reqTime' => '2012-05-06T00:12:07+00:00',
592 'expect' => '2012-05-05T00:12:07+00:00',
597 // @todo How to test setLastModified?
600 * @covers OutputPage::setRobotPolicy
601 * @covers OutputPage::getHeadLinksArray
603 public function testSetRobotPolicy() {
604 $op = $this->newInstance();
605 $op->setRobotPolicy( 'noindex, nofollow' );
607 $links = $op->getHeadLinksArray();
608 $this->assertContains( '<meta name="robots" content="noindex,nofollow"/>', $links );
612 * @covers OutputPage::setIndexPolicy
613 * @covers OutputPage::setFollowPolicy
614 * @covers OutputPage::getHeadLinksArray
616 public function testSetIndexFollowPolicies() {
617 $op = $this->newInstance();
618 $op->setIndexPolicy( 'noindex' );
619 $op->setFollowPolicy( 'nofollow' );
621 $links = $op->getHeadLinksArray();
622 $this->assertContains( '<meta name="robots" content="noindex,nofollow"/>', $links );
625 private function extractHTMLTitle( OutputPage
$op ) {
626 $html = $op->headElement( $op->getContext()->getSkin() );
628 // OutputPage should always output the title in a nice format such that regexes will work
629 // fine. If it doesn't, we'll fail the tests.
630 preg_match_all( '!<title>(.*?)</title>!', $html, $matches );
632 $this->assertLessThanOrEqual( 1, count( $matches[1] ), 'More than one <title>!' );
634 if ( !count( $matches[1] ) ) {
638 return $matches[1][0];
642 * Shorthand for getting the text of a message, in content language.
644 private static function getMsgText( $op, ...$msgParams ) {
645 return $op->msg( ...$msgParams )->inContentLanguage()->text();
649 * @covers OutputPage::setHTMLTitle
650 * @covers OutputPage::getHTMLTitle
652 public function testHTMLTitle() {
653 $op = $this->newInstance();
656 $this->assertSame( '', $op->getHTMLTitle() );
657 $this->assertSame( '', $op->getPageTitle() );
659 $this->getMsgText( $op, 'pagetitle', '' ),
660 $this->extractHTMLTitle( $op )
664 $op->setHTMLTitle( 'Potatoes will eat me' );
666 $this->assertSame( 'Potatoes will eat me', $op->getHTMLTitle() );
667 $this->assertSame( 'Potatoes will eat me', $this->extractHTMLTitle( $op ) );
668 // Shouldn't have changed the page title
669 $this->assertSame( '', $op->getPageTitle() );
672 $msg = $op->msg( 'mainpage' );
674 $op->setHTMLTitle( $msg );
675 $this->assertSame( $msg->text(), $op->getHTMLTitle() );
676 $this->assertSame( $msg->text(), $this->extractHTMLTitle( $op ) );
677 $this->assertSame( '', $op->getPageTitle() );
681 * @covers OutputPage::setRedirectedFrom
683 public function testSetRedirectedFrom() {
684 $op = $this->newInstance();
686 $op->setRedirectedFrom( Title
::newFromText( 'Talk:Some page' ) );
687 $this->assertSame( 'Talk:Some_page', $op->getJSVars()['wgRedirectedFrom'] );
691 * @covers OutputPage::setPageTitle
692 * @covers OutputPage::getPageTitle
694 public function testPageTitle() {
695 // We don't test the actual HTML output anywhere, because that's up to the skin.
696 $op = $this->newInstance();
699 $this->assertSame( '', $op->getPageTitle() );
700 $this->assertSame( '', $op->getHTMLTitle() );
702 // Test set to plain text
703 $op->setPageTitle( 'foobar' );
705 $this->assertSame( 'foobar', $op->getPageTitle() );
706 // HTML title should change as well
707 $this->assertSame( $this->getMsgText( $op, 'pagetitle', 'foobar' ), $op->getHTMLTitle() );
709 // Test set to text with good and bad HTML. We don't try to be comprehensive here, that
710 // belongs in Sanitizer tests.
711 $op->setPageTitle( '<script>a</script>&<i>b</i>' );
713 $this->assertSame( '<script>a</script>&<i>b</i>', $op->getPageTitle() );
715 $this->getMsgText( $op, 'pagetitle', '<script>a</script>&b' ),
719 // Test set to message
720 $text = $this->getMsgText( $op, 'mainpage' );
722 $op->setPageTitle( $op->msg( 'mainpage' )->inContentLanguage() );
723 $this->assertSame( $text, $op->getPageTitle() );
724 $this->assertSame( $this->getMsgText( $op, 'pagetitle', $text ), $op->getHTMLTitle() );
728 * @covers OutputPage::setTitle
730 public function testSetTitle() {
731 $op = $this->newInstance();
733 $this->assertSame( 'My test page', $op->getTitle()->getPrefixedText() );
735 $op->setTitle( Title
::newFromText( 'Another test page' ) );
737 $this->assertSame( 'Another test page', $op->getTitle()->getPrefixedText() );
741 * @covers OutputPage::setSubtitle
742 * @covers OutputPage::clearSubtitle
743 * @covers OutputPage::addSubtitle
744 * @covers OutputPage::getSubtitle
746 public function testSubtitle() {
747 $op = $this->newInstance();
749 $this->assertSame( '', $op->getSubtitle() );
751 $op->addSubtitle( '<b>foo</b>' );
753 $this->assertSame( '<b>foo</b>', $op->getSubtitle() );
755 $op->addSubtitle( $op->msg( 'mainpage' )->inContentLanguage() );
758 "<b>foo</b><br />\n\t\t\t\t" . $this->getMsgText( $op, 'mainpage' ),
762 $op->setSubtitle( 'There can be only one' );
764 $this->assertSame( 'There can be only one', $op->getSubtitle() );
766 $op->clearSubtitle();
768 $this->assertSame( '', $op->getSubtitle() );
772 * @dataProvider provideBacklinkSubtitle
774 * @covers OutputPage::buildBacklinkSubtitle
776 public function testBuildBacklinkSubtitle( $titles, $queries, $contains, $notContains ) {
777 if ( count( $titles ) > 1 ) {
779 $this->assertTrue( true );
783 $title = Title
::newFromText( $titles[0] );
784 $query = $queries[0];
786 $this->editPage( 'Page 1', '' );
787 $this->editPage( 'Page 2', '#REDIRECT [[Page 1]]' );
789 $str = OutputPage
::buildBacklinkSubtitle( $title, $query )->text();
791 foreach ( $contains as $substr ) {
792 $this->assertContains( $substr, $str );
795 foreach ( $notContains as $substr ) {
796 $this->assertNotContains( $substr, $str );
801 * @dataProvider provideBacklinkSubtitle
803 * @covers OutputPage::addBacklinkSubtitle
804 * @covers OutputPage::getSubtitle
806 public function testAddBacklinkSubtitle( $titles, $queries, $contains, $notContains ) {
807 $this->editPage( 'Page 1', '' );
808 $this->editPage( 'Page 2', '#REDIRECT [[Page 1]]' );
810 $op = $this->newInstance();
811 foreach ( $titles as $i => $unused ) {
812 $op->addBacklinkSubtitle( Title
::newFromText( $titles[$i] ), $queries[$i] );
815 $str = $op->getSubtitle();
817 foreach ( $contains as $substr ) {
818 $this->assertContains( $substr, $str );
821 foreach ( $notContains as $substr ) {
822 $this->assertNotContains( $substr, $str );
826 public function provideBacklinkSubtitle() {
832 [ 'redirect', 'Page 2' ],
842 [ [ 'action' => 'edit' ] ],
847 [ 'Page 1', 'Page 2' ],
849 [ 'Page 1', 'Page 2', "<br />\n\t\t\t\t" ],
852 // @todo Anything else to test?
857 * @covers OutputPage::setPrintable
858 * @covers OutputPage::isPrintable
860 public function testPrintable() {
861 $op = $this->newInstance();
863 $this->assertFalse( $op->isPrintable() );
867 $this->assertTrue( $op->isPrintable() );
871 * @covers OutputPage::disable
872 * @covers OutputPage::isDisabled
874 public function testDisable() {
875 $op = $this->newInstance();
877 $this->assertFalse( $op->isDisabled() );
878 $this->assertNotSame( '', $op->output( true ) );
882 $this->assertTrue( $op->isDisabled() );
883 $this->assertSame( '', $op->output( true ) );
887 * @covers OutputPage::showNewSectionLink
888 * @covers OutputPage::addParserOutputMetadata
889 * @covers OutputPage::addParserOutput
891 public function testShowNewSectionLink() {
892 $op = $this->newInstance();
894 $this->assertFalse( $op->showNewSectionLink() );
896 $pOut1 = $this->createParserOutputStub( 'getNewSection', true );
897 $op->addParserOutputMetadata( $pOut1 );
898 $this->assertTrue( $op->showNewSectionLink() );
900 $pOut2 = $this->createParserOutputStub( 'getNewSection', false );
901 $op->addParserOutput( $pOut2 );
902 $this->assertFalse( $op->showNewSectionLink() );
906 * @covers OutputPage::forceHideNewSectionLink
907 * @covers OutputPage::addParserOutputMetadata
908 * @covers OutputPage::addParserOutput
910 public function testForceHideNewSectionLink() {
911 $op = $this->newInstance();
913 $this->assertFalse( $op->forceHideNewSectionLink() );
915 $pOut1 = $this->createParserOutputStub( 'getHideNewSection', true );
916 $op->addParserOutputMetadata( $pOut1 );
917 $this->assertTrue( $op->forceHideNewSectionLink() );
919 $pOut2 = $this->createParserOutputStub( 'getHideNewSection', false );
920 $op->addParserOutput( $pOut2 );
921 $this->assertFalse( $op->forceHideNewSectionLink() );
925 * @covers OutputPage::setSyndicated
926 * @covers OutputPage::isSyndicated
928 public function testSetSyndicated() {
929 $op = $this->newInstance( [ 'Feed' => true ] );
930 $this->assertFalse( $op->isSyndicated() );
932 $op->setSyndicated();
933 $this->assertTrue( $op->isSyndicated() );
935 $op->setSyndicated( false );
936 $this->assertFalse( $op->isSyndicated() );
938 $op = $this->newInstance(); // Feed => false by default
939 $this->assertFalse( $op->isSyndicated() );
941 $op->setSyndicated();
942 $this->assertFalse( $op->isSyndicated() );
946 * @covers OutputPage::isSyndicated
947 * @covers OutputPage::setFeedAppendQuery
948 * @covers OutputPage::addFeedLink
949 * @covers OutputPage::getSyndicationLinks()
951 public function testFeedLinks() {
952 $op = $this->newInstance( [ 'Feed' => true ] );
953 $this->assertSame( [], $op->getSyndicationLinks() );
955 $op->addFeedLink( 'not a supported format', 'abc' );
956 $this->assertFalse( $op->isSyndicated() );
957 $this->assertSame( [], $op->getSyndicationLinks() );
959 $feedTypes = $op->getConfig()->get( 'AdvertisedFeedTypes' );
961 $op->addFeedLink( $feedTypes[0], 'def' );
962 $this->assertTrue( $op->isSyndicated() );
963 $this->assertSame( [ $feedTypes[0] => 'def' ], $op->getSyndicationLinks() );
965 $op->setFeedAppendQuery( false );
967 foreach ( $feedTypes as $type ) {
968 $expected[$type] = $op->getTitle()->getLocalURL( "feed=$type" );
970 $this->assertSame( $expected, $op->getSyndicationLinks() );
972 $op->setFeedAppendQuery( 'apples=oranges' );
973 foreach ( $feedTypes as $type ) {
974 $expected[$type] = $op->getTitle()->getLocalURL( "feed=$type&apples=oranges" );
976 $this->assertSame( $expected, $op->getSyndicationLinks() );
978 $op = $this->newInstance(); // Feed => false by default
979 $this->assertSame( [], $op->getSyndicationLinks() );
981 $op->addFeedLink( $feedTypes[0], 'def' );
982 $this->assertFalse( $op->isSyndicated() );
983 $this->assertSame( [], $op->getSyndicationLinks() );
987 * @covers OutputPage::setArticleFlag
988 * @covers OutputPage::isArticle
989 * @covers OutputPage::setArticleRelated
990 * @covers OutputPage::isArticleRelated
992 function testArticleFlags() {
993 $op = $this->newInstance();
994 $this->assertFalse( $op->isArticle() );
995 $this->assertTrue( $op->isArticleRelated() );
997 $op->setArticleRelated( false );
998 $this->assertFalse( $op->isArticle() );
999 $this->assertFalse( $op->isArticleRelated() );
1001 $op->setArticleFlag( true );
1002 $this->assertTrue( $op->isArticle() );
1003 $this->assertTrue( $op->isArticleRelated() );
1005 $op->setArticleFlag( false );
1006 $this->assertFalse( $op->isArticle() );
1007 $this->assertTrue( $op->isArticleRelated() );
1009 $op->setArticleFlag( true );
1010 $op->setArticleRelated( false );
1011 $this->assertFalse( $op->isArticle() );
1012 $this->assertFalse( $op->isArticleRelated() );
1016 * @covers OutputPage::addLanguageLinks
1017 * @covers OutputPage::setLanguageLinks
1018 * @covers OutputPage::getLanguageLinks
1019 * @covers OutputPage::addParserOutputMetadata
1020 * @covers OutputPage::addParserOutput
1022 function testLanguageLinks() {
1023 $op = $this->newInstance();
1024 $this->assertSame( [], $op->getLanguageLinks() );
1026 $op->addLanguageLinks( [ 'fr:A', 'it:B' ] );
1027 $this->assertSame( [ 'fr:A', 'it:B' ], $op->getLanguageLinks() );
1029 $op->addLanguageLinks( [ 'de:C', 'es:D' ] );
1030 $this->assertSame( [ 'fr:A', 'it:B', 'de:C', 'es:D' ], $op->getLanguageLinks() );
1032 $op->setLanguageLinks( [ 'pt:E' ] );
1033 $this->assertSame( [ 'pt:E' ], $op->getLanguageLinks() );
1035 $pOut1 = $this->createParserOutputStub( 'getLanguageLinks', [ 'he:F', 'ar:G' ] );
1036 $op->addParserOutputMetadata( $pOut1 );
1037 $this->assertSame( [ 'pt:E', 'he:F', 'ar:G' ], $op->getLanguageLinks() );
1039 $pOut2 = $this->createParserOutputStub( 'getLanguageLinks', [ 'pt:H' ] );
1040 $op->addParserOutput( $pOut2 );
1041 $this->assertSame( [ 'pt:E', 'he:F', 'ar:G', 'pt:H' ], $op->getLanguageLinks() );
1044 // @todo Are these category links tests too abstract and complicated for what they test? Would
1045 // it make sense to just write out all the tests by hand with maybe some copy-and-paste?
1048 * @dataProvider provideGetCategories
1050 * @covers OutputPage::addCategoryLinks
1051 * @covers OutputPage::getCategories
1052 * @covers OutputPage::getCategoryLinks
1054 * @param array $args Array of form [ category name => sort key ]
1055 * @param array $fakeResults Array of form [ category name => value to return from mocked
1057 * @param callable $variantLinkCallback Callback to replace findVariantLink() call
1058 * @param array $expectedNormal Expected return value of getCategoryLinks['normal']
1059 * @param array $expectedHidden Expected return value of getCategoryLinks['hidden']
1061 public function testAddCategoryLinks(
1062 array $args, array $fakeResults, callable
$variantLinkCallback = null,
1063 array $expectedNormal, array $expectedHidden
1065 $expectedNormal = $this->extractExpectedCategories( $expectedNormal, 'add' );
1066 $expectedHidden = $this->extractExpectedCategories( $expectedHidden, 'add' );
1068 $op = $this->setupCategoryTests( $fakeResults, $variantLinkCallback );
1070 $op->addCategoryLinks( $args );
1072 $this->doCategoryAsserts( $op, $expectedNormal, $expectedHidden );
1073 $this->doCategoryLinkAsserts( $op, $expectedNormal, $expectedHidden );
1077 * @dataProvider provideGetCategories
1079 * @covers OutputPage::addCategoryLinks
1080 * @covers OutputPage::getCategories
1081 * @covers OutputPage::getCategoryLinks
1083 public function testAddCategoryLinksOneByOne(
1084 array $args, array $fakeResults, callable
$variantLinkCallback = null,
1085 array $expectedNormal, array $expectedHidden
1087 if ( count( $args ) <= 1 ) {
1088 // @todo Should this be skipped instead of passed?
1089 $this->assertTrue( true );
1093 $expectedNormal = $this->extractExpectedCategories( $expectedNormal, 'onebyone' );
1094 $expectedHidden = $this->extractExpectedCategories( $expectedHidden, 'onebyone' );
1096 $op = $this->setupCategoryTests( $fakeResults, $variantLinkCallback );
1098 foreach ( $args as $key => $val ) {
1099 $op->addCategoryLinks( [ $key => $val ] );
1102 $this->doCategoryAsserts( $op, $expectedNormal, $expectedHidden );
1103 $this->doCategoryLinkAsserts( $op, $expectedNormal, $expectedHidden );
1107 * @dataProvider provideGetCategories
1109 * @covers OutputPage::setCategoryLinks
1110 * @covers OutputPage::getCategories
1111 * @covers OutputPage::getCategoryLinks
1113 public function testSetCategoryLinks(
1114 array $args, array $fakeResults, callable
$variantLinkCallback = null,
1115 array $expectedNormal, array $expectedHidden
1117 $expectedNormal = $this->extractExpectedCategories( $expectedNormal, 'set' );
1118 $expectedHidden = $this->extractExpectedCategories( $expectedHidden, 'set' );
1120 $op = $this->setupCategoryTests( $fakeResults, $variantLinkCallback );
1122 $op->setCategoryLinks( [ 'Initial page' => 'Initial page' ] );
1123 $op->setCategoryLinks( $args );
1125 // We don't reset the categories, for some reason, only the links
1126 $expectedNormalCats = array_merge( [ 'Initial page' ], $expectedNormal );
1127 $expectedCats = array_merge( $expectedHidden, $expectedNormalCats );
1129 $this->doCategoryAsserts( $op, $expectedNormalCats, $expectedHidden );
1130 $this->doCategoryLinkAsserts( $op, $expectedNormal, $expectedHidden );
1134 * @dataProvider provideGetCategories
1136 * @covers OutputPage::addParserOutputMetadata
1137 * @covers OutputPage::addParserOutput
1138 * @covers OutputPage::getCategories
1139 * @covers OutputPage::getCategoryLinks
1141 public function testParserOutputCategoryLinks(
1142 array $args, array $fakeResults, callable
$variantLinkCallback = null,
1143 array $expectedNormal, array $expectedHidden
1145 $expectedNormal = $this->extractExpectedCategories( $expectedNormal, 'pout' );
1146 $expectedHidden = $this->extractExpectedCategories( $expectedHidden, 'pout' );
1148 $op = $this->setupCategoryTests( $fakeResults, $variantLinkCallback );
1150 $stubPO = $this->createParserOutputStub( 'getCategories', $args );
1152 // addParserOutput and addParserOutputMetadata should behave identically for us, so
1153 // alternate to get coverage for both without adding extra tests
1156 $method = [ 'addParserOutputMetadata', 'addParserOutput' ][$idx %
2];
1157 $op->$method( $stubPO );
1159 $this->doCategoryAsserts( $op, $expectedNormal, $expectedHidden );
1160 $this->doCategoryLinkAsserts( $op, $expectedNormal, $expectedHidden );
1164 * We allow different expectations for different tests as an associative array, like
1165 * [ 'set' => [ ... ], 'default' => [ ... ] ] if setCategoryLinks() will give a different
1168 private function extractExpectedCategories( array $expected, $key ) {
1169 if ( !$expected ||
isset( $expected[0] ) ) {
1172 return $expected[$key] ??
$expected['default'];
1175 private function setupCategoryTests(
1176 array $fakeResults, callable
$variantLinkCallback = null
1178 $this->setMwGlobals( 'wgUsePigLatinVariant', true );
1180 $op = $this->getMockBuilder( OutputPage
::class )
1181 ->setConstructorArgs( [ new RequestContext() ] )
1182 ->setMethods( [ 'addCategoryLinksToLBAndGetResult', 'getTitle' ] )
1185 $title = Title
::newFromText( 'My test page' );
1186 $op->expects( $this->any() )
1187 ->method( 'getTitle' )
1188 ->will( $this->returnValue( $title ) );
1190 $op->expects( $this->any() )
1191 ->method( 'addCategoryLinksToLBAndGetResult' )
1192 ->will( $this->returnCallback( function ( array $categories ) use ( $fakeResults ) {
1194 foreach ( $categories as $category => $unused ) {
1195 if ( isset( $fakeResults[$category] ) ) {
1196 $return[] = $fakeResults[$category];
1199 return new FakeResultWrapper( $return );
1202 if ( $variantLinkCallback ) {
1203 $mockContLang = $this->getMockBuilder( Language
::class )
1204 ->setConstructorArgs( [ 'en' ] )
1205 ->setMethods( [ 'findVariantLink' ] )
1207 $mockContLang->expects( $this->any() )
1208 ->method( 'findVariantLink' )
1209 ->will( $this->returnCallback( $variantLinkCallback ) );
1210 $this->setContentLang( $mockContLang );
1213 $this->assertSame( [], $op->getCategories() );
1218 private function doCategoryAsserts( $op, $expectedNormal, $expectedHidden ) {
1219 $this->assertSame( array_merge( $expectedHidden, $expectedNormal ), $op->getCategories() );
1220 $this->assertSame( $expectedNormal, $op->getCategories( 'normal' ) );
1221 $this->assertSame( $expectedHidden, $op->getCategories( 'hidden' ) );
1224 private function doCategoryLinkAsserts( $op, $expectedNormal, $expectedHidden ) {
1225 $catLinks = $op->getCategoryLinks();
1226 $this->assertSame( (bool)$expectedNormal +
(bool)$expectedHidden, count( $catLinks ) );
1227 if ( $expectedNormal ) {
1228 $this->assertSame( count( $expectedNormal ), count( $catLinks['normal'] ) );
1230 if ( $expectedHidden ) {
1231 $this->assertSame( count( $expectedHidden ), count( $catLinks['hidden'] ) );
1234 foreach ( $expectedNormal as $i => $name ) {
1235 $this->assertContains( $name, $catLinks['normal'][$i] );
1237 foreach ( $expectedHidden as $i => $name ) {
1238 $this->assertContains( $name, $catLinks['hidden'][$i] );
1242 public function provideGetCategories() {
1244 'No categories' => [ [], [], null, [], [] ],
1246 [ 'Test1' => 'Some sortkey', 'Test2' => 'A different sortkey' ],
1247 [ 'Test1' => (object)[ 'pp_value' => 1, 'page_title' => 'Test1' ],
1248 'Test2' => (object)[ 'page_title' => 'Test2' ] ],
1253 'Invalid title' => [
1254 [ '[' => '[', 'Test' => 'Test' ],
1255 [ 'Test' => (object)[ 'page_title' => 'Test' ] ],
1261 [ 'Test' => 'Test', 'Estay' => 'Estay' ],
1262 [ 'Test' => (object)[ 'page_title' => 'Test' ] ],
1263 function ( &$link, &$title ) {
1264 if ( $link === 'Estay' ) {
1266 $title = Title
::makeTitleSafe( NS_CATEGORY
, $link );
1269 // For adding one by one, the variant gets added as well as the original category,
1270 // but if you add them all together the second time gets skipped.
1271 [ 'onebyone' => [ 'Test', 'Test' ], 'default' => [ 'Test' ] ],
1278 * @covers OutputPage::getCategories
1280 public function testGetCategoriesInvalid() {
1281 $this->setExpectedException( InvalidArgumentException
::class,
1282 'Invalid category type given: hiddne' );
1284 $op = $this->newInstance();
1285 $op->getCategories( 'hiddne' );
1288 // @todo Should we test addCategoryLinksToLBAndGetResult? If so, how? Insert some test rows in
1292 * @covers OutputPage::setIndicators
1293 * @covers OutputPage::getIndicators
1294 * @covers OutputPage::addParserOutputMetadata
1295 * @covers OutputPage::addParserOutput
1297 public function testIndicators() {
1298 $op = $this->newInstance();
1299 $this->assertSame( [], $op->getIndicators() );
1301 $op->setIndicators( [] );
1302 $this->assertSame( [], $op->getIndicators() );
1304 // Test sorting alphabetically
1305 $op->setIndicators( [ 'b' => 'x', 'a' => 'y' ] );
1306 $this->assertSame( [ 'a' => 'y', 'b' => 'x' ], $op->getIndicators() );
1308 // Test overwriting existing keys
1309 $op->setIndicators( [ 'c' => 'z', 'a' => 'w' ] );
1310 $this->assertSame( [ 'a' => 'w', 'b' => 'x', 'c' => 'z' ], $op->getIndicators() );
1312 // Test with addParserOutputMetadata
1313 $pOut1 = $this->createParserOutputStub( 'getIndicators', [ 'c' => 'u', 'd' => 'v' ] );
1314 $op->addParserOutputMetadata( $pOut1 );
1315 $this->assertSame( [ 'a' => 'w', 'b' => 'x', 'c' => 'u', 'd' => 'v' ],
1316 $op->getIndicators() );
1318 // Test with addParserOutput
1319 $pOut2 = $this->createParserOutputStub( 'getIndicators', [ 'a' => '!!!' ] );
1320 $op->addParserOutput( $pOut2 );
1321 $this->assertSame( [ 'a' => '!!!', 'b' => 'x', 'c' => 'u', 'd' => 'v' ],
1322 $op->getIndicators() );
1326 * @covers OutputPage::addHelpLink
1327 * @covers OutputPage::getIndicators
1329 public function testAddHelpLink() {
1330 $op = $this->newInstance();
1332 $op->addHelpLink( 'Manual:PHP unit testing' );
1333 $indicators = $op->getIndicators();
1334 $this->assertSame( [ 'mw-helplink' ], array_keys( $indicators ) );
1335 $this->assertContains( 'Manual:PHP_unit_testing', $indicators['mw-helplink'] );
1337 $op->addHelpLink( 'https://phpunit.de', true );
1338 $indicators = $op->getIndicators();
1339 $this->assertSame( [ 'mw-helplink' ], array_keys( $indicators ) );
1340 $this->assertContains( 'https://phpunit.de', $indicators['mw-helplink'] );
1341 $this->assertNotContains( 'mediawiki', $indicators['mw-helplink'] );
1342 $this->assertNotContains( 'Manual:PHP', $indicators['mw-helplink'] );
1346 * @covers OutputPage::prependHTML
1347 * @covers OutputPage::addHTML
1348 * @covers OutputPage::addElement
1349 * @covers OutputPage::clearHTML
1350 * @covers OutputPage::getHTML
1352 public function testBodyHTML() {
1353 $op = $this->newInstance();
1354 $this->assertSame( '', $op->getHTML() );
1356 $op->addHTML( 'a' );
1357 $this->assertSame( 'a', $op->getHTML() );
1359 $op->addHTML( 'b' );
1360 $this->assertSame( 'ab', $op->getHTML() );
1362 $op->prependHTML( 'c' );
1363 $this->assertSame( 'cab', $op->getHTML() );
1365 $op->addElement( 'p', [ 'id' => 'foo' ], 'd' );
1366 $this->assertSame( 'cab<p id="foo">d</p>', $op->getHTML() );
1369 $this->assertSame( '', $op->getHTML() );
1373 * @dataProvider provideRevisionId
1374 * @covers OutputPage::setRevisionId
1375 * @covers OutputPage::getRevisionId
1377 public function testRevisionId( $newVal, $expected ) {
1378 $op = $this->newInstance();
1380 $this->assertNull( $op->setRevisionId( $newVal ) );
1381 $this->assertSame( $expected, $op->getRevisionId() );
1382 $this->assertSame( $expected, $op->setRevisionId( null ) );
1383 $this->assertNull( $op->getRevisionId() );
1386 public function provideRevisionId() {
1393 [ '32% finished', 32 ],
1399 * @covers OutputPage::setRevisionTimestamp
1400 * @covers OutputPage::getRevisionTimestamp
1402 public function testRevisionTimestamp() {
1403 $op = $this->newInstance();
1404 $this->assertNull( $op->getRevisionTimestamp() );
1406 $this->assertNull( $op->setRevisionTimestamp( 'abc' ) );
1407 $this->assertSame( 'abc', $op->getRevisionTimestamp() );
1408 $this->assertSame( 'abc', $op->setRevisionTimestamp( null ) );
1409 $this->assertNull( $op->getRevisionTimestamp() );
1413 * @covers OutputPage::setFileVersion
1414 * @covers OutputPage::getFileVersion
1416 public function testFileVersion() {
1417 $op = $this->newInstance();
1418 $this->assertNull( $op->getFileVersion() );
1420 $stubFile = $this->createMock( File
::class );
1421 $stubFile->method( 'exists' )->willReturn( true );
1422 $stubFile->method( 'getTimestamp' )->willReturn( '12211221123321' );
1423 $stubFile->method( 'getSha1' )->willReturn( 'bf3ffa7047dc080f5855377a4f83cd18887e3b05' );
1425 $op->setFileVersion( $stubFile );
1427 $this->assertEquals(
1428 [ 'time' => '12211221123321', 'sha1' => 'bf3ffa7047dc080f5855377a4f83cd18887e3b05' ],
1429 $op->getFileVersion()
1432 $stubMissingFile = $this->createMock( File
::class );
1433 $stubMissingFile->method( 'exists' )->willReturn( false );
1435 $op->setFileVersion( $stubMissingFile );
1436 $this->assertNull( $op->getFileVersion() );
1438 $op->setFileVersion( $stubFile );
1439 $this->assertNotNull( $op->getFileVersion() );
1441 $op->setFileVersion( null );
1442 $this->assertNull( $op->getFileVersion() );
1446 * Call either with arguments $methodName, $returnValue; or an array
1447 * [ $methodName => $returnValue, $methodName => $returnValue, ... ]
1449 private function createParserOutputStub( ...$args ) {
1450 if ( count( $args ) === 0 ) {
1452 } elseif ( count( $args ) === 1 ) {
1453 $retVals = $args[0];
1454 } elseif ( count( $args ) === 2 ) {
1455 $retVals = [ $args[0] => $args[1] ];
1457 $pOut = $this->getMock( ParserOutput
::class );
1458 foreach ( $retVals as $method => $retVal ) {
1459 $pOut->method( $method )->willReturn( $retVal );
1462 $arrayReturningMethods = [
1464 'getFileSearchOptions',
1472 foreach ( $arrayReturningMethods as $method ) {
1473 $pOut->method( $method )->willReturn( [] );
1480 * @covers OutputPage::getTemplateIds
1481 * @covers OutputPage::addParserOutputMetadata
1482 * @covers OutputPage::addParserOutput
1484 public function testTemplateIds() {
1485 $op = $this->newInstance();
1486 $this->assertSame( [], $op->getTemplateIds() );
1488 // Test with no template id's
1489 $stubPOEmpty = $this->createParserOutputStub();
1490 $op->addParserOutputMetadata( $stubPOEmpty );
1491 $this->assertSame( [], $op->getTemplateIds() );
1493 // Test with some arbitrary template id's
1495 NS_MAIN
=> [ 'A' => 3, 'B' => 17 ],
1496 NS_TALK
=> [ 'C' => 31 ],
1497 NS_MEDIA
=> [ 'D' => -1 ],
1500 $stubPO1 = $this->createParserOutputStub( 'getTemplateIds', $ids );
1502 $op->addParserOutputMetadata( $stubPO1 );
1503 $this->assertSame( $ids, $op->getTemplateIds() );
1505 // Test merging with a second set of id's
1506 $stubPO2 = $this->createParserOutputStub( 'getTemplateIds', [
1507 NS_MAIN
=> [ 'E' => 1234 ],
1508 NS_PROJECT
=> [ 'F' => 5678 ],
1512 NS_MAIN
=> [ 'E' => 1234, 'A' => 3, 'B' => 17 ],
1513 NS_TALK
=> [ 'C' => 31 ],
1514 NS_MEDIA
=> [ 'D' => -1 ],
1515 NS_PROJECT
=> [ 'F' => 5678 ],
1518 $op->addParserOutput( $stubPO2 );
1519 $this->assertSame( $finalIds, $op->getTemplateIds() );
1521 // Test merging with an empty set of id's
1522 $op->addParserOutputMetadata( $stubPOEmpty );
1523 $this->assertSame( $finalIds, $op->getTemplateIds() );
1527 * @covers OutputPage::getFileSearchOptions
1528 * @covers OutputPage::addParserOutputMetadata
1529 * @covers OutputPage::addParserOutput
1531 public function testFileSearchOptions() {
1532 $op = $this->newInstance();
1533 $this->assertSame( [], $op->getFileSearchOptions() );
1535 // Test with no files
1536 $stubPOEmpty = $this->createParserOutputStub();
1538 $op->addParserOutputMetadata( $stubPOEmpty );
1539 $this->assertSame( [], $op->getFileSearchOptions() );
1541 // Test with some arbitrary files
1543 'A' => [ 'time' => null, 'sha1' => '' ],
1545 'time' => '12211221123321',
1546 'sha1' => 'bf3ffa7047dc080f5855377a4f83cd18887e3b05',
1550 $stubPO1 = $this->createParserOutputStub( 'getFileSearchOptions', $files1 );
1552 $op->addParserOutput( $stubPO1 );
1553 $this->assertSame( $files1, $op->getFileSearchOptions() );
1555 // Test merging with a second set of files
1557 'C' => [ 'time' => null, 'sha1' => '' ],
1558 'B' => [ 'time' => null, 'sha1' => '' ],
1561 $stubPO2 = $this->createParserOutputStub( 'getFileSearchOptions', $files2 );
1563 $op->addParserOutputMetadata( $stubPO2 );
1564 $this->assertSame( array_merge( $files1, $files2 ), $op->getFileSearchOptions() );
1566 // Test merging with an empty set of files
1567 $op->addParserOutput( $stubPOEmpty );
1568 $this->assertSame( array_merge( $files1, $files2 ), $op->getFileSearchOptions() );
1572 * @dataProvider provideAddWikiText
1573 * @covers OutputPage::addWikiTextAsInterface
1574 * @covers OutputPage::wrapWikiTextAsInterface
1575 * @covers OutputPage::addWikiTextAsContent
1576 * @covers OutputPage::getHTML
1578 public function testAddWikiText( $method, array $args, $expected ) {
1579 $op = $this->newInstance();
1580 $this->assertSame( '', $op->getHTML() );
1584 [ 'addWikiTextAsInterface', 'addWikiTextAsContent' ]
1585 ) && count( $args ) >= 3 && $args[2] === null ) {
1586 // Special placeholder because we can't get the actual title in the provider
1587 $args[2] = $op->getTitle();
1590 $op->$method( ...$args );
1591 $this->assertSame( $expected, $op->getHTML() );
1594 public function provideAddWikiText() {
1596 'addWikiTextAsInterface' => [
1597 'Simple wikitext' => [
1599 "<p><b>Bold</b>\n</p>",
1600 ], 'Untidy wikitext' => [
1602 "<p><b>Bold\n</b></p>",
1603 ], 'List at start' => [
1605 "<ul><li>List</li></ul>\n",
1606 ], 'List not at start' => [
1607 [ '* Not a list', false ],
1608 '<p>* Not a list</p>',
1609 ], 'No section edit links' => [
1611 "<h2><span class=\"mw-headline\" id=\"Title\">Title</span></h2>",
1612 ], 'With title at start' => [
1613 [ '* {{PAGENAME}}', true, Title
::newFromText( 'Talk:Some page' ) ],
1614 "<ul><li>Some page</li></ul>\n",
1615 ], 'With title at start' => [
1616 [ '* {{PAGENAME}}', false, Title
::newFromText( 'Talk:Some page' ), false ],
1617 "<p>* Some page</p>",
1618 ], 'Untidy input' => [
1619 [ '<b>{{PAGENAME}}', true, Title
::newFromText( 'Talk:Some page' ) ],
1620 "<p><b>Some page\n</b></p>",
1623 'addWikiTextAsContent' => [
1624 'SpecialNewimages' => [
1625 [ "<p lang='en' dir='ltr'>\nMy message" ],
1626 '<p lang="en" dir="ltr">' . "\nMy message</p>"
1627 ], 'List at start' => [
1629 "<ul><li>List</li></ul>",
1630 ], 'List not at start' => [
1631 [ '* <b>Not a list', false ],
1632 '<p>* <b>Not a list</b></p>',
1633 ], 'With title at start' => [
1634 [ '* {{PAGENAME}}', true, Title
::newFromText( 'Talk:Some page' ) ],
1635 "<ul><li>Some page</li></ul>\n",
1636 ], 'With title at start' => [
1637 [ '* {{PAGENAME}}', false, Title
::newFromText( 'Talk:Some page' ), false ],
1638 "<p>* Some page</p>",
1640 [ "<div class='mw-editintro'>{{PAGENAME}}", true, Title
::newFromText( 'Talk:Some page' ) ],
1641 '<div class="mw-editintro">' . "Some page</div>"
1644 'wrapWikiTextAsInterface' => [
1646 [ 'wrapperClass', 'text' ],
1647 "<div class=\"wrapperClass\"><p>text\n</p></div>"
1648 ], 'Spurious </div>' => [
1649 [ 'wrapperClass', 'text</div><div>more' ],
1650 "<div class=\"wrapperClass\"><p>text</p><div>more</div></div>"
1651 ], 'Extra newlines would break <p> wrappers' => [
1652 [ 'two classes', "1\n\n2\n\n3" ],
1653 "<div class=\"two classes\"><p>1\n</p><p>2\n</p><p>3\n</p></div>"
1654 ], 'Other unclosed tags' => [
1655 [ 'error', 'a<b>c<i>d' ],
1656 "<div class=\"error\"><p>a<b>c<i>d\n</i></b></p></div>"
1661 // We have to reformat our array to match what PHPUnit wants
1663 foreach ( $tests as $key => $subarray ) {
1664 foreach ( $subarray as $subkey => $val ) {
1665 $val = array_merge( [ $key ], $val );
1666 $ret[$subkey] = $val;
1674 * @covers OutputPage::addWikiTextAsInterface
1676 public function testAddWikiTextAsInterfaceNoTitle() {
1677 $this->setExpectedException( MWException
::class, 'Title is null' );
1679 $op = $this->newInstance( [], null, 'notitle' );
1680 $op->addWikiTextAsInterface( 'a' );
1684 * @covers OutputPage::addWikiTextAsContent
1686 public function testAddWikiTextAsContentNoTitle() {
1687 $this->setExpectedException( MWException
::class, 'Title is null' );
1689 $op = $this->newInstance( [], null, 'notitle' );
1690 $op->addWikiTextAsContent( 'a' );
1694 * @covers OutputPage::addWikiMsg
1696 public function testAddWikiMsg() {
1697 $msg = wfMessage( 'parentheses' );
1698 $this->assertSame( '(a)', $msg->rawParams( 'a' )->plain() );
1700 $op = $this->newInstance();
1701 $this->assertSame( '', $op->getHTML() );
1702 $op->addWikiMsg( 'parentheses', "<b>a" );
1703 // The input is bad unbalanced HTML, but the output is tidied
1704 $this->assertSame( "<p>(<b>a)\n</b></p>", $op->getHTML() );
1708 * @covers OutputPage::wrapWikiMsg
1710 public function testWrapWikiMsg() {
1711 $msg = wfMessage( 'parentheses' );
1712 $this->assertSame( '(a)', $msg->rawParams( 'a' )->plain() );
1714 $op = $this->newInstance();
1715 $this->assertSame( '', $op->getHTML() );
1716 $op->wrapWikiMsg( '[$1]', [ 'parentheses', "<b>a" ] );
1717 // The input is bad unbalanced HTML, but the output is tidied
1718 $this->assertSame( "<p>[(<b>a)]\n</b></p>", $op->getHTML() );
1722 * @covers OutputPage::addParserOutputMetadata
1723 * @covers OutputPage::addParserOutput
1725 public function testNoGallery() {
1726 $op = $this->newInstance();
1727 $this->assertFalse( $op->mNoGallery
);
1729 $stubPO1 = $this->createParserOutputStub( 'getNoGallery', true );
1730 $op->addParserOutputMetadata( $stubPO1 );
1731 $this->assertTrue( $op->mNoGallery
);
1733 $stubPO2 = $this->createParserOutputStub( 'getNoGallery', false );
1734 $op->addParserOutput( $stubPO2 );
1735 $this->assertFalse( $op->mNoGallery
);
1738 private static $parserOutputHookCalled;
1741 * @covers OutputPage::addParserOutputMetadata
1743 public function testParserOutputHooks() {
1744 $op = $this->newInstance();
1745 $pOut = $this->createParserOutputStub( 'getOutputHooks', [
1746 [ 'myhook', 'banana' ],
1747 [ 'yourhook', 'kumquat' ],
1748 [ 'theirhook', 'hippopotamus' ],
1751 self
::$parserOutputHookCalled = [];
1753 $this->setMwGlobals( 'wgParserOutputHooks', [
1754 'myhook' => function ( OutputPage
$innerOp, ParserOutput
$innerPOut, $data )
1755 use ( $op, $pOut ) {
1756 $this->assertSame( $op, $innerOp );
1757 $this->assertSame( $pOut, $innerPOut );
1758 $this->assertSame( 'banana', $data );
1759 self
::$parserOutputHookCalled[] = 'closure';
1761 'yourhook' => [ $this, 'parserOutputHookCallback' ],
1762 'theirhook' => [ __CLASS__
, 'parserOutputHookCallbackStatic' ],
1763 'uncalled' => function () {
1764 $this->assertTrue( false );
1768 $op->addParserOutputMetadata( $pOut );
1770 $this->assertSame( [ 'closure', 'callback', 'static' ], self
::$parserOutputHookCalled );
1773 public function parserOutputHookCallback(
1774 OutputPage
$op, ParserOutput
$pOut, $data
1776 $this->assertSame( 'kumquat', $data );
1778 self
::$parserOutputHookCalled[] = 'callback';
1781 public static function parserOutputHookCallbackStatic(
1782 OutputPage
$op, ParserOutput
$pOut, $data
1784 // All the assert methods are actually static, who knew!
1785 self
::assertSame( 'hippopotamus', $data );
1787 self
::$parserOutputHookCalled[] = 'static';
1790 // @todo Make sure to test the following in addParserOutputMetadata() as well when we add tests
1793 // * addModuleStyles()
1794 // * addJsConfigVars()
1796 // Otherwise those lines of addParserOutputMetadata() will be reported as covered, but we won't
1797 // be testing they actually work.
1800 * @covers OutputPage::addParserOutputText
1802 public function testAddParserOutputText() {
1803 $op = $this->newInstance();
1804 $this->assertSame( '', $op->getHTML() );
1806 $pOut = $this->createParserOutputStub( 'getText', '<some text>' );
1808 $op->addParserOutputMetadata( $pOut );
1809 $this->assertSame( '', $op->getHTML() );
1811 $op->addParserOutputText( $pOut );
1812 $this->assertSame( '<some text>', $op->getHTML() );
1816 * @covers OutputPage::addParserOutput
1818 public function testAddParserOutput() {
1819 $op = $this->newInstance();
1820 $this->assertSame( '', $op->getHTML() );
1821 $this->assertFalse( $op->showNewSectionLink() );
1823 $pOut = $this->createParserOutputStub( [
1824 'getText' => '<some text>',
1825 'getNewSection' => true,
1828 $op->addParserOutput( $pOut );
1829 $this->assertSame( '<some text>', $op->getHTML() );
1830 $this->assertTrue( $op->showNewSectionLink() );
1834 * @covers OutputPage::addTemplate
1836 public function testAddTemplate() {
1837 $template = $this->getMock( QuickTemplate
::class );
1838 $template->method( 'getHTML' )->willReturn( '<abc>&def;' );
1840 $op = $this->newInstance();
1841 $op->addTemplate( $template );
1843 $this->assertSame( '<abc>&def;', $op->getHTML() );
1847 * @dataProvider provideParse
1848 * @covers OutputPage::parse
1849 * @param array $args To pass to parse()
1850 * @param string $expectedHTML Expected return value for parse()
1851 * @param string $expectedHTML Expected return value for parseInline(), if different
1853 public function testParse( array $args, $expectedHTML ) {
1854 $this->hideDeprecated( 'OutputPage::parse' );
1855 $op = $this->newInstance();
1856 $this->assertSame( $expectedHTML, $op->parse( ...$args ) );
1860 * @dataProvider provideParse
1861 * @covers OutputPage::parseInline
1863 public function testParseInline( array $args, $expectedHTML, $expectedHTMLInline = null ) {
1864 if ( count( $args ) > 3 ) {
1865 // $language param not supported
1866 $this->assertTrue( true );
1869 $this->hideDeprecated( 'OutputPage::parseInline' );
1870 $op = $this->newInstance();
1871 $this->assertSame( $expectedHTMLInline ??
$expectedHTML, $op->parseInline( ...$args ) );
1874 public function provideParse() {
1876 'List at start of line (content)' => [
1877 [ '* List', true, false ],
1878 "<div class=\"mw-parser-output\"><ul><li>List</li></ul></div>",
1879 "<ul><li>List</li></ul>",
1881 'List at start of line (interface)' => [
1882 [ '* List', true, true ],
1883 "<ul><li>List</li></ul>",
1885 'List not at start (content)' => [
1886 [ "* ''Not'' list", false, false ],
1887 '<div class="mw-parser-output">* <i>Not</i> list</div>',
1888 '* <i>Not</i> list',
1890 'List not at start (interface)' => [
1891 [ "* ''Not'' list", false, true ],
1892 '* <i>Not</i> list',
1894 'Interface message' => [
1895 [ "''Italic''", true, true ],
1896 "<p><i>Italic</i>\n</p>",
1899 'formatnum (content)' => [
1900 [ '{{formatnum:123456.789}}', true, false ],
1901 "<div class=\"mw-parser-output\"><p>123,456.789\n</p></div>",
1904 'formatnum (interface)' => [
1905 [ '{{formatnum:123456.789}}', true, true ],
1906 "<p>123,456.789\n</p>",
1909 'Language (content)' => [
1910 [ '{{formatnum:123456.789}}', true, false, Language
::factory( 'is' ) ],
1911 "<div class=\"mw-parser-output\"><p>123.456,789\n</p></div>",
1913 'Language (interface)' => [
1914 [ '{{formatnum:123456.789}}', true, true, Language
::factory( 'is' ) ],
1915 "<p>123.456,789\n</p>",
1918 'No section edit links' => [
1920 '<div class="mw-parser-output"><h2><span class="mw-headline" id="Header">' .
1921 "Header</span></h2></div>",
1922 '<h2><span class="mw-headline" id="Header">Header</span></h2>',
1928 * @dataProvider provideParseAs
1929 * @covers OutputPage::parseAsContent
1930 * @param array $args To pass to parse()
1931 * @param string $expectedHTML Expected return value for parseAsContent()
1932 * @param string $expectedHTML Expected return value for parseInlineAsInterface(), if different
1934 public function testParseAsContent(
1935 array $args, $expectedHTML, $expectedHTMLInline = null
1937 $op = $this->newInstance();
1938 $this->assertSame( $expectedHTML, $op->parseAsContent( ...$args ) );
1942 * @dataProvider provideParseAs
1943 * @covers OutputPage::parseAsInterface
1944 * @param array $args To pass to parse()
1945 * @param string $expectedHTML Expected return value for parseAsInterface()
1946 * @param string $expectedHTML Expected return value for parseInlineAsInterface(), if different
1948 public function testParseAsInterface(
1949 array $args, $expectedHTML, $expectedHTMLInline = null
1951 $op = $this->newInstance();
1952 $this->assertSame( $expectedHTML, $op->parseAsInterface( ...$args ) );
1956 * @dataProvider provideParseAs
1957 * @covers OutputPage::parseInlineAsInterface
1959 public function testParseInlineAsInterface(
1960 array $args, $expectedHTML, $expectedHTMLInline = null
1962 $op = $this->newInstance();
1964 $expectedHTMLInline ??
$expectedHTML,
1965 $op->parseInlineAsInterface( ...$args )
1969 public function provideParseAs() {
1971 'List at start of line' => [
1973 "<ul><li>List</li></ul>",
1975 'List not at start' => [
1976 [ "* ''Not'' list", false ],
1977 '<p>* <i>Not</i> list</p>',
1978 '* <i>Not</i> list',
1981 [ "''Italic''", true ],
1982 "<p><i>Italic</i>\n</p>",
1986 [ '{{formatnum:123456.789}}', true ],
1987 "<p>123,456.789\n</p>",
1990 'No section edit links' => [
1992 '<h2><span class="mw-headline" id="Header">Header</span></h2>',
1998 * @covers OutputPage::parse
2000 public function testParseNullTitle() {
2001 $this->hideDeprecated( 'OutputPage::parse' );
2002 $this->setExpectedException( MWException
::class, 'Empty $mTitle in OutputPage::parseInternal' );
2003 $op = $this->newInstance( [], null, 'notitle' );
2008 * @covers OutputPage::parseInline
2010 public function testParseInlineNullTitle() {
2011 $this->hideDeprecated( 'OutputPage::parseInline' );
2012 $this->setExpectedException( MWException
::class, 'Empty $mTitle in OutputPage::parseInternal' );
2013 $op = $this->newInstance( [], null, 'notitle' );
2014 $op->parseInline( '' );
2018 * @covers OutputPage::parseAsContent
2020 public function testParseAsContentNullTitle() {
2021 $this->setExpectedException( MWException
::class, 'Empty $mTitle in OutputPage::parseInternal' );
2022 $op = $this->newInstance( [], null, 'notitle' );
2023 $op->parseAsContent( '' );
2027 * @covers OutputPage::parseAsInterface
2029 public function testParseAsInterfaceNullTitle() {
2030 $this->setExpectedException( MWException
::class, 'Empty $mTitle in OutputPage::parseInternal' );
2031 $op = $this->newInstance( [], null, 'notitle' );
2032 $op->parseAsInterface( '' );
2036 * @covers OutputPage::parseInlineAsInterface
2038 public function testParseInlineAsInterfaceNullTitle() {
2039 $this->setExpectedException( MWException
::class, 'Empty $mTitle in OutputPage::parseInternal' );
2040 $op = $this->newInstance( [], null, 'notitle' );
2041 $op->parseInlineAsInterface( '' );
2045 * @covers OutputPage::setCdnMaxage
2046 * @covers OutputPage::lowerCdnMaxage
2048 public function testCdnMaxage() {
2049 $op = $this->newInstance();
2050 $wrapper = TestingAccessWrapper
::newFromObject( $op );
2051 $this->assertSame( 0, $wrapper->mCdnMaxage
);
2053 $op->setCdnMaxage( -1 );
2054 $this->assertSame( -1, $wrapper->mCdnMaxage
);
2056 $op->setCdnMaxage( 120 );
2057 $this->assertSame( 120, $wrapper->mCdnMaxage
);
2059 $op->setCdnMaxage( 60 );
2060 $this->assertSame( 60, $wrapper->mCdnMaxage
);
2062 $op->setCdnMaxage( 180 );
2063 $this->assertSame( 180, $wrapper->mCdnMaxage
);
2065 $op->lowerCdnMaxage( 240 );
2066 $this->assertSame( 180, $wrapper->mCdnMaxage
);
2068 $op->setCdnMaxage( 300 );
2069 $this->assertSame( 240, $wrapper->mCdnMaxage
);
2071 $op->lowerCdnMaxage( 120 );
2072 $this->assertSame( 120, $wrapper->mCdnMaxage
);
2074 $op->setCdnMaxage( 180 );
2075 $this->assertSame( 120, $wrapper->mCdnMaxage
);
2077 $op->setCdnMaxage( 60 );
2078 $this->assertSame( 60, $wrapper->mCdnMaxage
);
2080 $op->setCdnMaxage( 240 );
2081 $this->assertSame( 120, $wrapper->mCdnMaxage
);
2084 /** @var int Faked time to set for tests that need it */
2085 private static $fakeTime;
2088 * @dataProvider provideAdaptCdnTTL
2089 * @covers OutputPage::adaptCdnTTL
2090 * @param array $args To pass to adaptCdnTTL()
2091 * @param int $expected Expected new value of mCdnMaxageLimit
2092 * @param array $options Associative array:
2093 * initialMaxage => Maxage to set before calling adaptCdnTTL() (default 86400)
2095 public function testAdaptCdnTTL( array $args, $expected, array $options = [] ) {
2097 MWTimestamp
::setFakeTime( self
::$fakeTime );
2099 $op = $this->newInstance();
2100 // Set a high maxage so that it will get reduced by adaptCdnTTL(). The default maxage
2101 // is 0, so adaptCdnTTL() won't mutate the object at all.
2102 $initial = $options['initialMaxage'] ??
86400;
2103 $op->setCdnMaxage( $initial );
2105 $op->adaptCdnTTL( ...$args );
2107 MWTimestamp
::setFakeTime( false );
2110 $wrapper = TestingAccessWrapper
::newFromObject( $op );
2112 // Special rules for false/null
2113 if ( $args[0] === null ||
$args[0] === false ) {
2114 $this->assertSame( $initial, $wrapper->mCdnMaxage
, 'member value' );
2115 $op->setCdnMaxage( $expected +
1 );
2116 $this->assertSame( $expected +
1, $wrapper->mCdnMaxage
, 'member value after new set' );
2120 $this->assertSame( $expected, $wrapper->mCdnMaxageLimit
, 'limit value' );
2122 if ( $initial >= $expected ) {
2123 $this->assertSame( $expected, $wrapper->mCdnMaxage
, 'member value' );
2125 $this->assertSame( $initial, $wrapper->mCdnMaxage
, 'member value' );
2128 $op->setCdnMaxage( $expected +
1 );
2129 $this->assertSame( $expected, $wrapper->mCdnMaxage
, 'member value after new set' );
2132 public function provideAdaptCdnTTL() {
2133 global $wgCdnMaxAge;
2135 self
::$fakeTime = $now;
2137 'Five minutes ago' => [ [ $now - 300 ], 270 ],
2138 'Now' => [ [ +
0 ], IExpiringStore
::TTL_MINUTE
],
2139 'Five minutes from now' => [ [ $now +
300 ], IExpiringStore
::TTL_MINUTE
],
2140 'Five minutes ago, initial maxage four minutes' =>
2141 [ [ $now - 300 ], 270, [ 'initialMaxage' => 240 ] ],
2142 'A very long time ago' => [ [ $now - 1000000000 ], $wgCdnMaxAge ],
2143 'Initial maxage zero' => [ [ $now - 300 ], 270, [ 'initialMaxage' => 0 ] ],
2145 'false' => [ [ false ], IExpiringStore
::TTL_MINUTE
],
2146 'null' => [ [ null ], IExpiringStore
::TTL_MINUTE
],
2147 "'0'" => [ [ '0' ], IExpiringStore
::TTL_MINUTE
],
2148 'Empty string' => [ [ '' ], IExpiringStore
::TTL_MINUTE
],
2149 // @todo These give incorrect results due to timezones, how to test?
2150 //"'now'" => [ [ 'now' ], IExpiringStore::TTL_MINUTE ],
2151 //"'parse error'" => [ [ 'parse error' ], IExpiringStore::TTL_MINUTE ],
2153 'Now, minTTL 0' => [ [ $now, 0 ], IExpiringStore
::TTL_MINUTE
],
2154 'Now, minTTL 0.000001' => [ [ $now, 0.000001 ], 0 ],
2155 'A very long time ago, maxTTL even longer' =>
2156 [ [ $now - 1000000000, 0, 1000000001 ], 900000000 ],
2161 * @covers OutputPage::enableClientCache
2162 * @covers OutputPage::addParserOutputMetadata
2163 * @covers OutputPage::addParserOutput
2165 public function testClientCache() {
2166 $op = $this->newInstance();
2168 // Test initial value
2169 $this->assertSame( true, $op->enableClientCache( null ) );
2170 // Test that calling with null doesn't change the value
2171 $this->assertSame( true, $op->enableClientCache( null ) );
2173 // Test setting to false
2174 $this->assertSame( true, $op->enableClientCache( false ) );
2175 $this->assertSame( false, $op->enableClientCache( null ) );
2176 // Test that calling with null doesn't change the value
2177 $this->assertSame( false, $op->enableClientCache( null ) );
2179 // Test that a cacheable ParserOutput doesn't set to true
2180 $pOutCacheable = $this->createParserOutputStub( 'isCacheable', true );
2181 $op->addParserOutputMetadata( $pOutCacheable );
2182 $this->assertSame( false, $op->enableClientCache( null ) );
2184 // Test setting back to true
2185 $this->assertSame( false, $op->enableClientCache( true ) );
2186 $this->assertSame( true, $op->enableClientCache( null ) );
2188 // Test that an uncacheable ParserOutput does set to false
2189 $pOutUncacheable = $this->createParserOutputStub( 'isCacheable', false );
2190 $op->addParserOutput( $pOutUncacheable );
2191 $this->assertSame( false, $op->enableClientCache( null ) );
2195 * @covers OutputPage::getCacheVaryCookies
2197 public function testGetCacheVaryCookies() {
2198 global $wgCookiePrefix, $wgDBname;
2199 $op = $this->newInstance();
2200 $prefix = $wgCookiePrefix !== false ?
$wgCookiePrefix : $wgDBname;
2201 $expectedCookies = [
2203 "{$prefix}LoggedOut",
2204 "{$prefix}_session",
2210 // We have to reset the cookies because getCacheVaryCookies may have already been called
2211 TestingAccessWrapper
::newFromClass( OutputPage
::class )->cacheVaryCookies
= null;
2213 $this->setMwGlobals( 'wgCacheVaryCookies', [ 'cookie1' ] );
2214 $this->setTemporaryHook( 'GetCacheVaryCookies',
2215 function ( $innerOP, &$cookies ) use ( $op, $expectedCookies ) {
2216 $this->assertSame( $op, $innerOP );
2217 $cookies[] = 'cookie2';
2218 $this->assertSame( $expectedCookies, $cookies );
2222 $this->assertSame( $expectedCookies, $op->getCacheVaryCookies() );
2226 * @covers OutputPage::haveCacheVaryCookies
2228 public function testHaveCacheVaryCookies() {
2229 $request = new FauxRequest();
2230 $op = $this->newInstance( [], $request );
2232 // No cookies are set.
2233 $this->assertFalse( $op->haveCacheVaryCookies() );
2235 // 'Token' is present but empty, so it shouldn't count.
2236 $request->setCookie( 'Token', '' );
2237 $this->assertFalse( $op->haveCacheVaryCookies() );
2239 // 'Token' present and nonempty.
2240 $request->setCookie( 'Token', '123' );
2241 $this->assertTrue( $op->haveCacheVaryCookies() );
2245 * @dataProvider provideVaryHeaders
2247 * @covers OutputPage::addVaryHeader
2248 * @covers OutputPage::getVaryHeader
2250 * @param array[] $calls For each array, call addVaryHeader() with those arguments
2251 * @param string[] $cookies Array of cookie names to vary on
2252 * @param string $vary Text of expected Vary header (including the 'Vary: ')
2254 public function testVaryHeaders( array $calls, array $cookies, $vary ) {
2255 // Get rid of default Vary fields
2256 $op = $this->getMockBuilder( OutputPage
::class )
2257 ->setConstructorArgs( [ new RequestContext() ] )
2258 ->setMethods( [ 'getCacheVaryCookies' ] )
2260 $op->expects( $this->any() )
2261 ->method( 'getCacheVaryCookies' )
2262 ->will( $this->returnValue( $cookies ) );
2263 TestingAccessWrapper
::newFromObject( $op )->mVaryHeader
= [];
2265 $this->hideDeprecated( 'addVaryHeader $option is ignored' );
2266 foreach ( $calls as $call ) {
2267 $op->addVaryHeader( ...$call );
2269 $this->assertEquals( $vary, $op->getVaryHeader(), 'Vary:' );
2272 public function provideVaryHeaders() {
2279 'Single header' => [
2286 'Non-unique headers' => [
2289 [ 'Accept-Language' ],
2293 'Vary: Cookie, Accept-Language',
2295 'Two headers with single options' => [
2296 // Options are deprecated since 1.34
2298 [ 'Cookie', [ 'param=phpsessid' ] ],
2299 [ 'Accept-Language', [ 'substr=en' ] ],
2302 'Vary: Cookie, Accept-Language',
2304 'One header with multiple options' => [
2305 // Options are deprecated since 1.34
2307 [ 'Cookie', [ 'param=phpsessid', 'param=userId' ] ],
2312 'Duplicate option' => [
2313 // Options are deprecated since 1.34
2315 [ 'Cookie', [ 'param=phpsessid' ] ],
2316 [ 'Cookie', [ 'param=phpsessid' ] ],
2317 [ 'Accept-Language', [ 'substr=en', 'substr=en' ] ],
2320 'Vary: Cookie, Accept-Language',
2322 'Same header, different options' => [
2323 // Options are deprecated since 1.34
2325 [ 'Cookie', [ 'param=phpsessid' ] ],
2326 [ 'Cookie', [ 'param=userId' ] ],
2331 'No header, vary cookies' => [
2333 [ 'cookie1', 'cookie2' ],
2336 'Cookie header with option plus vary cookies' => [
2337 // Options are deprecated since 1.34
2339 [ 'Cookie', [ 'param=cookie1' ] ],
2341 [ 'cookie2', 'cookie3' ],
2344 'Non-cookie header plus vary cookies' => [
2346 [ 'Accept-Language' ],
2349 'Vary: Accept-Language, Cookie',
2351 'Cookie and non-cookie headers plus vary cookies' => [
2352 // Options are deprecated since 1.34
2354 [ 'Cookie', [ 'param=cookie1' ] ],
2355 [ 'Accept-Language' ],
2358 'Vary: Cookie, Accept-Language',
2364 * @covers OutputPage::getVaryHeader
2366 public function testVaryHeaderDefault() {
2367 $op = $this->newInstance();
2368 $this->assertSame( 'Vary: Accept-Encoding, Cookie', $op->getVaryHeader() );
2372 * @dataProvider provideLinkHeaders
2374 * @covers OutputPage::addLinkHeader
2375 * @covers OutputPage::getLinkHeader
2377 public function testLinkHeaders( array $headers, $result ) {
2378 $op = $this->newInstance();
2380 foreach ( $headers as $header ) {
2381 $op->addLinkHeader( $header );
2384 $this->assertEquals( $result, $op->getLinkHeader() );
2387 public function provideLinkHeaders() {
2394 [ '<https://foo/bar.jpg>;rel=preload;as=image' ],
2395 'Link: <https://foo/bar.jpg>;rel=preload;as=image',
2399 '<https://foo/bar.jpg>;rel=preload;as=image',
2400 '<https://foo/baz.jpg>;rel=preload;as=image'
2402 'Link: <https://foo/bar.jpg>;rel=preload;as=image,<https://foo/baz.jpg>;' .
2403 'rel=preload;as=image',
2409 * @dataProvider provideAddAcceptLanguage
2410 * @covers OutputPage::addAcceptLanguage
2412 public function testAddAcceptLanguage(
2413 $code, array $variants, $expected, array $options = []
2415 $req = new FauxRequest( in_array( 'varianturl', $options ) ?
[ 'variant' => 'x' ] : [] );
2416 $op = $this->newInstance( [], $req, in_array( 'notitle', $options ) ?
'notitle' : null );
2418 if ( !in_array( 'notitle', $options ) ) {
2419 $mockLang = $this->getMock( Language
::class );
2421 if ( in_array( 'varianturl', $options ) ) {
2422 $mockLang->expects( $this->never() )->method( $this->anything() );
2424 $mockLang->method( 'hasVariants' )->willReturn( count( $variants ) > 1 );
2425 $mockLang->method( 'getVariants' )->willReturn( $variants );
2426 $mockLang->method( 'getCode' )->willReturn( $code );
2429 $mockTitle = $this->getMock( Title
::class );
2430 $mockTitle->method( 'getPageLanguage' )->willReturn( $mockLang );
2432 $op->setTitle( $mockTitle );
2435 // This will run addAcceptLanguage()
2436 $op->sendCacheControl();
2437 $this->assertSame( "Vary: $expected", $op->getVaryHeader() );
2440 public function provideAddAcceptLanguage() {
2445 'Accept-Encoding, Cookie',
2447 'One simple variant' => [
2449 [ 'en', 'en-x-piglatin' ],
2450 'Accept-Encoding, Cookie, Accept-Language',
2452 'Multiple variants with BCP47 alternatives' => [
2454 [ 'zh', 'zh-hans', 'zh-cn', 'zh-tw' ],
2455 'Accept-Encoding, Cookie, Accept-Language',
2459 [ 'en', 'en-x-piglatin' ],
2460 'Accept-Encoding, Cookie',
2463 'Variant in URL' => [
2465 [ 'en', 'en-x-piglatin' ],
2466 'Accept-Encoding, Cookie',
2473 * @covers OutputPage::preventClickjacking
2474 * @covers OutputPage::allowClickjacking
2475 * @covers OutputPage::getPreventClickjacking
2476 * @covers OutputPage::addParserOutputMetadata
2477 * @covers OutputPage::addParserOutput
2479 public function testClickjacking() {
2480 $op = $this->newInstance();
2481 $this->assertTrue( $op->getPreventClickjacking() );
2483 $op->allowClickjacking();
2484 $this->assertFalse( $op->getPreventClickjacking() );
2486 $op->preventClickjacking();
2487 $this->assertTrue( $op->getPreventClickjacking() );
2489 $op->preventClickjacking( false );
2490 $this->assertFalse( $op->getPreventClickjacking() );
2492 $pOut1 = $this->createParserOutputStub( 'preventClickjacking', true );
2493 $op->addParserOutputMetadata( $pOut1 );
2494 $this->assertTrue( $op->getPreventClickjacking() );
2496 // The ParserOutput can't allow, only prevent
2497 $pOut2 = $this->createParserOutputStub( 'preventClickjacking', false );
2498 $op->addParserOutputMetadata( $pOut2 );
2499 $this->assertTrue( $op->getPreventClickjacking() );
2501 // Reset to test with addParserOutput()
2502 $op->allowClickjacking();
2503 $this->assertFalse( $op->getPreventClickjacking() );
2505 $op->addParserOutput( $pOut1 );
2506 $this->assertTrue( $op->getPreventClickjacking() );
2508 $op->addParserOutput( $pOut2 );
2509 $this->assertTrue( $op->getPreventClickjacking() );
2513 * @dataProvider provideGetFrameOptions
2514 * @covers OutputPage::getFrameOptions
2515 * @covers OutputPage::preventClickjacking
2517 public function testGetFrameOptions(
2518 $breakFrames, $preventClickjacking, $editPageFrameOptions, $expected
2520 $op = $this->newInstance( [
2521 'BreakFrames' => $breakFrames,
2522 'EditPageFrameOptions' => $editPageFrameOptions,
2524 $op->preventClickjacking( $preventClickjacking );
2526 $this->assertSame( $expected, $op->getFrameOptions() );
2529 public function provideGetFrameOptions() {
2531 'BreakFrames true' => [ true, false, false, 'DENY' ],
2532 'Allow clickjacking locally' => [ false, false, 'DENY', false ],
2533 'Allow clickjacking globally' => [ false, true, false, false ],
2534 'DENY globally' => [ false, true, 'DENY', 'DENY' ],
2535 'SAMEORIGIN' => [ false, true, 'SAMEORIGIN', 'SAMEORIGIN' ],
2536 'BreakFrames with SAMEORIGIN' => [ true, true, 'SAMEORIGIN', 'DENY' ],
2541 * See ResourceLoaderClientHtmlTest for full coverage.
2543 * @dataProvider provideMakeResourceLoaderLink
2545 * @covers OutputPage::makeResourceLoaderLink
2547 public function testMakeResourceLoaderLink( $args, $expectedHtml ) {
2548 $this->setMwGlobals( [
2549 'wgResourceLoaderDebug' => false,
2550 'wgLoadScript' => 'http://127.0.0.1:8080/w/load.php',
2551 'wgCSPReportOnlyHeader' => true,
2553 $class = new ReflectionClass( OutputPage
::class );
2554 $method = $class->getMethod( 'makeResourceLoaderLink' );
2555 $method->setAccessible( true );
2556 $ctx = new RequestContext();
2557 $skinFactory = MediaWikiServices
::getInstance()->getSkinFactory();
2558 $ctx->setSkin( $skinFactory->makeSkin( 'fallback' ) );
2559 $ctx->setLanguage( 'en' );
2560 $out = new OutputPage( $ctx );
2561 $nonce = $class->getProperty( 'CSPNonce' );
2562 $nonce->setAccessible( true );
2563 $nonce->setValue( $out, 'secret' );
2564 $rl = $out->getResourceLoader();
2565 $rl->setMessageBlobStore( $this->createMock( MessageBlobStore
::class ) );
2567 'test.foo' => new ResourceLoaderTestModule( [
2568 'script' => 'mw.test.foo( { a: true } );',
2569 'styles' => '.mw-test-foo { content: "style"; }',
2571 'test.bar' => new ResourceLoaderTestModule( [
2572 'script' => 'mw.test.bar( { a: true } );',
2573 'styles' => '.mw-test-bar { content: "style"; }',
2575 'test.baz' => new ResourceLoaderTestModule( [
2576 'script' => 'mw.test.baz( { a: true } );',
2577 'styles' => '.mw-test-baz { content: "style"; }',
2579 'test.quux' => new ResourceLoaderTestModule( [
2580 'script' => 'mw.test.baz( { token: 123 } );',
2581 'styles' => '/* pref-animate=off */ .mw-icon { transition: none; }',
2582 'group' => 'private',
2584 'test.noscript' => new ResourceLoaderTestModule( [
2585 'styles' => '.stuff { color: red; }',
2586 'group' => 'noscript',
2588 'test.group.foo' => new ResourceLoaderTestModule( [
2589 'script' => 'mw.doStuff( "foo" );',
2592 'test.group.bar' => new ResourceLoaderTestModule( [
2593 'script' => 'mw.doStuff( "bar" );',
2597 $links = $method->invokeArgs( $out, $args );
2598 $actualHtml = strval( $links );
2599 $this->assertEquals( $expectedHtml, $actualHtml );
2602 public static function provideMakeResourceLoaderLink() {
2603 // phpcs:disable Generic.Files.LineLength
2605 // Single only=scripts load
2607 [ 'test.foo', ResourceLoaderModule
::TYPE_SCRIPTS
],
2608 "<script nonce=\"secret\">(RLQ=window.RLQ||[]).push(function(){"
2609 . 'mw.loader.load("http://127.0.0.1:8080/w/load.php?lang=en\u0026modules=test.foo\u0026only=scripts");'
2612 // Multiple only=styles load
2614 [ [ 'test.baz', 'test.foo', 'test.bar' ], ResourceLoaderModule
::TYPE_STYLES
],
2616 '<link rel="stylesheet" href="http://127.0.0.1:8080/w/load.php?lang=en&modules=test.bar%2Cbaz%2Cfoo&only=styles"/>'
2618 // Private embed (only=scripts)
2620 [ 'test.quux', ResourceLoaderModule
::TYPE_SCRIPTS
],
2621 "<script nonce=\"secret\">(RLQ=window.RLQ||[]).push(function(){"
2622 . "mw.test.baz({token:123});\nmw.loader.state({\"test.quux\":\"ready\"});"
2625 // Load private module (combined)
2627 [ 'test.quux', ResourceLoaderModule
::TYPE_COMBINED
],
2628 "<script nonce=\"secret\">(RLQ=window.RLQ||[]).push(function(){"
2629 . "mw.loader.implement(\"test.quux@1ev0ijv\",function($,jQuery,require,module){"
2630 . "mw.test.baz({token:123});},{\"css\":[\".mw-icon{transition:none}"
2631 . "\"]});});</script>"
2635 [ [], ResourceLoaderModule
::TYPE_COMBINED
],
2640 [ 'test.noscript', ResourceLoaderModule
::TYPE_STYLES
],
2641 '<noscript><link rel="stylesheet" href="http://127.0.0.1:8080/w/load.php?lang=en&modules=test.noscript&only=styles"/></noscript>'
2643 // Load two modules in separate groups
2645 [ [ 'test.group.foo', 'test.group.bar' ], ResourceLoaderModule
::TYPE_COMBINED
],
2646 "<script nonce=\"secret\">(RLQ=window.RLQ||[]).push(function(){"
2647 . 'mw.loader.load("http://127.0.0.1:8080/w/load.php?lang=en\u0026modules=test.group.bar");'
2648 . 'mw.loader.load("http://127.0.0.1:8080/w/load.php?lang=en\u0026modules=test.group.foo");'
2656 * @dataProvider provideBuildExemptModules
2658 * @covers OutputPage::buildExemptModules
2660 public function testBuildExemptModules( array $exemptStyleModules, $expect ) {
2661 $this->setMwGlobals( [
2662 'wgResourceLoaderDebug' => false,
2663 'wgLoadScript' => '/w/load.php',
2664 // Stub wgCacheEpoch as it influences getVersionHash used for the
2665 // urls in the expected HTML
2666 'wgCacheEpoch' => '20140101000000',
2670 $ctx = new RequestContext();
2671 $skinFactory = MediaWikiServices
::getInstance()->getSkinFactory();
2672 $ctx->setSkin( $skinFactory->makeSkin( 'fallback' ) );
2673 $ctx->setLanguage( 'en' );
2674 $op = $this->getMockBuilder( OutputPage
::class )
2675 ->setConstructorArgs( [ $ctx ] )
2676 ->setMethods( [ 'buildCssLinksArray' ] )
2678 $op->expects( $this->any() )
2679 ->method( 'buildCssLinksArray' )
2681 $rl = $op->getResourceLoader();
2682 $rl->setMessageBlobStore( $this->createMock( MessageBlobStore
::class ) );
2684 // Register custom modules
2686 'example.site.a' => new ResourceLoaderTestModule( [ 'group' => 'site' ] ),
2687 'example.site.b' => new ResourceLoaderTestModule( [ 'group' => 'site' ] ),
2688 'example.user' => new ResourceLoaderTestModule( [ 'group' => 'user' ] ),
2691 $op = TestingAccessWrapper
::newFromObject( $op );
2692 $op->rlExemptStyleModules
= $exemptStyleModules;
2693 $this->assertEquals(
2695 strval( $op->buildExemptModules() )
2699 public static function provideBuildExemptModules() {
2700 // phpcs:disable Generic.Files.LineLength
2703 'exemptStyleModules' => [],
2704 '<meta name="ResourceLoaderDynamicStyles" content=""/>',
2707 'exemptStyleModules' => [ 'site' => [], 'noscript' => [], 'private' => [], 'user' => [] ],
2708 '<meta name="ResourceLoaderDynamicStyles" content=""/>',
2710 'default logged-out' => [
2711 'exemptStyleModules' => [ 'site' => [ 'site.styles' ] ],
2712 '<meta name="ResourceLoaderDynamicStyles" content=""/>' . "\n" .
2713 '<link rel="stylesheet" href="/w/load.php?lang=en&modules=site.styles&only=styles"/>',
2715 'default logged-in' => [
2716 'exemptStyleModules' => [ 'site' => [ 'site.styles' ], 'user' => [ 'user.styles' ] ],
2717 '<meta name="ResourceLoaderDynamicStyles" content=""/>' . "\n" .
2718 '<link rel="stylesheet" href="/w/load.php?lang=en&modules=site.styles&only=styles"/>' . "\n" .
2719 '<link rel="stylesheet" href="/w/load.php?lang=en&modules=user.styles&only=styles&version=1ai9g6t"/>',
2721 'custom modules' => [
2722 'exemptStyleModules' => [
2723 'site' => [ 'site.styles', 'example.site.a', 'example.site.b' ],
2724 'user' => [ 'user.styles', 'example.user' ],
2726 '<meta name="ResourceLoaderDynamicStyles" content=""/>' . "\n" .
2727 '<link rel="stylesheet" href="/w/load.php?lang=en&modules=example.site.a%2Cb&only=styles"/>' . "\n" .
2728 '<link rel="stylesheet" href="/w/load.php?lang=en&modules=site.styles&only=styles"/>' . "\n" .
2729 '<link rel="stylesheet" href="/w/load.php?lang=en&modules=example.user&only=styles&version=0a56zyi"/>' . "\n" .
2730 '<link rel="stylesheet" href="/w/load.php?lang=en&modules=user.styles&only=styles&version=1ai9g6t"/>',
2737 * @dataProvider provideTransformFilePath
2738 * @covers OutputPage::transformFilePath
2739 * @covers OutputPage::transformResourcePath
2741 public function testTransformResourcePath( $baseDir, $basePath, $uploadDir = null,
2742 $uploadPath = null, $path = null, $expected = null
2744 if ( $path === null ) {
2745 // Skip optional $uploadDir and $uploadPath
2747 $expected = $uploadPath;
2748 $uploadDir = "$baseDir/images";
2749 $uploadPath = "$basePath/images";
2751 $this->setMwGlobals( 'IP', $baseDir );
2752 $conf = new HashConfig( [
2753 'ResourceBasePath' => $basePath,
2754 'UploadDirectory' => $uploadDir,
2755 'UploadPath' => $uploadPath,
2758 // Some of these paths don't exist and will cause warnings
2759 Wikimedia\
suppressWarnings();
2760 $actual = OutputPage
::transformResourcePath( $conf, $path );
2761 Wikimedia\restoreWarnings
();
2763 $this->assertEquals( $expected ?
: $path, $actual );
2766 public static function provideTransformFilePath() {
2767 $baseDir = dirname( __DIR__
) . '/data/media';
2769 // File that matches basePath, and exists. Hash found and appended.
2771 'baseDir' => $baseDir, 'basePath' => '/w',
2775 // File that matches basePath, but not found on disk. Empty query.
2777 'baseDir' => $baseDir, 'basePath' => '/w',
2781 // File not matching basePath. Ignored.
2783 'baseDir' => $baseDir, 'basePath' => '/w',
2786 // Empty string. Ignored.
2788 'baseDir' => $baseDir, 'basePath' => '/w',
2792 // Similar path, but with domain component. Ignored.
2794 'baseDir' => $baseDir, 'basePath' => '/w',
2795 '//example.org/w/test.jpg'
2798 'baseDir' => $baseDir, 'basePath' => '/w',
2799 'https://example.org/w/test.jpg'
2801 // Unrelated path with domain component. Ignored.
2803 'baseDir' => $baseDir, 'basePath' => '/w',
2804 'https://example.org/files/test.jpg'
2807 'baseDir' => $baseDir, 'basePath' => '/w',
2808 '//example.org/files/test.jpg'
2810 // Unrelated path with domain, and empty base path (root mw install). Ignored.
2812 'baseDir' => $baseDir, 'basePath' => '',
2813 'https://example.org/files/test.jpg'
2816 'baseDir' => $baseDir, 'basePath' => '',
2818 '//example.org/files/test.jpg'
2820 // Check UploadPath before ResourceBasePath (T155146)
2822 'baseDir' => dirname( $baseDir ), 'basePath' => '',
2823 'uploadDir' => $baseDir, 'uploadPath' => '/images',
2825 '/images/test.jpg?edcf2'
2831 * Tests a particular case of transformCssMedia, using the given input, globals,
2832 * expected return, and message
2834 * Asserts that $expectedReturn is returned.
2836 * options['printableQuery'] - value of query string for printable, or omitted for none
2837 * options['handheldQuery'] - value of query string for handheld, or omitted for none
2838 * options['media'] - passed into the method under the same name
2839 * options['expectedReturn'] - expected return value
2840 * options['message'] - PHPUnit message for assertion
2842 * @param array $args Key-value array of arguments as shown above
2844 protected function assertTransformCssMediaCase( $args ) {
2846 if ( isset( $args['printableQuery'] ) ) {
2847 $queryData['printable'] = $args['printableQuery'];
2850 if ( isset( $args['handheldQuery'] ) ) {
2851 $queryData['handheld'] = $args['handheldQuery'];
2854 $fauxRequest = new FauxRequest( $queryData, false );
2855 $this->setMwGlobals( [
2856 'wgRequest' => $fauxRequest,
2859 $actualReturn = OutputPage
::transformCssMedia( $args['media'] );
2860 $this->assertSame( $args['expectedReturn'], $actualReturn, $args['message'] );
2864 * Tests print requests
2866 * @covers OutputPage::transformCssMedia
2868 public function testPrintRequests() {
2869 $this->assertTransformCssMediaCase( [
2870 'printableQuery' => '1',
2871 'media' => 'screen',
2872 'expectedReturn' => null,
2873 'message' => 'On printable request, screen returns null'
2876 $this->assertTransformCssMediaCase( [
2877 'printableQuery' => '1',
2878 'media' => self
::SCREEN_MEDIA_QUERY
,
2879 'expectedReturn' => null,
2880 'message' => 'On printable request, screen media query returns null'
2883 $this->assertTransformCssMediaCase( [
2884 'printableQuery' => '1',
2885 'media' => self
::SCREEN_ONLY_MEDIA_QUERY
,
2886 'expectedReturn' => null,
2887 'message' => 'On printable request, screen media query with only returns null'
2890 $this->assertTransformCssMediaCase( [
2891 'printableQuery' => '1',
2893 'expectedReturn' => '',
2894 'message' => 'On printable request, media print returns empty string'
2899 * Tests screen requests, without either query parameter set
2901 * @covers OutputPage::transformCssMedia
2903 public function testScreenRequests() {
2904 $this->assertTransformCssMediaCase( [
2905 'media' => 'screen',
2906 'expectedReturn' => 'screen',
2907 'message' => 'On screen request, screen media type is preserved'
2910 $this->assertTransformCssMediaCase( [
2911 'media' => 'handheld',
2912 'expectedReturn' => 'handheld',
2913 'message' => 'On screen request, handheld media type is preserved'
2916 $this->assertTransformCssMediaCase( [
2917 'media' => self
::SCREEN_MEDIA_QUERY
,
2918 'expectedReturn' => self
::SCREEN_MEDIA_QUERY
,
2919 'message' => 'On screen request, screen media query is preserved.'
2922 $this->assertTransformCssMediaCase( [
2923 'media' => self
::SCREEN_ONLY_MEDIA_QUERY
,
2924 'expectedReturn' => self
::SCREEN_ONLY_MEDIA_QUERY
,
2925 'message' => 'On screen request, screen media query with only is preserved.'
2928 $this->assertTransformCssMediaCase( [
2930 'expectedReturn' => 'print',
2931 'message' => 'On screen request, print media type is preserved'
2936 * Tests handheld behavior
2938 * @covers OutputPage::transformCssMedia
2940 public function testHandheld() {
2941 $this->assertTransformCssMediaCase( [
2942 'handheldQuery' => '1',
2943 'media' => 'handheld',
2944 'expectedReturn' => '',
2945 'message' => 'On request with handheld querystring and media is handheld, returns empty string'
2948 $this->assertTransformCssMediaCase( [
2949 'handheldQuery' => '1',
2950 'media' => 'screen',
2951 'expectedReturn' => null,
2952 'message' => 'On request with handheld querystring and media is screen, returns null'
2957 * @covers OutputPage::isTOCEnabled
2958 * @covers OutputPage::addParserOutputMetadata
2959 * @covers OutputPage::addParserOutput
2961 public function testIsTOCEnabled() {
2962 $op = $this->newInstance();
2963 $this->assertFalse( $op->isTOCEnabled() );
2965 $pOut1 = $this->createParserOutputStub( 'getTOCHTML', false );
2966 $op->addParserOutputMetadata( $pOut1 );
2967 $this->assertFalse( $op->isTOCEnabled() );
2969 $pOut2 = $this->createParserOutputStub( 'getTOCHTML', true );
2970 $op->addParserOutput( $pOut2 );
2971 $this->assertTrue( $op->isTOCEnabled() );
2973 // The parser output doesn't disable the TOC after it was enabled
2974 $op->addParserOutputMetadata( $pOut1 );
2975 $this->assertTrue( $op->isTOCEnabled() );
2979 * @dataProvider providePreloadLinkHeaders
2980 * @covers ResourceLoaderSkinModule::getPreloadLinks
2981 * @covers ResourceLoaderSkinModule::getLogoPreloadlinks
2983 public function testPreloadLinkHeaders( $config, $result ) {
2984 $this->setMwGlobals( $config );
2985 $ctx = $this->getMockBuilder( ResourceLoaderContext
::class )
2986 ->disableOriginalConstructor()->getMock();
2987 $module = new ResourceLoaderSkinModule();
2989 $this->assertEquals( [ $result ], $module->getHeaders( $ctx ) );
2992 public function providePreloadLinkHeaders() {
2996 'wgResourceBasePath' => '/w',
2997 'wgLogo' => '/img/default.png',
2999 '1.5x' => '/img/one-point-five.png',
3000 '2x' => '/img/two-x.png',
3003 'Link: </img/default.png>;rel=preload;as=image;media=' .
3004 'not all and (min-resolution: 1.5dppx),' .
3005 '</img/one-point-five.png>;rel=preload;as=image;media=' .
3006 '(min-resolution: 1.5dppx) and (max-resolution: 1.999999dppx),' .
3007 '</img/two-x.png>;rel=preload;as=image;media=(min-resolution: 2dppx)'
3011 'wgResourceBasePath' => '/w',
3012 'wgLogo' => '/img/default.png',
3013 'wgLogoHD' => false,
3015 'Link: </img/default.png>;rel=preload;as=image'
3019 'wgResourceBasePath' => '/w',
3020 'wgLogo' => '/img/default.png',
3022 '2x' => '/img/two-x.png',
3025 'Link: </img/default.png>;rel=preload;as=image;media=' .
3026 'not all and (min-resolution: 2dppx),' .
3027 '</img/two-x.png>;rel=preload;as=image;media=(min-resolution: 2dppx)'
3031 'wgResourceBasePath' => '/w',
3032 'wgLogo' => '/img/default.png',
3034 'svg' => '/img/vector.svg',
3037 'Link: </img/vector.svg>;rel=preload;as=image'
3042 'wgResourceBasePath' => '/w',
3043 'wgLogo' => '/w/test.jpg',
3044 'wgLogoHD' => false,
3045 'wgUploadPath' => '/w/images',
3046 'IP' => dirname( __DIR__
) . '/data/media',
3048 'Link: </w/test.jpg?edcf2>;rel=preload;as=image',
3054 * @return OutputPage
3056 private function newInstance( $config = [], WebRequest
$request = null, $options = [] ) {
3057 $context = new RequestContext();
3059 $context->setConfig( new MultiConfig( [
3060 new HashConfig( $config +
[
3061 'AppleTouchIcon' => false,
3062 'DisableLangConversion' => true,
3063 'EnableCanonicalServerLink' => false,
3066 'LanguageCode' => false,
3067 'ReferrerPolicy' => false,
3068 'RightsPage' => false,
3069 'RightsUrl' => false,
3070 'UniversalEditButton' => false,
3072 $context->getConfig()
3075 if ( !in_array( 'notitle', (array)$options ) ) {
3076 $context->setTitle( Title
::newFromText( 'My test page' ) );
3080 $context->setRequest( $request );
3083 return new OutputPage( $context );