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 private function extractHTMLTitle( OutputPage
$op ) {
456 $html = $op->headElement( $op->getContext()->getSkin() );
458 // OutputPage should always output the title in a nice format such that regexes will work
459 // fine. If it doesn't, we'll fail the tests.
460 preg_match_all( '!<title>(.*?)</title>!', $html, $matches );
462 $this->assertLessThanOrEqual( 1, count( $matches[1] ), 'More than one <title>!' );
464 if ( !count( $matches[1] ) ) {
468 return $matches[1][0];
472 * Shorthand for getting the text of a message, in content language.
474 private static function getMsgText( $op, ...$msgParams ) {
475 return $op->msg( ...$msgParams )->inContentLanguage()->text();
479 * @covers OutputPage::setHTMLTitle
480 * @covers OutputPage::getHTMLTitle
482 public function testHTMLTitle() {
483 $op = $this->newInstance();
486 $this->assertSame( '', $op->getHTMLTitle() );
487 $this->assertSame( '', $op->getPageTitle() );
489 $this->getMsgText( $op, 'pagetitle', '' ),
490 $this->extractHTMLTitle( $op )
494 $op->setHTMLTitle( 'Potatoes will eat me' );
496 $this->assertSame( 'Potatoes will eat me', $op->getHTMLTitle() );
497 $this->assertSame( 'Potatoes will eat me', $this->extractHTMLTitle( $op ) );
498 // Shouldn't have changed the page title
499 $this->assertSame( '', $op->getPageTitle() );
502 $msg = $op->msg( 'mainpage' );
504 $op->setHTMLTitle( $msg );
505 $this->assertSame( $msg->text(), $op->getHTMLTitle() );
506 $this->assertSame( $msg->text(), $this->extractHTMLTitle( $op ) );
507 $this->assertSame( '', $op->getPageTitle() );
511 * @covers OutputPage::setRedirectedFrom
513 public function testSetRedirectedFrom() {
514 $op = $this->newInstance();
516 $op->setRedirectedFrom( Title
::newFromText( 'Talk:Some page' ) );
517 $this->assertSame( 'Talk:Some_page', $op->getJSVars()['wgRedirectedFrom'] );
521 * @covers OutputPage::setPageTitle
522 * @covers OutputPage::getPageTitle
524 public function testPageTitle() {
525 // We don't test the actual HTML output anywhere, because that's up to the skin.
526 $op = $this->newInstance();
529 $this->assertSame( '', $op->getPageTitle() );
530 $this->assertSame( '', $op->getHTMLTitle() );
532 // Test set to plain text
533 $op->setPageTitle( 'foobar' );
535 $this->assertSame( 'foobar', $op->getPageTitle() );
536 // HTML title should change as well
537 $this->assertSame( $this->getMsgText( $op, 'pagetitle', 'foobar' ), $op->getHTMLTitle() );
539 // Test set to text with good and bad HTML. We don't try to be comprehensive here, that
540 // belongs in Sanitizer tests.
541 $op->setPageTitle( '<script>a</script>&<i>b</i>' );
543 $this->assertSame( '<script>a</script>&<i>b</i>', $op->getPageTitle() );
545 $this->getMsgText( $op, 'pagetitle', '<script>a</script>&b' ),
549 // Test set to message
550 $text = $this->getMsgText( $op, 'mainpage' );
552 $op->setPageTitle( $op->msg( 'mainpage' )->inContentLanguage() );
553 $this->assertSame( $text, $op->getPageTitle() );
554 $this->assertSame( $this->getMsgText( $op, 'pagetitle', $text ), $op->getHTMLTitle() );
558 * @covers OutputPage::setTitle
560 public function testSetTitle() {
561 $op = $this->newInstance();
563 $this->assertSame( 'My test page', $op->getTitle()->getPrefixedText() );
565 $op->setTitle( Title
::newFromText( 'Another test page' ) );
567 $this->assertSame( 'Another test page', $op->getTitle()->getPrefixedText() );
571 * @covers OutputPage::setSubtitle
572 * @covers OutputPage::clearSubtitle
573 * @covers OutputPage::addSubtitle
574 * @covers OutputPage::getSubtitle
576 public function testSubtitle() {
577 $op = $this->newInstance();
579 $this->assertSame( '', $op->getSubtitle() );
581 $op->addSubtitle( '<b>foo</b>' );
583 $this->assertSame( '<b>foo</b>', $op->getSubtitle() );
585 $op->addSubtitle( $op->msg( 'mainpage' )->inContentLanguage() );
588 "<b>foo</b><br />\n\t\t\t\t" . $this->getMsgText( $op, 'mainpage' ),
592 $op->setSubtitle( 'There can be only one' );
594 $this->assertSame( 'There can be only one', $op->getSubtitle() );
596 $op->clearSubtitle();
598 $this->assertSame( '', $op->getSubtitle() );
602 * @dataProvider provideBacklinkSubtitle
604 * @covers OutputPage::buildBacklinkSubtitle
606 public function testBuildBacklinkSubtitle( Title
$title, $query, $contains, $notContains ) {
607 $this->editPage( 'Page 1', '' );
608 $this->editPage( 'Page 2', '#REDIRECT [[Page 1]]' );
610 $str = OutputPage
::buildBacklinkSubtitle( $title, $query )->text();
612 foreach ( $contains as $substr ) {
613 $this->assertContains( $substr, $str );
616 foreach ( $notContains as $substr ) {
617 $this->assertNotContains( $substr, $str );
622 * @dataProvider provideBacklinkSubtitle
624 * @covers OutputPage::addBacklinkSubtitle
625 * @covers OutputPage::getSubtitle
627 public function testAddBacklinkSubtitle( Title
$title, $query, $contains, $notContains ) {
628 $this->editPage( 'Page 1', '' );
629 $this->editPage( 'Page 2', '#REDIRECT [[Page 1]]' );
631 $op = $this->newInstance();
632 $op->addBacklinkSubtitle( $title, $query );
634 $str = $op->getSubtitle();
636 foreach ( $contains as $substr ) {
637 $this->assertContains( $substr, $str );
640 foreach ( $notContains as $substr ) {
641 $this->assertNotContains( $substr, $str );
645 public function provideBacklinkSubtitle() {
646 $page1 = Title
::newFromText( 'Page 1' );
647 $page2 = Title
::newFromText( 'Page 2' );
650 [ $page1, [], [ 'Page 1' ], [ 'redirect', 'Page 2' ] ],
651 [ $page2, [], [ 'redirect=no' ], [ 'Page 1' ] ],
652 [ $page1, [ 'action' => 'edit' ], [ 'action=edit' ], [] ],
653 // @todo Anything else to test?
658 * @covers OutputPage::addCategoryLinks
659 * @covers OutputPage::getCategories
661 public function testGetCategories() {
662 $fakeResultWrapper = new FakeResultWrapper( [
665 'page_title' => 'Test'
668 'page_title' => 'Test2'
671 $op = $this->getMockBuilder( OutputPage
::class )
672 ->setConstructorArgs( [ new RequestContext() ] )
673 ->setMethods( [ 'addCategoryLinksToLBAndGetResult' ] )
675 $op->expects( $this->any() )
676 ->method( 'addCategoryLinksToLBAndGetResult' )
677 ->will( $this->returnValue( $fakeResultWrapper ) );
679 $op->addCategoryLinks( [
683 $this->assertEquals( [ 0 => 'Test', '1' => 'Test2' ], $op->getCategories() );
684 $this->assertEquals( [ 0 => 'Test2' ], $op->getCategories( 'normal' ) );
685 $this->assertEquals( [ 0 => 'Test' ], $op->getCategories( 'hidden' ) );
689 * @covers OutputPage::haveCacheVaryCookies
691 public function testHaveCacheVaryCookies() {
692 $request = new FauxRequest();
693 $context = new RequestContext();
694 $context->setRequest( $request );
695 $op = new OutputPage( $context );
697 // No cookies are set.
698 $this->assertFalse( $op->haveCacheVaryCookies() );
700 // 'Token' is present but empty, so it shouldn't count.
701 $request->setCookie( 'Token', '' );
702 $this->assertFalse( $op->haveCacheVaryCookies() );
704 // 'Token' present and nonempty.
705 $request->setCookie( 'Token', '123' );
706 $this->assertTrue( $op->haveCacheVaryCookies() );
710 * @dataProvider provideVaryHeaders
712 * @covers OutputPage::addVaryHeader
713 * @covers OutputPage::getVaryHeader
714 * @covers OutputPage::getKeyHeader
716 public function testVaryHeaders( $calls, $vary, $key ) {
717 // get rid of default Vary fields
718 $op = $this->getMockBuilder( OutputPage
::class )
719 ->setConstructorArgs( [ new RequestContext() ] )
720 ->setMethods( [ 'getCacheVaryCookies' ] )
722 $op->expects( $this->any() )
723 ->method( 'getCacheVaryCookies' )
724 ->will( $this->returnValue( [] ) );
725 TestingAccessWrapper
::newFromObject( $op )->mVaryHeader
= [];
727 foreach ( $calls as $call ) {
728 call_user_func_array( [ $op, 'addVaryHeader' ], $call );
730 $this->assertEquals( $vary, $op->getVaryHeader(), 'Vary:' );
731 $this->assertEquals( $key, $op->getKeyHeader(), 'Key:' );
734 public function provideVaryHeaders() {
735 // note: getKeyHeader() automatically adds Vary: Cookie
744 [ // non-unique headers
747 [ 'Accept-Language' ],
750 'Vary: Cookie, Accept-Language',
751 'Key: Cookie,Accept-Language',
753 [ // two headers with single options
755 [ 'Cookie', [ 'param=phpsessid' ] ],
756 [ 'Accept-Language', [ 'substr=en' ] ],
758 'Vary: Cookie, Accept-Language',
759 'Key: Cookie;param=phpsessid,Accept-Language;substr=en',
761 [ // one header with multiple options
763 [ 'Cookie', [ 'param=phpsessid', 'param=userId' ] ],
766 'Key: Cookie;param=phpsessid;param=userId',
768 [ // Duplicate option
770 [ 'Cookie', [ 'param=phpsessid' ] ],
771 [ 'Cookie', [ 'param=phpsessid' ] ],
772 [ 'Accept-Language', [ 'substr=en', 'substr=en' ] ],
774 'Vary: Cookie, Accept-Language',
775 'Key: Cookie;param=phpsessid,Accept-Language;substr=en',
777 [ // Same header, different options
779 [ 'Cookie', [ 'param=phpsessid' ] ],
780 [ 'Cookie', [ 'param=userId' ] ],
783 'Key: Cookie;param=phpsessid;param=userId',
789 * @dataProvider provideLinkHeaders
791 * @covers OutputPage::addLinkHeader
792 * @covers OutputPage::getLinkHeader
794 public function testLinkHeaders( $headers, $result ) {
795 $op = $this->newInstance();
797 foreach ( $headers as $header ) {
798 $op->addLinkHeader( $header );
801 $this->assertEquals( $result, $op->getLinkHeader() );
804 public function provideLinkHeaders() {
811 [ '<https://foo/bar.jpg>;rel=preload;as=image' ],
812 'Link: <https://foo/bar.jpg>;rel=preload;as=image',
815 [ '<https://foo/bar.jpg>;rel=preload;as=image','<https://foo/baz.jpg>;rel=preload;as=image' ],
816 'Link: <https://foo/bar.jpg>;rel=preload;as=image,<https://foo/baz.jpg>;rel=preload;as=image',
822 * See ResourceLoaderClientHtmlTest for full coverage.
824 * @dataProvider provideMakeResourceLoaderLink
826 * @covers OutputPage::makeResourceLoaderLink
828 public function testMakeResourceLoaderLink( $args, $expectedHtml ) {
829 $this->setMwGlobals( [
830 'wgResourceLoaderDebug' => false,
831 'wgLoadScript' => 'http://127.0.0.1:8080/w/load.php',
832 'wgCSPReportOnlyHeader' => true,
834 $class = new ReflectionClass( OutputPage
::class );
835 $method = $class->getMethod( 'makeResourceLoaderLink' );
836 $method->setAccessible( true );
837 $ctx = new RequestContext();
838 $ctx->setSkin( SkinFactory
::getDefaultInstance()->makeSkin( 'fallback' ) );
839 $ctx->setLanguage( 'en' );
840 $out = new OutputPage( $ctx );
841 $nonce = $class->getProperty( 'CSPNonce' );
842 $nonce->setAccessible( true );
843 $nonce->setValue( $out, 'secret' );
844 $rl = $out->getResourceLoader();
845 $rl->setMessageBlobStore( new NullMessageBlobStore() );
847 'test.foo' => new ResourceLoaderTestModule( [
848 'script' => 'mw.test.foo( { a: true } );',
849 'styles' => '.mw-test-foo { content: "style"; }',
851 'test.bar' => new ResourceLoaderTestModule( [
852 'script' => 'mw.test.bar( { a: true } );',
853 'styles' => '.mw-test-bar { content: "style"; }',
855 'test.baz' => new ResourceLoaderTestModule( [
856 'script' => 'mw.test.baz( { a: true } );',
857 'styles' => '.mw-test-baz { content: "style"; }',
859 'test.quux' => new ResourceLoaderTestModule( [
860 'script' => 'mw.test.baz( { token: 123 } );',
861 'styles' => '/* pref-animate=off */ .mw-icon { transition: none; }',
862 'group' => 'private',
864 'test.noscript' => new ResourceLoaderTestModule( [
865 'styles' => '.stuff { color: red; }',
866 'group' => 'noscript',
868 'test.group.foo' => new ResourceLoaderTestModule( [
869 'script' => 'mw.doStuff( "foo" );',
872 'test.group.bar' => new ResourceLoaderTestModule( [
873 'script' => 'mw.doStuff( "bar" );',
877 $links = $method->invokeArgs( $out, $args );
878 $actualHtml = strval( $links );
879 $this->assertEquals( $expectedHtml, $actualHtml );
882 public static function provideMakeResourceLoaderLink() {
883 // phpcs:disable Generic.Files.LineLength
885 // Single only=scripts load
887 [ 'test.foo', ResourceLoaderModule
::TYPE_SCRIPTS
],
888 "<script nonce=\"secret\">(window.RLQ=window.RLQ||[]).push(function(){"
889 . 'mw.loader.load("http://127.0.0.1:8080/w/load.php?debug=false\u0026lang=en\u0026modules=test.foo\u0026only=scripts\u0026skin=fallback");'
892 // Multiple only=styles load
894 [ [ 'test.baz', 'test.foo', 'test.bar' ], ResourceLoaderModule
::TYPE_STYLES
],
896 '<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"/>'
898 // Private embed (only=scripts)
900 [ 'test.quux', ResourceLoaderModule
::TYPE_SCRIPTS
],
901 "<script nonce=\"secret\">(window.RLQ=window.RLQ||[]).push(function(){"
902 . "mw.test.baz({token:123});\nmw.loader.state({\"test.quux\":\"ready\"});"
905 // Load private module (combined)
907 [ 'test.quux', ResourceLoaderModule
::TYPE_COMBINED
],
908 "<script nonce=\"secret\">(window.RLQ=window.RLQ||[]).push(function(){"
909 . "mw.loader.implement(\"test.quux@1ev0ijv\",function($,jQuery,require,module){"
910 . "mw.test.baz({token:123});},{\"css\":[\".mw-icon{transition:none}"
911 . "\"]});});</script>"
915 [ [], ResourceLoaderModule
::TYPE_COMBINED
],
920 [ 'test.noscript', ResourceLoaderModule
::TYPE_STYLES
],
921 '<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>'
923 // Load two modules in separate groups
925 [ [ 'test.group.foo', 'test.group.bar' ], ResourceLoaderModule
::TYPE_COMBINED
],
926 "<script nonce=\"secret\">(window.RLQ=window.RLQ||[]).push(function(){"
927 . 'mw.loader.load("http://127.0.0.1:8080/w/load.php?debug=false\u0026lang=en\u0026modules=test.group.bar\u0026skin=fallback");'
928 . 'mw.loader.load("http://127.0.0.1:8080/w/load.php?debug=false\u0026lang=en\u0026modules=test.group.foo\u0026skin=fallback");'
936 * @dataProvider provideBuildExemptModules
938 * @covers OutputPage::buildExemptModules
940 public function testBuildExemptModules( array $exemptStyleModules, $expect ) {
941 $this->setMwGlobals( [
942 'wgResourceLoaderDebug' => false,
943 'wgLoadScript' => '/w/load.php',
944 // Stub wgCacheEpoch as it influences getVersionHash used for the
945 // urls in the expected HTML
946 'wgCacheEpoch' => '20140101000000',
950 $ctx = new RequestContext();
951 $ctx->setSkin( SkinFactory
::getDefaultInstance()->makeSkin( 'fallback' ) );
952 $ctx->setLanguage( 'en' );
953 $op = $this->getMockBuilder( OutputPage
::class )
954 ->setConstructorArgs( [ $ctx ] )
955 ->setMethods( [ 'buildCssLinksArray' ] )
957 $op->expects( $this->any() )
958 ->method( 'buildCssLinksArray' )
960 $rl = $op->getResourceLoader();
961 $rl->setMessageBlobStore( new NullMessageBlobStore() );
963 // Register custom modules
965 'example.site.a' => new ResourceLoaderTestModule( [ 'group' => 'site' ] ),
966 'example.site.b' => new ResourceLoaderTestModule( [ 'group' => 'site' ] ),
967 'example.user' => new ResourceLoaderTestModule( [ 'group' => 'user' ] ),
970 $op = TestingAccessWrapper
::newFromObject( $op );
971 $op->rlExemptStyleModules
= $exemptStyleModules;
974 strval( $op->buildExemptModules() )
978 public static function provideBuildExemptModules() {
979 // phpcs:disable Generic.Files.LineLength
982 'exemptStyleModules' => [],
983 '<meta name="ResourceLoaderDynamicStyles" content=""/>',
986 'exemptStyleModules' => [ 'site' => [], 'noscript' => [], 'private' => [], 'user' => [] ],
987 '<meta name="ResourceLoaderDynamicStyles" content=""/>',
989 'default logged-out' => [
990 'exemptStyleModules' => [ 'site' => [ 'site.styles' ] ],
991 '<meta name="ResourceLoaderDynamicStyles" content=""/>' . "\n" .
992 '<link rel="stylesheet" href="/w/load.php?debug=false&lang=en&modules=site.styles&only=styles&skin=fallback"/>',
994 'default logged-in' => [
995 'exemptStyleModules' => [ 'site' => [ 'site.styles' ], 'user' => [ 'user.styles' ] ],
996 '<meta name="ResourceLoaderDynamicStyles" content=""/>' . "\n" .
997 '<link rel="stylesheet" href="/w/load.php?debug=false&lang=en&modules=site.styles&only=styles&skin=fallback"/>' . "\n" .
998 '<link rel="stylesheet" href="/w/load.php?debug=false&lang=en&modules=user.styles&only=styles&skin=fallback&version=1e9z0ox"/>',
1000 'custom modules' => [
1001 'exemptStyleModules' => [
1002 'site' => [ 'site.styles', 'example.site.a', 'example.site.b' ],
1003 'user' => [ 'user.styles', 'example.user' ],
1005 '<meta name="ResourceLoaderDynamicStyles" content=""/>' . "\n" .
1006 '<link rel="stylesheet" href="/w/load.php?debug=false&lang=en&modules=example.site.a%2Cb&only=styles&skin=fallback"/>' . "\n" .
1007 '<link rel="stylesheet" href="/w/load.php?debug=false&lang=en&modules=site.styles&only=styles&skin=fallback"/>' . "\n" .
1008 '<link rel="stylesheet" href="/w/load.php?debug=false&lang=en&modules=example.user&only=styles&skin=fallback&version=0a56zyi"/>' . "\n" .
1009 '<link rel="stylesheet" href="/w/load.php?debug=false&lang=en&modules=user.styles&only=styles&skin=fallback&version=1e9z0ox"/>',
1016 * @dataProvider provideTransformFilePath
1017 * @covers OutputPage::transformFilePath
1018 * @covers OutputPage::transformResourcePath
1020 public function testTransformResourcePath( $baseDir, $basePath, $uploadDir = null,
1021 $uploadPath = null, $path = null, $expected = null
1023 if ( $path === null ) {
1024 // Skip optional $uploadDir and $uploadPath
1026 $expected = $uploadPath;
1027 $uploadDir = "$baseDir/images";
1028 $uploadPath = "$basePath/images";
1030 $this->setMwGlobals( 'IP', $baseDir );
1031 $conf = new HashConfig( [
1032 'ResourceBasePath' => $basePath,
1033 'UploadDirectory' => $uploadDir,
1034 'UploadPath' => $uploadPath,
1037 // Some of these paths don't exist and will cause warnings
1038 Wikimedia\
suppressWarnings();
1039 $actual = OutputPage
::transformResourcePath( $conf, $path );
1040 Wikimedia\restoreWarnings
();
1042 $this->assertEquals( $expected ?
: $path, $actual );
1045 public static function provideTransformFilePath() {
1046 $baseDir = dirname( __DIR__
) . '/data/media';
1048 // File that matches basePath, and exists. Hash found and appended.
1050 'baseDir' => $baseDir, 'basePath' => '/w',
1054 // File that matches basePath, but not found on disk. Empty query.
1056 'baseDir' => $baseDir, 'basePath' => '/w',
1060 // File not matching basePath. Ignored.
1062 'baseDir' => $baseDir, 'basePath' => '/w',
1065 // Empty string. Ignored.
1067 'baseDir' => $baseDir, 'basePath' => '/w',
1071 // Similar path, but with domain component. Ignored.
1073 'baseDir' => $baseDir, 'basePath' => '/w',
1074 '//example.org/w/test.jpg'
1077 'baseDir' => $baseDir, 'basePath' => '/w',
1078 'https://example.org/w/test.jpg'
1080 // Unrelated path with domain component. Ignored.
1082 'baseDir' => $baseDir, 'basePath' => '/w',
1083 'https://example.org/files/test.jpg'
1086 'baseDir' => $baseDir, 'basePath' => '/w',
1087 '//example.org/files/test.jpg'
1089 // Unrelated path with domain, and empty base path (root mw install). Ignored.
1091 'baseDir' => $baseDir, 'basePath' => '',
1092 'https://example.org/files/test.jpg'
1095 'baseDir' => $baseDir, 'basePath' => '',
1097 '//example.org/files/test.jpg'
1099 // Check UploadPath before ResourceBasePath (T155146)
1101 'baseDir' => dirname( $baseDir ), 'basePath' => '',
1102 'uploadDir' => $baseDir, 'uploadPath' => '/images',
1104 '/images/test.jpg?edcf2'
1110 * Tests a particular case of transformCssMedia, using the given input, globals,
1111 * expected return, and message
1113 * Asserts that $expectedReturn is returned.
1115 * options['printableQuery'] - value of query string for printable, or omitted for none
1116 * options['handheldQuery'] - value of query string for handheld, or omitted for none
1117 * options['media'] - passed into the method under the same name
1118 * options['expectedReturn'] - expected return value
1119 * options['message'] - PHPUnit message for assertion
1121 * @param array $args Key-value array of arguments as shown above
1123 protected function assertTransformCssMediaCase( $args ) {
1125 if ( isset( $args['printableQuery'] ) ) {
1126 $queryData['printable'] = $args['printableQuery'];
1129 if ( isset( $args['handheldQuery'] ) ) {
1130 $queryData['handheld'] = $args['handheldQuery'];
1133 $fauxRequest = new FauxRequest( $queryData, false );
1134 $this->setMwGlobals( [
1135 'wgRequest' => $fauxRequest,
1138 $actualReturn = OutputPage
::transformCssMedia( $args['media'] );
1139 $this->assertSame( $args['expectedReturn'], $actualReturn, $args['message'] );
1143 * Tests print requests
1145 * @covers OutputPage::transformCssMedia
1147 public function testPrintRequests() {
1148 $this->assertTransformCssMediaCase( [
1149 'printableQuery' => '1',
1150 'media' => 'screen',
1151 'expectedReturn' => null,
1152 'message' => 'On printable request, screen returns null'
1155 $this->assertTransformCssMediaCase( [
1156 'printableQuery' => '1',
1157 'media' => self
::SCREEN_MEDIA_QUERY
,
1158 'expectedReturn' => null,
1159 'message' => 'On printable request, screen media query returns null'
1162 $this->assertTransformCssMediaCase( [
1163 'printableQuery' => '1',
1164 'media' => self
::SCREEN_ONLY_MEDIA_QUERY
,
1165 'expectedReturn' => null,
1166 'message' => 'On printable request, screen media query with only returns null'
1169 $this->assertTransformCssMediaCase( [
1170 'printableQuery' => '1',
1172 'expectedReturn' => '',
1173 'message' => 'On printable request, media print returns empty string'
1178 * Tests screen requests, without either query parameter set
1180 * @covers OutputPage::transformCssMedia
1182 public function testScreenRequests() {
1183 $this->assertTransformCssMediaCase( [
1184 'media' => 'screen',
1185 'expectedReturn' => 'screen',
1186 'message' => 'On screen request, screen media type is preserved'
1189 $this->assertTransformCssMediaCase( [
1190 'media' => 'handheld',
1191 'expectedReturn' => 'handheld',
1192 'message' => 'On screen request, handheld media type is preserved'
1195 $this->assertTransformCssMediaCase( [
1196 'media' => self
::SCREEN_MEDIA_QUERY
,
1197 'expectedReturn' => self
::SCREEN_MEDIA_QUERY
,
1198 'message' => 'On screen request, screen media query is preserved.'
1201 $this->assertTransformCssMediaCase( [
1202 'media' => self
::SCREEN_ONLY_MEDIA_QUERY
,
1203 'expectedReturn' => self
::SCREEN_ONLY_MEDIA_QUERY
,
1204 'message' => 'On screen request, screen media query with only is preserved.'
1207 $this->assertTransformCssMediaCase( [
1209 'expectedReturn' => 'print',
1210 'message' => 'On screen request, print media type is preserved'
1215 * Tests handheld behavior
1217 * @covers OutputPage::transformCssMedia
1219 public function testHandheld() {
1220 $this->assertTransformCssMediaCase( [
1221 'handheldQuery' => '1',
1222 'media' => 'handheld',
1223 'expectedReturn' => '',
1224 'message' => 'On request with handheld querystring and media is handheld, returns empty string'
1227 $this->assertTransformCssMediaCase( [
1228 'handheldQuery' => '1',
1229 'media' => 'screen',
1230 'expectedReturn' => null,
1231 'message' => 'On request with handheld querystring and media is screen, returns null'
1236 * @dataProvider providePreloadLinkHeaders
1237 * @covers OutputPage::addLogoPreloadLinkHeaders
1238 * @covers ResourceLoaderSkinModule::getLogo
1240 public function testPreloadLinkHeaders( $config, $result, $baseDir = null ) {
1242 $this->setMwGlobals( 'IP', $baseDir );
1244 $out = TestingAccessWrapper
::newFromObject( $this->newInstance( $config ) );
1245 $out->addLogoPreloadLinkHeaders();
1247 $this->assertEquals( $result, $out->getLinkHeader() );
1250 public function providePreloadLinkHeaders() {
1254 'ResourceBasePath' => '/w',
1255 'Logo' => '/img/default.png',
1257 '1.5x' => '/img/one-point-five.png',
1258 '2x' => '/img/two-x.png',
1261 'Link: </img/default.png>;rel=preload;as=image;media=' .
1262 'not all and (min-resolution: 1.5dppx),' .
1263 '</img/one-point-five.png>;rel=preload;as=image;media=' .
1264 '(min-resolution: 1.5dppx) and (max-resolution: 1.999999dppx),' .
1265 '</img/two-x.png>;rel=preload;as=image;media=(min-resolution: 2dppx)'
1269 'ResourceBasePath' => '/w',
1270 'Logo' => '/img/default.png',
1273 'Link: </img/default.png>;rel=preload;as=image'
1277 'ResourceBasePath' => '/w',
1278 'Logo' => '/img/default.png',
1280 '2x' => '/img/two-x.png',
1283 'Link: </img/default.png>;rel=preload;as=image;media=' .
1284 'not all and (min-resolution: 2dppx),' .
1285 '</img/two-x.png>;rel=preload;as=image;media=(min-resolution: 2dppx)'
1289 'ResourceBasePath' => '/w',
1290 'Logo' => '/img/default.png',
1292 'svg' => '/img/vector.svg',
1295 'Link: </img/vector.svg>;rel=preload;as=image'
1300 'ResourceBasePath' => '/w',
1301 'Logo' => '/w/test.jpg',
1303 'UploadPath' => '/w/images',
1305 'Link: </w/test.jpg?edcf2>;rel=preload;as=image',
1306 'baseDir' => dirname( __DIR__
) . '/data/media',
1312 * @return OutputPage
1314 private function newInstance( $config = [], WebRequest
$request = null ) {
1315 $context = new RequestContext();
1317 $context->setConfig( new MultiConfig( [
1318 new HashConfig( $config +
[
1319 'AppleTouchIcon' => false,
1320 'DisableLangConversion' => true,
1321 'EnableCanonicalServerLink' => false,
1324 'LanguageCode' => false,
1325 'ReferrerPolicy' => false,
1326 'RightsPage' => false,
1327 'RightsUrl' => false,
1328 'UniversalEditButton' => false,
1330 $context->getConfig()
1333 $context->setTitle( Title
::newFromText( 'My test page' ) );
1336 $context->setRequest( $request );
1339 return new OutputPage( $context );
1344 * MessageBlobStore that doesn't do anything
1346 class NullMessageBlobStore
extends MessageBlobStore
{
1347 public function get( ResourceLoader
$resourceLoader, $modules, $lang ) {
1351 public function updateModule( $name, ResourceLoaderModule
$module, $lang ) {
1354 public function updateMessage( $key ) {
1357 public function clear() {