Debian Codegraph @

Lib/test/test_locale.py

raw
1 from decimal import Decimal
2 from test.support import verbose, is_android, is_emscripten, is_wasi
3 from test.support.warnings_helper import check_warnings
4 from test.support.import_helper import import_fresh_module
5 from unittest import mock
6 import unittest
7 import locale
8 import os
9 import sys
10 import codecs
11
12
13 class BaseLocalizedTest(unittest.TestCase):
14 #
15 # Base class for tests using a real locale
16 #
17
18 @classmethod
19 def setUpClass(cls):
20 if sys.platform == 'darwin':
21 import os
22 tlocs = ("en_US.UTF-8", "en_US.ISO8859-1", "en_US")
23 if int(os.uname().release.split('.')[0]) < 10:
24 # The locale test work fine on OSX 10.6, I (ronaldoussoren)
25 # haven't had time yet to verify if tests work on OSX 10.5
26 # (10.4 is known to be bad)
27 raise unittest.SkipTest("Locale support on MacOSX is minimal")
28 elif sys.platform.startswith("win"):
29 tlocs = ("En", "English")
30 else:
31 tlocs = ("en_US.UTF-8", "en_US.ISO8859-1",
32 "en_US.US-ASCII", "en_US")
33 try:
34 oldlocale = locale.setlocale(locale.LC_NUMERIC)
35 for tloc in tlocs:
36 try:
37 locale.setlocale(locale.LC_NUMERIC, tloc)
38 except locale.Error:
39 continue
40 break
41 else:
42 raise unittest.SkipTest("Test locale not supported "
43 "(tried %s)" % (', '.join(tlocs)))
44 cls.enUS_locale = tloc
45 finally:
46 locale.setlocale(locale.LC_NUMERIC, oldlocale)
47
48 def setUp(self):
49 oldlocale = locale.setlocale(self.locale_type)
50 self.addCleanup(locale.setlocale, self.locale_type, oldlocale)
51 locale.setlocale(self.locale_type, self.enUS_locale)
52 if verbose:
53 print("testing with %r..." % self.enUS_locale, end=' ', flush=True)
54
55
56 class BaseCookedTest(unittest.TestCase):
57 #
58 # Base class for tests using cooked localeconv() values
59 #
60
61 def setUp(self):
62 locale._override_localeconv = self.cooked_values
63
64 def tearDown(self):
65 locale._override_localeconv = {}
66
67 class CCookedTest(BaseCookedTest):
68 # A cooked "C" locale
69
70 cooked_values = {
71 'currency_symbol': '',
72 'decimal_point': '.',
73 'frac_digits': 127,
74 'grouping': [],
75 'int_curr_symbol': '',
76 'int_frac_digits': 127,
77 'mon_decimal_point': '',
78 'mon_grouping': [],
79 'mon_thousands_sep': '',
80 'n_cs_precedes': 127,
81 'n_sep_by_space': 127,
82 'n_sign_posn': 127,
83 'negative_sign': '',
84 'p_cs_precedes': 127,
85 'p_sep_by_space': 127,
86 'p_sign_posn': 127,
87 'positive_sign': '',
88 'thousands_sep': ''
89 }
90
91 class EnUSCookedTest(BaseCookedTest):
92 # A cooked "en_US" locale
93
94 cooked_values = {
95 'currency_symbol': '$',
96 'decimal_point': '.',
97 'frac_digits': 2,
98 'grouping': [3, 3, 0],
99 'int_curr_symbol': 'USD ',
100 'int_frac_digits': 2,
101 'mon_decimal_point': '.',
102 'mon_grouping': [3, 3, 0],
103 'mon_thousands_sep': ',',
104 'n_cs_precedes': 1,
105 'n_sep_by_space': 0,
106 'n_sign_posn': 1,
107 'negative_sign': '-',
108 'p_cs_precedes': 1,
109 'p_sep_by_space': 0,
110 'p_sign_posn': 1,
111 'positive_sign': '',
112 'thousands_sep': ','
113 }
114
115
116 class FrFRCookedTest(BaseCookedTest):
117 # A cooked "fr_FR" locale with a space character as decimal separator
118 # and a non-ASCII currency symbol.
119
120 cooked_values = {
121 'currency_symbol': '\u20ac',
122 'decimal_point': ',',
123 'frac_digits': 2,
124 'grouping': [3, 3, 0],
125 'int_curr_symbol': 'EUR ',
126 'int_frac_digits': 2,
127 'mon_decimal_point': ',',
128 'mon_grouping': [3, 3, 0],
129 'mon_thousands_sep': ' ',
130 'n_cs_precedes': 0,
131 'n_sep_by_space': 1,
132 'n_sign_posn': 1,
133 'negative_sign': '-',
134 'p_cs_precedes': 0,
135 'p_sep_by_space': 1,
136 'p_sign_posn': 1,
137 'positive_sign': '',
138 'thousands_sep': ' '
139 }
140
141
142 class BaseFormattingTest(object):
143 #
144 # Utility functions for formatting tests
145 #
146
147 def _test_format_string(self, format, value, out, **format_opts):
148 self.assertEqual(
149 locale.format_string(format, value, **format_opts), out)
150
151 def _test_currency(self, value, out, **format_opts):
152 self.assertEqual(locale.currency(value, **format_opts), out)
153
154
155 class EnUSNumberFormatting(BaseFormattingTest):
156 # XXX there is a grouping + padding bug when the thousands separator
157 # is empty but the grouping array contains values (e.g. Solaris 10)
158
159 def setUp(self):
160 self.sep = locale.localeconv()['thousands_sep']
161
162 def test_grouping(self):
163 self._test_format_string("%f", 1024, grouping=1, out='1%s024.000000' % self.sep)
164 self._test_format_string("%f", 102, grouping=1, out='102.000000')
165 self._test_format_string("%f", -42, grouping=1, out='-42.000000')
166 self._test_format_string("%+f", -42, grouping=1, out='-42.000000')
167
168 def test_grouping_and_padding(self):
169 self._test_format_string("%20.f", -42, grouping=1, out='-42'.rjust(20))
170 if self.sep:
171 self._test_format_string("%+10.f", -4200, grouping=1,
172 out=('-4%s200' % self.sep).rjust(10))
173 self._test_format_string("%-10.f", -4200, grouping=1,
174 out=('-4%s200' % self.sep).ljust(10))
175
176 def test_integer_grouping(self):
177 self._test_format_string("%d", 4200, grouping=True, out='4%s200' % self.sep)
178 self._test_format_string("%+d", 4200, grouping=True, out='+4%s200' % self.sep)
179 self._test_format_string("%+d", -4200, grouping=True, out='-4%s200' % self.sep)
180
181 def test_integer_grouping_and_padding(self):
182 self._test_format_string("%10d", 4200, grouping=True,
183 out=('4%s200' % self.sep).rjust(10))
184 self._test_format_string("%-10d", -4200, grouping=True,
185 out=('-4%s200' % self.sep).ljust(10))
186
187 def test_simple(self):
188 self._test_format_string("%f", 1024, grouping=0, out='1024.000000')
189 self._test_format_string("%f", 102, grouping=0, out='102.000000')
190 self._test_format_string("%f", -42, grouping=0, out='-42.000000')
191 self._test_format_string("%+f", -42, grouping=0, out='-42.000000')
192
193 def test_padding(self):
194 self._test_format_string("%20.f", -42, grouping=0, out='-42'.rjust(20))
195 self._test_format_string("%+10.f", -4200, grouping=0, out='-4200'.rjust(10))
196 self._test_format_string("%-10.f", 4200, grouping=0, out='4200'.ljust(10))
197
198 def test_complex_formatting(self):
199 # Spaces in formatting string
200 self._test_format_string("One million is %i", 1000000, grouping=1,
201 out='One million is 1%s000%s000' % (self.sep, self.sep))
202 self._test_format_string("One million is %i", 1000000, grouping=1,
203 out='One million is 1%s000%s000' % (self.sep, self.sep))
204 # Dots in formatting string
205 self._test_format_string(".%f.", 1000.0, out='.1000.000000.')
206 # Padding
207 if self.sep:
208 self._test_format_string("--> %10.2f", 4200, grouping=1,
209 out='--> ' + ('4%s200.00' % self.sep).rjust(10))
210 # Asterisk formats
211 self._test_format_string("%10.*f", (2, 1000), grouping=0,
212 out='1000.00'.rjust(10))
213 if self.sep:
214 self._test_format_string("%*.*f", (10, 2, 1000), grouping=1,
215 out=('1%s000.00' % self.sep).rjust(10))
216 # Test more-in-one
217 if self.sep:
218 self._test_format_string("int %i float %.2f str %s",
219 (1000, 1000.0, 'str'), grouping=1,
220 out='int 1%s000 float 1%s000.00 str str' %
221 (self.sep, self.sep))
222
223 self._test_format_string("total=%i%%", 100, out='total=100%')
224 self._test_format_string("newline: %i\n", 3, out='newline: 3\n')
225 self._test_format_string("extra: %ii", 3, out='extra: 3i')
226
227
228 class TestLocaleFormatString(unittest.TestCase):
229 """General tests on locale.format_string"""
230
231 def test_percent_escape(self):
232 self.assertEqual(locale.format_string('%f%%', 1.0), '%f%%' % 1.0)
233 self.assertEqual(locale.format_string('%d %f%%d', (1, 1.0)),
234 '%d %f%%d' % (1, 1.0))
235 self.assertEqual(locale.format_string('%(foo)s %%d', {'foo': 'bar'}),
236 ('%(foo)s %%d' % {'foo': 'bar'}))
237
238 def test_mapping(self):
239 self.assertEqual(locale.format_string('%(foo)s bing.', {'foo': 'bar'}),
240 ('%(foo)s bing.' % {'foo': 'bar'}))
241 self.assertEqual(locale.format_string('%(foo)s', {'foo': 'bar'}),
242 ('%(foo)s' % {'foo': 'bar'}))
243
244
245
246 class TestNumberFormatting(BaseLocalizedTest, EnUSNumberFormatting):
247 # Test number formatting with a real English locale.
248
249 locale_type = locale.LC_NUMERIC
250
251 def setUp(self):
252 BaseLocalizedTest.setUp(self)
253 EnUSNumberFormatting.setUp(self)
254
255
256 class TestEnUSNumberFormatting(EnUSCookedTest, EnUSNumberFormatting):
257 # Test number formatting with a cooked "en_US" locale.
258
259 def setUp(self):
260 EnUSCookedTest.setUp(self)
261 EnUSNumberFormatting.setUp(self)
262
263 def test_currency(self):
264 self._test_currency(50000, "$50000.00")
265 self._test_currency(50000, "$50,000.00", grouping=True)
266 self._test_currency(50000, "USD 50,000.00",
267 grouping=True, international=True)
268
269
270 class TestCNumberFormatting(CCookedTest, BaseFormattingTest):
271 # Test number formatting with a cooked "C" locale.
272
273 def test_grouping(self):
274 self._test_format_string("%.2f", 12345.67, grouping=True, out='12345.67')
275
276 def test_grouping_and_padding(self):
277 self._test_format_string("%9.2f", 12345.67, grouping=True, out=' 12345.67')
278
279
280 class TestFrFRNumberFormatting(FrFRCookedTest, BaseFormattingTest):
281 # Test number formatting with a cooked "fr_FR" locale.
282
283 def test_decimal_point(self):
284 self._test_format_string("%.2f", 12345.67, out='12345,67')
285
286 def test_grouping(self):
287 self._test_format_string("%.2f", 345.67, grouping=True, out='345,67')
288 self._test_format_string("%.2f", 12345.67, grouping=True, out='12 345,67')
289
290 def test_grouping_and_padding(self):
291 self._test_format_string("%6.2f", 345.67, grouping=True, out='345,67')
292 self._test_format_string("%7.2f", 345.67, grouping=True, out=' 345,67')
293 self._test_format_string("%8.2f", 12345.67, grouping=True, out='12 345,67')
294 self._test_format_string("%9.2f", 12345.67, grouping=True, out='12 345,67')
295 self._test_format_string("%10.2f", 12345.67, grouping=True, out=' 12 345,67')
296 self._test_format_string("%-6.2f", 345.67, grouping=True, out='345,67')
297 self._test_format_string("%-7.2f", 345.67, grouping=True, out='345,67 ')
298 self._test_format_string("%-8.2f", 12345.67, grouping=True, out='12 345,67')
299 self._test_format_string("%-9.2f", 12345.67, grouping=True, out='12 345,67')
300 self._test_format_string("%-10.2f", 12345.67, grouping=True, out='12 345,67 ')
301
302 def test_integer_grouping(self):
303 self._test_format_string("%d", 200, grouping=True, out='200')
304 self._test_format_string("%d", 4200, grouping=True, out='4 200')
305
306 def test_integer_grouping_and_padding(self):
307 self._test_format_string("%4d", 4200, grouping=True, out='4 200')
308 self._test_format_string("%5d", 4200, grouping=True, out='4 200')
309 self._test_format_string("%10d", 4200, grouping=True, out='4 200'.rjust(10))
310 self._test_format_string("%-4d", 4200, grouping=True, out='4 200')
311 self._test_format_string("%-5d", 4200, grouping=True, out='4 200')
312 self._test_format_string("%-10d", 4200, grouping=True, out='4 200'.ljust(10))
313
314 def test_currency(self):
315 euro = '\u20ac'
316 self._test_currency(50000, "50000,00 " + euro)
317 self._test_currency(50000, "50 000,00 " + euro, grouping=True)
318 self._test_currency(50000, "50 000,00 EUR",
319 grouping=True, international=True)
320
321
322 class TestCollation(unittest.TestCase):
323 # Test string collation functions
324
325 def test_strcoll(self):
326 self.assertLess(locale.strcoll('a', 'b'), 0)
327 self.assertEqual(locale.strcoll('a', 'a'), 0)
328 self.assertGreater(locale.strcoll('b', 'a'), 0)
329 # embedded null character
330 self.assertRaises(ValueError, locale.strcoll, 'a\0', 'a')
331 self.assertRaises(ValueError, locale.strcoll, 'a', 'a\0')
332
333 def test_strxfrm(self):
334 self.assertLess(locale.strxfrm('a'), locale.strxfrm('b'))
335 # embedded null character
336 self.assertRaises(ValueError, locale.strxfrm, 'a\0')
337
338
339 class TestEnUSCollation(BaseLocalizedTest, TestCollation):
340 # Test string collation functions with a real English locale
341
342 locale_type = locale.LC_ALL
343
344 def setUp(self):
345 enc = codecs.lookup(locale.getencoding() or 'ascii').name
346 if enc not in ('utf-8', 'iso8859-1', 'cp1252'):
347 raise unittest.SkipTest('encoding not suitable')
348 if enc != 'iso8859-1' and is_android:
349 raise unittest.SkipTest('wcscoll/wcsxfrm have known bugs')
350 BaseLocalizedTest.setUp(self)
351
352 @unittest.skipIf(sys.platform.startswith('aix'),
353 'bpo-29972: broken test on AIX')
354 @unittest.skipIf(
355 is_emscripten or is_wasi,
356 "musl libc issue on Emscripten/WASI, bpo-46390"
357 )
358 @unittest.skipIf(sys.platform.startswith("netbsd"),
359 "gh-124108: NetBSD doesn't support UTF-8 for LC_COLLATE")
360 def test_strcoll_with_diacritic(self):
361 self.assertLess(locale.strcoll('à', 'b'), 0)
362
363 @unittest.skipIf(sys.platform.startswith('aix'),
364 'bpo-29972: broken test on AIX')
365 @unittest.skipIf(
366 is_emscripten or is_wasi,
367 "musl libc issue on Emscripten/WASI, bpo-46390"
368 )
369 @unittest.skipIf(sys.platform.startswith("netbsd"),
370 "gh-124108: NetBSD doesn't support UTF-8 for LC_COLLATE")
371 def test_strxfrm_with_diacritic(self):
372 self.assertLess(locale.strxfrm('à'), locale.strxfrm('b'))
373
374
375 class NormalizeTest(unittest.TestCase):
376 def check(self, localename, expected):
377 self.assertEqual(locale.normalize(localename), expected, msg=localename)
378
379 def test_locale_alias(self):
380 for localename, alias in locale.locale_alias.items():
381 with self.subTest(locale=(localename, alias)):
382 self.check(localename, alias)
383
384 def test_empty(self):
385 self.check('', '')
386
387 def test_c(self):
388 self.check('c', 'C')
389 self.check('posix', 'C')
390
391 def test_c_utf8(self):
392 self.check('c.utf8', 'C.UTF-8')
393 self.check('C.UTF-8', 'C.UTF-8')
394
395 def test_english(self):
396 self.check('en', 'en_US.ISO8859-1')
397 self.check('EN', 'en_US.ISO8859-1')
398 self.check('en.iso88591', 'en_US.ISO8859-1')
399 self.check('en_US', 'en_US.ISO8859-1')
400 self.check('en_us', 'en_US.ISO8859-1')
401 self.check('en_GB', 'en_GB.ISO8859-1')
402 self.check('en_US.UTF-8', 'en_US.UTF-8')
403 self.check('en_US.utf8', 'en_US.UTF-8')
404 self.check('en_US:UTF-8', 'en_US.UTF-8')
405 self.check('en_US.ISO8859-1', 'en_US.ISO8859-1')
406 self.check('en_US.US-ASCII', 'en_US.ISO8859-1')
407 self.check('en_US.88591', 'en_US.ISO8859-1')
408 self.check('en_US.885915', 'en_US.ISO8859-15')
409 self.check('english', 'en_EN.ISO8859-1')
410 self.check('english_uk.ascii', 'en_GB.ISO8859-1')
411
412 def test_hyphenated_encoding(self):
413 self.check('az_AZ.iso88599e', 'az_AZ.ISO8859-9E')
414 self.check('az_AZ.ISO8859-9E', 'az_AZ.ISO8859-9E')
415 self.check('tt_RU.koi8c', 'tt_RU.KOI8-C')
416 self.check('tt_RU.KOI8-C', 'tt_RU.KOI8-C')
417 self.check('lo_LA.cp1133', 'lo_LA.IBM-CP1133')
418 self.check('lo_LA.ibmcp1133', 'lo_LA.IBM-CP1133')
419 self.check('lo_LA.IBM-CP1133', 'lo_LA.IBM-CP1133')
420 self.check('uk_ua.microsoftcp1251', 'uk_UA.CP1251')
421 self.check('uk_ua.microsoft-cp1251', 'uk_UA.CP1251')
422 self.check('ka_ge.georgianacademy', 'ka_GE.GEORGIAN-ACADEMY')
423 self.check('ka_GE.GEORGIAN-ACADEMY', 'ka_GE.GEORGIAN-ACADEMY')
424 self.check('cs_CZ.iso88592', 'cs_CZ.ISO8859-2')
425 self.check('cs_CZ.ISO8859-2', 'cs_CZ.ISO8859-2')
426
427 def test_euro_modifier(self):
428 self.check('de_DE@euro', 'de_DE.ISO8859-15')
429 self.check('en_US.ISO8859-15@euro', 'en_US.ISO8859-15')
430 self.check('de_DE.utf8@euro', 'de_DE.UTF-8')
431
432 def test_latin_modifier(self):
433 self.check('be_BY.UTF-8@latin', 'be_BY.UTF-8@latin')
434 self.check('sr_RS.UTF-8@latin', 'sr_RS.UTF-8@latin')
435 self.check('sr_RS.UTF-8@latn', 'sr_RS.UTF-8@latin')
436
437 def test_valencia_modifier(self):
438 self.check('ca_ES.UTF-8@valencia', 'ca_ES.UTF-8@valencia')
439 self.check('ca_ES@valencia', 'ca_ES.UTF-8@valencia')
440 self.check('ca@valencia', 'ca_ES.ISO8859-1@valencia')
441
442 def test_devanagari_modifier(self):
443 self.check('ks_IN.UTF-8@devanagari', 'ks_IN.UTF-8@devanagari')
444 self.check('ks_IN@devanagari', 'ks_IN.UTF-8@devanagari')
445 self.check('ks@devanagari', 'ks_IN.UTF-8@devanagari')
446 self.check('ks_IN.UTF-8', 'ks_IN.UTF-8')
447 self.check('ks_IN', 'ks_IN.UTF-8')
448 self.check('ks', 'ks_IN.UTF-8')
449 self.check('sd_IN.UTF-8@devanagari', 'sd_IN.UTF-8@devanagari')
450 self.check('sd_IN@devanagari', 'sd_IN.UTF-8@devanagari')
451 self.check('sd@devanagari', 'sd_IN.UTF-8@devanagari')
452 self.check('sd_IN.UTF-8', 'sd_IN.UTF-8')
453 self.check('sd_IN', 'sd_IN.UTF-8')
454 self.check('sd', 'sd_IN.UTF-8')
455
456 def test_euc_encoding(self):
457 self.check('ja_jp.euc', 'ja_JP.eucJP')
458 self.check('ja_jp.eucjp', 'ja_JP.eucJP')
459 self.check('ko_kr.euc', 'ko_KR.eucKR')
460 self.check('ko_kr.euckr', 'ko_KR.eucKR')
461 self.check('zh_cn.euc', 'zh_CN.eucCN')
462 self.check('zh_tw.euc', 'zh_TW.eucTW')
463 self.check('zh_tw.euctw', 'zh_TW.eucTW')
464
465 def test_japanese(self):
466 self.check('ja', 'ja_JP.eucJP')
467 self.check('ja.jis', 'ja_JP.JIS7')
468 self.check('ja.sjis', 'ja_JP.SJIS')
469 self.check('ja_jp', 'ja_JP.eucJP')
470 self.check('ja_jp.ajec', 'ja_JP.eucJP')
471 self.check('ja_jp.euc', 'ja_JP.eucJP')
472 self.check('ja_jp.eucjp', 'ja_JP.eucJP')
473 self.check('ja_jp.iso-2022-jp', 'ja_JP.JIS7')
474 self.check('ja_jp.iso2022jp', 'ja_JP.JIS7')
475 self.check('ja_jp.jis', 'ja_JP.JIS7')
476 self.check('ja_jp.jis7', 'ja_JP.JIS7')
477 self.check('ja_jp.mscode', 'ja_JP.SJIS')
478 self.check('ja_jp.pck', 'ja_JP.SJIS')
479 self.check('ja_jp.sjis', 'ja_JP.SJIS')
480 self.check('ja_jp.ujis', 'ja_JP.eucJP')
481 self.check('ja_jp.utf8', 'ja_JP.UTF-8')
482 self.check('japan', 'ja_JP.eucJP')
483 self.check('japanese', 'ja_JP.eucJP')
484 self.check('japanese-euc', 'ja_JP.eucJP')
485 self.check('japanese.euc', 'ja_JP.eucJP')
486 self.check('japanese.sjis', 'ja_JP.SJIS')
487 self.check('jp_jp', 'ja_JP.eucJP')
488
489
490 class TestRealLocales(unittest.TestCase):
491 def setUp(self):
492 oldlocale = locale.setlocale(locale.LC_CTYPE)
493 self.addCleanup(locale.setlocale, locale.LC_CTYPE, oldlocale)
494
495 def test_getsetlocale_issue1813(self):
496 # Issue #1813: setting and getting the locale under a Turkish locale
497 try:
498 locale.setlocale(locale.LC_CTYPE, 'tr_TR')
499 except locale.Error:
500 # Unsupported locale on this system
501 self.skipTest('test needs Turkish locale')
502 loc = locale.getlocale(locale.LC_CTYPE)
503 if verbose:
504 print('testing with %a' % (loc,), end=' ', flush=True)
505 try:
506 locale.setlocale(locale.LC_CTYPE, loc)
507 except locale.Error as exc:
508 # bpo-37945: setlocale(LC_CTYPE) fails with getlocale(LC_CTYPE)
509 # and the tr_TR locale on Windows. getlocale() builds a locale
510 # which is not recognize by setlocale().
511 self.skipTest(f"setlocale(LC_CTYPE, {loc!r}) failed: {exc!r}")
512 self.assertEqual(loc, locale.getlocale(locale.LC_CTYPE))
513
514 @unittest.skipUnless(os.name == 'nt', 'requires Windows')
515 def test_setlocale_long_encoding(self):
516 with self.assertRaises(locale.Error):
517 locale.setlocale(locale.LC_CTYPE, 'English.%016d' % 1252)
518 locale.setlocale(locale.LC_CTYPE, 'English.%015d' % 1252)
519 loc = locale.setlocale(locale.LC_ALL)
520 self.assertIn('.1252', loc)
521 loc2 = loc.replace('.1252', '.%016d' % 1252, 1)
522 with self.assertRaises(locale.Error):
523 locale.setlocale(locale.LC_ALL, loc2)
524 loc2 = loc.replace('.1252', '.%015d' % 1252, 1)
525 locale.setlocale(locale.LC_ALL, loc2)
526
527 # gh-137273: Debug assertion failure on Windows for long encoding.
528 with self.assertRaises(locale.Error):
529 locale.setlocale(locale.LC_CTYPE, 'en_US.' + 'x'*16)
530 locale.setlocale(locale.LC_CTYPE, 'en_US.UTF-8')
531 loc = locale.setlocale(locale.LC_ALL)
532 self.assertIn('.UTF-8', loc)
533 loc2 = loc.replace('.UTF-8', '.' + 'x'*16, 1)
534 with self.assertRaises(locale.Error):
535 locale.setlocale(locale.LC_ALL, loc2)
536
537
538 class TestMiscellaneous(unittest.TestCase):
539 def test_defaults_UTF8(self):
540 # Issue #18378: on (at least) macOS setting LC_CTYPE to "UTF-8" is
541 # valid. Furthermore LC_CTYPE=UTF is used by the UTF-8 locale coercing
542 # during interpreter startup (on macOS).
543 import _locale
544 import os
545
546 self.assertEqual(locale._parse_localename('UTF-8'), (None, 'UTF-8'))
547
548 if hasattr(_locale, '_getdefaultlocale'):
549 orig_getlocale = _locale._getdefaultlocale
550 del _locale._getdefaultlocale
551 else:
552 orig_getlocale = None
553
554 orig_env = {}
555 try:
556 for key in ('LC_ALL', 'LC_CTYPE', 'LANG', 'LANGUAGE'):
557 if key in os.environ:
558 orig_env[key] = os.environ[key]
559 del os.environ[key]
560
561 os.environ['LC_CTYPE'] = 'UTF-8'
562
563 with check_warnings(('', DeprecationWarning)):
564 self.assertEqual(locale.getdefaultlocale(), (None, 'UTF-8'))
565
566 finally:
567 for k in orig_env:
568 os.environ[k] = orig_env[k]
569
570 if 'LC_CTYPE' not in orig_env:
571 del os.environ['LC_CTYPE']
572
573 if orig_getlocale is not None:
574 _locale._getdefaultlocale = orig_getlocale
575
576 def test_getencoding(self):
577 # Invoke getencoding to make sure it does not cause exceptions.
578 enc = locale.getencoding()
579 self.assertIsInstance(enc, str)
580 self.assertNotEqual(enc, "")
581 # make sure it is valid
582 codecs.lookup(enc)
583
584 def test_getencoding_fallback(self):
585 # When _locale.getencoding() is missing, locale.getencoding() uses
586 # the Python filesystem
587 encoding = 'FALLBACK_ENCODING'
588 with mock.patch.object(sys, 'getfilesystemencoding',
589 return_value=encoding):
590 locale_fallback = import_fresh_module('locale', blocked=['_locale'])
591 self.assertEqual(locale_fallback.getencoding(), encoding)
592
593 def test_getpreferredencoding(self):
594 # Invoke getpreferredencoding to make sure it does not cause exceptions.
595 enc = locale.getpreferredencoding()
596 if enc:
597 # If encoding non-empty, make sure it is valid
598 codecs.lookup(enc)
599
600 def test_strcoll_3303(self):
601 # test crasher from bug #3303
602 self.assertRaises(TypeError, locale.strcoll, "a", None)
603 self.assertRaises(TypeError, locale.strcoll, b"a", None)
604
605 def test_setlocale_category(self):
606 locale.setlocale(locale.LC_ALL)
607 locale.setlocale(locale.LC_TIME)
608 locale.setlocale(locale.LC_CTYPE)
609 locale.setlocale(locale.LC_COLLATE)
610 locale.setlocale(locale.LC_MONETARY)
611 locale.setlocale(locale.LC_NUMERIC)
612
613 # crasher from bug #7419
614 self.assertRaises(locale.Error, locale.setlocale, 12345)
615
616 def test_invalid_locale_format_in_localetuple(self):
617 with self.assertRaises(TypeError):
618 locale.setlocale(locale.LC_ALL, b'fi_FI')
619
620 def test_invalid_iterable_in_localetuple(self):
621 with self.assertRaises(TypeError):
622 locale.setlocale(locale.LC_ALL, (b'not', b'valid'))
623
624
625 class BaseDelocalizeTest(BaseLocalizedTest):
626
627 def _test_delocalize(self, value, out):
628 self.assertEqual(locale.delocalize(value), out)
629
630 def _test_atof(self, value, out):
631 self.assertEqual(locale.atof(value), out)
632
633 def _test_atoi(self, value, out):
634 self.assertEqual(locale.atoi(value), out)
635
636
637 class TestEnUSDelocalize(EnUSCookedTest, BaseDelocalizeTest):
638
639 def test_delocalize(self):
640 self._test_delocalize('50000.00', '50000.00')
641 self._test_delocalize('50,000.00', '50000.00')
642
643 def test_atof(self):
644 self._test_atof('50000.00', 50000.)
645 self._test_atof('50,000.00', 50000.)
646
647 def test_atoi(self):
648 self._test_atoi('50000', 50000)
649 self._test_atoi('50,000', 50000)
650
651
652 class TestCDelocalizeTest(CCookedTest, BaseDelocalizeTest):
653
654 def test_delocalize(self):
655 self._test_delocalize('50000.00', '50000.00')
656
657 def test_atof(self):
658 self._test_atof('50000.00', 50000.)
659
660 def test_atoi(self):
661 self._test_atoi('50000', 50000)
662
663
664 class TestfrFRDelocalizeTest(FrFRCookedTest, BaseDelocalizeTest):
665
666 def test_delocalize(self):
667 self._test_delocalize('50000,00', '50000.00')
668 self._test_delocalize('50 000,00', '50000.00')
669
670 def test_atof(self):
671 self._test_atof('50000,00', 50000.)
672 self._test_atof('50 000,00', 50000.)
673
674 def test_atoi(self):
675 self._test_atoi('50000', 50000)
676 self._test_atoi('50 000', 50000)
677
678
679 class BaseLocalizeTest(BaseLocalizedTest):
680
681 def _test_localize(self, value, out, grouping=False):
682 self.assertEqual(locale.localize(value, grouping=grouping), out)
683
684
685 class TestEnUSLocalize(EnUSCookedTest, BaseLocalizeTest):
686
687 def test_localize(self):
688 self._test_localize('50000.00', '50000.00')
689 self._test_localize(
690 '{0:.16f}'.format(Decimal('1.15')), '1.1500000000000000')
691
692
693 class TestCLocalize(CCookedTest, BaseLocalizeTest):
694
695 def test_localize(self):
696 self._test_localize('50000.00', '50000.00')
697
698
699 class TestfrFRLocalize(FrFRCookedTest, BaseLocalizeTest):
700
701 def test_localize(self):
702 self._test_localize('50000.00', '50000,00')
703 self._test_localize('50000.00', '50 000,00', grouping=True)
704
705
706 if __name__ == '__main__':
707 unittest.main()