Merge "FauxRequest: don’t override getValues()"
[lhc/web/wiklou.git] / tests / phpunit / includes / resourceloader / ResourceLoaderTest.php
1 <?php
2
3 use Wikimedia\TestingAccessWrapper;
4 use MediaWiki\MediaWikiServices;
5
6 class ResourceLoaderTest extends ResourceLoaderTestCase {
7
8 protected function setUp() {
9 parent::setUp();
10
11 $this->setMwGlobals( [
12 'wgShowExceptionDetails' => true,
13 ] );
14 }
15
16 /**
17 * Ensure the ResourceLoaderRegisterModules hook is called.
18 * @coversNothing
19 */
20 public function testServiceWiring() {
21 $ranHook = 0;
22 $this->setMwGlobals( 'wgHooks', [
23 'ResourceLoaderRegisterModules' => [
24 function ( &$resourceLoader ) use ( &$ranHook ) {
25 $ranHook++;
26 }
27 ]
28 ] );
29
30 MediaWikiServices::getInstance()->getResourceLoader();
31
32 $this->assertSame( 1, $ranHook, 'Hook was called' );
33 }
34
35 public static function provideInvalidModuleName() {
36 return [
37 'name with 300 chars' => [ str_repeat( 'x', 300 ) ],
38 'name with bang' => [ 'this!that' ],
39 'name with comma' => [ 'this,that' ],
40 'name with pipe' => [ 'this|that' ],
41 ];
42 }
43
44 public static function provideValidModuleName() {
45 return [
46 'empty string' => [ '' ],
47 'simple name' => [ 'this.and-that2' ],
48 'name with 100 chars' => [ str_repeat( 'x', 100 ) ],
49 'name with hash' => [ 'this#that' ],
50 'name with slash' => [ 'this/that' ],
51 'name with at' => [ 'this@that' ],
52 ];
53 }
54
55 /**
56 * @dataProvider provideInvalidModuleName
57 * @covers ResourceLoader
58 */
59 public function testIsValidModuleName_invalid( $name ) {
60 $this->assertFalse( ResourceLoader::isValidModuleName( $name ) );
61 }
62
63 /**
64 * @dataProvider provideValidModuleName
65 * @covers ResourceLoader
66 */
67 public function testIsValidModuleName_valid( $name ) {
68 $this->assertTrue( ResourceLoader::isValidModuleName( $name ) );
69 }
70
71 /**
72 * @covers ResourceLoader::register
73 * @covers ResourceLoader::getModule
74 */
75 public function testRegisterValidArray() {
76 $resourceLoader = new EmptyResourceLoader();
77 // Covers case of register() setting $rl->moduleInfos,
78 // but $rl->modules lazy-populated by getModule()
79 $resourceLoader->register( 'test', [ 'class' => ResourceLoaderTestModule::class ] );
80 $this->assertInstanceOf(
81 ResourceLoaderTestModule::class,
82 $resourceLoader->getModule( 'test' )
83 );
84 }
85
86 /**
87 * @covers ResourceLoader::register
88 * @group medium
89 */
90 public function testRegisterEmptyString() {
91 $resourceLoader = new EmptyResourceLoader();
92 $resourceLoader->register( '', [ 'class' => ResourceLoaderTestModule::class ] );
93 $this->assertInstanceOf(
94 ResourceLoaderTestModule::class,
95 $resourceLoader->getModule( '' )
96 );
97 }
98
99 /**
100 * @covers ResourceLoader::register
101 * @group medium
102 */
103 public function testRegisterInvalidName() {
104 $resourceLoader = new EmptyResourceLoader();
105 $this->setExpectedException( MWException::class, "name 'test!invalid' is invalid" );
106 $resourceLoader->register( 'test!invalid', [] );
107 }
108
109 /**
110 * @covers ResourceLoader::register
111 */
112 public function testRegisterInvalidType() {
113 $resourceLoader = new EmptyResourceLoader();
114 $this->setExpectedException( InvalidArgumentException::class, 'Invalid module info' );
115 $resourceLoader->register( 'test', new stdClass() );
116 }
117
118 /**
119 * @covers ResourceLoader::register
120 */
121 public function testRegisterDuplicate() {
122 $logger = $this->getMockBuilder( Psr\Log\LoggerInterface::class )->getMock();
123 $logger->expects( $this->once() )
124 ->method( 'warning' );
125 $resourceLoader = new EmptyResourceLoader( null, $logger );
126
127 $resourceLoader->register( 'test', [ 'class' => ResourceLoaderSkinModule::class ] );
128 $resourceLoader->register( 'test', [ 'class' => ResourceLoaderStartUpModule::class ] );
129 $this->assertInstanceOf(
130 ResourceLoaderStartUpModule::class,
131 $resourceLoader->getModule( 'test' ),
132 'last one wins'
133 );
134 }
135
136 /**
137 * @covers ResourceLoader::getModuleNames
138 */
139 public function testGetModuleNames() {
140 // Use an empty one so that core and extension modules don't get in.
141 $resourceLoader = new EmptyResourceLoader();
142 $resourceLoader->register( 'test.foo', [] );
143 $resourceLoader->register( 'test.bar', [] );
144 $this->assertEquals(
145 [ 'startup', 'test.foo', 'test.bar' ],
146 $resourceLoader->getModuleNames()
147 );
148 }
149
150 public function provideTestIsFileModule() {
151 $fileModuleObj = $this->createMock( ResourceLoaderFileModule::class );
152 return [
153 'factory ignored' => [ false,
154 [
155 'factory' => function () {
156 return new ResourceLoaderTestModule();
157 }
158 ]
159 ],
160 'factory ignored (actual FileModule)' => [ false,
161 [
162 'factory' => function () use ( $fileModuleObj ) {
163 return $fileModuleObj;
164 }
165 ]
166 ],
167 'simple empty' => [ true,
168 []
169 ],
170 'simple scripts' => [ true,
171 [ 'scripts' => 'example.js' ]
172 ],
173 'simple scripts with targets' => [ true, [
174 'scripts' => [ 'a.js', 'b.js' ],
175 'targets' => [ 'desktop', 'mobile' ],
176 ] ],
177 'FileModule' => [ true,
178 [ 'class' => ResourceLoaderFileModule::class, 'scripts' => 'example.js' ]
179 ],
180 'TestModule' => [ false,
181 [ 'class' => ResourceLoaderTestModule::class, 'scripts' => 'example.js' ]
182 ],
183 'SkinModule (FileModule subclass)' => [ true,
184 [ 'class' => ResourceLoaderSkinModule::class, 'scripts' => 'example.js' ]
185 ],
186 'WikiModule' => [ false, [
187 'class' => ResourceLoaderWikiModule::class,
188 'scripts' => [ 'MediaWiki:Example.js' ],
189 ] ],
190 ];
191 }
192
193 /**
194 * @dataProvider provideTestIsFileModule
195 * @covers ResourceLoader::isFileModule
196 */
197 public function testIsFileModule( $expected, $module ) {
198 $rl = TestingAccessWrapper::newFromObject( new EmptyResourceLoader() );
199 $rl->register( 'test', $module );
200 $this->assertSame( $expected, $rl->isFileModule( 'test' ) );
201 }
202
203 /**
204 * @covers ResourceLoader::isFileModule
205 */
206 public function testIsFileModuleUnknown() {
207 $rl = TestingAccessWrapper::newFromObject( new EmptyResourceLoader() );
208 $this->assertSame( false, $rl->isFileModule( 'unknown' ) );
209 }
210
211 /**
212 * @covers ResourceLoader::isModuleRegistered
213 */
214 public function testIsModuleRegistered() {
215 $rl = new EmptyResourceLoader();
216 $rl->register( 'test', [] );
217 $this->assertTrue( $rl->isModuleRegistered( 'test' ) );
218 $this->assertFalse( $rl->isModuleRegistered( 'test.unknown' ) );
219 }
220
221 /**
222 * @covers ResourceLoader::getModule
223 */
224 public function testGetModuleUnknown() {
225 $rl = new EmptyResourceLoader();
226 $this->assertSame( null, $rl->getModule( 'test' ) );
227 }
228
229 /**
230 * @covers ResourceLoader::getModule
231 */
232 public function testGetModuleClass() {
233 $rl = new EmptyResourceLoader();
234 $rl->register( 'test', [ 'class' => ResourceLoaderTestModule::class ] );
235 $this->assertInstanceOf(
236 ResourceLoaderTestModule::class,
237 $rl->getModule( 'test' )
238 );
239 }
240
241 /**
242 * @covers ResourceLoader::getModule
243 */
244 public function testGetModuleFactory() {
245 $factory = function ( array $info ) {
246 $this->assertArrayHasKey( 'kitten', $info );
247 return new ResourceLoaderTestModule( $info );
248 };
249
250 $rl = new EmptyResourceLoader();
251 $rl->register( 'test', [ 'factory' => $factory, 'kitten' => 'little ball of fur' ] );
252 $this->assertInstanceOf(
253 ResourceLoaderTestModule::class,
254 $rl->getModule( 'test' )
255 );
256 }
257
258 /**
259 * @covers ResourceLoader::getModule
260 */
261 public function testGetModuleClassDefault() {
262 $rl = new EmptyResourceLoader();
263 $rl->register( 'test', [] );
264 $this->assertInstanceOf(
265 ResourceLoaderFileModule::class,
266 $rl->getModule( 'test' ),
267 'Array-style module registrations default to FileModule'
268 );
269 }
270
271 /**
272 * @covers ResourceLoader::getLessCompiler
273 */
274 public function testLessImportDirs() {
275 $rl = new EmptyResourceLoader();
276 $lc = $rl->getLessCompiler( [ 'foo' => '2px', 'Foo' => '#eeeeee' ] );
277 $basePath = dirname( dirname( __DIR__ ) ) . '/data/less';
278 $lc->SetImportDirs( [
279 "$basePath/common" => '',
280 ] );
281 $css = $lc->parseFile( "$basePath/module/use-import-dir.less" )->getCss();
282 $this->assertStringEqualsFile( "$basePath/module/styles.css", $css );
283 }
284
285 public static function providePackedModules() {
286 return [
287 [
288 'Example from makePackedModulesString doc comment',
289 [ 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' ],
290 'foo.bar,baz|bar.baz,quux',
291 ],
292 [
293 'Example from expandModuleNames doc comment',
294 [ 'jquery.foo', 'jquery.bar', 'jquery.ui.baz', 'jquery.ui.quux' ],
295 'jquery.foo,bar|jquery.ui.baz,quux',
296 ],
297 [
298 'Regression fixed in r87497 (7fee86c38e) with dotless names',
299 [ 'foo', 'bar', 'baz' ],
300 'foo,bar,baz',
301 ],
302 [
303 'Prefixless modules after a prefixed module',
304 [ 'single.module', 'foobar', 'foobaz' ],
305 'single.module|foobar,foobaz',
306 ],
307 [
308 'Ordering',
309 [ 'foo', 'foo.baz', 'baz.quux', 'foo.bar' ],
310 'foo|foo.baz,bar|baz.quux',
311 [ 'foo', 'foo.baz', 'foo.bar', 'baz.quux' ],
312 ]
313 ];
314 }
315
316 /**
317 * @dataProvider providePackedModules
318 * @covers ResourceLoader::makePackedModulesString
319 */
320 public function testMakePackedModulesString( $desc, $modules, $packed ) {
321 $this->assertEquals( $packed, ResourceLoader::makePackedModulesString( $modules ), $desc );
322 }
323
324 /**
325 * @dataProvider providePackedModules
326 * @covers ResourceLoader::expandModuleNames
327 */
328 public function testExpandModuleNames( $desc, $modules, $packed, $unpacked = null ) {
329 $this->assertEquals(
330 $unpacked ?: $modules,
331 ResourceLoader::expandModuleNames( $packed ),
332 $desc
333 );
334 }
335
336 public static function provideAddSource() {
337 return [
338 [ 'foowiki', 'https://example.org/w/load.php', 'foowiki' ],
339 [ 'foowiki', [ 'loadScript' => 'https://example.org/w/load.php' ], 'foowiki' ],
340 [
341 [
342 'foowiki' => 'https://example.org/w/load.php',
343 'bazwiki' => 'https://example.com/w/load.php',
344 ],
345 null,
346 [ 'foowiki', 'bazwiki' ]
347 ]
348 ];
349 }
350
351 /**
352 * @dataProvider provideAddSource
353 * @covers ResourceLoader::addSource
354 * @covers ResourceLoader::getSources
355 */
356 public function testAddSource( $name, $info, $expected ) {
357 $rl = new EmptyResourceLoader;
358 $rl->addSource( $name, $info );
359 if ( is_array( $expected ) ) {
360 foreach ( $expected as $source ) {
361 $this->assertArrayHasKey( $source, $rl->getSources() );
362 }
363 } else {
364 $this->assertArrayHasKey( $expected, $rl->getSources() );
365 }
366 }
367
368 /**
369 * @covers ResourceLoader::addSource
370 */
371 public function testAddSourceDupe() {
372 $rl = new EmptyResourceLoader;
373 $this->setExpectedException(
374 MWException::class, 'ResourceLoader duplicate source addition error'
375 );
376 $rl->addSource( 'foo', 'https://example.org/w/load.php' );
377 $rl->addSource( 'foo', 'https://example.com/w/load.php' );
378 }
379
380 /**
381 * @covers ResourceLoader::addSource
382 */
383 public function testAddSourceInvalid() {
384 $rl = new EmptyResourceLoader;
385 $this->setExpectedException( MWException::class, 'with no "loadScript" key' );
386 $rl->addSource( 'foo', [ 'x' => 'https://example.org/w/load.php' ] );
387 }
388
389 public static function provideLoaderImplement() {
390 return [
391 [ [
392 'title' => 'Implement scripts, styles and messages',
393
394 'name' => 'test.example',
395 'scripts' => 'mw.example();',
396 'styles' => [ 'css' => [ '.mw-example {}' ] ],
397 'messages' => [ 'example' => '' ],
398 'templates' => [],
399
400 'expected' => 'mw.loader.implement( "test.example", function ( $, jQuery, require, module ) {
401 mw.example();
402 }, {
403 "css": [
404 ".mw-example {}"
405 ]
406 }, {
407 "example": ""
408 } );',
409 ] ],
410 [ [
411 'title' => 'Implement scripts',
412
413 'name' => 'test.example',
414 'scripts' => 'mw.example();',
415 'styles' => [],
416
417 'expected' => 'mw.loader.implement( "test.example", function ( $, jQuery, require, module ) {
418 mw.example();
419 } );',
420 ] ],
421 [ [
422 'title' => 'Implement styles',
423
424 'name' => 'test.example',
425 'scripts' => [],
426 'styles' => [ 'css' => [ '.mw-example {}' ] ],
427
428 'expected' => 'mw.loader.implement( "test.example", [], {
429 "css": [
430 ".mw-example {}"
431 ]
432 } );',
433 ] ],
434 [ [
435 'title' => 'Implement scripts and messages',
436
437 'name' => 'test.example',
438 'scripts' => 'mw.example();',
439 'messages' => [ 'example' => '' ],
440
441 'expected' => 'mw.loader.implement( "test.example", function ( $, jQuery, require, module ) {
442 mw.example();
443 }, {}, {
444 "example": ""
445 } );',
446 ] ],
447 [ [
448 'title' => 'Implement scripts and templates',
449
450 'name' => 'test.example',
451 'scripts' => 'mw.example();',
452 'templates' => [ 'example.html' => '' ],
453
454 'expected' => 'mw.loader.implement( "test.example", function ( $, jQuery, require, module ) {
455 mw.example();
456 }, {}, {}, {
457 "example.html": ""
458 } );',
459 ] ],
460 [ [
461 'title' => 'Implement unwrapped user script',
462
463 'name' => 'user',
464 'scripts' => 'mw.example( 1 );',
465 'wrap' => false,
466
467 'expected' => 'mw.loader.implement( "user", "mw.example( 1 );" );',
468 ] ],
469 [ [
470 'title' => 'Implement multi-file script',
471
472 'name' => 'test.multifile',
473 'scripts' => [
474 'files' => [
475 'one.js' => [
476 'type' => 'script',
477 'content' => 'mw.example( 1 );',
478 ],
479 'two.json' => [
480 'type' => 'data',
481 'content' => [ 'n' => 2 ],
482 ],
483 'three.js' => [
484 'type' => 'script',
485 'content' => 'mw.example( 3 );'
486 ],
487 ],
488 'main' => 'three.js',
489 ],
490
491 'expected' => <<<END
492 mw.loader.implement( "test.multifile", {
493 "main": "three.js",
494 "files": {
495 "one.js": function ( require, module ) {
496 mw.example( 1 );
497 },
498 "two.json": {
499 "n": 2
500 },
501 "three.js": function ( require, module ) {
502 mw.example( 3 );
503 }
504 }
505 } );
506 END
507 ] ],
508 ];
509 }
510
511 /**
512 * @dataProvider provideLoaderImplement
513 * @covers ResourceLoader::makeLoaderImplementScript
514 * @covers ResourceLoader::trimArray
515 */
516 public function testMakeLoaderImplementScript( $case ) {
517 $case += [
518 'wrap' => true,
519 'styles' => [], 'templates' => [], 'messages' => new XmlJsCode( '{}' ), 'packageFiles' => [],
520 ];
521 ResourceLoader::clearCache();
522 $this->setMwGlobals( 'wgResourceLoaderDebug', true );
523
524 $rl = TestingAccessWrapper::newFromClass( ResourceLoader::class );
525 $this->assertEquals(
526 $case['expected'],
527 $rl->makeLoaderImplementScript(
528 $case['name'],
529 ( $case['wrap'] && is_string( $case['scripts'] ) )
530 ? new XmlJsCode( $case['scripts'] )
531 : $case['scripts'],
532 $case['styles'],
533 $case['messages'],
534 $case['templates'],
535 $case['packageFiles']
536 )
537 );
538 }
539
540 /**
541 * @covers ResourceLoader::makeLoaderImplementScript
542 */
543 public function testMakeLoaderImplementScriptInvalid() {
544 $this->setExpectedException( MWException::class, 'Invalid scripts error' );
545 $rl = TestingAccessWrapper::newFromClass( ResourceLoader::class );
546 $rl->makeLoaderImplementScript(
547 'test', // name
548 123, // scripts
549 null, // styles
550 null, // messages
551 null, // templates
552 null // package files
553 );
554 }
555
556 /**
557 * @covers ResourceLoader::makeLoaderRegisterScript
558 */
559 public function testMakeLoaderRegisterScript() {
560 $this->assertEquals(
561 'mw.loader.register([
562 [
563 "test.name",
564 "1234567"
565 ]
566 ]);',
567 ResourceLoader::makeLoaderRegisterScript( [
568 [ 'test.name', '1234567' ],
569 ] ),
570 'Nested array parameter'
571 );
572
573 $this->assertEquals(
574 'mw.loader.register([
575 [
576 "test.foo",
577 "100"
578 ],
579 [
580 "test.bar",
581 "200",
582 [
583 "test.unknown"
584 ]
585 ],
586 [
587 "test.baz",
588 "300",
589 [
590 3,
591 0
592 ]
593 ],
594 [
595 "test.quux",
596 "400",
597 [],
598 null,
599 null,
600 "return true;"
601 ]
602 ]);',
603 ResourceLoader::makeLoaderRegisterScript( [
604 [ 'test.foo', '100' , [], null, null ],
605 [ 'test.bar', '200', [ 'test.unknown' ], null ],
606 [ 'test.baz', '300', [ 'test.quux', 'test.foo' ], null ],
607 [ 'test.quux', '400', [], null, null, 'return true;' ],
608 ] ),
609 'Compact dependency indexes'
610 );
611 }
612
613 /**
614 * @covers ResourceLoader::makeLoaderSourcesScript
615 */
616 public function testMakeLoaderSourcesScript() {
617 $this->assertEquals(
618 'mw.loader.addSource({
619 "local": "/w/load.php"
620 });',
621 ResourceLoader::makeLoaderSourcesScript( 'local', '/w/load.php' )
622 );
623 $this->assertEquals(
624 'mw.loader.addSource({
625 "local": "/w/load.php"
626 });',
627 ResourceLoader::makeLoaderSourcesScript( [ 'local' => '/w/load.php' ] )
628 );
629 $this->assertEquals(
630 'mw.loader.addSource({
631 "local": "/w/load.php",
632 "example": "https://example.org/w/load.php"
633 });',
634 ResourceLoader::makeLoaderSourcesScript( [
635 'local' => '/w/load.php',
636 'example' => 'https://example.org/w/load.php'
637 ] )
638 );
639 $this->assertEquals(
640 'mw.loader.addSource([]);',
641 ResourceLoader::makeLoaderSourcesScript( [] )
642 );
643 }
644
645 private static function fakeSources() {
646 return [
647 'examplewiki' => [
648 'loadScript' => '//example.org/w/load.php',
649 'apiScript' => '//example.org/w/api.php',
650 ],
651 'example2wiki' => [
652 'loadScript' => '//example.com/w/load.php',
653 'apiScript' => '//example.com/w/api.php',
654 ],
655 ];
656 }
657
658 /**
659 * @covers ResourceLoader::getLoadScript
660 */
661 public function testGetLoadScript() {
662 $rl = new EmptyResourceLoader();
663 $sources = self::fakeSources();
664 $rl->addSource( $sources );
665 foreach ( [ 'examplewiki', 'example2wiki' ] as $name ) {
666 $this->assertEquals( $rl->getLoadScript( $name ), $sources[$name]['loadScript'] );
667 }
668
669 try {
670 $rl->getLoadScript( 'thiswasneverreigstered' );
671 $this->assertTrue( false, 'ResourceLoader::getLoadScript should have thrown an exception' );
672 } catch ( MWException $e ) {
673 $this->assertTrue( true );
674 }
675 }
676
677 protected function getFailFerryMock( $getter = 'getScript' ) {
678 $mock = $this->getMockBuilder( ResourceLoaderTestModule::class )
679 ->setMethods( [ $getter ] )
680 ->getMock();
681 $mock->method( $getter )->will( $this->throwException(
682 new Exception( 'Ferry not found' )
683 ) );
684 return $mock;
685 }
686
687 protected function getSimpleModuleMock( $script = '' ) {
688 $mock = $this->getMockBuilder( ResourceLoaderTestModule::class )
689 ->setMethods( [ 'getScript' ] )
690 ->getMock();
691 $mock->method( 'getScript' )->willReturn( $script );
692 return $mock;
693 }
694
695 protected function getSimpleStyleModuleMock( $styles = '' ) {
696 $mock = $this->getMockBuilder( ResourceLoaderTestModule::class )
697 ->setMethods( [ 'getStyles' ] )
698 ->getMock();
699 $mock->method( 'getStyles' )->willReturn( [ '' => $styles ] );
700 return $mock;
701 }
702
703 /**
704 * @covers ResourceLoader::getCombinedVersion
705 */
706 public function testGetCombinedVersion() {
707 $rl = $this->getMockBuilder( EmptyResourceLoader::class )
708 // Disable log from outputErrorAndLog
709 ->setMethods( [ 'outputErrorAndLog' ] )->getMock();
710 $rl->register( [
711 'foo' => [ 'class' => ResourceLoaderTestModule::class ],
712 'ferry' => [
713 'factory' => function () {
714 return self::getFailFerryMock();
715 }
716 ],
717 'bar' => [ 'class' => ResourceLoaderTestModule::class ],
718 ] );
719 $context = $this->getResourceLoaderContext( [], $rl );
720
721 $this->assertSame(
722 '',
723 $rl->getCombinedVersion( $context, [] ),
724 'empty list'
725 );
726
727 $this->assertEquals(
728 self::BLANK_COMBI,
729 $rl->getCombinedVersion( $context, [ 'foo' ] ),
730 'compute foo'
731 );
732
733 // Verify that getCombinedVersion() does not throw when ferry fails.
734 // Instead it gracefully continues to combine the remaining modules.
735 $this->assertEquals(
736 ResourceLoader::makeHash( self::BLANK_VERSION . self::BLANK_VERSION ),
737 $rl->getCombinedVersion( $context, [ 'foo', 'ferry', 'bar' ] ),
738 'compute foo+ferry+bar (T152266)'
739 );
740 }
741
742 public static function provideMakeModuleResponseConcat() {
743 $testcases = [
744 [
745 'modules' => [
746 'foo' => 'foo()',
747 ],
748 'expected' => "foo()\n" . 'mw.loader.state({
749 "foo": "ready"
750 });',
751 'minified' => "foo()\n" . 'mw.loader.state({"foo":"ready"});',
752 'message' => 'Script without semi-colon',
753 ],
754 [
755 'modules' => [
756 'foo' => 'foo()',
757 'bar' => 'bar()',
758 ],
759 'expected' => "foo()\nbar()\n" . 'mw.loader.state({
760 "foo": "ready",
761 "bar": "ready"
762 });',
763 'minified' => "foo()\nbar()\n" . 'mw.loader.state({"foo":"ready","bar":"ready"});',
764 'message' => 'Two scripts without semi-colon',
765 ],
766 [
767 'modules' => [
768 'foo' => "foo()\n// bar();"
769 ],
770 'expected' => "foo()\n// bar();\n" . 'mw.loader.state({
771 "foo": "ready"
772 });',
773 'minified' => "foo()\n" . 'mw.loader.state({"foo":"ready"});',
774 'message' => 'Script with semi-colon in comment (T162719)',
775 ],
776 ];
777 $ret = [];
778 foreach ( $testcases as $i => $case ) {
779 $ret["#$i"] = [
780 $case['modules'],
781 $case['expected'],
782 true, // debug
783 $case['message'],
784 ];
785 $ret["#$i (minified)"] = [
786 $case['modules'],
787 $case['minified'],
788 false, // debug
789 $case['message'],
790 ];
791 }
792 return $ret;
793 }
794
795 /**
796 * Verify how multiple scripts and mw.loader.state() calls are concatenated.
797 *
798 * @dataProvider provideMakeModuleResponseConcat
799 * @covers ResourceLoader::makeModuleResponse
800 */
801 public function testMakeModuleResponseConcat( $scripts, $expected, $debug, $message = null ) {
802 $rl = new EmptyResourceLoader();
803 $modules = array_map( function ( $script ) {
804 return self::getSimpleModuleMock( $script );
805 }, $scripts );
806
807 $context = $this->getResourceLoaderContext(
808 [
809 'modules' => implode( '|', array_keys( $modules ) ),
810 'only' => 'scripts',
811 'debug' => $debug ? 'true' : 'false',
812 ],
813 $rl
814 );
815
816 $response = $rl->makeModuleResponse( $context, $modules );
817 $this->assertSame( [], $rl->getErrors(), 'Errors' );
818 $this->assertEquals( $expected, $response, $message ?: 'Response' );
819 }
820
821 /**
822 * @covers ResourceLoader::makeModuleResponse
823 */
824 public function testMakeModuleResponseEmpty() {
825 $rl = new EmptyResourceLoader();
826 $context = $this->getResourceLoaderContext(
827 [ 'modules' => '', 'only' => 'scripts' ],
828 $rl
829 );
830
831 $response = $rl->makeModuleResponse( $context, [] );
832 $this->assertSame( [], $rl->getErrors(), 'Errors' );
833 $this->assertRegExp( '/^\/\*.+no modules were requested.+\*\/$/ms', $response );
834 }
835
836 /**
837 * Verify that when building module content in a load.php response,
838 * an exception from one module will not break script output from
839 * other modules.
840 *
841 * @covers ResourceLoader::makeModuleResponse
842 */
843 public function testMakeModuleResponseError() {
844 $modules = [
845 'foo' => self::getSimpleModuleMock( 'foo();' ),
846 'ferry' => self::getFailFerryMock(),
847 'bar' => self::getSimpleModuleMock( 'bar();' ),
848 ];
849 $rl = new EmptyResourceLoader();
850 $context = $this->getResourceLoaderContext(
851 [
852 'modules' => 'foo|ferry|bar',
853 'only' => 'scripts',
854 ],
855 $rl
856 );
857
858 // Disable log from makeModuleResponse via outputErrorAndLog
859 $this->setLogger( 'exception', new Psr\Log\NullLogger() );
860
861 $response = $rl->makeModuleResponse( $context, $modules );
862 $errors = $rl->getErrors();
863
864 $this->assertCount( 1, $errors );
865 $this->assertRegExp( '/Ferry not found/', $errors[0] );
866 $this->assertEquals(
867 "foo();\nbar();\n" . 'mw.loader.state({
868 "ferry": "error",
869 "foo": "ready",
870 "bar": "ready"
871 });',
872 $response
873 );
874 }
875
876 /**
877 * Verify that exceptions in PHP for one module will not break others
878 * (stylesheet response).
879 *
880 * @covers ResourceLoader::makeModuleResponse
881 */
882 public function testMakeModuleResponseErrorCSS() {
883 $modules = [
884 'foo' => self::getSimpleStyleModuleMock( '.foo{}' ),
885 'ferry' => self::getFailFerryMock( 'getStyles' ),
886 'bar' => self::getSimpleStyleModuleMock( '.bar{}' ),
887 ];
888 $rl = new EmptyResourceLoader();
889 $context = $this->getResourceLoaderContext(
890 [
891 'modules' => 'foo|ferry|bar',
892 'only' => 'styles',
893 'debug' => 'false',
894 ],
895 $rl
896 );
897
898 // Disable log from makeModuleResponse via outputErrorAndLog
899 $this->setLogger( 'exception', new Psr\Log\NullLogger() );
900
901 $response = $rl->makeModuleResponse( $context, $modules );
902 $errors = $rl->getErrors();
903
904 $this->assertCount( 2, $errors );
905 $this->assertRegExp( '/Ferry not found/', $errors[0] );
906 $this->assertRegExp( '/Problem.+"ferry":\s*"error"/ms', $errors[1] );
907 $this->assertEquals(
908 '.foo{}.bar{}',
909 $response
910 );
911 }
912
913 /**
914 * Verify that when building the startup module response,
915 * an exception from one module class will not break the entire
916 * startup module response. See T152266.
917 *
918 * @covers ResourceLoader::makeModuleResponse
919 */
920 public function testMakeModuleResponseStartupError() {
921 // This is an integration test that uses a lot of MediaWiki state,
922 // provide the full Config object here.
923 $rl = new EmptyResourceLoader( MediaWikiServices::getInstance()->getMainConfig() );
924 $rl->register( [
925 'foo' => [ 'factory' => function () {
926 return self::getSimpleModuleMock( 'foo();' );
927 } ],
928 'ferry' => [ 'factory' => function () {
929 return self::getFailFerryMock();
930 } ],
931 'bar' => [ 'factory' => function () {
932 return self::getSimpleModuleMock( 'bar();' );
933 } ],
934 ] );
935 $context = $this->getResourceLoaderContext(
936 [
937 'modules' => 'startup',
938 'only' => 'scripts',
939 ],
940 $rl
941 );
942
943 $this->assertEquals(
944 [ 'startup', 'foo', 'ferry', 'bar' ],
945 $rl->getModuleNames(),
946 'getModuleNames'
947 );
948
949 // Disable log from makeModuleResponse via outputErrorAndLog
950 $this->setLogger( 'exception', new Psr\Log\NullLogger() );
951
952 $modules = [ 'startup' => $rl->getModule( 'startup' ) ];
953 $response = $rl->makeModuleResponse( $context, $modules );
954 $errors = $rl->getErrors();
955
956 $this->assertRegExp( '/Ferry not found/', $errors[0] );
957 $this->assertCount( 1, $errors );
958 $this->assertRegExp(
959 '/isCompatible.*window\.RLQ/s',
960 $response,
961 'startup response undisrupted (T152266)'
962 );
963 $this->assertRegExp(
964 '/register\([^)]+"ferry",\s*""/s',
965 $response,
966 'startup response registers broken module'
967 );
968 $this->assertRegExp(
969 '/state\([^)]+"ferry":\s*"error"/s',
970 $response,
971 'startup response sets state to error'
972 );
973 }
974
975 /**
976 * Integration test for modules sending extra HTTP response headers.
977 *
978 * @covers ResourceLoaderModule::getHeaders
979 * @covers ResourceLoaderModule::buildContent
980 * @covers ResourceLoader::makeModuleResponse
981 */
982 public function testMakeModuleResponseExtraHeaders() {
983 $module = $this->getMockBuilder( ResourceLoaderTestModule::class )
984 ->setMethods( [ 'getPreloadLinks' ] )->getMock();
985 $module->method( 'getPreloadLinks' )->willReturn( [
986 'https://example.org/script.js' => [ 'as' => 'script' ],
987 ] );
988
989 $rl = new EmptyResourceLoader();
990 $context = $this->getResourceLoaderContext(
991 [ 'modules' => 'foo', 'only' => 'scripts' ],
992 $rl
993 );
994
995 $modules = [ 'foo' => $module ];
996 $response = $rl->makeModuleResponse( $context, $modules );
997 $extraHeaders = TestingAccessWrapper::newFromObject( $rl )->extraHeaders;
998
999 $this->assertEquals(
1000 [
1001 'Link: <https://example.org/script.js>;rel=preload;as=script'
1002 ],
1003 $extraHeaders,
1004 'Extra headers'
1005 );
1006 }
1007
1008 /**
1009 * @covers ResourceLoaderModule::getHeaders
1010 * @covers ResourceLoaderModule::buildContent
1011 * @covers ResourceLoader::makeModuleResponse
1012 */
1013 public function testMakeModuleResponseExtraHeadersMulti() {
1014 $foo = $this->getMockBuilder( ResourceLoaderTestModule::class )
1015 ->setMethods( [ 'getPreloadLinks' ] )->getMock();
1016 $foo->method( 'getPreloadLinks' )->willReturn( [
1017 'https://example.org/script.js' => [ 'as' => 'script' ],
1018 ] );
1019
1020 $bar = $this->getMockBuilder( ResourceLoaderTestModule::class )
1021 ->setMethods( [ 'getPreloadLinks' ] )->getMock();
1022 $bar->method( 'getPreloadLinks' )->willReturn( [
1023 '/example.png' => [ 'as' => 'image' ],
1024 '/example.jpg' => [ 'as' => 'image' ],
1025 ] );
1026
1027 $rl = new EmptyResourceLoader();
1028 $context = $this->getResourceLoaderContext(
1029 [ 'modules' => 'foo|bar', 'only' => 'scripts' ],
1030 $rl
1031 );
1032
1033 $modules = [ 'foo' => $foo, 'bar' => $bar ];
1034 $response = $rl->makeModuleResponse( $context, $modules );
1035 $extraHeaders = TestingAccessWrapper::newFromObject( $rl )->extraHeaders;
1036 $this->assertEquals(
1037 [
1038 'Link: <https://example.org/script.js>;rel=preload;as=script',
1039 'Link: </example.png>;rel=preload;as=image,</example.jpg>;rel=preload;as=image'
1040 ],
1041 $extraHeaders,
1042 'Extra headers'
1043 );
1044 }
1045
1046 /**
1047 * @covers ResourceLoader::respond
1048 */
1049 public function testRespondEmpty() {
1050 $rl = $this->getMockBuilder( EmptyResourceLoader::class )
1051 ->setMethods( [
1052 'tryRespondNotModified',
1053 'sendResponseHeaders',
1054 'measureResponseTime',
1055 ] )
1056 ->getMock();
1057 $context = $this->getResourceLoaderContext( [ 'modules' => '' ], $rl );
1058
1059 $rl->expects( $this->once() )->method( 'measureResponseTime' );
1060 $this->expectOutputRegex( '/no modules were requested/' );
1061
1062 $rl->respond( $context );
1063 }
1064
1065 /**
1066 * @covers ResourceLoader::respond
1067 */
1068 public function testRespondSimple() {
1069 $module = new ResourceLoaderTestModule( [ 'script' => 'foo();' ] );
1070 $rl = $this->getMockBuilder( EmptyResourceLoader::class )
1071 ->setMethods( [
1072 'measureResponseTime',
1073 'tryRespondNotModified',
1074 'sendResponseHeaders',
1075 'makeModuleResponse',
1076 ] )
1077 ->getMock();
1078 $rl->register( 'test', [
1079 'factory' => function () use ( $module ) {
1080 return $module;
1081 }
1082 ] );
1083 $context = $this->getResourceLoaderContext(
1084 [ 'modules' => 'test', 'only' => null ],
1085 $rl
1086 );
1087
1088 $rl->expects( $this->once() )->method( 'makeModuleResponse' )
1089 ->with( $context, [ 'test' => $module ] )
1090 ->willReturn( 'implement_foo;' );
1091 $this->expectOutputRegex( '/^implement_foo;/' );
1092
1093 $rl->respond( $context );
1094 }
1095
1096 /**
1097 * Refuse requests for private modules.
1098 *
1099 * @covers ResourceLoader::respond
1100 */
1101 public function testRespondErrorPrivate() {
1102 $rl = $this->getMockBuilder( EmptyResourceLoader::class )
1103 ->setMethods( [
1104 'measureResponseTime',
1105 'tryRespondNotModified',
1106 'sendResponseHeaders',
1107 ] )
1108 ->getMock();
1109 $rl->register( [
1110 'foo' => [ 'class' => ResourceLoaderTestModule::class ],
1111 'bar' => [ 'class' => ResourceLoaderTestModule::class, 'group' => 'private' ],
1112 ] );
1113 $context = $this->getResourceLoaderContext(
1114 [ 'modules' => 'foo|bar', 'only' => null ],
1115 $rl
1116 );
1117
1118 $this->expectOutputRegex( '/^\/\*.+Cannot build private module/s' );
1119 $rl->respond( $context );
1120 }
1121
1122 /**
1123 * @covers ResourceLoader::respond
1124 */
1125 public function testRespondInternalFailures() {
1126 $module = new ResourceLoaderTestModule( [ 'script' => 'foo();' ] );
1127 $rl = $this->getMockBuilder( EmptyResourceLoader::class )
1128 ->setMethods( [
1129 'measureResponseTime',
1130 'preloadModuleInfo',
1131 'getCombinedVersion',
1132 'tryRespondNotModified',
1133 'makeModuleResponse',
1134 'sendResponseHeaders',
1135 ] )
1136 ->getMock();
1137 $rl->register( 'test', [
1138 'factory' => function () use ( $module ) {
1139 return $module;
1140 }
1141 ] );
1142 $context = $this->getResourceLoaderContext( [ 'modules' => 'test' ], $rl );
1143 // Disable logging from outputErrorAndLog
1144 $this->setLogger( 'exception', new Psr\Log\NullLogger() );
1145
1146 $rl->expects( $this->once() )->method( 'preloadModuleInfo' )
1147 ->willThrowException( new Exception( 'Preload error' ) );
1148 $rl->expects( $this->once() )->method( 'getCombinedVersion' )
1149 ->willThrowException( new Exception( 'Version error' ) );
1150 $rl->expects( $this->once() )->method( 'makeModuleResponse' )
1151 ->with( $context, [ 'test' => $module ] )
1152 ->willReturn( 'foo;' );
1153 // Internal errors should be caught and logged without affecting module output
1154 $this->expectOutputRegex( '/^\/\*.+Preload error.+Version error.+\*\/.*foo;/ms' );
1155
1156 $rl->respond( $context );
1157 }
1158
1159 /**
1160 * @covers ResourceLoader::measureResponseTime
1161 */
1162 public function testMeasureResponseTime() {
1163 $stats = $this->getMockBuilder( NullStatsdDataFactory::class )
1164 ->setMethods( [ 'timing' ] )->getMock();
1165 $this->setService( 'StatsdDataFactory', $stats );
1166
1167 $stats->expects( $this->once() )->method( 'timing' )
1168 ->with( 'resourceloader.responseTime', $this->anything() );
1169
1170 $timing = new Timing();
1171 $timing->mark( 'requestShutdown' );
1172 $rl = TestingAccessWrapper::newFromObject( new EmptyResourceLoader );
1173 $rl->measureResponseTime( $timing );
1174 DeferredUpdates::doUpdates();
1175 }
1176 }