USe the system locale if the parameter default_language is not set while instanciating Ki18n
This commit is contained in:
@@ -113,15 +113,26 @@ from pathlib import Path
|
||||
from ki18n import Ki18n
|
||||
|
||||
manager = Ki18n(
|
||||
default_language="en",
|
||||
project_root=Path(__file__).resolve().parent,
|
||||
)
|
||||
```
|
||||
|
||||
The default language is `en`. Each language's display name is read from the
|
||||
If `default_language` is omitted (or `None`), the language of the operating
|
||||
system locale (`Ki18n.get_locale().id`, see
|
||||
[Detect the system locale](#detect-the-system-locale)) is used, provided a
|
||||
`strings.json` for it exists. A regional locale falls back to its parent: `de_AT`
|
||||
selects `de` if there is no `de_AT`. If the locale cannot be determined or matches
|
||||
no available language, `DEFAULT_LANGUAGE` (`en`) is used. Pass
|
||||
`default_language="en"` (or any other language ID) to disable the detection and
|
||||
always start in that language.
|
||||
|
||||
Each language's display name is read from the
|
||||
`language` entry in its `strings.json`. The default language folder and its
|
||||
valid `strings.json` must exist under `<project_root>/i18n/` during
|
||||
construction. Language folders under the user data tree can add languages to
|
||||
construction when it is used, that is when `default_language` is passed or
|
||||
the system locale yields no available language. A language that was chosen
|
||||
from the system locale only has to provide a `strings.json` (installed or in the
|
||||
user folder). Language folders under the user data tree can add languages to
|
||||
the discovered mapping or override the display name for an installed language.
|
||||
|
||||
`Ki18n` is a process-wide singleton. Only the first successful construction
|
||||
@@ -140,7 +151,7 @@ The application installation resources are then read from
|
||||
|
||||
```python
|
||||
language = i18n.get_language()
|
||||
default = i18n.get_default_language()
|
||||
default = i18n.get_default_language() # explicit, system locale or DEFAULT_LANGUAGE
|
||||
languages = i18n.get_available_languages()
|
||||
|
||||
i18n.set_language("de")
|
||||
@@ -165,12 +176,12 @@ 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
|
||||
```
|
||||
|
||||
The manager uses this locale automatically when it is constructed without
|
||||
`default_language`, so there is normally no need to call `set_language(locale.id)`
|
||||
yourself at startup.
|
||||
|
||||
`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`
|
||||
|
||||
+39
-12
@@ -61,7 +61,8 @@ my-app/
|
||||
from ki18n import Ki18n, i18n
|
||||
|
||||
# Optional: configure the manager before the first translation is requested.
|
||||
Ki18n("en") # default language; project_root is bundle_root()
|
||||
Ki18n() # default language: system locale, else "en"; project_root is bundle_root()
|
||||
# Ki18n("en") # or always start in a fixed language
|
||||
|
||||
print(i18n.t("greeting", name="Ada")) # Hello, Ada!
|
||||
print(i18n.p("files.found", 3)) # 3 files found
|
||||
@@ -96,7 +97,7 @@ Resources are read from two locations:
|
||||
|
||||
| Location | Path | Purpose |
|
||||
| --- | --- | --- |
|
||||
| Installed | `<project_root>/i18n/` | Shipped with the application. Must contain the default language. |
|
||||
| Installed | `<project_root>/i18n/` | Shipped with the application. Must contain `DEFAULT_LANGUAGE` (or the explicitly passed default language). |
|
||||
| User | `<local_root>/i18n/` | Optional per-user customization and additional languages. |
|
||||
|
||||
User resources take precedence over installed ones. `strings.json` files are
|
||||
@@ -207,7 +208,7 @@ from ki18n.ki18n import ki18n, DEFAULT_LANGUAGE # submodule-only names
|
||||
|
||||
| Name | Description |
|
||||
| --- | --- |
|
||||
| `DEFAULT_LANGUAGE` | `"en"`. Default value of the `default_language` parameter. |
|
||||
| `DEFAULT_LANGUAGE` | `"en"`. Language used when `default_language` is omitted and the system locale yields no available language. |
|
||||
| `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). |
|
||||
@@ -217,17 +218,19 @@ from ki18n.ki18n import ki18n, DEFAULT_LANGUAGE # submodule-only names
|
||||
|
||||
```python
|
||||
Ki18n(
|
||||
default_language: str = "en",
|
||||
default_language: str | None = None,
|
||||
project_root: str | Path | None = None,
|
||||
local_root: str | Path | None = None,
|
||||
)
|
||||
```
|
||||
|
||||
Creates (or returns) the singleton manager and loads the default language.
|
||||
Creates (or returns) the singleton manager and loads the default language. If
|
||||
`default_language` is omitted, it is derived from the system locale; see
|
||||
[Default language](#default-language).
|
||||
|
||||
| Parameter | Description |
|
||||
| --- | --- |
|
||||
| `default_language` | Language that is active after construction. Also the language that is listed first and that must be shipped with the application. Normalized (`"de-at"` → `"de_AT"`). |
|
||||
| `default_language` | Language that is active after construction, and the one that is listed first. Normalized (`"de-at"` → `"de_AT"`). If omitted or `None`, the language of the system locale is used when a `strings.json` exists for it, otherwise `DEFAULT_LANGUAGE`; see [Default language](#default-language). An explicitly passed language must be shipped with the application. |
|
||||
| `project_root` | Application directory that contains the installed `i18n/` folder. `~` is expanded. If omitted, [`ki18n.paths.bundle_root()`](#7-ki18npaths-module-reference) is used: the application root, independent of where ki18n is located. |
|
||||
| `local_root` | The application's per-user directory; user resources are read from its `i18n/` subfolder. `~` is expanded. If omitted: `<user data dir>/<application name>` (see below). The application name is the name of `project_root`; in a frozen one-file build it is the name of the executable (without extension), because the extraction directory changes on every start. |
|
||||
|
||||
@@ -244,14 +247,14 @@ Default user data directory (used when `local_root` is omitted):
|
||||
| Exception | Condition |
|
||||
| --- | --- |
|
||||
| `ValueError` | `default_language` is not a valid language ID. |
|
||||
| `FileNotFoundError` | The installed `i18n/` directory, the default language folder or its `strings.json` does not exist. |
|
||||
| `FileNotFoundError` | The installed `i18n/` directory does not exist, or the default language is an explicitly passed language or `DEFAULT_LANGUAGE` (no matching system locale) and its installed folder or `strings.json` does not exist. |
|
||||
| `ValueError` | An installed `strings.json` is invalid, lacks `language`, or two installed folders normalize to the same ID. |
|
||||
|
||||
**Attributes** (read them, do not modify them)
|
||||
|
||||
| Attribute | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| `default_language` | `str` | Normalized default language. |
|
||||
| `default_language` | `str` | Normalized default language: the explicit one, the system locale's language or `DEFAULT_LANGUAGE`. |
|
||||
| `project_root` | `Path` | Resolved application directory. |
|
||||
| `i18n_root` | `Path` | `project_root / "i18n"`. |
|
||||
| `local_root` | `Path` | Per-user directory. |
|
||||
@@ -269,7 +272,9 @@ Returns the ID of the active language (always one of the keys of
|
||||
|
||||
#### `get_default_language() -> str`
|
||||
|
||||
Returns the normalized default language passed to the constructor.
|
||||
Returns the normalized default language chosen during construction: the language
|
||||
passed to the constructor, otherwise the system locale's language, otherwise
|
||||
`DEFAULT_LANGUAGE`.
|
||||
|
||||
#### `get_available_languages() -> dict[str, str]`
|
||||
|
||||
@@ -321,7 +326,8 @@ SystemLocale(raw='de_DE.UTF-8', id='de_DE', language='de', script=None,
|
||||
'de_DE'
|
||||
```
|
||||
|
||||
Typical use: start in the user's language if it is available.
|
||||
The constructor uses this locale automatically if no `default_language` is passed
|
||||
(see [Default language](#default-language)). It can also be applied later:
|
||||
|
||||
```python
|
||||
locale = Ki18n.get_locale()
|
||||
@@ -329,7 +335,7 @@ 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
|
||||
pass # not available: keep the current language
|
||||
```
|
||||
|
||||
On macOS the `defaults` tool is started as a subprocess (5 second timeout) when
|
||||
@@ -465,6 +471,27 @@ public API and may change.
|
||||
|
||||
## 5. Resolution rules
|
||||
|
||||
### Default language
|
||||
|
||||
Applies to the first construction of `Ki18n`:
|
||||
|
||||
1. If `default_language` is passed, it is used as given (normalized). Its installed
|
||||
folder and `strings.json` must exist, otherwise `FileNotFoundError` is raised.
|
||||
The system locale is not queried.
|
||||
2. Otherwise `Ki18n.get_locale()` is called. If it returns a locale, its `id` and
|
||||
then its progressively broader parents are looked up in the
|
||||
[available languages](#available-languages): `de_AT` tries `de_AT`, then `de`;
|
||||
`sr_Latn_RS` tries `sr_Latn_RS`, `sr_Latn`, `sr`. The first one found becomes
|
||||
the default language. User-only languages (a user folder with a `strings.json`
|
||||
that defines `language`) count as available.
|
||||
3. If `get_locale()` returns `None` (locale not determinable, or `C`/`POSIX`) or
|
||||
none of the IDs is available, `DEFAULT_LANGUAGE` is used. In this case its
|
||||
installed folder and `strings.json` must exist, otherwise `FileNotFoundError`
|
||||
is raised.
|
||||
|
||||
The chosen language is the active language, is returned by
|
||||
`get_default_language()` and is listed first by `get_available_languages()`.
|
||||
|
||||
### Available languages
|
||||
|
||||
1. All folders in the user and installed `i18n/` roots are scanned.
|
||||
@@ -639,7 +666,7 @@ Notes:
|
||||
| --- | --- | --- |
|
||||
| `ValueError` | constructor | Invalid default language ID. |
|
||||
| `ValueError` | constructor, `set_language` | Invalid or inconsistent **installed** resource files (bad JSON, bad value types, missing `language`, missing `one`/`many`, duplicate folders). |
|
||||
| `FileNotFoundError` | constructor | Missing installed `i18n/` folder, default language folder, or its `strings.json`. |
|
||||
| `FileNotFoundError` | constructor | Missing installed `i18n/` folder, or missing installed folder / `strings.json` of the explicit default language or of `DEFAULT_LANGUAGE`. |
|
||||
| `FileNotFoundError` | `set_language` | The language's files disappeared after start-up. |
|
||||
| `ValueError` | `set_language` | Unknown language or invalid ID. |
|
||||
| `ValueError` | `t` | Key refers to a plural object. |
|
||||
|
||||
+65
-11
@@ -16,6 +16,11 @@ as a whole by the user's file.
|
||||
The :class:`Ki18n` manager is a process-wide singleton: only its first
|
||||
construction uses the provided default language, project root and local root.
|
||||
|
||||
If no default language is passed, the language of the operating system's locale
|
||||
(:meth:`Ki18n.get_locale`) is used when a ``strings.json`` for it exists (a
|
||||
regional locale such as ``de_AT`` falls back to ``de``). Otherwise
|
||||
:data:`DEFAULT_LANGUAGE` is used.
|
||||
|
||||
``key_aliases`` maps former translation keys to current ones. It is applied to the **user's**
|
||||
``strings.json`` files only (with a logged warning), so files written for an older key scheme keep
|
||||
working. If a file contains both a former and the current key, the current key wins.
|
||||
@@ -243,7 +248,7 @@ class Ki18n:
|
||||
|
||||
def __new__(
|
||||
cls,
|
||||
default_language: str = DEFAULT_LANGUAGE,
|
||||
default_language: str | None = None,
|
||||
project_root: str | Path | None = None,
|
||||
local_root: str | Path | None = None,
|
||||
) -> Ki18n:
|
||||
@@ -253,12 +258,21 @@ class Ki18n:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
default_language: str = DEFAULT_LANGUAGE,
|
||||
default_language: str | None = None,
|
||||
project_root: str | Path | None = None,
|
||||
local_root: str | Path | None = None,
|
||||
) -> None:
|
||||
"""Create the manager (only the first construction has an effect).
|
||||
|
||||
``default_language`` is the language that is active after construction.
|
||||
If it is ``None`` (the default), the language of the system locale
|
||||
(``get_locale().id``) is used provided it matches a language that has a
|
||||
``strings.json`` (installed or user); a regional locale falls back to its
|
||||
parent language. If the locale cannot be determined or matches no
|
||||
available language, :data:`DEFAULT_LANGUAGE` is used, which must be
|
||||
shipped with the application. An explicitly passed language is always
|
||||
used as given and must be shipped with the application.
|
||||
|
||||
``project_root`` is the directory containing the installed ``i18n``
|
||||
folder; if omitted it is :func:`ki18n.paths.bundle_root`.
|
||||
``local_root`` is the application's per-user directory (for example ``~/.local/share/my-app``); user resources are read from its
|
||||
@@ -269,6 +283,7 @@ class Ki18n:
|
||||
if getattr(self, "_initialized", False):
|
||||
return
|
||||
|
||||
if default_language is not None:
|
||||
try:
|
||||
default_language = _normalize_language_id(default_language)
|
||||
except ValueError as exc:
|
||||
@@ -279,7 +294,6 @@ class Ki18n:
|
||||
else:
|
||||
root = Path(project_root).expanduser().resolve()
|
||||
|
||||
self.default_language = default_language
|
||||
self.project_root = root
|
||||
self.i18n_root = root / "i18n"
|
||||
self._app_name = self._default_app_name(root)
|
||||
@@ -289,12 +303,23 @@ class Ki18n:
|
||||
self.local_root = Path(local_root).expanduser().resolve()
|
||||
self._user_i18n_root = self.local_root / "i18n"
|
||||
self._listeners: list[Callable[[str], None]] = []
|
||||
self._current_language = default_language
|
||||
self._english_translations: dict[str, _TranslationValue] | None = None
|
||||
|
||||
# Discover user languages first, then installed languages, while still
|
||||
# requiring the default language to ship with the application.
|
||||
languages = self._discover_available_languages(default_language)
|
||||
# Discover user languages first, then installed languages.
|
||||
if default_language is None:
|
||||
# No explicit default: prefer the system locale if a matching
|
||||
# language exists, otherwise fall back to DEFAULT_LANGUAGE.
|
||||
languages = self._discover_available_languages()
|
||||
default_language = self._system_default_language(languages)
|
||||
if default_language is None:
|
||||
default_language = DEFAULT_LANGUAGE
|
||||
self._require_installed_language(default_language)
|
||||
else:
|
||||
# Explicit default: it must ship with the application.
|
||||
self._require_installed_language(default_language)
|
||||
languages = self._discover_available_languages()
|
||||
self.default_language = default_language
|
||||
self._current_language = default_language
|
||||
self.available_languages = languages
|
||||
|
||||
# Load before marking the singleton initialized. A failure leaves it
|
||||
@@ -359,13 +384,17 @@ class Ki18n:
|
||||
layers.append((language_dir / "strings.json", is_user))
|
||||
return layers
|
||||
|
||||
def _discover_available_languages(self, default_language: str) -> dict[str, str]:
|
||||
"""Read language names from user and installed resource folders."""
|
||||
def _require_installed_language(self, default_language: str) -> None:
|
||||
"""Ensure that the default language ships with the application.
|
||||
|
||||
Raises :class:`FileNotFoundError` if the installed ``i18n`` directory, the
|
||||
language folder (matched ignoring case) or its ``strings.json`` is missing.
|
||||
"""
|
||||
if not self.i18n_root.is_dir():
|
||||
raise FileNotFoundError(f"Internal i18n directory not found: {self.i18n_root}")
|
||||
|
||||
default_directory = self.i18n_root / default_language
|
||||
if not default_directory.is_dir() and self.i18n_root.is_dir():
|
||||
if not default_directory.is_dir():
|
||||
try:
|
||||
default_directory = next(
|
||||
entry for entry in self.i18n_root.iterdir()
|
||||
@@ -383,6 +412,27 @@ class Ki18n:
|
||||
f"Default language strings not found: {default_strings}"
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _system_default_language(languages: dict[str, str]) -> str | None:
|
||||
"""Pick the language of the system locale from ``languages``.
|
||||
|
||||
The locale ID (for example ``de_AT``) is tried first, then its progressively
|
||||
broader parents (``de``). Returns ``None`` if the locale cannot be
|
||||
determined or none of these IDs is an available language.
|
||||
"""
|
||||
locale = Ki18n.get_locale()
|
||||
if locale is None:
|
||||
return None
|
||||
return next(
|
||||
(candidate for candidate in _language_fallbacks(locale.id) if candidate in languages),
|
||||
None,
|
||||
)
|
||||
|
||||
def _discover_available_languages(self) -> dict[str, str]:
|
||||
"""Read language names from user and installed resource folders."""
|
||||
if not self.i18n_root.is_dir():
|
||||
raise FileNotFoundError(f"Internal i18n directory not found: {self.i18n_root}")
|
||||
|
||||
languages: dict[str, str] = {}
|
||||
unnamed_user_languages: set[str] = set()
|
||||
# User resources first: their language name (if any) wins; a user file without
|
||||
@@ -502,7 +552,11 @@ class Ki18n:
|
||||
return self._current_language
|
||||
|
||||
def get_default_language(self) -> str:
|
||||
"""Return the language selected when this manager was initialized."""
|
||||
"""Return the default language chosen when this manager was initialized.
|
||||
|
||||
This is the explicitly passed language, otherwise the system locale's
|
||||
language if available, otherwise :data:`DEFAULT_LANGUAGE`.
|
||||
"""
|
||||
return self.default_language
|
||||
|
||||
@staticmethod
|
||||
|
||||
@@ -5,6 +5,8 @@ The suite uses [pytest](https://docs.pytest.org/) with
|
||||
operated through Textual's `Pilot` (clicks and key presses in the headless test
|
||||
driver `App.run_test`).
|
||||
|
||||
`Ki18n.get_locale()` is replaced by a stub returning `None` for every test (autouse fixture in `conftest.py`), so the results do not depend on the machine's locale; `test_locale.py` restores the real implementation, other tests use the `system_locale` fixture.
|
||||
|
||||
Every test runs in temporary directories (installed and user resources;
|
||||
`XDG_DATA_HOME` and `LOCALAPPDATA` are redirected), so real user data is never
|
||||
read. The `Ki18n` singleton is reset before and after every test.
|
||||
@@ -33,6 +35,7 @@ Configuration lives in `pyproject.toml` (`[tool.pytest.ini_options]`):
|
||||
| `test_set_language.py` | `set_language()`, error cases, listeners |
|
||||
| `test_translate.py` | `t()`: fallback order, formatting |
|
||||
| `test_plural.py` | `p()`: categories, `#count`/`{count}`, fallbacks |
|
||||
| `test_default_language.py` | Default language from the system locale (regional fallback, `DEFAULT_LANGUAGE` fallback, explicit language unaffected) |
|
||||
| `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 |
|
||||
@@ -46,6 +49,7 @@ Configuration lives in `pyproject.toml` (`[tool.pytest.ini_options]`):
|
||||
`env.make()` / `env.remake()`, directories `app_dir`, `user_dir`, `data_home`.
|
||||
- `installed` - `env` with the example languages `en` and `de` installed, no manager yet.
|
||||
- `manager` - `installed` plus a constructed `Ki18n` instance.
|
||||
- `system_locale` - callable that makes `Ki18n.get_locale()` report a locale, e.g. `system_locale("de_AT")`, or `None`.
|
||||
- `log_warnings` - callable returning the library's WARNING messages so far.
|
||||
|
||||
## Known deviations between documentation and code
|
||||
|
||||
+27
-1
@@ -6,7 +6,7 @@ import logging
|
||||
|
||||
import pytest
|
||||
|
||||
from ki18n.ki18n import Ki18n
|
||||
from ki18n.ki18n import Ki18n, _parse_system_locale
|
||||
from support import LOGGER, Env
|
||||
|
||||
|
||||
@@ -18,6 +18,32 @@ def _reset_singleton():
|
||||
Ki18n._instance = None
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _no_system_locale(monkeypatch):
|
||||
"""Pretend that the system locale cannot be determined.
|
||||
|
||||
Without an explicit default language ``Ki18n`` uses the system locale, so the
|
||||
tests must not depend on the machine they run on. Tests that need a locale
|
||||
set one with the ``system_locale`` fixture.
|
||||
"""
|
||||
monkeypatch.setattr(Ki18n, "get_locale", staticmethod(lambda: None))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def system_locale(monkeypatch):
|
||||
"""Return a function that makes ``Ki18n.get_locale()`` report a given locale.
|
||||
|
||||
``system_locale("de_AT")`` builds a ``SystemLocale`` from the name;
|
||||
``system_locale(None)`` simulates an undeterminable locale.
|
||||
"""
|
||||
|
||||
def apply(name: str | None) -> None:
|
||||
locale = None if name is None else _parse_system_locale(name, "LANG")
|
||||
monkeypatch.setattr(Ki18n, "get_locale", staticmethod(lambda: locale))
|
||||
|
||||
return apply
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def env(tmp_path, monkeypatch) -> Env:
|
||||
"""Isolated application and user directories.
|
||||
|
||||
@@ -116,7 +116,7 @@ def test_non_english_default_language(env):
|
||||
assert manager.t("greeting") == "Hallo"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("code", ["!!", "", "de/DE", None])
|
||||
@pytest.mark.parametrize("code", ["!!", "", "de/DE", 42])
|
||||
def test_invalid_default_language_raises_value_error(env, code):
|
||||
env.install_defaults()
|
||||
with pytest.raises(ValueError, match="Invalid default language"):
|
||||
|
||||
@@ -0,0 +1,252 @@
|
||||
"""Tests for the default language that is derived from the system locale.
|
||||
|
||||
If ``Ki18n`` is constructed without a ``default_language``, the ID of
|
||||
``Ki18n.get_locale()`` is used when it matches an available language (regional
|
||||
locales fall back to their parents). Otherwise ``DEFAULT_LANGUAGE`` is used.
|
||||
|
||||
``conftest.py`` makes ``Ki18n.get_locale()`` return ``None`` for every test; the
|
||||
``system_locale`` fixture simulates a specific locale instead.
|
||||
"""
|
||||
|
||||
import importlib
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
from ki18n import Ki18n, i18n
|
||||
from support import DE, EN
|
||||
|
||||
ki18n_module = importlib.import_module("ki18n.ki18n")
|
||||
|
||||
|
||||
def construct(env, **kwargs) -> Ki18n:
|
||||
"""Construct the manager without passing ``default_language`` at all."""
|
||||
kwargs.setdefault("project_root", env.app_dir)
|
||||
kwargs.setdefault("local_root", env.user_dir)
|
||||
return Ki18n(**kwargs)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# The system locale decides
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_system_locale_language_is_used(installed, system_locale):
|
||||
system_locale("de_DE.UTF-8")
|
||||
manager = construct(installed)
|
||||
assert manager.get_default_language() == "de"
|
||||
assert manager.get_language() == "de"
|
||||
assert manager.t("greeting") == "Hallo"
|
||||
|
||||
|
||||
def test_system_locale_matching_the_fallback_language(installed, system_locale):
|
||||
system_locale("en_US.UTF-8")
|
||||
manager = construct(installed)
|
||||
assert manager.get_default_language() == "en"
|
||||
assert manager.get_language() == "en"
|
||||
|
||||
|
||||
def test_language_without_region_is_matched(installed, system_locale):
|
||||
system_locale("de")
|
||||
assert construct(installed).get_language() == "de"
|
||||
|
||||
|
||||
def test_explicit_none_behaves_like_an_omitted_argument(installed, system_locale):
|
||||
system_locale("de_DE")
|
||||
manager = installed.make(None)
|
||||
assert manager.get_default_language() == "de"
|
||||
assert manager.get_language() == "de"
|
||||
|
||||
|
||||
def test_regional_locale_prefers_the_exact_regional_language(installed, system_locale):
|
||||
installed.install("de_AT", {"language": "Deutsch (Österreich)", "greeting": "Servus"})
|
||||
system_locale("de_AT.UTF-8")
|
||||
manager = construct(installed)
|
||||
assert manager.get_default_language() == "de_AT"
|
||||
assert manager.get_language() == "de_AT"
|
||||
assert manager.t("greeting") == "Servus"
|
||||
|
||||
|
||||
def test_regional_locale_falls_back_to_the_parent_language(installed, system_locale):
|
||||
system_locale("de_CH.UTF-8")
|
||||
manager = construct(installed)
|
||||
assert manager.get_default_language() == "de"
|
||||
assert manager.get_language() == "de"
|
||||
|
||||
|
||||
def test_script_locale_falls_back_through_all_parents(env, system_locale):
|
||||
env.install("en", EN)
|
||||
env.install("sr", {"language": "Srpski", "greeting": "Zdravo"})
|
||||
system_locale("sr_Latn_RS")
|
||||
assert construct(env).get_language() == "sr"
|
||||
|
||||
|
||||
def test_matched_language_is_listed_first(installed, system_locale):
|
||||
system_locale("de_DE")
|
||||
languages = construct(installed).get_available_languages()
|
||||
assert list(languages) == ["de", "en"]
|
||||
|
||||
|
||||
def test_other_languages_keep_working_after_a_locale_default(installed, system_locale):
|
||||
system_locale("de_DE")
|
||||
manager = construct(installed)
|
||||
manager.set_language("en")
|
||||
assert manager.t("greeting") == "Hello"
|
||||
assert manager.get_default_language() == "de"
|
||||
|
||||
|
||||
def test_missing_keys_fall_back_to_english_for_a_locale_default(installed, system_locale):
|
||||
system_locale("de_DE")
|
||||
manager = construct(installed)
|
||||
assert "only.en" not in DE
|
||||
assert manager.t("only.en") == "Only in English"
|
||||
|
||||
|
||||
def test_user_only_language_can_be_selected_by_the_locale(installed, system_locale):
|
||||
installed.user("fr", {"language": "Français", "greeting": "Bonjour"})
|
||||
system_locale("fr_FR.UTF-8")
|
||||
manager = construct(installed)
|
||||
assert manager.get_default_language() == "fr"
|
||||
assert manager.t("greeting") == "Bonjour"
|
||||
|
||||
|
||||
def test_user_overlay_applies_to_the_locale_language(installed, system_locale):
|
||||
installed.user("de", {"greeting": "Moin"})
|
||||
system_locale("de_DE")
|
||||
manager = construct(installed)
|
||||
assert manager.get_language() == "de"
|
||||
assert manager.t("greeting") == "Moin"
|
||||
assert manager.t("farewell") == "Tschüss"
|
||||
|
||||
|
||||
def test_locale_language_does_not_need_the_fallback_language(env, system_locale):
|
||||
env.install("de", DE)
|
||||
system_locale("de_DE")
|
||||
manager = construct(env)
|
||||
assert manager.get_language() == "de"
|
||||
assert manager.t("greeting") == "Hallo"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Fallback to DEFAULT_LANGUAGE
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_undeterminable_locale_uses_default_language(installed, system_locale):
|
||||
system_locale(None)
|
||||
manager = construct(installed)
|
||||
assert manager.get_default_language() == ki18n_module.DEFAULT_LANGUAGE == "en"
|
||||
assert manager.get_language() == "en"
|
||||
|
||||
|
||||
def test_locale_without_matching_language_uses_default_language(installed, system_locale):
|
||||
system_locale("fr_FR.UTF-8")
|
||||
manager = construct(installed)
|
||||
assert manager.get_default_language() == "en"
|
||||
assert manager.get_language() == "en"
|
||||
assert manager.t("greeting") == "Hello"
|
||||
|
||||
|
||||
def test_fallback_is_the_value_of_default_language_constant(installed, system_locale, monkeypatch):
|
||||
monkeypatch.setattr(ki18n_module, "DEFAULT_LANGUAGE", "de")
|
||||
system_locale("fr_FR")
|
||||
manager = construct(installed)
|
||||
assert manager.get_default_language() == "de"
|
||||
assert manager.get_language() == "de"
|
||||
|
||||
|
||||
def test_invalid_user_file_does_not_make_its_language_available(
|
||||
installed, system_locale, log_warnings
|
||||
):
|
||||
installed.user("fr", "{ this is not json")
|
||||
system_locale("fr_FR")
|
||||
manager = construct(installed)
|
||||
assert manager.get_language() == "en"
|
||||
assert any("fr" in message for message in log_warnings())
|
||||
|
||||
|
||||
def test_fallback_language_must_be_installed(env, system_locale):
|
||||
env.install("de", DE)
|
||||
system_locale("fr_FR")
|
||||
with pytest.raises(FileNotFoundError, match="'en'"):
|
||||
construct(env)
|
||||
|
||||
|
||||
def test_fallback_language_without_strings_file_raises(env, system_locale):
|
||||
env.install("en", None, help_text="# Help")
|
||||
system_locale(None)
|
||||
with pytest.raises(FileNotFoundError):
|
||||
construct(env)
|
||||
|
||||
|
||||
def test_missing_i18n_directory_raises_without_explicit_language(env, system_locale):
|
||||
system_locale("de_DE")
|
||||
with pytest.raises(FileNotFoundError, match="i18n"):
|
||||
construct(env)
|
||||
|
||||
|
||||
def test_failed_construction_can_be_retried_with_a_locale(env, system_locale):
|
||||
(env.app_dir / "i18n").mkdir()
|
||||
system_locale("de_DE")
|
||||
with pytest.raises(FileNotFoundError):
|
||||
construct(env)
|
||||
env.install("de", DE)
|
||||
manager = construct(env)
|
||||
assert manager.get_language() == "de"
|
||||
assert Ki18n() is manager
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# An explicit default language is not affected
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_explicit_language_wins_over_the_system_locale(installed, system_locale):
|
||||
system_locale("de_DE")
|
||||
manager = installed.make("en")
|
||||
assert manager.get_default_language() == "en"
|
||||
assert manager.get_language() == "en"
|
||||
|
||||
|
||||
def test_explicit_language_is_not_replaced_when_the_locale_is_unavailable(installed, system_locale):
|
||||
system_locale("fr_FR")
|
||||
manager = installed.make("de")
|
||||
assert manager.get_language() == "de"
|
||||
|
||||
|
||||
def test_explicit_language_must_still_be_installed(env, system_locale):
|
||||
env.install("de", DE)
|
||||
system_locale("de_DE")
|
||||
with pytest.raises(FileNotFoundError, match="'en'"):
|
||||
env.make("en")
|
||||
|
||||
|
||||
def test_explicit_language_does_not_query_the_locale(installed, monkeypatch):
|
||||
def unexpected():
|
||||
raise AssertionError("get_locale must not be called")
|
||||
|
||||
monkeypatch.setattr(Ki18n, "get_locale", staticmethod(unexpected))
|
||||
assert installed.make("en").get_language() == "en"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Singleton and lazy handle
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_later_construction_does_not_re_evaluate_the_locale(installed, system_locale):
|
||||
system_locale("de_DE")
|
||||
first = construct(installed)
|
||||
system_locale("en_US")
|
||||
assert construct(installed) is first
|
||||
assert first.get_default_language() == "de"
|
||||
|
||||
|
||||
def test_lazy_handle_uses_the_system_locale_on_first_use(env, system_locale, monkeypatch):
|
||||
env.install_defaults()
|
||||
system_locale("de_DE")
|
||||
monkeypatch.setattr(sys, "argv", [str(env.app_dir / "main.py")])
|
||||
assert Ki18n._instance is None
|
||||
assert i18n.get_language() == "de"
|
||||
assert i18n.get_default_language() == "de"
|
||||
assert i18n.t("greeting") == "Hallo"
|
||||
@@ -20,6 +20,15 @@ ki18n_module = importlib.import_module("ki18n.ki18n")
|
||||
|
||||
ENV_VARS = ("LC_ALL", "LC_MESSAGES", "LANG", "LANGUAGE")
|
||||
|
||||
# conftest.py replaces ``Ki18n.get_locale`` for all tests; this module tests the
|
||||
# real implementation, so it is captured at import time and restored per test.
|
||||
_REAL_GET_LOCALE = Ki18n.__dict__["get_locale"]
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _real_system_locale(monkeypatch):
|
||||
monkeypatch.setattr(Ki18n, "get_locale", _REAL_GET_LOCALE)
|
||||
|
||||
|
||||
def set_env(monkeypatch, **variables):
|
||||
for name, value in variables.items():
|
||||
|
||||
Reference in New Issue
Block a user