test__locale.py 7.72 KB
Newer Older
1 2 3 4 5 6
from _locale import (setlocale, LC_ALL, LC_CTYPE, LC_NUMERIC, localeconv, Error)
try:
    from _locale import (RADIXCHAR, THOUSEP, nl_langinfo)
except ImportError:
    nl_langinfo = None

7 8
import codecs
import locale
9
import sys
10
import unittest
11 12
from platform import uname

13 14
if uname().system == "Darwin":
    maj, min, mic = [int(part) for part in uname().release.split(".")]
15
    if (maj, min, mic) < (8, 0, 0):
Benjamin Peterson's avatar
Benjamin Peterson committed
16
        raise unittest.SkipTest("locale support broken for OS X < 10.4")
17 18

candidate_locales = ['es_UY', 'fr_FR', 'fi_FI', 'es_CO', 'pt_PT', 'it_IT',
19 20
    'et_EE', 'es_PY', 'no_NO', 'nl_NL', 'lv_LV', 'el_GR', 'be_BY', 'fr_BE',
    'ro_RO', 'ru_UA', 'ru_RU', 'es_VE', 'ca_ES', 'se_NO', 'es_EC', 'id_ID',
21
    'ka_GE', 'es_CL', 'wa_BE', 'hu_HU', 'lt_LT', 'sl_SI', 'hr_HR', 'es_AR',
22 23 24 25
    'es_ES', 'oc_FR', 'gl_ES', 'bg_BG', 'is_IS', 'mk_MK', 'de_AT', 'pt_BR',
    'da_DK', 'nn_NO', 'cs_CZ', 'de_LU', 'es_BO', 'sq_AL', 'sk_SK', 'fr_CH',
    'de_DE', 'sr_YU', 'br_FR', 'nl_BE', 'sv_FI', 'pl_PL', 'fr_CA', 'fo_FO',
    'bs_BA', 'fr_LU', 'kl_GL', 'fa_IR', 'de_BE', 'sv_SE', 'it_CH', 'uk_UA',
26
    'eu_ES', 'vi_VN', 'af_ZA', 'nb_NO', 'en_DK', 'tg_TJ', 'ps_AF', 'en_US',
27 28
    'fr_FR.ISO8859-1', 'fr_FR.UTF-8', 'fr_FR.ISO8859-15@euro',
    'ru_RU.KOI8-R', 'ko_KR.eucKR']
29

30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
def setUpModule():
    global candidate_locales
    # Issue #13441: Skip some locales (e.g. cs_CZ and hu_HU) on Solaris to
    # workaround a mbstowcs() bug. For example, on Solaris, the hu_HU locale uses
    # the locale encoding ISO-8859-2, the thousauds separator is b'\xA0' and it is
    # decoded as U+30000020 (an invalid character) by mbstowcs().
    if sys.platform == 'sunos5':
        old_locale = locale.setlocale(locale.LC_ALL)
        try:
            locales = []
            for loc in candidate_locales:
                try:
                    locale.setlocale(locale.LC_ALL, loc)
                except Error:
                    continue
                encoding = locale.getpreferredencoding(False)
                try:
                    localeconv()
                except Exception as err:
                    print("WARNING: Skip locale %s (encoding %s): [%s] %s"
                        % (loc, encoding, type(err), err))
                else:
                    locales.append(loc)
            candidate_locales = locales
        finally:
            locale.setlocale(locale.LC_ALL, old_locale)

    # Workaround for MSVC6(debug) crash bug
    if "MSC v.1200" in sys.version:
        def accept(loc):
            a = loc.split(".")
            return not(len(a) == 2 and len(a[-1]) >= 9)
        candidate_locales = [loc for loc in candidate_locales if accept(loc)]
63

64 65 66
# List known locale values to test against when available.
# Dict formatted as ``<locale> : (<decimal_point>, <thousands_sep>)``.  If a
# value is not known, use '' .
67 68 69
known_numerics = {
    'en_US': ('.', ','),
    'de_DE' : (',', '.'),
70 71 72
    # The French thousands separator may be a breaking or non-breaking space
    # depending on the platform, so do not test it
    'fr_FR' : (',', ''),
73 74
    'ps_AF': ('\u066b', '\u066c'),
}
75

76 77 78
class _LocaleTests(unittest.TestCase):

    def setUp(self):
79
        self.oldlocale = setlocale(LC_ALL)
80 81

    def tearDown(self):
82
        setlocale(LC_ALL, self.oldlocale)
83

84 85 86 87 88 89 90 91 92 93 94 95
    # Want to know what value was calculated, what it was compared against,
    # what function was used for the calculation, what type of data was used,
    # the locale that was supposedly set, and the actual locale that is set.
    lc_numeric_err_msg = "%s != %s (%s for %s; set to %s, using %s)"

    def numeric_tester(self, calc_type, calc_value, data_type, used_locale):
        """Compare calculation against known value, if available"""
        try:
            set_locale = setlocale(LC_NUMERIC)
        except Error:
            set_locale = "<not able to determine>"
        known_value = known_numerics.get(used_locale,
96
                                    ('', ''))[data_type == 'thousands_sep']
97
        if known_value and calc_value:
98
            self.assertEqual(calc_value, known_value,
99 100 101 102
                                self.lc_numeric_err_msg % (
                                    calc_value, known_value,
                                    calc_type, data_type, set_locale,
                                    used_locale))
103
            return True
104

105
    @unittest.skipUnless(nl_langinfo, "nl_langinfo is not available")
106 107
    def test_lc_numeric_nl_langinfo(self):
        # Test nl_langinfo against known values
108
        tested = False
109 110 111
        for loc in candidate_locales:
            try:
                setlocale(LC_NUMERIC, loc)
112
                setlocale(LC_CTYPE, loc)
113 114
            except Error:
                continue
115 116
            for li, lc in ((RADIXCHAR, "decimal_point"),
                            (THOUSEP, "thousands_sep")):
117 118 119 120
                if self.numeric_tester('nl_langinfo', nl_langinfo(li), lc, loc):
                    tested = True
        if not tested:
            self.skipTest('no suitable locales')
121 122 123

    def test_lc_numeric_localeconv(self):
        # Test localeconv against known values
124
        tested = False
125 126 127
        for loc in candidate_locales:
            try:
                setlocale(LC_NUMERIC, loc)
128
                setlocale(LC_CTYPE, loc)
129 130
            except Error:
                continue
131
            formatting = localeconv()
132 133
            for lc in ("decimal_point",
                        "thousands_sep"):
134 135 136 137
                if self.numeric_tester('localeconv', formatting[lc], lc, loc):
                    tested = True
        if not tested:
            self.skipTest('no suitable locales')
138

139
    @unittest.skipUnless(nl_langinfo, "nl_langinfo is not available")
140 141
    def test_lc_numeric_basic(self):
        # Test nl_langinfo against localeconv
142
        tested = False
143 144 145
        for loc in candidate_locales:
            try:
                setlocale(LC_NUMERIC, loc)
146
                setlocale(LC_CTYPE, loc)
147 148
            except Error:
                continue
149 150
            for li, lc in ((RADIXCHAR, "decimal_point"),
                            (THOUSEP, "thousands_sep")):
151 152
                nl_radixchar = nl_langinfo(li)
                li_radixchar = localeconv()[lc]
153 154 155 156
                try:
                    set_locale = setlocale(LC_NUMERIC)
                except Error:
                    set_locale = "<not able to determine>"
157
                self.assertEqual(nl_radixchar, li_radixchar,
158 159 160 161
                                "%s (nl_langinfo) != %s (localeconv) "
                                "(set to %s, using %s)" % (
                                                nl_radixchar, li_radixchar,
                                                loc, set_locale))
162 163 164
                tested = True
        if not tested:
            self.skipTest('no suitable locales')
165

Fredrik Lundh's avatar
Fredrik Lundh committed
166 167 168
    def test_float_parsing(self):
        # Bug #1391872: Test whether float parsing is okay on European
        # locales.
169
        tested = False
Fredrik Lundh's avatar
Fredrik Lundh committed
170 171 172
        for loc in candidate_locales:
            try:
                setlocale(LC_NUMERIC, loc)
173
                setlocale(LC_CTYPE, loc)
Fredrik Lundh's avatar
Fredrik Lundh committed
174 175
            except Error:
                continue
176 177 178 179 180

            # Ignore buggy locale databases. (Mac OS 10.4 and some other BSDs)
            if loc == 'eu_ES' and localeconv()['decimal_point'] == "' ":
                continue

181
            self.assertEqual(int(eval('3.14') * 100), 314,
182
                                "using eval('3.14') failed for %s" % loc)
183
            self.assertEqual(int(float('3.14') * 100), 314,
184
                                "using float('3.14') failed for %s" % loc)
185 186 187
            if localeconv()['decimal_point'] != '.':
                self.assertRaises(ValueError, float,
                                  localeconv()['decimal_point'].join(['1', '23']))
188 189 190
            tested = True
        if not tested:
            self.skipTest('no suitable locales')
Fredrik Lundh's avatar
Fredrik Lundh committed
191

192 193

if __name__ == '__main__':
194
    unittest.main()