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 // Ensure that we don't affect the global ResourceLoader state.
16 protected function setUp() {
18 ResourceLoader
::clearCache();
20 protected function tearDown() {
22 ResourceLoader
::clearCache();
26 * @dataProvider provideRedirect
28 * @covers OutputPage::__construct
29 * @covers OutputPage::redirect
30 * @covers OutputPage::getRedirect
32 public function testRedirect( $url, $code = null ) {
33 $op = $this->newInstance();
34 if ( isset( $code ) ) {
35 $op->redirect( $url, $code );
37 $op->redirect( $url );
39 $expectedUrl = str_replace( "\n", '', $url );
40 $this->assertSame( $expectedUrl, $op->getRedirect() );
41 $this->assertSame( $expectedUrl, $op->mRedirect
);
42 $this->assertSame( $code ??
'302', $op->mRedirectCode
);
45 public function provideRedirect() {
47 [ 'http://example.com' ],
48 [ 'http://example.com', '400' ],
49 [ 'http://example.com', 'squirrels!!!' ],
55 * @covers OutputPage::setCopyrightUrl
56 * @covers OutputPage::getHeadLinksArray
58 public function testSetCopyrightUrl() {
59 $op = $this->newInstance();
60 $op->setCopyrightUrl( 'http://example.com' );
63 Html
::element( 'link', [ 'rel' => 'license', 'href' => 'http://example.com' ] ),
64 $op->getHeadLinksArray()['copyright']
68 // @todo How to test setStatusCode?
71 * @covers OutputPage::addMeta
72 * @covers OutputPage::getMetaTags
73 * @covers OutputPage::getHeadLinksArray
75 public function testMetaTags() {
76 $op = $this->newInstance();
77 $op->addMeta( 'http:expires', '0' );
78 $op->addMeta( 'keywords', 'first' );
79 $op->addMeta( 'keywords', 'second' );
80 $op->addMeta( 'og:title', 'Ta-duh' );
83 [ 'http:expires', '0' ],
84 [ 'keywords', 'first' ],
85 [ 'keywords', 'second' ],
86 [ 'og:title', 'Ta-duh' ],
88 $this->assertSame( $expected, $op->getMetaTags() );
90 $links = $op->getHeadLinksArray();
91 $this->assertContains( '<meta http-equiv="expires" content="0"/>', $links );
92 $this->assertContains( '<meta name="keywords" content="first"/>', $links );
93 $this->assertContains( '<meta name="keywords" content="second"/>', $links );
94 $this->assertContains( '<meta property="og:title" content="Ta-duh"/>', $links );
95 $this->assertArrayNotHasKey( 'meta-robots', $links );
99 * @covers OutputPage::addLink
100 * @covers OutputPage::getLinkTags
101 * @covers OutputPage::getHeadLinksArray
103 public function testAddLink() {
104 $op = $this->newInstance();
108 [ 'rel' => 'foo', 'href' => 'http://example.com' ],
111 foreach ( $links as $link ) {
112 $op->addLink( $link );
115 $this->assertSame( $links, $op->getLinkTags() );
117 $result = $op->getHeadLinksArray();
119 foreach ( $links as $link ) {
120 $this->assertContains( Html
::element( 'link', $link ), $result );
125 * @covers OutputPage::setCanonicalUrl
126 * @covers OutputPage::getCanonicalUrl
127 * @covers OutputPage::getHeadLinksArray
129 public function testSetCanonicalUrl() {
130 $op = $this->newInstance();
131 $op->setCanonicalUrl( 'http://example.comm' );
132 $op->setCanonicalUrl( 'http://example.com' );
134 $this->assertSame( 'http://example.com', $op->getCanonicalUrl() );
136 $headLinks = $op->getHeadLinksArray();
138 $this->assertContains( Html
::element( 'link', [
139 'rel' => 'canonical', 'href' => 'http://example.com'
142 $this->assertNotContains( Html
::element( 'link', [
143 'rel' => 'canonical', 'href' => 'http://example.comm'
148 * @covers OutputPage::addScript
150 public function testAddScript() {
151 $op = $this->newInstance();
152 $op->addScript( 'some random string' );
154 $this->assertContains( "\nsome random string\n", "\n" . $op->getBottomScripts() . "\n" );
158 * @covers OutputPage::addScriptFile
160 public function testAddScriptFile() {
161 $op = $this->newInstance();
162 $op->addScriptFile( '/somescript.js' );
163 $op->addScriptFile( '//example.com/somescript.js' );
165 $this->assertContains(
166 "\n" . Html
::linkedScript( '/somescript.js', $op->getCSPNonce() ) .
167 Html
::linkedScript( '//example.com/somescript.js', $op->getCSPNonce() ) . "\n",
168 "\n" . $op->getBottomScripts() . "\n"
173 * Test that addScriptFile() throws due to deprecation.
175 * @covers OutputPage::addScriptFile
177 public function testAddDeprecatedScriptFileWarning() {
178 $this->setExpectedException( PHPUnit_Framework_Error_Deprecated
::class,
179 'Use of OutputPage::addScriptFile was deprecated in MediaWiki 1.24.' );
181 $op = $this->newInstance();
182 $op->addScriptFile( 'ignored-script.js' );
186 * Test the actual behavior of the method (in the case where it doesn't throw, e.g., in
187 * production). Since it threw an exception once in this file, it won't when we call it again.
189 * @covers OutputPage::addScriptFile
191 public function testAddDeprecatedScriptFileNoOp() {
192 $op = $this->newInstance();
193 $op->addScriptFile( 'ignored-script.js' );
195 $this->assertNotContains( 'ignored-script.js', '' . $op->getBottomScripts() );
199 * @covers OutputPage::addInlineScript
201 public function testAddInlineScript() {
202 $op = $this->newInstance();
203 $op->addInlineScript( 'let foo = "bar";' );
204 $op->addInlineScript( 'alert( foo );' );
206 $this->assertContains(
207 "\n" . Html
::inlineScript( "\nlet foo = \"bar\";\n", $op->getCSPNonce() ) . "\n" .
208 Html
::inlineScript( "\nalert( foo );\n", $op->getCSPNonce() ) . "\n",
209 "\n" . $op->getBottomScripts() . "\n"
213 // @todo How to test filterModules(), warnModuleTargetFilter(), getModules(), etc.?
216 * @covers OutputPage::getTarget
217 * @covers OutputPage::setTarget
219 public function testSetTarget() {
220 $op = $this->newInstance();
221 $op->setTarget( 'foo' );
223 $this->assertSame( 'foo', $op->getTarget() );
224 // @todo What else? Test some actual effect?
227 // @todo How to test addContentOverride(Callback)?
230 * @covers OutputPage::getHeadItemsArray
231 * @covers OutputPage::addHeadItem
232 * @covers OutputPage::addHeadItems
233 * @covers OutputPage::hasHeadItem
235 public function testHeadItems() {
236 $op = $this->newInstance();
237 $op->addHeadItem( 'a', 'b' );
238 $op->addHeadItems( [ 'c' => '<d>&', 'e' => 'f', 'a' => 'q' ] );
239 $op->addHeadItem( 'e', 'g' );
240 $op->addHeadItems( 'x' );
242 $this->assertSame( [ 'a' => 'q', 'c' => '<d>&', 'e' => 'g', 'x' ],
243 $op->getHeadItemsArray() );
245 $this->assertTrue( $op->hasHeadItem( 'a' ) );
246 $this->assertTrue( $op->hasHeadItem( 'c' ) );
247 $this->assertTrue( $op->hasHeadItem( 'e' ) );
248 $this->assertTrue( $op->hasHeadItem( '0' ) );
250 $this->assertContains( "\nq\n<d>&\ng\nx\n",
251 '' . $op->headElement( $op->getContext()->getSkin() ) );
255 * @covers OutputPage::getHeadItemsArray
256 * @covers OutputPage::addParserOutputMetadata
258 public function testHeadItemsParserOutput() {
259 $op = $this->newInstance();
260 $stubPO1 = $this->createParserOutputStub( 'getHeadItems', [ 'a' => 'b' ] );
261 $op->addParserOutputMetadata( $stubPO1 );
262 $stubPO2 = $this->createParserOutputStub( 'getHeadItems',
263 [ 'c' => '<d>&', 'e' => 'f', 'a' => 'q' ] );
264 $op->addParserOutputMetadata( $stubPO2 );
265 $stubPO3 = $this->createParserOutputStub( 'getHeadItems', [ 'e' => 'g' ] );
266 $op->addParserOutputMetadata( $stubPO3 );
267 $stubPO4 = $this->createParserOutputStub( 'getHeadItems', [ 'x' ] );
268 $op->addParserOutputMetadata( $stubPO4 );
270 $this->assertSame( [ 'a' => 'q', 'c' => '<d>&', 'e' => 'g', 'x' ],
271 $op->getHeadItemsArray() );
273 $this->assertTrue( $op->hasHeadItem( 'a' ) );
274 $this->assertTrue( $op->hasHeadItem( 'c' ) );
275 $this->assertTrue( $op->hasHeadItem( 'e' ) );
276 $this->assertTrue( $op->hasHeadItem( '0' ) );
277 $this->assertFalse( $op->hasHeadItem( 'b' ) );
279 $this->assertContains( "\nq\n<d>&\ng\nx\n",
280 '' . $op->headElement( $op->getContext()->getSkin() ) );
284 * @covers OutputPage::addBodyClasses
286 public function testAddBodyClasses() {
287 $op = $this->newInstance();
288 $op->addBodyClasses( 'a' );
289 $op->addBodyClasses( 'mediawiki' );
290 $op->addBodyClasses( 'b c' );
291 $op->addBodyClasses( [ 'd', 'e' ] );
292 $op->addBodyClasses( 'a' );
294 $this->assertContains( '"a mediawiki b c d e ltr',
295 '' . $op->headElement( $op->getContext()->getSkin() ) );
299 * @covers OutputPage::setArticleBodyOnly
300 * @covers OutputPage::getArticleBodyOnly
302 public function testArticleBodyOnly() {
303 $op = $this->newInstance();
304 $this->assertFalse( $op->getArticleBodyOnly() );
306 $op->setArticleBodyOnly( true );
307 $this->assertTrue( $op->getArticleBodyOnly() );
309 $op->addHTML( '<b>a</b>' );
311 $this->assertSame( '<b>a</b>', $op->output( true ) );
315 * @covers OutputPage::setProperty
316 * @covers OutputPage::getProperty
318 public function testProperties() {
319 $op = $this->newInstance();
321 $this->assertNull( $op->getProperty( 'foo' ) );
323 $op->setProperty( 'foo', 'bar' );
324 $op->setProperty( 'baz', 'quz' );
326 $this->assertSame( 'bar', $op->getProperty( 'foo' ) );
327 $this->assertSame( 'quz', $op->getProperty( 'baz' ) );
331 * @dataProvider provideCheckLastModified
333 * @covers OutputPage::checkLastModified
334 * @covers OutputPage::getCdnCacheEpoch
336 public function testCheckLastModified(
337 $timestamp, $ifModifiedSince, $expected, $config = [], $callback = null
339 $request = new FauxRequest();
340 if ( $ifModifiedSince ) {
341 if ( is_numeric( $ifModifiedSince ) ) {
343 $ifModifiedSince = date( 'D, d M Y H:i:s', $ifModifiedSince ) . ' GMT';
345 $request->setHeader( 'If-Modified-Since', $ifModifiedSince );
348 if ( !isset( $config['CacheEpoch'] ) ) {
349 // Make sure it's not too recent
350 $config['CacheEpoch'] = '20000101000000';
353 $op = $this->newInstance( $config, $request );
356 $callback( $op, $this );
359 // Avoid a complaint about not being able to disable compression
360 Wikimedia\
suppressWarnings();
362 $this->assertEquals( $expected, $op->checkLastModified( $timestamp ) );
364 Wikimedia\restoreWarnings
();
368 public function provideCheckLastModified() {
369 $lastModified = time() - 3600;
372 [ '0', $lastModified, false ],
373 'Timestamp Unix epoch' =>
374 [ '19700101000000', $lastModified, false ],
375 'Timestamp same as If-Modified-Since' =>
376 [ $lastModified, $lastModified, true ],
377 'Timestamp one second after If-Modified-Since' =>
378 [ $lastModified +
1, $lastModified, false ],
379 'No If-Modified-Since' =>
380 [ $lastModified +
1, null, false ],
381 'Malformed If-Modified-Since' =>
382 [ $lastModified +
1, 'GIBBERING WOMBATS !!!', false ],
383 'Non-standard IE-style If-Modified-Since' =>
384 [ $lastModified, date( 'D, d M Y H:i:s', $lastModified ) . ' GMT; length=5202',
386 // @todo Should we fix this behavior to match the spec? Probably no reason to.
387 'If-Modified-Since not per spec but we accept it anyway because strtotime does' =>
388 [ $lastModified, "@$lastModified", true ],
389 '$wgCachePages = false' =>
390 [ $lastModified, $lastModified, false, [ 'CachePages' => false ] ],
392 [ $lastModified, $lastModified, false,
393 [ 'CacheEpoch' => wfTimestamp( TS_MW
, $lastModified +
1 ) ] ],
394 'Recently-touched user' =>
395 [ $lastModified, $lastModified, false, [],
397 $op->getContext()->setUser( $this->getTestUser()->getUser() );
399 'After Squid expiry' =>
400 [ $lastModified, $lastModified, false,
401 [ 'UseSquid' => true, 'SquidMaxage' => 3599 ] ],
402 'Hook allows cache use' =>
403 [ $lastModified +
1, $lastModified, true, [],
404 function ( $op, $that ) {
405 $that->setTemporaryHook( 'OutputPageCheckLastModified',
406 function ( &$modifiedTimes ) {
407 $modifiedTimes = [ 1 ];
411 'Hooks prohibits cache use' =>
412 [ $lastModified, $lastModified, false, [],
413 function ( $op, $that ) {
414 $that->setTemporaryHook( 'OutputPageCheckLastModified',
415 function ( &$modifiedTimes ) {
416 $modifiedTimes = [ max( $modifiedTimes ) +
1 ];
424 * @dataProvider provideCdnCacheEpoch
426 * @covers OutputPage::getCdnCacheEpoch
428 public function testCdnCacheEpoch( $params ) {
429 $out = TestingAccessWrapper
::newFromObject( $this->newInstance() );
430 $reqTime = strtotime( $params['reqTime'] );
431 $pageTime = strtotime( $params['pageTime'] );
432 $actual = max( $pageTime, $out->getCdnCacheEpoch( $reqTime, $params['maxAge'] ) );
436 gmdate( DateTime
::ATOM
, $actual ),
441 public static function provideCdnCacheEpoch() {
443 'pageTime' => '2011-04-01T12:00:00+00:00',
444 'maxAge' => 24 * 3600,
447 'after 1s' => [ $base +
[
448 'reqTime' => '2011-04-01T12:00:01+00:00',
449 'expect' => '2011-04-01T12:00:00+00:00',
451 'after 23h' => [ $base +
[
452 'reqTime' => '2011-04-02T11:00:00+00:00',
453 'expect' => '2011-04-01T12:00:00+00:00',
455 'after 24h and a bit' => [ $base +
[
456 'reqTime' => '2011-04-02T12:34:56+00:00',
457 'expect' => '2011-04-01T12:34:56+00:00',
459 'after a year' => [ $base +
[
460 'reqTime' => '2012-05-06T00:12:07+00:00',
461 'expect' => '2012-05-05T00:12:07+00:00',
466 // @todo How to test setLastModified?
469 * @covers OutputPage::setRobotPolicy
470 * @covers OutputPage::getHeadLinksArray
472 public function testSetRobotPolicy() {
473 $op = $this->newInstance();
474 $op->setRobotPolicy( 'noindex, nofollow' );
476 $links = $op->getHeadLinksArray();
477 $this->assertContains( '<meta name="robots" content="noindex,nofollow"/>', $links );
481 * @covers OutputPage::setIndexPolicy
482 * @covers OutputPage::setFollowPolicy
483 * @covers OutputPage::getHeadLinksArray
485 public function testSetIndexFollowPolicies() {
486 $op = $this->newInstance();
487 $op->setIndexPolicy( 'noindex' );
488 $op->setFollowPolicy( 'nofollow' );
490 $links = $op->getHeadLinksArray();
491 $this->assertContains( '<meta name="robots" content="noindex,nofollow"/>', $links );
494 private function extractHTMLTitle( OutputPage
$op ) {
495 $html = $op->headElement( $op->getContext()->getSkin() );
497 // OutputPage should always output the title in a nice format such that regexes will work
498 // fine. If it doesn't, we'll fail the tests.
499 preg_match_all( '!<title>(.*?)</title>!', $html, $matches );
501 $this->assertLessThanOrEqual( 1, count( $matches[1] ), 'More than one <title>!' );
503 if ( !count( $matches[1] ) ) {
507 return $matches[1][0];
511 * Shorthand for getting the text of a message, in content language.
513 private static function getMsgText( $op, ...$msgParams ) {
514 return $op->msg( ...$msgParams )->inContentLanguage()->text();
518 * @covers OutputPage::setHTMLTitle
519 * @covers OutputPage::getHTMLTitle
521 public function testHTMLTitle() {
522 $op = $this->newInstance();
525 $this->assertSame( '', $op->getHTMLTitle() );
526 $this->assertSame( '', $op->getPageTitle() );
528 $this->getMsgText( $op, 'pagetitle', '' ),
529 $this->extractHTMLTitle( $op )
533 $op->setHTMLTitle( 'Potatoes will eat me' );
535 $this->assertSame( 'Potatoes will eat me', $op->getHTMLTitle() );
536 $this->assertSame( 'Potatoes will eat me', $this->extractHTMLTitle( $op ) );
537 // Shouldn't have changed the page title
538 $this->assertSame( '', $op->getPageTitle() );
541 $msg = $op->msg( 'mainpage' );
543 $op->setHTMLTitle( $msg );
544 $this->assertSame( $msg->text(), $op->getHTMLTitle() );
545 $this->assertSame( $msg->text(), $this->extractHTMLTitle( $op ) );
546 $this->assertSame( '', $op->getPageTitle() );
550 * @covers OutputPage::setRedirectedFrom
552 public function testSetRedirectedFrom() {
553 $op = $this->newInstance();
555 $op->setRedirectedFrom( Title
::newFromText( 'Talk:Some page' ) );
556 $this->assertSame( 'Talk:Some_page', $op->getJSVars()['wgRedirectedFrom'] );
560 * @covers OutputPage::setPageTitle
561 * @covers OutputPage::getPageTitle
563 public function testPageTitle() {
564 // We don't test the actual HTML output anywhere, because that's up to the skin.
565 $op = $this->newInstance();
568 $this->assertSame( '', $op->getPageTitle() );
569 $this->assertSame( '', $op->getHTMLTitle() );
571 // Test set to plain text
572 $op->setPageTitle( 'foobar' );
574 $this->assertSame( 'foobar', $op->getPageTitle() );
575 // HTML title should change as well
576 $this->assertSame( $this->getMsgText( $op, 'pagetitle', 'foobar' ), $op->getHTMLTitle() );
578 // Test set to text with good and bad HTML. We don't try to be comprehensive here, that
579 // belongs in Sanitizer tests.
580 $op->setPageTitle( '<script>a</script>&<i>b</i>' );
582 $this->assertSame( '<script>a</script>&<i>b</i>', $op->getPageTitle() );
584 $this->getMsgText( $op, 'pagetitle', '<script>a</script>&b' ),
588 // Test set to message
589 $text = $this->getMsgText( $op, 'mainpage' );
591 $op->setPageTitle( $op->msg( 'mainpage' )->inContentLanguage() );
592 $this->assertSame( $text, $op->getPageTitle() );
593 $this->assertSame( $this->getMsgText( $op, 'pagetitle', $text ), $op->getHTMLTitle() );
597 * @covers OutputPage::setTitle
599 public function testSetTitle() {
600 $op = $this->newInstance();
602 $this->assertSame( 'My test page', $op->getTitle()->getPrefixedText() );
604 $op->setTitle( Title
::newFromText( 'Another test page' ) );
606 $this->assertSame( 'Another test page', $op->getTitle()->getPrefixedText() );
610 * @covers OutputPage::setSubtitle
611 * @covers OutputPage::clearSubtitle
612 * @covers OutputPage::addSubtitle
613 * @covers OutputPage::getSubtitle
615 public function testSubtitle() {
616 $op = $this->newInstance();
618 $this->assertSame( '', $op->getSubtitle() );
620 $op->addSubtitle( '<b>foo</b>' );
622 $this->assertSame( '<b>foo</b>', $op->getSubtitle() );
624 $op->addSubtitle( $op->msg( 'mainpage' )->inContentLanguage() );
627 "<b>foo</b><br />\n\t\t\t\t" . $this->getMsgText( $op, 'mainpage' ),
631 $op->setSubtitle( 'There can be only one' );
633 $this->assertSame( 'There can be only one', $op->getSubtitle() );
635 $op->clearSubtitle();
637 $this->assertSame( '', $op->getSubtitle() );
641 * @dataProvider provideBacklinkSubtitle
643 * @covers OutputPage::buildBacklinkSubtitle
645 public function testBuildBacklinkSubtitle( $titles, $queries, $contains, $notContains ) {
646 if ( count( $titles ) > 1 ) {
648 $this->assertTrue( true );
652 $title = Title
::newFromText( $titles[0] );
653 $query = $queries[0];
655 $this->editPage( 'Page 1', '' );
656 $this->editPage( 'Page 2', '#REDIRECT [[Page 1]]' );
658 $str = OutputPage
::buildBacklinkSubtitle( $title, $query )->text();
660 foreach ( $contains as $substr ) {
661 $this->assertContains( $substr, $str );
664 foreach ( $notContains as $substr ) {
665 $this->assertNotContains( $substr, $str );
670 * @dataProvider provideBacklinkSubtitle
672 * @covers OutputPage::addBacklinkSubtitle
673 * @covers OutputPage::getSubtitle
675 public function testAddBacklinkSubtitle( $titles, $queries, $contains, $notContains ) {
676 $this->editPage( 'Page 1', '' );
677 $this->editPage( 'Page 2', '#REDIRECT [[Page 1]]' );
679 $op = $this->newInstance();
680 foreach ( $titles as $i => $unused ) {
681 $op->addBacklinkSubtitle( Title
::newFromText( $titles[$i] ), $queries[$i] );
684 $str = $op->getSubtitle();
686 foreach ( $contains as $substr ) {
687 $this->assertContains( $substr, $str );
690 foreach ( $notContains as $substr ) {
691 $this->assertNotContains( $substr, $str );
695 public function provideBacklinkSubtitle() {
701 [ 'redirect', 'Page 2' ],
711 [ [ 'action' => 'edit' ] ],
716 [ 'Page 1', 'Page 2' ],
718 [ 'Page 1', 'Page 2', "<br />\n\t\t\t\t" ],
721 // @todo Anything else to test?
726 * @covers OutputPage::setPrintable
727 * @covers OutputPage::isPrintable
729 public function testPrintable() {
730 $op = $this->newInstance();
732 $this->assertFalse( $op->isPrintable() );
736 $this->assertTrue( $op->isPrintable() );
740 * @covers OutputPage::disable
741 * @covers OutputPage::isDisabled
743 public function testDisable() {
744 $op = $this->newInstance();
746 $this->assertFalse( $op->isDisabled() );
747 $this->assertNotSame( '', $op->output( true ) );
751 $this->assertTrue( $op->isDisabled() );
752 $this->assertSame( '', $op->output( true ) );
756 * @covers OutputPage::showNewSectionLink
757 * @covers OutputPage::addParserOutputMetadata
759 public function testShowNewSectionLink() {
760 $op = $this->newInstance();
762 $this->assertFalse( $op->showNewSectionLink() );
764 $po = new ParserOutput();
765 $po->setNewSection( true );
766 $op->addParserOutputMetadata( $po );
768 $this->assertTrue( $op->showNewSectionLink() );
772 * @covers OutputPage::forceHideNewSectionLink
773 * @covers OutputPage::addParserOutputMetadata
775 public function testForceHideNewSectionLink() {
776 $op = $this->newInstance();
778 $this->assertFalse( $op->forceHideNewSectionLink() );
780 $po = new ParserOutput();
781 $po->hideNewSection( true );
782 $op->addParserOutputMetadata( $po );
784 $this->assertTrue( $op->forceHideNewSectionLink() );
788 * @covers OutputPage::setSyndicated
789 * @covers OutputPage::isSyndicated
791 public function testSetSyndicated() {
792 $op = $this->newInstance();
793 $this->assertFalse( $op->isSyndicated() );
795 $op->setSyndicated();
796 $this->assertTrue( $op->isSyndicated() );
798 $op->setSyndicated( false );
799 $this->assertFalse( $op->isSyndicated() );
803 * @covers OutputPage::isSyndicated
804 * @covers OutputPage::setFeedAppendQuery
805 * @covers OutputPage::addFeedLink
806 * @covers OutputPage::getSyndicationLinks()
808 public function testFeedLinks() {
809 $op = $this->newInstance();
810 $this->assertSame( [], $op->getSyndicationLinks() );
812 $op->addFeedLink( 'not a supported format', 'abc' );
813 $this->assertFalse( $op->isSyndicated() );
814 $this->assertSame( [], $op->getSyndicationLinks() );
816 $feedTypes = $op->getConfig()->get( 'AdvertisedFeedTypes' );
818 $op->addFeedLink( $feedTypes[0], 'def' );
819 $this->assertTrue( $op->isSyndicated() );
820 $this->assertSame( [ $feedTypes[0] => 'def' ], $op->getSyndicationLinks() );
822 $op->setFeedAppendQuery( false );
824 foreach ( $feedTypes as $type ) {
825 $expected[$type] = $op->getTitle()->getLocalURL( "feed=$type" );
827 $this->assertSame( $expected, $op->getSyndicationLinks() );
829 $op->setFeedAppendQuery( 'apples=oranges' );
830 foreach ( $feedTypes as $type ) {
831 $expected[$type] = $op->getTitle()->getLocalURL( "feed=$type&apples=oranges" );
833 $this->assertSame( $expected, $op->getSyndicationLinks() );
837 * @covers OutputPage::setArticleFlag
838 * @covers OutputPage::isArticle
839 * @covers OutputPage::setArticleRelated
840 * @covers OutputPage::isArticleRelated
842 function testArticleFlags() {
843 $op = $this->newInstance();
844 $this->assertFalse( $op->isArticle() );
845 $this->assertTrue( $op->isArticleRelated() );
847 $op->setArticleRelated( false );
848 $this->assertFalse( $op->isArticle() );
849 $this->assertFalse( $op->isArticleRelated() );
851 $op->setArticleFlag( true );
852 $this->assertTrue( $op->isArticle() );
853 $this->assertTrue( $op->isArticleRelated() );
855 $op->setArticleFlag( false );
856 $this->assertFalse( $op->isArticle() );
857 $this->assertTrue( $op->isArticleRelated() );
859 $op->setArticleFlag( true );
860 $op->setArticleRelated( false );
861 $this->assertFalse( $op->isArticle() );
862 $this->assertFalse( $op->isArticleRelated() );
866 * @covers OutputPage::addLanguageLinks
867 * @covers OutputPage::setLanguageLinks
868 * @covers OutputPage::getLanguageLinks
869 * @covers OutputPage::addParserOutputMetadata
871 function testLanguageLinks() {
872 $op = $this->newInstance();
873 $this->assertSame( [], $op->getLanguageLinks() );
875 $op->addLanguageLinks( [ 'fr:A', 'it:B' ] );
876 $this->assertSame( [ 'fr:A', 'it:B' ], $op->getLanguageLinks() );
878 $op->addLanguageLinks( [ 'de:C', 'es:D' ] );
879 $this->assertSame( [ 'fr:A', 'it:B', 'de:C', 'es:D' ], $op->getLanguageLinks() );
881 $op->setLanguageLinks( [ 'pt:E' ] );
882 $this->assertSame( [ 'pt:E' ], $op->getLanguageLinks() );
884 $po = new ParserOutput();
885 $po->setLanguageLinks( [ 'he:F', 'ar:G' ] );
886 $op->addParserOutputMetadata( $po );
887 $this->assertSame( [ 'pt:E', 'he:F', 'ar:G' ], $op->getLanguageLinks() );
890 // @todo Are these category links tests too abstract and complicated for what they test? Would
891 // it make sense to just write out all the tests by hand with maybe some copy-and-paste?
894 * @dataProvider provideGetCategories
896 * @covers OutputPage::addCategoryLinks
897 * @covers OutputPage::getCategories
898 * @covers OutputPage::getCategoryLinks
900 * @param array $args Array of form [ category name => sort key ]
901 * @param array $fakeResults Array of form [ category name => value to return from mocked
903 * @param callback $variantLinkCallback Callback to replace findVariantLink() call
904 * @param array $expectedNormal Expected return value of getCategoryLinks['normal']
905 * @param array $expectedHidden Expected return value of getCategoryLinks['hidden']
907 public function testAddCategoryLinks(
908 array $args, array $fakeResults, callable
$variantLinkCallback = null,
909 array $expectedNormal, array $expectedHidden
911 $expectedNormal = $this->extractExpectedCategories( $expectedNormal, 'add' );
912 $expectedHidden = $this->extractExpectedCategories( $expectedHidden, 'add' );
914 $op = $this->setupCategoryTests( $fakeResults, $variantLinkCallback );
916 $op->addCategoryLinks( $args );
918 $this->doCategoryAsserts( $op, $expectedNormal, $expectedHidden );
919 $this->doCategoryLinkAsserts( $op, $expectedNormal, $expectedHidden );
923 * @dataProvider provideGetCategories
925 * @covers OutputPage::addCategoryLinks
926 * @covers OutputPage::getCategories
927 * @covers OutputPage::getCategoryLinks
929 public function testAddCategoryLinksOneByOne(
930 array $args, array $fakeResults, callable
$variantLinkCallback = null,
931 array $expectedNormal, array $expectedHidden
933 if ( count( $args ) <= 1 ) {
934 // @todo Should this be skipped instead of passed?
935 $this->assertTrue( true );
939 $expectedNormal = $this->extractExpectedCategories( $expectedNormal, 'onebyone' );
940 $expectedHidden = $this->extractExpectedCategories( $expectedHidden, 'onebyone' );
942 $op = $this->setupCategoryTests( $fakeResults, $variantLinkCallback );
944 foreach ( $args as $key => $val ) {
945 $op->addCategoryLinks( [ $key => $val ] );
948 $this->doCategoryAsserts( $op, $expectedNormal, $expectedHidden );
949 $this->doCategoryLinkAsserts( $op, $expectedNormal, $expectedHidden );
953 * @dataProvider provideGetCategories
955 * @covers OutputPage::setCategoryLinks
956 * @covers OutputPage::getCategories
957 * @covers OutputPage::getCategoryLinks
959 public function testSetCategoryLinks(
960 array $args, array $fakeResults, callable
$variantLinkCallback = null,
961 array $expectedNormal, array $expectedHidden
963 $expectedNormal = $this->extractExpectedCategories( $expectedNormal, 'set' );
964 $expectedHidden = $this->extractExpectedCategories( $expectedHidden, 'set' );
966 $op = $this->setupCategoryTests( $fakeResults, $variantLinkCallback );
968 $op->setCategoryLinks( [ 'Initial page' => 'Initial page' ] );
969 $op->setCategoryLinks( $args );
971 // We don't reset the categories, for some reason, only the links
972 $expectedNormalCats = array_merge( [ 'Initial page' ], $expectedNormal );
973 $expectedCats = array_merge( $expectedHidden, $expectedNormalCats );
975 $this->doCategoryAsserts( $op, $expectedNormalCats, $expectedHidden );
976 $this->doCategoryLinkAsserts( $op, $expectedNormal, $expectedHidden );
980 * @dataProvider provideGetCategories
982 * @covers OutputPage::addParserOutputMetadata
983 * @covers OutputPage::getCategories
984 * @covers OutputPage::getCategoryLinks
986 public function testParserOutputCategoryLinks(
987 array $args, array $fakeResults, callable
$variantLinkCallback = null,
988 array $expectedNormal, array $expectedHidden
990 $expectedNormal = $this->extractExpectedCategories( $expectedNormal, 'pout' );
991 $expectedHidden = $this->extractExpectedCategories( $expectedHidden, 'pout' );
993 $op = $this->setupCategoryTests( $fakeResults, $variantLinkCallback );
995 $stubPO = $this->createParserOutputStub( 'getCategories', $args );
997 $op->addParserOutputMetadata( $stubPO );
999 $this->doCategoryAsserts( $op, $expectedNormal, $expectedHidden );
1000 $this->doCategoryLinkAsserts( $op, $expectedNormal, $expectedHidden );
1004 * We allow different expectations for different tests as an associative array, like
1005 * [ 'set' => [ ... ], 'default' => [ ... ] ] if setCategoryLinks() will give a different
1008 private function extractExpectedCategories( array $expected, $key ) {
1009 if ( !$expected ||
isset( $expected[0] ) ) {
1012 return $expected[$key] ??
$expected['default'];
1015 private function setupCategoryTests(
1016 array $fakeResults, callable
$variantLinkCallback = null
1018 $this->setMwGlobals( 'wgUsePigLatinVariant', true );
1020 $op = $this->getMockBuilder( OutputPage
::class )
1021 ->setConstructorArgs( [ new RequestContext() ] )
1022 ->setMethods( [ 'addCategoryLinksToLBAndGetResult' ] )
1025 $op->expects( $this->any() )
1026 ->method( 'addCategoryLinksToLBAndGetResult' )
1027 ->will( $this->returnCallback( function ( array $categories ) use ( $fakeResults ) {
1029 foreach ( $categories as $category => $unused ) {
1030 if ( isset( $fakeResults[$category] ) ) {
1031 $return[] = $fakeResults[$category];
1034 return new FakeResultWrapper( $return );
1037 if ( $variantLinkCallback ) {
1038 $mockContLang = $this->getMockBuilder( Language
::class )
1039 ->setConstructorArgs( [ 'en' ] )
1040 ->setMethods( [ 'findVariantLink' ] )
1042 $mockContLang->expects( $this->any() )
1043 ->method( 'findVariantLink' )
1044 ->will( $this->returnCallback( $variantLinkCallback ) );
1045 $this->setContentLang( $mockContLang );
1048 $this->assertSame( [], $op->getCategories() );
1053 private function doCategoryAsserts( $op, $expectedNormal, $expectedHidden ) {
1054 $this->assertSame( array_merge( $expectedHidden, $expectedNormal ), $op->getCategories() );
1055 $this->assertSame( $expectedNormal, $op->getCategories( 'normal' ) );
1056 $this->assertSame( $expectedHidden, $op->getCategories( 'hidden' ) );
1059 private function doCategoryLinkAsserts( $op, $expectedNormal, $expectedHidden ) {
1060 $catLinks = $op->getCategoryLinks();
1061 $this->assertSame( (bool)$expectedNormal +
(bool)$expectedHidden, count( $catLinks ) );
1062 if ( $expectedNormal ) {
1063 $this->assertSame( count( $expectedNormal ), count( $catLinks['normal'] ) );
1065 if ( $expectedHidden ) {
1066 $this->assertSame( count( $expectedHidden ), count( $catLinks['hidden'] ) );
1069 foreach ( $expectedNormal as $i => $name ) {
1070 $this->assertContains( $name, $catLinks['normal'][$i] );
1072 foreach ( $expectedHidden as $i => $name ) {
1073 $this->assertContains( $name, $catLinks['hidden'][$i] );
1077 public function provideGetCategories() {
1079 'No categories' => [ [], [], null, [], [] ],
1081 [ 'Test1' => 'Some sortkey', 'Test2' => 'A different sortkey' ],
1082 [ 'Test1' => (object)[ 'pp_value' => 1, 'page_title' => 'Test1' ],
1083 'Test2' => (object)[ 'page_title' => 'Test2' ] ],
1088 'Invalid title' => [
1089 [ '[' => '[', 'Test' => 'Test' ],
1090 [ 'Test' => (object)[ 'page_title' => 'Test' ] ],
1096 [ 'Test' => 'Test', 'Estay' => 'Estay' ],
1097 [ 'Test' => (object)[ 'page_title' => 'Test' ] ],
1098 function ( &$link, &$title ) {
1099 if ( $link === 'Estay' ) {
1101 $title = Title
::makeTitleSafe( NS_CATEGORY
, $link );
1104 // For adding one by one, the variant gets added as well as the original category,
1105 // but if you add them all together the second time gets skipped.
1106 [ 'onebyone' => [ 'Test', 'Test' ], 'default' => [ 'Test' ] ],
1113 * @covers OutputPage::getCategories
1115 public function testGetCategoriesInvalid() {
1116 $this->setExpectedException( InvalidArgumentException
::class,
1117 'Invalid category type given: hiddne' );
1119 $op = $this->newInstance();
1120 $op->getCategories( 'hiddne' );
1123 // @todo Should we test addCategoryLinksToLBAndGetResult? If so, how? Insert some test rows in
1127 * @covers OutputPage::setIndicators
1128 * @covers OutputPage::getIndicators
1129 * @covers OutputPage::addParserOutputMetadata
1131 public function testIndicators() {
1132 $op = $this->newInstance();
1133 $this->assertSame( [], $op->getIndicators() );
1135 $op->setIndicators( [] );
1136 $this->assertSame( [], $op->getIndicators() );
1138 // Test sorting alphabetically
1139 $op->setIndicators( [ 'b' => 'x', 'a' => 'y' ] );
1140 $this->assertSame( [ 'a' => 'y', 'b' => 'x' ], $op->getIndicators() );
1142 // Test overwriting existing keys
1143 $op->setIndicators( [ 'c' => 'z', 'a' => 'w' ] );
1144 $this->assertSame( [ 'a' => 'w', 'b' => 'x', 'c' => 'z' ], $op->getIndicators() );
1146 // Test with ParserOutput
1147 $stubPO = $this->createParserOutputStub( 'getIndicators', [ 'c' => 'u', 'd' => 'v' ] );
1148 $op->addParserOutputMetadata( $stubPO );
1149 $this->assertSame( [ 'a' => 'w', 'b' => 'x', 'c' => 'u', 'd' => 'v' ],
1150 $op->getIndicators() );
1154 * @covers OutputPage::addHelpLink
1155 * @covers OutputPage::getIndicators
1157 public function testAddHelpLink() {
1158 $op = $this->newInstance();
1160 $op->addHelpLink( 'Manual:PHP unit testing' );
1161 $indicators = $op->getIndicators();
1162 $this->assertSame( [ 'mw-helplink' ], array_keys( $indicators ) );
1163 $this->assertContains( 'Manual:PHP_unit_testing', $indicators['mw-helplink'] );
1165 $op->addHelpLink( 'https://phpunit.de', true );
1166 $indicators = $op->getIndicators();
1167 $this->assertSame( [ 'mw-helplink' ], array_keys( $indicators ) );
1168 $this->assertContains( 'https://phpunit.de', $indicators['mw-helplink'] );
1169 $this->assertNotContains( 'mediawiki', $indicators['mw-helplink'] );
1170 $this->assertNotContains( 'Manual:PHP', $indicators['mw-helplink'] );
1174 * @covers OutputPage::prependHTML
1175 * @covers OutputPage::addHTML
1176 * @covers OutputPage::addElement
1177 * @covers OutputPage::clearHTML
1178 * @covers OutputPage::getHTML
1180 public function testBodyHTML() {
1181 $op = $this->newInstance();
1182 $this->assertSame( '', $op->getHTML() );
1184 $op->addHTML( 'a' );
1185 $this->assertSame( 'a', $op->getHTML() );
1187 $op->addHTML( 'b' );
1188 $this->assertSame( 'ab', $op->getHTML() );
1190 $op->prependHTML( 'c' );
1191 $this->assertSame( 'cab', $op->getHTML() );
1193 $op->addElement( 'p', [ 'id' => 'foo' ], 'd' );
1194 $this->assertSame( 'cab<p id="foo">d</p>', $op->getHTML() );
1197 $this->assertSame( '', $op->getHTML() );
1201 * @dataProvider provideRevisionId
1202 * @covers OutputPage::setRevisionId
1203 * @covers OutputPage::getRevisionId
1205 public function testRevisionId( $newVal, $expected ) {
1206 $op = $this->newInstance();
1208 $this->assertNull( $op->setRevisionId( $newVal ) );
1209 $this->assertSame( $expected, $op->getRevisionId() );
1210 $this->assertSame( $expected, $op->setRevisionId( null ) );
1211 $this->assertNull( $op->getRevisionId() );
1214 public function provideRevisionId() {
1221 [ '32% finished', 32 ],
1227 * @covers OutputPage::setRevisionTimestamp
1228 * @covers OutputPage::getRevisionTimestamp
1230 public function testRevisionTimestamp() {
1231 $op = $this->newInstance();
1232 $this->assertNull( $op->getRevisionTimestamp() );
1234 $this->assertNull( $op->setRevisionTimestamp( 'abc' ) );
1235 $this->assertSame( 'abc', $op->getRevisionTimestamp() );
1236 $this->assertSame( 'abc', $op->setRevisionTimestamp( null ) );
1237 $this->assertNull( $op->getRevisionTimestamp() );
1241 * @covers OutputPage::setFileVersion
1242 * @covers OutputPage::getFileVersion
1244 public function testFileVersion() {
1245 $op = $this->newInstance();
1246 $this->assertNull( $op->getFileVersion() );
1248 $stubFile = $this->createMock( File
::class );
1249 $stubFile->method( 'exists' )->willReturn( true );
1250 $stubFile->method( 'getTimestamp' )->willReturn( '12211221123321' );
1251 $stubFile->method( 'getSha1' )->willReturn( 'bf3ffa7047dc080f5855377a4f83cd18887e3b05' );
1253 $op->setFileVersion( $stubFile );
1255 $this->assertEquals(
1256 [ 'time' => '12211221123321', 'sha1' => 'bf3ffa7047dc080f5855377a4f83cd18887e3b05' ],
1257 $op->getFileVersion()
1260 $stubMissingFile = $this->createMock( File
::class );
1261 $stubMissingFile->method( 'exists' )->willReturn( false );
1263 $op->setFileVersion( $stubMissingFile );
1264 $this->assertNull( $op->getFileVersion() );
1266 $op->setFileVersion( $stubFile );
1267 $this->assertNotNull( $op->getFileVersion() );
1269 $op->setFileVersion( null );
1270 $this->assertNull( $op->getFileVersion() );
1273 private function createParserOutputStub( $method = '', $retVal = [] ) {
1274 $pOut = $this->getMock( ParserOutput
::class );
1275 if ( $method !== '' ) {
1276 $pOut->method( $method )->willReturn( $retVal );
1279 $arrayReturningMethods = [
1281 'getFileSearchOptions',
1289 foreach ( $arrayReturningMethods as $method ) {
1290 $pOut->method( $method )->willReturn( [] );
1297 * @covers OutputPage::getTemplateIds
1298 * @covers OutputPage::addParserOutputMetadata
1300 public function testTemplateIds() {
1301 $op = $this->newInstance();
1302 $this->assertSame( [], $op->getTemplateIds() );
1304 // Test with no template id's
1305 $stubPOEmpty = $this->createParserOutputStub();
1306 $op->addParserOutputMetadata( $stubPOEmpty );
1307 $this->assertSame( [], $op->getTemplateIds() );
1309 // Test with some arbitrary template id's
1311 NS_MAIN
=> [ 'A' => 3, 'B' => 17 ],
1312 NS_TALK
=> [ 'C' => 31 ],
1313 NS_MEDIA
=> [ 'D' => -1 ],
1316 $stubPO1 = $this->createParserOutputStub( 'getTemplateIds', $ids );
1318 $op->addParserOutputMetadata( $stubPO1 );
1319 $this->assertSame( $ids, $op->getTemplateIds() );
1321 // Test merging with a second set of id's
1322 $stubPO2 = $this->createParserOutputStub( 'getTemplateIds', [
1323 NS_MAIN
=> [ 'E' => 1234 ],
1324 NS_PROJECT
=> [ 'F' => 5678 ],
1328 NS_MAIN
=> [ 'E' => 1234, 'A' => 3, 'B' => 17 ],
1329 NS_TALK
=> [ 'C' => 31 ],
1330 NS_MEDIA
=> [ 'D' => -1 ],
1331 NS_PROJECT
=> [ 'F' => 5678 ],
1334 $op->addParserOutputMetadata( $stubPO2 );
1335 $this->assertSame( $finalIds, $op->getTemplateIds() );
1337 // Test merging with an empty set of id's
1338 $op->addParserOutputMetadata( $stubPOEmpty );
1339 $this->assertSame( $finalIds, $op->getTemplateIds() );
1343 * @covers OutputPage::getFileSearchOptions
1344 * @covers OutputPage::addParserOutputMetadata
1346 public function testFileSearchOptions() {
1347 $op = $this->newInstance();
1348 $this->assertSame( [], $op->getFileSearchOptions() );
1350 // Test with no files
1351 $stubPOEmpty = $this->createParserOutputStub();
1353 $op->addParserOutputMetadata( $stubPOEmpty );
1354 $this->assertSame( [], $op->getFileSearchOptions() );
1356 // Test with some arbitrary files
1358 'A' => [ 'time' => null, 'sha1' => '' ],
1360 'time' => '12211221123321',
1361 'sha1' => 'bf3ffa7047dc080f5855377a4f83cd18887e3b05',
1365 $stubPO1 = $this->createParserOutputStub( 'getFileSearchOptions', $files1 );
1367 $op->addParserOutputMetadata( $stubPO1 );
1368 $this->assertSame( $files1, $op->getFileSearchOptions() );
1370 // Test merging with a second set of files
1372 'C' => [ 'time' => null, 'sha1' => '' ],
1373 'B' => [ 'time' => null, 'sha1' => '' ],
1376 $stubPO2 = $this->createParserOutputStub( 'getFileSearchOptions', $files2 );
1378 $op->addParserOutputMetadata( $stubPO2 );
1379 $this->assertSame( array_merge( $files1, $files2 ), $op->getFileSearchOptions() );
1381 // Test merging with an empty set of files
1382 $op->addParserOutputMetadata( $stubPOEmpty );
1383 $this->assertSame( array_merge( $files1, $files2 ), $op->getFileSearchOptions() );
1387 * @dataProvider provideAddWikiText
1388 * @covers OutputPage::addWikiText
1389 * @covers OutputPage::addWikiTextWithTitle
1390 * @covers OutputPage::addWikiTextTitle
1391 * @covers OutputPage::getHTML
1393 public function testAddWikiText( $method, array $args, $expected ) {
1394 $op = $this->newInstance();
1395 $this->assertSame( '', $op->getHTML() );
1399 [ 'addWikiTextWithTitle', 'addWikiTextTitleTidy', 'addWikiTextTitle' ]
1400 ) && count( $args ) >= 2 && $args[1] === null ) {
1401 // Special placeholder because we can't get the actual title in the provider
1402 $args[1] = $op->getTitle();
1405 $op->$method( ...$args );
1406 $this->assertSame( $expected, $op->getHTML() );
1409 public function provideAddWikiText() {
1412 'Simple wikitext' => [
1414 "<p><b>Bold</b>\n</p>",
1415 ], 'List at start' => [
1417 "<ul><li>List</li></ul>\n",
1418 ], 'List not at start' => [
1419 [ '* Not a list', false ],
1421 ], 'Non-interface' => [
1422 [ "'''Bold'''", true, false ],
1423 "<div class=\"mw-parser-output\"><p><b>Bold</b>\n</p></div>",
1424 ], 'No section edit links' => [
1426 "<h2><span class=\"mw-headline\" id=\"Title\">Title</span></h2>\n",
1429 'addWikiTextWithTitle' => [
1430 'With title at start' => [
1431 [ '* {{PAGENAME}}', Title
::newFromText( 'Talk:Some page' ) ],
1432 "<div class=\"mw-parser-output\"><ul><li>Some page</li></ul>\n</div>",
1433 ], 'With title at start' => [
1434 [ '* {{PAGENAME}}', Title
::newFromText( 'Talk:Some page' ), false ],
1435 "<div class=\"mw-parser-output\">* Some page</div>",
1440 // Test all the others on addWikiTextTitle as well
1441 foreach ( $tests['addWikiText'] as $key => $val ) {
1442 $args = [ $val[0][0], null, $val[0][1] ??
true, false, $val[0][2] ??
true ];
1443 $tests['addWikiTextTitle']["$key (addWikiTextTitle)"] =
1444 array_merge( [ $args ], array_slice( $val, 1 ) );
1446 foreach ( $tests['addWikiTextWithTitle'] as $key => $val ) {
1447 $args = [ $val[0][0], $val[0][1], $val[0][2] ??
true ];
1448 $tests['addWikiTextTitle']["$key (addWikiTextTitle)"] =
1449 array_merge( [ $args ], array_slice( $val, 1 ) );
1452 // We have to reformat our array to match what PHPUnit wants
1454 foreach ( $tests as $key => $subarray ) {
1455 foreach ( $subarray as $subkey => $val ) {
1456 $val = array_merge( [ $key ], $val );
1457 $ret[$subkey] = $val;
1465 * @covers OutputPage::addWikiText
1467 public function testAddWikiTextNoTitle() {
1468 $this->setExpectedException( MWException
::class, 'Title is null' );
1470 $op = $this->newInstance( [], null, 'notitle' );
1471 $op->addWikiText( 'a' );
1474 // @todo How should we cover the Tidy variants?
1477 * @covers OutputPage::addParserOutputMetadata
1479 public function testNoGallery() {
1480 $op = $this->newInstance();
1481 $this->assertFalse( $op->mNoGallery
);
1483 $stubPO1 = $this->createParserOutputStub( 'getNoGallery', true );
1484 $op->addParserOutputMetadata( $stubPO1 );
1485 $this->assertTrue( $op->mNoGallery
);
1487 $stubPO2 = $this->createParserOutputStub( 'getNoGallery', false );
1488 $op->addParserOutputMetadata( $stubPO2 );
1489 $this->assertFalse( $op->mNoGallery
);
1492 // @todo Make sure to test the following in addParserOutputMetadata() as well when we add tests
1494 // * enableClientCache()
1496 // * addModuleScripts()
1497 // * addModuleStyles()
1498 // * addJsConfigVars()
1499 // * preventClickJacking()
1500 // Otherwise those lines of addParserOutputMetadata() will be reported as covered, but we won't
1501 // be testing they actually work.
1504 * @covers OutputPage::haveCacheVaryCookies
1506 public function testHaveCacheVaryCookies() {
1507 $request = new FauxRequest();
1508 $context = new RequestContext();
1509 $context->setRequest( $request );
1510 $op = new OutputPage( $context );
1512 // No cookies are set.
1513 $this->assertFalse( $op->haveCacheVaryCookies() );
1515 // 'Token' is present but empty, so it shouldn't count.
1516 $request->setCookie( 'Token', '' );
1517 $this->assertFalse( $op->haveCacheVaryCookies() );
1519 // 'Token' present and nonempty.
1520 $request->setCookie( 'Token', '123' );
1521 $this->assertTrue( $op->haveCacheVaryCookies() );
1525 * @dataProvider provideVaryHeaders
1527 * @covers OutputPage::addVaryHeader
1528 * @covers OutputPage::getVaryHeader
1529 * @covers OutputPage::getKeyHeader
1531 public function testVaryHeaders( $calls, $vary, $key ) {
1532 // get rid of default Vary fields
1533 $op = $this->getMockBuilder( OutputPage
::class )
1534 ->setConstructorArgs( [ new RequestContext() ] )
1535 ->setMethods( [ 'getCacheVaryCookies' ] )
1537 $op->expects( $this->any() )
1538 ->method( 'getCacheVaryCookies' )
1539 ->will( $this->returnValue( [] ) );
1540 TestingAccessWrapper
::newFromObject( $op )->mVaryHeader
= [];
1542 foreach ( $calls as $call ) {
1543 call_user_func_array( [ $op, 'addVaryHeader' ], $call );
1545 $this->assertEquals( $vary, $op->getVaryHeader(), 'Vary:' );
1546 $this->assertEquals( $key, $op->getKeyHeader(), 'Key:' );
1549 public function provideVaryHeaders() {
1550 // note: getKeyHeader() automatically adds Vary: Cookie
1559 [ // non-unique headers
1562 [ 'Accept-Language' ],
1565 'Vary: Cookie, Accept-Language',
1566 'Key: Cookie,Accept-Language',
1568 [ // two headers with single options
1570 [ 'Cookie', [ 'param=phpsessid' ] ],
1571 [ 'Accept-Language', [ 'substr=en' ] ],
1573 'Vary: Cookie, Accept-Language',
1574 'Key: Cookie;param=phpsessid,Accept-Language;substr=en',
1576 [ // one header with multiple options
1578 [ 'Cookie', [ 'param=phpsessid', 'param=userId' ] ],
1581 'Key: Cookie;param=phpsessid;param=userId',
1583 [ // Duplicate option
1585 [ 'Cookie', [ 'param=phpsessid' ] ],
1586 [ 'Cookie', [ 'param=phpsessid' ] ],
1587 [ 'Accept-Language', [ 'substr=en', 'substr=en' ] ],
1589 'Vary: Cookie, Accept-Language',
1590 'Key: Cookie;param=phpsessid,Accept-Language;substr=en',
1592 [ // Same header, different options
1594 [ 'Cookie', [ 'param=phpsessid' ] ],
1595 [ 'Cookie', [ 'param=userId' ] ],
1598 'Key: Cookie;param=phpsessid;param=userId',
1604 * @dataProvider provideLinkHeaders
1606 * @covers OutputPage::addLinkHeader
1607 * @covers OutputPage::getLinkHeader
1609 public function testLinkHeaders( $headers, $result ) {
1610 $op = $this->newInstance();
1612 foreach ( $headers as $header ) {
1613 $op->addLinkHeader( $header );
1616 $this->assertEquals( $result, $op->getLinkHeader() );
1619 public function provideLinkHeaders() {
1626 [ '<https://foo/bar.jpg>;rel=preload;as=image' ],
1627 'Link: <https://foo/bar.jpg>;rel=preload;as=image',
1630 [ '<https://foo/bar.jpg>;rel=preload;as=image','<https://foo/baz.jpg>;rel=preload;as=image' ],
1631 'Link: <https://foo/bar.jpg>;rel=preload;as=image,<https://foo/baz.jpg>;rel=preload;as=image',
1637 * See ResourceLoaderClientHtmlTest for full coverage.
1639 * @dataProvider provideMakeResourceLoaderLink
1641 * @covers OutputPage::makeResourceLoaderLink
1643 public function testMakeResourceLoaderLink( $args, $expectedHtml ) {
1644 $this->setMwGlobals( [
1645 'wgResourceLoaderDebug' => false,
1646 'wgLoadScript' => 'http://127.0.0.1:8080/w/load.php',
1647 'wgCSPReportOnlyHeader' => true,
1649 $class = new ReflectionClass( OutputPage
::class );
1650 $method = $class->getMethod( 'makeResourceLoaderLink' );
1651 $method->setAccessible( true );
1652 $ctx = new RequestContext();
1653 $ctx->setSkin( SkinFactory
::getDefaultInstance()->makeSkin( 'fallback' ) );
1654 $ctx->setLanguage( 'en' );
1655 $out = new OutputPage( $ctx );
1656 $nonce = $class->getProperty( 'CSPNonce' );
1657 $nonce->setAccessible( true );
1658 $nonce->setValue( $out, 'secret' );
1659 $rl = $out->getResourceLoader();
1660 $rl->setMessageBlobStore( new NullMessageBlobStore() );
1662 'test.foo' => new ResourceLoaderTestModule( [
1663 'script' => 'mw.test.foo( { a: true } );',
1664 'styles' => '.mw-test-foo { content: "style"; }',
1666 'test.bar' => new ResourceLoaderTestModule( [
1667 'script' => 'mw.test.bar( { a: true } );',
1668 'styles' => '.mw-test-bar { content: "style"; }',
1670 'test.baz' => new ResourceLoaderTestModule( [
1671 'script' => 'mw.test.baz( { a: true } );',
1672 'styles' => '.mw-test-baz { content: "style"; }',
1674 'test.quux' => new ResourceLoaderTestModule( [
1675 'script' => 'mw.test.baz( { token: 123 } );',
1676 'styles' => '/* pref-animate=off */ .mw-icon { transition: none; }',
1677 'group' => 'private',
1679 'test.noscript' => new ResourceLoaderTestModule( [
1680 'styles' => '.stuff { color: red; }',
1681 'group' => 'noscript',
1683 'test.group.foo' => new ResourceLoaderTestModule( [
1684 'script' => 'mw.doStuff( "foo" );',
1687 'test.group.bar' => new ResourceLoaderTestModule( [
1688 'script' => 'mw.doStuff( "bar" );',
1692 $links = $method->invokeArgs( $out, $args );
1693 $actualHtml = strval( $links );
1694 $this->assertEquals( $expectedHtml, $actualHtml );
1697 public static function provideMakeResourceLoaderLink() {
1698 // phpcs:disable Generic.Files.LineLength
1700 // Single only=scripts load
1702 [ 'test.foo', ResourceLoaderModule
::TYPE_SCRIPTS
],
1703 "<script nonce=\"secret\">(window.RLQ=window.RLQ||[]).push(function(){"
1704 . 'mw.loader.load("http://127.0.0.1:8080/w/load.php?debug=false\u0026lang=en\u0026modules=test.foo\u0026only=scripts\u0026skin=fallback");'
1707 // Multiple only=styles load
1709 [ [ 'test.baz', 'test.foo', 'test.bar' ], ResourceLoaderModule
::TYPE_STYLES
],
1711 '<link rel="stylesheet" href="http://127.0.0.1:8080/w/load.php?debug=false&lang=en&modules=test.bar%2Cbaz%2Cfoo&only=styles&skin=fallback"/>'
1713 // Private embed (only=scripts)
1715 [ 'test.quux', ResourceLoaderModule
::TYPE_SCRIPTS
],
1716 "<script nonce=\"secret\">(window.RLQ=window.RLQ||[]).push(function(){"
1717 . "mw.test.baz({token:123});\nmw.loader.state({\"test.quux\":\"ready\"});"
1720 // Load private module (combined)
1722 [ 'test.quux', ResourceLoaderModule
::TYPE_COMBINED
],
1723 "<script nonce=\"secret\">(window.RLQ=window.RLQ||[]).push(function(){"
1724 . "mw.loader.implement(\"test.quux@1ev0ijv\",function($,jQuery,require,module){"
1725 . "mw.test.baz({token:123});},{\"css\":[\".mw-icon{transition:none}"
1726 . "\"]});});</script>"
1730 [ [], ResourceLoaderModule
::TYPE_COMBINED
],
1735 [ 'test.noscript', ResourceLoaderModule
::TYPE_STYLES
],
1736 '<noscript><link rel="stylesheet" href="http://127.0.0.1:8080/w/load.php?debug=false&lang=en&modules=test.noscript&only=styles&skin=fallback"/></noscript>'
1738 // Load two modules in separate groups
1740 [ [ 'test.group.foo', 'test.group.bar' ], ResourceLoaderModule
::TYPE_COMBINED
],
1741 "<script nonce=\"secret\">(window.RLQ=window.RLQ||[]).push(function(){"
1742 . 'mw.loader.load("http://127.0.0.1:8080/w/load.php?debug=false\u0026lang=en\u0026modules=test.group.bar\u0026skin=fallback");'
1743 . 'mw.loader.load("http://127.0.0.1:8080/w/load.php?debug=false\u0026lang=en\u0026modules=test.group.foo\u0026skin=fallback");'
1751 * @dataProvider provideBuildExemptModules
1753 * @covers OutputPage::buildExemptModules
1755 public function testBuildExemptModules( array $exemptStyleModules, $expect ) {
1756 $this->setMwGlobals( [
1757 'wgResourceLoaderDebug' => false,
1758 'wgLoadScript' => '/w/load.php',
1759 // Stub wgCacheEpoch as it influences getVersionHash used for the
1760 // urls in the expected HTML
1761 'wgCacheEpoch' => '20140101000000',
1765 $ctx = new RequestContext();
1766 $ctx->setSkin( SkinFactory
::getDefaultInstance()->makeSkin( 'fallback' ) );
1767 $ctx->setLanguage( 'en' );
1768 $op = $this->getMockBuilder( OutputPage
::class )
1769 ->setConstructorArgs( [ $ctx ] )
1770 ->setMethods( [ 'buildCssLinksArray' ] )
1772 $op->expects( $this->any() )
1773 ->method( 'buildCssLinksArray' )
1775 $rl = $op->getResourceLoader();
1776 $rl->setMessageBlobStore( new NullMessageBlobStore() );
1778 // Register custom modules
1780 'example.site.a' => new ResourceLoaderTestModule( [ 'group' => 'site' ] ),
1781 'example.site.b' => new ResourceLoaderTestModule( [ 'group' => 'site' ] ),
1782 'example.user' => new ResourceLoaderTestModule( [ 'group' => 'user' ] ),
1785 $op = TestingAccessWrapper
::newFromObject( $op );
1786 $op->rlExemptStyleModules
= $exemptStyleModules;
1787 $this->assertEquals(
1789 strval( $op->buildExemptModules() )
1793 public static function provideBuildExemptModules() {
1794 // phpcs:disable Generic.Files.LineLength
1797 'exemptStyleModules' => [],
1798 '<meta name="ResourceLoaderDynamicStyles" content=""/>',
1801 'exemptStyleModules' => [ 'site' => [], 'noscript' => [], 'private' => [], 'user' => [] ],
1802 '<meta name="ResourceLoaderDynamicStyles" content=""/>',
1804 'default logged-out' => [
1805 'exemptStyleModules' => [ 'site' => [ 'site.styles' ] ],
1806 '<meta name="ResourceLoaderDynamicStyles" content=""/>' . "\n" .
1807 '<link rel="stylesheet" href="/w/load.php?debug=false&lang=en&modules=site.styles&only=styles&skin=fallback"/>',
1809 'default logged-in' => [
1810 'exemptStyleModules' => [ 'site' => [ 'site.styles' ], 'user' => [ 'user.styles' ] ],
1811 '<meta name="ResourceLoaderDynamicStyles" content=""/>' . "\n" .
1812 '<link rel="stylesheet" href="/w/load.php?debug=false&lang=en&modules=site.styles&only=styles&skin=fallback"/>' . "\n" .
1813 '<link rel="stylesheet" href="/w/load.php?debug=false&lang=en&modules=user.styles&only=styles&skin=fallback&version=1ai9g6t"/>',
1815 'custom modules' => [
1816 'exemptStyleModules' => [
1817 'site' => [ 'site.styles', 'example.site.a', 'example.site.b' ],
1818 'user' => [ 'user.styles', 'example.user' ],
1820 '<meta name="ResourceLoaderDynamicStyles" content=""/>' . "\n" .
1821 '<link rel="stylesheet" href="/w/load.php?debug=false&lang=en&modules=example.site.a%2Cb&only=styles&skin=fallback"/>' . "\n" .
1822 '<link rel="stylesheet" href="/w/load.php?debug=false&lang=en&modules=site.styles&only=styles&skin=fallback"/>' . "\n" .
1823 '<link rel="stylesheet" href="/w/load.php?debug=false&lang=en&modules=example.user&only=styles&skin=fallback&version=0a56zyi"/>' . "\n" .
1824 '<link rel="stylesheet" href="/w/load.php?debug=false&lang=en&modules=user.styles&only=styles&skin=fallback&version=1ai9g6t"/>',
1831 * @dataProvider provideTransformFilePath
1832 * @covers OutputPage::transformFilePath
1833 * @covers OutputPage::transformResourcePath
1835 public function testTransformResourcePath( $baseDir, $basePath, $uploadDir = null,
1836 $uploadPath = null, $path = null, $expected = null
1838 if ( $path === null ) {
1839 // Skip optional $uploadDir and $uploadPath
1841 $expected = $uploadPath;
1842 $uploadDir = "$baseDir/images";
1843 $uploadPath = "$basePath/images";
1845 $this->setMwGlobals( 'IP', $baseDir );
1846 $conf = new HashConfig( [
1847 'ResourceBasePath' => $basePath,
1848 'UploadDirectory' => $uploadDir,
1849 'UploadPath' => $uploadPath,
1852 // Some of these paths don't exist and will cause warnings
1853 Wikimedia\
suppressWarnings();
1854 $actual = OutputPage
::transformResourcePath( $conf, $path );
1855 Wikimedia\restoreWarnings
();
1857 $this->assertEquals( $expected ?
: $path, $actual );
1860 public static function provideTransformFilePath() {
1861 $baseDir = dirname( __DIR__
) . '/data/media';
1863 // File that matches basePath, and exists. Hash found and appended.
1865 'baseDir' => $baseDir, 'basePath' => '/w',
1869 // File that matches basePath, but not found on disk. Empty query.
1871 'baseDir' => $baseDir, 'basePath' => '/w',
1875 // File not matching basePath. Ignored.
1877 'baseDir' => $baseDir, 'basePath' => '/w',
1880 // Empty string. Ignored.
1882 'baseDir' => $baseDir, 'basePath' => '/w',
1886 // Similar path, but with domain component. Ignored.
1888 'baseDir' => $baseDir, 'basePath' => '/w',
1889 '//example.org/w/test.jpg'
1892 'baseDir' => $baseDir, 'basePath' => '/w',
1893 'https://example.org/w/test.jpg'
1895 // Unrelated path with domain component. Ignored.
1897 'baseDir' => $baseDir, 'basePath' => '/w',
1898 'https://example.org/files/test.jpg'
1901 'baseDir' => $baseDir, 'basePath' => '/w',
1902 '//example.org/files/test.jpg'
1904 // Unrelated path with domain, and empty base path (root mw install). Ignored.
1906 'baseDir' => $baseDir, 'basePath' => '',
1907 'https://example.org/files/test.jpg'
1910 'baseDir' => $baseDir, 'basePath' => '',
1912 '//example.org/files/test.jpg'
1914 // Check UploadPath before ResourceBasePath (T155146)
1916 'baseDir' => dirname( $baseDir ), 'basePath' => '',
1917 'uploadDir' => $baseDir, 'uploadPath' => '/images',
1919 '/images/test.jpg?edcf2'
1925 * Tests a particular case of transformCssMedia, using the given input, globals,
1926 * expected return, and message
1928 * Asserts that $expectedReturn is returned.
1930 * options['printableQuery'] - value of query string for printable, or omitted for none
1931 * options['handheldQuery'] - value of query string for handheld, or omitted for none
1932 * options['media'] - passed into the method under the same name
1933 * options['expectedReturn'] - expected return value
1934 * options['message'] - PHPUnit message for assertion
1936 * @param array $args Key-value array of arguments as shown above
1938 protected function assertTransformCssMediaCase( $args ) {
1940 if ( isset( $args['printableQuery'] ) ) {
1941 $queryData['printable'] = $args['printableQuery'];
1944 if ( isset( $args['handheldQuery'] ) ) {
1945 $queryData['handheld'] = $args['handheldQuery'];
1948 $fauxRequest = new FauxRequest( $queryData, false );
1949 $this->setMwGlobals( [
1950 'wgRequest' => $fauxRequest,
1953 $actualReturn = OutputPage
::transformCssMedia( $args['media'] );
1954 $this->assertSame( $args['expectedReturn'], $actualReturn, $args['message'] );
1958 * Tests print requests
1960 * @covers OutputPage::transformCssMedia
1962 public function testPrintRequests() {
1963 $this->assertTransformCssMediaCase( [
1964 'printableQuery' => '1',
1965 'media' => 'screen',
1966 'expectedReturn' => null,
1967 'message' => 'On printable request, screen returns null'
1970 $this->assertTransformCssMediaCase( [
1971 'printableQuery' => '1',
1972 'media' => self
::SCREEN_MEDIA_QUERY
,
1973 'expectedReturn' => null,
1974 'message' => 'On printable request, screen media query returns null'
1977 $this->assertTransformCssMediaCase( [
1978 'printableQuery' => '1',
1979 'media' => self
::SCREEN_ONLY_MEDIA_QUERY
,
1980 'expectedReturn' => null,
1981 'message' => 'On printable request, screen media query with only returns null'
1984 $this->assertTransformCssMediaCase( [
1985 'printableQuery' => '1',
1987 'expectedReturn' => '',
1988 'message' => 'On printable request, media print returns empty string'
1993 * Tests screen requests, without either query parameter set
1995 * @covers OutputPage::transformCssMedia
1997 public function testScreenRequests() {
1998 $this->assertTransformCssMediaCase( [
1999 'media' => 'screen',
2000 'expectedReturn' => 'screen',
2001 'message' => 'On screen request, screen media type is preserved'
2004 $this->assertTransformCssMediaCase( [
2005 'media' => 'handheld',
2006 'expectedReturn' => 'handheld',
2007 'message' => 'On screen request, handheld media type is preserved'
2010 $this->assertTransformCssMediaCase( [
2011 'media' => self
::SCREEN_MEDIA_QUERY
,
2012 'expectedReturn' => self
::SCREEN_MEDIA_QUERY
,
2013 'message' => 'On screen request, screen media query is preserved.'
2016 $this->assertTransformCssMediaCase( [
2017 'media' => self
::SCREEN_ONLY_MEDIA_QUERY
,
2018 'expectedReturn' => self
::SCREEN_ONLY_MEDIA_QUERY
,
2019 'message' => 'On screen request, screen media query with only is preserved.'
2022 $this->assertTransformCssMediaCase( [
2024 'expectedReturn' => 'print',
2025 'message' => 'On screen request, print media type is preserved'
2030 * Tests handheld behavior
2032 * @covers OutputPage::transformCssMedia
2034 public function testHandheld() {
2035 $this->assertTransformCssMediaCase( [
2036 'handheldQuery' => '1',
2037 'media' => 'handheld',
2038 'expectedReturn' => '',
2039 'message' => 'On request with handheld querystring and media is handheld, returns empty string'
2042 $this->assertTransformCssMediaCase( [
2043 'handheldQuery' => '1',
2044 'media' => 'screen',
2045 'expectedReturn' => null,
2046 'message' => 'On request with handheld querystring and media is screen, returns null'
2051 * @return OutputPage
2053 private function newInstance( $config = [], WebRequest
$request = null, $options = [] ) {
2054 $context = new RequestContext();
2056 $context->setConfig( new MultiConfig( [
2057 new HashConfig( $config +
[
2058 'AppleTouchIcon' => false,
2059 'DisableLangConversion' => true,
2060 'EnableCanonicalServerLink' => false,
2063 'LanguageCode' => false,
2064 'ReferrerPolicy' => false,
2065 'RightsPage' => false,
2066 'RightsUrl' => false,
2067 'UniversalEditButton' => false,
2069 $context->getConfig()
2072 if ( !in_array( 'notitle', (array)$options ) ) {
2073 $context->setTitle( Title
::newFromText( 'My test page' ) );
2077 $context->setRequest( $request );
2080 return new OutputPage( $context );
2085 * MessageBlobStore that doesn't do anything
2087 class NullMessageBlobStore
extends MessageBlobStore
{
2088 public function get( ResourceLoader
$resourceLoader, $modules, $lang ) {
2092 public function updateModule( $name, ResourceLoaderModule
$module, $lang ) {
2095 public function updateMessage( $key ) {
2098 public function clear() {