Debian Codegraph @

tests/phpunit/structure/ResourcesTest.php

raw symbols SCIP
1 <?php
2
3 use JsonSchema\Validator;
4 use MediaWiki\MainConfigNames;
5 use MediaWiki\MediaWikiServices;
6 use MediaWiki\Request\FauxRequest;
7 use MediaWiki\ResourceLoader as RL;
8 use Wikimedia\Minify\CSSMin;
9 use Wikimedia\TestingAccessWrapper;
10
11 /**
12 * Checks for making sure registered resources are sensible.
13 *
14 * @author Antoine Musso
15 * @author Niklas Laxström
16 * @author Santhosh Thottingal
17 * @copyright © 2012, Antoine Musso
18 * @copyright © 2012, Niklas Laxström
19 * @copyright © 2012, Santhosh Thottingal
20 *
21 * @coversNothing
22 * @group Database
23 */
24 class ResourcesTest extends MediaWikiIntegrationTestCase {
25
26 public function testStyleMedia() {
27 foreach ( self::provideMediaStylesheets() as [ $moduleName, $media, $filename, $css ] ) {
28 $cssText = CSSMin::minify( $css->cssText );
29
30 $this->assertStringNotContainsString(
31 '@media',
32 $cssText,
33 'Stylesheets should not both specify "media" and contain @media'
34 );
35 }
36 }
37
38 /**
39 * Verify that all modules specified as dependencies of other modules actually
40 * exist and are not illegal.
41 *
42 * @todo Modules can dynamically choose dependencies based on context. This method
43 * does not find all such variations.
44 */
45 public function testValidDependencies() {
46 $data = self::getAllModules();
47 $illegalDeps = [ 'startup' ];
48 // Can't depend on modules in the `noscript` group, find all such module names
49 // to add to $illegalDeps. See T291735
50 /** @var RL\Module $module */
51 foreach ( $data['modules'] as $moduleName => $module ) {
52 if ( $module->getGroup() === 'noscript' ) {
53 $illegalDeps[] = $moduleName;
54 }
55 }
56
57 // Avoid an assert for each module to keep the test fast.
58 // Instead, perform a single assertion against everything at once.
59 // When all is good, actual/expected are both empty arrays.
60 // When we find issues, add the violations to 'actual' and add an empty
61 // key to 'expected'. These keys in expected are because the PHPUnit diff
62 // (as of 6.5) only goes one level deep.
63 $actualUnknown = [];
64 $expectedUnknown = [];
65 $actualIllegal = [];
66 $expectedIllegal = [];
67
68 /** @var RL\Module $module */
69 foreach ( $data['modules'] as $moduleName => $module ) {
70 foreach ( $module->getDependencies( $data['context'] ) as $dep ) {
71 if ( !isset( $data['modules'][$dep] ) ) {
72 $actualUnknown[$moduleName][] = $dep;
73 $expectedUnknown[$moduleName] = [];
74 }
75 if ( in_array( $dep, $illegalDeps, true ) ) {
76 $actualIllegal[$moduleName][] = $dep;
77 $expectedIllegal[$moduleName] = [];
78 }
79 }
80 }
81 $this->assertEquals( $expectedUnknown, $actualUnknown, 'Dependencies that do not exist' );
82 $this->assertEquals( $expectedIllegal, $actualIllegal, 'Dependencies that are not legal' );
83 }
84
85 public function testSchema() {
86 $data = include __DIR__ . '/../../../resources/Resources.php';
87 $schemaPath = __DIR__ . '/../../../docs/extension.schema.v2.json';
88
89 // Replace inline functions with fake callables
90 array_walk_recursive( $data, static function ( &$item, $key ) {
91 if ( $item instanceof Closure ) {
92 $item = 'Test::test';
93 }
94 } );
95 // Convert PHP associative arrays to stdClass objects recursively
96 $data = json_decode( json_encode( $data ) );
97
98 $validator = new Validator;
99 $validator->validate( $data, (object)[ '$ref' => 'file://' . $schemaPath . '#/properties/ResourceModules' ] );
100
101 $this->assertEquals(
102 [],
103 $validator->getErrors(),
104 'Found errors when validating Resources.php against the ResourceModules schema: ' .
105 json_encode( $validator->getErrors(), JSON_PRETTY_PRINT )
106 );
107 }
108
109 /**
110 * Verify that all specified messages actually exist.
111 */
112 public function testMissingMessages() {
113 $data = self::getAllModules();
114 $lang = MediaWikiServices::getInstance()->getLanguageFactory()->getLanguage( 'en' );
115
116 /** @var RL\Module $module */
117 foreach ( $data['modules'] as $moduleName => $module ) {
118 foreach ( $module->getMessages() as $msgKey ) {
119 $this->assertTrue(
120 wfMessage( $msgKey )->useDatabase( false )->inLanguage( $lang )->exists(),
121 "Message '$msgKey' required by '$moduleName' must exist"
122 );
123 }
124 }
125 }
126
127 /**
128 * Get all registered modules from ResouceLoader.
129 * @return array
130 */
131 protected static function getAllModules() {
132 global $wgEnableJavaScriptTest;
133
134 // Test existance of test suite files as well
135 // (can't use setUp or setMwGlobals because providers are static)
136 $org_wgEnableJavaScriptTest = $wgEnableJavaScriptTest;
137 $wgEnableJavaScriptTest = true;
138
139 // Get main ResourceLoader
140 $rl = MediaWikiServices::getInstance()->getResourceLoader();
141
142 $modules = [];
143
144 foreach ( $rl->getModuleNames() as $moduleName ) {
145 // Hack to unblock MediaWiki CI: T404729
146 if ( $moduleName === 'ext.pageviewinfo' ) {
147 continue;
148 }
149
150 $modules[$moduleName] = $rl->getModule( $moduleName );
151 }
152
153 // Restore settings
154 $wgEnableJavaScriptTest = $org_wgEnableJavaScriptTest;
155
156 return [
157 'modules' => $modules,
158 'resourceloader' => $rl,
159 'context' => new RL\Context( $rl, new FauxRequest() )
160 ];
161 }
162
163 /**
164 * Get all stylesheet files from modules that are an instance of
165 * RL\FileModule (or one of its subclasses).
166 */
167 public static function provideMediaStylesheets() {
168 $data = self::getAllModules();
169 $context = $data['context'];
170
171 foreach ( $data['modules'] as $moduleName => $module ) {
172 if ( !$module instanceof RL\FileModule ) {
173 continue;
174 }
175
176 $moduleProxy = TestingAccessWrapper::newFromObject( $module );
177
178 $styleFiles = $moduleProxy->getStyleFiles( $context );
179
180 foreach ( $styleFiles as $media => $files ) {
181 if ( $media && $media !== 'all' ) {
182 foreach ( $files as $file ) {
183 yield [
184 $moduleName,
185 $media,
186 $file,
187 // XXX: Wrapped in an object to keep it out of PHPUnit output
188 (object)[
189 'cssText' => $moduleProxy->readStyleFile( $file, $context )
190 ],
191 ];
192 }
193 }
194 }
195 }
196 }
197
198 /**
199 * Check all resource files from RL\FileModule modules.
200 */
201 public function testResourceFiles() {
202 $this->overrideConfigValues( [
203 MainConfigNames::Logo => false,
204 MainConfigNames::Logos => [],
205 ] );
206
207 $data = self::getAllModules();
208
209 // See also RL\FileModule::__construct
210 $filePathProps = [
211 // Lists of file paths
212 'lists' => [
213 'scripts',
214 'debugScripts',
215 'styles',
216 'packageFiles',
217 ],
218
219 // Collated lists of file paths
220 'nested-lists' => [
221 'languageScripts',
222 'skinScripts',
223 'skinStyles',
224 ],
225 ];
226
227 foreach ( $data['modules'] as $moduleName => $module ) {
228 if ( !$module instanceof RL\FileModule ) {
229 continue;
230 }
231
232 $moduleProxy = TestingAccessWrapper::newFromObject( $module );
233
234 $files = [];
235
236 foreach ( $filePathProps['lists'] as $propName ) {
237 $list = $moduleProxy->$propName;
238 if ( $list === null ) {
239 continue;
240 }
241 foreach ( $list as $key => $value ) {
242 // 'scripts' are numeral arrays.
243 // 'styles' can be numeral or associative.
244 // In case of associative the key is the file path
245 // and the value is the 'media' attribute.
246 if ( is_int( $key ) ) {
247 $files[] = $value;
248 } else {
249 $files[] = $key;
250 }
251 }
252 }
253
254 foreach ( $filePathProps['nested-lists'] as $propName ) {
255 $lists = $moduleProxy->$propName;
256 foreach ( $lists as $list ) {
257 foreach ( $list as $key => $value ) {
258 // We need the same filter as for 'lists',
259 // due to 'skinStyles'.
260 if ( is_int( $key ) ) {
261 $files[] = $value;
262 } else {
263 $files[] = $key;
264 }
265 }
266 }
267 }
268
269 foreach ( $files as $key => $file ) {
270 $fileInfo = $moduleProxy->expandFileInfo( $data['context'], $file, "files[$key]" );
271 if ( !isset( $fileInfo['filePath'] ) ) {
272 continue;
273 }
274 $relativePath = $fileInfo['filePath']->getPath();
275 $localPath = $fileInfo['filePath']->getLocalPath();
276 $this->assertFileExists(
277 $localPath,
278 "File '$relativePath' referenced by '$moduleName' must exist."
279 );
280 }
281
282 // To populate missingLocalFileRefs. Not sure how sensible this is inside this test...
283 $moduleProxy->readStyleFiles(
284 $module->getStyleFiles( $data['context'] ),
285 $data['context']
286 );
287
288 $missingLocalFileRefs = $moduleProxy->missingLocalFileRefs;
289
290 foreach ( $missingLocalFileRefs as $file ) {
291 $this->assertFileExists(
292 $file,
293 "File '$file' referenced by '$moduleName' must exist."
294 );
295 }
296 }
297 }
298
299 /**
300 * Check all image files from RL\ImageModule modules.
301 */
302 public function testImageFiles() {
303 $data = self::getAllModules();
304
305 foreach ( $data['modules'] as $moduleName => $module ) {
306 if ( !$module instanceof RL\ImageModule ) {
307 continue;
308 }
309
310 $imagesFiles = $module->getImages( $data['context'] );
311 foreach ( $imagesFiles as $file ) {
312 $relativePath = $file->getName();
313 $this->assertFileExists(
314 $file->getPath( $data['context'] ),
315 "File '$relativePath' referenced by '$moduleName' must exist."
316 );
317 }
318 }
319 }
320
321 public function testRespond() {
322 $rl = $this->getServiceContainer()->getResourceLoader();
323
324 // Test user-selectable skins plus the basic "fallback" skin. Other "skippable" skins
325 // (e.g. 'apioutput', 'authentication-popup') are special-purpose and most modules are
326 // never served with them in practice (T424462#11995284).
327 $skins = array_keys( $this->getServiceContainer()->getSkinFactory()->getAllowedSkins() );
328 $skins[] = 'fallback';
329
330 $failures = [];
331 foreach ( $rl->getModuleNames() as $moduleName ) {
332 $module = $rl->getModule( $moduleName );
333 // Private modules cannot be served from load.php
334 if ( $module->shouldSkipStructureTest() ) {
335 continue;
336 }
337 // Test only general (scripts) or only=styles responses.
338 $only = $module->getType() === RL\Module::LOAD_STYLES ? 'styles' : null;
339 foreach ( $skins as $skin ) {
340 $context = new RL\Context(
341 $rl,
342 new FauxRequest( [ 'modules' => $moduleName, 'only' => $only, 'skin' => $skin ] )
343 );
344 ob_start();
345 $rl->respond( $context );
346 ob_end_clean();
347 foreach ( $rl->getErrors() as $error ) {
348 $failures[] = "[$moduleName / $skin] $error";
349 }
350 }
351 }
352 $this->assertSame( [], $failures, 'ResourceLoader modules that failed to respond' );
353 }
354 }