Added handling of system locale

This commit is contained in:
2026-11-21 11:50:47 +01:00
parent 12b471f641
commit 16d17ac6df
7 changed files with 798 additions and 29 deletions
+7 -11
View File
@@ -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.
+460
View File
@@ -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 <key>``; 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"
+29 -10
View File
@@ -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",