Debian Codegraph @

tests/phpunit/unit/includes/language/LanguageNameUtilsTestTrait.php

raw symbols SCIP
1 <?php
2
3 // phpcs:disable MediaWiki.Commenting.FunctionComment.MissingParamTag -- Traits are not excluded
4
5 use MediaWiki\Languages\LanguageNameUtils;
6 use MediaWiki\MainConfigNames;
7
8 const AUTONYMS = LanguageNameUtils::AUTONYMS;
9 const ALL = LanguageNameUtils::ALL;
10 const DEFINED = LanguageNameUtils::DEFINED;
11 const SUPPORTED = LanguageNameUtils::SUPPORTED;
12
13 /**
14 * @internal For LanguageNameUtilsTest and LanguageIntegrationTest.
15 */
16 trait LanguageNameUtilsTestTrait {
17 abstract protected function isSupportedLanguage( $code );
18
19 /**
20 * @dataProvider provideIsSupportedLanguage
21 */
22 public function testIsSupportedLanguage( $code, $expected ) {
23 $this->assertSame( $expected, $this->isSupportedLanguage( $code ) );
24 }
25
26 public static function provideIsSupportedLanguage() {
27 return [
28 'en' => [ 'en', true ],
29 'fi' => [ 'fi', true ],
30 'bunny' => [ 'bunny', false ],
31 'qqq' => [ 'qqq', false ],
32 'uppercase is not considered supported' => [ 'FI', false ],
33 ];
34 }
35
36 abstract protected function isValidCode( $code );
37
38 /**
39 * We don't test that the result is cached, because that should only be noticeable if the
40 * configuration changes in between calls, and 1) that should never happen in normal operation,
41 * 2) if you do it you deserve whatever you get, and 3) once the static Language method is
42 * dropped and the invalid title regex is moved to something injected instead of a static call,
43 * the cache will be undetectable.
44 *
45 * @todo Should we test changes to $wgLegalTitleChars here? Does anybody actually change that?
46 * Is it possible to change it usefully without breaking everything?
47 *
48 * @dataProvider provideIsValidCode
49 * @param string $code
50 * @param bool $expected
51 */
52 public function testIsValidCode( $code, $expected ) {
53 $this->assertSame( $expected, $this->isValidCode( $code ) );
54 }
55
56 public static function provideIsValidCode() {
57 $ret = [
58 'en' => [ 'en', true ],
59 'en-GB' => [ 'en-GB', true ],
60 'Funny chars' => [ "%!$()*,-.;=?@^_`~\x80\xA2\xFF+", true ],
61 'Percent escape not allowed' => [ 'a%aF', false ],
62 'Percent with only one following char is okay' => [ '%a', true ],
63 'Percent with non-hex following chars is okay' => [ '%AG', true ],
64 'Named char reference "a"' => [ 'a&a', false ],
65 'Named char reference "A"' => [ 'a&A', false ],
66 'Named char reference "0"' => [ 'a&0', false ],
67 'Named char reference non-ASCII' => [ "a&\x92", false ],
68 'Numeric char reference' => [ "a&#0", false ],
69 'Hex char reference 0' => [ "a&#x0", false ],
70 'Hex char reference A' => [ "a&#xA", false ],
71 'Lone ampersand is valid for title but not lang code' => [ '&', false ],
72 'Ampersand followed by just # is valid for title but not lang code' => [ '&#', false ],
73 'Ampersand followed by # and non-x/digit is valid for title but not lang code' =>
74 [ '&#a', false ],
75 ];
76 $disallowedChars = ":/\\\000&<>'\"";
77 foreach ( str_split( $disallowedChars ) as $char ) {
78 $ret["Disallowed character $char"] = [ "a{$char}a", false ];
79 }
80 return $ret;
81 }
82
83 abstract protected function isValidBuiltInCode( $code );
84
85 /**
86 * @dataProvider provideIsValidBuiltInCode
87 * @param string $code
88 * @param bool $expected
89 */
90 public function testIsValidBuiltInCode( $code, $expected ) {
91 $this->assertSame( $expected, $this->isValidBuiltInCode( $code ) );
92 }
93
94 public static function provideIsValidBuiltInCode() {
95 return [
96 'Two letters, lowercase' => [ 'fr', true ],
97 'Two letters, uppercase' => [ 'EN', false ],
98 'Three letters' => [ 'tyv', true ],
99 'With dash' => [ 'be-tarask', true ],
100 'With extension (two dashes)' => [ 'be-x-old', true ],
101 'Reject underscores' => [ 'be_tarask', false ],
102 'One letter' => [ 'a', false ],
103 'Only digits' => [ '00', true ],
104 'Only dashes' => [ '--', true ],
105 'Unreasonably long' => [ str_repeat( 'x', 100 ), true ],
106 'qqq' => [ 'qqq', true ],
107 ];
108 }
109
110 abstract protected function isKnownLanguageTag( $code );
111
112 /**
113 * @dataProvider provideIsKnownLanguageTag
114 * @param string $code
115 * @param bool $expected
116 */
117 public function testIsKnownLanguageTag( $code, $expected ) {
118 $this->assertSame( $expected, $this->isKnownLanguageTag( $code ) );
119 }
120
121 public static function provideIsKnownLanguageTag() {
122 $invalidBuiltInCodes = array_filter( static::provideIsValidBuiltInCode(),
123 static function ( $arr ) {
124 // If isValidBuiltInCode() returns false, we want to also, but if it returns true,
125 // we could still return false from isKnownLanguageTag(), so skip those.
126 return !$arr[1];
127 }
128 );
129 return array_merge( $invalidBuiltInCodes, [
130 'Simple code' => [ 'fr', true ],
131 'An MW legacy tag' => [ 'bat-smg', true ],
132 'An internal standard MW name, for which a legacy tag is used externally' =>
133 [ 'sgs', true ],
134 'Non-existent two-letter code' => [ 'mw', false ],
135 'Very invalid language code' => [ 'foo"<bar', false ],
136 ] );
137 }
138
139 abstract protected function assertGetLanguageNames(
140 array $options, $expected, $code, ...$otherArgs
141 );
142
143 abstract protected function getLanguageNames( ...$args );
144
145 abstract protected function getLanguageName( ...$args );
146
147 /**
148 * @dataProvider provideGetLanguageNames
149 */
150 public function testGetLanguageNames( $expected, $code, ...$otherArgs ) {
151 $this->clearLanguageHook( 'LanguageGetTranslatedLanguageNames' );
152 $this->assertGetLanguageNames( [], $expected, $code, ...$otherArgs );
153 }
154
155 public static function provideGetLanguageNames() {
156 // @todo There are probably lots of interesting tests to add here.
157 return [
158 'Simple code' => [ 'Deutsch', 'de' ],
159 'Simple code in a different language' => [ 'Deutsch', 'de', 'fr' ],
160 'Invalid code' => [ '', '&' ],
161 'Pig Latin' => [ 'Igpay Atinlay', 'en-x-piglatin', AUTONYMS, ALL ],
162 'qqq doesn\'t have a name' => [ '', 'qqq', AUTONYMS, ALL ],
163 'An MW legacy tag is recognized' => [ 'žemaitėška', 'bat-smg' ],
164 'An internal standard name, for which a legacy tag is used externally, is supported' =>
165 [ 'žemaitėška', 'sgs', AUTONYMS, SUPPORTED ],
166 ];
167 }
168
169 /**
170 * Set hook for current test.
171 * @param string $hookName
172 * @param mixed $handler Value suitable for a hook handler
173 */
174 abstract protected function setLanguageTemporaryHook( string $hookName, $handler ): void;
175
176 /**
177 * Clear hook for the current test.
178 * @param string $hookName
179 */
180 abstract protected function clearLanguageHook( string $hookName ): void;
181
182 /**
183 * @dataProvider provideGetLanguageNames_withHook
184 */
185 public function testGetLanguageNames_withHook( $expected, $code, ...$otherArgs ) {
186 $this->setLanguageTemporaryHook( 'LanguageGetTranslatedLanguageNames',
187 static function ( &$names, $inLanguage ) {
188 switch ( $inLanguage ) {
189 case 'de':
190 $names = [
191 'de' => 'Deutsch',
192 'en' => 'Englisch',
193 'fr' => 'Französisch',
194 ];
195 break;
196
197 case 'en':
198 $names = [
199 'de' => 'German',
200 'en' => 'English',
201 'fr' => 'French',
202 'sqsqsqsq' => '!!?!',
203 'bat-smg' => 'Samogitian',
204 ];
205 break;
206
207 case 'fr':
208 $names = [
209 'de' => 'allemand',
210 'en' => 'anglais',
211 // Deliberate mistake (no cedilla)
212 'fr' => 'francais',
213 ];
214 break;
215 }
216 }
217 );
218
219 // Really we could dispense with assertGetLanguageNames() and just call
220 // testGetLanguageNames() here, but it looks weird to call a test method from another test
221 // method.
222 $this->assertGetLanguageNames( [], $expected, $code, ...$otherArgs );
223 }
224
225 public static function provideGetLanguageNames_withHook() {
226 return [
227 'Simple code in a different language' => [ 'allemand', 'de', 'fr' ],
228 'Invalid inLanguage defaults to English' => [ 'German', 'de', '&' ],
229 'If inLanguage not provided, default to autonym' => [ 'Deutsch', 'de' ],
230 'Hooks ignored for explicitly-requested autonym' => [ 'français', 'fr', 'fr' ],
231 'Hooks don\'t make a language supported' => [ '', 'es-419', 'en', SUPPORTED ],
232 'Hooks don\'t make a language defined' => [ '', 'sqsqsqsq', 'en', DEFINED ],
233 'Hooks do make a language name returned with ALL' => [ '!!?!', 'sqsqsqsq', 'en', ALL ],
234 ];
235 }
236
237 /**
238 * @dataProvider provideGetLanguageNames_ExtraLanguageNames
239 */
240 public function testGetLanguageNames_ExtraLanguageNames( $expected, $code, ...$otherArgs ) {
241 $this->setLanguageTemporaryHook( 'LanguageGetTranslatedLanguageNames',
242 static function ( &$names ) {
243 $names['de'] = 'die deutsche Sprache';
244 }
245 );
246 $this->assertGetLanguageNames(
247 [ MainConfigNames::ExtraLanguageNames => [ 'de' => 'deutsche Sprache', 'sqsqsqsq' => '!!?!' ] ],
248 $expected, $code, ...$otherArgs
249 );
250 }
251
252 public static function provideGetLanguageNames_ExtraLanguageNames() {
253 return [
254 'Simple extra language name' => [ '!!?!', 'sqsqsqsq' ],
255 'Extra language is defined' => [ '!!?!', 'sqsqsqsq', AUTONYMS, DEFINED ],
256 'Extra language is not supported' => [ '', 'sqsqsqsq', AUTONYMS, SUPPORTED ],
257 'Extra language overrides default' => [ 'deutsche Sprache', 'de' ],
258 'Extra language overrides hook for explicitly requested autonym' =>
259 [ 'deutsche Sprache', 'de', 'de' ],
260 'Hook overrides extra language for non-autonym' =>
261 [ 'die deutsche Sprache', 'de', 'fr' ],
262 ];
263 }
264
265 /**
266 * Test that getLanguageNames() defaults to DEFINED, and getLanguageName() defaults to ALL.
267 */
268 public function testGetLanguageNames_parameterDefault() {
269 $this->setLanguageTemporaryHook( 'LanguageGetTranslatedLanguageNames',
270 static function ( &$names ) {
271 $names = [ 'sqsqsqsq' => '!!?!' ];
272 }
273 );
274
275 // We use 'en' here because the hook is not run if we're requesting autonyms, although in
276 // this case (language that isn't defined by MediaWiki itself) that behavior seems wrong.
277 $this->assertArrayNotHasKey( 'sqsqsqsq', $this->getLanguageNames(), 'en' );
278
279 $this->assertSame( '!!?!', $this->getLanguageName( 'sqsqsqsq', 'en' ) );
280 }
281
282 /**
283 * @dataProvider provideGetLanguageNames_sorted
284 */
285 public function testGetLanguageNames_sorted( ...$args ) {
286 $names = $this->getLanguageNames( ...$args );
287 $sortedNames = $names;
288 ksort( $sortedNames );
289 $this->assertSame( $sortedNames, $names );
290 }
291
292 public static function provideGetLanguageNames_sorted() {
293 return [
294 [],
295 [ AUTONYMS ],
296 [ AUTONYMS, DEFINED ],
297 [ AUTONYMS, ALL ],
298 [ AUTONYMS, SUPPORTED ],
299 [ 'he', DEFINED ],
300 [ 'he', ALL ],
301 [ 'he', SUPPORTED ],
302 ];
303 }
304
305 public function testGetLanguageNames_hookNotCalledForAutonyms() {
306 $count = 0;
307 $this->setLanguageTemporaryHook( 'LanguageGetTranslatedLanguageNames',
308 static function () use ( &$count ) {
309 $count++;
310 }
311 );
312
313 $this->getLanguageNames();
314 $this->assertSame( 0, $count, 'Hook must not be called for autonyms' );
315
316 // We test elsewhere that the hook works, but the following verifies that our test is
317 // working and $count isn't being incremented above only because we're checking autonyms.
318 $this->getLanguageNames( 'fr' );
319 $this->assertSame( 1, $count, 'Hook must be called for non-autonyms' );
320 }
321
322 /**
323 * @dataProvider provideGetLanguageNames_pigLatin
324 */
325 public function testGetLanguageNames_pigLatin( $expected, ...$otherArgs ) {
326 $this->setLanguageTemporaryHook( 'LanguageGetTranslatedLanguageNames',
327 static function ( &$names, $inLanguage ) {
328 switch ( $inLanguage ) {
329 case 'fr':
330 $names = [ 'en-x-piglatin' => 'latin de cochons' ];
331 break;
332
333 case 'en-x-piglatin':
334 // Deliberately lowercase
335 $names = [ 'en-x-piglatin' => 'igpay atinlay' ];
336 break;
337 }
338 }
339 );
340
341 $this->assertGetLanguageNames(
342 [ MainConfigNames::UsePigLatinVariant => true ], $expected, 'en-x-piglatin', ...$otherArgs );
343 }
344
345 public static function provideGetLanguageNames_pigLatin() {
346 # Pig Latin is supported only if UsePigLatinVariant is true
347 # (which it is, for these tests)
348 return [
349 'Simple test' => [ 'Igpay Atinlay' ],
350 'Supported' => [ 'Igpay Atinlay', AUTONYMS, SUPPORTED ],
351 'Foreign language' => [ 'latin de cochons', 'fr' ],
352 'Hook doesn\'t override explicit autonym' =>
353 [ 'Igpay Atinlay', 'en-x-piglatin', 'en-x-piglatin' ],
354 ];
355 }
356
357 public function testGetLanguageNames_pigLatinNotSupported() {
358 // Pig Latin is "not supported" when UsePigLatinVariant is false
359 $this->assertGetLanguageNames(
360 [ MainConfigNames::UsePigLatinVariant => false ],
361 '', 'en-x-piglatin', AUTONYMS, SUPPORTED
362 );
363 }
364
365 /**
366 * Just for the sake of completeness, test that ExtraLanguageNames
367 * can override the name for Pig Latin. Nobody actually cares
368 * about this, but once we're testing the whole file we may as
369 * well be comprehensive.
370 */
371 public function testGetLanguageNames_pigLatinAndExtraLanguageNames() {
372 $this->assertGetLanguageNames(
373 [
374 MainConfigNames::UsePigLatinVariant => true,
375 MainConfigNames::ExtraLanguageNames => [ 'en-x-piglatin' => 'igpay atinlay' ]
376 ],
377 'igpay atinlay',
378 'en-x-piglatin'
379 );
380 }
381
382 public function testGetLanguageNames_xss(): void {
383 // not supported if disabled
384 $this->assertGetLanguageNames(
385 [
386 MainConfigNames::UseXssLanguage => false,
387 ],
388 '',
389 'x-xss'
390 );
391 // supported if enabled
392 $this->assertGetLanguageNames(
393 [
394 MainConfigNames::UseXssLanguage => true,
395 ],
396 'fake xss language (see $wgUseXssLanguage)',
397 'x-xss'
398 );
399 }
400
401 abstract protected function getFileName( ...$args );
402
403 /**
404 * @dataProvider provideGetFileName
405 */
406 public function testGetFileName( $expected, ...$args ) {
407 $this->assertSame( $expected, $this->getFileName( ...$args ) );
408 }
409
410 public static function provideGetFileName() {
411 return [
412 'Simple case' => [ 'MessagesXx.php', 'Messages', 'xx' ],
413 'With extension' => [ 'MessagesXx.ext', 'Messages', 'xx', '.ext' ],
414 'Replacing dashes' => [ '!__?', '!', '--', '?' ],
415 'Empty prefix and extension' => [ 'Xx', '', 'xx', '' ],
416 'Uppercase only first letter' => [ 'Messages_a.php', 'Messages', '-a' ],
417 ];
418 }
419
420 abstract protected function getMessagesFileName( $code );
421
422 /**
423 * @dataProvider provideGetMessagesFileName
424 * @param string $code
425 * @param string $expected
426 */
427 public function testGetMessagesFileName( $code, $expected ) {
428 $this->assertSame( $expected, $this->getMessagesFileName( $code ) );
429 }
430
431 public static function provideGetMessagesFileName() {
432 global $IP;
433 return [
434 'Simple case' => [ 'en', "$IP/languages/messages/MessagesEn.php" ],
435 'Replacing dashes' => [ '--', "$IP/languages/messages/Messages__.php" ],
436 'Uppercase only first letter' => [ '-a', "$IP/languages/messages/Messages_a.php" ],
437 ];
438 }
439
440 public function testGetMessagesFileName_withHook() {
441 $called = 0;
442
443 $this->setLanguageTemporaryHook( 'Language::getMessagesFileName',
444 function ( $code, &$file ) use ( &$called ) {
445 global $IP;
446
447 $called++;
448
449 $this->assertSame( 'ab-cd', $code );
450 $this->assertSame( "$IP/languages/messages/MessagesAb_cd.php", $file );
451 $file = 'bye-bye';
452 }
453 );
454
455 $this->assertSame( 'bye-bye', $this->getMessagesFileName( 'ab-cd' ) );
456 $this->assertSame( 1, $called );
457 }
458
459 abstract protected function getJsonMessagesFileName( $code );
460
461 public function testGetJsonMessagesFileName() {
462 global $IP;
463
464 // Not so much to test here, one test seems to be enough
465 $expected = "$IP/languages/i18n/en--123.json";
466 $this->assertSame( $expected, $this->getJsonMessagesFileName( 'en--123' ) );
467 }
468
469 /**
470 * getFileName, getMessagesFileName, and getJsonMessagesFileName all throw if they get an
471 * invalid code. To save boilerplate, test them all in one method.
472 *
473 * @dataProvider provideExceptionFromInvalidCode
474 * @param callable $callback Will throw when passed $code
475 * @param string $code
476 */
477 public function testExceptionFromInvalidCode( $callback, $code ) {
478 $this->expectException( InvalidArgumentException::class );
479 $this->expectExceptionMessage( "Invalid language code \"$code\"" );
480
481 $callback( $code );
482 }
483
484 public function provideExceptionFromInvalidCode() {
485 $ret = [];
486 foreach ( static::provideIsValidBuiltInCode() as $desc => [ $code, $valid ] ) {
487 if ( $valid ) {
488 // Won't get an exception from this one
489 continue;
490 }
491
492 // For getFileName, we define an anonymous function because of the extra first param
493 $ret["getFileName: $desc"] = [
494 function ( $code ) {
495 return $this->getFileName( 'Messages', $code );
496 },
497 $code
498 ];
499
500 $ret["getMessagesFileName: $desc"] =
501 [ [ $this, 'getMessagesFileName' ], $code ];
502
503 $ret["getJsonMessagesFileName: $desc"] =
504 [ [ $this, 'getJsonMessagesFileName' ], $code ];
505 }
506 return $ret;
507 }
508 }