Files
ki18n/test/conftest.py

92 lines
2.6 KiB
Python

"""Shared pytest fixtures for the ki18n tests."""
from __future__ import annotations
import logging
import pytest
from ki18n.ki18n import Ki18n, _parse_system_locale
from support import LOGGER, Env
@pytest.fixture(autouse=True)
def _reset_singleton():
"""Make sure no test sees (or leaks) a ``Ki18n`` singleton."""
Ki18n._instance = None
yield
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.
``XDG_DATA_HOME`` and ``LOCALAPPDATA`` point into the temporary directory, so
real user data is never touched.
"""
base = tmp_path.resolve()
environment = Env(base)
monkeypatch.setenv("XDG_DATA_HOME", str(environment.data_home))
monkeypatch.setenv("LOCALAPPDATA", str(environment.data_home))
return environment
@pytest.fixture
def manager(env: Env) -> Ki18n:
"""Manager with the installed example languages ``en`` and ``de``."""
env.install_defaults()
return env.make()
@pytest.fixture
def installed(env: Env) -> Env:
"""Environment with the installed example languages ``en`` and ``de``.
Unlike ``manager`` this does not create the ``Ki18n`` instance yet, so a test
can still add (user) resources before constructing it with ``installed.make()``.
"""
env.install_defaults()
return env
@pytest.fixture
def log_warnings(caplog):
"""Return a function listing the library's WARNING messages so far."""
caplog.set_level(logging.WARNING, logger=LOGGER)
def messages() -> list[str]:
return [
record.getMessage()
for record in caplog.records
if record.name == LOGGER and record.levelno >= logging.WARNING
]
return messages