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