Merge "Don't wrap output added by OutputPage::addWikiText*()"
[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 */
259 public function testHeadItemsParserOutput() {
260 $op = $this->newInstance();
261 $stubPO1 = $this->createParserOutputStub( 'getHeadItems', [ 'a' => 'b' ] );
262 $op->addParserOutputMetadata( $stubPO1 );
263 $stubPO2 = $this->createParserOutputStub( 'getHeadItems',
264 [ 'c' => '<d>&amp;', 'e' => 'f', 'a' => 'q' ] );
265 $op->addParserOutputMetadata( $stubPO2 );
266 $stubPO3 = $this->createParserOutputStub( 'getHeadItems', [ 'e' => 'g' ] );
267 $op->addParserOutputMetadata( $stubPO3 );
268 $stubPO4 = $this->createParserOutputStub( 'getHeadItems', [ 'x' ] );
269 $op->addParserOutputMetadata( $stubPO4 );
270
271 $this->assertSame( [ 'a' => 'q', 'c' => '<d>&amp;', 'e' => 'g', 'x' ],
272 $op->getHeadItemsArray() );
273
274 $this->assertTrue( $op->hasHeadItem( 'a' ) );
275 $this->assertTrue( $op->hasHeadItem( 'c' ) );
276 $this->assertTrue( $op->hasHeadItem( 'e' ) );
277 $this->assertTrue( $op->hasHeadItem( '0' ) );
278 $this->assertFalse( $op->hasHeadItem( 'b' ) );
279
280 $this->assertContains( "\nq\n<d>&amp;\ng\nx\n",
281 '' . $op->headElement( $op->getContext()->getSkin() ) );
282 }
283
284 /**
285 * @covers OutputPage::addBodyClasses
286 */
287 public function testAddBodyClasses() {
288 $op = $this->newInstance();
289 $op->addBodyClasses( 'a' );
290 $op->addBodyClasses( 'mediawiki' );
291 $op->addBodyClasses( 'b c' );
292 $op->addBodyClasses( [ 'd', 'e' ] );
293 $op->addBodyClasses( 'a' );
294
295 $this->assertContains( '"a mediawiki b c d e ltr',
296 '' . $op->headElement( $op->getContext()->getSkin() ) );
297 }
298
299 /**
300 * @covers OutputPage::setArticleBodyOnly
301 * @covers OutputPage::getArticleBodyOnly
302 */
303 public function testArticleBodyOnly() {
304 $op = $this->newInstance();
305 $this->assertFalse( $op->getArticleBodyOnly() );
306
307 $op->setArticleBodyOnly( true );
308 $this->assertTrue( $op->getArticleBodyOnly() );
309
310 $op->addHTML( '<b>a</b>' );
311
312 $this->assertSame( '<b>a</b>', $op->output( true ) );
313 }
314
315 /**
316 * @covers OutputPage::setProperty
317 * @covers OutputPage::getProperty
318 */
319 public function testProperties() {
320 $op = $this->newInstance();
321
322 $this->assertNull( $op->getProperty( 'foo' ) );
323
324 $op->setProperty( 'foo', 'bar' );
325 $op->setProperty( 'baz', 'quz' );
326
327 $this->assertSame( 'bar', $op->getProperty( 'foo' ) );
328 $this->assertSame( 'quz', $op->getProperty( 'baz' ) );
329 }
330
331 /**
332 * @dataProvider provideCheckLastModified
333 *
334 * @covers OutputPage::checkLastModified
335 * @covers OutputPage::getCdnCacheEpoch
336 */
337 public function testCheckLastModified(
338 $timestamp, $ifModifiedSince, $expected, $config = [], $callback = null
339 ) {
340 $request = new FauxRequest();
341 if ( $ifModifiedSince ) {
342 if ( is_numeric( $ifModifiedSince ) ) {
343 // Unix timestamp
344 $ifModifiedSince = date( 'D, d M Y H:i:s', $ifModifiedSince ) . ' GMT';
345 }
346 $request->setHeader( 'If-Modified-Since', $ifModifiedSince );
347 }
348
349 if ( !isset( $config['CacheEpoch'] ) ) {
350 // Make sure it's not too recent
351 $config['CacheEpoch'] = '20000101000000';
352 }
353
354 $op = $this->newInstance( $config, $request );
355
356 if ( $callback ) {
357 $callback( $op, $this );
358 }
359
360 // Avoid a complaint about not being able to disable compression
361 Wikimedia\suppressWarnings();
362 try {
363 $this->assertEquals( $expected, $op->checkLastModified( $timestamp ) );
364 } finally {
365 Wikimedia\restoreWarnings();
366 }
367 }
368
369 public function provideCheckLastModified() {
370 $lastModified = time() - 3600;
371 return [
372 'Timestamp 0' =>
373 [ '0', $lastModified, false ],
374 'Timestamp Unix epoch' =>
375 [ '19700101000000', $lastModified, false ],
376 'Timestamp same as If-Modified-Since' =>
377 [ $lastModified, $lastModified, true ],
378 'Timestamp one second after If-Modified-Since' =>
379 [ $lastModified + 1, $lastModified, false ],
380 'No If-Modified-Since' =>
381 [ $lastModified + 1, null, false ],
382 'Malformed If-Modified-Since' =>
383 [ $lastModified + 1, 'GIBBERING WOMBATS !!!', false ],
384 'Non-standard IE-style If-Modified-Since' =>
385 [ $lastModified, date( 'D, d M Y H:i:s', $lastModified ) . ' GMT; length=5202',
386 true ],
387 // @todo Should we fix this behavior to match the spec? Probably no reason to.
388 'If-Modified-Since not per spec but we accept it anyway because strtotime does' =>
389 [ $lastModified, "@$lastModified", true ],
390 '$wgCachePages = false' =>
391 [ $lastModified, $lastModified, false, [ 'CachePages' => false ] ],
392 '$wgCacheEpoch' =>
393 [ $lastModified, $lastModified, false,
394 [ 'CacheEpoch' => wfTimestamp( TS_MW, $lastModified + 1 ) ] ],
395 'Recently-touched user' =>
396 [ $lastModified, $lastModified, false, [],
397 function ( $op ) {
398 $op->getContext()->setUser( $this->getTestUser()->getUser() );
399 } ],
400 'After Squid expiry' =>
401 [ $lastModified, $lastModified, false,
402 [ 'UseSquid' => true, 'SquidMaxage' => 3599 ] ],
403 'Hook allows cache use' =>
404 [ $lastModified + 1, $lastModified, true, [],
405 function ( $op, $that ) {
406 $that->setTemporaryHook( 'OutputPageCheckLastModified',
407 function ( &$modifiedTimes ) {
408 $modifiedTimes = [ 1 ];
409 }
410 );
411 } ],
412 'Hooks prohibits cache use' =>
413 [ $lastModified, $lastModified, false, [],
414 function ( $op, $that ) {
415 $that->setTemporaryHook( 'OutputPageCheckLastModified',
416 function ( &$modifiedTimes ) {
417 $modifiedTimes = [ max( $modifiedTimes ) + 1 ];
418 }
419 );
420 } ],
421 ];
422 }
423
424 /**
425 * @dataProvider provideCdnCacheEpoch
426 *
427 * @covers OutputPage::getCdnCacheEpoch
428 */
429 public function testCdnCacheEpoch( $params ) {
430 $out = TestingAccessWrapper::newFromObject( $this->newInstance() );
431 $reqTime = strtotime( $params['reqTime'] );
432 $pageTime = strtotime( $params['pageTime'] );
433 $actual = max( $pageTime, $out->getCdnCacheEpoch( $reqTime, $params['maxAge'] ) );
434
435 $this->assertEquals(
436 $params['expect'],
437 gmdate( DateTime::ATOM, $actual ),
438 'cdn epoch'
439 );
440 }
441
442 public static function provideCdnCacheEpoch() {
443 $base = [
444 'pageTime' => '2011-04-01T12:00:00+00:00',
445 'maxAge' => 24 * 3600,
446 ];
447 return [
448 'after 1s' => [ $base + [
449 'reqTime' => '2011-04-01T12:00:01+00:00',
450 'expect' => '2011-04-01T12:00:00+00:00',
451 ] ],
452 'after 23h' => [ $base + [
453 'reqTime' => '2011-04-02T11:00:00+00:00',
454 'expect' => '2011-04-01T12:00:00+00:00',
455 ] ],
456 'after 24h and a bit' => [ $base + [
457 'reqTime' => '2011-04-02T12:34:56+00:00',
458 'expect' => '2011-04-01T12:34:56+00:00',
459 ] ],
460 'after a year' => [ $base + [
461 'reqTime' => '2012-05-06T00:12:07+00:00',
462 'expect' => '2012-05-05T00:12:07+00:00',
463 ] ],
464 ];
465 }
466
467 // @todo How to test setLastModified?
468
469 /**
470 * @covers OutputPage::setRobotPolicy
471 * @covers OutputPage::getHeadLinksArray
472 */
473 public function testSetRobotPolicy() {
474 $op = $this->newInstance();
475 $op->setRobotPolicy( 'noindex, nofollow' );
476
477 $links = $op->getHeadLinksArray();
478 $this->assertContains( '<meta name="robots" content="noindex,nofollow"/>', $links );
479 }
480
481 /**
482 * @covers OutputPage::setIndexPolicy
483 * @covers OutputPage::setFollowPolicy
484 * @covers OutputPage::getHeadLinksArray
485 */
486 public function testSetIndexFollowPolicies() {
487 $op = $this->newInstance();
488 $op->setIndexPolicy( 'noindex' );
489 $op->setFollowPolicy( 'nofollow' );
490
491 $links = $op->getHeadLinksArray();
492 $this->assertContains( '<meta name="robots" content="noindex,nofollow"/>', $links );
493 }
494
495 private function extractHTMLTitle( OutputPage $op ) {
496 $html = $op->headElement( $op->getContext()->getSkin() );
497
498 // OutputPage should always output the title in a nice format such that regexes will work
499 // fine. If it doesn't, we'll fail the tests.
500 preg_match_all( '!<title>(.*?)</title>!', $html, $matches );
501
502 $this->assertLessThanOrEqual( 1, count( $matches[1] ), 'More than one <title>!' );
503
504 if ( !count( $matches[1] ) ) {
505 return null;
506 }
507
508 return $matches[1][0];
509 }
510
511 /**
512 * Shorthand for getting the text of a message, in content language.
513 */
514 private static function getMsgText( $op, ...$msgParams ) {
515 return $op->msg( ...$msgParams )->inContentLanguage()->text();
516 }
517
518 /**
519 * @covers OutputPage::setHTMLTitle
520 * @covers OutputPage::getHTMLTitle
521 */
522 public function testHTMLTitle() {
523 $op = $this->newInstance();
524
525 // Default
526 $this->assertSame( '', $op->getHTMLTitle() );
527 $this->assertSame( '', $op->getPageTitle() );
528 $this->assertSame(
529 $this->getMsgText( $op, 'pagetitle', '' ),
530 $this->extractHTMLTitle( $op )
531 );
532
533 // Set to string
534 $op->setHTMLTitle( 'Potatoes will eat me' );
535
536 $this->assertSame( 'Potatoes will eat me', $op->getHTMLTitle() );
537 $this->assertSame( 'Potatoes will eat me', $this->extractHTMLTitle( $op ) );
538 // Shouldn't have changed the page title
539 $this->assertSame( '', $op->getPageTitle() );
540
541 // Set to message
542 $msg = $op->msg( 'mainpage' );
543
544 $op->setHTMLTitle( $msg );
545 $this->assertSame( $msg->text(), $op->getHTMLTitle() );
546 $this->assertSame( $msg->text(), $this->extractHTMLTitle( $op ) );
547 $this->assertSame( '', $op->getPageTitle() );
548 }
549
550 /**
551 * @covers OutputPage::setRedirectedFrom
552 */
553 public function testSetRedirectedFrom() {
554 $op = $this->newInstance();
555
556 $op->setRedirectedFrom( Title::newFromText( 'Talk:Some page' ) );
557 $this->assertSame( 'Talk:Some_page', $op->getJSVars()['wgRedirectedFrom'] );
558 }
559
560 /**
561 * @covers OutputPage::setPageTitle
562 * @covers OutputPage::getPageTitle
563 */
564 public function testPageTitle() {
565 // We don't test the actual HTML output anywhere, because that's up to the skin.
566 $op = $this->newInstance();
567
568 // Test default
569 $this->assertSame( '', $op->getPageTitle() );
570 $this->assertSame( '', $op->getHTMLTitle() );
571
572 // Test set to plain text
573 $op->setPageTitle( 'foobar' );
574
575 $this->assertSame( 'foobar', $op->getPageTitle() );
576 // HTML title should change as well
577 $this->assertSame( $this->getMsgText( $op, 'pagetitle', 'foobar' ), $op->getHTMLTitle() );
578
579 // Test set to text with good and bad HTML. We don't try to be comprehensive here, that
580 // belongs in Sanitizer tests.
581 $op->setPageTitle( '<script>a</script>&amp;<i>b</i>' );
582
583 $this->assertSame( '&lt;script&gt;a&lt;/script&gt;&amp;<i>b</i>', $op->getPageTitle() );
584 $this->assertSame(
585 $this->getMsgText( $op, 'pagetitle', '<script>a</script>&b' ),
586 $op->getHTMLTitle()
587 );
588
589 // Test set to message
590 $text = $this->getMsgText( $op, 'mainpage' );
591
592 $op->setPageTitle( $op->msg( 'mainpage' )->inContentLanguage() );
593 $this->assertSame( $text, $op->getPageTitle() );
594 $this->assertSame( $this->getMsgText( $op, 'pagetitle', $text ), $op->getHTMLTitle() );
595 }
596
597 /**
598 * @covers OutputPage::setTitle
599 */
600 public function testSetTitle() {
601 $op = $this->newInstance();
602
603 $this->assertSame( 'My test page', $op->getTitle()->getPrefixedText() );
604
605 $op->setTitle( Title::newFromText( 'Another test page' ) );
606
607 $this->assertSame( 'Another test page', $op->getTitle()->getPrefixedText() );
608 }
609
610 /**
611 * @covers OutputPage::setSubtitle
612 * @covers OutputPage::clearSubtitle
613 * @covers OutputPage::addSubtitle
614 * @covers OutputPage::getSubtitle
615 */
616 public function testSubtitle() {
617 $op = $this->newInstance();
618
619 $this->assertSame( '', $op->getSubtitle() );
620
621 $op->addSubtitle( '<b>foo</b>' );
622
623 $this->assertSame( '<b>foo</b>', $op->getSubtitle() );
624
625 $op->addSubtitle( $op->msg( 'mainpage' )->inContentLanguage() );
626
627 $this->assertSame(
628 "<b>foo</b><br />\n\t\t\t\t" . $this->getMsgText( $op, 'mainpage' ),
629 $op->getSubtitle()
630 );
631
632 $op->setSubtitle( 'There can be only one' );
633
634 $this->assertSame( 'There can be only one', $op->getSubtitle() );
635
636 $op->clearSubtitle();
637
638 $this->assertSame( '', $op->getSubtitle() );
639 }
640
641 /**
642 * @dataProvider provideBacklinkSubtitle
643 *
644 * @covers OutputPage::buildBacklinkSubtitle
645 */
646 public function testBuildBacklinkSubtitle( $titles, $queries, $contains, $notContains ) {
647 if ( count( $titles ) > 1 ) {
648 // Not applicable
649 $this->assertTrue( true );
650 return;
651 }
652
653 $title = Title::newFromText( $titles[0] );
654 $query = $queries[0];
655
656 $this->editPage( 'Page 1', '' );
657 $this->editPage( 'Page 2', '#REDIRECT [[Page 1]]' );
658
659 $str = OutputPage::buildBacklinkSubtitle( $title, $query )->text();
660
661 foreach ( $contains as $substr ) {
662 $this->assertContains( $substr, $str );
663 }
664
665 foreach ( $notContains as $substr ) {
666 $this->assertNotContains( $substr, $str );
667 }
668 }
669
670 /**
671 * @dataProvider provideBacklinkSubtitle
672 *
673 * @covers OutputPage::addBacklinkSubtitle
674 * @covers OutputPage::getSubtitle
675 */
676 public function testAddBacklinkSubtitle( $titles, $queries, $contains, $notContains ) {
677 $this->editPage( 'Page 1', '' );
678 $this->editPage( 'Page 2', '#REDIRECT [[Page 1]]' );
679
680 $op = $this->newInstance();
681 foreach ( $titles as $i => $unused ) {
682 $op->addBacklinkSubtitle( Title::newFromText( $titles[$i] ), $queries[$i] );
683 }
684
685 $str = $op->getSubtitle();
686
687 foreach ( $contains as $substr ) {
688 $this->assertContains( $substr, $str );
689 }
690
691 foreach ( $notContains as $substr ) {
692 $this->assertNotContains( $substr, $str );
693 }
694 }
695
696 public function provideBacklinkSubtitle() {
697 return [
698 [
699 [ 'Page 1' ],
700 [ [] ],
701 [ 'Page 1' ],
702 [ 'redirect', 'Page 2' ],
703 ],
704 [
705 [ 'Page 2' ],
706 [ [] ],
707 [ 'redirect=no' ],
708 [ 'Page 1' ],
709 ],
710 [
711 [ 'Page 1' ],
712 [ [ 'action' => 'edit' ] ],
713 [ 'action=edit' ],
714 [],
715 ],
716 [
717 [ 'Page 1', 'Page 2' ],
718 [ [], [] ],
719 [ 'Page 1', 'Page 2', "<br />\n\t\t\t\t" ],
720 [],
721 ],
722 // @todo Anything else to test?
723 ];
724 }
725
726 /**
727 * @covers OutputPage::setPrintable
728 * @covers OutputPage::isPrintable
729 */
730 public function testPrintable() {
731 $op = $this->newInstance();
732
733 $this->assertFalse( $op->isPrintable() );
734
735 $op->setPrintable();
736
737 $this->assertTrue( $op->isPrintable() );
738 }
739
740 /**
741 * @covers OutputPage::disable
742 * @covers OutputPage::isDisabled
743 */
744 public function testDisable() {
745 $op = $this->newInstance();
746
747 $this->assertFalse( $op->isDisabled() );
748 $this->assertNotSame( '', $op->output( true ) );
749
750 $op->disable();
751
752 $this->assertTrue( $op->isDisabled() );
753 $this->assertSame( '', $op->output( true ) );
754 }
755
756 /**
757 * @covers OutputPage::showNewSectionLink
758 * @covers OutputPage::addParserOutputMetadata
759 */
760 public function testShowNewSectionLink() {
761 $op = $this->newInstance();
762
763 $this->assertFalse( $op->showNewSectionLink() );
764
765 $po = new ParserOutput();
766 $po->setNewSection( true );
767 $op->addParserOutputMetadata( $po );
768
769 $this->assertTrue( $op->showNewSectionLink() );
770 }
771
772 /**
773 * @covers OutputPage::forceHideNewSectionLink
774 * @covers OutputPage::addParserOutputMetadata
775 */
776 public function testForceHideNewSectionLink() {
777 $op = $this->newInstance();
778
779 $this->assertFalse( $op->forceHideNewSectionLink() );
780
781 $po = new ParserOutput();
782 $po->hideNewSection( true );
783 $op->addParserOutputMetadata( $po );
784
785 $this->assertTrue( $op->forceHideNewSectionLink() );
786 }
787
788 /**
789 * @covers OutputPage::setSyndicated
790 * @covers OutputPage::isSyndicated
791 */
792 public function testSetSyndicated() {
793 $op = $this->newInstance();
794 $this->assertFalse( $op->isSyndicated() );
795
796 $op->setSyndicated();
797 $this->assertTrue( $op->isSyndicated() );
798
799 $op->setSyndicated( false );
800 $this->assertFalse( $op->isSyndicated() );
801 }
802
803 /**
804 * @covers OutputPage::isSyndicated
805 * @covers OutputPage::setFeedAppendQuery
806 * @covers OutputPage::addFeedLink
807 * @covers OutputPage::getSyndicationLinks()
808 */
809 public function testFeedLinks() {
810 $op = $this->newInstance();
811 $this->assertSame( [], $op->getSyndicationLinks() );
812
813 $op->addFeedLink( 'not a supported format', 'abc' );
814 $this->assertFalse( $op->isSyndicated() );
815 $this->assertSame( [], $op->getSyndicationLinks() );
816
817 $feedTypes = $op->getConfig()->get( 'AdvertisedFeedTypes' );
818
819 $op->addFeedLink( $feedTypes[0], 'def' );
820 $this->assertTrue( $op->isSyndicated() );
821 $this->assertSame( [ $feedTypes[0] => 'def' ], $op->getSyndicationLinks() );
822
823 $op->setFeedAppendQuery( false );
824 $expected = [];
825 foreach ( $feedTypes as $type ) {
826 $expected[$type] = $op->getTitle()->getLocalURL( "feed=$type" );
827 }
828 $this->assertSame( $expected, $op->getSyndicationLinks() );
829
830 $op->setFeedAppendQuery( 'apples=oranges' );
831 foreach ( $feedTypes as $type ) {
832 $expected[$type] = $op->getTitle()->getLocalURL( "feed=$type&apples=oranges" );
833 }
834 $this->assertSame( $expected, $op->getSyndicationLinks() );
835 }
836
837 /**
838 * @covers OutputPage::setArticleFlag
839 * @covers OutputPage::isArticle
840 * @covers OutputPage::setArticleRelated
841 * @covers OutputPage::isArticleRelated
842 */
843 function testArticleFlags() {
844 $op = $this->newInstance();
845 $this->assertFalse( $op->isArticle() );
846 $this->assertTrue( $op->isArticleRelated() );
847
848 $op->setArticleRelated( false );
849 $this->assertFalse( $op->isArticle() );
850 $this->assertFalse( $op->isArticleRelated() );
851
852 $op->setArticleFlag( true );
853 $this->assertTrue( $op->isArticle() );
854 $this->assertTrue( $op->isArticleRelated() );
855
856 $op->setArticleFlag( false );
857 $this->assertFalse( $op->isArticle() );
858 $this->assertTrue( $op->isArticleRelated() );
859
860 $op->setArticleFlag( true );
861 $op->setArticleRelated( false );
862 $this->assertFalse( $op->isArticle() );
863 $this->assertFalse( $op->isArticleRelated() );
864 }
865
866 /**
867 * @covers OutputPage::addLanguageLinks
868 * @covers OutputPage::setLanguageLinks
869 * @covers OutputPage::getLanguageLinks
870 * @covers OutputPage::addParserOutputMetadata
871 */
872 function testLanguageLinks() {
873 $op = $this->newInstance();
874 $this->assertSame( [], $op->getLanguageLinks() );
875
876 $op->addLanguageLinks( [ 'fr:A', 'it:B' ] );
877 $this->assertSame( [ 'fr:A', 'it:B' ], $op->getLanguageLinks() );
878
879 $op->addLanguageLinks( [ 'de:C', 'es:D' ] );
880 $this->assertSame( [ 'fr:A', 'it:B', 'de:C', 'es:D' ], $op->getLanguageLinks() );
881
882 $op->setLanguageLinks( [ 'pt:E' ] );
883 $this->assertSame( [ 'pt:E' ], $op->getLanguageLinks() );
884
885 $po = new ParserOutput();
886 $po->setLanguageLinks( [ 'he:F', 'ar:G' ] );
887 $op->addParserOutputMetadata( $po );
888 $this->assertSame( [ 'pt:E', 'he:F', 'ar:G' ], $op->getLanguageLinks() );
889 }
890
891 // @todo Are these category links tests too abstract and complicated for what they test? Would
892 // it make sense to just write out all the tests by hand with maybe some copy-and-paste?
893
894 /**
895 * @dataProvider provideGetCategories
896 *
897 * @covers OutputPage::addCategoryLinks
898 * @covers OutputPage::getCategories
899 * @covers OutputPage::getCategoryLinks
900 *
901 * @param array $args Array of form [ category name => sort key ]
902 * @param array $fakeResults Array of form [ category name => value to return from mocked
903 * LinkBatch ]
904 * @param callback $variantLinkCallback Callback to replace findVariantLink() call
905 * @param array $expectedNormal Expected return value of getCategoryLinks['normal']
906 * @param array $expectedHidden Expected return value of getCategoryLinks['hidden']
907 */
908 public function testAddCategoryLinks(
909 array $args, array $fakeResults, callable $variantLinkCallback = null,
910 array $expectedNormal, array $expectedHidden
911 ) {
912 $expectedNormal = $this->extractExpectedCategories( $expectedNormal, 'add' );
913 $expectedHidden = $this->extractExpectedCategories( $expectedHidden, 'add' );
914
915 $op = $this->setupCategoryTests( $fakeResults, $variantLinkCallback );
916
917 $op->addCategoryLinks( $args );
918
919 $this->doCategoryAsserts( $op, $expectedNormal, $expectedHidden );
920 $this->doCategoryLinkAsserts( $op, $expectedNormal, $expectedHidden );
921 }
922
923 /**
924 * @dataProvider provideGetCategories
925 *
926 * @covers OutputPage::addCategoryLinks
927 * @covers OutputPage::getCategories
928 * @covers OutputPage::getCategoryLinks
929 */
930 public function testAddCategoryLinksOneByOne(
931 array $args, array $fakeResults, callable $variantLinkCallback = null,
932 array $expectedNormal, array $expectedHidden
933 ) {
934 if ( count( $args ) <= 1 ) {
935 // @todo Should this be skipped instead of passed?
936 $this->assertTrue( true );
937 return;
938 }
939
940 $expectedNormal = $this->extractExpectedCategories( $expectedNormal, 'onebyone' );
941 $expectedHidden = $this->extractExpectedCategories( $expectedHidden, 'onebyone' );
942
943 $op = $this->setupCategoryTests( $fakeResults, $variantLinkCallback );
944
945 foreach ( $args as $key => $val ) {
946 $op->addCategoryLinks( [ $key => $val ] );
947 }
948
949 $this->doCategoryAsserts( $op, $expectedNormal, $expectedHidden );
950 $this->doCategoryLinkAsserts( $op, $expectedNormal, $expectedHidden );
951 }
952
953 /**
954 * @dataProvider provideGetCategories
955 *
956 * @covers OutputPage::setCategoryLinks
957 * @covers OutputPage::getCategories
958 * @covers OutputPage::getCategoryLinks
959 */
960 public function testSetCategoryLinks(
961 array $args, array $fakeResults, callable $variantLinkCallback = null,
962 array $expectedNormal, array $expectedHidden
963 ) {
964 $expectedNormal = $this->extractExpectedCategories( $expectedNormal, 'set' );
965 $expectedHidden = $this->extractExpectedCategories( $expectedHidden, 'set' );
966
967 $op = $this->setupCategoryTests( $fakeResults, $variantLinkCallback );
968
969 $op->setCategoryLinks( [ 'Initial page' => 'Initial page' ] );
970 $op->setCategoryLinks( $args );
971
972 // We don't reset the categories, for some reason, only the links
973 $expectedNormalCats = array_merge( [ 'Initial page' ], $expectedNormal );
974 $expectedCats = array_merge( $expectedHidden, $expectedNormalCats );
975
976 $this->doCategoryAsserts( $op, $expectedNormalCats, $expectedHidden );
977 $this->doCategoryLinkAsserts( $op, $expectedNormal, $expectedHidden );
978 }
979
980 /**
981 * @dataProvider provideGetCategories
982 *
983 * @covers OutputPage::addParserOutputMetadata
984 * @covers OutputPage::getCategories
985 * @covers OutputPage::getCategoryLinks
986 */
987 public function testParserOutputCategoryLinks(
988 array $args, array $fakeResults, callable $variantLinkCallback = null,
989 array $expectedNormal, array $expectedHidden
990 ) {
991 $expectedNormal = $this->extractExpectedCategories( $expectedNormal, 'pout' );
992 $expectedHidden = $this->extractExpectedCategories( $expectedHidden, 'pout' );
993
994 $op = $this->setupCategoryTests( $fakeResults, $variantLinkCallback );
995
996 $stubPO = $this->createParserOutputStub( 'getCategories', $args );
997
998 $op->addParserOutputMetadata( $stubPO );
999
1000 $this->doCategoryAsserts( $op, $expectedNormal, $expectedHidden );
1001 $this->doCategoryLinkAsserts( $op, $expectedNormal, $expectedHidden );
1002 }
1003
1004 /**
1005 * We allow different expectations for different tests as an associative array, like
1006 * [ 'set' => [ ... ], 'default' => [ ... ] ] if setCategoryLinks() will give a different
1007 * result.
1008 */
1009 private function extractExpectedCategories( array $expected, $key ) {
1010 if ( !$expected || isset( $expected[0] ) ) {
1011 return $expected;
1012 }
1013 return $expected[$key] ?? $expected['default'];
1014 }
1015
1016 private function setupCategoryTests(
1017 array $fakeResults, callable $variantLinkCallback = null
1018 ) : OutputPage {
1019 $this->setMwGlobals( 'wgUsePigLatinVariant', true );
1020
1021 $op = $this->getMockBuilder( OutputPage::class )
1022 ->setConstructorArgs( [ new RequestContext() ] )
1023 ->setMethods( [ 'addCategoryLinksToLBAndGetResult' ] )
1024 ->getMock();
1025
1026 $op->expects( $this->any() )
1027 ->method( 'addCategoryLinksToLBAndGetResult' )
1028 ->will( $this->returnCallback( function ( array $categories ) use ( $fakeResults ) {
1029 $return = [];
1030 foreach ( $categories as $category => $unused ) {
1031 if ( isset( $fakeResults[$category] ) ) {
1032 $return[] = $fakeResults[$category];
1033 }
1034 }
1035 return new FakeResultWrapper( $return );
1036 } ) );
1037
1038 if ( $variantLinkCallback ) {
1039 $mockContLang = $this->getMockBuilder( Language::class )
1040 ->setConstructorArgs( [ 'en' ] )
1041 ->setMethods( [ 'findVariantLink' ] )
1042 ->getMock();
1043 $mockContLang->expects( $this->any() )
1044 ->method( 'findVariantLink' )
1045 ->will( $this->returnCallback( $variantLinkCallback ) );
1046 $this->setContentLang( $mockContLang );
1047 }
1048
1049 $this->assertSame( [], $op->getCategories() );
1050
1051 return $op;
1052 }
1053
1054 private function doCategoryAsserts( $op, $expectedNormal, $expectedHidden ) {
1055 $this->assertSame( array_merge( $expectedHidden, $expectedNormal ), $op->getCategories() );
1056 $this->assertSame( $expectedNormal, $op->getCategories( 'normal' ) );
1057 $this->assertSame( $expectedHidden, $op->getCategories( 'hidden' ) );
1058 }
1059
1060 private function doCategoryLinkAsserts( $op, $expectedNormal, $expectedHidden ) {
1061 $catLinks = $op->getCategoryLinks();
1062 $this->assertSame( (bool)$expectedNormal + (bool)$expectedHidden, count( $catLinks ) );
1063 if ( $expectedNormal ) {
1064 $this->assertSame( count( $expectedNormal ), count( $catLinks['normal'] ) );
1065 }
1066 if ( $expectedHidden ) {
1067 $this->assertSame( count( $expectedHidden ), count( $catLinks['hidden'] ) );
1068 }
1069
1070 foreach ( $expectedNormal as $i => $name ) {
1071 $this->assertContains( $name, $catLinks['normal'][$i] );
1072 }
1073 foreach ( $expectedHidden as $i => $name ) {
1074 $this->assertContains( $name, $catLinks['hidden'][$i] );
1075 }
1076 }
1077
1078 public function provideGetCategories() {
1079 return [
1080 'No categories' => [ [], [], null, [], [] ],
1081 'Simple test' => [
1082 [ 'Test1' => 'Some sortkey', 'Test2' => 'A different sortkey' ],
1083 [ 'Test1' => (object)[ 'pp_value' => 1, 'page_title' => 'Test1' ],
1084 'Test2' => (object)[ 'page_title' => 'Test2' ] ],
1085 null,
1086 [ 'Test2' ],
1087 [ 'Test1' ],
1088 ],
1089 'Invalid title' => [
1090 [ '[' => '[', 'Test' => 'Test' ],
1091 [ 'Test' => (object)[ 'page_title' => 'Test' ] ],
1092 null,
1093 [ 'Test' ],
1094 [],
1095 ],
1096 'Variant link' => [
1097 [ 'Test' => 'Test', 'Estay' => 'Estay' ],
1098 [ 'Test' => (object)[ 'page_title' => 'Test' ] ],
1099 function ( &$link, &$title ) {
1100 if ( $link === 'Estay' ) {
1101 $link = 'Test';
1102 $title = Title::makeTitleSafe( NS_CATEGORY, $link );
1103 }
1104 },
1105 // For adding one by one, the variant gets added as well as the original category,
1106 // but if you add them all together the second time gets skipped.
1107 [ 'onebyone' => [ 'Test', 'Test' ], 'default' => [ 'Test' ] ],
1108 [],
1109 ],
1110 ];
1111 }
1112
1113 /**
1114 * @covers OutputPage::getCategories
1115 */
1116 public function testGetCategoriesInvalid() {
1117 $this->setExpectedException( InvalidArgumentException::class,
1118 'Invalid category type given: hiddne' );
1119
1120 $op = $this->newInstance();
1121 $op->getCategories( 'hiddne' );
1122 }
1123
1124 // @todo Should we test addCategoryLinksToLBAndGetResult? If so, how? Insert some test rows in
1125 // the DB?
1126
1127 /**
1128 * @covers OutputPage::setIndicators
1129 * @covers OutputPage::getIndicators
1130 * @covers OutputPage::addParserOutputMetadata
1131 */
1132 public function testIndicators() {
1133 $op = $this->newInstance();
1134 $this->assertSame( [], $op->getIndicators() );
1135
1136 $op->setIndicators( [] );
1137 $this->assertSame( [], $op->getIndicators() );
1138
1139 // Test sorting alphabetically
1140 $op->setIndicators( [ 'b' => 'x', 'a' => 'y' ] );
1141 $this->assertSame( [ 'a' => 'y', 'b' => 'x' ], $op->getIndicators() );
1142
1143 // Test overwriting existing keys
1144 $op->setIndicators( [ 'c' => 'z', 'a' => 'w' ] );
1145 $this->assertSame( [ 'a' => 'w', 'b' => 'x', 'c' => 'z' ], $op->getIndicators() );
1146
1147 // Test with ParserOutput
1148 $stubPO = $this->createParserOutputStub( 'getIndicators', [ 'c' => 'u', 'd' => 'v' ] );
1149 $op->addParserOutputMetadata( $stubPO );
1150 $this->assertSame( [ 'a' => 'w', 'b' => 'x', 'c' => 'u', 'd' => 'v' ],
1151 $op->getIndicators() );
1152 }
1153
1154 /**
1155 * @covers OutputPage::addHelpLink
1156 * @covers OutputPage::getIndicators
1157 */
1158 public function testAddHelpLink() {
1159 $op = $this->newInstance();
1160
1161 $op->addHelpLink( 'Manual:PHP unit testing' );
1162 $indicators = $op->getIndicators();
1163 $this->assertSame( [ 'mw-helplink' ], array_keys( $indicators ) );
1164 $this->assertContains( 'Manual:PHP_unit_testing', $indicators['mw-helplink'] );
1165
1166 $op->addHelpLink( 'https://phpunit.de', true );
1167 $indicators = $op->getIndicators();
1168 $this->assertSame( [ 'mw-helplink' ], array_keys( $indicators ) );
1169 $this->assertContains( 'https://phpunit.de', $indicators['mw-helplink'] );
1170 $this->assertNotContains( 'mediawiki', $indicators['mw-helplink'] );
1171 $this->assertNotContains( 'Manual:PHP', $indicators['mw-helplink'] );
1172 }
1173
1174 /**
1175 * @covers OutputPage::prependHTML
1176 * @covers OutputPage::addHTML
1177 * @covers OutputPage::addElement
1178 * @covers OutputPage::clearHTML
1179 * @covers OutputPage::getHTML
1180 */
1181 public function testBodyHTML() {
1182 $op = $this->newInstance();
1183 $this->assertSame( '', $op->getHTML() );
1184
1185 $op->addHTML( 'a' );
1186 $this->assertSame( 'a', $op->getHTML() );
1187
1188 $op->addHTML( 'b' );
1189 $this->assertSame( 'ab', $op->getHTML() );
1190
1191 $op->prependHTML( 'c' );
1192 $this->assertSame( 'cab', $op->getHTML() );
1193
1194 $op->addElement( 'p', [ 'id' => 'foo' ], 'd' );
1195 $this->assertSame( 'cab<p id="foo">d</p>', $op->getHTML() );
1196
1197 $op->clearHTML();
1198 $this->assertSame( '', $op->getHTML() );
1199 }
1200
1201 /**
1202 * @dataProvider provideRevisionId
1203 * @covers OutputPage::setRevisionId
1204 * @covers OutputPage::getRevisionId
1205 */
1206 public function testRevisionId( $newVal, $expected ) {
1207 $op = $this->newInstance();
1208
1209 $this->assertNull( $op->setRevisionId( $newVal ) );
1210 $this->assertSame( $expected, $op->getRevisionId() );
1211 $this->assertSame( $expected, $op->setRevisionId( null ) );
1212 $this->assertNull( $op->getRevisionId() );
1213 }
1214
1215 public function provideRevisionId() {
1216 return [
1217 [ null, null ],
1218 [ 7, 7 ],
1219 [ -1, -1 ],
1220 [ 3.2, 3 ],
1221 [ '0', 0 ],
1222 [ '32% finished', 32 ],
1223 [ false, 0 ],
1224 ];
1225 }
1226
1227 /**
1228 * @covers OutputPage::setRevisionTimestamp
1229 * @covers OutputPage::getRevisionTimestamp
1230 */
1231 public function testRevisionTimestamp() {
1232 $op = $this->newInstance();
1233 $this->assertNull( $op->getRevisionTimestamp() );
1234
1235 $this->assertNull( $op->setRevisionTimestamp( 'abc' ) );
1236 $this->assertSame( 'abc', $op->getRevisionTimestamp() );
1237 $this->assertSame( 'abc', $op->setRevisionTimestamp( null ) );
1238 $this->assertNull( $op->getRevisionTimestamp() );
1239 }
1240
1241 /**
1242 * @covers OutputPage::setFileVersion
1243 * @covers OutputPage::getFileVersion
1244 */
1245 public function testFileVersion() {
1246 $op = $this->newInstance();
1247 $this->assertNull( $op->getFileVersion() );
1248
1249 $stubFile = $this->createMock( File::class );
1250 $stubFile->method( 'exists' )->willReturn( true );
1251 $stubFile->method( 'getTimestamp' )->willReturn( '12211221123321' );
1252 $stubFile->method( 'getSha1' )->willReturn( 'bf3ffa7047dc080f5855377a4f83cd18887e3b05' );
1253
1254 $op->setFileVersion( $stubFile );
1255
1256 $this->assertEquals(
1257 [ 'time' => '12211221123321', 'sha1' => 'bf3ffa7047dc080f5855377a4f83cd18887e3b05' ],
1258 $op->getFileVersion()
1259 );
1260
1261 $stubMissingFile = $this->createMock( File::class );
1262 $stubMissingFile->method( 'exists' )->willReturn( false );
1263
1264 $op->setFileVersion( $stubMissingFile );
1265 $this->assertNull( $op->getFileVersion() );
1266
1267 $op->setFileVersion( $stubFile );
1268 $this->assertNotNull( $op->getFileVersion() );
1269
1270 $op->setFileVersion( null );
1271 $this->assertNull( $op->getFileVersion() );
1272 }
1273
1274 private function createParserOutputStub( $method = '', $retVal = [] ) {
1275 $pOut = $this->getMock( ParserOutput::class );
1276 if ( $method !== '' ) {
1277 $pOut->method( $method )->willReturn( $retVal );
1278 }
1279
1280 $arrayReturningMethods = [
1281 'getCategories',
1282 'getFileSearchOptions',
1283 'getHeadItems',
1284 'getIndicators',
1285 'getLanguageLinks',
1286 'getOutputHooks',
1287 'getTemplateIds',
1288 ];
1289
1290 foreach ( $arrayReturningMethods as $method ) {
1291 $pOut->method( $method )->willReturn( [] );
1292 }
1293
1294 return $pOut;
1295 }
1296
1297 /**
1298 * @covers OutputPage::getTemplateIds
1299 * @covers OutputPage::addParserOutputMetadata
1300 */
1301 public function testTemplateIds() {
1302 $op = $this->newInstance();
1303 $this->assertSame( [], $op->getTemplateIds() );
1304
1305 // Test with no template id's
1306 $stubPOEmpty = $this->createParserOutputStub();
1307 $op->addParserOutputMetadata( $stubPOEmpty );
1308 $this->assertSame( [], $op->getTemplateIds() );
1309
1310 // Test with some arbitrary template id's
1311 $ids = [
1312 NS_MAIN => [ 'A' => 3, 'B' => 17 ],
1313 NS_TALK => [ 'C' => 31 ],
1314 NS_MEDIA => [ 'D' => -1 ],
1315 ];
1316
1317 $stubPO1 = $this->createParserOutputStub( 'getTemplateIds', $ids );
1318
1319 $op->addParserOutputMetadata( $stubPO1 );
1320 $this->assertSame( $ids, $op->getTemplateIds() );
1321
1322 // Test merging with a second set of id's
1323 $stubPO2 = $this->createParserOutputStub( 'getTemplateIds', [
1324 NS_MAIN => [ 'E' => 1234 ],
1325 NS_PROJECT => [ 'F' => 5678 ],
1326 ] );
1327
1328 $finalIds = [
1329 NS_MAIN => [ 'E' => 1234, 'A' => 3, 'B' => 17 ],
1330 NS_TALK => [ 'C' => 31 ],
1331 NS_MEDIA => [ 'D' => -1 ],
1332 NS_PROJECT => [ 'F' => 5678 ],
1333 ];
1334
1335 $op->addParserOutputMetadata( $stubPO2 );
1336 $this->assertSame( $finalIds, $op->getTemplateIds() );
1337
1338 // Test merging with an empty set of id's
1339 $op->addParserOutputMetadata( $stubPOEmpty );
1340 $this->assertSame( $finalIds, $op->getTemplateIds() );
1341 }
1342
1343 /**
1344 * @covers OutputPage::getFileSearchOptions
1345 * @covers OutputPage::addParserOutputMetadata
1346 */
1347 public function testFileSearchOptions() {
1348 $op = $this->newInstance();
1349 $this->assertSame( [], $op->getFileSearchOptions() );
1350
1351 // Test with no files
1352 $stubPOEmpty = $this->createParserOutputStub();
1353
1354 $op->addParserOutputMetadata( $stubPOEmpty );
1355 $this->assertSame( [], $op->getFileSearchOptions() );
1356
1357 // Test with some arbitrary files
1358 $files1 = [
1359 'A' => [ 'time' => null, 'sha1' => '' ],
1360 'B' => [
1361 'time' => '12211221123321',
1362 'sha1' => 'bf3ffa7047dc080f5855377a4f83cd18887e3b05',
1363 ],
1364 ];
1365
1366 $stubPO1 = $this->createParserOutputStub( 'getFileSearchOptions', $files1 );
1367
1368 $op->addParserOutputMetadata( $stubPO1 );
1369 $this->assertSame( $files1, $op->getFileSearchOptions() );
1370
1371 // Test merging with a second set of files
1372 $files2 = [
1373 'C' => [ 'time' => null, 'sha1' => '' ],
1374 'B' => [ 'time' => null, 'sha1' => '' ],
1375 ];
1376
1377 $stubPO2 = $this->createParserOutputStub( 'getFileSearchOptions', $files2 );
1378
1379 $op->addParserOutputMetadata( $stubPO2 );
1380 $this->assertSame( array_merge( $files1, $files2 ), $op->getFileSearchOptions() );
1381
1382 // Test merging with an empty set of files
1383 $op->addParserOutputMetadata( $stubPOEmpty );
1384 $this->assertSame( array_merge( $files1, $files2 ), $op->getFileSearchOptions() );
1385 }
1386
1387 /**
1388 * @dataProvider provideAddWikiText
1389 * @covers OutputPage::addWikiText
1390 * @covers OutputPage::addWikiTextWithTitle
1391 * @covers OutputPage::addWikiTextTitle
1392 * @covers OutputPage::addWikiTextTidy
1393 * @covers OutputPage::addWikiTextTitleTidy
1394 * @covers OutputPage::getHTML
1395 */
1396 public function testAddWikiText( $method, array $args, $expected ) {
1397 $op = $this->newInstance();
1398 $this->assertSame( '', $op->getHTML() );
1399
1400 if ( in_array(
1401 $method,
1402 [ 'addWikiTextWithTitle', 'addWikiTextTitleTidy', 'addWikiTextTitle' ]
1403 ) && count( $args ) >= 2 && $args[1] === null ) {
1404 // Special placeholder because we can't get the actual title in the provider
1405 $args[1] = $op->getTitle();
1406 }
1407
1408 $op->$method( ...$args );
1409 $this->assertSame( $expected, $op->getHTML() );
1410 }
1411
1412 public function provideAddWikiText() {
1413 $tests = [
1414 'addWikiText' => [
1415 'Simple wikitext' => [
1416 [ "'''Bold'''" ],
1417 "<p><b>Bold</b>\n</p>",
1418 ], 'List at start' => [
1419 [ '* List' ],
1420 "<ul><li>List</li></ul>\n",
1421 ], 'List not at start' => [
1422 [ '* Not a list', false ],
1423 '* Not a list',
1424 ], 'Non-interface' => [
1425 [ "'''Bold'''", true, false ],
1426 "<p><b>Bold</b>\n</p>",
1427 ], 'No section edit links' => [
1428 [ '== Title ==' ],
1429 "<h2><span class=\"mw-headline\" id=\"Title\">Title</span></h2>\n",
1430 ],
1431 ],
1432 'addWikiTextWithTitle' => [
1433 'With title at start' => [
1434 [ '* {{PAGENAME}}', Title::newFromText( 'Talk:Some page' ) ],
1435 "<ul><li>Some page</li></ul>\n",
1436 ], 'With title at start' => [
1437 [ '* {{PAGENAME}}', Title::newFromText( 'Talk:Some page' ), false ],
1438 "* Some page",
1439 ],
1440 ],
1441 'addWikiTextTidy' => [
1442 'SpecialNewimages' => [
1443 [ "<p lang='en' dir='ltr'>\nMy message" ],
1444 '<p lang="en" dir="ltr">' . "\nMy message\n</p>"
1445 ], 'List at start' => [
1446 [ '* List' ],
1447 "<ul><li>List</li></ul>\n",
1448 ], 'List not at start' => [
1449 [ '* <b>Not a list', false ],
1450 '<p>* <b>Not a list</b></p>',
1451 ],
1452 ],
1453 'addWikiTextTitleTidy' => [
1454 'With title at start' => [
1455 [ '* {{PAGENAME}}', Title::newFromText( 'Talk:Some page' ) ],
1456 "<ul><li>Some page</li></ul>\n",
1457 ], 'With title at start' => [
1458 [ '* {{PAGENAME}}', Title::newFromText( 'Talk:Some page' ), false ],
1459 "<p>* Some page</p>",
1460 ], 'EditPage' => [
1461 [ "<div class='mw-editintro'>{{PAGENAME}}", Title::newFromText( 'Talk:Some page' ) ],
1462 '<div class="mw-editintro">' . "Some page\n</div>"
1463 ],
1464 ],
1465 ];
1466
1467 // Test all the others on addWikiTextTitle as well
1468 foreach ( $tests['addWikiText'] as $key => $val ) {
1469 $args = [ $val[0][0], null, $val[0][1] ?? true, false, $val[0][2] ?? true ];
1470 $tests['addWikiTextTitle']["$key (addWikiTextTitle)"] =
1471 array_merge( [ $args ], array_slice( $val, 1 ) );
1472 }
1473 foreach ( $tests['addWikiTextWithTitle'] as $key => $val ) {
1474 $args = [ $val[0][0], $val[0][1], $val[0][2] ?? true ];
1475 $tests['addWikiTextTitle']["$key (addWikiTextTitle)"] =
1476 array_merge( [ $args ], array_slice( $val, 1 ) );
1477 }
1478 foreach ( $tests['addWikiTextTidy'] as $key => $val ) {
1479 $args = [ $val[0][0], null, $val[0][1] ?? true, true, false ];
1480 $tests['addWikiTextTitle']["$key (addWikiTextTitle)"] =
1481 array_merge( [ $args ], array_slice( $val, 1 ) );
1482 }
1483 foreach ( $tests['addWikiTextTitleTidy'] as $key => $val ) {
1484 $args = [ $val[0][0], $val[0][1], $val[0][2] ?? true, true, false ];
1485 $tests['addWikiTextTitle']["$key (addWikiTextTitle)"] =
1486 array_merge( [ $args ], array_slice( $val, 1 ) );
1487 }
1488
1489 // We have to reformat our array to match what PHPUnit wants
1490 $ret = [];
1491 foreach ( $tests as $key => $subarray ) {
1492 foreach ( $subarray as $subkey => $val ) {
1493 $val = array_merge( [ $key ], $val );
1494 $ret[$subkey] = $val;
1495 }
1496 }
1497
1498 return $ret;
1499 }
1500
1501 /**
1502 * @covers OutputPage::addWikiText
1503 */
1504 public function testAddWikiTextNoTitle() {
1505 $this->setExpectedException( MWException::class, 'Title is null' );
1506
1507 $op = $this->newInstance( [], null, 'notitle' );
1508 $op->addWikiText( 'a' );
1509 }
1510
1511 /**
1512 * @covers OutputPage::addParserOutputMetadata
1513 */
1514 public function testNoGallery() {
1515 $op = $this->newInstance();
1516 $this->assertFalse( $op->mNoGallery );
1517
1518 $stubPO1 = $this->createParserOutputStub( 'getNoGallery', true );
1519 $op->addParserOutputMetadata( $stubPO1 );
1520 $this->assertTrue( $op->mNoGallery );
1521
1522 $stubPO2 = $this->createParserOutputStub( 'getNoGallery', false );
1523 $op->addParserOutputMetadata( $stubPO2 );
1524 $this->assertFalse( $op->mNoGallery );
1525 }
1526
1527 // @todo Make sure to test the following in addParserOutputMetadata() as well when we add tests
1528 // for them:
1529 // * enableClientCache()
1530 // * addModules()
1531 // * addModuleScripts()
1532 // * addModuleStyles()
1533 // * addJsConfigVars()
1534 // * preventClickJacking()
1535 // Otherwise those lines of addParserOutputMetadata() will be reported as covered, but we won't
1536 // be testing they actually work.
1537
1538 /**
1539 * @covers OutputPage::haveCacheVaryCookies
1540 */
1541 public function testHaveCacheVaryCookies() {
1542 $request = new FauxRequest();
1543 $context = new RequestContext();
1544 $context->setRequest( $request );
1545 $op = new OutputPage( $context );
1546
1547 // No cookies are set.
1548 $this->assertFalse( $op->haveCacheVaryCookies() );
1549
1550 // 'Token' is present but empty, so it shouldn't count.
1551 $request->setCookie( 'Token', '' );
1552 $this->assertFalse( $op->haveCacheVaryCookies() );
1553
1554 // 'Token' present and nonempty.
1555 $request->setCookie( 'Token', '123' );
1556 $this->assertTrue( $op->haveCacheVaryCookies() );
1557 }
1558
1559 /**
1560 * @dataProvider provideVaryHeaders
1561 *
1562 * @covers OutputPage::addVaryHeader
1563 * @covers OutputPage::getVaryHeader
1564 * @covers OutputPage::getKeyHeader
1565 */
1566 public function testVaryHeaders( $calls, $vary, $key ) {
1567 // get rid of default Vary fields
1568 $op = $this->getMockBuilder( OutputPage::class )
1569 ->setConstructorArgs( [ new RequestContext() ] )
1570 ->setMethods( [ 'getCacheVaryCookies' ] )
1571 ->getMock();
1572 $op->expects( $this->any() )
1573 ->method( 'getCacheVaryCookies' )
1574 ->will( $this->returnValue( [] ) );
1575 TestingAccessWrapper::newFromObject( $op )->mVaryHeader = [];
1576
1577 foreach ( $calls as $call ) {
1578 call_user_func_array( [ $op, 'addVaryHeader' ], $call );
1579 }
1580 $this->assertEquals( $vary, $op->getVaryHeader(), 'Vary:' );
1581 $this->assertEquals( $key, $op->getKeyHeader(), 'Key:' );
1582 }
1583
1584 public function provideVaryHeaders() {
1585 // note: getKeyHeader() automatically adds Vary: Cookie
1586 return [
1587 [ // single header
1588 [
1589 [ 'Cookie' ],
1590 ],
1591 'Vary: Cookie',
1592 'Key: Cookie',
1593 ],
1594 [ // non-unique headers
1595 [
1596 [ 'Cookie' ],
1597 [ 'Accept-Language' ],
1598 [ 'Cookie' ],
1599 ],
1600 'Vary: Cookie, Accept-Language',
1601 'Key: Cookie,Accept-Language',
1602 ],
1603 [ // two headers with single options
1604 [
1605 [ 'Cookie', [ 'param=phpsessid' ] ],
1606 [ 'Accept-Language', [ 'substr=en' ] ],
1607 ],
1608 'Vary: Cookie, Accept-Language',
1609 'Key: Cookie;param=phpsessid,Accept-Language;substr=en',
1610 ],
1611 [ // one header with multiple options
1612 [
1613 [ 'Cookie', [ 'param=phpsessid', 'param=userId' ] ],
1614 ],
1615 'Vary: Cookie',
1616 'Key: Cookie;param=phpsessid;param=userId',
1617 ],
1618 [ // Duplicate option
1619 [
1620 [ 'Cookie', [ 'param=phpsessid' ] ],
1621 [ 'Cookie', [ 'param=phpsessid' ] ],
1622 [ 'Accept-Language', [ 'substr=en', 'substr=en' ] ],
1623 ],
1624 'Vary: Cookie, Accept-Language',
1625 'Key: Cookie;param=phpsessid,Accept-Language;substr=en',
1626 ],
1627 [ // Same header, different options
1628 [
1629 [ 'Cookie', [ 'param=phpsessid' ] ],
1630 [ 'Cookie', [ 'param=userId' ] ],
1631 ],
1632 'Vary: Cookie',
1633 'Key: Cookie;param=phpsessid;param=userId',
1634 ],
1635 ];
1636 }
1637
1638 /**
1639 * @dataProvider provideLinkHeaders
1640 *
1641 * @covers OutputPage::addLinkHeader
1642 * @covers OutputPage::getLinkHeader
1643 */
1644 public function testLinkHeaders( $headers, $result ) {
1645 $op = $this->newInstance();
1646
1647 foreach ( $headers as $header ) {
1648 $op->addLinkHeader( $header );
1649 }
1650
1651 $this->assertEquals( $result, $op->getLinkHeader() );
1652 }
1653
1654 public function provideLinkHeaders() {
1655 return [
1656 [
1657 [],
1658 false
1659 ],
1660 [
1661 [ '<https://foo/bar.jpg>;rel=preload;as=image' ],
1662 'Link: <https://foo/bar.jpg>;rel=preload;as=image',
1663 ],
1664 [
1665 [ '<https://foo/bar.jpg>;rel=preload;as=image','<https://foo/baz.jpg>;rel=preload;as=image' ],
1666 'Link: <https://foo/bar.jpg>;rel=preload;as=image,<https://foo/baz.jpg>;rel=preload;as=image',
1667 ],
1668 ];
1669 }
1670
1671 /**
1672 * See ResourceLoaderClientHtmlTest for full coverage.
1673 *
1674 * @dataProvider provideMakeResourceLoaderLink
1675 *
1676 * @covers OutputPage::makeResourceLoaderLink
1677 */
1678 public function testMakeResourceLoaderLink( $args, $expectedHtml ) {
1679 $this->setMwGlobals( [
1680 'wgResourceLoaderDebug' => false,
1681 'wgLoadScript' => 'http://127.0.0.1:8080/w/load.php',
1682 'wgCSPReportOnlyHeader' => true,
1683 ] );
1684 $class = new ReflectionClass( OutputPage::class );
1685 $method = $class->getMethod( 'makeResourceLoaderLink' );
1686 $method->setAccessible( true );
1687 $ctx = new RequestContext();
1688 $ctx->setSkin( SkinFactory::getDefaultInstance()->makeSkin( 'fallback' ) );
1689 $ctx->setLanguage( 'en' );
1690 $out = new OutputPage( $ctx );
1691 $nonce = $class->getProperty( 'CSPNonce' );
1692 $nonce->setAccessible( true );
1693 $nonce->setValue( $out, 'secret' );
1694 $rl = $out->getResourceLoader();
1695 $rl->setMessageBlobStore( new NullMessageBlobStore() );
1696 $rl->register( [
1697 'test.foo' => new ResourceLoaderTestModule( [
1698 'script' => 'mw.test.foo( { a: true } );',
1699 'styles' => '.mw-test-foo { content: "style"; }',
1700 ] ),
1701 'test.bar' => new ResourceLoaderTestModule( [
1702 'script' => 'mw.test.bar( { a: true } );',
1703 'styles' => '.mw-test-bar { content: "style"; }',
1704 ] ),
1705 'test.baz' => new ResourceLoaderTestModule( [
1706 'script' => 'mw.test.baz( { a: true } );',
1707 'styles' => '.mw-test-baz { content: "style"; }',
1708 ] ),
1709 'test.quux' => new ResourceLoaderTestModule( [
1710 'script' => 'mw.test.baz( { token: 123 } );',
1711 'styles' => '/* pref-animate=off */ .mw-icon { transition: none; }',
1712 'group' => 'private',
1713 ] ),
1714 'test.noscript' => new ResourceLoaderTestModule( [
1715 'styles' => '.stuff { color: red; }',
1716 'group' => 'noscript',
1717 ] ),
1718 'test.group.foo' => new ResourceLoaderTestModule( [
1719 'script' => 'mw.doStuff( "foo" );',
1720 'group' => 'foo',
1721 ] ),
1722 'test.group.bar' => new ResourceLoaderTestModule( [
1723 'script' => 'mw.doStuff( "bar" );',
1724 'group' => 'bar',
1725 ] ),
1726 ] );
1727 $links = $method->invokeArgs( $out, $args );
1728 $actualHtml = strval( $links );
1729 $this->assertEquals( $expectedHtml, $actualHtml );
1730 }
1731
1732 public static function provideMakeResourceLoaderLink() {
1733 // phpcs:disable Generic.Files.LineLength
1734 return [
1735 // Single only=scripts load
1736 [
1737 [ 'test.foo', ResourceLoaderModule::TYPE_SCRIPTS ],
1738 "<script nonce=\"secret\">(window.RLQ=window.RLQ||[]).push(function(){"
1739 . 'mw.loader.load("http://127.0.0.1:8080/w/load.php?debug=false\u0026lang=en\u0026modules=test.foo\u0026only=scripts\u0026skin=fallback");'
1740 . "});</script>"
1741 ],
1742 // Multiple only=styles load
1743 [
1744 [ [ 'test.baz', 'test.foo', 'test.bar' ], ResourceLoaderModule::TYPE_STYLES ],
1745
1746 '<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"/>'
1747 ],
1748 // Private embed (only=scripts)
1749 [
1750 [ 'test.quux', ResourceLoaderModule::TYPE_SCRIPTS ],
1751 "<script nonce=\"secret\">(window.RLQ=window.RLQ||[]).push(function(){"
1752 . "mw.test.baz({token:123});\nmw.loader.state({\"test.quux\":\"ready\"});"
1753 . "});</script>"
1754 ],
1755 // Load private module (combined)
1756 [
1757 [ 'test.quux', ResourceLoaderModule::TYPE_COMBINED ],
1758 "<script nonce=\"secret\">(window.RLQ=window.RLQ||[]).push(function(){"
1759 . "mw.loader.implement(\"test.quux@1ev0ijv\",function($,jQuery,require,module){"
1760 . "mw.test.baz({token:123});},{\"css\":[\".mw-icon{transition:none}"
1761 . "\"]});});</script>"
1762 ],
1763 // Load no modules
1764 [
1765 [ [], ResourceLoaderModule::TYPE_COMBINED ],
1766 '',
1767 ],
1768 // noscript group
1769 [
1770 [ 'test.noscript', ResourceLoaderModule::TYPE_STYLES ],
1771 '<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>'
1772 ],
1773 // Load two modules in separate groups
1774 [
1775 [ [ 'test.group.foo', 'test.group.bar' ], ResourceLoaderModule::TYPE_COMBINED ],
1776 "<script nonce=\"secret\">(window.RLQ=window.RLQ||[]).push(function(){"
1777 . 'mw.loader.load("http://127.0.0.1:8080/w/load.php?debug=false\u0026lang=en\u0026modules=test.group.bar\u0026skin=fallback");'
1778 . 'mw.loader.load("http://127.0.0.1:8080/w/load.php?debug=false\u0026lang=en\u0026modules=test.group.foo\u0026skin=fallback");'
1779 . "});</script>"
1780 ],
1781 ];
1782 // phpcs:enable
1783 }
1784
1785 /**
1786 * @dataProvider provideBuildExemptModules
1787 *
1788 * @covers OutputPage::buildExemptModules
1789 */
1790 public function testBuildExemptModules( array $exemptStyleModules, $expect ) {
1791 $this->setMwGlobals( [
1792 'wgResourceLoaderDebug' => false,
1793 'wgLoadScript' => '/w/load.php',
1794 // Stub wgCacheEpoch as it influences getVersionHash used for the
1795 // urls in the expected HTML
1796 'wgCacheEpoch' => '20140101000000',
1797 ] );
1798
1799 // Set up stubs
1800 $ctx = new RequestContext();
1801 $ctx->setSkin( SkinFactory::getDefaultInstance()->makeSkin( 'fallback' ) );
1802 $ctx->setLanguage( 'en' );
1803 $op = $this->getMockBuilder( OutputPage::class )
1804 ->setConstructorArgs( [ $ctx ] )
1805 ->setMethods( [ 'buildCssLinksArray' ] )
1806 ->getMock();
1807 $op->expects( $this->any() )
1808 ->method( 'buildCssLinksArray' )
1809 ->willReturn( [] );
1810 $rl = $op->getResourceLoader();
1811 $rl->setMessageBlobStore( new NullMessageBlobStore() );
1812
1813 // Register custom modules
1814 $rl->register( [
1815 'example.site.a' => new ResourceLoaderTestModule( [ 'group' => 'site' ] ),
1816 'example.site.b' => new ResourceLoaderTestModule( [ 'group' => 'site' ] ),
1817 'example.user' => new ResourceLoaderTestModule( [ 'group' => 'user' ] ),
1818 ] );
1819
1820 $op = TestingAccessWrapper::newFromObject( $op );
1821 $op->rlExemptStyleModules = $exemptStyleModules;
1822 $this->assertEquals(
1823 $expect,
1824 strval( $op->buildExemptModules() )
1825 );
1826 }
1827
1828 public static function provideBuildExemptModules() {
1829 // phpcs:disable Generic.Files.LineLength
1830 return [
1831 'empty' => [
1832 'exemptStyleModules' => [],
1833 '<meta name="ResourceLoaderDynamicStyles" content=""/>',
1834 ],
1835 'empty sets' => [
1836 'exemptStyleModules' => [ 'site' => [], 'noscript' => [], 'private' => [], 'user' => [] ],
1837 '<meta name="ResourceLoaderDynamicStyles" content=""/>',
1838 ],
1839 'default logged-out' => [
1840 'exemptStyleModules' => [ 'site' => [ 'site.styles' ] ],
1841 '<meta name="ResourceLoaderDynamicStyles" content=""/>' . "\n" .
1842 '<link rel="stylesheet" href="/w/load.php?debug=false&amp;lang=en&amp;modules=site.styles&amp;only=styles&amp;skin=fallback"/>',
1843 ],
1844 'default logged-in' => [
1845 'exemptStyleModules' => [ 'site' => [ 'site.styles' ], 'user' => [ 'user.styles' ] ],
1846 '<meta name="ResourceLoaderDynamicStyles" content=""/>' . "\n" .
1847 '<link rel="stylesheet" href="/w/load.php?debug=false&amp;lang=en&amp;modules=site.styles&amp;only=styles&amp;skin=fallback"/>' . "\n" .
1848 '<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"/>',
1849 ],
1850 'custom modules' => [
1851 'exemptStyleModules' => [
1852 'site' => [ 'site.styles', 'example.site.a', 'example.site.b' ],
1853 'user' => [ 'user.styles', 'example.user' ],
1854 ],
1855 '<meta name="ResourceLoaderDynamicStyles" content=""/>' . "\n" .
1856 '<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" .
1857 '<link rel="stylesheet" href="/w/load.php?debug=false&amp;lang=en&amp;modules=site.styles&amp;only=styles&amp;skin=fallback"/>' . "\n" .
1858 '<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" .
1859 '<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"/>',
1860 ],
1861 ];
1862 // phpcs:enable
1863 }
1864
1865 /**
1866 * @dataProvider provideTransformFilePath
1867 * @covers OutputPage::transformFilePath
1868 * @covers OutputPage::transformResourcePath
1869 */
1870 public function testTransformResourcePath( $baseDir, $basePath, $uploadDir = null,
1871 $uploadPath = null, $path = null, $expected = null
1872 ) {
1873 if ( $path === null ) {
1874 // Skip optional $uploadDir and $uploadPath
1875 $path = $uploadDir;
1876 $expected = $uploadPath;
1877 $uploadDir = "$baseDir/images";
1878 $uploadPath = "$basePath/images";
1879 }
1880 $this->setMwGlobals( 'IP', $baseDir );
1881 $conf = new HashConfig( [
1882 'ResourceBasePath' => $basePath,
1883 'UploadDirectory' => $uploadDir,
1884 'UploadPath' => $uploadPath,
1885 ] );
1886
1887 // Some of these paths don't exist and will cause warnings
1888 Wikimedia\suppressWarnings();
1889 $actual = OutputPage::transformResourcePath( $conf, $path );
1890 Wikimedia\restoreWarnings();
1891
1892 $this->assertEquals( $expected ?: $path, $actual );
1893 }
1894
1895 public static function provideTransformFilePath() {
1896 $baseDir = dirname( __DIR__ ) . '/data/media';
1897 return [
1898 // File that matches basePath, and exists. Hash found and appended.
1899 [
1900 'baseDir' => $baseDir, 'basePath' => '/w',
1901 '/w/test.jpg',
1902 '/w/test.jpg?edcf2'
1903 ],
1904 // File that matches basePath, but not found on disk. Empty query.
1905 [
1906 'baseDir' => $baseDir, 'basePath' => '/w',
1907 '/w/unknown.png',
1908 '/w/unknown.png?'
1909 ],
1910 // File not matching basePath. Ignored.
1911 [
1912 'baseDir' => $baseDir, 'basePath' => '/w',
1913 '/files/test.jpg'
1914 ],
1915 // Empty string. Ignored.
1916 [
1917 'baseDir' => $baseDir, 'basePath' => '/w',
1918 '',
1919 ''
1920 ],
1921 // Similar path, but with domain component. Ignored.
1922 [
1923 'baseDir' => $baseDir, 'basePath' => '/w',
1924 '//example.org/w/test.jpg'
1925 ],
1926 [
1927 'baseDir' => $baseDir, 'basePath' => '/w',
1928 'https://example.org/w/test.jpg'
1929 ],
1930 // Unrelated path with domain component. Ignored.
1931 [
1932 'baseDir' => $baseDir, 'basePath' => '/w',
1933 'https://example.org/files/test.jpg'
1934 ],
1935 [
1936 'baseDir' => $baseDir, 'basePath' => '/w',
1937 '//example.org/files/test.jpg'
1938 ],
1939 // Unrelated path with domain, and empty base path (root mw install). Ignored.
1940 [
1941 'baseDir' => $baseDir, 'basePath' => '',
1942 'https://example.org/files/test.jpg'
1943 ],
1944 [
1945 'baseDir' => $baseDir, 'basePath' => '',
1946 // T155310
1947 '//example.org/files/test.jpg'
1948 ],
1949 // Check UploadPath before ResourceBasePath (T155146)
1950 [
1951 'baseDir' => dirname( $baseDir ), 'basePath' => '',
1952 'uploadDir' => $baseDir, 'uploadPath' => '/images',
1953 '/images/test.jpg',
1954 '/images/test.jpg?edcf2'
1955 ],
1956 ];
1957 }
1958
1959 /**
1960 * Tests a particular case of transformCssMedia, using the given input, globals,
1961 * expected return, and message
1962 *
1963 * Asserts that $expectedReturn is returned.
1964 *
1965 * options['printableQuery'] - value of query string for printable, or omitted for none
1966 * options['handheldQuery'] - value of query string for handheld, or omitted for none
1967 * options['media'] - passed into the method under the same name
1968 * options['expectedReturn'] - expected return value
1969 * options['message'] - PHPUnit message for assertion
1970 *
1971 * @param array $args Key-value array of arguments as shown above
1972 */
1973 protected function assertTransformCssMediaCase( $args ) {
1974 $queryData = [];
1975 if ( isset( $args['printableQuery'] ) ) {
1976 $queryData['printable'] = $args['printableQuery'];
1977 }
1978
1979 if ( isset( $args['handheldQuery'] ) ) {
1980 $queryData['handheld'] = $args['handheldQuery'];
1981 }
1982
1983 $fauxRequest = new FauxRequest( $queryData, false );
1984 $this->setMwGlobals( [
1985 'wgRequest' => $fauxRequest,
1986 ] );
1987
1988 $actualReturn = OutputPage::transformCssMedia( $args['media'] );
1989 $this->assertSame( $args['expectedReturn'], $actualReturn, $args['message'] );
1990 }
1991
1992 /**
1993 * Tests print requests
1994 *
1995 * @covers OutputPage::transformCssMedia
1996 */
1997 public function testPrintRequests() {
1998 $this->assertTransformCssMediaCase( [
1999 'printableQuery' => '1',
2000 'media' => 'screen',
2001 'expectedReturn' => null,
2002 'message' => 'On printable request, screen returns null'
2003 ] );
2004
2005 $this->assertTransformCssMediaCase( [
2006 'printableQuery' => '1',
2007 'media' => self::SCREEN_MEDIA_QUERY,
2008 'expectedReturn' => null,
2009 'message' => 'On printable request, screen media query returns null'
2010 ] );
2011
2012 $this->assertTransformCssMediaCase( [
2013 'printableQuery' => '1',
2014 'media' => self::SCREEN_ONLY_MEDIA_QUERY,
2015 'expectedReturn' => null,
2016 'message' => 'On printable request, screen media query with only returns null'
2017 ] );
2018
2019 $this->assertTransformCssMediaCase( [
2020 'printableQuery' => '1',
2021 'media' => 'print',
2022 'expectedReturn' => '',
2023 'message' => 'On printable request, media print returns empty string'
2024 ] );
2025 }
2026
2027 /**
2028 * Tests screen requests, without either query parameter set
2029 *
2030 * @covers OutputPage::transformCssMedia
2031 */
2032 public function testScreenRequests() {
2033 $this->assertTransformCssMediaCase( [
2034 'media' => 'screen',
2035 'expectedReturn' => 'screen',
2036 'message' => 'On screen request, screen media type is preserved'
2037 ] );
2038
2039 $this->assertTransformCssMediaCase( [
2040 'media' => 'handheld',
2041 'expectedReturn' => 'handheld',
2042 'message' => 'On screen request, handheld media type is preserved'
2043 ] );
2044
2045 $this->assertTransformCssMediaCase( [
2046 'media' => self::SCREEN_MEDIA_QUERY,
2047 'expectedReturn' => self::SCREEN_MEDIA_QUERY,
2048 'message' => 'On screen request, screen media query is preserved.'
2049 ] );
2050
2051 $this->assertTransformCssMediaCase( [
2052 'media' => self::SCREEN_ONLY_MEDIA_QUERY,
2053 'expectedReturn' => self::SCREEN_ONLY_MEDIA_QUERY,
2054 'message' => 'On screen request, screen media query with only is preserved.'
2055 ] );
2056
2057 $this->assertTransformCssMediaCase( [
2058 'media' => 'print',
2059 'expectedReturn' => 'print',
2060 'message' => 'On screen request, print media type is preserved'
2061 ] );
2062 }
2063
2064 /**
2065 * Tests handheld behavior
2066 *
2067 * @covers OutputPage::transformCssMedia
2068 */
2069 public function testHandheld() {
2070 $this->assertTransformCssMediaCase( [
2071 'handheldQuery' => '1',
2072 'media' => 'handheld',
2073 'expectedReturn' => '',
2074 'message' => 'On request with handheld querystring and media is handheld, returns empty string'
2075 ] );
2076
2077 $this->assertTransformCssMediaCase( [
2078 'handheldQuery' => '1',
2079 'media' => 'screen',
2080 'expectedReturn' => null,
2081 'message' => 'On request with handheld querystring and media is screen, returns null'
2082 ] );
2083 }
2084
2085 /**
2086 * @return OutputPage
2087 */
2088 private function newInstance( $config = [], WebRequest $request = null, $options = [] ) {
2089 $context = new RequestContext();
2090
2091 $context->setConfig( new MultiConfig( [
2092 new HashConfig( $config + [
2093 'AppleTouchIcon' => false,
2094 'DisableLangConversion' => true,
2095 'EnableCanonicalServerLink' => false,
2096 'Favicon' => false,
2097 'Feed' => false,
2098 'LanguageCode' => false,
2099 'ReferrerPolicy' => false,
2100 'RightsPage' => false,
2101 'RightsUrl' => false,
2102 'UniversalEditButton' => false,
2103 ] ),
2104 $context->getConfig()
2105 ] ) );
2106
2107 if ( !in_array( 'notitle', (array)$options ) ) {
2108 $context->setTitle( Title::newFromText( 'My test page' ) );
2109 }
2110
2111 if ( $request ) {
2112 $context->setRequest( $request );
2113 }
2114
2115 return new OutputPage( $context );
2116 }
2117 }
2118
2119 /**
2120 * MessageBlobStore that doesn't do anything
2121 */
2122 class NullMessageBlobStore extends MessageBlobStore {
2123 public function get( ResourceLoader $resourceLoader, $modules, $lang ) {
2124 return [];
2125 }
2126
2127 public function updateModule( $name, ResourceLoaderModule $module, $lang ) {
2128 }
2129
2130 public function updateMessage( $key ) {
2131 }
2132
2133 public function clear() {
2134 }
2135 }