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