Merge "Amend $namespaces in core for Javanese (jv)"
[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 [ 'baseDir' => $baseDir, 'basePath' => '/w', '/w/test.jpg', '/w/test.jpg?edcf2' ],
185 // File that matches basePath, but not found on disk. Empty query.
186 [ 'baseDir' => $baseDir, 'basePath' => '/w', '/w/unknown.png', '/w/unknown.png?' ],
187 // File not matching basePath. Ignored.
188 [ 'baseDir' => $baseDir, 'basePath' => '/w', '/files/test.jpg' ],
189 // Empty string. Ignored.
190 [ 'baseDir' => $baseDir, 'basePath' => '/w', '', '' ],
191 // Similar path, but with domain component. Ignored.
192 [ 'baseDir' => $baseDir, 'basePath' => '/w', '//example.org/w/test.jpg' ],
193 [ 'baseDir' => $baseDir, 'basePath' => '/w', 'https://example.org/w/test.jpg' ],
194 // Unrelated path with domain component. Ignored.
195 [ 'baseDir' => $baseDir, 'basePath' => '/w', 'https://example.org/files/test.jpg' ],
196 [ 'baseDir' => $baseDir, 'basePath' => '/w', '//example.org/files/test.jpg' ],
197 // Unrelated path with domain, and empty base path (root mw install). Ignored.
198 [ 'baseDir' => $baseDir, 'basePath' => '', 'https://example.org/files/test.jpg' ],
199 [ 'baseDir' => $baseDir, 'basePath' => '', '//example.org/files/test.jpg' ], // T155310
200 ];
201 }
202
203 /**
204 * @dataProvider provideTransformFilePath
205 * @covers OutputPage::transformFilePath
206 * @covers OutputPage::transformResourcePath
207 */
208 public function testTransformResourcePath( $baseDir, $basePath, $path, $expected = null ) {
209 $this->setMwGlobals( 'IP', $baseDir );
210 $conf = new HashConfig( [ 'ResourceBasePath' => $basePath ] );
211
212 MediaWiki\suppressWarnings();
213 $actual = OutputPage::transformResourcePath( $conf, $path );
214 MediaWiki\restoreWarnings();
215
216 $this->assertEquals( $expected ?: $path, $actual );
217 }
218
219 public static function provideMakeResourceLoaderLink() {
220 // @codingStandardsIgnoreStart Generic.Files.LineLength
221 return [
222 // Single only=scripts load
223 [
224 [ 'test.foo', ResourceLoaderModule::TYPE_SCRIPTS ],
225 "<script>(window.RLQ=window.RLQ||[]).push(function(){"
226 . 'mw.loader.load("http://127.0.0.1:8080/w/load.php?debug=false\u0026lang=en\u0026modules=test.foo\u0026only=scripts\u0026skin=fallback");'
227 . "});</script>"
228 ],
229 // Multiple only=styles load
230 [
231 [ [ 'test.baz', 'test.foo', 'test.bar' ], ResourceLoaderModule::TYPE_STYLES ],
232
233 '<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"/>'
234 ],
235 // Private embed (only=scripts)
236 [
237 [ 'test.quux', ResourceLoaderModule::TYPE_SCRIPTS ],
238 "<script>(window.RLQ=window.RLQ||[]).push(function(){"
239 . "mw.test.baz({token:123});mw.loader.state({\"test.quux\":\"ready\"});"
240 . "});</script>"
241 ],
242 ];
243 // @codingStandardsIgnoreEnd
244 }
245
246 /**
247 * See ResourceLoaderClientHtmlTest for full coverage.
248 *
249 * @dataProvider provideMakeResourceLoaderLink
250 * @covers OutputPage::makeResourceLoaderLink
251 */
252 public function testMakeResourceLoaderLink( $args, $expectedHtml ) {
253 $this->setMwGlobals( [
254 'wgResourceLoaderDebug' => false,
255 'wgLoadScript' => 'http://127.0.0.1:8080/w/load.php',
256 ] );
257 $class = new ReflectionClass( 'OutputPage' );
258 $method = $class->getMethod( 'makeResourceLoaderLink' );
259 $method->setAccessible( true );
260 $ctx = new RequestContext();
261 $ctx->setSkin( SkinFactory::getDefaultInstance()->makeSkin( 'fallback' ) );
262 $ctx->setLanguage( 'en' );
263 $out = new OutputPage( $ctx );
264 $rl = $out->getResourceLoader();
265 $rl->setMessageBlobStore( new NullMessageBlobStore() );
266 $rl->register( [
267 'test.foo' => new ResourceLoaderTestModule( [
268 'script' => 'mw.test.foo( { a: true } );',
269 'styles' => '.mw-test-foo { content: "style"; }',
270 ] ),
271 'test.bar' => new ResourceLoaderTestModule( [
272 'script' => 'mw.test.bar( { a: true } );',
273 'styles' => '.mw-test-bar { content: "style"; }',
274 ] ),
275 'test.baz' => new ResourceLoaderTestModule( [
276 'script' => 'mw.test.baz( { a: true } );',
277 'styles' => '.mw-test-baz { content: "style"; }',
278 ] ),
279 'test.quux' => new ResourceLoaderTestModule( [
280 'script' => 'mw.test.baz( { token: 123 } );',
281 'styles' => '/* pref-animate=off */ .mw-icon { transition: none; }',
282 'group' => 'private',
283 ] ),
284 ] );
285 $links = $method->invokeArgs( $out, $args );
286 $actualHtml = strval( $links );
287 $this->assertEquals( $expectedHtml, $actualHtml );
288 }
289
290 /**
291 * @dataProvider provideVaryHeaders
292 * @covers OutputPage::addVaryHeader
293 * @covers OutputPage::getVaryHeader
294 * @covers OutputPage::getKeyHeader
295 */
296 public function testVaryHeaders( $calls, $vary, $key ) {
297 // get rid of default Vary fields
298 $outputPage = $this->getMockBuilder( 'OutputPage' )
299 ->setConstructorArgs( [ new RequestContext() ] )
300 ->setMethods( [ 'getCacheVaryCookies' ] )
301 ->getMock();
302 $outputPage->expects( $this->any() )
303 ->method( 'getCacheVaryCookies' )
304 ->will( $this->returnValue( [] ) );
305 TestingAccessWrapper::newFromObject( $outputPage )->mVaryHeader = [];
306
307 foreach ( $calls as $call ) {
308 call_user_func_array( [ $outputPage, 'addVaryHeader' ], $call );
309 }
310 $this->assertEquals( $vary, $outputPage->getVaryHeader(), 'Vary:' );
311 $this->assertEquals( $key, $outputPage->getKeyHeader(), 'Key:' );
312 }
313
314 public function provideVaryHeaders() {
315 // note: getKeyHeader() automatically adds Vary: Cookie
316 return [
317 [ // single header
318 [
319 [ 'Cookie' ],
320 ],
321 'Vary: Cookie',
322 'Key: Cookie',
323 ],
324 [ // non-unique headers
325 [
326 [ 'Cookie' ],
327 [ 'Accept-Language' ],
328 [ 'Cookie' ],
329 ],
330 'Vary: Cookie, Accept-Language',
331 'Key: Cookie,Accept-Language',
332 ],
333 [ // two headers with single options
334 [
335 [ 'Cookie', [ 'param=phpsessid' ] ],
336 [ 'Accept-Language', [ 'substr=en' ] ],
337 ],
338 'Vary: Cookie, Accept-Language',
339 'Key: Cookie;param=phpsessid,Accept-Language;substr=en',
340 ],
341 [ // one header with multiple options
342 [
343 [ 'Cookie', [ 'param=phpsessid', 'param=userId' ] ],
344 ],
345 'Vary: Cookie',
346 'Key: Cookie;param=phpsessid;param=userId',
347 ],
348 [ // Duplicate option
349 [
350 [ 'Cookie', [ 'param=phpsessid' ] ],
351 [ 'Cookie', [ 'param=phpsessid' ] ],
352 [ 'Accept-Language', [ 'substr=en', 'substr=en' ] ],
353 ],
354 'Vary: Cookie, Accept-Language',
355 'Key: Cookie;param=phpsessid,Accept-Language;substr=en',
356 ],
357 [ // Same header, different options
358 [
359 [ 'Cookie', [ 'param=phpsessid' ] ],
360 [ 'Cookie', [ 'param=userId' ] ],
361 ],
362 'Vary: Cookie',
363 'Key: Cookie;param=phpsessid;param=userId',
364 ],
365 ];
366 }
367
368 /**
369 * @covers OutputPage::haveCacheVaryCookies
370 */
371 public function testHaveCacheVaryCookies() {
372 $request = new FauxRequest();
373 $context = new RequestContext();
374 $context->setRequest( $request );
375 $outputPage = new OutputPage( $context );
376
377 // No cookies are set.
378 $this->assertFalse( $outputPage->haveCacheVaryCookies() );
379
380 // 'Token' is present but empty, so it shouldn't count.
381 $request->setCookie( 'Token', '' );
382 $this->assertFalse( $outputPage->haveCacheVaryCookies() );
383
384 // 'Token' present and nonempty.
385 $request->setCookie( 'Token', '123' );
386 $this->assertTrue( $outputPage->haveCacheVaryCookies() );
387 }
388
389 /*
390 * @covers OutputPage::addCategoryLinks
391 * @covers OutputPage::getCategories
392 */
393 public function testGetCategories() {
394 $fakeResultWrapper = new FakeResultWrapper( [
395 (object) [
396 'pp_value' => 1,
397 'page_title' => 'Test'
398 ],
399 (object) [
400 'page_title' => 'Test2'
401 ]
402 ] );
403 $outputPage = $this->getMockBuilder( 'OutputPage' )
404 ->setConstructorArgs( [ new RequestContext() ] )
405 ->setMethods( [ 'addCategoryLinksToLBAndGetResult' ] )
406 ->getMock();
407 $outputPage->expects( $this->any() )
408 ->method( 'addCategoryLinksToLBAndGetResult' )
409 ->will( $this->returnValue( $fakeResultWrapper ) );
410
411 $outputPage->addCategoryLinks( [
412 'Test' => 'Test',
413 'Test2' => 'Test2',
414 ] );
415 $this->assertEquals( [ 0 => 'Test', '1' => 'Test2' ], $outputPage->getCategories() );
416 $this->assertEquals( [ 0 => 'Test2' ], $outputPage->getCategories( 'normal' ) );
417 $this->assertEquals( [ 0 => 'Test' ], $outputPage->getCategories( 'hidden' ) );
418 }
419
420 /**
421 * @return OutputPage
422 */
423 private function newInstance() {
424 $context = new RequestContext();
425
426 $context->setConfig( new HashConfig( [
427 'AppleTouchIcon' => false,
428 'DisableLangConversion' => true,
429 'EnableAPI' => false,
430 'EnableCanonicalServerLink' => false,
431 'Favicon' => false,
432 'Feed' => false,
433 'LanguageCode' => false,
434 'ReferrerPolicy' => false,
435 'RightsPage' => false,
436 'RightsUrl' => false,
437 'UniversalEditButton' => false,
438 ] ) );
439
440 return new OutputPage( $context );
441 }
442 }
443
444 /**
445 * MessageBlobStore that doesn't do anything
446 */
447 class NullMessageBlobStore extends MessageBlobStore {
448 public function get( ResourceLoader $resourceLoader, $modules, $lang ) {
449 return [];
450 }
451
452 public function insertMessageBlob( $name, ResourceLoaderModule $module, $lang ) {
453 return false;
454 }
455
456 public function updateModule( $name, ResourceLoaderModule $module, $lang ) {
457 }
458
459 public function updateMessage( $key ) {
460 }
461
462 public function clear() {
463 }
464 }