Exemple #1
0
def pytest_configure(config):
    key = "INTERNAL_OSINFO_DB_DATA_DIR"
    if key not in os.environ:
        os.environ[key] = os.path.realpath(
            os.path.join(os.path.dirname(__file__), "..", "data"))

    key = "INTERNAL_OSINFO_DB_DATA_SRC_DIR"
    if key not in os.environ:
        os.environ[key] = os.path.realpath(
            os.path.join(os.path.dirname(__file__), "..", "data"))

    # Needed for test reproducibility on any system not using a UTF-8 locale
    locale.setlocale(locale.LC_ALL, 'C')
    for loc in ["C.UTF-8", "C.utf8", "UTF-8", "en_US.UTF-8"]:
        try:
            locale.setlocale(locale.LC_CTYPE, loc)
            break
        except locale.Error:
            pass
    else:
        raise locale.Error("No UTF-8 locale found")

    # Default to --log-level=info if not otherwise specified
    if (hasattr(config.option, "log_level")
            and config.option.log_level is None):
        config.option.log_level = "info"

    # This will trigger some DATA_DIR validation
    from . import util
    dummy = util
Exemple #2
0
def path_join_robust(path, *paths):
    """
    Wrapper around `os.path.join` with handling for locale issues.

    Parameters
    ----------
    path : str
        The first path to join.
    paths : varargs
        Subsequent path strings to join.

    Returns
    -------
    joined_path : str
        The joined path string of the two path inputs.

    Raises
    ------
    locale.Error : A locale issue was detected that prevents path joining.
    """

    try:
        # gh-316: joining unicode and str can be saddening in Python 2.x
        path = str(path)
        paths = [str(another_path) for another_path in paths]

        return os.path.join(path, *paths)
    except UnicodeDecodeError as e:
        raise locale.Error("Unable to construct path. This is "
                           "likely a LOCALE issue:\n\n" + str(e))
def probe_locales(locales):
    for l in locales:
        try:
            locale.setlocale(locale.LC_ALL, l)
        except:
            pass
        else:
            return
    raise locale.Error('Could not find correct locale')
Exemple #4
0
def set_locale(lang):
    """Attempts to set locale."""

    if platform.system() in {"Linux", "Darwin"}:
        loc = "es_ES.utf8" if lang == "es" else "en_US.utf8"
    elif platform.system() == "Windows":
        loc = "es-ES" if lang == "es" else "en-US"
    else:
        raise locale.Error()

    locale.setlocale(locale.LC_ALL, loc)
 def SetLocaleForCountry(self, country):
     try:
         loc = LOCALES[country]
         locale.setlocale(locale.LC_ALL, loc)
     except locale.Error:
         raise locale.Error(
             "Need locale '%s' to use currency for country'%s'" %
             (loc, country))
     except KeyError:
         raise NotImplementedError(
             "Don't know what locale to use for country %s" % country)
def fake_set_locale(category, value=None, original_setlocale=locale.setlocale):
    """Fake version of locale.setlocale that only supports the default."""
    if value not in (None, '', 'C', 'POSIX'):
        raise locale.Error('locale emulation only supports "C" locale')
    return original_setlocale(category, 'C')
    def __init__(self,
                 element_id: str,
                 date_format: bytes,
                 time_zone: timezone = None,
                 text_locale: Union[str, tuple] = None,
                 start_year: int = None,
                 max_time_jump_seconds: int = 86400):
        """
        Create a DateTimeModelElement to parse dates using a custom, timezone and locale-aware implementation similar to strptime.
        @param date_format, is a byte string that represents the date format for parsing, see Python strptime specification for
        available formats. Supported format specifiers are:
            * %b: month name in current locale
            * %d: day in month, can be space or zero padded when followed by separator or at end of string.
            * %f: fraction of seconds (the digits after the the ".")
            * %H: hours from 00 to 23
            * %M: minutes
            * %m: two digit month number
            * %S: seconds
            * %s: seconds since the epoch (1970-01-01)
            * %Y: 4 digit year number
            * %z: detect and parse timezone strings like UTC, CET, +0001, etc. automatically.
        Common formats are:
            * "%b %d %H:%M:%S" e.g. for "Nov 19 05:08:43"
        @param time_zone the timezone for parsing the values or UTC when None.
        @param text_locale the locale to use for parsing the day, month names or None to use the default locale. The locale must be a tuple
        of (locale, encoding) or a string.
        @param start_year when parsing date records without any year information, assume this is the year of the first value parsed.
        @param max_time_jump_seconds for detection of year wraps with date formats missing year information, also the current time
        of values has to be tracked. This value defines the window within that the time may jump between two matches. When not
        within that window, the value is still parsed, corrected to the most likely value but does not change the detection year.
        """
        if not isinstance(element_id, str):
            msg = "element_id has to be of the type string."
            logging.getLogger(DEBUG_LOG_NAME).error(msg)
            raise TypeError(msg)
        if len(element_id) < 1:
            msg = "element_id must not be empty."
            logging.getLogger(DEBUG_LOG_NAME).error(msg)
            raise ValueError(msg)
        self.element_id = element_id
        self.time_zone = time_zone
        if time_zone is None:
            self.time_zone = timezone.utc
        self.text_locale = text_locale
        if text_locale is not None:
            if not isinstance(text_locale, str) and not isinstance(
                    text_locale, tuple):
                msg = "text_locale has to be of the type string or of the type tuple and have the length 2. (locale, encoding)"
                logging.getLogger(DEBUG_LOG_NAME).error(msg)
                raise TypeError(msg)
            if isinstance(text_locale, tuple) and len(text_locale) != 2:
                msg = "text_locale has to be of the type string or of the type tuple and have the length 2. (locale, encoding)"
                logging.getLogger(DEBUG_LOG_NAME).error(msg)
                raise ValueError(msg)
            try:
                old_locale = locale.getdefaultlocale()
                if old_locale != text_locale:
                    locale.setlocale(locale.LC_ALL, text_locale)
                    logging.getLogger(DEBUG_LOG_NAME).info(
                        "Changed time locale from %s to %s.", text_locale,
                        "".join(text_locale))
            except locale.Error:
                msg = "text_locale %s is not installed!" % text_locale
                logging.getLogger(DEBUG_LOG_NAME).error(msg)
                raise locale.Error(msg)
        # Make sure that dateFormat is valid and extract the relevant parts from it.
        self.format_has_year_flag = False
        self.format_has_tz_specifier = False
        self.tz_specifier_offset = 0
        self.tz_specifier_offset_str = None
        self.tz_specifier_format_length = -1
        self.date_format_parts: Union[List[Union[bytes, tuple]]] = []
        self.date_format = date_format
        if not isinstance(date_format, bytes):
            msg = "date_format has to be of the type bytes."
            logging.getLogger(DEBUG_LOG_NAME).error(msg)
            raise TypeError(msg)
        if len(date_format) <= 1:
            msg = "At least one date_format specifier must be defined."
            logging.getLogger(DEBUG_LOG_NAME).error(msg)
            raise ValueError(msg)
        self.scan_date_format(date_format)

        if start_year is not None and not isinstance(
                start_year, int) or isinstance(start_year, bool):
            msg = "start_year has to be of the type integer."
            logging.getLogger(DEBUG_LOG_NAME).error(msg)
            raise TypeError(msg)
        if (not self.format_has_year_flag) and (start_year is None):
            self.start_year = time.gmtime(None).tm_year
        elif start_year is None:  # this is needed so start_year is at any point an integer. (instead of being None)
            self.start_year = 0
        else:
            self.start_year = start_year

        if max_time_jump_seconds is not None and not isinstance(
                max_time_jump_seconds, int) or isinstance(
                    max_time_jump_seconds, bool):
            msg = "max_time_jump_seconds has to be of the type integer."
            logging.getLogger(DEBUG_LOG_NAME).error(msg)
            raise TypeError(msg)
        if max_time_jump_seconds <= 0:
            msg = "max_time_jump_seconds must not be lower than 1 second."
            logging.getLogger(DEBUG_LOG_NAME).error(msg)
            raise ValueError(msg)
        self.max_time_jump_seconds = max_time_jump_seconds
        self.last_parsed_seconds = 0
        self.epoch_start_time = datetime.fromtimestamp(0, self.time_zone)
Exemple #8
0
 def mock_setlocale(category: int, locale_name: str) -> str:
     raise locale.Error()
Exemple #9
0
SEARCH_FIELD_NAME = "ps_q"

DEFAULT_FROM_EMAIL = 'Pasporta Servo <*****@*****.**>'
SERVER_EMAIL = '*****@*****.**'

CSRF_COOKIE_AGE = None
CSRF_COOKIE_HTTPONLY = True

# Non-Django settings:

SYSTEM_LOCALE = f'{LANGUAGE_CODE}.{"UTF-8"}'
try:
    locale.setlocale(locale.LC_ALL, SYSTEM_LOCALE)
except locale.Error:
    raise locale.Error(
        f"Could not set locale {SYSTEM_LOCALE}: make sure that it is enabled on the system."
    )


def get_current_commit():
    import subprocess
    p = subprocess.run(
        ('git', 'show', '-s', '--no-color', '--format=%h %D'),
        capture_output=True,
        universal_newlines=True,
    )
    commit_hash, refnames = p.stdout.split(' ', maxsplit=1)
    branch = refnames.strip().replace('HEAD -> ', '').replace('HEAD, ',
                                                              '').split(',')[0]
    return (commit_hash, branch)
Exemple #10
0
 def test_get_encoding_error(self, mock_getpreferredencoding):
     mock_getpreferredencoding.side_effect = locale.Error()
     encoding = utils.get_encoding()
     self.assertEqual(encoding, "utf-8")
     mock_getpreferredencoding.assert_called_once()
Exemple #11
0
"""Test cases for formatting module."""
import locale
from unittest.mock import Mock
from unittest.mock import patch

from irpf_cei import formatting


@patch("locale.setlocale")
def test_set_locale_success(mock_locale_setlocale: Mock) -> None:
    """Return empty string."""
    assert formatting.set_locale() == ""


@patch("locale.setlocale", side_effect=locale.Error())
def test_set_locale_error(mock_locale_setlocale: Mock) -> None:
    """Return pt_BR locale."""
    assert formatting.set_locale() == "pt_BR.utf8"


@patch("locale.currency")
def test_get_currency_format(mock_locale_currency: Mock) -> None:
    """Give no error."""
    assert formatting.get_currency_format()