summaryrefslogtreecommitdiff
path: root/numpy/core/tests/_locales.py
blob: 28eebb14d29f694bc54865e7f6c2c64527cf4c99 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
"""Provide class for testing in French locale

"""
from __future__ import division, absolute_import, print_function

import sys
import locale

from numpy.testing import SkipTest

__ALL__ = ['CommaDecimalPointLocale']


def find_comma_decimal_point_locale():
    """See if platform has a decimal point as comma locale.

    Find a locale that uses a comma instead of a period as the
    decimal point.

    Returns
    -------
    old_locale: str
        Locale when the function was called.
    new_locale: {str, None)
        First French locale found, None if none found.

    """
    if sys.platform == 'win32':
        locales = ['FRENCH']
    else:
        locales = ['fr_FR', 'fr_FR.UTF-8', 'fi_FI', 'fi_FI.UTF-8']

    old_locale = locale.getlocale(locale.LC_NUMERIC)
    new_locale = None
    try:
        for loc in locales:
            try:
                locale.setlocale(locale.LC_NUMERIC, loc)
                new_locale = loc
                break
            except locale.Error:
                pass
    finally:
        locale.setlocale(locale.LC_NUMERIC, locale=old_locale)
    return old_locale, new_locale


class CommaDecimalPointLocale(object):
    """Sets LC_NUMERIC to a locale with comma as decimal point.

    Classes derived from this class have setup and teardown methods that run
    tests with locale.LC_NUMERIC set to a locale where commas (',') are used as
    the decimal point instead of periods ('.'). On exit the locale is restored
    to the initial locale. It also serves as context manager with the same
    effect. If no such locale is available, it raises SkipTest in both cases.

    .. versionadded:: 1.15.0

    """
    (cur_locale, tst_locale) = find_comma_decimal_point_locale()

    def setup(self):
        if self.tst_locale is None:
            raise SkipTest("No French locale available")
        locale.setlocale(locale.LC_NUMERIC, locale=self.tst_locale)

    def teardown(self):
        locale.setlocale(locale.LC_NUMERIC, locale=self.cur_locale)

    def __enter__(self):
        if self.tst_locale is None:
            raise SkipTest("No French locale available")
        locale.setlocale(locale.LC_NUMERIC, locale=self.tst_locale)

    def __exit__(self, type, value, traceback):
        locale.setlocale(locale.LC_NUMERIC, locale=self.cur_locale)