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