Remove $wgUseKeyHeader and OutputPage::getKeyHeader(), 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 *
2250 * @param array[] $calls For each array, call addVaryHeader() with those arguments
2251 * @param string[] $cookies Array of cookie names to vary on
2252 * @param string $vary Text of expected Vary header (including the 'Vary: ')
2253 * @param string $key Text of expected Key header (including the 'Key: ')
2254 */
2255 public function testVaryHeaders( array $calls, array $cookies, $vary ) {
2256 // Get rid of default Vary fields
2257 $op = $this->getMockBuilder( OutputPage::class )
2258 ->setConstructorArgs( [ new RequestContext() ] )
2259 ->setMethods( [ 'getCacheVaryCookies' ] )
2260 ->getMock();
2261 $op->expects( $this->any() )
2262 ->method( 'getCacheVaryCookies' )
2263 ->will( $this->returnValue( $cookies ) );
2264 TestingAccessWrapper::newFromObject( $op )->mVaryHeader = [];
2265
2266 $this->hideDeprecated( 'addVaryHeader $option is ignored' );
2267 foreach ( $calls as $call ) {
2268 $op->addVaryHeader( ...$call );
2269 }
2270 $this->assertEquals( $vary, $op->getVaryHeader(), 'Vary:' );
2271 }
2272
2273 public function provideVaryHeaders() {
2274 return [
2275 'No header' => [
2276 [],
2277 [],
2278 'Vary: ',
2279 ],
2280 'Single header' => [
2281 [
2282 [ 'Cookie' ],
2283 ],
2284 [],
2285 'Vary: Cookie',
2286 ],
2287 'Non-unique headers' => [
2288 [
2289 [ 'Cookie' ],
2290 [ 'Accept-Language' ],
2291 [ 'Cookie' ],
2292 ],
2293 [],
2294 'Vary: Cookie, Accept-Language',
2295 ],
2296 'Two headers with single options' => [
2297 // Options are deprecated since 1.34
2298 [
2299 [ 'Cookie', [ 'param=phpsessid' ] ],
2300 [ 'Accept-Language', [ 'substr=en' ] ],
2301 ],
2302 [],
2303 'Vary: Cookie, Accept-Language',
2304 ],
2305 'One header with multiple options' => [
2306 // Options are deprecated since 1.34
2307 [
2308 [ 'Cookie', [ 'param=phpsessid', 'param=userId' ] ],
2309 ],
2310 [],
2311 'Vary: Cookie',
2312 ],
2313 'Duplicate option' => [
2314 // Options are deprecated since 1.34
2315 [
2316 [ 'Cookie', [ 'param=phpsessid' ] ],
2317 [ 'Cookie', [ 'param=phpsessid' ] ],
2318 [ 'Accept-Language', [ 'substr=en', 'substr=en' ] ],
2319 ],
2320 [],
2321 'Vary: Cookie, Accept-Language',
2322 ],
2323 'Same header, different options' => [
2324 // Options are deprecated since 1.34
2325 [
2326 [ 'Cookie', [ 'param=phpsessid' ] ],
2327 [ 'Cookie', [ 'param=userId' ] ],
2328 ],
2329 [],
2330 'Vary: Cookie',
2331 ],
2332 'No header, vary cookies' => [
2333 [],
2334 [ 'cookie1', 'cookie2' ],
2335 'Vary: Cookie',
2336 ],
2337 'Cookie header with option plus vary cookies' => [
2338 // Options are deprecated since 1.34
2339 [
2340 [ 'Cookie', [ 'param=cookie1' ] ],
2341 ],
2342 [ 'cookie2', 'cookie3' ],
2343 'Vary: Cookie',
2344 ],
2345 'Non-cookie header plus vary cookies' => [
2346 [
2347 [ 'Accept-Language' ],
2348 ],
2349 [ 'cookie' ],
2350 'Vary: Accept-Language, Cookie',
2351 ],
2352 'Cookie and non-cookie headers plus vary cookies' => [
2353 // Options are deprecated since 1.34
2354 [
2355 [ 'Cookie', [ 'param=cookie1' ] ],
2356 [ 'Accept-Language' ],
2357 ],
2358 [ 'cookie2' ],
2359 'Vary: Cookie, Accept-Language',
2360 ],
2361 ];
2362 }
2363
2364 /**
2365 * @covers OutputPage::getVaryHeader
2366 */
2367 public function testVaryHeaderDefault() {
2368 $op = $this->newInstance();
2369 $this->assertSame( 'Vary: Accept-Encoding, Cookie', $op->getVaryHeader() );
2370 }
2371
2372 /**
2373 * @dataProvider provideLinkHeaders
2374 *
2375 * @covers OutputPage::addLinkHeader
2376 * @covers OutputPage::getLinkHeader
2377 */
2378 public function testLinkHeaders( array $headers, $result ) {
2379 $op = $this->newInstance();
2380
2381 foreach ( $headers as $header ) {
2382 $op->addLinkHeader( $header );
2383 }
2384
2385 $this->assertEquals( $result, $op->getLinkHeader() );
2386 }
2387
2388 public function provideLinkHeaders() {
2389 return [
2390 [
2391 [],
2392 false
2393 ],
2394 [
2395 [ '<https://foo/bar.jpg>;rel=preload;as=image' ],
2396 'Link: <https://foo/bar.jpg>;rel=preload;as=image',
2397 ],
2398 [
2399 [
2400 '<https://foo/bar.jpg>;rel=preload;as=image',
2401 '<https://foo/baz.jpg>;rel=preload;as=image'
2402 ],
2403 'Link: <https://foo/bar.jpg>;rel=preload;as=image,<https://foo/baz.jpg>;' .
2404 'rel=preload;as=image',
2405 ],
2406 ];
2407 }
2408
2409 /**
2410 * @dataProvider provideAddAcceptLanguage
2411 * @covers OutputPage::addAcceptLanguage
2412 */
2413 public function testAddAcceptLanguage(
2414 $code, array $variants, $expected, array $options = []
2415 ) {
2416 $req = new FauxRequest( in_array( 'varianturl', $options ) ? [ 'variant' => 'x' ] : [] );
2417 $op = $this->newInstance( [], $req, in_array( 'notitle', $options ) ? 'notitle' : null );
2418
2419 if ( !in_array( 'notitle', $options ) ) {
2420 $mockLang = $this->getMock( Language::class );
2421
2422 if ( in_array( 'varianturl', $options ) ) {
2423 $mockLang->expects( $this->never() )->method( $this->anything() );
2424 } else {
2425 $mockLang->method( 'hasVariants' )->willReturn( count( $variants ) > 1 );
2426 $mockLang->method( 'getVariants' )->willReturn( $variants );
2427 $mockLang->method( 'getCode' )->willReturn( $code );
2428 }
2429
2430 $mockTitle = $this->getMock( Title::class );
2431 $mockTitle->method( 'getPageLanguage' )->willReturn( $mockLang );
2432
2433 $op->setTitle( $mockTitle );
2434 }
2435
2436 // This will run addAcceptLanguage()
2437 $op->sendCacheControl();
2438 $this->assertSame( "Vary: $expected", $op->getVaryHeader() );
2439 }
2440
2441 public function provideAddAcceptLanguage() {
2442 return [
2443 'No variants' => [
2444 'en',
2445 [ 'en' ],
2446 'Accept-Encoding, Cookie',
2447 ],
2448 'One simple variant' => [
2449 'en',
2450 [ 'en', 'en-x-piglatin' ],
2451 'Accept-Encoding, Cookie, Accept-Language',
2452 ],
2453 'Multiple variants with BCP47 alternatives' => [
2454 'zh',
2455 [ 'zh', 'zh-hans', 'zh-cn', 'zh-tw' ],
2456 'Accept-Encoding, Cookie, Accept-Language',
2457 ],
2458 'No title' => [
2459 'en',
2460 [ 'en', 'en-x-piglatin' ],
2461 'Accept-Encoding, Cookie',
2462 [ 'notitle' ]
2463 ],
2464 'Variant in URL' => [
2465 'en',
2466 [ 'en', 'en-x-piglatin' ],
2467 'Accept-Encoding, Cookie',
2468 [ 'varianturl' ]
2469 ],
2470 ];
2471 }
2472
2473 /**
2474 * @covers OutputPage::preventClickjacking
2475 * @covers OutputPage::allowClickjacking
2476 * @covers OutputPage::getPreventClickjacking
2477 * @covers OutputPage::addParserOutputMetadata
2478 * @covers OutputPage::addParserOutput
2479 */
2480 public function testClickjacking() {
2481 $op = $this->newInstance();
2482 $this->assertTrue( $op->getPreventClickjacking() );
2483
2484 $op->allowClickjacking();
2485 $this->assertFalse( $op->getPreventClickjacking() );
2486
2487 $op->preventClickjacking();
2488 $this->assertTrue( $op->getPreventClickjacking() );
2489
2490 $op->preventClickjacking( false );
2491 $this->assertFalse( $op->getPreventClickjacking() );
2492
2493 $pOut1 = $this->createParserOutputStub( 'preventClickjacking', true );
2494 $op->addParserOutputMetadata( $pOut1 );
2495 $this->assertTrue( $op->getPreventClickjacking() );
2496
2497 // The ParserOutput can't allow, only prevent
2498 $pOut2 = $this->createParserOutputStub( 'preventClickjacking', false );
2499 $op->addParserOutputMetadata( $pOut2 );
2500 $this->assertTrue( $op->getPreventClickjacking() );
2501
2502 // Reset to test with addParserOutput()
2503 $op->allowClickjacking();
2504 $this->assertFalse( $op->getPreventClickjacking() );
2505
2506 $op->addParserOutput( $pOut1 );
2507 $this->assertTrue( $op->getPreventClickjacking() );
2508
2509 $op->addParserOutput( $pOut2 );
2510 $this->assertTrue( $op->getPreventClickjacking() );
2511 }
2512
2513 /**
2514 * @dataProvider provideGetFrameOptions
2515 * @covers OutputPage::getFrameOptions
2516 * @covers OutputPage::preventClickjacking
2517 */
2518 public function testGetFrameOptions(
2519 $breakFrames, $preventClickjacking, $editPageFrameOptions, $expected
2520 ) {
2521 $op = $this->newInstance( [
2522 'BreakFrames' => $breakFrames,
2523 'EditPageFrameOptions' => $editPageFrameOptions,
2524 ] );
2525 $op->preventClickjacking( $preventClickjacking );
2526
2527 $this->assertSame( $expected, $op->getFrameOptions() );
2528 }
2529
2530 public function provideGetFrameOptions() {
2531 return [
2532 'BreakFrames true' => [ true, false, false, 'DENY' ],
2533 'Allow clickjacking locally' => [ false, false, 'DENY', false ],
2534 'Allow clickjacking globally' => [ false, true, false, false ],
2535 'DENY globally' => [ false, true, 'DENY', 'DENY' ],
2536 'SAMEORIGIN' => [ false, true, 'SAMEORIGIN', 'SAMEORIGIN' ],
2537 'BreakFrames with SAMEORIGIN' => [ true, true, 'SAMEORIGIN', 'DENY' ],
2538 ];
2539 }
2540
2541 /**
2542 * See ResourceLoaderClientHtmlTest for full coverage.
2543 *
2544 * @dataProvider provideMakeResourceLoaderLink
2545 *
2546 * @covers OutputPage::makeResourceLoaderLink
2547 */
2548 public function testMakeResourceLoaderLink( $args, $expectedHtml ) {
2549 $this->setMwGlobals( [
2550 'wgResourceLoaderDebug' => false,
2551 'wgLoadScript' => 'http://127.0.0.1:8080/w/load.php',
2552 'wgCSPReportOnlyHeader' => true,
2553 ] );
2554 $class = new ReflectionClass( OutputPage::class );
2555 $method = $class->getMethod( 'makeResourceLoaderLink' );
2556 $method->setAccessible( true );
2557 $ctx = new RequestContext();
2558 $skinFactory = MediaWikiServices::getInstance()->getSkinFactory();
2559 $ctx->setSkin( $skinFactory->makeSkin( 'fallback' ) );
2560 $ctx->setLanguage( 'en' );
2561 $out = new OutputPage( $ctx );
2562 $nonce = $class->getProperty( 'CSPNonce' );
2563 $nonce->setAccessible( true );
2564 $nonce->setValue( $out, 'secret' );
2565 $rl = $out->getResourceLoader();
2566 $rl->setMessageBlobStore( $this->createMock( MessageBlobStore::class ) );
2567 $rl->register( [
2568 'test.foo' => new ResourceLoaderTestModule( [
2569 'script' => 'mw.test.foo( { a: true } );',
2570 'styles' => '.mw-test-foo { content: "style"; }',
2571 ] ),
2572 'test.bar' => new ResourceLoaderTestModule( [
2573 'script' => 'mw.test.bar( { a: true } );',
2574 'styles' => '.mw-test-bar { content: "style"; }',
2575 ] ),
2576 'test.baz' => new ResourceLoaderTestModule( [
2577 'script' => 'mw.test.baz( { a: true } );',
2578 'styles' => '.mw-test-baz { content: "style"; }',
2579 ] ),
2580 'test.quux' => new ResourceLoaderTestModule( [
2581 'script' => 'mw.test.baz( { token: 123 } );',
2582 'styles' => '/* pref-animate=off */ .mw-icon { transition: none; }',
2583 'group' => 'private',
2584 ] ),
2585 'test.noscript' => new ResourceLoaderTestModule( [
2586 'styles' => '.stuff { color: red; }',
2587 'group' => 'noscript',
2588 ] ),
2589 'test.group.foo' => new ResourceLoaderTestModule( [
2590 'script' => 'mw.doStuff( "foo" );',
2591 'group' => 'foo',
2592 ] ),
2593 'test.group.bar' => new ResourceLoaderTestModule( [
2594 'script' => 'mw.doStuff( "bar" );',
2595 'group' => 'bar',
2596 ] ),
2597 ] );
2598 $links = $method->invokeArgs( $out, $args );
2599 $actualHtml = strval( $links );
2600 $this->assertEquals( $expectedHtml, $actualHtml );
2601 }
2602
2603 public static function provideMakeResourceLoaderLink() {
2604 // phpcs:disable Generic.Files.LineLength
2605 return [
2606 // Single only=scripts load
2607 [
2608 [ 'test.foo', ResourceLoaderModule::TYPE_SCRIPTS ],
2609 "<script nonce=\"secret\">(RLQ=window.RLQ||[]).push(function(){"
2610 . 'mw.loader.load("http://127.0.0.1:8080/w/load.php?lang=en\u0026modules=test.foo\u0026only=scripts");'
2611 . "});</script>"
2612 ],
2613 // Multiple only=styles load
2614 [
2615 [ [ 'test.baz', 'test.foo', 'test.bar' ], ResourceLoaderModule::TYPE_STYLES ],
2616
2617 '<link rel="stylesheet" href="http://127.0.0.1:8080/w/load.php?lang=en&amp;modules=test.bar%2Cbaz%2Cfoo&amp;only=styles"/>'
2618 ],
2619 // Private embed (only=scripts)
2620 [
2621 [ 'test.quux', ResourceLoaderModule::TYPE_SCRIPTS ],
2622 "<script nonce=\"secret\">(RLQ=window.RLQ||[]).push(function(){"
2623 . "mw.test.baz({token:123});\nmw.loader.state({\"test.quux\":\"ready\"});"
2624 . "});</script>"
2625 ],
2626 // Load private module (combined)
2627 [
2628 [ 'test.quux', ResourceLoaderModule::TYPE_COMBINED ],
2629 "<script nonce=\"secret\">(RLQ=window.RLQ||[]).push(function(){"
2630 . "mw.loader.implement(\"test.quux@1ev0ijv\",function($,jQuery,require,module){"
2631 . "mw.test.baz({token:123});},{\"css\":[\".mw-icon{transition:none}"
2632 . "\"]});});</script>"
2633 ],
2634 // Load no modules
2635 [
2636 [ [], ResourceLoaderModule::TYPE_COMBINED ],
2637 '',
2638 ],
2639 // noscript group
2640 [
2641 [ 'test.noscript', ResourceLoaderModule::TYPE_STYLES ],
2642 '<noscript><link rel="stylesheet" href="http://127.0.0.1:8080/w/load.php?lang=en&amp;modules=test.noscript&amp;only=styles"/></noscript>'
2643 ],
2644 // Load two modules in separate groups
2645 [
2646 [ [ 'test.group.foo', 'test.group.bar' ], ResourceLoaderModule::TYPE_COMBINED ],
2647 "<script nonce=\"secret\">(RLQ=window.RLQ||[]).push(function(){"
2648 . 'mw.loader.load("http://127.0.0.1:8080/w/load.php?lang=en\u0026modules=test.group.bar");'
2649 . 'mw.loader.load("http://127.0.0.1:8080/w/load.php?lang=en\u0026modules=test.group.foo");'
2650 . "});</script>"
2651 ],
2652 ];
2653 // phpcs:enable
2654 }
2655
2656 /**
2657 * @dataProvider provideBuildExemptModules
2658 *
2659 * @covers OutputPage::buildExemptModules
2660 */
2661 public function testBuildExemptModules( array $exemptStyleModules, $expect ) {
2662 $this->setMwGlobals( [
2663 'wgResourceLoaderDebug' => false,
2664 'wgLoadScript' => '/w/load.php',
2665 // Stub wgCacheEpoch as it influences getVersionHash used for the
2666 // urls in the expected HTML
2667 'wgCacheEpoch' => '20140101000000',
2668 ] );
2669
2670 // Set up stubs
2671 $ctx = new RequestContext();
2672 $skinFactory = MediaWikiServices::getInstance()->getSkinFactory();
2673 $ctx->setSkin( $skinFactory->makeSkin( 'fallback' ) );
2674 $ctx->setLanguage( 'en' );
2675 $op = $this->getMockBuilder( OutputPage::class )
2676 ->setConstructorArgs( [ $ctx ] )
2677 ->setMethods( [ 'buildCssLinksArray' ] )
2678 ->getMock();
2679 $op->expects( $this->any() )
2680 ->method( 'buildCssLinksArray' )
2681 ->willReturn( [] );
2682 $rl = $op->getResourceLoader();
2683 $rl->setMessageBlobStore( $this->createMock( MessageBlobStore::class ) );
2684
2685 // Register custom modules
2686 $rl->register( [
2687 'example.site.a' => new ResourceLoaderTestModule( [ 'group' => 'site' ] ),
2688 'example.site.b' => new ResourceLoaderTestModule( [ 'group' => 'site' ] ),
2689 'example.user' => new ResourceLoaderTestModule( [ 'group' => 'user' ] ),
2690 ] );
2691
2692 $op = TestingAccessWrapper::newFromObject( $op );
2693 $op->rlExemptStyleModules = $exemptStyleModules;
2694 $this->assertEquals(
2695 $expect,
2696 strval( $op->buildExemptModules() )
2697 );
2698 }
2699
2700 public static function provideBuildExemptModules() {
2701 // phpcs:disable Generic.Files.LineLength
2702 return [
2703 'empty' => [
2704 'exemptStyleModules' => [],
2705 '<meta name="ResourceLoaderDynamicStyles" content=""/>',
2706 ],
2707 'empty sets' => [
2708 'exemptStyleModules' => [ 'site' => [], 'noscript' => [], 'private' => [], 'user' => [] ],
2709 '<meta name="ResourceLoaderDynamicStyles" content=""/>',
2710 ],
2711 'default logged-out' => [
2712 'exemptStyleModules' => [ 'site' => [ 'site.styles' ] ],
2713 '<meta name="ResourceLoaderDynamicStyles" content=""/>' . "\n" .
2714 '<link rel="stylesheet" href="/w/load.php?lang=en&amp;modules=site.styles&amp;only=styles"/>',
2715 ],
2716 'default logged-in' => [
2717 'exemptStyleModules' => [ 'site' => [ 'site.styles' ], 'user' => [ 'user.styles' ] ],
2718 '<meta name="ResourceLoaderDynamicStyles" content=""/>' . "\n" .
2719 '<link rel="stylesheet" href="/w/load.php?lang=en&amp;modules=site.styles&amp;only=styles"/>' . "\n" .
2720 '<link rel="stylesheet" href="/w/load.php?lang=en&amp;modules=user.styles&amp;only=styles&amp;version=1ai9g6t"/>',
2721 ],
2722 'custom modules' => [
2723 'exemptStyleModules' => [
2724 'site' => [ 'site.styles', 'example.site.a', 'example.site.b' ],
2725 'user' => [ 'user.styles', 'example.user' ],
2726 ],
2727 '<meta name="ResourceLoaderDynamicStyles" content=""/>' . "\n" .
2728 '<link rel="stylesheet" href="/w/load.php?lang=en&amp;modules=example.site.a%2Cb&amp;only=styles"/>' . "\n" .
2729 '<link rel="stylesheet" href="/w/load.php?lang=en&amp;modules=site.styles&amp;only=styles"/>' . "\n" .
2730 '<link rel="stylesheet" href="/w/load.php?lang=en&amp;modules=example.user&amp;only=styles&amp;version=0a56zyi"/>' . "\n" .
2731 '<link rel="stylesheet" href="/w/load.php?lang=en&amp;modules=user.styles&amp;only=styles&amp;version=1ai9g6t"/>',
2732 ],
2733 ];
2734 // phpcs:enable
2735 }
2736
2737 /**
2738 * @dataProvider provideTransformFilePath
2739 * @covers OutputPage::transformFilePath
2740 * @covers OutputPage::transformResourcePath
2741 */
2742 public function testTransformResourcePath( $baseDir, $basePath, $uploadDir = null,
2743 $uploadPath = null, $path = null, $expected = null
2744 ) {
2745 if ( $path === null ) {
2746 // Skip optional $uploadDir and $uploadPath
2747 $path = $uploadDir;
2748 $expected = $uploadPath;
2749 $uploadDir = "$baseDir/images";
2750 $uploadPath = "$basePath/images";
2751 }
2752 $this->setMwGlobals( 'IP', $baseDir );
2753 $conf = new HashConfig( [
2754 'ResourceBasePath' => $basePath,
2755 'UploadDirectory' => $uploadDir,
2756 'UploadPath' => $uploadPath,
2757 ] );
2758
2759 // Some of these paths don't exist and will cause warnings
2760 Wikimedia\suppressWarnings();
2761 $actual = OutputPage::transformResourcePath( $conf, $path );
2762 Wikimedia\restoreWarnings();
2763
2764 $this->assertEquals( $expected ?: $path, $actual );
2765 }
2766
2767 public static function provideTransformFilePath() {
2768 $baseDir = dirname( __DIR__ ) . '/data/media';
2769 return [
2770 // File that matches basePath, and exists. Hash found and appended.
2771 [
2772 'baseDir' => $baseDir, 'basePath' => '/w',
2773 '/w/test.jpg',
2774 '/w/test.jpg?edcf2'
2775 ],
2776 // File that matches basePath, but not found on disk. Empty query.
2777 [
2778 'baseDir' => $baseDir, 'basePath' => '/w',
2779 '/w/unknown.png',
2780 '/w/unknown.png?'
2781 ],
2782 // File not matching basePath. Ignored.
2783 [
2784 'baseDir' => $baseDir, 'basePath' => '/w',
2785 '/files/test.jpg'
2786 ],
2787 // Empty string. Ignored.
2788 [
2789 'baseDir' => $baseDir, 'basePath' => '/w',
2790 '',
2791 ''
2792 ],
2793 // Similar path, but with domain component. Ignored.
2794 [
2795 'baseDir' => $baseDir, 'basePath' => '/w',
2796 '//example.org/w/test.jpg'
2797 ],
2798 [
2799 'baseDir' => $baseDir, 'basePath' => '/w',
2800 'https://example.org/w/test.jpg'
2801 ],
2802 // Unrelated path with domain component. Ignored.
2803 [
2804 'baseDir' => $baseDir, 'basePath' => '/w',
2805 'https://example.org/files/test.jpg'
2806 ],
2807 [
2808 'baseDir' => $baseDir, 'basePath' => '/w',
2809 '//example.org/files/test.jpg'
2810 ],
2811 // Unrelated path with domain, and empty base path (root mw install). Ignored.
2812 [
2813 'baseDir' => $baseDir, 'basePath' => '',
2814 'https://example.org/files/test.jpg'
2815 ],
2816 [
2817 'baseDir' => $baseDir, 'basePath' => '',
2818 // T155310
2819 '//example.org/files/test.jpg'
2820 ],
2821 // Check UploadPath before ResourceBasePath (T155146)
2822 [
2823 'baseDir' => dirname( $baseDir ), 'basePath' => '',
2824 'uploadDir' => $baseDir, 'uploadPath' => '/images',
2825 '/images/test.jpg',
2826 '/images/test.jpg?edcf2'
2827 ],
2828 ];
2829 }
2830
2831 /**
2832 * Tests a particular case of transformCssMedia, using the given input, globals,
2833 * expected return, and message
2834 *
2835 * Asserts that $expectedReturn is returned.
2836 *
2837 * options['printableQuery'] - value of query string for printable, or omitted for none
2838 * options['handheldQuery'] - value of query string for handheld, or omitted for none
2839 * options['media'] - passed into the method under the same name
2840 * options['expectedReturn'] - expected return value
2841 * options['message'] - PHPUnit message for assertion
2842 *
2843 * @param array $args Key-value array of arguments as shown above
2844 */
2845 protected function assertTransformCssMediaCase( $args ) {
2846 $queryData = [];
2847 if ( isset( $args['printableQuery'] ) ) {
2848 $queryData['printable'] = $args['printableQuery'];
2849 }
2850
2851 if ( isset( $args['handheldQuery'] ) ) {
2852 $queryData['handheld'] = $args['handheldQuery'];
2853 }
2854
2855 $fauxRequest = new FauxRequest( $queryData, false );
2856 $this->setMwGlobals( [
2857 'wgRequest' => $fauxRequest,
2858 ] );
2859
2860 $actualReturn = OutputPage::transformCssMedia( $args['media'] );
2861 $this->assertSame( $args['expectedReturn'], $actualReturn, $args['message'] );
2862 }
2863
2864 /**
2865 * Tests print requests
2866 *
2867 * @covers OutputPage::transformCssMedia
2868 */
2869 public function testPrintRequests() {
2870 $this->assertTransformCssMediaCase( [
2871 'printableQuery' => '1',
2872 'media' => 'screen',
2873 'expectedReturn' => null,
2874 'message' => 'On printable request, screen returns null'
2875 ] );
2876
2877 $this->assertTransformCssMediaCase( [
2878 'printableQuery' => '1',
2879 'media' => self::SCREEN_MEDIA_QUERY,
2880 'expectedReturn' => null,
2881 'message' => 'On printable request, screen media query returns null'
2882 ] );
2883
2884 $this->assertTransformCssMediaCase( [
2885 'printableQuery' => '1',
2886 'media' => self::SCREEN_ONLY_MEDIA_QUERY,
2887 'expectedReturn' => null,
2888 'message' => 'On printable request, screen media query with only returns null'
2889 ] );
2890
2891 $this->assertTransformCssMediaCase( [
2892 'printableQuery' => '1',
2893 'media' => 'print',
2894 'expectedReturn' => '',
2895 'message' => 'On printable request, media print returns empty string'
2896 ] );
2897 }
2898
2899 /**
2900 * Tests screen requests, without either query parameter set
2901 *
2902 * @covers OutputPage::transformCssMedia
2903 */
2904 public function testScreenRequests() {
2905 $this->assertTransformCssMediaCase( [
2906 'media' => 'screen',
2907 'expectedReturn' => 'screen',
2908 'message' => 'On screen request, screen media type is preserved'
2909 ] );
2910
2911 $this->assertTransformCssMediaCase( [
2912 'media' => 'handheld',
2913 'expectedReturn' => 'handheld',
2914 'message' => 'On screen request, handheld media type is preserved'
2915 ] );
2916
2917 $this->assertTransformCssMediaCase( [
2918 'media' => self::SCREEN_MEDIA_QUERY,
2919 'expectedReturn' => self::SCREEN_MEDIA_QUERY,
2920 'message' => 'On screen request, screen media query is preserved.'
2921 ] );
2922
2923 $this->assertTransformCssMediaCase( [
2924 'media' => self::SCREEN_ONLY_MEDIA_QUERY,
2925 'expectedReturn' => self::SCREEN_ONLY_MEDIA_QUERY,
2926 'message' => 'On screen request, screen media query with only is preserved.'
2927 ] );
2928
2929 $this->assertTransformCssMediaCase( [
2930 'media' => 'print',
2931 'expectedReturn' => 'print',
2932 'message' => 'On screen request, print media type is preserved'
2933 ] );
2934 }
2935
2936 /**
2937 * Tests handheld behavior
2938 *
2939 * @covers OutputPage::transformCssMedia
2940 */
2941 public function testHandheld() {
2942 $this->assertTransformCssMediaCase( [
2943 'handheldQuery' => '1',
2944 'media' => 'handheld',
2945 'expectedReturn' => '',
2946 'message' => 'On request with handheld querystring and media is handheld, returns empty string'
2947 ] );
2948
2949 $this->assertTransformCssMediaCase( [
2950 'handheldQuery' => '1',
2951 'media' => 'screen',
2952 'expectedReturn' => null,
2953 'message' => 'On request with handheld querystring and media is screen, returns null'
2954 ] );
2955 }
2956
2957 /**
2958 * @covers OutputPage::isTOCEnabled
2959 * @covers OutputPage::addParserOutputMetadata
2960 * @covers OutputPage::addParserOutput
2961 */
2962 public function testIsTOCEnabled() {
2963 $op = $this->newInstance();
2964 $this->assertFalse( $op->isTOCEnabled() );
2965
2966 $pOut1 = $this->createParserOutputStub( 'getTOCHTML', false );
2967 $op->addParserOutputMetadata( $pOut1 );
2968 $this->assertFalse( $op->isTOCEnabled() );
2969
2970 $pOut2 = $this->createParserOutputStub( 'getTOCHTML', true );
2971 $op->addParserOutput( $pOut2 );
2972 $this->assertTrue( $op->isTOCEnabled() );
2973
2974 // The parser output doesn't disable the TOC after it was enabled
2975 $op->addParserOutputMetadata( $pOut1 );
2976 $this->assertTrue( $op->isTOCEnabled() );
2977 }
2978
2979 /**
2980 * @dataProvider providePreloadLinkHeaders
2981 * @covers ResourceLoaderSkinModule::getPreloadLinks
2982 * @covers ResourceLoaderSkinModule::getLogoPreloadlinks
2983 */
2984 public function testPreloadLinkHeaders( $config, $result ) {
2985 $this->setMwGlobals( $config );
2986 $ctx = $this->getMockBuilder( ResourceLoaderContext::class )
2987 ->disableOriginalConstructor()->getMock();
2988 $module = new ResourceLoaderSkinModule();
2989
2990 $this->assertEquals( [ $result ], $module->getHeaders( $ctx ) );
2991 }
2992
2993 public function providePreloadLinkHeaders() {
2994 return [
2995 [
2996 [
2997 'wgResourceBasePath' => '/w',
2998 'wgLogo' => '/img/default.png',
2999 'wgLogoHD' => [
3000 '1.5x' => '/img/one-point-five.png',
3001 '2x' => '/img/two-x.png',
3002 ],
3003 ],
3004 'Link: </img/default.png>;rel=preload;as=image;media=' .
3005 'not all and (min-resolution: 1.5dppx),' .
3006 '</img/one-point-five.png>;rel=preload;as=image;media=' .
3007 '(min-resolution: 1.5dppx) and (max-resolution: 1.999999dppx),' .
3008 '</img/two-x.png>;rel=preload;as=image;media=(min-resolution: 2dppx)'
3009 ],
3010 [
3011 [
3012 'wgResourceBasePath' => '/w',
3013 'wgLogo' => '/img/default.png',
3014 'wgLogoHD' => false,
3015 ],
3016 'Link: </img/default.png>;rel=preload;as=image'
3017 ],
3018 [
3019 [
3020 'wgResourceBasePath' => '/w',
3021 'wgLogo' => '/img/default.png',
3022 'wgLogoHD' => [
3023 '2x' => '/img/two-x.png',
3024 ],
3025 ],
3026 'Link: </img/default.png>;rel=preload;as=image;media=' .
3027 'not all and (min-resolution: 2dppx),' .
3028 '</img/two-x.png>;rel=preload;as=image;media=(min-resolution: 2dppx)'
3029 ],
3030 [
3031 [
3032 'wgResourceBasePath' => '/w',
3033 'wgLogo' => '/img/default.png',
3034 'wgLogoHD' => [
3035 'svg' => '/img/vector.svg',
3036 ],
3037 ],
3038 'Link: </img/vector.svg>;rel=preload;as=image'
3039
3040 ],
3041 [
3042 [
3043 'wgResourceBasePath' => '/w',
3044 'wgLogo' => '/w/test.jpg',
3045 'wgLogoHD' => false,
3046 'wgUploadPath' => '/w/images',
3047 'IP' => dirname( __DIR__ ) . '/data/media',
3048 ],
3049 'Link: </w/test.jpg?edcf2>;rel=preload;as=image',
3050 ],
3051 ];
3052 }
3053
3054 /**
3055 * @return OutputPage
3056 */
3057 private function newInstance( $config = [], WebRequest $request = null, $options = [] ) {
3058 $context = new RequestContext();
3059
3060 $context->setConfig( new MultiConfig( [
3061 new HashConfig( $config + [
3062 'AppleTouchIcon' => false,
3063 'DisableLangConversion' => true,
3064 'EnableCanonicalServerLink' => false,
3065 'Favicon' => false,
3066 'Feed' => false,
3067 'LanguageCode' => false,
3068 'ReferrerPolicy' => false,
3069 'RightsPage' => false,
3070 'RightsUrl' => false,
3071 'UniversalEditButton' => false,
3072 ] ),
3073 $context->getConfig()
3074 ] ) );
3075
3076 if ( !in_array( 'notitle', (array)$options ) ) {
3077 $context->setTitle( Title::newFromText( 'My test page' ) );
3078 }
3079
3080 if ( $request ) {
3081 $context->setRequest( $request );
3082 }
3083
3084 return new OutputPage( $context );
3085 }
3086 }