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