Debian Codegraph @

tests/test_apprise_translations.py

raw symbols SCIP
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 import ctypes
29 from importlib import reload
30
31 # Disable logging for a cleaner testing output
32 import logging
33 import os
34 import sys
35 from unittest import mock
36
37 from helpers import environ
38 import pytest
39
40 from apprise import locale
41
42 logging.disable(logging.CRITICAL)
43
44
45 def test_apprise_trans():
46 """
47 API: Test apprise locale object
48 """
49 lazytrans = locale.LazyTranslation("Token")
50 assert str(lazytrans) == "Token"
51
52
53 @pytest.mark.skipif("gettext" not in sys.modules, reason="Requires gettext")
54 def test_apprise_trans_gettext_init():
55 """
56 API: Handle gettext
57 """
58 # Toggle
59 locale.GETTEXT_LOADED = False
60
61 # Objects can still be created
62 al = locale.AppriseLocale()
63
64 with al.lang_at("en") as _:
65 # functions still behave as normal
66 assert _ is None
67
68 # Restore the object
69 locale.GETTEXT_LOADED = True
70
71
72 @pytest.mark.skipif("gettext" not in sys.modules, reason="Requires gettext")
73 @mock.patch("gettext.translation")
74 @mock.patch("locale.getlocale")
75 def test_apprise_trans_gettext_translations(
76 mock_getlocale, mock_gettext_trans
77 ):
78 """
79 API: Apprise() Gettext translations
80
81 """
82
83 # Set- our gettext.locale() return value
84 mock_getlocale.return_value = ("en_US", "UTF-8")
85
86 mock_gettext_trans.side_effect = FileNotFoundError()
87
88 # This throws internally but we handle it gracefully
89 al = locale.AppriseLocale()
90
91 with al.lang_at("en"):
92 # functions still behave as normal
93 pass
94
95 # This throws internally but we handle it gracefully
96 locale.AppriseLocale(language="fr")
97
98
99 @pytest.mark.skipif(hasattr(ctypes, "windll"), reason="Unique Nux test cases")
100 @pytest.mark.skipif("gettext" not in sys.modules, reason="Requires gettext")
101 @mock.patch("locale.getlocale")
102 def test_apprise_trans_gettext_lang_at(mock_getlocale):
103 """
104 API: Apprise() Gettext lang_at
105
106 """
107
108 # Set- our gettext.locale() return value
109 mock_getlocale.return_value = ("en_CA", "UTF-8")
110
111 # This throws internally but we handle it gracefully
112 al = locale.AppriseLocale()
113
114 # Edge Cases
115 assert al.add("en", set_default=False) is True
116 assert al.add("en", set_default=True) is True
117
118 with al.lang_at("en"):
119 # functions still behave as normal
120 pass
121
122 # This throws internally but we handle it gracefully
123 locale.AppriseLocale(language="fr")
124
125 with al.lang_at("en") as _:
126 # functions still behave as normal
127 assert callable(_)
128
129 with al.lang_at("es") as _:
130 # functions still behave as normal
131 assert callable(_)
132
133 with al.lang_at("fr") as _:
134 # functions still behave as normal
135 assert callable(_)
136
137 # Test our initialization when our fallback is a language we do
138 # not have. This is only done to test edge cases when for whatever
139 # reason the person who set up apprise does not have the languages
140 # installed.
141 fallback = locale.AppriseLocale._default_language
142 mock_getlocale.return_value = None
143
144 with environ("LANGUAGE", "LC_ALL", "LC_CTYPE", "LANG"):
145 # Our default language
146 locale.AppriseLocale._default_language = "zz"
147
148 # We will detect the zz since there were no environment variables to
149 # help us otherwise
150 assert locale.AppriseLocale.detect_language() is None
151 al = locale.AppriseLocale()
152
153 # No Language could be set becuause no locale directory exists for this
154 assert al.lang is None
155
156 with al.lang_at(None) as _:
157 # functions still behave as normal
158 assert callable(_)
159
160 with al.lang_at("en") as _:
161 # functions still behave as normal
162 assert callable(_)
163
164 with al.lang_at("es") as _:
165 # functions still behave as normal
166 assert callable(_)
167
168 with al.lang_at("fr") as _:
169 # functions still behave as normal
170 assert callable(_)
171
172 # We can still perform simple lookups; they access a dummy wrapper:
173 assert al.gettext("test") == "test"
174
175 with environ("LANGUAGE", "LC_CTYPE", LC_ALL="C.UTF-8", LANG="en_CA"):
176 # the UTF-8 entry is skipped over
177 locale.AppriseLocale._default_language = "fr"
178
179 # We will detect the english language (found in the LANG= environment
180 # variable which over-rides the _default
181 assert locale.AppriseLocale.detect_language() == "en"
182 al = locale.AppriseLocale()
183 assert al.lang == "en"
184 assert al.gettext("test") == "test"
185
186 # Test case with set_default set to False (so we're still set to 'fr')
187 assert al.add("zy", set_default=False) is False
188 assert al.gettext("test") == "test"
189
190 al.add("ab", set_default=True)
191 assert al.gettext("test") == "test"
192
193 assert al.add("zy", set_default=False) is False
194 locale.AppriseLocale._default_language = fallback
195
196
197 @pytest.mark.skipif("gettext" not in sys.modules, reason="Requires gettext")
198 def test_apprise_trans_add():
199 """
200 API: Apprise() Gettext add
201
202 """
203
204 # This throws internally but we handle it gracefully
205 al = locale.AppriseLocale()
206 with environ("LANGUAGE", "LC_ALL", "LC_CTYPE", "LANG"):
207 # English is the default/fallback type
208 assert al.add("en") is True
209
210 al = locale.AppriseLocale()
211 with environ("LANGUAGE", "LC_ALL", "LC_CTYPE", LANG="C.UTF-8"):
212 # Test English Environment
213 assert al.add("en") is True
214
215 al = locale.AppriseLocale()
216 with environ("LANGUAGE", "LC_ALL", "LC_CTYPE", LANG="en_CA.UTF-8"):
217 # Test English Environment
218 assert al.add("en") is True
219
220 # Double add (copy of above) to access logic that prevents adding it
221 # again
222 assert al.add("en") is True
223
224 # Invalid Language
225 assert al.add("bad") is False
226
227
228 @pytest.mark.skipif(
229 not hasattr(ctypes, "windll"), reason="Unique Windows test cases"
230 )
231 @pytest.mark.skipif("gettext" not in sys.modules, reason="Requires gettext")
232 @mock.patch("locale.getlocale")
233 def test_apprise_trans_windows_users_win(mock_getlocale):
234 """
235 API: Apprise() Windows Locale Testing (Win version)
236
237 """
238
239 # Set- our gettext.locale() return value
240 mock_getlocale.return_value = ("fr_CA", "UTF-8")
241
242 with mock.patch(
243 "ctypes.windll.kernel32.GetUserDefaultUILanguage"
244 ) as ui_lang:
245 # 4105 = en_CA
246 ui_lang.return_value = 4105
247
248 with environ("LANGUAGE", "LC_ALL", "LC_CTYPE", "LANG"):
249 # Our default language
250 locale.AppriseLocale._default_language = "zz"
251
252 # We will pick up the windll module and detect english
253 assert locale.AppriseLocale.detect_language() == "en"
254
255 # The below accesses the windows fallback code
256 with environ("LANGUAGE", "LC_ALL", "LC_CTYPE", LANG="es_AR"):
257 # Environment Variable Trumps
258 assert locale.AppriseLocale.detect_language() == "es"
259
260 # No environment variable, then the Windows environment is used
261 with environ("LANGUAGE", "LC_ALL", "LC_CTYPE", "LANG"):
262 # Windows Environment
263 assert locale.AppriseLocale.detect_language() == "en"
264
265 assert (
266 locale.AppriseLocale.detect_language(detect_fallback=False) is None
267 )
268
269 # 0 = IndexError
270 ui_lang.return_value = 0
271 with environ("LANGUAGE", "LANG", "LC_ALL", "LC_CTYPE"):
272 # We fall back to posix locale
273 assert locale.AppriseLocale.detect_language() == "fr"
274
275
276 @pytest.mark.skipif(hasattr(ctypes, "windll"), reason="Unique Nux test cases")
277 @pytest.mark.skipif("gettext" not in sys.modules, reason="Requires gettext")
278 @mock.patch("locale.getlocale")
279 def test_apprise_trans_windows_users_nux(mock_getlocale):
280 """
281 API: Apprise() Windows Locale Testing (Nux version)
282
283 """
284
285 # Set- our gettext.locale() return value
286 mock_getlocale.return_value = ("fr_CA", "UTF-8")
287
288 # Emulate a windows environment
289 windll = mock.Mock()
290 ctypes.windll = windll
291
292 # 4105 = en_CA
293 windll.kernel32.GetUserDefaultUILanguage.return_value = 4105
294
295 # Store default value to not break other tests
296 default_language = locale.AppriseLocale._default_language
297
298 with environ("LANGUAGE", "LC_ALL", "LC_CTYPE", "LANG"):
299 # Our default language
300 locale.AppriseLocale._default_language = "zz"
301
302 # We will pick up the windll module and detect english
303 assert locale.AppriseLocale.detect_language() == "en"
304
305 # The below accesses the windows fallback code
306 with environ("LANGUAGE", "LC_ALL", "LC_CTYPE", LANG="es_AR"):
307 # Environment Variable Trumps
308 assert locale.AppriseLocale.detect_language() == "es"
309
310 # No environment variable, then the Windows environment is used
311 with environ("LANGUAGE", "LC_ALL", "LC_CTYPE", "LANG"):
312 # Windows Environment
313 assert locale.AppriseLocale.detect_language() == "en"
314
315 assert locale.AppriseLocale.detect_language(detect_fallback=False) is None
316
317 # 0 = IndexError
318 windll.kernel32.GetUserDefaultUILanguage.return_value = 0
319 with environ("LANGUAGE", "LANG", "LC_ALL", "LC_CTYPE"):
320 # We fall back to posix locale
321 assert locale.AppriseLocale.detect_language() == "fr"
322
323 del ctypes.windll
324
325 # Restore default value
326 locale.AppriseLocale._default_language = default_language
327
328
329 @pytest.mark.skipif(sys.platform == "win32", reason="Unique Nux test cases")
330 @mock.patch("locale.getlocale")
331 def test_detect_language_using_env(mock_getlocale):
332 """Test the reading of information from an environment variable."""
333
334 # Set- our gettext.locale() return value
335 mock_getlocale.return_value = ("en_CA", "UTF-8")
336
337 # The below accesses the windows fallback code and fail
338 # then it will resort to the environment variables.
339 with environ("LANG", "LANGUAGE", "LC_ALL", "LC_CTYPE"):
340 # Language can now be detected in this case
341 assert isinstance(locale.AppriseLocale.detect_language(), str)
342
343 # Detect French language.
344 with environ("LANGUAGE", "LC_ALL", LC_CTYPE="garbage", LANG="fr_CA"):
345 assert locale.AppriseLocale.detect_language() == "fr"
346
347 # The following unsets all environment variables and sets LC_CTYPE
348 # This was causing Python 2.7 to internally parse UTF-8 as an invalid
349 # locale and throw an uncaught ValueError; Python v2 support has been
350 # dropped, but just to ensure this issue does not come back, we keep
351 # this test:
352 with environ(*list(os.environ.keys()), LC_CTYPE="UTF-8"):
353 assert isinstance(locale.AppriseLocale.detect_language(), str)
354
355 # Test with absolutely no environment variables what-so-ever
356 with environ(*list(os.environ.keys())):
357 assert isinstance(locale.AppriseLocale.detect_language(), str)
358
359 # Handle case where getlocale() can't be detected
360 mock_getlocale.return_value = None
361 with environ("LC_ALL", "LC_CTYPE", "LANG", "LANGUAGE"):
362 assert locale.AppriseLocale.detect_language() is None
363
364 mock_getlocale.return_value = (None, None)
365 with environ("LC_ALL", "LC_CTYPE", "LANG", "LANGUAGE"):
366 assert locale.AppriseLocale.detect_language() is None
367
368 # if detect_language and windows env fail us, then we don't
369 # set up a default language on first load
370 locale.AppriseLocale()
371
372
373 @pytest.mark.skipif("gettext" not in sys.modules, reason="Requires gettext")
374 def test_apprise_trans_gettext_missing(tmpdir):
375 """Verify we can still operate without the gettext library."""
376
377 # remove gettext from our system enviroment
378 del sys.modules["gettext"]
379
380 # Make our new path to a fake gettext (used to over-ride real one)
381 # have it fail right out of the gate
382 gettext_dir = tmpdir.mkdir("gettext")
383 gettext_dir.join("__init__.py").write("")
384 gettext_dir.join("gettext.py").write("""raise ImportError()""")
385
386 # Update our path to point path to head
387 sys.path.insert(0, str(gettext_dir))
388
389 # reload our module (forcing the import error when it tries to load gettext
390 reload(sys.modules["apprise.locale"])
391 from apprise import locale
392
393 assert locale.GETTEXT_LOADED is False
394
395 # Now roll our changes back
396 sys.path.pop(0)
397
398 # Reload again (reverting back)
399 reload(sys.modules["apprise.locale"])
400 from apprise import locale
401
402 assert locale.GETTEXT_LOADED is True
403
404
405 @mock.patch("gettext.translation")
406 def test_apprise_locale_add_existing_language(mock_translation):
407 """Re-add an existing language to hit fallback mapping path."""
408 # Return a fake gettext object with a valid gettext() method
409 dummy = mock.Mock()
410 dummy.gettext = lambda x: f"tr:{x}"
411 mock_translation.return_value = dummy
412
413 al = locale.AppriseLocale()
414 assert al.add("en", set_default=True) is True
415 assert al.add("en", set_default=False) is True
416
417
418 @mock.patch("gettext.translation")
419 @mock.patch("locale.getlocale")
420 def test_apprise_trans_successful_translation(
421 mock_getlocale, mock_translation
422 ):
423 """Trigger logger.trace by mocking successful gettext.translation()"""
424 mock_getlocale.return_value = ("en_CA", "UTF-8")
425
426 dummy_translation = mock.Mock()
427 dummy_translation.gettext = lambda x: f"tr:{x}"
428 mock_translation.return_value = dummy_translation
429
430 al = locale.AppriseLocale()
431 assert al.add("en") is True
432 assert al.gettext("test") == "tr:test"