authentik.root.tests.test_locales

Backend translation catalog tests

  1"""Backend translation catalog tests"""
  2
  3from gettext import GNUTranslations
  4from importlib.util import module_from_spec, spec_from_file_location
  5from pathlib import Path
  6from tempfile import TemporaryDirectory
  7from types import ModuleType
  8from unittest import skipUnless
  9from unittest.mock import patch
 10
 11from django.test import SimpleTestCase
 12from django.utils import translation
 13from django.utils.translation import to_locale
 14from yaml import safe_load
 15
 16REPO_ROOT = Path(__file__).resolve().parents[3]
 17
 18
 19def registry() -> list[dict]:
 20    return safe_load((REPO_ROOT / "locales.yaml").read_text())["locales"]
 21
 22
 23@skipUnless((REPO_ROOT / "locales.yaml").exists(), "Requires the repository checkout")
 24class TestLocales(SimpleTestCase):
 25    """Every catalog in locales.yaml must be where Django looks for it"""
 26
 27    def test_django_directory_names(self):
 28        """The registry's directory name is the one Django derives from the tag"""
 29        for row in registry():
 30            if row["django"]:
 31                self.assertEqual(row["django"], to_locale(row["tag"]), row["tag"])
 32
 33    def test_shipped_catalogs_load(self):
 34        """Activating a shipped tag serves translations from its catalog"""
 35        for row in registry():
 36            if not row["ship"] or row["django"] in (None, "en"):
 37                continue
 38            with self.subTest(row["tag"]):
 39                mo = REPO_ROOT / "locale" / row["django"] / "LC_MESSAGES" / "django.mo"
 40                with mo.open("rb") as file:
 41                    catalog = GNUTranslations(file)._catalog
 42                messages = {
 43                    msgid: msgstr
 44                    for msgid, msgstr in catalog.items()
 45                    # Plural and contextual entries are skipped. So are entries that match
 46                    # their msgid, which an English fallback would also satisfy.
 47                    if isinstance(msgid, str)
 48                    and msgid
 49                    and "\x04" not in msgid
 50                    and msgstr
 51                    and msgstr != msgid
 52                }
 53                self.assertTrue(messages)
 54                with translation.override(row["tag"]):
 55                    served = sum(
 56                        translation.gettext(msgid) == msgstr for msgid, msgstr in messages.items()
 57                    )
 58                # Django's own catalogs may override a few common strings.
 59                self.assertGreater(served / len(messages), 0.5)
 60
 61
 62def load_script() -> ModuleType:
 63    spec = spec_from_file_location("locales_script", REPO_ROOT / "scripts" / "locales.py")
 64    if not spec or not spec.loader:
 65        raise ImportError("scripts/locales.py")
 66    module = module_from_spec(spec)
 67    spec.loader.exec_module(module)
 68    return module
 69
 70
 71XLIFF = """<?xml version="1.0" ?><xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" version="1.2">
 72<file target-language="{language}" source-language="en" original="lit-localize-inputs">
 73<body>
 74<trans-unit id="s1">
 75  <source>Save</source>
 76  <target>{target}</target>
 77</trans-unit>
 78</body>
 79</file>
 80</xliff>
 81"""
 82
 83PO = """msgid ""
 84msgstr ""
 85"Content-Type: text/plain; charset=UTF-8\\n"
 86"Language: {language}\\n"
 87
 88msgid "Save"
 89msgstr "{target}"
 90"""
 91
 92
 93@skipUnless((REPO_ROOT / "scripts" / "locales.py").exists(), "Requires the repository checkout")
 94class TestLocalesScript(SimpleTestCase):
 95    """scripts/locales.py normalization, against a scratch tree"""
 96
 97    def setUp(self):
 98        self.script = load_script()
 99        self.tmp = TemporaryDirectory()
100        self.addCleanup(self.tmp.cleanup)
101        root = Path(self.tmp.name)
102        self.locale = root / "locale"
103        self.xliff = root / "web" / "xliff"
104        self.xliff.mkdir(parents=True)
105        self.locale.mkdir()
106        patcher = patch.multiple(
107            self.script, ROOT=root, LOCALE_DIR=self.locale, XLIFF_DIR=self.xliff
108        )
109        patcher.start()
110        self.addCleanup(patcher.stop)
111        self.registry = self.script.load_registry()
112
113    def write(self, path: Path, text: str) -> Path:
114        path.parent.mkdir(parents=True, exist_ok=True)
115        path.write_text(text)
116        return path
117
118    def test_canonical_xliff_language_is_normalized(self):
119        """A mapped Transifex export keeps its alias target-language; normalize fixes it"""
120        for tag, alias in (("ar", "ar-AA"), ("nb-NO", "no-NO")):
121            self.write(self.xliff / f"{tag}.xlf", XLIFF.format(language=alias, target="x"))
122        self.script.normalize_xliff_files(self.registry)
123        for tag in ("ar", "nb-NO"):
124            self.assertEqual(self.script.xliff_language(self.xliff / f"{tag}.xlf"), tag)
125
126    def test_merge_keeps_other_catalogs(self):
127        """Merging a Transifex directory moves files it doesn't merge"""
128        self.write(
129            self.locale / "fr_FR/LC_MESSAGES/django.po", PO.format(language="fr_FR", target="Old")
130        )
131        self.write(
132            self.locale / "fr-FR/LC_MESSAGES/django.po", PO.format(language="fr-FR", target="New")
133        )
134        self.write(
135            self.locale / "fr-FR/LC_MESSAGES/djangojs.po", PO.format(language="fr-FR", target="JS")
136        )
137        _, errors = self.script.normalize_locale_dirs(self.registry)
138        self.assertEqual(errors, [])
139        self.assertFalse((self.locale / "fr-FR").exists())
140        merged = (self.locale / "fr_FR/LC_MESSAGES/django.po").read_text()
141        self.assertIn('msgstr "New"', merged)
142        self.assertIn('"Language: fr_FR\\n"', merged)
143        self.assertTrue((self.locale / "fr_FR/LC_MESSAGES/djangojs.po").exists())
144        self.assertTrue((self.locale / "fr_FR/LC_MESSAGES/django.mo").exists())
145
146    def test_merge_conflict_deletes_nothing(self):
147        """A file that would overwrite different content stops the merge"""
148        self.write(
149            self.locale / "fr_FR/LC_MESSAGES/django.po", PO.format(language="fr_FR", target="Old")
150        )
151        self.write(self.locale / "fr_FR/NOTES", "canonical")
152        incoming = self.write(self.locale / "fr-FR/NOTES", "incoming")
153        _, errors = self.script.normalize_locale_dirs(self.registry)
154        self.assertEqual(len(errors), 1)
155        self.assertEqual(incoming.read_text(), "incoming")
REPO_ROOT = PosixPath('/home/runner/work/authentik/authentik')
def registry() -> list[dict]:
20def registry() -> list[dict]:
21    return safe_load((REPO_ROOT / "locales.yaml").read_text())["locales"]
@skipUnless((REPO_ROOT / 'locales.yaml').exists(), 'Requires the repository checkout')
class TestLocales(django.test.testcases.SimpleTestCase):
24@skipUnless((REPO_ROOT / "locales.yaml").exists(), "Requires the repository checkout")
25class TestLocales(SimpleTestCase):
26    """Every catalog in locales.yaml must be where Django looks for it"""
27
28    def test_django_directory_names(self):
29        """The registry's directory name is the one Django derives from the tag"""
30        for row in registry():
31            if row["django"]:
32                self.assertEqual(row["django"], to_locale(row["tag"]), row["tag"])
33
34    def test_shipped_catalogs_load(self):
35        """Activating a shipped tag serves translations from its catalog"""
36        for row in registry():
37            if not row["ship"] or row["django"] in (None, "en"):
38                continue
39            with self.subTest(row["tag"]):
40                mo = REPO_ROOT / "locale" / row["django"] / "LC_MESSAGES" / "django.mo"
41                with mo.open("rb") as file:
42                    catalog = GNUTranslations(file)._catalog
43                messages = {
44                    msgid: msgstr
45                    for msgid, msgstr in catalog.items()
46                    # Plural and contextual entries are skipped. So are entries that match
47                    # their msgid, which an English fallback would also satisfy.
48                    if isinstance(msgid, str)
49                    and msgid
50                    and "\x04" not in msgid
51                    and msgstr
52                    and msgstr != msgid
53                }
54                self.assertTrue(messages)
55                with translation.override(row["tag"]):
56                    served = sum(
57                        translation.gettext(msgid) == msgstr for msgid, msgstr in messages.items()
58                    )
59                # Django's own catalogs may override a few common strings.
60                self.assertGreater(served / len(messages), 0.5)

Every catalog in locales.yaml must be where Django looks for it

def test_django_directory_names(self):
28    def test_django_directory_names(self):
29        """The registry's directory name is the one Django derives from the tag"""
30        for row in registry():
31            if row["django"]:
32                self.assertEqual(row["django"], to_locale(row["tag"]), row["tag"])

The registry's directory name is the one Django derives from the tag

def test_shipped_catalogs_load(self):
34    def test_shipped_catalogs_load(self):
35        """Activating a shipped tag serves translations from its catalog"""
36        for row in registry():
37            if not row["ship"] or row["django"] in (None, "en"):
38                continue
39            with self.subTest(row["tag"]):
40                mo = REPO_ROOT / "locale" / row["django"] / "LC_MESSAGES" / "django.mo"
41                with mo.open("rb") as file:
42                    catalog = GNUTranslations(file)._catalog
43                messages = {
44                    msgid: msgstr
45                    for msgid, msgstr in catalog.items()
46                    # Plural and contextual entries are skipped. So are entries that match
47                    # their msgid, which an English fallback would also satisfy.
48                    if isinstance(msgid, str)
49                    and msgid
50                    and "\x04" not in msgid
51                    and msgstr
52                    and msgstr != msgid
53                }
54                self.assertTrue(messages)
55                with translation.override(row["tag"]):
56                    served = sum(
57                        translation.gettext(msgid) == msgstr for msgid, msgstr in messages.items()
58                    )
59                # Django's own catalogs may override a few common strings.
60                self.assertGreater(served / len(messages), 0.5)

Activating a shipped tag serves translations from its catalog

def load_script() -> module:
63def load_script() -> ModuleType:
64    spec = spec_from_file_location("locales_script", REPO_ROOT / "scripts" / "locales.py")
65    if not spec or not spec.loader:
66        raise ImportError("scripts/locales.py")
67    module = module_from_spec(spec)
68    spec.loader.exec_module(module)
69    return module
XLIFF = '<?xml version="1.0" ?><xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" version="1.2">\n<file target-language="{language}" source-language="en" original="lit-localize-inputs">\n<body>\n<trans-unit id="s1">\n <source>Save</source>\n <target>{target}</target>\n</trans-unit>\n</body>\n</file>\n</xliff>\n'
PO = 'msgid ""\nmsgstr ""\n"Content-Type: text/plain; charset=UTF-8\\n"\n"Language: {language}\\n"\n\nmsgid "Save"\nmsgstr "{target}"\n'
@skipUnless((REPO_ROOT / 'scripts' / 'locales.py').exists(), 'Requires the repository checkout')
class TestLocalesScript(django.test.testcases.SimpleTestCase):
 94@skipUnless((REPO_ROOT / "scripts" / "locales.py").exists(), "Requires the repository checkout")
 95class TestLocalesScript(SimpleTestCase):
 96    """scripts/locales.py normalization, against a scratch tree"""
 97
 98    def setUp(self):
 99        self.script = load_script()
100        self.tmp = TemporaryDirectory()
101        self.addCleanup(self.tmp.cleanup)
102        root = Path(self.tmp.name)
103        self.locale = root / "locale"
104        self.xliff = root / "web" / "xliff"
105        self.xliff.mkdir(parents=True)
106        self.locale.mkdir()
107        patcher = patch.multiple(
108            self.script, ROOT=root, LOCALE_DIR=self.locale, XLIFF_DIR=self.xliff
109        )
110        patcher.start()
111        self.addCleanup(patcher.stop)
112        self.registry = self.script.load_registry()
113
114    def write(self, path: Path, text: str) -> Path:
115        path.parent.mkdir(parents=True, exist_ok=True)
116        path.write_text(text)
117        return path
118
119    def test_canonical_xliff_language_is_normalized(self):
120        """A mapped Transifex export keeps its alias target-language; normalize fixes it"""
121        for tag, alias in (("ar", "ar-AA"), ("nb-NO", "no-NO")):
122            self.write(self.xliff / f"{tag}.xlf", XLIFF.format(language=alias, target="x"))
123        self.script.normalize_xliff_files(self.registry)
124        for tag in ("ar", "nb-NO"):
125            self.assertEqual(self.script.xliff_language(self.xliff / f"{tag}.xlf"), tag)
126
127    def test_merge_keeps_other_catalogs(self):
128        """Merging a Transifex directory moves files it doesn't merge"""
129        self.write(
130            self.locale / "fr_FR/LC_MESSAGES/django.po", PO.format(language="fr_FR", target="Old")
131        )
132        self.write(
133            self.locale / "fr-FR/LC_MESSAGES/django.po", PO.format(language="fr-FR", target="New")
134        )
135        self.write(
136            self.locale / "fr-FR/LC_MESSAGES/djangojs.po", PO.format(language="fr-FR", target="JS")
137        )
138        _, errors = self.script.normalize_locale_dirs(self.registry)
139        self.assertEqual(errors, [])
140        self.assertFalse((self.locale / "fr-FR").exists())
141        merged = (self.locale / "fr_FR/LC_MESSAGES/django.po").read_text()
142        self.assertIn('msgstr "New"', merged)
143        self.assertIn('"Language: fr_FR\\n"', merged)
144        self.assertTrue((self.locale / "fr_FR/LC_MESSAGES/djangojs.po").exists())
145        self.assertTrue((self.locale / "fr_FR/LC_MESSAGES/django.mo").exists())
146
147    def test_merge_conflict_deletes_nothing(self):
148        """A file that would overwrite different content stops the merge"""
149        self.write(
150            self.locale / "fr_FR/LC_MESSAGES/django.po", PO.format(language="fr_FR", target="Old")
151        )
152        self.write(self.locale / "fr_FR/NOTES", "canonical")
153        incoming = self.write(self.locale / "fr-FR/NOTES", "incoming")
154        _, errors = self.script.normalize_locale_dirs(self.registry)
155        self.assertEqual(len(errors), 1)
156        self.assertEqual(incoming.read_text(), "incoming")

scripts/locales.py normalization, against a scratch tree

def setUp(self):
 98    def setUp(self):
 99        self.script = load_script()
100        self.tmp = TemporaryDirectory()
101        self.addCleanup(self.tmp.cleanup)
102        root = Path(self.tmp.name)
103        self.locale = root / "locale"
104        self.xliff = root / "web" / "xliff"
105        self.xliff.mkdir(parents=True)
106        self.locale.mkdir()
107        patcher = patch.multiple(
108            self.script, ROOT=root, LOCALE_DIR=self.locale, XLIFF_DIR=self.xliff
109        )
110        patcher.start()
111        self.addCleanup(patcher.stop)
112        self.registry = self.script.load_registry()

Hook method for setting up the test fixture before exercising it.

def write(self, path: pathlib.Path, text: str) -> pathlib.Path:
114    def write(self, path: Path, text: str) -> Path:
115        path.parent.mkdir(parents=True, exist_ok=True)
116        path.write_text(text)
117        return path
def test_canonical_xliff_language_is_normalized(self):
119    def test_canonical_xliff_language_is_normalized(self):
120        """A mapped Transifex export keeps its alias target-language; normalize fixes it"""
121        for tag, alias in (("ar", "ar-AA"), ("nb-NO", "no-NO")):
122            self.write(self.xliff / f"{tag}.xlf", XLIFF.format(language=alias, target="x"))
123        self.script.normalize_xliff_files(self.registry)
124        for tag in ("ar", "nb-NO"):
125            self.assertEqual(self.script.xliff_language(self.xliff / f"{tag}.xlf"), tag)

A mapped Transifex export keeps its alias target-language; normalize fixes it

def test_merge_keeps_other_catalogs(self):
127    def test_merge_keeps_other_catalogs(self):
128        """Merging a Transifex directory moves files it doesn't merge"""
129        self.write(
130            self.locale / "fr_FR/LC_MESSAGES/django.po", PO.format(language="fr_FR", target="Old")
131        )
132        self.write(
133            self.locale / "fr-FR/LC_MESSAGES/django.po", PO.format(language="fr-FR", target="New")
134        )
135        self.write(
136            self.locale / "fr-FR/LC_MESSAGES/djangojs.po", PO.format(language="fr-FR", target="JS")
137        )
138        _, errors = self.script.normalize_locale_dirs(self.registry)
139        self.assertEqual(errors, [])
140        self.assertFalse((self.locale / "fr-FR").exists())
141        merged = (self.locale / "fr_FR/LC_MESSAGES/django.po").read_text()
142        self.assertIn('msgstr "New"', merged)
143        self.assertIn('"Language: fr_FR\\n"', merged)
144        self.assertTrue((self.locale / "fr_FR/LC_MESSAGES/djangojs.po").exists())
145        self.assertTrue((self.locale / "fr_FR/LC_MESSAGES/django.mo").exists())

Merging a Transifex directory moves files it doesn't merge

def test_merge_conflict_deletes_nothing(self):
147    def test_merge_conflict_deletes_nothing(self):
148        """A file that would overwrite different content stops the merge"""
149        self.write(
150            self.locale / "fr_FR/LC_MESSAGES/django.po", PO.format(language="fr_FR", target="Old")
151        )
152        self.write(self.locale / "fr_FR/NOTES", "canonical")
153        incoming = self.write(self.locale / "fr-FR/NOTES", "incoming")
154        _, errors = self.script.normalize_locale_dirs(self.registry)
155        self.assertEqual(len(errors), 1)
156        self.assertEqual(incoming.read_text(), "incoming")

A file that would overwrite different content stops the merge