MediaWiki  master
ResourceLoaderWikiModuleTest.php
Go to the documentation of this file.
1 <?php
2 
6 
11 
15  public function testConstructor( $params ) {
16  $module = new ResourceLoaderWikiModule( $params );
17  $this->assertInstanceOf( ResourceLoaderWikiModule::class, $module );
18  }
19 
20  public static function provideConstructor() {
21  yield 'null' => [ null ];
22  yield 'empty' => [ [] ];
23  yield 'unknown settings' => [ [ 'foo' => 'baz' ] ];
24  yield 'real settings' => [ [ 'MediaWiki:Common.js' ] ];
25  }
26 
27  private function prepareTitleInfo( array $mockInfo ) {
28  $module = TestingAccessWrapper::newFromClass( ResourceLoaderWikiModule::class );
29  $info = [];
30  foreach ( $mockInfo as $key => $val ) {
31  $info[ $module->makeTitleKey( Title::newFromText( $key ) ) ] = $val;
32  }
33  return $info;
34  }
35 
39  public function testGetPages( $params, Config $config, $expected ) {
40  $module = new ResourceLoaderWikiModule( $params );
41  $module->setConfig( $config );
42 
43  // Because getPages is protected..
44  $getPages = new ReflectionMethod( $module, 'getPages' );
45  $getPages->setAccessible( true );
46  $out = $getPages->invoke( $module, ResourceLoaderContext::newDummyContext() );
47  $this->assertSame( $expected, $out );
48  }
49 
50  public static function provideGetPages() {
51  $settings = self::getSettings() + [
52  'UseSiteJs' => true,
53  'UseSiteCss' => true,
54  ];
55 
56  $params = [
57  'styles' => [ 'MediaWiki:Common.css' ],
58  'scripts' => [ 'MediaWiki:Common.js' ],
59  ];
60 
61  return [
62  [ [], new HashConfig( $settings ), [] ],
63  [ $params, new HashConfig( $settings ), [
64  'MediaWiki:Common.js' => [ 'type' => 'script' ],
65  'MediaWiki:Common.css' => [ 'type' => 'style' ]
66  ] ],
67  [ $params, new HashConfig( [ 'UseSiteCss' => false ] + $settings ), [
68  'MediaWiki:Common.js' => [ 'type' => 'script' ],
69  ] ],
70  [ $params, new HashConfig( [ 'UseSiteJs' => false ] + $settings ), [
71  'MediaWiki:Common.css' => [ 'type' => 'style' ],
72  ] ],
73  [ $params,
74  new HashConfig(
75  [ 'UseSiteJs' => false, 'UseSiteCss' => false ]
76  ),
77  []
78  ],
79  ];
80  }
81 
85  public function testGetGroup( $params, $expected ) {
86  $module = new ResourceLoaderWikiModule( $params );
87  $this->assertSame( $expected, $module->getGroup() );
88  }
89 
90  public static function provideGetGroup() {
91  yield 'no group' => [ [], null ];
92  yield 'some group' => [ [ 'group' => 'foobar' ], 'foobar' ];
93  }
94 
98  public function testGetType( $params, $expected ) {
99  $module = new ResourceLoaderWikiModule( $params );
100  $this->assertSame( $expected, $module->getType() );
101  }
102 
103  public static function provideGetType() {
104  yield 'empty' => [
105  [],
106  ResourceLoaderWikiModule::LOAD_GENERAL,
107  ];
108  yield 'scripts' => [
109  [ 'scripts' => [ 'Example.js' ] ],
110  ResourceLoaderWikiModule::LOAD_GENERAL,
111  ];
112  yield 'styles' => [
113  [ 'styles' => [ 'Example.css' ] ],
114  ResourceLoaderWikiModule::LOAD_STYLES,
115  ];
116  yield 'styles and scripts' => [
117  [ 'styles' => [ 'Example.css' ], 'scripts' => [ 'Example.js' ] ],
118  ResourceLoaderWikiModule::LOAD_GENERAL,
119  ];
120  }
121 
125  public function testIsKnownEmpty( $titleInfo, $group, $dependencies, $expected ) {
126  $module = $this->getMockBuilder( ResourceLoaderWikiModule::class )
127  ->disableOriginalConstructor()
128  ->setMethods( [ 'getTitleInfo', 'getGroup', 'getDependencies' ] )
129  ->getMock();
130  $module->method( 'getTitleInfo' )
131  ->willReturn( $this->prepareTitleInfo( $titleInfo ) );
132  $module->method( 'getGroup' )
133  ->willReturn( $group );
134  $module->method( 'getDependencies' )
135  ->willReturn( $dependencies );
136  $context = $this->createMock( ResourceLoaderContext::class );
137  $this->assertSame( $expected, $module->isKnownEmpty( $context ) );
138  }
139 
140  public static function provideIsKnownEmpty() {
141  yield 'nothing' => [
142  [],
143  null,
144  [],
145  // No pages exist, considered empty.
146  true,
147  ];
148 
149  yield 'an empty page exists (no group)' => [
150  [ 'Project:Example/foo.js' => [ 'page_len' => 0 ] ],
151  null,
152  [],
153  // There is an existing page, so we should let the module be queued.
154  // Its emptiness might be temporary, hence considered non-empty (T70488).
155  false,
156  ];
157  yield 'an empty page exists (site group)' => [
158  [ 'MediaWiki:Foo.js' => [ 'page_len' => 0 ] ],
159  'site',
160  [],
161  // There is an existing page, hence considered non-empty.
162  false,
163  ];
164  yield 'an empty page exists (user group)' => [
165  [ 'User:Example/foo.js' => [ 'page_len' => 0 ] ],
166  'user',
167  [],
168  // There is an existing page, but it is empty.
169  // For user-specific modules, don't bother loading a known-empty module.
170  // Given user-specific HTML output, this will vary and re-appear if/when
171  // the page becomes non-empty again.
172  true,
173  ];
174 
175  yield 'no pages but having dependencies (no group)' => [
176  [],
177  null,
178  [ 'another-module' ],
179  false,
180  ];
181  yield 'no pages but having dependencies (site group)' => [
182  [],
183  'site',
184  [ 'another-module' ],
185  false,
186  ];
187  yield 'no pages but having dependencies (user group)' => [
188  [],
189  'user',
190  [ 'another-module' ],
191  false,
192  ];
193 
194  yield 'a non-empty page exists (user group)' => [
195  [ 'User:Example/foo.js' => [ 'page_len' => 25 ] ],
196  'user',
197  [],
198  false,
199  ];
200  yield 'a non-empty page exists (site group)' => [
201  [ 'MediaWiki:Foo.js' => [ 'page_len' => 25 ] ],
202  'site',
203  [],
204  false,
205  ];
206  }
207 
208  public function testGetTitleInfo() {
209  $pages = [
210  'MediaWiki:Common.css' => [ 'type' => 'styles' ],
211  'mediawiki: fallback.css' => [ 'type' => 'styles' ],
212  ];
213  $titleInfo = $this->prepareTitleInfo( [
214  'MediaWiki:Common.css' => [ 'page_len' => 1234 ],
215  'MediaWiki:Fallback.css' => [ 'page_len' => 0 ],
216  ] );
217  $expected = $titleInfo;
218 
219  $module = $this->getMockBuilder( ResourceLoaderWikiModule::class )
220  ->setMethods( [ 'getPages', 'getTitleInfo' ] )
221  ->getMock();
222  $module->method( 'getPages' )->willReturn( $pages );
223  $module->method( 'getTitleInfo' )->willReturn( $titleInfo );
224 
225  $context = $this->getMockBuilder( ResourceLoaderContext::class )
226  ->disableOriginalConstructor()
227  ->getMock();
228 
229  $module = TestingAccessWrapper::newFromObject( $module );
230  $this->assertSame( $expected, $module->getTitleInfo( $context ), 'Title info' );
231  }
232 
233  public function testGetPreloadedTitleInfo() {
234  $pages = [
235  'MediaWiki:Common.css' => [ 'type' => 'styles' ],
236  // Regression against T145673. It's impossible to statically declare page names in
237  // a canonical way since the canonical prefix is localised. As such, the preload
238  // cache computed the right cache key, but failed to find the results when
239  // doing an intersect on the canonical result, producing an empty array.
240  'mediawiki: fallback.css' => [ 'type' => 'styles' ],
241  ];
242  $titleInfo = $this->prepareTitleInfo( [
243  'MediaWiki:Common.css' => [ 'page_len' => 1234 ],
244  'MediaWiki:Fallback.css' => [ 'page_len' => 0 ],
245  ] );
246  $expected = $titleInfo;
247 
248  $module = $this->getMockBuilder( TestResourceLoaderWikiModule::class )
249  ->setMethods( [ 'getPages' ] )
250  ->getMock();
251  $module->method( 'getPages' )->willReturn( $pages );
252  // Can't mock static methods
253  $module::$returnFetchTitleInfo = $titleInfo;
254 
255  $rl = new EmptyResourceLoader();
256  $context = new ResourceLoaderContext( $rl, new FauxRequest() );
257 
259  Title::newFromText( 'MediaWiki:Common.css' ),
260  null,
261  null,
262  wfWikiID()
263  );
265  $context,
266  $this->createMock( IDatabase::class ),
267  [ 'testmodule' ]
268  );
269 
270  $module = TestingAccessWrapper::newFromObject( $module );
271  $this->assertSame( $expected, $module->getTitleInfo( $context ), 'Title info' );
272  }
273 
274  public function testGetPreloadedBadTitle() {
275  // Set up
277  $rl = new EmptyResourceLoader();
278  $rl->getConfig()->set( 'UseSiteJs', true );
279  $rl->getConfig()->set( 'UseSiteCss', true );
280  $rl->register( 'testmodule', [
282  // Covers preloadTitleInfo branch for invalid page name
283  'styles' => [ '[x]' ],
284  ] );
285  $context = new ResourceLoaderContext( $rl, new FauxRequest() );
286 
287  // Act
289  $context,
290  $this->createMock( IDatabase::class ),
291  [ 'testmodule' ]
292  );
293 
294  // Assert
295  $module = TestingAccessWrapper::newFromObject( $rl->getModule( 'testmodule' ) );
296  $this->assertSame( [], $module->getTitleInfo( $context ), 'Title info' );
297  }
298 
299  public function testGetPreloadedTitleInfoEmpty() {
301  // This covers the early return case
302  $this->assertSame(
303  null,
305  $context,
306  $this->createMock( IDatabase::class ),
307  []
308  )
309  );
310  }
311 
312  public static function provideGetContent() {
313  yield 'Bad title' => [ null, '[x]' ];
314 
315  yield 'No JS content found' => [ null, [
316  'text' => 'MediaWiki:Foo.js',
317  'ns' => NS_MEDIAWIKI,
318  'title' => 'Foo.js',
319  ] ];
320 
321  yield 'JS content' => [ 'code;', [
322  'text' => 'MediaWiki:Foo.js',
323  'ns' => NS_MEDIAWIKI,
324  'title' => 'Foo.js',
325  ], new JavaScriptContent( 'code;' ) ];
326 
327  yield 'CSS content' => [ 'code {}', [
328  'text' => 'MediaWiki:Foo.css',
329  'ns' => NS_MEDIAWIKI,
330  'title' => 'Foo.css',
331  ], new CssContent( 'code {}' ) ];
332 
333  yield 'Wikitext content' => [ null, [
334  'text' => 'MediaWiki:Foo',
335  'ns' => NS_MEDIAWIKI,
336  'title' => 'Foo',
337  ], new WikitextContent( 'code;' ) ];
338  }
339 
343  public function testGetContent( $expected, $title, Content $contentObj = null ) {
345  $module = $this->getMockBuilder( ResourceLoaderWikiModule::class )
346  ->setMethods( [ 'getContentObj' ] )->getMock();
347  $module->method( 'getContentObj' )
348  ->willReturn( $contentObj );
349 
350  if ( is_array( $title ) ) {
351  $title += [ 'ns' => NS_MAIN, 'id' => 1, 'len' => 1, 'redirect' => 0 ];
352  $titleText = $title['text'];
353  // Mock Title db access via LinkCache
354  MediaWikiServices::getInstance()->getLinkCache()->addGoodLinkObj(
355  $title['id'],
356  new TitleValue( $title['ns'], $title['title'] ),
357  $title['len'],
358  $title['redirect']
359  );
360  } else {
361  $titleText = $title;
362  }
363 
364  $module = TestingAccessWrapper::newFromObject( $module );
365  $this->assertSame(
366  $expected,
367  $module->getContent( $titleText, $context )
368  );
369  }
370 
371  public function testContentOverrides() {
372  $pages = [
373  'MediaWiki:Common.css' => [ 'type' => 'style' ],
374  ];
375 
376  $module = $this->getMockBuilder( ResourceLoaderWikiModule::class )
377  ->setMethods( [ 'getPages' ] )
378  ->getMock();
379  $module->method( 'getPages' )->willReturn( $pages );
380 
381  $rl = new EmptyResourceLoader();
383  new ResourceLoaderContext( $rl, new FauxRequest() )
384  );
385  $context->setContentOverrideCallback( function ( Title $t ) {
386  if ( $t->getPrefixedText() === 'MediaWiki:Common.css' ) {
387  return new CssContent( '.override{}' );
388  }
389  return null;
390  } );
391 
392  $this->assertTrue( $module->shouldEmbedModule( $context ) );
393  $this->assertSame( [
394  'all' => [
395  "/*\nMediaWiki:Common.css\n*/\n.override{}"
396  ]
397  ], $module->getStyles( $context ) );
398 
399  $context->setContentOverrideCallback( function ( Title $t ) {
400  if ( $t->getPrefixedText() === 'MediaWiki:Skin.css' ) {
401  return new CssContent( '.override{}' );
402  }
403  return null;
404  } );
405  $this->assertFalse( $module->shouldEmbedModule( $context ) );
406  }
407 
408  public function testGetContentForRedirects() {
409  // Set up context and module object
412  );
413  $module = $this->getMockBuilder( ResourceLoaderWikiModule::class )
414  ->setMethods( [ 'getPages' ] )
415  ->getMock();
416  $module->method( 'getPages' )
417  ->willReturn( [
418  'MediaWiki:Redirect.js' => [ 'type' => 'script' ]
419  ] );
420  $context->setContentOverrideCallback( function ( Title $title ) {
421  if ( $title->getPrefixedText() === 'MediaWiki:Redirect.js' ) {
423  return $handler->makeRedirectContent(
424  Title::makeTitle( NS_MEDIAWIKI, 'Target.js' )
425  );
426  } elseif ( $title->getPrefixedText() === 'MediaWiki:Target.js' ) {
427  return new JavaScriptContent( 'target;' );
428  } else {
429  return null;
430  }
431  } );
432 
433  // Mock away Title's db queries with LinkCache
434  MediaWikiServices::getInstance()->getLinkCache()->addGoodLinkObj(
435  1, // id
436  new TitleValue( NS_MEDIAWIKI, 'Redirect.js' ),
437  1, // len
438  1 // redirect
439  );
440 
441  $this->assertSame(
442  "/*\nMediaWiki:Redirect.js\n*/\ntarget;\n",
443  $module->getScript( $context ),
444  'Redirect resolved by getContent'
445  );
446  }
447 
448  public function tearDown() {
450  parent::tearDown();
451  }
452 }
453 
455  public static $returnFetchTitleInfo = null;
456 
457  protected static function fetchTitleInfo( IDatabase $db, array $pages, $fname = null ) {
458  $ret = self::$returnFetchTitleInfo;
459  self::$returnFetchTitleInfo = null;
460  return $ret;
461  }
462 }
Content object for CSS pages.
Definition: CssContent.php:35
static clearCaches()
Definition: Title.php:3168
Content handler for JavaScript pages.
const NS_MAIN
Definition: Defines.php:60
static invalidateModuleCache(Title $title, Revision $old=null, Revision $new=null, $domain)
Clear the preloadTitleInfo() cache for all wiki modules on this wiki on page change if it was a JS or...
static newDummyContext()
Return a dummy ResourceLoaderContext object suitable for passing into things that don&#39;t "really" need...
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:1972
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
testGetContent( $expected, $title, Content $contentObj=null)
provideGetContent
testConstructor( $params)
provideConstructor
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
getPrefixedText()
Get the prefixed title with spaces.
Definition: Title.php:1724
Content for JavaScript pages.
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 it can be in the form of< username >< more info > e g for bot passwords intended to be added to log contexts Fields it might only if the login was with a bot password it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable modifiable after all normalizations have been except for the $wgMaxImageArea check set to true or false to override the $wgMaxImageArea check result gives extension the possibility to transform it themselves $handler
Definition: hooks.txt:767
getResourceLoaderContext( $options=[], ResourceLoader $rl=null)
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 it can be in the form of< username >< more info > e g for bot passwords intended to be added to log contexts Fields it might only if the login was with a bot password it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output $out
Definition: hooks.txt:767
Allows changing specific properties of a context object, without changing the main one...
Interface for configuration instances.
Definition: Config.php:28
static preloadTitleInfo(ResourceLoaderContext $context, IDatabase $db, array $moduleNames)
testIsKnownEmpty( $titleInfo, $group, $dependencies, $expected)
provideIsKnownEmpty
$params
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:767
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:912
static fetchTitleInfo(IDatabase $db, array $pages, $fname=null)
wfWikiID()
Get an ASCII string identifying this wiki This is used as a prefix in memcached keys.
testGetPages( $params, Config $config, $expected)
provideGetPages
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
const NS_MEDIAWIKI
Definition: Defines.php:68
if(defined( 'MW_SETUP_CALLBACK')) $fname
Customization point after all loading (constants, functions, classes, DefaultSettings, LocalSettings).
Definition: Setup.php:131
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:592
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
Basic database interface for live and lazy-loaded relation database handles.
Definition: IDatabase.php:38
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
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:2621
testGetGroup( $params, $expected)
provideGetGroup
A Config instance which stores all settings as a member variable.
Definition: HashConfig.php:28
testGetType( $params, $expected)
provideGetType
Object passed around to modules which contains information about the state of a specific loader reque...
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:322