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
189 * @covers OutputPage::addScriptFile
191 public function testAddDeprecatedScriptFileNoOp() {
192 $this->hideDeprecated( 'OutputPage::addScriptFile' );
193 $op = $this->newInstance();
194 $op->addScriptFile( 'ignored-script.js' );
196 $this->assertNotContains( 'ignored-script.js', '' . $op->getBottomScripts() );
200 * @covers OutputPage::addInlineScript
202 public function testAddInlineScript() {
203 $op = $this->newInstance();
204 $op->addInlineScript( 'let foo = "bar";' );
205 $op->addInlineScript( 'alert( foo );' );
207 $this->assertContains(
208 "\n" . Html
::inlineScript( "\nlet foo = \"bar\";\n", $op->getCSPNonce() ) . "\n" .
209 Html
::inlineScript( "\nalert( foo );\n", $op->getCSPNonce() ) . "\n",
210 "\n" . $op->getBottomScripts() . "\n"
214 // @todo How to test filterModules(), warnModuleTargetFilter(), getModules(), etc.?
217 * @covers OutputPage::getTarget
218 * @covers OutputPage::setTarget
220 public function testSetTarget() {
221 $op = $this->newInstance();
222 $op->setTarget( 'foo' );
224 $this->assertSame( 'foo', $op->getTarget() );
225 // @todo What else? Test some actual effect?
228 // @todo How to test addContentOverride(Callback)?
231 * @covers OutputPage::getHeadItemsArray
232 * @covers OutputPage::addHeadItem
233 * @covers OutputPage::addHeadItems
234 * @covers OutputPage::hasHeadItem
236 public function testHeadItems() {
237 $op = $this->newInstance();
238 $op->addHeadItem( 'a', 'b' );
239 $op->addHeadItems( [ 'c' => '<d>&', 'e' => 'f', 'a' => 'q' ] );
240 $op->addHeadItem( 'e', 'g' );
241 $op->addHeadItems( 'x' );
243 $this->assertSame( [ 'a' => 'q', 'c' => '<d>&', 'e' => 'g', 'x' ],
244 $op->getHeadItemsArray() );
246 $this->assertTrue( $op->hasHeadItem( 'a' ) );
247 $this->assertTrue( $op->hasHeadItem( 'c' ) );
248 $this->assertTrue( $op->hasHeadItem( 'e' ) );
249 $this->assertTrue( $op->hasHeadItem( '0' ) );
251 $this->assertContains( "\nq\n<d>&\ng\nx\n",
252 '' . $op->headElement( $op->getContext()->getSkin() ) );
256 * @covers OutputPage::getHeadItemsArray
257 * @covers OutputPage::addParserOutputMetadata
259 public function testHeadItemsParserOutput() {
260 $op = $this->newInstance();
261 $stubPO1 = $this->createParserOutputStub( 'getHeadItems', [ 'a' => 'b' ] );
262 $op->addParserOutputMetadata( $stubPO1 );
263 $stubPO2 = $this->createParserOutputStub( 'getHeadItems',
264 [ 'c' => '<d>&', 'e' => 'f', 'a' => 'q' ] );
265 $op->addParserOutputMetadata( $stubPO2 );
266 $stubPO3 = $this->createParserOutputStub( 'getHeadItems', [ 'e' => 'g' ] );
267 $op->addParserOutputMetadata( $stubPO3 );
268 $stubPO4 = $this->createParserOutputStub( 'getHeadItems', [ 'x' ] );
269 $op->addParserOutputMetadata( $stubPO4 );
271 $this->assertSame( [ 'a' => 'q', 'c' => '<d>&', 'e' => 'g', 'x' ],
272 $op->getHeadItemsArray() );
274 $this->assertTrue( $op->hasHeadItem( 'a' ) );
275 $this->assertTrue( $op->hasHeadItem( 'c' ) );
276 $this->assertTrue( $op->hasHeadItem( 'e' ) );
277 $this->assertTrue( $op->hasHeadItem( '0' ) );
278 $this->assertFalse( $op->hasHeadItem( 'b' ) );
280 $this->assertContains( "\nq\n<d>&\ng\nx\n",
281 '' . $op->headElement( $op->getContext()->getSkin() ) );
285 * @covers OutputPage::addBodyClasses
287 public function testAddBodyClasses() {
288 $op = $this->newInstance();
289 $op->addBodyClasses( 'a' );
290 $op->addBodyClasses( 'mediawiki' );
291 $op->addBodyClasses( 'b c' );
292 $op->addBodyClasses( [ 'd', 'e' ] );
293 $op->addBodyClasses( 'a' );
295 $this->assertContains( '"a mediawiki b c d e ltr',
296 '' . $op->headElement( $op->getContext()->getSkin() ) );
300 * @covers OutputPage::setArticleBodyOnly
301 * @covers OutputPage::getArticleBodyOnly
303 public function testArticleBodyOnly() {
304 $op = $this->newInstance();
305 $this->assertFalse( $op->getArticleBodyOnly() );
307 $op->setArticleBodyOnly( true );
308 $this->assertTrue( $op->getArticleBodyOnly() );
310 $op->addHTML( '<b>a</b>' );
312 $this->assertSame( '<b>a</b>', $op->output( true ) );
316 * @covers OutputPage::setProperty
317 * @covers OutputPage::getProperty
319 public function testProperties() {
320 $op = $this->newInstance();
322 $this->assertNull( $op->getProperty( 'foo' ) );
324 $op->setProperty( 'foo', 'bar' );
325 $op->setProperty( 'baz', 'quz' );
327 $this->assertSame( 'bar', $op->getProperty( 'foo' ) );
328 $this->assertSame( 'quz', $op->getProperty( 'baz' ) );
332 * @dataProvider provideCheckLastModified
334 * @covers OutputPage::checkLastModified
335 * @covers OutputPage::getCdnCacheEpoch
337 public function testCheckLastModified(
338 $timestamp, $ifModifiedSince, $expected, $config = [], $callback = null
340 $request = new FauxRequest();
341 if ( $ifModifiedSince ) {
342 if ( is_numeric( $ifModifiedSince ) ) {
344 $ifModifiedSince = date( 'D, d M Y H:i:s', $ifModifiedSince ) . ' GMT';
346 $request->setHeader( 'If-Modified-Since', $ifModifiedSince );
349 if ( !isset( $config['CacheEpoch'] ) ) {
350 // Make sure it's not too recent
351 $config['CacheEpoch'] = '20000101000000';
354 $op = $this->newInstance( $config, $request );
357 $callback( $op, $this );
360 // Avoid a complaint about not being able to disable compression
361 Wikimedia\
suppressWarnings();
363 $this->assertEquals( $expected, $op->checkLastModified( $timestamp ) );
365 Wikimedia\restoreWarnings
();
369 public function provideCheckLastModified() {
370 $lastModified = time() - 3600;
373 [ '0', $lastModified, false ],
374 'Timestamp Unix epoch' =>
375 [ '19700101000000', $lastModified, false ],
376 'Timestamp same as If-Modified-Since' =>
377 [ $lastModified, $lastModified, true ],
378 'Timestamp one second after If-Modified-Since' =>
379 [ $lastModified +
1, $lastModified, false ],
380 'No If-Modified-Since' =>
381 [ $lastModified +
1, null, false ],
382 'Malformed If-Modified-Since' =>
383 [ $lastModified +
1, 'GIBBERING WOMBATS !!!', false ],
384 'Non-standard IE-style If-Modified-Since' =>
385 [ $lastModified, date( 'D, d M Y H:i:s', $lastModified ) . ' GMT; length=5202',
387 // @todo Should we fix this behavior to match the spec? Probably no reason to.
388 'If-Modified-Since not per spec but we accept it anyway because strtotime does' =>
389 [ $lastModified, "@$lastModified", true ],
390 '$wgCachePages = false' =>
391 [ $lastModified, $lastModified, false, [ 'CachePages' => false ] ],
393 [ $lastModified, $lastModified, false,
394 [ 'CacheEpoch' => wfTimestamp( TS_MW
, $lastModified +
1 ) ] ],
395 'Recently-touched user' =>
396 [ $lastModified, $lastModified, false, [],
398 $op->getContext()->setUser( $this->getTestUser()->getUser() );
400 'After Squid expiry' =>
401 [ $lastModified, $lastModified, false,
402 [ 'UseSquid' => true, 'SquidMaxage' => 3599 ] ],
403 'Hook allows cache use' =>
404 [ $lastModified +
1, $lastModified, true, [],
405 function ( $op, $that ) {
406 $that->setTemporaryHook( 'OutputPageCheckLastModified',
407 function ( &$modifiedTimes ) {
408 $modifiedTimes = [ 1 ];
412 'Hooks prohibits cache use' =>
413 [ $lastModified, $lastModified, false, [],
414 function ( $op, $that ) {
415 $that->setTemporaryHook( 'OutputPageCheckLastModified',
416 function ( &$modifiedTimes ) {
417 $modifiedTimes = [ max( $modifiedTimes ) +
1 ];
425 * @dataProvider provideCdnCacheEpoch
427 * @covers OutputPage::getCdnCacheEpoch
429 public function testCdnCacheEpoch( $params ) {
430 $out = TestingAccessWrapper
::newFromObject( $this->newInstance() );
431 $reqTime = strtotime( $params['reqTime'] );
432 $pageTime = strtotime( $params['pageTime'] );
433 $actual = max( $pageTime, $out->getCdnCacheEpoch( $reqTime, $params['maxAge'] ) );
437 gmdate( DateTime
::ATOM
, $actual ),
442 public static function provideCdnCacheEpoch() {
444 'pageTime' => '2011-04-01T12:00:00+00:00',
445 'maxAge' => 24 * 3600,
448 'after 1s' => [ $base +
[
449 'reqTime' => '2011-04-01T12:00:01+00:00',
450 'expect' => '2011-04-01T12:00:00+00:00',
452 'after 23h' => [ $base +
[
453 'reqTime' => '2011-04-02T11:00:00+00:00',
454 'expect' => '2011-04-01T12:00:00+00:00',
456 'after 24h and a bit' => [ $base +
[
457 'reqTime' => '2011-04-02T12:34:56+00:00',
458 'expect' => '2011-04-01T12:34:56+00:00',
460 'after a year' => [ $base +
[
461 'reqTime' => '2012-05-06T00:12:07+00:00',
462 'expect' => '2012-05-05T00:12:07+00:00',
467 // @todo How to test setLastModified?
470 * @covers OutputPage::setRobotPolicy
471 * @covers OutputPage::getHeadLinksArray
473 public function testSetRobotPolicy() {
474 $op = $this->newInstance();
475 $op->setRobotPolicy( 'noindex, nofollow' );
477 $links = $op->getHeadLinksArray();
478 $this->assertContains( '<meta name="robots" content="noindex,nofollow"/>', $links );
482 * @covers OutputPage::setIndexPolicy
483 * @covers OutputPage::setFollowPolicy
484 * @covers OutputPage::getHeadLinksArray
486 public function testSetIndexFollowPolicies() {
487 $op = $this->newInstance();
488 $op->setIndexPolicy( 'noindex' );
489 $op->setFollowPolicy( 'nofollow' );
491 $links = $op->getHeadLinksArray();
492 $this->assertContains( '<meta name="robots" content="noindex,nofollow"/>', $links );
495 private function extractHTMLTitle( OutputPage
$op ) {
496 $html = $op->headElement( $op->getContext()->getSkin() );
498 // OutputPage should always output the title in a nice format such that regexes will work
499 // fine. If it doesn't, we'll fail the tests.
500 preg_match_all( '!<title>(.*?)</title>!', $html, $matches );
502 $this->assertLessThanOrEqual( 1, count( $matches[1] ), 'More than one <title>!' );
504 if ( !count( $matches[1] ) ) {
508 return $matches[1][0];
512 * Shorthand for getting the text of a message, in content language.
514 private static function getMsgText( $op, ...$msgParams ) {
515 return $op->msg( ...$msgParams )->inContentLanguage()->text();
519 * @covers OutputPage::setHTMLTitle
520 * @covers OutputPage::getHTMLTitle
522 public function testHTMLTitle() {
523 $op = $this->newInstance();
526 $this->assertSame( '', $op->getHTMLTitle() );
527 $this->assertSame( '', $op->getPageTitle() );
529 $this->getMsgText( $op, 'pagetitle', '' ),
530 $this->extractHTMLTitle( $op )
534 $op->setHTMLTitle( 'Potatoes will eat me' );
536 $this->assertSame( 'Potatoes will eat me', $op->getHTMLTitle() );
537 $this->assertSame( 'Potatoes will eat me', $this->extractHTMLTitle( $op ) );
538 // Shouldn't have changed the page title
539 $this->assertSame( '', $op->getPageTitle() );
542 $msg = $op->msg( 'mainpage' );
544 $op->setHTMLTitle( $msg );
545 $this->assertSame( $msg->text(), $op->getHTMLTitle() );
546 $this->assertSame( $msg->text(), $this->extractHTMLTitle( $op ) );
547 $this->assertSame( '', $op->getPageTitle() );
551 * @covers OutputPage::setRedirectedFrom
553 public function testSetRedirectedFrom() {
554 $op = $this->newInstance();
556 $op->setRedirectedFrom( Title
::newFromText( 'Talk:Some page' ) );
557 $this->assertSame( 'Talk:Some_page', $op->getJSVars()['wgRedirectedFrom'] );
561 * @covers OutputPage::setPageTitle
562 * @covers OutputPage::getPageTitle
564 public function testPageTitle() {
565 // We don't test the actual HTML output anywhere, because that's up to the skin.
566 $op = $this->newInstance();
569 $this->assertSame( '', $op->getPageTitle() );
570 $this->assertSame( '', $op->getHTMLTitle() );
572 // Test set to plain text
573 $op->setPageTitle( 'foobar' );
575 $this->assertSame( 'foobar', $op->getPageTitle() );
576 // HTML title should change as well
577 $this->assertSame( $this->getMsgText( $op, 'pagetitle', 'foobar' ), $op->getHTMLTitle() );
579 // Test set to text with good and bad HTML. We don't try to be comprehensive here, that
580 // belongs in Sanitizer tests.
581 $op->setPageTitle( '<script>a</script>&<i>b</i>' );
583 $this->assertSame( '<script>a</script>&<i>b</i>', $op->getPageTitle() );
585 $this->getMsgText( $op, 'pagetitle', '<script>a</script>&b' ),
589 // Test set to message
590 $text = $this->getMsgText( $op, 'mainpage' );
592 $op->setPageTitle( $op->msg( 'mainpage' )->inContentLanguage() );
593 $this->assertSame( $text, $op->getPageTitle() );
594 $this->assertSame( $this->getMsgText( $op, 'pagetitle', $text ), $op->getHTMLTitle() );
598 * @covers OutputPage::setTitle
600 public function testSetTitle() {
601 $op = $this->newInstance();
603 $this->assertSame( 'My test page', $op->getTitle()->getPrefixedText() );
605 $op->setTitle( Title
::newFromText( 'Another test page' ) );
607 $this->assertSame( 'Another test page', $op->getTitle()->getPrefixedText() );
611 * @covers OutputPage::setSubtitle
612 * @covers OutputPage::clearSubtitle
613 * @covers OutputPage::addSubtitle
614 * @covers OutputPage::getSubtitle
616 public function testSubtitle() {
617 $op = $this->newInstance();
619 $this->assertSame( '', $op->getSubtitle() );
621 $op->addSubtitle( '<b>foo</b>' );
623 $this->assertSame( '<b>foo</b>', $op->getSubtitle() );
625 $op->addSubtitle( $op->msg( 'mainpage' )->inContentLanguage() );
628 "<b>foo</b><br />\n\t\t\t\t" . $this->getMsgText( $op, 'mainpage' ),
632 $op->setSubtitle( 'There can be only one' );
634 $this->assertSame( 'There can be only one', $op->getSubtitle() );
636 $op->clearSubtitle();
638 $this->assertSame( '', $op->getSubtitle() );
642 * @dataProvider provideBacklinkSubtitle
644 * @covers OutputPage::buildBacklinkSubtitle
646 public function testBuildBacklinkSubtitle( $titles, $queries, $contains, $notContains ) {
647 if ( count( $titles ) > 1 ) {
649 $this->assertTrue( true );
653 $title = Title
::newFromText( $titles[0] );
654 $query = $queries[0];
656 $this->editPage( 'Page 1', '' );
657 $this->editPage( 'Page 2', '#REDIRECT [[Page 1]]' );
659 $str = OutputPage
::buildBacklinkSubtitle( $title, $query )->text();
661 foreach ( $contains as $substr ) {
662 $this->assertContains( $substr, $str );
665 foreach ( $notContains as $substr ) {
666 $this->assertNotContains( $substr, $str );
671 * @dataProvider provideBacklinkSubtitle
673 * @covers OutputPage::addBacklinkSubtitle
674 * @covers OutputPage::getSubtitle
676 public function testAddBacklinkSubtitle( $titles, $queries, $contains, $notContains ) {
677 $this->editPage( 'Page 1', '' );
678 $this->editPage( 'Page 2', '#REDIRECT [[Page 1]]' );
680 $op = $this->newInstance();
681 foreach ( $titles as $i => $unused ) {
682 $op->addBacklinkSubtitle( Title
::newFromText( $titles[$i] ), $queries[$i] );
685 $str = $op->getSubtitle();
687 foreach ( $contains as $substr ) {
688 $this->assertContains( $substr, $str );
691 foreach ( $notContains as $substr ) {
692 $this->assertNotContains( $substr, $str );
696 public function provideBacklinkSubtitle() {
702 [ 'redirect', 'Page 2' ],
712 [ [ 'action' => 'edit' ] ],
717 [ 'Page 1', 'Page 2' ],
719 [ 'Page 1', 'Page 2', "<br />\n\t\t\t\t" ],
722 // @todo Anything else to test?
727 * @covers OutputPage::setPrintable
728 * @covers OutputPage::isPrintable
730 public function testPrintable() {
731 $op = $this->newInstance();
733 $this->assertFalse( $op->isPrintable() );
737 $this->assertTrue( $op->isPrintable() );
741 * @covers OutputPage::disable
742 * @covers OutputPage::isDisabled
744 public function testDisable() {
745 $op = $this->newInstance();
747 $this->assertFalse( $op->isDisabled() );
748 $this->assertNotSame( '', $op->output( true ) );
752 $this->assertTrue( $op->isDisabled() );
753 $this->assertSame( '', $op->output( true ) );
757 * @covers OutputPage::showNewSectionLink
758 * @covers OutputPage::addParserOutputMetadata
760 public function testShowNewSectionLink() {
761 $op = $this->newInstance();
763 $this->assertFalse( $op->showNewSectionLink() );
765 $po = new ParserOutput();
766 $po->setNewSection( true );
767 $op->addParserOutputMetadata( $po );
769 $this->assertTrue( $op->showNewSectionLink() );
773 * @covers OutputPage::forceHideNewSectionLink
774 * @covers OutputPage::addParserOutputMetadata
776 public function testForceHideNewSectionLink() {
777 $op = $this->newInstance();
779 $this->assertFalse( $op->forceHideNewSectionLink() );
781 $po = new ParserOutput();
782 $po->hideNewSection( true );
783 $op->addParserOutputMetadata( $po );
785 $this->assertTrue( $op->forceHideNewSectionLink() );
789 * @covers OutputPage::setSyndicated
790 * @covers OutputPage::isSyndicated
792 public function testSetSyndicated() {
793 $op = $this->newInstance();
794 $this->assertFalse( $op->isSyndicated() );
796 $op->setSyndicated();
797 $this->assertTrue( $op->isSyndicated() );
799 $op->setSyndicated( false );
800 $this->assertFalse( $op->isSyndicated() );
804 * @covers OutputPage::isSyndicated
805 * @covers OutputPage::setFeedAppendQuery
806 * @covers OutputPage::addFeedLink
807 * @covers OutputPage::getSyndicationLinks()
809 public function testFeedLinks() {
810 $op = $this->newInstance();
811 $this->assertSame( [], $op->getSyndicationLinks() );
813 $op->addFeedLink( 'not a supported format', 'abc' );
814 $this->assertFalse( $op->isSyndicated() );
815 $this->assertSame( [], $op->getSyndicationLinks() );
817 $feedTypes = $op->getConfig()->get( 'AdvertisedFeedTypes' );
819 $op->addFeedLink( $feedTypes[0], 'def' );
820 $this->assertTrue( $op->isSyndicated() );
821 $this->assertSame( [ $feedTypes[0] => 'def' ], $op->getSyndicationLinks() );
823 $op->setFeedAppendQuery( false );
825 foreach ( $feedTypes as $type ) {
826 $expected[$type] = $op->getTitle()->getLocalURL( "feed=$type" );
828 $this->assertSame( $expected, $op->getSyndicationLinks() );
830 $op->setFeedAppendQuery( 'apples=oranges' );
831 foreach ( $feedTypes as $type ) {
832 $expected[$type] = $op->getTitle()->getLocalURL( "feed=$type&apples=oranges" );
834 $this->assertSame( $expected, $op->getSyndicationLinks() );
838 * @covers OutputPage::setArticleFlag
839 * @covers OutputPage::isArticle
840 * @covers OutputPage::setArticleRelated
841 * @covers OutputPage::isArticleRelated
843 function testArticleFlags() {
844 $op = $this->newInstance();
845 $this->assertFalse( $op->isArticle() );
846 $this->assertTrue( $op->isArticleRelated() );
848 $op->setArticleRelated( false );
849 $this->assertFalse( $op->isArticle() );
850 $this->assertFalse( $op->isArticleRelated() );
852 $op->setArticleFlag( true );
853 $this->assertTrue( $op->isArticle() );
854 $this->assertTrue( $op->isArticleRelated() );
856 $op->setArticleFlag( false );
857 $this->assertFalse( $op->isArticle() );
858 $this->assertTrue( $op->isArticleRelated() );
860 $op->setArticleFlag( true );
861 $op->setArticleRelated( false );
862 $this->assertFalse( $op->isArticle() );
863 $this->assertFalse( $op->isArticleRelated() );
867 * @covers OutputPage::addLanguageLinks
868 * @covers OutputPage::setLanguageLinks
869 * @covers OutputPage::getLanguageLinks
870 * @covers OutputPage::addParserOutputMetadata
872 function testLanguageLinks() {
873 $op = $this->newInstance();
874 $this->assertSame( [], $op->getLanguageLinks() );
876 $op->addLanguageLinks( [ 'fr:A', 'it:B' ] );
877 $this->assertSame( [ 'fr:A', 'it:B' ], $op->getLanguageLinks() );
879 $op->addLanguageLinks( [ 'de:C', 'es:D' ] );
880 $this->assertSame( [ 'fr:A', 'it:B', 'de:C', 'es:D' ], $op->getLanguageLinks() );
882 $op->setLanguageLinks( [ 'pt:E' ] );
883 $this->assertSame( [ 'pt:E' ], $op->getLanguageLinks() );
885 $po = new ParserOutput();
886 $po->setLanguageLinks( [ 'he:F', 'ar:G' ] );
887 $op->addParserOutputMetadata( $po );
888 $this->assertSame( [ 'pt:E', 'he:F', 'ar:G' ], $op->getLanguageLinks() );
891 // @todo Are these category links tests too abstract and complicated for what they test? Would
892 // it make sense to just write out all the tests by hand with maybe some copy-and-paste?
895 * @dataProvider provideGetCategories
897 * @covers OutputPage::addCategoryLinks
898 * @covers OutputPage::getCategories
899 * @covers OutputPage::getCategoryLinks
901 * @param array $args Array of form [ category name => sort key ]
902 * @param array $fakeResults Array of form [ category name => value to return from mocked
904 * @param callback $variantLinkCallback Callback to replace findVariantLink() call
905 * @param array $expectedNormal Expected return value of getCategoryLinks['normal']
906 * @param array $expectedHidden Expected return value of getCategoryLinks['hidden']
908 public function testAddCategoryLinks(
909 array $args, array $fakeResults, callable
$variantLinkCallback = null,
910 array $expectedNormal, array $expectedHidden
912 $expectedNormal = $this->extractExpectedCategories( $expectedNormal, 'add' );
913 $expectedHidden = $this->extractExpectedCategories( $expectedHidden, 'add' );
915 $op = $this->setupCategoryTests( $fakeResults, $variantLinkCallback );
917 $op->addCategoryLinks( $args );
919 $this->doCategoryAsserts( $op, $expectedNormal, $expectedHidden );
920 $this->doCategoryLinkAsserts( $op, $expectedNormal, $expectedHidden );
924 * @dataProvider provideGetCategories
926 * @covers OutputPage::addCategoryLinks
927 * @covers OutputPage::getCategories
928 * @covers OutputPage::getCategoryLinks
930 public function testAddCategoryLinksOneByOne(
931 array $args, array $fakeResults, callable
$variantLinkCallback = null,
932 array $expectedNormal, array $expectedHidden
934 if ( count( $args ) <= 1 ) {
935 // @todo Should this be skipped instead of passed?
936 $this->assertTrue( true );
940 $expectedNormal = $this->extractExpectedCategories( $expectedNormal, 'onebyone' );
941 $expectedHidden = $this->extractExpectedCategories( $expectedHidden, 'onebyone' );
943 $op = $this->setupCategoryTests( $fakeResults, $variantLinkCallback );
945 foreach ( $args as $key => $val ) {
946 $op->addCategoryLinks( [ $key => $val ] );
949 $this->doCategoryAsserts( $op, $expectedNormal, $expectedHidden );
950 $this->doCategoryLinkAsserts( $op, $expectedNormal, $expectedHidden );
954 * @dataProvider provideGetCategories
956 * @covers OutputPage::setCategoryLinks
957 * @covers OutputPage::getCategories
958 * @covers OutputPage::getCategoryLinks
960 public function testSetCategoryLinks(
961 array $args, array $fakeResults, callable
$variantLinkCallback = null,
962 array $expectedNormal, array $expectedHidden
964 $expectedNormal = $this->extractExpectedCategories( $expectedNormal, 'set' );
965 $expectedHidden = $this->extractExpectedCategories( $expectedHidden, 'set' );
967 $op = $this->setupCategoryTests( $fakeResults, $variantLinkCallback );
969 $op->setCategoryLinks( [ 'Initial page' => 'Initial page' ] );
970 $op->setCategoryLinks( $args );
972 // We don't reset the categories, for some reason, only the links
973 $expectedNormalCats = array_merge( [ 'Initial page' ], $expectedNormal );
974 $expectedCats = array_merge( $expectedHidden, $expectedNormalCats );
976 $this->doCategoryAsserts( $op, $expectedNormalCats, $expectedHidden );
977 $this->doCategoryLinkAsserts( $op, $expectedNormal, $expectedHidden );
981 * @dataProvider provideGetCategories
983 * @covers OutputPage::addParserOutputMetadata
984 * @covers OutputPage::getCategories
985 * @covers OutputPage::getCategoryLinks
987 public function testParserOutputCategoryLinks(
988 array $args, array $fakeResults, callable
$variantLinkCallback = null,
989 array $expectedNormal, array $expectedHidden
991 $expectedNormal = $this->extractExpectedCategories( $expectedNormal, 'pout' );
992 $expectedHidden = $this->extractExpectedCategories( $expectedHidden, 'pout' );
994 $op = $this->setupCategoryTests( $fakeResults, $variantLinkCallback );
996 $stubPO = $this->createParserOutputStub( 'getCategories', $args );
998 $op->addParserOutputMetadata( $stubPO );
1000 $this->doCategoryAsserts( $op, $expectedNormal, $expectedHidden );
1001 $this->doCategoryLinkAsserts( $op, $expectedNormal, $expectedHidden );
1005 * We allow different expectations for different tests as an associative array, like
1006 * [ 'set' => [ ... ], 'default' => [ ... ] ] if setCategoryLinks() will give a different
1009 private function extractExpectedCategories( array $expected, $key ) {
1010 if ( !$expected ||
isset( $expected[0] ) ) {
1013 return $expected[$key] ??
$expected['default'];
1016 private function setupCategoryTests(
1017 array $fakeResults, callable
$variantLinkCallback = null
1019 $this->setMwGlobals( 'wgUsePigLatinVariant', true );
1021 $op = $this->getMockBuilder( OutputPage
::class )
1022 ->setConstructorArgs( [ new RequestContext() ] )
1023 ->setMethods( [ 'addCategoryLinksToLBAndGetResult' ] )
1026 $op->expects( $this->any() )
1027 ->method( 'addCategoryLinksToLBAndGetResult' )
1028 ->will( $this->returnCallback( function ( array $categories ) use ( $fakeResults ) {
1030 foreach ( $categories as $category => $unused ) {
1031 if ( isset( $fakeResults[$category] ) ) {
1032 $return[] = $fakeResults[$category];
1035 return new FakeResultWrapper( $return );
1038 if ( $variantLinkCallback ) {
1039 $mockContLang = $this->getMockBuilder( Language
::class )
1040 ->setConstructorArgs( [ 'en' ] )
1041 ->setMethods( [ 'findVariantLink' ] )
1043 $mockContLang->expects( $this->any() )
1044 ->method( 'findVariantLink' )
1045 ->will( $this->returnCallback( $variantLinkCallback ) );
1046 $this->setContentLang( $mockContLang );
1049 $this->assertSame( [], $op->getCategories() );
1054 private function doCategoryAsserts( $op, $expectedNormal, $expectedHidden ) {
1055 $this->assertSame( array_merge( $expectedHidden, $expectedNormal ), $op->getCategories() );
1056 $this->assertSame( $expectedNormal, $op->getCategories( 'normal' ) );
1057 $this->assertSame( $expectedHidden, $op->getCategories( 'hidden' ) );
1060 private function doCategoryLinkAsserts( $op, $expectedNormal, $expectedHidden ) {
1061 $catLinks = $op->getCategoryLinks();
1062 $this->assertSame( (bool)$expectedNormal +
(bool)$expectedHidden, count( $catLinks ) );
1063 if ( $expectedNormal ) {
1064 $this->assertSame( count( $expectedNormal ), count( $catLinks['normal'] ) );
1066 if ( $expectedHidden ) {
1067 $this->assertSame( count( $expectedHidden ), count( $catLinks['hidden'] ) );
1070 foreach ( $expectedNormal as $i => $name ) {
1071 $this->assertContains( $name, $catLinks['normal'][$i] );
1073 foreach ( $expectedHidden as $i => $name ) {
1074 $this->assertContains( $name, $catLinks['hidden'][$i] );
1078 public function provideGetCategories() {
1080 'No categories' => [ [], [], null, [], [] ],
1082 [ 'Test1' => 'Some sortkey', 'Test2' => 'A different sortkey' ],
1083 [ 'Test1' => (object)[ 'pp_value' => 1, 'page_title' => 'Test1' ],
1084 'Test2' => (object)[ 'page_title' => 'Test2' ] ],
1089 'Invalid title' => [
1090 [ '[' => '[', 'Test' => 'Test' ],
1091 [ 'Test' => (object)[ 'page_title' => 'Test' ] ],
1097 [ 'Test' => 'Test', 'Estay' => 'Estay' ],
1098 [ 'Test' => (object)[ 'page_title' => 'Test' ] ],
1099 function ( &$link, &$title ) {
1100 if ( $link === 'Estay' ) {
1102 $title = Title
::makeTitleSafe( NS_CATEGORY
, $link );
1105 // For adding one by one, the variant gets added as well as the original category,
1106 // but if you add them all together the second time gets skipped.
1107 [ 'onebyone' => [ 'Test', 'Test' ], 'default' => [ 'Test' ] ],
1114 * @covers OutputPage::getCategories
1116 public function testGetCategoriesInvalid() {
1117 $this->setExpectedException( InvalidArgumentException
::class,
1118 'Invalid category type given: hiddne' );
1120 $op = $this->newInstance();
1121 $op->getCategories( 'hiddne' );
1124 // @todo Should we test addCategoryLinksToLBAndGetResult? If so, how? Insert some test rows in
1128 * @covers OutputPage::setIndicators
1129 * @covers OutputPage::getIndicators
1130 * @covers OutputPage::addParserOutputMetadata
1132 public function testIndicators() {
1133 $op = $this->newInstance();
1134 $this->assertSame( [], $op->getIndicators() );
1136 $op->setIndicators( [] );
1137 $this->assertSame( [], $op->getIndicators() );
1139 // Test sorting alphabetically
1140 $op->setIndicators( [ 'b' => 'x', 'a' => 'y' ] );
1141 $this->assertSame( [ 'a' => 'y', 'b' => 'x' ], $op->getIndicators() );
1143 // Test overwriting existing keys
1144 $op->setIndicators( [ 'c' => 'z', 'a' => 'w' ] );
1145 $this->assertSame( [ 'a' => 'w', 'b' => 'x', 'c' => 'z' ], $op->getIndicators() );
1147 // Test with ParserOutput
1148 $stubPO = $this->createParserOutputStub( 'getIndicators', [ 'c' => 'u', 'd' => 'v' ] );
1149 $op->addParserOutputMetadata( $stubPO );
1150 $this->assertSame( [ 'a' => 'w', 'b' => 'x', 'c' => 'u', 'd' => 'v' ],
1151 $op->getIndicators() );
1155 * @covers OutputPage::addHelpLink
1156 * @covers OutputPage::getIndicators
1158 public function testAddHelpLink() {
1159 $op = $this->newInstance();
1161 $op->addHelpLink( 'Manual:PHP unit testing' );
1162 $indicators = $op->getIndicators();
1163 $this->assertSame( [ 'mw-helplink' ], array_keys( $indicators ) );
1164 $this->assertContains( 'Manual:PHP_unit_testing', $indicators['mw-helplink'] );
1166 $op->addHelpLink( 'https://phpunit.de', true );
1167 $indicators = $op->getIndicators();
1168 $this->assertSame( [ 'mw-helplink' ], array_keys( $indicators ) );
1169 $this->assertContains( 'https://phpunit.de', $indicators['mw-helplink'] );
1170 $this->assertNotContains( 'mediawiki', $indicators['mw-helplink'] );
1171 $this->assertNotContains( 'Manual:PHP', $indicators['mw-helplink'] );
1175 * @covers OutputPage::prependHTML
1176 * @covers OutputPage::addHTML
1177 * @covers OutputPage::addElement
1178 * @covers OutputPage::clearHTML
1179 * @covers OutputPage::getHTML
1181 public function testBodyHTML() {
1182 $op = $this->newInstance();
1183 $this->assertSame( '', $op->getHTML() );
1185 $op->addHTML( 'a' );
1186 $this->assertSame( 'a', $op->getHTML() );
1188 $op->addHTML( 'b' );
1189 $this->assertSame( 'ab', $op->getHTML() );
1191 $op->prependHTML( 'c' );
1192 $this->assertSame( 'cab', $op->getHTML() );
1194 $op->addElement( 'p', [ 'id' => 'foo' ], 'd' );
1195 $this->assertSame( 'cab<p id="foo">d</p>', $op->getHTML() );
1198 $this->assertSame( '', $op->getHTML() );
1202 * @dataProvider provideRevisionId
1203 * @covers OutputPage::setRevisionId
1204 * @covers OutputPage::getRevisionId
1206 public function testRevisionId( $newVal, $expected ) {
1207 $op = $this->newInstance();
1209 $this->assertNull( $op->setRevisionId( $newVal ) );
1210 $this->assertSame( $expected, $op->getRevisionId() );
1211 $this->assertSame( $expected, $op->setRevisionId( null ) );
1212 $this->assertNull( $op->getRevisionId() );
1215 public function provideRevisionId() {
1222 [ '32% finished', 32 ],
1228 * @covers OutputPage::setRevisionTimestamp
1229 * @covers OutputPage::getRevisionTimestamp
1231 public function testRevisionTimestamp() {
1232 $op = $this->newInstance();
1233 $this->assertNull( $op->getRevisionTimestamp() );
1235 $this->assertNull( $op->setRevisionTimestamp( 'abc' ) );
1236 $this->assertSame( 'abc', $op->getRevisionTimestamp() );
1237 $this->assertSame( 'abc', $op->setRevisionTimestamp( null ) );
1238 $this->assertNull( $op->getRevisionTimestamp() );
1242 * @covers OutputPage::setFileVersion
1243 * @covers OutputPage::getFileVersion
1245 public function testFileVersion() {
1246 $op = $this->newInstance();
1247 $this->assertNull( $op->getFileVersion() );
1249 $stubFile = $this->createMock( File
::class );
1250 $stubFile->method( 'exists' )->willReturn( true );
1251 $stubFile->method( 'getTimestamp' )->willReturn( '12211221123321' );
1252 $stubFile->method( 'getSha1' )->willReturn( 'bf3ffa7047dc080f5855377a4f83cd18887e3b05' );
1254 $op->setFileVersion( $stubFile );
1256 $this->assertEquals(
1257 [ 'time' => '12211221123321', 'sha1' => 'bf3ffa7047dc080f5855377a4f83cd18887e3b05' ],
1258 $op->getFileVersion()
1261 $stubMissingFile = $this->createMock( File
::class );
1262 $stubMissingFile->method( 'exists' )->willReturn( false );
1264 $op->setFileVersion( $stubMissingFile );
1265 $this->assertNull( $op->getFileVersion() );
1267 $op->setFileVersion( $stubFile );
1268 $this->assertNotNull( $op->getFileVersion() );
1270 $op->setFileVersion( null );
1271 $this->assertNull( $op->getFileVersion() );
1274 private function createParserOutputStub( $method = '', $retVal = [] ) {
1275 $pOut = $this->getMock( ParserOutput
::class );
1276 if ( $method !== '' ) {
1277 $pOut->method( $method )->willReturn( $retVal );
1280 $arrayReturningMethods = [
1282 'getFileSearchOptions',
1290 foreach ( $arrayReturningMethods as $method ) {
1291 $pOut->method( $method )->willReturn( [] );
1298 * @covers OutputPage::getTemplateIds
1299 * @covers OutputPage::addParserOutputMetadata
1301 public function testTemplateIds() {
1302 $op = $this->newInstance();
1303 $this->assertSame( [], $op->getTemplateIds() );
1305 // Test with no template id's
1306 $stubPOEmpty = $this->createParserOutputStub();
1307 $op->addParserOutputMetadata( $stubPOEmpty );
1308 $this->assertSame( [], $op->getTemplateIds() );
1310 // Test with some arbitrary template id's
1312 NS_MAIN
=> [ 'A' => 3, 'B' => 17 ],
1313 NS_TALK
=> [ 'C' => 31 ],
1314 NS_MEDIA
=> [ 'D' => -1 ],
1317 $stubPO1 = $this->createParserOutputStub( 'getTemplateIds', $ids );
1319 $op->addParserOutputMetadata( $stubPO1 );
1320 $this->assertSame( $ids, $op->getTemplateIds() );
1322 // Test merging with a second set of id's
1323 $stubPO2 = $this->createParserOutputStub( 'getTemplateIds', [
1324 NS_MAIN
=> [ 'E' => 1234 ],
1325 NS_PROJECT
=> [ 'F' => 5678 ],
1329 NS_MAIN
=> [ 'E' => 1234, 'A' => 3, 'B' => 17 ],
1330 NS_TALK
=> [ 'C' => 31 ],
1331 NS_MEDIA
=> [ 'D' => -1 ],
1332 NS_PROJECT
=> [ 'F' => 5678 ],
1335 $op->addParserOutputMetadata( $stubPO2 );
1336 $this->assertSame( $finalIds, $op->getTemplateIds() );
1338 // Test merging with an empty set of id's
1339 $op->addParserOutputMetadata( $stubPOEmpty );
1340 $this->assertSame( $finalIds, $op->getTemplateIds() );
1344 * @covers OutputPage::getFileSearchOptions
1345 * @covers OutputPage::addParserOutputMetadata
1347 public function testFileSearchOptions() {
1348 $op = $this->newInstance();
1349 $this->assertSame( [], $op->getFileSearchOptions() );
1351 // Test with no files
1352 $stubPOEmpty = $this->createParserOutputStub();
1354 $op->addParserOutputMetadata( $stubPOEmpty );
1355 $this->assertSame( [], $op->getFileSearchOptions() );
1357 // Test with some arbitrary files
1359 'A' => [ 'time' => null, 'sha1' => '' ],
1361 'time' => '12211221123321',
1362 'sha1' => 'bf3ffa7047dc080f5855377a4f83cd18887e3b05',
1366 $stubPO1 = $this->createParserOutputStub( 'getFileSearchOptions', $files1 );
1368 $op->addParserOutputMetadata( $stubPO1 );
1369 $this->assertSame( $files1, $op->getFileSearchOptions() );
1371 // Test merging with a second set of files
1373 'C' => [ 'time' => null, 'sha1' => '' ],
1374 'B' => [ 'time' => null, 'sha1' => '' ],
1377 $stubPO2 = $this->createParserOutputStub( 'getFileSearchOptions', $files2 );
1379 $op->addParserOutputMetadata( $stubPO2 );
1380 $this->assertSame( array_merge( $files1, $files2 ), $op->getFileSearchOptions() );
1382 // Test merging with an empty set of files
1383 $op->addParserOutputMetadata( $stubPOEmpty );
1384 $this->assertSame( array_merge( $files1, $files2 ), $op->getFileSearchOptions() );
1388 * @dataProvider provideAddWikiText
1389 * @covers OutputPage::addWikiText
1390 * @covers OutputPage::addWikiTextWithTitle
1391 * @covers OutputPage::addWikiTextTitle
1392 * @covers OutputPage::addWikiTextTidy
1393 * @covers OutputPage::addWikiTextTitleTidy
1394 * @covers OutputPage::getHTML
1396 public function testAddWikiText( $method, array $args, $expected ) {
1397 $op = $this->newInstance();
1398 $this->assertSame( '', $op->getHTML() );
1402 [ 'addWikiTextWithTitle', 'addWikiTextTitleTidy', 'addWikiTextTitle' ]
1403 ) && count( $args ) >= 2 && $args[1] === null ) {
1404 // Special placeholder because we can't get the actual title in the provider
1405 $args[1] = $op->getTitle();
1408 $op->$method( ...$args );
1409 $this->assertSame( $expected, $op->getHTML() );
1412 public function provideAddWikiText() {
1415 'Simple wikitext' => [
1417 "<p><b>Bold</b>\n</p>",
1418 ], 'List at start' => [
1420 "<ul><li>List</li></ul>\n",
1421 ], 'List not at start' => [
1422 [ '* Not a list', false ],
1424 ], 'Non-interface' => [
1425 [ "'''Bold'''", true, false ],
1426 "<p><b>Bold</b>\n</p>",
1427 ], 'No section edit links' => [
1429 "<h2><span class=\"mw-headline\" id=\"Title\">Title</span></h2>\n",
1432 'addWikiTextWithTitle' => [
1433 'With title at start' => [
1434 [ '* {{PAGENAME}}', Title
::newFromText( 'Talk:Some page' ) ],
1435 "<ul><li>Some page</li></ul>\n",
1436 ], 'With title at start' => [
1437 [ '* {{PAGENAME}}', Title
::newFromText( 'Talk:Some page' ), false ],
1441 'addWikiTextTidy' => [
1442 'SpecialNewimages' => [
1443 [ "<p lang='en' dir='ltr'>\nMy message" ],
1444 '<p lang="en" dir="ltr">' . "\nMy message\n</p>"
1445 ], 'List at start' => [
1447 "<ul><li>List</li></ul>\n",
1448 ], 'List not at start' => [
1449 [ '* <b>Not a list', false ],
1450 '<p>* <b>Not a list</b></p>',
1453 'addWikiTextTitleTidy' => [
1454 'With title at start' => [
1455 [ '* {{PAGENAME}}', Title
::newFromText( 'Talk:Some page' ) ],
1456 "<ul><li>Some page</li></ul>\n",
1457 ], 'With title at start' => [
1458 [ '* {{PAGENAME}}', Title
::newFromText( 'Talk:Some page' ), false ],
1459 "<p>* Some page</p>",
1461 [ "<div class='mw-editintro'>{{PAGENAME}}", Title
::newFromText( 'Talk:Some page' ) ],
1462 '<div class="mw-editintro">' . "Some page\n</div>"
1467 // Test all the others on addWikiTextTitle as well
1468 foreach ( $tests['addWikiText'] as $key => $val ) {
1469 $args = [ $val[0][0], null, $val[0][1] ??
true, false, $val[0][2] ??
true ];
1470 $tests['addWikiTextTitle']["$key (addWikiTextTitle)"] =
1471 array_merge( [ $args ], array_slice( $val, 1 ) );
1473 foreach ( $tests['addWikiTextWithTitle'] as $key => $val ) {
1474 $args = [ $val[0][0], $val[0][1], $val[0][2] ??
true ];
1475 $tests['addWikiTextTitle']["$key (addWikiTextTitle)"] =
1476 array_merge( [ $args ], array_slice( $val, 1 ) );
1478 foreach ( $tests['addWikiTextTidy'] as $key => $val ) {
1479 $args = [ $val[0][0], null, $val[0][1] ??
true, true, false ];
1480 $tests['addWikiTextTitle']["$key (addWikiTextTitle)"] =
1481 array_merge( [ $args ], array_slice( $val, 1 ) );
1483 foreach ( $tests['addWikiTextTitleTidy'] as $key => $val ) {
1484 $args = [ $val[0][0], $val[0][1], $val[0][2] ??
true, true, false ];
1485 $tests['addWikiTextTitle']["$key (addWikiTextTitle)"] =
1486 array_merge( [ $args ], array_slice( $val, 1 ) );
1489 // We have to reformat our array to match what PHPUnit wants
1491 foreach ( $tests as $key => $subarray ) {
1492 foreach ( $subarray as $subkey => $val ) {
1493 $val = array_merge( [ $key ], $val );
1494 $ret[$subkey] = $val;
1502 * @covers OutputPage::addWikiText
1504 public function testAddWikiTextNoTitle() {
1505 $this->setExpectedException( MWException
::class, 'Title is null' );
1507 $op = $this->newInstance( [], null, 'notitle' );
1508 $op->addWikiText( 'a' );
1512 * @covers OutputPage::addParserOutputMetadata
1514 public function testNoGallery() {
1515 $op = $this->newInstance();
1516 $this->assertFalse( $op->mNoGallery
);
1518 $stubPO1 = $this->createParserOutputStub( 'getNoGallery', true );
1519 $op->addParserOutputMetadata( $stubPO1 );
1520 $this->assertTrue( $op->mNoGallery
);
1522 $stubPO2 = $this->createParserOutputStub( 'getNoGallery', false );
1523 $op->addParserOutputMetadata( $stubPO2 );
1524 $this->assertFalse( $op->mNoGallery
);
1527 // @todo Make sure to test the following in addParserOutputMetadata() as well when we add tests
1529 // * enableClientCache()
1531 // * addModuleScripts()
1532 // * addModuleStyles()
1533 // * addJsConfigVars()
1534 // * preventClickJacking()
1535 // Otherwise those lines of addParserOutputMetadata() will be reported as covered, but we won't
1536 // be testing they actually work.
1539 * @covers OutputPage::haveCacheVaryCookies
1541 public function testHaveCacheVaryCookies() {
1542 $request = new FauxRequest();
1543 $context = new RequestContext();
1544 $context->setRequest( $request );
1545 $op = new OutputPage( $context );
1547 // No cookies are set.
1548 $this->assertFalse( $op->haveCacheVaryCookies() );
1550 // 'Token' is present but empty, so it shouldn't count.
1551 $request->setCookie( 'Token', '' );
1552 $this->assertFalse( $op->haveCacheVaryCookies() );
1554 // 'Token' present and nonempty.
1555 $request->setCookie( 'Token', '123' );
1556 $this->assertTrue( $op->haveCacheVaryCookies() );
1560 * @dataProvider provideVaryHeaders
1562 * @covers OutputPage::addVaryHeader
1563 * @covers OutputPage::getVaryHeader
1564 * @covers OutputPage::getKeyHeader
1566 public function testVaryHeaders( $calls, $vary, $key ) {
1567 // get rid of default Vary fields
1568 $op = $this->getMockBuilder( OutputPage
::class )
1569 ->setConstructorArgs( [ new RequestContext() ] )
1570 ->setMethods( [ 'getCacheVaryCookies' ] )
1572 $op->expects( $this->any() )
1573 ->method( 'getCacheVaryCookies' )
1574 ->will( $this->returnValue( [] ) );
1575 TestingAccessWrapper
::newFromObject( $op )->mVaryHeader
= [];
1577 foreach ( $calls as $call ) {
1578 call_user_func_array( [ $op, 'addVaryHeader' ], $call );
1580 $this->assertEquals( $vary, $op->getVaryHeader(), 'Vary:' );
1581 $this->assertEquals( $key, $op->getKeyHeader(), 'Key:' );
1584 public function provideVaryHeaders() {
1585 // note: getKeyHeader() automatically adds Vary: Cookie
1594 [ // non-unique headers
1597 [ 'Accept-Language' ],
1600 'Vary: Cookie, Accept-Language',
1601 'Key: Cookie,Accept-Language',
1603 [ // two headers with single options
1605 [ 'Cookie', [ 'param=phpsessid' ] ],
1606 [ 'Accept-Language', [ 'substr=en' ] ],
1608 'Vary: Cookie, Accept-Language',
1609 'Key: Cookie;param=phpsessid,Accept-Language;substr=en',
1611 [ // one header with multiple options
1613 [ 'Cookie', [ 'param=phpsessid', 'param=userId' ] ],
1616 'Key: Cookie;param=phpsessid;param=userId',
1618 [ // Duplicate option
1620 [ 'Cookie', [ 'param=phpsessid' ] ],
1621 [ 'Cookie', [ 'param=phpsessid' ] ],
1622 [ 'Accept-Language', [ 'substr=en', 'substr=en' ] ],
1624 'Vary: Cookie, Accept-Language',
1625 'Key: Cookie;param=phpsessid,Accept-Language;substr=en',
1627 [ // Same header, different options
1629 [ 'Cookie', [ 'param=phpsessid' ] ],
1630 [ 'Cookie', [ 'param=userId' ] ],
1633 'Key: Cookie;param=phpsessid;param=userId',
1639 * @dataProvider provideLinkHeaders
1641 * @covers OutputPage::addLinkHeader
1642 * @covers OutputPage::getLinkHeader
1644 public function testLinkHeaders( $headers, $result ) {
1645 $op = $this->newInstance();
1647 foreach ( $headers as $header ) {
1648 $op->addLinkHeader( $header );
1651 $this->assertEquals( $result, $op->getLinkHeader() );
1654 public function provideLinkHeaders() {
1661 [ '<https://foo/bar.jpg>;rel=preload;as=image' ],
1662 'Link: <https://foo/bar.jpg>;rel=preload;as=image',
1665 [ '<https://foo/bar.jpg>;rel=preload;as=image','<https://foo/baz.jpg>;rel=preload;as=image' ],
1666 'Link: <https://foo/bar.jpg>;rel=preload;as=image,<https://foo/baz.jpg>;rel=preload;as=image',
1672 * See ResourceLoaderClientHtmlTest for full coverage.
1674 * @dataProvider provideMakeResourceLoaderLink
1676 * @covers OutputPage::makeResourceLoaderLink
1678 public function testMakeResourceLoaderLink( $args, $expectedHtml ) {
1679 $this->setMwGlobals( [
1680 'wgResourceLoaderDebug' => false,
1681 'wgLoadScript' => 'http://127.0.0.1:8080/w/load.php',
1682 'wgCSPReportOnlyHeader' => true,
1684 $class = new ReflectionClass( OutputPage
::class );
1685 $method = $class->getMethod( 'makeResourceLoaderLink' );
1686 $method->setAccessible( true );
1687 $ctx = new RequestContext();
1688 $ctx->setSkin( SkinFactory
::getDefaultInstance()->makeSkin( 'fallback' ) );
1689 $ctx->setLanguage( 'en' );
1690 $out = new OutputPage( $ctx );
1691 $nonce = $class->getProperty( 'CSPNonce' );
1692 $nonce->setAccessible( true );
1693 $nonce->setValue( $out, 'secret' );
1694 $rl = $out->getResourceLoader();
1695 $rl->setMessageBlobStore( new NullMessageBlobStore() );
1697 'test.foo' => new ResourceLoaderTestModule( [
1698 'script' => 'mw.test.foo( { a: true } );',
1699 'styles' => '.mw-test-foo { content: "style"; }',
1701 'test.bar' => new ResourceLoaderTestModule( [
1702 'script' => 'mw.test.bar( { a: true } );',
1703 'styles' => '.mw-test-bar { content: "style"; }',
1705 'test.baz' => new ResourceLoaderTestModule( [
1706 'script' => 'mw.test.baz( { a: true } );',
1707 'styles' => '.mw-test-baz { content: "style"; }',
1709 'test.quux' => new ResourceLoaderTestModule( [
1710 'script' => 'mw.test.baz( { token: 123 } );',
1711 'styles' => '/* pref-animate=off */ .mw-icon { transition: none; }',
1712 'group' => 'private',
1714 'test.noscript' => new ResourceLoaderTestModule( [
1715 'styles' => '.stuff { color: red; }',
1716 'group' => 'noscript',
1718 'test.group.foo' => new ResourceLoaderTestModule( [
1719 'script' => 'mw.doStuff( "foo" );',
1722 'test.group.bar' => new ResourceLoaderTestModule( [
1723 'script' => 'mw.doStuff( "bar" );',
1727 $links = $method->invokeArgs( $out, $args );
1728 $actualHtml = strval( $links );
1729 $this->assertEquals( $expectedHtml, $actualHtml );
1732 public static function provideMakeResourceLoaderLink() {
1733 // phpcs:disable Generic.Files.LineLength
1735 // Single only=scripts load
1737 [ 'test.foo', ResourceLoaderModule
::TYPE_SCRIPTS
],
1738 "<script nonce=\"secret\">(window.RLQ=window.RLQ||[]).push(function(){"
1739 . 'mw.loader.load("http://127.0.0.1:8080/w/load.php?debug=false\u0026lang=en\u0026modules=test.foo\u0026only=scripts\u0026skin=fallback");'
1742 // Multiple only=styles load
1744 [ [ 'test.baz', 'test.foo', 'test.bar' ], ResourceLoaderModule
::TYPE_STYLES
],
1746 '<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"/>'
1748 // Private embed (only=scripts)
1750 [ 'test.quux', ResourceLoaderModule
::TYPE_SCRIPTS
],
1751 "<script nonce=\"secret\">(window.RLQ=window.RLQ||[]).push(function(){"
1752 . "mw.test.baz({token:123});\nmw.loader.state({\"test.quux\":\"ready\"});"
1755 // Load private module (combined)
1757 [ 'test.quux', ResourceLoaderModule
::TYPE_COMBINED
],
1758 "<script nonce=\"secret\">(window.RLQ=window.RLQ||[]).push(function(){"
1759 . "mw.loader.implement(\"test.quux@1ev0ijv\",function($,jQuery,require,module){"
1760 . "mw.test.baz({token:123});},{\"css\":[\".mw-icon{transition:none}"
1761 . "\"]});});</script>"
1765 [ [], ResourceLoaderModule
::TYPE_COMBINED
],
1770 [ 'test.noscript', ResourceLoaderModule
::TYPE_STYLES
],
1771 '<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>'
1773 // Load two modules in separate groups
1775 [ [ 'test.group.foo', 'test.group.bar' ], ResourceLoaderModule
::TYPE_COMBINED
],
1776 "<script nonce=\"secret\">(window.RLQ=window.RLQ||[]).push(function(){"
1777 . 'mw.loader.load("http://127.0.0.1:8080/w/load.php?debug=false\u0026lang=en\u0026modules=test.group.bar\u0026skin=fallback");'
1778 . 'mw.loader.load("http://127.0.0.1:8080/w/load.php?debug=false\u0026lang=en\u0026modules=test.group.foo\u0026skin=fallback");'
1786 * @dataProvider provideBuildExemptModules
1788 * @covers OutputPage::buildExemptModules
1790 public function testBuildExemptModules( array $exemptStyleModules, $expect ) {
1791 $this->setMwGlobals( [
1792 'wgResourceLoaderDebug' => false,
1793 'wgLoadScript' => '/w/load.php',
1794 // Stub wgCacheEpoch as it influences getVersionHash used for the
1795 // urls in the expected HTML
1796 'wgCacheEpoch' => '20140101000000',
1800 $ctx = new RequestContext();
1801 $ctx->setSkin( SkinFactory
::getDefaultInstance()->makeSkin( 'fallback' ) );
1802 $ctx->setLanguage( 'en' );
1803 $op = $this->getMockBuilder( OutputPage
::class )
1804 ->setConstructorArgs( [ $ctx ] )
1805 ->setMethods( [ 'buildCssLinksArray' ] )
1807 $op->expects( $this->any() )
1808 ->method( 'buildCssLinksArray' )
1810 $rl = $op->getResourceLoader();
1811 $rl->setMessageBlobStore( new NullMessageBlobStore() );
1813 // Register custom modules
1815 'example.site.a' => new ResourceLoaderTestModule( [ 'group' => 'site' ] ),
1816 'example.site.b' => new ResourceLoaderTestModule( [ 'group' => 'site' ] ),
1817 'example.user' => new ResourceLoaderTestModule( [ 'group' => 'user' ] ),
1820 $op = TestingAccessWrapper
::newFromObject( $op );
1821 $op->rlExemptStyleModules
= $exemptStyleModules;
1822 $this->assertEquals(
1824 strval( $op->buildExemptModules() )
1828 public static function provideBuildExemptModules() {
1829 // phpcs:disable Generic.Files.LineLength
1832 'exemptStyleModules' => [],
1833 '<meta name="ResourceLoaderDynamicStyles" content=""/>',
1836 'exemptStyleModules' => [ 'site' => [], 'noscript' => [], 'private' => [], 'user' => [] ],
1837 '<meta name="ResourceLoaderDynamicStyles" content=""/>',
1839 'default logged-out' => [
1840 'exemptStyleModules' => [ 'site' => [ 'site.styles' ] ],
1841 '<meta name="ResourceLoaderDynamicStyles" content=""/>' . "\n" .
1842 '<link rel="stylesheet" href="/w/load.php?debug=false&lang=en&modules=site.styles&only=styles&skin=fallback"/>',
1844 'default logged-in' => [
1845 'exemptStyleModules' => [ 'site' => [ 'site.styles' ], 'user' => [ 'user.styles' ] ],
1846 '<meta name="ResourceLoaderDynamicStyles" content=""/>' . "\n" .
1847 '<link rel="stylesheet" href="/w/load.php?debug=false&lang=en&modules=site.styles&only=styles&skin=fallback"/>' . "\n" .
1848 '<link rel="stylesheet" href="/w/load.php?debug=false&lang=en&modules=user.styles&only=styles&skin=fallback&version=1ai9g6t"/>',
1850 'custom modules' => [
1851 'exemptStyleModules' => [
1852 'site' => [ 'site.styles', 'example.site.a', 'example.site.b' ],
1853 'user' => [ 'user.styles', 'example.user' ],
1855 '<meta name="ResourceLoaderDynamicStyles" content=""/>' . "\n" .
1856 '<link rel="stylesheet" href="/w/load.php?debug=false&lang=en&modules=example.site.a%2Cb&only=styles&skin=fallback"/>' . "\n" .
1857 '<link rel="stylesheet" href="/w/load.php?debug=false&lang=en&modules=site.styles&only=styles&skin=fallback"/>' . "\n" .
1858 '<link rel="stylesheet" href="/w/load.php?debug=false&lang=en&modules=example.user&only=styles&skin=fallback&version=0a56zyi"/>' . "\n" .
1859 '<link rel="stylesheet" href="/w/load.php?debug=false&lang=en&modules=user.styles&only=styles&skin=fallback&version=1ai9g6t"/>',
1866 * @dataProvider provideTransformFilePath
1867 * @covers OutputPage::transformFilePath
1868 * @covers OutputPage::transformResourcePath
1870 public function testTransformResourcePath( $baseDir, $basePath, $uploadDir = null,
1871 $uploadPath = null, $path = null, $expected = null
1873 if ( $path === null ) {
1874 // Skip optional $uploadDir and $uploadPath
1876 $expected = $uploadPath;
1877 $uploadDir = "$baseDir/images";
1878 $uploadPath = "$basePath/images";
1880 $this->setMwGlobals( 'IP', $baseDir );
1881 $conf = new HashConfig( [
1882 'ResourceBasePath' => $basePath,
1883 'UploadDirectory' => $uploadDir,
1884 'UploadPath' => $uploadPath,
1887 // Some of these paths don't exist and will cause warnings
1888 Wikimedia\
suppressWarnings();
1889 $actual = OutputPage
::transformResourcePath( $conf, $path );
1890 Wikimedia\restoreWarnings
();
1892 $this->assertEquals( $expected ?
: $path, $actual );
1895 public static function provideTransformFilePath() {
1896 $baseDir = dirname( __DIR__
) . '/data/media';
1898 // File that matches basePath, and exists. Hash found and appended.
1900 'baseDir' => $baseDir, 'basePath' => '/w',
1904 // File that matches basePath, but not found on disk. Empty query.
1906 'baseDir' => $baseDir, 'basePath' => '/w',
1910 // File not matching basePath. Ignored.
1912 'baseDir' => $baseDir, 'basePath' => '/w',
1915 // Empty string. Ignored.
1917 'baseDir' => $baseDir, 'basePath' => '/w',
1921 // Similar path, but with domain component. Ignored.
1923 'baseDir' => $baseDir, 'basePath' => '/w',
1924 '//example.org/w/test.jpg'
1927 'baseDir' => $baseDir, 'basePath' => '/w',
1928 'https://example.org/w/test.jpg'
1930 // Unrelated path with domain component. Ignored.
1932 'baseDir' => $baseDir, 'basePath' => '/w',
1933 'https://example.org/files/test.jpg'
1936 'baseDir' => $baseDir, 'basePath' => '/w',
1937 '//example.org/files/test.jpg'
1939 // Unrelated path with domain, and empty base path (root mw install). Ignored.
1941 'baseDir' => $baseDir, 'basePath' => '',
1942 'https://example.org/files/test.jpg'
1945 'baseDir' => $baseDir, 'basePath' => '',
1947 '//example.org/files/test.jpg'
1949 // Check UploadPath before ResourceBasePath (T155146)
1951 'baseDir' => dirname( $baseDir ), 'basePath' => '',
1952 'uploadDir' => $baseDir, 'uploadPath' => '/images',
1954 '/images/test.jpg?edcf2'
1960 * Tests a particular case of transformCssMedia, using the given input, globals,
1961 * expected return, and message
1963 * Asserts that $expectedReturn is returned.
1965 * options['printableQuery'] - value of query string for printable, or omitted for none
1966 * options['handheldQuery'] - value of query string for handheld, or omitted for none
1967 * options['media'] - passed into the method under the same name
1968 * options['expectedReturn'] - expected return value
1969 * options['message'] - PHPUnit message for assertion
1971 * @param array $args Key-value array of arguments as shown above
1973 protected function assertTransformCssMediaCase( $args ) {
1975 if ( isset( $args['printableQuery'] ) ) {
1976 $queryData['printable'] = $args['printableQuery'];
1979 if ( isset( $args['handheldQuery'] ) ) {
1980 $queryData['handheld'] = $args['handheldQuery'];
1983 $fauxRequest = new FauxRequest( $queryData, false );
1984 $this->setMwGlobals( [
1985 'wgRequest' => $fauxRequest,
1988 $actualReturn = OutputPage
::transformCssMedia( $args['media'] );
1989 $this->assertSame( $args['expectedReturn'], $actualReturn, $args['message'] );
1993 * Tests print requests
1995 * @covers OutputPage::transformCssMedia
1997 public function testPrintRequests() {
1998 $this->assertTransformCssMediaCase( [
1999 'printableQuery' => '1',
2000 'media' => 'screen',
2001 'expectedReturn' => null,
2002 'message' => 'On printable request, screen returns null'
2005 $this->assertTransformCssMediaCase( [
2006 'printableQuery' => '1',
2007 'media' => self
::SCREEN_MEDIA_QUERY
,
2008 'expectedReturn' => null,
2009 'message' => 'On printable request, screen media query returns null'
2012 $this->assertTransformCssMediaCase( [
2013 'printableQuery' => '1',
2014 'media' => self
::SCREEN_ONLY_MEDIA_QUERY
,
2015 'expectedReturn' => null,
2016 'message' => 'On printable request, screen media query with only returns null'
2019 $this->assertTransformCssMediaCase( [
2020 'printableQuery' => '1',
2022 'expectedReturn' => '',
2023 'message' => 'On printable request, media print returns empty string'
2028 * Tests screen requests, without either query parameter set
2030 * @covers OutputPage::transformCssMedia
2032 public function testScreenRequests() {
2033 $this->assertTransformCssMediaCase( [
2034 'media' => 'screen',
2035 'expectedReturn' => 'screen',
2036 'message' => 'On screen request, screen media type is preserved'
2039 $this->assertTransformCssMediaCase( [
2040 'media' => 'handheld',
2041 'expectedReturn' => 'handheld',
2042 'message' => 'On screen request, handheld media type is preserved'
2045 $this->assertTransformCssMediaCase( [
2046 'media' => self
::SCREEN_MEDIA_QUERY
,
2047 'expectedReturn' => self
::SCREEN_MEDIA_QUERY
,
2048 'message' => 'On screen request, screen media query is preserved.'
2051 $this->assertTransformCssMediaCase( [
2052 'media' => self
::SCREEN_ONLY_MEDIA_QUERY
,
2053 'expectedReturn' => self
::SCREEN_ONLY_MEDIA_QUERY
,
2054 'message' => 'On screen request, screen media query with only is preserved.'
2057 $this->assertTransformCssMediaCase( [
2059 'expectedReturn' => 'print',
2060 'message' => 'On screen request, print media type is preserved'
2065 * Tests handheld behavior
2067 * @covers OutputPage::transformCssMedia
2069 public function testHandheld() {
2070 $this->assertTransformCssMediaCase( [
2071 'handheldQuery' => '1',
2072 'media' => 'handheld',
2073 'expectedReturn' => '',
2074 'message' => 'On request with handheld querystring and media is handheld, returns empty string'
2077 $this->assertTransformCssMediaCase( [
2078 'handheldQuery' => '1',
2079 'media' => 'screen',
2080 'expectedReturn' => null,
2081 'message' => 'On request with handheld querystring and media is screen, returns null'
2086 * @return OutputPage
2088 private function newInstance( $config = [], WebRequest
$request = null, $options = [] ) {
2089 $context = new RequestContext();
2091 $context->setConfig( new MultiConfig( [
2092 new HashConfig( $config +
[
2093 'AppleTouchIcon' => false,
2094 'DisableLangConversion' => true,
2095 'EnableCanonicalServerLink' => false,
2098 'LanguageCode' => false,
2099 'ReferrerPolicy' => false,
2100 'RightsPage' => false,
2101 'RightsUrl' => false,
2102 'UniversalEditButton' => false,
2104 $context->getConfig()
2107 if ( !in_array( 'notitle', (array)$options ) ) {
2108 $context->setTitle( Title
::newFromText( 'My test page' ) );
2112 $context->setRequest( $request );
2115 return new OutputPage( $context );
2120 * MessageBlobStore that doesn't do anything
2122 class NullMessageBlobStore
extends MessageBlobStore
{
2123 public function get( ResourceLoader
$resourceLoader, $modules, $lang ) {
2127 public function updateModule( $name, ResourceLoaderModule
$module, $lang ) {
2130 public function updateMessage( $key ) {
2133 public function clear() {