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)';
16 * @dataProvider provideRedirect
18 * @covers OutputPage::__construct
19 * @covers OutputPage::redirect
20 * @covers OutputPage::getRedirect
22 public function testRedirect( $url, $code = null ) {
23 $op = $this->newInstance();
24 if ( isset( $code ) ) {
25 $op->redirect( $url, $code );
27 $op->redirect( $url );
29 $expectedUrl = str_replace( "\n", '', $url );
30 $this->assertSame( $expectedUrl, $op->getRedirect() );
31 $this->assertSame( $expectedUrl, $op->mRedirect
);
32 $this->assertSame( $code ??
'302', $op->mRedirectCode
);
35 public function provideRedirect() {
37 [ 'http://example.com' ],
38 [ 'http://example.com', '400' ],
39 [ 'http://example.com', 'squirrels!!!' ],
45 * @covers OutputPage::setCopyrightUrl
46 * @covers OutputPage::getHeadLinksArray
48 public function testSetCopyrightUrl() {
49 $op = $this->newInstance();
50 $op->setCopyrightUrl( 'http://example.com' );
53 Html
::element( 'link', [ 'rel' => 'license', 'href' => 'http://example.com' ] ),
54 $op->getHeadLinksArray()['copyright']
58 // @todo How to test setStatusCode?
61 * @covers OutputPage::addMeta
62 * @covers OutputPage::getMetaTags
63 * @covers OutputPage::getHeadLinksArray
65 public function testMetaTags() {
66 $op = $this->newInstance();
67 $op->addMeta( 'http:expires', '0' );
68 $op->addMeta( 'keywords', 'first' );
69 $op->addMeta( 'keywords', 'second' );
70 $op->addMeta( 'og:title', 'Ta-duh' );
73 [ 'http:expires', '0' ],
74 [ 'keywords', 'first' ],
75 [ 'keywords', 'second' ],
76 [ 'og:title', 'Ta-duh' ],
78 $this->assertSame( $expected, $op->getMetaTags() );
80 $links = $op->getHeadLinksArray();
81 $this->assertContains( '<meta http-equiv="expires" content="0"/>', $links );
82 $this->assertContains( '<meta name="keywords" content="first"/>', $links );
83 $this->assertContains( '<meta name="keywords" content="second"/>', $links );
84 $this->assertContains( '<meta property="og:title" content="Ta-duh"/>', $links );
85 $this->assertArrayNotHasKey( 'meta-robots', $links );
89 * @covers OutputPage::addLink
90 * @covers OutputPage::getLinkTags
91 * @covers OutputPage::getHeadLinksArray
93 public function testAddLink() {
94 $op = $this->newInstance();
98 [ 'rel' => 'foo', 'href' => 'http://example.com' ],
101 foreach ( $links as $link ) {
102 $op->addLink( $link );
105 $this->assertSame( $links, $op->getLinkTags() );
107 $result = $op->getHeadLinksArray();
109 foreach ( $links as $link ) {
110 $this->assertContains( Html
::element( 'link', $link ), $result );
115 * @covers OutputPage::setCanonicalUrl
116 * @covers OutputPage::getCanonicalUrl
117 * @covers OutputPage::getHeadLinksArray
119 public function testSetCanonicalUrl() {
120 $op = $this->newInstance();
121 $op->setCanonicalUrl( 'http://example.comm' );
122 $op->setCanonicalUrl( 'http://example.com' );
124 $this->assertSame( 'http://example.com', $op->getCanonicalUrl() );
126 $headLinks = $op->getHeadLinksArray();
128 $this->assertContains( Html
::element( 'link', [
129 'rel' => 'canonical', 'href' => 'http://example.com'
132 $this->assertNotContains( Html
::element( 'link', [
133 'rel' => 'canonical', 'href' => 'http://example.comm'
138 * @covers OutputPage::addScript
140 public function testAddScript() {
141 $op = $this->newInstance();
142 $op->addScript( 'some random string' );
144 $this->assertContains( "\nsome random string\n", "\n" . $op->getBottomScripts() . "\n" );
148 * @covers OutputPage::addScriptFile
150 public function testAddScriptFile() {
151 $op = $this->newInstance();
152 $op->addScriptFile( '/somescript.js' );
153 $op->addScriptFile( '//example.com/somescript.js' );
155 $this->assertContains(
156 "\n" . Html
::linkedScript( '/somescript.js', $op->getCSPNonce() ) .
157 Html
::linkedScript( '//example.com/somescript.js', $op->getCSPNonce() ) . "\n",
158 "\n" . $op->getBottomScripts() . "\n"
163 * Test that addScriptFile() throws due to deprecation.
165 * @covers OutputPage::addScriptFile
167 public function testAddDeprecatedScriptFileWarning() {
168 $this->setExpectedException( PHPUnit_Framework_Error_Deprecated
::class,
169 'Use of OutputPage::addScriptFile was deprecated in MediaWiki 1.24.' );
171 $op = $this->newInstance();
172 $op->addScriptFile( 'ignored-script.js' );
176 * Test the actual behavior of the method (in the case where it doesn't throw, e.g., in
179 * @covers OutputPage::addScriptFile
181 public function testAddDeprecatedScriptFileNoOp() {
182 $this->hideDeprecated( 'OutputPage::addScriptFile' );
183 $op = $this->newInstance();
184 $op->addScriptFile( 'ignored-script.js' );
186 $this->assertNotContains( 'ignored-script.js', '' . $op->getBottomScripts() );
190 * @covers OutputPage::addInlineScript
192 public function testAddInlineScript() {
193 $op = $this->newInstance();
194 $op->addInlineScript( 'let foo = "bar";' );
195 $op->addInlineScript( 'alert( foo );' );
197 $this->assertContains(
198 "\n" . Html
::inlineScript( "\nlet foo = \"bar\";\n", $op->getCSPNonce() ) . "\n" .
199 Html
::inlineScript( "\nalert( foo );\n", $op->getCSPNonce() ) . "\n",
200 "\n" . $op->getBottomScripts() . "\n"
204 // @todo How to test filterModules(), warnModuleTargetFilter(), getModules(), etc.?
207 * @covers OutputPage::getTarget
208 * @covers OutputPage::setTarget
210 public function testSetTarget() {
211 $op = $this->newInstance();
212 $op->setTarget( 'foo' );
214 $this->assertSame( 'foo', $op->getTarget() );
215 // @todo What else? Test some actual effect?
218 // @todo How to test addContentOverride(Callback)?
221 * @covers OutputPage::getHeadItemsArray
222 * @covers OutputPage::addHeadItem
223 * @covers OutputPage::addHeadItems
224 * @covers OutputPage::hasHeadItem
226 public function testHeadItems() {
227 $op = $this->newInstance();
228 $op->addHeadItem( 'a', 'b' );
229 $op->addHeadItems( [ 'c' => '<d>&', 'e' => 'f', 'a' => 'q' ] );
230 $op->addHeadItem( 'e', 'g' );
231 $op->addHeadItems( 'x' );
233 $this->assertSame( [ 'a' => 'q', 'c' => '<d>&', 'e' => 'g', 'x' ],
234 $op->getHeadItemsArray() );
236 $this->assertTrue( $op->hasHeadItem( 'a' ) );
237 $this->assertTrue( $op->hasHeadItem( 'c' ) );
238 $this->assertTrue( $op->hasHeadItem( 'e' ) );
239 $this->assertTrue( $op->hasHeadItem( '0' ) );
241 $this->assertContains( "\nq\n<d>&\ng\nx\n",
242 '' . $op->headElement( $op->getContext()->getSkin() ) );
246 * @covers OutputPage::getHeadItemsArray
247 * @covers OutputPage::addParserOutputMetadata
249 public function testHeadItemsParserOutput() {
250 $op = $this->newInstance();
251 $stubPO1 = $this->createParserOutputStub( 'getHeadItems', [ 'a' => 'b' ] );
252 $op->addParserOutputMetadata( $stubPO1 );
253 $stubPO2 = $this->createParserOutputStub( 'getHeadItems',
254 [ 'c' => '<d>&', 'e' => 'f', 'a' => 'q' ] );
255 $op->addParserOutputMetadata( $stubPO2 );
256 $stubPO3 = $this->createParserOutputStub( 'getHeadItems', [ 'e' => 'g' ] );
257 $op->addParserOutputMetadata( $stubPO3 );
258 $stubPO4 = $this->createParserOutputStub( 'getHeadItems', [ 'x' ] );
259 $op->addParserOutputMetadata( $stubPO4 );
261 $this->assertSame( [ 'a' => 'q', 'c' => '<d>&', 'e' => 'g', 'x' ],
262 $op->getHeadItemsArray() );
264 $this->assertTrue( $op->hasHeadItem( 'a' ) );
265 $this->assertTrue( $op->hasHeadItem( 'c' ) );
266 $this->assertTrue( $op->hasHeadItem( 'e' ) );
267 $this->assertTrue( $op->hasHeadItem( '0' ) );
268 $this->assertFalse( $op->hasHeadItem( 'b' ) );
270 $this->assertContains( "\nq\n<d>&\ng\nx\n",
271 '' . $op->headElement( $op->getContext()->getSkin() ) );
275 * @covers OutputPage::addBodyClasses
277 public function testAddBodyClasses() {
278 $op = $this->newInstance();
279 $op->addBodyClasses( 'a' );
280 $op->addBodyClasses( 'mediawiki' );
281 $op->addBodyClasses( 'b c' );
282 $op->addBodyClasses( [ 'd', 'e' ] );
283 $op->addBodyClasses( 'a' );
285 $this->assertContains( '"a mediawiki b c d e ltr',
286 '' . $op->headElement( $op->getContext()->getSkin() ) );
290 * @covers OutputPage::setArticleBodyOnly
291 * @covers OutputPage::getArticleBodyOnly
293 public function testArticleBodyOnly() {
294 $op = $this->newInstance();
295 $this->assertFalse( $op->getArticleBodyOnly() );
297 $op->setArticleBodyOnly( true );
298 $this->assertTrue( $op->getArticleBodyOnly() );
300 $op->addHTML( '<b>a</b>' );
302 $this->assertSame( '<b>a</b>', $op->output( true ) );
306 * @covers OutputPage::setProperty
307 * @covers OutputPage::getProperty
309 public function testProperties() {
310 $op = $this->newInstance();
312 $this->assertNull( $op->getProperty( 'foo' ) );
314 $op->setProperty( 'foo', 'bar' );
315 $op->setProperty( 'baz', 'quz' );
317 $this->assertSame( 'bar', $op->getProperty( 'foo' ) );
318 $this->assertSame( 'quz', $op->getProperty( 'baz' ) );
322 * @dataProvider provideCheckLastModified
324 * @covers OutputPage::checkLastModified
325 * @covers OutputPage::getCdnCacheEpoch
327 public function testCheckLastModified(
328 $timestamp, $ifModifiedSince, $expected, $config = [], $callback = null
330 $request = new FauxRequest();
331 if ( $ifModifiedSince ) {
332 if ( is_numeric( $ifModifiedSince ) ) {
334 $ifModifiedSince = date( 'D, d M Y H:i:s', $ifModifiedSince ) . ' GMT';
336 $request->setHeader( 'If-Modified-Since', $ifModifiedSince );
339 if ( !isset( $config['CacheEpoch'] ) ) {
340 // Make sure it's not too recent
341 $config['CacheEpoch'] = '20000101000000';
344 $op = $this->newInstance( $config, $request );
347 $callback( $op, $this );
350 // Avoid a complaint about not being able to disable compression
351 Wikimedia\
suppressWarnings();
353 $this->assertEquals( $expected, $op->checkLastModified( $timestamp ) );
355 Wikimedia\restoreWarnings
();
359 public function provideCheckLastModified() {
360 $lastModified = time() - 3600;
363 [ '0', $lastModified, false ],
364 'Timestamp Unix epoch' =>
365 [ '19700101000000', $lastModified, false ],
366 'Timestamp same as If-Modified-Since' =>
367 [ $lastModified, $lastModified, true ],
368 'Timestamp one second after If-Modified-Since' =>
369 [ $lastModified +
1, $lastModified, false ],
370 'No If-Modified-Since' =>
371 [ $lastModified +
1, null, false ],
372 'Malformed If-Modified-Since' =>
373 [ $lastModified +
1, 'GIBBERING WOMBATS !!!', false ],
374 'Non-standard IE-style If-Modified-Since' =>
375 [ $lastModified, date( 'D, d M Y H:i:s', $lastModified ) . ' GMT; length=5202',
377 // @todo Should we fix this behavior to match the spec? Probably no reason to.
378 'If-Modified-Since not per spec but we accept it anyway because strtotime does' =>
379 [ $lastModified, "@$lastModified", true ],
380 '$wgCachePages = false' =>
381 [ $lastModified, $lastModified, false, [ 'CachePages' => false ] ],
383 [ $lastModified, $lastModified, false,
384 [ 'CacheEpoch' => wfTimestamp( TS_MW
, $lastModified +
1 ) ] ],
385 'Recently-touched user' =>
386 [ $lastModified, $lastModified, false, [],
388 $op->getContext()->setUser( $this->getTestUser()->getUser() );
390 'After Squid expiry' =>
391 [ $lastModified, $lastModified, false,
392 [ 'UseSquid' => true, 'SquidMaxage' => 3599 ] ],
393 'Hook allows cache use' =>
394 [ $lastModified +
1, $lastModified, true, [],
395 function ( $op, $that ) {
396 $that->setTemporaryHook( 'OutputPageCheckLastModified',
397 function ( &$modifiedTimes ) {
398 $modifiedTimes = [ 1 ];
402 'Hooks prohibits cache use' =>
403 [ $lastModified, $lastModified, false, [],
404 function ( $op, $that ) {
405 $that->setTemporaryHook( 'OutputPageCheckLastModified',
406 function ( &$modifiedTimes ) {
407 $modifiedTimes = [ max( $modifiedTimes ) +
1 ];
415 * @dataProvider provideCdnCacheEpoch
417 * @covers OutputPage::getCdnCacheEpoch
419 public function testCdnCacheEpoch( $params ) {
420 $out = TestingAccessWrapper
::newFromObject( $this->newInstance() );
421 $reqTime = strtotime( $params['reqTime'] );
422 $pageTime = strtotime( $params['pageTime'] );
423 $actual = max( $pageTime, $out->getCdnCacheEpoch( $reqTime, $params['maxAge'] ) );
427 gmdate( DateTime
::ATOM
, $actual ),
432 public static function provideCdnCacheEpoch() {
434 'pageTime' => '2011-04-01T12:00:00+00:00',
435 'maxAge' => 24 * 3600,
438 'after 1s' => [ $base +
[
439 'reqTime' => '2011-04-01T12:00:01+00:00',
440 'expect' => '2011-04-01T12:00:00+00:00',
442 'after 23h' => [ $base +
[
443 'reqTime' => '2011-04-02T11:00:00+00:00',
444 'expect' => '2011-04-01T12:00:00+00:00',
446 'after 24h and a bit' => [ $base +
[
447 'reqTime' => '2011-04-02T12:34:56+00:00',
448 'expect' => '2011-04-01T12:34:56+00:00',
450 'after a year' => [ $base +
[
451 'reqTime' => '2012-05-06T00:12:07+00:00',
452 'expect' => '2012-05-05T00:12:07+00:00',
457 // @todo How to test setLastModified?
460 * @covers OutputPage::setRobotPolicy
461 * @covers OutputPage::getHeadLinksArray
463 public function testSetRobotPolicy() {
464 $op = $this->newInstance();
465 $op->setRobotPolicy( 'noindex, nofollow' );
467 $links = $op->getHeadLinksArray();
468 $this->assertContains( '<meta name="robots" content="noindex,nofollow"/>', $links );
472 * @covers OutputPage::setIndexPolicy
473 * @covers OutputPage::setFollowPolicy
474 * @covers OutputPage::getHeadLinksArray
476 public function testSetIndexFollowPolicies() {
477 $op = $this->newInstance();
478 $op->setIndexPolicy( 'noindex' );
479 $op->setFollowPolicy( 'nofollow' );
481 $links = $op->getHeadLinksArray();
482 $this->assertContains( '<meta name="robots" content="noindex,nofollow"/>', $links );
485 private function extractHTMLTitle( OutputPage
$op ) {
486 $html = $op->headElement( $op->getContext()->getSkin() );
488 // OutputPage should always output the title in a nice format such that regexes will work
489 // fine. If it doesn't, we'll fail the tests.
490 preg_match_all( '!<title>(.*?)</title>!', $html, $matches );
492 $this->assertLessThanOrEqual( 1, count( $matches[1] ), 'More than one <title>!' );
494 if ( !count( $matches[1] ) ) {
498 return $matches[1][0];
502 * Shorthand for getting the text of a message, in content language.
504 private static function getMsgText( $op, ...$msgParams ) {
505 return $op->msg( ...$msgParams )->inContentLanguage()->text();
509 * @covers OutputPage::setHTMLTitle
510 * @covers OutputPage::getHTMLTitle
512 public function testHTMLTitle() {
513 $op = $this->newInstance();
516 $this->assertSame( '', $op->getHTMLTitle() );
517 $this->assertSame( '', $op->getPageTitle() );
519 $this->getMsgText( $op, 'pagetitle', '' ),
520 $this->extractHTMLTitle( $op )
524 $op->setHTMLTitle( 'Potatoes will eat me' );
526 $this->assertSame( 'Potatoes will eat me', $op->getHTMLTitle() );
527 $this->assertSame( 'Potatoes will eat me', $this->extractHTMLTitle( $op ) );
528 // Shouldn't have changed the page title
529 $this->assertSame( '', $op->getPageTitle() );
532 $msg = $op->msg( 'mainpage' );
534 $op->setHTMLTitle( $msg );
535 $this->assertSame( $msg->text(), $op->getHTMLTitle() );
536 $this->assertSame( $msg->text(), $this->extractHTMLTitle( $op ) );
537 $this->assertSame( '', $op->getPageTitle() );
541 * @covers OutputPage::setRedirectedFrom
543 public function testSetRedirectedFrom() {
544 $op = $this->newInstance();
546 $op->setRedirectedFrom( Title
::newFromText( 'Talk:Some page' ) );
547 $this->assertSame( 'Talk:Some_page', $op->getJSVars()['wgRedirectedFrom'] );
551 * @covers OutputPage::setPageTitle
552 * @covers OutputPage::getPageTitle
554 public function testPageTitle() {
555 // We don't test the actual HTML output anywhere, because that's up to the skin.
556 $op = $this->newInstance();
559 $this->assertSame( '', $op->getPageTitle() );
560 $this->assertSame( '', $op->getHTMLTitle() );
562 // Test set to plain text
563 $op->setPageTitle( 'foobar' );
565 $this->assertSame( 'foobar', $op->getPageTitle() );
566 // HTML title should change as well
567 $this->assertSame( $this->getMsgText( $op, 'pagetitle', 'foobar' ), $op->getHTMLTitle() );
569 // Test set to text with good and bad HTML. We don't try to be comprehensive here, that
570 // belongs in Sanitizer tests.
571 $op->setPageTitle( '<script>a</script>&<i>b</i>' );
573 $this->assertSame( '<script>a</script>&<i>b</i>', $op->getPageTitle() );
575 $this->getMsgText( $op, 'pagetitle', '<script>a</script>&b' ),
579 // Test set to message
580 $text = $this->getMsgText( $op, 'mainpage' );
582 $op->setPageTitle( $op->msg( 'mainpage' )->inContentLanguage() );
583 $this->assertSame( $text, $op->getPageTitle() );
584 $this->assertSame( $this->getMsgText( $op, 'pagetitle', $text ), $op->getHTMLTitle() );
588 * @covers OutputPage::setTitle
590 public function testSetTitle() {
591 $op = $this->newInstance();
593 $this->assertSame( 'My test page', $op->getTitle()->getPrefixedText() );
595 $op->setTitle( Title
::newFromText( 'Another test page' ) );
597 $this->assertSame( 'Another test page', $op->getTitle()->getPrefixedText() );
601 * @covers OutputPage::setSubtitle
602 * @covers OutputPage::clearSubtitle
603 * @covers OutputPage::addSubtitle
604 * @covers OutputPage::getSubtitle
606 public function testSubtitle() {
607 $op = $this->newInstance();
609 $this->assertSame( '', $op->getSubtitle() );
611 $op->addSubtitle( '<b>foo</b>' );
613 $this->assertSame( '<b>foo</b>', $op->getSubtitle() );
615 $op->addSubtitle( $op->msg( 'mainpage' )->inContentLanguage() );
618 "<b>foo</b><br />\n\t\t\t\t" . $this->getMsgText( $op, 'mainpage' ),
622 $op->setSubtitle( 'There can be only one' );
624 $this->assertSame( 'There can be only one', $op->getSubtitle() );
626 $op->clearSubtitle();
628 $this->assertSame( '', $op->getSubtitle() );
632 * @dataProvider provideBacklinkSubtitle
634 * @covers OutputPage::buildBacklinkSubtitle
636 public function testBuildBacklinkSubtitle( $titles, $queries, $contains, $notContains ) {
637 if ( count( $titles ) > 1 ) {
639 $this->assertTrue( true );
643 $title = Title
::newFromText( $titles[0] );
644 $query = $queries[0];
646 $this->editPage( 'Page 1', '' );
647 $this->editPage( 'Page 2', '#REDIRECT [[Page 1]]' );
649 $str = OutputPage
::buildBacklinkSubtitle( $title, $query )->text();
651 foreach ( $contains as $substr ) {
652 $this->assertContains( $substr, $str );
655 foreach ( $notContains as $substr ) {
656 $this->assertNotContains( $substr, $str );
661 * @dataProvider provideBacklinkSubtitle
663 * @covers OutputPage::addBacklinkSubtitle
664 * @covers OutputPage::getSubtitle
666 public function testAddBacklinkSubtitle( $titles, $queries, $contains, $notContains ) {
667 $this->editPage( 'Page 1', '' );
668 $this->editPage( 'Page 2', '#REDIRECT [[Page 1]]' );
670 $op = $this->newInstance();
671 foreach ( $titles as $i => $unused ) {
672 $op->addBacklinkSubtitle( Title
::newFromText( $titles[$i] ), $queries[$i] );
675 $str = $op->getSubtitle();
677 foreach ( $contains as $substr ) {
678 $this->assertContains( $substr, $str );
681 foreach ( $notContains as $substr ) {
682 $this->assertNotContains( $substr, $str );
686 public function provideBacklinkSubtitle() {
692 [ 'redirect', 'Page 2' ],
702 [ [ 'action' => 'edit' ] ],
707 [ 'Page 1', 'Page 2' ],
709 [ 'Page 1', 'Page 2', "<br />\n\t\t\t\t" ],
712 // @todo Anything else to test?
717 * @covers OutputPage::setPrintable
718 * @covers OutputPage::isPrintable
720 public function testPrintable() {
721 $op = $this->newInstance();
723 $this->assertFalse( $op->isPrintable() );
727 $this->assertTrue( $op->isPrintable() );
731 * @covers OutputPage::disable
732 * @covers OutputPage::isDisabled
734 public function testDisable() {
735 $op = $this->newInstance();
737 $this->assertFalse( $op->isDisabled() );
738 $this->assertNotSame( '', $op->output( true ) );
742 $this->assertTrue( $op->isDisabled() );
743 $this->assertSame( '', $op->output( true ) );
747 * @covers OutputPage::showNewSectionLink
748 * @covers OutputPage::addParserOutputMetadata
750 public function testShowNewSectionLink() {
751 $op = $this->newInstance();
753 $this->assertFalse( $op->showNewSectionLink() );
755 $po = new ParserOutput();
756 $po->setNewSection( true );
757 $op->addParserOutputMetadata( $po );
759 $this->assertTrue( $op->showNewSectionLink() );
763 * @covers OutputPage::forceHideNewSectionLink
764 * @covers OutputPage::addParserOutputMetadata
766 public function testForceHideNewSectionLink() {
767 $op = $this->newInstance();
769 $this->assertFalse( $op->forceHideNewSectionLink() );
771 $po = new ParserOutput();
772 $po->hideNewSection( true );
773 $op->addParserOutputMetadata( $po );
775 $this->assertTrue( $op->forceHideNewSectionLink() );
779 * @covers OutputPage::setSyndicated
780 * @covers OutputPage::isSyndicated
782 public function testSetSyndicated() {
783 $op = $this->newInstance();
784 $this->assertFalse( $op->isSyndicated() );
786 $op->setSyndicated();
787 $this->assertTrue( $op->isSyndicated() );
789 $op->setSyndicated( false );
790 $this->assertFalse( $op->isSyndicated() );
794 * @covers OutputPage::isSyndicated
795 * @covers OutputPage::setFeedAppendQuery
796 * @covers OutputPage::addFeedLink
797 * @covers OutputPage::getSyndicationLinks()
799 public function testFeedLinks() {
800 $op = $this->newInstance();
801 $this->assertSame( [], $op->getSyndicationLinks() );
803 $op->addFeedLink( 'not a supported format', 'abc' );
804 $this->assertFalse( $op->isSyndicated() );
805 $this->assertSame( [], $op->getSyndicationLinks() );
807 $feedTypes = $op->getConfig()->get( 'AdvertisedFeedTypes' );
809 $op->addFeedLink( $feedTypes[0], 'def' );
810 $this->assertTrue( $op->isSyndicated() );
811 $this->assertSame( [ $feedTypes[0] => 'def' ], $op->getSyndicationLinks() );
813 $op->setFeedAppendQuery( false );
815 foreach ( $feedTypes as $type ) {
816 $expected[$type] = $op->getTitle()->getLocalURL( "feed=$type" );
818 $this->assertSame( $expected, $op->getSyndicationLinks() );
820 $op->setFeedAppendQuery( 'apples=oranges' );
821 foreach ( $feedTypes as $type ) {
822 $expected[$type] = $op->getTitle()->getLocalURL( "feed=$type&apples=oranges" );
824 $this->assertSame( $expected, $op->getSyndicationLinks() );
828 * @covers OutputPage::setArticleFlag
829 * @covers OutputPage::isArticle
830 * @covers OutputPage::setArticleRelated
831 * @covers OutputPage::isArticleRelated
833 function testArticleFlags() {
834 $op = $this->newInstance();
835 $this->assertFalse( $op->isArticle() );
836 $this->assertTrue( $op->isArticleRelated() );
838 $op->setArticleRelated( false );
839 $this->assertFalse( $op->isArticle() );
840 $this->assertFalse( $op->isArticleRelated() );
842 $op->setArticleFlag( true );
843 $this->assertTrue( $op->isArticle() );
844 $this->assertTrue( $op->isArticleRelated() );
846 $op->setArticleFlag( false );
847 $this->assertFalse( $op->isArticle() );
848 $this->assertTrue( $op->isArticleRelated() );
850 $op->setArticleFlag( true );
851 $op->setArticleRelated( false );
852 $this->assertFalse( $op->isArticle() );
853 $this->assertFalse( $op->isArticleRelated() );
857 * @covers OutputPage::addLanguageLinks
858 * @covers OutputPage::setLanguageLinks
859 * @covers OutputPage::getLanguageLinks
860 * @covers OutputPage::addParserOutputMetadata
862 function testLanguageLinks() {
863 $op = $this->newInstance();
864 $this->assertSame( [], $op->getLanguageLinks() );
866 $op->addLanguageLinks( [ 'fr:A', 'it:B' ] );
867 $this->assertSame( [ 'fr:A', 'it:B' ], $op->getLanguageLinks() );
869 $op->addLanguageLinks( [ 'de:C', 'es:D' ] );
870 $this->assertSame( [ 'fr:A', 'it:B', 'de:C', 'es:D' ], $op->getLanguageLinks() );
872 $op->setLanguageLinks( [ 'pt:E' ] );
873 $this->assertSame( [ 'pt:E' ], $op->getLanguageLinks() );
875 $po = new ParserOutput();
876 $po->setLanguageLinks( [ 'he:F', 'ar:G' ] );
877 $op->addParserOutputMetadata( $po );
878 $this->assertSame( [ 'pt:E', 'he:F', 'ar:G' ], $op->getLanguageLinks() );
881 // @todo Are these category links tests too abstract and complicated for what they test? Would
882 // it make sense to just write out all the tests by hand with maybe some copy-and-paste?
885 * @dataProvider provideGetCategories
887 * @covers OutputPage::addCategoryLinks
888 * @covers OutputPage::getCategories
889 * @covers OutputPage::getCategoryLinks
891 * @param array $args Array of form [ category name => sort key ]
892 * @param array $fakeResults Array of form [ category name => value to return from mocked
894 * @param callback $variantLinkCallback Callback to replace findVariantLink() call
895 * @param array $expectedNormal Expected return value of getCategoryLinks['normal']
896 * @param array $expectedHidden Expected return value of getCategoryLinks['hidden']
898 public function testAddCategoryLinks(
899 array $args, array $fakeResults, callable
$variantLinkCallback = null,
900 array $expectedNormal, array $expectedHidden
902 $expectedNormal = $this->extractExpectedCategories( $expectedNormal, 'add' );
903 $expectedHidden = $this->extractExpectedCategories( $expectedHidden, 'add' );
905 $op = $this->setupCategoryTests( $fakeResults, $variantLinkCallback );
907 $op->addCategoryLinks( $args );
909 $this->doCategoryAsserts( $op, $expectedNormal, $expectedHidden );
910 $this->doCategoryLinkAsserts( $op, $expectedNormal, $expectedHidden );
914 * @dataProvider provideGetCategories
916 * @covers OutputPage::addCategoryLinks
917 * @covers OutputPage::getCategories
918 * @covers OutputPage::getCategoryLinks
920 public function testAddCategoryLinksOneByOne(
921 array $args, array $fakeResults, callable
$variantLinkCallback = null,
922 array $expectedNormal, array $expectedHidden
924 if ( count( $args ) <= 1 ) {
925 // @todo Should this be skipped instead of passed?
926 $this->assertTrue( true );
930 $expectedNormal = $this->extractExpectedCategories( $expectedNormal, 'onebyone' );
931 $expectedHidden = $this->extractExpectedCategories( $expectedHidden, 'onebyone' );
933 $op = $this->setupCategoryTests( $fakeResults, $variantLinkCallback );
935 foreach ( $args as $key => $val ) {
936 $op->addCategoryLinks( [ $key => $val ] );
939 $this->doCategoryAsserts( $op, $expectedNormal, $expectedHidden );
940 $this->doCategoryLinkAsserts( $op, $expectedNormal, $expectedHidden );
944 * @dataProvider provideGetCategories
946 * @covers OutputPage::setCategoryLinks
947 * @covers OutputPage::getCategories
948 * @covers OutputPage::getCategoryLinks
950 public function testSetCategoryLinks(
951 array $args, array $fakeResults, callable
$variantLinkCallback = null,
952 array $expectedNormal, array $expectedHidden
954 $expectedNormal = $this->extractExpectedCategories( $expectedNormal, 'set' );
955 $expectedHidden = $this->extractExpectedCategories( $expectedHidden, 'set' );
957 $op = $this->setupCategoryTests( $fakeResults, $variantLinkCallback );
959 $op->setCategoryLinks( [ 'Initial page' => 'Initial page' ] );
960 $op->setCategoryLinks( $args );
962 // We don't reset the categories, for some reason, only the links
963 $expectedNormalCats = array_merge( [ 'Initial page' ], $expectedNormal );
964 $expectedCats = array_merge( $expectedHidden, $expectedNormalCats );
966 $this->doCategoryAsserts( $op, $expectedNormalCats, $expectedHidden );
967 $this->doCategoryLinkAsserts( $op, $expectedNormal, $expectedHidden );
971 * @dataProvider provideGetCategories
973 * @covers OutputPage::addParserOutputMetadata
974 * @covers OutputPage::getCategories
975 * @covers OutputPage::getCategoryLinks
977 public function testParserOutputCategoryLinks(
978 array $args, array $fakeResults, callable
$variantLinkCallback = null,
979 array $expectedNormal, array $expectedHidden
981 $expectedNormal = $this->extractExpectedCategories( $expectedNormal, 'pout' );
982 $expectedHidden = $this->extractExpectedCategories( $expectedHidden, 'pout' );
984 $op = $this->setupCategoryTests( $fakeResults, $variantLinkCallback );
986 $stubPO = $this->createParserOutputStub( 'getCategories', $args );
988 $op->addParserOutputMetadata( $stubPO );
990 $this->doCategoryAsserts( $op, $expectedNormal, $expectedHidden );
991 $this->doCategoryLinkAsserts( $op, $expectedNormal, $expectedHidden );
995 * We allow different expectations for different tests as an associative array, like
996 * [ 'set' => [ ... ], 'default' => [ ... ] ] if setCategoryLinks() will give a different
999 private function extractExpectedCategories( array $expected, $key ) {
1000 if ( !$expected ||
isset( $expected[0] ) ) {
1003 return $expected[$key] ??
$expected['default'];
1006 private function setupCategoryTests(
1007 array $fakeResults, callable
$variantLinkCallback = null
1009 $this->setMwGlobals( 'wgUsePigLatinVariant', true );
1011 $op = $this->getMockBuilder( OutputPage
::class )
1012 ->setConstructorArgs( [ new RequestContext() ] )
1013 ->setMethods( [ 'addCategoryLinksToLBAndGetResult' ] )
1016 $op->expects( $this->any() )
1017 ->method( 'addCategoryLinksToLBAndGetResult' )
1018 ->will( $this->returnCallback( function ( array $categories ) use ( $fakeResults ) {
1020 foreach ( $categories as $category => $unused ) {
1021 if ( isset( $fakeResults[$category] ) ) {
1022 $return[] = $fakeResults[$category];
1025 return new FakeResultWrapper( $return );
1028 if ( $variantLinkCallback ) {
1029 $mockContLang = $this->getMockBuilder( Language
::class )
1030 ->setConstructorArgs( [ 'en' ] )
1031 ->setMethods( [ 'findVariantLink' ] )
1033 $mockContLang->expects( $this->any() )
1034 ->method( 'findVariantLink' )
1035 ->will( $this->returnCallback( $variantLinkCallback ) );
1036 $this->setContentLang( $mockContLang );
1039 $this->assertSame( [], $op->getCategories() );
1044 private function doCategoryAsserts( $op, $expectedNormal, $expectedHidden ) {
1045 $this->assertSame( array_merge( $expectedHidden, $expectedNormal ), $op->getCategories() );
1046 $this->assertSame( $expectedNormal, $op->getCategories( 'normal' ) );
1047 $this->assertSame( $expectedHidden, $op->getCategories( 'hidden' ) );
1050 private function doCategoryLinkAsserts( $op, $expectedNormal, $expectedHidden ) {
1051 $catLinks = $op->getCategoryLinks();
1052 $this->assertSame( (bool)$expectedNormal +
(bool)$expectedHidden, count( $catLinks ) );
1053 if ( $expectedNormal ) {
1054 $this->assertSame( count( $expectedNormal ), count( $catLinks['normal'] ) );
1056 if ( $expectedHidden ) {
1057 $this->assertSame( count( $expectedHidden ), count( $catLinks['hidden'] ) );
1060 foreach ( $expectedNormal as $i => $name ) {
1061 $this->assertContains( $name, $catLinks['normal'][$i] );
1063 foreach ( $expectedHidden as $i => $name ) {
1064 $this->assertContains( $name, $catLinks['hidden'][$i] );
1068 public function provideGetCategories() {
1070 'No categories' => [ [], [], null, [], [] ],
1072 [ 'Test1' => 'Some sortkey', 'Test2' => 'A different sortkey' ],
1073 [ 'Test1' => (object)[ 'pp_value' => 1, 'page_title' => 'Test1' ],
1074 'Test2' => (object)[ 'page_title' => 'Test2' ] ],
1079 'Invalid title' => [
1080 [ '[' => '[', 'Test' => 'Test' ],
1081 [ 'Test' => (object)[ 'page_title' => 'Test' ] ],
1087 [ 'Test' => 'Test', 'Estay' => 'Estay' ],
1088 [ 'Test' => (object)[ 'page_title' => 'Test' ] ],
1089 function ( &$link, &$title ) {
1090 if ( $link === 'Estay' ) {
1092 $title = Title
::makeTitleSafe( NS_CATEGORY
, $link );
1095 // For adding one by one, the variant gets added as well as the original category,
1096 // but if you add them all together the second time gets skipped.
1097 [ 'onebyone' => [ 'Test', 'Test' ], 'default' => [ 'Test' ] ],
1104 * @covers OutputPage::getCategories
1106 public function testGetCategoriesInvalid() {
1107 $this->setExpectedException( InvalidArgumentException
::class,
1108 'Invalid category type given: hiddne' );
1110 $op = $this->newInstance();
1111 $op->getCategories( 'hiddne' );
1114 // @todo Should we test addCategoryLinksToLBAndGetResult? If so, how? Insert some test rows in
1118 * @covers OutputPage::setIndicators
1119 * @covers OutputPage::getIndicators
1120 * @covers OutputPage::addParserOutputMetadata
1122 public function testIndicators() {
1123 $op = $this->newInstance();
1124 $this->assertSame( [], $op->getIndicators() );
1126 $op->setIndicators( [] );
1127 $this->assertSame( [], $op->getIndicators() );
1129 // Test sorting alphabetically
1130 $op->setIndicators( [ 'b' => 'x', 'a' => 'y' ] );
1131 $this->assertSame( [ 'a' => 'y', 'b' => 'x' ], $op->getIndicators() );
1133 // Test overwriting existing keys
1134 $op->setIndicators( [ 'c' => 'z', 'a' => 'w' ] );
1135 $this->assertSame( [ 'a' => 'w', 'b' => 'x', 'c' => 'z' ], $op->getIndicators() );
1137 // Test with ParserOutput
1138 $stubPO = $this->createParserOutputStub( 'getIndicators', [ 'c' => 'u', 'd' => 'v' ] );
1139 $op->addParserOutputMetadata( $stubPO );
1140 $this->assertSame( [ 'a' => 'w', 'b' => 'x', 'c' => 'u', 'd' => 'v' ],
1141 $op->getIndicators() );
1145 * @covers OutputPage::addHelpLink
1146 * @covers OutputPage::getIndicators
1148 public function testAddHelpLink() {
1149 $op = $this->newInstance();
1151 $op->addHelpLink( 'Manual:PHP unit testing' );
1152 $indicators = $op->getIndicators();
1153 $this->assertSame( [ 'mw-helplink' ], array_keys( $indicators ) );
1154 $this->assertContains( 'Manual:PHP_unit_testing', $indicators['mw-helplink'] );
1156 $op->addHelpLink( 'https://phpunit.de', true );
1157 $indicators = $op->getIndicators();
1158 $this->assertSame( [ 'mw-helplink' ], array_keys( $indicators ) );
1159 $this->assertContains( 'https://phpunit.de', $indicators['mw-helplink'] );
1160 $this->assertNotContains( 'mediawiki', $indicators['mw-helplink'] );
1161 $this->assertNotContains( 'Manual:PHP', $indicators['mw-helplink'] );
1165 * @covers OutputPage::prependHTML
1166 * @covers OutputPage::addHTML
1167 * @covers OutputPage::addElement
1168 * @covers OutputPage::clearHTML
1169 * @covers OutputPage::getHTML
1171 public function testBodyHTML() {
1172 $op = $this->newInstance();
1173 $this->assertSame( '', $op->getHTML() );
1175 $op->addHTML( 'a' );
1176 $this->assertSame( 'a', $op->getHTML() );
1178 $op->addHTML( 'b' );
1179 $this->assertSame( 'ab', $op->getHTML() );
1181 $op->prependHTML( 'c' );
1182 $this->assertSame( 'cab', $op->getHTML() );
1184 $op->addElement( 'p', [ 'id' => 'foo' ], 'd' );
1185 $this->assertSame( 'cab<p id="foo">d</p>', $op->getHTML() );
1188 $this->assertSame( '', $op->getHTML() );
1192 * @dataProvider provideRevisionId
1193 * @covers OutputPage::setRevisionId
1194 * @covers OutputPage::getRevisionId
1196 public function testRevisionId( $newVal, $expected ) {
1197 $op = $this->newInstance();
1199 $this->assertNull( $op->setRevisionId( $newVal ) );
1200 $this->assertSame( $expected, $op->getRevisionId() );
1201 $this->assertSame( $expected, $op->setRevisionId( null ) );
1202 $this->assertNull( $op->getRevisionId() );
1205 public function provideRevisionId() {
1212 [ '32% finished', 32 ],
1218 * @covers OutputPage::setRevisionTimestamp
1219 * @covers OutputPage::getRevisionTimestamp
1221 public function testRevisionTimestamp() {
1222 $op = $this->newInstance();
1223 $this->assertNull( $op->getRevisionTimestamp() );
1225 $this->assertNull( $op->setRevisionTimestamp( 'abc' ) );
1226 $this->assertSame( 'abc', $op->getRevisionTimestamp() );
1227 $this->assertSame( 'abc', $op->setRevisionTimestamp( null ) );
1228 $this->assertNull( $op->getRevisionTimestamp() );
1232 * @covers OutputPage::setFileVersion
1233 * @covers OutputPage::getFileVersion
1235 public function testFileVersion() {
1236 $op = $this->newInstance();
1237 $this->assertNull( $op->getFileVersion() );
1239 $stubFile = $this->createMock( File
::class );
1240 $stubFile->method( 'exists' )->willReturn( true );
1241 $stubFile->method( 'getTimestamp' )->willReturn( '12211221123321' );
1242 $stubFile->method( 'getSha1' )->willReturn( 'bf3ffa7047dc080f5855377a4f83cd18887e3b05' );
1244 $op->setFileVersion( $stubFile );
1246 $this->assertEquals(
1247 [ 'time' => '12211221123321', 'sha1' => 'bf3ffa7047dc080f5855377a4f83cd18887e3b05' ],
1248 $op->getFileVersion()
1251 $stubMissingFile = $this->createMock( File
::class );
1252 $stubMissingFile->method( 'exists' )->willReturn( false );
1254 $op->setFileVersion( $stubMissingFile );
1255 $this->assertNull( $op->getFileVersion() );
1257 $op->setFileVersion( $stubFile );
1258 $this->assertNotNull( $op->getFileVersion() );
1260 $op->setFileVersion( null );
1261 $this->assertNull( $op->getFileVersion() );
1264 private function createParserOutputStub( $method = '', $retVal = [] ) {
1265 $pOut = $this->getMock( ParserOutput
::class );
1266 if ( $method !== '' ) {
1267 $pOut->method( $method )->willReturn( $retVal );
1270 $arrayReturningMethods = [
1272 'getFileSearchOptions',
1280 foreach ( $arrayReturningMethods as $method ) {
1281 $pOut->method( $method )->willReturn( [] );
1288 * @covers OutputPage::getTemplateIds
1289 * @covers OutputPage::addParserOutputMetadata
1291 public function testTemplateIds() {
1292 $op = $this->newInstance();
1293 $this->assertSame( [], $op->getTemplateIds() );
1295 // Test with no template id's
1296 $stubPOEmpty = $this->createParserOutputStub();
1297 $op->addParserOutputMetadata( $stubPOEmpty );
1298 $this->assertSame( [], $op->getTemplateIds() );
1300 // Test with some arbitrary template id's
1302 NS_MAIN
=> [ 'A' => 3, 'B' => 17 ],
1303 NS_TALK
=> [ 'C' => 31 ],
1304 NS_MEDIA
=> [ 'D' => -1 ],
1307 $stubPO1 = $this->createParserOutputStub( 'getTemplateIds', $ids );
1309 $op->addParserOutputMetadata( $stubPO1 );
1310 $this->assertSame( $ids, $op->getTemplateIds() );
1312 // Test merging with a second set of id's
1313 $stubPO2 = $this->createParserOutputStub( 'getTemplateIds', [
1314 NS_MAIN
=> [ 'E' => 1234 ],
1315 NS_PROJECT
=> [ 'F' => 5678 ],
1319 NS_MAIN
=> [ 'E' => 1234, 'A' => 3, 'B' => 17 ],
1320 NS_TALK
=> [ 'C' => 31 ],
1321 NS_MEDIA
=> [ 'D' => -1 ],
1322 NS_PROJECT
=> [ 'F' => 5678 ],
1325 $op->addParserOutputMetadata( $stubPO2 );
1326 $this->assertSame( $finalIds, $op->getTemplateIds() );
1328 // Test merging with an empty set of id's
1329 $op->addParserOutputMetadata( $stubPOEmpty );
1330 $this->assertSame( $finalIds, $op->getTemplateIds() );
1334 * @covers OutputPage::getFileSearchOptions
1335 * @covers OutputPage::addParserOutputMetadata
1337 public function testFileSearchOptions() {
1338 $op = $this->newInstance();
1339 $this->assertSame( [], $op->getFileSearchOptions() );
1341 // Test with no files
1342 $stubPOEmpty = $this->createParserOutputStub();
1344 $op->addParserOutputMetadata( $stubPOEmpty );
1345 $this->assertSame( [], $op->getFileSearchOptions() );
1347 // Test with some arbitrary files
1349 'A' => [ 'time' => null, 'sha1' => '' ],
1351 'time' => '12211221123321',
1352 'sha1' => 'bf3ffa7047dc080f5855377a4f83cd18887e3b05',
1356 $stubPO1 = $this->createParserOutputStub( 'getFileSearchOptions', $files1 );
1358 $op->addParserOutputMetadata( $stubPO1 );
1359 $this->assertSame( $files1, $op->getFileSearchOptions() );
1361 // Test merging with a second set of files
1363 'C' => [ 'time' => null, 'sha1' => '' ],
1364 'B' => [ 'time' => null, 'sha1' => '' ],
1367 $stubPO2 = $this->createParserOutputStub( 'getFileSearchOptions', $files2 );
1369 $op->addParserOutputMetadata( $stubPO2 );
1370 $this->assertSame( array_merge( $files1, $files2 ), $op->getFileSearchOptions() );
1372 // Test merging with an empty set of files
1373 $op->addParserOutputMetadata( $stubPOEmpty );
1374 $this->assertSame( array_merge( $files1, $files2 ), $op->getFileSearchOptions() );
1378 * @dataProvider provideAddWikiText
1379 * @covers OutputPage::addWikiText
1380 * @covers OutputPage::addWikiTextWithTitle
1381 * @covers OutputPage::addWikiTextTitle
1382 * @covers OutputPage::addWikiTextTidy
1383 * @covers OutputPage::addWikiTextTitleTidy
1384 * @covers OutputPage::getHTML
1386 public function testAddWikiText( $method, array $args, $expected ) {
1387 $op = $this->newInstance();
1388 $this->assertSame( '', $op->getHTML() );
1392 [ 'addWikiTextWithTitle', 'addWikiTextTitleTidy', 'addWikiTextTitle' ]
1393 ) && count( $args ) >= 2 && $args[1] === null ) {
1394 // Special placeholder because we can't get the actual title in the provider
1395 $args[1] = $op->getTitle();
1398 $op->$method( ...$args );
1399 $this->assertSame( $expected, $op->getHTML() );
1402 public function provideAddWikiText() {
1405 'Simple wikitext' => [
1407 "<p><b>Bold</b>\n</p>",
1408 ], 'List at start' => [
1410 "<ul><li>List</li></ul>\n",
1411 ], 'List not at start' => [
1412 [ '* Not a list', false ],
1414 ], 'Non-interface' => [
1415 [ "'''Bold'''", true, false ],
1416 "<p><b>Bold</b>\n</p>",
1417 ], 'No section edit links' => [
1419 "<h2><span class=\"mw-headline\" id=\"Title\">Title</span></h2>\n",
1422 'addWikiTextWithTitle' => [
1423 'With title at start' => [
1424 [ '* {{PAGENAME}}', Title
::newFromText( 'Talk:Some page' ) ],
1425 "<ul><li>Some page</li></ul>\n",
1426 ], 'With title at start' => [
1427 [ '* {{PAGENAME}}', Title
::newFromText( 'Talk:Some page' ), false ],
1431 'addWikiTextTidy' => [
1432 'SpecialNewimages' => [
1433 [ "<p lang='en' dir='ltr'>\nMy message" ],
1434 '<p lang="en" dir="ltr">' . "\nMy message\n</p>"
1435 ], 'List at start' => [
1437 "<ul><li>List</li></ul>\n",
1438 ], 'List not at start' => [
1439 [ '* <b>Not a list', false ],
1440 '<p>* <b>Not a list</b></p>',
1443 'addWikiTextTitleTidy' => [
1444 'With title at start' => [
1445 [ '* {{PAGENAME}}', Title
::newFromText( 'Talk:Some page' ) ],
1446 "<ul><li>Some page</li></ul>\n",
1447 ], 'With title at start' => [
1448 [ '* {{PAGENAME}}', Title
::newFromText( 'Talk:Some page' ), false ],
1449 "<p>* Some page</p>",
1451 [ "<div class='mw-editintro'>{{PAGENAME}}", Title
::newFromText( 'Talk:Some page' ) ],
1452 '<div class="mw-editintro">' . "Some page\n</div>"
1457 // Test all the others on addWikiTextTitle as well
1458 foreach ( $tests['addWikiText'] as $key => $val ) {
1459 $args = [ $val[0][0], null, $val[0][1] ??
true, false, $val[0][2] ??
true ];
1460 $tests['addWikiTextTitle']["$key (addWikiTextTitle)"] =
1461 array_merge( [ $args ], array_slice( $val, 1 ) );
1463 foreach ( $tests['addWikiTextWithTitle'] as $key => $val ) {
1464 $args = [ $val[0][0], $val[0][1], $val[0][2] ??
true ];
1465 $tests['addWikiTextTitle']["$key (addWikiTextTitle)"] =
1466 array_merge( [ $args ], array_slice( $val, 1 ) );
1468 foreach ( $tests['addWikiTextTidy'] as $key => $val ) {
1469 $args = [ $val[0][0], null, $val[0][1] ??
true, true, false ];
1470 $tests['addWikiTextTitle']["$key (addWikiTextTitle)"] =
1471 array_merge( [ $args ], array_slice( $val, 1 ) );
1473 foreach ( $tests['addWikiTextTitleTidy'] as $key => $val ) {
1474 $args = [ $val[0][0], $val[0][1], $val[0][2] ??
true, true, false ];
1475 $tests['addWikiTextTitle']["$key (addWikiTextTitle)"] =
1476 array_merge( [ $args ], array_slice( $val, 1 ) );
1479 // We have to reformat our array to match what PHPUnit wants
1481 foreach ( $tests as $key => $subarray ) {
1482 foreach ( $subarray as $subkey => $val ) {
1483 $val = array_merge( [ $key ], $val );
1484 $ret[$subkey] = $val;
1492 * @covers OutputPage::addWikiText
1494 public function testAddWikiTextNoTitle() {
1495 $this->setExpectedException( MWException
::class, 'Title is null' );
1497 $op = $this->newInstance( [], null, 'notitle' );
1498 $op->addWikiText( 'a' );
1502 * @covers OutputPage::addParserOutputMetadata
1504 public function testNoGallery() {
1505 $op = $this->newInstance();
1506 $this->assertFalse( $op->mNoGallery
);
1508 $stubPO1 = $this->createParserOutputStub( 'getNoGallery', true );
1509 $op->addParserOutputMetadata( $stubPO1 );
1510 $this->assertTrue( $op->mNoGallery
);
1512 $stubPO2 = $this->createParserOutputStub( 'getNoGallery', false );
1513 $op->addParserOutputMetadata( $stubPO2 );
1514 $this->assertFalse( $op->mNoGallery
);
1517 // @todo Make sure to test the following in addParserOutputMetadata() as well when we add tests
1519 // * enableClientCache()
1521 // * addModuleScripts()
1522 // * addModuleStyles()
1523 // * addJsConfigVars()
1524 // * preventClickJacking()
1525 // Otherwise those lines of addParserOutputMetadata() will be reported as covered, but we won't
1526 // be testing they actually work.
1529 * @covers OutputPage::haveCacheVaryCookies
1531 public function testHaveCacheVaryCookies() {
1532 $request = new FauxRequest();
1533 $context = new RequestContext();
1534 $context->setRequest( $request );
1535 $op = new OutputPage( $context );
1537 // No cookies are set.
1538 $this->assertFalse( $op->haveCacheVaryCookies() );
1540 // 'Token' is present but empty, so it shouldn't count.
1541 $request->setCookie( 'Token', '' );
1542 $this->assertFalse( $op->haveCacheVaryCookies() );
1544 // 'Token' present and nonempty.
1545 $request->setCookie( 'Token', '123' );
1546 $this->assertTrue( $op->haveCacheVaryCookies() );
1550 * @dataProvider provideVaryHeaders
1552 * @covers OutputPage::addVaryHeader
1553 * @covers OutputPage::getVaryHeader
1554 * @covers OutputPage::getKeyHeader
1556 public function testVaryHeaders( $calls, $vary, $key ) {
1557 // get rid of default Vary fields
1558 $op = $this->getMockBuilder( OutputPage
::class )
1559 ->setConstructorArgs( [ new RequestContext() ] )
1560 ->setMethods( [ 'getCacheVaryCookies' ] )
1562 $op->expects( $this->any() )
1563 ->method( 'getCacheVaryCookies' )
1564 ->will( $this->returnValue( [] ) );
1565 TestingAccessWrapper
::newFromObject( $op )->mVaryHeader
= [];
1567 foreach ( $calls as $call ) {
1568 call_user_func_array( [ $op, 'addVaryHeader' ], $call );
1570 $this->assertEquals( $vary, $op->getVaryHeader(), 'Vary:' );
1571 $this->assertEquals( $key, $op->getKeyHeader(), 'Key:' );
1574 public function provideVaryHeaders() {
1575 // note: getKeyHeader() automatically adds Vary: Cookie
1584 [ // non-unique headers
1587 [ 'Accept-Language' ],
1590 'Vary: Cookie, Accept-Language',
1591 'Key: Cookie,Accept-Language',
1593 [ // two headers with single options
1595 [ 'Cookie', [ 'param=phpsessid' ] ],
1596 [ 'Accept-Language', [ 'substr=en' ] ],
1598 'Vary: Cookie, Accept-Language',
1599 'Key: Cookie;param=phpsessid,Accept-Language;substr=en',
1601 [ // one header with multiple options
1603 [ 'Cookie', [ 'param=phpsessid', 'param=userId' ] ],
1606 'Key: Cookie;param=phpsessid;param=userId',
1608 [ // Duplicate option
1610 [ 'Cookie', [ 'param=phpsessid' ] ],
1611 [ 'Cookie', [ 'param=phpsessid' ] ],
1612 [ 'Accept-Language', [ 'substr=en', 'substr=en' ] ],
1614 'Vary: Cookie, Accept-Language',
1615 'Key: Cookie;param=phpsessid,Accept-Language;substr=en',
1617 [ // Same header, different options
1619 [ 'Cookie', [ 'param=phpsessid' ] ],
1620 [ 'Cookie', [ 'param=userId' ] ],
1623 'Key: Cookie;param=phpsessid;param=userId',
1629 * @dataProvider provideLinkHeaders
1631 * @covers OutputPage::addLinkHeader
1632 * @covers OutputPage::getLinkHeader
1634 public function testLinkHeaders( $headers, $result ) {
1635 $op = $this->newInstance();
1637 foreach ( $headers as $header ) {
1638 $op->addLinkHeader( $header );
1641 $this->assertEquals( $result, $op->getLinkHeader() );
1644 public function provideLinkHeaders() {
1651 [ '<https://foo/bar.jpg>;rel=preload;as=image' ],
1652 'Link: <https://foo/bar.jpg>;rel=preload;as=image',
1655 [ '<https://foo/bar.jpg>;rel=preload;as=image','<https://foo/baz.jpg>;rel=preload;as=image' ],
1656 'Link: <https://foo/bar.jpg>;rel=preload;as=image,<https://foo/baz.jpg>;rel=preload;as=image',
1662 * See ResourceLoaderClientHtmlTest for full coverage.
1664 * @dataProvider provideMakeResourceLoaderLink
1666 * @covers OutputPage::makeResourceLoaderLink
1668 public function testMakeResourceLoaderLink( $args, $expectedHtml ) {
1669 $this->setMwGlobals( [
1670 'wgResourceLoaderDebug' => false,
1671 'wgLoadScript' => 'http://127.0.0.1:8080/w/load.php',
1672 'wgCSPReportOnlyHeader' => true,
1674 $class = new ReflectionClass( OutputPage
::class );
1675 $method = $class->getMethod( 'makeResourceLoaderLink' );
1676 $method->setAccessible( true );
1677 $ctx = new RequestContext();
1678 $ctx->setSkin( SkinFactory
::getDefaultInstance()->makeSkin( 'fallback' ) );
1679 $ctx->setLanguage( 'en' );
1680 $out = new OutputPage( $ctx );
1681 $nonce = $class->getProperty( 'CSPNonce' );
1682 $nonce->setAccessible( true );
1683 $nonce->setValue( $out, 'secret' );
1684 $rl = $out->getResourceLoader();
1685 $rl->setMessageBlobStore( new NullMessageBlobStore() );
1687 'test.foo' => new ResourceLoaderTestModule( [
1688 'script' => 'mw.test.foo( { a: true } );',
1689 'styles' => '.mw-test-foo { content: "style"; }',
1691 'test.bar' => new ResourceLoaderTestModule( [
1692 'script' => 'mw.test.bar( { a: true } );',
1693 'styles' => '.mw-test-bar { content: "style"; }',
1695 'test.baz' => new ResourceLoaderTestModule( [
1696 'script' => 'mw.test.baz( { a: true } );',
1697 'styles' => '.mw-test-baz { content: "style"; }',
1699 'test.quux' => new ResourceLoaderTestModule( [
1700 'script' => 'mw.test.baz( { token: 123 } );',
1701 'styles' => '/* pref-animate=off */ .mw-icon { transition: none; }',
1702 'group' => 'private',
1704 'test.noscript' => new ResourceLoaderTestModule( [
1705 'styles' => '.stuff { color: red; }',
1706 'group' => 'noscript',
1708 'test.group.foo' => new ResourceLoaderTestModule( [
1709 'script' => 'mw.doStuff( "foo" );',
1712 'test.group.bar' => new ResourceLoaderTestModule( [
1713 'script' => 'mw.doStuff( "bar" );',
1717 $links = $method->invokeArgs( $out, $args );
1718 $actualHtml = strval( $links );
1719 $this->assertEquals( $expectedHtml, $actualHtml );
1722 public static function provideMakeResourceLoaderLink() {
1723 // phpcs:disable Generic.Files.LineLength
1725 // Single only=scripts load
1727 [ 'test.foo', ResourceLoaderModule
::TYPE_SCRIPTS
],
1728 "<script nonce=\"secret\">(window.RLQ=window.RLQ||[]).push(function(){"
1729 . 'mw.loader.load("http://127.0.0.1:8080/w/load.php?debug=false\u0026lang=en\u0026modules=test.foo\u0026only=scripts\u0026skin=fallback");'
1732 // Multiple only=styles load
1734 [ [ 'test.baz', 'test.foo', 'test.bar' ], ResourceLoaderModule
::TYPE_STYLES
],
1736 '<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"/>'
1738 // Private embed (only=scripts)
1740 [ 'test.quux', ResourceLoaderModule
::TYPE_SCRIPTS
],
1741 "<script nonce=\"secret\">(window.RLQ=window.RLQ||[]).push(function(){"
1742 . "mw.test.baz({token:123});\nmw.loader.state({\"test.quux\":\"ready\"});"
1745 // Load private module (combined)
1747 [ 'test.quux', ResourceLoaderModule
::TYPE_COMBINED
],
1748 "<script nonce=\"secret\">(window.RLQ=window.RLQ||[]).push(function(){"
1749 . "mw.loader.implement(\"test.quux@1ev0ijv\",function($,jQuery,require,module){"
1750 . "mw.test.baz({token:123});},{\"css\":[\".mw-icon{transition:none}"
1751 . "\"]});});</script>"
1755 [ [], ResourceLoaderModule
::TYPE_COMBINED
],
1760 [ 'test.noscript', ResourceLoaderModule
::TYPE_STYLES
],
1761 '<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>'
1763 // Load two modules in separate groups
1765 [ [ 'test.group.foo', 'test.group.bar' ], ResourceLoaderModule
::TYPE_COMBINED
],
1766 "<script nonce=\"secret\">(window.RLQ=window.RLQ||[]).push(function(){"
1767 . 'mw.loader.load("http://127.0.0.1:8080/w/load.php?debug=false\u0026lang=en\u0026modules=test.group.bar\u0026skin=fallback");'
1768 . 'mw.loader.load("http://127.0.0.1:8080/w/load.php?debug=false\u0026lang=en\u0026modules=test.group.foo\u0026skin=fallback");'
1776 * @dataProvider provideBuildExemptModules
1778 * @covers OutputPage::buildExemptModules
1780 public function testBuildExemptModules( array $exemptStyleModules, $expect ) {
1781 $this->setMwGlobals( [
1782 'wgResourceLoaderDebug' => false,
1783 'wgLoadScript' => '/w/load.php',
1784 // Stub wgCacheEpoch as it influences getVersionHash used for the
1785 // urls in the expected HTML
1786 'wgCacheEpoch' => '20140101000000',
1790 $ctx = new RequestContext();
1791 $ctx->setSkin( SkinFactory
::getDefaultInstance()->makeSkin( 'fallback' ) );
1792 $ctx->setLanguage( 'en' );
1793 $op = $this->getMockBuilder( OutputPage
::class )
1794 ->setConstructorArgs( [ $ctx ] )
1795 ->setMethods( [ 'buildCssLinksArray' ] )
1797 $op->expects( $this->any() )
1798 ->method( 'buildCssLinksArray' )
1800 $rl = $op->getResourceLoader();
1801 $rl->setMessageBlobStore( new NullMessageBlobStore() );
1803 // Register custom modules
1805 'example.site.a' => new ResourceLoaderTestModule( [ 'group' => 'site' ] ),
1806 'example.site.b' => new ResourceLoaderTestModule( [ 'group' => 'site' ] ),
1807 'example.user' => new ResourceLoaderTestModule( [ 'group' => 'user' ] ),
1810 $op = TestingAccessWrapper
::newFromObject( $op );
1811 $op->rlExemptStyleModules
= $exemptStyleModules;
1812 $this->assertEquals(
1814 strval( $op->buildExemptModules() )
1818 public static function provideBuildExemptModules() {
1819 // phpcs:disable Generic.Files.LineLength
1822 'exemptStyleModules' => [],
1823 '<meta name="ResourceLoaderDynamicStyles" content=""/>',
1826 'exemptStyleModules' => [ 'site' => [], 'noscript' => [], 'private' => [], 'user' => [] ],
1827 '<meta name="ResourceLoaderDynamicStyles" content=""/>',
1829 'default logged-out' => [
1830 'exemptStyleModules' => [ 'site' => [ 'site.styles' ] ],
1831 '<meta name="ResourceLoaderDynamicStyles" content=""/>' . "\n" .
1832 '<link rel="stylesheet" href="/w/load.php?debug=false&lang=en&modules=site.styles&only=styles&skin=fallback"/>',
1834 'default logged-in' => [
1835 'exemptStyleModules' => [ 'site' => [ 'site.styles' ], 'user' => [ 'user.styles' ] ],
1836 '<meta name="ResourceLoaderDynamicStyles" content=""/>' . "\n" .
1837 '<link rel="stylesheet" href="/w/load.php?debug=false&lang=en&modules=site.styles&only=styles&skin=fallback"/>' . "\n" .
1838 '<link rel="stylesheet" href="/w/load.php?debug=false&lang=en&modules=user.styles&only=styles&skin=fallback&version=1ai9g6t"/>',
1840 'custom modules' => [
1841 'exemptStyleModules' => [
1842 'site' => [ 'site.styles', 'example.site.a', 'example.site.b' ],
1843 'user' => [ 'user.styles', 'example.user' ],
1845 '<meta name="ResourceLoaderDynamicStyles" content=""/>' . "\n" .
1846 '<link rel="stylesheet" href="/w/load.php?debug=false&lang=en&modules=example.site.a%2Cb&only=styles&skin=fallback"/>' . "\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=example.user&only=styles&skin=fallback&version=0a56zyi"/>' . "\n" .
1849 '<link rel="stylesheet" href="/w/load.php?debug=false&lang=en&modules=user.styles&only=styles&skin=fallback&version=1ai9g6t"/>',
1856 * @dataProvider provideTransformFilePath
1857 * @covers OutputPage::transformFilePath
1858 * @covers OutputPage::transformResourcePath
1860 public function testTransformResourcePath( $baseDir, $basePath, $uploadDir = null,
1861 $uploadPath = null, $path = null, $expected = null
1863 if ( $path === null ) {
1864 // Skip optional $uploadDir and $uploadPath
1866 $expected = $uploadPath;
1867 $uploadDir = "$baseDir/images";
1868 $uploadPath = "$basePath/images";
1870 $this->setMwGlobals( 'IP', $baseDir );
1871 $conf = new HashConfig( [
1872 'ResourceBasePath' => $basePath,
1873 'UploadDirectory' => $uploadDir,
1874 'UploadPath' => $uploadPath,
1877 // Some of these paths don't exist and will cause warnings
1878 Wikimedia\
suppressWarnings();
1879 $actual = OutputPage
::transformResourcePath( $conf, $path );
1880 Wikimedia\restoreWarnings
();
1882 $this->assertEquals( $expected ?
: $path, $actual );
1885 public static function provideTransformFilePath() {
1886 $baseDir = dirname( __DIR__
) . '/data/media';
1888 // File that matches basePath, and exists. Hash found and appended.
1890 'baseDir' => $baseDir, 'basePath' => '/w',
1894 // File that matches basePath, but not found on disk. Empty query.
1896 'baseDir' => $baseDir, 'basePath' => '/w',
1900 // File not matching basePath. Ignored.
1902 'baseDir' => $baseDir, 'basePath' => '/w',
1905 // Empty string. Ignored.
1907 'baseDir' => $baseDir, 'basePath' => '/w',
1911 // Similar path, but with domain component. Ignored.
1913 'baseDir' => $baseDir, 'basePath' => '/w',
1914 '//example.org/w/test.jpg'
1917 'baseDir' => $baseDir, 'basePath' => '/w',
1918 'https://example.org/w/test.jpg'
1920 // Unrelated path with domain component. Ignored.
1922 'baseDir' => $baseDir, 'basePath' => '/w',
1923 'https://example.org/files/test.jpg'
1926 'baseDir' => $baseDir, 'basePath' => '/w',
1927 '//example.org/files/test.jpg'
1929 // Unrelated path with domain, and empty base path (root mw install). Ignored.
1931 'baseDir' => $baseDir, 'basePath' => '',
1932 'https://example.org/files/test.jpg'
1935 'baseDir' => $baseDir, 'basePath' => '',
1937 '//example.org/files/test.jpg'
1939 // Check UploadPath before ResourceBasePath (T155146)
1941 'baseDir' => dirname( $baseDir ), 'basePath' => '',
1942 'uploadDir' => $baseDir, 'uploadPath' => '/images',
1944 '/images/test.jpg?edcf2'
1950 * Tests a particular case of transformCssMedia, using the given input, globals,
1951 * expected return, and message
1953 * Asserts that $expectedReturn is returned.
1955 * options['printableQuery'] - value of query string for printable, or omitted for none
1956 * options['handheldQuery'] - value of query string for handheld, or omitted for none
1957 * options['media'] - passed into the method under the same name
1958 * options['expectedReturn'] - expected return value
1959 * options['message'] - PHPUnit message for assertion
1961 * @param array $args Key-value array of arguments as shown above
1963 protected function assertTransformCssMediaCase( $args ) {
1965 if ( isset( $args['printableQuery'] ) ) {
1966 $queryData['printable'] = $args['printableQuery'];
1969 if ( isset( $args['handheldQuery'] ) ) {
1970 $queryData['handheld'] = $args['handheldQuery'];
1973 $fauxRequest = new FauxRequest( $queryData, false );
1974 $this->setMwGlobals( [
1975 'wgRequest' => $fauxRequest,
1978 $actualReturn = OutputPage
::transformCssMedia( $args['media'] );
1979 $this->assertSame( $args['expectedReturn'], $actualReturn, $args['message'] );
1983 * Tests print requests
1985 * @covers OutputPage::transformCssMedia
1987 public function testPrintRequests() {
1988 $this->assertTransformCssMediaCase( [
1989 'printableQuery' => '1',
1990 'media' => 'screen',
1991 'expectedReturn' => null,
1992 'message' => 'On printable request, screen returns null'
1995 $this->assertTransformCssMediaCase( [
1996 'printableQuery' => '1',
1997 'media' => self
::SCREEN_MEDIA_QUERY
,
1998 'expectedReturn' => null,
1999 'message' => 'On printable request, screen media query returns null'
2002 $this->assertTransformCssMediaCase( [
2003 'printableQuery' => '1',
2004 'media' => self
::SCREEN_ONLY_MEDIA_QUERY
,
2005 'expectedReturn' => null,
2006 'message' => 'On printable request, screen media query with only returns null'
2009 $this->assertTransformCssMediaCase( [
2010 'printableQuery' => '1',
2012 'expectedReturn' => '',
2013 'message' => 'On printable request, media print returns empty string'
2018 * Tests screen requests, without either query parameter set
2020 * @covers OutputPage::transformCssMedia
2022 public function testScreenRequests() {
2023 $this->assertTransformCssMediaCase( [
2024 'media' => 'screen',
2025 'expectedReturn' => 'screen',
2026 'message' => 'On screen request, screen media type is preserved'
2029 $this->assertTransformCssMediaCase( [
2030 'media' => 'handheld',
2031 'expectedReturn' => 'handheld',
2032 'message' => 'On screen request, handheld media type is preserved'
2035 $this->assertTransformCssMediaCase( [
2036 'media' => self
::SCREEN_MEDIA_QUERY
,
2037 'expectedReturn' => self
::SCREEN_MEDIA_QUERY
,
2038 'message' => 'On screen request, screen media query is preserved.'
2041 $this->assertTransformCssMediaCase( [
2042 'media' => self
::SCREEN_ONLY_MEDIA_QUERY
,
2043 'expectedReturn' => self
::SCREEN_ONLY_MEDIA_QUERY
,
2044 'message' => 'On screen request, screen media query with only is preserved.'
2047 $this->assertTransformCssMediaCase( [
2049 'expectedReturn' => 'print',
2050 'message' => 'On screen request, print media type is preserved'
2055 * Tests handheld behavior
2057 * @covers OutputPage::transformCssMedia
2059 public function testHandheld() {
2060 $this->assertTransformCssMediaCase( [
2061 'handheldQuery' => '1',
2062 'media' => 'handheld',
2063 'expectedReturn' => '',
2064 'message' => 'On request with handheld querystring and media is handheld, returns empty string'
2067 $this->assertTransformCssMediaCase( [
2068 'handheldQuery' => '1',
2069 'media' => 'screen',
2070 'expectedReturn' => null,
2071 'message' => 'On request with handheld querystring and media is screen, returns null'
2076 * @return OutputPage
2078 private function newInstance( $config = [], WebRequest
$request = null, $options = [] ) {
2079 $context = new RequestContext();
2081 $context->setConfig( new MultiConfig( [
2082 new HashConfig( $config +
[
2083 'AppleTouchIcon' => false,
2084 'DisableLangConversion' => true,
2085 'EnableCanonicalServerLink' => false,
2088 'LanguageCode' => false,
2089 'ReferrerPolicy' => false,
2090 'RightsPage' => false,
2091 'RightsUrl' => false,
2092 'UniversalEditButton' => false,
2094 $context->getConfig()
2097 if ( !in_array( 'notitle', (array)$options ) ) {
2098 $context->setTitle( Title
::newFromText( 'My test page' ) );
2102 $context->setRequest( $request );
2105 return new OutputPage( $context );
2110 * MessageBlobStore that doesn't do anything
2112 class NullMessageBlobStore
extends MessageBlobStore
{
2113 public function get( ResourceLoader
$resourceLoader, $modules, $lang ) {
2117 public function updateModule( $name, ResourceLoaderModule
$module, $lang ) {
2120 public function updateMessage( $key ) {
2123 public function clear() {