From 16d17ac6df6b84ebb5646a5720835999950fb1c2 Mon Sep 17 00:00:00 2001 From: ingo Date: Sat, 21 Nov 2026 11:50:47 +0100 Subject: [PATCH] Added handling of system locale --- README.md | 41 ++++ doc/API.md | 74 ++++++- src/ki18n/__init__.py | 14 +- src/ki18n/ki18n.py | 181 ++++++++++++++++ test/README.md | 18 +- test/test_locale.py | 460 ++++++++++++++++++++++++++++++++++++++++ test/test_public_api.py | 39 +++- 7 files changed, 798 insertions(+), 29 deletions(-) create mode 100644 test/test_locale.py diff --git a/README.md b/README.md index be5386a..1d95711 100644 --- a/README.md +++ b/README.md @@ -156,6 +156,47 @@ languages mapping. Unknown languages raise `ValueError`. A language change loads and validates its translation file before changing state. Selecting the active language is a no-op. +### Detect the system locale + +```python +from ki18n import Ki18n + +locale = Ki18n.get_locale() # no manager needed; also i18n.get_locale() +if locale is not None: + print(locale.id) # "de_DE" + print(locale.language, locale.region, locale.encoding) # de DE UTF-8 + try: + i18n.set_language(locale.id) # "de_DE" selects "de" if only "de" exists + except ValueError: + pass # language not available: keep the default +``` + +`get_locale()` describes the locale currently set in the operating system and +works on Linux, macOS (Darwin) and Windows. It returns a frozen `SystemLocale` +or `None` when no locale can be determined or the system uses the `C`/`POSIX` +locale. The result is not cached and does not change the active language. + +| Field | Meaning | +| --- | --- | +| `raw` | Value as reported by the system, e.g. `de_DE.UTF-8` (POSIX), `de_DE` (macOS), `de-DE` (Windows) | +| `id` | Normalized language ID (`de_DE`), accepted by `set_language()` | +| `language`, `script`, `region` | Parts of `id` (`de`, `None`, `DE`); `script` and `region` may be `None` | +| `encoding` | Character encoding from `raw` (`UTF-8`) or `None` | +| `source` | Where the value came from (see below) | + +Sources, in order: + +- **Linux and other POSIX systems**: the first non-empty of `LC_ALL`, + `LC_MESSAGES`, `LANG`. If it names a real locale, the `LANGUAGE` priority list + (colon separated, as used by `gettext`) takes precedence (`source` is + `LANGUAGE`). +- **macOS**: the same environment variables first (they are set by Terminal); + if they name no usable locale, e.g. in GUI applications, the system settings + `AppleLocale` and then `AppleLanguages` (read with `defaults read -g`). +- **Windows**: `GetUserDefaultLocaleName` (user locale), then + `GetUserDefaultUILanguage` (user interface language). Environment variables + are ignored. + ### Translate strings ```python diff --git a/doc/API.md b/doc/API.md index 65afe52..421d6e7 100644 --- a/doc/API.md +++ b/doc/API.md @@ -199,7 +199,7 @@ Keys missing from a new language fall back to English. ## 4. `ki18n.ki18n` module reference ```python -from ki18n import Ki18n, i18n, I18n # package-level exports +from ki18n import Ki18n, i18n, I18n, SystemLocale # package-level exports from ki18n.ki18n import ki18n, DEFAULT_LANGUAGE # submodule-only names ``` @@ -210,6 +210,7 @@ from ki18n.ki18n import ki18n, DEFAULT_LANGUAGE # submodule-only names | `DEFAULT_LANGUAGE` | `"en"`. Default value of the `default_language` parameter. | | `Ki18n` | The manager class. | | `i18n` | Lazy handle: every attribute access is forwarded to the `Ki18n` singleton, which is created with default arguments if it does not exist yet. Unknown attributes raise `AttributeError`. | +| `SystemLocale` | Frozen dataclass returned by `Ki18n.get_locale()`; see [`get_locale()`](#get_locale---systemlocale--none). | | `I18n`, `ki18n` | Compatibility aliases for `Ki18n`. Only `I18n` is exported by the package; `ki18n` would shadow the submodule `ki18n.ki18n`, so import it from the submodule. | ### `class Ki18n` @@ -283,6 +284,73 @@ no effect on the manager. {'en': 'English', 'de': 'Deutsch', 'fr': 'Français'} ``` +#### `get_locale() -> SystemLocale | None` + +A `staticmethod` that describes the operating system's **currently set locale**. +It works on Linux (and other POSIX systems), macOS (Darwin) and Windows, does +not need a constructed manager (`Ki18n.get_locale()`; `manager.get_locale()` and +`i18n.get_locale()` work as well), is not cached and does not change the active +language. + +Returns a [`SystemLocale`](#class-systemlocale), or `None` if no locale can be +determined or the system uses the `C`/`POSIX` locale. + +Where the value comes from: + +| Platform | Sources, in order | +| --- | --- | +| Linux and other POSIX | First non-empty of `LC_ALL`, `LC_MESSAGES`, `LANG`; if it names a real locale, the first usable entry of the `LANGUAGE` list takes precedence. | +| macOS | The same environment variables; if they name no usable locale (e.g. GUI applications), `defaults read -g AppleLocale`, then `defaults read -g AppleLanguages` (first usable entry). | +| Windows | `GetUserDefaultLocaleName` (user locale), then `GetUserDefaultUILanguage` (user interface language). Environment variables are ignored. | + +Rules for the environment variables: + +- The first non-empty variable of `LC_ALL`, `LC_MESSAGES`, `LANG` decides, even + if its value is unusable (then the result is `None`). +- `C`, `POSIX` and their variants (`C.UTF-8`, `POSIX.UTF-8`) mean "no locale". + In that case `LANGUAGE` is ignored, as in `gettext`. +- Empty and unusable `LANGUAGE` entries are skipped. +- Modifiers such as `@euro` and `@latin` do not influence `id`. + +```python +>>> locale = Ki18n.get_locale() +>>> locale +SystemLocale(raw='de_DE.UTF-8', id='de_DE', language='de', script=None, + region='DE', encoding='UTF-8', source='LANG') +>>> str(locale) +'de_DE' +``` + +Typical use: start in the user's language if it is available. + +```python +locale = Ki18n.get_locale() +if locale is not None: + try: + i18n.set_language(locale.id) # "de_DE" selects "de" if only "de" exists + except ValueError: + pass # not available: keep the default language +``` + +On macOS the `defaults` tool is started as a subprocess (5 second timeout) when +the environment gives no answer; if it fails, the result is `None`. + +#### `class SystemLocale` + +Frozen dataclass (hashable, comparable) returned by `get_locale()`. + +| Field | Type | Description | +| --- | --- | --- | +| `raw` | `str` | Value exactly as reported by the system (whitespace stripped), e.g. `"de_DE.UTF-8"`, `"de_DE"` (macOS), `"de-DE"` (Windows). | +| `id` | `str` | Normalized language ID (see [Language IDs](#language-ids)), e.g. `"de_DE"`, `"zh_Hans_CN"`. Accepted by `set_language()`. | +| `language` | `str` | Language part of `id`, e.g. `"de"`. | +| `script` | `str \| None` | Script part (four letters, title case), e.g. `"Hans"`. | +| `region` | `str \| None` | Region part (`"DE"` or three digits such as `"419"`). | +| `encoding` | `str \| None` | Encoding part of `raw` (`"UTF-8"`), `None` if the system reports none (always on macOS and Windows). | +| `source` | `str` | `"LC_ALL"`, `"LC_MESSAGES"`, `"LANG"`, `"LANGUAGE"`, `"AppleLocale"`, `"AppleLanguages"`, `"GetUserDefaultLocaleName"` or `"GetUserDefaultUILanguage"`. | + +`str(locale)` returns `id`. + #### `set_language(code: str) -> None` Activates a language and notifies the listeners. @@ -600,6 +668,10 @@ These points are based on reading the current source code. - **Fractional counts below 1.** `p()` accepts floats, but values between 0 and 1 (for example `0.5`) match no category and raise `ValueError` with the message `count must be nonnegative or None`. +- **System locale on POSIX is environment based.** `get_locale()` reads the + environment of the running process. Locale settings that are only stored in + files such as `/etc/locale.conf` and not exported to the process are not seen + on Linux. - **No automatic reload.** Resource files are read when a language is activated; selecting the already active language does nothing. - **Plain Markdown help.** `help.md` is returned verbatim; there is no merge with diff --git a/src/ki18n/__init__.py b/src/ki18n/__init__.py index 23bd16a..f195aaf 100644 --- a/src/ki18n/__init__.py +++ b/src/ki18n/__init__.py @@ -1,14 +1,14 @@ """ki18n: file-backed internationalization support for Python applications. - + The public names are re-exported here so that applications can write:: - + from ki18n import Ki18n, i18n - + The Textual dialogs live in :mod:`ki18n.help_screen` and :mod:`ki18n.language_select_screen`; they are not imported here, so importing this package does not require Textual. """ - -from .ki18n import I18n, Ki18n, i18n - -__all__ = ["I18n", "Ki18n", "i18n"] + +from .ki18n import I18n, Ki18n, SystemLocale, i18n + +__all__ = ["I18n", "Ki18n", "SystemLocale", "i18n"] diff --git a/src/ki18n/ki18n.py b/src/ki18n/ki18n.py index d1c92cf..f4f433b 100644 --- a/src/ki18n/ki18n.py +++ b/src/ki18n/ki18n.py @@ -26,9 +26,11 @@ from __future__ import annotations import json import logging import re +import subprocess import sys from collections.abc import Callable from copy import deepcopy +from dataclasses import dataclass from pathlib import Path from typing import Any @@ -70,6 +72,158 @@ def _language_fallbacks(code: str) -> tuple[str, ...]: return tuple("_".join(parts[:end]) for end in range(len(parts), 0, -1)) +# --------------------------------------------------------------------------- +# System locale detection +# --------------------------------------------------------------------------- + +#: Locale names that mean "no real locale" (POSIX default locale). +_C_LOCALE_NAMES = frozenset({"", "c", "posix"}) + +#: Size of the buffer for ``GetUserDefaultLocaleName`` (LOCALE_NAME_MAX_LENGTH). +_WINDOWS_LOCALE_NAME_LENGTH = 85 + + +@dataclass(frozen=True) +class SystemLocale: + """Description of the operating system's current locale. + + Returned by :meth:`Ki18n.get_locale`. + + * ``raw`` - the value exactly as reported by the system, for example + ``"de_DE.UTF-8"`` (POSIX), ``"de_DE"`` (macOS) or ``"de-DE"`` (Windows). + * ``id`` - the normalized language ID (``"de_DE"``); it can be passed to + :meth:`Ki18n.set_language`. + * ``language``, ``script``, ``region`` - the parts of ``id`` + (``"de"``, ``None``, ``"DE"``); ``script`` and ``region`` may be ``None``. + * ``encoding`` - the character encoding part of ``raw`` (``"UTF-8"``) or + ``None`` if the system does not report one. + * ``source`` - where the value was read from, for example ``"LC_ALL"``, + ``"LC_MESSAGES"``, ``"LANG"``, ``"LANGUAGE"``, ``"AppleLocale"``, + ``"AppleLanguages"``, ``"GetUserDefaultLocaleName"`` or + ``"GetUserDefaultUILanguage"``. + """ + + raw: str + id: str + language: str + script: str | None + region: str | None + encoding: str | None + source: str + + def __str__(self) -> str: + return self.id + + +def _is_c_locale(value: str) -> bool: + """True for the POSIX default locale (``C``, ``POSIX``, ``C.UTF-8``, empty).""" + base = value.strip().partition("@")[0].partition(".")[0] + return base.casefold() in _C_LOCALE_NAMES + + +def _parse_system_locale(raw: str, source: str) -> SystemLocale | None: + """Build a :class:`SystemLocale` from a locale name; ``None`` if unusable.""" + raw = raw.strip() + if _is_c_locale(raw): + return None + try: + identifier = _normalize_language_id(raw) + except ValueError: + return None + language, *rest = identifier.split("_") + script = next((p for p in rest if len(p) == 4 and p.isalpha()), None) + region = next( + (p for p in rest if (len(p) == 2 and p.isalpha()) or (len(p) == 3 and p.isdigit())), + None, + ) + encoding = raw.partition("@")[0].partition(".")[2] or None + return SystemLocale( + raw=raw, + id=identifier, + language=language, + script=script, + region=region, + encoding=encoding, + source=source, + ) + + +def _locale_from_environment() -> SystemLocale | None: + """Locale from the POSIX environment variables. + + ``LC_ALL`` overrides ``LC_MESSAGES``, which overrides ``LANG``; the first + non-empty one decides. If it names the ``C``/``POSIX`` locale there is no + usable locale. Otherwise the GNU ``LANGUAGE`` priority list (colon + separated) takes precedence, as in ``gettext``. + """ + environ = os.environ + for name in ("LC_ALL", "LC_MESSAGES", "LANG"): + value = environ.get(name, "").strip() + if value: + break + else: + return None + if _is_c_locale(value): + return None + for entry in environ.get("LANGUAGE", "").split(":"): + parsed = _parse_system_locale(entry, "LANGUAGE") + if parsed is not None: + return parsed + return _parse_system_locale(value, name) + + +def _read_macos_default(key: str) -> str | None: + """Read a global macOS preference with ``defaults read -g``.""" + try: + result = subprocess.run( + ["defaults", "read", "-g", key], + capture_output=True, + text=True, + timeout=5, + check=False, + ) + except (OSError, subprocess.SubprocessError): + return None + if result.returncode != 0: + return None + return result.stdout + + +def _locale_from_macos_defaults() -> SystemLocale | None: + """Locale from the macOS system settings (``AppleLocale``/``AppleLanguages``).""" + output = _read_macos_default("AppleLocale") + if output: + parsed = _parse_system_locale(output, "AppleLocale") + if parsed is not None: + return parsed + output = _read_macos_default("AppleLanguages") + if output: + # Output looks like: (\n "de-DE",\n "en-DE"\n) + for entry in re.findall(r'^\s*"?([^",()\s]+)"?\s*,?\s*$', output, re.MULTILINE): + parsed = _parse_system_locale(entry, "AppleLanguages") + if parsed is not None: + return parsed + return None + + +def _locale_from_windows() -> SystemLocale | None: + """Locale from the Windows API (user locale, then user interface language).""" + try: + import ctypes + import locale as locale_module + + kernel32 = ctypes.windll.kernel32 # type: ignore[attr-defined] + buffer = ctypes.create_unicode_buffer(_WINDOWS_LOCALE_NAME_LENGTH) + if kernel32.GetUserDefaultLocaleName(buffer, len(buffer)) > 0: + parsed = _parse_system_locale(buffer.value, "GetUserDefaultLocaleName") + if parsed is not None: + return parsed + name = locale_module.windows_locale.get(kernel32.GetUserDefaultUILanguage()) + except (AttributeError, OSError): + return None + return _parse_system_locale(name, "GetUserDefaultUILanguage") if name else None + + class Ki18n: """A process-wide internationalization manager. @@ -350,6 +504,33 @@ class Ki18n: """Return the language selected when this manager was initialized.""" return self.default_language + @staticmethod + def get_locale() -> SystemLocale | None: + """Describe the operating system's currently set locale. + + Works on Windows, macOS (Darwin) and Linux/other POSIX systems and does + not need a constructed manager: ``Ki18n.get_locale()``. + + * POSIX (Linux, macOS, ...): the environment variables ``LC_ALL``, + ``LC_MESSAGES`` and ``LANG`` (first non-empty one), refined by the + ``LANGUAGE`` priority list. + * macOS: if the environment names no usable locale (for example in GUI + applications), the system settings ``AppleLocale`` and then + ``AppleLanguages`` are read. + * Windows: the user locale (``GetUserDefaultLocaleName``), then the user + interface language (``GetUserDefaultUILanguage``). + + Returns ``None`` if no locale can be determined or the system uses the + ``C``/``POSIX`` locale. The result is not cached and does not change the + active language; use ``set_language(locale.id)`` for that. + """ + if sys.platform == "win32": + return _locale_from_windows() + found = _locale_from_environment() + if found is None and sys.platform == "darwin": + found = _locale_from_macos_defaults() + return found + def get_available_languages(self) -> dict[str, str]: """Return discovered languages ordered by display name.""" return dict( diff --git a/test/README.md b/test/README.md index 0548a23..d6c6205 100644 --- a/test/README.md +++ b/test/README.md @@ -26,7 +26,7 @@ Configuration lives in `pyproject.toml` (`[tool.pytest.ini_options]`): | `conftest.py` | Fixtures: `env`, `installed`, `manager`, `log_warnings`, singleton reset | | `support.py` | Example data (`EN`, `DE`, dialog keys) and the `Env` helper class | | `test_normalize.py` | Language ID normalization, fallback chains | -| `test_paths.py` | `ki18n.paths` (PyInstaller / source checkout, per-user data directories) | +| `test_paths.py` | `ki18n.paths`: frozen detection, `bundle_root()` independent of where ki18n lives | | `test_construction.py` | Constructor, singleton, `project_root`/`local_root`, data directories | | `test_discovery.py` | `get_available_languages()`, user and installed resources | | `test_loading.py` | Validation and merging of `strings.json`, regional layers | @@ -34,8 +34,9 @@ Configuration lives in `pyproject.toml` (`[tool.pytest.ini_options]`): | `test_translate.py` | `t()`: fallback order, formatting | | `test_plural.py` | `p()`: categories, `#count`/`{count}`, fallbacks | | `test_help.py` | `get_help()`: regions, user files, English fallback | +| `test_locale.py` | `Ki18n.get_locale()`: POSIX environment, macOS `defaults`, Windows API (all simulated on any host) | | `test_lazy_handle.py` | Module handle `i18n`, alias names | -| `test_public_api.py` | Public API as documented in the README | +| `test_public_api.py` | Public API as documented in the README (package-level exports) | | `test_shipped_resources.py` | Consistency of the shipped `i18n/` files | | `test_screens.py` | `HelpScreen` / `LanguageSelectScreen` driven with `Pilot`, plus a small integration app | @@ -49,12 +50,7 @@ Configuration lives in `pyproject.toml` (`[tool.pytest.ini_options]`): ## Known deviations between documentation and code -Cases that describe documented behavior the code does not currently fulfil are -marked `xfail(strict=True)`. They are reported as `xfailed` now and turn into -failures (`XPASS(strict)`) once the code is fixed - remove the marker then. - -- `test_public_api.py::test_package_exports_documented_names` - - `from ki18n import Ki18n, i18n, I18n`: `__init__.py` is empty. -- `test_translate.py::test_other_formatting_errors_return_unformatted_text` - - `_format()` only catches `KeyError`, `IndexError` and `ValueError`, so - `{name.attr}` / `{name[x]}` raise `AttributeError` / `TypeError`. +None at the moment. If a test is added for documented behavior that the code +does not fulfil yet, mark it `xfail(strict=True)`: it is reported as `xfailed` +until the code is fixed and then turns into a failure (`XPASS(strict)`), which +is the signal to remove the marker. diff --git a/test/test_locale.py b/test/test_locale.py new file mode 100644 index 0000000..afb1190 --- /dev/null +++ b/test/test_locale.py @@ -0,0 +1,460 @@ +"""Tests for ``Ki18n.get_locale`` (detection of the system locale). + +All platforms are simulated on any host: ``sys.platform`` is patched, the macOS +``defaults`` tool is replaced by a fake, and the Windows API by a fake +``ctypes.windll``. The POSIX environment variables are cleared for every test. +""" + +import ctypes +import dataclasses +import importlib +import subprocess +import sys +from types import SimpleNamespace + +import pytest + +from ki18n import Ki18n, SystemLocale, i18n + +ki18n_module = importlib.import_module("ki18n.ki18n") + +ENV_VARS = ("LC_ALL", "LC_MESSAGES", "LANG", "LANGUAGE") + + +def set_env(monkeypatch, **variables): + for name, value in variables.items(): + monkeypatch.setenv(name, value) + + +@pytest.fixture +def posix(monkeypatch): + """A Linux system whose locale environment variables are all unset.""" + for name in ENV_VARS: + monkeypatch.delenv(name, raising=False) + monkeypatch.setattr(sys, "platform", "linux") + return monkeypatch + + +# --------------------------------------------------------------------------- +# POSIX environment (Linux and other POSIX systems) +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("raw", "identifier", "language", "script", "region", "encoding"), + [ + ("de_DE.UTF-8", "de_DE", "de", None, "DE", "UTF-8"), + ("de_DE", "de_DE", "de", None, "DE", None), + ("en_US.utf8", "en_US", "en", None, "US", "utf8"), + ("de_DE@euro", "de_DE", "de", None, "DE", None), + ("sr_RS.UTF-8@latin", "sr_RS", "sr", None, "RS", "UTF-8"), + ("sr_Latn_RS", "sr_Latn_RS", "sr", "Latn", "RS", None), + ("es_419.UTF-8", "es_419", "es", None, "419", "UTF-8"), + ("de", "de", "de", None, None, None), + ("zh_CN.GB18030", "zh_CN", "zh", None, "CN", "GB18030"), + ("pt-BR", "pt_BR", "pt", None, "BR", None), + ("DE_de.UTF-8", "de_DE", "de", None, "DE", "UTF-8"), + ], +) +def test_locale_is_described_from_lang(posix, raw, identifier, language, script, region, encoding): + set_env(posix, LANG=raw) + locale = Ki18n.get_locale() + assert locale == SystemLocale( + raw=raw, id=identifier, language=language, script=script, + region=region, encoding=encoding, source="LANG", + ) + + +def test_surrounding_whitespace_is_ignored(posix): + set_env(posix, LANG=" de_DE.UTF-8 \n") + locale = Ki18n.get_locale() + assert locale.raw == "de_DE.UTF-8" + assert locale.id == "de_DE" + + +@pytest.mark.parametrize( + ("variables", "identifier", "source"), + [ + ({"LANG": "fr_FR.UTF-8"}, "fr_FR", "LANG"), + ({"LANG": "fr_FR.UTF-8", "LC_MESSAGES": "it_IT.UTF-8"}, "it_IT", "LC_MESSAGES"), + ( + {"LANG": "fr_FR.UTF-8", "LC_MESSAGES": "it_IT.UTF-8", "LC_ALL": "es_ES.UTF-8"}, + "es_ES", + "LC_ALL", + ), + ({"LC_ALL": "es_ES.UTF-8", "LANG": "fr_FR.UTF-8"}, "es_ES", "LC_ALL"), + ({"LC_MESSAGES": "it_IT.UTF-8"}, "it_IT", "LC_MESSAGES"), + ], +) +def test_variable_priority(posix, variables, identifier, source): + set_env(posix, **variables) + locale = Ki18n.get_locale() + assert (locale.id, locale.source) == (identifier, source) + + +@pytest.mark.parametrize("empty", ["", " "]) +def test_empty_variables_are_skipped(posix, empty): + set_env(posix, LC_ALL=empty, LC_MESSAGES=empty, LANG="fr_FR.UTF-8") + locale = Ki18n.get_locale() + assert (locale.id, locale.source) == ("fr_FR", "LANG") + + +def test_lc_all_with_c_locale_overrides_other_variables(posix): + set_env(posix, LC_ALL="C", LANG="de_DE.UTF-8") + assert Ki18n.get_locale() is None + + +# -- LANGUAGE priority list --------------------------------------------------- + + +def test_language_list_takes_precedence(posix): + set_env(posix, LANG="en_US.UTF-8", LANGUAGE="de:en") + locale = Ki18n.get_locale() + assert (locale.raw, locale.id, locale.source) == ("de", "de", "LANGUAGE") + assert locale.region is None + + +@pytest.mark.parametrize("language_list", ["::fr", "!!:fr", "C:fr", " :fr:de"]) +def test_unusable_language_entries_are_skipped(posix, language_list): + set_env(posix, LANG="en_US.UTF-8", LANGUAGE=language_list) + assert Ki18n.get_locale().id == "fr" + + +def test_unusable_language_list_falls_back_to_lang(posix): + set_env(posix, LANG="en_US.UTF-8", LANGUAGE="!!:::") + locale = Ki18n.get_locale() + assert (locale.id, locale.source) == ("en_US", "LANG") + + +def test_language_list_is_ignored_for_the_c_locale(posix): + set_env(posix, LANG="C", LANGUAGE="de") + assert Ki18n.get_locale() is None + + +def test_language_list_alone_is_not_enough(posix): + set_env(posix, LANGUAGE="de") + assert Ki18n.get_locale() is None + + +# -- no usable locale ------------------------------------------------------ + + +@pytest.mark.parametrize( + "value", + ["C", "c", "POSIX", "C.UTF-8", "C.utf8", "POSIX.UTF-8", "English_United States.1252", "!!", "de/DE"], +) +def test_unusable_lang_values_give_none(posix, value): + set_env(posix, LANG=value) + assert Ki18n.get_locale() is None + + +def test_nothing_set_gives_none(posix): + assert Ki18n.get_locale() is None + + +def test_first_non_empty_variable_decides_even_if_it_is_unusable(posix): + set_env(posix, LC_ALL="!!", LANG="de_DE.UTF-8") + assert Ki18n.get_locale() is None + + +# -- platform dispatch ------------------------------------------------------- + + +@pytest.mark.parametrize("platform", ["linux", "freebsd14", "sunos5", "cygwin"]) +def test_other_platforms_use_the_environment_only(posix, platform): + posix.setattr(sys, "platform", platform) + set_env(posix, LANG="de_DE.UTF-8") + + def forbidden(*args, **kwargs): + raise AssertionError("platform specific API must not be used") + + posix.setattr(ki18n_module, "_read_macos_default", forbidden) + posix.setattr(ki18n_module, "_locale_from_windows", forbidden) + assert Ki18n.get_locale().id == "de_DE" + + +def test_linux_without_locale_does_not_query_macos_defaults(posix): + def forbidden(key): + raise AssertionError("macOS defaults must not be read on Linux") + + posix.setattr(ki18n_module, "_read_macos_default", forbidden) + assert Ki18n.get_locale() is None + + +# --------------------------------------------------------------------------- +# macOS (Darwin) +# --------------------------------------------------------------------------- + + +class FakeDefaults: + """Stands in for ``defaults read -g ``; records the keys that were read.""" + + def __init__(self, **values): + self.values = values + self.reads = [] + + def __call__(self, key): + self.reads.append(key) + return self.values.get(key) + + +@pytest.fixture +def mac(monkeypatch): + """A macOS system without locale environment variables. + + Returns ``install(**values)``, which replaces ``defaults read -g`` by a fake. + """ + for name in ENV_VARS: + monkeypatch.delenv(name, raising=False) + monkeypatch.setattr(sys, "platform", "darwin") + + def install(**values) -> FakeDefaults: + defaults = FakeDefaults(**values) + monkeypatch.setattr(ki18n_module, "_read_macos_default", defaults) + return defaults + + return install + + +def test_macos_environment_wins_over_system_settings(mac, monkeypatch): + defaults = mac(AppleLocale="de_DE") + set_env(monkeypatch, LANG="fr_FR.UTF-8") + locale = Ki18n.get_locale() + assert (locale.id, locale.source) == ("fr_FR", "LANG") + assert defaults.reads == [] + + +def test_macos_reads_apple_locale_without_environment(mac): + mac(AppleLocale="de_DE\n") + locale = Ki18n.get_locale() + assert locale == SystemLocale( + raw="de_DE", id="de_DE", language="de", script=None, region="DE", + encoding=None, source="AppleLocale", + ) + + +@pytest.mark.parametrize("value", ["C", "C.UTF-8", "POSIX"]) +def test_macos_c_locale_in_environment_falls_back_to_system_settings(mac, monkeypatch, value): + mac(AppleLocale="de_DE") + set_env(monkeypatch, LANG=value) + assert Ki18n.get_locale().source == "AppleLocale" + + +def test_macos_apple_locale_modifiers_are_ignored(mac): + mac(AppleLocale="en_US@rg=dezzzz") + locale = Ki18n.get_locale() + assert locale.id == "en_US" + assert locale.raw == "en_US@rg=dezzzz" + + +def test_macos_falls_back_to_apple_languages(mac): + defaults = mac(AppleLanguages='(\n "en-DE",\n "de-DE"\n)\n') + locale = Ki18n.get_locale() + assert (locale.id, locale.raw, locale.source) == ("en_DE", "en-DE", "AppleLanguages") + assert defaults.reads == ["AppleLocale", "AppleLanguages"] + + +def test_macos_apple_languages_with_script_and_unquoted_entries(mac): + mac(AppleLanguages="(\n zh-Hans-CN,\n en\n)\n") + locale = Ki18n.get_locale() + assert (locale.id, locale.script, locale.region) == ("zh_Hans_CN", "Hans", "CN") + + +def test_macos_unusable_apple_locale_falls_back_to_apple_languages(mac): + mac(AppleLocale="C", AppleLanguages='(\n "fr-FR"\n)') + assert Ki18n.get_locale().id == "fr_FR" + + +def test_macos_skips_unusable_apple_languages_entries(mac): + mac(AppleLanguages='(\n "!!",\n "it-IT"\n)') + assert Ki18n.get_locale().id == "it_IT" + + +@pytest.mark.parametrize( + "values", + [{}, {"AppleLanguages": "(\n)\n"}, {"AppleLocale": "", "AppleLanguages": ""}], + ids=["nothing", "empty-list", "empty-strings"], +) +def test_macos_without_usable_settings_gives_none(mac, values): + mac(**values) + assert Ki18n.get_locale() is None + + +class TestReadMacosDefault: + """``_read_macos_default`` itself, with ``subprocess.run`` replaced.""" + + @staticmethod + def completed(stdout="", returncode=0): + return subprocess.CompletedProcess(["defaults"], returncode, stdout=stdout, stderr="") + + def test_returns_standard_output(self, monkeypatch): + calls = [] + + def fake_run(command, **kwargs): + calls.append((command, kwargs)) + return self.completed("de_DE\n") + + monkeypatch.setattr(ki18n_module.subprocess, "run", fake_run) + assert ki18n_module._read_macos_default("AppleLocale") == "de_DE\n" + command, kwargs = calls[0] + assert command == ["defaults", "read", "-g", "AppleLocale"] + assert kwargs["capture_output"] is True + assert kwargs["text"] is True + assert kwargs["timeout"] > 0 + + def test_failure_exit_code_gives_none(self, monkeypatch): + monkeypatch.setattr( + ki18n_module.subprocess, "run", lambda *a, **k: self.completed("", returncode=1) + ) + assert ki18n_module._read_macos_default("AppleLocale") is None + + @pytest.mark.parametrize( + "error", + [FileNotFoundError("defaults"), PermissionError(), subprocess.TimeoutExpired("defaults", 5)], + ids=["missing-tool", "permission", "timeout"], + ) + def test_errors_give_none(self, monkeypatch, error): + def fake_run(*args, **kwargs): + raise error + + monkeypatch.setattr(ki18n_module.subprocess, "run", fake_run) + assert ki18n_module._read_macos_default("AppleLocale") is None + + +# --------------------------------------------------------------------------- +# Windows +# --------------------------------------------------------------------------- + + +class FakeKernel32: + """Fake of the two ``kernel32`` functions used by the library.""" + + def __init__(self, locale_name="de-DE", ui_language=0x0407, fail=None): + self.locale_name = locale_name # None: the call fails (returns 0) + self.ui_language = ui_language + self.fail = fail + self.buffer_sizes = [] + + def GetUserDefaultLocaleName(self, buffer, size): # noqa: N802 (Windows API name) + if self.fail: + raise self.fail + self.buffer_sizes.append(size) + if self.locale_name is None: + return 0 + buffer.value = self.locale_name + return len(self.locale_name) + 1 + + def GetUserDefaultUILanguage(self): # noqa: N802 + return self.ui_language + + +@pytest.fixture +def windows(monkeypatch): + """A Windows system; the (ignored) POSIX variables are set on purpose. + + Returns ``install(kernel32)``, which replaces ``ctypes.windll.kernel32``. + """ + set_env(monkeypatch, LANG="en_US.UTF-8", LC_ALL="en_US.UTF-8") + monkeypatch.setattr(sys, "platform", "win32") + + def install(kernel32) -> FakeKernel32: + monkeypatch.setattr(ctypes, "windll", SimpleNamespace(kernel32=kernel32), raising=False) + return kernel32 + + return install + + +def test_windows_uses_the_user_locale_name(windows): + kernel32 = windows(FakeKernel32("de-DE")) + locale = Ki18n.get_locale() + assert locale == SystemLocale( + raw="de-DE", id="de_DE", language="de", script=None, region="DE", + encoding=None, source="GetUserDefaultLocaleName", + ) + assert kernel32.buffer_sizes == [85] + + +def test_windows_ignores_posix_environment_variables(windows): + windows(FakeKernel32("fr-FR")) + assert Ki18n.get_locale().id == "fr_FR" + + +def test_windows_locale_with_script(windows): + windows(FakeKernel32("zh-Hans-CN")) + locale = Ki18n.get_locale() + assert (locale.id, locale.script, locale.region) == ("zh_Hans_CN", "Hans", "CN") + + +@pytest.mark.parametrize("locale_name", [None, ""], ids=["call-fails", "empty-name"]) +def test_windows_falls_back_to_the_ui_language(windows, locale_name): + windows(FakeKernel32(locale_name, ui_language=0x0407)) + locale = Ki18n.get_locale() + assert (locale.id, locale.source) == ("de_DE", "GetUserDefaultUILanguage") + + +def test_windows_unknown_ui_language_gives_none(windows): + windows(FakeKernel32(None, ui_language=0xFFFF)) + assert Ki18n.get_locale() is None + + +def test_windows_without_windll_gives_none(windows, monkeypatch): + monkeypatch.delattr(ctypes, "windll", raising=False) + assert Ki18n.get_locale() is None + + +def test_windows_api_error_gives_none(windows): + windows(FakeKernel32(fail=OSError("boom"))) + assert Ki18n.get_locale() is None + + +# --------------------------------------------------------------------------- +# The result object and the method itself +# --------------------------------------------------------------------------- + + +def test_result_is_a_frozen_dataclass(posix): + set_env(posix, LANG="de_DE.UTF-8") + locale = Ki18n.get_locale() + assert isinstance(locale, SystemLocale) + assert dataclasses.is_dataclass(locale) + with pytest.raises(dataclasses.FrozenInstanceError): + locale.id = "xx" # type: ignore[misc] + assert hash(locale) == hash(Ki18n.get_locale()) + + +def test_str_is_the_normalized_id(posix): + set_env(posix, LANG="de_DE.UTF-8") + assert str(Ki18n.get_locale()) == "de_DE" + + +def test_does_not_need_a_constructed_manager(posix): + set_env(posix, LANG="de_DE.UTF-8") + assert Ki18n._instance is None + assert Ki18n.get_locale().id == "de_DE" + assert Ki18n._instance is None + + +def test_is_available_on_instances_and_the_handle(posix, manager): + set_env(posix, LANG="de_DE.UTF-8") + assert manager.get_locale() == Ki18n.get_locale() + assert i18n.get_locale() == Ki18n.get_locale() + + +def test_result_is_not_cached(posix): + set_env(posix, LANG="de_DE.UTF-8") + assert Ki18n.get_locale().id == "de_DE" + set_env(posix, LANG="fr_FR.UTF-8") + assert Ki18n.get_locale().id == "fr_FR" + + +def test_does_not_change_the_active_language(posix, manager): + set_env(posix, LANG="de_DE.UTF-8") + manager.get_locale() + assert manager.get_language() == "en" + + +def test_id_can_be_passed_to_set_language(posix, manager): + set_env(posix, LANG="de_DE.UTF-8") + manager.set_language(Ki18n.get_locale().id) + # "de_DE" is not installed, so the parent language "de" is activated. + assert manager.get_language() == "de" diff --git a/test/test_public_api.py b/test/test_public_api.py index a507de8..ddef297 100644 --- a/test/test_public_api.py +++ b/test/test_public_api.py @@ -10,20 +10,38 @@ import ki18n ki18n_module = importlib.import_module("ki18n.ki18n") -# The README shows ``from ki18n import Ki18n, i18n``. The package's -# ``__init__.py`` is currently empty, so these cases are expected to fail until -# the package re-exports the names (the demo scripts take the detour -# ``from ki18n.ki18n import ...``). Remove the xfail marker once it does. -# @pytest.mark.xfail(strict=True, raises=ImportError, -# reason="ki18n/__init__.py does not re-export the public names") @pytest.mark.parametrize( ("name", "target"), - [("Ki18n", "Ki18n"), ("i18n", "i18n"), ("I18n", "Ki18n")], + [ + ("Ki18n", "Ki18n"), + ("i18n", "i18n"), + ("I18n", "Ki18n"), + ("SystemLocale", "SystemLocale"), + ], ) def test_package_exports_documented_names(name, target): - namespace: dict = {} - exec(f"from ki18n import {name}", namespace) - assert namespace[name] is getattr(ki18n_module, target) + assert getattr(ki18n, name) is getattr(ki18n_module, target) + + +def test_readme_import_statement_works(): + from ki18n import Ki18n, i18n + + assert Ki18n is ki18n_module.Ki18n + assert i18n is ki18n_module.i18n + + +def test_all_lists_the_public_names(): + assert set(ki18n.__all__) == {"Ki18n", "i18n", "I18n", "SystemLocale"} + + +def test_package_attribute_ki18n_is_still_the_submodule(): + # Re-exporting names must not shadow ``ki18n.ki18n`` (the module). + assert ki18n.ki18n is ki18n_module + + +def test_importing_the_package_does_not_import_textual_dialogs(): + assert not hasattr(ki18n, "HelpScreen") + assert not hasattr(ki18n, "LanguageSelectScreen") def test_py_typed_marker_is_shipped(): @@ -36,6 +54,7 @@ def test_py_typed_marker_is_shipped(): "get_language", "get_default_language", "get_available_languages", + "get_locale", "set_language", "t", "p",