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
258 * @covers OutputPage::addParserOutput
260 public function testHeadItemsParserOutput() {
261 $op = $this->newInstance();
262 $stubPO1 = $this->createParserOutputStub( 'getHeadItems', [ 'a' => 'b' ] );
263 $op->addParserOutputMetadata( $stubPO1 );
264 $stubPO2 = $this->createParserOutputStub( 'getHeadItems',
265 [ 'c' => '<d>&', 'e' => 'f', 'a' => 'q' ] );
266 $op->addParserOutputMetadata( $stubPO2 );
267 $stubPO3 = $this->createParserOutputStub( 'getHeadItems', [ 'e' => 'g' ] );
268 $op->addParserOutput( $stubPO3 );
269 $stubPO4 = $this->createParserOutputStub( 'getHeadItems', [ 'x' ] );
270 $op->addParserOutputMetadata( $stubPO4 );
272 $this->assertSame( [ 'a' => 'q', 'c' => '<d>&', 'e' => 'g', 'x' ],
273 $op->getHeadItemsArray() );
275 $this->assertTrue( $op->hasHeadItem( 'a' ) );
276 $this->assertTrue( $op->hasHeadItem( 'c' ) );
277 $this->assertTrue( $op->hasHeadItem( 'e' ) );
278 $this->assertTrue( $op->hasHeadItem( '0' ) );
279 $this->assertFalse( $op->hasHeadItem( 'b' ) );
281 $this->assertContains( "\nq\n<d>&\ng\nx\n",
282 '' . $op->headElement( $op->getContext()->getSkin() ) );
286 * @covers OutputPage::addBodyClasses
288 public function testAddBodyClasses() {
289 $op = $this->newInstance();
290 $op->addBodyClasses( 'a' );
291 $op->addBodyClasses( 'mediawiki' );
292 $op->addBodyClasses( 'b c' );
293 $op->addBodyClasses( [ 'd', 'e' ] );
294 $op->addBodyClasses( 'a' );
296 $this->assertContains( '"a mediawiki b c d e ltr',
297 '' . $op->headElement( $op->getContext()->getSkin() ) );
301 * @covers OutputPage::setArticleBodyOnly
302 * @covers OutputPage::getArticleBodyOnly
304 public function testArticleBodyOnly() {
305 $op = $this->newInstance();
306 $this->assertFalse( $op->getArticleBodyOnly() );
308 $op->setArticleBodyOnly( true );
309 $this->assertTrue( $op->getArticleBodyOnly() );
311 $op->addHTML( '<b>a</b>' );
313 $this->assertSame( '<b>a</b>', $op->output( true ) );
317 * @covers OutputPage::setProperty
318 * @covers OutputPage::getProperty
320 public function testProperties() {
321 $op = $this->newInstance();
323 $this->assertNull( $op->getProperty( 'foo' ) );
325 $op->setProperty( 'foo', 'bar' );
326 $op->setProperty( 'baz', 'quz' );
328 $this->assertSame( 'bar', $op->getProperty( 'foo' ) );
329 $this->assertSame( 'quz', $op->getProperty( 'baz' ) );
333 * @dataProvider provideCheckLastModified
335 * @covers OutputPage::checkLastModified
336 * @covers OutputPage::getCdnCacheEpoch
338 public function testCheckLastModified(
339 $timestamp, $ifModifiedSince, $expected, $config = [], $callback = null
341 $request = new FauxRequest();
342 if ( $ifModifiedSince ) {
343 if ( is_numeric( $ifModifiedSince ) ) {
345 $ifModifiedSince = date( 'D, d M Y H:i:s', $ifModifiedSince ) . ' GMT';
347 $request->setHeader( 'If-Modified-Since', $ifModifiedSince );
350 if ( !isset( $config['CacheEpoch'] ) ) {
351 // Make sure it's not too recent
352 $config['CacheEpoch'] = '20000101000000';
355 $op = $this->newInstance( $config, $request );
358 $callback( $op, $this );
361 // Avoid a complaint about not being able to disable compression
362 Wikimedia\
suppressWarnings();
364 $this->assertEquals( $expected, $op->checkLastModified( $timestamp ) );
366 Wikimedia\restoreWarnings
();
370 public function provideCheckLastModified() {
371 $lastModified = time() - 3600;
374 [ '0', $lastModified, false ],
375 'Timestamp Unix epoch' =>
376 [ '19700101000000', $lastModified, false ],
377 'Timestamp same as If-Modified-Since' =>
378 [ $lastModified, $lastModified, true ],
379 'Timestamp one second after If-Modified-Since' =>
380 [ $lastModified +
1, $lastModified, false ],
381 'No If-Modified-Since' =>
382 [ $lastModified +
1, null, false ],
383 'Malformed If-Modified-Since' =>
384 [ $lastModified +
1, 'GIBBERING WOMBATS !!!', false ],
385 'Non-standard IE-style If-Modified-Since' =>
386 [ $lastModified, date( 'D, d M Y H:i:s', $lastModified ) . ' GMT; length=5202',
388 // @todo Should we fix this behavior to match the spec? Probably no reason to.
389 'If-Modified-Since not per spec but we accept it anyway because strtotime does' =>
390 [ $lastModified, "@$lastModified", true ],
391 '$wgCachePages = false' =>
392 [ $lastModified, $lastModified, false, [ 'CachePages' => false ] ],
394 [ $lastModified, $lastModified, false,
395 [ 'CacheEpoch' => wfTimestamp( TS_MW
, $lastModified +
1 ) ] ],
396 'Recently-touched user' =>
397 [ $lastModified, $lastModified, false, [],
399 $op->getContext()->setUser( $this->getTestUser()->getUser() );
401 'After Squid expiry' =>
402 [ $lastModified, $lastModified, false,
403 [ 'UseSquid' => true, 'SquidMaxage' => 3599 ] ],
404 'Hook allows cache use' =>
405 [ $lastModified +
1, $lastModified, true, [],
406 function ( $op, $that ) {
407 $that->setTemporaryHook( 'OutputPageCheckLastModified',
408 function ( &$modifiedTimes ) {
409 $modifiedTimes = [ 1 ];
413 'Hooks prohibits cache use' =>
414 [ $lastModified, $lastModified, false, [],
415 function ( $op, $that ) {
416 $that->setTemporaryHook( 'OutputPageCheckLastModified',
417 function ( &$modifiedTimes ) {
418 $modifiedTimes = [ max( $modifiedTimes ) +
1 ];
426 * @dataProvider provideCdnCacheEpoch
428 * @covers OutputPage::getCdnCacheEpoch
430 public function testCdnCacheEpoch( $params ) {
431 $out = TestingAccessWrapper
::newFromObject( $this->newInstance() );
432 $reqTime = strtotime( $params['reqTime'] );
433 $pageTime = strtotime( $params['pageTime'] );
434 $actual = max( $pageTime, $out->getCdnCacheEpoch( $reqTime, $params['maxAge'] ) );
438 gmdate( DateTime
::ATOM
, $actual ),
443 public static function provideCdnCacheEpoch() {
445 'pageTime' => '2011-04-01T12:00:00+00:00',
446 'maxAge' => 24 * 3600,
449 'after 1s' => [ $base +
[
450 'reqTime' => '2011-04-01T12:00:01+00:00',
451 'expect' => '2011-04-01T12:00:00+00:00',
453 'after 23h' => [ $base +
[
454 'reqTime' => '2011-04-02T11:00:00+00:00',
455 'expect' => '2011-04-01T12:00:00+00:00',
457 'after 24h and a bit' => [ $base +
[
458 'reqTime' => '2011-04-02T12:34:56+00:00',
459 'expect' => '2011-04-01T12:34:56+00:00',
461 'after a year' => [ $base +
[
462 'reqTime' => '2012-05-06T00:12:07+00:00',
463 'expect' => '2012-05-05T00:12:07+00:00',
468 // @todo How to test setLastModified?
471 * @covers OutputPage::setRobotPolicy
472 * @covers OutputPage::getHeadLinksArray
474 public function testSetRobotPolicy() {
475 $op = $this->newInstance();
476 $op->setRobotPolicy( 'noindex, nofollow' );
478 $links = $op->getHeadLinksArray();
479 $this->assertContains( '<meta name="robots" content="noindex,nofollow"/>', $links );
483 * @covers OutputPage::setIndexPolicy
484 * @covers OutputPage::setFollowPolicy
485 * @covers OutputPage::getHeadLinksArray
487 public function testSetIndexFollowPolicies() {
488 $op = $this->newInstance();
489 $op->setIndexPolicy( 'noindex' );
490 $op->setFollowPolicy( 'nofollow' );
492 $links = $op->getHeadLinksArray();
493 $this->assertContains( '<meta name="robots" content="noindex,nofollow"/>', $links );
496 private function extractHTMLTitle( OutputPage
$op ) {
497 $html = $op->headElement( $op->getContext()->getSkin() );
499 // OutputPage should always output the title in a nice format such that regexes will work
500 // fine. If it doesn't, we'll fail the tests.
501 preg_match_all( '!<title>(.*?)</title>!', $html, $matches );
503 $this->assertLessThanOrEqual( 1, count( $matches[1] ), 'More than one <title>!' );
505 if ( !count( $matches[1] ) ) {
509 return $matches[1][0];
513 * Shorthand for getting the text of a message, in content language.
515 private static function getMsgText( $op, ...$msgParams ) {
516 return $op->msg( ...$msgParams )->inContentLanguage()->text();
520 * @covers OutputPage::setHTMLTitle
521 * @covers OutputPage::getHTMLTitle
523 public function testHTMLTitle() {
524 $op = $this->newInstance();
527 $this->assertSame( '', $op->getHTMLTitle() );
528 $this->assertSame( '', $op->getPageTitle() );
530 $this->getMsgText( $op, 'pagetitle', '' ),
531 $this->extractHTMLTitle( $op )
535 $op->setHTMLTitle( 'Potatoes will eat me' );
537 $this->assertSame( 'Potatoes will eat me', $op->getHTMLTitle() );
538 $this->assertSame( 'Potatoes will eat me', $this->extractHTMLTitle( $op ) );
539 // Shouldn't have changed the page title
540 $this->assertSame( '', $op->getPageTitle() );
543 $msg = $op->msg( 'mainpage' );
545 $op->setHTMLTitle( $msg );
546 $this->assertSame( $msg->text(), $op->getHTMLTitle() );
547 $this->assertSame( $msg->text(), $this->extractHTMLTitle( $op ) );
548 $this->assertSame( '', $op->getPageTitle() );
552 * @covers OutputPage::setRedirectedFrom
554 public function testSetRedirectedFrom() {
555 $op = $this->newInstance();
557 $op->setRedirectedFrom( Title
::newFromText( 'Talk:Some page' ) );
558 $this->assertSame( 'Talk:Some_page', $op->getJSVars()['wgRedirectedFrom'] );
562 * @covers OutputPage::setPageTitle
563 * @covers OutputPage::getPageTitle
565 public function testPageTitle() {
566 // We don't test the actual HTML output anywhere, because that's up to the skin.
567 $op = $this->newInstance();
570 $this->assertSame( '', $op->getPageTitle() );
571 $this->assertSame( '', $op->getHTMLTitle() );
573 // Test set to plain text
574 $op->setPageTitle( 'foobar' );
576 $this->assertSame( 'foobar', $op->getPageTitle() );
577 // HTML title should change as well
578 $this->assertSame( $this->getMsgText( $op, 'pagetitle', 'foobar' ), $op->getHTMLTitle() );
580 // Test set to text with good and bad HTML. We don't try to be comprehensive here, that
581 // belongs in Sanitizer tests.
582 $op->setPageTitle( '<script>a</script>&<i>b</i>' );
584 $this->assertSame( '<script>a</script>&<i>b</i>', $op->getPageTitle() );
586 $this->getMsgText( $op, 'pagetitle', '<script>a</script>&b' ),
590 // Test set to message
591 $text = $this->getMsgText( $op, 'mainpage' );
593 $op->setPageTitle( $op->msg( 'mainpage' )->inContentLanguage() );
594 $this->assertSame( $text, $op->getPageTitle() );
595 $this->assertSame( $this->getMsgText( $op, 'pagetitle', $text ), $op->getHTMLTitle() );
599 * @covers OutputPage::setTitle
601 public function testSetTitle() {
602 $op = $this->newInstance();
604 $this->assertSame( 'My test page', $op->getTitle()->getPrefixedText() );
606 $op->setTitle( Title
::newFromText( 'Another test page' ) );
608 $this->assertSame( 'Another test page', $op->getTitle()->getPrefixedText() );
612 * @covers OutputPage::setSubtitle
613 * @covers OutputPage::clearSubtitle
614 * @covers OutputPage::addSubtitle
615 * @covers OutputPage::getSubtitle
617 public function testSubtitle() {
618 $op = $this->newInstance();
620 $this->assertSame( '', $op->getSubtitle() );
622 $op->addSubtitle( '<b>foo</b>' );
624 $this->assertSame( '<b>foo</b>', $op->getSubtitle() );
626 $op->addSubtitle( $op->msg( 'mainpage' )->inContentLanguage() );
629 "<b>foo</b><br />\n\t\t\t\t" . $this->getMsgText( $op, 'mainpage' ),
633 $op->setSubtitle( 'There can be only one' );
635 $this->assertSame( 'There can be only one', $op->getSubtitle() );
637 $op->clearSubtitle();
639 $this->assertSame( '', $op->getSubtitle() );
643 * @dataProvider provideBacklinkSubtitle
645 * @covers OutputPage::buildBacklinkSubtitle
647 public function testBuildBacklinkSubtitle( $titles, $queries, $contains, $notContains ) {
648 if ( count( $titles ) > 1 ) {
650 $this->assertTrue( true );
654 $title = Title
::newFromText( $titles[0] );
655 $query = $queries[0];
657 $this->editPage( 'Page 1', '' );
658 $this->editPage( 'Page 2', '#REDIRECT [[Page 1]]' );
660 $str = OutputPage
::buildBacklinkSubtitle( $title, $query )->text();
662 foreach ( $contains as $substr ) {
663 $this->assertContains( $substr, $str );
666 foreach ( $notContains as $substr ) {
667 $this->assertNotContains( $substr, $str );
672 * @dataProvider provideBacklinkSubtitle
674 * @covers OutputPage::addBacklinkSubtitle
675 * @covers OutputPage::getSubtitle
677 public function testAddBacklinkSubtitle( $titles, $queries, $contains, $notContains ) {
678 $this->editPage( 'Page 1', '' );
679 $this->editPage( 'Page 2', '#REDIRECT [[Page 1]]' );
681 $op = $this->newInstance();
682 foreach ( $titles as $i => $unused ) {
683 $op->addBacklinkSubtitle( Title
::newFromText( $titles[$i] ), $queries[$i] );
686 $str = $op->getSubtitle();
688 foreach ( $contains as $substr ) {
689 $this->assertContains( $substr, $str );
692 foreach ( $notContains as $substr ) {
693 $this->assertNotContains( $substr, $str );
697 public function provideBacklinkSubtitle() {
703 [ 'redirect', 'Page 2' ],
713 [ [ 'action' => 'edit' ] ],
718 [ 'Page 1', 'Page 2' ],
720 [ 'Page 1', 'Page 2', "<br />\n\t\t\t\t" ],
723 // @todo Anything else to test?
728 * @covers OutputPage::setPrintable
729 * @covers OutputPage::isPrintable
731 public function testPrintable() {
732 $op = $this->newInstance();
734 $this->assertFalse( $op->isPrintable() );
738 $this->assertTrue( $op->isPrintable() );
742 * @covers OutputPage::disable
743 * @covers OutputPage::isDisabled
745 public function testDisable() {
746 $op = $this->newInstance();
748 $this->assertFalse( $op->isDisabled() );
749 $this->assertNotSame( '', $op->output( true ) );
753 $this->assertTrue( $op->isDisabled() );
754 $this->assertSame( '', $op->output( true ) );
758 * @covers OutputPage::showNewSectionLink
759 * @covers OutputPage::addParserOutputMetadata
760 * @covers OutputPage::addParserOutput
762 public function testShowNewSectionLink() {
763 $op = $this->newInstance();
765 $this->assertFalse( $op->showNewSectionLink() );
767 $pOut1 = $this->createParserOutputStub( 'getNewSection', true );
768 $op->addParserOutputMetadata( $pOut1 );
769 $this->assertTrue( $op->showNewSectionLink() );
771 $pOut2 = $this->createParserOutputStub( 'getNewSection', false );
772 $op->addParserOutput( $pOut2 );
773 $this->assertFalse( $op->showNewSectionLink() );
777 * @covers OutputPage::forceHideNewSectionLink
778 * @covers OutputPage::addParserOutputMetadata
779 * @covers OutputPage::addParserOutput
781 public function testForceHideNewSectionLink() {
782 $op = $this->newInstance();
784 $this->assertFalse( $op->forceHideNewSectionLink() );
786 $pOut1 = $this->createParserOutputStub( 'getHideNewSection', true );
787 $op->addParserOutputMetadata( $pOut1 );
788 $this->assertTrue( $op->forceHideNewSectionLink() );
790 $pOut2 = $this->createParserOutputStub( 'getHideNewSection', false );
791 $op->addParserOutput( $pOut2 );
792 $this->assertFalse( $op->forceHideNewSectionLink() );
796 * @covers OutputPage::setSyndicated
797 * @covers OutputPage::isSyndicated
799 public function testSetSyndicated() {
800 $op = $this->newInstance();
801 $this->assertFalse( $op->isSyndicated() );
803 $op->setSyndicated();
804 $this->assertTrue( $op->isSyndicated() );
806 $op->setSyndicated( false );
807 $this->assertFalse( $op->isSyndicated() );
811 * @covers OutputPage::isSyndicated
812 * @covers OutputPage::setFeedAppendQuery
813 * @covers OutputPage::addFeedLink
814 * @covers OutputPage::getSyndicationLinks()
816 public function testFeedLinks() {
817 $op = $this->newInstance();
818 $this->assertSame( [], $op->getSyndicationLinks() );
820 $op->addFeedLink( 'not a supported format', 'abc' );
821 $this->assertFalse( $op->isSyndicated() );
822 $this->assertSame( [], $op->getSyndicationLinks() );
824 $feedTypes = $op->getConfig()->get( 'AdvertisedFeedTypes' );
826 $op->addFeedLink( $feedTypes[0], 'def' );
827 $this->assertTrue( $op->isSyndicated() );
828 $this->assertSame( [ $feedTypes[0] => 'def' ], $op->getSyndicationLinks() );
830 $op->setFeedAppendQuery( false );
832 foreach ( $feedTypes as $type ) {
833 $expected[$type] = $op->getTitle()->getLocalURL( "feed=$type" );
835 $this->assertSame( $expected, $op->getSyndicationLinks() );
837 $op->setFeedAppendQuery( 'apples=oranges' );
838 foreach ( $feedTypes as $type ) {
839 $expected[$type] = $op->getTitle()->getLocalURL( "feed=$type&apples=oranges" );
841 $this->assertSame( $expected, $op->getSyndicationLinks() );
845 * @covers OutputPage::setArticleFlag
846 * @covers OutputPage::isArticle
847 * @covers OutputPage::setArticleRelated
848 * @covers OutputPage::isArticleRelated
850 function testArticleFlags() {
851 $op = $this->newInstance();
852 $this->assertFalse( $op->isArticle() );
853 $this->assertTrue( $op->isArticleRelated() );
855 $op->setArticleRelated( false );
856 $this->assertFalse( $op->isArticle() );
857 $this->assertFalse( $op->isArticleRelated() );
859 $op->setArticleFlag( true );
860 $this->assertTrue( $op->isArticle() );
861 $this->assertTrue( $op->isArticleRelated() );
863 $op->setArticleFlag( false );
864 $this->assertFalse( $op->isArticle() );
865 $this->assertTrue( $op->isArticleRelated() );
867 $op->setArticleFlag( true );
868 $op->setArticleRelated( false );
869 $this->assertFalse( $op->isArticle() );
870 $this->assertFalse( $op->isArticleRelated() );
874 * @covers OutputPage::addLanguageLinks
875 * @covers OutputPage::setLanguageLinks
876 * @covers OutputPage::getLanguageLinks
877 * @covers OutputPage::addParserOutputMetadata
878 * @covers OutputPage::addParserOutput
880 function testLanguageLinks() {
881 $op = $this->newInstance();
882 $this->assertSame( [], $op->getLanguageLinks() );
884 $op->addLanguageLinks( [ 'fr:A', 'it:B' ] );
885 $this->assertSame( [ 'fr:A', 'it:B' ], $op->getLanguageLinks() );
887 $op->addLanguageLinks( [ 'de:C', 'es:D' ] );
888 $this->assertSame( [ 'fr:A', 'it:B', 'de:C', 'es:D' ], $op->getLanguageLinks() );
890 $op->setLanguageLinks( [ 'pt:E' ] );
891 $this->assertSame( [ 'pt:E' ], $op->getLanguageLinks() );
893 $pOut1 = $this->createParserOutputStub( 'getLanguageLinks', [ 'he:F', 'ar:G' ] );
894 $op->addParserOutputMetadata( $pOut1 );
895 $this->assertSame( [ 'pt:E', 'he:F', 'ar:G' ], $op->getLanguageLinks() );
897 $pOut2 = $this->createParserOutputStub( 'getLanguageLinks', [ 'pt:H' ] );
898 $op->addParserOutput( $pOut2 );
899 $this->assertSame( [ 'pt:E', 'he:F', 'ar:G', 'pt:H' ], $op->getLanguageLinks() );
902 // @todo Are these category links tests too abstract and complicated for what they test? Would
903 // it make sense to just write out all the tests by hand with maybe some copy-and-paste?
906 * @dataProvider provideGetCategories
908 * @covers OutputPage::addCategoryLinks
909 * @covers OutputPage::getCategories
910 * @covers OutputPage::getCategoryLinks
912 * @param array $args Array of form [ category name => sort key ]
913 * @param array $fakeResults Array of form [ category name => value to return from mocked
915 * @param callback $variantLinkCallback Callback to replace findVariantLink() call
916 * @param array $expectedNormal Expected return value of getCategoryLinks['normal']
917 * @param array $expectedHidden Expected return value of getCategoryLinks['hidden']
919 public function testAddCategoryLinks(
920 array $args, array $fakeResults, callable
$variantLinkCallback = null,
921 array $expectedNormal, array $expectedHidden
923 $expectedNormal = $this->extractExpectedCategories( $expectedNormal, 'add' );
924 $expectedHidden = $this->extractExpectedCategories( $expectedHidden, 'add' );
926 $op = $this->setupCategoryTests( $fakeResults, $variantLinkCallback );
928 $op->addCategoryLinks( $args );
930 $this->doCategoryAsserts( $op, $expectedNormal, $expectedHidden );
931 $this->doCategoryLinkAsserts( $op, $expectedNormal, $expectedHidden );
935 * @dataProvider provideGetCategories
937 * @covers OutputPage::addCategoryLinks
938 * @covers OutputPage::getCategories
939 * @covers OutputPage::getCategoryLinks
941 public function testAddCategoryLinksOneByOne(
942 array $args, array $fakeResults, callable
$variantLinkCallback = null,
943 array $expectedNormal, array $expectedHidden
945 if ( count( $args ) <= 1 ) {
946 // @todo Should this be skipped instead of passed?
947 $this->assertTrue( true );
951 $expectedNormal = $this->extractExpectedCategories( $expectedNormal, 'onebyone' );
952 $expectedHidden = $this->extractExpectedCategories( $expectedHidden, 'onebyone' );
954 $op = $this->setupCategoryTests( $fakeResults, $variantLinkCallback );
956 foreach ( $args as $key => $val ) {
957 $op->addCategoryLinks( [ $key => $val ] );
960 $this->doCategoryAsserts( $op, $expectedNormal, $expectedHidden );
961 $this->doCategoryLinkAsserts( $op, $expectedNormal, $expectedHidden );
965 * @dataProvider provideGetCategories
967 * @covers OutputPage::setCategoryLinks
968 * @covers OutputPage::getCategories
969 * @covers OutputPage::getCategoryLinks
971 public function testSetCategoryLinks(
972 array $args, array $fakeResults, callable
$variantLinkCallback = null,
973 array $expectedNormal, array $expectedHidden
975 $expectedNormal = $this->extractExpectedCategories( $expectedNormal, 'set' );
976 $expectedHidden = $this->extractExpectedCategories( $expectedHidden, 'set' );
978 $op = $this->setupCategoryTests( $fakeResults, $variantLinkCallback );
980 $op->setCategoryLinks( [ 'Initial page' => 'Initial page' ] );
981 $op->setCategoryLinks( $args );
983 // We don't reset the categories, for some reason, only the links
984 $expectedNormalCats = array_merge( [ 'Initial page' ], $expectedNormal );
985 $expectedCats = array_merge( $expectedHidden, $expectedNormalCats );
987 $this->doCategoryAsserts( $op, $expectedNormalCats, $expectedHidden );
988 $this->doCategoryLinkAsserts( $op, $expectedNormal, $expectedHidden );
992 * @dataProvider provideGetCategories
994 * @covers OutputPage::addParserOutputMetadata
995 * @covers OutputPage::addParserOutput
996 * @covers OutputPage::getCategories
997 * @covers OutputPage::getCategoryLinks
999 public function testParserOutputCategoryLinks(
1000 array $args, array $fakeResults, callable
$variantLinkCallback = null,
1001 array $expectedNormal, array $expectedHidden
1003 $expectedNormal = $this->extractExpectedCategories( $expectedNormal, 'pout' );
1004 $expectedHidden = $this->extractExpectedCategories( $expectedHidden, 'pout' );
1006 $op = $this->setupCategoryTests( $fakeResults, $variantLinkCallback );
1008 $stubPO = $this->createParserOutputStub( 'getCategories', $args );
1010 // addParserOutput and addParserOutputMetadata should behave identically for us, so
1011 // alternate to get coverage for both without adding extra tests
1014 $method = [ 'addParserOutputMetadata', 'addParserOutput' ][$idx %
2];
1015 $op->$method( $stubPO );
1017 $this->doCategoryAsserts( $op, $expectedNormal, $expectedHidden );
1018 $this->doCategoryLinkAsserts( $op, $expectedNormal, $expectedHidden );
1022 * We allow different expectations for different tests as an associative array, like
1023 * [ 'set' => [ ... ], 'default' => [ ... ] ] if setCategoryLinks() will give a different
1026 private function extractExpectedCategories( array $expected, $key ) {
1027 if ( !$expected ||
isset( $expected[0] ) ) {
1030 return $expected[$key] ??
$expected['default'];
1033 private function setupCategoryTests(
1034 array $fakeResults, callable
$variantLinkCallback = null
1036 $this->setMwGlobals( 'wgUsePigLatinVariant', true );
1038 $op = $this->getMockBuilder( OutputPage
::class )
1039 ->setConstructorArgs( [ new RequestContext() ] )
1040 ->setMethods( [ 'addCategoryLinksToLBAndGetResult', 'getTitle' ] )
1043 $title = Title
::newFromText( 'My test page' );
1044 $op->expects( $this->any() )
1045 ->method( 'getTitle' )
1046 ->will( $this->returnValue( $title ) );
1048 $op->expects( $this->any() )
1049 ->method( 'addCategoryLinksToLBAndGetResult' )
1050 ->will( $this->returnCallback( function ( array $categories ) use ( $fakeResults ) {
1052 foreach ( $categories as $category => $unused ) {
1053 if ( isset( $fakeResults[$category] ) ) {
1054 $return[] = $fakeResults[$category];
1057 return new FakeResultWrapper( $return );
1060 if ( $variantLinkCallback ) {
1061 $mockContLang = $this->getMockBuilder( Language
::class )
1062 ->setConstructorArgs( [ 'en' ] )
1063 ->setMethods( [ 'findVariantLink' ] )
1065 $mockContLang->expects( $this->any() )
1066 ->method( 'findVariantLink' )
1067 ->will( $this->returnCallback( $variantLinkCallback ) );
1068 $this->setContentLang( $mockContLang );
1071 $this->assertSame( [], $op->getCategories() );
1076 private function doCategoryAsserts( $op, $expectedNormal, $expectedHidden ) {
1077 $this->assertSame( array_merge( $expectedHidden, $expectedNormal ), $op->getCategories() );
1078 $this->assertSame( $expectedNormal, $op->getCategories( 'normal' ) );
1079 $this->assertSame( $expectedHidden, $op->getCategories( 'hidden' ) );
1082 private function doCategoryLinkAsserts( $op, $expectedNormal, $expectedHidden ) {
1083 $catLinks = $op->getCategoryLinks();
1084 $this->assertSame( (bool)$expectedNormal +
(bool)$expectedHidden, count( $catLinks ) );
1085 if ( $expectedNormal ) {
1086 $this->assertSame( count( $expectedNormal ), count( $catLinks['normal'] ) );
1088 if ( $expectedHidden ) {
1089 $this->assertSame( count( $expectedHidden ), count( $catLinks['hidden'] ) );
1092 foreach ( $expectedNormal as $i => $name ) {
1093 $this->assertContains( $name, $catLinks['normal'][$i] );
1095 foreach ( $expectedHidden as $i => $name ) {
1096 $this->assertContains( $name, $catLinks['hidden'][$i] );
1100 public function provideGetCategories() {
1102 'No categories' => [ [], [], null, [], [] ],
1104 [ 'Test1' => 'Some sortkey', 'Test2' => 'A different sortkey' ],
1105 [ 'Test1' => (object)[ 'pp_value' => 1, 'page_title' => 'Test1' ],
1106 'Test2' => (object)[ 'page_title' => 'Test2' ] ],
1111 'Invalid title' => [
1112 [ '[' => '[', 'Test' => 'Test' ],
1113 [ 'Test' => (object)[ 'page_title' => 'Test' ] ],
1119 [ 'Test' => 'Test', 'Estay' => 'Estay' ],
1120 [ 'Test' => (object)[ 'page_title' => 'Test' ] ],
1121 function ( &$link, &$title ) {
1122 if ( $link === 'Estay' ) {
1124 $title = Title
::makeTitleSafe( NS_CATEGORY
, $link );
1127 // For adding one by one, the variant gets added as well as the original category,
1128 // but if you add them all together the second time gets skipped.
1129 [ 'onebyone' => [ 'Test', 'Test' ], 'default' => [ 'Test' ] ],
1136 * @covers OutputPage::getCategories
1138 public function testGetCategoriesInvalid() {
1139 $this->setExpectedException( InvalidArgumentException
::class,
1140 'Invalid category type given: hiddne' );
1142 $op = $this->newInstance();
1143 $op->getCategories( 'hiddne' );
1146 // @todo Should we test addCategoryLinksToLBAndGetResult? If so, how? Insert some test rows in
1150 * @covers OutputPage::setIndicators
1151 * @covers OutputPage::getIndicators
1152 * @covers OutputPage::addParserOutputMetadata
1153 * @covers OutputPage::addParserOutput
1155 public function testIndicators() {
1156 $op = $this->newInstance();
1157 $this->assertSame( [], $op->getIndicators() );
1159 $op->setIndicators( [] );
1160 $this->assertSame( [], $op->getIndicators() );
1162 // Test sorting alphabetically
1163 $op->setIndicators( [ 'b' => 'x', 'a' => 'y' ] );
1164 $this->assertSame( [ 'a' => 'y', 'b' => 'x' ], $op->getIndicators() );
1166 // Test overwriting existing keys
1167 $op->setIndicators( [ 'c' => 'z', 'a' => 'w' ] );
1168 $this->assertSame( [ 'a' => 'w', 'b' => 'x', 'c' => 'z' ], $op->getIndicators() );
1170 // Test with addParserOutputMetadata
1171 $pOut1 = $this->createParserOutputStub( 'getIndicators', [ 'c' => 'u', 'd' => 'v' ] );
1172 $op->addParserOutputMetadata( $pOut1 );
1173 $this->assertSame( [ 'a' => 'w', 'b' => 'x', 'c' => 'u', 'd' => 'v' ],
1174 $op->getIndicators() );
1176 // Test with addParserOutput
1177 $pOut2 = $this->createParserOutputStub( 'getIndicators', [ 'a' => '!!!' ] );
1178 $op->addParserOutput( $pOut2 );
1179 $this->assertSame( [ 'a' => '!!!', 'b' => 'x', 'c' => 'u', 'd' => 'v' ],
1180 $op->getIndicators() );
1184 * @covers OutputPage::addHelpLink
1185 * @covers OutputPage::getIndicators
1187 public function testAddHelpLink() {
1188 $op = $this->newInstance();
1190 $op->addHelpLink( 'Manual:PHP unit testing' );
1191 $indicators = $op->getIndicators();
1192 $this->assertSame( [ 'mw-helplink' ], array_keys( $indicators ) );
1193 $this->assertContains( 'Manual:PHP_unit_testing', $indicators['mw-helplink'] );
1195 $op->addHelpLink( 'https://phpunit.de', true );
1196 $indicators = $op->getIndicators();
1197 $this->assertSame( [ 'mw-helplink' ], array_keys( $indicators ) );
1198 $this->assertContains( 'https://phpunit.de', $indicators['mw-helplink'] );
1199 $this->assertNotContains( 'mediawiki', $indicators['mw-helplink'] );
1200 $this->assertNotContains( 'Manual:PHP', $indicators['mw-helplink'] );
1204 * @covers OutputPage::prependHTML
1205 * @covers OutputPage::addHTML
1206 * @covers OutputPage::addElement
1207 * @covers OutputPage::clearHTML
1208 * @covers OutputPage::getHTML
1210 public function testBodyHTML() {
1211 $op = $this->newInstance();
1212 $this->assertSame( '', $op->getHTML() );
1214 $op->addHTML( 'a' );
1215 $this->assertSame( 'a', $op->getHTML() );
1217 $op->addHTML( 'b' );
1218 $this->assertSame( 'ab', $op->getHTML() );
1220 $op->prependHTML( 'c' );
1221 $this->assertSame( 'cab', $op->getHTML() );
1223 $op->addElement( 'p', [ 'id' => 'foo' ], 'd' );
1224 $this->assertSame( 'cab<p id="foo">d</p>', $op->getHTML() );
1227 $this->assertSame( '', $op->getHTML() );
1231 * @dataProvider provideRevisionId
1232 * @covers OutputPage::setRevisionId
1233 * @covers OutputPage::getRevisionId
1235 public function testRevisionId( $newVal, $expected ) {
1236 $op = $this->newInstance();
1238 $this->assertNull( $op->setRevisionId( $newVal ) );
1239 $this->assertSame( $expected, $op->getRevisionId() );
1240 $this->assertSame( $expected, $op->setRevisionId( null ) );
1241 $this->assertNull( $op->getRevisionId() );
1244 public function provideRevisionId() {
1251 [ '32% finished', 32 ],
1257 * @covers OutputPage::setRevisionTimestamp
1258 * @covers OutputPage::getRevisionTimestamp
1260 public function testRevisionTimestamp() {
1261 $op = $this->newInstance();
1262 $this->assertNull( $op->getRevisionTimestamp() );
1264 $this->assertNull( $op->setRevisionTimestamp( 'abc' ) );
1265 $this->assertSame( 'abc', $op->getRevisionTimestamp() );
1266 $this->assertSame( 'abc', $op->setRevisionTimestamp( null ) );
1267 $this->assertNull( $op->getRevisionTimestamp() );
1271 * @covers OutputPage::setFileVersion
1272 * @covers OutputPage::getFileVersion
1274 public function testFileVersion() {
1275 $op = $this->newInstance();
1276 $this->assertNull( $op->getFileVersion() );
1278 $stubFile = $this->createMock( File
::class );
1279 $stubFile->method( 'exists' )->willReturn( true );
1280 $stubFile->method( 'getTimestamp' )->willReturn( '12211221123321' );
1281 $stubFile->method( 'getSha1' )->willReturn( 'bf3ffa7047dc080f5855377a4f83cd18887e3b05' );
1283 $op->setFileVersion( $stubFile );
1285 $this->assertEquals(
1286 [ 'time' => '12211221123321', 'sha1' => 'bf3ffa7047dc080f5855377a4f83cd18887e3b05' ],
1287 $op->getFileVersion()
1290 $stubMissingFile = $this->createMock( File
::class );
1291 $stubMissingFile->method( 'exists' )->willReturn( false );
1293 $op->setFileVersion( $stubMissingFile );
1294 $this->assertNull( $op->getFileVersion() );
1296 $op->setFileVersion( $stubFile );
1297 $this->assertNotNull( $op->getFileVersion() );
1299 $op->setFileVersion( null );
1300 $this->assertNull( $op->getFileVersion() );
1304 * Call either with arguments $methodName, $returnValue; or an array
1305 * [ $methodName => $returnValue, $methodName => $returnValue, ... ]
1307 private function createParserOutputStub( ...$args ) {
1308 if ( count( $args ) === 0 ) {
1310 } elseif ( count( $args ) === 1 ) {
1311 $retVals = $args[0];
1312 } elseif ( count( $args ) === 2 ) {
1313 $retVals = [ $args[0] => $args[1] ];
1315 $pOut = $this->getMock( ParserOutput
::class );
1316 foreach ( $retVals as $method => $retVal ) {
1317 $pOut->method( $method )->willReturn( $retVal );
1320 $arrayReturningMethods = [
1322 'getFileSearchOptions',
1330 foreach ( $arrayReturningMethods as $method ) {
1331 $pOut->method( $method )->willReturn( [] );
1338 * @covers OutputPage::getTemplateIds
1339 * @covers OutputPage::addParserOutputMetadata
1340 * @covers OutputPage::addParserOutput
1342 public function testTemplateIds() {
1343 $op = $this->newInstance();
1344 $this->assertSame( [], $op->getTemplateIds() );
1346 // Test with no template id's
1347 $stubPOEmpty = $this->createParserOutputStub();
1348 $op->addParserOutputMetadata( $stubPOEmpty );
1349 $this->assertSame( [], $op->getTemplateIds() );
1351 // Test with some arbitrary template id's
1353 NS_MAIN
=> [ 'A' => 3, 'B' => 17 ],
1354 NS_TALK
=> [ 'C' => 31 ],
1355 NS_MEDIA
=> [ 'D' => -1 ],
1358 $stubPO1 = $this->createParserOutputStub( 'getTemplateIds', $ids );
1360 $op->addParserOutputMetadata( $stubPO1 );
1361 $this->assertSame( $ids, $op->getTemplateIds() );
1363 // Test merging with a second set of id's
1364 $stubPO2 = $this->createParserOutputStub( 'getTemplateIds', [
1365 NS_MAIN
=> [ 'E' => 1234 ],
1366 NS_PROJECT
=> [ 'F' => 5678 ],
1370 NS_MAIN
=> [ 'E' => 1234, 'A' => 3, 'B' => 17 ],
1371 NS_TALK
=> [ 'C' => 31 ],
1372 NS_MEDIA
=> [ 'D' => -1 ],
1373 NS_PROJECT
=> [ 'F' => 5678 ],
1376 $op->addParserOutput( $stubPO2 );
1377 $this->assertSame( $finalIds, $op->getTemplateIds() );
1379 // Test merging with an empty set of id's
1380 $op->addParserOutputMetadata( $stubPOEmpty );
1381 $this->assertSame( $finalIds, $op->getTemplateIds() );
1385 * @covers OutputPage::getFileSearchOptions
1386 * @covers OutputPage::addParserOutputMetadata
1387 * @covers OutputPage::addParserOutput
1389 public function testFileSearchOptions() {
1390 $op = $this->newInstance();
1391 $this->assertSame( [], $op->getFileSearchOptions() );
1393 // Test with no files
1394 $stubPOEmpty = $this->createParserOutputStub();
1396 $op->addParserOutputMetadata( $stubPOEmpty );
1397 $this->assertSame( [], $op->getFileSearchOptions() );
1399 // Test with some arbitrary files
1401 'A' => [ 'time' => null, 'sha1' => '' ],
1403 'time' => '12211221123321',
1404 'sha1' => 'bf3ffa7047dc080f5855377a4f83cd18887e3b05',
1408 $stubPO1 = $this->createParserOutputStub( 'getFileSearchOptions', $files1 );
1410 $op->addParserOutput( $stubPO1 );
1411 $this->assertSame( $files1, $op->getFileSearchOptions() );
1413 // Test merging with a second set of files
1415 'C' => [ 'time' => null, 'sha1' => '' ],
1416 'B' => [ 'time' => null, 'sha1' => '' ],
1419 $stubPO2 = $this->createParserOutputStub( 'getFileSearchOptions', $files2 );
1421 $op->addParserOutputMetadata( $stubPO2 );
1422 $this->assertSame( array_merge( $files1, $files2 ), $op->getFileSearchOptions() );
1424 // Test merging with an empty set of files
1425 $op->addParserOutput( $stubPOEmpty );
1426 $this->assertSame( array_merge( $files1, $files2 ), $op->getFileSearchOptions() );
1430 * @dataProvider provideAddWikiText
1431 * @covers OutputPage::addWikiText
1432 * @covers OutputPage::addWikiTextAsInterface
1433 * @covers OutputPage::wrapWikiTextAsInterface
1434 * @covers OutputPage::addWikiTextAsContent
1435 * @covers OutputPage::addWikiTextWithTitle
1436 * @covers OutputPage::addWikiTextTitle
1437 * @covers OutputPage::addWikiTextTidy
1438 * @covers OutputPage::addWikiTextTitleTidy
1439 * @covers OutputPage::getHTML
1441 public function testAddWikiText( $method, array $args, $expected ) {
1442 $op = $this->newInstance();
1443 $this->assertSame( '', $op->getHTML() );
1445 $this->hideDeprecated( 'OutputPage::addWikiText' );
1446 $this->hideDeprecated( 'OutputPage::addWikiTextTitle' );
1447 $this->hideDeprecated( 'OutputPage::addWikiTextWithTitle' );
1448 $this->hideDeprecated( 'OutputPage::addWikiTextTidy' );
1449 $this->hideDeprecated( 'OutputPage::addWikiTextTitleTidy' );
1450 $this->hideDeprecated( 'disabling tidy' );
1454 [ 'addWikiTextWithTitle', 'addWikiTextTitleTidy', 'addWikiTextTitle' ]
1455 ) && count( $args ) >= 2 && $args[1] === null ) {
1456 // Special placeholder because we can't get the actual title in the provider
1457 $args[1] = $op->getTitle();
1461 [ 'addWikiTextAsInterface', 'addWikiTextAsContent' ]
1462 ) && count( $args ) >= 3 && $args[2] === null ) {
1463 // Special placeholder because we can't get the actual title in the provider
1464 $args[2] = $op->getTitle();
1467 $op->$method( ...$args );
1468 $this->assertSame( $expected, $op->getHTML() );
1471 public function provideAddWikiText() {
1474 // Not tidied; this API is deprecated.
1475 'Simple wikitext' => [
1477 "<p><b>Bold</b>\n</p>",
1478 ], 'List at start' => [
1480 "<ul><li>List</li></ul>\n",
1481 ], 'List not at start' => [
1482 [ '* Not a list', false ],
1484 ], 'Non-interface' => [
1485 [ "'''Bold'''", true, false ],
1486 "<p><b>Bold</b>\n</p>",
1487 ], 'No section edit links' => [
1489 "<h2><span class=\"mw-headline\" id=\"Title\">Title</span></h2>\n",
1492 'addWikiTextWithTitle' => [
1493 // Untidied; this API is deprecated
1494 'With title at start' => [
1495 [ '* {{PAGENAME}}', Title
::newFromText( 'Talk:Some page' ) ],
1496 "<ul><li>Some page</li></ul>\n",
1497 ], 'With title at start' => [
1498 [ '* {{PAGENAME}}', Title
::newFromText( 'Talk:Some page' ), false ],
1502 'addWikiTextAsInterface' => [
1503 // Preferred interface: output is tidied
1504 'Simple wikitext' => [
1506 "<p><b>Bold</b>\n</p>",
1507 ], 'Untidy wikitext' => [
1509 "<p><b>Bold\n</b></p>",
1510 ], 'List at start' => [
1512 "<ul><li>List</li></ul>\n",
1513 ], 'List not at start' => [
1514 [ '* Not a list', false ],
1515 '<p>* Not a list</p>',
1516 ], 'No section edit links' => [
1518 "<h2><span class=\"mw-headline\" id=\"Title\">Title</span></h2>\n",
1519 ], 'With title at start' => [
1520 [ '* {{PAGENAME}}', true, Title
::newFromText( 'Talk:Some page' ) ],
1521 "<ul><li>Some page</li></ul>\n",
1522 ], 'With title at start' => [
1523 [ '* {{PAGENAME}}', false, Title
::newFromText( 'Talk:Some page' ), false ],
1524 "<p>* Some page</p>",
1525 ], 'Untidy input' => [
1526 [ '<b>{{PAGENAME}}', true, Title
::newFromText( 'Talk:Some page' ) ],
1527 "<p><b>Some page\n</b></p>",
1530 'addWikiTextAsContent' => [
1531 // Preferred interface: output is tidied
1532 'SpecialNewimages' => [
1533 [ "<p lang='en' dir='ltr'>\nMy message" ],
1534 '<p lang="en" dir="ltr">' . "\nMy message\n</p>"
1535 ], 'List at start' => [
1537 "<ul><li>List</li></ul>\n",
1538 ], 'List not at start' => [
1539 [ '* <b>Not a list', false ],
1540 '<p>* <b>Not a list</b></p>',
1541 ], 'With title at start' => [
1542 [ '* {{PAGENAME}}', true, Title
::newFromText( 'Talk:Some page' ) ],
1543 "<ul><li>Some page</li></ul>\n",
1544 ], 'With title at start' => [
1545 [ '* {{PAGENAME}}', false, Title
::newFromText( 'Talk:Some page' ), false ],
1546 "<p>* Some page</p>",
1548 [ "<div class='mw-editintro'>{{PAGENAME}}", true, Title
::newFromText( 'Talk:Some page' ) ],
1549 '<div class="mw-editintro">' . "Some page\n</div>"
1552 'wrapWikiTextAsInterface' => [
1554 [ 'wrapperClass', 'text' ],
1555 "<div class=\"wrapperClass\"><p>text\n</p></div>"
1556 ], 'Spurious </div>' => [
1557 [ 'wrapperClass', 'text</div><div>more' ],
1558 "<div class=\"wrapperClass\"><p>text</p><div>more\n</div></div>"
1559 ], 'Extra newlines would break <p> wrappers' => [
1560 [ 'two classes', "1\n\n2\n\n3" ],
1561 "<div class=\"two classes\"><p>1\n</p><p>2\n</p><p>3\n</p></div>"
1562 ], 'Other unclosed tags' => [
1563 [ 'error', 'a<b>c<i>d' ],
1564 "<div class=\"error\"><p>a<b>c<i>d\n</i></b></p></div>"
1569 // Test all the others on addWikiTextTitle as well
1570 foreach ( $tests['addWikiText'] as $key => $val ) {
1571 $args = [ $val[0][0], null, $val[0][1] ??
true, false, $val[0][2] ??
true ];
1572 $tests['addWikiTextTitle']["$key (addWikiTextTitle)"] =
1573 array_merge( [ $args ], array_slice( $val, 1 ) );
1575 foreach ( $tests['addWikiTextWithTitle'] as $key => $val ) {
1576 $args = [ $val[0][0], $val[0][1], $val[0][2] ??
true ];
1577 $tests['addWikiTextTitle']["$key (addWikiTextTitle)"] =
1578 array_merge( [ $args ], array_slice( $val, 1 ) );
1580 foreach ( $tests['addWikiTextAsInterface'] as $key => $val ) {
1581 $args = [ $val[0][0], $val[0][2] ??
null, $val[0][1] ??
true, true, true ];
1582 $tests['addWikiTextTitle']["$key (addWikiTextTitle)"] =
1583 array_merge( [ $args ], array_slice( $val, 1 ) );
1585 foreach ( $tests['addWikiTextAsContent'] as $key => $val ) {
1586 $args = [ $val[0][0], $val[0][2] ??
null, $val[0][1] ??
true, true, false ];
1587 $tests['addWikiTextTitle']["$key (addWikiTextTitle)"] =
1588 array_merge( [ $args ], array_slice( $val, 1 ) );
1590 // addWikiTextTidy / addWikiTextTitleTidy were old aliases of
1591 // addWikiTextAsContent
1592 foreach ( $tests['addWikiTextAsContent'] as $key => $val ) {
1593 if ( count( $val[0] ) > 2 ) {
1594 $args = [ $val[0][0], $val[0][2], $val[0][1] ??
true ];
1595 $tests['addWikiTextTitleTidy']["$key (addWikiTextTitleTidy)"] =
1596 array_merge( [ $args ], array_slice( $val, 1 ) );
1598 $args = [ $val[0][0], $val[0][1] ??
true ];
1599 $tests['addWikiTextTidy']["$key (addWikiTextTidy)"] =
1600 array_merge( [ $args ], array_slice( $val, 1 ) );
1604 // We have to reformat our array to match what PHPUnit wants
1606 foreach ( $tests as $key => $subarray ) {
1607 foreach ( $subarray as $subkey => $val ) {
1608 $val = array_merge( [ $key ], $val );
1609 $ret[$subkey] = $val;
1617 * @covers OutputPage::addWikiText
1619 public function testAddWikiTextNoTitle() {
1620 $this->hideDeprecated( 'OutputPage::addWikiText' );
1621 $this->setExpectedException( MWException
::class, 'Title is null' );
1623 $op = $this->newInstance( [], null, 'notitle' );
1624 $op->addWikiText( 'a' );
1628 * @covers OutputPage::addWikiTextAsInterface
1630 public function testAddWikiTextAsInterfaceNoTitle() {
1631 $this->setExpectedException( MWException
::class, 'Title is null' );
1633 $op = $this->newInstance( [], null, 'notitle' );
1634 $op->addWikiTextAsInterface( 'a' );
1638 * @covers OutputPage::addWikiTextAsContent
1640 public function testAddWikiTextAsContentNoTitle() {
1641 $this->setExpectedException( MWException
::class, 'Title is null' );
1643 $op = $this->newInstance( [], null, 'notitle' );
1644 $op->addWikiTextAsContent( 'a' );
1648 * @covers OutputPage::addWikiMsg
1650 public function testAddWikiMsg() {
1651 $msg = wfMessage( 'parentheses' );
1652 $this->assertSame( '(a)', $msg->rawParams( 'a' )->plain() );
1654 $op = $this->newInstance();
1655 $this->assertSame( '', $op->getHTML() );
1656 $op->addWikiMsg( 'parentheses', "<b>a" );
1657 // The input is bad unbalanced HTML, but the output is tidied
1658 $this->assertSame( "<p>(<b>a)\n</b></p>", $op->getHTML() );
1662 * @covers OutputPage::wrapWikiMsg
1664 public function testWrapWikiMsg() {
1665 $msg = wfMessage( 'parentheses' );
1666 $this->assertSame( '(a)', $msg->rawParams( 'a' )->plain() );
1668 $op = $this->newInstance();
1669 $this->assertSame( '', $op->getHTML() );
1670 $op->wrapWikiMsg( '[$1]', [ 'parentheses', "<b>a" ] );
1671 // The input is bad unbalanced HTML, but the output is tidied
1672 $this->assertSame( "<p>[(<b>a)]\n</b></p>", $op->getHTML() );
1676 * @covers OutputPage::addParserOutputMetadata
1677 * @covers OutputPage::addParserOutput
1679 public function testNoGallery() {
1680 $op = $this->newInstance();
1681 $this->assertFalse( $op->mNoGallery
);
1683 $stubPO1 = $this->createParserOutputStub( 'getNoGallery', true );
1684 $op->addParserOutputMetadata( $stubPO1 );
1685 $this->assertTrue( $op->mNoGallery
);
1687 $stubPO2 = $this->createParserOutputStub( 'getNoGallery', false );
1688 $op->addParserOutput( $stubPO2 );
1689 $this->assertFalse( $op->mNoGallery
);
1692 private static $parserOutputHookCalled;
1695 * @covers OutputPage::addParserOutputMetadata
1697 public function testParserOutputHooks() {
1698 $op = $this->newInstance();
1699 $pOut = $this->createParserOutputStub( 'getOutputHooks', [
1700 [ 'myhook', 'banana' ],
1701 [ 'yourhook', 'kumquat' ],
1702 [ 'theirhook', 'hippopotamus' ],
1705 self
::$parserOutputHookCalled = [];
1707 $this->setMwGlobals( 'wgParserOutputHooks', [
1708 'myhook' => function ( OutputPage
$innerOp, ParserOutput
$innerPOut, $data )
1709 use ( $op, $pOut ) {
1710 $this->assertSame( $op, $innerOp );
1711 $this->assertSame( $pOut, $innerPOut );
1712 $this->assertSame( 'banana', $data );
1713 self
::$parserOutputHookCalled[] = 'closure';
1715 'yourhook' => [ $this, 'parserOutputHookCallback' ],
1716 'theirhook' => [ __CLASS__
, 'parserOutputHookCallbackStatic' ],
1717 'uncalled' => function () {
1718 $this->assertTrue( false );
1722 $op->addParserOutputMetadata( $pOut );
1724 $this->assertSame( [ 'closure', 'callback', 'static' ], self
::$parserOutputHookCalled );
1727 public function parserOutputHookCallback(
1728 OutputPage
$op, ParserOutput
$pOut, $data
1730 $this->assertSame( 'kumquat', $data );
1732 self
::$parserOutputHookCalled[] = 'callback';
1735 public static function parserOutputHookCallbackStatic(
1736 OutputPage
$op, ParserOutput
$pOut, $data
1738 // All the assert methods are actually static, who knew!
1739 self
::assertSame( 'hippopotamus', $data );
1741 self
::$parserOutputHookCalled[] = 'static';
1744 // @todo Make sure to test the following in addParserOutputMetadata() as well when we add tests
1747 // * addModuleScripts()
1748 // * addModuleStyles()
1749 // * addJsConfigVars()
1751 // Otherwise those lines of addParserOutputMetadata() will be reported as covered, but we won't
1752 // be testing they actually work.
1755 * @covers OutputPage::addParserOutputText
1757 public function testAddParserOutputText() {
1758 $op = $this->newInstance();
1759 $this->assertSame( '', $op->getHTML() );
1761 $pOut = $this->createParserOutputStub( 'getText', '<some text>' );
1763 $op->addParserOutputMetadata( $pOut );
1764 $this->assertSame( '', $op->getHTML() );
1766 $op->addParserOutputText( $pOut );
1767 $this->assertSame( '<some text>', $op->getHTML() );
1771 * @covers OutputPage::addParserOutput
1773 public function testAddParserOutput() {
1774 $op = $this->newInstance();
1775 $this->assertSame( '', $op->getHTML() );
1776 $this->assertFalse( $op->showNewSectionLink() );
1778 $pOut = $this->createParserOutputStub( [
1779 'getText' => '<some text>',
1780 'getNewSection' => true,
1783 $op->addParserOutput( $pOut );
1784 $this->assertSame( '<some text>', $op->getHTML() );
1785 $this->assertTrue( $op->showNewSectionLink() );
1789 * @covers OutputPage::addTemplate
1791 public function testAddTemplate() {
1792 $template = $this->getMock( QuickTemplate
::class );
1793 $template->method( 'getHTML' )->willReturn( '<abc>&def;' );
1795 $op = $this->newInstance();
1796 $op->addTemplate( $template );
1798 $this->assertSame( '<abc>&def;', $op->getHTML() );
1802 * @dataProvider provideParse
1803 * @covers OutputPage::parse
1804 * @param array $args To pass to parse()
1805 * @param string $expectedHTML Expected return value for parse()
1806 * @param string $expectedHTML Expected return value for parseInline(), if different
1808 public function testParse( array $args, $expectedHTML ) {
1809 $op = $this->newInstance();
1810 $this->assertSame( $expectedHTML, $op->parse( ...$args ) );
1814 * @dataProvider provideParse
1815 * @covers OutputPage::parseInline
1817 public function testParseInline( array $args, $expectedHTML, $expectedHTMLInline = null ) {
1818 if ( count( $args ) > 3 ) {
1819 // $language param not supported
1820 $this->assertTrue( true );
1823 $op = $this->newInstance();
1824 $this->assertSame( $expectedHTMLInline ??
$expectedHTML, $op->parseInline( ...$args ) );
1827 public function provideParse() {
1829 'List at start of line' => [
1831 "<div class=\"mw-parser-output\"><ul><li>List</li></ul>\n</div>",
1833 'List not at start' => [
1834 [ "* ''Not'' list", false ],
1835 '<div class="mw-parser-output">* <i>Not</i> list</div>',
1838 [ "''Italic''", true, true ],
1839 "<p><i>Italic</i>\n</p>",
1843 [ '{{formatnum:123456.789}}' ],
1844 "<div class=\"mw-parser-output\"><p>123,456.789\n</p></div>",
1847 [ '{{formatnum:123456.789}}', true, false, Language
::factory( 'is' ) ],
1848 "<div class=\"mw-parser-output\"><p>123.456,789\n</p></div>",
1850 'Language with interface' => [
1851 [ '{{formatnum:123456.789}}', true, true, Language
::factory( 'is' ) ],
1852 "<p>123.456,789\n</p>",
1855 'No section edit links' => [
1857 '<div class="mw-parser-output"><h2><span class="mw-headline" id="Header">' .
1858 "Header</span></h2>\n</div>",
1864 * @covers OutputPage::parse
1866 public function testParseNullTitle() {
1867 $this->setExpectedException( MWException
::class, 'Empty $mTitle in OutputPage::parse' );
1868 $op = $this->newInstance( [], null, 'notitle' );
1873 * @covers OutputPage::parse
1875 public function testParseInlineNullTitle() {
1876 $this->setExpectedException( MWException
::class, 'Empty $mTitle in OutputPage::parse' );
1877 $op = $this->newInstance( [], null, 'notitle' );
1878 $op->parseInline( '' );
1882 * @covers OutputPage::setCdnMaxage
1883 * @covers OutputPage::lowerCdnMaxage
1885 public function testCdnMaxage() {
1886 $op = $this->newInstance();
1887 $wrapper = TestingAccessWrapper
::newFromObject( $op );
1888 $this->assertSame( 0, $wrapper->mCdnMaxage
);
1890 $op->setCdnMaxage( -1 );
1891 $this->assertSame( -1, $wrapper->mCdnMaxage
);
1893 $op->setCdnMaxage( 120 );
1894 $this->assertSame( 120, $wrapper->mCdnMaxage
);
1896 $op->setCdnMaxage( 60 );
1897 $this->assertSame( 60, $wrapper->mCdnMaxage
);
1899 $op->setCdnMaxage( 180 );
1900 $this->assertSame( 180, $wrapper->mCdnMaxage
);
1902 $op->lowerCdnMaxage( 240 );
1903 $this->assertSame( 180, $wrapper->mCdnMaxage
);
1905 $op->setCdnMaxage( 300 );
1906 $this->assertSame( 240, $wrapper->mCdnMaxage
);
1908 $op->lowerCdnMaxage( 120 );
1909 $this->assertSame( 120, $wrapper->mCdnMaxage
);
1911 $op->setCdnMaxage( 180 );
1912 $this->assertSame( 120, $wrapper->mCdnMaxage
);
1914 $op->setCdnMaxage( 60 );
1915 $this->assertSame( 60, $wrapper->mCdnMaxage
);
1917 $op->setCdnMaxage( 240 );
1918 $this->assertSame( 120, $wrapper->mCdnMaxage
);
1921 /** @var int Faked time to set for tests that need it */
1922 private static $fakeTime;
1925 * @dataProvider provideAdaptCdnTTL
1926 * @covers OutputPage::adaptCdnTTL
1927 * @param array $args To pass to adaptCdnTTL()
1928 * @param int $expected Expected new value of mCdnMaxageLimit
1929 * @param array $options Associative array:
1930 * initialMaxage => Maxage to set before calling adaptCdnTTL() (default 86400)
1932 public function testAdaptCdnTTL( array $args, $expected, array $options = [] ) {
1934 MWTimestamp
::setFakeTime( self
::$fakeTime );
1936 $op = $this->newInstance();
1937 // Set a high maxage so that it will get reduced by adaptCdnTTL(). The default maxage
1938 // is 0, so adaptCdnTTL() won't mutate the object at all.
1939 $initial = $options['initialMaxage'] ??
86400;
1940 $op->setCdnMaxage( $initial );
1942 $op->adaptCdnTTL( ...$args );
1944 MWTimestamp
::setFakeTime( false );
1947 $wrapper = TestingAccessWrapper
::newFromObject( $op );
1949 // Special rules for false/null
1950 if ( $args[0] === null ||
$args[0] === false ) {
1951 $this->assertSame( $initial, $wrapper->mCdnMaxage
, 'member value' );
1952 $op->setCdnMaxage( $expected +
1 );
1953 $this->assertSame( $expected +
1, $wrapper->mCdnMaxage
, 'member value after new set' );
1957 $this->assertSame( $expected, $wrapper->mCdnMaxageLimit
, 'limit value' );
1959 if ( $initial >= $expected ) {
1960 $this->assertSame( $expected, $wrapper->mCdnMaxage
, 'member value' );
1962 $this->assertSame( $initial, $wrapper->mCdnMaxage
, 'member value' );
1965 $op->setCdnMaxage( $expected +
1 );
1966 $this->assertSame( $expected, $wrapper->mCdnMaxage
, 'member value after new set' );
1969 public function provideAdaptCdnTTL() {
1970 global $wgSquidMaxage;
1972 self
::$fakeTime = $now;
1974 'Five minutes ago' => [ [ $now - 300 ], 270 ],
1975 'Now' => [ [ +
0 ], IExpiringStore
::TTL_MINUTE
],
1976 'Five minutes from now' => [ [ $now +
300 ], IExpiringStore
::TTL_MINUTE
],
1977 'Five minutes ago, initial maxage four minutes' =>
1978 [ [ $now - 300 ], 270, [ 'initialMaxage' => 240 ] ],
1979 'A very long time ago' => [ [ $now - 1000000000 ], $wgSquidMaxage ],
1980 'Initial maxage zero' => [ [ $now - 300 ], 270, [ 'initialMaxage' => 0 ] ],
1982 'false' => [ [ false ], IExpiringStore
::TTL_MINUTE
],
1983 'null' => [ [ null ], IExpiringStore
::TTL_MINUTE
],
1984 "'0'" => [ [ '0' ], IExpiringStore
::TTL_MINUTE
],
1985 'Empty string' => [ [ '' ], IExpiringStore
::TTL_MINUTE
],
1986 // @todo These give incorrect results due to timezones, how to test?
1987 //"'now'" => [ [ 'now' ], IExpiringStore::TTL_MINUTE ],
1988 //"'parse error'" => [ [ 'parse error' ], IExpiringStore::TTL_MINUTE ],
1990 'Now, minTTL 0' => [ [ $now, 0 ], IExpiringStore
::TTL_MINUTE
],
1991 'Now, minTTL 0.000001' => [ [ $now, 0.000001 ], 0 ],
1992 'A very long time ago, maxTTL even longer' =>
1993 [ [ $now - 1000000000, 0, 1000000001 ], 900000000 ],
1998 * @covers OutputPage::enableClientCache
1999 * @covers OutputPage::addParserOutputMetadata
2000 * @covers OutputPage::addParserOutput
2002 public function testClientCache() {
2003 $op = $this->newInstance();
2005 // Test initial value
2006 $this->assertSame( true, $op->enableClientCache( null ) );
2007 // Test that calling with null doesn't change the value
2008 $this->assertSame( true, $op->enableClientCache( null ) );
2010 // Test setting to false
2011 $this->assertSame( true, $op->enableClientCache( false ) );
2012 $this->assertSame( false, $op->enableClientCache( null ) );
2013 // Test that calling with null doesn't change the value
2014 $this->assertSame( false, $op->enableClientCache( null ) );
2016 // Test that a cacheable ParserOutput doesn't set to true
2017 $pOutCacheable = $this->createParserOutputStub( 'isCacheable', true );
2018 $op->addParserOutputMetadata( $pOutCacheable );
2019 $this->assertSame( false, $op->enableClientCache( null ) );
2021 // Test setting back to true
2022 $this->assertSame( false, $op->enableClientCache( true ) );
2023 $this->assertSame( true, $op->enableClientCache( null ) );
2025 // Test that an uncacheable ParserOutput does set to false
2026 $pOutUncacheable = $this->createParserOutputStub( 'isCacheable', false );
2027 $op->addParserOutput( $pOutUncacheable );
2028 $this->assertSame( false, $op->enableClientCache( null ) );
2032 * @covers OutputPage::getCacheVaryCookies
2034 public function testGetCacheVaryCookies() {
2035 global $wgCookiePrefix, $wgDBname;
2036 $op = $this->newInstance();
2037 $prefix = $wgCookiePrefix !== false ?
$wgCookiePrefix : $wgDBname;
2038 $expectedCookies = [
2040 "{$prefix}LoggedOut",
2041 "{$prefix}_session",
2047 // We have to reset the cookies because getCacheVaryCookies may have already been called
2048 TestingAccessWrapper
::newFromClass( OutputPage
::class )->cacheVaryCookies
= null;
2050 $this->setMwGlobals( 'wgCacheVaryCookies', [ 'cookie1' ] );
2051 $this->setTemporaryHook( 'GetCacheVaryCookies',
2052 function ( $innerOP, &$cookies ) use ( $op, $expectedCookies ) {
2053 $this->assertSame( $op, $innerOP );
2054 $cookies[] = 'cookie2';
2055 $this->assertSame( $expectedCookies, $cookies );
2059 $this->assertSame( $expectedCookies, $op->getCacheVaryCookies() );
2063 * @covers OutputPage::haveCacheVaryCookies
2065 public function testHaveCacheVaryCookies() {
2066 $request = new FauxRequest();
2067 $op = $this->newInstance( [], $request );
2069 // No cookies are set.
2070 $this->assertFalse( $op->haveCacheVaryCookies() );
2072 // 'Token' is present but empty, so it shouldn't count.
2073 $request->setCookie( 'Token', '' );
2074 $this->assertFalse( $op->haveCacheVaryCookies() );
2076 // 'Token' present and nonempty.
2077 $request->setCookie( 'Token', '123' );
2078 $this->assertTrue( $op->haveCacheVaryCookies() );
2082 * @dataProvider provideVaryHeaders
2084 * @covers OutputPage::addVaryHeader
2085 * @covers OutputPage::getVaryHeader
2086 * @covers OutputPage::getKeyHeader
2088 * @param array[] $calls For each array, call addVaryHeader() with those arguments
2089 * @param string[] $cookies Array of cookie names to vary on
2090 * @param string $vary Text of expected Vary header (including the 'Vary: ')
2091 * @param string $key Text of expected Key header (including the 'Key: ')
2093 public function testVaryHeaders( array $calls, array $cookies, $vary, $key ) {
2094 // Get rid of default Vary fields
2095 $op = $this->getMockBuilder( OutputPage
::class )
2096 ->setConstructorArgs( [ new RequestContext() ] )
2097 ->setMethods( [ 'getCacheVaryCookies' ] )
2099 $op->expects( $this->any() )
2100 ->method( 'getCacheVaryCookies' )
2101 ->will( $this->returnValue( $cookies ) );
2102 TestingAccessWrapper
::newFromObject( $op )->mVaryHeader
= [];
2104 $this->hideDeprecated( '$wgUseKeyHeader' );
2105 foreach ( $calls as $call ) {
2106 $op->addVaryHeader( ...$call );
2108 $this->assertEquals( $vary, $op->getVaryHeader(), 'Vary:' );
2109 $this->assertEquals( $key, $op->getKeyHeader(), 'Key:' );
2112 public function provideVaryHeaders() {
2113 // note: getKeyHeader() automatically adds Vary: Cookie
2121 'Single header' => [
2129 'Non-unique headers' => [
2132 [ 'Accept-Language' ],
2136 'Vary: Cookie, Accept-Language',
2137 'Key: Cookie,Accept-Language',
2139 'Two headers with single options' => [
2141 [ 'Cookie', [ 'param=phpsessid' ] ],
2142 [ 'Accept-Language', [ 'substr=en' ] ],
2145 'Vary: Cookie, Accept-Language',
2146 'Key: Cookie;param=phpsessid,Accept-Language;substr=en',
2148 'One header with multiple options' => [
2150 [ 'Cookie', [ 'param=phpsessid', 'param=userId' ] ],
2154 'Key: Cookie;param=phpsessid;param=userId',
2156 'Duplicate option' => [
2158 [ 'Cookie', [ 'param=phpsessid' ] ],
2159 [ 'Cookie', [ 'param=phpsessid' ] ],
2160 [ 'Accept-Language', [ 'substr=en', 'substr=en' ] ],
2163 'Vary: Cookie, Accept-Language',
2164 'Key: Cookie;param=phpsessid,Accept-Language;substr=en',
2166 'Same header, different options' => [
2168 [ 'Cookie', [ 'param=phpsessid' ] ],
2169 [ 'Cookie', [ 'param=userId' ] ],
2173 'Key: Cookie;param=phpsessid;param=userId',
2175 'No header, vary cookies' => [
2177 [ 'cookie1', 'cookie2' ],
2179 'Key: Cookie;param=cookie1;param=cookie2',
2181 'Cookie header with option plus vary cookies' => [
2183 [ 'Cookie', [ 'param=cookie1' ] ],
2185 [ 'cookie2', 'cookie3' ],
2187 'Key: Cookie;param=cookie1;param=cookie2;param=cookie3',
2189 'Non-cookie header plus vary cookies' => [
2191 [ 'Accept-Language' ],
2194 'Vary: Accept-Language, Cookie',
2195 'Key: Accept-Language,Cookie;param=cookie',
2197 'Cookie and non-cookie headers plus vary cookies' => [
2199 [ 'Cookie', [ 'param=cookie1' ] ],
2200 [ 'Accept-Language' ],
2203 'Vary: Cookie, Accept-Language',
2204 'Key: Cookie;param=cookie1;param=cookie2,Accept-Language',
2210 * @covers OutputPage::getVaryHeader
2212 public function testVaryHeaderDefault() {
2213 $op = $this->newInstance();
2214 $this->assertSame( 'Vary: Accept-Encoding, Cookie', $op->getVaryHeader() );
2218 * @dataProvider provideLinkHeaders
2220 * @covers OutputPage::addLinkHeader
2221 * @covers OutputPage::getLinkHeader
2223 public function testLinkHeaders( array $headers, $result ) {
2224 $op = $this->newInstance();
2226 foreach ( $headers as $header ) {
2227 $op->addLinkHeader( $header );
2230 $this->assertEquals( $result, $op->getLinkHeader() );
2233 public function provideLinkHeaders() {
2240 [ '<https://foo/bar.jpg>;rel=preload;as=image' ],
2241 'Link: <https://foo/bar.jpg>;rel=preload;as=image',
2245 '<https://foo/bar.jpg>;rel=preload;as=image',
2246 '<https://foo/baz.jpg>;rel=preload;as=image'
2248 'Link: <https://foo/bar.jpg>;rel=preload;as=image,<https://foo/baz.jpg>;' .
2249 'rel=preload;as=image',
2255 * @dataProvider provideAddAcceptLanguage
2256 * @covers OutputPage::addAcceptLanguage
2257 * @covers OutputPage::getKeyHeader
2259 public function testAddAcceptLanguage(
2260 $code, array $variants, array $expected, array $options = []
2262 $req = new FauxRequest( in_array( 'varianturl', $options ) ?
[ 'variant' => 'x' ] : [] );
2263 $op = $this->newInstance( [], $req, in_array( 'notitle', $options ) ?
'notitle' : null );
2265 if ( !in_array( 'notitle', $options ) ) {
2266 $mockLang = $this->getMock( Language
::class );
2268 if ( in_array( 'varianturl', $options ) ) {
2269 $mockLang->expects( $this->never() )->method( $this->anything() );
2271 $mockLang->method( 'hasVariants' )->willReturn( count( $variants ) > 1 );
2272 $mockLang->method( 'getVariants' )->willReturn( $variants );
2273 $mockLang->method( 'getCode' )->willReturn( $code );
2276 $mockTitle = $this->getMock( Title
::class );
2277 $mockTitle->method( 'getPageLanguage' )->willReturn( $mockLang );
2279 $op->setTitle( $mockTitle );
2282 // This will run addAcceptLanguage()
2283 $op->sendCacheControl();
2285 $this->hideDeprecated( '$wgUseKeyHeader' );
2286 $keyHeader = $op->getKeyHeader();
2289 $this->assertFalse( strpos( 'Accept-Language', $keyHeader ) );
2293 $keyHeader = explode( ' ', $keyHeader, 2 )[1];
2294 $keyHeader = explode( ',', $keyHeader );
2296 $acceptLanguage = null;
2297 foreach ( $keyHeader as $item ) {
2298 if ( strpos( $item, 'Accept-Language;' ) === 0 ) {
2299 $acceptLanguage = $item;
2304 $expectedString = 'Accept-Language;substr=' . implode( ';substr=', $expected );
2305 $this->assertSame( $expectedString, $acceptLanguage );
2308 public function provideAddAcceptLanguage() {
2310 'No variants' => [ 'en', [ 'en' ], [] ],
2311 'One simple variant' => [ 'en', [ 'en', 'en-x-piglatin' ], [ 'en-x-piglatin' ] ],
2312 'Multiple variants with BCP47 alternatives' => [
2314 [ 'zh', 'zh-hans', 'zh-cn', 'zh-tw' ],
2315 [ 'zh-hans', 'zh-Hans', 'zh-cn', 'zh-Hans-CN', 'zh-tw', 'zh-Hant-TW' ],
2317 'No title' => [ 'en', [ 'en', 'en-x-piglatin' ], [], [ 'notitle' ] ],
2318 'Variant in URL' => [ 'en', [ 'en', 'en-x-piglatin' ], [], [ 'varianturl' ] ],
2323 * @covers OutputPage::preventClickjacking
2324 * @covers OutputPage::allowClickjacking
2325 * @covers OutputPage::getPreventClickjacking
2326 * @covers OutputPage::addParserOutputMetadata
2327 * @covers OutputPage::addParserOutput
2329 public function testClickjacking() {
2330 $op = $this->newInstance();
2331 $this->assertTrue( $op->getPreventClickjacking() );
2333 $op->allowClickjacking();
2334 $this->assertFalse( $op->getPreventClickjacking() );
2336 $op->preventClickjacking();
2337 $this->assertTrue( $op->getPreventClickjacking() );
2339 $op->preventClickjacking( false );
2340 $this->assertFalse( $op->getPreventClickjacking() );
2342 $pOut1 = $this->createParserOutputStub( 'preventClickjacking', true );
2343 $op->addParserOutputMetadata( $pOut1 );
2344 $this->assertTrue( $op->getPreventClickjacking() );
2346 // The ParserOutput can't allow, only prevent
2347 $pOut2 = $this->createParserOutputStub( 'preventClickjacking', false );
2348 $op->addParserOutputMetadata( $pOut2 );
2349 $this->assertTrue( $op->getPreventClickjacking() );
2351 // Reset to test with addParserOutput()
2352 $op->allowClickjacking();
2353 $this->assertFalse( $op->getPreventClickjacking() );
2355 $op->addParserOutput( $pOut1 );
2356 $this->assertTrue( $op->getPreventClickjacking() );
2358 $op->addParserOutput( $pOut2 );
2359 $this->assertTrue( $op->getPreventClickjacking() );
2363 * @dataProvider provideGetFrameOptions
2364 * @covers OutputPage::getFrameOptions
2365 * @covers OutputPage::preventClickjacking
2367 public function testGetFrameOptions(
2368 $breakFrames, $preventClickjacking, $editPageFrameOptions, $expected
2370 $op = $this->newInstance( [
2371 'BreakFrames' => $breakFrames,
2372 'EditPageFrameOptions' => $editPageFrameOptions,
2374 $op->preventClickjacking( $preventClickjacking );
2376 $this->assertSame( $expected, $op->getFrameOptions() );
2379 public function provideGetFrameOptions() {
2381 'BreakFrames true' => [ true, false, false, 'DENY' ],
2382 'Allow clickjacking locally' => [ false, false, 'DENY', false ],
2383 'Allow clickjacking globally' => [ false, true, false, false ],
2384 'DENY globally' => [ false, true, 'DENY', 'DENY' ],
2385 'SAMEORIGIN' => [ false, true, 'SAMEORIGIN', 'SAMEORIGIN' ],
2386 'BreakFrames with SAMEORIGIN' => [ true, true, 'SAMEORIGIN', 'DENY' ],
2391 * See ResourceLoaderClientHtmlTest for full coverage.
2393 * @dataProvider provideMakeResourceLoaderLink
2395 * @covers OutputPage::makeResourceLoaderLink
2397 public function testMakeResourceLoaderLink( $args, $expectedHtml ) {
2398 $this->setMwGlobals( [
2399 'wgResourceLoaderDebug' => false,
2400 'wgLoadScript' => 'http://127.0.0.1:8080/w/load.php',
2401 'wgCSPReportOnlyHeader' => true,
2403 $class = new ReflectionClass( OutputPage
::class );
2404 $method = $class->getMethod( 'makeResourceLoaderLink' );
2405 $method->setAccessible( true );
2406 $ctx = new RequestContext();
2407 $ctx->setSkin( SkinFactory
::getDefaultInstance()->makeSkin( 'fallback' ) );
2408 $ctx->setLanguage( 'en' );
2409 $out = new OutputPage( $ctx );
2410 $nonce = $class->getProperty( 'CSPNonce' );
2411 $nonce->setAccessible( true );
2412 $nonce->setValue( $out, 'secret' );
2413 $rl = $out->getResourceLoader();
2414 $rl->setMessageBlobStore( new NullMessageBlobStore() );
2416 'test.foo' => new ResourceLoaderTestModule( [
2417 'script' => 'mw.test.foo( { a: true } );',
2418 'styles' => '.mw-test-foo { content: "style"; }',
2420 'test.bar' => new ResourceLoaderTestModule( [
2421 'script' => 'mw.test.bar( { a: true } );',
2422 'styles' => '.mw-test-bar { content: "style"; }',
2424 'test.baz' => new ResourceLoaderTestModule( [
2425 'script' => 'mw.test.baz( { a: true } );',
2426 'styles' => '.mw-test-baz { content: "style"; }',
2428 'test.quux' => new ResourceLoaderTestModule( [
2429 'script' => 'mw.test.baz( { token: 123 } );',
2430 'styles' => '/* pref-animate=off */ .mw-icon { transition: none; }',
2431 'group' => 'private',
2433 'test.noscript' => new ResourceLoaderTestModule( [
2434 'styles' => '.stuff { color: red; }',
2435 'group' => 'noscript',
2437 'test.group.foo' => new ResourceLoaderTestModule( [
2438 'script' => 'mw.doStuff( "foo" );',
2441 'test.group.bar' => new ResourceLoaderTestModule( [
2442 'script' => 'mw.doStuff( "bar" );',
2446 $links = $method->invokeArgs( $out, $args );
2447 $actualHtml = strval( $links );
2448 $this->assertEquals( $expectedHtml, $actualHtml );
2451 public static function provideMakeResourceLoaderLink() {
2452 // phpcs:disable Generic.Files.LineLength
2454 // Single only=scripts load
2456 [ 'test.foo', ResourceLoaderModule
::TYPE_SCRIPTS
],
2457 "<script nonce=\"secret\">(window.RLQ=window.RLQ||[]).push(function(){"
2458 . 'mw.loader.load("http://127.0.0.1:8080/w/load.php?debug=false\u0026lang=en\u0026modules=test.foo\u0026only=scripts\u0026skin=fallback");'
2461 // Multiple only=styles load
2463 [ [ 'test.baz', 'test.foo', 'test.bar' ], ResourceLoaderModule
::TYPE_STYLES
],
2465 '<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"/>'
2467 // Private embed (only=scripts)
2469 [ 'test.quux', ResourceLoaderModule
::TYPE_SCRIPTS
],
2470 "<script nonce=\"secret\">(window.RLQ=window.RLQ||[]).push(function(){"
2471 . "mw.test.baz({token:123});\nmw.loader.state({\"test.quux\":\"ready\"});"
2474 // Load private module (combined)
2476 [ 'test.quux', ResourceLoaderModule
::TYPE_COMBINED
],
2477 "<script nonce=\"secret\">(window.RLQ=window.RLQ||[]).push(function(){"
2478 . "mw.loader.implement(\"test.quux@1ev0ijv\",function($,jQuery,require,module){"
2479 . "mw.test.baz({token:123});},{\"css\":[\".mw-icon{transition:none}"
2480 . "\"]});});</script>"
2484 [ [], ResourceLoaderModule
::TYPE_COMBINED
],
2489 [ 'test.noscript', ResourceLoaderModule
::TYPE_STYLES
],
2490 '<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>'
2492 // Load two modules in separate groups
2494 [ [ 'test.group.foo', 'test.group.bar' ], ResourceLoaderModule
::TYPE_COMBINED
],
2495 "<script nonce=\"secret\">(window.RLQ=window.RLQ||[]).push(function(){"
2496 . 'mw.loader.load("http://127.0.0.1:8080/w/load.php?debug=false\u0026lang=en\u0026modules=test.group.bar\u0026skin=fallback");'
2497 . 'mw.loader.load("http://127.0.0.1:8080/w/load.php?debug=false\u0026lang=en\u0026modules=test.group.foo\u0026skin=fallback");'
2505 * @dataProvider provideBuildExemptModules
2507 * @covers OutputPage::buildExemptModules
2509 public function testBuildExemptModules( array $exemptStyleModules, $expect ) {
2510 $this->setMwGlobals( [
2511 'wgResourceLoaderDebug' => false,
2512 'wgLoadScript' => '/w/load.php',
2513 // Stub wgCacheEpoch as it influences getVersionHash used for the
2514 // urls in the expected HTML
2515 'wgCacheEpoch' => '20140101000000',
2519 $ctx = new RequestContext();
2520 $ctx->setSkin( SkinFactory
::getDefaultInstance()->makeSkin( 'fallback' ) );
2521 $ctx->setLanguage( 'en' );
2522 $op = $this->getMockBuilder( OutputPage
::class )
2523 ->setConstructorArgs( [ $ctx ] )
2524 ->setMethods( [ 'buildCssLinksArray' ] )
2526 $op->expects( $this->any() )
2527 ->method( 'buildCssLinksArray' )
2529 $rl = $op->getResourceLoader();
2530 $rl->setMessageBlobStore( new NullMessageBlobStore() );
2532 // Register custom modules
2534 'example.site.a' => new ResourceLoaderTestModule( [ 'group' => 'site' ] ),
2535 'example.site.b' => new ResourceLoaderTestModule( [ 'group' => 'site' ] ),
2536 'example.user' => new ResourceLoaderTestModule( [ 'group' => 'user' ] ),
2539 $op = TestingAccessWrapper
::newFromObject( $op );
2540 $op->rlExemptStyleModules
= $exemptStyleModules;
2541 $this->assertEquals(
2543 strval( $op->buildExemptModules() )
2547 public static function provideBuildExemptModules() {
2548 // phpcs:disable Generic.Files.LineLength
2551 'exemptStyleModules' => [],
2552 '<meta name="ResourceLoaderDynamicStyles" content=""/>',
2555 'exemptStyleModules' => [ 'site' => [], 'noscript' => [], 'private' => [], 'user' => [] ],
2556 '<meta name="ResourceLoaderDynamicStyles" content=""/>',
2558 'default logged-out' => [
2559 'exemptStyleModules' => [ 'site' => [ 'site.styles' ] ],
2560 '<meta name="ResourceLoaderDynamicStyles" content=""/>' . "\n" .
2561 '<link rel="stylesheet" href="/w/load.php?debug=false&lang=en&modules=site.styles&only=styles&skin=fallback"/>',
2563 'default logged-in' => [
2564 'exemptStyleModules' => [ 'site' => [ 'site.styles' ], 'user' => [ 'user.styles' ] ],
2565 '<meta name="ResourceLoaderDynamicStyles" content=""/>' . "\n" .
2566 '<link rel="stylesheet" href="/w/load.php?debug=false&lang=en&modules=site.styles&only=styles&skin=fallback"/>' . "\n" .
2567 '<link rel="stylesheet" href="/w/load.php?debug=false&lang=en&modules=user.styles&only=styles&skin=fallback&version=1ai9g6t"/>',
2569 'custom modules' => [
2570 'exemptStyleModules' => [
2571 'site' => [ 'site.styles', 'example.site.a', 'example.site.b' ],
2572 'user' => [ 'user.styles', 'example.user' ],
2574 '<meta name="ResourceLoaderDynamicStyles" content=""/>' . "\n" .
2575 '<link rel="stylesheet" href="/w/load.php?debug=false&lang=en&modules=example.site.a%2Cb&only=styles&skin=fallback"/>' . "\n" .
2576 '<link rel="stylesheet" href="/w/load.php?debug=false&lang=en&modules=site.styles&only=styles&skin=fallback"/>' . "\n" .
2577 '<link rel="stylesheet" href="/w/load.php?debug=false&lang=en&modules=example.user&only=styles&skin=fallback&version=0a56zyi"/>' . "\n" .
2578 '<link rel="stylesheet" href="/w/load.php?debug=false&lang=en&modules=user.styles&only=styles&skin=fallback&version=1ai9g6t"/>',
2585 * @dataProvider provideTransformFilePath
2586 * @covers OutputPage::transformFilePath
2587 * @covers OutputPage::transformResourcePath
2589 public function testTransformResourcePath( $baseDir, $basePath, $uploadDir = null,
2590 $uploadPath = null, $path = null, $expected = null
2592 if ( $path === null ) {
2593 // Skip optional $uploadDir and $uploadPath
2595 $expected = $uploadPath;
2596 $uploadDir = "$baseDir/images";
2597 $uploadPath = "$basePath/images";
2599 $this->setMwGlobals( 'IP', $baseDir );
2600 $conf = new HashConfig( [
2601 'ResourceBasePath' => $basePath,
2602 'UploadDirectory' => $uploadDir,
2603 'UploadPath' => $uploadPath,
2606 // Some of these paths don't exist and will cause warnings
2607 Wikimedia\
suppressWarnings();
2608 $actual = OutputPage
::transformResourcePath( $conf, $path );
2609 Wikimedia\restoreWarnings
();
2611 $this->assertEquals( $expected ?
: $path, $actual );
2614 public static function provideTransformFilePath() {
2615 $baseDir = dirname( __DIR__
) . '/data/media';
2617 // File that matches basePath, and exists. Hash found and appended.
2619 'baseDir' => $baseDir, 'basePath' => '/w',
2623 // File that matches basePath, but not found on disk. Empty query.
2625 'baseDir' => $baseDir, 'basePath' => '/w',
2629 // File not matching basePath. Ignored.
2631 'baseDir' => $baseDir, 'basePath' => '/w',
2634 // Empty string. Ignored.
2636 'baseDir' => $baseDir, 'basePath' => '/w',
2640 // Similar path, but with domain component. Ignored.
2642 'baseDir' => $baseDir, 'basePath' => '/w',
2643 '//example.org/w/test.jpg'
2646 'baseDir' => $baseDir, 'basePath' => '/w',
2647 'https://example.org/w/test.jpg'
2649 // Unrelated path with domain component. Ignored.
2651 'baseDir' => $baseDir, 'basePath' => '/w',
2652 'https://example.org/files/test.jpg'
2655 'baseDir' => $baseDir, 'basePath' => '/w',
2656 '//example.org/files/test.jpg'
2658 // Unrelated path with domain, and empty base path (root mw install). Ignored.
2660 'baseDir' => $baseDir, 'basePath' => '',
2661 'https://example.org/files/test.jpg'
2664 'baseDir' => $baseDir, 'basePath' => '',
2666 '//example.org/files/test.jpg'
2668 // Check UploadPath before ResourceBasePath (T155146)
2670 'baseDir' => dirname( $baseDir ), 'basePath' => '',
2671 'uploadDir' => $baseDir, 'uploadPath' => '/images',
2673 '/images/test.jpg?edcf2'
2679 * Tests a particular case of transformCssMedia, using the given input, globals,
2680 * expected return, and message
2682 * Asserts that $expectedReturn is returned.
2684 * options['printableQuery'] - value of query string for printable, or omitted for none
2685 * options['handheldQuery'] - value of query string for handheld, or omitted for none
2686 * options['media'] - passed into the method under the same name
2687 * options['expectedReturn'] - expected return value
2688 * options['message'] - PHPUnit message for assertion
2690 * @param array $args Key-value array of arguments as shown above
2692 protected function assertTransformCssMediaCase( $args ) {
2694 if ( isset( $args['printableQuery'] ) ) {
2695 $queryData['printable'] = $args['printableQuery'];
2698 if ( isset( $args['handheldQuery'] ) ) {
2699 $queryData['handheld'] = $args['handheldQuery'];
2702 $fauxRequest = new FauxRequest( $queryData, false );
2703 $this->setMwGlobals( [
2704 'wgRequest' => $fauxRequest,
2707 $actualReturn = OutputPage
::transformCssMedia( $args['media'] );
2708 $this->assertSame( $args['expectedReturn'], $actualReturn, $args['message'] );
2712 * Tests print requests
2714 * @covers OutputPage::transformCssMedia
2716 public function testPrintRequests() {
2717 $this->assertTransformCssMediaCase( [
2718 'printableQuery' => '1',
2719 'media' => 'screen',
2720 'expectedReturn' => null,
2721 'message' => 'On printable request, screen returns null'
2724 $this->assertTransformCssMediaCase( [
2725 'printableQuery' => '1',
2726 'media' => self
::SCREEN_MEDIA_QUERY
,
2727 'expectedReturn' => null,
2728 'message' => 'On printable request, screen media query returns null'
2731 $this->assertTransformCssMediaCase( [
2732 'printableQuery' => '1',
2733 'media' => self
::SCREEN_ONLY_MEDIA_QUERY
,
2734 'expectedReturn' => null,
2735 'message' => 'On printable request, screen media query with only returns null'
2738 $this->assertTransformCssMediaCase( [
2739 'printableQuery' => '1',
2741 'expectedReturn' => '',
2742 'message' => 'On printable request, media print returns empty string'
2747 * Tests screen requests, without either query parameter set
2749 * @covers OutputPage::transformCssMedia
2751 public function testScreenRequests() {
2752 $this->assertTransformCssMediaCase( [
2753 'media' => 'screen',
2754 'expectedReturn' => 'screen',
2755 'message' => 'On screen request, screen media type is preserved'
2758 $this->assertTransformCssMediaCase( [
2759 'media' => 'handheld',
2760 'expectedReturn' => 'handheld',
2761 'message' => 'On screen request, handheld media type is preserved'
2764 $this->assertTransformCssMediaCase( [
2765 'media' => self
::SCREEN_MEDIA_QUERY
,
2766 'expectedReturn' => self
::SCREEN_MEDIA_QUERY
,
2767 'message' => 'On screen request, screen media query is preserved.'
2770 $this->assertTransformCssMediaCase( [
2771 'media' => self
::SCREEN_ONLY_MEDIA_QUERY
,
2772 'expectedReturn' => self
::SCREEN_ONLY_MEDIA_QUERY
,
2773 'message' => 'On screen request, screen media query with only is preserved.'
2776 $this->assertTransformCssMediaCase( [
2778 'expectedReturn' => 'print',
2779 'message' => 'On screen request, print media type is preserved'
2784 * Tests handheld behavior
2786 * @covers OutputPage::transformCssMedia
2788 public function testHandheld() {
2789 $this->assertTransformCssMediaCase( [
2790 'handheldQuery' => '1',
2791 'media' => 'handheld',
2792 'expectedReturn' => '',
2793 'message' => 'On request with handheld querystring and media is handheld, returns empty string'
2796 $this->assertTransformCssMediaCase( [
2797 'handheldQuery' => '1',
2798 'media' => 'screen',
2799 'expectedReturn' => null,
2800 'message' => 'On request with handheld querystring and media is screen, returns null'
2805 * @covers OutputPage::isTOCEnabled
2806 * @covers OutputPage::addParserOutputMetadata
2807 * @covers OutputPage::addParserOutput
2809 public function testIsTOCEnabled() {
2810 $op = $this->newInstance();
2811 $this->assertFalse( $op->isTOCEnabled() );
2813 $pOut1 = $this->createParserOutputStub( 'getTOCHTML', false );
2814 $op->addParserOutputMetadata( $pOut1 );
2815 $this->assertFalse( $op->isTOCEnabled() );
2817 $pOut2 = $this->createParserOutputStub( 'getTOCHTML', true );
2818 $op->addParserOutput( $pOut2 );
2819 $this->assertTrue( $op->isTOCEnabled() );
2821 // The parser output doesn't disable the TOC after it was enabled
2822 $op->addParserOutputMetadata( $pOut1 );
2823 $this->assertTrue( $op->isTOCEnabled() );
2827 * @dataProvider providePreloadLinkHeaders
2828 * @covers ResourceLoaderSkinModule::getPreloadLinks
2829 * @covers ResourceLoaderSkinModule::getLogoPreloadlinks
2831 public function testPreloadLinkHeaders( $config, $result ) {
2832 $this->setMwGlobals( $config );
2833 $ctx = $this->getMockBuilder( ResourceLoaderContext
::class )
2834 ->disableOriginalConstructor()->getMock();
2835 $module = new ResourceLoaderSkinModule();
2837 $this->assertEquals( [ $result ], $module->getHeaders( $ctx ) );
2840 public function providePreloadLinkHeaders() {
2844 'wgResourceBasePath' => '/w',
2845 'wgLogo' => '/img/default.png',
2847 '1.5x' => '/img/one-point-five.png',
2848 '2x' => '/img/two-x.png',
2851 'Link: </img/default.png>;rel=preload;as=image;media=' .
2852 'not all and (min-resolution: 1.5dppx),' .
2853 '</img/one-point-five.png>;rel=preload;as=image;media=' .
2854 '(min-resolution: 1.5dppx) and (max-resolution: 1.999999dppx),' .
2855 '</img/two-x.png>;rel=preload;as=image;media=(min-resolution: 2dppx)'
2859 'wgResourceBasePath' => '/w',
2860 'wgLogo' => '/img/default.png',
2861 'wgLogoHD' => false,
2863 'Link: </img/default.png>;rel=preload;as=image'
2867 'wgResourceBasePath' => '/w',
2868 'wgLogo' => '/img/default.png',
2870 '2x' => '/img/two-x.png',
2873 'Link: </img/default.png>;rel=preload;as=image;media=' .
2874 'not all and (min-resolution: 2dppx),' .
2875 '</img/two-x.png>;rel=preload;as=image;media=(min-resolution: 2dppx)'
2879 'wgResourceBasePath' => '/w',
2880 'wgLogo' => '/img/default.png',
2882 'svg' => '/img/vector.svg',
2885 'Link: </img/vector.svg>;rel=preload;as=image'
2890 'wgResourceBasePath' => '/w',
2891 'wgLogo' => '/w/test.jpg',
2892 'wgLogoHD' => false,
2893 'wgUploadPath' => '/w/images',
2894 'IP' => dirname( __DIR__
) . '/data/media',
2896 'Link: </w/test.jpg?edcf2>;rel=preload;as=image',
2902 * @return OutputPage
2904 private function newInstance( $config = [], WebRequest
$request = null, $options = [] ) {
2905 $context = new RequestContext();
2907 $context->setConfig( new MultiConfig( [
2908 new HashConfig( $config +
[
2909 'AppleTouchIcon' => false,
2910 'DisableLangConversion' => true,
2911 'EnableCanonicalServerLink' => false,
2914 'LanguageCode' => false,
2915 'ReferrerPolicy' => false,
2916 'RightsPage' => false,
2917 'RightsUrl' => false,
2918 'UniversalEditButton' => false,
2920 $context->getConfig()
2923 if ( !in_array( 'notitle', (array)$options ) ) {
2924 $context->setTitle( Title
::newFromText( 'My test page' ) );
2928 $context->setRequest( $request );
2931 return new OutputPage( $context );
2936 * MessageBlobStore that doesn't do anything
2938 class NullMessageBlobStore
extends MessageBlobStore
{
2939 public function get( ResourceLoader
$resourceLoader, $modules, $lang ) {
2943 public function updateModule( $name, ResourceLoaderModule
$module, $lang ) {
2946 public function updateMessage( $key ) {
2949 public function clear() {