MediaWiki  master
ResourceLoaderTest.php
Go to the documentation of this file.
1 <?php
2 
5 
7 
8  protected function setUp() {
9  parent::setUp();
10 
11  $this->setMwGlobals( [
12  'wgShowExceptionDetails' => true,
13  ] );
14  }
15 
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 
61  public function testIsValidModuleName_invalid( $name ) {
62  $this->assertFalse( ResourceLoader::isValidModuleName( $name ) );
63  }
64 
69  public function testIsValidModuleName_valid( $name ) {
70  $this->assertTrue( ResourceLoader::isValidModuleName( $name ) );
71  }
72 
77  public function testRegisterValidObject() {
78  $module = new ResourceLoaderTestModule();
80  $resourceLoader->register( 'test', $module );
81  $this->assertEquals( $module, $resourceLoader->getModule( 'test' ) );
82  }
83 
88  public function testRegisterValidArray() {
89  $module = new ResourceLoaderTestModule();
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 
101  public function testRegisterEmptyString() {
102  $module = new ResourceLoaderTestModule();
104  $resourceLoader->register( '', $module );
105  $this->assertEquals( $module, $resourceLoader->getModule( '' ) );
106  }
107 
112  public function testRegisterInvalidName() {
114  $this->setExpectedException( MWException::class, "name 'test!invalid' is invalid" );
115  $resourceLoader->register( 'test!invalid', new ResourceLoaderTestModule() );
116  }
117 
121  public function testRegisterInvalidType() {
123  $this->setExpectedException( MWException::class, 'ResourceLoader module info type error' );
124  $resourceLoader->register( 'test', new stdClass() );
125  }
126 
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 
146  public function testGetModuleNames() {
147  // Use an empty one so that core and extension modules don't get in.
149  $resourceLoader->register( 'test.foo', new ResourceLoaderTestModule() );
150  $resourceLoader->register( 'test.bar', new ResourceLoaderTestModule() );
151  $this->assertEquals(
152  [ 'startup', '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,
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, [
190  'scripts' => [ 'MediaWiki:Example.js' ],
191  ] ],
192  ];
193  }
194 
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 
208  public function testIsFileModuleUnknown() {
209  $rl = TestingAccessWrapper::newFromObject( new EmptyResourceLoader() );
210  $this->assertSame( false, $rl->isFileModule( 'unknown' ) );
211  }
212 
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 
226  public function testGetModuleUnknown() {
227  $rl = new EmptyResourceLoader();
228  $this->assertSame( null, $rl->getModule( 'test' ) );
229  }
230 
234  public function testGetModuleClass() {
235  $rl = new EmptyResourceLoader();
236  $rl->register( 'test', [ 'class' => ResourceLoaderTestModule::class ] );
237  $this->assertInstanceOf(
239  $rl->getModule( 'test' )
240  );
241  }
242 
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(
256  $rl->getModule( 'test' )
257  );
258  }
259 
263  public function testGetModuleClassDefault() {
264  $rl = new EmptyResourceLoader();
265  $rl->register( 'test', [] );
266  $this->assertInstanceOf(
268  $rl->getModule( 'test' ),
269  'Array-style module registrations default to FileModule'
270  );
271  }
272 
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 
322  public function testMakePackedModulesString( $desc, $modules, $packed ) {
323  $this->assertEquals( $packed, ResourceLoader::makePackedModulesString( $modules ), $desc );
324  }
325 
330  public function testExpandModuleNames( $desc, $modules, $packed, $unpacked = null ) {
331  $this->assertEquals(
332  $unpacked ?: $modules,
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 
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() );
364  }
365  } else {
366  $this->assertArrayHasKey( $expected, $rl->getSources() );
367  }
368  }
369 
373  public function testAddSourceDupe() {
374  $rl = new EmptyResourceLoader;
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 
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' ] );
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 
518  public function testMakeLoaderImplementScript( $case ) {
519  $case += [
520  'wrap' => true,
521  'styles' => [], 'templates' => [], 'messages' => new XmlJsCode( '{}' ), 'packageFiles' => [],
522  ];
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 
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 
561  public function testMakeLoaderRegisterScript() {
562  $this->assertEquals(
563  'mw.loader.register( [
564  [
565  "test.name",
566  "1234567"
567  ]
568 ] );',
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 ] );',
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 
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 } );',
637  'local' => '/w/load.php',
638  'example' => 'https://example.org/w/load.php'
639  ] )
640  );
641  $this->assertEquals(
642  'mw.loader.addSource( [] );',
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 
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'] );
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 
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 
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 
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 
823  public function testMakeModuleResponseEmpty() {
824  $rl = new EmptyResourceLoader();
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 
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 );
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 
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 );
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 
922  // This is an integration test that uses a lot of MediaWiki state,
923  // provide the full Config object here.
924  $rl = new EmptyResourceLoader( MediaWikiServices::getInstance()->getMainConfig() );
925  $rl->register( [
926  'foo' => self::getSimpleModuleMock( 'foo();' ),
927  'ferry' => self::getFailFerryMock(),
928  'bar' => self::getSimpleModuleMock( 'bar();' ),
929  ] );
931  [
932  'modules' => 'startup',
933  'only' => 'scripts',
934  ],
935  $rl
936  );
937 
938  $this->assertEquals(
939  [ 'startup', 'foo', 'ferry', 'bar' ],
940  $rl->getModuleNames(),
941  'getModuleNames'
942  );
943 
944  // Disable log from makeModuleResponse via outputErrorAndLog
945  $this->setLogger( 'exception', new Psr\Log\NullLogger() );
946 
947  $modules = [ 'startup' => $rl->getModule( 'startup' ) ];
948  $response = $rl->makeModuleResponse( $context, $modules );
949  $errors = $rl->getErrors();
950 
951  $this->assertRegExp( '/Ferry not found/', $errors[0] );
952  $this->assertCount( 1, $errors );
953  $this->assertRegExp(
954  '/isCompatible.*window\.RLQ/s',
955  $response,
956  'startup response undisrupted (T152266)'
957  );
958  $this->assertRegExp(
959  '/register\([^)]+"ferry",\s*""/s',
960  $response,
961  'startup response registers broken module'
962  );
963  $this->assertRegExp(
964  '/state\([^)]+"ferry":\s*"error"/s',
965  $response,
966  'startup response sets state to error'
967  );
968  }
969 
978  $module = $this->getMockBuilder( ResourceLoaderTestModule::class )
979  ->setMethods( [ 'getPreloadLinks' ] )->getMock();
980  $module->method( 'getPreloadLinks' )->willReturn( [
981  'https://example.org/script.js' => [ 'as' => 'script' ],
982  ] );
983 
984  $rl = new EmptyResourceLoader();
985  $rl->register( [
986  'foo' => $module,
987  ] );
989  [ 'modules' => 'foo', 'only' => 'scripts' ],
990  $rl
991  );
992 
993  $modules = [ 'foo' => $rl->getModule( 'foo' ) ];
994  $response = $rl->makeModuleResponse( $context, $modules );
995  $extraHeaders = TestingAccessWrapper::newFromObject( $rl )->extraHeaders;
996 
997  $this->assertEquals(
998  [
999  'Link: <https://example.org/script.js>;rel=preload;as=script'
1000  ],
1001  $extraHeaders,
1002  'Extra headers'
1003  );
1004  }
1005 
1012  $foo = $this->getMockBuilder( ResourceLoaderTestModule::class )
1013  ->setMethods( [ 'getPreloadLinks' ] )->getMock();
1014  $foo->method( 'getPreloadLinks' )->willReturn( [
1015  'https://example.org/script.js' => [ 'as' => 'script' ],
1016  ] );
1017 
1018  $bar = $this->getMockBuilder( ResourceLoaderTestModule::class )
1019  ->setMethods( [ 'getPreloadLinks' ] )->getMock();
1020  $bar->method( 'getPreloadLinks' )->willReturn( [
1021  '/example.png' => [ 'as' => 'image' ],
1022  '/example.jpg' => [ 'as' => 'image' ],
1023  ] );
1024 
1025  $rl = new EmptyResourceLoader();
1026  $rl->register( [ 'foo' => $foo, 'bar' => $bar ] );
1028  [ 'modules' => 'foo|bar', 'only' => 'scripts' ],
1029  $rl
1030  );
1031 
1032  $modules = [ 'foo' => $rl->getModule( 'foo' ), 'bar' => $rl->getModule( 'bar' ) ];
1033  $response = $rl->makeModuleResponse( $context, $modules );
1034  $extraHeaders = TestingAccessWrapper::newFromObject( $rl )->extraHeaders;
1035  $this->assertEquals(
1036  [
1037  'Link: <https://example.org/script.js>;rel=preload;as=script',
1038  'Link: </example.png>;rel=preload;as=image,</example.jpg>;rel=preload;as=image'
1039  ],
1040  $extraHeaders,
1041  'Extra headers'
1042  );
1043  }
1044 
1048  public function testRespondEmpty() {
1049  $rl = $this->getMockBuilder( EmptyResourceLoader::class )
1050  ->setMethods( [
1051  'tryRespondNotModified',
1052  'sendResponseHeaders',
1053  'measureResponseTime',
1054  ] )
1055  ->getMock();
1056  $context = $this->getResourceLoaderContext( [ 'modules' => '' ], $rl );
1057 
1058  $rl->expects( $this->once() )->method( 'measureResponseTime' );
1059  $this->expectOutputRegex( '/no modules were requested/' );
1060 
1061  $rl->respond( $context );
1062  }
1063 
1067  public function testRespondSimple() {
1068  $module = new ResourceLoaderTestModule( [ 'script' => 'foo();' ] );
1069  $rl = $this->getMockBuilder( EmptyResourceLoader::class )
1070  ->setMethods( [
1071  'measureResponseTime',
1072  'tryRespondNotModified',
1073  'sendResponseHeaders',
1074  'makeModuleResponse',
1075  ] )
1076  ->getMock();
1077  $rl->register( 'test', $module );
1079  [ 'modules' => 'test', 'only' => null ],
1080  $rl
1081  );
1082 
1083  $rl->expects( $this->once() )->method( 'makeModuleResponse' )
1084  ->with( $context, [ 'test' => $module ] )
1085  ->willReturn( 'implement_foo;' );
1086  $this->expectOutputRegex( '/^implement_foo;/' );
1087 
1088  $rl->respond( $context );
1089  }
1090 
1094  public function testRespondInternalFailures() {
1095  $module = new ResourceLoaderTestModule( [ 'script' => 'foo();' ] );
1096  $rl = $this->getMockBuilder( EmptyResourceLoader::class )
1097  ->setMethods( [
1098  'measureResponseTime',
1099  'preloadModuleInfo',
1100  'getCombinedVersion',
1101  'tryRespondNotModified',
1102  'makeModuleResponse',
1103  'sendResponseHeaders',
1104  ] )
1105  ->getMock();
1106  $rl->register( 'test', $module );
1107  $context = $this->getResourceLoaderContext( [ 'modules' => 'test' ], $rl );
1108  // Disable logging from outputErrorAndLog
1109  $this->setLogger( 'exception', new Psr\Log\NullLogger() );
1110 
1111  $rl->expects( $this->once() )->method( 'preloadModuleInfo' )
1112  ->willThrowException( new Exception( 'Preload error' ) );
1113  $rl->expects( $this->once() )->method( 'getCombinedVersion' )
1114  ->willThrowException( new Exception( 'Version error' ) );
1115  $rl->expects( $this->once() )->method( 'makeModuleResponse' )
1116  ->with( $context, [ 'test' => $module ] )
1117  ->willReturn( 'foo;' );
1118  // Internal errors should be caught and logged without affecting module output
1119  $this->expectOutputRegex( '/^\/\*.+Preload error.+Version error.+\*\/.*foo;/ms' );
1120 
1121  $rl->respond( $context );
1122  }
1123 
1127  public function testMeasureResponseTime() {
1128  $stats = $this->getMockBuilder( NullStatsdDataFactory::class )
1129  ->setMethods( [ 'timing' ] )->getMock();
1130  $this->setService( 'StatsdDataFactory', $stats );
1131 
1132  $stats->expects( $this->once() )->method( 'timing' )
1133  ->with( 'resourceloader.responseTime', $this->anything() );
1134 
1135  $timing = new Timing();
1136  $timing->mark( 'requestShutdown' );
1137  $rl = TestingAccessWrapper::newFromObject( new EmptyResourceLoader );
1138  $rl->measureResponseTime( $timing );
1140  }
1141 }
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))
testAddSource( $name, $info, $expected)
provideAddSource ResourceLoader::addSource ResourceLoader::getSources
testAddSourceInvalid()
ResourceLoader::addSource.
testLessImportDirs()
ResourceLoader::getLessCompiler.
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:1982
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:2633
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2159
testGetModuleFactory()
ResourceLoader::getModule.
$basePath
Definition: addSite.php:5
testMeasureResponseTime()
ResourceLoader::measureResponseTime.
testMakeModuleResponseErrorCSS()
Verify that exceptions in PHP for one module will not break others (stylesheet response).
$source
testIsFileModuleUnknown()
ResourceLoader::isFileModule.
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 MediaWikiServices
Definition: injection.txt:23
testMakeLoaderRegisterScript()
ResourceLoader::makeLoaderRegisterScript.
testExpandModuleNames( $desc, $modules, $packed, $unpacked=null)
providePackedModules ResourceLoader::expandModuleNames
testGetModuleNames()
ResourceLoader::getModuleNames.
this hook is for auditing only $response
Definition: hooks.txt:780
static provideMakeModuleResponseConcat()
testRespondEmpty()
ResourceLoader::respond.
testGetLoadScript()
ResourceLoader::getLoadScript.
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
testMakeLoaderImplementScriptInvalid()
ResourceLoader::makeLoaderImplementScript.
testIsModuleRegistered()
ResourceLoader::isModuleRegistered.
testGetModuleClass()
ResourceLoader::getModule.
getResourceLoaderContext( $options=[], ResourceLoader $rl=null)
testMakeModuleResponseError()
Verify that when building module content in a load.php response, an exception from one module will no...
$modules
testMakeModuleResponseStartupError()
Verify that when building the startup module response, an exception from one module class will not br...
static makeHash( $value)
$css
testRegisterInvalidType()
ResourceLoader::register.
testRespondInternalFailures()
ResourceLoader::respond.
testMakePackedModulesString( $desc, $modules, $packed)
providePackedModules ResourceLoader::makePackedModulesString
A wrapper class which causes Xml::encodeJsVar() and Xml::encodeJsCall() to interpret a given string a...
Definition: XmlJsCode.php:40
An interface to help developers measure the performance of their applications.
Definition: Timing.php:45
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:780
testGetCombinedVersion()
ResourceLoader::getCombinedVersion.
overrideMwServices(Config $configOverrides=null, array $services=[])
Stashes the global instance of MediaWikiServices, and installs a new one, allowing test cases to over...
setMwGlobals( $pairs, $value=null)
Sets a global, maintaining a stashed version of the previous global to be restored in tearDown...
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
testRespondSimple()
ResourceLoader::respond.
getSimpleModuleMock( $script='')
setService( $name, $object)
Sets a service, maintaining a stashed version of the previous service to be restored in tearDown...
testRegisterDuplicate()
ResourceLoader::register.
static isValidModuleName( $moduleName)
Check a module name for validity.
testMakeModuleResponseExtraHeaders()
Integration test for modules sending extra HTTP response headers.
static clearCache()
Reset static members used for caching.
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
static doUpdates( $mode='run', $stage=self::ALL)
Do any deferred updates and clear the list.
testIsValidModuleName_invalid( $name)
provideInvalidModuleName ResourceLoader
testIsValidModuleName_valid( $name)
provideValidModuleName ResourceLoader
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
testMakeLoaderImplementScript( $case)
provideLoaderImplement ResourceLoader::makeLoaderImplementScript ResourceLoader::trimArray ...
testMakeModuleResponseExtraHeadersMulti()
ResourceLoaderModule::getHeaders ResourceLoaderModule::buildContent ResourceLoader::makeModuleRespons...
testServiceWiring()
Ensure the ResourceLoaderRegisterModules hook is called.
static makePackedModulesString( $modules)
Convert an array of module names to a packed query string.
static makeLoaderSourcesScript( $sources, $loadUrl=null)
Returns JS code which calls mw.loader.addSource() with the given parameters.
getFailFerryMock( $getter='getScript')
getSimpleStyleModuleMock( $styles='')
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:2633
static expandModuleNames( $modules)
Expand a string of the form jquery.foo,bar|jquery.ui.baz,quux to an array of module names like `[ &#39;jq...
static makeLoaderRegisterScript(array $modules)
Returns JS code which calls mw.loader.register with the given parameter.
addSource( $id, $loadUrl=null)
Add a foreign source of modules.
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:271
testRegisterEmptyString()
ResourceLoader::register medium.
testGetModuleClassDefault()
ResourceLoader::getModule.
$debug
Definition: mcc.php:31
testAddSourceDupe()
ResourceLoader::addSource.
testRegisterValidArray()
ResourceLoader::register ResourceLoader::getModule.
setLogger( $channel, LoggerInterface $logger)
Sets the logger for a specified channel, for the duration of the test.
testMakeLoaderSourcesScript()
ResourceLoader::makeLoaderSourcesScript.
testMakeModuleResponseConcat( $scripts, $expected, $debug, $message=null)
Verify how multiple scripts and mw.loader.state() calls are concatenated.
testRegisterValidObject()
ResourceLoader::register ResourceLoader::getModule.
testIsFileModule( $expected, $module)
provideTestIsFileModule ResourceLoader::isFileModule
testMakeModuleResponseEmpty()
ResourceLoader::makeModuleResponse.
testRegisterInvalidName()
ResourceLoader::register medium.
testGetModuleUnknown()
ResourceLoader::getModule.