MediaWiki  1.32.5
ResourceLoaderTest.php
Go to the documentation of this file.
1 <?php
2 
3 use Wikimedia\TestingAccessWrapper;
4 
6 
7  protected function setUp() {
8  parent::setUp();
9 
10  $this->setMwGlobals( [
11  'wgShowExceptionDetails' => true,
12  ] );
13  }
14 
20  public function testConstructRegistrationHook() {
21  $resourceLoaderRegisterModulesHook = false;
22 
23  $this->setMwGlobals( 'wgHooks', [
24  'ResourceLoaderRegisterModules' => [
25  function ( &$resourceLoader ) use ( &$resourceLoaderRegisterModulesHook ) {
26  $resourceLoaderRegisterModulesHook = true;
27  }
28  ]
29  ] );
30 
31  $unused = new ResourceLoader();
32  $this->assertTrue(
33  $resourceLoaderRegisterModulesHook,
34  'Hook ResourceLoaderRegisterModules called'
35  );
36  }
37 
42  public function testRegisterValidObject() {
43  $module = new ResourceLoaderTestModule();
45  $resourceLoader->register( 'test', $module );
46  $this->assertEquals( $module, $resourceLoader->getModule( 'test' ) );
47  }
48 
53  public function testRegisterValidArray() {
54  $module = new ResourceLoaderTestModule();
56  // Covers case of register() setting $rl->moduleInfos,
57  // but $rl->modules lazy-populated by getModule()
58  $resourceLoader->register( 'test', [ 'object' => $module ] );
59  $this->assertEquals( $module, $resourceLoader->getModule( 'test' ) );
60  }
61 
65  public function testRegisterEmptyString() {
66  $module = new ResourceLoaderTestModule();
68  $resourceLoader->register( '', $module );
69  $this->assertEquals( $module, $resourceLoader->getModule( '' ) );
70  }
71 
75  public function testRegisterInvalidName() {
77  $this->setExpectedException( MWException::class, "name 'test!invalid' is invalid" );
78  $resourceLoader->register( 'test!invalid', new ResourceLoaderTestModule() );
79  }
80 
84  public function testRegisterInvalidType() {
86  $this->setExpectedException( MWException::class, 'ResourceLoader module info type error' );
87  $resourceLoader->register( 'test', new stdClass() );
88  }
89 
93  public function testRegisterDuplicate() {
94  $logger = $this->getMockBuilder( Psr\Log\LoggerInterface::class )->getMock();
95  $logger->expects( $this->once() )
96  ->method( 'warning' );
97  $resourceLoader = new EmptyResourceLoader( null, $logger );
98 
99  $module1 = new ResourceLoaderTestModule();
100  $module2 = new ResourceLoaderTestModule();
101  $resourceLoader->register( 'test', $module1 );
102  $resourceLoader->register( 'test', $module2 );
103  $this->assertSame( $module2, $resourceLoader->getModule( 'test' ) );
104  }
105 
109  public function testGetModuleNames() {
110  // Use an empty one so that core and extension modules don't get in.
112  $resourceLoader->register( 'test.foo', new ResourceLoaderTestModule() );
113  $resourceLoader->register( 'test.bar', new ResourceLoaderTestModule() );
114  $this->assertEquals(
115  [ 'test.foo', 'test.bar' ],
116  $resourceLoader->getModuleNames()
117  );
118  }
119 
120  public function provideTestIsFileModule() {
121  $fileModuleObj = $this->getMockBuilder( ResourceLoaderFileModule::class )
122  ->disableOriginalConstructor()
123  ->getMock();
124  return [
125  'object' => [ false,
127  ],
128  'FileModule object' => [ false,
129  $fileModuleObj
130  ],
131  'simple empty' => [ true,
132  []
133  ],
134  'simple scripts' => [ true,
135  [ 'scripts' => 'example.js' ]
136  ],
137  'simple scripts, raw and targets' => [ true, [
138  'scripts' => [ 'a.js', 'b.js' ],
139  'raw' => true,
140  'targets' => [ 'desktop', 'mobile' ],
141  ] ],
142  'FileModule' => [ true,
143  [ 'class' => ResourceLoaderFileModule::class, 'scripts' => 'example.js' ]
144  ],
145  'TestModule' => [ false,
146  [ 'class' => ResourceLoaderTestModule::class, 'scripts' => 'example.js' ]
147  ],
148  'SkinModule (FileModule subclass)' => [ true,
149  [ 'class' => ResourceLoaderSkinModule::class, 'scripts' => 'example.js' ]
150  ],
151  'JqueryMsgModule (FileModule subclass)' => [ true, [
153  'scripts' => 'example.js',
154  ] ],
155  'WikiModule' => [ false, [
157  'scripts' => [ 'MediaWiki:Example.js' ],
158  ] ],
159  ];
160  }
161 
166  public function testIsFileModule( $expected, $module ) {
167  $rl = TestingAccessWrapper::newFromObject( new EmptyResourceLoader() );
168  $rl->register( 'test', $module );
169  $this->assertSame( $expected, $rl->isFileModule( 'test' ) );
170  }
171 
175  public function testIsFileModuleUnknown() {
176  $rl = TestingAccessWrapper::newFromObject( new EmptyResourceLoader() );
177  $this->assertSame( false, $rl->isFileModule( 'unknown' ) );
178  }
179 
183  public function testIsModuleRegistered() {
184  $rl = new EmptyResourceLoader();
185  $rl->register( 'test', new ResourceLoaderTestModule() );
186  $this->assertTrue( $rl->isModuleRegistered( 'test' ) );
187  $this->assertFalse( $rl->isModuleRegistered( 'test.unknown' ) );
188  }
189 
193  public function testGetModuleUnknown() {
194  $rl = new EmptyResourceLoader();
195  $this->assertSame( null, $rl->getModule( 'test' ) );
196  }
197 
201  public function testGetModuleClass() {
202  $rl = new EmptyResourceLoader();
203  $rl->register( 'test', [ 'class' => ResourceLoaderTestModule::class ] );
204  $this->assertInstanceOf(
206  $rl->getModule( 'test' )
207  );
208  }
209 
213  public function testGetModuleFactory() {
214  $factory = function ( array $info ) {
215  $this->assertArrayHasKey( 'kitten', $info );
216  return new ResourceLoaderTestModule( $info );
217  };
218 
219  $rl = new EmptyResourceLoader();
220  $rl->register( 'test', [ 'factory' => $factory, 'kitten' => 'little ball of fur' ] );
221  $this->assertInstanceOf(
223  $rl->getModule( 'test' )
224  );
225  }
226 
230  public function testGetModuleClassDefault() {
231  $rl = new EmptyResourceLoader();
232  $rl->register( 'test', [] );
233  $this->assertInstanceOf(
235  $rl->getModule( 'test' ),
236  'Array-style module registrations default to FileModule'
237  );
238  }
239 
243  public function testLessImportDirs() {
244  $rl = new EmptyResourceLoader();
245  $lc = $rl->getLessCompiler( [ 'foo' => '2px', 'Foo' => '#eeeeee' ] );
246  $basePath = dirname( dirname( __DIR__ ) ) . '/data/less';
247  $lc->SetImportDirs( [
248  "$basePath/common" => '',
249  ] );
250  $css = $lc->parseFile( "$basePath/module/use-import-dir.less" )->getCss();
251  $this->assertStringEqualsFile( "$basePath/module/styles.css", $css );
252  }
253 
254  public static function providePackedModules() {
255  return [
256  [
257  'Example from makePackedModulesString doc comment',
258  [ 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' ],
259  'foo.bar,baz|bar.baz,quux',
260  ],
261  [
262  'Example from expandModuleNames doc comment',
263  [ 'jquery.foo', 'jquery.bar', 'jquery.ui.baz', 'jquery.ui.quux' ],
264  'jquery.foo,bar|jquery.ui.baz,quux',
265  ],
266  [
267  'Regression fixed in r87497 (7fee86c38e) with dotless names',
268  [ 'foo', 'bar', 'baz' ],
269  'foo,bar,baz',
270  ],
271  [
272  'Prefixless modules after a prefixed module',
273  [ 'single.module', 'foobar', 'foobaz' ],
274  'single.module|foobar,foobaz',
275  ],
276  [
277  'Ordering',
278  [ 'foo', 'foo.baz', 'baz.quux', 'foo.bar' ],
279  'foo|foo.baz,bar|baz.quux',
280  [ 'foo', 'foo.baz', 'foo.bar', 'baz.quux' ],
281  ]
282  ];
283  }
284 
289  public function testMakePackedModulesString( $desc, $modules, $packed ) {
290  $this->assertEquals( $packed, ResourceLoader::makePackedModulesString( $modules ), $desc );
291  }
292 
297  public function testExpandModuleNames( $desc, $modules, $packed, $unpacked = null ) {
298  $this->assertEquals(
299  $unpacked ?: $modules,
301  $desc
302  );
303  }
304 
305  public static function provideAddSource() {
306  return [
307  [ 'foowiki', 'https://example.org/w/load.php', 'foowiki' ],
308  [ 'foowiki', [ 'loadScript' => 'https://example.org/w/load.php' ], 'foowiki' ],
309  [
310  [
311  'foowiki' => 'https://example.org/w/load.php',
312  'bazwiki' => 'https://example.com/w/load.php',
313  ],
314  null,
315  [ 'foowiki', 'bazwiki' ]
316  ]
317  ];
318  }
319 
325  public function testAddSource( $name, $info, $expected ) {
326  $rl = new ResourceLoader;
327  $rl->addSource( $name, $info );
328  if ( is_array( $expected ) ) {
329  foreach ( $expected as $source ) {
330  $this->assertArrayHasKey( $source, $rl->getSources() );
331  }
332  } else {
333  $this->assertArrayHasKey( $expected, $rl->getSources() );
334  }
335  }
336 
340  public function testAddSourceDupe() {
341  $rl = new ResourceLoader;
342  $this->setExpectedException(
343  MWException::class, 'ResourceLoader duplicate source addition error'
344  );
345  $rl->addSource( 'foo', 'https://example.org/w/load.php' );
346  $rl->addSource( 'foo', 'https://example.com/w/load.php' );
347  }
348 
352  public function testAddSourceInvalid() {
353  $rl = new ResourceLoader;
354  $this->setExpectedException( MWException::class, 'with no "loadScript" key' );
355  $rl->addSource( 'foo', [ 'x' => 'https://example.org/w/load.php' ] );
356  }
357 
358  public static function provideLoaderImplement() {
359  return [
360  [ [
361  'title' => 'Implement scripts, styles and messages',
362 
363  'name' => 'test.example',
364  'scripts' => 'mw.example();',
365  'styles' => [ 'css' => [ '.mw-example {}' ] ],
366  'messages' => [ 'example' => '' ],
367  'templates' => [],
368 
369  'expected' => 'mw.loader.implement( "test.example", function ( $, jQuery, require, module ) {
370 mw.example();
371 }, {
372  "css": [
373  ".mw-example {}"
374  ]
375 }, {
376  "example": ""
377 } );',
378  ] ],
379  [ [
380  'title' => 'Implement scripts',
381 
382  'name' => 'test.example',
383  'scripts' => 'mw.example();',
384  'styles' => [],
385 
386  'expected' => 'mw.loader.implement( "test.example", function ( $, jQuery, require, module ) {
387 mw.example();
388 } );',
389  ] ],
390  [ [
391  'title' => 'Implement styles',
392 
393  'name' => 'test.example',
394  'scripts' => [],
395  'styles' => [ 'css' => [ '.mw-example {}' ] ],
396 
397  'expected' => 'mw.loader.implement( "test.example", [], {
398  "css": [
399  ".mw-example {}"
400  ]
401 } );',
402  ] ],
403  [ [
404  'title' => 'Implement scripts and messages',
405 
406  'name' => 'test.example',
407  'scripts' => 'mw.example();',
408  'messages' => [ 'example' => '' ],
409 
410  'expected' => 'mw.loader.implement( "test.example", function ( $, jQuery, require, module ) {
411 mw.example();
412 }, {}, {
413  "example": ""
414 } );',
415  ] ],
416  [ [
417  'title' => 'Implement scripts and templates',
418 
419  'name' => 'test.example',
420  'scripts' => 'mw.example();',
421  'templates' => [ 'example.html' => '' ],
422 
423  'expected' => 'mw.loader.implement( "test.example", function ( $, jQuery, require, module ) {
424 mw.example();
425 }, {}, {}, {
426  "example.html": ""
427 } );',
428  ] ],
429  [ [
430  'title' => 'Implement unwrapped user script',
431 
432  'name' => 'user',
433  'scripts' => 'mw.example( 1 );',
434  'wrap' => false,
435 
436  'expected' => 'mw.loader.implement( "user", "mw.example( 1 );" );',
437  ] ],
438  ];
439  }
440 
446  public function testMakeLoaderImplementScript( $case ) {
447  $case += [
448  'wrap' => true,
449  'styles' => [], 'templates' => [], 'messages' => new XmlJsCode( '{}' )
450  ];
451  ResourceLoader::clearCache();
452  $this->setMwGlobals( 'wgResourceLoaderDebug', true );
453 
454  $rl = TestingAccessWrapper::newFromClass( ResourceLoader::class );
455  $this->assertEquals(
456  $case['expected'],
457  $rl->makeLoaderImplementScript(
458  $case['name'],
459  ( $case['wrap'] && is_string( $case['scripts'] ) )
460  ? new XmlJsCode( $case['scripts'] )
461  : $case['scripts'],
462  $case['styles'],
463  $case['messages'],
464  $case['templates']
465  )
466  );
467  }
468 
473  $this->setExpectedException( MWException::class, 'Invalid scripts error' );
474  $rl = TestingAccessWrapper::newFromClass( ResourceLoader::class );
475  $rl->makeLoaderImplementScript(
476  'test', // name
477  123, // scripts
478  null, // styles
479  null, // messages
480  null // templates
481  );
482  }
483 
487  public function testMakeLoaderRegisterScript() {
488  $this->assertEquals(
489  'mw.loader.register( [
490  [
491  "test.name",
492  "1234567"
493  ]
494 ] );',
495  ResourceLoader::makeLoaderRegisterScript( [
496  [ 'test.name', '1234567' ],
497  ] ),
498  'Nested array parameter'
499  );
500 
501  $this->assertEquals(
502  'mw.loader.register( [
503  [
504  "test.foo",
505  "100"
506  ],
507  [
508  "test.bar",
509  "200",
510  [
511  "test.unknown"
512  ]
513  ],
514  [
515  "test.baz",
516  "300",
517  [
518  3,
519  0
520  ]
521  ],
522  [
523  "test.quux",
524  "400",
525  [],
526  null,
527  null,
528  "return true;"
529  ]
530 ] );',
531  ResourceLoader::makeLoaderRegisterScript( [
532  [ 'test.foo', '100' , [], null, null ],
533  [ 'test.bar', '200', [ 'test.unknown' ], null ],
534  [ 'test.baz', '300', [ 'test.quux', 'test.foo' ], null ],
535  [ 'test.quux', '400', [], null, null, 'return true;' ],
536  ] ),
537  'Compact dependency indexes'
538  );
539  }
540 
544  public function testMakeLoaderSourcesScript() {
545  $this->assertEquals(
546  'mw.loader.addSource( {
547  "local": "/w/load.php"
548 } );',
549  ResourceLoader::makeLoaderSourcesScript( 'local', '/w/load.php' )
550  );
551  $this->assertEquals(
552  'mw.loader.addSource( {
553  "local": "/w/load.php"
554 } );',
555  ResourceLoader::makeLoaderSourcesScript( [ 'local' => '/w/load.php' ] )
556  );
557  $this->assertEquals(
558  'mw.loader.addSource( {
559  "local": "/w/load.php",
560  "example": "https://example.org/w/load.php"
561 } );',
562  ResourceLoader::makeLoaderSourcesScript( [
563  'local' => '/w/load.php',
564  'example' => 'https://example.org/w/load.php'
565  ] )
566  );
567  $this->assertEquals(
568  'mw.loader.addSource( [] );',
569  ResourceLoader::makeLoaderSourcesScript( [] )
570  );
571  }
572 
573  private static function fakeSources() {
574  return [
575  'examplewiki' => [
576  'loadScript' => '//example.org/w/load.php',
577  'apiScript' => '//example.org/w/api.php',
578  ],
579  'example2wiki' => [
580  'loadScript' => '//example.com/w/load.php',
581  'apiScript' => '//example.com/w/api.php',
582  ],
583  ];
584  }
585 
589  public function testGetLoadScript() {
590  $this->setMwGlobals( 'wgResourceLoaderSources', [] );
591  $rl = new ResourceLoader();
592  $sources = self::fakeSources();
593  $rl->addSource( $sources );
594  foreach ( [ 'examplewiki', 'example2wiki' ] as $name ) {
595  $this->assertEquals( $rl->getLoadScript( $name ), $sources[$name]['loadScript'] );
596  }
597 
598  try {
599  $rl->getLoadScript( 'thiswasneverreigstered' );
600  $this->assertTrue( false, 'ResourceLoader::getLoadScript should have thrown an exception' );
601  } catch ( MWException $e ) {
602  $this->assertTrue( true );
603  }
604  }
605 
606  protected function getFailFerryMock( $getter = 'getScript' ) {
607  $mock = $this->getMockBuilder( ResourceLoaderTestModule::class )
608  ->setMethods( [ $getter ] )
609  ->getMock();
610  $mock->method( $getter )->will( $this->throwException(
611  new Exception( 'Ferry not found' )
612  ) );
613  return $mock;
614  }
615 
616  protected function getSimpleModuleMock( $script = '' ) {
617  $mock = $this->getMockBuilder( ResourceLoaderTestModule::class )
618  ->setMethods( [ 'getScript' ] )
619  ->getMock();
620  $mock->method( 'getScript' )->willReturn( $script );
621  return $mock;
622  }
623 
624  protected function getSimpleStyleModuleMock( $styles = '' ) {
625  $mock = $this->getMockBuilder( ResourceLoaderTestModule::class )
626  ->setMethods( [ 'getStyles' ] )
627  ->getMock();
628  $mock->method( 'getStyles' )->willReturn( [ '' => $styles ] );
629  return $mock;
630  }
631 
635  public function testGetCombinedVersion() {
636  $rl = $this->getMockBuilder( EmptyResourceLoader::class )
637  // Disable log from outputErrorAndLog
638  ->setMethods( [ 'outputErrorAndLog' ] )->getMock();
639  $rl->register( [
640  'foo' => self::getSimpleModuleMock(),
641  'ferry' => self::getFailFerryMock(),
642  'bar' => self::getSimpleModuleMock(),
643  ] );
644  $context = $this->getResourceLoaderContext( [], $rl );
645 
646  $this->assertEquals(
647  '',
648  $rl->getCombinedVersion( $context, [] ),
649  'empty list'
650  );
651 
652  $this->assertEquals(
653  ResourceLoader::makeHash( self::BLANK_VERSION ),
654  $rl->getCombinedVersion( $context, [ 'foo' ] ),
655  'compute foo'
656  );
657 
658  // Verify that getCombinedVersion() does not throw when ferry fails.
659  // Instead it gracefully continues to combine the remaining modules.
660  $this->assertEquals(
661  ResourceLoader::makeHash( self::BLANK_VERSION . self::BLANK_VERSION ),
662  $rl->getCombinedVersion( $context, [ 'foo', 'ferry', 'bar' ] ),
663  'compute foo+ferry+bar (T152266)'
664  );
665  }
666 
667  public static function provideMakeModuleResponseConcat() {
668  $testcases = [
669  [
670  'modules' => [
671  'foo' => 'foo()',
672  ],
673  'expected' => "foo()\n" . 'mw.loader.state( {
674  "foo": "ready"
675 } );',
676  'minified' => "foo()\n" . 'mw.loader.state({"foo":"ready"});',
677  'message' => 'Script without semi-colon',
678  ],
679  [
680  'modules' => [
681  'foo' => 'foo()',
682  'bar' => 'bar()',
683  ],
684  'expected' => "foo()\nbar()\n" . 'mw.loader.state( {
685  "foo": "ready",
686  "bar": "ready"
687 } );',
688  'minified' => "foo()\nbar()\n" . 'mw.loader.state({"foo":"ready","bar":"ready"});',
689  'message' => 'Two scripts without semi-colon',
690  ],
691  [
692  'modules' => [
693  'foo' => "foo()\n// bar();"
694  ],
695  'expected' => "foo()\n// bar();\n" . 'mw.loader.state( {
696  "foo": "ready"
697 } );',
698  'minified' => "foo()\n" . 'mw.loader.state({"foo":"ready"});',
699  'message' => 'Script with semi-colon in comment (T162719)',
700  ],
701  ];
702  $ret = [];
703  foreach ( $testcases as $i => $case ) {
704  $ret["#$i"] = [
705  $case['modules'],
706  $case['expected'],
707  true, // debug
708  $case['message'],
709  ];
710  $ret["#$i (minified)"] = [
711  $case['modules'],
712  $case['minified'],
713  false, // debug
714  $case['message'],
715  ];
716  }
717  return $ret;
718  }
719 
726  public function testMakeModuleResponseConcat( $scripts, $expected, $debug, $message = null ) {
727  $rl = new EmptyResourceLoader();
728  $modules = array_map( function ( $script ) {
729  return self::getSimpleModuleMock( $script );
730  }, $scripts );
731  $rl->register( $modules );
732 
733  $this->setMwGlobals( 'wgResourceLoaderDebug', $debug );
735  [
736  'modules' => implode( '|', array_keys( $modules ) ),
737  'only' => 'scripts',
738  ],
739  $rl
740  );
741 
742  $response = $rl->makeModuleResponse( $context, $modules );
743  $this->assertSame( [], $rl->getErrors(), 'Errors' );
744  $this->assertEquals( $expected, $response, $message ?: 'Response' );
745  }
746 
750  public function testMakeModuleResponseEmpty() {
751  $rl = new EmptyResourceLoader();
753  [ 'modules' => '', 'only' => 'scripts' ],
754  $rl
755  );
756 
757  $response = $rl->makeModuleResponse( $context, [] );
758  $this->assertSame( [], $rl->getErrors(), 'Errors' );
759  $this->assertRegExp( '/^\/\*.+no modules were requested.+\*\/$/ms', $response );
760  }
761 
769  public function testMakeModuleResponseError() {
770  $modules = [
771  'foo' => self::getSimpleModuleMock( 'foo();' ),
772  'ferry' => self::getFailFerryMock(),
773  'bar' => self::getSimpleModuleMock( 'bar();' ),
774  ];
775  $rl = new EmptyResourceLoader();
776  $rl->register( $modules );
778  [
779  'modules' => 'foo|ferry|bar',
780  'only' => 'scripts',
781  ],
782  $rl
783  );
784 
785  // Disable log from makeModuleResponse via outputErrorAndLog
786  $this->setLogger( 'exception', new Psr\Log\NullLogger() );
787 
788  $response = $rl->makeModuleResponse( $context, $modules );
789  $errors = $rl->getErrors();
790 
791  $this->assertCount( 1, $errors );
792  $this->assertRegExp( '/Ferry not found/', $errors[0] );
793  $this->assertEquals(
794  "foo();\nbar();\n" . 'mw.loader.state( {
795  "ferry": "error",
796  "foo": "ready",
797  "bar": "ready"
798 } );',
799  $response
800  );
801  }
802 
809  public function testMakeModuleResponseErrorCSS() {
810  $modules = [
811  'foo' => self::getSimpleStyleModuleMock( '.foo{}' ),
812  'ferry' => self::getFailFerryMock( 'getStyles' ),
813  'bar' => self::getSimpleStyleModuleMock( '.bar{}' ),
814  ];
815  $rl = new EmptyResourceLoader();
816  $rl->register( $modules );
818  [
819  'modules' => 'foo|ferry|bar',
820  'only' => 'styles',
821  'debug' => 'false',
822  ],
823  $rl
824  );
825 
826  // Disable log from makeModuleResponse via outputErrorAndLog
827  $this->setLogger( 'exception', new Psr\Log\NullLogger() );
828 
829  $response = $rl->makeModuleResponse( $context, $modules );
830  $errors = $rl->getErrors();
831 
832  $this->assertCount( 2, $errors );
833  $this->assertRegExp( '/Ferry not found/', $errors[0] );
834  $this->assertRegExp( '/Problem.+"ferry":\s*"error"/ms', $errors[1] );
835  $this->assertEquals(
836  '.foo{}.bar{}',
837  $response
838  );
839  }
848  $rl = new EmptyResourceLoader();
849  $rl->register( [
850  'foo' => self::getSimpleModuleMock( 'foo();' ),
851  'ferry' => self::getFailFerryMock(),
852  'bar' => self::getSimpleModuleMock( 'bar();' ),
853  'startup' => [ 'class' => ResourceLoaderStartUpModule::class ],
854  ] );
856  [
857  'modules' => 'startup',
858  'only' => 'scripts',
859  ],
860  $rl
861  );
862 
863  $this->assertEquals(
864  [ 'foo', 'ferry', 'bar', 'startup' ],
865  $rl->getModuleNames(),
866  'getModuleNames'
867  );
868 
869  // Disable log from makeModuleResponse via outputErrorAndLog
870  $this->setLogger( 'exception', new Psr\Log\NullLogger() );
871 
872  $modules = [ 'startup' => $rl->getModule( 'startup' ) ];
873  $response = $rl->makeModuleResponse( $context, $modules );
874  $errors = $rl->getErrors();
875 
876  $this->assertRegExp( '/Ferry not found/', $errors[0] );
877  $this->assertCount( 1, $errors );
878  $this->assertRegExp(
879  '/isCompatible.*window\.RLQ/s',
880  $response,
881  'startup response undisrupted (T152266)'
882  );
883  $this->assertRegExp(
884  '/register\([^)]+"ferry",\s*""/s',
885  $response,
886  'startup response registers broken module'
887  );
888  $this->assertRegExp(
889  '/state\([^)]+"ferry":\s*"error"/s',
890  $response,
891  'startup response sets state to error'
892  );
893  }
894 
903  $module = $this->getMockBuilder( ResourceLoaderTestModule::class )
904  ->setMethods( [ 'getPreloadLinks' ] )->getMock();
905  $module->method( 'getPreloadLinks' )->willReturn( [
906  'https://example.org/script.js' => [ 'as' => 'script' ],
907  ] );
908 
909  $rl = new EmptyResourceLoader();
910  $rl->register( [
911  'foo' => $module,
912  ] );
914  [ 'modules' => 'foo', 'only' => 'scripts' ],
915  $rl
916  );
917 
918  $modules = [ 'foo' => $rl->getModule( 'foo' ) ];
919  $response = $rl->makeModuleResponse( $context, $modules );
920  $extraHeaders = TestingAccessWrapper::newFromObject( $rl )->extraHeaders;
921 
922  $this->assertEquals(
923  [
924  'Link: <https://example.org/script.js>;rel=preload;as=script'
925  ],
926  $extraHeaders,
927  'Extra headers'
928  );
929  }
930 
937  $foo = $this->getMockBuilder( ResourceLoaderTestModule::class )
938  ->setMethods( [ 'getPreloadLinks' ] )->getMock();
939  $foo->method( 'getPreloadLinks' )->willReturn( [
940  'https://example.org/script.js' => [ 'as' => 'script' ],
941  ] );
942 
943  $bar = $this->getMockBuilder( ResourceLoaderTestModule::class )
944  ->setMethods( [ 'getPreloadLinks' ] )->getMock();
945  $bar->method( 'getPreloadLinks' )->willReturn( [
946  '/example.png' => [ 'as' => 'image' ],
947  '/example.jpg' => [ 'as' => 'image' ],
948  ] );
949 
950  $rl = new EmptyResourceLoader();
951  $rl->register( [ 'foo' => $foo, 'bar' => $bar ] );
953  [ 'modules' => 'foo|bar', 'only' => 'scripts' ],
954  $rl
955  );
956 
957  $modules = [ 'foo' => $rl->getModule( 'foo' ), 'bar' => $rl->getModule( 'bar' ) ];
958  $response = $rl->makeModuleResponse( $context, $modules );
959  $extraHeaders = TestingAccessWrapper::newFromObject( $rl )->extraHeaders;
960  $this->assertEquals(
961  [
962  'Link: <https://example.org/script.js>;rel=preload;as=script',
963  'Link: </example.png>;rel=preload;as=image,</example.jpg>;rel=preload;as=image'
964  ],
965  $extraHeaders,
966  'Extra headers'
967  );
968  }
969 
973  public function testRespondEmpty() {
974  $rl = $this->getMockBuilder( EmptyResourceLoader::class )
975  ->setMethods( [
976  'tryRespondNotModified',
977  'sendResponseHeaders',
978  'measureResponseTime',
979  ] )
980  ->getMock();
981  $context = $this->getResourceLoaderContext( [ 'modules' => '' ], $rl );
982 
983  $rl->expects( $this->once() )->method( 'measureResponseTime' );
984  $this->expectOutputRegex( '/no modules were requested/' );
985 
986  $rl->respond( $context );
987  }
988 
992  public function testRespondSimple() {
993  $module = new ResourceLoaderTestModule( [ 'script' => 'foo();' ] );
994  $rl = $this->getMockBuilder( EmptyResourceLoader::class )
995  ->setMethods( [
996  'measureResponseTime',
997  'tryRespondNotModified',
998  'sendResponseHeaders',
999  'makeModuleResponse',
1000  ] )
1001  ->getMock();
1002  $rl->register( 'test', $module );
1004  [ 'modules' => 'test', 'only' => null ],
1005  $rl
1006  );
1007 
1008  $rl->expects( $this->once() )->method( 'makeModuleResponse' )
1009  ->with( $context, [ 'test' => $module ] )
1010  ->willReturn( 'implement_foo;' );
1011  $this->expectOutputRegex( '/^implement_foo;/' );
1012 
1013  $rl->respond( $context );
1014  }
1015 
1019  public function testRespondInternalFailures() {
1020  $module = new ResourceLoaderTestModule( [ 'script' => 'foo();' ] );
1021  $rl = $this->getMockBuilder( EmptyResourceLoader::class )
1022  ->setMethods( [
1023  'measureResponseTime',
1024  'preloadModuleInfo',
1025  'getCombinedVersion',
1026  'tryRespondNotModified',
1027  'makeModuleResponse',
1028  'sendResponseHeaders',
1029  ] )
1030  ->getMock();
1031  $rl->register( 'test', $module );
1032  $context = $this->getResourceLoaderContext( [ 'modules' => 'test' ], $rl );
1033  // Disable logging from outputErrorAndLog
1034  $this->setLogger( 'exception', new Psr\Log\NullLogger() );
1035 
1036  $rl->expects( $this->once() )->method( 'preloadModuleInfo' )
1037  ->willThrowException( new Exception( 'Preload error' ) );
1038  $rl->expects( $this->once() )->method( 'getCombinedVersion' )
1039  ->willThrowException( new Exception( 'Version error' ) );
1040  $rl->expects( $this->once() )->method( 'makeModuleResponse' )
1041  ->with( $context, [ 'test' => $module ] )
1042  ->willReturn( 'foo;' );
1043  // Internal errors should be caught and logged without affecting module output
1044  $this->expectOutputRegex( '/^\/\*.+Preload error.+Version error.+\*\/.*foo;/ms' );
1045 
1046  $rl->respond( $context );
1047  }
1048 
1052  public function testMeasureResponseTime() {
1053  $stats = $this->getMockBuilder( NullStatsdDataFactory::class )
1054  ->setMethods( [ 'timing' ] )->getMock();
1055  $this->setService( 'StatsdDataFactory', $stats );
1056 
1057  $stats->expects( $this->once() )->method( 'timing' )
1058  ->with( 'resourceloader.responseTime', $this->anything() );
1059 
1060  $timing = new Timing();
1061  $timing->mark( 'requestShutdown' );
1062  $rl = TestingAccessWrapper::newFromObject( new EmptyResourceLoader );
1063  $rl->measureResponseTime( $timing );
1065  }
1066 }
ResourceLoaderTest\setUp
setUp()
Definition: ResourceLoaderTest.php:7
ResourceLoaderTest\testIsFileModule
testIsFileModule( $expected, $module)
provideTestIsFileModule ResourceLoader::isFileModule
Definition: ResourceLoaderTest.php:166
ResourceLoaderTest\testRespondSimple
testRespondSimple()
ResourceLoader::respond.
Definition: ResourceLoaderTest.php:992
ResourceLoaderTest\testMakePackedModulesString
testMakePackedModulesString( $desc, $modules, $packed)
providePackedModules ResourceLoader::makePackedModulesString
Definition: ResourceLoaderTest.php:289
ResourceLoaderTest\testConstructRegistrationHook
testConstructRegistrationHook()
Ensure the ResourceLoaderRegisterModules hook is called.
Definition: ResourceLoaderTest.php:20
ResourceLoaderTest\testRegisterInvalidType
testRegisterInvalidType()
ResourceLoader::register.
Definition: ResourceLoaderTest.php:84
ResourceLoaderTest\testGetModuleClassDefault
testGetModuleClassDefault()
ResourceLoader::getModule.
Definition: ResourceLoaderTest.php:230
$context
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on and they can depend only on the ResourceLoaderContext $context
Definition: hooks.txt:2683
ResourceLoaderTest\getSimpleStyleModuleMock
getSimpleStyleModuleMock( $styles='')
Definition: ResourceLoaderTest.php:624
ResourceLoaderTest
Definition: ResourceLoaderTest.php:5
ResourceLoaderTest\testRegisterDuplicate
testRegisterDuplicate()
ResourceLoader::register.
Definition: ResourceLoaderTest.php:93
ResourceLoaderTest\testLessImportDirs
testLessImportDirs()
ResourceLoader::getLessCompiler.
Definition: ResourceLoaderTest.php:243
ResourceLoaderTest\testIsFileModuleUnknown
testIsFileModuleUnknown()
ResourceLoader::isFileModule.
Definition: ResourceLoaderTest.php:175
ResourceLoaderTest\testMakeModuleResponseError
testMakeModuleResponseError()
Verify that when building module content in a load.php response, an exception from one module will no...
Definition: ResourceLoaderTest.php:769
ResourceLoaderTest\testRegisterInvalidName
testRegisterInvalidName()
ResourceLoader::register.
Definition: ResourceLoaderTest.php:75
anything
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such and we might be restricted by PHP settings such as safe mode or open_basedir We cannot assume that the software even has read access anywhere useful Many shared hosts run all users web applications under the same so they can t rely on Unix and must forbid reads to even standard directories like tmp lest users read each others files We cannot assume that the user has the ability to install or run any programs not written as web accessible PHP scripts Since anything that works on cheap shared hosting will work if you have shell or root access MediaWiki s design is based around catering to the lowest common denominator Although we support higher end setups as the way many things work by default is tailored toward shared hosting These defaults are unconventional from the point of view of and they certainly aren t ideal for someone who s installing MediaWiki as MediaWiki does not conform to normal Unix filesystem layout Hopefully we ll offer direct support for standard layouts in the but for now *any change to the location of files is unsupported *Moving things and leaving symlinks will *probably *not break anything
Definition: distributors.txt:39
ResourceLoaderContext\expandModuleNames
static expandModuleNames( $modules)
Expand a string of the form jquery.foo,bar|jquery.ui.baz,quux to an array of module names like ‘[ 'jq...
Definition: ResourceLoaderContext.php:106
ResourceLoaderTest\testMakeLoaderImplementScriptInvalid
testMakeLoaderImplementScriptInvalid()
ResourceLoader::makeLoaderImplementScript.
Definition: ResourceLoaderTest.php:472
ResourceLoaderTest\testGetModuleNames
testGetModuleNames()
ResourceLoader::getModuleNames.
Definition: ResourceLoaderTest.php:109
$resourceLoader
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on and they can depend only on the ResourceLoaderContext such as when responding to a resource loader request or generating HTML output & $resourceLoader
Definition: hooks.txt:2683
ResourceLoaderTest\provideTestIsFileModule
provideTestIsFileModule()
Definition: ResourceLoaderTest.php:120
ResourceLoaderTest\testGetModuleClass
testGetModuleClass()
ResourceLoader::getModule.
Definition: ResourceLoaderTest.php:201
php
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
$debug
$debug
Definition: mcc.php:31
XmlJsCode
A wrapper class which causes Xml::encodeJsVar() and Xml::encodeJsCall() to interpret a given string a...
Definition: XmlJsCode.php:39
ResourceLoaderTest\provideAddSource
static provideAddSource()
Definition: ResourceLoaderTest.php:305
MWException
MediaWiki exception.
Definition: MWException.php:26
$css
$css
Definition: styleTest.css.php:54
ResourceLoaderTest\testMakeLoaderSourcesScript
testMakeLoaderSourcesScript()
ResourceLoader::makeLoaderSourcesScript.
Definition: ResourceLoaderTest.php:544
Timing
An interface to help developers measure the performance of their applications.
Definition: Timing.php:45
MediaWikiTestCase\setMwGlobals
setMwGlobals( $pairs, $value=null)
Sets a global, maintaining a stashed version of the previous global to be restored in tearDown.
Definition: MediaWikiTestCase.php:706
$modules
$modules
Definition: HTMLFormElement.php:12
ResourceLoaderTest\testRespondInternalFailures
testRespondInternalFailures()
ResourceLoader::respond.
Definition: ResourceLoaderTest.php:1019
use
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:10
ResourceLoaderTest\testAddSourceDupe
testAddSourceDupe()
ResourceLoader::addSource.
Definition: ResourceLoaderTest.php:340
ResourceLoaderTest\testMakeLoaderRegisterScript
testMakeLoaderRegisterScript()
ResourceLoader::makeLoaderRegisterScript.
Definition: ResourceLoaderTest.php:487
array
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
ResourceLoaderTest\testGetLoadScript
testGetLoadScript()
ResourceLoader::getLoadScript.
Definition: ResourceLoaderTest.php:589
ResourceLoaderTestModule
Definition: ResourceLoaderTestCase.php:86
ResourceLoaderTest\testRegisterValidArray
testRegisterValidArray()
ResourceLoader::register ResourceLoader::getModule.
Definition: ResourceLoaderTest.php:53
ResourceLoaderTest\provideMakeModuleResponseConcat
static provideMakeModuleResponseConcat()
Definition: ResourceLoaderTest.php:667
$name
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:302
ResourceLoaderTest\testRegisterEmptyString
testRegisterEmptyString()
ResourceLoader::register.
Definition: ResourceLoaderTest.php:65
$e
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2221
ResourceLoaderTest\testMakeModuleResponseExtraHeaders
testMakeModuleResponseExtraHeaders()
Integration test for modules sending extra HTTP response headers.
Definition: ResourceLoaderTest.php:902
ResourceLoaderTest\testMakeLoaderImplementScript
testMakeLoaderImplementScript( $case)
provideLoaderImplement ResourceLoader::makeLoaderImplementScript ResourceLoader::trimArray
Definition: ResourceLoaderTest.php:446
ResourceLoaderTest\testMakeModuleResponseConcat
testMakeModuleResponseConcat( $scripts, $expected, $debug, $message=null)
Verify how multiple scripts and mw.loader.state() calls are concatenated.
Definition: ResourceLoaderTest.php:726
ResourceLoaderTest\testRegisterValidObject
testRegisterValidObject()
ResourceLoader::register ResourceLoader::getModule.
Definition: ResourceLoaderTest.php:42
$ret
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses & $ret
Definition: hooks.txt:2044
ResourceLoaderTest\testRespondEmpty
testRespondEmpty()
ResourceLoader::respond.
Definition: ResourceLoaderTest.php:973
ResourceLoaderTest\testMakeModuleResponseErrorCSS
testMakeModuleResponseErrorCSS()
Verify that exceptions in PHP for one module will not break others (stylesheet response).
Definition: ResourceLoaderTest.php:809
ResourceLoaderTest\getSimpleModuleMock
getSimpleModuleMock( $script='')
Definition: ResourceLoaderTest.php:616
$response
this hook is for auditing only $response
Definition: hooks.txt:813
DeferredUpdates\doUpdates
static doUpdates( $mode='run', $stage=self::ALL)
Do any deferred updates and clear the list.
Definition: DeferredUpdates.php:130
ResourceLoaderTest\testExpandModuleNames
testExpandModuleNames( $desc, $modules, $packed, $unpacked=null)
providePackedModules ResourceLoaderContext::expandModuleNames
Definition: ResourceLoaderTest.php:297
ResourceLoaderTest\testGetCombinedVersion
testGetCombinedVersion()
ResourceLoader::getCombinedVersion.
Definition: ResourceLoaderTest.php:635
ResourceLoaderTest\testAddSourceInvalid
testAddSourceInvalid()
ResourceLoader::addSource.
Definition: ResourceLoaderTest.php:352
MediaWikiTestCase\setLogger
setLogger( $channel, LoggerInterface $logger)
Sets the logger for a specified channel, for the duration of the test.
Definition: MediaWikiTestCase.php:1115
ResourceLoaderTest\testMakeModuleResponseExtraHeadersMulti
testMakeModuleResponseExtraHeadersMulti()
ResourceLoaderModule::getHeaders ResourceLoaderModule::buildContent ResourceLoader::makeModuleRespons...
Definition: ResourceLoaderTest.php:936
EmptyResourceLoader
Definition: ResourceLoaderTestCase.php:173
ResourceLoaderTest\testGetModuleFactory
testGetModuleFactory()
ResourceLoader::getModule.
Definition: ResourceLoaderTest.php:213
ResourceLoaderTest\testMeasureResponseTime
testMeasureResponseTime()
ResourceLoader::measureResponseTime.
Definition: ResourceLoaderTest.php:1052
ResourceLoaderTestCase\getResourceLoaderContext
getResourceLoaderContext( $options=[], ResourceLoader $rl=null)
Definition: ResourceLoaderTestCase.php:23
ResourceLoaderTest\testIsModuleRegistered
testIsModuleRegistered()
ResourceLoader::isModuleRegistered.
Definition: ResourceLoaderTest.php:183
ResourceLoaderTest\fakeSources
static fakeSources()
Definition: ResourceLoaderTest.php:573
as
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
$basePath
$basePath
Definition: addSite.php:5
ResourceLoaderTest\getFailFerryMock
getFailFerryMock( $getter='getScript')
Definition: ResourceLoaderTest.php:606
$source
$source
Definition: mwdoc-filter.php:46
ResourceLoaderTest\providePackedModules
static providePackedModules()
Definition: ResourceLoaderTest.php:254
class
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
Definition: maintenance.txt:52
ResourceLoaderTest\testGetModuleUnknown
testGetModuleUnknown()
ResourceLoader::getModule.
Definition: ResourceLoaderTest.php:193
ResourceLoaderTest\testMakeModuleResponseStartupError
testMakeModuleResponseStartupError()
Verify that when building the startup module response, an exception from one module class will not br...
Definition: ResourceLoaderTest.php:847
MediaWikiTestCase\setService
setService( $name, $object)
Sets a service, maintaining a stashed version of the previous service to be restored in tearDown.
Definition: MediaWikiTestCase.php:646
ResourceLoaderTest\provideLoaderImplement
static provideLoaderImplement()
Definition: ResourceLoaderTest.php:358
ResourceLoaderTest\testMakeModuleResponseEmpty
testMakeModuleResponseEmpty()
ResourceLoader::makeModuleResponse.
Definition: ResourceLoaderTest.php:750
ResourceLoaderTest\testAddSource
testAddSource( $name, $info, $expected)
provideAddSource ResourceLoader::addSource ResourceLoader::getSources
Definition: ResourceLoaderTest.php:325
ResourceLoaderTestCase
Definition: ResourceLoaderTestCase.php:7