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( [ 'buildCssLinksArray' ] )
446 $outputPage->expects( $this->any() )
447 ->method( 'buildCssLinksArray' )
449 $rl = $outputPage->getResourceLoader();
450 $rl->setMessageBlobStore( new NullMessageBlobStore() );
452 // Register custom modules
454 'example.site.a' => new ResourceLoaderTestModule( [ 'group' => 'site' ] ),
455 'example.site.b' => new ResourceLoaderTestModule( [ 'group' => 'site' ] ),
456 'example.user' => new ResourceLoaderTestModule( [ 'group' => 'user' ] ),
459 $outputPage = TestingAccessWrapper
::newFromObject( $outputPage );
460 $outputPage->rlExemptStyleModules
= $exemptStyleModules;
463 strval( $outputPage->buildExemptModules() )
468 * @dataProvider provideVaryHeaders
469 * @covers OutputPage::addVaryHeader
470 * @covers OutputPage::getVaryHeader
471 * @covers OutputPage::getKeyHeader
473 public function testVaryHeaders( $calls, $vary, $key ) {
474 // get rid of default Vary fields
475 $outputPage = $this->getMockBuilder( OutputPage
::class )
476 ->setConstructorArgs( [ new RequestContext() ] )
477 ->setMethods( [ 'getCacheVaryCookies' ] )
479 $outputPage->expects( $this->any() )
480 ->method( 'getCacheVaryCookies' )
481 ->will( $this->returnValue( [] ) );
482 TestingAccessWrapper
::newFromObject( $outputPage )->mVaryHeader
= [];
484 foreach ( $calls as $call ) {
485 call_user_func_array( [ $outputPage, 'addVaryHeader' ], $call );
487 $this->assertEquals( $vary, $outputPage->getVaryHeader(), 'Vary:' );
488 $this->assertEquals( $key, $outputPage->getKeyHeader(), 'Key:' );
491 public function provideVaryHeaders() {
492 // note: getKeyHeader() automatically adds Vary: Cookie
501 [ // non-unique headers
504 [ 'Accept-Language' ],
507 'Vary: Cookie, Accept-Language',
508 'Key: Cookie,Accept-Language',
510 [ // two headers with single options
512 [ 'Cookie', [ 'param=phpsessid' ] ],
513 [ 'Accept-Language', [ 'substr=en' ] ],
515 'Vary: Cookie, Accept-Language',
516 'Key: Cookie;param=phpsessid,Accept-Language;substr=en',
518 [ // one header with multiple options
520 [ 'Cookie', [ 'param=phpsessid', 'param=userId' ] ],
523 'Key: Cookie;param=phpsessid;param=userId',
525 [ // Duplicate option
527 [ 'Cookie', [ 'param=phpsessid' ] ],
528 [ 'Cookie', [ 'param=phpsessid' ] ],
529 [ 'Accept-Language', [ 'substr=en', 'substr=en' ] ],
531 'Vary: Cookie, Accept-Language',
532 'Key: Cookie;param=phpsessid,Accept-Language;substr=en',
534 [ // Same header, different options
536 [ 'Cookie', [ 'param=phpsessid' ] ],
537 [ 'Cookie', [ 'param=userId' ] ],
540 'Key: Cookie;param=phpsessid;param=userId',
546 * @covers OutputPage::haveCacheVaryCookies
548 public function testHaveCacheVaryCookies() {
549 $request = new FauxRequest();
550 $context = new RequestContext();
551 $context->setRequest( $request );
552 $outputPage = new OutputPage( $context );
554 // No cookies are set.
555 $this->assertFalse( $outputPage->haveCacheVaryCookies() );
557 // 'Token' is present but empty, so it shouldn't count.
558 $request->setCookie( 'Token', '' );
559 $this->assertFalse( $outputPage->haveCacheVaryCookies() );
561 // 'Token' present and nonempty.
562 $request->setCookie( 'Token', '123' );
563 $this->assertTrue( $outputPage->haveCacheVaryCookies() );
567 * @covers OutputPage::addCategoryLinks
568 * @covers OutputPage::getCategories
570 public function testGetCategories() {
571 $fakeResultWrapper = new FakeResultWrapper( [
574 'page_title' => 'Test'
577 'page_title' => 'Test2'
580 $outputPage = $this->getMockBuilder( OutputPage
::class )
581 ->setConstructorArgs( [ new RequestContext() ] )
582 ->setMethods( [ 'addCategoryLinksToLBAndGetResult' ] )
584 $outputPage->expects( $this->any() )
585 ->method( 'addCategoryLinksToLBAndGetResult' )
586 ->will( $this->returnValue( $fakeResultWrapper ) );
588 $outputPage->addCategoryLinks( [
592 $this->assertEquals( [ 0 => 'Test', '1' => 'Test2' ], $outputPage->getCategories() );
593 $this->assertEquals( [ 0 => 'Test2' ], $outputPage->getCategories( 'normal' ) );
594 $this->assertEquals( [ 0 => 'Test' ], $outputPage->getCategories( 'hidden' ) );
598 * @dataProvider provideLinkHeaders
599 * @covers OutputPage::addLinkHeader
600 * @covers OutputPage::getLinkHeader
602 public function testLinkHeaders( $headers, $result ) {
603 $outputPage = $this->newInstance();
605 foreach ( $headers as $header ) {
606 $outputPage->addLinkHeader( $header );
609 $this->assertEquals( $result, $outputPage->getLinkHeader() );
612 public function provideLinkHeaders() {
619 [ '<https://foo/bar.jpg>;rel=preload;as=image' ],
620 'Link: <https://foo/bar.jpg>;rel=preload;as=image',
623 [ '<https://foo/bar.jpg>;rel=preload;as=image','<https://foo/baz.jpg>;rel=preload;as=image' ],
624 'Link: <https://foo/bar.jpg>;rel=preload;as=image,<https://foo/baz.jpg>;rel=preload;as=image',
630 * @dataProvider providePreloadLinkHeaders
631 * @covers OutputPage::addLogoPreloadLinkHeaders
632 * @covers ResourceLoaderSkinModule::getLogo
634 public function testPreloadLinkHeaders( $config, $result, $baseDir = null ) {
636 $this->setMwGlobals( 'IP', $baseDir );
638 $out = TestingAccessWrapper
::newFromObject( $this->newInstance( $config ) );
639 $out->addLogoPreloadLinkHeaders();
641 $this->assertEquals( $result, $out->getLinkHeader() );
644 public function providePreloadLinkHeaders() {
648 'ResourceBasePath' => '/w',
649 'Logo' => '/img/default.png',
651 '1.5x' => '/img/one-point-five.png',
652 '2x' => '/img/two-x.png',
655 'Link: </img/default.png>;rel=preload;as=image;media=' .
656 'not all and (min-resolution: 1.5dppx),' .
657 '</img/one-point-five.png>;rel=preload;as=image;media=' .
658 '(min-resolution: 1.5dppx) and (max-resolution: 1.999999dppx),' .
659 '</img/two-x.png>;rel=preload;as=image;media=(min-resolution: 2dppx)'
663 'ResourceBasePath' => '/w',
664 'Logo' => '/img/default.png',
667 'Link: </img/default.png>;rel=preload;as=image'
671 'ResourceBasePath' => '/w',
672 'Logo' => '/img/default.png',
674 '2x' => '/img/two-x.png',
677 'Link: </img/default.png>;rel=preload;as=image;media=' .
678 'not all and (min-resolution: 2dppx),' .
679 '</img/two-x.png>;rel=preload;as=image;media=(min-resolution: 2dppx)'
683 'ResourceBasePath' => '/w',
684 'Logo' => '/img/default.png',
686 'svg' => '/img/vector.svg',
689 'Link: </img/vector.svg>;rel=preload;as=image'
694 'ResourceBasePath' => '/w',
695 'Logo' => '/w/test.jpg',
697 'UploadPath' => '/w/images',
699 'Link: </w/test.jpg?edcf2>;rel=preload;as=image',
700 'baseDir' => dirname( __DIR__
) . '/data/media',
708 private function newInstance( $config = [] ) {
709 $context = new RequestContext();
711 $context->setConfig( new HashConfig( $config +
[
712 'AppleTouchIcon' => false,
713 'DisableLangConversion' => true,
714 'EnableCanonicalServerLink' => false,
717 'LanguageCode' => false,
718 'ReferrerPolicy' => false,
719 'RightsPage' => false,
720 'RightsUrl' => false,
721 'UniversalEditButton' => false,
724 return new OutputPage( $context );
729 * MessageBlobStore that doesn't do anything
731 class NullMessageBlobStore
extends MessageBlobStore
{
732 public function get( ResourceLoader
$resourceLoader, $modules, $lang ) {
736 public function updateModule( $name, ResourceLoaderModule
$module, $lang ) {
739 public function updateMessage( $key ) {
742 public function clear() {