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
155 public function testCdnCacheEpoch( $params ) {
156 $out = TestingAccessWrapper
::newFromObject( $this->newInstance() );
157 $reqTime = strtotime( $params['reqTime'] );
158 $pageTime = strtotime( $params['pageTime'] );
159 $actual = max( $pageTime, $out->getCdnCacheEpoch( $reqTime, $params['maxAge'] ) );
163 gmdate( DateTime
::ATOM
, $actual ),
169 * Tests screen requests, without either query parameter set
170 * @covers OutputPage::transformCssMedia
172 public function testScreenRequests() {
173 $this->assertTransformCssMediaCase( [
175 'expectedReturn' => 'screen',
176 'message' => 'On screen request, screen media type is preserved'
179 $this->assertTransformCssMediaCase( [
180 'media' => 'handheld',
181 'expectedReturn' => 'handheld',
182 'message' => 'On screen request, handheld media type is preserved'
185 $this->assertTransformCssMediaCase( [
186 'media' => self
::SCREEN_MEDIA_QUERY
,
187 'expectedReturn' => self
::SCREEN_MEDIA_QUERY
,
188 'message' => 'On screen request, screen media query is preserved.'
191 $this->assertTransformCssMediaCase( [
192 'media' => self
::SCREEN_ONLY_MEDIA_QUERY
,
193 'expectedReturn' => self
::SCREEN_ONLY_MEDIA_QUERY
,
194 'message' => 'On screen request, screen media query with only is preserved.'
197 $this->assertTransformCssMediaCase( [
199 'expectedReturn' => 'print',
200 'message' => 'On screen request, print media type is preserved'
205 * Tests handheld behavior
206 * @covers OutputPage::transformCssMedia
208 public function testHandheld() {
209 $this->assertTransformCssMediaCase( [
210 'handheldQuery' => '1',
211 'media' => 'handheld',
212 'expectedReturn' => '',
213 'message' => 'On request with handheld querystring and media is handheld, returns empty string'
216 $this->assertTransformCssMediaCase( [
217 'handheldQuery' => '1',
219 'expectedReturn' => null,
220 'message' => 'On request with handheld querystring and media is screen, returns null'
224 public static function provideTransformFilePath() {
225 $baseDir = dirname( __DIR__
) . '/data/media';
227 // File that matches basePath, and exists. Hash found and appended.
229 'baseDir' => $baseDir, 'basePath' => '/w',
233 // File that matches basePath, but not found on disk. Empty query.
235 'baseDir' => $baseDir, 'basePath' => '/w',
239 // File not matching basePath. Ignored.
241 'baseDir' => $baseDir, 'basePath' => '/w',
244 // Empty string. Ignored.
246 'baseDir' => $baseDir, 'basePath' => '/w',
250 // Similar path, but with domain component. Ignored.
252 'baseDir' => $baseDir, 'basePath' => '/w',
253 '//example.org/w/test.jpg'
256 'baseDir' => $baseDir, 'basePath' => '/w',
257 'https://example.org/w/test.jpg'
259 // Unrelated path with domain component. Ignored.
261 'baseDir' => $baseDir, 'basePath' => '/w',
262 'https://example.org/files/test.jpg'
265 'baseDir' => $baseDir, 'basePath' => '/w',
266 '//example.org/files/test.jpg'
268 // Unrelated path with domain, and empty base path (root mw install). Ignored.
270 'baseDir' => $baseDir, 'basePath' => '',
271 'https://example.org/files/test.jpg'
274 'baseDir' => $baseDir, 'basePath' => '',
276 '//example.org/files/test.jpg'
278 // Check UploadPath before ResourceBasePath (T155146)
280 'baseDir' => dirname( $baseDir ), 'basePath' => '',
281 'uploadDir' => $baseDir, 'uploadPath' => '/images',
283 '/images/test.jpg?edcf2'
289 * @dataProvider provideTransformFilePath
290 * @covers OutputPage::transformFilePath
291 * @covers OutputPage::transformResourcePath
293 public function testTransformResourcePath( $baseDir, $basePath, $uploadDir = null,
294 $uploadPath = null, $path = null, $expected = null
296 if ( $path === null ) {
297 // Skip optional $uploadDir and $uploadPath
299 $expected = $uploadPath;
300 $uploadDir = "$baseDir/images";
301 $uploadPath = "$basePath/images";
303 $this->setMwGlobals( 'IP', $baseDir );
304 $conf = new HashConfig( [
305 'ResourceBasePath' => $basePath,
306 'UploadDirectory' => $uploadDir,
307 'UploadPath' => $uploadPath,
310 Wikimedia\
suppressWarnings();
311 $actual = OutputPage
::transformResourcePath( $conf, $path );
312 Wikimedia\restoreWarnings
();
314 $this->assertEquals( $expected ?
: $path, $actual );
317 public static function provideMakeResourceLoaderLink() {
318 // phpcs:disable Generic.Files.LineLength
320 // Single only=scripts load
322 [ 'test.foo', ResourceLoaderModule
::TYPE_SCRIPTS
],
323 "<script>(window.RLQ=window.RLQ||[]).push(function(){"
324 . 'mw.loader.load("http://127.0.0.1:8080/w/load.php?debug=false\u0026lang=en\u0026modules=test.foo\u0026only=scripts\u0026skin=fallback");'
327 // Multiple only=styles load
329 [ [ 'test.baz', 'test.foo', 'test.bar' ], ResourceLoaderModule
::TYPE_STYLES
],
331 '<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"/>'
333 // Private embed (only=scripts)
335 [ 'test.quux', ResourceLoaderModule
::TYPE_SCRIPTS
],
336 "<script>(window.RLQ=window.RLQ||[]).push(function(){"
337 . "mw.test.baz({token:123});\nmw.loader.state({\"test.quux\":\"ready\"});"
345 * See ResourceLoaderClientHtmlTest for full coverage.
347 * @dataProvider provideMakeResourceLoaderLink
348 * @covers OutputPage::makeResourceLoaderLink
350 public function testMakeResourceLoaderLink( $args, $expectedHtml ) {
351 $this->setMwGlobals( [
352 'wgResourceLoaderDebug' => false,
353 'wgLoadScript' => 'http://127.0.0.1:8080/w/load.php',
355 $class = new ReflectionClass( OutputPage
::class );
356 $method = $class->getMethod( 'makeResourceLoaderLink' );
357 $method->setAccessible( true );
358 $ctx = new RequestContext();
359 $ctx->setSkin( SkinFactory
::getDefaultInstance()->makeSkin( 'fallback' ) );
360 $ctx->setLanguage( 'en' );
361 $out = new OutputPage( $ctx );
362 $rl = $out->getResourceLoader();
363 $rl->setMessageBlobStore( new NullMessageBlobStore() );
365 'test.foo' => new ResourceLoaderTestModule( [
366 'script' => 'mw.test.foo( { a: true } );',
367 'styles' => '.mw-test-foo { content: "style"; }',
369 'test.bar' => new ResourceLoaderTestModule( [
370 'script' => 'mw.test.bar( { a: true } );',
371 'styles' => '.mw-test-bar { content: "style"; }',
373 'test.baz' => new ResourceLoaderTestModule( [
374 'script' => 'mw.test.baz( { a: true } );',
375 'styles' => '.mw-test-baz { content: "style"; }',
377 'test.quux' => new ResourceLoaderTestModule( [
378 'script' => 'mw.test.baz( { token: 123 } );',
379 'styles' => '/* pref-animate=off */ .mw-icon { transition: none; }',
380 'group' => 'private',
383 $links = $method->invokeArgs( $out, $args );
384 $actualHtml = strval( $links );
385 $this->assertEquals( $expectedHtml, $actualHtml );
388 public static function provideBuildExemptModules() {
389 // phpcs:disable Generic.Files.LineLength
392 'exemptStyleModules' => [],
393 '<meta name="ResourceLoaderDynamicStyles" content=""/>',
396 'exemptStyleModules' => [ 'site' => [], 'noscript' => [], 'private' => [], 'user' => [] ],
397 '<meta name="ResourceLoaderDynamicStyles" content=""/>',
399 'default logged-out' => [
400 'exemptStyleModules' => [ 'site' => [ 'site.styles' ] ],
401 '<meta name="ResourceLoaderDynamicStyles" content=""/>' . "\n" .
402 '<link rel="stylesheet" href="/w/load.php?debug=false&lang=en&modules=site.styles&only=styles&skin=fallback"/>',
404 'default logged-in' => [
405 'exemptStyleModules' => [ 'site' => [ 'site.styles' ], 'user' => [ 'user.styles' ] ],
406 '<meta name="ResourceLoaderDynamicStyles" content=""/>' . "\n" .
407 '<link rel="stylesheet" href="/w/load.php?debug=false&lang=en&modules=site.styles&only=styles&skin=fallback"/>' . "\n" .
408 '<link rel="stylesheet" href="/w/load.php?debug=false&lang=en&modules=user.styles&only=styles&skin=fallback&version=1e9z0ox"/>',
410 'custom modules' => [
411 'exemptStyleModules' => [
412 'site' => [ 'site.styles', 'example.site.a', 'example.site.b' ],
413 'user' => [ 'user.styles', 'example.user' ],
415 '<meta name="ResourceLoaderDynamicStyles" content=""/>' . "\n" .
416 '<link rel="stylesheet" href="/w/load.php?debug=false&lang=en&modules=example.site.a%2Cb&only=styles&skin=fallback"/>' . "\n" .
417 '<link rel="stylesheet" href="/w/load.php?debug=false&lang=en&modules=site.styles&only=styles&skin=fallback"/>' . "\n" .
418 '<link rel="stylesheet" href="/w/load.php?debug=false&lang=en&modules=example.user&only=styles&skin=fallback&version=0a56zyi"/>' . "\n" .
419 '<link rel="stylesheet" href="/w/load.php?debug=false&lang=en&modules=user.styles&only=styles&skin=fallback&version=1e9z0ox"/>',
426 * @dataProvider provideBuildExemptModules
427 * @covers OutputPage::buildExemptModules
429 public function testBuildExemptModules( array $exemptStyleModules, $expect ) {
430 $this->setMwGlobals( [
431 'wgResourceLoaderDebug' => false,
432 'wgLoadScript' => '/w/load.php',
433 // Stub wgCacheEpoch as it influences getVersionHash used for the
434 // urls in the expected HTML
435 'wgCacheEpoch' => '20140101000000',
439 $ctx = new RequestContext();
440 $ctx->setSkin( SkinFactory
::getDefaultInstance()->makeSkin( 'fallback' ) );
441 $ctx->setLanguage( 'en' );
442 $outputPage = $this->getMockBuilder( OutputPage
::class )
443 ->setConstructorArgs( [ $ctx ] )
444 ->setMethods( [ 'isUserCssPreview', 'buildCssLinksArray' ] )
446 $outputPage->expects( $this->any() )
447 ->method( 'isUserCssPreview' )
448 ->willReturn( false );
449 $outputPage->expects( $this->any() )
450 ->method( 'buildCssLinksArray' )
452 $rl = $outputPage->getResourceLoader();
453 $rl->setMessageBlobStore( new NullMessageBlobStore() );
455 // Register custom modules
457 'example.site.a' => new ResourceLoaderTestModule( [ 'group' => 'site' ] ),
458 'example.site.b' => new ResourceLoaderTestModule( [ 'group' => 'site' ] ),
459 'example.user' => new ResourceLoaderTestModule( [ 'group' => 'user' ] ),
462 $outputPage = TestingAccessWrapper
::newFromObject( $outputPage );
463 $outputPage->rlExemptStyleModules
= $exemptStyleModules;
466 strval( $outputPage->buildExemptModules() )
471 * @dataProvider provideVaryHeaders
472 * @covers OutputPage::addVaryHeader
473 * @covers OutputPage::getVaryHeader
474 * @covers OutputPage::getKeyHeader
476 public function testVaryHeaders( $calls, $vary, $key ) {
477 // get rid of default Vary fields
478 $outputPage = $this->getMockBuilder( OutputPage
::class )
479 ->setConstructorArgs( [ new RequestContext() ] )
480 ->setMethods( [ 'getCacheVaryCookies' ] )
482 $outputPage->expects( $this->any() )
483 ->method( 'getCacheVaryCookies' )
484 ->will( $this->returnValue( [] ) );
485 TestingAccessWrapper
::newFromObject( $outputPage )->mVaryHeader
= [];
487 foreach ( $calls as $call ) {
488 call_user_func_array( [ $outputPage, 'addVaryHeader' ], $call );
490 $this->assertEquals( $vary, $outputPage->getVaryHeader(), 'Vary:' );
491 $this->assertEquals( $key, $outputPage->getKeyHeader(), 'Key:' );
494 public function provideVaryHeaders() {
495 // note: getKeyHeader() automatically adds Vary: Cookie
504 [ // non-unique headers
507 [ 'Accept-Language' ],
510 'Vary: Cookie, Accept-Language',
511 'Key: Cookie,Accept-Language',
513 [ // two headers with single options
515 [ 'Cookie', [ 'param=phpsessid' ] ],
516 [ 'Accept-Language', [ 'substr=en' ] ],
518 'Vary: Cookie, Accept-Language',
519 'Key: Cookie;param=phpsessid,Accept-Language;substr=en',
521 [ // one header with multiple options
523 [ 'Cookie', [ 'param=phpsessid', 'param=userId' ] ],
526 'Key: Cookie;param=phpsessid;param=userId',
528 [ // Duplicate option
530 [ 'Cookie', [ 'param=phpsessid' ] ],
531 [ 'Cookie', [ 'param=phpsessid' ] ],
532 [ 'Accept-Language', [ 'substr=en', 'substr=en' ] ],
534 'Vary: Cookie, Accept-Language',
535 'Key: Cookie;param=phpsessid,Accept-Language;substr=en',
537 [ // Same header, different options
539 [ 'Cookie', [ 'param=phpsessid' ] ],
540 [ 'Cookie', [ 'param=userId' ] ],
543 'Key: Cookie;param=phpsessid;param=userId',
549 * @covers OutputPage::haveCacheVaryCookies
551 public function testHaveCacheVaryCookies() {
552 $request = new FauxRequest();
553 $context = new RequestContext();
554 $context->setRequest( $request );
555 $outputPage = new OutputPage( $context );
557 // No cookies are set.
558 $this->assertFalse( $outputPage->haveCacheVaryCookies() );
560 // 'Token' is present but empty, so it shouldn't count.
561 $request->setCookie( 'Token', '' );
562 $this->assertFalse( $outputPage->haveCacheVaryCookies() );
564 // 'Token' present and nonempty.
565 $request->setCookie( 'Token', '123' );
566 $this->assertTrue( $outputPage->haveCacheVaryCookies() );
570 * @covers OutputPage::addCategoryLinks
571 * @covers OutputPage::getCategories
573 public function testGetCategories() {
574 $fakeResultWrapper = new FakeResultWrapper( [
577 'page_title' => 'Test'
580 'page_title' => 'Test2'
583 $outputPage = $this->getMockBuilder( OutputPage
::class )
584 ->setConstructorArgs( [ new RequestContext() ] )
585 ->setMethods( [ 'addCategoryLinksToLBAndGetResult' ] )
587 $outputPage->expects( $this->any() )
588 ->method( 'addCategoryLinksToLBAndGetResult' )
589 ->will( $this->returnValue( $fakeResultWrapper ) );
591 $outputPage->addCategoryLinks( [
595 $this->assertEquals( [ 0 => 'Test', '1' => 'Test2' ], $outputPage->getCategories() );
596 $this->assertEquals( [ 0 => 'Test2' ], $outputPage->getCategories( 'normal' ) );
597 $this->assertEquals( [ 0 => 'Test' ], $outputPage->getCategories( 'hidden' ) );
601 * @dataProvider provideLinkHeaders
602 * @covers OutputPage::addLinkHeader
603 * @covers OutputPage::getLinkHeader
605 public function testLinkHeaders( $headers, $result ) {
606 $outputPage = $this->newInstance();
608 foreach ( $headers as $header ) {
609 $outputPage->addLinkHeader( $header );
612 $this->assertEquals( $result, $outputPage->getLinkHeader() );
615 public function provideLinkHeaders() {
622 [ '<https://foo/bar.jpg>;rel=preload;as=image' ],
623 'Link: <https://foo/bar.jpg>;rel=preload;as=image',
626 [ '<https://foo/bar.jpg>;rel=preload;as=image','<https://foo/baz.jpg>;rel=preload;as=image' ],
627 'Link: <https://foo/bar.jpg>;rel=preload;as=image,<https://foo/baz.jpg>;rel=preload;as=image',
633 * @dataProvider providePreloadLinkHeaders
634 * @covers OutputPage::addLogoPreloadLinkHeaders
635 * @covers ResourceLoaderSkinModule::getLogo
637 public function testPreloadLinkHeaders( $config, $result, $baseDir = null ) {
639 $this->setMwGlobals( 'IP', $baseDir );
641 $out = TestingAccessWrapper
::newFromObject( $this->newInstance( $config ) );
642 $out->addLogoPreloadLinkHeaders();
644 $this->assertEquals( $result, $out->getLinkHeader() );
647 public function providePreloadLinkHeaders() {
651 'ResourceBasePath' => '/w',
652 'Logo' => '/img/default.png',
654 '1.5x' => '/img/one-point-five.png',
655 '2x' => '/img/two-x.png',
658 'Link: </img/default.png>;rel=preload;as=image;media=' .
659 'not all and (min-resolution: 1.5dppx),' .
660 '</img/one-point-five.png>;rel=preload;as=image;media=' .
661 '(min-resolution: 1.5dppx) and (max-resolution: 1.999999dppx),' .
662 '</img/two-x.png>;rel=preload;as=image;media=(min-resolution: 2dppx)'
666 'ResourceBasePath' => '/w',
667 'Logo' => '/img/default.png',
670 'Link: </img/default.png>;rel=preload;as=image'
674 'ResourceBasePath' => '/w',
675 'Logo' => '/img/default.png',
677 '2x' => '/img/two-x.png',
680 'Link: </img/default.png>;rel=preload;as=image;media=' .
681 'not all and (min-resolution: 2dppx),' .
682 '</img/two-x.png>;rel=preload;as=image;media=(min-resolution: 2dppx)'
686 'ResourceBasePath' => '/w',
687 'Logo' => '/img/default.png',
689 'svg' => '/img/vector.svg',
692 'Link: </img/vector.svg>;rel=preload;as=image'
697 'ResourceBasePath' => '/w',
698 'Logo' => '/w/test.jpg',
700 'UploadPath' => '/w/images',
702 'Link: </w/test.jpg?edcf2>;rel=preload;as=image',
703 'baseDir' => dirname( __DIR__
) . '/data/media',
711 private function newInstance( $config = [] ) {
712 $context = new RequestContext();
714 $context->setConfig( new HashConfig( $config +
[
715 'AppleTouchIcon' => false,
716 'DisableLangConversion' => true,
717 'EnableCanonicalServerLink' => false,
720 'LanguageCode' => false,
721 'ReferrerPolicy' => false,
722 'RightsPage' => false,
723 'RightsUrl' => false,
724 'UniversalEditButton' => false,
727 return new OutputPage( $context );
732 * MessageBlobStore that doesn't do anything
734 class NullMessageBlobStore
extends MessageBlobStore
{
735 public function get( ResourceLoader
$resourceLoader, $modules, $lang ) {
739 public function updateModule( $name, ResourceLoaderModule
$module, $lang ) {
742 public function updateMessage( $key ) {
745 public function clear() {