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