blob: 19abe596fd57ad7b59e8bcc20f3c40e8bb384d17 [file] [log] [blame]
Benjamin Petersone549ead2009-03-28 21:42:05 +00001from test.support import run_unittest, verbose
Stefan Krahf187a022011-08-02 01:06:16 +02002from platform import linux_distribution
Antoine Pitrou83d6a872008-07-25 21:45:08 +00003import unittest
Martin v. Löwis88ad12a2001-04-13 08:09:50 +00004import locale
Guido van Rossumfc349862001-04-15 13:15:56 +00005import sys
Antoine Pitrou83d6a872008-07-25 21:45:08 +00006import codecs
Martin v. Löwis88ad12a2001-04-13 08:09:50 +00007
Antoine Pitrou13856ea2008-07-26 21:02:53 +00008enUS_locale = None
9
10def get_enUS_locale():
11 global enUS_locale
Ronald Oussoren501aeff2010-04-18 15:02:38 +000012 if sys.platform == 'darwin':
13 import os
14 tlocs = ("en_US.UTF-8", "en_US.ISO8859-1", "en_US")
15 if int(os.uname()[2].split('.')[0]) < 10:
16 # The locale test work fine on OSX 10.6, I (ronaldoussoren)
17 # haven't had time yet to verify if tests work on OSX 10.5
18 # (10.4 is known to be bad)
19 raise unittest.SkipTest("Locale support on MacOSX is minimal")
20 elif sys.platform.startswith("win"):
Antoine Pitrou13856ea2008-07-26 21:02:53 +000021 tlocs = ("En", "English")
22 else:
Antoine Pitrou6a448d42009-10-19 19:43:09 +000023 tlocs = ("en_US.UTF-8", "en_US.ISO8859-1", "en_US.US-ASCII", "en_US")
Antoine Pitrou13856ea2008-07-26 21:02:53 +000024 oldlocale = locale.setlocale(locale.LC_NUMERIC)
25 for tloc in tlocs:
26 try:
27 locale.setlocale(locale.LC_NUMERIC, tloc)
28 except locale.Error:
29 continue
30 break
31 else:
Benjamin Petersone549ead2009-03-28 21:42:05 +000032 raise unittest.SkipTest(
Antoine Pitrou13856ea2008-07-26 21:02:53 +000033 "Test locale not supported (tried %s)" % (', '.join(tlocs)))
34 enUS_locale = tloc
35 locale.setlocale(locale.LC_NUMERIC, oldlocale)
36
37
Antoine Pitrou83d6a872008-07-25 21:45:08 +000038class BaseLocalizedTest(unittest.TestCase):
39 #
40 # Base class for tests using a real locale
41 #
Martin v. Löwis88ad12a2001-04-13 08:09:50 +000042
Antoine Pitrou83d6a872008-07-25 21:45:08 +000043 def setUp(self):
Antoine Pitrou83d6a872008-07-25 21:45:08 +000044 self.oldlocale = locale.setlocale(self.locale_type)
Antoine Pitrou13856ea2008-07-26 21:02:53 +000045 locale.setlocale(self.locale_type, enUS_locale)
Martin v. Löwis88ad12a2001-04-13 08:09:50 +000046 if verbose:
Antoine Pitrou13856ea2008-07-26 21:02:53 +000047 print("testing with \"%s\"..." % enUS_locale, end=' ')
Martin v. Löwis88ad12a2001-04-13 08:09:50 +000048
Antoine Pitrou83d6a872008-07-25 21:45:08 +000049 def tearDown(self):
50 locale.setlocale(self.locale_type, self.oldlocale)
Thomas Wouters477c8d52006-05-27 19:21:47 +000051
Thomas Wouters477c8d52006-05-27 19:21:47 +000052
Antoine Pitrou83d6a872008-07-25 21:45:08 +000053class BaseCookedTest(unittest.TestCase):
54 #
55 # Base class for tests using cooked localeconv() values
56 #
Georg Brandl3dbca812008-07-23 16:10:53 +000057
Antoine Pitrou83d6a872008-07-25 21:45:08 +000058 def setUp(self):
59 locale._override_localeconv = self.cooked_values
60
61 def tearDown(self):
62 locale._override_localeconv = {}
63
64class CCookedTest(BaseCookedTest):
65 # A cooked "C" locale
66
67 cooked_values = {
68 'currency_symbol': '',
69 'decimal_point': '.',
70 'frac_digits': 127,
71 'grouping': [],
72 'int_curr_symbol': '',
73 'int_frac_digits': 127,
74 'mon_decimal_point': '',
75 'mon_grouping': [],
76 'mon_thousands_sep': '',
77 'n_cs_precedes': 127,
78 'n_sep_by_space': 127,
79 'n_sign_posn': 127,
80 'negative_sign': '',
81 'p_cs_precedes': 127,
82 'p_sep_by_space': 127,
83 'p_sign_posn': 127,
84 'positive_sign': '',
85 'thousands_sep': ''
86 }
87
88class EnUSCookedTest(BaseCookedTest):
89 # A cooked "en_US" locale
90
91 cooked_values = {
92 'currency_symbol': '$',
93 'decimal_point': '.',
94 'frac_digits': 2,
95 'grouping': [3, 3, 0],
96 'int_curr_symbol': 'USD ',
97 'int_frac_digits': 2,
98 'mon_decimal_point': '.',
99 'mon_grouping': [3, 3, 0],
100 'mon_thousands_sep': ',',
101 'n_cs_precedes': 1,
102 'n_sep_by_space': 0,
103 'n_sign_posn': 1,
104 'negative_sign': '-',
105 'p_cs_precedes': 1,
106 'p_sep_by_space': 0,
107 'p_sign_posn': 1,
108 'positive_sign': '',
109 'thousands_sep': ','
110 }
111
112
Antoine Pitrou350370c2009-03-14 00:13:13 +0000113class FrFRCookedTest(BaseCookedTest):
114 # A cooked "fr_FR" locale with a space character as decimal separator
115 # and a non-ASCII currency symbol.
116
117 cooked_values = {
118 'currency_symbol': '\u20ac',
119 'decimal_point': ',',
120 'frac_digits': 2,
121 'grouping': [3, 3, 0],
122 'int_curr_symbol': 'EUR ',
123 'int_frac_digits': 2,
124 'mon_decimal_point': ',',
125 'mon_grouping': [3, 3, 0],
126 'mon_thousands_sep': ' ',
127 'n_cs_precedes': 0,
128 'n_sep_by_space': 1,
129 'n_sign_posn': 1,
130 'negative_sign': '-',
131 'p_cs_precedes': 0,
132 'p_sep_by_space': 1,
133 'p_sign_posn': 1,
134 'positive_sign': '',
135 'thousands_sep': ' '
136 }
137
138
Antoine Pitrou83d6a872008-07-25 21:45:08 +0000139class BaseFormattingTest(object):
140 #
141 # Utility functions for formatting tests
142 #
143
144 def _test_formatfunc(self, format, value, out, func, **format_opts):
145 self.assertEqual(
146 func(format, value, **format_opts), out)
147
148 def _test_format(self, format, value, out, **format_opts):
149 self._test_formatfunc(format, value, out,
150 func=locale.format, **format_opts)
151
152 def _test_format_string(self, format, value, out, **format_opts):
153 self._test_formatfunc(format, value, out,
154 func=locale.format_string, **format_opts)
155
156 def _test_currency(self, value, out, **format_opts):
157 self.assertEqual(locale.currency(value, **format_opts), out)
158
159
160class EnUSNumberFormatting(BaseFormattingTest):
Antoine Pitrou13856ea2008-07-26 21:02:53 +0000161 # XXX there is a grouping + padding bug when the thousands separator
162 # is empty but the grouping array contains values (e.g. Solaris 10)
Antoine Pitrou83d6a872008-07-25 21:45:08 +0000163
164 def setUp(self):
Antoine Pitrou83d6a872008-07-25 21:45:08 +0000165 self.sep = locale.localeconv()['thousands_sep']
166
167 def test_grouping(self):
168 self._test_format("%f", 1024, grouping=1, out='1%s024.000000' % self.sep)
169 self._test_format("%f", 102, grouping=1, out='102.000000')
170 self._test_format("%f", -42, grouping=1, out='-42.000000')
171 self._test_format("%+f", -42, grouping=1, out='-42.000000')
172
173 def test_grouping_and_padding(self):
174 self._test_format("%20.f", -42, grouping=1, out='-42'.rjust(20))
Antoine Pitrou13856ea2008-07-26 21:02:53 +0000175 if self.sep:
176 self._test_format("%+10.f", -4200, grouping=1,
177 out=('-4%s200' % self.sep).rjust(10))
178 self._test_format("%-10.f", -4200, grouping=1,
179 out=('-4%s200' % self.sep).ljust(10))
Antoine Pitrou83d6a872008-07-25 21:45:08 +0000180
181 def test_integer_grouping(self):
182 self._test_format("%d", 4200, grouping=True, out='4%s200' % self.sep)
183 self._test_format("%+d", 4200, grouping=True, out='+4%s200' % self.sep)
184 self._test_format("%+d", -4200, grouping=True, out='-4%s200' % self.sep)
185
Antoine Pitrou350370c2009-03-14 00:13:13 +0000186 def test_integer_grouping_and_padding(self):
187 self._test_format("%10d", 4200, grouping=True,
188 out=('4%s200' % self.sep).rjust(10))
189 self._test_format("%-10d", -4200, grouping=True,
190 out=('-4%s200' % self.sep).ljust(10))
191
Antoine Pitrou83d6a872008-07-25 21:45:08 +0000192 def test_simple(self):
193 self._test_format("%f", 1024, grouping=0, out='1024.000000')
194 self._test_format("%f", 102, grouping=0, out='102.000000')
195 self._test_format("%f", -42, grouping=0, out='-42.000000')
196 self._test_format("%+f", -42, grouping=0, out='-42.000000')
197
198 def test_padding(self):
199 self._test_format("%20.f", -42, grouping=0, out='-42'.rjust(20))
200 self._test_format("%+10.f", -4200, grouping=0, out='-4200'.rjust(10))
201 self._test_format("%-10.f", 4200, grouping=0, out='4200'.ljust(10))
202
203 def test_complex_formatting(self):
204 # Spaces in formatting string
205 self._test_format_string("One million is %i", 1000000, grouping=1,
206 out='One million is 1%s000%s000' % (self.sep, self.sep))
207 self._test_format_string("One million is %i", 1000000, grouping=1,
208 out='One million is 1%s000%s000' % (self.sep, self.sep))
209 # Dots in formatting string
210 self._test_format_string(".%f.", 1000.0, out='.1000.000000.')
211 # Padding
Antoine Pitrou13856ea2008-07-26 21:02:53 +0000212 if self.sep:
213 self._test_format_string("--> %10.2f", 4200, grouping=1,
214 out='--> ' + ('4%s200.00' % self.sep).rjust(10))
Antoine Pitrou83d6a872008-07-25 21:45:08 +0000215 # Asterisk formats
216 self._test_format_string("%10.*f", (2, 1000), grouping=0,
217 out='1000.00'.rjust(10))
Antoine Pitrou13856ea2008-07-26 21:02:53 +0000218 if self.sep:
219 self._test_format_string("%*.*f", (10, 2, 1000), grouping=1,
220 out=('1%s000.00' % self.sep).rjust(10))
Antoine Pitrou83d6a872008-07-25 21:45:08 +0000221 # Test more-in-one
Antoine Pitrou13856ea2008-07-26 21:02:53 +0000222 if self.sep:
223 self._test_format_string("int %i float %.2f str %s",
224 (1000, 1000.0, 'str'), grouping=1,
225 out='int 1%s000 float 1%s000.00 str str' %
226 (self.sep, self.sep))
Antoine Pitrou83d6a872008-07-25 21:45:08 +0000227
228
R. David Murraye59482e2009-04-01 03:42:00 +0000229class TestFormatPatternArg(unittest.TestCase):
230 # Test handling of pattern argument of format
231
232 def test_onlyOnePattern(self):
233 # Issue 2522: accept exactly one % pattern, and no extra chars.
234 self.assertRaises(ValueError, locale.format, "%f\n", 'foo')
235 self.assertRaises(ValueError, locale.format, "%f\r", 'foo')
236 self.assertRaises(ValueError, locale.format, "%f\r\n", 'foo')
237 self.assertRaises(ValueError, locale.format, " %f", 'foo')
238 self.assertRaises(ValueError, locale.format, "%fg", 'foo')
239 self.assertRaises(ValueError, locale.format, "%^g", 'foo')
R. David Murrayad78d152010-04-27 02:45:53 +0000240 self.assertRaises(ValueError, locale.format, "%f%%", 'foo')
241
242
243class TestLocaleFormatString(unittest.TestCase):
244 """General tests on locale.format_string"""
245
246 def test_percent_escape(self):
247 self.assertEqual(locale.format_string('%f%%', 1.0), '%f%%' % 1.0)
248 self.assertEqual(locale.format_string('%d %f%%d', (1, 1.0)),
249 '%d %f%%d' % (1, 1.0))
250 self.assertEqual(locale.format_string('%(foo)s %%d', {'foo': 'bar'}),
251 ('%(foo)s %%d' % {'foo': 'bar'}))
252
253 def test_mapping(self):
254 self.assertEqual(locale.format_string('%(foo)s bing.', {'foo': 'bar'}),
255 ('%(foo)s bing.' % {'foo': 'bar'}))
256 self.assertEqual(locale.format_string('%(foo)s', {'foo': 'bar'}),
257 ('%(foo)s' % {'foo': 'bar'}))
258
R. David Murraye59482e2009-04-01 03:42:00 +0000259
260
Antoine Pitrou83d6a872008-07-25 21:45:08 +0000261class TestNumberFormatting(BaseLocalizedTest, EnUSNumberFormatting):
262 # Test number formatting with a real English locale.
263
264 locale_type = locale.LC_NUMERIC
265
266 def setUp(self):
267 BaseLocalizedTest.setUp(self)
268 EnUSNumberFormatting.setUp(self)
269
270
271class TestEnUSNumberFormatting(EnUSCookedTest, EnUSNumberFormatting):
272 # Test number formatting with a cooked "en_US" locale.
273
274 def setUp(self):
275 EnUSCookedTest.setUp(self)
276 EnUSNumberFormatting.setUp(self)
277
278 def test_currency(self):
279 self._test_currency(50000, "$50000.00")
280 self._test_currency(50000, "$50,000.00", grouping=True)
281 self._test_currency(50000, "USD 50,000.00",
282 grouping=True, international=True)
283
284
285class TestCNumberFormatting(CCookedTest, BaseFormattingTest):
286 # Test number formatting with a cooked "C" locale.
287
288 def test_grouping(self):
289 self._test_format("%.2f", 12345.67, grouping=True, out='12345.67')
290
291 def test_grouping_and_padding(self):
292 self._test_format("%9.2f", 12345.67, grouping=True, out=' 12345.67')
293
294
Antoine Pitrou350370c2009-03-14 00:13:13 +0000295class TestFrFRNumberFormatting(FrFRCookedTest, BaseFormattingTest):
296 # Test number formatting with a cooked "fr_FR" locale.
297
298 def test_decimal_point(self):
299 self._test_format("%.2f", 12345.67, out='12345,67')
300
301 def test_grouping(self):
302 self._test_format("%.2f", 345.67, grouping=True, out='345,67')
303 self._test_format("%.2f", 12345.67, grouping=True, out='12 345,67')
304
305 def test_grouping_and_padding(self):
306 self._test_format("%6.2f", 345.67, grouping=True, out='345,67')
307 self._test_format("%7.2f", 345.67, grouping=True, out=' 345,67')
308 self._test_format("%8.2f", 12345.67, grouping=True, out='12 345,67')
309 self._test_format("%9.2f", 12345.67, grouping=True, out='12 345,67')
310 self._test_format("%10.2f", 12345.67, grouping=True, out=' 12 345,67')
311 self._test_format("%-6.2f", 345.67, grouping=True, out='345,67')
312 self._test_format("%-7.2f", 345.67, grouping=True, out='345,67 ')
313 self._test_format("%-8.2f", 12345.67, grouping=True, out='12 345,67')
314 self._test_format("%-9.2f", 12345.67, grouping=True, out='12 345,67')
315 self._test_format("%-10.2f", 12345.67, grouping=True, out='12 345,67 ')
316
317 def test_integer_grouping(self):
318 self._test_format("%d", 200, grouping=True, out='200')
319 self._test_format("%d", 4200, grouping=True, out='4 200')
320
321 def test_integer_grouping_and_padding(self):
322 self._test_format("%4d", 4200, grouping=True, out='4 200')
323 self._test_format("%5d", 4200, grouping=True, out='4 200')
324 self._test_format("%10d", 4200, grouping=True, out='4 200'.rjust(10))
325 self._test_format("%-4d", 4200, grouping=True, out='4 200')
326 self._test_format("%-5d", 4200, grouping=True, out='4 200')
327 self._test_format("%-10d", 4200, grouping=True, out='4 200'.ljust(10))
328
329 def test_currency(self):
330 euro = '\u20ac'
331 self._test_currency(50000, "50000,00 " + euro)
332 self._test_currency(50000, "50 000,00 " + euro, grouping=True)
333 # XXX is the trailing space a bug?
334 self._test_currency(50000, "50 000,00 EUR ",
335 grouping=True, international=True)
336
337
Antoine Pitrou6a448d42009-10-19 19:43:09 +0000338class TestCollation(unittest.TestCase):
339 # Test string collation functions
340
341 def test_strcoll(self):
342 self.assertLess(locale.strcoll('a', 'b'), 0)
343 self.assertEqual(locale.strcoll('a', 'a'), 0)
344 self.assertGreater(locale.strcoll('b', 'a'), 0)
345
346 def test_strxfrm(self):
347 self.assertLess(locale.strxfrm('a'), locale.strxfrm('b'))
348
349
350class TestEnUSCollation(BaseLocalizedTest, TestCollation):
351 # Test string collation functions with a real English locale
352
353 locale_type = locale.LC_ALL
354
355 def setUp(self):
Antoine Pitrou6a448d42009-10-19 19:43:09 +0000356 enc = codecs.lookup(locale.getpreferredencoding(False) or 'ascii').name
357 if enc not in ('utf-8', 'iso8859-1', 'cp1252'):
358 raise unittest.SkipTest('encoding not suitable')
359 if enc != 'iso8859-1' and (sys.platform == 'darwin' or
360 sys.platform.startswith('freebsd')):
361 raise unittest.SkipTest('wcscoll/wcsxfrm have known bugs')
Hirokazu Yamamotob3b390d2010-09-23 15:20:15 +0000362 BaseLocalizedTest.setUp(self)
Antoine Pitrou6a448d42009-10-19 19:43:09 +0000363
364 def test_strcoll_with_diacritic(self):
365 self.assertLess(locale.strcoll('à', 'b'), 0)
366
367 def test_strxfrm_with_diacritic(self):
368 self.assertLess(locale.strxfrm('à'), locale.strxfrm('b'))
369
370
Antoine Pitrou83d6a872008-07-25 21:45:08 +0000371class TestMiscellaneous(unittest.TestCase):
372 def test_getpreferredencoding(self):
373 # Invoke getpreferredencoding to make sure it does not cause exceptions.
374 enc = locale.getpreferredencoding()
375 if enc:
376 # If encoding non-empty, make sure it is valid
377 codecs.lookup(enc)
378
Antoine Pitrou6a448d42009-10-19 19:43:09 +0000379 def test_strcoll_3303(self):
380 # test crasher from bug #3303
381 self.assertRaises(TypeError, locale.strcoll, "a", None)
382 self.assertRaises(TypeError, locale.strcoll, b"a", None)
Antoine Pitrou83d6a872008-07-25 21:45:08 +0000383
Amaury Forgeot d'Arc64f3ca42009-12-01 21:59:18 +0000384 def test_setlocale_category(self):
385 locale.setlocale(locale.LC_ALL)
386 locale.setlocale(locale.LC_TIME)
387 locale.setlocale(locale.LC_CTYPE)
388 locale.setlocale(locale.LC_COLLATE)
389 locale.setlocale(locale.LC_MONETARY)
390 locale.setlocale(locale.LC_NUMERIC)
391
392 # crasher from bug #7419
393 self.assertRaises(locale.Error, locale.setlocale, 12345)
394
Stefan Krahf187a022011-08-02 01:06:16 +0200395 @unittest.skipIf(linux_distribution()[0] == 'Fedora', "Fedora setlocale() "
396 "bug: https://bugzilla.redhat.com/show_bug.cgi?id=726536")
Antoine Pitrou0e3c5a82011-07-24 02:40:25 +0200397 def test_getsetlocale_issue1813(self):
398 # Issue #1813: setting and getting the locale under a Turkish locale
Antoine Pitroud05066d2011-07-26 23:55:33 +0200399 oldlocale = locale.setlocale(locale.LC_CTYPE)
Antoine Pitrou0e3c5a82011-07-24 02:40:25 +0200400 self.addCleanup(locale.setlocale, locale.LC_CTYPE, oldlocale)
401 try:
402 locale.setlocale(locale.LC_CTYPE, 'tr_TR')
403 except locale.Error:
404 # Unsupported locale on this system
405 self.skipTest('test needs Turkish locale')
Antoine Pitroud05066d2011-07-26 23:55:33 +0200406 loc = locale.getlocale(locale.LC_CTYPE)
Antoine Pitrou83d21932011-07-26 14:45:22 +0200407 if verbose:
408 print('got locale %a' % (loc,))
Antoine Pitrou0e3c5a82011-07-24 02:40:25 +0200409 locale.setlocale(locale.LC_CTYPE, loc)
Antoine Pitroud05066d2011-07-26 23:55:33 +0200410 self.assertEqual(loc, locale.getlocale(locale.LC_CTYPE))
Antoine Pitrou0e3c5a82011-07-24 02:40:25 +0200411
Antoine Pitrou83d6a872008-07-25 21:45:08 +0000412
413def test_main():
Antoine Pitrou13856ea2008-07-26 21:02:53 +0000414 tests = [
415 TestMiscellaneous,
R. David Murraye59482e2009-04-01 03:42:00 +0000416 TestFormatPatternArg,
R. David Murrayad78d152010-04-27 02:45:53 +0000417 TestLocaleFormatString,
Antoine Pitrou13856ea2008-07-26 21:02:53 +0000418 TestEnUSNumberFormatting,
Antoine Pitrou350370c2009-03-14 00:13:13 +0000419 TestCNumberFormatting,
420 TestFrFRNumberFormatting,
Antoine Pitrou6a448d42009-10-19 19:43:09 +0000421 TestCollation
Antoine Pitrou13856ea2008-07-26 21:02:53 +0000422 ]
Benjamin Petersone549ead2009-03-28 21:42:05 +0000423 # SkipTest can't be raised inside unittests, handle it manually instead
Antoine Pitrou13856ea2008-07-26 21:02:53 +0000424 try:
425 get_enUS_locale()
Benjamin Petersone549ead2009-03-28 21:42:05 +0000426 except unittest.SkipTest as e:
Antoine Pitrou13856ea2008-07-26 21:02:53 +0000427 if verbose:
428 print("Some tests will be disabled: %s" % e)
429 else:
Antoine Pitrou6a448d42009-10-19 19:43:09 +0000430 tests += [TestNumberFormatting, TestEnUSCollation]
Antoine Pitrou13856ea2008-07-26 21:02:53 +0000431 run_unittest(*tests)
Antoine Pitrou83d6a872008-07-25 21:45:08 +0000432
433if __name__ == '__main__':
434 test_main()