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