Advertise feeds only if $wgFeed is enabled
[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 // @codingStandardsIgnoreStart Generic.Files.LineLength
16 const RSS_RC_LINK = '<link rel="alternate" type="application/rss+xml" title=" RSS feed" href="/w/index.php?title=Special:RecentChanges&amp;feed=rss"/>';
17 const ATOM_RC_LINK = '<link rel="alternate" type="application/atom+xml" title=" Atom feed" href="/w/index.php?title=Special:RecentChanges&amp;feed=atom"/>';
18
19 const RSS_TEST_LINK = '<link rel="alternate" type="application/rss+xml" title="&quot;Test&quot; RSS feed" href="fake-link"/>';
20 const ATOM_TEST_LINK = '<link rel="alternate" type="application/atom+xml" title="&quot;Test&quot; Atom feed" href="fake-link"/>';
21 // @codingStandardsIgnoreEnd
22
23 // Ensure that we don't affect the global ResourceLoader state.
24 protected function setUp() {
25 parent::setUp();
26 ResourceLoader::clearCache();
27 }
28 protected function tearDown() {
29 parent::tearDown();
30 ResourceLoader::clearCache();
31 }
32
33 /**
34 * @dataProvider provideRedirect
35 *
36 * @covers OutputPage::__construct
37 * @covers OutputPage::redirect
38 * @covers OutputPage::getRedirect
39 */
40 public function testRedirect( $url, $code = null ) {
41 $op = $this->newInstance();
42 if ( isset( $code ) ) {
43 $op->redirect( $url, $code );
44 } else {
45 $op->redirect( $url );
46 }
47 $expectedUrl = str_replace( "\n", '', $url );
48 $this->assertSame( $expectedUrl, $op->getRedirect() );
49 $this->assertSame( $expectedUrl, $op->mRedirect );
50 $this->assertSame( $code ?? '302', $op->mRedirectCode );
51 }
52
53 public function provideRedirect() {
54 return [
55 [ 'http://example.com' ],
56 [ 'http://example.com', '400' ],
57 [ 'http://example.com', 'squirrels!!!' ],
58 [ "a\nb" ],
59 ];
60 }
61
62 private function setupFeedLinks( $feed, $types ) {
63 $outputPage = $this->newInstance( [
64 'AdvertisedFeedTypes' => $types,
65 'Feed' => $feed,
66 'OverrideSiteFeed' => false,
67 'Script' => '/w',
68 'Sitename' => false,
69 ] );
70 $outputPage->setTitle( Title::makeTitle( NS_MAIN, 'Test' ) );
71 $this->setMwGlobals( [
72 'wgScript' => '/w/index.php',
73 ] );
74 return $outputPage;
75 }
76
77 private function assertFeedLinks( $outputPage, $message, $present, $non_present ) {
78 $links = $outputPage->getHeadLinksArray();
79 foreach ( $present as $link ) {
80 $this->assertContains( $link, $links, $message );
81 }
82 foreach ( $non_present as $link ) {
83 $this->assertNotContains( $link, $links, $message );
84 }
85 }
86
87 private function assertFeedUILinks( $outputPage, $ui_links ) {
88 if ( $ui_links ) {
89 $this->assertTrue( $outputPage->isSyndicated(), 'Syndication should be offered' );
90 $this->assertGreaterThan( 0, count( $outputPage->getSyndicationLinks() ),
91 'Some syndication links should be there' );
92 } else {
93 $this->assertFalse( $outputPage->isSyndicated(), 'No syndication should be offered' );
94 $this->assertEquals( 0, count( $outputPage->getSyndicationLinks() ),
95 'No syndication links should be there' );
96 }
97 }
98
99 public static function provideFeedLinkData() {
100 return [
101 [
102 true, [ 'rss' ], 'Only RSS RC link should be offerred',
103 [ self::RSS_RC_LINK ], [ self::ATOM_RC_LINK ]
104 ],
105 [
106 true, [ 'atom' ], 'Only Atom RC link should be offerred',
107 [ self::ATOM_RC_LINK ], [ self::RSS_RC_LINK ]
108 ],
109 [
110 true, [], 'No RC feed formats should be offerred',
111 [], [ self::ATOM_RC_LINK, self::RSS_RC_LINK ]
112 ],
113 [
114 false, [ 'atom' ], 'No RC feeds should be offerred',
115 [], [ self::ATOM_RC_LINK, self::RSS_RC_LINK ]
116 ],
117 ];
118 }
119
120 /**
121 * @covers OutputPage::setCopyrightUrl
122 * @covers OutputPage::getHeadLinksArray
123 */
124 public function testSetCopyrightUrl() {
125 $op = $this->newInstance();
126 $op->setCopyrightUrl( 'http://example.com' );
127
128 $this->assertSame(
129 Html::element( 'link', [ 'rel' => 'license', 'href' => 'http://example.com' ] ),
130 $op->getHeadLinksArray()['copyright']
131 );
132 }
133
134 /**
135 * @dataProvider provideFeedLinkData
136 * @covers OutputPage::getHeadLinksArray
137 */
138 public function testRecentChangesFeed( $feed, $advertised_feed_types,
139 $message, $present, $non_present ) {
140 $outputPage = $this->setupFeedLinks( $feed, $advertised_feed_types );
141 $this->assertFeedLinks( $outputPage, $message, $present, $non_present );
142 }
143
144 public static function provideAdditionalFeedData() {
145 return [
146 [
147 true, [ 'atom' ], 'Additional Atom feed should be offered',
148 'atom',
149 [ self::ATOM_TEST_LINK, self::ATOM_RC_LINK ],
150 [ self::RSS_TEST_LINK, self::RSS_RC_LINK ],
151 true,
152 ],
153 [
154 true, [ 'rss' ], 'Additional RSS feed should be offered',
155 'rss',
156 [ self::RSS_TEST_LINK, self::RSS_RC_LINK ],
157 [ self::ATOM_TEST_LINK, self::ATOM_RC_LINK ],
158 true,
159 ],
160 [
161 true, [ 'rss' ], 'Additional Atom feed should NOT be offered with RSS enabled',
162 'atom',
163 [ self::RSS_RC_LINK ],
164 [ self::RSS_TEST_LINK, self::ATOM_TEST_LINK, self::ATOM_RC_LINK ],
165 false,
166 ],
167 [
168 false, [ 'atom' ], 'Additional Atom feed should NOT be offered, all feeds disabled',
169 'atom',
170 [],
171 [
172 self::RSS_TEST_LINK, self::ATOM_TEST_LINK,
173 self::ATOM_RC_LINK, self::ATOM_RC_LINK,
174 ],
175 false,
176 ],
177 ];
178 }
179
180 /**
181 * @dataProvider provideAdditionalFeedData
182 * @covers OutputPage::getHeadLinksArray
183 * @covers OutputPage::addFeedLink
184 * @covers OutputPage::getSyndicationLinks
185 * @covers OutputPage::isSyndicated
186 */
187 public function testAdditionalFeeds( $feed, $advertised_feed_types, $message,
188 $additional_feed_type, $present, $non_present, $any_ui_links ) {
189 $outputPage = $this->setupFeedLinks( $feed, $advertised_feed_types );
190 $outputPage->addFeedLink( $additional_feed_type, 'fake-link' );
191 $this->assertFeedLinks( $outputPage, $message, $present, $non_present );
192 $this->assertFeedUILinks( $outputPage, $any_ui_links );
193 }
194
195 // @todo How to test setStatusCode?
196
197 /**
198 * @covers OutputPage::addMeta
199 * @covers OutputPage::getMetaTags
200 * @covers OutputPage::getHeadLinksArray
201 */
202 public function testMetaTags() {
203 $op = $this->newInstance();
204 $op->addMeta( 'http:expires', '0' );
205 $op->addMeta( 'keywords', 'first' );
206 $op->addMeta( 'keywords', 'second' );
207 $op->addMeta( 'og:title', 'Ta-duh' );
208
209 $expected = [
210 [ 'http:expires', '0' ],
211 [ 'keywords', 'first' ],
212 [ 'keywords', 'second' ],
213 [ 'og:title', 'Ta-duh' ],
214 ];
215 $this->assertSame( $expected, $op->getMetaTags() );
216
217 $links = $op->getHeadLinksArray();
218 $this->assertContains( '<meta http-equiv="expires" content="0"/>', $links );
219 $this->assertContains( '<meta name="keywords" content="first"/>', $links );
220 $this->assertContains( '<meta name="keywords" content="second"/>', $links );
221 $this->assertContains( '<meta property="og:title" content="Ta-duh"/>', $links );
222 $this->assertArrayNotHasKey( 'meta-robots', $links );
223 }
224
225 /**
226 * @covers OutputPage::addLink
227 * @covers OutputPage::getLinkTags
228 * @covers OutputPage::getHeadLinksArray
229 */
230 public function testAddLink() {
231 $op = $this->newInstance();
232
233 $links = [
234 [],
235 [ 'rel' => 'foo', 'href' => 'http://example.com' ],
236 ];
237
238 foreach ( $links as $link ) {
239 $op->addLink( $link );
240 }
241
242 $this->assertSame( $links, $op->getLinkTags() );
243
244 $result = $op->getHeadLinksArray();
245
246 foreach ( $links as $link ) {
247 $this->assertContains( Html::element( 'link', $link ), $result );
248 }
249 }
250
251 /**
252 * @covers OutputPage::setCanonicalUrl
253 * @covers OutputPage::getCanonicalUrl
254 * @covers OutputPage::getHeadLinksArray
255 */
256 public function testSetCanonicalUrl() {
257 $op = $this->newInstance();
258 $op->setCanonicalUrl( 'http://example.comm' );
259 $op->setCanonicalUrl( 'http://example.com' );
260
261 $this->assertSame( 'http://example.com', $op->getCanonicalUrl() );
262
263 $headLinks = $op->getHeadLinksArray();
264
265 $this->assertContains( Html::element( 'link', [
266 'rel' => 'canonical', 'href' => 'http://example.com'
267 ] ), $headLinks );
268
269 $this->assertNotContains( Html::element( 'link', [
270 'rel' => 'canonical', 'href' => 'http://example.comm'
271 ] ), $headLinks );
272 }
273
274 /**
275 * @covers OutputPage::addScript
276 */
277 public function testAddScript() {
278 $op = $this->newInstance();
279 $op->addScript( 'some random string' );
280
281 $this->assertContains( "\nsome random string\n", "\n" . $op->getBottomScripts() . "\n" );
282 }
283
284 /**
285 * @covers OutputPage::addScriptFile
286 */
287 public function testAddScriptFile() {
288 $op = $this->newInstance();
289 $op->addScriptFile( '/somescript.js' );
290 $op->addScriptFile( '//example.com/somescript.js' );
291
292 $this->assertContains(
293 "\n" . Html::linkedScript( '/somescript.js', $op->getCSPNonce() ) .
294 Html::linkedScript( '//example.com/somescript.js', $op->getCSPNonce() ) . "\n",
295 "\n" . $op->getBottomScripts() . "\n"
296 );
297 }
298
299 /**
300 * Test that addScriptFile() throws due to deprecation.
301 *
302 * @covers OutputPage::addScriptFile
303 */
304 public function testAddDeprecatedScriptFileWarning() {
305 $this->setExpectedException( PHPUnit_Framework_Error_Deprecated::class,
306 'Use of OutputPage::addScriptFile was deprecated in MediaWiki 1.24.' );
307
308 $op = $this->newInstance();
309 $op->addScriptFile( 'ignored-script.js' );
310 }
311
312 /**
313 * Test the actual behavior of the method (in the case where it doesn't throw, e.g., in
314 * production).
315 *
316 * @covers OutputPage::addScriptFile
317 */
318 public function testAddDeprecatedScriptFileNoOp() {
319 $this->hideDeprecated( 'OutputPage::addScriptFile' );
320 $op = $this->newInstance();
321 $op->addScriptFile( 'ignored-script.js' );
322
323 $this->assertNotContains( 'ignored-script.js', '' . $op->getBottomScripts() );
324 }
325
326 /**
327 * @covers OutputPage::addInlineScript
328 */
329 public function testAddInlineScript() {
330 $op = $this->newInstance();
331 $op->addInlineScript( 'let foo = "bar";' );
332 $op->addInlineScript( 'alert( foo );' );
333
334 $this->assertContains(
335 "\n" . Html::inlineScript( "\nlet foo = \"bar\";\n", $op->getCSPNonce() ) . "\n" .
336 Html::inlineScript( "\nalert( foo );\n", $op->getCSPNonce() ) . "\n",
337 "\n" . $op->getBottomScripts() . "\n"
338 );
339 }
340
341 // @todo How to test filterModules(), warnModuleTargetFilter(), getModules(), etc.?
342
343 /**
344 * @covers OutputPage::getTarget
345 * @covers OutputPage::setTarget
346 */
347 public function testSetTarget() {
348 $op = $this->newInstance();
349 $op->setTarget( 'foo' );
350
351 $this->assertSame( 'foo', $op->getTarget() );
352 // @todo What else? Test some actual effect?
353 }
354
355 // @todo How to test addContentOverride(Callback)?
356
357 /**
358 * @covers OutputPage::getHeadItemsArray
359 * @covers OutputPage::addHeadItem
360 * @covers OutputPage::addHeadItems
361 * @covers OutputPage::hasHeadItem
362 */
363 public function testHeadItems() {
364 $op = $this->newInstance();
365 $op->addHeadItem( 'a', 'b' );
366 $op->addHeadItems( [ 'c' => '<d>&amp;', 'e' => 'f', 'a' => 'q' ] );
367 $op->addHeadItem( 'e', 'g' );
368 $op->addHeadItems( 'x' );
369
370 $this->assertSame( [ 'a' => 'q', 'c' => '<d>&amp;', 'e' => 'g', 'x' ],
371 $op->getHeadItemsArray() );
372
373 $this->assertTrue( $op->hasHeadItem( 'a' ) );
374 $this->assertTrue( $op->hasHeadItem( 'c' ) );
375 $this->assertTrue( $op->hasHeadItem( 'e' ) );
376 $this->assertTrue( $op->hasHeadItem( '0' ) );
377
378 $this->assertContains( "\nq\n<d>&amp;\ng\nx\n",
379 '' . $op->headElement( $op->getContext()->getSkin() ) );
380 }
381
382 /**
383 * @covers OutputPage::getHeadItemsArray
384 * @covers OutputPage::addParserOutputMetadata
385 * @covers OutputPage::addParserOutput
386 */
387 public function testHeadItemsParserOutput() {
388 $op = $this->newInstance();
389 $stubPO1 = $this->createParserOutputStub( 'getHeadItems', [ 'a' => 'b' ] );
390 $op->addParserOutputMetadata( $stubPO1 );
391 $stubPO2 = $this->createParserOutputStub( 'getHeadItems',
392 [ 'c' => '<d>&amp;', 'e' => 'f', 'a' => 'q' ] );
393 $op->addParserOutputMetadata( $stubPO2 );
394 $stubPO3 = $this->createParserOutputStub( 'getHeadItems', [ 'e' => 'g' ] );
395 $op->addParserOutput( $stubPO3 );
396 $stubPO4 = $this->createParserOutputStub( 'getHeadItems', [ 'x' ] );
397 $op->addParserOutputMetadata( $stubPO4 );
398
399 $this->assertSame( [ 'a' => 'q', 'c' => '<d>&amp;', 'e' => 'g', 'x' ],
400 $op->getHeadItemsArray() );
401
402 $this->assertTrue( $op->hasHeadItem( 'a' ) );
403 $this->assertTrue( $op->hasHeadItem( 'c' ) );
404 $this->assertTrue( $op->hasHeadItem( 'e' ) );
405 $this->assertTrue( $op->hasHeadItem( '0' ) );
406 $this->assertFalse( $op->hasHeadItem( 'b' ) );
407
408 $this->assertContains( "\nq\n<d>&amp;\ng\nx\n",
409 '' . $op->headElement( $op->getContext()->getSkin() ) );
410 }
411
412 /**
413 * @covers OutputPage::addBodyClasses
414 */
415 public function testAddBodyClasses() {
416 $op = $this->newInstance();
417 $op->addBodyClasses( 'a' );
418 $op->addBodyClasses( 'mediawiki' );
419 $op->addBodyClasses( 'b c' );
420 $op->addBodyClasses( [ 'd', 'e' ] );
421 $op->addBodyClasses( 'a' );
422
423 $this->assertContains( '"a mediawiki b c d e ltr',
424 '' . $op->headElement( $op->getContext()->getSkin() ) );
425 }
426
427 /**
428 * @covers OutputPage::setArticleBodyOnly
429 * @covers OutputPage::getArticleBodyOnly
430 */
431 public function testArticleBodyOnly() {
432 $op = $this->newInstance();
433 $this->assertFalse( $op->getArticleBodyOnly() );
434
435 $op->setArticleBodyOnly( true );
436 $this->assertTrue( $op->getArticleBodyOnly() );
437
438 $op->addHTML( '<b>a</b>' );
439
440 $this->assertSame( '<b>a</b>', $op->output( true ) );
441 }
442
443 /**
444 * @covers OutputPage::setProperty
445 * @covers OutputPage::getProperty
446 */
447 public function testProperties() {
448 $op = $this->newInstance();
449
450 $this->assertNull( $op->getProperty( 'foo' ) );
451
452 $op->setProperty( 'foo', 'bar' );
453 $op->setProperty( 'baz', 'quz' );
454
455 $this->assertSame( 'bar', $op->getProperty( 'foo' ) );
456 $this->assertSame( 'quz', $op->getProperty( 'baz' ) );
457 }
458
459 /**
460 * @dataProvider provideCheckLastModified
461 *
462 * @covers OutputPage::checkLastModified
463 * @covers OutputPage::getCdnCacheEpoch
464 */
465 public function testCheckLastModified(
466 $timestamp, $ifModifiedSince, $expected, $config = [], $callback = null
467 ) {
468 $request = new FauxRequest();
469 if ( $ifModifiedSince ) {
470 if ( is_numeric( $ifModifiedSince ) ) {
471 // Unix timestamp
472 $ifModifiedSince = date( 'D, d M Y H:i:s', $ifModifiedSince ) . ' GMT';
473 }
474 $request->setHeader( 'If-Modified-Since', $ifModifiedSince );
475 }
476
477 if ( !isset( $config['CacheEpoch'] ) ) {
478 // Make sure it's not too recent
479 $config['CacheEpoch'] = '20000101000000';
480 }
481
482 $op = $this->newInstance( $config, $request );
483
484 if ( $callback ) {
485 $callback( $op, $this );
486 }
487
488 // Avoid a complaint about not being able to disable compression
489 Wikimedia\suppressWarnings();
490 try {
491 $this->assertEquals( $expected, $op->checkLastModified( $timestamp ) );
492 } finally {
493 Wikimedia\restoreWarnings();
494 }
495 }
496
497 public function provideCheckLastModified() {
498 $lastModified = time() - 3600;
499 return [
500 'Timestamp 0' =>
501 [ '0', $lastModified, false ],
502 'Timestamp Unix epoch' =>
503 [ '19700101000000', $lastModified, false ],
504 'Timestamp same as If-Modified-Since' =>
505 [ $lastModified, $lastModified, true ],
506 'Timestamp one second after If-Modified-Since' =>
507 [ $lastModified + 1, $lastModified, false ],
508 'No If-Modified-Since' =>
509 [ $lastModified + 1, null, false ],
510 'Malformed If-Modified-Since' =>
511 [ $lastModified + 1, 'GIBBERING WOMBATS !!!', false ],
512 'Non-standard IE-style If-Modified-Since' =>
513 [ $lastModified, date( 'D, d M Y H:i:s', $lastModified ) . ' GMT; length=5202',
514 true ],
515 // @todo Should we fix this behavior to match the spec? Probably no reason to.
516 'If-Modified-Since not per spec but we accept it anyway because strtotime does' =>
517 [ $lastModified, "@$lastModified", true ],
518 '$wgCachePages = false' =>
519 [ $lastModified, $lastModified, false, [ 'CachePages' => false ] ],
520 '$wgCacheEpoch' =>
521 [ $lastModified, $lastModified, false,
522 [ 'CacheEpoch' => wfTimestamp( TS_MW, $lastModified + 1 ) ] ],
523 'Recently-touched user' =>
524 [ $lastModified, $lastModified, false, [],
525 function ( $op ) {
526 $op->getContext()->setUser( $this->getTestUser()->getUser() );
527 } ],
528 'After Squid expiry' =>
529 [ $lastModified, $lastModified, false,
530 [ 'UseSquid' => true, 'SquidMaxage' => 3599 ] ],
531 'Hook allows cache use' =>
532 [ $lastModified + 1, $lastModified, true, [],
533 function ( $op, $that ) {
534 $that->setTemporaryHook( 'OutputPageCheckLastModified',
535 function ( &$modifiedTimes ) {
536 $modifiedTimes = [ 1 ];
537 }
538 );
539 } ],
540 'Hooks prohibits cache use' =>
541 [ $lastModified, $lastModified, false, [],
542 function ( $op, $that ) {
543 $that->setTemporaryHook( 'OutputPageCheckLastModified',
544 function ( &$modifiedTimes ) {
545 $modifiedTimes = [ max( $modifiedTimes ) + 1 ];
546 }
547 );
548 } ],
549 ];
550 }
551
552 /**
553 * @dataProvider provideCdnCacheEpoch
554 *
555 * @covers OutputPage::getCdnCacheEpoch
556 */
557 public function testCdnCacheEpoch( $params ) {
558 $out = TestingAccessWrapper::newFromObject( $this->newInstance() );
559 $reqTime = strtotime( $params['reqTime'] );
560 $pageTime = strtotime( $params['pageTime'] );
561 $actual = max( $pageTime, $out->getCdnCacheEpoch( $reqTime, $params['maxAge'] ) );
562
563 $this->assertEquals(
564 $params['expect'],
565 gmdate( DateTime::ATOM, $actual ),
566 'cdn epoch'
567 );
568 }
569
570 public static function provideCdnCacheEpoch() {
571 $base = [
572 'pageTime' => '2011-04-01T12:00:00+00:00',
573 'maxAge' => 24 * 3600,
574 ];
575 return [
576 'after 1s' => [ $base + [
577 'reqTime' => '2011-04-01T12:00:01+00:00',
578 'expect' => '2011-04-01T12:00:00+00:00',
579 ] ],
580 'after 23h' => [ $base + [
581 'reqTime' => '2011-04-02T11:00:00+00:00',
582 'expect' => '2011-04-01T12:00:00+00:00',
583 ] ],
584 'after 24h and a bit' => [ $base + [
585 'reqTime' => '2011-04-02T12:34:56+00:00',
586 'expect' => '2011-04-01T12:34:56+00:00',
587 ] ],
588 'after a year' => [ $base + [
589 'reqTime' => '2012-05-06T00:12:07+00:00',
590 'expect' => '2012-05-05T00:12:07+00:00',
591 ] ],
592 ];
593 }
594
595 // @todo How to test setLastModified?
596
597 /**
598 * @covers OutputPage::setRobotPolicy
599 * @covers OutputPage::getHeadLinksArray
600 */
601 public function testSetRobotPolicy() {
602 $op = $this->newInstance();
603 $op->setRobotPolicy( 'noindex, nofollow' );
604
605 $links = $op->getHeadLinksArray();
606 $this->assertContains( '<meta name="robots" content="noindex,nofollow"/>', $links );
607 }
608
609 /**
610 * @covers OutputPage::setIndexPolicy
611 * @covers OutputPage::setFollowPolicy
612 * @covers OutputPage::getHeadLinksArray
613 */
614 public function testSetIndexFollowPolicies() {
615 $op = $this->newInstance();
616 $op->setIndexPolicy( 'noindex' );
617 $op->setFollowPolicy( 'nofollow' );
618
619 $links = $op->getHeadLinksArray();
620 $this->assertContains( '<meta name="robots" content="noindex,nofollow"/>', $links );
621 }
622
623 private function extractHTMLTitle( OutputPage $op ) {
624 $html = $op->headElement( $op->getContext()->getSkin() );
625
626 // OutputPage should always output the title in a nice format such that regexes will work
627 // fine. If it doesn't, we'll fail the tests.
628 preg_match_all( '!<title>(.*?)</title>!', $html, $matches );
629
630 $this->assertLessThanOrEqual( 1, count( $matches[1] ), 'More than one <title>!' );
631
632 if ( !count( $matches[1] ) ) {
633 return null;
634 }
635
636 return $matches[1][0];
637 }
638
639 /**
640 * Shorthand for getting the text of a message, in content language.
641 */
642 private static function getMsgText( $op, ...$msgParams ) {
643 return $op->msg( ...$msgParams )->inContentLanguage()->text();
644 }
645
646 /**
647 * @covers OutputPage::setHTMLTitle
648 * @covers OutputPage::getHTMLTitle
649 */
650 public function testHTMLTitle() {
651 $op = $this->newInstance();
652
653 // Default
654 $this->assertSame( '', $op->getHTMLTitle() );
655 $this->assertSame( '', $op->getPageTitle() );
656 $this->assertSame(
657 $this->getMsgText( $op, 'pagetitle', '' ),
658 $this->extractHTMLTitle( $op )
659 );
660
661 // Set to string
662 $op->setHTMLTitle( 'Potatoes will eat me' );
663
664 $this->assertSame( 'Potatoes will eat me', $op->getHTMLTitle() );
665 $this->assertSame( 'Potatoes will eat me', $this->extractHTMLTitle( $op ) );
666 // Shouldn't have changed the page title
667 $this->assertSame( '', $op->getPageTitle() );
668
669 // Set to message
670 $msg = $op->msg( 'mainpage' );
671
672 $op->setHTMLTitle( $msg );
673 $this->assertSame( $msg->text(), $op->getHTMLTitle() );
674 $this->assertSame( $msg->text(), $this->extractHTMLTitle( $op ) );
675 $this->assertSame( '', $op->getPageTitle() );
676 }
677
678 /**
679 * @covers OutputPage::setRedirectedFrom
680 */
681 public function testSetRedirectedFrom() {
682 $op = $this->newInstance();
683
684 $op->setRedirectedFrom( Title::newFromText( 'Talk:Some page' ) );
685 $this->assertSame( 'Talk:Some_page', $op->getJSVars()['wgRedirectedFrom'] );
686 }
687
688 /**
689 * @covers OutputPage::setPageTitle
690 * @covers OutputPage::getPageTitle
691 */
692 public function testPageTitle() {
693 // We don't test the actual HTML output anywhere, because that's up to the skin.
694 $op = $this->newInstance();
695
696 // Test default
697 $this->assertSame( '', $op->getPageTitle() );
698 $this->assertSame( '', $op->getHTMLTitle() );
699
700 // Test set to plain text
701 $op->setPageTitle( 'foobar' );
702
703 $this->assertSame( 'foobar', $op->getPageTitle() );
704 // HTML title should change as well
705 $this->assertSame( $this->getMsgText( $op, 'pagetitle', 'foobar' ), $op->getHTMLTitle() );
706
707 // Test set to text with good and bad HTML. We don't try to be comprehensive here, that
708 // belongs in Sanitizer tests.
709 $op->setPageTitle( '<script>a</script>&amp;<i>b</i>' );
710
711 $this->assertSame( '&lt;script&gt;a&lt;/script&gt;&amp;<i>b</i>', $op->getPageTitle() );
712 $this->assertSame(
713 $this->getMsgText( $op, 'pagetitle', '<script>a</script>&b' ),
714 $op->getHTMLTitle()
715 );
716
717 // Test set to message
718 $text = $this->getMsgText( $op, 'mainpage' );
719
720 $op->setPageTitle( $op->msg( 'mainpage' )->inContentLanguage() );
721 $this->assertSame( $text, $op->getPageTitle() );
722 $this->assertSame( $this->getMsgText( $op, 'pagetitle', $text ), $op->getHTMLTitle() );
723 }
724
725 /**
726 * @covers OutputPage::setTitle
727 */
728 public function testSetTitle() {
729 $op = $this->newInstance();
730
731 $this->assertSame( 'My test page', $op->getTitle()->getPrefixedText() );
732
733 $op->setTitle( Title::newFromText( 'Another test page' ) );
734
735 $this->assertSame( 'Another test page', $op->getTitle()->getPrefixedText() );
736 }
737
738 /**
739 * @covers OutputPage::setSubtitle
740 * @covers OutputPage::clearSubtitle
741 * @covers OutputPage::addSubtitle
742 * @covers OutputPage::getSubtitle
743 */
744 public function testSubtitle() {
745 $op = $this->newInstance();
746
747 $this->assertSame( '', $op->getSubtitle() );
748
749 $op->addSubtitle( '<b>foo</b>' );
750
751 $this->assertSame( '<b>foo</b>', $op->getSubtitle() );
752
753 $op->addSubtitle( $op->msg( 'mainpage' )->inContentLanguage() );
754
755 $this->assertSame(
756 "<b>foo</b><br />\n\t\t\t\t" . $this->getMsgText( $op, 'mainpage' ),
757 $op->getSubtitle()
758 );
759
760 $op->setSubtitle( 'There can be only one' );
761
762 $this->assertSame( 'There can be only one', $op->getSubtitle() );
763
764 $op->clearSubtitle();
765
766 $this->assertSame( '', $op->getSubtitle() );
767 }
768
769 /**
770 * @dataProvider provideBacklinkSubtitle
771 *
772 * @covers OutputPage::buildBacklinkSubtitle
773 */
774 public function testBuildBacklinkSubtitle( $titles, $queries, $contains, $notContains ) {
775 if ( count( $titles ) > 1 ) {
776 // Not applicable
777 $this->assertTrue( true );
778 return;
779 }
780
781 $title = Title::newFromText( $titles[0] );
782 $query = $queries[0];
783
784 $this->editPage( 'Page 1', '' );
785 $this->editPage( 'Page 2', '#REDIRECT [[Page 1]]' );
786
787 $str = OutputPage::buildBacklinkSubtitle( $title, $query )->text();
788
789 foreach ( $contains as $substr ) {
790 $this->assertContains( $substr, $str );
791 }
792
793 foreach ( $notContains as $substr ) {
794 $this->assertNotContains( $substr, $str );
795 }
796 }
797
798 /**
799 * @dataProvider provideBacklinkSubtitle
800 *
801 * @covers OutputPage::addBacklinkSubtitle
802 * @covers OutputPage::getSubtitle
803 */
804 public function testAddBacklinkSubtitle( $titles, $queries, $contains, $notContains ) {
805 $this->editPage( 'Page 1', '' );
806 $this->editPage( 'Page 2', '#REDIRECT [[Page 1]]' );
807
808 $op = $this->newInstance();
809 foreach ( $titles as $i => $unused ) {
810 $op->addBacklinkSubtitle( Title::newFromText( $titles[$i] ), $queries[$i] );
811 }
812
813 $str = $op->getSubtitle();
814
815 foreach ( $contains as $substr ) {
816 $this->assertContains( $substr, $str );
817 }
818
819 foreach ( $notContains as $substr ) {
820 $this->assertNotContains( $substr, $str );
821 }
822 }
823
824 public function provideBacklinkSubtitle() {
825 return [
826 [
827 [ 'Page 1' ],
828 [ [] ],
829 [ 'Page 1' ],
830 [ 'redirect', 'Page 2' ],
831 ],
832 [
833 [ 'Page 2' ],
834 [ [] ],
835 [ 'redirect=no' ],
836 [ 'Page 1' ],
837 ],
838 [
839 [ 'Page 1' ],
840 [ [ 'action' => 'edit' ] ],
841 [ 'action=edit' ],
842 [],
843 ],
844 [
845 [ 'Page 1', 'Page 2' ],
846 [ [], [] ],
847 [ 'Page 1', 'Page 2', "<br />\n\t\t\t\t" ],
848 [],
849 ],
850 // @todo Anything else to test?
851 ];
852 }
853
854 /**
855 * @covers OutputPage::setPrintable
856 * @covers OutputPage::isPrintable
857 */
858 public function testPrintable() {
859 $op = $this->newInstance();
860
861 $this->assertFalse( $op->isPrintable() );
862
863 $op->setPrintable();
864
865 $this->assertTrue( $op->isPrintable() );
866 }
867
868 /**
869 * @covers OutputPage::disable
870 * @covers OutputPage::isDisabled
871 */
872 public function testDisable() {
873 $op = $this->newInstance();
874
875 $this->assertFalse( $op->isDisabled() );
876 $this->assertNotSame( '', $op->output( true ) );
877
878 $op->disable();
879
880 $this->assertTrue( $op->isDisabled() );
881 $this->assertSame( '', $op->output( true ) );
882 }
883
884 /**
885 * @covers OutputPage::showNewSectionLink
886 * @covers OutputPage::addParserOutputMetadata
887 * @covers OutputPage::addParserOutput
888 */
889 public function testShowNewSectionLink() {
890 $op = $this->newInstance();
891
892 $this->assertFalse( $op->showNewSectionLink() );
893
894 $pOut1 = $this->createParserOutputStub( 'getNewSection', true );
895 $op->addParserOutputMetadata( $pOut1 );
896 $this->assertTrue( $op->showNewSectionLink() );
897
898 $pOut2 = $this->createParserOutputStub( 'getNewSection', false );
899 $op->addParserOutput( $pOut2 );
900 $this->assertFalse( $op->showNewSectionLink() );
901 }
902
903 /**
904 * @covers OutputPage::forceHideNewSectionLink
905 * @covers OutputPage::addParserOutputMetadata
906 * @covers OutputPage::addParserOutput
907 */
908 public function testForceHideNewSectionLink() {
909 $op = $this->newInstance();
910
911 $this->assertFalse( $op->forceHideNewSectionLink() );
912
913 $pOut1 = $this->createParserOutputStub( 'getHideNewSection', true );
914 $op->addParserOutputMetadata( $pOut1 );
915 $this->assertTrue( $op->forceHideNewSectionLink() );
916
917 $pOut2 = $this->createParserOutputStub( 'getHideNewSection', false );
918 $op->addParserOutput( $pOut2 );
919 $this->assertFalse( $op->forceHideNewSectionLink() );
920 }
921
922 /**
923 * @covers OutputPage::setSyndicated
924 * @covers OutputPage::isSyndicated
925 */
926 public function testSetSyndicated() {
927 $op = $this->newInstance( [ 'Feed' => true ] );
928 $this->assertFalse( $op->isSyndicated() );
929
930 $op->setSyndicated();
931 $this->assertTrue( $op->isSyndicated() );
932
933 $op->setSyndicated( false );
934 $this->assertFalse( $op->isSyndicated() );
935
936 $op = $this->newInstance(); // Feed => false by default
937 $this->assertFalse( $op->isSyndicated() );
938
939 $op->setSyndicated();
940 $this->assertFalse( $op->isSyndicated() );
941 }
942
943 /**
944 * @covers OutputPage::isSyndicated
945 * @covers OutputPage::setFeedAppendQuery
946 * @covers OutputPage::addFeedLink
947 * @covers OutputPage::getSyndicationLinks()
948 */
949 public function testFeedLinks() {
950 $op = $this->newInstance( [ 'Feed' => true ] );
951 $this->assertSame( [], $op->getSyndicationLinks() );
952
953 $op->addFeedLink( 'not a supported format', 'abc' );
954 $this->assertFalse( $op->isSyndicated() );
955 $this->assertSame( [], $op->getSyndicationLinks() );
956
957 $feedTypes = $op->getConfig()->get( 'AdvertisedFeedTypes' );
958
959 $op->addFeedLink( $feedTypes[0], 'def' );
960 $this->assertTrue( $op->isSyndicated() );
961 $this->assertSame( [ $feedTypes[0] => 'def' ], $op->getSyndicationLinks() );
962
963 $op->setFeedAppendQuery( false );
964 $expected = [];
965 foreach ( $feedTypes as $type ) {
966 $expected[$type] = $op->getTitle()->getLocalURL( "feed=$type" );
967 }
968 $this->assertSame( $expected, $op->getSyndicationLinks() );
969
970 $op->setFeedAppendQuery( 'apples=oranges' );
971 foreach ( $feedTypes as $type ) {
972 $expected[$type] = $op->getTitle()->getLocalURL( "feed=$type&apples=oranges" );
973 }
974 $this->assertSame( $expected, $op->getSyndicationLinks() );
975
976 $op = $this->newInstance(); // Feed => false by default
977 $this->assertSame( [], $op->getSyndicationLinks() );
978
979 $op->addFeedLink( $feedTypes[0], 'def' );
980 $this->assertFalse( $op->isSyndicated() );
981 $this->assertSame( [], $op->getSyndicationLinks() );
982 }
983
984 /**
985 * @covers OutputPage::setArticleFlag
986 * @covers OutputPage::isArticle
987 * @covers OutputPage::setArticleRelated
988 * @covers OutputPage::isArticleRelated
989 */
990 function testArticleFlags() {
991 $op = $this->newInstance();
992 $this->assertFalse( $op->isArticle() );
993 $this->assertTrue( $op->isArticleRelated() );
994
995 $op->setArticleRelated( false );
996 $this->assertFalse( $op->isArticle() );
997 $this->assertFalse( $op->isArticleRelated() );
998
999 $op->setArticleFlag( true );
1000 $this->assertTrue( $op->isArticle() );
1001 $this->assertTrue( $op->isArticleRelated() );
1002
1003 $op->setArticleFlag( false );
1004 $this->assertFalse( $op->isArticle() );
1005 $this->assertTrue( $op->isArticleRelated() );
1006
1007 $op->setArticleFlag( true );
1008 $op->setArticleRelated( false );
1009 $this->assertFalse( $op->isArticle() );
1010 $this->assertFalse( $op->isArticleRelated() );
1011 }
1012
1013 /**
1014 * @covers OutputPage::addLanguageLinks
1015 * @covers OutputPage::setLanguageLinks
1016 * @covers OutputPage::getLanguageLinks
1017 * @covers OutputPage::addParserOutputMetadata
1018 * @covers OutputPage::addParserOutput
1019 */
1020 function testLanguageLinks() {
1021 $op = $this->newInstance();
1022 $this->assertSame( [], $op->getLanguageLinks() );
1023
1024 $op->addLanguageLinks( [ 'fr:A', 'it:B' ] );
1025 $this->assertSame( [ 'fr:A', 'it:B' ], $op->getLanguageLinks() );
1026
1027 $op->addLanguageLinks( [ 'de:C', 'es:D' ] );
1028 $this->assertSame( [ 'fr:A', 'it:B', 'de:C', 'es:D' ], $op->getLanguageLinks() );
1029
1030 $op->setLanguageLinks( [ 'pt:E' ] );
1031 $this->assertSame( [ 'pt:E' ], $op->getLanguageLinks() );
1032
1033 $pOut1 = $this->createParserOutputStub( 'getLanguageLinks', [ 'he:F', 'ar:G' ] );
1034 $op->addParserOutputMetadata( $pOut1 );
1035 $this->assertSame( [ 'pt:E', 'he:F', 'ar:G' ], $op->getLanguageLinks() );
1036
1037 $pOut2 = $this->createParserOutputStub( 'getLanguageLinks', [ 'pt:H' ] );
1038 $op->addParserOutput( $pOut2 );
1039 $this->assertSame( [ 'pt:E', 'he:F', 'ar:G', 'pt:H' ], $op->getLanguageLinks() );
1040 }
1041
1042 // @todo Are these category links tests too abstract and complicated for what they test? Would
1043 // it make sense to just write out all the tests by hand with maybe some copy-and-paste?
1044
1045 /**
1046 * @dataProvider provideGetCategories
1047 *
1048 * @covers OutputPage::addCategoryLinks
1049 * @covers OutputPage::getCategories
1050 * @covers OutputPage::getCategoryLinks
1051 *
1052 * @param array $args Array of form [ category name => sort key ]
1053 * @param array $fakeResults Array of form [ category name => value to return from mocked
1054 * LinkBatch ]
1055 * @param callable $variantLinkCallback Callback to replace findVariantLink() call
1056 * @param array $expectedNormal Expected return value of getCategoryLinks['normal']
1057 * @param array $expectedHidden Expected return value of getCategoryLinks['hidden']
1058 */
1059 public function testAddCategoryLinks(
1060 array $args, array $fakeResults, callable $variantLinkCallback = null,
1061 array $expectedNormal, array $expectedHidden
1062 ) {
1063 $expectedNormal = $this->extractExpectedCategories( $expectedNormal, 'add' );
1064 $expectedHidden = $this->extractExpectedCategories( $expectedHidden, 'add' );
1065
1066 $op = $this->setupCategoryTests( $fakeResults, $variantLinkCallback );
1067
1068 $op->addCategoryLinks( $args );
1069
1070 $this->doCategoryAsserts( $op, $expectedNormal, $expectedHidden );
1071 $this->doCategoryLinkAsserts( $op, $expectedNormal, $expectedHidden );
1072 }
1073
1074 /**
1075 * @dataProvider provideGetCategories
1076 *
1077 * @covers OutputPage::addCategoryLinks
1078 * @covers OutputPage::getCategories
1079 * @covers OutputPage::getCategoryLinks
1080 */
1081 public function testAddCategoryLinksOneByOne(
1082 array $args, array $fakeResults, callable $variantLinkCallback = null,
1083 array $expectedNormal, array $expectedHidden
1084 ) {
1085 if ( count( $args ) <= 1 ) {
1086 // @todo Should this be skipped instead of passed?
1087 $this->assertTrue( true );
1088 return;
1089 }
1090
1091 $expectedNormal = $this->extractExpectedCategories( $expectedNormal, 'onebyone' );
1092 $expectedHidden = $this->extractExpectedCategories( $expectedHidden, 'onebyone' );
1093
1094 $op = $this->setupCategoryTests( $fakeResults, $variantLinkCallback );
1095
1096 foreach ( $args as $key => $val ) {
1097 $op->addCategoryLinks( [ $key => $val ] );
1098 }
1099
1100 $this->doCategoryAsserts( $op, $expectedNormal, $expectedHidden );
1101 $this->doCategoryLinkAsserts( $op, $expectedNormal, $expectedHidden );
1102 }
1103
1104 /**
1105 * @dataProvider provideGetCategories
1106 *
1107 * @covers OutputPage::setCategoryLinks
1108 * @covers OutputPage::getCategories
1109 * @covers OutputPage::getCategoryLinks
1110 */
1111 public function testSetCategoryLinks(
1112 array $args, array $fakeResults, callable $variantLinkCallback = null,
1113 array $expectedNormal, array $expectedHidden
1114 ) {
1115 $expectedNormal = $this->extractExpectedCategories( $expectedNormal, 'set' );
1116 $expectedHidden = $this->extractExpectedCategories( $expectedHidden, 'set' );
1117
1118 $op = $this->setupCategoryTests( $fakeResults, $variantLinkCallback );
1119
1120 $op->setCategoryLinks( [ 'Initial page' => 'Initial page' ] );
1121 $op->setCategoryLinks( $args );
1122
1123 // We don't reset the categories, for some reason, only the links
1124 $expectedNormalCats = array_merge( [ 'Initial page' ], $expectedNormal );
1125 $expectedCats = array_merge( $expectedHidden, $expectedNormalCats );
1126
1127 $this->doCategoryAsserts( $op, $expectedNormalCats, $expectedHidden );
1128 $this->doCategoryLinkAsserts( $op, $expectedNormal, $expectedHidden );
1129 }
1130
1131 /**
1132 * @dataProvider provideGetCategories
1133 *
1134 * @covers OutputPage::addParserOutputMetadata
1135 * @covers OutputPage::addParserOutput
1136 * @covers OutputPage::getCategories
1137 * @covers OutputPage::getCategoryLinks
1138 */
1139 public function testParserOutputCategoryLinks(
1140 array $args, array $fakeResults, callable $variantLinkCallback = null,
1141 array $expectedNormal, array $expectedHidden
1142 ) {
1143 $expectedNormal = $this->extractExpectedCategories( $expectedNormal, 'pout' );
1144 $expectedHidden = $this->extractExpectedCategories( $expectedHidden, 'pout' );
1145
1146 $op = $this->setupCategoryTests( $fakeResults, $variantLinkCallback );
1147
1148 $stubPO = $this->createParserOutputStub( 'getCategories', $args );
1149
1150 // addParserOutput and addParserOutputMetadata should behave identically for us, so
1151 // alternate to get coverage for both without adding extra tests
1152 static $idx = 0;
1153 $idx++;
1154 $method = [ 'addParserOutputMetadata', 'addParserOutput' ][$idx % 2];
1155 $op->$method( $stubPO );
1156
1157 $this->doCategoryAsserts( $op, $expectedNormal, $expectedHidden );
1158 $this->doCategoryLinkAsserts( $op, $expectedNormal, $expectedHidden );
1159 }
1160
1161 /**
1162 * We allow different expectations for different tests as an associative array, like
1163 * [ 'set' => [ ... ], 'default' => [ ... ] ] if setCategoryLinks() will give a different
1164 * result.
1165 */
1166 private function extractExpectedCategories( array $expected, $key ) {
1167 if ( !$expected || isset( $expected[0] ) ) {
1168 return $expected;
1169 }
1170 return $expected[$key] ?? $expected['default'];
1171 }
1172
1173 private function setupCategoryTests(
1174 array $fakeResults, callable $variantLinkCallback = null
1175 ) : OutputPage {
1176 $this->setMwGlobals( 'wgUsePigLatinVariant', true );
1177
1178 $op = $this->getMockBuilder( OutputPage::class )
1179 ->setConstructorArgs( [ new RequestContext() ] )
1180 ->setMethods( [ 'addCategoryLinksToLBAndGetResult', 'getTitle' ] )
1181 ->getMock();
1182
1183 $title = Title::newFromText( 'My test page' );
1184 $op->expects( $this->any() )
1185 ->method( 'getTitle' )
1186 ->will( $this->returnValue( $title ) );
1187
1188 $op->expects( $this->any() )
1189 ->method( 'addCategoryLinksToLBAndGetResult' )
1190 ->will( $this->returnCallback( function ( array $categories ) use ( $fakeResults ) {
1191 $return = [];
1192 foreach ( $categories as $category => $unused ) {
1193 if ( isset( $fakeResults[$category] ) ) {
1194 $return[] = $fakeResults[$category];
1195 }
1196 }
1197 return new FakeResultWrapper( $return );
1198 } ) );
1199
1200 if ( $variantLinkCallback ) {
1201 $mockContLang = $this->getMockBuilder( Language::class )
1202 ->setConstructorArgs( [ 'en' ] )
1203 ->setMethods( [ 'findVariantLink' ] )
1204 ->getMock();
1205 $mockContLang->expects( $this->any() )
1206 ->method( 'findVariantLink' )
1207 ->will( $this->returnCallback( $variantLinkCallback ) );
1208 $this->setContentLang( $mockContLang );
1209 }
1210
1211 $this->assertSame( [], $op->getCategories() );
1212
1213 return $op;
1214 }
1215
1216 private function doCategoryAsserts( $op, $expectedNormal, $expectedHidden ) {
1217 $this->assertSame( array_merge( $expectedHidden, $expectedNormal ), $op->getCategories() );
1218 $this->assertSame( $expectedNormal, $op->getCategories( 'normal' ) );
1219 $this->assertSame( $expectedHidden, $op->getCategories( 'hidden' ) );
1220 }
1221
1222 private function doCategoryLinkAsserts( $op, $expectedNormal, $expectedHidden ) {
1223 $catLinks = $op->getCategoryLinks();
1224 $this->assertSame( (bool)$expectedNormal + (bool)$expectedHidden, count( $catLinks ) );
1225 if ( $expectedNormal ) {
1226 $this->assertSame( count( $expectedNormal ), count( $catLinks['normal'] ) );
1227 }
1228 if ( $expectedHidden ) {
1229 $this->assertSame( count( $expectedHidden ), count( $catLinks['hidden'] ) );
1230 }
1231
1232 foreach ( $expectedNormal as $i => $name ) {
1233 $this->assertContains( $name, $catLinks['normal'][$i] );
1234 }
1235 foreach ( $expectedHidden as $i => $name ) {
1236 $this->assertContains( $name, $catLinks['hidden'][$i] );
1237 }
1238 }
1239
1240 public function provideGetCategories() {
1241 return [
1242 'No categories' => [ [], [], null, [], [] ],
1243 'Simple test' => [
1244 [ 'Test1' => 'Some sortkey', 'Test2' => 'A different sortkey' ],
1245 [ 'Test1' => (object)[ 'pp_value' => 1, 'page_title' => 'Test1' ],
1246 'Test2' => (object)[ 'page_title' => 'Test2' ] ],
1247 null,
1248 [ 'Test2' ],
1249 [ 'Test1' ],
1250 ],
1251 'Invalid title' => [
1252 [ '[' => '[', 'Test' => 'Test' ],
1253 [ 'Test' => (object)[ 'page_title' => 'Test' ] ],
1254 null,
1255 [ 'Test' ],
1256 [],
1257 ],
1258 'Variant link' => [
1259 [ 'Test' => 'Test', 'Estay' => 'Estay' ],
1260 [ 'Test' => (object)[ 'page_title' => 'Test' ] ],
1261 function ( &$link, &$title ) {
1262 if ( $link === 'Estay' ) {
1263 $link = 'Test';
1264 $title = Title::makeTitleSafe( NS_CATEGORY, $link );
1265 }
1266 },
1267 // For adding one by one, the variant gets added as well as the original category,
1268 // but if you add them all together the second time gets skipped.
1269 [ 'onebyone' => [ 'Test', 'Test' ], 'default' => [ 'Test' ] ],
1270 [],
1271 ],
1272 ];
1273 }
1274
1275 /**
1276 * @covers OutputPage::getCategories
1277 */
1278 public function testGetCategoriesInvalid() {
1279 $this->setExpectedException( InvalidArgumentException::class,
1280 'Invalid category type given: hiddne' );
1281
1282 $op = $this->newInstance();
1283 $op->getCategories( 'hiddne' );
1284 }
1285
1286 // @todo Should we test addCategoryLinksToLBAndGetResult? If so, how? Insert some test rows in
1287 // the DB?
1288
1289 /**
1290 * @covers OutputPage::setIndicators
1291 * @covers OutputPage::getIndicators
1292 * @covers OutputPage::addParserOutputMetadata
1293 * @covers OutputPage::addParserOutput
1294 */
1295 public function testIndicators() {
1296 $op = $this->newInstance();
1297 $this->assertSame( [], $op->getIndicators() );
1298
1299 $op->setIndicators( [] );
1300 $this->assertSame( [], $op->getIndicators() );
1301
1302 // Test sorting alphabetically
1303 $op->setIndicators( [ 'b' => 'x', 'a' => 'y' ] );
1304 $this->assertSame( [ 'a' => 'y', 'b' => 'x' ], $op->getIndicators() );
1305
1306 // Test overwriting existing keys
1307 $op->setIndicators( [ 'c' => 'z', 'a' => 'w' ] );
1308 $this->assertSame( [ 'a' => 'w', 'b' => 'x', 'c' => 'z' ], $op->getIndicators() );
1309
1310 // Test with addParserOutputMetadata
1311 $pOut1 = $this->createParserOutputStub( 'getIndicators', [ 'c' => 'u', 'd' => 'v' ] );
1312 $op->addParserOutputMetadata( $pOut1 );
1313 $this->assertSame( [ 'a' => 'w', 'b' => 'x', 'c' => 'u', 'd' => 'v' ],
1314 $op->getIndicators() );
1315
1316 // Test with addParserOutput
1317 $pOut2 = $this->createParserOutputStub( 'getIndicators', [ 'a' => '!!!' ] );
1318 $op->addParserOutput( $pOut2 );
1319 $this->assertSame( [ 'a' => '!!!', 'b' => 'x', 'c' => 'u', 'd' => 'v' ],
1320 $op->getIndicators() );
1321 }
1322
1323 /**
1324 * @covers OutputPage::addHelpLink
1325 * @covers OutputPage::getIndicators
1326 */
1327 public function testAddHelpLink() {
1328 $op = $this->newInstance();
1329
1330 $op->addHelpLink( 'Manual:PHP unit testing' );
1331 $indicators = $op->getIndicators();
1332 $this->assertSame( [ 'mw-helplink' ], array_keys( $indicators ) );
1333 $this->assertContains( 'Manual:PHP_unit_testing', $indicators['mw-helplink'] );
1334
1335 $op->addHelpLink( 'https://phpunit.de', true );
1336 $indicators = $op->getIndicators();
1337 $this->assertSame( [ 'mw-helplink' ], array_keys( $indicators ) );
1338 $this->assertContains( 'https://phpunit.de', $indicators['mw-helplink'] );
1339 $this->assertNotContains( 'mediawiki', $indicators['mw-helplink'] );
1340 $this->assertNotContains( 'Manual:PHP', $indicators['mw-helplink'] );
1341 }
1342
1343 /**
1344 * @covers OutputPage::prependHTML
1345 * @covers OutputPage::addHTML
1346 * @covers OutputPage::addElement
1347 * @covers OutputPage::clearHTML
1348 * @covers OutputPage::getHTML
1349 */
1350 public function testBodyHTML() {
1351 $op = $this->newInstance();
1352 $this->assertSame( '', $op->getHTML() );
1353
1354 $op->addHTML( 'a' );
1355 $this->assertSame( 'a', $op->getHTML() );
1356
1357 $op->addHTML( 'b' );
1358 $this->assertSame( 'ab', $op->getHTML() );
1359
1360 $op->prependHTML( 'c' );
1361 $this->assertSame( 'cab', $op->getHTML() );
1362
1363 $op->addElement( 'p', [ 'id' => 'foo' ], 'd' );
1364 $this->assertSame( 'cab<p id="foo">d</p>', $op->getHTML() );
1365
1366 $op->clearHTML();
1367 $this->assertSame( '', $op->getHTML() );
1368 }
1369
1370 /**
1371 * @dataProvider provideRevisionId
1372 * @covers OutputPage::setRevisionId
1373 * @covers OutputPage::getRevisionId
1374 */
1375 public function testRevisionId( $newVal, $expected ) {
1376 $op = $this->newInstance();
1377
1378 $this->assertNull( $op->setRevisionId( $newVal ) );
1379 $this->assertSame( $expected, $op->getRevisionId() );
1380 $this->assertSame( $expected, $op->setRevisionId( null ) );
1381 $this->assertNull( $op->getRevisionId() );
1382 }
1383
1384 public function provideRevisionId() {
1385 return [
1386 [ null, null ],
1387 [ 7, 7 ],
1388 [ -1, -1 ],
1389 [ 3.2, 3 ],
1390 [ '0', 0 ],
1391 [ '32% finished', 32 ],
1392 [ false, 0 ],
1393 ];
1394 }
1395
1396 /**
1397 * @covers OutputPage::setRevisionTimestamp
1398 * @covers OutputPage::getRevisionTimestamp
1399 */
1400 public function testRevisionTimestamp() {
1401 $op = $this->newInstance();
1402 $this->assertNull( $op->getRevisionTimestamp() );
1403
1404 $this->assertNull( $op->setRevisionTimestamp( 'abc' ) );
1405 $this->assertSame( 'abc', $op->getRevisionTimestamp() );
1406 $this->assertSame( 'abc', $op->setRevisionTimestamp( null ) );
1407 $this->assertNull( $op->getRevisionTimestamp() );
1408 }
1409
1410 /**
1411 * @covers OutputPage::setFileVersion
1412 * @covers OutputPage::getFileVersion
1413 */
1414 public function testFileVersion() {
1415 $op = $this->newInstance();
1416 $this->assertNull( $op->getFileVersion() );
1417
1418 $stubFile = $this->createMock( File::class );
1419 $stubFile->method( 'exists' )->willReturn( true );
1420 $stubFile->method( 'getTimestamp' )->willReturn( '12211221123321' );
1421 $stubFile->method( 'getSha1' )->willReturn( 'bf3ffa7047dc080f5855377a4f83cd18887e3b05' );
1422
1423 $op->setFileVersion( $stubFile );
1424
1425 $this->assertEquals(
1426 [ 'time' => '12211221123321', 'sha1' => 'bf3ffa7047dc080f5855377a4f83cd18887e3b05' ],
1427 $op->getFileVersion()
1428 );
1429
1430 $stubMissingFile = $this->createMock( File::class );
1431 $stubMissingFile->method( 'exists' )->willReturn( false );
1432
1433 $op->setFileVersion( $stubMissingFile );
1434 $this->assertNull( $op->getFileVersion() );
1435
1436 $op->setFileVersion( $stubFile );
1437 $this->assertNotNull( $op->getFileVersion() );
1438
1439 $op->setFileVersion( null );
1440 $this->assertNull( $op->getFileVersion() );
1441 }
1442
1443 /**
1444 * Call either with arguments $methodName, $returnValue; or an array
1445 * [ $methodName => $returnValue, $methodName => $returnValue, ... ]
1446 */
1447 private function createParserOutputStub( ...$args ) {
1448 if ( count( $args ) === 0 ) {
1449 $retVals = [];
1450 } elseif ( count( $args ) === 1 ) {
1451 $retVals = $args[0];
1452 } elseif ( count( $args ) === 2 ) {
1453 $retVals = [ $args[0] => $args[1] ];
1454 }
1455 $pOut = $this->getMock( ParserOutput::class );
1456 foreach ( $retVals as $method => $retVal ) {
1457 $pOut->method( $method )->willReturn( $retVal );
1458 }
1459
1460 $arrayReturningMethods = [
1461 'getCategories',
1462 'getFileSearchOptions',
1463 'getHeadItems',
1464 'getIndicators',
1465 'getLanguageLinks',
1466 'getOutputHooks',
1467 'getTemplateIds',
1468 ];
1469
1470 foreach ( $arrayReturningMethods as $method ) {
1471 $pOut->method( $method )->willReturn( [] );
1472 }
1473
1474 return $pOut;
1475 }
1476
1477 /**
1478 * @covers OutputPage::getTemplateIds
1479 * @covers OutputPage::addParserOutputMetadata
1480 * @covers OutputPage::addParserOutput
1481 */
1482 public function testTemplateIds() {
1483 $op = $this->newInstance();
1484 $this->assertSame( [], $op->getTemplateIds() );
1485
1486 // Test with no template id's
1487 $stubPOEmpty = $this->createParserOutputStub();
1488 $op->addParserOutputMetadata( $stubPOEmpty );
1489 $this->assertSame( [], $op->getTemplateIds() );
1490
1491 // Test with some arbitrary template id's
1492 $ids = [
1493 NS_MAIN => [ 'A' => 3, 'B' => 17 ],
1494 NS_TALK => [ 'C' => 31 ],
1495 NS_MEDIA => [ 'D' => -1 ],
1496 ];
1497
1498 $stubPO1 = $this->createParserOutputStub( 'getTemplateIds', $ids );
1499
1500 $op->addParserOutputMetadata( $stubPO1 );
1501 $this->assertSame( $ids, $op->getTemplateIds() );
1502
1503 // Test merging with a second set of id's
1504 $stubPO2 = $this->createParserOutputStub( 'getTemplateIds', [
1505 NS_MAIN => [ 'E' => 1234 ],
1506 NS_PROJECT => [ 'F' => 5678 ],
1507 ] );
1508
1509 $finalIds = [
1510 NS_MAIN => [ 'E' => 1234, 'A' => 3, 'B' => 17 ],
1511 NS_TALK => [ 'C' => 31 ],
1512 NS_MEDIA => [ 'D' => -1 ],
1513 NS_PROJECT => [ 'F' => 5678 ],
1514 ];
1515
1516 $op->addParserOutput( $stubPO2 );
1517 $this->assertSame( $finalIds, $op->getTemplateIds() );
1518
1519 // Test merging with an empty set of id's
1520 $op->addParserOutputMetadata( $stubPOEmpty );
1521 $this->assertSame( $finalIds, $op->getTemplateIds() );
1522 }
1523
1524 /**
1525 * @covers OutputPage::getFileSearchOptions
1526 * @covers OutputPage::addParserOutputMetadata
1527 * @covers OutputPage::addParserOutput
1528 */
1529 public function testFileSearchOptions() {
1530 $op = $this->newInstance();
1531 $this->assertSame( [], $op->getFileSearchOptions() );
1532
1533 // Test with no files
1534 $stubPOEmpty = $this->createParserOutputStub();
1535
1536 $op->addParserOutputMetadata( $stubPOEmpty );
1537 $this->assertSame( [], $op->getFileSearchOptions() );
1538
1539 // Test with some arbitrary files
1540 $files1 = [
1541 'A' => [ 'time' => null, 'sha1' => '' ],
1542 'B' => [
1543 'time' => '12211221123321',
1544 'sha1' => 'bf3ffa7047dc080f5855377a4f83cd18887e3b05',
1545 ],
1546 ];
1547
1548 $stubPO1 = $this->createParserOutputStub( 'getFileSearchOptions', $files1 );
1549
1550 $op->addParserOutput( $stubPO1 );
1551 $this->assertSame( $files1, $op->getFileSearchOptions() );
1552
1553 // Test merging with a second set of files
1554 $files2 = [
1555 'C' => [ 'time' => null, 'sha1' => '' ],
1556 'B' => [ 'time' => null, 'sha1' => '' ],
1557 ];
1558
1559 $stubPO2 = $this->createParserOutputStub( 'getFileSearchOptions', $files2 );
1560
1561 $op->addParserOutputMetadata( $stubPO2 );
1562 $this->assertSame( array_merge( $files1, $files2 ), $op->getFileSearchOptions() );
1563
1564 // Test merging with an empty set of files
1565 $op->addParserOutput( $stubPOEmpty );
1566 $this->assertSame( array_merge( $files1, $files2 ), $op->getFileSearchOptions() );
1567 }
1568
1569 /**
1570 * @dataProvider provideAddWikiText
1571 * @covers OutputPage::addWikiText
1572 * @covers OutputPage::addWikiTextAsInterface
1573 * @covers OutputPage::wrapWikiTextAsInterface
1574 * @covers OutputPage::addWikiTextAsContent
1575 * @covers OutputPage::addWikiTextWithTitle
1576 * @covers OutputPage::addWikiTextTitle
1577 * @covers OutputPage::addWikiTextTidy
1578 * @covers OutputPage::addWikiTextTitleTidy
1579 * @covers OutputPage::getHTML
1580 */
1581 public function testAddWikiText( $method, array $args, $expected ) {
1582 $op = $this->newInstance();
1583 $this->assertSame( '', $op->getHTML() );
1584
1585 $this->hideDeprecated( 'OutputPage::addWikiText' );
1586 $this->hideDeprecated( 'OutputPage::addWikiTextTitle' );
1587 $this->hideDeprecated( 'OutputPage::addWikiTextWithTitle' );
1588 $this->hideDeprecated( 'OutputPage::addWikiTextTidy' );
1589 $this->hideDeprecated( 'OutputPage::addWikiTextTitleTidy' );
1590 $this->hideDeprecated( 'disabling tidy' );
1591
1592 if ( in_array(
1593 $method,
1594 [ 'addWikiTextWithTitle', 'addWikiTextTitleTidy', 'addWikiTextTitle' ]
1595 ) && count( $args ) >= 2 && $args[1] === null ) {
1596 // Special placeholder because we can't get the actual title in the provider
1597 $args[1] = $op->getTitle();
1598 }
1599 if ( in_array(
1600 $method,
1601 [ 'addWikiTextAsInterface', 'addWikiTextAsContent' ]
1602 ) && count( $args ) >= 3 && $args[2] === null ) {
1603 // Special placeholder because we can't get the actual title in the provider
1604 $args[2] = $op->getTitle();
1605 }
1606
1607 $op->$method( ...$args );
1608 $this->assertSame( $expected, $op->getHTML() );
1609 }
1610
1611 public function provideAddWikiText() {
1612 $tests = [
1613 'addWikiText' => [
1614 // Not tidied; this API is deprecated.
1615 'Simple wikitext' => [
1616 [ "'''Bold'''" ],
1617 "<p><b>Bold</b>\n</p>",
1618 ], 'List at start' => [
1619 [ '* List' ],
1620 "<ul><li>List</li></ul>\n",
1621 ], 'List not at start' => [
1622 [ '* Not a list', false ],
1623 '* Not a list',
1624 ], 'Non-interface' => [
1625 [ "'''Bold'''", true, false ],
1626 "<p><b>Bold</b>\n</p>",
1627 ], 'No section edit links' => [
1628 [ '== Title ==' ],
1629 "<h2><span class=\"mw-headline\" id=\"Title\">Title</span></h2>\n",
1630 ],
1631 ],
1632 'addWikiTextWithTitle' => [
1633 // Untidied; this API is deprecated
1634 'With title at start' => [
1635 [ '* {{PAGENAME}}', Title::newFromText( 'Talk:Some page' ) ],
1636 "<ul><li>Some page</li></ul>\n",
1637 ], 'With title at start' => [
1638 [ '* {{PAGENAME}}', Title::newFromText( 'Talk:Some page' ), false ],
1639 "* Some page",
1640 ],
1641 ],
1642 'addWikiTextAsInterface' => [
1643 // Preferred interface: output is tidied
1644 'Simple wikitext' => [
1645 [ "'''Bold'''" ],
1646 "<p><b>Bold</b>\n</p>",
1647 ], 'Untidy wikitext' => [
1648 [ "<b>Bold" ],
1649 "<p><b>Bold\n</b></p>",
1650 ], 'List at start' => [
1651 [ '* List' ],
1652 "<ul><li>List</li></ul>\n",
1653 ], 'List not at start' => [
1654 [ '* Not a list', false ],
1655 '<p>* Not a list</p>',
1656 ], 'No section edit links' => [
1657 [ '== Title ==' ],
1658 "<h2><span class=\"mw-headline\" id=\"Title\">Title</span></h2>\n",
1659 ], 'With title at start' => [
1660 [ '* {{PAGENAME}}', true, Title::newFromText( 'Talk:Some page' ) ],
1661 "<ul><li>Some page</li></ul>\n",
1662 ], 'With title at start' => [
1663 [ '* {{PAGENAME}}', false, Title::newFromText( 'Talk:Some page' ), false ],
1664 "<p>* Some page</p>",
1665 ], 'Untidy input' => [
1666 [ '<b>{{PAGENAME}}', true, Title::newFromText( 'Talk:Some page' ) ],
1667 "<p><b>Some page\n</b></p>",
1668 ],
1669 ],
1670 'addWikiTextAsContent' => [
1671 // Preferred interface: output is tidied
1672 'SpecialNewimages' => [
1673 [ "<p lang='en' dir='ltr'>\nMy message" ],
1674 '<p lang="en" dir="ltr">' . "\nMy message\n</p>"
1675 ], 'List at start' => [
1676 [ '* List' ],
1677 "<ul><li>List</li></ul>\n",
1678 ], 'List not at start' => [
1679 [ '* <b>Not a list', false ],
1680 '<p>* <b>Not a list</b></p>',
1681 ], 'With title at start' => [
1682 [ '* {{PAGENAME}}', true, Title::newFromText( 'Talk:Some page' ) ],
1683 "<ul><li>Some page</li></ul>\n",
1684 ], 'With title at start' => [
1685 [ '* {{PAGENAME}}', false, Title::newFromText( 'Talk:Some page' ), false ],
1686 "<p>* Some page</p>",
1687 ], 'EditPage' => [
1688 [ "<div class='mw-editintro'>{{PAGENAME}}", true, Title::newFromText( 'Talk:Some page' ) ],
1689 '<div class="mw-editintro">' . "Some page\n</div>"
1690 ],
1691 ],
1692 'wrapWikiTextAsInterface' => [
1693 'Simple' => [
1694 [ 'wrapperClass', 'text' ],
1695 "<div class=\"wrapperClass\"><p>text\n</p></div>"
1696 ], 'Spurious </div>' => [
1697 [ 'wrapperClass', 'text</div><div>more' ],
1698 "<div class=\"wrapperClass\"><p>text</p><div>more\n</div></div>"
1699 ], 'Extra newlines would break <p> wrappers' => [
1700 [ 'two classes', "1\n\n2\n\n3" ],
1701 "<div class=\"two classes\"><p>1\n</p><p>2\n</p><p>3\n</p></div>"
1702 ], 'Other unclosed tags' => [
1703 [ 'error', 'a<b>c<i>d' ],
1704 "<div class=\"error\"><p>a<b>c<i>d\n</i></b></p></div>"
1705 ],
1706 ],
1707 ];
1708
1709 // Test all the others on addWikiTextTitle as well
1710 foreach ( $tests['addWikiText'] as $key => $val ) {
1711 $args = [ $val[0][0], null, $val[0][1] ?? true, false, $val[0][2] ?? true ];
1712 $tests['addWikiTextTitle']["$key (addWikiTextTitle)"] =
1713 array_merge( [ $args ], array_slice( $val, 1 ) );
1714 }
1715 foreach ( $tests['addWikiTextWithTitle'] as $key => $val ) {
1716 $args = [ $val[0][0], $val[0][1], $val[0][2] ?? true ];
1717 $tests['addWikiTextTitle']["$key (addWikiTextTitle)"] =
1718 array_merge( [ $args ], array_slice( $val, 1 ) );
1719 }
1720 foreach ( $tests['addWikiTextAsInterface'] as $key => $val ) {
1721 $args = [ $val[0][0], $val[0][2] ?? null, $val[0][1] ?? true, true, true ];
1722 $tests['addWikiTextTitle']["$key (addWikiTextTitle)"] =
1723 array_merge( [ $args ], array_slice( $val, 1 ) );
1724 }
1725 foreach ( $tests['addWikiTextAsContent'] as $key => $val ) {
1726 $args = [ $val[0][0], $val[0][2] ?? null, $val[0][1] ?? true, true, false ];
1727 $tests['addWikiTextTitle']["$key (addWikiTextTitle)"] =
1728 array_merge( [ $args ], array_slice( $val, 1 ) );
1729 }
1730 // addWikiTextTidy / addWikiTextTitleTidy were old aliases of
1731 // addWikiTextAsContent
1732 foreach ( $tests['addWikiTextAsContent'] as $key => $val ) {
1733 if ( count( $val[0] ) > 2 ) {
1734 $args = [ $val[0][0], $val[0][2], $val[0][1] ?? true ];
1735 $tests['addWikiTextTitleTidy']["$key (addWikiTextTitleTidy)"] =
1736 array_merge( [ $args ], array_slice( $val, 1 ) );
1737 } else {
1738 $args = [ $val[0][0], $val[0][1] ?? true ];
1739 $tests['addWikiTextTidy']["$key (addWikiTextTidy)"] =
1740 array_merge( [ $args ], array_slice( $val, 1 ) );
1741 }
1742 }
1743
1744 // We have to reformat our array to match what PHPUnit wants
1745 $ret = [];
1746 foreach ( $tests as $key => $subarray ) {
1747 foreach ( $subarray as $subkey => $val ) {
1748 $val = array_merge( [ $key ], $val );
1749 $ret[$subkey] = $val;
1750 }
1751 }
1752
1753 return $ret;
1754 }
1755
1756 /**
1757 * @covers OutputPage::addWikiText
1758 */
1759 public function testAddWikiTextNoTitle() {
1760 $this->hideDeprecated( 'OutputPage::addWikiText' );
1761 $this->setExpectedException( MWException::class, 'Title is null' );
1762
1763 $op = $this->newInstance( [], null, 'notitle' );
1764 $op->addWikiText( 'a' );
1765 }
1766
1767 /**
1768 * @covers OutputPage::addWikiTextAsInterface
1769 */
1770 public function testAddWikiTextAsInterfaceNoTitle() {
1771 $this->setExpectedException( MWException::class, 'Title is null' );
1772
1773 $op = $this->newInstance( [], null, 'notitle' );
1774 $op->addWikiTextAsInterface( 'a' );
1775 }
1776
1777 /**
1778 * @covers OutputPage::addWikiTextAsContent
1779 */
1780 public function testAddWikiTextAsContentNoTitle() {
1781 $this->setExpectedException( MWException::class, 'Title is null' );
1782
1783 $op = $this->newInstance( [], null, 'notitle' );
1784 $op->addWikiTextAsContent( 'a' );
1785 }
1786
1787 /**
1788 * @covers OutputPage::addWikiMsg
1789 */
1790 public function testAddWikiMsg() {
1791 $msg = wfMessage( 'parentheses' );
1792 $this->assertSame( '(a)', $msg->rawParams( 'a' )->plain() );
1793
1794 $op = $this->newInstance();
1795 $this->assertSame( '', $op->getHTML() );
1796 $op->addWikiMsg( 'parentheses', "<b>a" );
1797 // The input is bad unbalanced HTML, but the output is tidied
1798 $this->assertSame( "<p>(<b>a)\n</b></p>", $op->getHTML() );
1799 }
1800
1801 /**
1802 * @covers OutputPage::wrapWikiMsg
1803 */
1804 public function testWrapWikiMsg() {
1805 $msg = wfMessage( 'parentheses' );
1806 $this->assertSame( '(a)', $msg->rawParams( 'a' )->plain() );
1807
1808 $op = $this->newInstance();
1809 $this->assertSame( '', $op->getHTML() );
1810 $op->wrapWikiMsg( '[$1]', [ 'parentheses', "<b>a" ] );
1811 // The input is bad unbalanced HTML, but the output is tidied
1812 $this->assertSame( "<p>[(<b>a)]\n</b></p>", $op->getHTML() );
1813 }
1814
1815 /**
1816 * @covers OutputPage::addParserOutputMetadata
1817 * @covers OutputPage::addParserOutput
1818 */
1819 public function testNoGallery() {
1820 $op = $this->newInstance();
1821 $this->assertFalse( $op->mNoGallery );
1822
1823 $stubPO1 = $this->createParserOutputStub( 'getNoGallery', true );
1824 $op->addParserOutputMetadata( $stubPO1 );
1825 $this->assertTrue( $op->mNoGallery );
1826
1827 $stubPO2 = $this->createParserOutputStub( 'getNoGallery', false );
1828 $op->addParserOutput( $stubPO2 );
1829 $this->assertFalse( $op->mNoGallery );
1830 }
1831
1832 private static $parserOutputHookCalled;
1833
1834 /**
1835 * @covers OutputPage::addParserOutputMetadata
1836 */
1837 public function testParserOutputHooks() {
1838 $op = $this->newInstance();
1839 $pOut = $this->createParserOutputStub( 'getOutputHooks', [
1840 [ 'myhook', 'banana' ],
1841 [ 'yourhook', 'kumquat' ],
1842 [ 'theirhook', 'hippopotamus' ],
1843 ] );
1844
1845 self::$parserOutputHookCalled = [];
1846
1847 $this->setMwGlobals( 'wgParserOutputHooks', [
1848 'myhook' => function ( OutputPage $innerOp, ParserOutput $innerPOut, $data )
1849 use ( $op, $pOut ) {
1850 $this->assertSame( $op, $innerOp );
1851 $this->assertSame( $pOut, $innerPOut );
1852 $this->assertSame( 'banana', $data );
1853 self::$parserOutputHookCalled[] = 'closure';
1854 },
1855 'yourhook' => [ $this, 'parserOutputHookCallback' ],
1856 'theirhook' => [ __CLASS__, 'parserOutputHookCallbackStatic' ],
1857 'uncalled' => function () {
1858 $this->assertTrue( false );
1859 },
1860 ] );
1861
1862 $op->addParserOutputMetadata( $pOut );
1863
1864 $this->assertSame( [ 'closure', 'callback', 'static' ], self::$parserOutputHookCalled );
1865 }
1866
1867 public function parserOutputHookCallback(
1868 OutputPage $op, ParserOutput $pOut, $data
1869 ) {
1870 $this->assertSame( 'kumquat', $data );
1871
1872 self::$parserOutputHookCalled[] = 'callback';
1873 }
1874
1875 public static function parserOutputHookCallbackStatic(
1876 OutputPage $op, ParserOutput $pOut, $data
1877 ) {
1878 // All the assert methods are actually static, who knew!
1879 self::assertSame( 'hippopotamus', $data );
1880
1881 self::$parserOutputHookCalled[] = 'static';
1882 }
1883
1884 // @todo Make sure to test the following in addParserOutputMetadata() as well when we add tests
1885 // for them:
1886 // * addModules()
1887 // * addModuleStyles()
1888 // * addJsConfigVars()
1889 // * enableOOUI()
1890 // Otherwise those lines of addParserOutputMetadata() will be reported as covered, but we won't
1891 // be testing they actually work.
1892
1893 /**
1894 * @covers OutputPage::addParserOutputText
1895 */
1896 public function testAddParserOutputText() {
1897 $op = $this->newInstance();
1898 $this->assertSame( '', $op->getHTML() );
1899
1900 $pOut = $this->createParserOutputStub( 'getText', '<some text>' );
1901
1902 $op->addParserOutputMetadata( $pOut );
1903 $this->assertSame( '', $op->getHTML() );
1904
1905 $op->addParserOutputText( $pOut );
1906 $this->assertSame( '<some text>', $op->getHTML() );
1907 }
1908
1909 /**
1910 * @covers OutputPage::addParserOutput
1911 */
1912 public function testAddParserOutput() {
1913 $op = $this->newInstance();
1914 $this->assertSame( '', $op->getHTML() );
1915 $this->assertFalse( $op->showNewSectionLink() );
1916
1917 $pOut = $this->createParserOutputStub( [
1918 'getText' => '<some text>',
1919 'getNewSection' => true,
1920 ] );
1921
1922 $op->addParserOutput( $pOut );
1923 $this->assertSame( '<some text>', $op->getHTML() );
1924 $this->assertTrue( $op->showNewSectionLink() );
1925 }
1926
1927 /**
1928 * @covers OutputPage::addTemplate
1929 */
1930 public function testAddTemplate() {
1931 $template = $this->getMock( QuickTemplate::class );
1932 $template->method( 'getHTML' )->willReturn( '<abc>&def;' );
1933
1934 $op = $this->newInstance();
1935 $op->addTemplate( $template );
1936
1937 $this->assertSame( '<abc>&def;', $op->getHTML() );
1938 }
1939
1940 /**
1941 * @dataProvider provideParse
1942 * @covers OutputPage::parse
1943 * @param array $args To pass to parse()
1944 * @param string $expectedHTML Expected return value for parse()
1945 * @param string $expectedHTML Expected return value for parseInline(), if different
1946 */
1947 public function testParse( array $args, $expectedHTML ) {
1948 $this->hideDeprecated( 'OutputPage::parse' );
1949 $op = $this->newInstance();
1950 $this->assertSame( $expectedHTML, $op->parse( ...$args ) );
1951 }
1952
1953 /**
1954 * @dataProvider provideParse
1955 * @covers OutputPage::parseInline
1956 */
1957 public function testParseInline( array $args, $expectedHTML, $expectedHTMLInline = null ) {
1958 if ( count( $args ) > 3 ) {
1959 // $language param not supported
1960 $this->assertTrue( true );
1961 return;
1962 }
1963 $this->hideDeprecated( 'OutputPage::parseInline' );
1964 $op = $this->newInstance();
1965 $this->assertSame( $expectedHTMLInline ?? $expectedHTML, $op->parseInline( ...$args ) );
1966 }
1967
1968 public function provideParse() {
1969 return [
1970 'List at start of line (content)' => [
1971 [ '* List', true, false ],
1972 "<div class=\"mw-parser-output\"><ul><li>List</li></ul>\n</div>",
1973 "<ul><li>List</li></ul>\n",
1974 ],
1975 'List at start of line (interface)' => [
1976 [ '* List', true, true ],
1977 "<ul><li>List</li></ul>\n",
1978 ],
1979 'List not at start (content)' => [
1980 [ "* ''Not'' list", false, false ],
1981 '<div class="mw-parser-output">* <i>Not</i> list</div>',
1982 '* <i>Not</i> list',
1983 ],
1984 'List not at start (interface)' => [
1985 [ "* ''Not'' list", false, true ],
1986 '* <i>Not</i> list',
1987 ],
1988 'Interface message' => [
1989 [ "''Italic''", true, true ],
1990 "<p><i>Italic</i>\n</p>",
1991 '<i>Italic</i>',
1992 ],
1993 'formatnum (content)' => [
1994 [ '{{formatnum:123456.789}}', true, false ],
1995 "<div class=\"mw-parser-output\"><p>123,456.789\n</p></div>",
1996 "123,456.789",
1997 ],
1998 'formatnum (interface)' => [
1999 [ '{{formatnum:123456.789}}', true, true ],
2000 "<p>123,456.789\n</p>",
2001 "123,456.789",
2002 ],
2003 'Language (content)' => [
2004 [ '{{formatnum:123456.789}}', true, false, Language::factory( 'is' ) ],
2005 "<div class=\"mw-parser-output\"><p>123.456,789\n</p></div>",
2006 ],
2007 'Language (interface)' => [
2008 [ '{{formatnum:123456.789}}', true, true, Language::factory( 'is' ) ],
2009 "<p>123.456,789\n</p>",
2010 '123.456,789',
2011 ],
2012 'No section edit links' => [
2013 [ '== Header ==' ],
2014 '<div class="mw-parser-output"><h2><span class="mw-headline" id="Header">' .
2015 "Header</span></h2>\n</div>",
2016 '<h2><span class="mw-headline" id="Header">Header</span></h2>' .
2017 "\n",
2018 ]
2019 ];
2020 }
2021
2022 /**
2023 * @dataProvider provideParseAs
2024 * @covers OutputPage::parseAsContent
2025 * @param array $args To pass to parse()
2026 * @param string $expectedHTML Expected return value for parseAsContent()
2027 * @param string $expectedHTML Expected return value for parseInlineAsInterface(), if different
2028 */
2029 public function testParseAsContent(
2030 array $args, $expectedHTML, $expectedHTMLInline = null
2031 ) {
2032 $op = $this->newInstance();
2033 $this->assertSame( $expectedHTML, $op->parseAsContent( ...$args ) );
2034 }
2035
2036 /**
2037 * @dataProvider provideParseAs
2038 * @covers OutputPage::parseAsInterface
2039 * @param array $args To pass to parse()
2040 * @param string $expectedHTML Expected return value for parseAsInterface()
2041 * @param string $expectedHTML Expected return value for parseInlineAsInterface(), if different
2042 */
2043 public function testParseAsInterface(
2044 array $args, $expectedHTML, $expectedHTMLInline = null
2045 ) {
2046 $op = $this->newInstance();
2047 $this->assertSame( $expectedHTML, $op->parseAsInterface( ...$args ) );
2048 }
2049
2050 /**
2051 * @dataProvider provideParseAs
2052 * @covers OutputPage::parseInlineAsInterface
2053 */
2054 public function testParseInlineAsInterface(
2055 array $args, $expectedHTML, $expectedHTMLInline = null
2056 ) {
2057 $op = $this->newInstance();
2058 $this->assertSame(
2059 $expectedHTMLInline ?? $expectedHTML,
2060 $op->parseInlineAsInterface( ...$args )
2061 );
2062 }
2063
2064 public function provideParseAs() {
2065 return [
2066 'List at start of line' => [
2067 [ '* List', true ],
2068 "<ul><li>List</li></ul>\n",
2069 ],
2070 'List not at start' => [
2071 [ "* ''Not'' list", false ],
2072 '<p>* <i>Not</i> list</p>',
2073 '* <i>Not</i> list',
2074 ],
2075 'Italics' => [
2076 [ "''Italic''", true ],
2077 "<p><i>Italic</i>\n</p>",
2078 '<i>Italic</i>',
2079 ],
2080 'formatnum' => [
2081 [ '{{formatnum:123456.789}}', true ],
2082 "<p>123,456.789\n</p>",
2083 "123,456.789",
2084 ],
2085 'No section edit links' => [
2086 [ '== Header ==' ],
2087 '<h2><span class="mw-headline" id="Header">Header</span></h2>' .
2088 "\n",
2089 ]
2090 ];
2091 }
2092
2093 /**
2094 * @covers OutputPage::parse
2095 */
2096 public function testParseNullTitle() {
2097 $this->hideDeprecated( 'OutputPage::parse' );
2098 $this->setExpectedException( MWException::class, 'Empty $mTitle in OutputPage::parseInternal' );
2099 $op = $this->newInstance( [], null, 'notitle' );
2100 $op->parse( '' );
2101 }
2102
2103 /**
2104 * @covers OutputPage::parseInline
2105 */
2106 public function testParseInlineNullTitle() {
2107 $this->hideDeprecated( 'OutputPage::parseInline' );
2108 $this->setExpectedException( MWException::class, 'Empty $mTitle in OutputPage::parseInternal' );
2109 $op = $this->newInstance( [], null, 'notitle' );
2110 $op->parseInline( '' );
2111 }
2112
2113 /**
2114 * @covers OutputPage::parseAsContent
2115 */
2116 public function testParseAsContentNullTitle() {
2117 $this->setExpectedException( MWException::class, 'Empty $mTitle in OutputPage::parseInternal' );
2118 $op = $this->newInstance( [], null, 'notitle' );
2119 $op->parseAsContent( '' );
2120 }
2121
2122 /**
2123 * @covers OutputPage::parseAsInterface
2124 */
2125 public function testParseAsInterfaceNullTitle() {
2126 $this->setExpectedException( MWException::class, 'Empty $mTitle in OutputPage::parseInternal' );
2127 $op = $this->newInstance( [], null, 'notitle' );
2128 $op->parseAsInterface( '' );
2129 }
2130
2131 /**
2132 * @covers OutputPage::parseInlineAsInterface
2133 */
2134 public function testParseInlineAsInterfaceNullTitle() {
2135 $this->setExpectedException( MWException::class, 'Empty $mTitle in OutputPage::parseInternal' );
2136 $op = $this->newInstance( [], null, 'notitle' );
2137 $op->parseInlineAsInterface( '' );
2138 }
2139
2140 /**
2141 * @covers OutputPage::setCdnMaxage
2142 * @covers OutputPage::lowerCdnMaxage
2143 */
2144 public function testCdnMaxage() {
2145 $op = $this->newInstance();
2146 $wrapper = TestingAccessWrapper::newFromObject( $op );
2147 $this->assertSame( 0, $wrapper->mCdnMaxage );
2148
2149 $op->setCdnMaxage( -1 );
2150 $this->assertSame( -1, $wrapper->mCdnMaxage );
2151
2152 $op->setCdnMaxage( 120 );
2153 $this->assertSame( 120, $wrapper->mCdnMaxage );
2154
2155 $op->setCdnMaxage( 60 );
2156 $this->assertSame( 60, $wrapper->mCdnMaxage );
2157
2158 $op->setCdnMaxage( 180 );
2159 $this->assertSame( 180, $wrapper->mCdnMaxage );
2160
2161 $op->lowerCdnMaxage( 240 );
2162 $this->assertSame( 180, $wrapper->mCdnMaxage );
2163
2164 $op->setCdnMaxage( 300 );
2165 $this->assertSame( 240, $wrapper->mCdnMaxage );
2166
2167 $op->lowerCdnMaxage( 120 );
2168 $this->assertSame( 120, $wrapper->mCdnMaxage );
2169
2170 $op->setCdnMaxage( 180 );
2171 $this->assertSame( 120, $wrapper->mCdnMaxage );
2172
2173 $op->setCdnMaxage( 60 );
2174 $this->assertSame( 60, $wrapper->mCdnMaxage );
2175
2176 $op->setCdnMaxage( 240 );
2177 $this->assertSame( 120, $wrapper->mCdnMaxage );
2178 }
2179
2180 /** @var int Faked time to set for tests that need it */
2181 private static $fakeTime;
2182
2183 /**
2184 * @dataProvider provideAdaptCdnTTL
2185 * @covers OutputPage::adaptCdnTTL
2186 * @param array $args To pass to adaptCdnTTL()
2187 * @param int $expected Expected new value of mCdnMaxageLimit
2188 * @param array $options Associative array:
2189 * initialMaxage => Maxage to set before calling adaptCdnTTL() (default 86400)
2190 */
2191 public function testAdaptCdnTTL( array $args, $expected, array $options = [] ) {
2192 try {
2193 MWTimestamp::setFakeTime( self::$fakeTime );
2194
2195 $op = $this->newInstance();
2196 // Set a high maxage so that it will get reduced by adaptCdnTTL(). The default maxage
2197 // is 0, so adaptCdnTTL() won't mutate the object at all.
2198 $initial = $options['initialMaxage'] ?? 86400;
2199 $op->setCdnMaxage( $initial );
2200
2201 $op->adaptCdnTTL( ...$args );
2202 } finally {
2203 MWTimestamp::setFakeTime( false );
2204 }
2205
2206 $wrapper = TestingAccessWrapper::newFromObject( $op );
2207
2208 // Special rules for false/null
2209 if ( $args[0] === null || $args[0] === false ) {
2210 $this->assertSame( $initial, $wrapper->mCdnMaxage, 'member value' );
2211 $op->setCdnMaxage( $expected + 1 );
2212 $this->assertSame( $expected + 1, $wrapper->mCdnMaxage, 'member value after new set' );
2213 return;
2214 }
2215
2216 $this->assertSame( $expected, $wrapper->mCdnMaxageLimit, 'limit value' );
2217
2218 if ( $initial >= $expected ) {
2219 $this->assertSame( $expected, $wrapper->mCdnMaxage, 'member value' );
2220 } else {
2221 $this->assertSame( $initial, $wrapper->mCdnMaxage, 'member value' );
2222 }
2223
2224 $op->setCdnMaxage( $expected + 1 );
2225 $this->assertSame( $expected, $wrapper->mCdnMaxage, 'member value after new set' );
2226 }
2227
2228 public function provideAdaptCdnTTL() {
2229 global $wgSquidMaxage;
2230 $now = time();
2231 self::$fakeTime = $now;
2232 return [
2233 'Five minutes ago' => [ [ $now - 300 ], 270 ],
2234 'Now' => [ [ +0 ], IExpiringStore::TTL_MINUTE ],
2235 'Five minutes from now' => [ [ $now + 300 ], IExpiringStore::TTL_MINUTE ],
2236 'Five minutes ago, initial maxage four minutes' =>
2237 [ [ $now - 300 ], 270, [ 'initialMaxage' => 240 ] ],
2238 'A very long time ago' => [ [ $now - 1000000000 ], $wgSquidMaxage ],
2239 'Initial maxage zero' => [ [ $now - 300 ], 270, [ 'initialMaxage' => 0 ] ],
2240
2241 'false' => [ [ false ], IExpiringStore::TTL_MINUTE ],
2242 'null' => [ [ null ], IExpiringStore::TTL_MINUTE ],
2243 "'0'" => [ [ '0' ], IExpiringStore::TTL_MINUTE ],
2244 'Empty string' => [ [ '' ], IExpiringStore::TTL_MINUTE ],
2245 // @todo These give incorrect results due to timezones, how to test?
2246 //"'now'" => [ [ 'now' ], IExpiringStore::TTL_MINUTE ],
2247 //"'parse error'" => [ [ 'parse error' ], IExpiringStore::TTL_MINUTE ],
2248
2249 'Now, minTTL 0' => [ [ $now, 0 ], IExpiringStore::TTL_MINUTE ],
2250 'Now, minTTL 0.000001' => [ [ $now, 0.000001 ], 0 ],
2251 'A very long time ago, maxTTL even longer' =>
2252 [ [ $now - 1000000000, 0, 1000000001 ], 900000000 ],
2253 ];
2254 }
2255
2256 /**
2257 * @covers OutputPage::enableClientCache
2258 * @covers OutputPage::addParserOutputMetadata
2259 * @covers OutputPage::addParserOutput
2260 */
2261 public function testClientCache() {
2262 $op = $this->newInstance();
2263
2264 // Test initial value
2265 $this->assertSame( true, $op->enableClientCache( null ) );
2266 // Test that calling with null doesn't change the value
2267 $this->assertSame( true, $op->enableClientCache( null ) );
2268
2269 // Test setting to false
2270 $this->assertSame( true, $op->enableClientCache( false ) );
2271 $this->assertSame( false, $op->enableClientCache( null ) );
2272 // Test that calling with null doesn't change the value
2273 $this->assertSame( false, $op->enableClientCache( null ) );
2274
2275 // Test that a cacheable ParserOutput doesn't set to true
2276 $pOutCacheable = $this->createParserOutputStub( 'isCacheable', true );
2277 $op->addParserOutputMetadata( $pOutCacheable );
2278 $this->assertSame( false, $op->enableClientCache( null ) );
2279
2280 // Test setting back to true
2281 $this->assertSame( false, $op->enableClientCache( true ) );
2282 $this->assertSame( true, $op->enableClientCache( null ) );
2283
2284 // Test that an uncacheable ParserOutput does set to false
2285 $pOutUncacheable = $this->createParserOutputStub( 'isCacheable', false );
2286 $op->addParserOutput( $pOutUncacheable );
2287 $this->assertSame( false, $op->enableClientCache( null ) );
2288 }
2289
2290 /**
2291 * @covers OutputPage::getCacheVaryCookies
2292 */
2293 public function testGetCacheVaryCookies() {
2294 global $wgCookiePrefix, $wgDBname;
2295 $op = $this->newInstance();
2296 $prefix = $wgCookiePrefix !== false ? $wgCookiePrefix : $wgDBname;
2297 $expectedCookies = [
2298 "{$prefix}Token",
2299 "{$prefix}LoggedOut",
2300 "{$prefix}_session",
2301 'forceHTTPS',
2302 'cookie1',
2303 'cookie2',
2304 ];
2305
2306 // We have to reset the cookies because getCacheVaryCookies may have already been called
2307 TestingAccessWrapper::newFromClass( OutputPage::class )->cacheVaryCookies = null;
2308
2309 $this->setMwGlobals( 'wgCacheVaryCookies', [ 'cookie1' ] );
2310 $this->setTemporaryHook( 'GetCacheVaryCookies',
2311 function ( $innerOP, &$cookies ) use ( $op, $expectedCookies ) {
2312 $this->assertSame( $op, $innerOP );
2313 $cookies[] = 'cookie2';
2314 $this->assertSame( $expectedCookies, $cookies );
2315 }
2316 );
2317
2318 $this->assertSame( $expectedCookies, $op->getCacheVaryCookies() );
2319 }
2320
2321 /**
2322 * @covers OutputPage::haveCacheVaryCookies
2323 */
2324 public function testHaveCacheVaryCookies() {
2325 $request = new FauxRequest();
2326 $op = $this->newInstance( [], $request );
2327
2328 // No cookies are set.
2329 $this->assertFalse( $op->haveCacheVaryCookies() );
2330
2331 // 'Token' is present but empty, so it shouldn't count.
2332 $request->setCookie( 'Token', '' );
2333 $this->assertFalse( $op->haveCacheVaryCookies() );
2334
2335 // 'Token' present and nonempty.
2336 $request->setCookie( 'Token', '123' );
2337 $this->assertTrue( $op->haveCacheVaryCookies() );
2338 }
2339
2340 /**
2341 * @dataProvider provideVaryHeaders
2342 *
2343 * @covers OutputPage::addVaryHeader
2344 * @covers OutputPage::getVaryHeader
2345 * @covers OutputPage::getKeyHeader
2346 *
2347 * @param array[] $calls For each array, call addVaryHeader() with those arguments
2348 * @param string[] $cookies Array of cookie names to vary on
2349 * @param string $vary Text of expected Vary header (including the 'Vary: ')
2350 * @param string $key Text of expected Key header (including the 'Key: ')
2351 */
2352 public function testVaryHeaders( array $calls, array $cookies, $vary, $key ) {
2353 // Get rid of default Vary fields
2354 $op = $this->getMockBuilder( OutputPage::class )
2355 ->setConstructorArgs( [ new RequestContext() ] )
2356 ->setMethods( [ 'getCacheVaryCookies' ] )
2357 ->getMock();
2358 $op->expects( $this->any() )
2359 ->method( 'getCacheVaryCookies' )
2360 ->will( $this->returnValue( $cookies ) );
2361 TestingAccessWrapper::newFromObject( $op )->mVaryHeader = [];
2362
2363 $this->hideDeprecated( '$wgUseKeyHeader' );
2364 foreach ( $calls as $call ) {
2365 $op->addVaryHeader( ...$call );
2366 }
2367 $this->assertEquals( $vary, $op->getVaryHeader(), 'Vary:' );
2368 $this->assertEquals( $key, $op->getKeyHeader(), 'Key:' );
2369 }
2370
2371 public function provideVaryHeaders() {
2372 // note: getKeyHeader() automatically adds Vary: Cookie
2373 return [
2374 'No header' => [
2375 [],
2376 [],
2377 'Vary: ',
2378 'Key: Cookie',
2379 ],
2380 'Single header' => [
2381 [
2382 [ 'Cookie' ],
2383 ],
2384 [],
2385 'Vary: Cookie',
2386 'Key: Cookie',
2387 ],
2388 'Non-unique headers' => [
2389 [
2390 [ 'Cookie' ],
2391 [ 'Accept-Language' ],
2392 [ 'Cookie' ],
2393 ],
2394 [],
2395 'Vary: Cookie, Accept-Language',
2396 'Key: Cookie,Accept-Language',
2397 ],
2398 'Two headers with single options' => [
2399 [
2400 [ 'Cookie', [ 'param=phpsessid' ] ],
2401 [ 'Accept-Language', [ 'substr=en' ] ],
2402 ],
2403 [],
2404 'Vary: Cookie, Accept-Language',
2405 'Key: Cookie;param=phpsessid,Accept-Language;substr=en',
2406 ],
2407 'One header with multiple options' => [
2408 [
2409 [ 'Cookie', [ 'param=phpsessid', 'param=userId' ] ],
2410 ],
2411 [],
2412 'Vary: Cookie',
2413 'Key: Cookie;param=phpsessid;param=userId',
2414 ],
2415 'Duplicate option' => [
2416 [
2417 [ 'Cookie', [ 'param=phpsessid' ] ],
2418 [ 'Cookie', [ 'param=phpsessid' ] ],
2419 [ 'Accept-Language', [ 'substr=en', 'substr=en' ] ],
2420 ],
2421 [],
2422 'Vary: Cookie, Accept-Language',
2423 'Key: Cookie;param=phpsessid,Accept-Language;substr=en',
2424 ],
2425 'Same header, different options' => [
2426 [
2427 [ 'Cookie', [ 'param=phpsessid' ] ],
2428 [ 'Cookie', [ 'param=userId' ] ],
2429 ],
2430 [],
2431 'Vary: Cookie',
2432 'Key: Cookie;param=phpsessid;param=userId',
2433 ],
2434 'No header, vary cookies' => [
2435 [],
2436 [ 'cookie1', 'cookie2' ],
2437 'Vary: Cookie',
2438 'Key: Cookie;param=cookie1;param=cookie2',
2439 ],
2440 'Cookie header with option plus vary cookies' => [
2441 [
2442 [ 'Cookie', [ 'param=cookie1' ] ],
2443 ],
2444 [ 'cookie2', 'cookie3' ],
2445 'Vary: Cookie',
2446 'Key: Cookie;param=cookie1;param=cookie2;param=cookie3',
2447 ],
2448 'Non-cookie header plus vary cookies' => [
2449 [
2450 [ 'Accept-Language' ],
2451 ],
2452 [ 'cookie' ],
2453 'Vary: Accept-Language, Cookie',
2454 'Key: Accept-Language,Cookie;param=cookie',
2455 ],
2456 'Cookie and non-cookie headers plus vary cookies' => [
2457 [
2458 [ 'Cookie', [ 'param=cookie1' ] ],
2459 [ 'Accept-Language' ],
2460 ],
2461 [ 'cookie2' ],
2462 'Vary: Cookie, Accept-Language',
2463 'Key: Cookie;param=cookie1;param=cookie2,Accept-Language',
2464 ],
2465 ];
2466 }
2467
2468 /**
2469 * @covers OutputPage::getVaryHeader
2470 */
2471 public function testVaryHeaderDefault() {
2472 $op = $this->newInstance();
2473 $this->assertSame( 'Vary: Accept-Encoding, Cookie', $op->getVaryHeader() );
2474 }
2475
2476 /**
2477 * @dataProvider provideLinkHeaders
2478 *
2479 * @covers OutputPage::addLinkHeader
2480 * @covers OutputPage::getLinkHeader
2481 */
2482 public function testLinkHeaders( array $headers, $result ) {
2483 $op = $this->newInstance();
2484
2485 foreach ( $headers as $header ) {
2486 $op->addLinkHeader( $header );
2487 }
2488
2489 $this->assertEquals( $result, $op->getLinkHeader() );
2490 }
2491
2492 public function provideLinkHeaders() {
2493 return [
2494 [
2495 [],
2496 false
2497 ],
2498 [
2499 [ '<https://foo/bar.jpg>;rel=preload;as=image' ],
2500 'Link: <https://foo/bar.jpg>;rel=preload;as=image',
2501 ],
2502 [
2503 [
2504 '<https://foo/bar.jpg>;rel=preload;as=image',
2505 '<https://foo/baz.jpg>;rel=preload;as=image'
2506 ],
2507 'Link: <https://foo/bar.jpg>;rel=preload;as=image,<https://foo/baz.jpg>;' .
2508 'rel=preload;as=image',
2509 ],
2510 ];
2511 }
2512
2513 /**
2514 * @dataProvider provideAddAcceptLanguage
2515 * @covers OutputPage::addAcceptLanguage
2516 * @covers OutputPage::getKeyHeader
2517 */
2518 public function testAddAcceptLanguage(
2519 $code, array $variants, array $expected, array $options = []
2520 ) {
2521 $req = new FauxRequest( in_array( 'varianturl', $options ) ? [ 'variant' => 'x' ] : [] );
2522 $op = $this->newInstance( [], $req, in_array( 'notitle', $options ) ? 'notitle' : null );
2523
2524 if ( !in_array( 'notitle', $options ) ) {
2525 $mockLang = $this->getMock( Language::class );
2526
2527 if ( in_array( 'varianturl', $options ) ) {
2528 $mockLang->expects( $this->never() )->method( $this->anything() );
2529 } else {
2530 $mockLang->method( 'hasVariants' )->willReturn( count( $variants ) > 1 );
2531 $mockLang->method( 'getVariants' )->willReturn( $variants );
2532 $mockLang->method( 'getCode' )->willReturn( $code );
2533 }
2534
2535 $mockTitle = $this->getMock( Title::class );
2536 $mockTitle->method( 'getPageLanguage' )->willReturn( $mockLang );
2537
2538 $op->setTitle( $mockTitle );
2539 }
2540
2541 // This will run addAcceptLanguage()
2542 $op->sendCacheControl();
2543
2544 $this->hideDeprecated( '$wgUseKeyHeader' );
2545 $keyHeader = $op->getKeyHeader();
2546
2547 if ( !$expected ) {
2548 $this->assertFalse( strpos( 'Accept-Language', $keyHeader ) );
2549 return;
2550 }
2551
2552 $keyHeader = explode( ' ', $keyHeader, 2 )[1];
2553 $keyHeader = explode( ',', $keyHeader );
2554
2555 $acceptLanguage = null;
2556 foreach ( $keyHeader as $item ) {
2557 if ( strpos( $item, 'Accept-Language;' ) === 0 ) {
2558 $acceptLanguage = $item;
2559 break;
2560 }
2561 }
2562
2563 $expectedString = 'Accept-Language;substr=' . implode( ';substr=', $expected );
2564 $this->assertSame( $expectedString, $acceptLanguage );
2565 }
2566
2567 public function provideAddAcceptLanguage() {
2568 return [
2569 'No variants' => [ 'en', [ 'en' ], [] ],
2570 'One simple variant' => [ 'en', [ 'en', 'en-x-piglatin' ], [ 'en-x-piglatin' ] ],
2571 'Multiple variants with BCP47 alternatives' => [
2572 'zh',
2573 [ 'zh', 'zh-hans', 'zh-cn', 'zh-tw' ],
2574 [ 'zh-hans', 'zh-Hans', 'zh-cn', 'zh-Hans-CN', 'zh-tw', 'zh-Hant-TW' ],
2575 ],
2576 'No title' => [ 'en', [ 'en', 'en-x-piglatin' ], [], [ 'notitle' ] ],
2577 'Variant in URL' => [ 'en', [ 'en', 'en-x-piglatin' ], [], [ 'varianturl' ] ],
2578 ];
2579 }
2580
2581 /**
2582 * @covers OutputPage::preventClickjacking
2583 * @covers OutputPage::allowClickjacking
2584 * @covers OutputPage::getPreventClickjacking
2585 * @covers OutputPage::addParserOutputMetadata
2586 * @covers OutputPage::addParserOutput
2587 */
2588 public function testClickjacking() {
2589 $op = $this->newInstance();
2590 $this->assertTrue( $op->getPreventClickjacking() );
2591
2592 $op->allowClickjacking();
2593 $this->assertFalse( $op->getPreventClickjacking() );
2594
2595 $op->preventClickjacking();
2596 $this->assertTrue( $op->getPreventClickjacking() );
2597
2598 $op->preventClickjacking( false );
2599 $this->assertFalse( $op->getPreventClickjacking() );
2600
2601 $pOut1 = $this->createParserOutputStub( 'preventClickjacking', true );
2602 $op->addParserOutputMetadata( $pOut1 );
2603 $this->assertTrue( $op->getPreventClickjacking() );
2604
2605 // The ParserOutput can't allow, only prevent
2606 $pOut2 = $this->createParserOutputStub( 'preventClickjacking', false );
2607 $op->addParserOutputMetadata( $pOut2 );
2608 $this->assertTrue( $op->getPreventClickjacking() );
2609
2610 // Reset to test with addParserOutput()
2611 $op->allowClickjacking();
2612 $this->assertFalse( $op->getPreventClickjacking() );
2613
2614 $op->addParserOutput( $pOut1 );
2615 $this->assertTrue( $op->getPreventClickjacking() );
2616
2617 $op->addParserOutput( $pOut2 );
2618 $this->assertTrue( $op->getPreventClickjacking() );
2619 }
2620
2621 /**
2622 * @dataProvider provideGetFrameOptions
2623 * @covers OutputPage::getFrameOptions
2624 * @covers OutputPage::preventClickjacking
2625 */
2626 public function testGetFrameOptions(
2627 $breakFrames, $preventClickjacking, $editPageFrameOptions, $expected
2628 ) {
2629 $op = $this->newInstance( [
2630 'BreakFrames' => $breakFrames,
2631 'EditPageFrameOptions' => $editPageFrameOptions,
2632 ] );
2633 $op->preventClickjacking( $preventClickjacking );
2634
2635 $this->assertSame( $expected, $op->getFrameOptions() );
2636 }
2637
2638 public function provideGetFrameOptions() {
2639 return [
2640 'BreakFrames true' => [ true, false, false, 'DENY' ],
2641 'Allow clickjacking locally' => [ false, false, 'DENY', false ],
2642 'Allow clickjacking globally' => [ false, true, false, false ],
2643 'DENY globally' => [ false, true, 'DENY', 'DENY' ],
2644 'SAMEORIGIN' => [ false, true, 'SAMEORIGIN', 'SAMEORIGIN' ],
2645 'BreakFrames with SAMEORIGIN' => [ true, true, 'SAMEORIGIN', 'DENY' ],
2646 ];
2647 }
2648
2649 /**
2650 * See ResourceLoaderClientHtmlTest for full coverage.
2651 *
2652 * @dataProvider provideMakeResourceLoaderLink
2653 *
2654 * @covers OutputPage::makeResourceLoaderLink
2655 */
2656 public function testMakeResourceLoaderLink( $args, $expectedHtml ) {
2657 $this->setMwGlobals( [
2658 'wgResourceLoaderDebug' => false,
2659 'wgLoadScript' => 'http://127.0.0.1:8080/w/load.php',
2660 'wgCSPReportOnlyHeader' => true,
2661 ] );
2662 $class = new ReflectionClass( OutputPage::class );
2663 $method = $class->getMethod( 'makeResourceLoaderLink' );
2664 $method->setAccessible( true );
2665 $ctx = new RequestContext();
2666 $ctx->setSkin( SkinFactory::getDefaultInstance()->makeSkin( 'fallback' ) );
2667 $ctx->setLanguage( 'en' );
2668 $out = new OutputPage( $ctx );
2669 $nonce = $class->getProperty( 'CSPNonce' );
2670 $nonce->setAccessible( true );
2671 $nonce->setValue( $out, 'secret' );
2672 $rl = $out->getResourceLoader();
2673 $rl->setMessageBlobStore( $this->createMock( MessageBlobStore::class ) );
2674 $rl->register( [
2675 'test.foo' => new ResourceLoaderTestModule( [
2676 'script' => 'mw.test.foo( { a: true } );',
2677 'styles' => '.mw-test-foo { content: "style"; }',
2678 ] ),
2679 'test.bar' => new ResourceLoaderTestModule( [
2680 'script' => 'mw.test.bar( { a: true } );',
2681 'styles' => '.mw-test-bar { content: "style"; }',
2682 ] ),
2683 'test.baz' => new ResourceLoaderTestModule( [
2684 'script' => 'mw.test.baz( { a: true } );',
2685 'styles' => '.mw-test-baz { content: "style"; }',
2686 ] ),
2687 'test.quux' => new ResourceLoaderTestModule( [
2688 'script' => 'mw.test.baz( { token: 123 } );',
2689 'styles' => '/* pref-animate=off */ .mw-icon { transition: none; }',
2690 'group' => 'private',
2691 ] ),
2692 'test.noscript' => new ResourceLoaderTestModule( [
2693 'styles' => '.stuff { color: red; }',
2694 'group' => 'noscript',
2695 ] ),
2696 'test.group.foo' => new ResourceLoaderTestModule( [
2697 'script' => 'mw.doStuff( "foo" );',
2698 'group' => 'foo',
2699 ] ),
2700 'test.group.bar' => new ResourceLoaderTestModule( [
2701 'script' => 'mw.doStuff( "bar" );',
2702 'group' => 'bar',
2703 ] ),
2704 ] );
2705 $links = $method->invokeArgs( $out, $args );
2706 $actualHtml = strval( $links );
2707 $this->assertEquals( $expectedHtml, $actualHtml );
2708 }
2709
2710 public static function provideMakeResourceLoaderLink() {
2711 // phpcs:disable Generic.Files.LineLength
2712 return [
2713 // Single only=scripts load
2714 [
2715 [ 'test.foo', ResourceLoaderModule::TYPE_SCRIPTS ],
2716 "<script nonce=\"secret\">(window.RLQ=window.RLQ||[]).push(function(){"
2717 . 'mw.loader.load("http://127.0.0.1:8080/w/load.php?lang=en\u0026modules=test.foo\u0026only=scripts\u0026skin=fallback");'
2718 . "});</script>"
2719 ],
2720 // Multiple only=styles load
2721 [
2722 [ [ 'test.baz', 'test.foo', 'test.bar' ], ResourceLoaderModule::TYPE_STYLES ],
2723
2724 '<link rel="stylesheet" href="http://127.0.0.1:8080/w/load.php?lang=en&amp;modules=test.bar%2Cbaz%2Cfoo&amp;only=styles&amp;skin=fallback"/>'
2725 ],
2726 // Private embed (only=scripts)
2727 [
2728 [ 'test.quux', ResourceLoaderModule::TYPE_SCRIPTS ],
2729 "<script nonce=\"secret\">(window.RLQ=window.RLQ||[]).push(function(){"
2730 . "mw.test.baz({token:123});\nmw.loader.state({\"test.quux\":\"ready\"});"
2731 . "});</script>"
2732 ],
2733 // Load private module (combined)
2734 [
2735 [ 'test.quux', ResourceLoaderModule::TYPE_COMBINED ],
2736 "<script nonce=\"secret\">(window.RLQ=window.RLQ||[]).push(function(){"
2737 . "mw.loader.implement(\"test.quux@1ev0ijv\",function($,jQuery,require,module){"
2738 . "mw.test.baz({token:123});},{\"css\":[\".mw-icon{transition:none}"
2739 . "\"]});});</script>"
2740 ],
2741 // Load no modules
2742 [
2743 [ [], ResourceLoaderModule::TYPE_COMBINED ],
2744 '',
2745 ],
2746 // noscript group
2747 [
2748 [ 'test.noscript', ResourceLoaderModule::TYPE_STYLES ],
2749 '<noscript><link rel="stylesheet" href="http://127.0.0.1:8080/w/load.php?lang=en&amp;modules=test.noscript&amp;only=styles&amp;skin=fallback"/></noscript>'
2750 ],
2751 // Load two modules in separate groups
2752 [
2753 [ [ 'test.group.foo', 'test.group.bar' ], ResourceLoaderModule::TYPE_COMBINED ],
2754 "<script nonce=\"secret\">(window.RLQ=window.RLQ||[]).push(function(){"
2755 . 'mw.loader.load("http://127.0.0.1:8080/w/load.php?lang=en\u0026modules=test.group.bar\u0026skin=fallback");'
2756 . 'mw.loader.load("http://127.0.0.1:8080/w/load.php?lang=en\u0026modules=test.group.foo\u0026skin=fallback");'
2757 . "});</script>"
2758 ],
2759 ];
2760 // phpcs:enable
2761 }
2762
2763 /**
2764 * @dataProvider provideBuildExemptModules
2765 *
2766 * @covers OutputPage::buildExemptModules
2767 */
2768 public function testBuildExemptModules( array $exemptStyleModules, $expect ) {
2769 $this->setMwGlobals( [
2770 'wgResourceLoaderDebug' => false,
2771 'wgLoadScript' => '/w/load.php',
2772 // Stub wgCacheEpoch as it influences getVersionHash used for the
2773 // urls in the expected HTML
2774 'wgCacheEpoch' => '20140101000000',
2775 ] );
2776
2777 // Set up stubs
2778 $ctx = new RequestContext();
2779 $ctx->setSkin( SkinFactory::getDefaultInstance()->makeSkin( 'fallback' ) );
2780 $ctx->setLanguage( 'en' );
2781 $op = $this->getMockBuilder( OutputPage::class )
2782 ->setConstructorArgs( [ $ctx ] )
2783 ->setMethods( [ 'buildCssLinksArray' ] )
2784 ->getMock();
2785 $op->expects( $this->any() )
2786 ->method( 'buildCssLinksArray' )
2787 ->willReturn( [] );
2788 $rl = $op->getResourceLoader();
2789 $rl->setMessageBlobStore( $this->createMock( MessageBlobStore::class ) );
2790
2791 // Register custom modules
2792 $rl->register( [
2793 'example.site.a' => new ResourceLoaderTestModule( [ 'group' => 'site' ] ),
2794 'example.site.b' => new ResourceLoaderTestModule( [ 'group' => 'site' ] ),
2795 'example.user' => new ResourceLoaderTestModule( [ 'group' => 'user' ] ),
2796 ] );
2797
2798 $op = TestingAccessWrapper::newFromObject( $op );
2799 $op->rlExemptStyleModules = $exemptStyleModules;
2800 $this->assertEquals(
2801 $expect,
2802 strval( $op->buildExemptModules() )
2803 );
2804 }
2805
2806 public static function provideBuildExemptModules() {
2807 // phpcs:disable Generic.Files.LineLength
2808 return [
2809 'empty' => [
2810 'exemptStyleModules' => [],
2811 '<meta name="ResourceLoaderDynamicStyles" content=""/>',
2812 ],
2813 'empty sets' => [
2814 'exemptStyleModules' => [ 'site' => [], 'noscript' => [], 'private' => [], 'user' => [] ],
2815 '<meta name="ResourceLoaderDynamicStyles" content=""/>',
2816 ],
2817 'default logged-out' => [
2818 'exemptStyleModules' => [ 'site' => [ 'site.styles' ] ],
2819 '<meta name="ResourceLoaderDynamicStyles" content=""/>' . "\n" .
2820 '<link rel="stylesheet" href="/w/load.php?lang=en&amp;modules=site.styles&amp;only=styles&amp;skin=fallback"/>',
2821 ],
2822 'default logged-in' => [
2823 'exemptStyleModules' => [ 'site' => [ 'site.styles' ], 'user' => [ 'user.styles' ] ],
2824 '<meta name="ResourceLoaderDynamicStyles" content=""/>' . "\n" .
2825 '<link rel="stylesheet" href="/w/load.php?lang=en&amp;modules=site.styles&amp;only=styles&amp;skin=fallback"/>' . "\n" .
2826 '<link rel="stylesheet" href="/w/load.php?lang=en&amp;modules=user.styles&amp;only=styles&amp;skin=fallback&amp;version=1ai9g6t"/>',
2827 ],
2828 'custom modules' => [
2829 'exemptStyleModules' => [
2830 'site' => [ 'site.styles', 'example.site.a', 'example.site.b' ],
2831 'user' => [ 'user.styles', 'example.user' ],
2832 ],
2833 '<meta name="ResourceLoaderDynamicStyles" content=""/>' . "\n" .
2834 '<link rel="stylesheet" href="/w/load.php?lang=en&amp;modules=example.site.a%2Cb&amp;only=styles&amp;skin=fallback"/>' . "\n" .
2835 '<link rel="stylesheet" href="/w/load.php?lang=en&amp;modules=site.styles&amp;only=styles&amp;skin=fallback"/>' . "\n" .
2836 '<link rel="stylesheet" href="/w/load.php?lang=en&amp;modules=example.user&amp;only=styles&amp;skin=fallback&amp;version=0a56zyi"/>' . "\n" .
2837 '<link rel="stylesheet" href="/w/load.php?lang=en&amp;modules=user.styles&amp;only=styles&amp;skin=fallback&amp;version=1ai9g6t"/>',
2838 ],
2839 ];
2840 // phpcs:enable
2841 }
2842
2843 /**
2844 * @dataProvider provideTransformFilePath
2845 * @covers OutputPage::transformFilePath
2846 * @covers OutputPage::transformResourcePath
2847 */
2848 public function testTransformResourcePath( $baseDir, $basePath, $uploadDir = null,
2849 $uploadPath = null, $path = null, $expected = null
2850 ) {
2851 if ( $path === null ) {
2852 // Skip optional $uploadDir and $uploadPath
2853 $path = $uploadDir;
2854 $expected = $uploadPath;
2855 $uploadDir = "$baseDir/images";
2856 $uploadPath = "$basePath/images";
2857 }
2858 $this->setMwGlobals( 'IP', $baseDir );
2859 $conf = new HashConfig( [
2860 'ResourceBasePath' => $basePath,
2861 'UploadDirectory' => $uploadDir,
2862 'UploadPath' => $uploadPath,
2863 ] );
2864
2865 // Some of these paths don't exist and will cause warnings
2866 Wikimedia\suppressWarnings();
2867 $actual = OutputPage::transformResourcePath( $conf, $path );
2868 Wikimedia\restoreWarnings();
2869
2870 $this->assertEquals( $expected ?: $path, $actual );
2871 }
2872
2873 public static function provideTransformFilePath() {
2874 $baseDir = dirname( __DIR__ ) . '/data/media';
2875 return [
2876 // File that matches basePath, and exists. Hash found and appended.
2877 [
2878 'baseDir' => $baseDir, 'basePath' => '/w',
2879 '/w/test.jpg',
2880 '/w/test.jpg?edcf2'
2881 ],
2882 // File that matches basePath, but not found on disk. Empty query.
2883 [
2884 'baseDir' => $baseDir, 'basePath' => '/w',
2885 '/w/unknown.png',
2886 '/w/unknown.png?'
2887 ],
2888 // File not matching basePath. Ignored.
2889 [
2890 'baseDir' => $baseDir, 'basePath' => '/w',
2891 '/files/test.jpg'
2892 ],
2893 // Empty string. Ignored.
2894 [
2895 'baseDir' => $baseDir, 'basePath' => '/w',
2896 '',
2897 ''
2898 ],
2899 // Similar path, but with domain component. Ignored.
2900 [
2901 'baseDir' => $baseDir, 'basePath' => '/w',
2902 '//example.org/w/test.jpg'
2903 ],
2904 [
2905 'baseDir' => $baseDir, 'basePath' => '/w',
2906 'https://example.org/w/test.jpg'
2907 ],
2908 // Unrelated path with domain component. Ignored.
2909 [
2910 'baseDir' => $baseDir, 'basePath' => '/w',
2911 'https://example.org/files/test.jpg'
2912 ],
2913 [
2914 'baseDir' => $baseDir, 'basePath' => '/w',
2915 '//example.org/files/test.jpg'
2916 ],
2917 // Unrelated path with domain, and empty base path (root mw install). Ignored.
2918 [
2919 'baseDir' => $baseDir, 'basePath' => '',
2920 'https://example.org/files/test.jpg'
2921 ],
2922 [
2923 'baseDir' => $baseDir, 'basePath' => '',
2924 // T155310
2925 '//example.org/files/test.jpg'
2926 ],
2927 // Check UploadPath before ResourceBasePath (T155146)
2928 [
2929 'baseDir' => dirname( $baseDir ), 'basePath' => '',
2930 'uploadDir' => $baseDir, 'uploadPath' => '/images',
2931 '/images/test.jpg',
2932 '/images/test.jpg?edcf2'
2933 ],
2934 ];
2935 }
2936
2937 /**
2938 * Tests a particular case of transformCssMedia, using the given input, globals,
2939 * expected return, and message
2940 *
2941 * Asserts that $expectedReturn is returned.
2942 *
2943 * options['printableQuery'] - value of query string for printable, or omitted for none
2944 * options['handheldQuery'] - value of query string for handheld, or omitted for none
2945 * options['media'] - passed into the method under the same name
2946 * options['expectedReturn'] - expected return value
2947 * options['message'] - PHPUnit message for assertion
2948 *
2949 * @param array $args Key-value array of arguments as shown above
2950 */
2951 protected function assertTransformCssMediaCase( $args ) {
2952 $queryData = [];
2953 if ( isset( $args['printableQuery'] ) ) {
2954 $queryData['printable'] = $args['printableQuery'];
2955 }
2956
2957 if ( isset( $args['handheldQuery'] ) ) {
2958 $queryData['handheld'] = $args['handheldQuery'];
2959 }
2960
2961 $fauxRequest = new FauxRequest( $queryData, false );
2962 $this->setMwGlobals( [
2963 'wgRequest' => $fauxRequest,
2964 ] );
2965
2966 $actualReturn = OutputPage::transformCssMedia( $args['media'] );
2967 $this->assertSame( $args['expectedReturn'], $actualReturn, $args['message'] );
2968 }
2969
2970 /**
2971 * Tests print requests
2972 *
2973 * @covers OutputPage::transformCssMedia
2974 */
2975 public function testPrintRequests() {
2976 $this->assertTransformCssMediaCase( [
2977 'printableQuery' => '1',
2978 'media' => 'screen',
2979 'expectedReturn' => null,
2980 'message' => 'On printable request, screen returns null'
2981 ] );
2982
2983 $this->assertTransformCssMediaCase( [
2984 'printableQuery' => '1',
2985 'media' => self::SCREEN_MEDIA_QUERY,
2986 'expectedReturn' => null,
2987 'message' => 'On printable request, screen media query returns null'
2988 ] );
2989
2990 $this->assertTransformCssMediaCase( [
2991 'printableQuery' => '1',
2992 'media' => self::SCREEN_ONLY_MEDIA_QUERY,
2993 'expectedReturn' => null,
2994 'message' => 'On printable request, screen media query with only returns null'
2995 ] );
2996
2997 $this->assertTransformCssMediaCase( [
2998 'printableQuery' => '1',
2999 'media' => 'print',
3000 'expectedReturn' => '',
3001 'message' => 'On printable request, media print returns empty string'
3002 ] );
3003 }
3004
3005 /**
3006 * Tests screen requests, without either query parameter set
3007 *
3008 * @covers OutputPage::transformCssMedia
3009 */
3010 public function testScreenRequests() {
3011 $this->assertTransformCssMediaCase( [
3012 'media' => 'screen',
3013 'expectedReturn' => 'screen',
3014 'message' => 'On screen request, screen media type is preserved'
3015 ] );
3016
3017 $this->assertTransformCssMediaCase( [
3018 'media' => 'handheld',
3019 'expectedReturn' => 'handheld',
3020 'message' => 'On screen request, handheld media type is preserved'
3021 ] );
3022
3023 $this->assertTransformCssMediaCase( [
3024 'media' => self::SCREEN_MEDIA_QUERY,
3025 'expectedReturn' => self::SCREEN_MEDIA_QUERY,
3026 'message' => 'On screen request, screen media query is preserved.'
3027 ] );
3028
3029 $this->assertTransformCssMediaCase( [
3030 'media' => self::SCREEN_ONLY_MEDIA_QUERY,
3031 'expectedReturn' => self::SCREEN_ONLY_MEDIA_QUERY,
3032 'message' => 'On screen request, screen media query with only is preserved.'
3033 ] );
3034
3035 $this->assertTransformCssMediaCase( [
3036 'media' => 'print',
3037 'expectedReturn' => 'print',
3038 'message' => 'On screen request, print media type is preserved'
3039 ] );
3040 }
3041
3042 /**
3043 * Tests handheld behavior
3044 *
3045 * @covers OutputPage::transformCssMedia
3046 */
3047 public function testHandheld() {
3048 $this->assertTransformCssMediaCase( [
3049 'handheldQuery' => '1',
3050 'media' => 'handheld',
3051 'expectedReturn' => '',
3052 'message' => 'On request with handheld querystring and media is handheld, returns empty string'
3053 ] );
3054
3055 $this->assertTransformCssMediaCase( [
3056 'handheldQuery' => '1',
3057 'media' => 'screen',
3058 'expectedReturn' => null,
3059 'message' => 'On request with handheld querystring and media is screen, returns null'
3060 ] );
3061 }
3062
3063 /**
3064 * @covers OutputPage::isTOCEnabled
3065 * @covers OutputPage::addParserOutputMetadata
3066 * @covers OutputPage::addParserOutput
3067 */
3068 public function testIsTOCEnabled() {
3069 $op = $this->newInstance();
3070 $this->assertFalse( $op->isTOCEnabled() );
3071
3072 $pOut1 = $this->createParserOutputStub( 'getTOCHTML', false );
3073 $op->addParserOutputMetadata( $pOut1 );
3074 $this->assertFalse( $op->isTOCEnabled() );
3075
3076 $pOut2 = $this->createParserOutputStub( 'getTOCHTML', true );
3077 $op->addParserOutput( $pOut2 );
3078 $this->assertTrue( $op->isTOCEnabled() );
3079
3080 // The parser output doesn't disable the TOC after it was enabled
3081 $op->addParserOutputMetadata( $pOut1 );
3082 $this->assertTrue( $op->isTOCEnabled() );
3083 }
3084
3085 /**
3086 * @dataProvider providePreloadLinkHeaders
3087 * @covers ResourceLoaderSkinModule::getPreloadLinks
3088 * @covers ResourceLoaderSkinModule::getLogoPreloadlinks
3089 */
3090 public function testPreloadLinkHeaders( $config, $result ) {
3091 $this->setMwGlobals( $config );
3092 $ctx = $this->getMockBuilder( ResourceLoaderContext::class )
3093 ->disableOriginalConstructor()->getMock();
3094 $module = new ResourceLoaderSkinModule();
3095
3096 $this->assertEquals( [ $result ], $module->getHeaders( $ctx ) );
3097 }
3098
3099 public function providePreloadLinkHeaders() {
3100 return [
3101 [
3102 [
3103 'wgResourceBasePath' => '/w',
3104 'wgLogo' => '/img/default.png',
3105 'wgLogoHD' => [
3106 '1.5x' => '/img/one-point-five.png',
3107 '2x' => '/img/two-x.png',
3108 ],
3109 ],
3110 'Link: </img/default.png>;rel=preload;as=image;media=' .
3111 'not all and (min-resolution: 1.5dppx),' .
3112 '</img/one-point-five.png>;rel=preload;as=image;media=' .
3113 '(min-resolution: 1.5dppx) and (max-resolution: 1.999999dppx),' .
3114 '</img/two-x.png>;rel=preload;as=image;media=(min-resolution: 2dppx)'
3115 ],
3116 [
3117 [
3118 'wgResourceBasePath' => '/w',
3119 'wgLogo' => '/img/default.png',
3120 'wgLogoHD' => false,
3121 ],
3122 'Link: </img/default.png>;rel=preload;as=image'
3123 ],
3124 [
3125 [
3126 'wgResourceBasePath' => '/w',
3127 'wgLogo' => '/img/default.png',
3128 'wgLogoHD' => [
3129 '2x' => '/img/two-x.png',
3130 ],
3131 ],
3132 'Link: </img/default.png>;rel=preload;as=image;media=' .
3133 'not all and (min-resolution: 2dppx),' .
3134 '</img/two-x.png>;rel=preload;as=image;media=(min-resolution: 2dppx)'
3135 ],
3136 [
3137 [
3138 'wgResourceBasePath' => '/w',
3139 'wgLogo' => '/img/default.png',
3140 'wgLogoHD' => [
3141 'svg' => '/img/vector.svg',
3142 ],
3143 ],
3144 'Link: </img/vector.svg>;rel=preload;as=image'
3145
3146 ],
3147 [
3148 [
3149 'wgResourceBasePath' => '/w',
3150 'wgLogo' => '/w/test.jpg',
3151 'wgLogoHD' => false,
3152 'wgUploadPath' => '/w/images',
3153 'IP' => dirname( __DIR__ ) . '/data/media',
3154 ],
3155 'Link: </w/test.jpg?edcf2>;rel=preload;as=image',
3156 ],
3157 ];
3158 }
3159
3160 /**
3161 * @return OutputPage
3162 */
3163 private function newInstance( $config = [], WebRequest $request = null, $options = [] ) {
3164 $context = new RequestContext();
3165
3166 $context->setConfig( new MultiConfig( [
3167 new HashConfig( $config + [
3168 'AppleTouchIcon' => false,
3169 'DisableLangConversion' => true,
3170 'EnableCanonicalServerLink' => false,
3171 'Favicon' => false,
3172 'Feed' => false,
3173 'LanguageCode' => false,
3174 'ReferrerPolicy' => false,
3175 'RightsPage' => false,
3176 'RightsUrl' => false,
3177 'UniversalEditButton' => false,
3178 ] ),
3179 $context->getConfig()
3180 ] ) );
3181
3182 if ( !in_array( 'notitle', (array)$options ) ) {
3183 $context->setTitle( Title::newFromText( 'My test page' ) );
3184 }
3185
3186 if ( $request ) {
3187 $context->setRequest( $request );
3188 }
3189
3190 return new OutputPage( $context );
3191 }
3192 }