Debian Codegraph @

tests/test_core.py

raw
1 #
2 # Copyright (C) 2007-2011 Edgewall Software, 2013-2025 the Babel team
3 # All rights reserved.
4 #
5 # This software is licensed as described in the file LICENSE, which
6 # you should have received as part of this distribution. The terms
7 # are also available at https://github.com/python-babel/babel/blob/master/LICENSE.
8 #
9 # This software consists of voluntary contributions made by many
10 # individuals. For the exact contribution history, see the revision
11 # history and logs, available at https://github.com/python-babel/babel/commits/master/.
12
13 import pytest
14
15 from babel import core
16 from babel.core import Locale, default_locale
17
18
19 def test_locale_provides_access_to_cldr_locale_data():
20 locale = Locale('en', 'US')
21 assert locale.display_name == 'English (United States)'
22 assert locale.number_symbols["latn"]['decimal'] == '.'
23
24
25 def test_locale_repr():
26 assert repr(Locale('en', 'US')) == "Locale('en', territory='US')"
27 assert (repr(Locale('de', 'DE')) == "Locale('de', territory='DE')")
28 assert (repr(Locale('zh', 'CN', script='Hans')) == "Locale('zh', territory='CN', script='Hans')")
29
30
31 def test_locale_comparison():
32 en_US = Locale('en', 'US')
33 en_US_2 = Locale('en', 'US')
34 fi_FI = Locale('fi', 'FI')
35 bad_en_US = Locale('en_US')
36 assert en_US == en_US
37 assert en_US == en_US_2
38 assert en_US != fi_FI
39 assert not (en_US != en_US_2)
40 assert en_US is not None
41 assert en_US != bad_en_US
42 assert fi_FI != bad_en_US
43
44
45 def test_can_return_default_locale(monkeypatch):
46 monkeypatch.setenv('LC_MESSAGES', 'fr_FR.UTF-8')
47 assert Locale('fr', 'FR') == Locale.default('LC_MESSAGES')
48
49
50 def test_ignore_invalid_locales_in_lc_ctype(monkeypatch):
51 # This is a regression test specifically for a bad LC_CTYPE setting on
52 # MacOS X 10.6 (#200)
53 monkeypatch.setenv('LC_CTYPE', 'UTF-8')
54 # must not throw an exception
55 default_locale('LC_CTYPE')
56
57
58 def test_zone_aliases_and_territories():
59 aliases = core.get_global('zone_aliases')
60 territories = core.get_global('zone_territories')
61 assert aliases['GMT'] == 'Etc/GMT'
62 assert aliases['UTC'] == 'Etc/UTC'
63 assert territories['Europe/Berlin'] == 'DE'
64 # Check that the canonical (IANA) names are used in `territories`,
65 # but that aliases are still available.
66 assert territories['Africa/Asmara'] == 'ER'
67 assert aliases['Africa/Asmera'] == 'Africa/Asmara'
68 assert territories['Europe/Kyiv'] == 'UA'
69 assert aliases['Europe/Kiev'] == 'Europe/Kyiv'
70
71
72 def test_hash():
73 locale_a = Locale('en', 'US')
74 locale_b = Locale('en', 'US')
75 locale_c = Locale('fi', 'FI')
76 assert hash(locale_a) == hash(locale_b)
77 assert hash(locale_a) != hash(locale_c)
78
79
80 class TestLocaleClass:
81
82 def test_attributes(self):
83 locale = Locale('en', 'US')
84 assert locale.language == 'en'
85 assert locale.territory == 'US'
86
87 def test_default(self, monkeypatch):
88 for name in ['LANGUAGE', 'LC_ALL', 'LC_CTYPE', 'LC_MESSAGES']:
89 monkeypatch.setenv(name, '')
90 monkeypatch.setenv('LANG', 'fr_FR.UTF-8')
91 default = Locale.default('LC_MESSAGES')
92 assert (default.language, default.territory) == ('fr', 'FR')
93
94 def test_negotiate(self):
95 de_DE = Locale.negotiate(['de_DE', 'en_US'], ['de_DE', 'de_AT'])
96 assert (de_DE.language, de_DE.territory) == ('de', 'DE')
97 de = Locale.negotiate(['de_DE', 'en_US'], ['en', 'de'])
98 assert (de.language, de.territory) == ('de', None)
99 nothing = Locale.negotiate(['de_DE', 'de'], ['en_US'])
100 assert nothing is None
101
102 def test_negotiate_custom_separator(self):
103 de_DE = Locale.negotiate(['de-DE', 'de'], ['en-us', 'de-de'], sep='-')
104 assert (de_DE.language, de_DE.territory) == ('de', 'DE')
105
106 def test_parse(self):
107 locale = Locale.parse('de-DE', sep='-')
108 assert locale.display_name == 'Deutsch (Deutschland)'
109
110 de_DE = Locale.parse(locale)
111 assert (de_DE.language, de_DE.territory) == ('de', 'DE')
112
113 def test_parse_likely_subtags(self):
114 locale = Locale.parse('zh-TW', sep='-')
115 assert locale.language == 'zh'
116 assert locale.territory == 'TW'
117 assert locale.script == 'Hant'
118
119 locale = Locale.parse('zh_CN')
120 assert locale.language == 'zh'
121 assert locale.territory == 'CN'
122 assert locale.script == 'Hans'
123
124 locale = Locale.parse('zh_SG')
125 assert locale.language == 'zh'
126 assert locale.territory == 'SG'
127 assert locale.script == 'Hans'
128
129 locale = Locale.parse('und_AT')
130 assert locale.language == 'de'
131 assert locale.territory == 'AT'
132
133 locale = Locale.parse('und_UK')
134 assert locale.language == 'en'
135 assert locale.territory == 'GB'
136 assert locale.script is None
137
138 def test_get_display_name(self):
139 zh_CN = Locale('zh', 'CN', script='Hans')
140 assert zh_CN.get_display_name('en') == 'Chinese (Simplified, China)'
141
142 def test_display_name_property(self):
143 assert Locale('en').display_name == 'English'
144 assert Locale('en', 'US').display_name == 'English (United States)'
145 assert Locale('sv').display_name == 'svenska'
146
147 def test_english_name_property(self):
148 assert Locale('de').english_name == 'German'
149 assert Locale('de', 'DE').english_name == 'German (Germany)'
150
151 def test_languages_property(self):
152 assert Locale('de', 'DE').languages['ja'] == 'Japanisch'
153
154 def test_scripts_property(self):
155 assert Locale('en', 'US').scripts['Hira'] == 'Hiragana'
156
157 def test_territories_property(self):
158 assert Locale('es', 'CO').territories['DE'] == 'Alemania'
159
160 def test_variants_property(self):
161 assert (Locale('de', 'DE').variants['1901'] ==
162 'Alte deutsche Rechtschreibung')
163
164 def test_currencies_property(self):
165 assert Locale('en').currencies['COP'] == 'Colombian Peso'
166 assert Locale('de', 'DE').currencies['COP'] == 'Kolumbianischer Peso'
167
168 def test_currency_symbols_property(self):
169 assert Locale('en', 'US').currency_symbols['USD'] == '$'
170 assert Locale('es', 'CO').currency_symbols['USD'] == 'US$'
171
172 def test_number_symbols_property(self):
173 assert Locale('fr', 'FR').number_symbols["latn"]['decimal'] == ','
174 assert Locale('ar', 'IL').number_symbols["arab"]['percentSign'] == '٪\u061c'
175 assert Locale('ar', 'IL').number_symbols["latn"]['percentSign'] == '\u200e%\u200e'
176
177 def test_other_numbering_systems_property(self):
178 assert Locale('fr', 'FR').other_numbering_systems['native'] == 'latn'
179 assert 'traditional' not in Locale('fr', 'FR').other_numbering_systems
180
181 assert Locale('el', 'GR').other_numbering_systems['native'] == 'latn'
182 assert Locale('el', 'GR').other_numbering_systems['traditional'] == 'grek'
183
184 def test_default_numbering_systems_property(self):
185 assert Locale('en', 'GB').default_numbering_system == 'latn'
186 assert Locale('ar', 'EG').default_numbering_system == 'arab'
187
188 @pytest.mark.all_locales
189 def test_all_locales_have_default_numbering_system(self, locale):
190 locale = Locale.parse(locale)
191 assert locale.default_numbering_system
192
193 def test_decimal_formats(self):
194 assert Locale('en', 'US').decimal_formats[None].pattern == '#,##0.###'
195
196 def test_currency_formats_property(self):
197 assert (Locale('en', 'US').currency_formats['standard'].pattern ==
198 '\xa4#,##0.00')
199 assert (Locale('en', 'US').currency_formats['accounting'].pattern ==
200 '\xa4#,##0.00;(\xa4#,##0.00)')
201
202 def test_percent_formats_property(self):
203 assert Locale('en', 'US').percent_formats[None].pattern == '#,##0%'
204
205 def test_scientific_formats_property(self):
206 assert Locale('en', 'US').scientific_formats[None].pattern == '#E0'
207
208 def test_periods_property(self):
209 assert Locale('en', 'US').periods['am'] == 'AM'
210
211 def test_days_property(self):
212 assert Locale('de', 'DE').days['format']['wide'][3] == 'Donnerstag'
213
214 def test_months_property(self):
215 assert Locale('de', 'DE').months['format']['wide'][10] == 'Oktober'
216
217 def test_quarters_property(self):
218 assert Locale('de', 'DE').quarters['format']['wide'][1] == '1. Quartal'
219
220 def test_eras_property(self):
221 assert Locale('en', 'US').eras['wide'][1] == 'Anno Domini'
222 assert Locale('en', 'US').eras['abbreviated'][0] == 'BC'
223
224 def test_time_zones_property(self):
225 time_zones = Locale('en', 'US').time_zones
226 assert (time_zones['Europe/London']['long']['daylight'] ==
227 'British Summer Time')
228 assert time_zones['America/St_Johns']['city'] == 'St. John\u2019s'
229
230 def test_meta_zones_property(self):
231 meta_zones = Locale('en', 'US').meta_zones
232 assert (meta_zones['Europe_Central']['long']['daylight'] ==
233 'Central European Summer Time')
234
235 def test_zone_formats_property(self):
236 assert Locale('en', 'US').zone_formats['fallback'] == '%(1)s (%(0)s)'
237 assert Locale('pt', 'BR').zone_formats['region'] == 'Hor\xe1rio %s'
238
239 def test_first_week_day_property(self):
240 assert Locale('de', 'DE').first_week_day == 0
241 assert Locale('en', 'US').first_week_day == 6
242
243 def test_weekend_start_property(self):
244 assert Locale('de', 'DE').weekend_start == 5
245
246 def test_weekend_end_property(self):
247 assert Locale('de', 'DE').weekend_end == 6
248
249 def test_min_week_days_property(self):
250 assert Locale('de', 'DE').min_week_days == 4
251
252 def test_date_formats_property(self):
253 assert Locale('en', 'US').date_formats['short'].pattern == 'M/d/yy'
254 assert Locale('fr', 'FR').date_formats['long'].pattern == 'd MMMM y'
255
256 def test_time_formats_property(self):
257 assert Locale('en', 'US').time_formats['short'].pattern == 'h:mm\u202fa'
258 assert Locale('fr', 'FR').time_formats['long'].pattern == 'HH:mm:ss z'
259
260 def test_datetime_formats_property(self):
261 assert Locale('en').datetime_formats['full'] == "{1}, {0}"
262 assert Locale('th').datetime_formats['medium'] == '{1} {0}'
263
264 def test_datetime_skeleton_property(self):
265 assert Locale('en').datetime_skeletons['Md'].pattern == "M/d"
266 assert Locale('th').datetime_skeletons['Md'].pattern == 'd/M'
267
268 def test_plural_form_property(self):
269 assert Locale('en').plural_form(1) == 'one'
270 assert Locale('en').plural_form(0) == 'other'
271 assert Locale('fr').plural_form(0) == 'one'
272 assert Locale('ru').plural_form(100) == 'many'
273
274
275 def test_default_locale(monkeypatch):
276 for name in ['LANGUAGE', 'LANG', 'LC_ALL', 'LC_CTYPE', 'LC_MESSAGES']:
277 monkeypatch.setenv(name, '')
278 monkeypatch.setenv('LANG', 'fr_FR.UTF-8')
279 assert default_locale('LC_MESSAGES') == 'fr_FR'
280 monkeypatch.setenv('LC_MESSAGES', 'POSIX')
281 assert default_locale('LC_MESSAGES') == 'en_US_POSIX'
282
283 for value in ['C', 'C.UTF-8', 'POSIX']:
284 monkeypatch.setenv('LANGUAGE', value)
285 assert default_locale() == 'en_US_POSIX'
286
287
288 def test_default_locale_multiple_args(monkeypatch):
289 for name in ['LANGUAGE', 'LANG', 'LC_ALL', 'LC_CTYPE', 'LC_MESSAGES', 'LC_MONETARY', 'LC_NUMERIC']:
290 monkeypatch.setenv(name, '')
291 assert default_locale(["", 0, None]) is None
292 monkeypatch.setenv('LANG', 'en_US')
293 assert default_locale(('LC_MONETARY', 'LC_NUMERIC')) == 'en_US' # No LC_MONETARY or LC_NUMERIC set
294 monkeypatch.setenv('LC_NUMERIC', 'fr_FR.UTF-8')
295 assert default_locale(('LC_MONETARY', 'LC_NUMERIC')) == 'fr_FR' # LC_NUMERIC set
296 monkeypatch.setenv('LC_MONETARY', 'fi_FI.UTF-8')
297 assert default_locale(('LC_MONETARY', 'LC_NUMERIC')) == 'fi_FI' # LC_MONETARY set, it takes precedence
298
299
300 def test_default_locale_bad_arg():
301 with pytest.raises(TypeError):
302 default_locale(42)
303
304
305 def test_negotiate_locale():
306 assert (core.negotiate_locale(['de_DE', 'en_US'], ['de_DE', 'de_AT']) ==
307 'de_DE')
308 assert core.negotiate_locale(['de_DE', 'en_US'], ['en', 'de']) == 'de'
309 assert (core.negotiate_locale(['de_DE', 'en_US'], ['de_de', 'de_at']) ==
310 'de_DE')
311 assert (core.negotiate_locale(['de_DE', 'en_US'], ['de_de', 'de_at']) ==
312 'de_DE')
313 assert (core.negotiate_locale(['ja', 'en_US'], ['ja_JP', 'en_US']) ==
314 'ja_JP')
315 assert core.negotiate_locale(['no', 'sv'], ['nb_NO', 'sv_SE']) == 'nb_NO'
316
317
318 def test_parse_locale():
319 assert core.parse_locale('zh_CN') == ('zh', 'CN', None, None)
320 assert core.parse_locale('zh_Hans_CN') == ('zh', 'CN', 'Hans', None)
321 assert core.parse_locale('zh-CN', sep='-') == ('zh', 'CN', None, None)
322
323 with pytest.raises(ValueError, match="'not_a_LOCALE_String' is not a valid locale identifier"):
324 core.parse_locale('not_a_LOCALE_String')
325
326 assert core.parse_locale('it_IT@euro') == ('it', 'IT', None, None, 'euro')
327 assert core.parse_locale('it_IT@something') == ('it', 'IT', None, None, 'something')
328
329 assert core.parse_locale('en_US.UTF-8') == ('en', 'US', None, None)
330 assert (core.parse_locale('de_DE.iso885915@euro') ==
331 ('de', 'DE', None, None, 'euro'))
332
333 with pytest.raises(ValueError, match="empty"):
334 core.parse_locale("")
335
336
337 @pytest.mark.parametrize('filename', [
338 'babel/global.dat',
339 'babel/locale-data/root.dat',
340 'babel/locale-data/en.dat',
341 'babel/locale-data/en_US.dat',
342 'babel/locale-data/en_US_POSIX.dat',
343 'babel/locale-data/zh_Hans_CN.dat',
344 'babel/locale-data/zh_Hant_TW.dat',
345 'babel/locale-data/es_419.dat',
346 ])
347 def test_compatible_classes_in_global_and_localedata(filename):
348 import pickle
349
350 class Unpickler(pickle.Unpickler):
351
352 def find_class(self, module, name):
353 # *.dat files must have compatible classes between Python 2 and 3
354 if module.split('.')[0] == 'babel':
355 return pickle.Unpickler.find_class(self, module, name)
356 raise pickle.UnpicklingError(f"global '{module}.{name}' is forbidden")
357
358 with open(filename, 'rb') as f:
359 assert Unpickler(f).load()
360
361
362 def test_issue_601_no_language_name_but_has_variant():
363 # kw_GB has a variant for Finnish but no actual language name for Finnish,
364 # so `get_display_name()` previously crashed with a TypeError as it attempted
365 # to concatenate " (Finnish)" to None.
366 # Instead, it's better to return None altogether, as we can't reliably format
367 # part of a language name.
368
369 assert Locale.parse('fi_FI').get_display_name('kw_GB') is None
370
371
372 def test_issue_814():
373 loc = Locale.parse('ca_ES_valencia')
374 assert loc.variant == "VALENCIA"
375 assert loc.get_display_name() == 'català (Espanya, valencià)'
376
377
378 def test_issue_1112():
379 """
380 Test that an alternate spelling of `Türkei` doesn't inadvertently
381 get imported from `de_AT` to replace the parent's non-alternate spelling.
382 """
383 assert (
384 Locale.parse('de').territories['TR'] ==
385 Locale.parse('de_AT').territories['TR'] ==
386 Locale.parse('de_CH').territories['TR'] ==
387 Locale.parse('de_DE').territories['TR'] ==
388 'Türkei'
389 )
390
391
392 def test_language_alt_official_not_used():
393 # If there exists an official and customary language name, the customary
394 # name should be used.
395 #
396 # For example, here 'Muscogee' should be used instead of 'Mvskoke':
397 # <language type="mus">Muscogee</language>
398 # <language type="mus" alt="official">Mvskoke</language>
399
400 locale = Locale('mus')
401 assert locale.get_display_name() == 'Mvskoke'
402 assert locale.get_display_name(Locale('en')) == 'Muscogee'
403
404
405 def test_locale_parse_empty():
406 with pytest.raises(ValueError, match="Empty") as ei:
407 Locale.parse("")
408 assert isinstance(ei.value.args[0], str)
409 with pytest.raises(TypeError, match="Empty"):
410 Locale.parse(None)
411 with pytest.raises(TypeError, match="Empty"):
412 Locale.parse(False) # weird...!
413
414
415 def test_get_cldr_version():
416 assert core.get_cldr_version() == "48"