Debian Codegraph @

tests/test_i18n_status.py

raw
1 # BSD 2-Clause License
2 #
3 # Apprise - Push Notification Library.
4 # Copyright (c) 2026, Chris Caron <[email protected]>
5 #
6 # Redistribution and use in source and binary forms, with or without
7 # modification, are permitted provided that the following conditions are met:
8 #
9 # 1. Redistributions of source code must retain the above copyright notice,
10 # this list of conditions and the following disclaimer.
11 #
12 # 2. Redistributions in binary form must reproduce the above copyright notice,
13 # this list of conditions and the following disclaimer in the documentation
14 # and/or other materials provided with the distribution.
15 #
16 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17 # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
20 # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21 # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22 # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24 # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25 # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26 # POSSIBILITY OF SUCH DAMAGE.
27
28
29 # Disable logging for a cleaner testing output
30 import builtins
31 import importlib.util
32 import logging
33 import os
34 import sys
35
36 import pytest
37
38 logging.disable(logging.CRITICAL)
39
40 # Our translation report lives beside the packaging tooling rather than
41 # inside the apprise package, so it is loaded by path
42 SCRIPT = os.path.join(
43 os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
44 "packaging",
45 "i18n_status.py",
46 )
47
48 _spec = importlib.util.spec_from_file_location("i18n_status", SCRIPT)
49 i18n_status = importlib.util.module_from_spec(_spec)
50 _spec.loader.exec_module(i18n_status)
51
52
53 HEADER = """\
54 msgid ""
55 msgstr ""
56 "Project-Id-Version: apprise 1.0.0\\n"
57 "Language: {language}\\n"
58 "MIME-Version: 1.0\\n"
59 "Content-Type: text/plain; charset=utf-8\\n"
60 "Content-Transfer-Encoding: 8bit\\n"
61 """
62
63
64 def write_catalog(root, language, entries, header=True):
65 """Write a catalog for ``language`` under ``root`` and return its path."""
66 path = os.path.join(str(root), language, "LC_MESSAGES")
67 os.makedirs(path, exist_ok=True)
68 target = os.path.join(path, "apprise.po")
69 with open(target, "w", encoding="utf-8") as fp:
70 if header:
71 fp.write(HEADER.format(language=language))
72
73 fp.write("\n" + entries)
74
75 return target
76
77
78 def test_read_catalog(tmpdir):
79 """Every shape our catalogs can take is read back correctly."""
80
81 path = write_catalog(
82 tmpdir,
83 "xx",
84 """
85 #: apprise/url.py:1
86 msgid "Token"
87 msgstr "Jeton"
88
89 #: apprise/url.py:2
90 #, fuzzy
91 msgid "Password"
92 msgstr "Guessed"
93
94 #. A translator note
95 #: apprise/url.py:3
96 msgid "A very long string that a tool decided to wrap onto another line"
97 msgstr ""
98 "Une chaine tres longue "
99 "qu un outil a decide de couper"
100
101 msgid "Quoted \\"value\\" with a \\\\ and a \\ttab"
102 msgstr "Traduit"
103
104 msgid "A literal \\\\n stays as it was written"
105 msgstr "Traduit"
106
107 msgctxt "menu"
108 msgid "Open"
109 msgstr "Ouvrir"
110
111 msgid "One file"
112 msgid_plural "Many files"
113 msgstr[0] "Un fichier"
114 msgstr[1] "Des fichiers"
115
116 #~ msgid "Removed"
117 #~ msgstr "Retire"
118
119 msgid Lost its quoting
120 msgstr "Ignored"
121
122 """,
123 )
124
125 translations, fuzzy = i18n_status.read_catalog(path)
126
127 # A plain entry, and one a tool only guessed at
128 assert translations["Token"] == "Jeton"
129 assert fuzzy == {"Password"}
130
131 # A wrapped translation is joined back together
132 assert (
133 translations[
134 "A very long string that a tool decided to wrap onto another line"
135 ]
136 == "Une chaine tres longue qu un outil a decide de couper"
137 )
138
139 # Escapes are resolved on both sides
140 assert 'Quoted "value" with a \\ and a \ttab' in translations
141
142 # An escaped backslash is not re-read as the start of the next escape
143 assert translations["A literal \\n stays as it was written"] == "Traduit"
144
145 # A context or plural entry is left out rather than read wrongly
146 assert "Open" not in translations
147 assert "One file" not in translations
148
149 # So is anything the template no longer has
150 assert "Removed" not in translations
151
152 # A hand broken entry is stepped over rather than crashing the report
153 assert "Lost its quoting" not in translations
154
155
156 def test_reference_from_source():
157 """Our strings are read from the Apprise source, not from a file."""
158
159 msgids, origin = i18n_status.reference()
160 assert origin == "source"
161
162 # A label only the source knows about proves nothing on disk was used
163 assert "Verify SSL" in msgids
164 assert len(msgids) > 400
165
166
167 def test_reference_from_template(tmpdir, monkeypatch):
168 """The template is the fallback when Babel is unavailable."""
169
170 monkeypatch.setattr(i18n_status, "extract", lambda: None)
171 monkeypatch.setattr(
172 i18n_status, "POT_FILE", os.path.join(str(tmpdir), "apprise.pot")
173 )
174
175 # With no template either, there is nothing to measure against
176 assert i18n_status.reference() == ([], "")
177
178 with open(i18n_status.POT_FILE, "w", encoding="utf-8") as fp:
179 fp.write(HEADER.format(language="en"))
180 fp.write('\nmsgid "Token"\nmsgstr ""\n')
181
182 assert i18n_status.reference() == (["Token"], "template")
183
184
185 def test_reference_without_babel(monkeypatch):
186 """No Babel means no strings can be read out of the source."""
187
188 # Hide Babel the way an environment without it would
189 real_import = builtins.__import__
190
191 def deny(name, *args, **kwargs):
192 if name.startswith("babel"):
193 raise ImportError(name)
194
195 return real_import(name, *args, **kwargs)
196
197 monkeypatch.setattr(builtins, "__import__", deny)
198 assert i18n_status.extract() is None
199
200
201 def run(monkeypatch, capsys, *args):
202 """Run the report with ``args`` and return its (code, output)."""
203 monkeypatch.setattr(sys, "argv", ["i18n_status.py", *args])
204 code = i18n_status.main()
205 return (code, capsys.readouterr())
206
207
208 def test_status_complete(tmpdir, monkeypatch, capsys):
209 """A fully translated language is reported as complete."""
210
211 monkeypatch.setattr(i18n_status, "I18N_DIR", str(tmpdir))
212 monkeypatch.setattr(i18n_status, "extract", lambda: ["Token"])
213 write_catalog(tmpdir, "fr", 'msgid "Token"\nmsgstr "Jeton"\n')
214
215 code, out = run(monkeypatch, capsys)
216 assert code == 0
217 assert "fr" in out.out
218 assert "complete" in out.out
219 assert "Every language is fully translated" in out.out
220
221 # Nothing is left to do, so --strict is happy too
222 assert run(monkeypatch, capsys, "--strict")[0] == 0
223
224
225 def test_status_gaps(tmpdir, monkeypatch, capsys):
226 """Untranslated and fuzzy strings are each listed as a bullet."""
227
228 monkeypatch.setattr(i18n_status, "I18N_DIR", str(tmpdir))
229 monkeypatch.setattr(
230 i18n_status, "extract", lambda: ["Token", "Secret", "Password"]
231 )
232 write_catalog(
233 tmpdir,
234 "fr",
235 """
236 msgid "Token"
237 msgstr "Jeton"
238
239 msgid "Secret"
240 msgstr ""
241
242 #, fuzzy
243 msgid "Password"
244 msgstr "Guessed"
245 """,
246 )
247
248 code, out = run(monkeypatch, capsys)
249 assert code == 0
250 assert "needs help" in out.out
251 assert " - Secret" in out.out
252 assert " - Password (marked fuzzy; please confirm it)" in out.out
253 assert "tox -e i18n" in out.out
254
255 # The summary on its own leaves the bullets out
256 code, out = run(monkeypatch, capsys, "--quiet")
257 assert code == 0
258 assert "needs help" in out.out
259 assert " - Secret" not in out.out
260
261 # Anything left over is an error when we are asked to be strict
262 assert run(monkeypatch, capsys, "--strict", "-l", "fr")[0] == 1
263
264
265 def test_status_missing_everywhere(tmpdir, monkeypatch, capsys):
266 """A string no catalog has yet is still reported against the source."""
267
268 monkeypatch.setattr(i18n_status, "I18N_DIR", str(tmpdir))
269 monkeypatch.setattr(
270 i18n_status, "POT_FILE", os.path.join(str(tmpdir), "apprise.pot")
271 )
272
273 # Two languages agree with each other and both fall short of the source
274 for language in ("de", "fr"):
275 write_catalog(tmpdir, language, 'msgid "Token"\nmsgstr "Token"\n')
276
277 monkeypatch.setattr(
278 i18n_status, "extract", lambda: ["Token", "Brand New Label"]
279 )
280
281 code, out = run(monkeypatch, capsys, "--strict")
282 assert code == 1
283 assert "1/2" in out.out
284 assert out.out.count(" - Brand New Label") == 2
285
286 # Falling back to a template that is behind the source is announced
287 monkeypatch.setattr(i18n_status, "extract", lambda: None)
288 with open(i18n_status.POT_FILE, "w", encoding="utf-8") as fp:
289 fp.write(HEADER.format(language="en"))
290 fp.write('\nmsgid "Token"\nmsgstr ""\n')
291
292 code, out = run(monkeypatch, capsys)
293 assert code == 0
294 assert "Measured against apprise/i18n/apprise.pot" in out.out
295
296
297 def test_status_strict_needs_source(tmpdir, monkeypatch, capsys):
298 """Strict mode refuses to certify against a file that can be stale."""
299
300 monkeypatch.setattr(i18n_status, "I18N_DIR", str(tmpdir))
301 monkeypatch.setattr(i18n_status, "extract", lambda: None)
302 monkeypatch.setattr(
303 i18n_status, "POT_FILE", os.path.join(str(tmpdir), "apprise.pot")
304 )
305 write_catalog(tmpdir, "fr", 'msgid "Token"\nmsgstr "Jeton"\n')
306 with open(i18n_status.POT_FILE, "w", encoding="utf-8") as fp:
307 fp.write(HEADER.format(language="en"))
308 fp.write('\nmsgid "Token"\nmsgstr ""\n')
309
310 # The template says everything is translated, and it may well be behind
311 # the source, so strict mode will not sign off on it
312 code, out = run(monkeypatch, capsys, "--strict")
313 assert code == 1
314 assert "Babel is required" in out.err
315
316 # Without --strict the same run reports on the template instead
317 code, out = run(monkeypatch, capsys)
318 assert code == 0
319 assert "Measured against apprise/i18n/apprise.pot" in out.out
320
321
322 def test_status_unknown_language(tmpdir, monkeypatch, capsys):
323 """A name with no catalog behind it is refused."""
324
325 monkeypatch.setattr(i18n_status, "I18N_DIR", str(tmpdir))
326 write_catalog(tmpdir, "fr", 'msgid "Token"\nmsgstr "Jeton"\n')
327
328 # A directory without a catalog inside it is not a language
329 os.makedirs(os.path.join(str(tmpdir), "__pycache__"), exist_ok=True)
330
331 code, out = run(monkeypatch, capsys, "-l", "__pycache__")
332 assert code == 1
333 assert "No translation exists for: __pycache__" in out.err
334
335
336 def test_status_no_catalogs(tmpdir, monkeypatch, capsys):
337 """Nothing to report on is an error rather than a traceback."""
338
339 monkeypatch.setattr(i18n_status, "I18N_DIR", str(tmpdir))
340
341 code, out = run(monkeypatch, capsys)
342 assert code == 1
343 assert "No translations were found" in out.err
344
345
346 def test_status_no_strings(tmpdir, monkeypatch, capsys):
347 """A catalog holding nothing but a header tells us to rebuild."""
348
349 monkeypatch.setattr(i18n_status, "I18N_DIR", str(tmpdir))
350 monkeypatch.setattr(i18n_status, "extract", lambda: None)
351 monkeypatch.setattr(
352 i18n_status, "POT_FILE", os.path.join(str(tmpdir), "apprise.pot")
353 )
354 write_catalog(tmpdir, "fr", "")
355
356 code, out = run(monkeypatch, capsys)
357 assert code == 1
358 assert "No translatable strings were found" in out.err
359
360
361 def test_languages_found():
362 """Our own catalogs are discovered from the repository."""
363
364 # Apprise ships these; a missing one means a catalog was lost
365 found = i18n_status.languages()
366 assert "en" in found
367 assert "fr" in found
368
369 # Every entry we report on has a catalog behind it
370 for language in found:
371 assert os.path.isfile(
372 os.path.join(i18n_status.I18N_DIR, language, i18n_status.CATALOG)
373 )
374
375
376 def test_catalog_state():
377 """A catalog with nothing outstanding reports itself as complete."""
378
379 catalog = i18n_status.Catalog("fr")
380 assert catalog.complete
381
382 # Either list is enough to need a person
383 catalog.missing.append("Token")
384 assert not catalog.complete
385
386 catalog.missing.clear()
387 catalog.fuzzy.append("Token")
388 assert not catalog.complete
389
390
391 def test_real_catalogs_complete():
392 """Every language Apprise ships covers every string in the source."""
393
394 # Read from the source so a catalog can not vouch for another one
395 msgids = i18n_status.extract()
396 if msgids is None:
397 pytest.skip("Requires Babel to read our strings from the source")
398
399 assert msgids
400
401 for language in i18n_status.languages():
402 catalog = i18n_status.inspect(language, msgids)
403 assert catalog.complete, (
404 f"{language} is missing {catalog.missing + catalog.fuzzy};"
405 " run `tox -e i18n-status` for the full report"
406 )
407
408
409 def test_status_entry_point(monkeypatch, capsys):
410 """The report runs against our own catalogs without a failure."""
411
412 # Our own translations are complete, so this is a clean run
413 assert run(monkeypatch, capsys, "--quiet", "--strict")[0] == 0