ApiMain: Always create a new printer in getPrinterByName()
[lhc/web/wiklou.git] / tests / phpunit / includes / OutputPageTest.php
1 <?php
2
3 use Wikimedia\TestingAccessWrapper;
4
5 /**
6 *
7 * @author Matthew Flaschen
8 *
9 * @group Database
10 * @group Output
11 *
12 * @todo factor tests in this class into providers and test methods
13 */
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)';
17
18 /**
19 * @covers OutputPage::addMeta
20 * @covers OutputPage::getMetaTags
21 * @covers OutputPage::getHeadLinksArray
22 */
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' );
29
30 $expected = [
31 [ 'http:expires', '0' ],
32 [ 'keywords', 'first' ],
33 [ 'keywords', 'second' ],
34 [ 'og:title', 'Ta-duh' ],
35 ];
36 $this->assertSame( $expected, $outputPage->getMetaTags() );
37
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 );
44 }
45
46 /**
47 * @covers OutputPage::setIndexPolicy
48 * @covers OutputPage::setFollowPolicy
49 * @covers OutputPage::getHeadLinksArray
50 */
51 public function testRobotsPolicies() {
52 $outputPage = $this->newInstance();
53 $outputPage->setIndexPolicy( 'noindex' );
54 $outputPage->setFollowPolicy( 'nofollow' );
55
56 $links = $outputPage->getHeadLinksArray();
57 $this->assertContains( '<meta name="robots" content="noindex,nofollow"/>', $links );
58 }
59
60 /**
61 * Tests a particular case of transformCssMedia, using the given input, globals,
62 * expected return, and message
63 *
64 * Asserts that $expectedReturn is returned.
65 *
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
71 *
72 * @param array $args Key-value array of arguments as shown above
73 */
74 protected function assertTransformCssMediaCase( $args ) {
75 $queryData = [];
76 if ( isset( $args['printableQuery'] ) ) {
77 $queryData['printable'] = $args['printableQuery'];
78 }
79
80 if ( isset( $args['handheldQuery'] ) ) {
81 $queryData['handheld'] = $args['handheldQuery'];
82 }
83
84 $fauxRequest = new FauxRequest( $queryData, false );
85 $this->setMwGlobals( [
86 'wgRequest' => $fauxRequest,
87 ] );
88
89 $actualReturn = OutputPage::transformCssMedia( $args['media'] );
90 $this->assertSame( $args['expectedReturn'], $actualReturn, $args['message'] );
91 }
92
93 /**
94 * Tests print requests
95 * @covers OutputPage::transformCssMedia
96 */
97 public function testPrintRequests() {
98 $this->assertTransformCssMediaCase( [
99 'printableQuery' => '1',
100 'media' => 'screen',
101 'expectedReturn' => null,
102 'message' => 'On printable request, screen returns null'
103 ] );
104
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'
110 ] );
111
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'
117 ] );
118
119 $this->assertTransformCssMediaCase( [
120 'printableQuery' => '1',
121 'media' => 'print',
122 'expectedReturn' => '',
123 'message' => 'On printable request, media print returns empty string'
124 ] );
125 }
126
127 public static function provideCdnCacheEpoch() {
128 $base = [
129 'pageTime' => '2011-04-01T12:00:00+00:00',
130 'maxAge' => 24 * 3600,
131 ];
132 return [
133 'after 1s' => [ $base + [
134 'reqTime' => '2011-04-01T12:00:01+00:00',
135 'expect' => '2011-04-01T12:00:00+00:00',
136 ] ],
137 'after 23h' => [ $base + [
138 'reqTime' => '2011-04-02T11:00:00+00:00',
139 'expect' => '2011-04-01T12:00:00+00:00',
140 ] ],
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',
144 ] ],
145 'after a year' => [ $base + [
146 'reqTime' => '2012-05-06T00:12:07+00:00',
147 'expect' => '2012-05-05T00:12:07+00:00',
148 ] ],
149 ];
150 }
151
152 /**
153 * @dataProvider provideCdnCacheEpoch
154 * @covers OutputPage::getCdnCacheEpoch
155 */
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'] ) );
161
162 $this->assertEquals(
163 $params['expect'],
164 gmdate( DateTime::ATOM, $actual ),
165 'cdn epoch'
166 );
167 }
168
169 /**
170 * Tests screen requests, without either query parameter set
171 * @covers OutputPage::transformCssMedia
172 */
173 public function testScreenRequests() {
174 $this->assertTransformCssMediaCase( [
175 'media' => 'screen',
176 'expectedReturn' => 'screen',
177 'message' => 'On screen request, screen media type is preserved'
178 ] );
179
180 $this->assertTransformCssMediaCase( [
181 'media' => 'handheld',
182 'expectedReturn' => 'handheld',
183 'message' => 'On screen request, handheld media type is preserved'
184 ] );
185
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.'
190 ] );
191
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.'
196 ] );
197
198 $this->assertTransformCssMediaCase( [
199 'media' => 'print',
200 'expectedReturn' => 'print',
201 'message' => 'On screen request, print media type is preserved'
202 ] );
203 }
204
205 /**
206 * Tests handheld behavior
207 * @covers OutputPage::transformCssMedia
208 */
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'
215 ] );
216
217 $this->assertTransformCssMediaCase( [
218 'handheldQuery' => '1',
219 'media' => 'screen',
220 'expectedReturn' => null,
221 'message' => 'On request with handheld querystring and media is screen, returns null'
222 ] );
223 }
224
225 public static function provideTransformFilePath() {
226 $baseDir = dirname( __DIR__ ) . '/data/media';
227 return [
228 // File that matches basePath, and exists. Hash found and appended.
229 [
230 'baseDir' => $baseDir, 'basePath' => '/w',
231 '/w/test.jpg',
232 '/w/test.jpg?edcf2'
233 ],
234 // File that matches basePath, but not found on disk. Empty query.
235 [
236 'baseDir' => $baseDir, 'basePath' => '/w',
237 '/w/unknown.png',
238 '/w/unknown.png?'
239 ],
240 // File not matching basePath. Ignored.
241 [
242 'baseDir' => $baseDir, 'basePath' => '/w',
243 '/files/test.jpg'
244 ],
245 // Empty string. Ignored.
246 [
247 'baseDir' => $baseDir, 'basePath' => '/w',
248 '',
249 ''
250 ],
251 // Similar path, but with domain component. Ignored.
252 [
253 'baseDir' => $baseDir, 'basePath' => '/w',
254 '//example.org/w/test.jpg'
255 ],
256 [
257 'baseDir' => $baseDir, 'basePath' => '/w',
258 'https://example.org/w/test.jpg'
259 ],
260 // Unrelated path with domain component. Ignored.
261 [
262 'baseDir' => $baseDir, 'basePath' => '/w',
263 'https://example.org/files/test.jpg'
264 ],
265 [
266 'baseDir' => $baseDir, 'basePath' => '/w',
267 '//example.org/files/test.jpg'
268 ],
269 // Unrelated path with domain, and empty base path (root mw install). Ignored.
270 [
271 'baseDir' => $baseDir, 'basePath' => '',
272 'https://example.org/files/test.jpg'
273 ],
274 [
275 'baseDir' => $baseDir, 'basePath' => '',
276 // T155310
277 '//example.org/files/test.jpg'
278 ],
279 // Check UploadPath before ResourceBasePath (T155146)
280 [
281 'baseDir' => dirname( $baseDir ), 'basePath' => '',
282 'uploadDir' => $baseDir, 'uploadPath' => '/images',
283 '/images/test.jpg',
284 '/images/test.jpg?edcf2'
285 ],
286 ];
287 }
288
289 /**
290 * @dataProvider provideTransformFilePath
291 * @covers OutputPage::transformFilePath
292 * @covers OutputPage::transformResourcePath
293 */
294 public function testTransformResourcePath( $baseDir, $basePath, $uploadDir = null,
295 $uploadPath = null, $path = null, $expected = null
296 ) {
297 if ( $path === null ) {
298 // Skip optional $uploadDir and $uploadPath
299 $path = $uploadDir;
300 $expected = $uploadPath;
301 $uploadDir = "$baseDir/images";
302 $uploadPath = "$basePath/images";
303 }
304 $this->setMwGlobals( 'IP', $baseDir );
305 $conf = new HashConfig( [
306 'ResourceBasePath' => $basePath,
307 'UploadDirectory' => $uploadDir,
308 'UploadPath' => $uploadPath,
309 ] );
310
311 Wikimedia\suppressWarnings();
312 $actual = OutputPage::transformResourcePath( $conf, $path );
313 Wikimedia\restoreWarnings();
314
315 $this->assertEquals( $expected ?: $path, $actual );
316 }
317
318 public static function provideMakeResourceLoaderLink() {
319 // phpcs:disable Generic.Files.LineLength
320 return [
321 // Single only=scripts load
322 [
323 [ 'test.foo', ResourceLoaderModule::TYPE_SCRIPTS ],
324 "<script nonce=\"secret\">(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");'
326 . "});</script>"
327 ],
328 // Multiple only=styles load
329 [
330 [ [ 'test.baz', 'test.foo', 'test.bar' ], ResourceLoaderModule::TYPE_STYLES ],
331
332 '<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"/>'
333 ],
334 // Private embed (only=scripts)
335 [
336 [ 'test.quux', ResourceLoaderModule::TYPE_SCRIPTS ],
337 "<script nonce=\"secret\">(window.RLQ=window.RLQ||[]).push(function(){"
338 . "mw.test.baz({token:123});\nmw.loader.state({\"test.quux\":\"ready\"});"
339 . "});</script>"
340 ],
341 // Load private module (combined)
342 [
343 [ 'test.quux', ResourceLoaderModule::TYPE_COMBINED ],
344 "<script nonce=\"secret\">(window.RLQ=window.RLQ||[]).push(function(){"
345 . "mw.loader.implement(\"test.quux@1ev0ijv\",function($,jQuery,require,module){"
346 . "mw.test.baz({token:123});},{\"css\":[\".mw-icon{transition:none}"
347 . "\"]});});</script>"
348 ],
349 // Load no modules
350 [
351 [ [], ResourceLoaderModule::TYPE_COMBINED ],
352 '',
353 ],
354 // noscript group
355 [
356 [ 'test.noscript', ResourceLoaderModule::TYPE_STYLES ],
357 '<noscript><link rel="stylesheet" href="http://127.0.0.1:8080/w/load.php?debug=false&amp;lang=en&amp;modules=test.noscript&amp;only=styles&amp;skin=fallback"/></noscript>'
358 ],
359 // Load two modules in separate groups
360 [
361 [ [ 'test.group.foo', 'test.group.bar' ], ResourceLoaderModule::TYPE_COMBINED ],
362 "<script nonce=\"secret\">(window.RLQ=window.RLQ||[]).push(function(){"
363 . 'mw.loader.load("http://127.0.0.1:8080/w/load.php?debug=false\u0026lang=en\u0026modules=test.group.bar\u0026skin=fallback");'
364 . 'mw.loader.load("http://127.0.0.1:8080/w/load.php?debug=false\u0026lang=en\u0026modules=test.group.foo\u0026skin=fallback");'
365 . "});</script>"
366 ],
367 ];
368 // phpcs:enable
369 }
370
371 /**
372 * See ResourceLoaderClientHtmlTest for full coverage.
373 *
374 * @dataProvider provideMakeResourceLoaderLink
375 * @covers OutputPage::makeResourceLoaderLink
376 */
377 public function testMakeResourceLoaderLink( $args, $expectedHtml ) {
378 $this->setMwGlobals( [
379 'wgResourceLoaderDebug' => false,
380 'wgLoadScript' => 'http://127.0.0.1:8080/w/load.php',
381 'wgCSPReportOnlyHeader' => true,
382 ] );
383 $class = new ReflectionClass( OutputPage::class );
384 $method = $class->getMethod( 'makeResourceLoaderLink' );
385 $method->setAccessible( true );
386 $ctx = new RequestContext();
387 $ctx->setSkin( SkinFactory::getDefaultInstance()->makeSkin( 'fallback' ) );
388 $ctx->setLanguage( 'en' );
389 $out = new OutputPage( $ctx );
390 $nonce = $class->getProperty( 'CSPNonce' );
391 $nonce->setAccessible( true );
392 $nonce->setValue( $out, 'secret' );
393 $rl = $out->getResourceLoader();
394 $rl->setMessageBlobStore( new NullMessageBlobStore() );
395 $rl->register( [
396 'test.foo' => new ResourceLoaderTestModule( [
397 'script' => 'mw.test.foo( { a: true } );',
398 'styles' => '.mw-test-foo { content: "style"; }',
399 ] ),
400 'test.bar' => new ResourceLoaderTestModule( [
401 'script' => 'mw.test.bar( { a: true } );',
402 'styles' => '.mw-test-bar { content: "style"; }',
403 ] ),
404 'test.baz' => new ResourceLoaderTestModule( [
405 'script' => 'mw.test.baz( { a: true } );',
406 'styles' => '.mw-test-baz { content: "style"; }',
407 ] ),
408 'test.quux' => new ResourceLoaderTestModule( [
409 'script' => 'mw.test.baz( { token: 123 } );',
410 'styles' => '/* pref-animate=off */ .mw-icon { transition: none; }',
411 'group' => 'private',
412 ] ),
413 'test.noscript' => new ResourceLoaderTestModule( [
414 'styles' => '.stuff { color: red; }',
415 'group' => 'noscript',
416 ] ),
417 'test.group.foo' => new ResourceLoaderTestModule( [
418 'script' => 'mw.doStuff( "foo" );',
419 'group' => 'foo',
420 ] ),
421 'test.group.bar' => new ResourceLoaderTestModule( [
422 'script' => 'mw.doStuff( "bar" );',
423 'group' => 'bar',
424 ] ),
425 ] );
426 $links = $method->invokeArgs( $out, $args );
427 $actualHtml = strval( $links );
428 $this->assertEquals( $expectedHtml, $actualHtml );
429 }
430
431 public static function provideBuildExemptModules() {
432 // phpcs:disable Generic.Files.LineLength
433 return [
434 'empty' => [
435 'exemptStyleModules' => [],
436 '<meta name="ResourceLoaderDynamicStyles" content=""/>',
437 ],
438 'empty sets' => [
439 'exemptStyleModules' => [ 'site' => [], 'noscript' => [], 'private' => [], 'user' => [] ],
440 '<meta name="ResourceLoaderDynamicStyles" content=""/>',
441 ],
442 'default logged-out' => [
443 'exemptStyleModules' => [ 'site' => [ 'site.styles' ] ],
444 '<meta name="ResourceLoaderDynamicStyles" content=""/>' . "\n" .
445 '<link rel="stylesheet" href="/w/load.php?debug=false&amp;lang=en&amp;modules=site.styles&amp;only=styles&amp;skin=fallback"/>',
446 ],
447 'default logged-in' => [
448 'exemptStyleModules' => [ 'site' => [ 'site.styles' ], 'user' => [ 'user.styles' ] ],
449 '<meta name="ResourceLoaderDynamicStyles" content=""/>' . "\n" .
450 '<link rel="stylesheet" href="/w/load.php?debug=false&amp;lang=en&amp;modules=site.styles&amp;only=styles&amp;skin=fallback"/>' . "\n" .
451 '<link rel="stylesheet" href="/w/load.php?debug=false&amp;lang=en&amp;modules=user.styles&amp;only=styles&amp;skin=fallback&amp;version=1e9z0ox"/>',
452 ],
453 'custom modules' => [
454 'exemptStyleModules' => [
455 'site' => [ 'site.styles', 'example.site.a', 'example.site.b' ],
456 'user' => [ 'user.styles', 'example.user' ],
457 ],
458 '<meta name="ResourceLoaderDynamicStyles" content=""/>' . "\n" .
459 '<link rel="stylesheet" href="/w/load.php?debug=false&amp;lang=en&amp;modules=example.site.a%2Cb&amp;only=styles&amp;skin=fallback"/>' . "\n" .
460 '<link rel="stylesheet" href="/w/load.php?debug=false&amp;lang=en&amp;modules=site.styles&amp;only=styles&amp;skin=fallback"/>' . "\n" .
461 '<link rel="stylesheet" href="/w/load.php?debug=false&amp;lang=en&amp;modules=example.user&amp;only=styles&amp;skin=fallback&amp;version=0a56zyi"/>' . "\n" .
462 '<link rel="stylesheet" href="/w/load.php?debug=false&amp;lang=en&amp;modules=user.styles&amp;only=styles&amp;skin=fallback&amp;version=1e9z0ox"/>',
463 ],
464 ];
465 // phpcs:enable
466 }
467
468 /**
469 * @dataProvider provideBuildExemptModules
470 * @covers OutputPage::buildExemptModules
471 */
472 public function testBuildExemptModules( array $exemptStyleModules, $expect ) {
473 $this->setMwGlobals( [
474 'wgResourceLoaderDebug' => false,
475 'wgLoadScript' => '/w/load.php',
476 // Stub wgCacheEpoch as it influences getVersionHash used for the
477 // urls in the expected HTML
478 'wgCacheEpoch' => '20140101000000',
479 ] );
480
481 // Set up stubs
482 $ctx = new RequestContext();
483 $ctx->setSkin( SkinFactory::getDefaultInstance()->makeSkin( 'fallback' ) );
484 $ctx->setLanguage( 'en' );
485 $outputPage = $this->getMockBuilder( OutputPage::class )
486 ->setConstructorArgs( [ $ctx ] )
487 ->setMethods( [ 'buildCssLinksArray' ] )
488 ->getMock();
489 $outputPage->expects( $this->any() )
490 ->method( 'buildCssLinksArray' )
491 ->willReturn( [] );
492 $rl = $outputPage->getResourceLoader();
493 $rl->setMessageBlobStore( new NullMessageBlobStore() );
494
495 // Register custom modules
496 $rl->register( [
497 'example.site.a' => new ResourceLoaderTestModule( [ 'group' => 'site' ] ),
498 'example.site.b' => new ResourceLoaderTestModule( [ 'group' => 'site' ] ),
499 'example.user' => new ResourceLoaderTestModule( [ 'group' => 'user' ] ),
500 ] );
501
502 $outputPage = TestingAccessWrapper::newFromObject( $outputPage );
503 $outputPage->rlExemptStyleModules = $exemptStyleModules;
504 $this->assertEquals(
505 $expect,
506 strval( $outputPage->buildExemptModules() )
507 );
508 }
509
510 /**
511 * @dataProvider provideVaryHeaders
512 * @covers OutputPage::addVaryHeader
513 * @covers OutputPage::getVaryHeader
514 * @covers OutputPage::getKeyHeader
515 */
516 public function testVaryHeaders( $calls, $vary, $key ) {
517 // get rid of default Vary fields
518 $outputPage = $this->getMockBuilder( OutputPage::class )
519 ->setConstructorArgs( [ new RequestContext() ] )
520 ->setMethods( [ 'getCacheVaryCookies' ] )
521 ->getMock();
522 $outputPage->expects( $this->any() )
523 ->method( 'getCacheVaryCookies' )
524 ->will( $this->returnValue( [] ) );
525 TestingAccessWrapper::newFromObject( $outputPage )->mVaryHeader = [];
526
527 foreach ( $calls as $call ) {
528 call_user_func_array( [ $outputPage, 'addVaryHeader' ], $call );
529 }
530 $this->assertEquals( $vary, $outputPage->getVaryHeader(), 'Vary:' );
531 $this->assertEquals( $key, $outputPage->getKeyHeader(), 'Key:' );
532 }
533
534 public function provideVaryHeaders() {
535 // note: getKeyHeader() automatically adds Vary: Cookie
536 return [
537 [ // single header
538 [
539 [ 'Cookie' ],
540 ],
541 'Vary: Cookie',
542 'Key: Cookie',
543 ],
544 [ // non-unique headers
545 [
546 [ 'Cookie' ],
547 [ 'Accept-Language' ],
548 [ 'Cookie' ],
549 ],
550 'Vary: Cookie, Accept-Language',
551 'Key: Cookie,Accept-Language',
552 ],
553 [ // two headers with single options
554 [
555 [ 'Cookie', [ 'param=phpsessid' ] ],
556 [ 'Accept-Language', [ 'substr=en' ] ],
557 ],
558 'Vary: Cookie, Accept-Language',
559 'Key: Cookie;param=phpsessid,Accept-Language;substr=en',
560 ],
561 [ // one header with multiple options
562 [
563 [ 'Cookie', [ 'param=phpsessid', 'param=userId' ] ],
564 ],
565 'Vary: Cookie',
566 'Key: Cookie;param=phpsessid;param=userId',
567 ],
568 [ // Duplicate option
569 [
570 [ 'Cookie', [ 'param=phpsessid' ] ],
571 [ 'Cookie', [ 'param=phpsessid' ] ],
572 [ 'Accept-Language', [ 'substr=en', 'substr=en' ] ],
573 ],
574 'Vary: Cookie, Accept-Language',
575 'Key: Cookie;param=phpsessid,Accept-Language;substr=en',
576 ],
577 [ // Same header, different options
578 [
579 [ 'Cookie', [ 'param=phpsessid' ] ],
580 [ 'Cookie', [ 'param=userId' ] ],
581 ],
582 'Vary: Cookie',
583 'Key: Cookie;param=phpsessid;param=userId',
584 ],
585 ];
586 }
587
588 /**
589 * @covers OutputPage::haveCacheVaryCookies
590 */
591 public function testHaveCacheVaryCookies() {
592 $request = new FauxRequest();
593 $context = new RequestContext();
594 $context->setRequest( $request );
595 $outputPage = new OutputPage( $context );
596
597 // No cookies are set.
598 $this->assertFalse( $outputPage->haveCacheVaryCookies() );
599
600 // 'Token' is present but empty, so it shouldn't count.
601 $request->setCookie( 'Token', '' );
602 $this->assertFalse( $outputPage->haveCacheVaryCookies() );
603
604 // 'Token' present and nonempty.
605 $request->setCookie( 'Token', '123' );
606 $this->assertTrue( $outputPage->haveCacheVaryCookies() );
607 }
608
609 /**
610 * @covers OutputPage::addCategoryLinks
611 * @covers OutputPage::getCategories
612 */
613 public function testGetCategories() {
614 $fakeResultWrapper = new FakeResultWrapper( [
615 (object)[
616 'pp_value' => 1,
617 'page_title' => 'Test'
618 ],
619 (object)[
620 'page_title' => 'Test2'
621 ]
622 ] );
623 $outputPage = $this->getMockBuilder( OutputPage::class )
624 ->setConstructorArgs( [ new RequestContext() ] )
625 ->setMethods( [ 'addCategoryLinksToLBAndGetResult' ] )
626 ->getMock();
627 $outputPage->expects( $this->any() )
628 ->method( 'addCategoryLinksToLBAndGetResult' )
629 ->will( $this->returnValue( $fakeResultWrapper ) );
630
631 $outputPage->addCategoryLinks( [
632 'Test' => 'Test',
633 'Test2' => 'Test2',
634 ] );
635 $this->assertEquals( [ 0 => 'Test', '1' => 'Test2' ], $outputPage->getCategories() );
636 $this->assertEquals( [ 0 => 'Test2' ], $outputPage->getCategories( 'normal' ) );
637 $this->assertEquals( [ 0 => 'Test' ], $outputPage->getCategories( 'hidden' ) );
638 }
639
640 /**
641 * @dataProvider provideLinkHeaders
642 * @covers OutputPage::addLinkHeader
643 * @covers OutputPage::getLinkHeader
644 */
645 public function testLinkHeaders( $headers, $result ) {
646 $outputPage = $this->newInstance();
647
648 foreach ( $headers as $header ) {
649 $outputPage->addLinkHeader( $header );
650 }
651
652 $this->assertEquals( $result, $outputPage->getLinkHeader() );
653 }
654
655 public function provideLinkHeaders() {
656 return [
657 [
658 [],
659 false
660 ],
661 [
662 [ '<https://foo/bar.jpg>;rel=preload;as=image' ],
663 'Link: <https://foo/bar.jpg>;rel=preload;as=image',
664 ],
665 [
666 [ '<https://foo/bar.jpg>;rel=preload;as=image','<https://foo/baz.jpg>;rel=preload;as=image' ],
667 'Link: <https://foo/bar.jpg>;rel=preload;as=image,<https://foo/baz.jpg>;rel=preload;as=image',
668 ],
669 ];
670 }
671
672 /**
673 * @dataProvider providePreloadLinkHeaders
674 * @covers OutputPage::addLogoPreloadLinkHeaders
675 * @covers ResourceLoaderSkinModule::getLogo
676 */
677 public function testPreloadLinkHeaders( $config, $result, $baseDir = null ) {
678 if ( $baseDir ) {
679 $this->setMwGlobals( 'IP', $baseDir );
680 }
681 $out = TestingAccessWrapper::newFromObject( $this->newInstance( $config ) );
682 $out->addLogoPreloadLinkHeaders();
683
684 $this->assertEquals( $result, $out->getLinkHeader() );
685 }
686
687 public function providePreloadLinkHeaders() {
688 return [
689 [
690 [
691 'ResourceBasePath' => '/w',
692 'Logo' => '/img/default.png',
693 'LogoHD' => [
694 '1.5x' => '/img/one-point-five.png',
695 '2x' => '/img/two-x.png',
696 ],
697 ],
698 'Link: </img/default.png>;rel=preload;as=image;media=' .
699 'not all and (min-resolution: 1.5dppx),' .
700 '</img/one-point-five.png>;rel=preload;as=image;media=' .
701 '(min-resolution: 1.5dppx) and (max-resolution: 1.999999dppx),' .
702 '</img/two-x.png>;rel=preload;as=image;media=(min-resolution: 2dppx)'
703 ],
704 [
705 [
706 'ResourceBasePath' => '/w',
707 'Logo' => '/img/default.png',
708 'LogoHD' => false,
709 ],
710 'Link: </img/default.png>;rel=preload;as=image'
711 ],
712 [
713 [
714 'ResourceBasePath' => '/w',
715 'Logo' => '/img/default.png',
716 'LogoHD' => [
717 '2x' => '/img/two-x.png',
718 ],
719 ],
720 'Link: </img/default.png>;rel=preload;as=image;media=' .
721 'not all and (min-resolution: 2dppx),' .
722 '</img/two-x.png>;rel=preload;as=image;media=(min-resolution: 2dppx)'
723 ],
724 [
725 [
726 'ResourceBasePath' => '/w',
727 'Logo' => '/img/default.png',
728 'LogoHD' => [
729 'svg' => '/img/vector.svg',
730 ],
731 ],
732 'Link: </img/vector.svg>;rel=preload;as=image'
733
734 ],
735 [
736 [
737 'ResourceBasePath' => '/w',
738 'Logo' => '/w/test.jpg',
739 'LogoHD' => false,
740 'UploadPath' => '/w/images',
741 ],
742 'Link: </w/test.jpg?edcf2>;rel=preload;as=image',
743 'baseDir' => dirname( __DIR__ ) . '/data/media',
744 ],
745 ];
746 }
747
748 /**
749 * @return OutputPage
750 */
751 private function newInstance( $config = [] ) {
752 $context = new RequestContext();
753
754 $context->setConfig( new HashConfig( $config + [
755 'AppleTouchIcon' => false,
756 'DisableLangConversion' => true,
757 'EnableCanonicalServerLink' => false,
758 'Favicon' => false,
759 'Feed' => false,
760 'LanguageCode' => false,
761 'ReferrerPolicy' => false,
762 'RightsPage' => false,
763 'RightsUrl' => false,
764 'UniversalEditButton' => false,
765 ] ) );
766
767 return new OutputPage( $context );
768 }
769 }
770
771 /**
772 * MessageBlobStore that doesn't do anything
773 */
774 class NullMessageBlobStore extends MessageBlobStore {
775 public function get( ResourceLoader $resourceLoader, $modules, $lang ) {
776 return [];
777 }
778
779 public function updateModule( $name, ResourceLoaderModule $module, $lang ) {
780 }
781
782 public function updateMessage( $key ) {
783 }
784
785 public function clear() {
786 }
787 }