OutputPageTest should be independent of $wgResourceLoaderDebug setting
[lhc/web/wiklou.git] / tests / phpunit / includes / OutputPageTest.php
1 <?php
2
3 use Wikimedia\TestingAccessWrapper;
4
5 /**
6 * @author Matthew Flaschen
7 *
8 * @group Database
9 * @group Output
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 // Ensure that we don't affect the global ResourceLoader state.
16 protected function setUp() {
17 parent::setUp();
18 ResourceLoader::clearCache();
19 }
20 protected function tearDown() {
21 parent::tearDown();
22 ResourceLoader::clearCache();
23 }
24
25 /**
26 * @dataProvider provideRedirect
27 *
28 * @covers OutputPage::__construct
29 * @covers OutputPage::redirect
30 * @covers OutputPage::getRedirect
31 */
32 public function testRedirect( $url, $code = null ) {
33 $op = $this->newInstance();
34 if ( isset( $code ) ) {
35 $op->redirect( $url, $code );
36 } else {
37 $op->redirect( $url );
38 }
39 $expectedUrl = str_replace( "\n", '', $url );
40 $this->assertSame( $expectedUrl, $op->getRedirect() );
41 $this->assertSame( $expectedUrl, $op->mRedirect );
42 $this->assertSame( $code ?? '302', $op->mRedirectCode );
43 }
44
45 public function provideRedirect() {
46 return [
47 [ 'http://example.com' ],
48 [ 'http://example.com', '400' ],
49 [ 'http://example.com', 'squirrels!!!' ],
50 [ "a\nb" ],
51 ];
52 }
53
54 /**
55 * @covers OutputPage::setCopyrightUrl
56 * @covers OutputPage::getHeadLinksArray
57 */
58 public function testSetCopyrightUrl() {
59 $op = $this->newInstance();
60 $op->setCopyrightUrl( 'http://example.com' );
61
62 $this->assertSame(
63 Html::element( 'link', [ 'rel' => 'license', 'href' => 'http://example.com' ] ),
64 $op->getHeadLinksArray()['copyright']
65 );
66 }
67
68 // @todo How to test setStatusCode?
69
70 /**
71 * @covers OutputPage::addMeta
72 * @covers OutputPage::getMetaTags
73 * @covers OutputPage::getHeadLinksArray
74 */
75 public function testMetaTags() {
76 $op = $this->newInstance();
77 $op->addMeta( 'http:expires', '0' );
78 $op->addMeta( 'keywords', 'first' );
79 $op->addMeta( 'keywords', 'second' );
80 $op->addMeta( 'og:title', 'Ta-duh' );
81
82 $expected = [
83 [ 'http:expires', '0' ],
84 [ 'keywords', 'first' ],
85 [ 'keywords', 'second' ],
86 [ 'og:title', 'Ta-duh' ],
87 ];
88 $this->assertSame( $expected, $op->getMetaTags() );
89
90 $links = $op->getHeadLinksArray();
91 $this->assertContains( '<meta http-equiv="expires" content="0"/>', $links );
92 $this->assertContains( '<meta name="keywords" content="first"/>', $links );
93 $this->assertContains( '<meta name="keywords" content="second"/>', $links );
94 $this->assertContains( '<meta property="og:title" content="Ta-duh"/>', $links );
95 $this->assertArrayNotHasKey( 'meta-robots', $links );
96 }
97
98 /**
99 * @covers OutputPage::addLink
100 * @covers OutputPage::getLinkTags
101 * @covers OutputPage::getHeadLinksArray
102 */
103 public function testAddLink() {
104 $op = $this->newInstance();
105
106 $links = [
107 [],
108 [ 'rel' => 'foo', 'href' => 'http://example.com' ],
109 ];
110
111 foreach ( $links as $link ) {
112 $op->addLink( $link );
113 }
114
115 $this->assertSame( $links, $op->getLinkTags() );
116
117 $result = $op->getHeadLinksArray();
118
119 foreach ( $links as $link ) {
120 $this->assertContains( Html::element( 'link', $link ), $result );
121 }
122 }
123
124 /**
125 * @covers OutputPage::setCanonicalUrl
126 * @covers OutputPage::getCanonicalUrl
127 * @covers OutputPage::getHeadLinksArray
128 */
129 public function testSetCanonicalUrl() {
130 $op = $this->newInstance();
131 $op->setCanonicalUrl( 'http://example.comm' );
132 $op->setCanonicalUrl( 'http://example.com' );
133
134 $this->assertSame( 'http://example.com', $op->getCanonicalUrl() );
135
136 $headLinks = $op->getHeadLinksArray();
137
138 $this->assertContains( Html::element( 'link', [
139 'rel' => 'canonical', 'href' => 'http://example.com'
140 ] ), $headLinks );
141
142 $this->assertNotContains( Html::element( 'link', [
143 'rel' => 'canonical', 'href' => 'http://example.comm'
144 ] ), $headLinks );
145 }
146
147 /**
148 * @covers OutputPage::addScript
149 */
150 public function testAddScript() {
151 $op = $this->newInstance();
152 $op->addScript( 'some random string' );
153
154 $this->assertContains( "\nsome random string\n", "\n" . $op->getBottomScripts() . "\n" );
155 }
156
157 /**
158 * @covers OutputPage::addScriptFile
159 */
160 public function testAddScriptFile() {
161 $op = $this->newInstance();
162 $op->addScriptFile( '/somescript.js' );
163 $op->addScriptFile( '//example.com/somescript.js' );
164
165 $this->assertContains(
166 "\n" . Html::linkedScript( '/somescript.js', $op->getCSPNonce() ) .
167 Html::linkedScript( '//example.com/somescript.js', $op->getCSPNonce() ) . "\n",
168 "\n" . $op->getBottomScripts() . "\n"
169 );
170 }
171
172 /**
173 * Test that addScriptFile() throws due to deprecation.
174 *
175 * @covers OutputPage::addScriptFile
176 */
177 public function testAddDeprecatedScriptFileWarning() {
178 $this->setExpectedException( PHPUnit_Framework_Error_Deprecated::class,
179 'Use of OutputPage::addScriptFile was deprecated in MediaWiki 1.24.' );
180
181 $op = $this->newInstance();
182 $op->addScriptFile( 'ignored-script.js' );
183 }
184
185 /**
186 * Test the actual behavior of the method (in the case where it doesn't throw, e.g., in
187 * production). Since it threw an exception once in this file, it won't when we call it again.
188 *
189 * @covers OutputPage::addScriptFile
190 */
191 public function testAddDeprecatedScriptFileNoOp() {
192 $op = $this->newInstance();
193 $op->addScriptFile( 'ignored-script.js' );
194
195 $this->assertNotContains( 'ignored-script.js', '' . $op->getBottomScripts() );
196 }
197
198 /**
199 * @covers OutputPage::addInlineScript
200 */
201 public function testAddInlineScript() {
202 $op = $this->newInstance();
203 $op->addInlineScript( 'let foo = "bar";' );
204 $op->addInlineScript( 'alert( foo );' );
205
206 $this->assertContains(
207 "\n" . Html::inlineScript( "\nlet foo = \"bar\";\n", $op->getCSPNonce() ) . "\n" .
208 Html::inlineScript( "\nalert( foo );\n", $op->getCSPNonce() ) . "\n",
209 "\n" . $op->getBottomScripts() . "\n"
210 );
211 }
212
213 // @todo How to test filterModules(), warnModuleTargetFilter(), getModules(), etc.?
214
215 /**
216 * @covers OutputPage::getTarget
217 * @covers OutputPage::setTarget
218 */
219 public function testSetTarget() {
220 $op = $this->newInstance();
221 $op->setTarget( 'foo' );
222
223 $this->assertSame( 'foo', $op->getTarget() );
224 // @todo What else? Test some actual effect?
225 }
226
227 // @todo How to test addContentOverride(Callback)?
228
229 /**
230 * @covers OutputPage::getHeadItemsArray
231 * @covers OutputPage::addHeadItem
232 * @covers OutputPage::addHeadItems
233 * @covers OutputPage::hasHeadItem
234 */
235 public function testHeadItems() {
236 $op = $this->newInstance();
237 $op->addHeadItem( 'a', 'b' );
238 $op->addHeadItems( [ 'c' => '<d>&amp;', 'e' => 'f', 'a' => 'q' ] );
239 $op->addHeadItem( 'e', 'g' );
240 $op->addHeadItems( 'x' );
241
242 $this->assertSame( [ 'a' => 'q', 'c' => '<d>&amp;', 'e' => 'g', 'x' ],
243 $op->getHeadItemsArray() );
244
245 $this->assertTrue( $op->hasHeadItem( 'a' ) );
246 $this->assertTrue( $op->hasHeadItem( 'c' ) );
247 $this->assertTrue( $op->hasHeadItem( 'e' ) );
248 $this->assertTrue( $op->hasHeadItem( '0' ) );
249
250 $this->assertContains( "\nq\n<d>&amp;\ng\nx\n",
251 '' . $op->headElement( $op->getContext()->getSkin() ) );
252 }
253
254 /**
255 * @covers OutputPage::getHeadItemsArray
256 * @covers OutputPage::addParserOutputMetadata
257 */
258 public function testHeadItemsParserOutput() {
259 $op = $this->newInstance();
260 $stubPO1 = $this->createParserOutputStub( 'getHeadItems', [ 'a' => 'b' ] );
261 $op->addParserOutputMetadata( $stubPO1 );
262 $stubPO2 = $this->createParserOutputStub( 'getHeadItems',
263 [ 'c' => '<d>&amp;', 'e' => 'f', 'a' => 'q' ] );
264 $op->addParserOutputMetadata( $stubPO2 );
265 $stubPO3 = $this->createParserOutputStub( 'getHeadItems', [ 'e' => 'g' ] );
266 $op->addParserOutputMetadata( $stubPO3 );
267 $stubPO4 = $this->createParserOutputStub( 'getHeadItems', [ 'x' ] );
268 $op->addParserOutputMetadata( $stubPO4 );
269
270 $this->assertSame( [ 'a' => 'q', 'c' => '<d>&amp;', 'e' => 'g', 'x' ],
271 $op->getHeadItemsArray() );
272
273 $this->assertTrue( $op->hasHeadItem( 'a' ) );
274 $this->assertTrue( $op->hasHeadItem( 'c' ) );
275 $this->assertTrue( $op->hasHeadItem( 'e' ) );
276 $this->assertTrue( $op->hasHeadItem( '0' ) );
277 $this->assertFalse( $op->hasHeadItem( 'b' ) );
278
279 $this->assertContains( "\nq\n<d>&amp;\ng\nx\n",
280 '' . $op->headElement( $op->getContext()->getSkin() ) );
281 }
282
283 /**
284 * @covers OutputPage::addBodyClasses
285 */
286 public function testAddBodyClasses() {
287 $op = $this->newInstance();
288 $op->addBodyClasses( 'a' );
289 $op->addBodyClasses( 'mediawiki' );
290 $op->addBodyClasses( 'b c' );
291 $op->addBodyClasses( [ 'd', 'e' ] );
292 $op->addBodyClasses( 'a' );
293
294 $this->assertContains( '"a mediawiki b c d e ltr',
295 '' . $op->headElement( $op->getContext()->getSkin() ) );
296 }
297
298 /**
299 * @covers OutputPage::setArticleBodyOnly
300 * @covers OutputPage::getArticleBodyOnly
301 */
302 public function testArticleBodyOnly() {
303 $op = $this->newInstance();
304 $this->assertFalse( $op->getArticleBodyOnly() );
305
306 $op->setArticleBodyOnly( true );
307 $this->assertTrue( $op->getArticleBodyOnly() );
308
309 $op->addHTML( '<b>a</b>' );
310
311 $this->assertSame( '<b>a</b>', $op->output( true ) );
312 }
313
314 /**
315 * @covers OutputPage::setProperty
316 * @covers OutputPage::getProperty
317 */
318 public function testProperties() {
319 $op = $this->newInstance();
320
321 $this->assertNull( $op->getProperty( 'foo' ) );
322
323 $op->setProperty( 'foo', 'bar' );
324 $op->setProperty( 'baz', 'quz' );
325
326 $this->assertSame( 'bar', $op->getProperty( 'foo' ) );
327 $this->assertSame( 'quz', $op->getProperty( 'baz' ) );
328 }
329
330 /**
331 * @dataProvider provideCheckLastModified
332 *
333 * @covers OutputPage::checkLastModified
334 * @covers OutputPage::getCdnCacheEpoch
335 */
336 public function testCheckLastModified(
337 $timestamp, $ifModifiedSince, $expected, $config = [], $callback = null
338 ) {
339 $request = new FauxRequest();
340 if ( $ifModifiedSince ) {
341 if ( is_numeric( $ifModifiedSince ) ) {
342 // Unix timestamp
343 $ifModifiedSince = date( 'D, d M Y H:i:s', $ifModifiedSince ) . ' GMT';
344 }
345 $request->setHeader( 'If-Modified-Since', $ifModifiedSince );
346 }
347
348 if ( !isset( $config['CacheEpoch'] ) ) {
349 // Make sure it's not too recent
350 $config['CacheEpoch'] = '20000101000000';
351 }
352
353 $op = $this->newInstance( $config, $request );
354
355 if ( $callback ) {
356 $callback( $op, $this );
357 }
358
359 // Avoid a complaint about not being able to disable compression
360 Wikimedia\suppressWarnings();
361 try {
362 $this->assertEquals( $expected, $op->checkLastModified( $timestamp ) );
363 } finally {
364 Wikimedia\restoreWarnings();
365 }
366 }
367
368 public function provideCheckLastModified() {
369 $lastModified = time() - 3600;
370 return [
371 'Timestamp 0' =>
372 [ '0', $lastModified, false ],
373 'Timestamp Unix epoch' =>
374 [ '19700101000000', $lastModified, false ],
375 'Timestamp same as If-Modified-Since' =>
376 [ $lastModified, $lastModified, true ],
377 'Timestamp one second after If-Modified-Since' =>
378 [ $lastModified + 1, $lastModified, false ],
379 'No If-Modified-Since' =>
380 [ $lastModified + 1, null, false ],
381 'Malformed If-Modified-Since' =>
382 [ $lastModified + 1, 'GIBBERING WOMBATS !!!', false ],
383 'Non-standard IE-style If-Modified-Since' =>
384 [ $lastModified, date( 'D, d M Y H:i:s', $lastModified ) . ' GMT; length=5202',
385 true ],
386 // @todo Should we fix this behavior to match the spec? Probably no reason to.
387 'If-Modified-Since not per spec but we accept it anyway because strtotime does' =>
388 [ $lastModified, "@$lastModified", true ],
389 '$wgCachePages = false' =>
390 [ $lastModified, $lastModified, false, [ 'CachePages' => false ] ],
391 '$wgCacheEpoch' =>
392 [ $lastModified, $lastModified, false,
393 [ 'CacheEpoch' => wfTimestamp( TS_MW, $lastModified + 1 ) ] ],
394 'Recently-touched user' =>
395 [ $lastModified, $lastModified, false, [],
396 function ( $op ) {
397 $op->getContext()->setUser( $this->getTestUser()->getUser() );
398 } ],
399 'After Squid expiry' =>
400 [ $lastModified, $lastModified, false,
401 [ 'UseSquid' => true, 'SquidMaxage' => 3599 ] ],
402 'Hook allows cache use' =>
403 [ $lastModified + 1, $lastModified, true, [],
404 function ( $op, $that ) {
405 $that->setTemporaryHook( 'OutputPageCheckLastModified',
406 function ( &$modifiedTimes ) {
407 $modifiedTimes = [ 1 ];
408 }
409 );
410 } ],
411 'Hooks prohibits cache use' =>
412 [ $lastModified, $lastModified, false, [],
413 function ( $op, $that ) {
414 $that->setTemporaryHook( 'OutputPageCheckLastModified',
415 function ( &$modifiedTimes ) {
416 $modifiedTimes = [ max( $modifiedTimes ) + 1 ];
417 }
418 );
419 } ],
420 ];
421 }
422
423 /**
424 * @dataProvider provideCdnCacheEpoch
425 *
426 * @covers OutputPage::getCdnCacheEpoch
427 */
428 public function testCdnCacheEpoch( $params ) {
429 $out = TestingAccessWrapper::newFromObject( $this->newInstance() );
430 $reqTime = strtotime( $params['reqTime'] );
431 $pageTime = strtotime( $params['pageTime'] );
432 $actual = max( $pageTime, $out->getCdnCacheEpoch( $reqTime, $params['maxAge'] ) );
433
434 $this->assertEquals(
435 $params['expect'],
436 gmdate( DateTime::ATOM, $actual ),
437 'cdn epoch'
438 );
439 }
440
441 public static function provideCdnCacheEpoch() {
442 $base = [
443 'pageTime' => '2011-04-01T12:00:00+00:00',
444 'maxAge' => 24 * 3600,
445 ];
446 return [
447 'after 1s' => [ $base + [
448 'reqTime' => '2011-04-01T12:00:01+00:00',
449 'expect' => '2011-04-01T12:00:00+00:00',
450 ] ],
451 'after 23h' => [ $base + [
452 'reqTime' => '2011-04-02T11:00:00+00:00',
453 'expect' => '2011-04-01T12:00:00+00:00',
454 ] ],
455 'after 24h and a bit' => [ $base + [
456 'reqTime' => '2011-04-02T12:34:56+00:00',
457 'expect' => '2011-04-01T12:34:56+00:00',
458 ] ],
459 'after a year' => [ $base + [
460 'reqTime' => '2012-05-06T00:12:07+00:00',
461 'expect' => '2012-05-05T00:12:07+00:00',
462 ] ],
463 ];
464 }
465
466 // @todo How to test setLastModified?
467
468 /**
469 * @covers OutputPage::setRobotPolicy
470 * @covers OutputPage::getHeadLinksArray
471 */
472 public function testSetRobotPolicy() {
473 $op = $this->newInstance();
474 $op->setRobotPolicy( 'noindex, nofollow' );
475
476 $links = $op->getHeadLinksArray();
477 $this->assertContains( '<meta name="robots" content="noindex,nofollow"/>', $links );
478 }
479
480 /**
481 * @covers OutputPage::setIndexPolicy
482 * @covers OutputPage::setFollowPolicy
483 * @covers OutputPage::getHeadLinksArray
484 */
485 public function testSetIndexFollowPolicies() {
486 $op = $this->newInstance();
487 $op->setIndexPolicy( 'noindex' );
488 $op->setFollowPolicy( 'nofollow' );
489
490 $links = $op->getHeadLinksArray();
491 $this->assertContains( '<meta name="robots" content="noindex,nofollow"/>', $links );
492 }
493
494 private function extractHTMLTitle( OutputPage $op ) {
495 $html = $op->headElement( $op->getContext()->getSkin() );
496
497 // OutputPage should always output the title in a nice format such that regexes will work
498 // fine. If it doesn't, we'll fail the tests.
499 preg_match_all( '!<title>(.*?)</title>!', $html, $matches );
500
501 $this->assertLessThanOrEqual( 1, count( $matches[1] ), 'More than one <title>!' );
502
503 if ( !count( $matches[1] ) ) {
504 return null;
505 }
506
507 return $matches[1][0];
508 }
509
510 /**
511 * Shorthand for getting the text of a message, in content language.
512 */
513 private static function getMsgText( $op, ...$msgParams ) {
514 return $op->msg( ...$msgParams )->inContentLanguage()->text();
515 }
516
517 /**
518 * @covers OutputPage::setHTMLTitle
519 * @covers OutputPage::getHTMLTitle
520 */
521 public function testHTMLTitle() {
522 $op = $this->newInstance();
523
524 // Default
525 $this->assertSame( '', $op->getHTMLTitle() );
526 $this->assertSame( '', $op->getPageTitle() );
527 $this->assertSame(
528 $this->getMsgText( $op, 'pagetitle', '' ),
529 $this->extractHTMLTitle( $op )
530 );
531
532 // Set to string
533 $op->setHTMLTitle( 'Potatoes will eat me' );
534
535 $this->assertSame( 'Potatoes will eat me', $op->getHTMLTitle() );
536 $this->assertSame( 'Potatoes will eat me', $this->extractHTMLTitle( $op ) );
537 // Shouldn't have changed the page title
538 $this->assertSame( '', $op->getPageTitle() );
539
540 // Set to message
541 $msg = $op->msg( 'mainpage' );
542
543 $op->setHTMLTitle( $msg );
544 $this->assertSame( $msg->text(), $op->getHTMLTitle() );
545 $this->assertSame( $msg->text(), $this->extractHTMLTitle( $op ) );
546 $this->assertSame( '', $op->getPageTitle() );
547 }
548
549 /**
550 * @covers OutputPage::setRedirectedFrom
551 */
552 public function testSetRedirectedFrom() {
553 $op = $this->newInstance();
554
555 $op->setRedirectedFrom( Title::newFromText( 'Talk:Some page' ) );
556 $this->assertSame( 'Talk:Some_page', $op->getJSVars()['wgRedirectedFrom'] );
557 }
558
559 /**
560 * @covers OutputPage::setPageTitle
561 * @covers OutputPage::getPageTitle
562 */
563 public function testPageTitle() {
564 // We don't test the actual HTML output anywhere, because that's up to the skin.
565 $op = $this->newInstance();
566
567 // Test default
568 $this->assertSame( '', $op->getPageTitle() );
569 $this->assertSame( '', $op->getHTMLTitle() );
570
571 // Test set to plain text
572 $op->setPageTitle( 'foobar' );
573
574 $this->assertSame( 'foobar', $op->getPageTitle() );
575 // HTML title should change as well
576 $this->assertSame( $this->getMsgText( $op, 'pagetitle', 'foobar' ), $op->getHTMLTitle() );
577
578 // Test set to text with good and bad HTML. We don't try to be comprehensive here, that
579 // belongs in Sanitizer tests.
580 $op->setPageTitle( '<script>a</script>&amp;<i>b</i>' );
581
582 $this->assertSame( '&lt;script&gt;a&lt;/script&gt;&amp;<i>b</i>', $op->getPageTitle() );
583 $this->assertSame(
584 $this->getMsgText( $op, 'pagetitle', '<script>a</script>&b' ),
585 $op->getHTMLTitle()
586 );
587
588 // Test set to message
589 $text = $this->getMsgText( $op, 'mainpage' );
590
591 $op->setPageTitle( $op->msg( 'mainpage' )->inContentLanguage() );
592 $this->assertSame( $text, $op->getPageTitle() );
593 $this->assertSame( $this->getMsgText( $op, 'pagetitle', $text ), $op->getHTMLTitle() );
594 }
595
596 /**
597 * @covers OutputPage::setTitle
598 */
599 public function testSetTitle() {
600 $op = $this->newInstance();
601
602 $this->assertSame( 'My test page', $op->getTitle()->getPrefixedText() );
603
604 $op->setTitle( Title::newFromText( 'Another test page' ) );
605
606 $this->assertSame( 'Another test page', $op->getTitle()->getPrefixedText() );
607 }
608
609 /**
610 * @covers OutputPage::setSubtitle
611 * @covers OutputPage::clearSubtitle
612 * @covers OutputPage::addSubtitle
613 * @covers OutputPage::getSubtitle
614 */
615 public function testSubtitle() {
616 $op = $this->newInstance();
617
618 $this->assertSame( '', $op->getSubtitle() );
619
620 $op->addSubtitle( '<b>foo</b>' );
621
622 $this->assertSame( '<b>foo</b>', $op->getSubtitle() );
623
624 $op->addSubtitle( $op->msg( 'mainpage' )->inContentLanguage() );
625
626 $this->assertSame(
627 "<b>foo</b><br />\n\t\t\t\t" . $this->getMsgText( $op, 'mainpage' ),
628 $op->getSubtitle()
629 );
630
631 $op->setSubtitle( 'There can be only one' );
632
633 $this->assertSame( 'There can be only one', $op->getSubtitle() );
634
635 $op->clearSubtitle();
636
637 $this->assertSame( '', $op->getSubtitle() );
638 }
639
640 /**
641 * @dataProvider provideBacklinkSubtitle
642 *
643 * @covers OutputPage::buildBacklinkSubtitle
644 */
645 public function testBuildBacklinkSubtitle( $titles, $queries, $contains, $notContains ) {
646 if ( count( $titles ) > 1 ) {
647 // Not applicable
648 $this->assertTrue( true );
649 return;
650 }
651
652 $title = Title::newFromText( $titles[0] );
653 $query = $queries[0];
654
655 $this->editPage( 'Page 1', '' );
656 $this->editPage( 'Page 2', '#REDIRECT [[Page 1]]' );
657
658 $str = OutputPage::buildBacklinkSubtitle( $title, $query )->text();
659
660 foreach ( $contains as $substr ) {
661 $this->assertContains( $substr, $str );
662 }
663
664 foreach ( $notContains as $substr ) {
665 $this->assertNotContains( $substr, $str );
666 }
667 }
668
669 /**
670 * @dataProvider provideBacklinkSubtitle
671 *
672 * @covers OutputPage::addBacklinkSubtitle
673 * @covers OutputPage::getSubtitle
674 */
675 public function testAddBacklinkSubtitle( $titles, $queries, $contains, $notContains ) {
676 $this->editPage( 'Page 1', '' );
677 $this->editPage( 'Page 2', '#REDIRECT [[Page 1]]' );
678
679 $op = $this->newInstance();
680 foreach ( $titles as $i => $unused ) {
681 $op->addBacklinkSubtitle( Title::newFromText( $titles[$i] ), $queries[$i] );
682 }
683
684 $str = $op->getSubtitle();
685
686 foreach ( $contains as $substr ) {
687 $this->assertContains( $substr, $str );
688 }
689
690 foreach ( $notContains as $substr ) {
691 $this->assertNotContains( $substr, $str );
692 }
693 }
694
695 public function provideBacklinkSubtitle() {
696 return [
697 [
698 [ 'Page 1' ],
699 [ [] ],
700 [ 'Page 1' ],
701 [ 'redirect', 'Page 2' ],
702 ],
703 [
704 [ 'Page 2' ],
705 [ [] ],
706 [ 'redirect=no' ],
707 [ 'Page 1' ],
708 ],
709 [
710 [ 'Page 1' ],
711 [ [ 'action' => 'edit' ] ],
712 [ 'action=edit' ],
713 [],
714 ],
715 [
716 [ 'Page 1', 'Page 2' ],
717 [ [], [] ],
718 [ 'Page 1', 'Page 2', "<br />\n\t\t\t\t" ],
719 [],
720 ],
721 // @todo Anything else to test?
722 ];
723 }
724
725 /**
726 * @covers OutputPage::setPrintable
727 * @covers OutputPage::isPrintable
728 */
729 public function testPrintable() {
730 $op = $this->newInstance();
731
732 $this->assertFalse( $op->isPrintable() );
733
734 $op->setPrintable();
735
736 $this->assertTrue( $op->isPrintable() );
737 }
738
739 /**
740 * @covers OutputPage::disable
741 * @covers OutputPage::isDisabled
742 */
743 public function testDisable() {
744 $op = $this->newInstance();
745
746 $this->assertFalse( $op->isDisabled() );
747 $this->assertNotSame( '', $op->output( true ) );
748
749 $op->disable();
750
751 $this->assertTrue( $op->isDisabled() );
752 $this->assertSame( '', $op->output( true ) );
753 }
754
755 /**
756 * @covers OutputPage::showNewSectionLink
757 * @covers OutputPage::addParserOutputMetadata
758 */
759 public function testShowNewSectionLink() {
760 $op = $this->newInstance();
761
762 $this->assertFalse( $op->showNewSectionLink() );
763
764 $po = new ParserOutput();
765 $po->setNewSection( true );
766 $op->addParserOutputMetadata( $po );
767
768 $this->assertTrue( $op->showNewSectionLink() );
769 }
770
771 /**
772 * @covers OutputPage::forceHideNewSectionLink
773 * @covers OutputPage::addParserOutputMetadata
774 */
775 public function testForceHideNewSectionLink() {
776 $op = $this->newInstance();
777
778 $this->assertFalse( $op->forceHideNewSectionLink() );
779
780 $po = new ParserOutput();
781 $po->hideNewSection( true );
782 $op->addParserOutputMetadata( $po );
783
784 $this->assertTrue( $op->forceHideNewSectionLink() );
785 }
786
787 /**
788 * @covers OutputPage::setSyndicated
789 * @covers OutputPage::isSyndicated
790 */
791 public function testSetSyndicated() {
792 $op = $this->newInstance();
793 $this->assertFalse( $op->isSyndicated() );
794
795 $op->setSyndicated();
796 $this->assertTrue( $op->isSyndicated() );
797
798 $op->setSyndicated( false );
799 $this->assertFalse( $op->isSyndicated() );
800 }
801
802 /**
803 * @covers OutputPage::isSyndicated
804 * @covers OutputPage::setFeedAppendQuery
805 * @covers OutputPage::addFeedLink
806 * @covers OutputPage::getSyndicationLinks()
807 */
808 public function testFeedLinks() {
809 $op = $this->newInstance();
810 $this->assertSame( [], $op->getSyndicationLinks() );
811
812 $op->addFeedLink( 'not a supported format', 'abc' );
813 $this->assertFalse( $op->isSyndicated() );
814 $this->assertSame( [], $op->getSyndicationLinks() );
815
816 $feedTypes = $op->getConfig()->get( 'AdvertisedFeedTypes' );
817
818 $op->addFeedLink( $feedTypes[0], 'def' );
819 $this->assertTrue( $op->isSyndicated() );
820 $this->assertSame( [ $feedTypes[0] => 'def' ], $op->getSyndicationLinks() );
821
822 $op->setFeedAppendQuery( false );
823 $expected = [];
824 foreach ( $feedTypes as $type ) {
825 $expected[$type] = $op->getTitle()->getLocalURL( "feed=$type" );
826 }
827 $this->assertSame( $expected, $op->getSyndicationLinks() );
828
829 $op->setFeedAppendQuery( 'apples=oranges' );
830 foreach ( $feedTypes as $type ) {
831 $expected[$type] = $op->getTitle()->getLocalURL( "feed=$type&apples=oranges" );
832 }
833 $this->assertSame( $expected, $op->getSyndicationLinks() );
834 }
835
836 /**
837 * @covers OutputPage::setArticleFlag
838 * @covers OutputPage::isArticle
839 * @covers OutputPage::setArticleRelated
840 * @covers OutputPage::isArticleRelated
841 */
842 function testArticleFlags() {
843 $op = $this->newInstance();
844 $this->assertFalse( $op->isArticle() );
845 $this->assertTrue( $op->isArticleRelated() );
846
847 $op->setArticleRelated( false );
848 $this->assertFalse( $op->isArticle() );
849 $this->assertFalse( $op->isArticleRelated() );
850
851 $op->setArticleFlag( true );
852 $this->assertTrue( $op->isArticle() );
853 $this->assertTrue( $op->isArticleRelated() );
854
855 $op->setArticleFlag( false );
856 $this->assertFalse( $op->isArticle() );
857 $this->assertTrue( $op->isArticleRelated() );
858
859 $op->setArticleFlag( true );
860 $op->setArticleRelated( false );
861 $this->assertFalse( $op->isArticle() );
862 $this->assertFalse( $op->isArticleRelated() );
863 }
864
865 /**
866 * @covers OutputPage::addLanguageLinks
867 * @covers OutputPage::setLanguageLinks
868 * @covers OutputPage::getLanguageLinks
869 * @covers OutputPage::addParserOutputMetadata
870 */
871 function testLanguageLinks() {
872 $op = $this->newInstance();
873 $this->assertSame( [], $op->getLanguageLinks() );
874
875 $op->addLanguageLinks( [ 'fr:A', 'it:B' ] );
876 $this->assertSame( [ 'fr:A', 'it:B' ], $op->getLanguageLinks() );
877
878 $op->addLanguageLinks( [ 'de:C', 'es:D' ] );
879 $this->assertSame( [ 'fr:A', 'it:B', 'de:C', 'es:D' ], $op->getLanguageLinks() );
880
881 $op->setLanguageLinks( [ 'pt:E' ] );
882 $this->assertSame( [ 'pt:E' ], $op->getLanguageLinks() );
883
884 $po = new ParserOutput();
885 $po->setLanguageLinks( [ 'he:F', 'ar:G' ] );
886 $op->addParserOutputMetadata( $po );
887 $this->assertSame( [ 'pt:E', 'he:F', 'ar:G' ], $op->getLanguageLinks() );
888 }
889
890 // @todo Are these category links tests too abstract and complicated for what they test? Would
891 // it make sense to just write out all the tests by hand with maybe some copy-and-paste?
892
893 /**
894 * @dataProvider provideGetCategories
895 *
896 * @covers OutputPage::addCategoryLinks
897 * @covers OutputPage::getCategories
898 * @covers OutputPage::getCategoryLinks
899 *
900 * @param array $args Array of form [ category name => sort key ]
901 * @param array $fakeResults Array of form [ category name => value to return from mocked
902 * LinkBatch ]
903 * @param callback $variantLinkCallback Callback to replace findVariantLink() call
904 * @param array $expectedNormal Expected return value of getCategoryLinks['normal']
905 * @param array $expectedHidden Expected return value of getCategoryLinks['hidden']
906 */
907 public function testAddCategoryLinks(
908 array $args, array $fakeResults, callable $variantLinkCallback = null,
909 array $expectedNormal, array $expectedHidden
910 ) {
911 $expectedNormal = $this->extractExpectedCategories( $expectedNormal, 'add' );
912 $expectedHidden = $this->extractExpectedCategories( $expectedHidden, 'add' );
913
914 $op = $this->setupCategoryTests( $fakeResults, $variantLinkCallback );
915
916 $op->addCategoryLinks( $args );
917
918 $this->doCategoryAsserts( $op, $expectedNormal, $expectedHidden );
919 $this->doCategoryLinkAsserts( $op, $expectedNormal, $expectedHidden );
920 }
921
922 /**
923 * @dataProvider provideGetCategories
924 *
925 * @covers OutputPage::addCategoryLinks
926 * @covers OutputPage::getCategories
927 * @covers OutputPage::getCategoryLinks
928 */
929 public function testAddCategoryLinksOneByOne(
930 array $args, array $fakeResults, callable $variantLinkCallback = null,
931 array $expectedNormal, array $expectedHidden
932 ) {
933 if ( count( $args ) <= 1 ) {
934 // @todo Should this be skipped instead of passed?
935 $this->assertTrue( true );
936 return;
937 }
938
939 $expectedNormal = $this->extractExpectedCategories( $expectedNormal, 'onebyone' );
940 $expectedHidden = $this->extractExpectedCategories( $expectedHidden, 'onebyone' );
941
942 $op = $this->setupCategoryTests( $fakeResults, $variantLinkCallback );
943
944 foreach ( $args as $key => $val ) {
945 $op->addCategoryLinks( [ $key => $val ] );
946 }
947
948 $this->doCategoryAsserts( $op, $expectedNormal, $expectedHidden );
949 $this->doCategoryLinkAsserts( $op, $expectedNormal, $expectedHidden );
950 }
951
952 /**
953 * @dataProvider provideGetCategories
954 *
955 * @covers OutputPage::setCategoryLinks
956 * @covers OutputPage::getCategories
957 * @covers OutputPage::getCategoryLinks
958 */
959 public function testSetCategoryLinks(
960 array $args, array $fakeResults, callable $variantLinkCallback = null,
961 array $expectedNormal, array $expectedHidden
962 ) {
963 $expectedNormal = $this->extractExpectedCategories( $expectedNormal, 'set' );
964 $expectedHidden = $this->extractExpectedCategories( $expectedHidden, 'set' );
965
966 $op = $this->setupCategoryTests( $fakeResults, $variantLinkCallback );
967
968 $op->setCategoryLinks( [ 'Initial page' => 'Initial page' ] );
969 $op->setCategoryLinks( $args );
970
971 // We don't reset the categories, for some reason, only the links
972 $expectedNormalCats = array_merge( [ 'Initial page' ], $expectedNormal );
973 $expectedCats = array_merge( $expectedHidden, $expectedNormalCats );
974
975 $this->doCategoryAsserts( $op, $expectedNormalCats, $expectedHidden );
976 $this->doCategoryLinkAsserts( $op, $expectedNormal, $expectedHidden );
977 }
978
979 /**
980 * @dataProvider provideGetCategories
981 *
982 * @covers OutputPage::addParserOutputMetadata
983 * @covers OutputPage::getCategories
984 * @covers OutputPage::getCategoryLinks
985 */
986 public function testParserOutputCategoryLinks(
987 array $args, array $fakeResults, callable $variantLinkCallback = null,
988 array $expectedNormal, array $expectedHidden
989 ) {
990 $expectedNormal = $this->extractExpectedCategories( $expectedNormal, 'pout' );
991 $expectedHidden = $this->extractExpectedCategories( $expectedHidden, 'pout' );
992
993 $op = $this->setupCategoryTests( $fakeResults, $variantLinkCallback );
994
995 $stubPO = $this->createParserOutputStub( 'getCategories', $args );
996
997 $op->addParserOutputMetadata( $stubPO );
998
999 $this->doCategoryAsserts( $op, $expectedNormal, $expectedHidden );
1000 $this->doCategoryLinkAsserts( $op, $expectedNormal, $expectedHidden );
1001 }
1002
1003 /**
1004 * We allow different expectations for different tests as an associative array, like
1005 * [ 'set' => [ ... ], 'default' => [ ... ] ] if setCategoryLinks() will give a different
1006 * result.
1007 */
1008 private function extractExpectedCategories( array $expected, $key ) {
1009 if ( !$expected || isset( $expected[0] ) ) {
1010 return $expected;
1011 }
1012 return $expected[$key] ?? $expected['default'];
1013 }
1014
1015 private function setupCategoryTests(
1016 array $fakeResults, callable $variantLinkCallback = null
1017 ) : OutputPage {
1018 $this->setMwGlobals( 'wgUsePigLatinVariant', true );
1019
1020 $op = $this->getMockBuilder( OutputPage::class )
1021 ->setConstructorArgs( [ new RequestContext() ] )
1022 ->setMethods( [ 'addCategoryLinksToLBAndGetResult' ] )
1023 ->getMock();
1024
1025 $op->expects( $this->any() )
1026 ->method( 'addCategoryLinksToLBAndGetResult' )
1027 ->will( $this->returnCallback( function ( array $categories ) use ( $fakeResults ) {
1028 $return = [];
1029 foreach ( $categories as $category => $unused ) {
1030 if ( isset( $fakeResults[$category] ) ) {
1031 $return[] = $fakeResults[$category];
1032 }
1033 }
1034 return new FakeResultWrapper( $return );
1035 } ) );
1036
1037 if ( $variantLinkCallback ) {
1038 $mockContLang = $this->getMockBuilder( Language::class )
1039 ->setConstructorArgs( [ 'en' ] )
1040 ->setMethods( [ 'findVariantLink' ] )
1041 ->getMock();
1042 $mockContLang->expects( $this->any() )
1043 ->method( 'findVariantLink' )
1044 ->will( $this->returnCallback( $variantLinkCallback ) );
1045 $this->setContentLang( $mockContLang );
1046 }
1047
1048 $this->assertSame( [], $op->getCategories() );
1049
1050 return $op;
1051 }
1052
1053 private function doCategoryAsserts( $op, $expectedNormal, $expectedHidden ) {
1054 $this->assertSame( array_merge( $expectedHidden, $expectedNormal ), $op->getCategories() );
1055 $this->assertSame( $expectedNormal, $op->getCategories( 'normal' ) );
1056 $this->assertSame( $expectedHidden, $op->getCategories( 'hidden' ) );
1057 }
1058
1059 private function doCategoryLinkAsserts( $op, $expectedNormal, $expectedHidden ) {
1060 $catLinks = $op->getCategoryLinks();
1061 $this->assertSame( (bool)$expectedNormal + (bool)$expectedHidden, count( $catLinks ) );
1062 if ( $expectedNormal ) {
1063 $this->assertSame( count( $expectedNormal ), count( $catLinks['normal'] ) );
1064 }
1065 if ( $expectedHidden ) {
1066 $this->assertSame( count( $expectedHidden ), count( $catLinks['hidden'] ) );
1067 }
1068
1069 foreach ( $expectedNormal as $i => $name ) {
1070 $this->assertContains( $name, $catLinks['normal'][$i] );
1071 }
1072 foreach ( $expectedHidden as $i => $name ) {
1073 $this->assertContains( $name, $catLinks['hidden'][$i] );
1074 }
1075 }
1076
1077 public function provideGetCategories() {
1078 return [
1079 'No categories' => [ [], [], null, [], [] ],
1080 'Simple test' => [
1081 [ 'Test1' => 'Some sortkey', 'Test2' => 'A different sortkey' ],
1082 [ 'Test1' => (object)[ 'pp_value' => 1, 'page_title' => 'Test1' ],
1083 'Test2' => (object)[ 'page_title' => 'Test2' ] ],
1084 null,
1085 [ 'Test2' ],
1086 [ 'Test1' ],
1087 ],
1088 'Invalid title' => [
1089 [ '[' => '[', 'Test' => 'Test' ],
1090 [ 'Test' => (object)[ 'page_title' => 'Test' ] ],
1091 null,
1092 [ 'Test' ],
1093 [],
1094 ],
1095 'Variant link' => [
1096 [ 'Test' => 'Test', 'Estay' => 'Estay' ],
1097 [ 'Test' => (object)[ 'page_title' => 'Test' ] ],
1098 function ( &$link, &$title ) {
1099 if ( $link === 'Estay' ) {
1100 $link = 'Test';
1101 $title = Title::makeTitleSafe( NS_CATEGORY, $link );
1102 }
1103 },
1104 // For adding one by one, the variant gets added as well as the original category,
1105 // but if you add them all together the second time gets skipped.
1106 [ 'onebyone' => [ 'Test', 'Test' ], 'default' => [ 'Test' ] ],
1107 [],
1108 ],
1109 ];
1110 }
1111
1112 /**
1113 * @covers OutputPage::getCategories
1114 */
1115 public function testGetCategoriesInvalid() {
1116 $this->setExpectedException( InvalidArgumentException::class,
1117 'Invalid category type given: hiddne' );
1118
1119 $op = $this->newInstance();
1120 $op->getCategories( 'hiddne' );
1121 }
1122
1123 // @todo Should we test addCategoryLinksToLBAndGetResult? If so, how? Insert some test rows in
1124 // the DB?
1125
1126 /**
1127 * @covers OutputPage::setIndicators
1128 * @covers OutputPage::getIndicators
1129 * @covers OutputPage::addParserOutputMetadata
1130 */
1131 public function testIndicators() {
1132 $op = $this->newInstance();
1133 $this->assertSame( [], $op->getIndicators() );
1134
1135 $op->setIndicators( [] );
1136 $this->assertSame( [], $op->getIndicators() );
1137
1138 // Test sorting alphabetically
1139 $op->setIndicators( [ 'b' => 'x', 'a' => 'y' ] );
1140 $this->assertSame( [ 'a' => 'y', 'b' => 'x' ], $op->getIndicators() );
1141
1142 // Test overwriting existing keys
1143 $op->setIndicators( [ 'c' => 'z', 'a' => 'w' ] );
1144 $this->assertSame( [ 'a' => 'w', 'b' => 'x', 'c' => 'z' ], $op->getIndicators() );
1145
1146 // Test with ParserOutput
1147 $stubPO = $this->createParserOutputStub( 'getIndicators', [ 'c' => 'u', 'd' => 'v' ] );
1148 $op->addParserOutputMetadata( $stubPO );
1149 $this->assertSame( [ 'a' => 'w', 'b' => 'x', 'c' => 'u', 'd' => 'v' ],
1150 $op->getIndicators() );
1151 }
1152
1153 /**
1154 * @covers OutputPage::addHelpLink
1155 * @covers OutputPage::getIndicators
1156 */
1157 public function testAddHelpLink() {
1158 $op = $this->newInstance();
1159
1160 $op->addHelpLink( 'Manual:PHP unit testing' );
1161 $indicators = $op->getIndicators();
1162 $this->assertSame( [ 'mw-helplink' ], array_keys( $indicators ) );
1163 $this->assertContains( 'Manual:PHP_unit_testing', $indicators['mw-helplink'] );
1164
1165 $op->addHelpLink( 'https://phpunit.de', true );
1166 $indicators = $op->getIndicators();
1167 $this->assertSame( [ 'mw-helplink' ], array_keys( $indicators ) );
1168 $this->assertContains( 'https://phpunit.de', $indicators['mw-helplink'] );
1169 $this->assertNotContains( 'mediawiki', $indicators['mw-helplink'] );
1170 $this->assertNotContains( 'Manual:PHP', $indicators['mw-helplink'] );
1171 }
1172
1173 /**
1174 * @covers OutputPage::prependHTML
1175 * @covers OutputPage::addHTML
1176 * @covers OutputPage::addElement
1177 * @covers OutputPage::clearHTML
1178 * @covers OutputPage::getHTML
1179 */
1180 public function testBodyHTML() {
1181 $op = $this->newInstance();
1182 $this->assertSame( '', $op->getHTML() );
1183
1184 $op->addHTML( 'a' );
1185 $this->assertSame( 'a', $op->getHTML() );
1186
1187 $op->addHTML( 'b' );
1188 $this->assertSame( 'ab', $op->getHTML() );
1189
1190 $op->prependHTML( 'c' );
1191 $this->assertSame( 'cab', $op->getHTML() );
1192
1193 $op->addElement( 'p', [ 'id' => 'foo' ], 'd' );
1194 $this->assertSame( 'cab<p id="foo">d</p>', $op->getHTML() );
1195
1196 $op->clearHTML();
1197 $this->assertSame( '', $op->getHTML() );
1198 }
1199
1200 /**
1201 * @dataProvider provideRevisionId
1202 * @covers OutputPage::setRevisionId
1203 * @covers OutputPage::getRevisionId
1204 */
1205 public function testRevisionId( $newVal, $expected ) {
1206 $op = $this->newInstance();
1207
1208 $this->assertNull( $op->setRevisionId( $newVal ) );
1209 $this->assertSame( $expected, $op->getRevisionId() );
1210 $this->assertSame( $expected, $op->setRevisionId( null ) );
1211 $this->assertNull( $op->getRevisionId() );
1212 }
1213
1214 public function provideRevisionId() {
1215 return [
1216 [ null, null ],
1217 [ 7, 7 ],
1218 [ -1, -1 ],
1219 [ 3.2, 3 ],
1220 [ '0', 0 ],
1221 [ '32% finished', 32 ],
1222 [ false, 0 ],
1223 ];
1224 }
1225
1226 /**
1227 * @covers OutputPage::setRevisionTimestamp
1228 * @covers OutputPage::getRevisionTimestamp
1229 */
1230 public function testRevisionTimestamp() {
1231 $op = $this->newInstance();
1232 $this->assertNull( $op->getRevisionTimestamp() );
1233
1234 $this->assertNull( $op->setRevisionTimestamp( 'abc' ) );
1235 $this->assertSame( 'abc', $op->getRevisionTimestamp() );
1236 $this->assertSame( 'abc', $op->setRevisionTimestamp( null ) );
1237 $this->assertNull( $op->getRevisionTimestamp() );
1238 }
1239
1240 /**
1241 * @covers OutputPage::setFileVersion
1242 * @covers OutputPage::getFileVersion
1243 */
1244 public function testFileVersion() {
1245 $op = $this->newInstance();
1246 $this->assertNull( $op->getFileVersion() );
1247
1248 $stubFile = $this->createMock( File::class );
1249 $stubFile->method( 'exists' )->willReturn( true );
1250 $stubFile->method( 'getTimestamp' )->willReturn( '12211221123321' );
1251 $stubFile->method( 'getSha1' )->willReturn( 'bf3ffa7047dc080f5855377a4f83cd18887e3b05' );
1252
1253 $op->setFileVersion( $stubFile );
1254
1255 $this->assertEquals(
1256 [ 'time' => '12211221123321', 'sha1' => 'bf3ffa7047dc080f5855377a4f83cd18887e3b05' ],
1257 $op->getFileVersion()
1258 );
1259
1260 $stubMissingFile = $this->createMock( File::class );
1261 $stubMissingFile->method( 'exists' )->willReturn( false );
1262
1263 $op->setFileVersion( $stubMissingFile );
1264 $this->assertNull( $op->getFileVersion() );
1265
1266 $op->setFileVersion( $stubFile );
1267 $this->assertNotNull( $op->getFileVersion() );
1268
1269 $op->setFileVersion( null );
1270 $this->assertNull( $op->getFileVersion() );
1271 }
1272
1273 private function createParserOutputStub( $method = '', $retVal = [] ) {
1274 $pOut = $this->getMock( ParserOutput::class );
1275 if ( $method !== '' ) {
1276 $pOut->method( $method )->willReturn( $retVal );
1277 }
1278
1279 $arrayReturningMethods = [
1280 'getCategories',
1281 'getFileSearchOptions',
1282 'getHeadItems',
1283 'getIndicators',
1284 'getLanguageLinks',
1285 'getOutputHooks',
1286 'getTemplateIds',
1287 ];
1288
1289 foreach ( $arrayReturningMethods as $method ) {
1290 $pOut->method( $method )->willReturn( [] );
1291 }
1292
1293 return $pOut;
1294 }
1295
1296 /**
1297 * @covers OutputPage::getTemplateIds
1298 * @covers OutputPage::addParserOutputMetadata
1299 */
1300 public function testTemplateIds() {
1301 $op = $this->newInstance();
1302 $this->assertSame( [], $op->getTemplateIds() );
1303
1304 // Test with no template id's
1305 $stubPOEmpty = $this->createParserOutputStub();
1306 $op->addParserOutputMetadata( $stubPOEmpty );
1307 $this->assertSame( [], $op->getTemplateIds() );
1308
1309 // Test with some arbitrary template id's
1310 $ids = [
1311 NS_MAIN => [ 'A' => 3, 'B' => 17 ],
1312 NS_TALK => [ 'C' => 31 ],
1313 NS_MEDIA => [ 'D' => -1 ],
1314 ];
1315
1316 $stubPO1 = $this->createParserOutputStub( 'getTemplateIds', $ids );
1317
1318 $op->addParserOutputMetadata( $stubPO1 );
1319 $this->assertSame( $ids, $op->getTemplateIds() );
1320
1321 // Test merging with a second set of id's
1322 $stubPO2 = $this->createParserOutputStub( 'getTemplateIds', [
1323 NS_MAIN => [ 'E' => 1234 ],
1324 NS_PROJECT => [ 'F' => 5678 ],
1325 ] );
1326
1327 $finalIds = [
1328 NS_MAIN => [ 'E' => 1234, 'A' => 3, 'B' => 17 ],
1329 NS_TALK => [ 'C' => 31 ],
1330 NS_MEDIA => [ 'D' => -1 ],
1331 NS_PROJECT => [ 'F' => 5678 ],
1332 ];
1333
1334 $op->addParserOutputMetadata( $stubPO2 );
1335 $this->assertSame( $finalIds, $op->getTemplateIds() );
1336
1337 // Test merging with an empty set of id's
1338 $op->addParserOutputMetadata( $stubPOEmpty );
1339 $this->assertSame( $finalIds, $op->getTemplateIds() );
1340 }
1341
1342 /**
1343 * @covers OutputPage::getFileSearchOptions
1344 * @covers OutputPage::addParserOutputMetadata
1345 */
1346 public function testFileSearchOptions() {
1347 $op = $this->newInstance();
1348 $this->assertSame( [], $op->getFileSearchOptions() );
1349
1350 // Test with no files
1351 $stubPOEmpty = $this->createParserOutputStub();
1352
1353 $op->addParserOutputMetadata( $stubPOEmpty );
1354 $this->assertSame( [], $op->getFileSearchOptions() );
1355
1356 // Test with some arbitrary files
1357 $files1 = [
1358 'A' => [ 'time' => null, 'sha1' => '' ],
1359 'B' => [
1360 'time' => '12211221123321',
1361 'sha1' => 'bf3ffa7047dc080f5855377a4f83cd18887e3b05',
1362 ],
1363 ];
1364
1365 $stubPO1 = $this->createParserOutputStub( 'getFileSearchOptions', $files1 );
1366
1367 $op->addParserOutputMetadata( $stubPO1 );
1368 $this->assertSame( $files1, $op->getFileSearchOptions() );
1369
1370 // Test merging with a second set of files
1371 $files2 = [
1372 'C' => [ 'time' => null, 'sha1' => '' ],
1373 'B' => [ 'time' => null, 'sha1' => '' ],
1374 ];
1375
1376 $stubPO2 = $this->createParserOutputStub( 'getFileSearchOptions', $files2 );
1377
1378 $op->addParserOutputMetadata( $stubPO2 );
1379 $this->assertSame( array_merge( $files1, $files2 ), $op->getFileSearchOptions() );
1380
1381 // Test merging with an empty set of files
1382 $op->addParserOutputMetadata( $stubPOEmpty );
1383 $this->assertSame( array_merge( $files1, $files2 ), $op->getFileSearchOptions() );
1384 }
1385
1386 /**
1387 * @dataProvider provideAddWikiText
1388 * @covers OutputPage::addWikiText
1389 * @covers OutputPage::addWikiTextWithTitle
1390 * @covers OutputPage::addWikiTextTitle
1391 * @covers OutputPage::getHTML
1392 */
1393 public function testAddWikiText( $method, array $args, $expected ) {
1394 $op = $this->newInstance();
1395 $this->assertSame( '', $op->getHTML() );
1396
1397 if ( in_array(
1398 $method,
1399 [ 'addWikiTextWithTitle', 'addWikiTextTitleTidy', 'addWikiTextTitle' ]
1400 ) && count( $args ) >= 2 && $args[1] === null ) {
1401 // Special placeholder because we can't get the actual title in the provider
1402 $args[1] = $op->getTitle();
1403 }
1404
1405 $op->$method( ...$args );
1406 $this->assertSame( $expected, $op->getHTML() );
1407 }
1408
1409 public function provideAddWikiText() {
1410 $tests = [
1411 'addWikiText' => [
1412 'Simple wikitext' => [
1413 [ "'''Bold'''" ],
1414 "<p><b>Bold</b>\n</p>",
1415 ], 'List at start' => [
1416 [ '* List' ],
1417 "<ul><li>List</li></ul>\n",
1418 ], 'List not at start' => [
1419 [ '* Not a list', false ],
1420 '* Not a list',
1421 ], 'Non-interface' => [
1422 [ "'''Bold'''", true, false ],
1423 "<div class=\"mw-parser-output\"><p><b>Bold</b>\n</p></div>",
1424 ], 'No section edit links' => [
1425 [ '== Title ==' ],
1426 "<h2><span class=\"mw-headline\" id=\"Title\">Title</span></h2>\n",
1427 ],
1428 ],
1429 'addWikiTextWithTitle' => [
1430 'With title at start' => [
1431 [ '* {{PAGENAME}}', Title::newFromText( 'Talk:Some page' ) ],
1432 "<div class=\"mw-parser-output\"><ul><li>Some page</li></ul>\n</div>",
1433 ], 'With title at start' => [
1434 [ '* {{PAGENAME}}', Title::newFromText( 'Talk:Some page' ), false ],
1435 "<div class=\"mw-parser-output\">* Some page</div>",
1436 ],
1437 ],
1438 ];
1439
1440 // Test all the others on addWikiTextTitle as well
1441 foreach ( $tests['addWikiText'] as $key => $val ) {
1442 $args = [ $val[0][0], null, $val[0][1] ?? true, false, $val[0][2] ?? true ];
1443 $tests['addWikiTextTitle']["$key (addWikiTextTitle)"] =
1444 array_merge( [ $args ], array_slice( $val, 1 ) );
1445 }
1446 foreach ( $tests['addWikiTextWithTitle'] as $key => $val ) {
1447 $args = [ $val[0][0], $val[0][1], $val[0][2] ?? true ];
1448 $tests['addWikiTextTitle']["$key (addWikiTextTitle)"] =
1449 array_merge( [ $args ], array_slice( $val, 1 ) );
1450 }
1451
1452 // We have to reformat our array to match what PHPUnit wants
1453 $ret = [];
1454 foreach ( $tests as $key => $subarray ) {
1455 foreach ( $subarray as $subkey => $val ) {
1456 $val = array_merge( [ $key ], $val );
1457 $ret[$subkey] = $val;
1458 }
1459 }
1460
1461 return $ret;
1462 }
1463
1464 /**
1465 * @covers OutputPage::addWikiText
1466 */
1467 public function testAddWikiTextNoTitle() {
1468 $this->setExpectedException( MWException::class, 'Title is null' );
1469
1470 $op = $this->newInstance( [], null, 'notitle' );
1471 $op->addWikiText( 'a' );
1472 }
1473
1474 // @todo How should we cover the Tidy variants?
1475
1476 /**
1477 * @covers OutputPage::addParserOutputMetadata
1478 */
1479 public function testNoGallery() {
1480 $op = $this->newInstance();
1481 $this->assertFalse( $op->mNoGallery );
1482
1483 $stubPO1 = $this->createParserOutputStub( 'getNoGallery', true );
1484 $op->addParserOutputMetadata( $stubPO1 );
1485 $this->assertTrue( $op->mNoGallery );
1486
1487 $stubPO2 = $this->createParserOutputStub( 'getNoGallery', false );
1488 $op->addParserOutputMetadata( $stubPO2 );
1489 $this->assertFalse( $op->mNoGallery );
1490 }
1491
1492 // @todo Make sure to test the following in addParserOutputMetadata() as well when we add tests
1493 // for them:
1494 // * enableClientCache()
1495 // * addModules()
1496 // * addModuleScripts()
1497 // * addModuleStyles()
1498 // * addJsConfigVars()
1499 // * preventClickJacking()
1500 // Otherwise those lines of addParserOutputMetadata() will be reported as covered, but we won't
1501 // be testing they actually work.
1502
1503 /**
1504 * @covers OutputPage::haveCacheVaryCookies
1505 */
1506 public function testHaveCacheVaryCookies() {
1507 $request = new FauxRequest();
1508 $context = new RequestContext();
1509 $context->setRequest( $request );
1510 $op = new OutputPage( $context );
1511
1512 // No cookies are set.
1513 $this->assertFalse( $op->haveCacheVaryCookies() );
1514
1515 // 'Token' is present but empty, so it shouldn't count.
1516 $request->setCookie( 'Token', '' );
1517 $this->assertFalse( $op->haveCacheVaryCookies() );
1518
1519 // 'Token' present and nonempty.
1520 $request->setCookie( 'Token', '123' );
1521 $this->assertTrue( $op->haveCacheVaryCookies() );
1522 }
1523
1524 /**
1525 * @dataProvider provideVaryHeaders
1526 *
1527 * @covers OutputPage::addVaryHeader
1528 * @covers OutputPage::getVaryHeader
1529 * @covers OutputPage::getKeyHeader
1530 */
1531 public function testVaryHeaders( $calls, $vary, $key ) {
1532 // get rid of default Vary fields
1533 $op = $this->getMockBuilder( OutputPage::class )
1534 ->setConstructorArgs( [ new RequestContext() ] )
1535 ->setMethods( [ 'getCacheVaryCookies' ] )
1536 ->getMock();
1537 $op->expects( $this->any() )
1538 ->method( 'getCacheVaryCookies' )
1539 ->will( $this->returnValue( [] ) );
1540 TestingAccessWrapper::newFromObject( $op )->mVaryHeader = [];
1541
1542 foreach ( $calls as $call ) {
1543 call_user_func_array( [ $op, 'addVaryHeader' ], $call );
1544 }
1545 $this->assertEquals( $vary, $op->getVaryHeader(), 'Vary:' );
1546 $this->assertEquals( $key, $op->getKeyHeader(), 'Key:' );
1547 }
1548
1549 public function provideVaryHeaders() {
1550 // note: getKeyHeader() automatically adds Vary: Cookie
1551 return [
1552 [ // single header
1553 [
1554 [ 'Cookie' ],
1555 ],
1556 'Vary: Cookie',
1557 'Key: Cookie',
1558 ],
1559 [ // non-unique headers
1560 [
1561 [ 'Cookie' ],
1562 [ 'Accept-Language' ],
1563 [ 'Cookie' ],
1564 ],
1565 'Vary: Cookie, Accept-Language',
1566 'Key: Cookie,Accept-Language',
1567 ],
1568 [ // two headers with single options
1569 [
1570 [ 'Cookie', [ 'param=phpsessid' ] ],
1571 [ 'Accept-Language', [ 'substr=en' ] ],
1572 ],
1573 'Vary: Cookie, Accept-Language',
1574 'Key: Cookie;param=phpsessid,Accept-Language;substr=en',
1575 ],
1576 [ // one header with multiple options
1577 [
1578 [ 'Cookie', [ 'param=phpsessid', 'param=userId' ] ],
1579 ],
1580 'Vary: Cookie',
1581 'Key: Cookie;param=phpsessid;param=userId',
1582 ],
1583 [ // Duplicate option
1584 [
1585 [ 'Cookie', [ 'param=phpsessid' ] ],
1586 [ 'Cookie', [ 'param=phpsessid' ] ],
1587 [ 'Accept-Language', [ 'substr=en', 'substr=en' ] ],
1588 ],
1589 'Vary: Cookie, Accept-Language',
1590 'Key: Cookie;param=phpsessid,Accept-Language;substr=en',
1591 ],
1592 [ // Same header, different options
1593 [
1594 [ 'Cookie', [ 'param=phpsessid' ] ],
1595 [ 'Cookie', [ 'param=userId' ] ],
1596 ],
1597 'Vary: Cookie',
1598 'Key: Cookie;param=phpsessid;param=userId',
1599 ],
1600 ];
1601 }
1602
1603 /**
1604 * @dataProvider provideLinkHeaders
1605 *
1606 * @covers OutputPage::addLinkHeader
1607 * @covers OutputPage::getLinkHeader
1608 */
1609 public function testLinkHeaders( $headers, $result ) {
1610 $op = $this->newInstance();
1611
1612 foreach ( $headers as $header ) {
1613 $op->addLinkHeader( $header );
1614 }
1615
1616 $this->assertEquals( $result, $op->getLinkHeader() );
1617 }
1618
1619 public function provideLinkHeaders() {
1620 return [
1621 [
1622 [],
1623 false
1624 ],
1625 [
1626 [ '<https://foo/bar.jpg>;rel=preload;as=image' ],
1627 'Link: <https://foo/bar.jpg>;rel=preload;as=image',
1628 ],
1629 [
1630 [ '<https://foo/bar.jpg>;rel=preload;as=image','<https://foo/baz.jpg>;rel=preload;as=image' ],
1631 'Link: <https://foo/bar.jpg>;rel=preload;as=image,<https://foo/baz.jpg>;rel=preload;as=image',
1632 ],
1633 ];
1634 }
1635
1636 /**
1637 * See ResourceLoaderClientHtmlTest for full coverage.
1638 *
1639 * @dataProvider provideMakeResourceLoaderLink
1640 *
1641 * @covers OutputPage::makeResourceLoaderLink
1642 */
1643 public function testMakeResourceLoaderLink( $args, $expectedHtml ) {
1644 $this->setMwGlobals( [
1645 'wgResourceLoaderDebug' => false,
1646 'wgLoadScript' => 'http://127.0.0.1:8080/w/load.php',
1647 'wgCSPReportOnlyHeader' => true,
1648 ] );
1649 $class = new ReflectionClass( OutputPage::class );
1650 $method = $class->getMethod( 'makeResourceLoaderLink' );
1651 $method->setAccessible( true );
1652 $ctx = new RequestContext();
1653 $ctx->setSkin( SkinFactory::getDefaultInstance()->makeSkin( 'fallback' ) );
1654 $ctx->setLanguage( 'en' );
1655 $out = new OutputPage( $ctx );
1656 $nonce = $class->getProperty( 'CSPNonce' );
1657 $nonce->setAccessible( true );
1658 $nonce->setValue( $out, 'secret' );
1659 $rl = $out->getResourceLoader();
1660 $rl->setMessageBlobStore( new NullMessageBlobStore() );
1661 $rl->register( [
1662 'test.foo' => new ResourceLoaderTestModule( [
1663 'script' => 'mw.test.foo( { a: true } );',
1664 'styles' => '.mw-test-foo { content: "style"; }',
1665 ] ),
1666 'test.bar' => new ResourceLoaderTestModule( [
1667 'script' => 'mw.test.bar( { a: true } );',
1668 'styles' => '.mw-test-bar { content: "style"; }',
1669 ] ),
1670 'test.baz' => new ResourceLoaderTestModule( [
1671 'script' => 'mw.test.baz( { a: true } );',
1672 'styles' => '.mw-test-baz { content: "style"; }',
1673 ] ),
1674 'test.quux' => new ResourceLoaderTestModule( [
1675 'script' => 'mw.test.baz( { token: 123 } );',
1676 'styles' => '/* pref-animate=off */ .mw-icon { transition: none; }',
1677 'group' => 'private',
1678 ] ),
1679 'test.noscript' => new ResourceLoaderTestModule( [
1680 'styles' => '.stuff { color: red; }',
1681 'group' => 'noscript',
1682 ] ),
1683 'test.group.foo' => new ResourceLoaderTestModule( [
1684 'script' => 'mw.doStuff( "foo" );',
1685 'group' => 'foo',
1686 ] ),
1687 'test.group.bar' => new ResourceLoaderTestModule( [
1688 'script' => 'mw.doStuff( "bar" );',
1689 'group' => 'bar',
1690 ] ),
1691 ] );
1692 $links = $method->invokeArgs( $out, $args );
1693 $actualHtml = strval( $links );
1694 $this->assertEquals( $expectedHtml, $actualHtml );
1695 }
1696
1697 public static function provideMakeResourceLoaderLink() {
1698 // phpcs:disable Generic.Files.LineLength
1699 return [
1700 // Single only=scripts load
1701 [
1702 [ 'test.foo', ResourceLoaderModule::TYPE_SCRIPTS ],
1703 "<script nonce=\"secret\">(window.RLQ=window.RLQ||[]).push(function(){"
1704 . 'mw.loader.load("http://127.0.0.1:8080/w/load.php?debug=false\u0026lang=en\u0026modules=test.foo\u0026only=scripts\u0026skin=fallback");'
1705 . "});</script>"
1706 ],
1707 // Multiple only=styles load
1708 [
1709 [ [ 'test.baz', 'test.foo', 'test.bar' ], ResourceLoaderModule::TYPE_STYLES ],
1710
1711 '<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"/>'
1712 ],
1713 // Private embed (only=scripts)
1714 [
1715 [ 'test.quux', ResourceLoaderModule::TYPE_SCRIPTS ],
1716 "<script nonce=\"secret\">(window.RLQ=window.RLQ||[]).push(function(){"
1717 . "mw.test.baz({token:123});\nmw.loader.state({\"test.quux\":\"ready\"});"
1718 . "});</script>"
1719 ],
1720 // Load private module (combined)
1721 [
1722 [ 'test.quux', ResourceLoaderModule::TYPE_COMBINED ],
1723 "<script nonce=\"secret\">(window.RLQ=window.RLQ||[]).push(function(){"
1724 . "mw.loader.implement(\"test.quux@1ev0ijv\",function($,jQuery,require,module){"
1725 . "mw.test.baz({token:123});},{\"css\":[\".mw-icon{transition:none}"
1726 . "\"]});});</script>"
1727 ],
1728 // Load no modules
1729 [
1730 [ [], ResourceLoaderModule::TYPE_COMBINED ],
1731 '',
1732 ],
1733 // noscript group
1734 [
1735 [ 'test.noscript', ResourceLoaderModule::TYPE_STYLES ],
1736 '<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>'
1737 ],
1738 // Load two modules in separate groups
1739 [
1740 [ [ 'test.group.foo', 'test.group.bar' ], ResourceLoaderModule::TYPE_COMBINED ],
1741 "<script nonce=\"secret\">(window.RLQ=window.RLQ||[]).push(function(){"
1742 . 'mw.loader.load("http://127.0.0.1:8080/w/load.php?debug=false\u0026lang=en\u0026modules=test.group.bar\u0026skin=fallback");'
1743 . 'mw.loader.load("http://127.0.0.1:8080/w/load.php?debug=false\u0026lang=en\u0026modules=test.group.foo\u0026skin=fallback");'
1744 . "});</script>"
1745 ],
1746 ];
1747 // phpcs:enable
1748 }
1749
1750 /**
1751 * @dataProvider provideBuildExemptModules
1752 *
1753 * @covers OutputPage::buildExemptModules
1754 */
1755 public function testBuildExemptModules( array $exemptStyleModules, $expect ) {
1756 $this->setMwGlobals( [
1757 'wgResourceLoaderDebug' => false,
1758 'wgLoadScript' => '/w/load.php',
1759 // Stub wgCacheEpoch as it influences getVersionHash used for the
1760 // urls in the expected HTML
1761 'wgCacheEpoch' => '20140101000000',
1762 ] );
1763
1764 // Set up stubs
1765 $ctx = new RequestContext();
1766 $ctx->setSkin( SkinFactory::getDefaultInstance()->makeSkin( 'fallback' ) );
1767 $ctx->setLanguage( 'en' );
1768 $op = $this->getMockBuilder( OutputPage::class )
1769 ->setConstructorArgs( [ $ctx ] )
1770 ->setMethods( [ 'buildCssLinksArray' ] )
1771 ->getMock();
1772 $op->expects( $this->any() )
1773 ->method( 'buildCssLinksArray' )
1774 ->willReturn( [] );
1775 $rl = $op->getResourceLoader();
1776 $rl->setMessageBlobStore( new NullMessageBlobStore() );
1777
1778 // Register custom modules
1779 $rl->register( [
1780 'example.site.a' => new ResourceLoaderTestModule( [ 'group' => 'site' ] ),
1781 'example.site.b' => new ResourceLoaderTestModule( [ 'group' => 'site' ] ),
1782 'example.user' => new ResourceLoaderTestModule( [ 'group' => 'user' ] ),
1783 ] );
1784
1785 $op = TestingAccessWrapper::newFromObject( $op );
1786 $op->rlExemptStyleModules = $exemptStyleModules;
1787 $this->assertEquals(
1788 $expect,
1789 strval( $op->buildExemptModules() )
1790 );
1791 }
1792
1793 public static function provideBuildExemptModules() {
1794 // phpcs:disable Generic.Files.LineLength
1795 return [
1796 'empty' => [
1797 'exemptStyleModules' => [],
1798 '<meta name="ResourceLoaderDynamicStyles" content=""/>',
1799 ],
1800 'empty sets' => [
1801 'exemptStyleModules' => [ 'site' => [], 'noscript' => [], 'private' => [], 'user' => [] ],
1802 '<meta name="ResourceLoaderDynamicStyles" content=""/>',
1803 ],
1804 'default logged-out' => [
1805 'exemptStyleModules' => [ 'site' => [ 'site.styles' ] ],
1806 '<meta name="ResourceLoaderDynamicStyles" content=""/>' . "\n" .
1807 '<link rel="stylesheet" href="/w/load.php?debug=false&amp;lang=en&amp;modules=site.styles&amp;only=styles&amp;skin=fallback"/>',
1808 ],
1809 'default logged-in' => [
1810 'exemptStyleModules' => [ 'site' => [ 'site.styles' ], 'user' => [ 'user.styles' ] ],
1811 '<meta name="ResourceLoaderDynamicStyles" content=""/>' . "\n" .
1812 '<link rel="stylesheet" href="/w/load.php?debug=false&amp;lang=en&amp;modules=site.styles&amp;only=styles&amp;skin=fallback"/>' . "\n" .
1813 '<link rel="stylesheet" href="/w/load.php?debug=false&amp;lang=en&amp;modules=user.styles&amp;only=styles&amp;skin=fallback&amp;version=1ai9g6t"/>',
1814 ],
1815 'custom modules' => [
1816 'exemptStyleModules' => [
1817 'site' => [ 'site.styles', 'example.site.a', 'example.site.b' ],
1818 'user' => [ 'user.styles', 'example.user' ],
1819 ],
1820 '<meta name="ResourceLoaderDynamicStyles" content=""/>' . "\n" .
1821 '<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" .
1822 '<link rel="stylesheet" href="/w/load.php?debug=false&amp;lang=en&amp;modules=site.styles&amp;only=styles&amp;skin=fallback"/>' . "\n" .
1823 '<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" .
1824 '<link rel="stylesheet" href="/w/load.php?debug=false&amp;lang=en&amp;modules=user.styles&amp;only=styles&amp;skin=fallback&amp;version=1ai9g6t"/>',
1825 ],
1826 ];
1827 // phpcs:enable
1828 }
1829
1830 /**
1831 * @dataProvider provideTransformFilePath
1832 * @covers OutputPage::transformFilePath
1833 * @covers OutputPage::transformResourcePath
1834 */
1835 public function testTransformResourcePath( $baseDir, $basePath, $uploadDir = null,
1836 $uploadPath = null, $path = null, $expected = null
1837 ) {
1838 if ( $path === null ) {
1839 // Skip optional $uploadDir and $uploadPath
1840 $path = $uploadDir;
1841 $expected = $uploadPath;
1842 $uploadDir = "$baseDir/images";
1843 $uploadPath = "$basePath/images";
1844 }
1845 $this->setMwGlobals( 'IP', $baseDir );
1846 $conf = new HashConfig( [
1847 'ResourceBasePath' => $basePath,
1848 'UploadDirectory' => $uploadDir,
1849 'UploadPath' => $uploadPath,
1850 ] );
1851
1852 // Some of these paths don't exist and will cause warnings
1853 Wikimedia\suppressWarnings();
1854 $actual = OutputPage::transformResourcePath( $conf, $path );
1855 Wikimedia\restoreWarnings();
1856
1857 $this->assertEquals( $expected ?: $path, $actual );
1858 }
1859
1860 public static function provideTransformFilePath() {
1861 $baseDir = dirname( __DIR__ ) . '/data/media';
1862 return [
1863 // File that matches basePath, and exists. Hash found and appended.
1864 [
1865 'baseDir' => $baseDir, 'basePath' => '/w',
1866 '/w/test.jpg',
1867 '/w/test.jpg?edcf2'
1868 ],
1869 // File that matches basePath, but not found on disk. Empty query.
1870 [
1871 'baseDir' => $baseDir, 'basePath' => '/w',
1872 '/w/unknown.png',
1873 '/w/unknown.png?'
1874 ],
1875 // File not matching basePath. Ignored.
1876 [
1877 'baseDir' => $baseDir, 'basePath' => '/w',
1878 '/files/test.jpg'
1879 ],
1880 // Empty string. Ignored.
1881 [
1882 'baseDir' => $baseDir, 'basePath' => '/w',
1883 '',
1884 ''
1885 ],
1886 // Similar path, but with domain component. Ignored.
1887 [
1888 'baseDir' => $baseDir, 'basePath' => '/w',
1889 '//example.org/w/test.jpg'
1890 ],
1891 [
1892 'baseDir' => $baseDir, 'basePath' => '/w',
1893 'https://example.org/w/test.jpg'
1894 ],
1895 // Unrelated path with domain component. Ignored.
1896 [
1897 'baseDir' => $baseDir, 'basePath' => '/w',
1898 'https://example.org/files/test.jpg'
1899 ],
1900 [
1901 'baseDir' => $baseDir, 'basePath' => '/w',
1902 '//example.org/files/test.jpg'
1903 ],
1904 // Unrelated path with domain, and empty base path (root mw install). Ignored.
1905 [
1906 'baseDir' => $baseDir, 'basePath' => '',
1907 'https://example.org/files/test.jpg'
1908 ],
1909 [
1910 'baseDir' => $baseDir, 'basePath' => '',
1911 // T155310
1912 '//example.org/files/test.jpg'
1913 ],
1914 // Check UploadPath before ResourceBasePath (T155146)
1915 [
1916 'baseDir' => dirname( $baseDir ), 'basePath' => '',
1917 'uploadDir' => $baseDir, 'uploadPath' => '/images',
1918 '/images/test.jpg',
1919 '/images/test.jpg?edcf2'
1920 ],
1921 ];
1922 }
1923
1924 /**
1925 * Tests a particular case of transformCssMedia, using the given input, globals,
1926 * expected return, and message
1927 *
1928 * Asserts that $expectedReturn is returned.
1929 *
1930 * options['printableQuery'] - value of query string for printable, or omitted for none
1931 * options['handheldQuery'] - value of query string for handheld, or omitted for none
1932 * options['media'] - passed into the method under the same name
1933 * options['expectedReturn'] - expected return value
1934 * options['message'] - PHPUnit message for assertion
1935 *
1936 * @param array $args Key-value array of arguments as shown above
1937 */
1938 protected function assertTransformCssMediaCase( $args ) {
1939 $queryData = [];
1940 if ( isset( $args['printableQuery'] ) ) {
1941 $queryData['printable'] = $args['printableQuery'];
1942 }
1943
1944 if ( isset( $args['handheldQuery'] ) ) {
1945 $queryData['handheld'] = $args['handheldQuery'];
1946 }
1947
1948 $fauxRequest = new FauxRequest( $queryData, false );
1949 $this->setMwGlobals( [
1950 'wgRequest' => $fauxRequest,
1951 ] );
1952
1953 $actualReturn = OutputPage::transformCssMedia( $args['media'] );
1954 $this->assertSame( $args['expectedReturn'], $actualReturn, $args['message'] );
1955 }
1956
1957 /**
1958 * Tests print requests
1959 *
1960 * @covers OutputPage::transformCssMedia
1961 */
1962 public function testPrintRequests() {
1963 $this->assertTransformCssMediaCase( [
1964 'printableQuery' => '1',
1965 'media' => 'screen',
1966 'expectedReturn' => null,
1967 'message' => 'On printable request, screen returns null'
1968 ] );
1969
1970 $this->assertTransformCssMediaCase( [
1971 'printableQuery' => '1',
1972 'media' => self::SCREEN_MEDIA_QUERY,
1973 'expectedReturn' => null,
1974 'message' => 'On printable request, screen media query returns null'
1975 ] );
1976
1977 $this->assertTransformCssMediaCase( [
1978 'printableQuery' => '1',
1979 'media' => self::SCREEN_ONLY_MEDIA_QUERY,
1980 'expectedReturn' => null,
1981 'message' => 'On printable request, screen media query with only returns null'
1982 ] );
1983
1984 $this->assertTransformCssMediaCase( [
1985 'printableQuery' => '1',
1986 'media' => 'print',
1987 'expectedReturn' => '',
1988 'message' => 'On printable request, media print returns empty string'
1989 ] );
1990 }
1991
1992 /**
1993 * Tests screen requests, without either query parameter set
1994 *
1995 * @covers OutputPage::transformCssMedia
1996 */
1997 public function testScreenRequests() {
1998 $this->assertTransformCssMediaCase( [
1999 'media' => 'screen',
2000 'expectedReturn' => 'screen',
2001 'message' => 'On screen request, screen media type is preserved'
2002 ] );
2003
2004 $this->assertTransformCssMediaCase( [
2005 'media' => 'handheld',
2006 'expectedReturn' => 'handheld',
2007 'message' => 'On screen request, handheld media type is preserved'
2008 ] );
2009
2010 $this->assertTransformCssMediaCase( [
2011 'media' => self::SCREEN_MEDIA_QUERY,
2012 'expectedReturn' => self::SCREEN_MEDIA_QUERY,
2013 'message' => 'On screen request, screen media query is preserved.'
2014 ] );
2015
2016 $this->assertTransformCssMediaCase( [
2017 'media' => self::SCREEN_ONLY_MEDIA_QUERY,
2018 'expectedReturn' => self::SCREEN_ONLY_MEDIA_QUERY,
2019 'message' => 'On screen request, screen media query with only is preserved.'
2020 ] );
2021
2022 $this->assertTransformCssMediaCase( [
2023 'media' => 'print',
2024 'expectedReturn' => 'print',
2025 'message' => 'On screen request, print media type is preserved'
2026 ] );
2027 }
2028
2029 /**
2030 * Tests handheld behavior
2031 *
2032 * @covers OutputPage::transformCssMedia
2033 */
2034 public function testHandheld() {
2035 $this->assertTransformCssMediaCase( [
2036 'handheldQuery' => '1',
2037 'media' => 'handheld',
2038 'expectedReturn' => '',
2039 'message' => 'On request with handheld querystring and media is handheld, returns empty string'
2040 ] );
2041
2042 $this->assertTransformCssMediaCase( [
2043 'handheldQuery' => '1',
2044 'media' => 'screen',
2045 'expectedReturn' => null,
2046 'message' => 'On request with handheld querystring and media is screen, returns null'
2047 ] );
2048 }
2049
2050 /**
2051 * @return OutputPage
2052 */
2053 private function newInstance( $config = [], WebRequest $request = null, $options = [] ) {
2054 $context = new RequestContext();
2055
2056 $context->setConfig( new MultiConfig( [
2057 new HashConfig( $config + [
2058 'AppleTouchIcon' => false,
2059 'DisableLangConversion' => true,
2060 'EnableCanonicalServerLink' => false,
2061 'Favicon' => false,
2062 'Feed' => false,
2063 'LanguageCode' => false,
2064 'ReferrerPolicy' => false,
2065 'RightsPage' => false,
2066 'RightsUrl' => false,
2067 'UniversalEditButton' => false,
2068 ] ),
2069 $context->getConfig()
2070 ] ) );
2071
2072 if ( !in_array( 'notitle', (array)$options ) ) {
2073 $context->setTitle( Title::newFromText( 'My test page' ) );
2074 }
2075
2076 if ( $request ) {
2077 $context->setRequest( $request );
2078 }
2079
2080 return new OutputPage( $context );
2081 }
2082 }
2083
2084 /**
2085 * MessageBlobStore that doesn't do anything
2086 */
2087 class NullMessageBlobStore extends MessageBlobStore {
2088 public function get( ResourceLoader $resourceLoader, $modules, $lang ) {
2089 return [];
2090 }
2091
2092 public function updateModule( $name, ResourceLoaderModule $module, $lang ) {
2093 }
2094
2095 public function updateMessage( $key ) {
2096 }
2097
2098 public function clear() {
2099 }
2100 }