MediaWiki  1.33.0
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  'WikiModule' => [ false, [
153  'scripts' => [ 'MediaWiki:Example.js' ],
154  ] ],
155  ];
156  }
157 
162  public function testIsFileModule( $expected, $module ) {
163  $rl = TestingAccessWrapper::newFromObject( new EmptyResourceLoader() );
164  $rl->register( 'test', $module );
165  $this->assertSame( $expected, $rl->isFileModule( 'test' ) );
166  }
167 
171  public function testIsFileModuleUnknown() {
172  $rl = TestingAccessWrapper::newFromObject( new EmptyResourceLoader() );
173  $this->assertSame( false, $rl->isFileModule( 'unknown' ) );
174  }
175 
179  public function testIsModuleRegistered() {
180  $rl = new EmptyResourceLoader();
181  $rl->register( 'test', new ResourceLoaderTestModule() );
182  $this->assertTrue( $rl->isModuleRegistered( 'test' ) );
183  $this->assertFalse( $rl->isModuleRegistered( 'test.unknown' ) );
184  }
185 
189  public function testGetModuleUnknown() {
190  $rl = new EmptyResourceLoader();
191  $this->assertSame( null, $rl->getModule( 'test' ) );
192  }
193 
197  public function testGetModuleClass() {
198  $rl = new EmptyResourceLoader();
199  $rl->register( 'test', [ 'class' => ResourceLoaderTestModule::class ] );
200  $this->assertInstanceOf(
202  $rl->getModule( 'test' )
203  );
204  }
205 
209  public function testGetModuleFactory() {
210  $factory = function ( array $info ) {
211  $this->assertArrayHasKey( 'kitten', $info );
212  return new ResourceLoaderTestModule( $info );
213  };
214 
215  $rl = new EmptyResourceLoader();
216  $rl->register( 'test', [ 'factory' => $factory, 'kitten' => 'little ball of fur' ] );
217  $this->assertInstanceOf(
219  $rl->getModule( 'test' )
220  );
221  }
222 
226  public function testGetModuleClassDefault() {
227  $rl = new EmptyResourceLoader();
228  $rl->register( 'test', [] );
229  $this->assertInstanceOf(
231  $rl->getModule( 'test' ),
232  'Array-style module registrations default to FileModule'
233  );
234  }
235 
239  public function testLessImportDirs() {
240  $rl = new EmptyResourceLoader();
241  $lc = $rl->getLessCompiler( [ 'foo' => '2px', 'Foo' => '#eeeeee' ] );
242  $basePath = dirname( dirname( __DIR__ ) ) . '/data/less';
243  $lc->SetImportDirs( [
244  "$basePath/common" => '',
245  ] );
246  $css = $lc->parseFile( "$basePath/module/use-import-dir.less" )->getCss();
247  $this->assertStringEqualsFile( "$basePath/module/styles.css", $css );
248  }
249 
250  public static function providePackedModules() {
251  return [
252  [
253  'Example from makePackedModulesString doc comment',
254  [ 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' ],
255  'foo.bar,baz|bar.baz,quux',
256  ],
257  [
258  'Example from expandModuleNames doc comment',
259  [ 'jquery.foo', 'jquery.bar', 'jquery.ui.baz', 'jquery.ui.quux' ],
260  'jquery.foo,bar|jquery.ui.baz,quux',
261  ],
262  [
263  'Regression fixed in r87497 (7fee86c38e) with dotless names',
264  [ 'foo', 'bar', 'baz' ],
265  'foo,bar,baz',
266  ],
267  [
268  'Prefixless modules after a prefixed module',
269  [ 'single.module', 'foobar', 'foobaz' ],
270  'single.module|foobar,foobaz',
271  ],
272  [
273  'Ordering',
274  [ 'foo', 'foo.baz', 'baz.quux', 'foo.bar' ],
275  'foo|foo.baz,bar|baz.quux',
276  [ 'foo', 'foo.baz', 'foo.bar', 'baz.quux' ],
277  ]
278  ];
279  }
280 
285  public function testMakePackedModulesString( $desc, $modules, $packed ) {
286  $this->assertEquals( $packed, ResourceLoader::makePackedModulesString( $modules ), $desc );
287  }
288 
293  public function testExpandModuleNames( $desc, $modules, $packed, $unpacked = null ) {
294  $this->assertEquals(
295  $unpacked ?: $modules,
296  ResourceLoader::expandModuleNames( $packed ),
297  $desc
298  );
299  }
300 
301  public static function provideAddSource() {
302  return [
303  [ 'foowiki', 'https://example.org/w/load.php', 'foowiki' ],
304  [ 'foowiki', [ 'loadScript' => 'https://example.org/w/load.php' ], 'foowiki' ],
305  [
306  [
307  'foowiki' => 'https://example.org/w/load.php',
308  'bazwiki' => 'https://example.com/w/load.php',
309  ],
310  null,
311  [ 'foowiki', 'bazwiki' ]
312  ]
313  ];
314  }
315 
321  public function testAddSource( $name, $info, $expected ) {
322  $rl = new ResourceLoader;
323  $rl->addSource( $name, $info );
324  if ( is_array( $expected ) ) {
325  foreach ( $expected as $source ) {
326  $this->assertArrayHasKey( $source, $rl->getSources() );
327  }
328  } else {
329  $this->assertArrayHasKey( $expected, $rl->getSources() );
330  }
331  }
332 
336  public function testAddSourceDupe() {
337  $rl = new ResourceLoader;
338  $this->setExpectedException(
339  MWException::class, 'ResourceLoader duplicate source addition error'
340  );
341  $rl->addSource( 'foo', 'https://example.org/w/load.php' );
342  $rl->addSource( 'foo', 'https://example.com/w/load.php' );
343  }
344 
348  public function testAddSourceInvalid() {
349  $rl = new ResourceLoader;
350  $this->setExpectedException( MWException::class, 'with no "loadScript" key' );
351  $rl->addSource( 'foo', [ 'x' => 'https://example.org/w/load.php' ] );
352  }
353 
354  public static function provideLoaderImplement() {
355  return [
356  [ [
357  'title' => 'Implement scripts, styles and messages',
358 
359  'name' => 'test.example',
360  'scripts' => 'mw.example();',
361  'styles' => [ 'css' => [ '.mw-example {}' ] ],
362  'messages' => [ 'example' => '' ],
363  'templates' => [],
364 
365  'expected' => 'mw.loader.implement( "test.example", function ( $, jQuery, require, module ) {
366 mw.example();
367 }, {
368  "css": [
369  ".mw-example {}"
370  ]
371 }, {
372  "example": ""
373 } );',
374  ] ],
375  [ [
376  'title' => 'Implement scripts',
377 
378  'name' => 'test.example',
379  'scripts' => 'mw.example();',
380  'styles' => [],
381 
382  'expected' => 'mw.loader.implement( "test.example", function ( $, jQuery, require, module ) {
383 mw.example();
384 } );',
385  ] ],
386  [ [
387  'title' => 'Implement styles',
388 
389  'name' => 'test.example',
390  'scripts' => [],
391  'styles' => [ 'css' => [ '.mw-example {}' ] ],
392 
393  'expected' => 'mw.loader.implement( "test.example", [], {
394  "css": [
395  ".mw-example {}"
396  ]
397 } );',
398  ] ],
399  [ [
400  'title' => 'Implement scripts and messages',
401 
402  'name' => 'test.example',
403  'scripts' => 'mw.example();',
404  'messages' => [ 'example' => '' ],
405 
406  'expected' => 'mw.loader.implement( "test.example", function ( $, jQuery, require, module ) {
407 mw.example();
408 }, {}, {
409  "example": ""
410 } );',
411  ] ],
412  [ [
413  'title' => 'Implement scripts and templates',
414 
415  'name' => 'test.example',
416  'scripts' => 'mw.example();',
417  'templates' => [ 'example.html' => '' ],
418 
419  'expected' => 'mw.loader.implement( "test.example", function ( $, jQuery, require, module ) {
420 mw.example();
421 }, {}, {}, {
422  "example.html": ""
423 } );',
424  ] ],
425  [ [
426  'title' => 'Implement unwrapped user script',
427 
428  'name' => 'user',
429  'scripts' => 'mw.example( 1 );',
430  'wrap' => false,
431 
432  'expected' => 'mw.loader.implement( "user", "mw.example( 1 );" );',
433  ] ],
434  [ [
435  'title' => 'Implement multi-file script',
436 
437  'name' => 'test.multifile',
438  'scripts' => [
439  'files' => [
440  'one.js' => [
441  'type' => 'script',
442  'content' => 'mw.example( 1 );',
443  ],
444  'two.json' => [
445  'type' => 'data',
446  'content' => [ 'n' => 2 ],
447  ],
448  'three.js' => [
449  'type' => 'script',
450  'content' => 'mw.example( 3 );'
451  ],
452  ],
453  'main' => 'three.js',
454  ],
455 
456  'expected' => <<<END
457 mw.loader.implement( "test.multifile", {
458  "main": "three.js",
459  "files": {
460  "one.js": function ( require, module ) {
461 mw.example( 1 );
462 },
463  "two.json": {
464  "n": 2
465 },
466  "three.js": function ( require, module ) {
467 mw.example( 3 );
468 }
469 }
470 } );
471 END
472  ] ],
473  ];
474  }
475 
481  public function testMakeLoaderImplementScript( $case ) {
482  $case += [
483  'wrap' => true,
484  'styles' => [], 'templates' => [], 'messages' => new XmlJsCode( '{}' ), 'packageFiles' => [],
485  ];
486  ResourceLoader::clearCache();
487  $this->setMwGlobals( 'wgResourceLoaderDebug', true );
488 
489  $rl = TestingAccessWrapper::newFromClass( ResourceLoader::class );
490  $this->assertEquals(
491  $case['expected'],
492  $rl->makeLoaderImplementScript(
493  $case['name'],
494  ( $case['wrap'] && is_string( $case['scripts'] ) )
495  ? new XmlJsCode( $case['scripts'] )
496  : $case['scripts'],
497  $case['styles'],
498  $case['messages'],
499  $case['templates'],
500  $case['packageFiles']
501  )
502  );
503  }
504 
509  $this->setExpectedException( MWException::class, 'Invalid scripts error' );
510  $rl = TestingAccessWrapper::newFromClass( ResourceLoader::class );
511  $rl->makeLoaderImplementScript(
512  'test', // name
513  123, // scripts
514  null, // styles
515  null, // messages
516  null, // templates
517  null // package files
518  );
519  }
520 
524  public function testMakeLoaderRegisterScript() {
525  $this->assertEquals(
526  'mw.loader.register( [
527  [
528  "test.name",
529  "1234567"
530  ]
531 ] );',
532  ResourceLoader::makeLoaderRegisterScript( [
533  [ 'test.name', '1234567' ],
534  ] ),
535  'Nested array parameter'
536  );
537 
538  $this->assertEquals(
539  'mw.loader.register( [
540  [
541  "test.foo",
542  "100"
543  ],
544  [
545  "test.bar",
546  "200",
547  [
548  "test.unknown"
549  ]
550  ],
551  [
552  "test.baz",
553  "300",
554  [
555  3,
556  0
557  ]
558  ],
559  [
560  "test.quux",
561  "400",
562  [],
563  null,
564  null,
565  "return true;"
566  ]
567 ] );',
568  ResourceLoader::makeLoaderRegisterScript( [
569  [ 'test.foo', '100' , [], null, null ],
570  [ 'test.bar', '200', [ 'test.unknown' ], null ],
571  [ 'test.baz', '300', [ 'test.quux', 'test.foo' ], null ],
572  [ 'test.quux', '400', [], null, null, 'return true;' ],
573  ] ),
574  'Compact dependency indexes'
575  );
576  }
577 
581  public function testMakeLoaderSourcesScript() {
582  $this->assertEquals(
583  'mw.loader.addSource( {
584  "local": "/w/load.php"
585 } );',
586  ResourceLoader::makeLoaderSourcesScript( 'local', '/w/load.php' )
587  );
588  $this->assertEquals(
589  'mw.loader.addSource( {
590  "local": "/w/load.php"
591 } );',
592  ResourceLoader::makeLoaderSourcesScript( [ 'local' => '/w/load.php' ] )
593  );
594  $this->assertEquals(
595  'mw.loader.addSource( {
596  "local": "/w/load.php",
597  "example": "https://example.org/w/load.php"
598 } );',
599  ResourceLoader::makeLoaderSourcesScript( [
600  'local' => '/w/load.php',
601  'example' => 'https://example.org/w/load.php'
602  ] )
603  );
604  $this->assertEquals(
605  'mw.loader.addSource( [] );',
606  ResourceLoader::makeLoaderSourcesScript( [] )
607  );
608  }
609 
610  private static function fakeSources() {
611  return [
612  'examplewiki' => [
613  'loadScript' => '//example.org/w/load.php',
614  'apiScript' => '//example.org/w/api.php',
615  ],
616  'example2wiki' => [
617  'loadScript' => '//example.com/w/load.php',
618  'apiScript' => '//example.com/w/api.php',
619  ],
620  ];
621  }
622 
626  public function testGetLoadScript() {
627  $rl = new ResourceLoader();
628  $sources = self::fakeSources();
629  $rl->addSource( $sources );
630  foreach ( [ 'examplewiki', 'example2wiki' ] as $name ) {
631  $this->assertEquals( $rl->getLoadScript( $name ), $sources[$name]['loadScript'] );
632  }
633 
634  try {
635  $rl->getLoadScript( 'thiswasneverreigstered' );
636  $this->assertTrue( false, 'ResourceLoader::getLoadScript should have thrown an exception' );
637  } catch ( MWException $e ) {
638  $this->assertTrue( true );
639  }
640  }
641 
642  protected function getFailFerryMock( $getter = 'getScript' ) {
643  $mock = $this->getMockBuilder( ResourceLoaderTestModule::class )
644  ->setMethods( [ $getter ] )
645  ->getMock();
646  $mock->method( $getter )->will( $this->throwException(
647  new Exception( 'Ferry not found' )
648  ) );
649  return $mock;
650  }
651 
652  protected function getSimpleModuleMock( $script = '' ) {
653  $mock = $this->getMockBuilder( ResourceLoaderTestModule::class )
654  ->setMethods( [ 'getScript' ] )
655  ->getMock();
656  $mock->method( 'getScript' )->willReturn( $script );
657  return $mock;
658  }
659 
660  protected function getSimpleStyleModuleMock( $styles = '' ) {
661  $mock = $this->getMockBuilder( ResourceLoaderTestModule::class )
662  ->setMethods( [ 'getStyles' ] )
663  ->getMock();
664  $mock->method( 'getStyles' )->willReturn( [ '' => $styles ] );
665  return $mock;
666  }
667 
671  public function testGetCombinedVersion() {
672  $rl = $this->getMockBuilder( EmptyResourceLoader::class )
673  // Disable log from outputErrorAndLog
674  ->setMethods( [ 'outputErrorAndLog' ] )->getMock();
675  $rl->register( [
676  'foo' => self::getSimpleModuleMock(),
677  'ferry' => self::getFailFerryMock(),
678  'bar' => self::getSimpleModuleMock(),
679  ] );
680  $context = $this->getResourceLoaderContext( [], $rl );
681 
682  $this->assertEquals(
683  '',
684  $rl->getCombinedVersion( $context, [] ),
685  'empty list'
686  );
687 
688  $this->assertEquals(
689  ResourceLoader::makeHash( self::BLANK_VERSION ),
690  $rl->getCombinedVersion( $context, [ 'foo' ] ),
691  'compute foo'
692  );
693 
694  // Verify that getCombinedVersion() does not throw when ferry fails.
695  // Instead it gracefully continues to combine the remaining modules.
696  $this->assertEquals(
697  ResourceLoader::makeHash( self::BLANK_VERSION . self::BLANK_VERSION ),
698  $rl->getCombinedVersion( $context, [ 'foo', 'ferry', 'bar' ] ),
699  'compute foo+ferry+bar (T152266)'
700  );
701  }
702 
703  public static function provideMakeModuleResponseConcat() {
704  $testcases = [
705  [
706  'modules' => [
707  'foo' => 'foo()',
708  ],
709  'expected' => "foo()\n" . 'mw.loader.state( {
710  "foo": "ready"
711 } );',
712  'minified' => "foo()\n" . 'mw.loader.state({"foo":"ready"});',
713  'message' => 'Script without semi-colon',
714  ],
715  [
716  'modules' => [
717  'foo' => 'foo()',
718  'bar' => 'bar()',
719  ],
720  'expected' => "foo()\nbar()\n" . 'mw.loader.state( {
721  "foo": "ready",
722  "bar": "ready"
723 } );',
724  'minified' => "foo()\nbar()\n" . 'mw.loader.state({"foo":"ready","bar":"ready"});',
725  'message' => 'Two scripts without semi-colon',
726  ],
727  [
728  'modules' => [
729  'foo' => "foo()\n// bar();"
730  ],
731  'expected' => "foo()\n// bar();\n" . 'mw.loader.state( {
732  "foo": "ready"
733 } );',
734  'minified' => "foo()\n" . 'mw.loader.state({"foo":"ready"});',
735  'message' => 'Script with semi-colon in comment (T162719)',
736  ],
737  ];
738  $ret = [];
739  foreach ( $testcases as $i => $case ) {
740  $ret["#$i"] = [
741  $case['modules'],
742  $case['expected'],
743  true, // debug
744  $case['message'],
745  ];
746  $ret["#$i (minified)"] = [
747  $case['modules'],
748  $case['minified'],
749  false, // debug
750  $case['message'],
751  ];
752  }
753  return $ret;
754  }
755 
762  public function testMakeModuleResponseConcat( $scripts, $expected, $debug, $message = null ) {
763  $rl = new EmptyResourceLoader();
764  $modules = array_map( function ( $script ) {
765  return self::getSimpleModuleMock( $script );
766  }, $scripts );
767  $rl->register( $modules );
768 
770  [
771  'modules' => implode( '|', array_keys( $modules ) ),
772  'only' => 'scripts',
773  'debug' => $debug ? 'true' : 'false',
774  ],
775  $rl
776  );
777 
778  $response = $rl->makeModuleResponse( $context, $modules );
779  $this->assertSame( [], $rl->getErrors(), 'Errors' );
780  $this->assertEquals( $expected, $response, $message ?: 'Response' );
781  }
782 
786  public function testMakeModuleResponseEmpty() {
787  $rl = new EmptyResourceLoader();
789  [ 'modules' => '', 'only' => 'scripts' ],
790  $rl
791  );
792 
793  $response = $rl->makeModuleResponse( $context, [] );
794  $this->assertSame( [], $rl->getErrors(), 'Errors' );
795  $this->assertRegExp( '/^\/\*.+no modules were requested.+\*\/$/ms', $response );
796  }
797 
805  public function testMakeModuleResponseError() {
806  $modules = [
807  'foo' => self::getSimpleModuleMock( 'foo();' ),
808  'ferry' => self::getFailFerryMock(),
809  'bar' => self::getSimpleModuleMock( 'bar();' ),
810  ];
811  $rl = new EmptyResourceLoader();
812  $rl->register( $modules );
814  [
815  'modules' => 'foo|ferry|bar',
816  'only' => 'scripts',
817  ],
818  $rl
819  );
820 
821  // Disable log from makeModuleResponse via outputErrorAndLog
822  $this->setLogger( 'exception', new Psr\Log\NullLogger() );
823 
824  $response = $rl->makeModuleResponse( $context, $modules );
825  $errors = $rl->getErrors();
826 
827  $this->assertCount( 1, $errors );
828  $this->assertRegExp( '/Ferry not found/', $errors[0] );
829  $this->assertEquals(
830  "foo();\nbar();\n" . 'mw.loader.state( {
831  "ferry": "error",
832  "foo": "ready",
833  "bar": "ready"
834 } );',
835  $response
836  );
837  }
838 
845  public function testMakeModuleResponseErrorCSS() {
846  $modules = [
847  'foo' => self::getSimpleStyleModuleMock( '.foo{}' ),
848  'ferry' => self::getFailFerryMock( 'getStyles' ),
849  'bar' => self::getSimpleStyleModuleMock( '.bar{}' ),
850  ];
851  $rl = new EmptyResourceLoader();
852  $rl->register( $modules );
854  [
855  'modules' => 'foo|ferry|bar',
856  'only' => 'styles',
857  'debug' => 'false',
858  ],
859  $rl
860  );
861 
862  // Disable log from makeModuleResponse via outputErrorAndLog
863  $this->setLogger( 'exception', new Psr\Log\NullLogger() );
864 
865  $response = $rl->makeModuleResponse( $context, $modules );
866  $errors = $rl->getErrors();
867 
868  $this->assertCount( 2, $errors );
869  $this->assertRegExp( '/Ferry not found/', $errors[0] );
870  $this->assertRegExp( '/Problem.+"ferry":\s*"error"/ms', $errors[1] );
871  $this->assertEquals(
872  '.foo{}.bar{}',
873  $response
874  );
875  }
876 
885  $rl = new EmptyResourceLoader();
886  $rl->register( [
887  'foo' => self::getSimpleModuleMock( 'foo();' ),
888  'ferry' => self::getFailFerryMock(),
889  'bar' => self::getSimpleModuleMock( 'bar();' ),
890  'startup' => [ 'class' => ResourceLoaderStartUpModule::class ],
891  ] );
893  [
894  'modules' => 'startup',
895  'only' => 'scripts',
896  ],
897  $rl
898  );
899 
900  $this->assertEquals(
901  [ 'foo', 'ferry', 'bar', 'startup' ],
902  $rl->getModuleNames(),
903  'getModuleNames'
904  );
905 
906  // Disable log from makeModuleResponse via outputErrorAndLog
907  $this->setLogger( 'exception', new Psr\Log\NullLogger() );
908 
909  $modules = [ 'startup' => $rl->getModule( 'startup' ) ];
910  $response = $rl->makeModuleResponse( $context, $modules );
911  $errors = $rl->getErrors();
912 
913  $this->assertRegExp( '/Ferry not found/', $errors[0] );
914  $this->assertCount( 1, $errors );
915  $this->assertRegExp(
916  '/isCompatible.*window\.RLQ/s',
917  $response,
918  'startup response undisrupted (T152266)'
919  );
920  $this->assertRegExp(
921  '/register\([^)]+"ferry",\s*""/s',
922  $response,
923  'startup response registers broken module'
924  );
925  $this->assertRegExp(
926  '/state\([^)]+"ferry":\s*"error"/s',
927  $response,
928  'startup response sets state to error'
929  );
930  }
931 
940  $module = $this->getMockBuilder( ResourceLoaderTestModule::class )
941  ->setMethods( [ 'getPreloadLinks' ] )->getMock();
942  $module->method( 'getPreloadLinks' )->willReturn( [
943  'https://example.org/script.js' => [ 'as' => 'script' ],
944  ] );
945 
946  $rl = new EmptyResourceLoader();
947  $rl->register( [
948  'foo' => $module,
949  ] );
951  [ 'modules' => 'foo', 'only' => 'scripts' ],
952  $rl
953  );
954 
955  $modules = [ 'foo' => $rl->getModule( 'foo' ) ];
956  $response = $rl->makeModuleResponse( $context, $modules );
957  $extraHeaders = TestingAccessWrapper::newFromObject( $rl )->extraHeaders;
958 
959  $this->assertEquals(
960  [
961  'Link: <https://example.org/script.js>;rel=preload;as=script'
962  ],
963  $extraHeaders,
964  'Extra headers'
965  );
966  }
967 
974  $foo = $this->getMockBuilder( ResourceLoaderTestModule::class )
975  ->setMethods( [ 'getPreloadLinks' ] )->getMock();
976  $foo->method( 'getPreloadLinks' )->willReturn( [
977  'https://example.org/script.js' => [ 'as' => 'script' ],
978  ] );
979 
980  $bar = $this->getMockBuilder( ResourceLoaderTestModule::class )
981  ->setMethods( [ 'getPreloadLinks' ] )->getMock();
982  $bar->method( 'getPreloadLinks' )->willReturn( [
983  '/example.png' => [ 'as' => 'image' ],
984  '/example.jpg' => [ 'as' => 'image' ],
985  ] );
986 
987  $rl = new EmptyResourceLoader();
988  $rl->register( [ 'foo' => $foo, 'bar' => $bar ] );
990  [ 'modules' => 'foo|bar', 'only' => 'scripts' ],
991  $rl
992  );
993 
994  $modules = [ 'foo' => $rl->getModule( 'foo' ), 'bar' => $rl->getModule( 'bar' ) ];
995  $response = $rl->makeModuleResponse( $context, $modules );
996  $extraHeaders = TestingAccessWrapper::newFromObject( $rl )->extraHeaders;
997  $this->assertEquals(
998  [
999  'Link: <https://example.org/script.js>;rel=preload;as=script',
1000  'Link: </example.png>;rel=preload;as=image,</example.jpg>;rel=preload;as=image'
1001  ],
1002  $extraHeaders,
1003  'Extra headers'
1004  );
1005  }
1006 
1010  public function testRespondEmpty() {
1011  $rl = $this->getMockBuilder( EmptyResourceLoader::class )
1012  ->setMethods( [
1013  'tryRespondNotModified',
1014  'sendResponseHeaders',
1015  'measureResponseTime',
1016  ] )
1017  ->getMock();
1018  $context = $this->getResourceLoaderContext( [ 'modules' => '' ], $rl );
1019 
1020  $rl->expects( $this->once() )->method( 'measureResponseTime' );
1021  $this->expectOutputRegex( '/no modules were requested/' );
1022 
1023  $rl->respond( $context );
1024  }
1025 
1029  public function testRespondSimple() {
1030  $module = new ResourceLoaderTestModule( [ 'script' => 'foo();' ] );
1031  $rl = $this->getMockBuilder( EmptyResourceLoader::class )
1032  ->setMethods( [
1033  'measureResponseTime',
1034  'tryRespondNotModified',
1035  'sendResponseHeaders',
1036  'makeModuleResponse',
1037  ] )
1038  ->getMock();
1039  $rl->register( 'test', $module );
1041  [ 'modules' => 'test', 'only' => null ],
1042  $rl
1043  );
1044 
1045  $rl->expects( $this->once() )->method( 'makeModuleResponse' )
1046  ->with( $context, [ 'test' => $module ] )
1047  ->willReturn( 'implement_foo;' );
1048  $this->expectOutputRegex( '/^implement_foo;/' );
1049 
1050  $rl->respond( $context );
1051  }
1052 
1056  public function testRespondInternalFailures() {
1057  $module = new ResourceLoaderTestModule( [ 'script' => 'foo();' ] );
1058  $rl = $this->getMockBuilder( EmptyResourceLoader::class )
1059  ->setMethods( [
1060  'measureResponseTime',
1061  'preloadModuleInfo',
1062  'getCombinedVersion',
1063  'tryRespondNotModified',
1064  'makeModuleResponse',
1065  'sendResponseHeaders',
1066  ] )
1067  ->getMock();
1068  $rl->register( 'test', $module );
1069  $context = $this->getResourceLoaderContext( [ 'modules' => 'test' ], $rl );
1070  // Disable logging from outputErrorAndLog
1071  $this->setLogger( 'exception', new Psr\Log\NullLogger() );
1072 
1073  $rl->expects( $this->once() )->method( 'preloadModuleInfo' )
1074  ->willThrowException( new Exception( 'Preload error' ) );
1075  $rl->expects( $this->once() )->method( 'getCombinedVersion' )
1076  ->willThrowException( new Exception( 'Version error' ) );
1077  $rl->expects( $this->once() )->method( 'makeModuleResponse' )
1078  ->with( $context, [ 'test' => $module ] )
1079  ->willReturn( 'foo;' );
1080  // Internal errors should be caught and logged without affecting module output
1081  $this->expectOutputRegex( '/^\/\*.+Preload error.+Version error.+\*\/.*foo;/ms' );
1082 
1083  $rl->respond( $context );
1084  }
1085 
1089  public function testMeasureResponseTime() {
1090  $stats = $this->getMockBuilder( NullStatsdDataFactory::class )
1091  ->setMethods( [ 'timing' ] )->getMock();
1092  $this->setService( 'StatsdDataFactory', $stats );
1093 
1094  $stats->expects( $this->once() )->method( 'timing' )
1095  ->with( 'resourceloader.responseTime', $this->anything() );
1096 
1097  $timing = new Timing();
1098  $timing->mark( 'requestShutdown' );
1099  $rl = TestingAccessWrapper::newFromObject( new EmptyResourceLoader );
1100  $rl->measureResponseTime( $timing );
1102  }
1103 }
ResourceLoaderTest\setUp
setUp()
Definition: ResourceLoaderTest.php:7
ResourceLoaderTest\testIsFileModule
testIsFileModule( $expected, $module)
provideTestIsFileModule ResourceLoader::isFileModule
Definition: ResourceLoaderTest.php:162
ResourceLoaderTest\testRespondSimple
testRespondSimple()
ResourceLoader::respond.
Definition: ResourceLoaderTest.php:1029
ResourceLoaderTest\testMakePackedModulesString
testMakePackedModulesString( $desc, $modules, $packed)
providePackedModules ResourceLoader::makePackedModulesString
Definition: ResourceLoaderTest.php:285
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:226
$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:2636
ResourceLoaderTest\getSimpleStyleModuleMock
getSimpleStyleModuleMock( $styles='')
Definition: ResourceLoaderTest.php:660
ResourceLoaderTest
Definition: ResourceLoaderTest.php:5
ResourceLoaderTest\testRegisterDuplicate
testRegisterDuplicate()
ResourceLoader::register.
Definition: ResourceLoaderTest.php:93
ResourceLoaderTest\testLessImportDirs
testLessImportDirs()
ResourceLoader::getLessCompiler.
Definition: ResourceLoaderTest.php:239
ResourceLoaderTest\testIsFileModuleUnknown
testIsFileModuleUnknown()
ResourceLoader::isFileModule.
Definition: ResourceLoaderTest.php:171
ResourceLoaderTest\testMakeModuleResponseError
testMakeModuleResponseError()
Verify that when building module content in a load.php response, an exception from one module will no...
Definition: ResourceLoaderTest.php:805
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
ResourceLoaderTest\testMakeLoaderImplementScriptInvalid
testMakeLoaderImplementScriptInvalid()
ResourceLoader::makeLoaderImplementScript.
Definition: ResourceLoaderTest.php:508
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:2636
ResourceLoaderTest\provideTestIsFileModule
provideTestIsFileModule()
Definition: ResourceLoaderTest.php:120
ResourceLoaderTest\testGetModuleClass
testGetModuleClass()
ResourceLoader::getModule.
Definition: ResourceLoaderTest.php:197
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:40
ResourceLoaderTest\provideAddSource
static provideAddSource()
Definition: ResourceLoaderTest.php:301
MWException
MediaWiki exception.
Definition: MWException.php:26
$css
$css
Definition: styleTest.css.php:54
ResourceLoaderTest\testMakeLoaderSourcesScript
testMakeLoaderSourcesScript()
ResourceLoader::makeLoaderSourcesScript.
Definition: ResourceLoaderTest.php:581
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:709
$modules
$modules
Definition: HTMLFormElement.php:12
ResourceLoaderTest\testRespondInternalFailures
testRespondInternalFailures()
ResourceLoader::respond.
Definition: ResourceLoaderTest.php:1056
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:336
ResourceLoaderTest\testMakeLoaderRegisterScript
testMakeLoaderRegisterScript()
ResourceLoader::makeLoaderRegisterScript.
Definition: ResourceLoaderTest.php:524
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:626
ResourceLoaderTestModule
Definition: ResourceLoaderTestCase.php:85
ResourceLoaderTest\testRegisterValidArray
testRegisterValidArray()
ResourceLoader::register ResourceLoader::getModule.
Definition: ResourceLoaderTest.php:53
ResourceLoaderTest\provideMakeModuleResponseConcat
static provideMakeModuleResponseConcat()
Definition: ResourceLoaderTest.php:703
$name
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:271
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:2162
ResourceLoaderTest\testMakeModuleResponseExtraHeaders
testMakeModuleResponseExtraHeaders()
Integration test for modules sending extra HTTP response headers.
Definition: ResourceLoaderTest.php:939
ResourceLoaderTest\testMakeLoaderImplementScript
testMakeLoaderImplementScript( $case)
provideLoaderImplement ResourceLoader::makeLoaderImplementScript ResourceLoader::trimArray
Definition: ResourceLoaderTest.php:481
ResourceLoaderTest\testMakeModuleResponseConcat
testMakeModuleResponseConcat( $scripts, $expected, $debug, $message=null)
Verify how multiple scripts and mw.loader.state() calls are concatenated.
Definition: ResourceLoaderTest.php:762
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:1985
ResourceLoaderTest\testRespondEmpty
testRespondEmpty()
ResourceLoader::respond.
Definition: ResourceLoaderTest.php:1010
ResourceLoaderTest\testMakeModuleResponseErrorCSS
testMakeModuleResponseErrorCSS()
Verify that exceptions in PHP for one module will not break others (stylesheet response).
Definition: ResourceLoaderTest.php:845
ResourceLoaderTest\getSimpleModuleMock
getSimpleModuleMock( $script='')
Definition: ResourceLoaderTest.php:652
$response
this hook is for auditing only $response
Definition: hooks.txt:780
DeferredUpdates\doUpdates
static doUpdates( $mode='run', $stage=self::ALL)
Do any deferred updates and clear the list.
Definition: DeferredUpdates.php:133
ResourceLoaderTest\testExpandModuleNames
testExpandModuleNames( $desc, $modules, $packed, $unpacked=null)
providePackedModules ResourceLoader::expandModuleNames
Definition: ResourceLoaderTest.php:293
ResourceLoaderTest\testGetCombinedVersion
testGetCombinedVersion()
ResourceLoader::getCombinedVersion.
Definition: ResourceLoaderTest.php:671
ResourceLoaderTest\testAddSourceInvalid
testAddSourceInvalid()
ResourceLoader::addSource.
Definition: ResourceLoaderTest.php:348
MediaWikiTestCase\setLogger
setLogger( $channel, LoggerInterface $logger)
Sets the logger for a specified channel, for the duration of the test.
Definition: MediaWikiTestCase.php:1118
ResourceLoaderTest\testMakeModuleResponseExtraHeadersMulti
testMakeModuleResponseExtraHeadersMulti()
ResourceLoaderModule::getHeaders ResourceLoaderModule::buildContent ResourceLoader::makeModuleRespons...
Definition: ResourceLoaderTest.php:973
EmptyResourceLoader
Definition: ResourceLoaderTestCase.php:172
ResourceLoaderTest\testGetModuleFactory
testGetModuleFactory()
ResourceLoader::getModule.
Definition: ResourceLoaderTest.php:209
ResourceLoaderTest\testMeasureResponseTime
testMeasureResponseTime()
ResourceLoader::measureResponseTime.
Definition: ResourceLoaderTest.php:1089
ResourceLoaderTestCase\getResourceLoaderContext
getResourceLoaderContext( $options=[], ResourceLoader $rl=null)
Definition: ResourceLoaderTestCase.php:23
ResourceLoaderTest\testIsModuleRegistered
testIsModuleRegistered()
ResourceLoader::isModuleRegistered.
Definition: ResourceLoaderTest.php:179
ResourceLoaderTest\fakeSources
static fakeSources()
Definition: ResourceLoaderTest.php:610
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:642
$source
$source
Definition: mwdoc-filter.php:46
ResourceLoaderTest\providePackedModules
static providePackedModules()
Definition: ResourceLoaderTest.php:250
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:189
ResourceLoaderTest\testMakeModuleResponseStartupError
testMakeModuleResponseStartupError()
Verify that when building the startup module response, an exception from one module class will not br...
Definition: ResourceLoaderTest.php:884
MediaWikiTestCase\setService
setService( $name, $object)
Sets a service, maintaining a stashed version of the previous service to be restored in tearDown.
Definition: MediaWikiTestCase.php:649
ResourceLoaderTest\provideLoaderImplement
static provideLoaderImplement()
Definition: ResourceLoaderTest.php:354
ResourceLoaderTest\testMakeModuleResponseEmpty
testMakeModuleResponseEmpty()
ResourceLoader::makeModuleResponse.
Definition: ResourceLoaderTest.php:786
ResourceLoaderTest\testAddSource
testAddSource( $name, $info, $expected)
provideAddSource ResourceLoader::addSource ResourceLoader::getSources
Definition: ResourceLoaderTest.php:321
ResourceLoaderTestCase
Definition: ResourceLoaderTestCase.php:7