Deprecate and rename 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 if ( in_array(
1408 $method,
1409 [ 'addWikiTextWithTitle', 'addWikiTextTitleTidy', 'addWikiTextTitle' ]
1410 ) && count( $args ) >= 2 && $args[1] === null ) {
1411 // Special placeholder because we can't get the actual title in the provider
1412 $args[1] = $op->getTitle();
1413 }
1414 if ( in_array(
1415 $method,
1416 [ 'addWikiTextAsInterface', 'addWikiTextAsContent' ]
1417 ) && count( $args ) >= 3 && $args[2] === null ) {
1418 // Special placeholder because we can't get the actual title in the provider
1419 $args[2] = $op->getTitle();
1420 }
1421
1422 $op->$method( ...$args );
1423 $this->assertSame( $expected, $op->getHTML() );
1424 }
1425
1426 public function provideAddWikiText() {
1427 $tests = [
1428 'addWikiText' => [
1429 // Not tidied; this API is deprecated.
1430 'Simple wikitext' => [
1431 [ "'''Bold'''" ],
1432 "<p><b>Bold</b>\n</p>",
1433 ], 'List at start' => [
1434 [ '* List' ],
1435 "<ul><li>List</li></ul>\n",
1436 ], 'List not at start' => [
1437 [ '* Not a list', false ],
1438 '* Not a list',
1439 ], 'Non-interface' => [
1440 [ "'''Bold'''", true, false ],
1441 "<p><b>Bold</b>\n</p>",
1442 ], 'No section edit links' => [
1443 [ '== Title ==' ],
1444 "<h2><span class=\"mw-headline\" id=\"Title\">Title</span></h2>\n",
1445 ],
1446 ],
1447 'addWikiTextWithTitle' => [
1448 // Untidied; this API is deprecated
1449 'With title at start' => [
1450 [ '* {{PAGENAME}}', Title::newFromText( 'Talk:Some page' ) ],
1451 "<ul><li>Some page</li></ul>\n",
1452 ], 'With title at start' => [
1453 [ '* {{PAGENAME}}', Title::newFromText( 'Talk:Some page' ), false ],
1454 "* Some page",
1455 ],
1456 ],
1457 'addWikiTextAsInterface' => [
1458 // Preferred interface: output is tidied
1459 'Simple wikitext' => [
1460 [ "'''Bold'''" ],
1461 "<p><b>Bold</b>\n</p>",
1462 ], 'Untidy wikitext' => [
1463 [ "<b>Bold" ],
1464 "<p><b>Bold\n</b></p>",
1465 ], 'List at start' => [
1466 [ '* List' ],
1467 "<ul><li>List</li></ul>\n",
1468 ], 'List not at start' => [
1469 [ '* Not a list', false ],
1470 '<p>* Not a list</p>',
1471 ], 'No section edit links' => [
1472 [ '== Title ==' ],
1473 "<h2><span class=\"mw-headline\" id=\"Title\">Title</span></h2>\n",
1474 ], 'With title at start' => [
1475 [ '* {{PAGENAME}}', true, Title::newFromText( 'Talk:Some page' ) ],
1476 "<ul><li>Some page</li></ul>\n",
1477 ], 'With title at start' => [
1478 [ '* {{PAGENAME}}', false, Title::newFromText( 'Talk:Some page' ), false ],
1479 "<p>* Some page</p>",
1480 ], 'Untidy input' => [
1481 [ '<b>{{PAGENAME}}', true, Title::newFromText( 'Talk:Some page' ) ],
1482 "<p><b>Some page\n</b></p>",
1483 ],
1484 ],
1485 'addWikiTextAsContent' => [
1486 // Preferred interface: output is tidied
1487 'SpecialNewimages' => [
1488 [ "<p lang='en' dir='ltr'>\nMy message" ],
1489 '<p lang="en" dir="ltr">' . "\nMy message\n</p>"
1490 ], 'List at start' => [
1491 [ '* List' ],
1492 "<ul><li>List</li></ul>\n",
1493 ], 'List not at start' => [
1494 [ '* <b>Not a list', false ],
1495 '<p>* <b>Not a list</b></p>',
1496 ], 'With title at start' => [
1497 [ '* {{PAGENAME}}', true, Title::newFromText( 'Talk:Some page' ) ],
1498 "<ul><li>Some page</li></ul>\n",
1499 ], 'With title at start' => [
1500 [ '* {{PAGENAME}}', false, Title::newFromText( 'Talk:Some page' ), false ],
1501 "<p>* Some page</p>",
1502 ], 'EditPage' => [
1503 [ "<div class='mw-editintro'>{{PAGENAME}}", true, Title::newFromText( 'Talk:Some page' ) ],
1504 '<div class="mw-editintro">' . "Some page\n</div>"
1505 ],
1506 ],
1507 ];
1508
1509 // Test all the others on addWikiTextTitle as well
1510 foreach ( $tests['addWikiText'] as $key => $val ) {
1511 $args = [ $val[0][0], null, $val[0][1] ?? true, false, $val[0][2] ?? true ];
1512 $tests['addWikiTextTitle']["$key (addWikiTextTitle)"] =
1513 array_merge( [ $args ], array_slice( $val, 1 ) );
1514 }
1515 foreach ( $tests['addWikiTextWithTitle'] as $key => $val ) {
1516 $args = [ $val[0][0], $val[0][1], $val[0][2] ?? true ];
1517 $tests['addWikiTextTitle']["$key (addWikiTextTitle)"] =
1518 array_merge( [ $args ], array_slice( $val, 1 ) );
1519 }
1520 foreach ( $tests['addWikiTextAsInterface'] as $key => $val ) {
1521 $args = [ $val[0][0], $val[0][2] ?? null, $val[0][1] ?? true, true, true ];
1522 $tests['addWikiTextTitle']["$key (addWikiTextTitle)"] =
1523 array_merge( [ $args ], array_slice( $val, 1 ) );
1524 }
1525 foreach ( $tests['addWikiTextAsContent'] as $key => $val ) {
1526 $args = [ $val[0][0], $val[0][2] ?? null, $val[0][1] ?? true, true, false ];
1527 $tests['addWikiTextTitle']["$key (addWikiTextTitle)"] =
1528 array_merge( [ $args ], array_slice( $val, 1 ) );
1529 }
1530 // addWikiTextTidy / addWikiTextTitleTidy were old aliases of
1531 // addWikiTextAsContent
1532 foreach ( $tests['addWikiTextAsContent'] as $key => $val ) {
1533 if ( count( $val[0] ) > 2 ) {
1534 $args = [ $val[0][0], $val[0][2], $val[0][1] ?? true ];
1535 $tests['addWikiTextTitleTidy']["$key (addWikiTextTitleTidy)"] =
1536 array_merge( [ $args ], array_slice( $val, 1 ) );
1537 } else {
1538 $args = [ $val[0][0], $val[0][1] ?? true ];
1539 $tests['addWikiTextTidy']["$key (addWikiTextTidy)"] =
1540 array_merge( [ $args ], array_slice( $val, 1 ) );
1541 }
1542 }
1543
1544 // We have to reformat our array to match what PHPUnit wants
1545 $ret = [];
1546 foreach ( $tests as $key => $subarray ) {
1547 foreach ( $subarray as $subkey => $val ) {
1548 $val = array_merge( [ $key ], $val );
1549 $ret[$subkey] = $val;
1550 }
1551 }
1552
1553 return $ret;
1554 }
1555
1556 /**
1557 * @covers OutputPage::addWikiText
1558 */
1559 public function testAddWikiTextNoTitle() {
1560 $this->setExpectedException( MWException::class, 'Title is null' );
1561
1562 $op = $this->newInstance( [], null, 'notitle' );
1563 $op->addWikiText( 'a' );
1564 }
1565
1566 /**
1567 * @covers OutputPage::addWikiTextAsInterface
1568 */
1569 public function testAddWikiTextAsInterfaceNoTitle() {
1570 $this->setExpectedException( MWException::class, 'Title is null' );
1571
1572 $op = $this->newInstance( [], null, 'notitle' );
1573 $op->addWikiTextAsInterface( 'a' );
1574 }
1575
1576 /**
1577 * @covers OutputPage::addWikiTextAsContent
1578 */
1579 public function testAddWikiTextAsContentNoTitle() {
1580 $this->setExpectedException( MWException::class, 'Title is null' );
1581
1582 $op = $this->newInstance( [], null, 'notitle' );
1583 $op->addWikiTextAsContent( 'a' );
1584 }
1585
1586 /**
1587 * @covers OutputPage::addWikiMsg
1588 */
1589 public function testAddWikiMsg() {
1590 $msg = wfMessage( 'parentheses' );
1591 $this->assertSame( '(a)', $msg->rawParams( 'a' )->plain() );
1592
1593 $op = $this->newInstance();
1594 $this->assertSame( '', $op->getHTML() );
1595 $op->addWikiMsg( 'parentheses', "<b>a" );
1596 // This is known to be bad unbalanced HTML; this will be fixed
1597 // by I743f4185a03403f8d9b9db010ff1ee4e9342e062 (T198214)
1598 $this->assertSame( "<p>(<b>a)\n</p>", $op->getHTML() );
1599 }
1600
1601 /**
1602 * @covers OutputPage::wrapWikiMsg
1603 */
1604 public function testWrapWikiMsg() {
1605 $msg = wfMessage( 'parentheses' );
1606 $this->assertSame( '(a)', $msg->rawParams( 'a' )->plain() );
1607
1608 $op = $this->newInstance();
1609 $this->assertSame( '', $op->getHTML() );
1610 $op->wrapWikiMsg( '[$1]', [ 'parentheses', "<b>a" ] );
1611 // This is known to be bad unbalanced HTML; this will be fixed
1612 // by I743f4185a03403f8d9b9db010ff1ee4e9342e062 (T198214)
1613 $this->assertSame( "<p>[(<b>a)]\n</p>", $op->getHTML() );
1614 }
1615
1616 /**
1617 * @covers OutputPage::addParserOutputMetadata
1618 */
1619 public function testNoGallery() {
1620 $op = $this->newInstance();
1621 $this->assertFalse( $op->mNoGallery );
1622
1623 $stubPO1 = $this->createParserOutputStub( 'getNoGallery', true );
1624 $op->addParserOutputMetadata( $stubPO1 );
1625 $this->assertTrue( $op->mNoGallery );
1626
1627 $stubPO2 = $this->createParserOutputStub( 'getNoGallery', false );
1628 $op->addParserOutputMetadata( $stubPO2 );
1629 $this->assertFalse( $op->mNoGallery );
1630 }
1631
1632 // @todo Make sure to test the following in addParserOutputMetadata() as well when we add tests
1633 // for them:
1634 // * enableClientCache()
1635 // * addModules()
1636 // * addModuleScripts()
1637 // * addModuleStyles()
1638 // * addJsConfigVars()
1639 // * preventClickJacking()
1640 // Otherwise those lines of addParserOutputMetadata() will be reported as covered, but we won't
1641 // be testing they actually work.
1642
1643 /**
1644 * @covers OutputPage::haveCacheVaryCookies
1645 */
1646 public function testHaveCacheVaryCookies() {
1647 $request = new FauxRequest();
1648 $context = new RequestContext();
1649 $context->setRequest( $request );
1650 $op = new OutputPage( $context );
1651
1652 // No cookies are set.
1653 $this->assertFalse( $op->haveCacheVaryCookies() );
1654
1655 // 'Token' is present but empty, so it shouldn't count.
1656 $request->setCookie( 'Token', '' );
1657 $this->assertFalse( $op->haveCacheVaryCookies() );
1658
1659 // 'Token' present and nonempty.
1660 $request->setCookie( 'Token', '123' );
1661 $this->assertTrue( $op->haveCacheVaryCookies() );
1662 }
1663
1664 /**
1665 * @dataProvider provideVaryHeaders
1666 *
1667 * @covers OutputPage::addVaryHeader
1668 * @covers OutputPage::getVaryHeader
1669 * @covers OutputPage::getKeyHeader
1670 */
1671 public function testVaryHeaders( $calls, $vary, $key ) {
1672 // get rid of default Vary fields
1673 $op = $this->getMockBuilder( OutputPage::class )
1674 ->setConstructorArgs( [ new RequestContext() ] )
1675 ->setMethods( [ 'getCacheVaryCookies' ] )
1676 ->getMock();
1677 $op->expects( $this->any() )
1678 ->method( 'getCacheVaryCookies' )
1679 ->will( $this->returnValue( [] ) );
1680 TestingAccessWrapper::newFromObject( $op )->mVaryHeader = [];
1681
1682 foreach ( $calls as $call ) {
1683 call_user_func_array( [ $op, 'addVaryHeader' ], $call );
1684 }
1685 $this->assertEquals( $vary, $op->getVaryHeader(), 'Vary:' );
1686 $this->assertEquals( $key, $op->getKeyHeader(), 'Key:' );
1687 }
1688
1689 public function provideVaryHeaders() {
1690 // note: getKeyHeader() automatically adds Vary: Cookie
1691 return [
1692 [ // single header
1693 [
1694 [ 'Cookie' ],
1695 ],
1696 'Vary: Cookie',
1697 'Key: Cookie',
1698 ],
1699 [ // non-unique headers
1700 [
1701 [ 'Cookie' ],
1702 [ 'Accept-Language' ],
1703 [ 'Cookie' ],
1704 ],
1705 'Vary: Cookie, Accept-Language',
1706 'Key: Cookie,Accept-Language',
1707 ],
1708 [ // two headers with single options
1709 [
1710 [ 'Cookie', [ 'param=phpsessid' ] ],
1711 [ 'Accept-Language', [ 'substr=en' ] ],
1712 ],
1713 'Vary: Cookie, Accept-Language',
1714 'Key: Cookie;param=phpsessid,Accept-Language;substr=en',
1715 ],
1716 [ // one header with multiple options
1717 [
1718 [ 'Cookie', [ 'param=phpsessid', 'param=userId' ] ],
1719 ],
1720 'Vary: Cookie',
1721 'Key: Cookie;param=phpsessid;param=userId',
1722 ],
1723 [ // Duplicate option
1724 [
1725 [ 'Cookie', [ 'param=phpsessid' ] ],
1726 [ 'Cookie', [ 'param=phpsessid' ] ],
1727 [ 'Accept-Language', [ 'substr=en', 'substr=en' ] ],
1728 ],
1729 'Vary: Cookie, Accept-Language',
1730 'Key: Cookie;param=phpsessid,Accept-Language;substr=en',
1731 ],
1732 [ // Same header, different options
1733 [
1734 [ 'Cookie', [ 'param=phpsessid' ] ],
1735 [ 'Cookie', [ 'param=userId' ] ],
1736 ],
1737 'Vary: Cookie',
1738 'Key: Cookie;param=phpsessid;param=userId',
1739 ],
1740 ];
1741 }
1742
1743 /**
1744 * @dataProvider provideLinkHeaders
1745 *
1746 * @covers OutputPage::addLinkHeader
1747 * @covers OutputPage::getLinkHeader
1748 */
1749 public function testLinkHeaders( $headers, $result ) {
1750 $op = $this->newInstance();
1751
1752 foreach ( $headers as $header ) {
1753 $op->addLinkHeader( $header );
1754 }
1755
1756 $this->assertEquals( $result, $op->getLinkHeader() );
1757 }
1758
1759 public function provideLinkHeaders() {
1760 return [
1761 [
1762 [],
1763 false
1764 ],
1765 [
1766 [ '<https://foo/bar.jpg>;rel=preload;as=image' ],
1767 'Link: <https://foo/bar.jpg>;rel=preload;as=image',
1768 ],
1769 [
1770 [ '<https://foo/bar.jpg>;rel=preload;as=image','<https://foo/baz.jpg>;rel=preload;as=image' ],
1771 'Link: <https://foo/bar.jpg>;rel=preload;as=image,<https://foo/baz.jpg>;rel=preload;as=image',
1772 ],
1773 ];
1774 }
1775
1776 /**
1777 * See ResourceLoaderClientHtmlTest for full coverage.
1778 *
1779 * @dataProvider provideMakeResourceLoaderLink
1780 *
1781 * @covers OutputPage::makeResourceLoaderLink
1782 */
1783 public function testMakeResourceLoaderLink( $args, $expectedHtml ) {
1784 $this->setMwGlobals( [
1785 'wgResourceLoaderDebug' => false,
1786 'wgLoadScript' => 'http://127.0.0.1:8080/w/load.php',
1787 'wgCSPReportOnlyHeader' => true,
1788 ] );
1789 $class = new ReflectionClass( OutputPage::class );
1790 $method = $class->getMethod( 'makeResourceLoaderLink' );
1791 $method->setAccessible( true );
1792 $ctx = new RequestContext();
1793 $ctx->setSkin( SkinFactory::getDefaultInstance()->makeSkin( 'fallback' ) );
1794 $ctx->setLanguage( 'en' );
1795 $out = new OutputPage( $ctx );
1796 $nonce = $class->getProperty( 'CSPNonce' );
1797 $nonce->setAccessible( true );
1798 $nonce->setValue( $out, 'secret' );
1799 $rl = $out->getResourceLoader();
1800 $rl->setMessageBlobStore( new NullMessageBlobStore() );
1801 $rl->register( [
1802 'test.foo' => new ResourceLoaderTestModule( [
1803 'script' => 'mw.test.foo( { a: true } );',
1804 'styles' => '.mw-test-foo { content: "style"; }',
1805 ] ),
1806 'test.bar' => new ResourceLoaderTestModule( [
1807 'script' => 'mw.test.bar( { a: true } );',
1808 'styles' => '.mw-test-bar { content: "style"; }',
1809 ] ),
1810 'test.baz' => new ResourceLoaderTestModule( [
1811 'script' => 'mw.test.baz( { a: true } );',
1812 'styles' => '.mw-test-baz { content: "style"; }',
1813 ] ),
1814 'test.quux' => new ResourceLoaderTestModule( [
1815 'script' => 'mw.test.baz( { token: 123 } );',
1816 'styles' => '/* pref-animate=off */ .mw-icon { transition: none; }',
1817 'group' => 'private',
1818 ] ),
1819 'test.noscript' => new ResourceLoaderTestModule( [
1820 'styles' => '.stuff { color: red; }',
1821 'group' => 'noscript',
1822 ] ),
1823 'test.group.foo' => new ResourceLoaderTestModule( [
1824 'script' => 'mw.doStuff( "foo" );',
1825 'group' => 'foo',
1826 ] ),
1827 'test.group.bar' => new ResourceLoaderTestModule( [
1828 'script' => 'mw.doStuff( "bar" );',
1829 'group' => 'bar',
1830 ] ),
1831 ] );
1832 $links = $method->invokeArgs( $out, $args );
1833 $actualHtml = strval( $links );
1834 $this->assertEquals( $expectedHtml, $actualHtml );
1835 }
1836
1837 public static function provideMakeResourceLoaderLink() {
1838 // phpcs:disable Generic.Files.LineLength
1839 return [
1840 // Single only=scripts load
1841 [
1842 [ 'test.foo', ResourceLoaderModule::TYPE_SCRIPTS ],
1843 "<script nonce=\"secret\">(window.RLQ=window.RLQ||[]).push(function(){"
1844 . 'mw.loader.load("http://127.0.0.1:8080/w/load.php?debug=false\u0026lang=en\u0026modules=test.foo\u0026only=scripts\u0026skin=fallback");'
1845 . "});</script>"
1846 ],
1847 // Multiple only=styles load
1848 [
1849 [ [ 'test.baz', 'test.foo', 'test.bar' ], ResourceLoaderModule::TYPE_STYLES ],
1850
1851 '<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"/>'
1852 ],
1853 // Private embed (only=scripts)
1854 [
1855 [ 'test.quux', ResourceLoaderModule::TYPE_SCRIPTS ],
1856 "<script nonce=\"secret\">(window.RLQ=window.RLQ||[]).push(function(){"
1857 . "mw.test.baz({token:123});\nmw.loader.state({\"test.quux\":\"ready\"});"
1858 . "});</script>"
1859 ],
1860 // Load private module (combined)
1861 [
1862 [ 'test.quux', ResourceLoaderModule::TYPE_COMBINED ],
1863 "<script nonce=\"secret\">(window.RLQ=window.RLQ||[]).push(function(){"
1864 . "mw.loader.implement(\"test.quux@1ev0ijv\",function($,jQuery,require,module){"
1865 . "mw.test.baz({token:123});},{\"css\":[\".mw-icon{transition:none}"
1866 . "\"]});});</script>"
1867 ],
1868 // Load no modules
1869 [
1870 [ [], ResourceLoaderModule::TYPE_COMBINED ],
1871 '',
1872 ],
1873 // noscript group
1874 [
1875 [ 'test.noscript', ResourceLoaderModule::TYPE_STYLES ],
1876 '<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>'
1877 ],
1878 // Load two modules in separate groups
1879 [
1880 [ [ 'test.group.foo', 'test.group.bar' ], ResourceLoaderModule::TYPE_COMBINED ],
1881 "<script nonce=\"secret\">(window.RLQ=window.RLQ||[]).push(function(){"
1882 . 'mw.loader.load("http://127.0.0.1:8080/w/load.php?debug=false\u0026lang=en\u0026modules=test.group.bar\u0026skin=fallback");'
1883 . 'mw.loader.load("http://127.0.0.1:8080/w/load.php?debug=false\u0026lang=en\u0026modules=test.group.foo\u0026skin=fallback");'
1884 . "});</script>"
1885 ],
1886 ];
1887 // phpcs:enable
1888 }
1889
1890 /**
1891 * @dataProvider provideBuildExemptModules
1892 *
1893 * @covers OutputPage::buildExemptModules
1894 */
1895 public function testBuildExemptModules( array $exemptStyleModules, $expect ) {
1896 $this->setMwGlobals( [
1897 'wgResourceLoaderDebug' => false,
1898 'wgLoadScript' => '/w/load.php',
1899 // Stub wgCacheEpoch as it influences getVersionHash used for the
1900 // urls in the expected HTML
1901 'wgCacheEpoch' => '20140101000000',
1902 ] );
1903
1904 // Set up stubs
1905 $ctx = new RequestContext();
1906 $ctx->setSkin( SkinFactory::getDefaultInstance()->makeSkin( 'fallback' ) );
1907 $ctx->setLanguage( 'en' );
1908 $op = $this->getMockBuilder( OutputPage::class )
1909 ->setConstructorArgs( [ $ctx ] )
1910 ->setMethods( [ 'buildCssLinksArray' ] )
1911 ->getMock();
1912 $op->expects( $this->any() )
1913 ->method( 'buildCssLinksArray' )
1914 ->willReturn( [] );
1915 $rl = $op->getResourceLoader();
1916 $rl->setMessageBlobStore( new NullMessageBlobStore() );
1917
1918 // Register custom modules
1919 $rl->register( [
1920 'example.site.a' => new ResourceLoaderTestModule( [ 'group' => 'site' ] ),
1921 'example.site.b' => new ResourceLoaderTestModule( [ 'group' => 'site' ] ),
1922 'example.user' => new ResourceLoaderTestModule( [ 'group' => 'user' ] ),
1923 ] );
1924
1925 $op = TestingAccessWrapper::newFromObject( $op );
1926 $op->rlExemptStyleModules = $exemptStyleModules;
1927 $this->assertEquals(
1928 $expect,
1929 strval( $op->buildExemptModules() )
1930 );
1931 }
1932
1933 public static function provideBuildExemptModules() {
1934 // phpcs:disable Generic.Files.LineLength
1935 return [
1936 'empty' => [
1937 'exemptStyleModules' => [],
1938 '<meta name="ResourceLoaderDynamicStyles" content=""/>',
1939 ],
1940 'empty sets' => [
1941 'exemptStyleModules' => [ 'site' => [], 'noscript' => [], 'private' => [], 'user' => [] ],
1942 '<meta name="ResourceLoaderDynamicStyles" content=""/>',
1943 ],
1944 'default logged-out' => [
1945 'exemptStyleModules' => [ 'site' => [ 'site.styles' ] ],
1946 '<meta name="ResourceLoaderDynamicStyles" content=""/>' . "\n" .
1947 '<link rel="stylesheet" href="/w/load.php?debug=false&amp;lang=en&amp;modules=site.styles&amp;only=styles&amp;skin=fallback"/>',
1948 ],
1949 'default logged-in' => [
1950 'exemptStyleModules' => [ 'site' => [ 'site.styles' ], 'user' => [ 'user.styles' ] ],
1951 '<meta name="ResourceLoaderDynamicStyles" content=""/>' . "\n" .
1952 '<link rel="stylesheet" href="/w/load.php?debug=false&amp;lang=en&amp;modules=site.styles&amp;only=styles&amp;skin=fallback"/>' . "\n" .
1953 '<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"/>',
1954 ],
1955 'custom modules' => [
1956 'exemptStyleModules' => [
1957 'site' => [ 'site.styles', 'example.site.a', 'example.site.b' ],
1958 'user' => [ 'user.styles', 'example.user' ],
1959 ],
1960 '<meta name="ResourceLoaderDynamicStyles" content=""/>' . "\n" .
1961 '<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" .
1962 '<link rel="stylesheet" href="/w/load.php?debug=false&amp;lang=en&amp;modules=site.styles&amp;only=styles&amp;skin=fallback"/>' . "\n" .
1963 '<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" .
1964 '<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"/>',
1965 ],
1966 ];
1967 // phpcs:enable
1968 }
1969
1970 /**
1971 * @dataProvider provideTransformFilePath
1972 * @covers OutputPage::transformFilePath
1973 * @covers OutputPage::transformResourcePath
1974 */
1975 public function testTransformResourcePath( $baseDir, $basePath, $uploadDir = null,
1976 $uploadPath = null, $path = null, $expected = null
1977 ) {
1978 if ( $path === null ) {
1979 // Skip optional $uploadDir and $uploadPath
1980 $path = $uploadDir;
1981 $expected = $uploadPath;
1982 $uploadDir = "$baseDir/images";
1983 $uploadPath = "$basePath/images";
1984 }
1985 $this->setMwGlobals( 'IP', $baseDir );
1986 $conf = new HashConfig( [
1987 'ResourceBasePath' => $basePath,
1988 'UploadDirectory' => $uploadDir,
1989 'UploadPath' => $uploadPath,
1990 ] );
1991
1992 // Some of these paths don't exist and will cause warnings
1993 Wikimedia\suppressWarnings();
1994 $actual = OutputPage::transformResourcePath( $conf, $path );
1995 Wikimedia\restoreWarnings();
1996
1997 $this->assertEquals( $expected ?: $path, $actual );
1998 }
1999
2000 public static function provideTransformFilePath() {
2001 $baseDir = dirname( __DIR__ ) . '/data/media';
2002 return [
2003 // File that matches basePath, and exists. Hash found and appended.
2004 [
2005 'baseDir' => $baseDir, 'basePath' => '/w',
2006 '/w/test.jpg',
2007 '/w/test.jpg?edcf2'
2008 ],
2009 // File that matches basePath, but not found on disk. Empty query.
2010 [
2011 'baseDir' => $baseDir, 'basePath' => '/w',
2012 '/w/unknown.png',
2013 '/w/unknown.png?'
2014 ],
2015 // File not matching basePath. Ignored.
2016 [
2017 'baseDir' => $baseDir, 'basePath' => '/w',
2018 '/files/test.jpg'
2019 ],
2020 // Empty string. Ignored.
2021 [
2022 'baseDir' => $baseDir, 'basePath' => '/w',
2023 '',
2024 ''
2025 ],
2026 // Similar path, but with domain component. Ignored.
2027 [
2028 'baseDir' => $baseDir, 'basePath' => '/w',
2029 '//example.org/w/test.jpg'
2030 ],
2031 [
2032 'baseDir' => $baseDir, 'basePath' => '/w',
2033 'https://example.org/w/test.jpg'
2034 ],
2035 // Unrelated path with domain component. Ignored.
2036 [
2037 'baseDir' => $baseDir, 'basePath' => '/w',
2038 'https://example.org/files/test.jpg'
2039 ],
2040 [
2041 'baseDir' => $baseDir, 'basePath' => '/w',
2042 '//example.org/files/test.jpg'
2043 ],
2044 // Unrelated path with domain, and empty base path (root mw install). Ignored.
2045 [
2046 'baseDir' => $baseDir, 'basePath' => '',
2047 'https://example.org/files/test.jpg'
2048 ],
2049 [
2050 'baseDir' => $baseDir, 'basePath' => '',
2051 // T155310
2052 '//example.org/files/test.jpg'
2053 ],
2054 // Check UploadPath before ResourceBasePath (T155146)
2055 [
2056 'baseDir' => dirname( $baseDir ), 'basePath' => '',
2057 'uploadDir' => $baseDir, 'uploadPath' => '/images',
2058 '/images/test.jpg',
2059 '/images/test.jpg?edcf2'
2060 ],
2061 ];
2062 }
2063
2064 /**
2065 * Tests a particular case of transformCssMedia, using the given input, globals,
2066 * expected return, and message
2067 *
2068 * Asserts that $expectedReturn is returned.
2069 *
2070 * options['printableQuery'] - value of query string for printable, or omitted for none
2071 * options['handheldQuery'] - value of query string for handheld, or omitted for none
2072 * options['media'] - passed into the method under the same name
2073 * options['expectedReturn'] - expected return value
2074 * options['message'] - PHPUnit message for assertion
2075 *
2076 * @param array $args Key-value array of arguments as shown above
2077 */
2078 protected function assertTransformCssMediaCase( $args ) {
2079 $queryData = [];
2080 if ( isset( $args['printableQuery'] ) ) {
2081 $queryData['printable'] = $args['printableQuery'];
2082 }
2083
2084 if ( isset( $args['handheldQuery'] ) ) {
2085 $queryData['handheld'] = $args['handheldQuery'];
2086 }
2087
2088 $fauxRequest = new FauxRequest( $queryData, false );
2089 $this->setMwGlobals( [
2090 'wgRequest' => $fauxRequest,
2091 ] );
2092
2093 $actualReturn = OutputPage::transformCssMedia( $args['media'] );
2094 $this->assertSame( $args['expectedReturn'], $actualReturn, $args['message'] );
2095 }
2096
2097 /**
2098 * Tests print requests
2099 *
2100 * @covers OutputPage::transformCssMedia
2101 */
2102 public function testPrintRequests() {
2103 $this->assertTransformCssMediaCase( [
2104 'printableQuery' => '1',
2105 'media' => 'screen',
2106 'expectedReturn' => null,
2107 'message' => 'On printable request, screen returns null'
2108 ] );
2109
2110 $this->assertTransformCssMediaCase( [
2111 'printableQuery' => '1',
2112 'media' => self::SCREEN_MEDIA_QUERY,
2113 'expectedReturn' => null,
2114 'message' => 'On printable request, screen media query returns null'
2115 ] );
2116
2117 $this->assertTransformCssMediaCase( [
2118 'printableQuery' => '1',
2119 'media' => self::SCREEN_ONLY_MEDIA_QUERY,
2120 'expectedReturn' => null,
2121 'message' => 'On printable request, screen media query with only returns null'
2122 ] );
2123
2124 $this->assertTransformCssMediaCase( [
2125 'printableQuery' => '1',
2126 'media' => 'print',
2127 'expectedReturn' => '',
2128 'message' => 'On printable request, media print returns empty string'
2129 ] );
2130 }
2131
2132 /**
2133 * Tests screen requests, without either query parameter set
2134 *
2135 * @covers OutputPage::transformCssMedia
2136 */
2137 public function testScreenRequests() {
2138 $this->assertTransformCssMediaCase( [
2139 'media' => 'screen',
2140 'expectedReturn' => 'screen',
2141 'message' => 'On screen request, screen media type is preserved'
2142 ] );
2143
2144 $this->assertTransformCssMediaCase( [
2145 'media' => 'handheld',
2146 'expectedReturn' => 'handheld',
2147 'message' => 'On screen request, handheld media type is preserved'
2148 ] );
2149
2150 $this->assertTransformCssMediaCase( [
2151 'media' => self::SCREEN_MEDIA_QUERY,
2152 'expectedReturn' => self::SCREEN_MEDIA_QUERY,
2153 'message' => 'On screen request, screen media query is preserved.'
2154 ] );
2155
2156 $this->assertTransformCssMediaCase( [
2157 'media' => self::SCREEN_ONLY_MEDIA_QUERY,
2158 'expectedReturn' => self::SCREEN_ONLY_MEDIA_QUERY,
2159 'message' => 'On screen request, screen media query with only is preserved.'
2160 ] );
2161
2162 $this->assertTransformCssMediaCase( [
2163 'media' => 'print',
2164 'expectedReturn' => 'print',
2165 'message' => 'On screen request, print media type is preserved'
2166 ] );
2167 }
2168
2169 /**
2170 * Tests handheld behavior
2171 *
2172 * @covers OutputPage::transformCssMedia
2173 */
2174 public function testHandheld() {
2175 $this->assertTransformCssMediaCase( [
2176 'handheldQuery' => '1',
2177 'media' => 'handheld',
2178 'expectedReturn' => '',
2179 'message' => 'On request with handheld querystring and media is handheld, returns empty string'
2180 ] );
2181
2182 $this->assertTransformCssMediaCase( [
2183 'handheldQuery' => '1',
2184 'media' => 'screen',
2185 'expectedReturn' => null,
2186 'message' => 'On request with handheld querystring and media is screen, returns null'
2187 ] );
2188 }
2189
2190 /**
2191 * @return OutputPage
2192 */
2193 private function newInstance( $config = [], WebRequest $request = null, $options = [] ) {
2194 $context = new RequestContext();
2195
2196 $context->setConfig( new MultiConfig( [
2197 new HashConfig( $config + [
2198 'AppleTouchIcon' => false,
2199 'DisableLangConversion' => true,
2200 'EnableCanonicalServerLink' => false,
2201 'Favicon' => false,
2202 'Feed' => false,
2203 'LanguageCode' => false,
2204 'ReferrerPolicy' => false,
2205 'RightsPage' => false,
2206 'RightsUrl' => false,
2207 'UniversalEditButton' => false,
2208 ] ),
2209 $context->getConfig()
2210 ] ) );
2211
2212 if ( !in_array( 'notitle', (array)$options ) ) {
2213 $context->setTitle( Title::newFromText( 'My test page' ) );
2214 }
2215
2216 if ( $request ) {
2217 $context->setRequest( $request );
2218 }
2219
2220 return new OutputPage( $context );
2221 }
2222 }
2223
2224 /**
2225 * MessageBlobStore that doesn't do anything
2226 */
2227 class NullMessageBlobStore extends MessageBlobStore {
2228 public function get( ResourceLoader $resourceLoader, $modules, $lang ) {
2229 return [];
2230 }
2231
2232 public function updateModule( $name, ResourceLoaderModule $module, $lang ) {
2233 }
2234
2235 public function updateMessage( $key ) {
2236 }
2237
2238 public function clear() {
2239 }
2240 }