Preload the logo using link rel="preload" http header
[lhc/web/wiklou.git] / tests / phpunit / includes / OutputPageTest.php
1 <?php
2
3 /**
4 *
5 * @author Matthew Flaschen
6 *
7 * @group Database
8 * @group Output
9 *
10 * @todo factor tests in this class into providers and test methods
11 */
12 class OutputPageTest extends MediaWikiTestCase {
13 const SCREEN_MEDIA_QUERY = 'screen and (min-width: 982px)';
14 const SCREEN_ONLY_MEDIA_QUERY = 'only screen and (min-width: 982px)';
15
16 /**
17 * @covers OutputPage::addMeta
18 * @covers OutputPage::getMetaTags
19 * @covers OutputPage::getHeadLinksArray
20 */
21 public function testMetaTags() {
22 $outputPage = $this->newInstance();
23 $outputPage->addMeta( 'http:expires', '0' );
24 $outputPage->addMeta( 'keywords', 'first' );
25 $outputPage->addMeta( 'keywords', 'second' );
26 $outputPage->addMeta( 'og:title', 'Ta-duh' );
27
28 $expected = [
29 [ 'http:expires', '0' ],
30 [ 'keywords', 'first' ],
31 [ 'keywords', 'second' ],
32 [ 'og:title', 'Ta-duh' ],
33 ];
34 $this->assertSame( $expected, $outputPage->getMetaTags() );
35
36 $links = $outputPage->getHeadLinksArray();
37 $this->assertContains( '<meta http-equiv="expires" content="0"/>', $links );
38 $this->assertContains( '<meta name="keywords" content="first"/>', $links );
39 $this->assertContains( '<meta name="keywords" content="second"/>', $links );
40 $this->assertContains( '<meta property="og:title" content="Ta-duh"/>', $links );
41 $this->assertArrayNotHasKey( 'meta-robots', $links );
42 }
43
44 /**
45 * @covers OutputPage::setIndexPolicy
46 * @covers OutputPage::setFollowPolicy
47 * @covers OutputPage::getHeadLinksArray
48 */
49 public function testRobotsPolicies() {
50 $outputPage = $this->newInstance();
51 $outputPage->setIndexPolicy( 'noindex' );
52 $outputPage->setFollowPolicy( 'nofollow' );
53
54 $links = $outputPage->getHeadLinksArray();
55 $this->assertContains( '<meta name="robots" content="noindex,nofollow"/>', $links );
56 }
57
58 /**
59 * Tests a particular case of transformCssMedia, using the given input, globals,
60 * expected return, and message
61 *
62 * Asserts that $expectedReturn is returned.
63 *
64 * options['printableQuery'] - value of query string for printable, or omitted for none
65 * options['handheldQuery'] - value of query string for handheld, or omitted for none
66 * options['media'] - passed into the method under the same name
67 * options['expectedReturn'] - expected return value
68 * options['message'] - PHPUnit message for assertion
69 *
70 * @param array $args Key-value array of arguments as shown above
71 */
72 protected function assertTransformCssMediaCase( $args ) {
73 $queryData = [];
74 if ( isset( $args['printableQuery'] ) ) {
75 $queryData['printable'] = $args['printableQuery'];
76 }
77
78 if ( isset( $args['handheldQuery'] ) ) {
79 $queryData['handheld'] = $args['handheldQuery'];
80 }
81
82 $fauxRequest = new FauxRequest( $queryData, false );
83 $this->setMwGlobals( [
84 'wgRequest' => $fauxRequest,
85 ] );
86
87 $actualReturn = OutputPage::transformCssMedia( $args['media'] );
88 $this->assertSame( $args['expectedReturn'], $actualReturn, $args['message'] );
89 }
90
91 /**
92 * Tests print requests
93 * @covers OutputPage::transformCssMedia
94 */
95 public function testPrintRequests() {
96 $this->assertTransformCssMediaCase( [
97 'printableQuery' => '1',
98 'media' => 'screen',
99 'expectedReturn' => null,
100 'message' => 'On printable request, screen returns null'
101 ] );
102
103 $this->assertTransformCssMediaCase( [
104 'printableQuery' => '1',
105 'media' => self::SCREEN_MEDIA_QUERY,
106 'expectedReturn' => null,
107 'message' => 'On printable request, screen media query returns null'
108 ] );
109
110 $this->assertTransformCssMediaCase( [
111 'printableQuery' => '1',
112 'media' => self::SCREEN_ONLY_MEDIA_QUERY,
113 'expectedReturn' => null,
114 'message' => 'On printable request, screen media query with only returns null'
115 ] );
116
117 $this->assertTransformCssMediaCase( [
118 'printableQuery' => '1',
119 'media' => 'print',
120 'expectedReturn' => '',
121 'message' => 'On printable request, media print returns empty string'
122 ] );
123 }
124
125 /**
126 * Tests screen requests, without either query parameter set
127 * @covers OutputPage::transformCssMedia
128 */
129 public function testScreenRequests() {
130 $this->assertTransformCssMediaCase( [
131 'media' => 'screen',
132 'expectedReturn' => 'screen',
133 'message' => 'On screen request, screen media type is preserved'
134 ] );
135
136 $this->assertTransformCssMediaCase( [
137 'media' => 'handheld',
138 'expectedReturn' => 'handheld',
139 'message' => 'On screen request, handheld media type is preserved'
140 ] );
141
142 $this->assertTransformCssMediaCase( [
143 'media' => self::SCREEN_MEDIA_QUERY,
144 'expectedReturn' => self::SCREEN_MEDIA_QUERY,
145 'message' => 'On screen request, screen media query is preserved.'
146 ] );
147
148 $this->assertTransformCssMediaCase( [
149 'media' => self::SCREEN_ONLY_MEDIA_QUERY,
150 'expectedReturn' => self::SCREEN_ONLY_MEDIA_QUERY,
151 'message' => 'On screen request, screen media query with only is preserved.'
152 ] );
153
154 $this->assertTransformCssMediaCase( [
155 'media' => 'print',
156 'expectedReturn' => 'print',
157 'message' => 'On screen request, print media type is preserved'
158 ] );
159 }
160
161 /**
162 * Tests handheld behavior
163 * @covers OutputPage::transformCssMedia
164 */
165 public function testHandheld() {
166 $this->assertTransformCssMediaCase( [
167 'handheldQuery' => '1',
168 'media' => 'handheld',
169 'expectedReturn' => '',
170 'message' => 'On request with handheld querystring and media is handheld, returns empty string'
171 ] );
172
173 $this->assertTransformCssMediaCase( [
174 'handheldQuery' => '1',
175 'media' => 'screen',
176 'expectedReturn' => null,
177 'message' => 'On request with handheld querystring and media is screen, returns null'
178 ] );
179 }
180
181 public static function provideTransformFilePath() {
182 $baseDir = dirname( __DIR__ ) . '/data/media';
183 return [
184 // File that matches basePath, and exists. Hash found and appended.
185 [
186 'baseDir' => $baseDir, 'basePath' => '/w',
187 '/w/test.jpg',
188 '/w/test.jpg?edcf2'
189 ],
190 // File that matches basePath, but not found on disk. Empty query.
191 [
192 'baseDir' => $baseDir, 'basePath' => '/w',
193 '/w/unknown.png',
194 '/w/unknown.png?'
195 ],
196 // File not matching basePath. Ignored.
197 [
198 'baseDir' => $baseDir, 'basePath' => '/w',
199 '/files/test.jpg'
200 ],
201 // Empty string. Ignored.
202 [
203 'baseDir' => $baseDir, 'basePath' => '/w',
204 '',
205 ''
206 ],
207 // Similar path, but with domain component. Ignored.
208 [
209 'baseDir' => $baseDir, 'basePath' => '/w',
210 '//example.org/w/test.jpg'
211 ],
212 [
213 'baseDir' => $baseDir, 'basePath' => '/w',
214 'https://example.org/w/test.jpg'
215 ],
216 // Unrelated path with domain component. Ignored.
217 [
218 'baseDir' => $baseDir, 'basePath' => '/w',
219 'https://example.org/files/test.jpg'
220 ],
221 [
222 'baseDir' => $baseDir, 'basePath' => '/w',
223 '//example.org/files/test.jpg'
224 ],
225 // Unrelated path with domain, and empty base path (root mw install). Ignored.
226 [
227 'baseDir' => $baseDir, 'basePath' => '',
228 'https://example.org/files/test.jpg'
229 ],
230 [
231 'baseDir' => $baseDir, 'basePath' => '',
232 // T155310
233 '//example.org/files/test.jpg'
234 ],
235 // Check UploadPath before ResourceBasePath (T155146)
236 [
237 'baseDir' => dirname( $baseDir ), 'basePath' => '',
238 'uploadDir' => $baseDir, 'uploadPath' => '/images',
239 '/images/test.jpg',
240 '/images/test.jpg?edcf2'
241 ],
242 ];
243 }
244
245 /**
246 * @dataProvider provideTransformFilePath
247 * @covers OutputPage::transformFilePath
248 * @covers OutputPage::transformResourcePath
249 */
250 public function testTransformResourcePath( $baseDir, $basePath, $uploadDir = null,
251 $uploadPath = null, $path = null, $expected = null
252 ) {
253 if ( $path === null ) {
254 // Skip optional $uploadDir and $uploadPath
255 $path = $uploadDir;
256 $expected = $uploadPath;
257 $uploadDir = "$baseDir/images";
258 $uploadPath = "$basePath/images";
259 }
260 $this->setMwGlobals( 'IP', $baseDir );
261 $conf = new HashConfig( [
262 'ResourceBasePath' => $basePath,
263 'UploadDirectory' => $uploadDir,
264 'UploadPath' => $uploadPath,
265 ] );
266
267 MediaWiki\suppressWarnings();
268 $actual = OutputPage::transformResourcePath( $conf, $path );
269 MediaWiki\restoreWarnings();
270
271 $this->assertEquals( $expected ?: $path, $actual );
272 }
273
274 public static function provideMakeResourceLoaderLink() {
275 // @codingStandardsIgnoreStart Generic.Files.LineLength
276 return [
277 // Single only=scripts load
278 [
279 [ 'test.foo', ResourceLoaderModule::TYPE_SCRIPTS ],
280 "<script>(window.RLQ=window.RLQ||[]).push(function(){"
281 . 'mw.loader.load("http://127.0.0.1:8080/w/load.php?debug=false\u0026lang=en\u0026modules=test.foo\u0026only=scripts\u0026skin=fallback");'
282 . "});</script>"
283 ],
284 // Multiple only=styles load
285 [
286 [ [ 'test.baz', 'test.foo', 'test.bar' ], ResourceLoaderModule::TYPE_STYLES ],
287
288 '<link rel="stylesheet" href="http://127.0.0.1:8080/w/load.php?debug=false&amp;lang=en&amp;modules=test.bar%2Cbaz%2Cfoo&amp;only=styles&amp;skin=fallback"/>'
289 ],
290 // Private embed (only=scripts)
291 [
292 [ 'test.quux', ResourceLoaderModule::TYPE_SCRIPTS ],
293 "<script>(window.RLQ=window.RLQ||[]).push(function(){"
294 . "mw.test.baz({token:123});mw.loader.state({\"test.quux\":\"ready\"});"
295 . "});</script>"
296 ],
297 ];
298 // @codingStandardsIgnoreEnd
299 }
300
301 /**
302 * See ResourceLoaderClientHtmlTest for full coverage.
303 *
304 * @dataProvider provideMakeResourceLoaderLink
305 * @covers OutputPage::makeResourceLoaderLink
306 */
307 public function testMakeResourceLoaderLink( $args, $expectedHtml ) {
308 $this->setMwGlobals( [
309 'wgResourceLoaderDebug' => false,
310 'wgLoadScript' => 'http://127.0.0.1:8080/w/load.php',
311 ] );
312 $class = new ReflectionClass( 'OutputPage' );
313 $method = $class->getMethod( 'makeResourceLoaderLink' );
314 $method->setAccessible( true );
315 $ctx = new RequestContext();
316 $ctx->setSkin( SkinFactory::getDefaultInstance()->makeSkin( 'fallback' ) );
317 $ctx->setLanguage( 'en' );
318 $out = new OutputPage( $ctx );
319 $rl = $out->getResourceLoader();
320 $rl->setMessageBlobStore( new NullMessageBlobStore() );
321 $rl->register( [
322 'test.foo' => new ResourceLoaderTestModule( [
323 'script' => 'mw.test.foo( { a: true } );',
324 'styles' => '.mw-test-foo { content: "style"; }',
325 ] ),
326 'test.bar' => new ResourceLoaderTestModule( [
327 'script' => 'mw.test.bar( { a: true } );',
328 'styles' => '.mw-test-bar { content: "style"; }',
329 ] ),
330 'test.baz' => new ResourceLoaderTestModule( [
331 'script' => 'mw.test.baz( { a: true } );',
332 'styles' => '.mw-test-baz { content: "style"; }',
333 ] ),
334 'test.quux' => new ResourceLoaderTestModule( [
335 'script' => 'mw.test.baz( { token: 123 } );',
336 'styles' => '/* pref-animate=off */ .mw-icon { transition: none; }',
337 'group' => 'private',
338 ] ),
339 ] );
340 $links = $method->invokeArgs( $out, $args );
341 $actualHtml = strval( $links );
342 $this->assertEquals( $expectedHtml, $actualHtml );
343 }
344
345 /**
346 * @dataProvider provideVaryHeaders
347 * @covers OutputPage::addVaryHeader
348 * @covers OutputPage::getVaryHeader
349 * @covers OutputPage::getKeyHeader
350 */
351 public function testVaryHeaders( $calls, $vary, $key ) {
352 // get rid of default Vary fields
353 $outputPage = $this->getMockBuilder( 'OutputPage' )
354 ->setConstructorArgs( [ new RequestContext() ] )
355 ->setMethods( [ 'getCacheVaryCookies' ] )
356 ->getMock();
357 $outputPage->expects( $this->any() )
358 ->method( 'getCacheVaryCookies' )
359 ->will( $this->returnValue( [] ) );
360 TestingAccessWrapper::newFromObject( $outputPage )->mVaryHeader = [];
361
362 foreach ( $calls as $call ) {
363 call_user_func_array( [ $outputPage, 'addVaryHeader' ], $call );
364 }
365 $this->assertEquals( $vary, $outputPage->getVaryHeader(), 'Vary:' );
366 $this->assertEquals( $key, $outputPage->getKeyHeader(), 'Key:' );
367 }
368
369 public function provideVaryHeaders() {
370 // note: getKeyHeader() automatically adds Vary: Cookie
371 return [
372 [ // single header
373 [
374 [ 'Cookie' ],
375 ],
376 'Vary: Cookie',
377 'Key: Cookie',
378 ],
379 [ // non-unique headers
380 [
381 [ 'Cookie' ],
382 [ 'Accept-Language' ],
383 [ 'Cookie' ],
384 ],
385 'Vary: Cookie, Accept-Language',
386 'Key: Cookie,Accept-Language',
387 ],
388 [ // two headers with single options
389 [
390 [ 'Cookie', [ 'param=phpsessid' ] ],
391 [ 'Accept-Language', [ 'substr=en' ] ],
392 ],
393 'Vary: Cookie, Accept-Language',
394 'Key: Cookie;param=phpsessid,Accept-Language;substr=en',
395 ],
396 [ // one header with multiple options
397 [
398 [ 'Cookie', [ 'param=phpsessid', 'param=userId' ] ],
399 ],
400 'Vary: Cookie',
401 'Key: Cookie;param=phpsessid;param=userId',
402 ],
403 [ // Duplicate option
404 [
405 [ 'Cookie', [ 'param=phpsessid' ] ],
406 [ 'Cookie', [ 'param=phpsessid' ] ],
407 [ 'Accept-Language', [ 'substr=en', 'substr=en' ] ],
408 ],
409 'Vary: Cookie, Accept-Language',
410 'Key: Cookie;param=phpsessid,Accept-Language;substr=en',
411 ],
412 [ // Same header, different options
413 [
414 [ 'Cookie', [ 'param=phpsessid' ] ],
415 [ 'Cookie', [ 'param=userId' ] ],
416 ],
417 'Vary: Cookie',
418 'Key: Cookie;param=phpsessid;param=userId',
419 ],
420 ];
421 }
422
423 /**
424 * @covers OutputPage::haveCacheVaryCookies
425 */
426 public function testHaveCacheVaryCookies() {
427 $request = new FauxRequest();
428 $context = new RequestContext();
429 $context->setRequest( $request );
430 $outputPage = new OutputPage( $context );
431
432 // No cookies are set.
433 $this->assertFalse( $outputPage->haveCacheVaryCookies() );
434
435 // 'Token' is present but empty, so it shouldn't count.
436 $request->setCookie( 'Token', '' );
437 $this->assertFalse( $outputPage->haveCacheVaryCookies() );
438
439 // 'Token' present and nonempty.
440 $request->setCookie( 'Token', '123' );
441 $this->assertTrue( $outputPage->haveCacheVaryCookies() );
442 }
443
444 /*
445 * @covers OutputPage::addCategoryLinks
446 * @covers OutputPage::getCategories
447 */
448 public function testGetCategories() {
449 $fakeResultWrapper = new FakeResultWrapper( [
450 (object) [
451 'pp_value' => 1,
452 'page_title' => 'Test'
453 ],
454 (object) [
455 'page_title' => 'Test2'
456 ]
457 ] );
458 $outputPage = $this->getMockBuilder( 'OutputPage' )
459 ->setConstructorArgs( [ new RequestContext() ] )
460 ->setMethods( [ 'addCategoryLinksToLBAndGetResult' ] )
461 ->getMock();
462 $outputPage->expects( $this->any() )
463 ->method( 'addCategoryLinksToLBAndGetResult' )
464 ->will( $this->returnValue( $fakeResultWrapper ) );
465
466 $outputPage->addCategoryLinks( [
467 'Test' => 'Test',
468 'Test2' => 'Test2',
469 ] );
470 $this->assertEquals( [ 0 => 'Test', '1' => 'Test2' ], $outputPage->getCategories() );
471 $this->assertEquals( [ 0 => 'Test2' ], $outputPage->getCategories( 'normal' ) );
472 $this->assertEquals( [ 0 => 'Test' ], $outputPage->getCategories( 'hidden' ) );
473 }
474
475 /**
476 * @dataProvider provideLinkHeaders
477 * @covers OutputPage::addLinkHeader
478 * @covers OutputPage::getLinkHeader
479 */
480 public function testLinkHeaders( $headers, $result ) {
481 $outputPage = $this->newInstance();
482
483 foreach ( $headers as $header ) {
484 $outputPage->addLinkHeader( $header );
485 }
486
487 $this->assertEquals( $result, $outputPage->getLinkHeader() );
488 }
489
490 public function provideLinkHeaders() {
491 return [
492 [
493 [],
494 false
495 ],
496 [
497 [ '<https://foo/bar.jpg>;rel=preload;as=image' ],
498 'Link: <https://foo/bar.jpg>;rel=preload;as=image',
499 ],
500 [
501 [ '<https://foo/bar.jpg>;rel=preload;as=image','<https://foo/baz.jpg>;rel=preload;as=image' ],
502 'Link: <https://foo/bar.jpg>;rel=preload;as=image,<https://foo/baz.jpg>;rel=preload;as=image',
503 ],
504 ];
505 }
506
507 /**
508 * @dataProvider providePreloadLinkHeaders
509 * @covers OutputPage::addLogoPreloadLinkHeaders
510 */
511 public function testPreloadLinkHeaders( $config, $result ) {
512 $out = TestingAccessWrapper::newFromObject( $this->newInstance( $config ) );
513 $out->addLogoPreloadLinkHeaders();
514
515 $this->assertEquals( $result, $out->getLinkHeader() );
516 }
517
518 public function providePreloadLinkHeaders() {
519 return [
520 [
521 [
522 'Logo' => '/img/default.png',
523 'LogoHD' => [
524 '1.5x' => '/img/one-point-five.png',
525 '2x' => '/img/two-x.png',
526 ],
527 ],
528 'Link: </img/default.png>;rel=preload;as=image;media=' .
529 'not all and (min-resolution: 1.5dppx),' .
530 '</img/one-point-five.png>;rel=preload;as=image;media=' .
531 '(min-resolution: 1.5dppx) and (max-resolution: 1.999999dppx),' .
532 '</img/two-x.png>;rel=preload;as=image;media=(min-resolution: 2dppx)'
533 ],
534 [
535 [
536 'Logo' => '/img/default.png',
537 'LogoHD' => false,
538 ],
539 'Link: </img/default.png>;rel=preload;as=image'
540 ],
541 [
542 [
543 'Logo' => '/img/default.png',
544 'LogoHD' => [
545 '2x' => '/img/two-x.png',
546 ],
547 ],
548 'Link: </img/default.png>;rel=preload;as=image;media=' .
549 'not all and (min-resolution: 2dppx),' .
550 '</img/two-x.png>;rel=preload;as=image;media=(min-resolution: 2dppx)'
551 ],
552 ];
553 }
554
555 /**
556 * @return OutputPage
557 */
558 private function newInstance( $config = [] ) {
559 $context = new RequestContext();
560
561 $context->setConfig( new HashConfig( $config + [
562 'AppleTouchIcon' => false,
563 'DisableLangConversion' => true,
564 'EnableAPI' => false,
565 'EnableCanonicalServerLink' => false,
566 'Favicon' => false,
567 'Feed' => false,
568 'LanguageCode' => false,
569 'ReferrerPolicy' => false,
570 'RightsPage' => false,
571 'RightsUrl' => false,
572 'UniversalEditButton' => false,
573 ] ) );
574
575 return new OutputPage( $context );
576 }
577 }
578
579 /**
580 * MessageBlobStore that doesn't do anything
581 */
582 class NullMessageBlobStore extends MessageBlobStore {
583 public function get( ResourceLoader $resourceLoader, $modules, $lang ) {
584 return [];
585 }
586
587 public function insertMessageBlob( $name, ResourceLoaderModule $module, $lang ) {
588 return false;
589 }
590
591 public function updateModule( $name, ResourceLoaderModule $module, $lang ) {
592 }
593
594 public function updateMessage( $key ) {
595 }
596
597 public function clear() {
598 }
599 }