Debian Codegraph @

tests/phpunit/includes/ResourceLoader/WikiModuleTest.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\Tests\ResourceLoader;
4
5 use LinkCacheTestTrait;
6 use MediaWiki\Config\Config;
7 use MediaWiki\Config\HashConfig;
8 use MediaWiki\Content\Content;
9 use MediaWiki\Content\CssContent;
10 use MediaWiki\Content\JavaScriptContent;
11 use MediaWiki\Content\JavaScriptContentHandler;
12 use MediaWiki\Content\WikitextContent;
13 use MediaWiki\MainConfigNames;
14 use MediaWiki\Page\PageIdentity;
15 use MediaWiki\Page\PageIdentityValue;
16 use MediaWiki\Page\PageRecord;
17 use MediaWiki\Page\PageStore;
18 use MediaWiki\Request\FauxRequest;
19 use MediaWiki\ResourceLoader\Context;
20 use MediaWiki\ResourceLoader\DerivativeContext;
21 use MediaWiki\ResourceLoader\WikiModule;
22 use MediaWiki\Title\Title;
23 use MediaWiki\Title\TitleValue;
24 use ReflectionMethod;
25 use RuntimeException;
26 use Wikimedia\Rdbms\IReadableDatabase;
27 use Wikimedia\TestingAccessWrapper;
28 use Wikimedia\Timestamp\ConvertibleTimestamp;
29
30 /**
31 * @group ResourceLoader
32 * @group Database
33 * @covers \MediaWiki\ResourceLoader\WikiModule
34 */
35 class WikiModuleTest extends ResourceLoaderTestCase {
36 use LinkCacheTestTrait;
37
38 /**
39 * @dataProvider provideConstructor
40 */
41 public function testConstructor( $params ) {
42 $module = new WikiModule( $params );
43 $this->assertInstanceOf( WikiModule::class, $module );
44 }
45
46 public static function provideConstructor() {
47 yield 'null' => [ null ];
48 yield 'empty' => [ [] ];
49 yield 'unknown settings' => [ [ 'foo' => 'baz' ] ];
50 yield 'real settings' => [ [ 'MediaWiki:Common.js' ] ];
51 }
52
53 private function makeTitleInfo( array $mockInfo ) {
54 $wikiModuleClass = TestingAccessWrapper::newFromClass( WikiModule::class );
55 $info = [];
56 foreach ( $mockInfo as $val ) {
57 $title = $val['title'];
58 unset( $val['title'] );
59 $info[ $wikiModuleClass->makeTitleKey( $title ) ] = $val;
60 }
61 return $info;
62 }
63
64 /**
65 * @dataProvider provideGetPages
66 */
67 public function testGetPages( $params, Config $config, $expected ) {
68 $module = new WikiModule( $params );
69 $module->setConfig( $config );
70
71 // Because getPages is protected..
72 $getPages = new ReflectionMethod( $module, 'getPages' );
73 $out = $getPages->invoke( $module, Context::newDummyContext() );
74 $this->assertSame( $expected, $out );
75 }
76
77 public static function provideGetPages() {
78 $settings = self::getSettings() + [
79 MainConfigNames::UseSiteJs => true,
80 MainConfigNames::UseSiteCss => true,
81 ];
82
83 $params = [
84 'styles' => [ 'MediaWiki:Common.css' ],
85 'scripts' => [ 'MediaWiki:Common.js' ],
86 ];
87
88 return [
89 [ [], new HashConfig( $settings ), [] ],
90 [ $params, new HashConfig( $settings ), [
91 'MediaWiki:Common.js' => [ 'type' => 'script' ],
92 'MediaWiki:Common.css' => [ 'type' => 'style' ]
93 ] ],
94 [ $params, new HashConfig( [ MainConfigNames::UseSiteCss => false ] + $settings ), [
95 'MediaWiki:Common.js' => [ 'type' => 'script' ],
96 ] ],
97 [ $params, new HashConfig( [ MainConfigNames::UseSiteJs => false ] + $settings ), [
98 'MediaWiki:Common.css' => [ 'type' => 'style' ],
99 ] ],
100 [ $params,
101 new HashConfig(
102 [ MainConfigNames::UseSiteJs => false, MainConfigNames::UseSiteCss => false ]
103 ),
104 []
105 ],
106 ];
107 }
108
109 /**
110 * @dataProvider provideGetGroup
111 */
112 public function testGetGroup( $params, $expected ) {
113 $module = new WikiModule( $params );
114 $this->assertSame( $expected, $module->getGroup() );
115 }
116
117 public static function provideGetGroup() {
118 yield 'no group' => [ [], null ];
119 yield 'some group' => [ [ 'group' => 'foobar' ], 'foobar' ];
120 }
121
122 /**
123 * @dataProvider provideGetType
124 */
125 public function testGetType( $params, $expected ) {
126 $module = new WikiModule( $params );
127 $this->assertSame( $expected, $module->getType() );
128 }
129
130 public static function provideGetType() {
131 yield 'empty' => [
132 [],
133 WikiModule::LOAD_GENERAL,
134 ];
135 yield 'scripts' => [
136 [ 'scripts' => [ 'Example.js' ] ],
137 WikiModule::LOAD_GENERAL,
138 ];
139 yield 'styles' => [
140 [ 'styles' => [ 'Example.css' ] ],
141 WikiModule::LOAD_STYLES,
142 ];
143 yield 'styles and scripts' => [
144 [ 'styles' => [ 'Example.css' ], 'scripts' => [ 'Example.js' ] ],
145 WikiModule::LOAD_GENERAL,
146 ];
147 }
148
149 /**
150 * @dataProvider provideIsKnownEmpty
151 */
152 public function testIsKnownEmpty( $titleInfo, $group, $dependencies, $expected ) {
153 $module = $this->getMockBuilder( WikiModule::class )
154 ->disableOriginalConstructor()
155 ->onlyMethods( [ 'getTitleInfo', 'getGroup', 'getDependencies' ] )
156 ->getMock();
157 $module->method( 'getTitleInfo' )
158 ->willReturn( $this->makeTitleInfo( $titleInfo ) );
159 $module->method( 'getGroup' )
160 ->willReturn( $group );
161 $module->method( 'getDependencies' )
162 ->willReturn( $dependencies );
163 $context = $this->createMock( Context::class );
164 $this->assertSame( $expected, $module->isKnownEmpty( $context ) );
165 }
166
167 public static function provideIsKnownEmpty() {
168 yield 'nothing' => [
169 [],
170 null,
171 [],
172 // No pages exist, considered empty.
173 true,
174 ];
175
176 yield 'an empty page exists (no group)' => [
177 [ [ 'title' => new TitleValue( NS_USER, 'Example/foo.js' ), 'page_len' => 0 ] ],
178 null,
179 [],
180 // There is an existing page, so we should let the module be queued.
181 // Its emptiness might be temporary, hence considered non-empty (T70488).
182 false,
183 ];
184 yield 'an empty page exists (site group)' => [
185 [ [ 'title' => new TitleValue( NS_MEDIAWIKI, 'Foo.js' ), 'page_len' => 0 ] ],
186 'site',
187 [],
188 // There is an existing page, hence considered non-empty.
189 false,
190 ];
191 yield 'an empty page exists (user group)' => [
192 [ [ 'title' => new TitleValue( NS_USER, 'Example/foo.js' ), 'page_len' => 0 ] ],
193 'user',
194 [],
195 // There is an existing page, but it is empty.
196 // For user-specific modules, don't bother loading a known-empty module.
197 // Given user-specific HTML output, this will vary and re-appear if/when
198 // the page becomes non-empty again.
199 true,
200 ];
201
202 yield 'no pages but having dependencies (no group)' => [
203 [],
204 null,
205 [ 'another-module' ],
206 false,
207 ];
208 yield 'no pages but having dependencies (site group)' => [
209 [],
210 'site',
211 [ 'another-module' ],
212 false,
213 ];
214 yield 'no pages but having dependencies (user group)' => [
215 [],
216 'user',
217 [ 'another-module' ],
218 false,
219 ];
220
221 yield 'a non-empty page exists (user group)' => [
222 [ [ 'title' => new TitleValue( NS_USER, 'Example/foo.js' ), 'page_len' => 25 ] ],
223 'user',
224 [],
225 false,
226 ];
227 yield 'a non-empty page exists (site group)' => [
228 [ [ 'title' => new TitleValue( NS_MEDIAWIKI, 'Foo.js' ), 'page_len' => 25 ] ],
229 'site',
230 [],
231 false,
232 ];
233 }
234
235 public function testGetPreloadedTitleInfo() {
236 // Set up
237 ConvertibleTimestamp::setFakeTime( '20110401090000' );
238 $this->editPage( 'MediaWiki:TestA.css', '.mw-first {}', 'First' );
239 $this->editPage( 'MediaWiki:TestEmpty.css', '', 'Empty' );
240 $this->editPage( 'MediaWiki:TestB.css', '.mw-second {}', 'Second' );
241 $rl = new EmptyResourceLoader();
242 $rl->getConfig()->set( MainConfigNames::UseSiteJs, true );
243 $rl->getConfig()->set( MainConfigNames::UseSiteCss, true );
244 $rl->register( 'testmodule1', [
245 'class' => TestResourceLoaderWikiModule::class,
246 'styles' => [
247 'MediaWiki:TestA.css',
248 // Regression against T145673. It's impossible to statically declare page names in
249 // a canonical way since the canonical prefix is localised. As such, the preload
250 // cache computed the right cache key, but failed to find the results when
251 // doing an intersect on the canonical result, producing an empty array.
252 'mediawiki: testEmpty.css',
253 ],
254 ] );
255 $rl->register( 'testmodule2', [
256 'class' => TestResourceLoaderWikiModule::class,
257 'styles' => [
258 'MediaWiki:TestB.css',
259 ],
260 ] );
261 $context = new Context( $rl, new FauxRequest() );
262
263 // Warm up the cache
264 WikiModule::preloadTitleInfo(
265 $context,
266 [ 'testmodule1', 'testmodule2' ]
267 );
268 // The module uses TestResourceLoaderWikiModule, which disables fetchTitleInfo() by default.
269 // If getTitleInfo() returns the data here, it means preloadTitleInfo succeeded.
270 $module1 = TestingAccessWrapper::newFromObject( $rl->getModule( 'testmodule1' ) );
271 $this->assertArrayContains( [
272 '8:TestA.css' => [ 'page_len' => '12', 'page_touched' => '20110401090000' ],
273 '8:TestEmpty.css' => [ 'page_len' => '0', 'page_touched' => '20110401090000' ],
274 ], $module1->getTitleInfo( $context ), 'Title info' );
275 $module2 = TestingAccessWrapper::newFromObject( $rl->getModule( 'testmodule2' ) );
276 $this->assertArrayContains( [
277 '8:TestB.css' => [ 'page_len' => '13', 'page_touched' => '20110401090000' ],
278 ], $module2->getTitleInfo( $context ), 'Title info' );
279 }
280
281 public function testGetPreloadedBadTitle() {
282 // Set up
283 TestResourceLoaderWikiModule::$returnFetchTitleInfo = [];
284 $rl = new EmptyResourceLoader();
285 $rl->getConfig()->set( MainConfigNames::UseSiteJs, true );
286 $rl->getConfig()->set( MainConfigNames::UseSiteCss, true );
287 $rl->register( 'testmodule', [
288 'class' => TestResourceLoaderWikiModule::class,
289 // Covers preloadTitleInfo branch for invalid page name
290 'styles' => [ '[x]' ],
291 ] );
292 $context = new Context( $rl, new FauxRequest() );
293
294 // Act
295 TestResourceLoaderWikiModule::preloadTitleInfo(
296 $context,
297 [ 'testmodule' ]
298 );
299
300 // Assert
301 $module = TestingAccessWrapper::newFromObject( $rl->getModule( 'testmodule' ) );
302 $this->assertSame( [], $module->getTitleInfo( $context ), 'Title info' );
303 }
304
305 public function testGetPreloadedTitleInfoEmpty() {
306 $context = new Context( new EmptyResourceLoader(), new FauxRequest() );
307 // This covers the early return case
308 $this->assertSame(
309 null,
310 WikiModule::preloadTitleInfo(
311 $context,
312 []
313 )
314 );
315 }
316
317 public static function provideGetContent() {
318 yield 'Bad title' => [ null, '[x]' ];
319
320 yield 'No JS content found' => [ null, [
321 'text' => 'MediaWiki:Foo.js',
322 'ns' => NS_MEDIAWIKI,
323 'title' => 'Foo.js',
324 ] ];
325
326 yield 'JS content' => [ 'code;', [
327 'text' => 'MediaWiki:Foo.js',
328 'ns' => NS_MEDIAWIKI,
329 'title' => 'Foo.js',
330 ], new JavaScriptContent( 'code;' ) ];
331
332 yield 'CSS content' => [ 'code {}', [
333 'text' => 'MediaWiki:Foo.css',
334 'ns' => NS_MEDIAWIKI,
335 'title' => 'Foo.css',
336 ], new CssContent( 'code {}' ) ];
337
338 yield 'Wikitext content' => [ null, [
339 'text' => 'MediaWiki:Foo',
340 'ns' => NS_MEDIAWIKI,
341 'title' => 'Foo',
342 ], new WikitextContent( 'code;' ) ];
343 }
344
345 /**
346 * @dataProvider provideGetContent
347 */
348 public function testGetContent( $expected, $title, ?Content $contentObj = null ) {
349 $context = $this->getResourceLoaderContext( [], new EmptyResourceLoader );
350 $module = $this->getMockBuilder( WikiModule::class )
351 ->onlyMethods( [ 'getContentObj' ] )->getMock();
352 $module->method( 'getContentObj' )
353 ->willReturn( $contentObj );
354
355 if ( is_array( $title ) ) {
356 $title += [ 'ns' => NS_MAIN, 'id' => 1, 'len' => 1, 'redirect' => 0 ];
357 $titleText = $title['text'];
358 // Mock page table access via PageStore
359 $pageStore = $this->createNoOpMock( PageStore::class, [ 'getPageByText' ] );
360 $pageStore->method( 'getPageByText' )->willReturn(
361 new PageIdentityValue(
362 $title['id'], $title['ns'], $title['text'], PageRecord::LOCAL
363 )
364 );
365 } else {
366 $titleText = $title;
367 }
368
369 $module = TestingAccessWrapper::newFromObject( $module );
370 $this->assertSame(
371 $expected,
372 $module->getContent( $titleText, $context )
373 );
374 }
375
376 public function testContentOverrides() {
377 $pages = [
378 'MediaWiki:Common.css' => [ 'type' => 'style' ],
379 ];
380
381 $rl = new EmptyResourceLoader();
382
383 $module = $this->getMockBuilder( WikiModule::class )
384 ->onlyMethods( [ 'getPages' ] )
385 ->getMock();
386 $module->method( 'getPages' )->willReturn( $pages );
387 $module->setConfig( $rl->getConfig() );
388
389 $context = new DerivativeContext(
390 new Context( $rl, new FauxRequest() )
391 );
392 $context->setContentOverrideCallback( static function ( PageIdentity $t ) {
393 if ( $t->getDBkey() === 'Common.css' ) {
394 return new CssContent( '.override{}' );
395 }
396 return null;
397 } );
398
399 $this->assertTrue( $module->shouldEmbedModule( $context ) );
400 $this->assertSame( [
401 'all' => [
402 "/*\nMediaWiki:Common.css\n*/\n.override{}"
403 ]
404 ], $module->getStyles( $context ) );
405
406 $context->setContentOverrideCallback( static function ( PageIdentity $t ) {
407 if ( $t->getDBkey() === 'Skin.css' ) {
408 return new CssContent( '.override{}' );
409 }
410 return null;
411 } );
412 $this->assertFalse( $module->shouldEmbedModule( $context ) );
413 }
414
415 public function testGetContentForRedirects() {
416 // Set up context and module object
417 $context = new DerivativeContext(
418 $this->getResourceLoaderContext( [], new EmptyResourceLoader )
419 );
420 $module = $this->getMockBuilder( WikiModule::class )
421 ->onlyMethods( [ 'getPages' ] )
422 ->getMock();
423 $module->method( 'getPages' )
424 ->willReturn( [
425 'MediaWiki:Redirect.js' => [ 'type' => 'script' ]
426 ] );
427 $module->setConfig( $context->getResourceLoader()->getConfig() );
428 $context->setContentOverrideCallback( static function ( PageIdentity $title ) {
429 if ( $title->getDBkey() === 'Redirect.js' ) {
430 $handler = new JavaScriptContentHandler();
431 return $handler->makeRedirectContent(
432 Title::makeTitle( NS_MEDIAWIKI, 'Target.js' )
433 );
434 } elseif ( $title->getDBkey() === 'Target.js' ) {
435 return new JavaScriptContent( 'target;' );
436 } else {
437 return null;
438 }
439 } );
440
441 // Mock away Title's db queries with LinkCache
442 $this->addGoodLinkObject( 1, new TitleValue( NS_MEDIAWIKI, 'Redirect.js' ), 1, 1 );
443
444 $this->assertSame(
445 "/*\nMediaWiki:Redirect.js\n*/\ntarget;\n",
446 $module->getScript( $context ),
447 'Redirect resolved by getContent'
448 );
449 }
450 }
451
452 class TestResourceLoaderWikiModule extends WikiModule {
453 /** @var array|null */
454 public static $returnFetchTitleInfo = null;
455
456 protected static function fetchTitleInfo( IReadableDatabase $db, array $pages, $fname = null ) {
457 $ret = self::$returnFetchTitleInfo;
458 self::$returnFetchTitleInfo = null;
459 if ( $ret === null ) {
460 // If a call is expected, a mock return value must be planted first
461 throw new RuntimeException( 'Unexpected fetchTitleInfo call' );
462 }
463 return $ret;
464 }
465 }