3 use Wikimedia\TestingAccessWrapper
;
7 * @author Matthew Flaschen
12 * @todo factor tests in this class into providers and test methods
14 class OutputPageTest
extends MediaWikiTestCase
{
15 const SCREEN_MEDIA_QUERY
= 'screen and (min-width: 982px)';
16 const SCREEN_ONLY_MEDIA_QUERY
= 'only screen and (min-width: 982px)';
19 * @covers OutputPage::addMeta
20 * @covers OutputPage::getMetaTags
21 * @covers OutputPage::getHeadLinksArray
23 public function testMetaTags() {
24 $outputPage = $this->newInstance();
25 $outputPage->addMeta( 'http:expires', '0' );
26 $outputPage->addMeta( 'keywords', 'first' );
27 $outputPage->addMeta( 'keywords', 'second' );
28 $outputPage->addMeta( 'og:title', 'Ta-duh' );
31 [ 'http:expires', '0' ],
32 [ 'keywords', 'first' ],
33 [ 'keywords', 'second' ],
34 [ 'og:title', 'Ta-duh' ],
36 $this->assertSame( $expected, $outputPage->getMetaTags() );
38 $links = $outputPage->getHeadLinksArray();
39 $this->assertContains( '<meta http-equiv="expires" content="0"/>', $links );
40 $this->assertContains( '<meta name="keywords" content="first"/>', $links );
41 $this->assertContains( '<meta name="keywords" content="second"/>', $links );
42 $this->assertContains( '<meta property="og:title" content="Ta-duh"/>', $links );
43 $this->assertArrayNotHasKey( 'meta-robots', $links );
47 * @covers OutputPage::setIndexPolicy
48 * @covers OutputPage::setFollowPolicy
49 * @covers OutputPage::getHeadLinksArray
51 public function testRobotsPolicies() {
52 $outputPage = $this->newInstance();
53 $outputPage->setIndexPolicy( 'noindex' );
54 $outputPage->setFollowPolicy( 'nofollow' );
56 $links = $outputPage->getHeadLinksArray();
57 $this->assertContains( '<meta name="robots" content="noindex,nofollow"/>', $links );
61 * Tests a particular case of transformCssMedia, using the given input, globals,
62 * expected return, and message
64 * Asserts that $expectedReturn is returned.
66 * options['printableQuery'] - value of query string for printable, or omitted for none
67 * options['handheldQuery'] - value of query string for handheld, or omitted for none
68 * options['media'] - passed into the method under the same name
69 * options['expectedReturn'] - expected return value
70 * options['message'] - PHPUnit message for assertion
72 * @param array $args Key-value array of arguments as shown above
74 protected function assertTransformCssMediaCase( $args ) {
76 if ( isset( $args['printableQuery'] ) ) {
77 $queryData['printable'] = $args['printableQuery'];
80 if ( isset( $args['handheldQuery'] ) ) {
81 $queryData['handheld'] = $args['handheldQuery'];
84 $fauxRequest = new FauxRequest( $queryData, false );
85 $this->setMwGlobals( [
86 'wgRequest' => $fauxRequest,
89 $actualReturn = OutputPage
::transformCssMedia( $args['media'] );
90 $this->assertSame( $args['expectedReturn'], $actualReturn, $args['message'] );
94 * Tests print requests
95 * @covers OutputPage::transformCssMedia
97 public function testPrintRequests() {
98 $this->assertTransformCssMediaCase( [
99 'printableQuery' => '1',
101 'expectedReturn' => null,
102 'message' => 'On printable request, screen returns null'
105 $this->assertTransformCssMediaCase( [
106 'printableQuery' => '1',
107 'media' => self
::SCREEN_MEDIA_QUERY
,
108 'expectedReturn' => null,
109 'message' => 'On printable request, screen media query returns null'
112 $this->assertTransformCssMediaCase( [
113 'printableQuery' => '1',
114 'media' => self
::SCREEN_ONLY_MEDIA_QUERY
,
115 'expectedReturn' => null,
116 'message' => 'On printable request, screen media query with only returns null'
119 $this->assertTransformCssMediaCase( [
120 'printableQuery' => '1',
122 'expectedReturn' => '',
123 'message' => 'On printable request, media print returns empty string'
127 public static function provideCdnCacheEpoch() {
129 'pageTime' => '2011-04-01T12:00:00+00:00',
130 'maxAge' => 24 * 3600,
133 'after 1s' => [ $base +
[
134 'reqTime' => '2011-04-01T12:00:01+00:00',
135 'expect' => '2011-04-01T12:00:00+00:00',
137 'after 23h' => [ $base +
[
138 'reqTime' => '2011-04-02T11:00:00+00:00',
139 'expect' => '2011-04-01T12:00:00+00:00',
141 'after 24h and a bit' => [ $base +
[
142 'reqTime' => '2011-04-02T12:34:56+00:00',
143 'expect' => '2011-04-01T12:34:56+00:00',
145 'after a year' => [ $base +
[
146 'reqTime' => '2012-05-06T00:12:07+00:00',
147 'expect' => '2012-05-05T00:12:07+00:00',
153 * @dataProvider provideCdnCacheEpoch
154 * @covers OutputPage::getCdnCacheEpoch
156 public function testCdnCacheEpoch( $params ) {
157 $out = TestingAccessWrapper
::newFromObject( $this->newInstance() );
158 $reqTime = strtotime( $params['reqTime'] );
159 $pageTime = strtotime( $params['pageTime'] );
160 $actual = max( $pageTime, $out->getCdnCacheEpoch( $reqTime, $params['maxAge'] ) );
164 gmdate( DateTime
::ATOM
, $actual ),
170 * Tests screen requests, without either query parameter set
171 * @covers OutputPage::transformCssMedia
173 public function testScreenRequests() {
174 $this->assertTransformCssMediaCase( [
176 'expectedReturn' => 'screen',
177 'message' => 'On screen request, screen media type is preserved'
180 $this->assertTransformCssMediaCase( [
181 'media' => 'handheld',
182 'expectedReturn' => 'handheld',
183 'message' => 'On screen request, handheld media type is preserved'
186 $this->assertTransformCssMediaCase( [
187 'media' => self
::SCREEN_MEDIA_QUERY
,
188 'expectedReturn' => self
::SCREEN_MEDIA_QUERY
,
189 'message' => 'On screen request, screen media query is preserved.'
192 $this->assertTransformCssMediaCase( [
193 'media' => self
::SCREEN_ONLY_MEDIA_QUERY
,
194 'expectedReturn' => self
::SCREEN_ONLY_MEDIA_QUERY
,
195 'message' => 'On screen request, screen media query with only is preserved.'
198 $this->assertTransformCssMediaCase( [
200 'expectedReturn' => 'print',
201 'message' => 'On screen request, print media type is preserved'
206 * Tests handheld behavior
207 * @covers OutputPage::transformCssMedia
209 public function testHandheld() {
210 $this->assertTransformCssMediaCase( [
211 'handheldQuery' => '1',
212 'media' => 'handheld',
213 'expectedReturn' => '',
214 'message' => 'On request with handheld querystring and media is handheld, returns empty string'
217 $this->assertTransformCssMediaCase( [
218 'handheldQuery' => '1',
220 'expectedReturn' => null,
221 'message' => 'On request with handheld querystring and media is screen, returns null'
225 public static function provideTransformFilePath() {
226 $baseDir = dirname( __DIR__
) . '/data/media';
228 // File that matches basePath, and exists. Hash found and appended.
230 'baseDir' => $baseDir, 'basePath' => '/w',
234 // File that matches basePath, but not found on disk. Empty query.
236 'baseDir' => $baseDir, 'basePath' => '/w',
240 // File not matching basePath. Ignored.
242 'baseDir' => $baseDir, 'basePath' => '/w',
245 // Empty string. Ignored.
247 'baseDir' => $baseDir, 'basePath' => '/w',
251 // Similar path, but with domain component. Ignored.
253 'baseDir' => $baseDir, 'basePath' => '/w',
254 '//example.org/w/test.jpg'
257 'baseDir' => $baseDir, 'basePath' => '/w',
258 'https://example.org/w/test.jpg'
260 // Unrelated path with domain component. Ignored.
262 'baseDir' => $baseDir, 'basePath' => '/w',
263 'https://example.org/files/test.jpg'
266 'baseDir' => $baseDir, 'basePath' => '/w',
267 '//example.org/files/test.jpg'
269 // Unrelated path with domain, and empty base path (root mw install). Ignored.
271 'baseDir' => $baseDir, 'basePath' => '',
272 'https://example.org/files/test.jpg'
275 'baseDir' => $baseDir, 'basePath' => '',
277 '//example.org/files/test.jpg'
279 // Check UploadPath before ResourceBasePath (T155146)
281 'baseDir' => dirname( $baseDir ), 'basePath' => '',
282 'uploadDir' => $baseDir, 'uploadPath' => '/images',
284 '/images/test.jpg?edcf2'
290 * @dataProvider provideTransformFilePath
291 * @covers OutputPage::transformFilePath
292 * @covers OutputPage::transformResourcePath
294 public function testTransformResourcePath( $baseDir, $basePath, $uploadDir = null,
295 $uploadPath = null, $path = null, $expected = null
297 if ( $path === null ) {
298 // Skip optional $uploadDir and $uploadPath
300 $expected = $uploadPath;
301 $uploadDir = "$baseDir/images";
302 $uploadPath = "$basePath/images";
304 $this->setMwGlobals( 'IP', $baseDir );
305 $conf = new HashConfig( [
306 'ResourceBasePath' => $basePath,
307 'UploadDirectory' => $uploadDir,
308 'UploadPath' => $uploadPath,
311 Wikimedia\
suppressWarnings();
312 $actual = OutputPage
::transformResourcePath( $conf, $path );
313 Wikimedia\restoreWarnings
();
315 $this->assertEquals( $expected ?
: $path, $actual );
318 public static function provideMakeResourceLoaderLink() {
319 // phpcs:disable Generic.Files.LineLength
321 // Single only=scripts load
323 [ 'test.foo', ResourceLoaderModule
::TYPE_SCRIPTS
],
324 "<script>(window.RLQ=window.RLQ||[]).push(function(){"
325 . 'mw.loader.load("http://127.0.0.1:8080/w/load.php?debug=false\u0026lang=en\u0026modules=test.foo\u0026only=scripts\u0026skin=fallback");'
328 // Multiple only=styles load
330 [ [ 'test.baz', 'test.foo', 'test.bar' ], ResourceLoaderModule
::TYPE_STYLES
],
332 '<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"/>'
334 // Private embed (only=scripts)
336 [ 'test.quux', ResourceLoaderModule
::TYPE_SCRIPTS
],
337 "<script>(window.RLQ=window.RLQ||[]).push(function(){"
338 . "mw.test.baz({token:123});\nmw.loader.state({\"test.quux\":\"ready\"});"
346 * See ResourceLoaderClientHtmlTest for full coverage.
348 * @dataProvider provideMakeResourceLoaderLink
349 * @covers OutputPage::makeResourceLoaderLink
351 public function testMakeResourceLoaderLink( $args, $expectedHtml ) {
352 $this->setMwGlobals( [
353 'wgResourceLoaderDebug' => false,
354 'wgLoadScript' => 'http://127.0.0.1:8080/w/load.php',
356 $class = new ReflectionClass( OutputPage
::class );
357 $method = $class->getMethod( 'makeResourceLoaderLink' );
358 $method->setAccessible( true );
359 $ctx = new RequestContext();
360 $ctx->setSkin( SkinFactory
::getDefaultInstance()->makeSkin( 'fallback' ) );
361 $ctx->setLanguage( 'en' );
362 $out = new OutputPage( $ctx );
363 $rl = $out->getResourceLoader();
364 $rl->setMessageBlobStore( new NullMessageBlobStore() );
366 'test.foo' => new ResourceLoaderTestModule( [
367 'script' => 'mw.test.foo( { a: true } );',
368 'styles' => '.mw-test-foo { content: "style"; }',
370 'test.bar' => new ResourceLoaderTestModule( [
371 'script' => 'mw.test.bar( { a: true } );',
372 'styles' => '.mw-test-bar { content: "style"; }',
374 'test.baz' => new ResourceLoaderTestModule( [
375 'script' => 'mw.test.baz( { a: true } );',
376 'styles' => '.mw-test-baz { content: "style"; }',
378 'test.quux' => new ResourceLoaderTestModule( [
379 'script' => 'mw.test.baz( { token: 123 } );',
380 'styles' => '/* pref-animate=off */ .mw-icon { transition: none; }',
381 'group' => 'private',
384 $links = $method->invokeArgs( $out, $args );
385 $actualHtml = strval( $links );
386 $this->assertEquals( $expectedHtml, $actualHtml );
389 public static function provideBuildExemptModules() {
390 // phpcs:disable Generic.Files.LineLength
393 'exemptStyleModules' => [],
394 '<meta name="ResourceLoaderDynamicStyles" content=""/>',
397 'exemptStyleModules' => [ 'site' => [], 'noscript' => [], 'private' => [], 'user' => [] ],
398 '<meta name="ResourceLoaderDynamicStyles" content=""/>',
400 'default logged-out' => [
401 'exemptStyleModules' => [ 'site' => [ 'site.styles' ] ],
402 '<meta name="ResourceLoaderDynamicStyles" content=""/>' . "\n" .
403 '<link rel="stylesheet" href="/w/load.php?debug=false&lang=en&modules=site.styles&only=styles&skin=fallback"/>',
405 'default logged-in' => [
406 'exemptStyleModules' => [ 'site' => [ 'site.styles' ], 'user' => [ 'user.styles' ] ],
407 '<meta name="ResourceLoaderDynamicStyles" content=""/>' . "\n" .
408 '<link rel="stylesheet" href="/w/load.php?debug=false&lang=en&modules=site.styles&only=styles&skin=fallback"/>' . "\n" .
409 '<link rel="stylesheet" href="/w/load.php?debug=false&lang=en&modules=user.styles&only=styles&skin=fallback&version=1e9z0ox"/>',
411 'custom modules' => [
412 'exemptStyleModules' => [
413 'site' => [ 'site.styles', 'example.site.a', 'example.site.b' ],
414 'user' => [ 'user.styles', 'example.user' ],
416 '<meta name="ResourceLoaderDynamicStyles" content=""/>' . "\n" .
417 '<link rel="stylesheet" href="/w/load.php?debug=false&lang=en&modules=example.site.a%2Cb&only=styles&skin=fallback"/>' . "\n" .
418 '<link rel="stylesheet" href="/w/load.php?debug=false&lang=en&modules=site.styles&only=styles&skin=fallback"/>' . "\n" .
419 '<link rel="stylesheet" href="/w/load.php?debug=false&lang=en&modules=example.user&only=styles&skin=fallback&version=0a56zyi"/>' . "\n" .
420 '<link rel="stylesheet" href="/w/load.php?debug=false&lang=en&modules=user.styles&only=styles&skin=fallback&version=1e9z0ox"/>',
427 * @dataProvider provideBuildExemptModules
428 * @covers OutputPage::buildExemptModules
430 public function testBuildExemptModules( array $exemptStyleModules, $expect ) {
431 $this->setMwGlobals( [
432 'wgResourceLoaderDebug' => false,
433 'wgLoadScript' => '/w/load.php',
434 // Stub wgCacheEpoch as it influences getVersionHash used for the
435 // urls in the expected HTML
436 'wgCacheEpoch' => '20140101000000',
440 $ctx = new RequestContext();
441 $ctx->setSkin( SkinFactory
::getDefaultInstance()->makeSkin( 'fallback' ) );
442 $ctx->setLanguage( 'en' );
443 $outputPage = $this->getMockBuilder( OutputPage
::class )
444 ->setConstructorArgs( [ $ctx ] )
445 ->setMethods( [ 'buildCssLinksArray' ] )
447 $outputPage->expects( $this->any() )
448 ->method( 'buildCssLinksArray' )
450 $rl = $outputPage->getResourceLoader();
451 $rl->setMessageBlobStore( new NullMessageBlobStore() );
453 // Register custom modules
455 'example.site.a' => new ResourceLoaderTestModule( [ 'group' => 'site' ] ),
456 'example.site.b' => new ResourceLoaderTestModule( [ 'group' => 'site' ] ),
457 'example.user' => new ResourceLoaderTestModule( [ 'group' => 'user' ] ),
460 $outputPage = TestingAccessWrapper
::newFromObject( $outputPage );
461 $outputPage->rlExemptStyleModules
= $exemptStyleModules;
464 strval( $outputPage->buildExemptModules() )
469 * @dataProvider provideVaryHeaders
470 * @covers OutputPage::addVaryHeader
471 * @covers OutputPage::getVaryHeader
472 * @covers OutputPage::getKeyHeader
474 public function testVaryHeaders( $calls, $vary, $key ) {
475 // get rid of default Vary fields
476 $outputPage = $this->getMockBuilder( OutputPage
::class )
477 ->setConstructorArgs( [ new RequestContext() ] )
478 ->setMethods( [ 'getCacheVaryCookies' ] )
480 $outputPage->expects( $this->any() )
481 ->method( 'getCacheVaryCookies' )
482 ->will( $this->returnValue( [] ) );
483 TestingAccessWrapper
::newFromObject( $outputPage )->mVaryHeader
= [];
485 foreach ( $calls as $call ) {
486 call_user_func_array( [ $outputPage, 'addVaryHeader' ], $call );
488 $this->assertEquals( $vary, $outputPage->getVaryHeader(), 'Vary:' );
489 $this->assertEquals( $key, $outputPage->getKeyHeader(), 'Key:' );
492 public function provideVaryHeaders() {
493 // note: getKeyHeader() automatically adds Vary: Cookie
502 [ // non-unique headers
505 [ 'Accept-Language' ],
508 'Vary: Cookie, Accept-Language',
509 'Key: Cookie,Accept-Language',
511 [ // two headers with single options
513 [ 'Cookie', [ 'param=phpsessid' ] ],
514 [ 'Accept-Language', [ 'substr=en' ] ],
516 'Vary: Cookie, Accept-Language',
517 'Key: Cookie;param=phpsessid,Accept-Language;substr=en',
519 [ // one header with multiple options
521 [ 'Cookie', [ 'param=phpsessid', 'param=userId' ] ],
524 'Key: Cookie;param=phpsessid;param=userId',
526 [ // Duplicate option
528 [ 'Cookie', [ 'param=phpsessid' ] ],
529 [ 'Cookie', [ 'param=phpsessid' ] ],
530 [ 'Accept-Language', [ 'substr=en', 'substr=en' ] ],
532 'Vary: Cookie, Accept-Language',
533 'Key: Cookie;param=phpsessid,Accept-Language;substr=en',
535 [ // Same header, different options
537 [ 'Cookie', [ 'param=phpsessid' ] ],
538 [ 'Cookie', [ 'param=userId' ] ],
541 'Key: Cookie;param=phpsessid;param=userId',
547 * @covers OutputPage::haveCacheVaryCookies
549 public function testHaveCacheVaryCookies() {
550 $request = new FauxRequest();
551 $context = new RequestContext();
552 $context->setRequest( $request );
553 $outputPage = new OutputPage( $context );
555 // No cookies are set.
556 $this->assertFalse( $outputPage->haveCacheVaryCookies() );
558 // 'Token' is present but empty, so it shouldn't count.
559 $request->setCookie( 'Token', '' );
560 $this->assertFalse( $outputPage->haveCacheVaryCookies() );
562 // 'Token' present and nonempty.
563 $request->setCookie( 'Token', '123' );
564 $this->assertTrue( $outputPage->haveCacheVaryCookies() );
568 * @covers OutputPage::addCategoryLinks
569 * @covers OutputPage::getCategories
571 public function testGetCategories() {
572 $fakeResultWrapper = new FakeResultWrapper( [
575 'page_title' => 'Test'
578 'page_title' => 'Test2'
581 $outputPage = $this->getMockBuilder( OutputPage
::class )
582 ->setConstructorArgs( [ new RequestContext() ] )
583 ->setMethods( [ 'addCategoryLinksToLBAndGetResult' ] )
585 $outputPage->expects( $this->any() )
586 ->method( 'addCategoryLinksToLBAndGetResult' )
587 ->will( $this->returnValue( $fakeResultWrapper ) );
589 $outputPage->addCategoryLinks( [
593 $this->assertEquals( [ 0 => 'Test', '1' => 'Test2' ], $outputPage->getCategories() );
594 $this->assertEquals( [ 0 => 'Test2' ], $outputPage->getCategories( 'normal' ) );
595 $this->assertEquals( [ 0 => 'Test' ], $outputPage->getCategories( 'hidden' ) );
599 * @dataProvider provideLinkHeaders
600 * @covers OutputPage::addLinkHeader
601 * @covers OutputPage::getLinkHeader
603 public function testLinkHeaders( $headers, $result ) {
604 $outputPage = $this->newInstance();
606 foreach ( $headers as $header ) {
607 $outputPage->addLinkHeader( $header );
610 $this->assertEquals( $result, $outputPage->getLinkHeader() );
613 public function provideLinkHeaders() {
620 [ '<https://foo/bar.jpg>;rel=preload;as=image' ],
621 'Link: <https://foo/bar.jpg>;rel=preload;as=image',
624 [ '<https://foo/bar.jpg>;rel=preload;as=image','<https://foo/baz.jpg>;rel=preload;as=image' ],
625 'Link: <https://foo/bar.jpg>;rel=preload;as=image,<https://foo/baz.jpg>;rel=preload;as=image',
631 * @dataProvider providePreloadLinkHeaders
632 * @covers OutputPage::addLogoPreloadLinkHeaders
633 * @covers ResourceLoaderSkinModule::getLogo
635 public function testPreloadLinkHeaders( $config, $result, $baseDir = null ) {
637 $this->setMwGlobals( 'IP', $baseDir );
639 $out = TestingAccessWrapper
::newFromObject( $this->newInstance( $config ) );
640 $out->addLogoPreloadLinkHeaders();
642 $this->assertEquals( $result, $out->getLinkHeader() );
645 public function providePreloadLinkHeaders() {
649 'ResourceBasePath' => '/w',
650 'Logo' => '/img/default.png',
652 '1.5x' => '/img/one-point-five.png',
653 '2x' => '/img/two-x.png',
656 'Link: </img/default.png>;rel=preload;as=image;media=' .
657 'not all and (min-resolution: 1.5dppx),' .
658 '</img/one-point-five.png>;rel=preload;as=image;media=' .
659 '(min-resolution: 1.5dppx) and (max-resolution: 1.999999dppx),' .
660 '</img/two-x.png>;rel=preload;as=image;media=(min-resolution: 2dppx)'
664 'ResourceBasePath' => '/w',
665 'Logo' => '/img/default.png',
668 'Link: </img/default.png>;rel=preload;as=image'
672 'ResourceBasePath' => '/w',
673 'Logo' => '/img/default.png',
675 '2x' => '/img/two-x.png',
678 'Link: </img/default.png>;rel=preload;as=image;media=' .
679 'not all and (min-resolution: 2dppx),' .
680 '</img/two-x.png>;rel=preload;as=image;media=(min-resolution: 2dppx)'
684 'ResourceBasePath' => '/w',
685 'Logo' => '/img/default.png',
687 'svg' => '/img/vector.svg',
690 'Link: </img/vector.svg>;rel=preload;as=image'
695 'ResourceBasePath' => '/w',
696 'Logo' => '/w/test.jpg',
698 'UploadPath' => '/w/images',
700 'Link: </w/test.jpg?edcf2>;rel=preload;as=image',
701 'baseDir' => dirname( __DIR__
) . '/data/media',
709 private function newInstance( $config = [] ) {
710 $context = new RequestContext();
712 $context->setConfig( new HashConfig( $config +
[
713 'AppleTouchIcon' => false,
714 'DisableLangConversion' => true,
715 'EnableCanonicalServerLink' => false,
718 'LanguageCode' => false,
719 'ReferrerPolicy' => false,
720 'RightsPage' => false,
721 'RightsUrl' => false,
722 'UniversalEditButton' => false,
725 return new OutputPage( $context );
730 * MessageBlobStore that doesn't do anything
732 class NullMessageBlobStore
extends MessageBlobStore
{
733 public function get( ResourceLoader
$resourceLoader, $modules, $lang ) {
737 public function updateModule( $name, ResourceLoaderModule
$module, $lang ) {
740 public function updateMessage( $key ) {
743 public function clear() {