Debian Codegraph @

tests/test_localedata.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 os
14 import pickle
15 import random
16 import sys
17 import tempfile
18
19 import pytest
20
21 from babel import Locale, UnknownLocaleError, localedata
22
23
24 def test_merge_items():
25 d = {1: 'foo', 3: 'baz'}
26 localedata.merge(d, {1: 'Foo', 2: 'Bar'})
27 assert d == {1: 'Foo', 2: 'Bar', 3: 'baz'}
28
29
30 def test_merge_nested_dict():
31 d1 = {'x': {'a': 1, 'b': 2, 'c': 3}}
32 d2 = {'x': {'a': 1, 'b': 12, 'd': 14}}
33 localedata.merge(d1, d2)
34 assert d1 == {'x': {'a': 1, 'b': 12, 'c': 3, 'd': 14}}
35
36
37 def test_merge_nested_dict_no_overlap():
38 d1 = {'x': {'a': 1, 'b': 2}}
39 d2 = {'y': {'a': 11, 'b': 12}}
40 localedata.merge(d1, d2)
41 assert d1 == {'x': {'a': 1, 'b': 2}, 'y': {'a': 11, 'b': 12}}
42
43
44 def test_merge_with_alias_and_resolve():
45 alias = localedata.Alias('x')
46 d1 = {
47 'x': {'a': 1, 'b': 2, 'c': 3},
48 'y': alias,
49 }
50 d2 = {
51 'x': {'a': 1, 'b': 12, 'd': 14},
52 'y': {'b': 22, 'e': 25},
53 }
54 localedata.merge(d1, d2)
55 assert d1 == {'x': {'a': 1, 'b': 12, 'c': 3, 'd': 14}, 'y': (alias, {'b': 22, 'e': 25})}
56 d = localedata.LocaleDataDict(d1)
57 assert dict(d.items()) == {'x': {'a': 1, 'b': 12, 'c': 3, 'd': 14}, 'y': {'a': 1, 'b': 22, 'c': 3, 'd': 14, 'e': 25}}
58 # Resolving the partial alias must not have written the result back into the underlying data (GH-1234)
59 assert d1['y'] == (alias, {'b': 22, 'e': 25})
60
61
62 def test_alias_resolving_to_partially_overridden_alias():
63 # An alias chain that lands on an `(alias, overrides)` tuple
64 # must apply the overrides on top of the resolved target.
65 x_alias = localedata.Alias(('x',))
66 data = {
67 'x': {'a': 1, 'b': 2},
68 'y': (x_alias, {'b': 22, 'c': 33}), # 'x', partially overridden
69 'z': localedata.Alias(('y',)), # an alias landing on the tuple
70 }
71 expected = {'a': 1, 'b': 22, 'c': 33}
72 assert localedata.Alias(('z',)).resolve(data) == expected
73 d = localedata.LocaleDataDict(data)
74 assert dict(d['z']) == expected
75 # Ensure original data is as before:
76 assert data['x'] == {'a': 1, 'b': 2}
77 assert data['y'] == (x_alias, {'b': 22, 'c': 33})
78
79
80 def test_load():
81 assert localedata.load('en_US')['languages']['sv'] == 'Swedish'
82 assert localedata.load('en_US') is localedata.load('en_US')
83
84
85 def _calendar_snapshot(name):
86 locale = Locale.parse(name)
87 return {
88 'months': dict(locale.months['stand-alone']['wide']),
89 'months_abbr': dict(locale.months['format']['abbreviated']),
90 'days': dict(locale.days['stand-alone']['wide']),
91 'quarters': dict(locale.quarters['stand-alone']['wide']),
92 'eras': dict(locale.eras['wide']),
93 }
94
95
96 @pytest.mark.parametrize('reverse', (False, True))
97 def test_no_cross_locale_contamination(reverse):
98 """
99 Alias-heavy calendar data (e.g. what `format_date(..., 'LLLL')` reads)
100 must be identical whether a locale is loaded into a cold cache or after
101 other locales have already been read: e.g.
102 * reading 'he' must not turn Norwegian month names Hebrew
103 * reading 'aa' must not turn everyone else's stand-alone quarters into root's 'Q1' placeholders.
104
105 Regression test for https://github.com/python-babel/babel/issues/1234
106 """
107 locales = ('aa', 'de', 'fr', 'he', 'ja', 'no')
108 cold = {}
109 for name in locales:
110 localedata.clear_caches()
111 cold[name] = _calendar_snapshot(name)
112
113 assert cold['he']['months'] != cold['de']['months'] # Sanity check
114
115 localedata.clear_caches()
116 warm = {name: _calendar_snapshot(name) for name in (reversed(locales) if reverse else locales)}
117 assert warm == cold
118 # Repeated reads in the warmed-up state must stay correct too
119 assert {name: _calendar_snapshot(name) for name in locales} == cold
120
121
122 def test_manual_locale_data_writes(request):
123 """Writes into `Locale(...)._data` (misguided as they may be) must be
124 visible to subsequent reads."""
125
126 # Note that this test codifies how Babel has traditionally worked;
127 # if you're working on e.g. locale immutability, this test should not
128 # be made to pass under that scheme.
129
130 localedata.clear_caches()
131 # This test mutates shared cached locale data; start others afresh
132 request.addfinalizer(localedata.clear_caches)
133
134 locale = Locale.parse('de')
135 # Prime the memoization through both an alias and a plain path
136 # (in 'de', stand-alone wide months are a plain Alias to format ones)
137 assert locale.months['stand-alone']['wide'][10] == 'Oktober'
138 assert locale.months['format']['wide'][10] == 'Oktober'
139
140 # A leaf write must be visible on the next read...
141 locale.months['format']['wide'][10] = 'Rocktober'
142 assert locale.months['format']['wide'][10] == 'Rocktober'
143 # ... also through an alias resolving to the written-to dict ...
144 assert locale.months['stand-alone']['wide'][10] == 'Rocktober'
145 # ... and (as has always been the case, since writes land in the
146 # shared load() data) to other same-name Locale instances.
147 assert Locale.parse('de').months['format']['wide'][10] == 'Rocktober'
148
149 # Replacing a whole subtree must invalidate its memoized wrapper
150 locale._data['months'] = {'format': {'wide': {10: 'blocktober'}}}
151 assert locale.months['format']['wide'][10] == 'blocktober'
152
153 # Deletions must be visible too
154 del locale._data['months']
155 with pytest.raises(KeyError):
156 _ = locale.months['format']
157
158
159 def test_load_inheritance(monkeypatch):
160 localedata.clear_caches()
161 localedata.load('hi_Latn')
162 # Must not be ['root', 'hi_Latn'] even though 'hi_Latn' matches the 'lang_Script'
163 # form used by 'nonLikelyScripts'. This is because 'hi_Latn' has an explicit parent locale 'en_IN'.
164 assert set(localedata._cache) == {'root', 'en', 'en_001', 'en_IN', 'hi_Latn'}
165
166
167 localedata.clear_caches()
168 localedata.load('az_Arab')
169 # Must not include 'az' as 'Arab' is not a likely script for 'az'.
170 assert set(localedata._cache) == {'root', 'az_Arab'}
171
172
173 def test_merge():
174 d = {1: 'foo', 3: 'baz'}
175 localedata.merge(d, {1: 'Foo', 2: 'Bar'})
176 assert d == {1: 'Foo', 2: 'Bar', 3: 'baz'}
177
178
179 def test_locale_identification():
180 for locale in localedata.locale_identifiers():
181 assert localedata.exists(locale)
182
183
184 def test_unique_ids():
185 # Check all locale IDs are uniques.
186 all_ids = localedata.locale_identifiers()
187 assert len(all_ids) == len(set(all_ids))
188 # Check locale IDs don't collide after lower-case normalization.
189 lower_case_ids = [id.lower() for id in all_ids]
190 assert len(lower_case_ids) == len(set(lower_case_ids))
191
192
193 def test_mixedcased_locale():
194 for locale in localedata.locale_identifiers():
195 locale_id = ''.join(c.lower() if random.random() < 0.5 else c.upper() for c in locale)
196 assert localedata.exists(locale_id)
197
198
199 def test_locale_argument_acceptance():
200 # Testing None input.
201 normalized_locale = localedata.normalize_locale(None)
202 assert normalized_locale is None
203 assert not localedata.exists(None)
204
205 # Testing tuple input.
206 normalized_locale = localedata.normalize_locale(['en_us', None])
207 assert normalized_locale is None
208 assert not localedata.exists(('en_us', None))
209
210
211 def test_locale_identifiers_cache(monkeypatch):
212 original_listdir = localedata.os.listdir
213 listdir_calls = []
214
215 def listdir_spy(*args):
216 rv = original_listdir(*args)
217 listdir_calls.append((args, rv))
218 return rv
219
220 monkeypatch.setattr(localedata.os, 'listdir', listdir_spy)
221 localedata.locale_identifiers.cache_clear()
222 assert not listdir_calls
223 l = localedata.locale_identifiers()
224 assert len(listdir_calls) == 1
225 assert localedata.locale_identifiers() is l
226 assert len(listdir_calls) == 1
227 localedata.locale_identifiers.cache_clear()
228 assert localedata.locale_identifiers()
229 assert len(listdir_calls) == 2
230
231
232 def test_locale_name_cleanup():
233 """
234 Test that locale identifiers are cleaned up to avoid directory traversal.
235 """
236 no_exist_name = os.path.join(tempfile.gettempdir(), "babel%d.dat" % random.randint(1, 99999))
237 with open(no_exist_name, "wb") as f:
238 pickle.dump({}, f)
239
240 try:
241 name = os.path.splitext(os.path.relpath(no_exist_name, localedata._dirname))[0]
242 except ValueError:
243 if sys.platform == "win32":
244 pytest.skip("unable to form relpath")
245 raise
246
247 assert not localedata.exists(name)
248 with pytest.raises(IOError):
249 localedata.load(name)
250 with pytest.raises(UnknownLocaleError):
251 Locale(name)
252
253
254 @pytest.mark.skipif(sys.platform != "win32", reason="windows-only test")
255 def test_reserved_locale_names():
256 for name in ("con", "aux", "nul", "prn", "com8", "lpt5"):
257 with pytest.raises(ValueError):
258 localedata.load(name)
259 with pytest.raises(ValueError):
260 Locale(name)