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