Hard deprecate unused OutputPage::addWikiText* methods
[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', 'getTitle' ] )
1024 ->getMock();
1025
1026 $title = Title::newFromText( 'My test page' );
1027 $op->expects( $this->any() )
1028 ->method( 'getTitle' )
1029 ->will( $this->returnValue( $title ) );
1030
1031 $op->expects( $this->any() )
1032 ->method( 'addCategoryLinksToLBAndGetResult' )
1033 ->will( $this->returnCallback( function ( array $categories ) use ( $fakeResults ) {
1034 $return = [];
1035 foreach ( $categories as $category => $unused ) {
1036 if ( isset( $fakeResults[$category] ) ) {
1037 $return[] = $fakeResults[$category];
1038 }
1039 }
1040 return new FakeResultWrapper( $return );
1041 } ) );
1042
1043 if ( $variantLinkCallback ) {
1044 $mockContLang = $this->getMockBuilder( Language::class )
1045 ->setConstructorArgs( [ 'en' ] )
1046 ->setMethods( [ 'findVariantLink' ] )
1047 ->getMock();
1048 $mockContLang->expects( $this->any() )
1049 ->method( 'findVariantLink' )
1050 ->will( $this->returnCallback( $variantLinkCallback ) );
1051 $this->setContentLang( $mockContLang );
1052 }
1053
1054 $this->assertSame( [], $op->getCategories() );
1055
1056 return $op;
1057 }
1058
1059 private function doCategoryAsserts( $op, $expectedNormal, $expectedHidden ) {
1060 $this->assertSame( array_merge( $expectedHidden, $expectedNormal ), $op->getCategories() );
1061 $this->assertSame( $expectedNormal, $op->getCategories( 'normal' ) );
1062 $this->assertSame( $expectedHidden, $op->getCategories( 'hidden' ) );
1063 }
1064
1065 private function doCategoryLinkAsserts( $op, $expectedNormal, $expectedHidden ) {
1066 $catLinks = $op->getCategoryLinks();
1067 $this->assertSame( (bool)$expectedNormal + (bool)$expectedHidden, count( $catLinks ) );
1068 if ( $expectedNormal ) {
1069 $this->assertSame( count( $expectedNormal ), count( $catLinks['normal'] ) );
1070 }
1071 if ( $expectedHidden ) {
1072 $this->assertSame( count( $expectedHidden ), count( $catLinks['hidden'] ) );
1073 }
1074
1075 foreach ( $expectedNormal as $i => $name ) {
1076 $this->assertContains( $name, $catLinks['normal'][$i] );
1077 }
1078 foreach ( $expectedHidden as $i => $name ) {
1079 $this->assertContains( $name, $catLinks['hidden'][$i] );
1080 }
1081 }
1082
1083 public function provideGetCategories() {
1084 return [
1085 'No categories' => [ [], [], null, [], [] ],
1086 'Simple test' => [
1087 [ 'Test1' => 'Some sortkey', 'Test2' => 'A different sortkey' ],
1088 [ 'Test1' => (object)[ 'pp_value' => 1, 'page_title' => 'Test1' ],
1089 'Test2' => (object)[ 'page_title' => 'Test2' ] ],
1090 null,
1091 [ 'Test2' ],
1092 [ 'Test1' ],
1093 ],
1094 'Invalid title' => [
1095 [ '[' => '[', 'Test' => 'Test' ],
1096 [ 'Test' => (object)[ 'page_title' => 'Test' ] ],
1097 null,
1098 [ 'Test' ],
1099 [],
1100 ],
1101 'Variant link' => [
1102 [ 'Test' => 'Test', 'Estay' => 'Estay' ],
1103 [ 'Test' => (object)[ 'page_title' => 'Test' ] ],
1104 function ( &$link, &$title ) {
1105 if ( $link === 'Estay' ) {
1106 $link = 'Test';
1107 $title = Title::makeTitleSafe( NS_CATEGORY, $link );
1108 }
1109 },
1110 // For adding one by one, the variant gets added as well as the original category,
1111 // but if you add them all together the second time gets skipped.
1112 [ 'onebyone' => [ 'Test', 'Test' ], 'default' => [ 'Test' ] ],
1113 [],
1114 ],
1115 ];
1116 }
1117
1118 /**
1119 * @covers OutputPage::getCategories
1120 */
1121 public function testGetCategoriesInvalid() {
1122 $this->setExpectedException( InvalidArgumentException::class,
1123 'Invalid category type given: hiddne' );
1124
1125 $op = $this->newInstance();
1126 $op->getCategories( 'hiddne' );
1127 }
1128
1129 // @todo Should we test addCategoryLinksToLBAndGetResult? If so, how? Insert some test rows in
1130 // the DB?
1131
1132 /**
1133 * @covers OutputPage::setIndicators
1134 * @covers OutputPage::getIndicators
1135 * @covers OutputPage::addParserOutputMetadata
1136 */
1137 public function testIndicators() {
1138 $op = $this->newInstance();
1139 $this->assertSame( [], $op->getIndicators() );
1140
1141 $op->setIndicators( [] );
1142 $this->assertSame( [], $op->getIndicators() );
1143
1144 // Test sorting alphabetically
1145 $op->setIndicators( [ 'b' => 'x', 'a' => 'y' ] );
1146 $this->assertSame( [ 'a' => 'y', 'b' => 'x' ], $op->getIndicators() );
1147
1148 // Test overwriting existing keys
1149 $op->setIndicators( [ 'c' => 'z', 'a' => 'w' ] );
1150 $this->assertSame( [ 'a' => 'w', 'b' => 'x', 'c' => 'z' ], $op->getIndicators() );
1151
1152 // Test with ParserOutput
1153 $stubPO = $this->createParserOutputStub( 'getIndicators', [ 'c' => 'u', 'd' => 'v' ] );
1154 $op->addParserOutputMetadata( $stubPO );
1155 $this->assertSame( [ 'a' => 'w', 'b' => 'x', 'c' => 'u', 'd' => 'v' ],
1156 $op->getIndicators() );
1157 }
1158
1159 /**
1160 * @covers OutputPage::addHelpLink
1161 * @covers OutputPage::getIndicators
1162 */
1163 public function testAddHelpLink() {
1164 $op = $this->newInstance();
1165
1166 $op->addHelpLink( 'Manual:PHP unit testing' );
1167 $indicators = $op->getIndicators();
1168 $this->assertSame( [ 'mw-helplink' ], array_keys( $indicators ) );
1169 $this->assertContains( 'Manual:PHP_unit_testing', $indicators['mw-helplink'] );
1170
1171 $op->addHelpLink( 'https://phpunit.de', true );
1172 $indicators = $op->getIndicators();
1173 $this->assertSame( [ 'mw-helplink' ], array_keys( $indicators ) );
1174 $this->assertContains( 'https://phpunit.de', $indicators['mw-helplink'] );
1175 $this->assertNotContains( 'mediawiki', $indicators['mw-helplink'] );
1176 $this->assertNotContains( 'Manual:PHP', $indicators['mw-helplink'] );
1177 }
1178
1179 /**
1180 * @covers OutputPage::prependHTML
1181 * @covers OutputPage::addHTML
1182 * @covers OutputPage::addElement
1183 * @covers OutputPage::clearHTML
1184 * @covers OutputPage::getHTML
1185 */
1186 public function testBodyHTML() {
1187 $op = $this->newInstance();
1188 $this->assertSame( '', $op->getHTML() );
1189
1190 $op->addHTML( 'a' );
1191 $this->assertSame( 'a', $op->getHTML() );
1192
1193 $op->addHTML( 'b' );
1194 $this->assertSame( 'ab', $op->getHTML() );
1195
1196 $op->prependHTML( 'c' );
1197 $this->assertSame( 'cab', $op->getHTML() );
1198
1199 $op->addElement( 'p', [ 'id' => 'foo' ], 'd' );
1200 $this->assertSame( 'cab<p id="foo">d</p>', $op->getHTML() );
1201
1202 $op->clearHTML();
1203 $this->assertSame( '', $op->getHTML() );
1204 }
1205
1206 /**
1207 * @dataProvider provideRevisionId
1208 * @covers OutputPage::setRevisionId
1209 * @covers OutputPage::getRevisionId
1210 */
1211 public function testRevisionId( $newVal, $expected ) {
1212 $op = $this->newInstance();
1213
1214 $this->assertNull( $op->setRevisionId( $newVal ) );
1215 $this->assertSame( $expected, $op->getRevisionId() );
1216 $this->assertSame( $expected, $op->setRevisionId( null ) );
1217 $this->assertNull( $op->getRevisionId() );
1218 }
1219
1220 public function provideRevisionId() {
1221 return [
1222 [ null, null ],
1223 [ 7, 7 ],
1224 [ -1, -1 ],
1225 [ 3.2, 3 ],
1226 [ '0', 0 ],
1227 [ '32% finished', 32 ],
1228 [ false, 0 ],
1229 ];
1230 }
1231
1232 /**
1233 * @covers OutputPage::setRevisionTimestamp
1234 * @covers OutputPage::getRevisionTimestamp
1235 */
1236 public function testRevisionTimestamp() {
1237 $op = $this->newInstance();
1238 $this->assertNull( $op->getRevisionTimestamp() );
1239
1240 $this->assertNull( $op->setRevisionTimestamp( 'abc' ) );
1241 $this->assertSame( 'abc', $op->getRevisionTimestamp() );
1242 $this->assertSame( 'abc', $op->setRevisionTimestamp( null ) );
1243 $this->assertNull( $op->getRevisionTimestamp() );
1244 }
1245
1246 /**
1247 * @covers OutputPage::setFileVersion
1248 * @covers OutputPage::getFileVersion
1249 */
1250 public function testFileVersion() {
1251 $op = $this->newInstance();
1252 $this->assertNull( $op->getFileVersion() );
1253
1254 $stubFile = $this->createMock( File::class );
1255 $stubFile->method( 'exists' )->willReturn( true );
1256 $stubFile->method( 'getTimestamp' )->willReturn( '12211221123321' );
1257 $stubFile->method( 'getSha1' )->willReturn( 'bf3ffa7047dc080f5855377a4f83cd18887e3b05' );
1258
1259 $op->setFileVersion( $stubFile );
1260
1261 $this->assertEquals(
1262 [ 'time' => '12211221123321', 'sha1' => 'bf3ffa7047dc080f5855377a4f83cd18887e3b05' ],
1263 $op->getFileVersion()
1264 );
1265
1266 $stubMissingFile = $this->createMock( File::class );
1267 $stubMissingFile->method( 'exists' )->willReturn( false );
1268
1269 $op->setFileVersion( $stubMissingFile );
1270 $this->assertNull( $op->getFileVersion() );
1271
1272 $op->setFileVersion( $stubFile );
1273 $this->assertNotNull( $op->getFileVersion() );
1274
1275 $op->setFileVersion( null );
1276 $this->assertNull( $op->getFileVersion() );
1277 }
1278
1279 private function createParserOutputStub( $method = '', $retVal = [] ) {
1280 $pOut = $this->getMock( ParserOutput::class );
1281 if ( $method !== '' ) {
1282 $pOut->method( $method )->willReturn( $retVal );
1283 }
1284
1285 $arrayReturningMethods = [
1286 'getCategories',
1287 'getFileSearchOptions',
1288 'getHeadItems',
1289 'getIndicators',
1290 'getLanguageLinks',
1291 'getOutputHooks',
1292 'getTemplateIds',
1293 ];
1294
1295 foreach ( $arrayReturningMethods as $method ) {
1296 $pOut->method( $method )->willReturn( [] );
1297 }
1298
1299 return $pOut;
1300 }
1301
1302 /**
1303 * @covers OutputPage::getTemplateIds
1304 * @covers OutputPage::addParserOutputMetadata
1305 */
1306 public function testTemplateIds() {
1307 $op = $this->newInstance();
1308 $this->assertSame( [], $op->getTemplateIds() );
1309
1310 // Test with no template id's
1311 $stubPOEmpty = $this->createParserOutputStub();
1312 $op->addParserOutputMetadata( $stubPOEmpty );
1313 $this->assertSame( [], $op->getTemplateIds() );
1314
1315 // Test with some arbitrary template id's
1316 $ids = [
1317 NS_MAIN => [ 'A' => 3, 'B' => 17 ],
1318 NS_TALK => [ 'C' => 31 ],
1319 NS_MEDIA => [ 'D' => -1 ],
1320 ];
1321
1322 $stubPO1 = $this->createParserOutputStub( 'getTemplateIds', $ids );
1323
1324 $op->addParserOutputMetadata( $stubPO1 );
1325 $this->assertSame( $ids, $op->getTemplateIds() );
1326
1327 // Test merging with a second set of id's
1328 $stubPO2 = $this->createParserOutputStub( 'getTemplateIds', [
1329 NS_MAIN => [ 'E' => 1234 ],
1330 NS_PROJECT => [ 'F' => 5678 ],
1331 ] );
1332
1333 $finalIds = [
1334 NS_MAIN => [ 'E' => 1234, 'A' => 3, 'B' => 17 ],
1335 NS_TALK => [ 'C' => 31 ],
1336 NS_MEDIA => [ 'D' => -1 ],
1337 NS_PROJECT => [ 'F' => 5678 ],
1338 ];
1339
1340 $op->addParserOutputMetadata( $stubPO2 );
1341 $this->assertSame( $finalIds, $op->getTemplateIds() );
1342
1343 // Test merging with an empty set of id's
1344 $op->addParserOutputMetadata( $stubPOEmpty );
1345 $this->assertSame( $finalIds, $op->getTemplateIds() );
1346 }
1347
1348 /**
1349 * @covers OutputPage::getFileSearchOptions
1350 * @covers OutputPage::addParserOutputMetadata
1351 */
1352 public function testFileSearchOptions() {
1353 $op = $this->newInstance();
1354 $this->assertSame( [], $op->getFileSearchOptions() );
1355
1356 // Test with no files
1357 $stubPOEmpty = $this->createParserOutputStub();
1358
1359 $op->addParserOutputMetadata( $stubPOEmpty );
1360 $this->assertSame( [], $op->getFileSearchOptions() );
1361
1362 // Test with some arbitrary files
1363 $files1 = [
1364 'A' => [ 'time' => null, 'sha1' => '' ],
1365 'B' => [
1366 'time' => '12211221123321',
1367 'sha1' => 'bf3ffa7047dc080f5855377a4f83cd18887e3b05',
1368 ],
1369 ];
1370
1371 $stubPO1 = $this->createParserOutputStub( 'getFileSearchOptions', $files1 );
1372
1373 $op->addParserOutputMetadata( $stubPO1 );
1374 $this->assertSame( $files1, $op->getFileSearchOptions() );
1375
1376 // Test merging with a second set of files
1377 $files2 = [
1378 'C' => [ 'time' => null, 'sha1' => '' ],
1379 'B' => [ 'time' => null, 'sha1' => '' ],
1380 ];
1381
1382 $stubPO2 = $this->createParserOutputStub( 'getFileSearchOptions', $files2 );
1383
1384 $op->addParserOutputMetadata( $stubPO2 );
1385 $this->assertSame( array_merge( $files1, $files2 ), $op->getFileSearchOptions() );
1386
1387 // Test merging with an empty set of files
1388 $op->addParserOutputMetadata( $stubPOEmpty );
1389 $this->assertSame( array_merge( $files1, $files2 ), $op->getFileSearchOptions() );
1390 }
1391
1392 /**
1393 * @dataProvider provideAddWikiText
1394 * @covers OutputPage::addWikiText
1395 * @covers OutputPage::addWikiTextAsInterface
1396 * @covers OutputPage::addWikiTextAsContent
1397 * @covers OutputPage::addWikiTextWithTitle
1398 * @covers OutputPage::addWikiTextTitle
1399 * @covers OutputPage::addWikiTextTidy
1400 * @covers OutputPage::addWikiTextTitleTidy
1401 * @covers OutputPage::getHTML
1402 */
1403 public function testAddWikiText( $method, array $args, $expected ) {
1404 $op = $this->newInstance();
1405 $this->assertSame( '', $op->getHTML() );
1406
1407 $this->hideDeprecated( 'OutputPage::addWikiTextTitle' );
1408 $this->hideDeprecated( 'OutputPage::addWikiTextWithTitle' );
1409 if ( in_array(
1410 $method,
1411 [ 'addWikiTextWithTitle', 'addWikiTextTitleTidy', 'addWikiTextTitle' ]
1412 ) && count( $args ) >= 2 && $args[1] === null ) {
1413 // Special placeholder because we can't get the actual title in the provider
1414 $args[1] = $op->getTitle();
1415 }
1416 if ( in_array(
1417 $method,
1418 [ 'addWikiTextAsInterface', 'addWikiTextAsContent' ]
1419 ) && count( $args ) >= 3 && $args[2] === null ) {
1420 // Special placeholder because we can't get the actual title in the provider
1421 $args[2] = $op->getTitle();
1422 }
1423
1424 $op->$method( ...$args );
1425 $this->assertSame( $expected, $op->getHTML() );
1426 }
1427
1428 public function provideAddWikiText() {
1429 $tests = [
1430 'addWikiText' => [
1431 // Not tidied; this API is deprecated.
1432 'Simple wikitext' => [
1433 [ "'''Bold'''" ],
1434 "<p><b>Bold</b>\n</p>",
1435 ], 'List at start' => [
1436 [ '* List' ],
1437 "<ul><li>List</li></ul>\n",
1438 ], 'List not at start' => [
1439 [ '* Not a list', false ],
1440 '* Not a list',
1441 ], 'Non-interface' => [
1442 [ "'''Bold'''", true, false ],
1443 "<p><b>Bold</b>\n</p>",
1444 ], 'No section edit links' => [
1445 [ '== Title ==' ],
1446 "<h2><span class=\"mw-headline\" id=\"Title\">Title</span></h2>\n",
1447 ],
1448 ],
1449 'addWikiTextWithTitle' => [
1450 // Untidied; this API is deprecated
1451 'With title at start' => [
1452 [ '* {{PAGENAME}}', Title::newFromText( 'Talk:Some page' ) ],
1453 "<ul><li>Some page</li></ul>\n",
1454 ], 'With title at start' => [
1455 [ '* {{PAGENAME}}', Title::newFromText( 'Talk:Some page' ), false ],
1456 "* Some page",
1457 ],
1458 ],
1459 'addWikiTextAsInterface' => [
1460 // Preferred interface: output is tidied
1461 'Simple wikitext' => [
1462 [ "'''Bold'''" ],
1463 "<p><b>Bold</b>\n</p>",
1464 ], 'Untidy wikitext' => [
1465 [ "<b>Bold" ],
1466 "<p><b>Bold\n</b></p>",
1467 ], 'List at start' => [
1468 [ '* List' ],
1469 "<ul><li>List</li></ul>\n",
1470 ], 'List not at start' => [
1471 [ '* Not a list', false ],
1472 '<p>* Not a list</p>',
1473 ], 'No section edit links' => [
1474 [ '== Title ==' ],
1475 "<h2><span class=\"mw-headline\" id=\"Title\">Title</span></h2>\n",
1476 ], 'With title at start' => [
1477 [ '* {{PAGENAME}}', true, Title::newFromText( 'Talk:Some page' ) ],
1478 "<ul><li>Some page</li></ul>\n",
1479 ], 'With title at start' => [
1480 [ '* {{PAGENAME}}', false, Title::newFromText( 'Talk:Some page' ), false ],
1481 "<p>* Some page</p>",
1482 ], 'Untidy input' => [
1483 [ '<b>{{PAGENAME}}', true, Title::newFromText( 'Talk:Some page' ) ],
1484 "<p><b>Some page\n</b></p>",
1485 ],
1486 ],
1487 'addWikiTextAsContent' => [
1488 // Preferred interface: output is tidied
1489 'SpecialNewimages' => [
1490 [ "<p lang='en' dir='ltr'>\nMy message" ],
1491 '<p lang="en" dir="ltr">' . "\nMy message\n</p>"
1492 ], 'List at start' => [
1493 [ '* List' ],
1494 "<ul><li>List</li></ul>\n",
1495 ], 'List not at start' => [
1496 [ '* <b>Not a list', false ],
1497 '<p>* <b>Not a list</b></p>',
1498 ], 'With title at start' => [
1499 [ '* {{PAGENAME}}', true, Title::newFromText( 'Talk:Some page' ) ],
1500 "<ul><li>Some page</li></ul>\n",
1501 ], 'With title at start' => [
1502 [ '* {{PAGENAME}}', false, Title::newFromText( 'Talk:Some page' ), false ],
1503 "<p>* Some page</p>",
1504 ], 'EditPage' => [
1505 [ "<div class='mw-editintro'>{{PAGENAME}}", true, Title::newFromText( 'Talk:Some page' ) ],
1506 '<div class="mw-editintro">' . "Some page\n</div>"
1507 ],
1508 ],
1509 ];
1510
1511 // Test all the others on addWikiTextTitle as well
1512 foreach ( $tests['addWikiText'] as $key => $val ) {
1513 $args = [ $val[0][0], null, $val[0][1] ?? true, false, $val[0][2] ?? true ];
1514 $tests['addWikiTextTitle']["$key (addWikiTextTitle)"] =
1515 array_merge( [ $args ], array_slice( $val, 1 ) );
1516 }
1517 foreach ( $tests['addWikiTextWithTitle'] as $key => $val ) {
1518 $args = [ $val[0][0], $val[0][1], $val[0][2] ?? true ];
1519 $tests['addWikiTextTitle']["$key (addWikiTextTitle)"] =
1520 array_merge( [ $args ], array_slice( $val, 1 ) );
1521 }
1522 foreach ( $tests['addWikiTextAsInterface'] as $key => $val ) {
1523 $args = [ $val[0][0], $val[0][2] ?? null, $val[0][1] ?? true, true, true ];
1524 $tests['addWikiTextTitle']["$key (addWikiTextTitle)"] =
1525 array_merge( [ $args ], array_slice( $val, 1 ) );
1526 }
1527 foreach ( $tests['addWikiTextAsContent'] as $key => $val ) {
1528 $args = [ $val[0][0], $val[0][2] ?? null, $val[0][1] ?? true, true, false ];
1529 $tests['addWikiTextTitle']["$key (addWikiTextTitle)"] =
1530 array_merge( [ $args ], array_slice( $val, 1 ) );
1531 }
1532 // addWikiTextTidy / addWikiTextTitleTidy were old aliases of
1533 // addWikiTextAsContent
1534 foreach ( $tests['addWikiTextAsContent'] as $key => $val ) {
1535 if ( count( $val[0] ) > 2 ) {
1536 $args = [ $val[0][0], $val[0][2], $val[0][1] ?? true ];
1537 $tests['addWikiTextTitleTidy']["$key (addWikiTextTitleTidy)"] =
1538 array_merge( [ $args ], array_slice( $val, 1 ) );
1539 } else {
1540 $args = [ $val[0][0], $val[0][1] ?? true ];
1541 $tests['addWikiTextTidy']["$key (addWikiTextTidy)"] =
1542 array_merge( [ $args ], array_slice( $val, 1 ) );
1543 }
1544 }
1545
1546 // We have to reformat our array to match what PHPUnit wants
1547 $ret = [];
1548 foreach ( $tests as $key => $subarray ) {
1549 foreach ( $subarray as $subkey => $val ) {
1550 $val = array_merge( [ $key ], $val );
1551 $ret[$subkey] = $val;
1552 }
1553 }
1554
1555 return $ret;
1556 }
1557
1558 /**
1559 * @covers OutputPage::addWikiText
1560 */
1561 public function testAddWikiTextNoTitle() {
1562 $this->setExpectedException( MWException::class, 'Title is null' );
1563
1564 $op = $this->newInstance( [], null, 'notitle' );
1565 $op->addWikiText( 'a' );
1566 }
1567
1568 /**
1569 * @covers OutputPage::addWikiTextAsInterface
1570 */
1571 public function testAddWikiTextAsInterfaceNoTitle() {
1572 $this->setExpectedException( MWException::class, 'Title is null' );
1573
1574 $op = $this->newInstance( [], null, 'notitle' );
1575 $op->addWikiTextAsInterface( 'a' );
1576 }
1577
1578 /**
1579 * @covers OutputPage::addWikiTextAsContent
1580 */
1581 public function testAddWikiTextAsContentNoTitle() {
1582 $this->setExpectedException( MWException::class, 'Title is null' );
1583
1584 $op = $this->newInstance( [], null, 'notitle' );
1585 $op->addWikiTextAsContent( 'a' );
1586 }
1587
1588 /**
1589 * @covers OutputPage::addWikiMsg
1590 */
1591 public function testAddWikiMsg() {
1592 $msg = wfMessage( 'parentheses' );
1593 $this->assertSame( '(a)', $msg->rawParams( 'a' )->plain() );
1594
1595 $op = $this->newInstance();
1596 $this->assertSame( '', $op->getHTML() );
1597 $op->addWikiMsg( 'parentheses', "<b>a" );
1598 // This is known to be bad unbalanced HTML; this will be fixed
1599 // by I743f4185a03403f8d9b9db010ff1ee4e9342e062 (T198214)
1600 $this->assertSame( "<p>(<b>a)\n</p>", $op->getHTML() );
1601 }
1602
1603 /**
1604 * @covers OutputPage::wrapWikiMsg
1605 */
1606 public function testWrapWikiMsg() {
1607 $msg = wfMessage( 'parentheses' );
1608 $this->assertSame( '(a)', $msg->rawParams( 'a' )->plain() );
1609
1610 $op = $this->newInstance();
1611 $this->assertSame( '', $op->getHTML() );
1612 $op->wrapWikiMsg( '[$1]', [ 'parentheses', "<b>a" ] );
1613 // This is known to be bad unbalanced HTML; this will be fixed
1614 // by I743f4185a03403f8d9b9db010ff1ee4e9342e062 (T198214)
1615 $this->assertSame( "<p>[(<b>a)]\n</p>", $op->getHTML() );
1616 }
1617
1618 /**
1619 * @covers OutputPage::addParserOutputMetadata
1620 */
1621 public function testNoGallery() {
1622 $op = $this->newInstance();
1623 $this->assertFalse( $op->mNoGallery );
1624
1625 $stubPO1 = $this->createParserOutputStub( 'getNoGallery', true );
1626 $op->addParserOutputMetadata( $stubPO1 );
1627 $this->assertTrue( $op->mNoGallery );
1628
1629 $stubPO2 = $this->createParserOutputStub( 'getNoGallery', false );
1630 $op->addParserOutputMetadata( $stubPO2 );
1631 $this->assertFalse( $op->mNoGallery );
1632 }
1633
1634 // @todo Make sure to test the following in addParserOutputMetadata() as well when we add tests
1635 // for them:
1636 // * enableClientCache()
1637 // * addModules()
1638 // * addModuleScripts()
1639 // * addModuleStyles()
1640 // * addJsConfigVars()
1641 // * preventClickJacking()
1642 // Otherwise those lines of addParserOutputMetadata() will be reported as covered, but we won't
1643 // be testing they actually work.
1644
1645 /**
1646 * @covers OutputPage::haveCacheVaryCookies
1647 */
1648 public function testHaveCacheVaryCookies() {
1649 $request = new FauxRequest();
1650 $context = new RequestContext();
1651 $context->setRequest( $request );
1652 $op = new OutputPage( $context );
1653
1654 // No cookies are set.
1655 $this->assertFalse( $op->haveCacheVaryCookies() );
1656
1657 // 'Token' is present but empty, so it shouldn't count.
1658 $request->setCookie( 'Token', '' );
1659 $this->assertFalse( $op->haveCacheVaryCookies() );
1660
1661 // 'Token' present and nonempty.
1662 $request->setCookie( 'Token', '123' );
1663 $this->assertTrue( $op->haveCacheVaryCookies() );
1664 }
1665
1666 /**
1667 * @dataProvider provideVaryHeaders
1668 *
1669 * @covers OutputPage::addVaryHeader
1670 * @covers OutputPage::getVaryHeader
1671 * @covers OutputPage::getKeyHeader
1672 */
1673 public function testVaryHeaders( $calls, $vary, $key ) {
1674 // get rid of default Vary fields
1675 $op = $this->getMockBuilder( OutputPage::class )
1676 ->setConstructorArgs( [ new RequestContext() ] )
1677 ->setMethods( [ 'getCacheVaryCookies' ] )
1678 ->getMock();
1679 $op->expects( $this->any() )
1680 ->method( 'getCacheVaryCookies' )
1681 ->will( $this->returnValue( [] ) );
1682 TestingAccessWrapper::newFromObject( $op )->mVaryHeader = [];
1683
1684 foreach ( $calls as $call ) {
1685 call_user_func_array( [ $op, 'addVaryHeader' ], $call );
1686 }
1687 $this->assertEquals( $vary, $op->getVaryHeader(), 'Vary:' );
1688 $this->assertEquals( $key, $op->getKeyHeader(), 'Key:' );
1689 }
1690
1691 public function provideVaryHeaders() {
1692 // note: getKeyHeader() automatically adds Vary: Cookie
1693 return [
1694 [ // single header
1695 [
1696 [ 'Cookie' ],
1697 ],
1698 'Vary: Cookie',
1699 'Key: Cookie',
1700 ],
1701 [ // non-unique headers
1702 [
1703 [ 'Cookie' ],
1704 [ 'Accept-Language' ],
1705 [ 'Cookie' ],
1706 ],
1707 'Vary: Cookie, Accept-Language',
1708 'Key: Cookie,Accept-Language',
1709 ],
1710 [ // two headers with single options
1711 [
1712 [ 'Cookie', [ 'param=phpsessid' ] ],
1713 [ 'Accept-Language', [ 'substr=en' ] ],
1714 ],
1715 'Vary: Cookie, Accept-Language',
1716 'Key: Cookie;param=phpsessid,Accept-Language;substr=en',
1717 ],
1718 [ // one header with multiple options
1719 [
1720 [ 'Cookie', [ 'param=phpsessid', 'param=userId' ] ],
1721 ],
1722 'Vary: Cookie',
1723 'Key: Cookie;param=phpsessid;param=userId',
1724 ],
1725 [ // Duplicate option
1726 [
1727 [ 'Cookie', [ 'param=phpsessid' ] ],
1728 [ 'Cookie', [ 'param=phpsessid' ] ],
1729 [ 'Accept-Language', [ 'substr=en', 'substr=en' ] ],
1730 ],
1731 'Vary: Cookie, Accept-Language',
1732 'Key: Cookie;param=phpsessid,Accept-Language;substr=en',
1733 ],
1734 [ // Same header, different options
1735 [
1736 [ 'Cookie', [ 'param=phpsessid' ] ],
1737 [ 'Cookie', [ 'param=userId' ] ],
1738 ],
1739 'Vary: Cookie',
1740 'Key: Cookie;param=phpsessid;param=userId',
1741 ],
1742 ];
1743 }
1744
1745 /**
1746 * @dataProvider provideLinkHeaders
1747 *
1748 * @covers OutputPage::addLinkHeader
1749 * @covers OutputPage::getLinkHeader
1750 */
1751 public function testLinkHeaders( $headers, $result ) {
1752 $op = $this->newInstance();
1753
1754 foreach ( $headers as $header ) {
1755 $op->addLinkHeader( $header );
1756 }
1757
1758 $this->assertEquals( $result, $op->getLinkHeader() );
1759 }
1760
1761 public function provideLinkHeaders() {
1762 return [
1763 [
1764 [],
1765 false
1766 ],
1767 [
1768 [ '<https://foo/bar.jpg>;rel=preload;as=image' ],
1769 'Link: <https://foo/bar.jpg>;rel=preload;as=image',
1770 ],
1771 [
1772 [ '<https://foo/bar.jpg>;rel=preload;as=image','<https://foo/baz.jpg>;rel=preload;as=image' ],
1773 'Link: <https://foo/bar.jpg>;rel=preload;as=image,<https://foo/baz.jpg>;rel=preload;as=image',
1774 ],
1775 ];
1776 }
1777
1778 /**
1779 * See ResourceLoaderClientHtmlTest for full coverage.
1780 *
1781 * @dataProvider provideMakeResourceLoaderLink
1782 *
1783 * @covers OutputPage::makeResourceLoaderLink
1784 */
1785 public function testMakeResourceLoaderLink( $args, $expectedHtml ) {
1786 $this->setMwGlobals( [
1787 'wgResourceLoaderDebug' => false,
1788 'wgLoadScript' => 'http://127.0.0.1:8080/w/load.php',
1789 'wgCSPReportOnlyHeader' => true,
1790 ] );
1791 $class = new ReflectionClass( OutputPage::class );
1792 $method = $class->getMethod( 'makeResourceLoaderLink' );
1793 $method->setAccessible( true );
1794 $ctx = new RequestContext();
1795 $ctx->setSkin( SkinFactory::getDefaultInstance()->makeSkin( 'fallback' ) );
1796 $ctx->setLanguage( 'en' );
1797 $out = new OutputPage( $ctx );
1798 $nonce = $class->getProperty( 'CSPNonce' );
1799 $nonce->setAccessible( true );
1800 $nonce->setValue( $out, 'secret' );
1801 $rl = $out->getResourceLoader();
1802 $rl->setMessageBlobStore( new NullMessageBlobStore() );
1803 $rl->register( [
1804 'test.foo' => new ResourceLoaderTestModule( [
1805 'script' => 'mw.test.foo( { a: true } );',
1806 'styles' => '.mw-test-foo { content: "style"; }',
1807 ] ),
1808 'test.bar' => new ResourceLoaderTestModule( [
1809 'script' => 'mw.test.bar( { a: true } );',
1810 'styles' => '.mw-test-bar { content: "style"; }',
1811 ] ),
1812 'test.baz' => new ResourceLoaderTestModule( [
1813 'script' => 'mw.test.baz( { a: true } );',
1814 'styles' => '.mw-test-baz { content: "style"; }',
1815 ] ),
1816 'test.quux' => new ResourceLoaderTestModule( [
1817 'script' => 'mw.test.baz( { token: 123 } );',
1818 'styles' => '/* pref-animate=off */ .mw-icon { transition: none; }',
1819 'group' => 'private',
1820 ] ),
1821 'test.noscript' => new ResourceLoaderTestModule( [
1822 'styles' => '.stuff { color: red; }',
1823 'group' => 'noscript',
1824 ] ),
1825 'test.group.foo' => new ResourceLoaderTestModule( [
1826 'script' => 'mw.doStuff( "foo" );',
1827 'group' => 'foo',
1828 ] ),
1829 'test.group.bar' => new ResourceLoaderTestModule( [
1830 'script' => 'mw.doStuff( "bar" );',
1831 'group' => 'bar',
1832 ] ),
1833 ] );
1834 $links = $method->invokeArgs( $out, $args );
1835 $actualHtml = strval( $links );
1836 $this->assertEquals( $expectedHtml, $actualHtml );
1837 }
1838
1839 public static function provideMakeResourceLoaderLink() {
1840 // phpcs:disable Generic.Files.LineLength
1841 return [
1842 // Single only=scripts load
1843 [
1844 [ 'test.foo', ResourceLoaderModule::TYPE_SCRIPTS ],
1845 "<script nonce=\"secret\">(window.RLQ=window.RLQ||[]).push(function(){"
1846 . 'mw.loader.load("http://127.0.0.1:8080/w/load.php?debug=false\u0026lang=en\u0026modules=test.foo\u0026only=scripts\u0026skin=fallback");'
1847 . "});</script>"
1848 ],
1849 // Multiple only=styles load
1850 [
1851 [ [ 'test.baz', 'test.foo', 'test.bar' ], ResourceLoaderModule::TYPE_STYLES ],
1852
1853 '<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"/>'
1854 ],
1855 // Private embed (only=scripts)
1856 [
1857 [ 'test.quux', ResourceLoaderModule::TYPE_SCRIPTS ],
1858 "<script nonce=\"secret\">(window.RLQ=window.RLQ||[]).push(function(){"
1859 . "mw.test.baz({token:123});\nmw.loader.state({\"test.quux\":\"ready\"});"
1860 . "});</script>"
1861 ],
1862 // Load private module (combined)
1863 [
1864 [ 'test.quux', ResourceLoaderModule::TYPE_COMBINED ],
1865 "<script nonce=\"secret\">(window.RLQ=window.RLQ||[]).push(function(){"
1866 . "mw.loader.implement(\"test.quux@1ev0ijv\",function($,jQuery,require,module){"
1867 . "mw.test.baz({token:123});},{\"css\":[\".mw-icon{transition:none}"
1868 . "\"]});});</script>"
1869 ],
1870 // Load no modules
1871 [
1872 [ [], ResourceLoaderModule::TYPE_COMBINED ],
1873 '',
1874 ],
1875 // noscript group
1876 [
1877 [ 'test.noscript', ResourceLoaderModule::TYPE_STYLES ],
1878 '<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>'
1879 ],
1880 // Load two modules in separate groups
1881 [
1882 [ [ 'test.group.foo', 'test.group.bar' ], ResourceLoaderModule::TYPE_COMBINED ],
1883 "<script nonce=\"secret\">(window.RLQ=window.RLQ||[]).push(function(){"
1884 . 'mw.loader.load("http://127.0.0.1:8080/w/load.php?debug=false\u0026lang=en\u0026modules=test.group.bar\u0026skin=fallback");'
1885 . 'mw.loader.load("http://127.0.0.1:8080/w/load.php?debug=false\u0026lang=en\u0026modules=test.group.foo\u0026skin=fallback");'
1886 . "});</script>"
1887 ],
1888 ];
1889 // phpcs:enable
1890 }
1891
1892 /**
1893 * @dataProvider provideBuildExemptModules
1894 *
1895 * @covers OutputPage::buildExemptModules
1896 */
1897 public function testBuildExemptModules( array $exemptStyleModules, $expect ) {
1898 $this->setMwGlobals( [
1899 'wgResourceLoaderDebug' => false,
1900 'wgLoadScript' => '/w/load.php',
1901 // Stub wgCacheEpoch as it influences getVersionHash used for the
1902 // urls in the expected HTML
1903 'wgCacheEpoch' => '20140101000000',
1904 ] );
1905
1906 // Set up stubs
1907 $ctx = new RequestContext();
1908 $ctx->setSkin( SkinFactory::getDefaultInstance()->makeSkin( 'fallback' ) );
1909 $ctx->setLanguage( 'en' );
1910 $op = $this->getMockBuilder( OutputPage::class )
1911 ->setConstructorArgs( [ $ctx ] )
1912 ->setMethods( [ 'buildCssLinksArray' ] )
1913 ->getMock();
1914 $op->expects( $this->any() )
1915 ->method( 'buildCssLinksArray' )
1916 ->willReturn( [] );
1917 $rl = $op->getResourceLoader();
1918 $rl->setMessageBlobStore( new NullMessageBlobStore() );
1919
1920 // Register custom modules
1921 $rl->register( [
1922 'example.site.a' => new ResourceLoaderTestModule( [ 'group' => 'site' ] ),
1923 'example.site.b' => new ResourceLoaderTestModule( [ 'group' => 'site' ] ),
1924 'example.user' => new ResourceLoaderTestModule( [ 'group' => 'user' ] ),
1925 ] );
1926
1927 $op = TestingAccessWrapper::newFromObject( $op );
1928 $op->rlExemptStyleModules = $exemptStyleModules;
1929 $this->assertEquals(
1930 $expect,
1931 strval( $op->buildExemptModules() )
1932 );
1933 }
1934
1935 public static function provideBuildExemptModules() {
1936 // phpcs:disable Generic.Files.LineLength
1937 return [
1938 'empty' => [
1939 'exemptStyleModules' => [],
1940 '<meta name="ResourceLoaderDynamicStyles" content=""/>',
1941 ],
1942 'empty sets' => [
1943 'exemptStyleModules' => [ 'site' => [], 'noscript' => [], 'private' => [], 'user' => [] ],
1944 '<meta name="ResourceLoaderDynamicStyles" content=""/>',
1945 ],
1946 'default logged-out' => [
1947 'exemptStyleModules' => [ 'site' => [ 'site.styles' ] ],
1948 '<meta name="ResourceLoaderDynamicStyles" content=""/>' . "\n" .
1949 '<link rel="stylesheet" href="/w/load.php?debug=false&amp;lang=en&amp;modules=site.styles&amp;only=styles&amp;skin=fallback"/>',
1950 ],
1951 'default logged-in' => [
1952 'exemptStyleModules' => [ 'site' => [ 'site.styles' ], 'user' => [ 'user.styles' ] ],
1953 '<meta name="ResourceLoaderDynamicStyles" content=""/>' . "\n" .
1954 '<link rel="stylesheet" href="/w/load.php?debug=false&amp;lang=en&amp;modules=site.styles&amp;only=styles&amp;skin=fallback"/>' . "\n" .
1955 '<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"/>',
1956 ],
1957 'custom modules' => [
1958 'exemptStyleModules' => [
1959 'site' => [ 'site.styles', 'example.site.a', 'example.site.b' ],
1960 'user' => [ 'user.styles', 'example.user' ],
1961 ],
1962 '<meta name="ResourceLoaderDynamicStyles" content=""/>' . "\n" .
1963 '<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" .
1964 '<link rel="stylesheet" href="/w/load.php?debug=false&amp;lang=en&amp;modules=site.styles&amp;only=styles&amp;skin=fallback"/>' . "\n" .
1965 '<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" .
1966 '<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"/>',
1967 ],
1968 ];
1969 // phpcs:enable
1970 }
1971
1972 /**
1973 * @dataProvider provideTransformFilePath
1974 * @covers OutputPage::transformFilePath
1975 * @covers OutputPage::transformResourcePath
1976 */
1977 public function testTransformResourcePath( $baseDir, $basePath, $uploadDir = null,
1978 $uploadPath = null, $path = null, $expected = null
1979 ) {
1980 if ( $path === null ) {
1981 // Skip optional $uploadDir and $uploadPath
1982 $path = $uploadDir;
1983 $expected = $uploadPath;
1984 $uploadDir = "$baseDir/images";
1985 $uploadPath = "$basePath/images";
1986 }
1987 $this->setMwGlobals( 'IP', $baseDir );
1988 $conf = new HashConfig( [
1989 'ResourceBasePath' => $basePath,
1990 'UploadDirectory' => $uploadDir,
1991 'UploadPath' => $uploadPath,
1992 ] );
1993
1994 // Some of these paths don't exist and will cause warnings
1995 Wikimedia\suppressWarnings();
1996 $actual = OutputPage::transformResourcePath( $conf, $path );
1997 Wikimedia\restoreWarnings();
1998
1999 $this->assertEquals( $expected ?: $path, $actual );
2000 }
2001
2002 public static function provideTransformFilePath() {
2003 $baseDir = dirname( __DIR__ ) . '/data/media';
2004 return [
2005 // File that matches basePath, and exists. Hash found and appended.
2006 [
2007 'baseDir' => $baseDir, 'basePath' => '/w',
2008 '/w/test.jpg',
2009 '/w/test.jpg?edcf2'
2010 ],
2011 // File that matches basePath, but not found on disk. Empty query.
2012 [
2013 'baseDir' => $baseDir, 'basePath' => '/w',
2014 '/w/unknown.png',
2015 '/w/unknown.png?'
2016 ],
2017 // File not matching basePath. Ignored.
2018 [
2019 'baseDir' => $baseDir, 'basePath' => '/w',
2020 '/files/test.jpg'
2021 ],
2022 // Empty string. Ignored.
2023 [
2024 'baseDir' => $baseDir, 'basePath' => '/w',
2025 '',
2026 ''
2027 ],
2028 // Similar path, but with domain component. Ignored.
2029 [
2030 'baseDir' => $baseDir, 'basePath' => '/w',
2031 '//example.org/w/test.jpg'
2032 ],
2033 [
2034 'baseDir' => $baseDir, 'basePath' => '/w',
2035 'https://example.org/w/test.jpg'
2036 ],
2037 // Unrelated path with domain component. Ignored.
2038 [
2039 'baseDir' => $baseDir, 'basePath' => '/w',
2040 'https://example.org/files/test.jpg'
2041 ],
2042 [
2043 'baseDir' => $baseDir, 'basePath' => '/w',
2044 '//example.org/files/test.jpg'
2045 ],
2046 // Unrelated path with domain, and empty base path (root mw install). Ignored.
2047 [
2048 'baseDir' => $baseDir, 'basePath' => '',
2049 'https://example.org/files/test.jpg'
2050 ],
2051 [
2052 'baseDir' => $baseDir, 'basePath' => '',
2053 // T155310
2054 '//example.org/files/test.jpg'
2055 ],
2056 // Check UploadPath before ResourceBasePath (T155146)
2057 [
2058 'baseDir' => dirname( $baseDir ), 'basePath' => '',
2059 'uploadDir' => $baseDir, 'uploadPath' => '/images',
2060 '/images/test.jpg',
2061 '/images/test.jpg?edcf2'
2062 ],
2063 ];
2064 }
2065
2066 /**
2067 * Tests a particular case of transformCssMedia, using the given input, globals,
2068 * expected return, and message
2069 *
2070 * Asserts that $expectedReturn is returned.
2071 *
2072 * options['printableQuery'] - value of query string for printable, or omitted for none
2073 * options['handheldQuery'] - value of query string for handheld, or omitted for none
2074 * options['media'] - passed into the method under the same name
2075 * options['expectedReturn'] - expected return value
2076 * options['message'] - PHPUnit message for assertion
2077 *
2078 * @param array $args Key-value array of arguments as shown above
2079 */
2080 protected function assertTransformCssMediaCase( $args ) {
2081 $queryData = [];
2082 if ( isset( $args['printableQuery'] ) ) {
2083 $queryData['printable'] = $args['printableQuery'];
2084 }
2085
2086 if ( isset( $args['handheldQuery'] ) ) {
2087 $queryData['handheld'] = $args['handheldQuery'];
2088 }
2089
2090 $fauxRequest = new FauxRequest( $queryData, false );
2091 $this->setMwGlobals( [
2092 'wgRequest' => $fauxRequest,
2093 ] );
2094
2095 $actualReturn = OutputPage::transformCssMedia( $args['media'] );
2096 $this->assertSame( $args['expectedReturn'], $actualReturn, $args['message'] );
2097 }
2098
2099 /**
2100 * Tests print requests
2101 *
2102 * @covers OutputPage::transformCssMedia
2103 */
2104 public function testPrintRequests() {
2105 $this->assertTransformCssMediaCase( [
2106 'printableQuery' => '1',
2107 'media' => 'screen',
2108 'expectedReturn' => null,
2109 'message' => 'On printable request, screen returns null'
2110 ] );
2111
2112 $this->assertTransformCssMediaCase( [
2113 'printableQuery' => '1',
2114 'media' => self::SCREEN_MEDIA_QUERY,
2115 'expectedReturn' => null,
2116 'message' => 'On printable request, screen media query returns null'
2117 ] );
2118
2119 $this->assertTransformCssMediaCase( [
2120 'printableQuery' => '1',
2121 'media' => self::SCREEN_ONLY_MEDIA_QUERY,
2122 'expectedReturn' => null,
2123 'message' => 'On printable request, screen media query with only returns null'
2124 ] );
2125
2126 $this->assertTransformCssMediaCase( [
2127 'printableQuery' => '1',
2128 'media' => 'print',
2129 'expectedReturn' => '',
2130 'message' => 'On printable request, media print returns empty string'
2131 ] );
2132 }
2133
2134 /**
2135 * Tests screen requests, without either query parameter set
2136 *
2137 * @covers OutputPage::transformCssMedia
2138 */
2139 public function testScreenRequests() {
2140 $this->assertTransformCssMediaCase( [
2141 'media' => 'screen',
2142 'expectedReturn' => 'screen',
2143 'message' => 'On screen request, screen media type is preserved'
2144 ] );
2145
2146 $this->assertTransformCssMediaCase( [
2147 'media' => 'handheld',
2148 'expectedReturn' => 'handheld',
2149 'message' => 'On screen request, handheld media type is preserved'
2150 ] );
2151
2152 $this->assertTransformCssMediaCase( [
2153 'media' => self::SCREEN_MEDIA_QUERY,
2154 'expectedReturn' => self::SCREEN_MEDIA_QUERY,
2155 'message' => 'On screen request, screen media query is preserved.'
2156 ] );
2157
2158 $this->assertTransformCssMediaCase( [
2159 'media' => self::SCREEN_ONLY_MEDIA_QUERY,
2160 'expectedReturn' => self::SCREEN_ONLY_MEDIA_QUERY,
2161 'message' => 'On screen request, screen media query with only is preserved.'
2162 ] );
2163
2164 $this->assertTransformCssMediaCase( [
2165 'media' => 'print',
2166 'expectedReturn' => 'print',
2167 'message' => 'On screen request, print media type is preserved'
2168 ] );
2169 }
2170
2171 /**
2172 * Tests handheld behavior
2173 *
2174 * @covers OutputPage::transformCssMedia
2175 */
2176 public function testHandheld() {
2177 $this->assertTransformCssMediaCase( [
2178 'handheldQuery' => '1',
2179 'media' => 'handheld',
2180 'expectedReturn' => '',
2181 'message' => 'On request with handheld querystring and media is handheld, returns empty string'
2182 ] );
2183
2184 $this->assertTransformCssMediaCase( [
2185 'handheldQuery' => '1',
2186 'media' => 'screen',
2187 'expectedReturn' => null,
2188 'message' => 'On request with handheld querystring and media is screen, returns null'
2189 ] );
2190 }
2191
2192 /**
2193 * @return OutputPage
2194 */
2195 private function newInstance( $config = [], WebRequest $request = null, $options = [] ) {
2196 $context = new RequestContext();
2197
2198 $context->setConfig( new MultiConfig( [
2199 new HashConfig( $config + [
2200 'AppleTouchIcon' => false,
2201 'DisableLangConversion' => true,
2202 'EnableCanonicalServerLink' => false,
2203 'Favicon' => false,
2204 'Feed' => false,
2205 'LanguageCode' => false,
2206 'ReferrerPolicy' => false,
2207 'RightsPage' => false,
2208 'RightsUrl' => false,
2209 'UniversalEditButton' => false,
2210 ] ),
2211 $context->getConfig()
2212 ] ) );
2213
2214 if ( !in_array( 'notitle', (array)$options ) ) {
2215 $context->setTitle( Title::newFromText( 'My test page' ) );
2216 }
2217
2218 if ( $request ) {
2219 $context->setRequest( $request );
2220 }
2221
2222 return new OutputPage( $context );
2223 }
2224 }
2225
2226 /**
2227 * MessageBlobStore that doesn't do anything
2228 */
2229 class NullMessageBlobStore extends MessageBlobStore {
2230 public function get( ResourceLoader $resourceLoader, $modules, $lang ) {
2231 return [];
2232 }
2233
2234 public function updateModule( $name, ResourceLoaderModule $module, $lang ) {
2235 }
2236
2237 public function updateMessage( $key ) {
2238 }
2239
2240 public function clear() {
2241 }
2242 }