summaryrefslogtreecommitdiffhomepage
path: root/tests/__init__.py
blob: 7ded9f18a1ca5d0e524cec793cd24a0426ced281 (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
"""Base classes and helpers for testing paramiko."""

import functools
import locale
import os

from pytest import skip


# List of locales which have non-ascii characters in all categories.
# Omits most European languages which for instance may have only some months
# with names that include accented characters.
_non_ascii_locales = [
    # East Asian locales
    "ja_JP", "ko_KR", "zh_CN", "zh_TW",
    # European locales with non-latin alphabets
    "el_GR", "ru_RU", "uk_UA",
]
# Also include UTF-8 versions of these locales
_non_ascii_locales.extend([name + ".utf8" for name in _non_ascii_locales])


def requireNonAsciiLocale(category_name="LC_ALL"):
    """Run decorated test under a non-ascii locale or skip if not possible."""
    if os.name != "posix":
        return skip("Non-posix OSes don't really use C locales")
    cat = getattr(locale, category_name)
    return functools.partial(_decorate_with_locale, cat, _non_ascii_locales)


def _decorate_with_locale(category, try_locales, test_method):
    """Decorate test_method to run after switching to a different locale."""

    def _test_under_locale(testself):
        original = locale.setlocale(category)
        while try_locales:
            try:
                locale.setlocale(category, try_locales[0])
            except locale.Error:
                # Mutating original list is ok, setlocale would keep failing
                try_locales.pop(0)
            else:
                try:
                    return test_method(testself)
                finally:
                    locale.setlocale(category, original)
        skipTest = getattr(testself, "skipTest", None)
        if skipTest is not None:
            skipTest("No usable locales installed")

    functools.update_wrapper(_test_under_locale, test_method)
    return _test_under_locale