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'
128 * Tests screen requests, without either query parameter set
129 * @covers OutputPage::transformCssMedia
131 public function testScreenRequests() {
132 $this->assertTransformCssMediaCase( [
134 'expectedReturn' => 'screen',
135 'message' => 'On screen request, screen media type is preserved'
138 $this->assertTransformCssMediaCase( [
139 'media' => 'handheld',
140 'expectedReturn' => 'handheld',
141 'message' => 'On screen request, handheld media type is preserved'
144 $this->assertTransformCssMediaCase( [
145 'media' => self
::SCREEN_MEDIA_QUERY
,
146 'expectedReturn' => self
::SCREEN_MEDIA_QUERY
,
147 'message' => 'On screen request, screen media query is preserved.'
150 $this->assertTransformCssMediaCase( [
151 'media' => self
::SCREEN_ONLY_MEDIA_QUERY
,
152 'expectedReturn' => self
::SCREEN_ONLY_MEDIA_QUERY
,
153 'message' => 'On screen request, screen media query with only is preserved.'
156 $this->assertTransformCssMediaCase( [
158 'expectedReturn' => 'print',
159 'message' => 'On screen request, print media type is preserved'
164 * Tests handheld behavior
165 * @covers OutputPage::transformCssMedia
167 public function testHandheld() {
168 $this->assertTransformCssMediaCase( [
169 'handheldQuery' => '1',
170 'media' => 'handheld',
171 'expectedReturn' => '',
172 'message' => 'On request with handheld querystring and media is handheld, returns empty string'
175 $this->assertTransformCssMediaCase( [
176 'handheldQuery' => '1',
178 'expectedReturn' => null,
179 'message' => 'On request with handheld querystring and media is screen, returns null'
183 public static function provideTransformFilePath() {
184 $baseDir = dirname( __DIR__
) . '/data/media';
186 // File that matches basePath, and exists. Hash found and appended.
188 'baseDir' => $baseDir, 'basePath' => '/w',
192 // File that matches basePath, but not found on disk. Empty query.
194 'baseDir' => $baseDir, 'basePath' => '/w',
198 // File not matching basePath. Ignored.
200 'baseDir' => $baseDir, 'basePath' => '/w',
203 // Empty string. Ignored.
205 'baseDir' => $baseDir, 'basePath' => '/w',
209 // Similar path, but with domain component. Ignored.
211 'baseDir' => $baseDir, 'basePath' => '/w',
212 '//example.org/w/test.jpg'
215 'baseDir' => $baseDir, 'basePath' => '/w',
216 'https://example.org/w/test.jpg'
218 // Unrelated path with domain component. Ignored.
220 'baseDir' => $baseDir, 'basePath' => '/w',
221 'https://example.org/files/test.jpg'
224 'baseDir' => $baseDir, 'basePath' => '/w',
225 '//example.org/files/test.jpg'
227 // Unrelated path with domain, and empty base path (root mw install). Ignored.
229 'baseDir' => $baseDir, 'basePath' => '',
230 'https://example.org/files/test.jpg'
233 'baseDir' => $baseDir, 'basePath' => '',
235 '//example.org/files/test.jpg'
237 // Check UploadPath before ResourceBasePath (T155146)
239 'baseDir' => dirname( $baseDir ), 'basePath' => '',
240 'uploadDir' => $baseDir, 'uploadPath' => '/images',
242 '/images/test.jpg?edcf2'
248 * @dataProvider provideTransformFilePath
249 * @covers OutputPage::transformFilePath
250 * @covers OutputPage::transformResourcePath
252 public function testTransformResourcePath( $baseDir, $basePath, $uploadDir = null,
253 $uploadPath = null, $path = null, $expected = null
255 if ( $path === null ) {
256 // Skip optional $uploadDir and $uploadPath
258 $expected = $uploadPath;
259 $uploadDir = "$baseDir/images";
260 $uploadPath = "$basePath/images";
262 $this->setMwGlobals( 'IP', $baseDir );
263 $conf = new HashConfig( [
264 'ResourceBasePath' => $basePath,
265 'UploadDirectory' => $uploadDir,
266 'UploadPath' => $uploadPath,
269 MediaWiki\
suppressWarnings();
270 $actual = OutputPage
::transformResourcePath( $conf, $path );
271 MediaWiki\restoreWarnings
();
273 $this->assertEquals( $expected ?
: $path, $actual );
276 public static function provideMakeResourceLoaderLink() {
277 // @codingStandardsIgnoreStart Generic.Files.LineLength
279 // Single only=scripts load
281 [ 'test.foo', ResourceLoaderModule
::TYPE_SCRIPTS
],
282 "<script>(window.RLQ=window.RLQ||[]).push(function(){"
283 . 'mw.loader.load("http://127.0.0.1:8080/w/load.php?debug=false\u0026lang=en\u0026modules=test.foo\u0026only=scripts\u0026skin=fallback");'
286 // Multiple only=styles load
288 [ [ 'test.baz', 'test.foo', 'test.bar' ], ResourceLoaderModule
::TYPE_STYLES
],
290 '<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"/>'
292 // Private embed (only=scripts)
294 [ 'test.quux', ResourceLoaderModule
::TYPE_SCRIPTS
],
295 "<script>(window.RLQ=window.RLQ||[]).push(function(){"
296 . "mw.test.baz({token:123});mw.loader.state({\"test.quux\":\"ready\"});"
300 // @codingStandardsIgnoreEnd
304 * See ResourceLoaderClientHtmlTest for full coverage.
306 * @dataProvider provideMakeResourceLoaderLink
307 * @covers OutputPage::makeResourceLoaderLink
309 public function testMakeResourceLoaderLink( $args, $expectedHtml ) {
310 $this->setMwGlobals( [
311 'wgResourceLoaderDebug' => false,
312 'wgLoadScript' => 'http://127.0.0.1:8080/w/load.php',
314 $class = new ReflectionClass( 'OutputPage' );
315 $method = $class->getMethod( 'makeResourceLoaderLink' );
316 $method->setAccessible( true );
317 $ctx = new RequestContext();
318 $ctx->setSkin( SkinFactory
::getDefaultInstance()->makeSkin( 'fallback' ) );
319 $ctx->setLanguage( 'en' );
320 $out = new OutputPage( $ctx );
321 $rl = $out->getResourceLoader();
322 $rl->setMessageBlobStore( new NullMessageBlobStore() );
324 'test.foo' => new ResourceLoaderTestModule( [
325 'script' => 'mw.test.foo( { a: true } );',
326 'styles' => '.mw-test-foo { content: "style"; }',
328 'test.bar' => new ResourceLoaderTestModule( [
329 'script' => 'mw.test.bar( { a: true } );',
330 'styles' => '.mw-test-bar { content: "style"; }',
332 'test.baz' => new ResourceLoaderTestModule( [
333 'script' => 'mw.test.baz( { a: true } );',
334 'styles' => '.mw-test-baz { content: "style"; }',
336 'test.quux' => new ResourceLoaderTestModule( [
337 'script' => 'mw.test.baz( { token: 123 } );',
338 'styles' => '/* pref-animate=off */ .mw-icon { transition: none; }',
339 'group' => 'private',
342 $links = $method->invokeArgs( $out, $args );
343 $actualHtml = strval( $links );
344 $this->assertEquals( $expectedHtml, $actualHtml );
348 * @dataProvider provideVaryHeaders
349 * @covers OutputPage::addVaryHeader
350 * @covers OutputPage::getVaryHeader
351 * @covers OutputPage::getKeyHeader
353 public function testVaryHeaders( $calls, $vary, $key ) {
354 // get rid of default Vary fields
355 $outputPage = $this->getMockBuilder( 'OutputPage' )
356 ->setConstructorArgs( [ new RequestContext() ] )
357 ->setMethods( [ 'getCacheVaryCookies' ] )
359 $outputPage->expects( $this->any() )
360 ->method( 'getCacheVaryCookies' )
361 ->will( $this->returnValue( [] ) );
362 TestingAccessWrapper
::newFromObject( $outputPage )->mVaryHeader
= [];
364 foreach ( $calls as $call ) {
365 call_user_func_array( [ $outputPage, 'addVaryHeader' ], $call );
367 $this->assertEquals( $vary, $outputPage->getVaryHeader(), 'Vary:' );
368 $this->assertEquals( $key, $outputPage->getKeyHeader(), 'Key:' );
371 public function provideVaryHeaders() {
372 // note: getKeyHeader() automatically adds Vary: Cookie
381 [ // non-unique headers
384 [ 'Accept-Language' ],
387 'Vary: Cookie, Accept-Language',
388 'Key: Cookie,Accept-Language',
390 [ // two headers with single options
392 [ 'Cookie', [ 'param=phpsessid' ] ],
393 [ 'Accept-Language', [ 'substr=en' ] ],
395 'Vary: Cookie, Accept-Language',
396 'Key: Cookie;param=phpsessid,Accept-Language;substr=en',
398 [ // one header with multiple options
400 [ 'Cookie', [ 'param=phpsessid', 'param=userId' ] ],
403 'Key: Cookie;param=phpsessid;param=userId',
405 [ // Duplicate option
407 [ 'Cookie', [ 'param=phpsessid' ] ],
408 [ 'Cookie', [ 'param=phpsessid' ] ],
409 [ 'Accept-Language', [ 'substr=en', 'substr=en' ] ],
411 'Vary: Cookie, Accept-Language',
412 'Key: Cookie;param=phpsessid,Accept-Language;substr=en',
414 [ // Same header, different options
416 [ 'Cookie', [ 'param=phpsessid' ] ],
417 [ 'Cookie', [ 'param=userId' ] ],
420 'Key: Cookie;param=phpsessid;param=userId',
426 * @covers OutputPage::haveCacheVaryCookies
428 public function testHaveCacheVaryCookies() {
429 $request = new FauxRequest();
430 $context = new RequestContext();
431 $context->setRequest( $request );
432 $outputPage = new OutputPage( $context );
434 // No cookies are set.
435 $this->assertFalse( $outputPage->haveCacheVaryCookies() );
437 // 'Token' is present but empty, so it shouldn't count.
438 $request->setCookie( 'Token', '' );
439 $this->assertFalse( $outputPage->haveCacheVaryCookies() );
441 // 'Token' present and nonempty.
442 $request->setCookie( 'Token', '123' );
443 $this->assertTrue( $outputPage->haveCacheVaryCookies() );
447 * @covers OutputPage::addCategoryLinks
448 * @covers OutputPage::getCategories
450 public function testGetCategories() {
451 $fakeResultWrapper = new FakeResultWrapper( [
454 'page_title' => 'Test'
457 'page_title' => 'Test2'
460 $outputPage = $this->getMockBuilder( 'OutputPage' )
461 ->setConstructorArgs( [ new RequestContext() ] )
462 ->setMethods( [ 'addCategoryLinksToLBAndGetResult' ] )
464 $outputPage->expects( $this->any() )
465 ->method( 'addCategoryLinksToLBAndGetResult' )
466 ->will( $this->returnValue( $fakeResultWrapper ) );
468 $outputPage->addCategoryLinks( [
472 $this->assertEquals( [ 0 => 'Test', '1' => 'Test2' ], $outputPage->getCategories() );
473 $this->assertEquals( [ 0 => 'Test2' ], $outputPage->getCategories( 'normal' ) );
474 $this->assertEquals( [ 0 => 'Test' ], $outputPage->getCategories( 'hidden' ) );
478 * @dataProvider provideLinkHeaders
479 * @covers OutputPage::addLinkHeader
480 * @covers OutputPage::getLinkHeader
482 public function testLinkHeaders( $headers, $result ) {
483 $outputPage = $this->newInstance();
485 foreach ( $headers as $header ) {
486 $outputPage->addLinkHeader( $header );
489 $this->assertEquals( $result, $outputPage->getLinkHeader() );
492 public function provideLinkHeaders() {
499 [ '<https://foo/bar.jpg>;rel=preload;as=image' ],
500 'Link: <https://foo/bar.jpg>;rel=preload;as=image',
503 [ '<https://foo/bar.jpg>;rel=preload;as=image','<https://foo/baz.jpg>;rel=preload;as=image' ],
504 'Link: <https://foo/bar.jpg>;rel=preload;as=image,<https://foo/baz.jpg>;rel=preload;as=image',
510 * @dataProvider providePreloadLinkHeaders
511 * @covers OutputPage::addLogoPreloadLinkHeaders
512 * @covers ResourceLoaderSkinModule::getLogo
514 public function testPreloadLinkHeaders( $config, $result, $baseDir = null ) {
516 $this->setMwGlobals( 'IP', $baseDir );
518 $out = TestingAccessWrapper
::newFromObject( $this->newInstance( $config ) );
519 $out->addLogoPreloadLinkHeaders();
521 $this->assertEquals( $result, $out->getLinkHeader() );
524 public function providePreloadLinkHeaders() {
528 'ResourceBasePath' => '/w',
529 'Logo' => '/img/default.png',
531 '1.5x' => '/img/one-point-five.png',
532 '2x' => '/img/two-x.png',
535 'Link: </img/default.png>;rel=preload;as=image;media=' .
536 'not all and (min-resolution: 1.5dppx),' .
537 '</img/one-point-five.png>;rel=preload;as=image;media=' .
538 '(min-resolution: 1.5dppx) and (max-resolution: 1.999999dppx),' .
539 '</img/two-x.png>;rel=preload;as=image;media=(min-resolution: 2dppx)'
543 'ResourceBasePath' => '/w',
544 'Logo' => '/img/default.png',
547 'Link: </img/default.png>;rel=preload;as=image'
551 'ResourceBasePath' => '/w',
552 'Logo' => '/img/default.png',
554 '2x' => '/img/two-x.png',
557 'Link: </img/default.png>;rel=preload;as=image;media=' .
558 'not all and (min-resolution: 2dppx),' .
559 '</img/two-x.png>;rel=preload;as=image;media=(min-resolution: 2dppx)'
563 'ResourceBasePath' => '/w',
564 'Logo' => '/w/test.jpg',
566 'UploadPath' => '/w/images',
568 'Link: </w/test.jpg?edcf2>;rel=preload;as=image',
569 'baseDir' => dirname( __DIR__
) . '/data/media',
577 private function newInstance( $config = [] ) {
578 $context = new RequestContext();
580 $context->setConfig( new HashConfig( $config +
[
581 'AppleTouchIcon' => false,
582 'DisableLangConversion' => true,
583 'EnableAPI' => false,
584 'EnableCanonicalServerLink' => false,
587 'LanguageCode' => false,
588 'ReferrerPolicy' => false,
589 'RightsPage' => false,
590 'RightsUrl' => false,
591 'UniversalEditButton' => false,
594 return new OutputPage( $context );
599 * MessageBlobStore that doesn't do anything
601 class NullMessageBlobStore
extends MessageBlobStore
{
602 public function get( ResourceLoader
$resourceLoader, $modules, $lang ) {
606 public function insertMessageBlob( $name, ResourceLoaderModule
$module, $lang ) {
610 public function updateModule( $name, ResourceLoaderModule
$module, $lang ) {
613 public function updateMessage( $key ) {
616 public function clear() {