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