3 use Wikimedia\TestingAccessWrapper
;
6 * @author Matthew Flaschen
11 class OutputPageTest
extends MediaWikiTestCase
{
12 const SCREEN_MEDIA_QUERY
= 'screen and (min-width: 982px)';
13 const SCREEN_ONLY_MEDIA_QUERY
= 'only screen and (min-width: 982px)';
16 * @dataProvider provideRedirect
18 * @covers OutputPage::__construct
19 * @covers OutputPage::redirect
20 * @covers OutputPage::getRedirect
22 public function testRedirect( $url, $code = null ) {
23 $op = $this->newInstance();
24 if ( isset( $code ) ) {
25 $op->redirect( $url, $code );
27 $op->redirect( $url );
29 $expectedUrl = str_replace( "\n", '', $url );
30 $this->assertSame( $expectedUrl, $op->getRedirect() );
31 $this->assertSame( $expectedUrl, $op->mRedirect
);
32 $this->assertSame( $code ??
'302', $op->mRedirectCode
);
35 public function provideRedirect() {
37 [ 'http://example.com' ],
38 [ 'http://example.com', '400' ],
39 [ 'http://example.com', 'squirrels!!!' ],
45 * @covers OutputPage::setCopyrightUrl
46 * @covers OutputPage::getHeadLinksArray
48 public function testSetCopyrightUrl() {
49 $op = $this->newInstance();
50 $op->setCopyrightUrl( 'http://example.com' );
53 Html
::element( 'link', [ 'rel' => 'license', 'href' => 'http://example.com' ] ),
54 $op->getHeadLinksArray()['copyright']
58 // @todo How to test setStatusCode?
61 * @covers OutputPage::addMeta
62 * @covers OutputPage::getMetaTags
63 * @covers OutputPage::getHeadLinksArray
65 public function testMetaTags() {
66 $op = $this->newInstance();
67 $op->addMeta( 'http:expires', '0' );
68 $op->addMeta( 'keywords', 'first' );
69 $op->addMeta( 'keywords', 'second' );
70 $op->addMeta( 'og:title', 'Ta-duh' );
73 [ 'http:expires', '0' ],
74 [ 'keywords', 'first' ],
75 [ 'keywords', 'second' ],
76 [ 'og:title', 'Ta-duh' ],
78 $this->assertSame( $expected, $op->getMetaTags() );
80 $links = $op->getHeadLinksArray();
81 $this->assertContains( '<meta http-equiv="expires" content="0"/>', $links );
82 $this->assertContains( '<meta name="keywords" content="first"/>', $links );
83 $this->assertContains( '<meta name="keywords" content="second"/>', $links );
84 $this->assertContains( '<meta property="og:title" content="Ta-duh"/>', $links );
85 $this->assertArrayNotHasKey( 'meta-robots', $links );
89 * @covers OutputPage::addLink
90 * @covers OutputPage::getLinkTags
91 * @covers OutputPage::getHeadLinksArray
93 public function testAddLink() {
94 $op = $this->newInstance();
98 [ 'rel' => 'foo', 'href' => 'http://example.com' ],
101 foreach ( $links as $link ) {
102 $op->addLink( $link );
105 $this->assertSame( $links, $op->getLinkTags() );
107 $result = $op->getHeadLinksArray();
109 foreach ( $links as $link ) {
110 $this->assertContains( Html
::element( 'link', $link ), $result );
115 * @covers OutputPage::setCanonicalUrl
116 * @covers OutputPage::getCanonicalUrl
117 * @covers OutputPage::getHeadLinksArray
119 public function testSetCanonicalUrl() {
120 $op = $this->newInstance();
121 $op->setCanonicalUrl( 'http://example.comm' );
122 $op->setCanonicalUrl( 'http://example.com' );
124 $this->assertSame( 'http://example.com', $op->getCanonicalUrl() );
126 $headLinks = $op->getHeadLinksArray();
128 $this->assertContains( Html
::element( 'link', [
129 'rel' => 'canonical', 'href' => 'http://example.com'
132 $this->assertNotContains( Html
::element( 'link', [
133 'rel' => 'canonical', 'href' => 'http://example.comm'
138 * @covers OutputPage::addScript
140 public function testAddScript() {
141 $op = $this->newInstance();
142 $op->addScript( 'some random string' );
144 $this->assertContains( "\nsome random string\n", "\n" . $op->getBottomScripts() . "\n" );
148 * @covers OutputPage::addScriptFile
150 public function testAddScriptFile() {
151 $op = $this->newInstance();
152 $op->addScriptFile( '/somescript.js' );
153 $op->addScriptFile( '//example.com/somescript.js' );
155 $this->assertContains(
156 "\n" . Html
::linkedScript( '/somescript.js', $op->getCSPNonce() ) .
157 Html
::linkedScript( '//example.com/somescript.js', $op->getCSPNonce() ) . "\n",
158 "\n" . $op->getBottomScripts() . "\n"
163 * Test that addScriptFile() throws due to deprecation.
165 * @covers OutputPage::addScriptFile
167 public function testAddDeprecatedScriptFileWarning() {
168 $this->setExpectedException( PHPUnit_Framework_Error_Deprecated
::class,
169 'Use of OutputPage::addScriptFile was deprecated in MediaWiki 1.24.' );
171 $op = $this->newInstance();
172 $op->addScriptFile( 'ignored-script.js' );
176 * Test the actual behavior of the method (in the case where it doesn't throw, e.g., in
177 * production). Since it threw an exception once in this file, it won't when we call it again.
179 * @covers OutputPage::addScriptFile
181 public function testAddDeprecatedScriptFileNoOp() {
182 $op = $this->newInstance();
183 $op->addScriptFile( 'ignored-script.js' );
185 $this->assertNotContains( 'ignored-script.js', '' . $op->getBottomScripts() );
189 * @covers OutputPage::addInlineScript
191 public function testAddInlineScript() {
192 $op = $this->newInstance();
193 $op->addInlineScript( 'let foo = "bar";' );
194 $op->addInlineScript( 'alert( foo );' );
196 $this->assertContains(
197 "\n" . Html
::inlineScript( "\nlet foo = \"bar\";\n", $op->getCSPNonce() ) . "\n" .
198 Html
::inlineScript( "\nalert( foo );\n", $op->getCSPNonce() ) . "\n",
199 "\n" . $op->getBottomScripts() . "\n"
203 // @todo How to test filterModules(), warnModuleTargetFilter(), getModules(), etc.?
206 * @covers OutputPage::getTarget
207 * @covers OutputPage::setTarget
209 public function testSetTarget() {
210 $op = $this->newInstance();
211 $op->setTarget( 'foo' );
213 $this->assertSame( 'foo', $op->getTarget() );
214 // @todo What else? Test some actual effect?
217 // @todo How to test addContentOverride(Callback)?
220 * @covers OutputPage::getHeadItemsArray
221 * @covers OutputPage::addHeadItem
222 * @covers OutputPage::addHeadItems
223 * @covers OutputPage::hasHeadItem
225 public function testHeadItems() {
226 $op = $this->newInstance();
227 $op->addHeadItem( 'a', 'b' );
228 $op->addHeadItems( [ 'c' => '<d>&', 'e' => 'f', 'a' => 'q' ] );
229 $op->addHeadItem( 'e', 'g' );
230 $op->addHeadItems( 'x' );
232 $this->assertSame( [ 'a' => 'q', 'c' => '<d>&', 'e' => 'g', 'x' ],
233 $op->getHeadItemsArray() );
235 $this->assertTrue( $op->hasHeadItem( 'a' ) );
236 $this->assertTrue( $op->hasHeadItem( 'c' ) );
237 $this->assertTrue( $op->hasHeadItem( 'e' ) );
238 $this->assertTrue( $op->hasHeadItem( '0' ) );
240 $this->assertContains( "\nq\n<d>&\ng\nx\n",
241 '' . $op->headElement( $op->getContext()->getSkin() ) );
245 * @covers OutputPage::addBodyClasses
247 public function testAddBodyClasses() {
248 $op = $this->newInstance();
249 $op->addBodyClasses( 'a' );
250 $op->addBodyClasses( 'mediawiki' );
251 $op->addBodyClasses( 'b c' );
252 $op->addBodyClasses( [ 'd', 'e' ] );
253 $op->addBodyClasses( 'a' );
255 $this->assertContains( '"a mediawiki b c d e ltr',
256 '' . $op->headElement( $op->getContext()->getSkin() ) );
260 * @covers OutputPage::setArticleBodyOnly
261 * @covers OutputPage::getArticleBodyOnly
263 public function testArticleBodyOnly() {
264 $op = $this->newInstance();
265 $this->assertFalse( $op->getArticleBodyOnly() );
267 $op->setArticleBodyOnly( true );
268 $this->assertTrue( $op->getArticleBodyOnly() );
270 $op->addHTML( '<b>a</b>' );
272 $this->assertSame( '<b>a</b>', $op->output( true ) );
276 * @covers OutputPage::setProperty
277 * @covers OutputPage::getProperty
279 public function testProperties() {
280 $op = $this->newInstance();
282 $this->assertNull( $op->getProperty( 'foo' ) );
284 $op->setProperty( 'foo', 'bar' );
285 $op->setProperty( 'baz', 'quz' );
287 $this->assertSame( 'bar', $op->getProperty( 'foo' ) );
288 $this->assertSame( 'quz', $op->getProperty( 'baz' ) );
292 * @dataProvider provideCheckLastModified
294 * @covers OutputPage::checkLastModified
295 * @covers OutputPage::getCdnCacheEpoch
297 public function testCheckLastModified(
298 $timestamp, $ifModifiedSince, $expected, $config = [], $callback = null
300 $request = new FauxRequest();
301 if ( $ifModifiedSince ) {
302 if ( is_numeric( $ifModifiedSince ) ) {
304 $ifModifiedSince = date( 'D, d M Y H:i:s', $ifModifiedSince ) . ' GMT';
306 $request->setHeader( 'If-Modified-Since', $ifModifiedSince );
309 if ( !isset( $config['CacheEpoch'] ) ) {
310 // Make sure it's not too recent
311 $config['CacheEpoch'] = '20000101000000';
314 $op = $this->newInstance( $config, $request );
317 $callback( $op, $this );
320 // Avoid a complaint about not being able to disable compression
321 Wikimedia\
suppressWarnings();
323 $this->assertEquals( $expected, $op->checkLastModified( $timestamp ) );
325 Wikimedia\restoreWarnings
();
329 public function provideCheckLastModified() {
330 $lastModified = time() - 3600;
333 [ '0', $lastModified, false ],
334 'Timestamp Unix epoch' =>
335 [ '19700101000000', $lastModified, false ],
336 'Timestamp same as If-Modified-Since' =>
337 [ $lastModified, $lastModified, true ],
338 'Timestamp one second after If-Modified-Since' =>
339 [ $lastModified +
1, $lastModified, false ],
340 'No If-Modified-Since' =>
341 [ $lastModified +
1, null, false ],
342 'Malformed If-Modified-Since' =>
343 [ $lastModified +
1, 'GIBBERING WOMBATS !!!', false ],
344 'Non-standard IE-style If-Modified-Since' =>
345 [ $lastModified, date( 'D, d M Y H:i:s', $lastModified ) . ' GMT; length=5202',
347 // @todo Should we fix this behavior to match the spec? Probably no reason to.
348 'If-Modified-Since not per spec but we accept it anyway because strtotime does' =>
349 [ $lastModified, "@$lastModified", true ],
350 '$wgCachePages = false' =>
351 [ $lastModified, $lastModified, false, [ 'CachePages' => false ] ],
353 [ $lastModified, $lastModified, false,
354 [ 'CacheEpoch' => wfTimestamp( TS_MW
, $lastModified +
1 ) ] ],
355 'Recently-touched user' =>
356 [ $lastModified, $lastModified, false, [],
358 $op->getContext()->setUser( $this->getTestUser()->getUser() );
360 'After Squid expiry' =>
361 [ $lastModified, $lastModified, false,
362 [ 'UseSquid' => true, 'SquidMaxage' => 3599 ] ],
363 'Hook allows cache use' =>
364 [ $lastModified +
1, $lastModified, true, [],
365 function ( $op, $that ) {
366 $that->setTemporaryHook( 'OutputPageCheckLastModified',
367 function ( &$modifiedTimes ) {
368 $modifiedTimes = [ 1 ];
372 'Hooks prohibits cache use' =>
373 [ $lastModified, $lastModified, false, [],
374 function ( $op, $that ) {
375 $that->setTemporaryHook( 'OutputPageCheckLastModified',
376 function ( &$modifiedTimes ) {
377 $modifiedTimes = [ max( $modifiedTimes ) +
1 ];
385 * @dataProvider provideCdnCacheEpoch
387 * @covers OutputPage::getCdnCacheEpoch
389 public function testCdnCacheEpoch( $params ) {
390 $out = TestingAccessWrapper
::newFromObject( $this->newInstance() );
391 $reqTime = strtotime( $params['reqTime'] );
392 $pageTime = strtotime( $params['pageTime'] );
393 $actual = max( $pageTime, $out->getCdnCacheEpoch( $reqTime, $params['maxAge'] ) );
397 gmdate( DateTime
::ATOM
, $actual ),
402 public static function provideCdnCacheEpoch() {
404 'pageTime' => '2011-04-01T12:00:00+00:00',
405 'maxAge' => 24 * 3600,
408 'after 1s' => [ $base +
[
409 'reqTime' => '2011-04-01T12:00:01+00:00',
410 'expect' => '2011-04-01T12:00:00+00:00',
412 'after 23h' => [ $base +
[
413 'reqTime' => '2011-04-02T11:00:00+00:00',
414 'expect' => '2011-04-01T12:00:00+00:00',
416 'after 24h and a bit' => [ $base +
[
417 'reqTime' => '2011-04-02T12:34:56+00:00',
418 'expect' => '2011-04-01T12:34:56+00:00',
420 'after a year' => [ $base +
[
421 'reqTime' => '2012-05-06T00:12:07+00:00',
422 'expect' => '2012-05-05T00:12:07+00:00',
427 // @todo How to test setLastModified?
430 * @covers OutputPage::setRobotPolicy
431 * @covers OutputPage::getHeadLinksArray
433 public function testSetRobotPolicy() {
434 $op = $this->newInstance();
435 $op->setRobotPolicy( 'noindex, nofollow' );
437 $links = $op->getHeadLinksArray();
438 $this->assertContains( '<meta name="robots" content="noindex,nofollow"/>', $links );
442 * @covers OutputPage::setIndexPolicy
443 * @covers OutputPage::setFollowPolicy
444 * @covers OutputPage::getHeadLinksArray
446 public function testSetIndexFollowPolicies() {
447 $op = $this->newInstance();
448 $op->setIndexPolicy( 'noindex' );
449 $op->setFollowPolicy( 'nofollow' );
451 $links = $op->getHeadLinksArray();
452 $this->assertContains( '<meta name="robots" content="noindex,nofollow"/>', $links );
455 // @todo mPageTitleActionText has done nothing and has no callers for a long time:
457 // * e4d21170 inadvertently made it do nothing (Apr 2009)
458 // * 10ecfcb0/cadc951d removed the dead code that would have at least indicated what it was
459 // supposed to do (Nov 2010)
460 // * 9e230f30/2d045fa1 removed from history pages because it did nothing (Oct/Aug 2011)
461 // * e275ea28 removed from articles (Oct 2011)
462 // * ae45908c removed from EditPage (Oct 2011)
464 // Nice if we had had tests so these things couldn't happen by mistake, right?!
466 // https://phabricator.wikimedia.org/T200643
468 private function extractHTMLTitle( OutputPage
$op ) {
469 $html = $op->headElement( $op->getContext()->getSkin() );
471 // OutputPage should always output the title in a nice format such that regexes will work
472 // fine. If it doesn't, we'll fail the tests.
473 preg_match_all( '!<title>(.*?)</title>!', $html, $matches );
475 $this->assertLessThanOrEqual( 1, count( $matches[1] ), 'More than one <title>!' );
477 if ( !count( $matches[1] ) ) {
481 return $matches[1][0];
485 * Shorthand for getting the text of a message, in content language.
487 private static function getMsgText( $op, ...$msgParams ) {
488 return $op->msg( ...$msgParams )->inContentLanguage()->text();
492 * @covers OutputPage::setHTMLTitle
493 * @covers OutputPage::getHTMLTitle
495 public function testHTMLTitle() {
496 $op = $this->newInstance();
499 $this->assertSame( '', $op->getHTMLTitle() );
500 $this->assertSame( '', $op->getPageTitle() );
502 $this->getMsgText( $op, 'pagetitle', '' ),
503 $this->extractHTMLTitle( $op )
507 $op->setHTMLTitle( 'Potatoes will eat me' );
509 $this->assertSame( 'Potatoes will eat me', $op->getHTMLTitle() );
510 $this->assertSame( 'Potatoes will eat me', $this->extractHTMLTitle( $op ) );
511 // Shouldn't have changed the page title
512 $this->assertSame( '', $op->getPageTitle() );
515 $msg = $op->msg( 'mainpage' );
517 $op->setHTMLTitle( $msg );
518 $this->assertSame( $msg->text(), $op->getHTMLTitle() );
519 $this->assertSame( $msg->text(), $this->extractHTMLTitle( $op ) );
520 $this->assertSame( '', $op->getPageTitle() );
524 * @covers OutputPage::setRedirectedFrom
526 public function testSetRedirectedFrom() {
527 $op = $this->newInstance();
529 $op->setRedirectedFrom( Title
::newFromText( 'Talk:Some page' ) );
530 $this->assertSame( 'Talk:Some_page', $op->getJSVars()['wgRedirectedFrom'] );
534 * @covers OutputPage::setPageTitle
535 * @covers OutputPage::getPageTitle
537 public function testPageTitle() {
538 // We don't test the actual HTML output anywhere, because that's up to the skin.
539 $op = $this->newInstance();
542 $this->assertSame( '', $op->getPageTitle() );
543 $this->assertSame( '', $op->getHTMLTitle() );
545 // Test set to plain text
546 $op->setPageTitle( 'foobar' );
548 $this->assertSame( 'foobar', $op->getPageTitle() );
549 // HTML title should change as well
550 $this->assertSame( $this->getMsgText( $op, 'pagetitle', 'foobar' ), $op->getHTMLTitle() );
552 // Test set to text with good and bad HTML. We don't try to be comprehensive here, that
553 // belongs in Sanitizer tests.
554 $op->setPageTitle( '<script>a</script>&<i>b</i>' );
556 $this->assertSame( '<script>a</script>&<i>b</i>', $op->getPageTitle() );
558 $this->getMsgText( $op, 'pagetitle', '<script>a</script>&b' ),
562 // Test set to message
563 $text = $this->getMsgText( $op, 'mainpage' );
565 $op->setPageTitle( $op->msg( 'mainpage' )->inContentLanguage() );
566 $this->assertSame( $text, $op->getPageTitle() );
567 $this->assertSame( $this->getMsgText( $op, 'pagetitle', $text ), $op->getHTMLTitle() );
571 * @covers OutputPage::setTitle
573 public function testSetTitle() {
574 $op = $this->newInstance();
576 $this->assertSame( 'My test page', $op->getTitle()->getPrefixedText() );
578 $op->setTitle( Title
::newFromText( 'Another test page' ) );
580 $this->assertSame( 'Another test page', $op->getTitle()->getPrefixedText() );
584 * @covers OutputPage::setSubtitle
585 * @covers OutputPage::clearSubtitle
586 * @covers OutputPage::addSubtitle
587 * @covers OutputPage::getSubtitle
589 public function testSubtitle() {
590 $op = $this->newInstance();
592 $this->assertSame( '', $op->getSubtitle() );
594 $op->addSubtitle( '<b>foo</b>' );
596 $this->assertSame( '<b>foo</b>', $op->getSubtitle() );
598 $op->addSubtitle( $op->msg( 'mainpage' )->inContentLanguage() );
601 "<b>foo</b><br />\n\t\t\t\t" . $this->getMsgText( $op, 'mainpage' ),
605 $op->setSubtitle( 'There can be only one' );
607 $this->assertSame( 'There can be only one', $op->getSubtitle() );
609 $op->clearSubtitle();
611 $this->assertSame( '', $op->getSubtitle() );
615 * @dataProvider provideBacklinkSubtitle
617 * @covers OutputPage::buildBacklinkSubtitle
619 public function testBuildBacklinkSubtitle( Title
$title, $query, $contains, $notContains ) {
620 $this->editPage( 'Page 1', '' );
621 $this->editPage( 'Page 2', '#REDIRECT [[Page 1]]' );
623 $str = OutputPage
::buildBacklinkSubtitle( $title, $query )->text();
625 foreach ( $contains as $substr ) {
626 $this->assertContains( $substr, $str );
629 foreach ( $notContains as $substr ) {
630 $this->assertNotContains( $substr, $str );
635 * @dataProvider provideBacklinkSubtitle
637 * @covers OutputPage::addBacklinkSubtitle
638 * @covers OutputPage::getSubtitle
640 public function testAddBacklinkSubtitle( Title
$title, $query, $contains, $notContains ) {
641 $this->editPage( 'Page 1', '' );
642 $this->editPage( 'Page 2', '#REDIRECT [[Page 1]]' );
644 $op = $this->newInstance();
645 $op->addBacklinkSubtitle( $title, $query );
647 $str = $op->getSubtitle();
649 foreach ( $contains as $substr ) {
650 $this->assertContains( $substr, $str );
653 foreach ( $notContains as $substr ) {
654 $this->assertNotContains( $substr, $str );
658 public function provideBacklinkSubtitle() {
659 $page1 = Title
::newFromText( 'Page 1' );
660 $page2 = Title
::newFromText( 'Page 2' );
663 [ $page1, [], [ 'Page 1' ], [ 'redirect', 'Page 2' ] ],
664 [ $page2, [], [ 'redirect=no' ], [ 'Page 1' ] ],
665 [ $page1, [ 'action' => 'edit' ], [ 'action=edit' ], [] ],
666 // @todo Anything else to test?
671 * @covers OutputPage::addCategoryLinks
672 * @covers OutputPage::getCategories
674 public function testGetCategories() {
675 $fakeResultWrapper = new FakeResultWrapper( [
678 'page_title' => 'Test'
681 'page_title' => 'Test2'
684 $op = $this->getMockBuilder( OutputPage
::class )
685 ->setConstructorArgs( [ new RequestContext() ] )
686 ->setMethods( [ 'addCategoryLinksToLBAndGetResult' ] )
688 $op->expects( $this->any() )
689 ->method( 'addCategoryLinksToLBAndGetResult' )
690 ->will( $this->returnValue( $fakeResultWrapper ) );
692 $op->addCategoryLinks( [
696 $this->assertEquals( [ 0 => 'Test', '1' => 'Test2' ], $op->getCategories() );
697 $this->assertEquals( [ 0 => 'Test2' ], $op->getCategories( 'normal' ) );
698 $this->assertEquals( [ 0 => 'Test' ], $op->getCategories( 'hidden' ) );
702 * @covers OutputPage::haveCacheVaryCookies
704 public function testHaveCacheVaryCookies() {
705 $request = new FauxRequest();
706 $context = new RequestContext();
707 $context->setRequest( $request );
708 $op = new OutputPage( $context );
710 // No cookies are set.
711 $this->assertFalse( $op->haveCacheVaryCookies() );
713 // 'Token' is present but empty, so it shouldn't count.
714 $request->setCookie( 'Token', '' );
715 $this->assertFalse( $op->haveCacheVaryCookies() );
717 // 'Token' present and nonempty.
718 $request->setCookie( 'Token', '123' );
719 $this->assertTrue( $op->haveCacheVaryCookies() );
723 * @dataProvider provideVaryHeaders
725 * @covers OutputPage::addVaryHeader
726 * @covers OutputPage::getVaryHeader
727 * @covers OutputPage::getKeyHeader
729 public function testVaryHeaders( $calls, $vary, $key ) {
730 // get rid of default Vary fields
731 $op = $this->getMockBuilder( OutputPage
::class )
732 ->setConstructorArgs( [ new RequestContext() ] )
733 ->setMethods( [ 'getCacheVaryCookies' ] )
735 $op->expects( $this->any() )
736 ->method( 'getCacheVaryCookies' )
737 ->will( $this->returnValue( [] ) );
738 TestingAccessWrapper
::newFromObject( $op )->mVaryHeader
= [];
740 foreach ( $calls as $call ) {
741 call_user_func_array( [ $op, 'addVaryHeader' ], $call );
743 $this->assertEquals( $vary, $op->getVaryHeader(), 'Vary:' );
744 $this->assertEquals( $key, $op->getKeyHeader(), 'Key:' );
747 public function provideVaryHeaders() {
748 // note: getKeyHeader() automatically adds Vary: Cookie
757 [ // non-unique headers
760 [ 'Accept-Language' ],
763 'Vary: Cookie, Accept-Language',
764 'Key: Cookie,Accept-Language',
766 [ // two headers with single options
768 [ 'Cookie', [ 'param=phpsessid' ] ],
769 [ 'Accept-Language', [ 'substr=en' ] ],
771 'Vary: Cookie, Accept-Language',
772 'Key: Cookie;param=phpsessid,Accept-Language;substr=en',
774 [ // one header with multiple options
776 [ 'Cookie', [ 'param=phpsessid', 'param=userId' ] ],
779 'Key: Cookie;param=phpsessid;param=userId',
781 [ // Duplicate option
783 [ 'Cookie', [ 'param=phpsessid' ] ],
784 [ 'Cookie', [ 'param=phpsessid' ] ],
785 [ 'Accept-Language', [ 'substr=en', 'substr=en' ] ],
787 'Vary: Cookie, Accept-Language',
788 'Key: Cookie;param=phpsessid,Accept-Language;substr=en',
790 [ // Same header, different options
792 [ 'Cookie', [ 'param=phpsessid' ] ],
793 [ 'Cookie', [ 'param=userId' ] ],
796 'Key: Cookie;param=phpsessid;param=userId',
802 * @dataProvider provideLinkHeaders
804 * @covers OutputPage::addLinkHeader
805 * @covers OutputPage::getLinkHeader
807 public function testLinkHeaders( $headers, $result ) {
808 $op = $this->newInstance();
810 foreach ( $headers as $header ) {
811 $op->addLinkHeader( $header );
814 $this->assertEquals( $result, $op->getLinkHeader() );
817 public function provideLinkHeaders() {
824 [ '<https://foo/bar.jpg>;rel=preload;as=image' ],
825 'Link: <https://foo/bar.jpg>;rel=preload;as=image',
828 [ '<https://foo/bar.jpg>;rel=preload;as=image','<https://foo/baz.jpg>;rel=preload;as=image' ],
829 'Link: <https://foo/bar.jpg>;rel=preload;as=image,<https://foo/baz.jpg>;rel=preload;as=image',
835 * See ResourceLoaderClientHtmlTest for full coverage.
837 * @dataProvider provideMakeResourceLoaderLink
839 * @covers OutputPage::makeResourceLoaderLink
841 public function testMakeResourceLoaderLink( $args, $expectedHtml ) {
842 $this->setMwGlobals( [
843 'wgResourceLoaderDebug' => false,
844 'wgLoadScript' => 'http://127.0.0.1:8080/w/load.php',
845 'wgCSPReportOnlyHeader' => true,
847 $class = new ReflectionClass( OutputPage
::class );
848 $method = $class->getMethod( 'makeResourceLoaderLink' );
849 $method->setAccessible( true );
850 $ctx = new RequestContext();
851 $ctx->setSkin( SkinFactory
::getDefaultInstance()->makeSkin( 'fallback' ) );
852 $ctx->setLanguage( 'en' );
853 $out = new OutputPage( $ctx );
854 $nonce = $class->getProperty( 'CSPNonce' );
855 $nonce->setAccessible( true );
856 $nonce->setValue( $out, 'secret' );
857 $rl = $out->getResourceLoader();
858 $rl->setMessageBlobStore( new NullMessageBlobStore() );
860 'test.foo' => new ResourceLoaderTestModule( [
861 'script' => 'mw.test.foo( { a: true } );',
862 'styles' => '.mw-test-foo { content: "style"; }',
864 'test.bar' => new ResourceLoaderTestModule( [
865 'script' => 'mw.test.bar( { a: true } );',
866 'styles' => '.mw-test-bar { content: "style"; }',
868 'test.baz' => new ResourceLoaderTestModule( [
869 'script' => 'mw.test.baz( { a: true } );',
870 'styles' => '.mw-test-baz { content: "style"; }',
872 'test.quux' => new ResourceLoaderTestModule( [
873 'script' => 'mw.test.baz( { token: 123 } );',
874 'styles' => '/* pref-animate=off */ .mw-icon { transition: none; }',
875 'group' => 'private',
877 'test.noscript' => new ResourceLoaderTestModule( [
878 'styles' => '.stuff { color: red; }',
879 'group' => 'noscript',
881 'test.group.foo' => new ResourceLoaderTestModule( [
882 'script' => 'mw.doStuff( "foo" );',
885 'test.group.bar' => new ResourceLoaderTestModule( [
886 'script' => 'mw.doStuff( "bar" );',
890 $links = $method->invokeArgs( $out, $args );
891 $actualHtml = strval( $links );
892 $this->assertEquals( $expectedHtml, $actualHtml );
895 public static function provideMakeResourceLoaderLink() {
896 // phpcs:disable Generic.Files.LineLength
898 // Single only=scripts load
900 [ 'test.foo', ResourceLoaderModule
::TYPE_SCRIPTS
],
901 "<script nonce=\"secret\">(window.RLQ=window.RLQ||[]).push(function(){"
902 . 'mw.loader.load("http://127.0.0.1:8080/w/load.php?debug=false\u0026lang=en\u0026modules=test.foo\u0026only=scripts\u0026skin=fallback");'
905 // Multiple only=styles load
907 [ [ 'test.baz', 'test.foo', 'test.bar' ], ResourceLoaderModule
::TYPE_STYLES
],
909 '<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"/>'
911 // Private embed (only=scripts)
913 [ 'test.quux', ResourceLoaderModule
::TYPE_SCRIPTS
],
914 "<script nonce=\"secret\">(window.RLQ=window.RLQ||[]).push(function(){"
915 . "mw.test.baz({token:123});\nmw.loader.state({\"test.quux\":\"ready\"});"
918 // Load private module (combined)
920 [ 'test.quux', ResourceLoaderModule
::TYPE_COMBINED
],
921 "<script nonce=\"secret\">(window.RLQ=window.RLQ||[]).push(function(){"
922 . "mw.loader.implement(\"test.quux@1ev0ijv\",function($,jQuery,require,module){"
923 . "mw.test.baz({token:123});},{\"css\":[\".mw-icon{transition:none}"
924 . "\"]});});</script>"
928 [ [], ResourceLoaderModule
::TYPE_COMBINED
],
933 [ 'test.noscript', ResourceLoaderModule
::TYPE_STYLES
],
934 '<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>'
936 // Load two modules in separate groups
938 [ [ 'test.group.foo', 'test.group.bar' ], ResourceLoaderModule
::TYPE_COMBINED
],
939 "<script nonce=\"secret\">(window.RLQ=window.RLQ||[]).push(function(){"
940 . 'mw.loader.load("http://127.0.0.1:8080/w/load.php?debug=false\u0026lang=en\u0026modules=test.group.bar\u0026skin=fallback");'
941 . 'mw.loader.load("http://127.0.0.1:8080/w/load.php?debug=false\u0026lang=en\u0026modules=test.group.foo\u0026skin=fallback");'
949 * @dataProvider provideBuildExemptModules
951 * @covers OutputPage::buildExemptModules
953 public function testBuildExemptModules( array $exemptStyleModules, $expect ) {
954 $this->setMwGlobals( [
955 'wgResourceLoaderDebug' => false,
956 'wgLoadScript' => '/w/load.php',
957 // Stub wgCacheEpoch as it influences getVersionHash used for the
958 // urls in the expected HTML
959 'wgCacheEpoch' => '20140101000000',
963 $ctx = new RequestContext();
964 $ctx->setSkin( SkinFactory
::getDefaultInstance()->makeSkin( 'fallback' ) );
965 $ctx->setLanguage( 'en' );
966 $op = $this->getMockBuilder( OutputPage
::class )
967 ->setConstructorArgs( [ $ctx ] )
968 ->setMethods( [ 'buildCssLinksArray' ] )
970 $op->expects( $this->any() )
971 ->method( 'buildCssLinksArray' )
973 $rl = $op->getResourceLoader();
974 $rl->setMessageBlobStore( new NullMessageBlobStore() );
976 // Register custom modules
978 'example.site.a' => new ResourceLoaderTestModule( [ 'group' => 'site' ] ),
979 'example.site.b' => new ResourceLoaderTestModule( [ 'group' => 'site' ] ),
980 'example.user' => new ResourceLoaderTestModule( [ 'group' => 'user' ] ),
983 $op = TestingAccessWrapper
::newFromObject( $op );
984 $op->rlExemptStyleModules
= $exemptStyleModules;
987 strval( $op->buildExemptModules() )
991 public static function provideBuildExemptModules() {
992 // phpcs:disable Generic.Files.LineLength
995 'exemptStyleModules' => [],
996 '<meta name="ResourceLoaderDynamicStyles" content=""/>',
999 'exemptStyleModules' => [ 'site' => [], 'noscript' => [], 'private' => [], 'user' => [] ],
1000 '<meta name="ResourceLoaderDynamicStyles" content=""/>',
1002 'default logged-out' => [
1003 'exemptStyleModules' => [ 'site' => [ 'site.styles' ] ],
1004 '<meta name="ResourceLoaderDynamicStyles" content=""/>' . "\n" .
1005 '<link rel="stylesheet" href="/w/load.php?debug=false&lang=en&modules=site.styles&only=styles&skin=fallback"/>',
1007 'default logged-in' => [
1008 'exemptStyleModules' => [ 'site' => [ 'site.styles' ], 'user' => [ 'user.styles' ] ],
1009 '<meta name="ResourceLoaderDynamicStyles" content=""/>' . "\n" .
1010 '<link rel="stylesheet" href="/w/load.php?debug=false&lang=en&modules=site.styles&only=styles&skin=fallback"/>' . "\n" .
1011 '<link rel="stylesheet" href="/w/load.php?debug=false&lang=en&modules=user.styles&only=styles&skin=fallback&version=1e9z0ox"/>',
1013 'custom modules' => [
1014 'exemptStyleModules' => [
1015 'site' => [ 'site.styles', 'example.site.a', 'example.site.b' ],
1016 'user' => [ 'user.styles', 'example.user' ],
1018 '<meta name="ResourceLoaderDynamicStyles" content=""/>' . "\n" .
1019 '<link rel="stylesheet" href="/w/load.php?debug=false&lang=en&modules=example.site.a%2Cb&only=styles&skin=fallback"/>' . "\n" .
1020 '<link rel="stylesheet" href="/w/load.php?debug=false&lang=en&modules=site.styles&only=styles&skin=fallback"/>' . "\n" .
1021 '<link rel="stylesheet" href="/w/load.php?debug=false&lang=en&modules=example.user&only=styles&skin=fallback&version=0a56zyi"/>' . "\n" .
1022 '<link rel="stylesheet" href="/w/load.php?debug=false&lang=en&modules=user.styles&only=styles&skin=fallback&version=1e9z0ox"/>',
1029 * @dataProvider provideTransformFilePath
1030 * @covers OutputPage::transformFilePath
1031 * @covers OutputPage::transformResourcePath
1033 public function testTransformResourcePath( $baseDir, $basePath, $uploadDir = null,
1034 $uploadPath = null, $path = null, $expected = null
1036 if ( $path === null ) {
1037 // Skip optional $uploadDir and $uploadPath
1039 $expected = $uploadPath;
1040 $uploadDir = "$baseDir/images";
1041 $uploadPath = "$basePath/images";
1043 $this->setMwGlobals( 'IP', $baseDir );
1044 $conf = new HashConfig( [
1045 'ResourceBasePath' => $basePath,
1046 'UploadDirectory' => $uploadDir,
1047 'UploadPath' => $uploadPath,
1050 // Some of these paths don't exist and will cause warnings
1051 Wikimedia\
suppressWarnings();
1052 $actual = OutputPage
::transformResourcePath( $conf, $path );
1053 Wikimedia\restoreWarnings
();
1055 $this->assertEquals( $expected ?
: $path, $actual );
1058 public static function provideTransformFilePath() {
1059 $baseDir = dirname( __DIR__
) . '/data/media';
1061 // File that matches basePath, and exists. Hash found and appended.
1063 'baseDir' => $baseDir, 'basePath' => '/w',
1067 // File that matches basePath, but not found on disk. Empty query.
1069 'baseDir' => $baseDir, 'basePath' => '/w',
1073 // File not matching basePath. Ignored.
1075 'baseDir' => $baseDir, 'basePath' => '/w',
1078 // Empty string. Ignored.
1080 'baseDir' => $baseDir, 'basePath' => '/w',
1084 // Similar path, but with domain component. Ignored.
1086 'baseDir' => $baseDir, 'basePath' => '/w',
1087 '//example.org/w/test.jpg'
1090 'baseDir' => $baseDir, 'basePath' => '/w',
1091 'https://example.org/w/test.jpg'
1093 // Unrelated path with domain component. Ignored.
1095 'baseDir' => $baseDir, 'basePath' => '/w',
1096 'https://example.org/files/test.jpg'
1099 'baseDir' => $baseDir, 'basePath' => '/w',
1100 '//example.org/files/test.jpg'
1102 // Unrelated path with domain, and empty base path (root mw install). Ignored.
1104 'baseDir' => $baseDir, 'basePath' => '',
1105 'https://example.org/files/test.jpg'
1108 'baseDir' => $baseDir, 'basePath' => '',
1110 '//example.org/files/test.jpg'
1112 // Check UploadPath before ResourceBasePath (T155146)
1114 'baseDir' => dirname( $baseDir ), 'basePath' => '',
1115 'uploadDir' => $baseDir, 'uploadPath' => '/images',
1117 '/images/test.jpg?edcf2'
1123 * Tests a particular case of transformCssMedia, using the given input, globals,
1124 * expected return, and message
1126 * Asserts that $expectedReturn is returned.
1128 * options['printableQuery'] - value of query string for printable, or omitted for none
1129 * options['handheldQuery'] - value of query string for handheld, or omitted for none
1130 * options['media'] - passed into the method under the same name
1131 * options['expectedReturn'] - expected return value
1132 * options['message'] - PHPUnit message for assertion
1134 * @param array $args Key-value array of arguments as shown above
1136 protected function assertTransformCssMediaCase( $args ) {
1138 if ( isset( $args['printableQuery'] ) ) {
1139 $queryData['printable'] = $args['printableQuery'];
1142 if ( isset( $args['handheldQuery'] ) ) {
1143 $queryData['handheld'] = $args['handheldQuery'];
1146 $fauxRequest = new FauxRequest( $queryData, false );
1147 $this->setMwGlobals( [
1148 'wgRequest' => $fauxRequest,
1151 $actualReturn = OutputPage
::transformCssMedia( $args['media'] );
1152 $this->assertSame( $args['expectedReturn'], $actualReturn, $args['message'] );
1156 * Tests print requests
1158 * @covers OutputPage::transformCssMedia
1160 public function testPrintRequests() {
1161 $this->assertTransformCssMediaCase( [
1162 'printableQuery' => '1',
1163 'media' => 'screen',
1164 'expectedReturn' => null,
1165 'message' => 'On printable request, screen returns null'
1168 $this->assertTransformCssMediaCase( [
1169 'printableQuery' => '1',
1170 'media' => self
::SCREEN_MEDIA_QUERY
,
1171 'expectedReturn' => null,
1172 'message' => 'On printable request, screen media query returns null'
1175 $this->assertTransformCssMediaCase( [
1176 'printableQuery' => '1',
1177 'media' => self
::SCREEN_ONLY_MEDIA_QUERY
,
1178 'expectedReturn' => null,
1179 'message' => 'On printable request, screen media query with only returns null'
1182 $this->assertTransformCssMediaCase( [
1183 'printableQuery' => '1',
1185 'expectedReturn' => '',
1186 'message' => 'On printable request, media print returns empty string'
1191 * Tests screen requests, without either query parameter set
1193 * @covers OutputPage::transformCssMedia
1195 public function testScreenRequests() {
1196 $this->assertTransformCssMediaCase( [
1197 'media' => 'screen',
1198 'expectedReturn' => 'screen',
1199 'message' => 'On screen request, screen media type is preserved'
1202 $this->assertTransformCssMediaCase( [
1203 'media' => 'handheld',
1204 'expectedReturn' => 'handheld',
1205 'message' => 'On screen request, handheld media type is preserved'
1208 $this->assertTransformCssMediaCase( [
1209 'media' => self
::SCREEN_MEDIA_QUERY
,
1210 'expectedReturn' => self
::SCREEN_MEDIA_QUERY
,
1211 'message' => 'On screen request, screen media query is preserved.'
1214 $this->assertTransformCssMediaCase( [
1215 'media' => self
::SCREEN_ONLY_MEDIA_QUERY
,
1216 'expectedReturn' => self
::SCREEN_ONLY_MEDIA_QUERY
,
1217 'message' => 'On screen request, screen media query with only is preserved.'
1220 $this->assertTransformCssMediaCase( [
1222 'expectedReturn' => 'print',
1223 'message' => 'On screen request, print media type is preserved'
1228 * Tests handheld behavior
1230 * @covers OutputPage::transformCssMedia
1232 public function testHandheld() {
1233 $this->assertTransformCssMediaCase( [
1234 'handheldQuery' => '1',
1235 'media' => 'handheld',
1236 'expectedReturn' => '',
1237 'message' => 'On request with handheld querystring and media is handheld, returns empty string'
1240 $this->assertTransformCssMediaCase( [
1241 'handheldQuery' => '1',
1242 'media' => 'screen',
1243 'expectedReturn' => null,
1244 'message' => 'On request with handheld querystring and media is screen, returns null'
1249 * @dataProvider providePreloadLinkHeaders
1250 * @covers OutputPage::addLogoPreloadLinkHeaders
1251 * @covers ResourceLoaderSkinModule::getLogo
1253 public function testPreloadLinkHeaders( $config, $result, $baseDir = null ) {
1255 $this->setMwGlobals( 'IP', $baseDir );
1257 $out = TestingAccessWrapper
::newFromObject( $this->newInstance( $config ) );
1258 $out->addLogoPreloadLinkHeaders();
1260 $this->assertEquals( $result, $out->getLinkHeader() );
1263 public function providePreloadLinkHeaders() {
1267 'ResourceBasePath' => '/w',
1268 'Logo' => '/img/default.png',
1270 '1.5x' => '/img/one-point-five.png',
1271 '2x' => '/img/two-x.png',
1274 'Link: </img/default.png>;rel=preload;as=image;media=' .
1275 'not all and (min-resolution: 1.5dppx),' .
1276 '</img/one-point-five.png>;rel=preload;as=image;media=' .
1277 '(min-resolution: 1.5dppx) and (max-resolution: 1.999999dppx),' .
1278 '</img/two-x.png>;rel=preload;as=image;media=(min-resolution: 2dppx)'
1282 'ResourceBasePath' => '/w',
1283 'Logo' => '/img/default.png',
1286 'Link: </img/default.png>;rel=preload;as=image'
1290 'ResourceBasePath' => '/w',
1291 'Logo' => '/img/default.png',
1293 '2x' => '/img/two-x.png',
1296 'Link: </img/default.png>;rel=preload;as=image;media=' .
1297 'not all and (min-resolution: 2dppx),' .
1298 '</img/two-x.png>;rel=preload;as=image;media=(min-resolution: 2dppx)'
1302 'ResourceBasePath' => '/w',
1303 'Logo' => '/img/default.png',
1305 'svg' => '/img/vector.svg',
1308 'Link: </img/vector.svg>;rel=preload;as=image'
1313 'ResourceBasePath' => '/w',
1314 'Logo' => '/w/test.jpg',
1316 'UploadPath' => '/w/images',
1318 'Link: </w/test.jpg?edcf2>;rel=preload;as=image',
1319 'baseDir' => dirname( __DIR__
) . '/data/media',
1325 * @return OutputPage
1327 private function newInstance( $config = [], WebRequest
$request = null ) {
1328 $context = new RequestContext();
1330 $context->setConfig( new MultiConfig( [
1331 new HashConfig( $config +
[
1332 'AppleTouchIcon' => false,
1333 'DisableLangConversion' => true,
1334 'EnableCanonicalServerLink' => false,
1337 'LanguageCode' => false,
1338 'ReferrerPolicy' => false,
1339 'RightsPage' => false,
1340 'RightsUrl' => false,
1341 'UniversalEditButton' => false,
1343 $context->getConfig()
1346 $context->setTitle( Title
::newFromText( 'My test page' ) );
1349 $context->setRequest( $request );
1352 return new OutputPage( $context );
1357 * MessageBlobStore that doesn't do anything
1359 class NullMessageBlobStore
extends MessageBlobStore
{
1360 public function get( ResourceLoader
$resourceLoader, $modules, $lang ) {
1364 public function updateModule( $name, ResourceLoaderModule
$module, $lang ) {
1367 public function updateMessage( $key ) {
1370 public function clear() {