3 use Wikimedia\TestingAccessWrapper
;
4 use MediaWiki\MediaWikiServices
;
6 class ResourceLoaderTest
extends ResourceLoaderTestCase
{
8 protected function setUp() {
11 $this->setMwGlobals( [
12 'wgShowExceptionDetails' => true,
17 * Ensure the ResourceLoaderRegisterModules hook is called.
20 public function testServiceWiring() {
21 $this->overrideMwServices();
24 $this->setMwGlobals( 'wgHooks', [
25 'ResourceLoaderRegisterModules' => [
26 function ( &$resourceLoader ) use ( &$ranHook ) {
32 MediaWikiServices
::getInstance()->getResourceLoader();
34 $this->assertSame( 1, $ranHook, 'Hook was called' );
37 public static function provideInvalidModuleName() {
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' ],
46 public static function provideValidModuleName() {
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' ],
58 * @dataProvider provideInvalidModuleName
59 * @covers ResourceLoader
61 public function testIsValidModuleName_invalid( $name ) {
62 $this->assertFalse( ResourceLoader
::isValidModuleName( $name ) );
66 * @dataProvider provideValidModuleName
67 * @covers ResourceLoader
69 public function testIsValidModuleName_valid( $name ) {
70 $this->assertTrue( ResourceLoader
::isValidModuleName( $name ) );
74 * @covers ResourceLoader::register
75 * @covers ResourceLoader::getModule
77 public function testRegisterValidArray() {
78 $resourceLoader = new EmptyResourceLoader();
79 // Covers case of register() setting $rl->moduleInfos,
80 // but $rl->modules lazy-populated by getModule()
81 $resourceLoader->register( 'test', [ 'class' => ResourceLoaderTestModule
::class ] );
82 $this->assertInstanceOf(
83 ResourceLoaderTestModule
::class,
84 $resourceLoader->getModule( 'test' )
89 * @covers ResourceLoader::register
92 public function testRegisterEmptyString() {
93 $resourceLoader = new EmptyResourceLoader();
94 $resourceLoader->register( '', [ 'class' => ResourceLoaderTestModule
::class ] );
95 $this->assertInstanceOf(
96 ResourceLoaderTestModule
::class,
97 $resourceLoader->getModule( '' )
102 * @covers ResourceLoader::register
105 public function testRegisterInvalidName() {
106 $resourceLoader = new EmptyResourceLoader();
107 $this->setExpectedException( MWException
::class, "name 'test!invalid' is invalid" );
108 $resourceLoader->register( 'test!invalid', [] );
112 * @covers ResourceLoader::register
114 public function testRegisterInvalidType() {
115 $resourceLoader = new EmptyResourceLoader();
116 $this->setExpectedException( InvalidArgumentException
::class, 'Invalid module info' );
117 $resourceLoader->register( 'test', new stdClass() );
121 * @covers ResourceLoader::register
123 public function testRegisterDuplicate() {
124 $logger = $this->getMockBuilder( Psr\Log\LoggerInterface
::class )->getMock();
125 $logger->expects( $this->once() )
126 ->method( 'warning' );
127 $resourceLoader = new EmptyResourceLoader( null, $logger );
129 $resourceLoader->register( 'test', [ 'class' => ResourceLoaderSkinModule
::class ] );
130 $resourceLoader->register( 'test', [ 'class' => ResourceLoaderStartUpModule
::class ] );
131 $this->assertInstanceOf(
132 ResourceLoaderStartUpModule
::class,
133 $resourceLoader->getModule( 'test' ),
139 * @covers ResourceLoader::getModuleNames
141 public function testGetModuleNames() {
142 // Use an empty one so that core and extension modules don't get in.
143 $resourceLoader = new EmptyResourceLoader();
144 $resourceLoader->register( 'test.foo', [] );
145 $resourceLoader->register( 'test.bar', [] );
147 [ 'startup', 'test.foo', 'test.bar' ],
148 $resourceLoader->getModuleNames()
152 public function provideTestIsFileModule() {
153 $fileModuleObj = $this->createMock( ResourceLoaderFileModule
::class );
155 'factory ignored' => [ false,
157 'factory' => function () {
158 return new ResourceLoaderTestModule();
162 'factory ignored (actual FileModule)' => [ false,
164 'factory' => function () use ( $fileModuleObj ) {
165 return $fileModuleObj;
169 'simple empty' => [ true,
172 'simple scripts' => [ true,
173 [ 'scripts' => 'example.js' ]
175 'simple scripts with targets' => [ true, [
176 'scripts' => [ 'a.js', 'b.js' ],
177 'targets' => [ 'desktop', 'mobile' ],
179 'FileModule' => [ true,
180 [ 'class' => ResourceLoaderFileModule
::class, 'scripts' => 'example.js' ]
182 'TestModule' => [ false,
183 [ 'class' => ResourceLoaderTestModule
::class, 'scripts' => 'example.js' ]
185 'SkinModule (FileModule subclass)' => [ true,
186 [ 'class' => ResourceLoaderSkinModule
::class, 'scripts' => 'example.js' ]
188 'WikiModule' => [ false, [
189 'class' => ResourceLoaderWikiModule
::class,
190 'scripts' => [ 'MediaWiki:Example.js' ],
196 * @dataProvider provideTestIsFileModule
197 * @covers ResourceLoader::isFileModule
199 public function testIsFileModule( $expected, $module ) {
200 $rl = TestingAccessWrapper
::newFromObject( new EmptyResourceLoader() );
201 $rl->register( 'test', $module );
202 $this->assertSame( $expected, $rl->isFileModule( 'test' ) );
206 * @covers ResourceLoader::isFileModule
208 public function testIsFileModuleUnknown() {
209 $rl = TestingAccessWrapper
::newFromObject( new EmptyResourceLoader() );
210 $this->assertSame( false, $rl->isFileModule( 'unknown' ) );
214 * @covers ResourceLoader::isModuleRegistered
216 public function testIsModuleRegistered() {
217 $rl = new EmptyResourceLoader();
218 $rl->register( 'test', [] );
219 $this->assertTrue( $rl->isModuleRegistered( 'test' ) );
220 $this->assertFalse( $rl->isModuleRegistered( 'test.unknown' ) );
224 * @covers ResourceLoader::getModule
226 public function testGetModuleUnknown() {
227 $rl = new EmptyResourceLoader();
228 $this->assertSame( null, $rl->getModule( 'test' ) );
232 * @covers ResourceLoader::getModule
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' )
244 * @covers ResourceLoader::getModule
246 public function testGetModuleFactory() {
247 $factory = function ( array $info ) {
248 $this->assertArrayHasKey( 'kitten', $info );
249 return new ResourceLoaderTestModule( $info );
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' )
261 * @covers ResourceLoader::getModule
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'
274 * @covers ResourceLoader::getLessCompiler
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" => '',
283 $css = $lc->parseFile( "$basePath/module/use-import-dir.less" )->getCss();
284 $this->assertStringEqualsFile( "$basePath/module/styles.css", $css );
287 public static function providePackedModules() {
290 'Example from makePackedModulesString doc comment',
291 [ 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' ],
292 'foo.bar,baz|bar.baz,quux',
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',
300 'Regression fixed in r87497 (7fee86c38e) with dotless names',
301 [ 'foo', 'bar', 'baz' ],
305 'Prefixless modules after a prefixed module',
306 [ 'single.module', 'foobar', 'foobaz' ],
307 'single.module|foobar,foobaz',
311 [ 'foo', 'foo.baz', 'baz.quux', 'foo.bar' ],
312 'foo|foo.baz,bar|baz.quux',
313 [ 'foo', 'foo.baz', 'foo.bar', 'baz.quux' ],
319 * @dataProvider providePackedModules
320 * @covers ResourceLoader::makePackedModulesString
322 public function testMakePackedModulesString( $desc, $modules, $packed ) {
323 $this->assertEquals( $packed, ResourceLoader
::makePackedModulesString( $modules ), $desc );
327 * @dataProvider providePackedModules
328 * @covers ResourceLoader::expandModuleNames
330 public function testExpandModuleNames( $desc, $modules, $packed, $unpacked = null ) {
332 $unpacked ?
: $modules,
333 ResourceLoader
::expandModuleNames( $packed ),
338 public static function provideAddSource() {
340 [ 'foowiki', 'https://example.org/w/load.php', 'foowiki' ],
341 [ 'foowiki', [ 'loadScript' => 'https://example.org/w/load.php' ], 'foowiki' ],
344 'foowiki' => 'https://example.org/w/load.php',
345 'bazwiki' => 'https://example.com/w/load.php',
348 [ 'foowiki', 'bazwiki' ]
354 * @dataProvider provideAddSource
355 * @covers ResourceLoader::addSource
356 * @covers ResourceLoader::getSources
358 public function testAddSource( $name, $info, $expected ) {
359 $rl = new EmptyResourceLoader
;
360 $rl->addSource( $name, $info );
361 if ( is_array( $expected ) ) {
362 foreach ( $expected as $source ) {
363 $this->assertArrayHasKey( $source, $rl->getSources() );
366 $this->assertArrayHasKey( $expected, $rl->getSources() );
371 * @covers ResourceLoader::addSource
373 public function testAddSourceDupe() {
374 $rl = new EmptyResourceLoader
;
375 $this->setExpectedException(
376 MWException
::class, 'ResourceLoader duplicate source addition error'
378 $rl->addSource( 'foo', 'https://example.org/w/load.php' );
379 $rl->addSource( 'foo', 'https://example.com/w/load.php' );
383 * @covers ResourceLoader::addSource
385 public function testAddSourceInvalid() {
386 $rl = new EmptyResourceLoader
;
387 $this->setExpectedException( MWException
::class, 'with no "loadScript" key' );
388 $rl->addSource( 'foo', [ 'x' => 'https://example.org/w/load.php' ] );
391 public static function provideLoaderImplement() {
394 'title' => 'Implement scripts, styles and messages',
396 'name' => 'test.example',
397 'scripts' => 'mw.example();',
398 'styles' => [ 'css' => [ '.mw-example {}' ] ],
399 'messages' => [ 'example' => '' ],
402 'expected' => 'mw.loader.implement( "test.example", function ( $, jQuery, require, module ) {
413 'title' => 'Implement scripts',
415 'name' => 'test.example',
416 'scripts' => 'mw.example();',
419 'expected' => 'mw.loader.implement( "test.example", function ( $, jQuery, require, module ) {
424 'title' => 'Implement styles',
426 'name' => 'test.example',
428 'styles' => [ 'css' => [ '.mw-example {}' ] ],
430 'expected' => 'mw.loader.implement( "test.example", [], {
437 'title' => 'Implement scripts and messages',
439 'name' => 'test.example',
440 'scripts' => 'mw.example();',
441 'messages' => [ 'example' => '' ],
443 'expected' => 'mw.loader.implement( "test.example", function ( $, jQuery, require, module ) {
450 'title' => 'Implement scripts and templates',
452 'name' => 'test.example',
453 'scripts' => 'mw.example();',
454 'templates' => [ 'example.html' => '' ],
456 'expected' => 'mw.loader.implement( "test.example", function ( $, jQuery, require, module ) {
463 'title' => 'Implement unwrapped user script',
466 'scripts' => 'mw.example( 1 );',
469 'expected' => 'mw.loader.implement( "user", "mw.example( 1 );" );',
472 'title' => 'Implement multi-file script',
474 'name' => 'test.multifile',
479 'content' => 'mw.example( 1 );',
483 'content' => [ 'n' => 2 ],
487 'content' => 'mw.example( 3 );'
490 'main' => 'three.js',
494 mw.loader.implement( "test.multifile", {
497 "one.js": function ( require, module ) {
503 "three.js": function ( require, module ) {
514 * @dataProvider provideLoaderImplement
515 * @covers ResourceLoader::makeLoaderImplementScript
516 * @covers ResourceLoader::trimArray
518 public function testMakeLoaderImplementScript( $case ) {
521 'styles' => [], 'templates' => [], 'messages' => new XmlJsCode( '{}' ), 'packageFiles' => [],
523 ResourceLoader
::clearCache();
524 $this->setMwGlobals( 'wgResourceLoaderDebug', true );
526 $rl = TestingAccessWrapper
::newFromClass( ResourceLoader
::class );
529 $rl->makeLoaderImplementScript(
531 ( $case['wrap'] && is_string( $case['scripts'] ) )
532 ?
new XmlJsCode( $case['scripts'] )
537 $case['packageFiles']
543 * @covers ResourceLoader::makeLoaderImplementScript
545 public function testMakeLoaderImplementScriptInvalid() {
546 $this->setExpectedException( MWException
::class, 'Invalid scripts error' );
547 $rl = TestingAccessWrapper
::newFromClass( ResourceLoader
::class );
548 $rl->makeLoaderImplementScript(
554 null // package files
559 * @covers ResourceLoader::makeLoaderRegisterScript
561 public function testMakeLoaderRegisterScript() {
563 'mw.loader.register([
569 ResourceLoader
::makeLoaderRegisterScript( [
570 [ 'test.name', '1234567' ],
572 'Nested array parameter'
576 'mw.loader.register([
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;' ],
611 'Compact dependency indexes'
616 * @covers ResourceLoader::makeLoaderSourcesScript
618 public function testMakeLoaderSourcesScript() {
620 'mw.loader.addSource({
621 "local": "/w/load.php"
623 ResourceLoader
::makeLoaderSourcesScript( 'local', '/w/load.php' )
626 'mw.loader.addSource({
627 "local": "/w/load.php"
629 ResourceLoader
::makeLoaderSourcesScript( [ 'local' => '/w/load.php' ] )
632 'mw.loader.addSource({
633 "local": "/w/load.php",
634 "example": "https://example.org/w/load.php"
636 ResourceLoader
::makeLoaderSourcesScript( [
637 'local' => '/w/load.php',
638 'example' => 'https://example.org/w/load.php'
642 'mw.loader.addSource([]);',
643 ResourceLoader
::makeLoaderSourcesScript( [] )
647 private static function fakeSources() {
650 'loadScript' => '//example.org/w/load.php',
651 'apiScript' => '//example.org/w/api.php',
654 'loadScript' => '//example.com/w/load.php',
655 'apiScript' => '//example.com/w/api.php',
661 * @covers ResourceLoader::getLoadScript
663 public function testGetLoadScript() {
664 $rl = new EmptyResourceLoader();
665 $sources = self
::fakeSources();
666 $rl->addSource( $sources );
667 foreach ( [ 'examplewiki', 'example2wiki' ] as $name ) {
668 $this->assertEquals( $rl->getLoadScript( $name ), $sources[$name]['loadScript'] );
672 $rl->getLoadScript( 'thiswasneverreigstered' );
673 $this->assertTrue( false, 'ResourceLoader::getLoadScript should have thrown an exception' );
674 } catch ( MWException
$e ) {
675 $this->assertTrue( true );
679 protected function getFailFerryMock( $getter = 'getScript' ) {
680 $mock = $this->getMockBuilder( ResourceLoaderTestModule
::class )
681 ->setMethods( [ $getter ] )
683 $mock->method( $getter )->will( $this->throwException(
684 new Exception( 'Ferry not found' )
689 protected function getSimpleModuleMock( $script = '' ) {
690 $mock = $this->getMockBuilder( ResourceLoaderTestModule
::class )
691 ->setMethods( [ 'getScript' ] )
693 $mock->method( 'getScript' )->willReturn( $script );
697 protected function getSimpleStyleModuleMock( $styles = '' ) {
698 $mock = $this->getMockBuilder( ResourceLoaderTestModule
::class )
699 ->setMethods( [ 'getStyles' ] )
701 $mock->method( 'getStyles' )->willReturn( [ '' => $styles ] );
706 * @covers ResourceLoader::getCombinedVersion
708 public function testGetCombinedVersion() {
709 $rl = $this->getMockBuilder( EmptyResourceLoader
::class )
710 // Disable log from outputErrorAndLog
711 ->setMethods( [ 'outputErrorAndLog' ] )->getMock();
713 'foo' => [ 'class' => ResourceLoaderTestModule
::class ],
715 'factory' => function () {
716 return self
::getFailFerryMock();
719 'bar' => [ 'class' => ResourceLoaderTestModule
::class ],
721 $context = $this->getResourceLoaderContext( [], $rl );
725 $rl->getCombinedVersion( $context, [] ),
730 ResourceLoader
::makeHash( self
::BLANK_VERSION
),
731 $rl->getCombinedVersion( $context, [ 'foo' ] ),
735 // Verify that getCombinedVersion() does not throw when ferry fails.
736 // Instead it gracefully continues to combine the remaining modules.
738 ResourceLoader
::makeHash( self
::BLANK_VERSION
. self
::BLANK_VERSION
),
739 $rl->getCombinedVersion( $context, [ 'foo', 'ferry', 'bar' ] ),
740 'compute foo+ferry+bar (T152266)'
744 public static function provideMakeModuleResponseConcat() {
750 'expected' => "foo()\n" . 'mw.loader.state({
753 'minified' => "foo()\n" . 'mw.loader.state({"foo":"ready"});',
754 'message' => 'Script without semi-colon',
761 'expected' => "foo()\nbar()\n" . 'mw.loader.state({
765 'minified' => "foo()\nbar()\n" . 'mw.loader.state({"foo":"ready","bar":"ready"});',
766 'message' => 'Two scripts without semi-colon',
770 'foo' => "foo()\n// bar();"
772 'expected' => "foo()\n// bar();\n" . 'mw.loader.state({
775 'minified' => "foo()\n" . 'mw.loader.state({"foo":"ready"});',
776 'message' => 'Script with semi-colon in comment (T162719)',
780 foreach ( $testcases as $i => $case ) {
787 $ret["#$i (minified)"] = [
798 * Verify how multiple scripts and mw.loader.state() calls are concatenated.
800 * @dataProvider provideMakeModuleResponseConcat
801 * @covers ResourceLoader::makeModuleResponse
803 public function testMakeModuleResponseConcat( $scripts, $expected, $debug, $message = null ) {
804 $rl = new EmptyResourceLoader();
805 $modules = array_map( function ( $script ) {
806 return self
::getSimpleModuleMock( $script );
809 $context = $this->getResourceLoaderContext(
811 'modules' => implode( '|', array_keys( $modules ) ),
813 'debug' => $debug ?
'true' : 'false',
818 $response = $rl->makeModuleResponse( $context, $modules );
819 $this->assertSame( [], $rl->getErrors(), 'Errors' );
820 $this->assertEquals( $expected, $response, $message ?
: 'Response' );
824 * @covers ResourceLoader::makeModuleResponse
826 public function testMakeModuleResponseEmpty() {
827 $rl = new EmptyResourceLoader();
828 $context = $this->getResourceLoaderContext(
829 [ 'modules' => '', 'only' => 'scripts' ],
833 $response = $rl->makeModuleResponse( $context, [] );
834 $this->assertSame( [], $rl->getErrors(), 'Errors' );
835 $this->assertRegExp( '/^\/\*.+no modules were requested.+\*\/$/ms', $response );
839 * Verify that when building module content in a load.php response,
840 * an exception from one module will not break script output from
843 * @covers ResourceLoader::makeModuleResponse
845 public function testMakeModuleResponseError() {
847 'foo' => self
::getSimpleModuleMock( 'foo();' ),
848 'ferry' => self
::getFailFerryMock(),
849 'bar' => self
::getSimpleModuleMock( 'bar();' ),
851 $rl = new EmptyResourceLoader();
852 $context = $this->getResourceLoaderContext(
854 'modules' => 'foo|ferry|bar',
860 // Disable log from makeModuleResponse via outputErrorAndLog
861 $this->setLogger( 'exception', new Psr\Log\
NullLogger() );
863 $response = $rl->makeModuleResponse( $context, $modules );
864 $errors = $rl->getErrors();
866 $this->assertCount( 1, $errors );
867 $this->assertRegExp( '/Ferry not found/', $errors[0] );
869 "foo();\nbar();\n" . 'mw.loader.state({
879 * Verify that exceptions in PHP for one module will not break others
880 * (stylesheet response).
882 * @covers ResourceLoader::makeModuleResponse
884 public function testMakeModuleResponseErrorCSS() {
886 'foo' => self
::getSimpleStyleModuleMock( '.foo{}' ),
887 'ferry' => self
::getFailFerryMock( 'getStyles' ),
888 'bar' => self
::getSimpleStyleModuleMock( '.bar{}' ),
890 $rl = new EmptyResourceLoader();
891 $context = $this->getResourceLoaderContext(
893 'modules' => 'foo|ferry|bar',
900 // Disable log from makeModuleResponse via outputErrorAndLog
901 $this->setLogger( 'exception', new Psr\Log\
NullLogger() );
903 $response = $rl->makeModuleResponse( $context, $modules );
904 $errors = $rl->getErrors();
906 $this->assertCount( 2, $errors );
907 $this->assertRegExp( '/Ferry not found/', $errors[0] );
908 $this->assertRegExp( '/Problem.+"ferry":\s*"error"/ms', $errors[1] );
916 * Verify that when building the startup module response,
917 * an exception from one module class will not break the entire
918 * startup module response. See T152266.
920 * @covers ResourceLoader::makeModuleResponse
922 public function testMakeModuleResponseStartupError() {
923 // This is an integration test that uses a lot of MediaWiki state,
924 // provide the full Config object here.
925 $rl = new EmptyResourceLoader( MediaWikiServices
::getInstance()->getMainConfig() );
927 'foo' => [ 'factory' => function () {
928 return self
::getSimpleModuleMock( 'foo();' );
930 'ferry' => [ 'factory' => function () {
931 return self
::getFailFerryMock();
933 'bar' => [ 'factory' => function () {
934 return self
::getSimpleModuleMock( 'bar();' );
937 $context = $this->getResourceLoaderContext(
939 'modules' => 'startup',
946 [ 'startup', 'foo', 'ferry', 'bar' ],
947 $rl->getModuleNames(),
951 // Disable log from makeModuleResponse via outputErrorAndLog
952 $this->setLogger( 'exception', new Psr\Log\
NullLogger() );
954 $modules = [ 'startup' => $rl->getModule( 'startup' ) ];
955 $response = $rl->makeModuleResponse( $context, $modules );
956 $errors = $rl->getErrors();
958 $this->assertRegExp( '/Ferry not found/', $errors[0] );
959 $this->assertCount( 1, $errors );
961 '/isCompatible.*window\.RLQ/s',
963 'startup response undisrupted (T152266)'
966 '/register\([^)]+"ferry",\s*""/s',
968 'startup response registers broken module'
971 '/state\([^)]+"ferry":\s*"error"/s',
973 'startup response sets state to error'
978 * Integration test for modules sending extra HTTP response headers.
980 * @covers ResourceLoaderModule::getHeaders
981 * @covers ResourceLoaderModule::buildContent
982 * @covers ResourceLoader::makeModuleResponse
984 public function testMakeModuleResponseExtraHeaders() {
985 $module = $this->getMockBuilder( ResourceLoaderTestModule
::class )
986 ->setMethods( [ 'getPreloadLinks' ] )->getMock();
987 $module->method( 'getPreloadLinks' )->willReturn( [
988 'https://example.org/script.js' => [ 'as' => 'script' ],
991 $rl = new EmptyResourceLoader();
992 $context = $this->getResourceLoaderContext(
993 [ 'modules' => 'foo', 'only' => 'scripts' ],
997 $modules = [ 'foo' => $module ];
998 $response = $rl->makeModuleResponse( $context, $modules );
999 $extraHeaders = TestingAccessWrapper
::newFromObject( $rl )->extraHeaders
;
1001 $this->assertEquals(
1003 'Link: <https://example.org/script.js>;rel=preload;as=script'
1011 * @covers ResourceLoaderModule::getHeaders
1012 * @covers ResourceLoaderModule::buildContent
1013 * @covers ResourceLoader::makeModuleResponse
1015 public function testMakeModuleResponseExtraHeadersMulti() {
1016 $foo = $this->getMockBuilder( ResourceLoaderTestModule
::class )
1017 ->setMethods( [ 'getPreloadLinks' ] )->getMock();
1018 $foo->method( 'getPreloadLinks' )->willReturn( [
1019 'https://example.org/script.js' => [ 'as' => 'script' ],
1022 $bar = $this->getMockBuilder( ResourceLoaderTestModule
::class )
1023 ->setMethods( [ 'getPreloadLinks' ] )->getMock();
1024 $bar->method( 'getPreloadLinks' )->willReturn( [
1025 '/example.png' => [ 'as' => 'image' ],
1026 '/example.jpg' => [ 'as' => 'image' ],
1029 $rl = new EmptyResourceLoader();
1030 $context = $this->getResourceLoaderContext(
1031 [ 'modules' => 'foo|bar', 'only' => 'scripts' ],
1035 $modules = [ 'foo' => $foo, 'bar' => $bar ];
1036 $response = $rl->makeModuleResponse( $context, $modules );
1037 $extraHeaders = TestingAccessWrapper
::newFromObject( $rl )->extraHeaders
;
1038 $this->assertEquals(
1040 'Link: <https://example.org/script.js>;rel=preload;as=script',
1041 'Link: </example.png>;rel=preload;as=image,</example.jpg>;rel=preload;as=image'
1049 * @covers ResourceLoader::respond
1051 public function testRespondEmpty() {
1052 $rl = $this->getMockBuilder( EmptyResourceLoader
::class )
1054 'tryRespondNotModified',
1055 'sendResponseHeaders',
1056 'measureResponseTime',
1059 $context = $this->getResourceLoaderContext( [ 'modules' => '' ], $rl );
1061 $rl->expects( $this->once() )->method( 'measureResponseTime' );
1062 $this->expectOutputRegex( '/no modules were requested/' );
1064 $rl->respond( $context );
1068 * @covers ResourceLoader::respond
1070 public function testRespondSimple() {
1071 $module = new ResourceLoaderTestModule( [ 'script' => 'foo();' ] );
1072 $rl = $this->getMockBuilder( EmptyResourceLoader
::class )
1074 'measureResponseTime',
1075 'tryRespondNotModified',
1076 'sendResponseHeaders',
1077 'makeModuleResponse',
1080 $rl->register( 'test', [
1081 'factory' => function () use ( $module ) {
1085 $context = $this->getResourceLoaderContext(
1086 [ 'modules' => 'test', 'only' => null ],
1090 $rl->expects( $this->once() )->method( 'makeModuleResponse' )
1091 ->with( $context, [ 'test' => $module ] )
1092 ->willReturn( 'implement_foo;' );
1093 $this->expectOutputRegex( '/^implement_foo;/' );
1095 $rl->respond( $context );
1099 * @covers ResourceLoader::respond
1101 public function testRespondInternalFailures() {
1102 $module = new ResourceLoaderTestModule( [ 'script' => 'foo();' ] );
1103 $rl = $this->getMockBuilder( EmptyResourceLoader
::class )
1105 'measureResponseTime',
1106 'preloadModuleInfo',
1107 'getCombinedVersion',
1108 'tryRespondNotModified',
1109 'makeModuleResponse',
1110 'sendResponseHeaders',
1113 $rl->register( 'test', [
1114 'factory' => function () use ( $module ) {
1118 $context = $this->getResourceLoaderContext( [ 'modules' => 'test' ], $rl );
1119 // Disable logging from outputErrorAndLog
1120 $this->setLogger( 'exception', new Psr\Log\
NullLogger() );
1122 $rl->expects( $this->once() )->method( 'preloadModuleInfo' )
1123 ->willThrowException( new Exception( 'Preload error' ) );
1124 $rl->expects( $this->once() )->method( 'getCombinedVersion' )
1125 ->willThrowException( new Exception( 'Version error' ) );
1126 $rl->expects( $this->once() )->method( 'makeModuleResponse' )
1127 ->with( $context, [ 'test' => $module ] )
1128 ->willReturn( 'foo;' );
1129 // Internal errors should be caught and logged without affecting module output
1130 $this->expectOutputRegex( '/^\/\*.+Preload error.+Version error.+\*\/.*foo;/ms' );
1132 $rl->respond( $context );
1136 * @covers ResourceLoader::measureResponseTime
1138 public function testMeasureResponseTime() {
1139 $stats = $this->getMockBuilder( NullStatsdDataFactory
::class )
1140 ->setMethods( [ 'timing' ] )->getMock();
1141 $this->setService( 'StatsdDataFactory', $stats );
1143 $stats->expects( $this->once() )->method( 'timing' )
1144 ->with( 'resourceloader.responseTime', $this->anything() );
1146 $timing = new Timing();
1147 $timing->mark( 'requestShutdown' );
1148 $rl = TestingAccessWrapper
::newFromObject( new EmptyResourceLoader
);
1149 $rl->measureResponseTime( $timing );
1150 DeferredUpdates
::doUpdates();