3 use Wikimedia\TestingAccessWrapper
;
6 * @author Matthew Flaschen
11 class OutputPageTest
extends MediaWikiTestCase
{
12 const SCREEN_MEDIA_QUERY
= 'screen and (min-width: 982px)';
13 const SCREEN_ONLY_MEDIA_QUERY
= 'only screen and (min-width: 982px)';
15 // Ensure that we don't affect the global ResourceLoader state.
16 protected function setUp() {
18 ResourceLoader
::clearCache();
20 protected function tearDown() {
22 ResourceLoader
::clearCache();
26 * @dataProvider provideRedirect
28 * @covers OutputPage::__construct
29 * @covers OutputPage::redirect
30 * @covers OutputPage::getRedirect
32 public function testRedirect( $url, $code = null ) {
33 $op = $this->newInstance();
34 if ( isset( $code ) ) {
35 $op->redirect( $url, $code );
37 $op->redirect( $url );
39 $expectedUrl = str_replace( "\n", '', $url );
40 $this->assertSame( $expectedUrl, $op->getRedirect() );
41 $this->assertSame( $expectedUrl, $op->mRedirect
);
42 $this->assertSame( $code ??
'302', $op->mRedirectCode
);
45 public function provideRedirect() {
47 [ 'http://example.com' ],
48 [ 'http://example.com', '400' ],
49 [ 'http://example.com', 'squirrels!!!' ],
55 * @covers OutputPage::setCopyrightUrl
56 * @covers OutputPage::getHeadLinksArray
58 public function testSetCopyrightUrl() {
59 $op = $this->newInstance();
60 $op->setCopyrightUrl( 'http://example.com' );
63 Html
::element( 'link', [ 'rel' => 'license', 'href' => 'http://example.com' ] ),
64 $op->getHeadLinksArray()['copyright']
68 // @todo How to test setStatusCode?
71 * @covers OutputPage::addMeta
72 * @covers OutputPage::getMetaTags
73 * @covers OutputPage::getHeadLinksArray
75 public function testMetaTags() {
76 $op = $this->newInstance();
77 $op->addMeta( 'http:expires', '0' );
78 $op->addMeta( 'keywords', 'first' );
79 $op->addMeta( 'keywords', 'second' );
80 $op->addMeta( 'og:title', 'Ta-duh' );
83 [ 'http:expires', '0' ],
84 [ 'keywords', 'first' ],
85 [ 'keywords', 'second' ],
86 [ 'og:title', 'Ta-duh' ],
88 $this->assertSame( $expected, $op->getMetaTags() );
90 $links = $op->getHeadLinksArray();
91 $this->assertContains( '<meta http-equiv="expires" content="0"/>', $links );
92 $this->assertContains( '<meta name="keywords" content="first"/>', $links );
93 $this->assertContains( '<meta name="keywords" content="second"/>', $links );
94 $this->assertContains( '<meta property="og:title" content="Ta-duh"/>', $links );
95 $this->assertArrayNotHasKey( 'meta-robots', $links );
99 * @covers OutputPage::addLink
100 * @covers OutputPage::getLinkTags
101 * @covers OutputPage::getHeadLinksArray
103 public function testAddLink() {
104 $op = $this->newInstance();
108 [ 'rel' => 'foo', 'href' => 'http://example.com' ],
111 foreach ( $links as $link ) {
112 $op->addLink( $link );
115 $this->assertSame( $links, $op->getLinkTags() );
117 $result = $op->getHeadLinksArray();
119 foreach ( $links as $link ) {
120 $this->assertContains( Html
::element( 'link', $link ), $result );
125 * @covers OutputPage::setCanonicalUrl
126 * @covers OutputPage::getCanonicalUrl
127 * @covers OutputPage::getHeadLinksArray
129 public function testSetCanonicalUrl() {
130 $op = $this->newInstance();
131 $op->setCanonicalUrl( 'http://example.comm' );
132 $op->setCanonicalUrl( 'http://example.com' );
134 $this->assertSame( 'http://example.com', $op->getCanonicalUrl() );
136 $headLinks = $op->getHeadLinksArray();
138 $this->assertContains( Html
::element( 'link', [
139 'rel' => 'canonical', 'href' => 'http://example.com'
142 $this->assertNotContains( Html
::element( 'link', [
143 'rel' => 'canonical', 'href' => 'http://example.comm'
148 * @covers OutputPage::addScript
150 public function testAddScript() {
151 $op = $this->newInstance();
152 $op->addScript( 'some random string' );
154 $this->assertContains( "\nsome random string\n", "\n" . $op->getBottomScripts() . "\n" );
158 * @covers OutputPage::addScriptFile
160 public function testAddScriptFile() {
161 $op = $this->newInstance();
162 $op->addScriptFile( '/somescript.js' );
163 $op->addScriptFile( '//example.com/somescript.js' );
165 $this->assertContains(
166 "\n" . Html
::linkedScript( '/somescript.js', $op->getCSPNonce() ) .
167 Html
::linkedScript( '//example.com/somescript.js', $op->getCSPNonce() ) . "\n",
168 "\n" . $op->getBottomScripts() . "\n"
173 * Test that addScriptFile() throws due to deprecation.
175 * @covers OutputPage::addScriptFile
177 public function testAddDeprecatedScriptFileWarning() {
178 $this->setExpectedException( PHPUnit_Framework_Error_Deprecated
::class,
179 'Use of OutputPage::addScriptFile was deprecated in MediaWiki 1.24.' );
181 $op = $this->newInstance();
182 $op->addScriptFile( 'ignored-script.js' );
186 * Test the actual behavior of the method (in the case where it doesn't throw, e.g., in
189 * @covers OutputPage::addScriptFile
191 public function testAddDeprecatedScriptFileNoOp() {
192 $this->hideDeprecated( 'OutputPage::addScriptFile' );
193 $op = $this->newInstance();
194 $op->addScriptFile( 'ignored-script.js' );
196 $this->assertNotContains( 'ignored-script.js', '' . $op->getBottomScripts() );
200 * @covers OutputPage::addInlineScript
202 public function testAddInlineScript() {
203 $op = $this->newInstance();
204 $op->addInlineScript( 'let foo = "bar";' );
205 $op->addInlineScript( 'alert( foo );' );
207 $this->assertContains(
208 "\n" . Html
::inlineScript( "\nlet foo = \"bar\";\n", $op->getCSPNonce() ) . "\n" .
209 Html
::inlineScript( "\nalert( foo );\n", $op->getCSPNonce() ) . "\n",
210 "\n" . $op->getBottomScripts() . "\n"
214 // @todo How to test filterModules(), warnModuleTargetFilter(), getModules(), etc.?
217 * @covers OutputPage::getTarget
218 * @covers OutputPage::setTarget
220 public function testSetTarget() {
221 $op = $this->newInstance();
222 $op->setTarget( 'foo' );
224 $this->assertSame( 'foo', $op->getTarget() );
225 // @todo What else? Test some actual effect?
228 // @todo How to test addContentOverride(Callback)?
231 * @covers OutputPage::getHeadItemsArray
232 * @covers OutputPage::addHeadItem
233 * @covers OutputPage::addHeadItems
234 * @covers OutputPage::hasHeadItem
236 public function testHeadItems() {
237 $op = $this->newInstance();
238 $op->addHeadItem( 'a', 'b' );
239 $op->addHeadItems( [ 'c' => '<d>&', 'e' => 'f', 'a' => 'q' ] );
240 $op->addHeadItem( 'e', 'g' );
241 $op->addHeadItems( 'x' );
243 $this->assertSame( [ 'a' => 'q', 'c' => '<d>&', 'e' => 'g', 'x' ],
244 $op->getHeadItemsArray() );
246 $this->assertTrue( $op->hasHeadItem( 'a' ) );
247 $this->assertTrue( $op->hasHeadItem( 'c' ) );
248 $this->assertTrue( $op->hasHeadItem( 'e' ) );
249 $this->assertTrue( $op->hasHeadItem( '0' ) );
251 $this->assertContains( "\nq\n<d>&\ng\nx\n",
252 '' . $op->headElement( $op->getContext()->getSkin() ) );
256 * @covers OutputPage::getHeadItemsArray
257 * @covers OutputPage::addParserOutputMetadata
259 public function testHeadItemsParserOutput() {
260 $op = $this->newInstance();
261 $stubPO1 = $this->createParserOutputStub( 'getHeadItems', [ 'a' => 'b' ] );
262 $op->addParserOutputMetadata( $stubPO1 );
263 $stubPO2 = $this->createParserOutputStub( 'getHeadItems',
264 [ 'c' => '<d>&', 'e' => 'f', 'a' => 'q' ] );
265 $op->addParserOutputMetadata( $stubPO2 );
266 $stubPO3 = $this->createParserOutputStub( 'getHeadItems', [ 'e' => 'g' ] );
267 $op->addParserOutputMetadata( $stubPO3 );
268 $stubPO4 = $this->createParserOutputStub( 'getHeadItems', [ 'x' ] );
269 $op->addParserOutputMetadata( $stubPO4 );
271 $this->assertSame( [ 'a' => 'q', 'c' => '<d>&', 'e' => 'g', 'x' ],
272 $op->getHeadItemsArray() );
274 $this->assertTrue( $op->hasHeadItem( 'a' ) );
275 $this->assertTrue( $op->hasHeadItem( 'c' ) );
276 $this->assertTrue( $op->hasHeadItem( 'e' ) );
277 $this->assertTrue( $op->hasHeadItem( '0' ) );
278 $this->assertFalse( $op->hasHeadItem( 'b' ) );
280 $this->assertContains( "\nq\n<d>&\ng\nx\n",
281 '' . $op->headElement( $op->getContext()->getSkin() ) );
285 * @covers OutputPage::addBodyClasses
287 public function testAddBodyClasses() {
288 $op = $this->newInstance();
289 $op->addBodyClasses( 'a' );
290 $op->addBodyClasses( 'mediawiki' );
291 $op->addBodyClasses( 'b c' );
292 $op->addBodyClasses( [ 'd', 'e' ] );
293 $op->addBodyClasses( 'a' );
295 $this->assertContains( '"a mediawiki b c d e ltr',
296 '' . $op->headElement( $op->getContext()->getSkin() ) );
300 * @covers OutputPage::setArticleBodyOnly
301 * @covers OutputPage::getArticleBodyOnly
303 public function testArticleBodyOnly() {
304 $op = $this->newInstance();
305 $this->assertFalse( $op->getArticleBodyOnly() );
307 $op->setArticleBodyOnly( true );
308 $this->assertTrue( $op->getArticleBodyOnly() );
310 $op->addHTML( '<b>a</b>' );
312 $this->assertSame( '<b>a</b>', $op->output( true ) );
316 * @covers OutputPage::setProperty
317 * @covers OutputPage::getProperty
319 public function testProperties() {
320 $op = $this->newInstance();
322 $this->assertNull( $op->getProperty( 'foo' ) );
324 $op->setProperty( 'foo', 'bar' );
325 $op->setProperty( 'baz', 'quz' );
327 $this->assertSame( 'bar', $op->getProperty( 'foo' ) );
328 $this->assertSame( 'quz', $op->getProperty( 'baz' ) );
332 * @dataProvider provideCheckLastModified
334 * @covers OutputPage::checkLastModified
335 * @covers OutputPage::getCdnCacheEpoch
337 public function testCheckLastModified(
338 $timestamp, $ifModifiedSince, $expected, $config = [], $callback = null
340 $request = new FauxRequest();
341 if ( $ifModifiedSince ) {
342 if ( is_numeric( $ifModifiedSince ) ) {
344 $ifModifiedSince = date( 'D, d M Y H:i:s', $ifModifiedSince ) . ' GMT';
346 $request->setHeader( 'If-Modified-Since', $ifModifiedSince );
349 if ( !isset( $config['CacheEpoch'] ) ) {
350 // Make sure it's not too recent
351 $config['CacheEpoch'] = '20000101000000';
354 $op = $this->newInstance( $config, $request );
357 $callback( $op, $this );
360 // Avoid a complaint about not being able to disable compression
361 Wikimedia\
suppressWarnings();
363 $this->assertEquals( $expected, $op->checkLastModified( $timestamp ) );
365 Wikimedia\restoreWarnings
();
369 public function provideCheckLastModified() {
370 $lastModified = time() - 3600;
373 [ '0', $lastModified, false ],
374 'Timestamp Unix epoch' =>
375 [ '19700101000000', $lastModified, false ],
376 'Timestamp same as If-Modified-Since' =>
377 [ $lastModified, $lastModified, true ],
378 'Timestamp one second after If-Modified-Since' =>
379 [ $lastModified +
1, $lastModified, false ],
380 'No If-Modified-Since' =>
381 [ $lastModified +
1, null, false ],
382 'Malformed If-Modified-Since' =>
383 [ $lastModified +
1, 'GIBBERING WOMBATS !!!', false ],
384 'Non-standard IE-style If-Modified-Since' =>
385 [ $lastModified, date( 'D, d M Y H:i:s', $lastModified ) . ' GMT; length=5202',
387 // @todo Should we fix this behavior to match the spec? Probably no reason to.
388 'If-Modified-Since not per spec but we accept it anyway because strtotime does' =>
389 [ $lastModified, "@$lastModified", true ],
390 '$wgCachePages = false' =>
391 [ $lastModified, $lastModified, false, [ 'CachePages' => false ] ],
393 [ $lastModified, $lastModified, false,
394 [ 'CacheEpoch' => wfTimestamp( TS_MW
, $lastModified +
1 ) ] ],
395 'Recently-touched user' =>
396 [ $lastModified, $lastModified, false, [],
398 $op->getContext()->setUser( $this->getTestUser()->getUser() );
400 'After Squid expiry' =>
401 [ $lastModified, $lastModified, false,
402 [ 'UseSquid' => true, 'SquidMaxage' => 3599 ] ],
403 'Hook allows cache use' =>
404 [ $lastModified +
1, $lastModified, true, [],
405 function ( $op, $that ) {
406 $that->setTemporaryHook( 'OutputPageCheckLastModified',
407 function ( &$modifiedTimes ) {
408 $modifiedTimes = [ 1 ];
412 'Hooks prohibits cache use' =>
413 [ $lastModified, $lastModified, false, [],
414 function ( $op, $that ) {
415 $that->setTemporaryHook( 'OutputPageCheckLastModified',
416 function ( &$modifiedTimes ) {
417 $modifiedTimes = [ max( $modifiedTimes ) +
1 ];
425 * @dataProvider provideCdnCacheEpoch
427 * @covers OutputPage::getCdnCacheEpoch
429 public function testCdnCacheEpoch( $params ) {
430 $out = TestingAccessWrapper
::newFromObject( $this->newInstance() );
431 $reqTime = strtotime( $params['reqTime'] );
432 $pageTime = strtotime( $params['pageTime'] );
433 $actual = max( $pageTime, $out->getCdnCacheEpoch( $reqTime, $params['maxAge'] ) );
437 gmdate( DateTime
::ATOM
, $actual ),
442 public static function provideCdnCacheEpoch() {
444 'pageTime' => '2011-04-01T12:00:00+00:00',
445 'maxAge' => 24 * 3600,
448 'after 1s' => [ $base +
[
449 'reqTime' => '2011-04-01T12:00:01+00:00',
450 'expect' => '2011-04-01T12:00:00+00:00',
452 'after 23h' => [ $base +
[
453 'reqTime' => '2011-04-02T11:00:00+00:00',
454 'expect' => '2011-04-01T12:00:00+00:00',
456 'after 24h and a bit' => [ $base +
[
457 'reqTime' => '2011-04-02T12:34:56+00:00',
458 'expect' => '2011-04-01T12:34:56+00:00',
460 'after a year' => [ $base +
[
461 'reqTime' => '2012-05-06T00:12:07+00:00',
462 'expect' => '2012-05-05T00:12:07+00:00',
467 // @todo How to test setLastModified?
470 * @covers OutputPage::setRobotPolicy
471 * @covers OutputPage::getHeadLinksArray
473 public function testSetRobotPolicy() {
474 $op = $this->newInstance();
475 $op->setRobotPolicy( 'noindex, nofollow' );
477 $links = $op->getHeadLinksArray();
478 $this->assertContains( '<meta name="robots" content="noindex,nofollow"/>', $links );
482 * @covers OutputPage::setIndexPolicy
483 * @covers OutputPage::setFollowPolicy
484 * @covers OutputPage::getHeadLinksArray
486 public function testSetIndexFollowPolicies() {
487 $op = $this->newInstance();
488 $op->setIndexPolicy( 'noindex' );
489 $op->setFollowPolicy( 'nofollow' );
491 $links = $op->getHeadLinksArray();
492 $this->assertContains( '<meta name="robots" content="noindex,nofollow"/>', $links );
495 private function extractHTMLTitle( OutputPage
$op ) {
496 $html = $op->headElement( $op->getContext()->getSkin() );
498 // OutputPage should always output the title in a nice format such that regexes will work
499 // fine. If it doesn't, we'll fail the tests.
500 preg_match_all( '!<title>(.*?)</title>!', $html, $matches );
502 $this->assertLessThanOrEqual( 1, count( $matches[1] ), 'More than one <title>!' );
504 if ( !count( $matches[1] ) ) {
508 return $matches[1][0];
512 * Shorthand for getting the text of a message, in content language.
514 private static function getMsgText( $op, ...$msgParams ) {
515 return $op->msg( ...$msgParams )->inContentLanguage()->text();
519 * @covers OutputPage::setHTMLTitle
520 * @covers OutputPage::getHTMLTitle
522 public function testHTMLTitle() {
523 $op = $this->newInstance();
526 $this->assertSame( '', $op->getHTMLTitle() );
527 $this->assertSame( '', $op->getPageTitle() );
529 $this->getMsgText( $op, 'pagetitle', '' ),
530 $this->extractHTMLTitle( $op )
534 $op->setHTMLTitle( 'Potatoes will eat me' );
536 $this->assertSame( 'Potatoes will eat me', $op->getHTMLTitle() );
537 $this->assertSame( 'Potatoes will eat me', $this->extractHTMLTitle( $op ) );
538 // Shouldn't have changed the page title
539 $this->assertSame( '', $op->getPageTitle() );
542 $msg = $op->msg( 'mainpage' );
544 $op->setHTMLTitle( $msg );
545 $this->assertSame( $msg->text(), $op->getHTMLTitle() );
546 $this->assertSame( $msg->text(), $this->extractHTMLTitle( $op ) );
547 $this->assertSame( '', $op->getPageTitle() );
551 * @covers OutputPage::setRedirectedFrom
553 public function testSetRedirectedFrom() {
554 $op = $this->newInstance();
556 $op->setRedirectedFrom( Title
::newFromText( 'Talk:Some page' ) );
557 $this->assertSame( 'Talk:Some_page', $op->getJSVars()['wgRedirectedFrom'] );
561 * @covers OutputPage::setPageTitle
562 * @covers OutputPage::getPageTitle
564 public function testPageTitle() {
565 // We don't test the actual HTML output anywhere, because that's up to the skin.
566 $op = $this->newInstance();
569 $this->assertSame( '', $op->getPageTitle() );
570 $this->assertSame( '', $op->getHTMLTitle() );
572 // Test set to plain text
573 $op->setPageTitle( 'foobar' );
575 $this->assertSame( 'foobar', $op->getPageTitle() );
576 // HTML title should change as well
577 $this->assertSame( $this->getMsgText( $op, 'pagetitle', 'foobar' ), $op->getHTMLTitle() );
579 // Test set to text with good and bad HTML. We don't try to be comprehensive here, that
580 // belongs in Sanitizer tests.
581 $op->setPageTitle( '<script>a</script>&<i>b</i>' );
583 $this->assertSame( '<script>a</script>&<i>b</i>', $op->getPageTitle() );
585 $this->getMsgText( $op, 'pagetitle', '<script>a</script>&b' ),
589 // Test set to message
590 $text = $this->getMsgText( $op, 'mainpage' );
592 $op->setPageTitle( $op->msg( 'mainpage' )->inContentLanguage() );
593 $this->assertSame( $text, $op->getPageTitle() );
594 $this->assertSame( $this->getMsgText( $op, 'pagetitle', $text ), $op->getHTMLTitle() );
598 * @covers OutputPage::setTitle
600 public function testSetTitle() {
601 $op = $this->newInstance();
603 $this->assertSame( 'My test page', $op->getTitle()->getPrefixedText() );
605 $op->setTitle( Title
::newFromText( 'Another test page' ) );
607 $this->assertSame( 'Another test page', $op->getTitle()->getPrefixedText() );
611 * @covers OutputPage::setSubtitle
612 * @covers OutputPage::clearSubtitle
613 * @covers OutputPage::addSubtitle
614 * @covers OutputPage::getSubtitle
616 public function testSubtitle() {
617 $op = $this->newInstance();
619 $this->assertSame( '', $op->getSubtitle() );
621 $op->addSubtitle( '<b>foo</b>' );
623 $this->assertSame( '<b>foo</b>', $op->getSubtitle() );
625 $op->addSubtitle( $op->msg( 'mainpage' )->inContentLanguage() );
628 "<b>foo</b><br />\n\t\t\t\t" . $this->getMsgText( $op, 'mainpage' ),
632 $op->setSubtitle( 'There can be only one' );
634 $this->assertSame( 'There can be only one', $op->getSubtitle() );
636 $op->clearSubtitle();
638 $this->assertSame( '', $op->getSubtitle() );
642 * @dataProvider provideBacklinkSubtitle
644 * @covers OutputPage::buildBacklinkSubtitle
646 public function testBuildBacklinkSubtitle( $titles, $queries, $contains, $notContains ) {
647 if ( count( $titles ) > 1 ) {
649 $this->assertTrue( true );
653 $title = Title
::newFromText( $titles[0] );
654 $query = $queries[0];
656 $this->editPage( 'Page 1', '' );
657 $this->editPage( 'Page 2', '#REDIRECT [[Page 1]]' );
659 $str = OutputPage
::buildBacklinkSubtitle( $title, $query )->text();
661 foreach ( $contains as $substr ) {
662 $this->assertContains( $substr, $str );
665 foreach ( $notContains as $substr ) {
666 $this->assertNotContains( $substr, $str );
671 * @dataProvider provideBacklinkSubtitle
673 * @covers OutputPage::addBacklinkSubtitle
674 * @covers OutputPage::getSubtitle
676 public function testAddBacklinkSubtitle( $titles, $queries, $contains, $notContains ) {
677 $this->editPage( 'Page 1', '' );
678 $this->editPage( 'Page 2', '#REDIRECT [[Page 1]]' );
680 $op = $this->newInstance();
681 foreach ( $titles as $i => $unused ) {
682 $op->addBacklinkSubtitle( Title
::newFromText( $titles[$i] ), $queries[$i] );
685 $str = $op->getSubtitle();
687 foreach ( $contains as $substr ) {
688 $this->assertContains( $substr, $str );
691 foreach ( $notContains as $substr ) {
692 $this->assertNotContains( $substr, $str );
696 public function provideBacklinkSubtitle() {
702 [ 'redirect', 'Page 2' ],
712 [ [ 'action' => 'edit' ] ],
717 [ 'Page 1', 'Page 2' ],
719 [ 'Page 1', 'Page 2', "<br />\n\t\t\t\t" ],
722 // @todo Anything else to test?
727 * @covers OutputPage::setPrintable
728 * @covers OutputPage::isPrintable
730 public function testPrintable() {
731 $op = $this->newInstance();
733 $this->assertFalse( $op->isPrintable() );
737 $this->assertTrue( $op->isPrintable() );
741 * @covers OutputPage::disable
742 * @covers OutputPage::isDisabled
744 public function testDisable() {
745 $op = $this->newInstance();
747 $this->assertFalse( $op->isDisabled() );
748 $this->assertNotSame( '', $op->output( true ) );
752 $this->assertTrue( $op->isDisabled() );
753 $this->assertSame( '', $op->output( true ) );
757 * @covers OutputPage::showNewSectionLink
758 * @covers OutputPage::addParserOutputMetadata
760 public function testShowNewSectionLink() {
761 $op = $this->newInstance();
763 $this->assertFalse( $op->showNewSectionLink() );
765 $po = new ParserOutput();
766 $po->setNewSection( true );
767 $op->addParserOutputMetadata( $po );
769 $this->assertTrue( $op->showNewSectionLink() );
773 * @covers OutputPage::forceHideNewSectionLink
774 * @covers OutputPage::addParserOutputMetadata
776 public function testForceHideNewSectionLink() {
777 $op = $this->newInstance();
779 $this->assertFalse( $op->forceHideNewSectionLink() );
781 $po = new ParserOutput();
782 $po->hideNewSection( true );
783 $op->addParserOutputMetadata( $po );
785 $this->assertTrue( $op->forceHideNewSectionLink() );
789 * @covers OutputPage::setSyndicated
790 * @covers OutputPage::isSyndicated
792 public function testSetSyndicated() {
793 $op = $this->newInstance();
794 $this->assertFalse( $op->isSyndicated() );
796 $op->setSyndicated();
797 $this->assertTrue( $op->isSyndicated() );
799 $op->setSyndicated( false );
800 $this->assertFalse( $op->isSyndicated() );
804 * @covers OutputPage::isSyndicated
805 * @covers OutputPage::setFeedAppendQuery
806 * @covers OutputPage::addFeedLink
807 * @covers OutputPage::getSyndicationLinks()
809 public function testFeedLinks() {
810 $op = $this->newInstance();
811 $this->assertSame( [], $op->getSyndicationLinks() );
813 $op->addFeedLink( 'not a supported format', 'abc' );
814 $this->assertFalse( $op->isSyndicated() );
815 $this->assertSame( [], $op->getSyndicationLinks() );
817 $feedTypes = $op->getConfig()->get( 'AdvertisedFeedTypes' );
819 $op->addFeedLink( $feedTypes[0], 'def' );
820 $this->assertTrue( $op->isSyndicated() );
821 $this->assertSame( [ $feedTypes[0] => 'def' ], $op->getSyndicationLinks() );
823 $op->setFeedAppendQuery( false );
825 foreach ( $feedTypes as $type ) {
826 $expected[$type] = $op->getTitle()->getLocalURL( "feed=$type" );
828 $this->assertSame( $expected, $op->getSyndicationLinks() );
830 $op->setFeedAppendQuery( 'apples=oranges' );
831 foreach ( $feedTypes as $type ) {
832 $expected[$type] = $op->getTitle()->getLocalURL( "feed=$type&apples=oranges" );
834 $this->assertSame( $expected, $op->getSyndicationLinks() );
838 * @covers OutputPage::setArticleFlag
839 * @covers OutputPage::isArticle
840 * @covers OutputPage::setArticleRelated
841 * @covers OutputPage::isArticleRelated
843 function testArticleFlags() {
844 $op = $this->newInstance();
845 $this->assertFalse( $op->isArticle() );
846 $this->assertTrue( $op->isArticleRelated() );
848 $op->setArticleRelated( false );
849 $this->assertFalse( $op->isArticle() );
850 $this->assertFalse( $op->isArticleRelated() );
852 $op->setArticleFlag( true );
853 $this->assertTrue( $op->isArticle() );
854 $this->assertTrue( $op->isArticleRelated() );
856 $op->setArticleFlag( false );
857 $this->assertFalse( $op->isArticle() );
858 $this->assertTrue( $op->isArticleRelated() );
860 $op->setArticleFlag( true );
861 $op->setArticleRelated( false );
862 $this->assertFalse( $op->isArticle() );
863 $this->assertFalse( $op->isArticleRelated() );
867 * @covers OutputPage::addLanguageLinks
868 * @covers OutputPage::setLanguageLinks
869 * @covers OutputPage::getLanguageLinks
870 * @covers OutputPage::addParserOutputMetadata
872 function testLanguageLinks() {
873 $op = $this->newInstance();
874 $this->assertSame( [], $op->getLanguageLinks() );
876 $op->addLanguageLinks( [ 'fr:A', 'it:B' ] );
877 $this->assertSame( [ 'fr:A', 'it:B' ], $op->getLanguageLinks() );
879 $op->addLanguageLinks( [ 'de:C', 'es:D' ] );
880 $this->assertSame( [ 'fr:A', 'it:B', 'de:C', 'es:D' ], $op->getLanguageLinks() );
882 $op->setLanguageLinks( [ 'pt:E' ] );
883 $this->assertSame( [ 'pt:E' ], $op->getLanguageLinks() );
885 $po = new ParserOutput();
886 $po->setLanguageLinks( [ 'he:F', 'ar:G' ] );
887 $op->addParserOutputMetadata( $po );
888 $this->assertSame( [ 'pt:E', 'he:F', 'ar:G' ], $op->getLanguageLinks() );
891 // @todo Are these category links tests too abstract and complicated for what they test? Would
892 // it make sense to just write out all the tests by hand with maybe some copy-and-paste?
895 * @dataProvider provideGetCategories
897 * @covers OutputPage::addCategoryLinks
898 * @covers OutputPage::getCategories
899 * @covers OutputPage::getCategoryLinks
901 * @param array $args Array of form [ category name => sort key ]
902 * @param array $fakeResults Array of form [ category name => value to return from mocked
904 * @param callback $variantLinkCallback Callback to replace findVariantLink() call
905 * @param array $expectedNormal Expected return value of getCategoryLinks['normal']
906 * @param array $expectedHidden Expected return value of getCategoryLinks['hidden']
908 public function testAddCategoryLinks(
909 array $args, array $fakeResults, callable
$variantLinkCallback = null,
910 array $expectedNormal, array $expectedHidden
912 $expectedNormal = $this->extractExpectedCategories( $expectedNormal, 'add' );
913 $expectedHidden = $this->extractExpectedCategories( $expectedHidden, 'add' );
915 $op = $this->setupCategoryTests( $fakeResults, $variantLinkCallback );
917 $op->addCategoryLinks( $args );
919 $this->doCategoryAsserts( $op, $expectedNormal, $expectedHidden );
920 $this->doCategoryLinkAsserts( $op, $expectedNormal, $expectedHidden );
924 * @dataProvider provideGetCategories
926 * @covers OutputPage::addCategoryLinks
927 * @covers OutputPage::getCategories
928 * @covers OutputPage::getCategoryLinks
930 public function testAddCategoryLinksOneByOne(
931 array $args, array $fakeResults, callable
$variantLinkCallback = null,
932 array $expectedNormal, array $expectedHidden
934 if ( count( $args ) <= 1 ) {
935 // @todo Should this be skipped instead of passed?
936 $this->assertTrue( true );
940 $expectedNormal = $this->extractExpectedCategories( $expectedNormal, 'onebyone' );
941 $expectedHidden = $this->extractExpectedCategories( $expectedHidden, 'onebyone' );
943 $op = $this->setupCategoryTests( $fakeResults, $variantLinkCallback );
945 foreach ( $args as $key => $val ) {
946 $op->addCategoryLinks( [ $key => $val ] );
949 $this->doCategoryAsserts( $op, $expectedNormal, $expectedHidden );
950 $this->doCategoryLinkAsserts( $op, $expectedNormal, $expectedHidden );
954 * @dataProvider provideGetCategories
956 * @covers OutputPage::setCategoryLinks
957 * @covers OutputPage::getCategories
958 * @covers OutputPage::getCategoryLinks
960 public function testSetCategoryLinks(
961 array $args, array $fakeResults, callable
$variantLinkCallback = null,
962 array $expectedNormal, array $expectedHidden
964 $expectedNormal = $this->extractExpectedCategories( $expectedNormal, 'set' );
965 $expectedHidden = $this->extractExpectedCategories( $expectedHidden, 'set' );
967 $op = $this->setupCategoryTests( $fakeResults, $variantLinkCallback );
969 $op->setCategoryLinks( [ 'Initial page' => 'Initial page' ] );
970 $op->setCategoryLinks( $args );
972 // We don't reset the categories, for some reason, only the links
973 $expectedNormalCats = array_merge( [ 'Initial page' ], $expectedNormal );
974 $expectedCats = array_merge( $expectedHidden, $expectedNormalCats );
976 $this->doCategoryAsserts( $op, $expectedNormalCats, $expectedHidden );
977 $this->doCategoryLinkAsserts( $op, $expectedNormal, $expectedHidden );
981 * @dataProvider provideGetCategories
983 * @covers OutputPage::addParserOutputMetadata
984 * @covers OutputPage::getCategories
985 * @covers OutputPage::getCategoryLinks
987 public function testParserOutputCategoryLinks(
988 array $args, array $fakeResults, callable
$variantLinkCallback = null,
989 array $expectedNormal, array $expectedHidden
991 $expectedNormal = $this->extractExpectedCategories( $expectedNormal, 'pout' );
992 $expectedHidden = $this->extractExpectedCategories( $expectedHidden, 'pout' );
994 $op = $this->setupCategoryTests( $fakeResults, $variantLinkCallback );
996 $stubPO = $this->createParserOutputStub( 'getCategories', $args );
998 $op->addParserOutputMetadata( $stubPO );
1000 $this->doCategoryAsserts( $op, $expectedNormal, $expectedHidden );
1001 $this->doCategoryLinkAsserts( $op, $expectedNormal, $expectedHidden );
1005 * We allow different expectations for different tests as an associative array, like
1006 * [ 'set' => [ ... ], 'default' => [ ... ] ] if setCategoryLinks() will give a different
1009 private function extractExpectedCategories( array $expected, $key ) {
1010 if ( !$expected ||
isset( $expected[0] ) ) {
1013 return $expected[$key] ??
$expected['default'];
1016 private function setupCategoryTests(
1017 array $fakeResults, callable
$variantLinkCallback = null
1019 $this->setMwGlobals( 'wgUsePigLatinVariant', true );
1021 $op = $this->getMockBuilder( OutputPage
::class )
1022 ->setConstructorArgs( [ new RequestContext() ] )
1023 ->setMethods( [ 'addCategoryLinksToLBAndGetResult', 'getTitle' ] )
1026 $title = Title
::newFromText( 'My test page' );
1027 $op->expects( $this->any() )
1028 ->method( 'getTitle' )
1029 ->will( $this->returnValue( $title ) );
1031 $op->expects( $this->any() )
1032 ->method( 'addCategoryLinksToLBAndGetResult' )
1033 ->will( $this->returnCallback( function ( array $categories ) use ( $fakeResults ) {
1035 foreach ( $categories as $category => $unused ) {
1036 if ( isset( $fakeResults[$category] ) ) {
1037 $return[] = $fakeResults[$category];
1040 return new FakeResultWrapper( $return );
1043 if ( $variantLinkCallback ) {
1044 $mockContLang = $this->getMockBuilder( Language
::class )
1045 ->setConstructorArgs( [ 'en' ] )
1046 ->setMethods( [ 'findVariantLink' ] )
1048 $mockContLang->expects( $this->any() )
1049 ->method( 'findVariantLink' )
1050 ->will( $this->returnCallback( $variantLinkCallback ) );
1051 $this->setContentLang( $mockContLang );
1054 $this->assertSame( [], $op->getCategories() );
1059 private function doCategoryAsserts( $op, $expectedNormal, $expectedHidden ) {
1060 $this->assertSame( array_merge( $expectedHidden, $expectedNormal ), $op->getCategories() );
1061 $this->assertSame( $expectedNormal, $op->getCategories( 'normal' ) );
1062 $this->assertSame( $expectedHidden, $op->getCategories( 'hidden' ) );
1065 private function doCategoryLinkAsserts( $op, $expectedNormal, $expectedHidden ) {
1066 $catLinks = $op->getCategoryLinks();
1067 $this->assertSame( (bool)$expectedNormal +
(bool)$expectedHidden, count( $catLinks ) );
1068 if ( $expectedNormal ) {
1069 $this->assertSame( count( $expectedNormal ), count( $catLinks['normal'] ) );
1071 if ( $expectedHidden ) {
1072 $this->assertSame( count( $expectedHidden ), count( $catLinks['hidden'] ) );
1075 foreach ( $expectedNormal as $i => $name ) {
1076 $this->assertContains( $name, $catLinks['normal'][$i] );
1078 foreach ( $expectedHidden as $i => $name ) {
1079 $this->assertContains( $name, $catLinks['hidden'][$i] );
1083 public function provideGetCategories() {
1085 'No categories' => [ [], [], null, [], [] ],
1087 [ 'Test1' => 'Some sortkey', 'Test2' => 'A different sortkey' ],
1088 [ 'Test1' => (object)[ 'pp_value' => 1, 'page_title' => 'Test1' ],
1089 'Test2' => (object)[ 'page_title' => 'Test2' ] ],
1094 'Invalid title' => [
1095 [ '[' => '[', 'Test' => 'Test' ],
1096 [ 'Test' => (object)[ 'page_title' => 'Test' ] ],
1102 [ 'Test' => 'Test', 'Estay' => 'Estay' ],
1103 [ 'Test' => (object)[ 'page_title' => 'Test' ] ],
1104 function ( &$link, &$title ) {
1105 if ( $link === 'Estay' ) {
1107 $title = Title
::makeTitleSafe( NS_CATEGORY
, $link );
1110 // For adding one by one, the variant gets added as well as the original category,
1111 // but if you add them all together the second time gets skipped.
1112 [ 'onebyone' => [ 'Test', 'Test' ], 'default' => [ 'Test' ] ],
1119 * @covers OutputPage::getCategories
1121 public function testGetCategoriesInvalid() {
1122 $this->setExpectedException( InvalidArgumentException
::class,
1123 'Invalid category type given: hiddne' );
1125 $op = $this->newInstance();
1126 $op->getCategories( 'hiddne' );
1129 // @todo Should we test addCategoryLinksToLBAndGetResult? If so, how? Insert some test rows in
1133 * @covers OutputPage::setIndicators
1134 * @covers OutputPage::getIndicators
1135 * @covers OutputPage::addParserOutputMetadata
1137 public function testIndicators() {
1138 $op = $this->newInstance();
1139 $this->assertSame( [], $op->getIndicators() );
1141 $op->setIndicators( [] );
1142 $this->assertSame( [], $op->getIndicators() );
1144 // Test sorting alphabetically
1145 $op->setIndicators( [ 'b' => 'x', 'a' => 'y' ] );
1146 $this->assertSame( [ 'a' => 'y', 'b' => 'x' ], $op->getIndicators() );
1148 // Test overwriting existing keys
1149 $op->setIndicators( [ 'c' => 'z', 'a' => 'w' ] );
1150 $this->assertSame( [ 'a' => 'w', 'b' => 'x', 'c' => 'z' ], $op->getIndicators() );
1152 // Test with ParserOutput
1153 $stubPO = $this->createParserOutputStub( 'getIndicators', [ 'c' => 'u', 'd' => 'v' ] );
1154 $op->addParserOutputMetadata( $stubPO );
1155 $this->assertSame( [ 'a' => 'w', 'b' => 'x', 'c' => 'u', 'd' => 'v' ],
1156 $op->getIndicators() );
1160 * @covers OutputPage::addHelpLink
1161 * @covers OutputPage::getIndicators
1163 public function testAddHelpLink() {
1164 $op = $this->newInstance();
1166 $op->addHelpLink( 'Manual:PHP unit testing' );
1167 $indicators = $op->getIndicators();
1168 $this->assertSame( [ 'mw-helplink' ], array_keys( $indicators ) );
1169 $this->assertContains( 'Manual:PHP_unit_testing', $indicators['mw-helplink'] );
1171 $op->addHelpLink( 'https://phpunit.de', true );
1172 $indicators = $op->getIndicators();
1173 $this->assertSame( [ 'mw-helplink' ], array_keys( $indicators ) );
1174 $this->assertContains( 'https://phpunit.de', $indicators['mw-helplink'] );
1175 $this->assertNotContains( 'mediawiki', $indicators['mw-helplink'] );
1176 $this->assertNotContains( 'Manual:PHP', $indicators['mw-helplink'] );
1180 * @covers OutputPage::prependHTML
1181 * @covers OutputPage::addHTML
1182 * @covers OutputPage::addElement
1183 * @covers OutputPage::clearHTML
1184 * @covers OutputPage::getHTML
1186 public function testBodyHTML() {
1187 $op = $this->newInstance();
1188 $this->assertSame( '', $op->getHTML() );
1190 $op->addHTML( 'a' );
1191 $this->assertSame( 'a', $op->getHTML() );
1193 $op->addHTML( 'b' );
1194 $this->assertSame( 'ab', $op->getHTML() );
1196 $op->prependHTML( 'c' );
1197 $this->assertSame( 'cab', $op->getHTML() );
1199 $op->addElement( 'p', [ 'id' => 'foo' ], 'd' );
1200 $this->assertSame( 'cab<p id="foo">d</p>', $op->getHTML() );
1203 $this->assertSame( '', $op->getHTML() );
1207 * @dataProvider provideRevisionId
1208 * @covers OutputPage::setRevisionId
1209 * @covers OutputPage::getRevisionId
1211 public function testRevisionId( $newVal, $expected ) {
1212 $op = $this->newInstance();
1214 $this->assertNull( $op->setRevisionId( $newVal ) );
1215 $this->assertSame( $expected, $op->getRevisionId() );
1216 $this->assertSame( $expected, $op->setRevisionId( null ) );
1217 $this->assertNull( $op->getRevisionId() );
1220 public function provideRevisionId() {
1227 [ '32% finished', 32 ],
1233 * @covers OutputPage::setRevisionTimestamp
1234 * @covers OutputPage::getRevisionTimestamp
1236 public function testRevisionTimestamp() {
1237 $op = $this->newInstance();
1238 $this->assertNull( $op->getRevisionTimestamp() );
1240 $this->assertNull( $op->setRevisionTimestamp( 'abc' ) );
1241 $this->assertSame( 'abc', $op->getRevisionTimestamp() );
1242 $this->assertSame( 'abc', $op->setRevisionTimestamp( null ) );
1243 $this->assertNull( $op->getRevisionTimestamp() );
1247 * @covers OutputPage::setFileVersion
1248 * @covers OutputPage::getFileVersion
1250 public function testFileVersion() {
1251 $op = $this->newInstance();
1252 $this->assertNull( $op->getFileVersion() );
1254 $stubFile = $this->createMock( File
::class );
1255 $stubFile->method( 'exists' )->willReturn( true );
1256 $stubFile->method( 'getTimestamp' )->willReturn( '12211221123321' );
1257 $stubFile->method( 'getSha1' )->willReturn( 'bf3ffa7047dc080f5855377a4f83cd18887e3b05' );
1259 $op->setFileVersion( $stubFile );
1261 $this->assertEquals(
1262 [ 'time' => '12211221123321', 'sha1' => 'bf3ffa7047dc080f5855377a4f83cd18887e3b05' ],
1263 $op->getFileVersion()
1266 $stubMissingFile = $this->createMock( File
::class );
1267 $stubMissingFile->method( 'exists' )->willReturn( false );
1269 $op->setFileVersion( $stubMissingFile );
1270 $this->assertNull( $op->getFileVersion() );
1272 $op->setFileVersion( $stubFile );
1273 $this->assertNotNull( $op->getFileVersion() );
1275 $op->setFileVersion( null );
1276 $this->assertNull( $op->getFileVersion() );
1279 private function createParserOutputStub( $method = '', $retVal = [] ) {
1280 $pOut = $this->getMock( ParserOutput
::class );
1281 if ( $method !== '' ) {
1282 $pOut->method( $method )->willReturn( $retVal );
1285 $arrayReturningMethods = [
1287 'getFileSearchOptions',
1295 foreach ( $arrayReturningMethods as $method ) {
1296 $pOut->method( $method )->willReturn( [] );
1303 * @covers OutputPage::getTemplateIds
1304 * @covers OutputPage::addParserOutputMetadata
1306 public function testTemplateIds() {
1307 $op = $this->newInstance();
1308 $this->assertSame( [], $op->getTemplateIds() );
1310 // Test with no template id's
1311 $stubPOEmpty = $this->createParserOutputStub();
1312 $op->addParserOutputMetadata( $stubPOEmpty );
1313 $this->assertSame( [], $op->getTemplateIds() );
1315 // Test with some arbitrary template id's
1317 NS_MAIN
=> [ 'A' => 3, 'B' => 17 ],
1318 NS_TALK
=> [ 'C' => 31 ],
1319 NS_MEDIA
=> [ 'D' => -1 ],
1322 $stubPO1 = $this->createParserOutputStub( 'getTemplateIds', $ids );
1324 $op->addParserOutputMetadata( $stubPO1 );
1325 $this->assertSame( $ids, $op->getTemplateIds() );
1327 // Test merging with a second set of id's
1328 $stubPO2 = $this->createParserOutputStub( 'getTemplateIds', [
1329 NS_MAIN
=> [ 'E' => 1234 ],
1330 NS_PROJECT
=> [ 'F' => 5678 ],
1334 NS_MAIN
=> [ 'E' => 1234, 'A' => 3, 'B' => 17 ],
1335 NS_TALK
=> [ 'C' => 31 ],
1336 NS_MEDIA
=> [ 'D' => -1 ],
1337 NS_PROJECT
=> [ 'F' => 5678 ],
1340 $op->addParserOutputMetadata( $stubPO2 );
1341 $this->assertSame( $finalIds, $op->getTemplateIds() );
1343 // Test merging with an empty set of id's
1344 $op->addParserOutputMetadata( $stubPOEmpty );
1345 $this->assertSame( $finalIds, $op->getTemplateIds() );
1349 * @covers OutputPage::getFileSearchOptions
1350 * @covers OutputPage::addParserOutputMetadata
1352 public function testFileSearchOptions() {
1353 $op = $this->newInstance();
1354 $this->assertSame( [], $op->getFileSearchOptions() );
1356 // Test with no files
1357 $stubPOEmpty = $this->createParserOutputStub();
1359 $op->addParserOutputMetadata( $stubPOEmpty );
1360 $this->assertSame( [], $op->getFileSearchOptions() );
1362 // Test with some arbitrary files
1364 'A' => [ 'time' => null, 'sha1' => '' ],
1366 'time' => '12211221123321',
1367 'sha1' => 'bf3ffa7047dc080f5855377a4f83cd18887e3b05',
1371 $stubPO1 = $this->createParserOutputStub( 'getFileSearchOptions', $files1 );
1373 $op->addParserOutputMetadata( $stubPO1 );
1374 $this->assertSame( $files1, $op->getFileSearchOptions() );
1376 // Test merging with a second set of files
1378 'C' => [ 'time' => null, 'sha1' => '' ],
1379 'B' => [ 'time' => null, 'sha1' => '' ],
1382 $stubPO2 = $this->createParserOutputStub( 'getFileSearchOptions', $files2 );
1384 $op->addParserOutputMetadata( $stubPO2 );
1385 $this->assertSame( array_merge( $files1, $files2 ), $op->getFileSearchOptions() );
1387 // Test merging with an empty set of files
1388 $op->addParserOutputMetadata( $stubPOEmpty );
1389 $this->assertSame( array_merge( $files1, $files2 ), $op->getFileSearchOptions() );
1393 * @dataProvider provideAddWikiText
1394 * @covers OutputPage::addWikiText
1395 * @covers OutputPage::addWikiTextAsInterface
1396 * @covers OutputPage::addWikiTextAsContent
1397 * @covers OutputPage::addWikiTextWithTitle
1398 * @covers OutputPage::addWikiTextTitle
1399 * @covers OutputPage::addWikiTextTidy
1400 * @covers OutputPage::addWikiTextTitleTidy
1401 * @covers OutputPage::getHTML
1403 public function testAddWikiText( $method, array $args, $expected ) {
1404 $op = $this->newInstance();
1405 $this->assertSame( '', $op->getHTML() );
1407 $this->hideDeprecated( 'OutputPage::addWikiTextTitle' );
1408 $this->hideDeprecated( 'OutputPage::addWikiTextWithTitle' );
1409 $this->hideDeprecated( 'OutputPage::addWikiTextTidy' );
1410 $this->hideDeprecated( 'OutputPage::addWikiTextTitleTidy' );
1413 [ 'addWikiTextWithTitle', 'addWikiTextTitleTidy', 'addWikiTextTitle' ]
1414 ) && count( $args ) >= 2 && $args[1] === null ) {
1415 // Special placeholder because we can't get the actual title in the provider
1416 $args[1] = $op->getTitle();
1420 [ 'addWikiTextAsInterface', 'addWikiTextAsContent' ]
1421 ) && count( $args ) >= 3 && $args[2] === null ) {
1422 // Special placeholder because we can't get the actual title in the provider
1423 $args[2] = $op->getTitle();
1426 $op->$method( ...$args );
1427 $this->assertSame( $expected, $op->getHTML() );
1430 public function provideAddWikiText() {
1433 // Not tidied; this API is deprecated.
1434 'Simple wikitext' => [
1436 "<p><b>Bold</b>\n</p>",
1437 ], 'List at start' => [
1439 "<ul><li>List</li></ul>\n",
1440 ], 'List not at start' => [
1441 [ '* Not a list', false ],
1443 ], 'Non-interface' => [
1444 [ "'''Bold'''", true, false ],
1445 "<p><b>Bold</b>\n</p>",
1446 ], 'No section edit links' => [
1448 "<h2><span class=\"mw-headline\" id=\"Title\">Title</span></h2>\n",
1451 'addWikiTextWithTitle' => [
1452 // Untidied; this API is deprecated
1453 'With title at start' => [
1454 [ '* {{PAGENAME}}', Title
::newFromText( 'Talk:Some page' ) ],
1455 "<ul><li>Some page</li></ul>\n",
1456 ], 'With title at start' => [
1457 [ '* {{PAGENAME}}', Title
::newFromText( 'Talk:Some page' ), false ],
1461 'addWikiTextAsInterface' => [
1462 // Preferred interface: output is tidied
1463 'Simple wikitext' => [
1465 "<p><b>Bold</b>\n</p>",
1466 ], 'Untidy wikitext' => [
1468 "<p><b>Bold\n</b></p>",
1469 ], 'List at start' => [
1471 "<ul><li>List</li></ul>\n",
1472 ], 'List not at start' => [
1473 [ '* Not a list', false ],
1474 '<p>* Not a list</p>',
1475 ], 'No section edit links' => [
1477 "<h2><span class=\"mw-headline\" id=\"Title\">Title</span></h2>\n",
1478 ], 'With title at start' => [
1479 [ '* {{PAGENAME}}', true, Title
::newFromText( 'Talk:Some page' ) ],
1480 "<ul><li>Some page</li></ul>\n",
1481 ], 'With title at start' => [
1482 [ '* {{PAGENAME}}', false, Title
::newFromText( 'Talk:Some page' ), false ],
1483 "<p>* Some page</p>",
1484 ], 'Untidy input' => [
1485 [ '<b>{{PAGENAME}}', true, Title
::newFromText( 'Talk:Some page' ) ],
1486 "<p><b>Some page\n</b></p>",
1489 'addWikiTextAsContent' => [
1490 // Preferred interface: output is tidied
1491 'SpecialNewimages' => [
1492 [ "<p lang='en' dir='ltr'>\nMy message" ],
1493 '<p lang="en" dir="ltr">' . "\nMy message\n</p>"
1494 ], 'List at start' => [
1496 "<ul><li>List</li></ul>\n",
1497 ], 'List not at start' => [
1498 [ '* <b>Not a list', false ],
1499 '<p>* <b>Not a list</b></p>',
1500 ], 'With title at start' => [
1501 [ '* {{PAGENAME}}', true, Title
::newFromText( 'Talk:Some page' ) ],
1502 "<ul><li>Some page</li></ul>\n",
1503 ], 'With title at start' => [
1504 [ '* {{PAGENAME}}', false, Title
::newFromText( 'Talk:Some page' ), false ],
1505 "<p>* Some page</p>",
1507 [ "<div class='mw-editintro'>{{PAGENAME}}", true, Title
::newFromText( 'Talk:Some page' ) ],
1508 '<div class="mw-editintro">' . "Some page\n</div>"
1513 // Test all the others on addWikiTextTitle as well
1514 foreach ( $tests['addWikiText'] as $key => $val ) {
1515 $args = [ $val[0][0], null, $val[0][1] ??
true, false, $val[0][2] ??
true ];
1516 $tests['addWikiTextTitle']["$key (addWikiTextTitle)"] =
1517 array_merge( [ $args ], array_slice( $val, 1 ) );
1519 foreach ( $tests['addWikiTextWithTitle'] as $key => $val ) {
1520 $args = [ $val[0][0], $val[0][1], $val[0][2] ??
true ];
1521 $tests['addWikiTextTitle']["$key (addWikiTextTitle)"] =
1522 array_merge( [ $args ], array_slice( $val, 1 ) );
1524 foreach ( $tests['addWikiTextAsInterface'] as $key => $val ) {
1525 $args = [ $val[0][0], $val[0][2] ??
null, $val[0][1] ??
true, true, true ];
1526 $tests['addWikiTextTitle']["$key (addWikiTextTitle)"] =
1527 array_merge( [ $args ], array_slice( $val, 1 ) );
1529 foreach ( $tests['addWikiTextAsContent'] as $key => $val ) {
1530 $args = [ $val[0][0], $val[0][2] ??
null, $val[0][1] ??
true, true, false ];
1531 $tests['addWikiTextTitle']["$key (addWikiTextTitle)"] =
1532 array_merge( [ $args ], array_slice( $val, 1 ) );
1534 // addWikiTextTidy / addWikiTextTitleTidy were old aliases of
1535 // addWikiTextAsContent
1536 foreach ( $tests['addWikiTextAsContent'] as $key => $val ) {
1537 if ( count( $val[0] ) > 2 ) {
1538 $args = [ $val[0][0], $val[0][2], $val[0][1] ??
true ];
1539 $tests['addWikiTextTitleTidy']["$key (addWikiTextTitleTidy)"] =
1540 array_merge( [ $args ], array_slice( $val, 1 ) );
1542 $args = [ $val[0][0], $val[0][1] ??
true ];
1543 $tests['addWikiTextTidy']["$key (addWikiTextTidy)"] =
1544 array_merge( [ $args ], array_slice( $val, 1 ) );
1548 // We have to reformat our array to match what PHPUnit wants
1550 foreach ( $tests as $key => $subarray ) {
1551 foreach ( $subarray as $subkey => $val ) {
1552 $val = array_merge( [ $key ], $val );
1553 $ret[$subkey] = $val;
1561 * @covers OutputPage::addWikiText
1563 public function testAddWikiTextNoTitle() {
1564 $this->setExpectedException( MWException
::class, 'Title is null' );
1566 $op = $this->newInstance( [], null, 'notitle' );
1567 $op->addWikiText( 'a' );
1571 * @covers OutputPage::addWikiTextAsInterface
1573 public function testAddWikiTextAsInterfaceNoTitle() {
1574 $this->setExpectedException( MWException
::class, 'Title is null' );
1576 $op = $this->newInstance( [], null, 'notitle' );
1577 $op->addWikiTextAsInterface( 'a' );
1581 * @covers OutputPage::addWikiTextAsContent
1583 public function testAddWikiTextAsContentNoTitle() {
1584 $this->setExpectedException( MWException
::class, 'Title is null' );
1586 $op = $this->newInstance( [], null, 'notitle' );
1587 $op->addWikiTextAsContent( 'a' );
1591 * @covers OutputPage::addWikiMsg
1593 public function testAddWikiMsg() {
1594 $msg = wfMessage( 'parentheses' );
1595 $this->assertSame( '(a)', $msg->rawParams( 'a' )->plain() );
1597 $op = $this->newInstance();
1598 $this->assertSame( '', $op->getHTML() );
1599 $op->addWikiMsg( 'parentheses', "<b>a" );
1600 // This is known to be bad unbalanced HTML; this will be fixed
1601 // by I743f4185a03403f8d9b9db010ff1ee4e9342e062 (T198214)
1602 $this->assertSame( "<p>(<b>a)\n</p>", $op->getHTML() );
1606 * @covers OutputPage::wrapWikiMsg
1608 public function testWrapWikiMsg() {
1609 $msg = wfMessage( 'parentheses' );
1610 $this->assertSame( '(a)', $msg->rawParams( 'a' )->plain() );
1612 $op = $this->newInstance();
1613 $this->assertSame( '', $op->getHTML() );
1614 $op->wrapWikiMsg( '[$1]', [ 'parentheses', "<b>a" ] );
1615 // This is known to be bad unbalanced HTML; this will be fixed
1616 // by I743f4185a03403f8d9b9db010ff1ee4e9342e062 (T198214)
1617 $this->assertSame( "<p>[(<b>a)]\n</p>", $op->getHTML() );
1621 * @covers OutputPage::addParserOutputMetadata
1623 public function testNoGallery() {
1624 $op = $this->newInstance();
1625 $this->assertFalse( $op->mNoGallery
);
1627 $stubPO1 = $this->createParserOutputStub( 'getNoGallery', true );
1628 $op->addParserOutputMetadata( $stubPO1 );
1629 $this->assertTrue( $op->mNoGallery
);
1631 $stubPO2 = $this->createParserOutputStub( 'getNoGallery', false );
1632 $op->addParserOutputMetadata( $stubPO2 );
1633 $this->assertFalse( $op->mNoGallery
);
1636 // @todo Make sure to test the following in addParserOutputMetadata() as well when we add tests
1638 // * enableClientCache()
1640 // * addModuleScripts()
1641 // * addModuleStyles()
1642 // * addJsConfigVars()
1643 // * preventClickJacking()
1644 // Otherwise those lines of addParserOutputMetadata() will be reported as covered, but we won't
1645 // be testing they actually work.
1648 * @covers OutputPage::haveCacheVaryCookies
1650 public function testHaveCacheVaryCookies() {
1651 $request = new FauxRequest();
1652 $context = new RequestContext();
1653 $context->setRequest( $request );
1654 $op = new OutputPage( $context );
1656 // No cookies are set.
1657 $this->assertFalse( $op->haveCacheVaryCookies() );
1659 // 'Token' is present but empty, so it shouldn't count.
1660 $request->setCookie( 'Token', '' );
1661 $this->assertFalse( $op->haveCacheVaryCookies() );
1663 // 'Token' present and nonempty.
1664 $request->setCookie( 'Token', '123' );
1665 $this->assertTrue( $op->haveCacheVaryCookies() );
1669 * @dataProvider provideVaryHeaders
1671 * @covers OutputPage::addVaryHeader
1672 * @covers OutputPage::getVaryHeader
1673 * @covers OutputPage::getKeyHeader
1675 public function testVaryHeaders( $calls, $vary, $key ) {
1676 // get rid of default Vary fields
1677 $op = $this->getMockBuilder( OutputPage
::class )
1678 ->setConstructorArgs( [ new RequestContext() ] )
1679 ->setMethods( [ 'getCacheVaryCookies' ] )
1681 $op->expects( $this->any() )
1682 ->method( 'getCacheVaryCookies' )
1683 ->will( $this->returnValue( [] ) );
1684 TestingAccessWrapper
::newFromObject( $op )->mVaryHeader
= [];
1686 foreach ( $calls as $call ) {
1687 call_user_func_array( [ $op, 'addVaryHeader' ], $call );
1689 $this->assertEquals( $vary, $op->getVaryHeader(), 'Vary:' );
1690 $this->assertEquals( $key, $op->getKeyHeader(), 'Key:' );
1693 public function provideVaryHeaders() {
1694 // note: getKeyHeader() automatically adds Vary: Cookie
1703 [ // non-unique headers
1706 [ 'Accept-Language' ],
1709 'Vary: Cookie, Accept-Language',
1710 'Key: Cookie,Accept-Language',
1712 [ // two headers with single options
1714 [ 'Cookie', [ 'param=phpsessid' ] ],
1715 [ 'Accept-Language', [ 'substr=en' ] ],
1717 'Vary: Cookie, Accept-Language',
1718 'Key: Cookie;param=phpsessid,Accept-Language;substr=en',
1720 [ // one header with multiple options
1722 [ 'Cookie', [ 'param=phpsessid', 'param=userId' ] ],
1725 'Key: Cookie;param=phpsessid;param=userId',
1727 [ // Duplicate option
1729 [ 'Cookie', [ 'param=phpsessid' ] ],
1730 [ 'Cookie', [ 'param=phpsessid' ] ],
1731 [ 'Accept-Language', [ 'substr=en', 'substr=en' ] ],
1733 'Vary: Cookie, Accept-Language',
1734 'Key: Cookie;param=phpsessid,Accept-Language;substr=en',
1736 [ // Same header, different options
1738 [ 'Cookie', [ 'param=phpsessid' ] ],
1739 [ 'Cookie', [ 'param=userId' ] ],
1742 'Key: Cookie;param=phpsessid;param=userId',
1748 * @dataProvider provideLinkHeaders
1750 * @covers OutputPage::addLinkHeader
1751 * @covers OutputPage::getLinkHeader
1753 public function testLinkHeaders( $headers, $result ) {
1754 $op = $this->newInstance();
1756 foreach ( $headers as $header ) {
1757 $op->addLinkHeader( $header );
1760 $this->assertEquals( $result, $op->getLinkHeader() );
1763 public function provideLinkHeaders() {
1770 [ '<https://foo/bar.jpg>;rel=preload;as=image' ],
1771 'Link: <https://foo/bar.jpg>;rel=preload;as=image',
1774 [ '<https://foo/bar.jpg>;rel=preload;as=image','<https://foo/baz.jpg>;rel=preload;as=image' ],
1775 'Link: <https://foo/bar.jpg>;rel=preload;as=image,<https://foo/baz.jpg>;rel=preload;as=image',
1781 * See ResourceLoaderClientHtmlTest for full coverage.
1783 * @dataProvider provideMakeResourceLoaderLink
1785 * @covers OutputPage::makeResourceLoaderLink
1787 public function testMakeResourceLoaderLink( $args, $expectedHtml ) {
1788 $this->setMwGlobals( [
1789 'wgResourceLoaderDebug' => false,
1790 'wgLoadScript' => 'http://127.0.0.1:8080/w/load.php',
1791 'wgCSPReportOnlyHeader' => true,
1793 $class = new ReflectionClass( OutputPage
::class );
1794 $method = $class->getMethod( 'makeResourceLoaderLink' );
1795 $method->setAccessible( true );
1796 $ctx = new RequestContext();
1797 $ctx->setSkin( SkinFactory
::getDefaultInstance()->makeSkin( 'fallback' ) );
1798 $ctx->setLanguage( 'en' );
1799 $out = new OutputPage( $ctx );
1800 $nonce = $class->getProperty( 'CSPNonce' );
1801 $nonce->setAccessible( true );
1802 $nonce->setValue( $out, 'secret' );
1803 $rl = $out->getResourceLoader();
1804 $rl->setMessageBlobStore( new NullMessageBlobStore() );
1806 'test.foo' => new ResourceLoaderTestModule( [
1807 'script' => 'mw.test.foo( { a: true } );',
1808 'styles' => '.mw-test-foo { content: "style"; }',
1810 'test.bar' => new ResourceLoaderTestModule( [
1811 'script' => 'mw.test.bar( { a: true } );',
1812 'styles' => '.mw-test-bar { content: "style"; }',
1814 'test.baz' => new ResourceLoaderTestModule( [
1815 'script' => 'mw.test.baz( { a: true } );',
1816 'styles' => '.mw-test-baz { content: "style"; }',
1818 'test.quux' => new ResourceLoaderTestModule( [
1819 'script' => 'mw.test.baz( { token: 123 } );',
1820 'styles' => '/* pref-animate=off */ .mw-icon { transition: none; }',
1821 'group' => 'private',
1823 'test.noscript' => new ResourceLoaderTestModule( [
1824 'styles' => '.stuff { color: red; }',
1825 'group' => 'noscript',
1827 'test.group.foo' => new ResourceLoaderTestModule( [
1828 'script' => 'mw.doStuff( "foo" );',
1831 'test.group.bar' => new ResourceLoaderTestModule( [
1832 'script' => 'mw.doStuff( "bar" );',
1836 $links = $method->invokeArgs( $out, $args );
1837 $actualHtml = strval( $links );
1838 $this->assertEquals( $expectedHtml, $actualHtml );
1841 public static function provideMakeResourceLoaderLink() {
1842 // phpcs:disable Generic.Files.LineLength
1844 // Single only=scripts load
1846 [ 'test.foo', ResourceLoaderModule
::TYPE_SCRIPTS
],
1847 "<script nonce=\"secret\">(window.RLQ=window.RLQ||[]).push(function(){"
1848 . 'mw.loader.load("http://127.0.0.1:8080/w/load.php?debug=false\u0026lang=en\u0026modules=test.foo\u0026only=scripts\u0026skin=fallback");'
1851 // Multiple only=styles load
1853 [ [ 'test.baz', 'test.foo', 'test.bar' ], ResourceLoaderModule
::TYPE_STYLES
],
1855 '<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"/>'
1857 // Private embed (only=scripts)
1859 [ 'test.quux', ResourceLoaderModule
::TYPE_SCRIPTS
],
1860 "<script nonce=\"secret\">(window.RLQ=window.RLQ||[]).push(function(){"
1861 . "mw.test.baz({token:123});\nmw.loader.state({\"test.quux\":\"ready\"});"
1864 // Load private module (combined)
1866 [ 'test.quux', ResourceLoaderModule
::TYPE_COMBINED
],
1867 "<script nonce=\"secret\">(window.RLQ=window.RLQ||[]).push(function(){"
1868 . "mw.loader.implement(\"test.quux@1ev0ijv\",function($,jQuery,require,module){"
1869 . "mw.test.baz({token:123});},{\"css\":[\".mw-icon{transition:none}"
1870 . "\"]});});</script>"
1874 [ [], ResourceLoaderModule
::TYPE_COMBINED
],
1879 [ 'test.noscript', ResourceLoaderModule
::TYPE_STYLES
],
1880 '<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>'
1882 // Load two modules in separate groups
1884 [ [ 'test.group.foo', 'test.group.bar' ], ResourceLoaderModule
::TYPE_COMBINED
],
1885 "<script nonce=\"secret\">(window.RLQ=window.RLQ||[]).push(function(){"
1886 . 'mw.loader.load("http://127.0.0.1:8080/w/load.php?debug=false\u0026lang=en\u0026modules=test.group.bar\u0026skin=fallback");'
1887 . 'mw.loader.load("http://127.0.0.1:8080/w/load.php?debug=false\u0026lang=en\u0026modules=test.group.foo\u0026skin=fallback");'
1895 * @dataProvider provideBuildExemptModules
1897 * @covers OutputPage::buildExemptModules
1899 public function testBuildExemptModules( array $exemptStyleModules, $expect ) {
1900 $this->setMwGlobals( [
1901 'wgResourceLoaderDebug' => false,
1902 'wgLoadScript' => '/w/load.php',
1903 // Stub wgCacheEpoch as it influences getVersionHash used for the
1904 // urls in the expected HTML
1905 'wgCacheEpoch' => '20140101000000',
1909 $ctx = new RequestContext();
1910 $ctx->setSkin( SkinFactory
::getDefaultInstance()->makeSkin( 'fallback' ) );
1911 $ctx->setLanguage( 'en' );
1912 $op = $this->getMockBuilder( OutputPage
::class )
1913 ->setConstructorArgs( [ $ctx ] )
1914 ->setMethods( [ 'buildCssLinksArray' ] )
1916 $op->expects( $this->any() )
1917 ->method( 'buildCssLinksArray' )
1919 $rl = $op->getResourceLoader();
1920 $rl->setMessageBlobStore( new NullMessageBlobStore() );
1922 // Register custom modules
1924 'example.site.a' => new ResourceLoaderTestModule( [ 'group' => 'site' ] ),
1925 'example.site.b' => new ResourceLoaderTestModule( [ 'group' => 'site' ] ),
1926 'example.user' => new ResourceLoaderTestModule( [ 'group' => 'user' ] ),
1929 $op = TestingAccessWrapper
::newFromObject( $op );
1930 $op->rlExemptStyleModules
= $exemptStyleModules;
1931 $this->assertEquals(
1933 strval( $op->buildExemptModules() )
1937 public static function provideBuildExemptModules() {
1938 // phpcs:disable Generic.Files.LineLength
1941 'exemptStyleModules' => [],
1942 '<meta name="ResourceLoaderDynamicStyles" content=""/>',
1945 'exemptStyleModules' => [ 'site' => [], 'noscript' => [], 'private' => [], 'user' => [] ],
1946 '<meta name="ResourceLoaderDynamicStyles" content=""/>',
1948 'default logged-out' => [
1949 'exemptStyleModules' => [ 'site' => [ 'site.styles' ] ],
1950 '<meta name="ResourceLoaderDynamicStyles" content=""/>' . "\n" .
1951 '<link rel="stylesheet" href="/w/load.php?debug=false&lang=en&modules=site.styles&only=styles&skin=fallback"/>',
1953 'default logged-in' => [
1954 'exemptStyleModules' => [ 'site' => [ 'site.styles' ], 'user' => [ 'user.styles' ] ],
1955 '<meta name="ResourceLoaderDynamicStyles" content=""/>' . "\n" .
1956 '<link rel="stylesheet" href="/w/load.php?debug=false&lang=en&modules=site.styles&only=styles&skin=fallback"/>' . "\n" .
1957 '<link rel="stylesheet" href="/w/load.php?debug=false&lang=en&modules=user.styles&only=styles&skin=fallback&version=1ai9g6t"/>',
1959 'custom modules' => [
1960 'exemptStyleModules' => [
1961 'site' => [ 'site.styles', 'example.site.a', 'example.site.b' ],
1962 'user' => [ 'user.styles', 'example.user' ],
1964 '<meta name="ResourceLoaderDynamicStyles" content=""/>' . "\n" .
1965 '<link rel="stylesheet" href="/w/load.php?debug=false&lang=en&modules=example.site.a%2Cb&only=styles&skin=fallback"/>' . "\n" .
1966 '<link rel="stylesheet" href="/w/load.php?debug=false&lang=en&modules=site.styles&only=styles&skin=fallback"/>' . "\n" .
1967 '<link rel="stylesheet" href="/w/load.php?debug=false&lang=en&modules=example.user&only=styles&skin=fallback&version=0a56zyi"/>' . "\n" .
1968 '<link rel="stylesheet" href="/w/load.php?debug=false&lang=en&modules=user.styles&only=styles&skin=fallback&version=1ai9g6t"/>',
1975 * @dataProvider provideTransformFilePath
1976 * @covers OutputPage::transformFilePath
1977 * @covers OutputPage::transformResourcePath
1979 public function testTransformResourcePath( $baseDir, $basePath, $uploadDir = null,
1980 $uploadPath = null, $path = null, $expected = null
1982 if ( $path === null ) {
1983 // Skip optional $uploadDir and $uploadPath
1985 $expected = $uploadPath;
1986 $uploadDir = "$baseDir/images";
1987 $uploadPath = "$basePath/images";
1989 $this->setMwGlobals( 'IP', $baseDir );
1990 $conf = new HashConfig( [
1991 'ResourceBasePath' => $basePath,
1992 'UploadDirectory' => $uploadDir,
1993 'UploadPath' => $uploadPath,
1996 // Some of these paths don't exist and will cause warnings
1997 Wikimedia\
suppressWarnings();
1998 $actual = OutputPage
::transformResourcePath( $conf, $path );
1999 Wikimedia\restoreWarnings
();
2001 $this->assertEquals( $expected ?
: $path, $actual );
2004 public static function provideTransformFilePath() {
2005 $baseDir = dirname( __DIR__
) . '/data/media';
2007 // File that matches basePath, and exists. Hash found and appended.
2009 'baseDir' => $baseDir, 'basePath' => '/w',
2013 // File that matches basePath, but not found on disk. Empty query.
2015 'baseDir' => $baseDir, 'basePath' => '/w',
2019 // File not matching basePath. Ignored.
2021 'baseDir' => $baseDir, 'basePath' => '/w',
2024 // Empty string. Ignored.
2026 'baseDir' => $baseDir, 'basePath' => '/w',
2030 // Similar path, but with domain component. Ignored.
2032 'baseDir' => $baseDir, 'basePath' => '/w',
2033 '//example.org/w/test.jpg'
2036 'baseDir' => $baseDir, 'basePath' => '/w',
2037 'https://example.org/w/test.jpg'
2039 // Unrelated path with domain component. Ignored.
2041 'baseDir' => $baseDir, 'basePath' => '/w',
2042 'https://example.org/files/test.jpg'
2045 'baseDir' => $baseDir, 'basePath' => '/w',
2046 '//example.org/files/test.jpg'
2048 // Unrelated path with domain, and empty base path (root mw install). Ignored.
2050 'baseDir' => $baseDir, 'basePath' => '',
2051 'https://example.org/files/test.jpg'
2054 'baseDir' => $baseDir, 'basePath' => '',
2056 '//example.org/files/test.jpg'
2058 // Check UploadPath before ResourceBasePath (T155146)
2060 'baseDir' => dirname( $baseDir ), 'basePath' => '',
2061 'uploadDir' => $baseDir, 'uploadPath' => '/images',
2063 '/images/test.jpg?edcf2'
2069 * Tests a particular case of transformCssMedia, using the given input, globals,
2070 * expected return, and message
2072 * Asserts that $expectedReturn is returned.
2074 * options['printableQuery'] - value of query string for printable, or omitted for none
2075 * options['handheldQuery'] - value of query string for handheld, or omitted for none
2076 * options['media'] - passed into the method under the same name
2077 * options['expectedReturn'] - expected return value
2078 * options['message'] - PHPUnit message for assertion
2080 * @param array $args Key-value array of arguments as shown above
2082 protected function assertTransformCssMediaCase( $args ) {
2084 if ( isset( $args['printableQuery'] ) ) {
2085 $queryData['printable'] = $args['printableQuery'];
2088 if ( isset( $args['handheldQuery'] ) ) {
2089 $queryData['handheld'] = $args['handheldQuery'];
2092 $fauxRequest = new FauxRequest( $queryData, false );
2093 $this->setMwGlobals( [
2094 'wgRequest' => $fauxRequest,
2097 $actualReturn = OutputPage
::transformCssMedia( $args['media'] );
2098 $this->assertSame( $args['expectedReturn'], $actualReturn, $args['message'] );
2102 * Tests print requests
2104 * @covers OutputPage::transformCssMedia
2106 public function testPrintRequests() {
2107 $this->assertTransformCssMediaCase( [
2108 'printableQuery' => '1',
2109 'media' => 'screen',
2110 'expectedReturn' => null,
2111 'message' => 'On printable request, screen returns null'
2114 $this->assertTransformCssMediaCase( [
2115 'printableQuery' => '1',
2116 'media' => self
::SCREEN_MEDIA_QUERY
,
2117 'expectedReturn' => null,
2118 'message' => 'On printable request, screen media query returns null'
2121 $this->assertTransformCssMediaCase( [
2122 'printableQuery' => '1',
2123 'media' => self
::SCREEN_ONLY_MEDIA_QUERY
,
2124 'expectedReturn' => null,
2125 'message' => 'On printable request, screen media query with only returns null'
2128 $this->assertTransformCssMediaCase( [
2129 'printableQuery' => '1',
2131 'expectedReturn' => '',
2132 'message' => 'On printable request, media print returns empty string'
2137 * Tests screen requests, without either query parameter set
2139 * @covers OutputPage::transformCssMedia
2141 public function testScreenRequests() {
2142 $this->assertTransformCssMediaCase( [
2143 'media' => 'screen',
2144 'expectedReturn' => 'screen',
2145 'message' => 'On screen request, screen media type is preserved'
2148 $this->assertTransformCssMediaCase( [
2149 'media' => 'handheld',
2150 'expectedReturn' => 'handheld',
2151 'message' => 'On screen request, handheld media type is preserved'
2154 $this->assertTransformCssMediaCase( [
2155 'media' => self
::SCREEN_MEDIA_QUERY
,
2156 'expectedReturn' => self
::SCREEN_MEDIA_QUERY
,
2157 'message' => 'On screen request, screen media query is preserved.'
2160 $this->assertTransformCssMediaCase( [
2161 'media' => self
::SCREEN_ONLY_MEDIA_QUERY
,
2162 'expectedReturn' => self
::SCREEN_ONLY_MEDIA_QUERY
,
2163 'message' => 'On screen request, screen media query with only is preserved.'
2166 $this->assertTransformCssMediaCase( [
2168 'expectedReturn' => 'print',
2169 'message' => 'On screen request, print media type is preserved'
2174 * Tests handheld behavior
2176 * @covers OutputPage::transformCssMedia
2178 public function testHandheld() {
2179 $this->assertTransformCssMediaCase( [
2180 'handheldQuery' => '1',
2181 'media' => 'handheld',
2182 'expectedReturn' => '',
2183 'message' => 'On request with handheld querystring and media is handheld, returns empty string'
2186 $this->assertTransformCssMediaCase( [
2187 'handheldQuery' => '1',
2188 'media' => 'screen',
2189 'expectedReturn' => null,
2190 'message' => 'On request with handheld querystring and media is screen, returns null'
2195 * @return OutputPage
2197 private function newInstance( $config = [], WebRequest
$request = null, $options = [] ) {
2198 $context = new RequestContext();
2200 $context->setConfig( new MultiConfig( [
2201 new HashConfig( $config +
[
2202 'AppleTouchIcon' => false,
2203 'DisableLangConversion' => true,
2204 'EnableCanonicalServerLink' => false,
2207 'LanguageCode' => false,
2208 'ReferrerPolicy' => false,
2209 'RightsPage' => false,
2210 'RightsUrl' => false,
2211 'UniversalEditButton' => false,
2213 $context->getConfig()
2216 if ( !in_array( 'notitle', (array)$options ) ) {
2217 $context->setTitle( Title
::newFromText( 'My test page' ) );
2221 $context->setRequest( $request );
2224 return new OutputPage( $context );
2229 * MessageBlobStore that doesn't do anything
2231 class NullMessageBlobStore
extends MessageBlobStore
{
2232 public function get( ResourceLoader
$resourceLoader, $modules, $lang ) {
2236 public function updateModule( $name, ResourceLoaderModule
$module, $lang ) {
2239 public function updateMessage( $key ) {
2242 public function clear() {