Debian Codegraph @

Lib/test/test_gettext.py

raw
1 import os
2 import base64
3 import gettext
4 import unittest
5 import unittest.mock
6 from functools import partial
7
8 from test import support
9 from test.support import os_helper
10
11
12 # TODO:
13 # - Add new tests, for example for "dgettext"
14 # - Remove dummy tests, for example testing for single and double quotes
15 # has no sense, it would have if we were testing a parser (i.e. pygettext)
16 # - Tests should have only one assert.
17
18 GNU_MO_DATA = b'''\
19 3hIElQAAAAAJAAAAHAAAAGQAAAAAAAAArAAAAAAAAACsAAAAFQAAAK0AAAAjAAAAwwAAAKEAAADn
20 AAAAMAAAAIkBAAAHAAAAugEAABYAAADCAQAAHAAAANkBAAALAAAA9gEAAEIBAAACAgAAFgAAAEUD
21 AAAeAAAAXAMAAKEAAAB7AwAAMgAAAB0EAAAFAAAAUAQAABsAAABWBAAAIQAAAHIEAAAJAAAAlAQA
22 AABSYXltb25kIEx1eHVyeSBZYWNoLXQAVGhlcmUgaXMgJXMgZmlsZQBUaGVyZSBhcmUgJXMgZmls
23 ZXMAVGhpcyBtb2R1bGUgcHJvdmlkZXMgaW50ZXJuYXRpb25hbGl6YXRpb24gYW5kIGxvY2FsaXph
24 dGlvbgpzdXBwb3J0IGZvciB5b3VyIFB5dGhvbiBwcm9ncmFtcyBieSBwcm92aWRpbmcgYW4gaW50
25 ZXJmYWNlIHRvIHRoZSBHTlUKZ2V0dGV4dCBtZXNzYWdlIGNhdGFsb2cgbGlicmFyeS4AV2l0aCBj
26 b250ZXh0BFRoZXJlIGlzICVzIGZpbGUAVGhlcmUgYXJlICVzIGZpbGVzAG11bGx1c2sAbXkgY29u
27 dGV4dARudWRnZSBudWRnZQBteSBvdGhlciBjb250ZXh0BG51ZGdlIG51ZGdlAG51ZGdlIG51ZGdl
28 AFByb2plY3QtSWQtVmVyc2lvbjogMi4wClBPLVJldmlzaW9uLURhdGU6IDIwMDMtMDQtMTEgMTQ6
29 MzItMDQwMApMYXN0LVRyYW5zbGF0b3I6IEouIERhdmlkIEliYW5leiA8ai1kYXZpZEBub29zLmZy
30 PgpMYW5ndWFnZS1UZWFtOiBYWCA8cHl0aG9uLWRldkBweXRob24ub3JnPgpNSU1FLVZlcnNpb246
31 IDEuMApDb250ZW50LVR5cGU6IHRleHQvcGxhaW47IGNoYXJzZXQ9aXNvLTg4NTktMQpDb250ZW50
32 LVRyYW5zZmVyLUVuY29kaW5nOiA4Yml0CkdlbmVyYXRlZC1CeTogcHlnZXR0ZXh0LnB5IDEuMQpQ
33 bHVyYWwtRm9ybXM6IG5wbHVyYWxzPTI7IHBsdXJhbD1uIT0xOwoAVGhyb2F0d29iYmxlciBNYW5n
34 cm92ZQBIYXkgJXMgZmljaGVybwBIYXkgJXMgZmljaGVyb3MAR3V2ZiB6YnFoeXIgY2ViaXZxcmYg
35 dmFncmVhbmd2YmFueXZtbmd2YmEgbmFxIHlicG55dm1uZ3ZiYQpmaGNjYmVnIHNiZSBsYmhlIENs
36 Z3ViYSBjZWJ0ZW56ZiBvbCBjZWJpdnF2YXQgbmEgdmFncmVzbnByIGdiIGd1ciBUQUgKdHJnZ3Jr
37 ZyB6cmZmbnRyIHBuZ255YnQgeXZvZW5lbC4ASGF5ICVzIGZpY2hlcm8gKGNvbnRleHQpAEhheSAl
38 cyBmaWNoZXJvcyAoY29udGV4dCkAYmFjb24Ad2luayB3aW5rIChpbiAibXkgY29udGV4dCIpAHdp
39 bmsgd2luayAoaW4gIm15IG90aGVyIGNvbnRleHQiKQB3aW5rIHdpbmsA
40 '''
41
42 # .mo file with an invalid magic number
43 GNU_MO_DATA_BAD_MAGIC_NUMBER = base64.b64encode(b'ABCD')
44
45 # This data contains an invalid major version number (5)
46 # An unexpected major version number should be treated as an error when
47 # parsing a .mo file
48
49 GNU_MO_DATA_BAD_MAJOR_VERSION = b'''\
50 3hIElQAABQAGAAAAHAAAAEwAAAALAAAAfAAAAAAAAACoAAAAFQAAAKkAAAAjAAAAvwAAAKEAAADj
51 AAAABwAAAIUBAAALAAAAjQEAAEUBAACZAQAAFgAAAN8CAAAeAAAA9gIAAKEAAAAVAwAABQAAALcD
52 AAAJAAAAvQMAAAEAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAABQAAAAYAAAACAAAAAFJh
53 eW1vbmQgTHV4dXJ5IFlhY2gtdABUaGVyZSBpcyAlcyBmaWxlAFRoZXJlIGFyZSAlcyBmaWxlcwBU
54 aGlzIG1vZHVsZSBwcm92aWRlcyBpbnRlcm5hdGlvbmFsaXphdGlvbiBhbmQgbG9jYWxpemF0aW9u
55 CnN1cHBvcnQgZm9yIHlvdXIgUHl0aG9uIHByb2dyYW1zIGJ5IHByb3ZpZGluZyBhbiBpbnRlcmZh
56 Y2UgdG8gdGhlIEdOVQpnZXR0ZXh0IG1lc3NhZ2UgY2F0YWxvZyBsaWJyYXJ5LgBtdWxsdXNrAG51
57 ZGdlIG51ZGdlAFByb2plY3QtSWQtVmVyc2lvbjogMi4wClBPLVJldmlzaW9uLURhdGU6IDIwMDAt
58 MDgtMjkgMTI6MTktMDQ6MDAKTGFzdC1UcmFuc2xhdG9yOiBKLiBEYXZpZCBJYsOhw7FleiA8ai1k
59 YXZpZEBub29zLmZyPgpMYW5ndWFnZS1UZWFtOiBYWCA8cHl0aG9uLWRldkBweXRob24ub3JnPgpN
60 SU1FLVZlcnNpb246IDEuMApDb250ZW50LVR5cGU6IHRleHQvcGxhaW47IGNoYXJzZXQ9aXNvLTg4
61 NTktMQpDb250ZW50LVRyYW5zZmVyLUVuY29kaW5nOiBub25lCkdlbmVyYXRlZC1CeTogcHlnZXR0
62 ZXh0LnB5IDEuMQpQbHVyYWwtRm9ybXM6IG5wbHVyYWxzPTI7IHBsdXJhbD1uIT0xOwoAVGhyb2F0
63 d29iYmxlciBNYW5ncm92ZQBIYXkgJXMgZmljaGVybwBIYXkgJXMgZmljaGVyb3MAR3V2ZiB6YnFo
64 eXIgY2ViaXZxcmYgdmFncmVhbmd2YmFueXZtbmd2YmEgbmFxIHlicG55dm1uZ3ZiYQpmaGNjYmVn
65 IHNiZSBsYmhlIENsZ3ViYSBjZWJ0ZW56ZiBvbCBjZWJpdnF2YXQgbmEgdmFncmVzbnByIGdiIGd1
66 ciBUQUgKdHJnZ3JrZyB6cmZmbnRyIHBuZ255YnQgeXZvZW5lbC4AYmFjb24Ad2luayB3aW5rAA==
67 '''
68
69 # This data contains an invalid minor version number (7)
70 # An unexpected minor version number only indicates that some of the file's
71 # contents may not be able to be read. It does not indicate an error.
72
73 GNU_MO_DATA_BAD_MINOR_VERSION = b'''\
74 3hIElQcAAAAGAAAAHAAAAEwAAAALAAAAfAAAAAAAAACoAAAAFQAAAKkAAAAjAAAAvwAAAKEAAADj
75 AAAABwAAAIUBAAALAAAAjQEAAEUBAACZAQAAFgAAAN8CAAAeAAAA9gIAAKEAAAAVAwAABQAAALcD
76 AAAJAAAAvQMAAAEAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAABQAAAAYAAAACAAAAAFJh
77 eW1vbmQgTHV4dXJ5IFlhY2gtdABUaGVyZSBpcyAlcyBmaWxlAFRoZXJlIGFyZSAlcyBmaWxlcwBU
78 aGlzIG1vZHVsZSBwcm92aWRlcyBpbnRlcm5hdGlvbmFsaXphdGlvbiBhbmQgbG9jYWxpemF0aW9u
79 CnN1cHBvcnQgZm9yIHlvdXIgUHl0aG9uIHByb2dyYW1zIGJ5IHByb3ZpZGluZyBhbiBpbnRlcmZh
80 Y2UgdG8gdGhlIEdOVQpnZXR0ZXh0IG1lc3NhZ2UgY2F0YWxvZyBsaWJyYXJ5LgBtdWxsdXNrAG51
81 ZGdlIG51ZGdlAFByb2plY3QtSWQtVmVyc2lvbjogMi4wClBPLVJldmlzaW9uLURhdGU6IDIwMDAt
82 MDgtMjkgMTI6MTktMDQ6MDAKTGFzdC1UcmFuc2xhdG9yOiBKLiBEYXZpZCBJYsOhw7FleiA8ai1k
83 YXZpZEBub29zLmZyPgpMYW5ndWFnZS1UZWFtOiBYWCA8cHl0aG9uLWRldkBweXRob24ub3JnPgpN
84 SU1FLVZlcnNpb246IDEuMApDb250ZW50LVR5cGU6IHRleHQvcGxhaW47IGNoYXJzZXQ9aXNvLTg4
85 NTktMQpDb250ZW50LVRyYW5zZmVyLUVuY29kaW5nOiBub25lCkdlbmVyYXRlZC1CeTogcHlnZXR0
86 ZXh0LnB5IDEuMQpQbHVyYWwtRm9ybXM6IG5wbHVyYWxzPTI7IHBsdXJhbD1uIT0xOwoAVGhyb2F0
87 d29iYmxlciBNYW5ncm92ZQBIYXkgJXMgZmljaGVybwBIYXkgJXMgZmljaGVyb3MAR3V2ZiB6YnFo
88 eXIgY2ViaXZxcmYgdmFncmVhbmd2YmFueXZtbmd2YmEgbmFxIHlicG55dm1uZ3ZiYQpmaGNjYmVn
89 IHNiZSBsYmhlIENsZ3ViYSBjZWJ0ZW56ZiBvbCBjZWJpdnF2YXQgbmEgdmFncmVzbnByIGdiIGd1
90 ciBUQUgKdHJnZ3JrZyB6cmZmbnRyIHBuZ255YnQgeXZvZW5lbC4AYmFjb24Ad2luayB3aW5rAA==
91 '''
92
93 # Corrupt .mo file
94 # Generated from
95 #
96 # msgid "foo"
97 # msgstr "bar"
98 #
99 # with msgfmt --no-hash
100 #
101 # The translation offset is changed to 0xFFFFFFFF,
102 # making it larger than the file size, which should
103 # raise an error when parsing.
104 GNU_MO_DATA_CORRUPT = base64.b64encode(bytes([
105 0xDE, 0x12, 0x04, 0x95, # Magic
106 0x00, 0x00, 0x00, 0x00, # Version
107 0x01, 0x00, 0x00, 0x00, # Message count
108 0x1C, 0x00, 0x00, 0x00, # Message offset
109 0x24, 0x00, 0x00, 0x00, # Translation offset
110 0x00, 0x00, 0x00, 0x00, # Hash table size
111 0x2C, 0x00, 0x00, 0x00, # Hash table offset
112 0x03, 0x00, 0x00, 0x00, # 1st message length
113 0x2C, 0x00, 0x00, 0x00, # 1st message offset
114 0x03, 0x00, 0x00, 0x00, # 1st trans length
115 0xFF, 0xFF, 0xFF, 0xFF, # 1st trans offset (Modified to make it invalid)
116 0x66, 0x6F, 0x6F, 0x00, # Message data
117 0x62, 0x61, 0x72, 0x00, # Message data
118 ]))
119
120
121 GNU_MO_DATA_BIG_ENDIAN = base64.b64encode(bytes([
122 0x95, 0x04, 0x12, 0xDE, # Magic
123 0x00, 0x00, 0x00, 0x00, # Version
124 0x00, 0x00, 0x00, 0x01, # Message count
125 0x00, 0x00, 0x00, 0x1C, # Message offset
126 0x00, 0x00, 0x00, 0x24, # Translation offset
127 0x00, 0x00, 0x00, 0x00, # Hash table size
128 0x00, 0x00, 0x00, 0x2C, # Hash table offset
129 0x00, 0x00, 0x00, 0x03, # 1st message length
130 0x00, 0x00, 0x00, 0x2C, # 1st message offset
131 0x00, 0x00, 0x00, 0x03, # 1st trans length
132 0x00, 0x00, 0x00, 0x30, # 1st trans offset
133 0x66, 0x6F, 0x6F, 0x00, # Message data
134 0x62, 0x61, 0x72, 0x00, # Message data
135 ]))
136
137 UMO_DATA = b'''\
138 3hIElQAAAAADAAAAHAAAADQAAAAAAAAAAAAAAAAAAABMAAAABAAAAE0AAAAQAAAAUgAAAA8BAABj
139 AAAABAAAAHMBAAAWAAAAeAEAAABhYsOeAG15Y29udGV4dMOeBGFiw54AUHJvamVjdC1JZC1WZXJz
140 aW9uOiAyLjAKUE8tUmV2aXNpb24tRGF0ZTogMjAwMy0wNC0xMSAxMjo0Mi0wNDAwCkxhc3QtVHJh
141 bnNsYXRvcjogQmFycnkgQS4gV0Fyc2F3IDxiYXJyeUBweXRob24ub3JnPgpMYW5ndWFnZS1UZWFt
142 OiBYWCA8cHl0aG9uLWRldkBweXRob24ub3JnPgpNSU1FLVZlcnNpb246IDEuMApDb250ZW50LVR5
143 cGU6IHRleHQvcGxhaW47IGNoYXJzZXQ9dXRmLTgKQ29udGVudC1UcmFuc2Zlci1FbmNvZGluZzog
144 N2JpdApHZW5lcmF0ZWQtQnk6IG1hbnVhbGx5CgDCpHl6AMKkeXogKGNvbnRleHQgdmVyc2lvbikA
145 '''
146
147 MMO_DATA = b'''\
148 3hIElQAAAAABAAAAHAAAACQAAAADAAAALAAAAAAAAAA4AAAAeAEAADkAAAABAAAAAAAAAAAAAAAA
149 UHJvamVjdC1JZC1WZXJzaW9uOiBObyBQcm9qZWN0IDAuMApQT1QtQ3JlYXRpb24tRGF0ZTogV2Vk
150 IERlYyAxMSAwNzo0NDoxNSAyMDAyClBPLVJldmlzaW9uLURhdGU6IDIwMDItMDgtMTQgMDE6MTg6
151 NTgrMDA6MDAKTGFzdC1UcmFuc2xhdG9yOiBKb2huIERvZSA8amRvZUBleGFtcGxlLmNvbT4KSmFu
152 ZSBGb29iYXIgPGpmb29iYXJAZXhhbXBsZS5jb20+Ckxhbmd1YWdlLVRlYW06IHh4IDx4eEBleGFt
153 cGxlLmNvbT4KTUlNRS1WZXJzaW9uOiAxLjAKQ29udGVudC1UeXBlOiB0ZXh0L3BsYWluOyBjaGFy
154 c2V0PWlzby04ODU5LTE1CkNvbnRlbnQtVHJhbnNmZXItRW5jb2Rpbmc6IHF1b3RlZC1wcmludGFi
155 bGUKR2VuZXJhdGVkLUJ5OiBweWdldHRleHQucHkgMS4zCgA=
156 '''
157
158 LOCALEDIR = os.path.join('xx', 'LC_MESSAGES')
159 MOFILE = os.path.join(LOCALEDIR, 'gettext.mo')
160 MOFILE_BAD_MAGIC_NUMBER = os.path.join(LOCALEDIR, 'gettext_bad_magic_number.mo')
161 MOFILE_BAD_MAJOR_VERSION = os.path.join(LOCALEDIR, 'gettext_bad_major_version.mo')
162 MOFILE_BAD_MINOR_VERSION = os.path.join(LOCALEDIR, 'gettext_bad_minor_version.mo')
163 MOFILE_CORRUPT = os.path.join(LOCALEDIR, 'gettext_corrupt.mo')
164 MOFILE_BIG_ENDIAN = os.path.join(LOCALEDIR, 'gettext_big_endian.mo')
165 UMOFILE = os.path.join(LOCALEDIR, 'ugettext.mo')
166 MMOFILE = os.path.join(LOCALEDIR, 'metadata.mo')
167
168
169 def reset_gettext():
170 gettext._localedirs.clear()
171 gettext._current_domain = 'messages'
172 gettext._translations.clear()
173
174
175 class GettextBaseTest(unittest.TestCase):
176 @classmethod
177 def setUpClass(cls):
178 cls.addClassCleanup(os_helper.rmtree, os.path.split(LOCALEDIR)[0])
179 if not os.path.isdir(LOCALEDIR):
180 os.makedirs(LOCALEDIR)
181 with open(MOFILE, 'wb') as fp:
182 fp.write(base64.decodebytes(GNU_MO_DATA))
183 with open(MOFILE_BAD_MAGIC_NUMBER, 'wb') as fp:
184 fp.write(base64.decodebytes(GNU_MO_DATA_BAD_MAGIC_NUMBER))
185 with open(MOFILE_BAD_MAJOR_VERSION, 'wb') as fp:
186 fp.write(base64.decodebytes(GNU_MO_DATA_BAD_MAJOR_VERSION))
187 with open(MOFILE_BAD_MINOR_VERSION, 'wb') as fp:
188 fp.write(base64.decodebytes(GNU_MO_DATA_BAD_MINOR_VERSION))
189 with open(MOFILE_CORRUPT, 'wb') as fp:
190 fp.write(base64.decodebytes(GNU_MO_DATA_CORRUPT))
191 with open(MOFILE_BIG_ENDIAN, 'wb') as fp:
192 fp.write(base64.decodebytes(GNU_MO_DATA_BIG_ENDIAN))
193 with open(UMOFILE, 'wb') as fp:
194 fp.write(base64.decodebytes(UMO_DATA))
195 with open(MMOFILE, 'wb') as fp:
196 fp.write(base64.decodebytes(MMO_DATA))
197
198 def setUp(self):
199 self.env = self.enterContext(os_helper.EnvironmentVarGuard())
200 self.env['LANGUAGE'] = 'xx'
201 reset_gettext()
202 self.addCleanup(reset_gettext)
203
204
205 GNU_MO_DATA_ISSUE_17898 = b'''\
206 3hIElQAAAAABAAAAHAAAACQAAAAAAAAAAAAAAAAAAAAsAAAAggAAAC0AAAAAUGx1cmFsLUZvcm1z
207 OiBucGx1cmFscz0yOyBwbHVyYWw9KG4gIT0gMSk7CiMtIy0jLSMtIyAgbWVzc2FnZXMucG8gKEVk
208 WCBTdHVkaW8pICAjLSMtIy0jLSMKQ29udGVudC1UeXBlOiB0ZXh0L3BsYWluOyBjaGFyc2V0PVVU
209 Ri04CgA=
210 '''
211
212 class GettextTestCase1(GettextBaseTest):
213 def setUp(self):
214 GettextBaseTest.setUp(self)
215 self.localedir = os.curdir
216 self.mofile = MOFILE
217 gettext.install('gettext', self.localedir, names=['pgettext'])
218
219 def test_some_translations(self):
220 eq = self.assertEqual
221 # test some translations
222 eq(_('albatross'), 'albatross')
223 eq(_('mullusk'), 'bacon')
224 eq(_(r'Raymond Luxury Yach-t'), 'Throatwobbler Mangrove')
225 eq(_(r'nudge nudge'), 'wink wink')
226
227 def test_some_translations_with_context(self):
228 eq = self.assertEqual
229 eq(pgettext('my context', 'nudge nudge'),
230 'wink wink (in "my context")')
231 eq(pgettext('my other context', 'nudge nudge'),
232 'wink wink (in "my other context")')
233
234 def test_double_quotes(self):
235 eq = self.assertEqual
236 # double quotes
237 eq(_("albatross"), 'albatross')
238 eq(_("mullusk"), 'bacon')
239 eq(_(r"Raymond Luxury Yach-t"), 'Throatwobbler Mangrove')
240 eq(_(r"nudge nudge"), 'wink wink')
241
242 def test_triple_single_quotes(self):
243 eq = self.assertEqual
244 # triple single quotes
245 eq(_('''albatross'''), 'albatross')
246 eq(_('''mullusk'''), 'bacon')
247 eq(_(r'''Raymond Luxury Yach-t'''), 'Throatwobbler Mangrove')
248 eq(_(r'''nudge nudge'''), 'wink wink')
249
250 def test_triple_double_quotes(self):
251 eq = self.assertEqual
252 # triple double quotes
253 eq(_("""albatross"""), 'albatross')
254 eq(_("""mullusk"""), 'bacon')
255 eq(_(r"""Raymond Luxury Yach-t"""), 'Throatwobbler Mangrove')
256 eq(_(r"""nudge nudge"""), 'wink wink')
257
258 def test_multiline_strings(self):
259 eq = self.assertEqual
260 # multiline strings
261 eq(_('''This module provides internationalization and localization
262 support for your Python programs by providing an interface to the GNU
263 gettext message catalog library.'''),
264 '''Guvf zbqhyr cebivqrf vagreangvbanyvmngvba naq ybpnyvmngvba
265 fhccbeg sbe lbhe Clguba cebtenzf ol cebivqvat na vagresnpr gb gur TAH
266 trggrkg zrffntr pngnybt yvoenel.''')
267
268 def test_the_alternative_interface(self):
269 eq = self.assertEqual
270 neq = self.assertNotEqual
271 # test the alternative interface
272 with open(self.mofile, 'rb') as fp:
273 t = gettext.GNUTranslations(fp)
274 # Install the translation object
275 t.install()
276 eq(_('nudge nudge'), 'wink wink')
277 # Try unicode return type
278 t.install()
279 eq(_('mullusk'), 'bacon')
280 # Test installation of other methods
281 import builtins
282 t.install(names=["gettext", "ngettext"])
283 eq(_, t.gettext)
284 eq(builtins.gettext, t.gettext)
285 eq(ngettext, t.ngettext)
286 neq(pgettext, t.pgettext)
287 del builtins.gettext
288 del builtins.ngettext
289
290
291 class GettextTestCase2(GettextBaseTest):
292 def setUp(self):
293 GettextBaseTest.setUp(self)
294 self.localedir = os.curdir
295 # Set up the bindings
296 gettext.bindtextdomain('gettext', self.localedir)
297 gettext.textdomain('gettext')
298 # For convenience
299 self._ = gettext.gettext
300
301 def test_bindtextdomain(self):
302 self.assertEqual(gettext.bindtextdomain('gettext'), self.localedir)
303
304 def test_textdomain(self):
305 self.assertEqual(gettext.textdomain(), 'gettext')
306
307 def test_bad_magic_number(self):
308 with open(MOFILE_BAD_MAGIC_NUMBER, 'rb') as fp:
309 with self.assertRaises(OSError) as cm:
310 gettext.GNUTranslations(fp)
311
312 exception = cm.exception
313 self.assertEqual(exception.errno, 0)
314 self.assertEqual(exception.strerror, "Bad magic number")
315 self.assertEqual(exception.filename, MOFILE_BAD_MAGIC_NUMBER)
316
317 def test_bad_major_version(self):
318 with open(MOFILE_BAD_MAJOR_VERSION, 'rb') as fp:
319 with self.assertRaises(OSError) as cm:
320 gettext.GNUTranslations(fp)
321
322 exception = cm.exception
323 self.assertEqual(exception.errno, 0)
324 self.assertEqual(exception.strerror, "Bad version number 5")
325 self.assertEqual(exception.filename, MOFILE_BAD_MAJOR_VERSION)
326
327 def test_bad_minor_version(self):
328 with open(MOFILE_BAD_MINOR_VERSION, 'rb') as fp:
329 # Check that no error is thrown with a bad minor version number
330 gettext.GNUTranslations(fp)
331
332 def test_corrupt_file(self):
333 with open(MOFILE_CORRUPT, 'rb') as fp:
334 with self.assertRaises(OSError) as cm:
335 gettext.GNUTranslations(fp)
336
337 exception = cm.exception
338 self.assertEqual(exception.errno, 0)
339 self.assertEqual(exception.strerror, "File is corrupt")
340 self.assertEqual(exception.filename, MOFILE_CORRUPT)
341
342 def test_big_endian_file(self):
343 with open(MOFILE_BIG_ENDIAN, 'rb') as fp:
344 t = gettext.GNUTranslations(fp)
345
346 self.assertEqual(t.gettext('foo'), 'bar')
347
348 def test_some_translations(self):
349 eq = self.assertEqual
350 # test some translations
351 eq(self._('albatross'), 'albatross')
352 eq(self._('mullusk'), 'bacon')
353 eq(self._(r'Raymond Luxury Yach-t'), 'Throatwobbler Mangrove')
354 eq(self._(r'nudge nudge'), 'wink wink')
355
356 def test_some_translations_with_context(self):
357 eq = self.assertEqual
358 eq(gettext.pgettext('my context', 'nudge nudge'),
359 'wink wink (in "my context")')
360 eq(gettext.pgettext('my other context', 'nudge nudge'),
361 'wink wink (in "my other context")')
362
363 def test_some_translations_with_context_and_domain(self):
364 eq = self.assertEqual
365 eq(gettext.dpgettext('gettext', 'my context', 'nudge nudge'),
366 'wink wink (in "my context")')
367 eq(gettext.dpgettext('gettext', 'my other context', 'nudge nudge'),
368 'wink wink (in "my other context")')
369
370 def test_double_quotes(self):
371 eq = self.assertEqual
372 # double quotes
373 eq(self._("albatross"), 'albatross')
374 eq(self._("mullusk"), 'bacon')
375 eq(self._(r"Raymond Luxury Yach-t"), 'Throatwobbler Mangrove')
376 eq(self._(r"nudge nudge"), 'wink wink')
377
378 def test_triple_single_quotes(self):
379 eq = self.assertEqual
380 # triple single quotes
381 eq(self._('''albatross'''), 'albatross')
382 eq(self._('''mullusk'''), 'bacon')
383 eq(self._(r'''Raymond Luxury Yach-t'''), 'Throatwobbler Mangrove')
384 eq(self._(r'''nudge nudge'''), 'wink wink')
385
386 def test_triple_double_quotes(self):
387 eq = self.assertEqual
388 # triple double quotes
389 eq(self._("""albatross"""), 'albatross')
390 eq(self._("""mullusk"""), 'bacon')
391 eq(self._(r"""Raymond Luxury Yach-t"""), 'Throatwobbler Mangrove')
392 eq(self._(r"""nudge nudge"""), 'wink wink')
393
394 def test_multiline_strings(self):
395 eq = self.assertEqual
396 # multiline strings
397 eq(self._('''This module provides internationalization and localization
398 support for your Python programs by providing an interface to the GNU
399 gettext message catalog library.'''),
400 '''Guvf zbqhyr cebivqrf vagreangvbanyvmngvba naq ybpnyvmngvba
401 fhccbeg sbe lbhe Clguba cebtenzf ol cebivqvat na vagresnpr gb gur TAH
402 trggrkg zrffntr pngnybt yvoenel.''')
403
404
405 class PluralFormsTests:
406
407 def _test_plural_forms(self, ngettext, gettext,
408 singular, plural, tsingular, tplural,
409 numbers_only=True):
410 x = ngettext(singular, plural, 1)
411 self.assertEqual(x, tsingular)
412 x = ngettext(singular, plural, 2)
413 self.assertEqual(x, tplural)
414 x = gettext(singular)
415 self.assertEqual(x, tsingular)
416
417 lineno = self._test_plural_forms.__code__.co_firstlineno + 12
418 with self.assertWarns(DeprecationWarning) as cm:
419 x = ngettext(singular, plural, 1.0)
420 self.assertEqual(cm.filename, __file__)
421 self.assertEqual(cm.lineno, lineno)
422 self.assertEqual(x, tsingular)
423 with self.assertWarns(DeprecationWarning) as cm:
424 x = ngettext(singular, plural, 1.1)
425 self.assertEqual(cm.filename, __file__)
426 self.assertEqual(cm.lineno, lineno + 5)
427 self.assertEqual(x, tplural)
428
429 if numbers_only:
430 with self.assertRaises(TypeError):
431 ngettext(singular, plural, None)
432 else:
433 with self.assertWarns(DeprecationWarning) as cm:
434 x = ngettext(singular, plural, None)
435 self.assertEqual(x, tplural)
436
437 def test_plural_forms(self):
438 self._test_plural_forms(
439 self.ngettext, self.gettext,
440 'There is %s file', 'There are %s files',
441 'Hay %s fichero', 'Hay %s ficheros')
442 self._test_plural_forms(
443 self.ngettext, self.gettext,
444 '%d file deleted', '%d files deleted',
445 '%d file deleted', '%d files deleted')
446
447 def test_plural_context_forms(self):
448 ngettext = partial(self.npgettext, 'With context')
449 gettext = partial(self.pgettext, 'With context')
450 self._test_plural_forms(
451 ngettext, gettext,
452 'There is %s file', 'There are %s files',
453 'Hay %s fichero (context)', 'Hay %s ficheros (context)')
454 self._test_plural_forms(
455 ngettext, gettext,
456 '%d file deleted', '%d files deleted',
457 '%d file deleted', '%d files deleted')
458
459 def test_plural_wrong_context_forms(self):
460 self._test_plural_forms(
461 partial(self.npgettext, 'Unknown context'),
462 partial(self.pgettext, 'Unknown context'),
463 'There is %s file', 'There are %s files',
464 'There is %s file', 'There are %s files')
465
466
467 class GNUTranslationsPluralFormsTestCase(PluralFormsTests, GettextBaseTest):
468 def setUp(self):
469 GettextBaseTest.setUp(self)
470 # Set up the bindings
471 gettext.bindtextdomain('gettext', os.curdir)
472 gettext.textdomain('gettext')
473
474 self.gettext = gettext.gettext
475 self.ngettext = gettext.ngettext
476 self.pgettext = gettext.pgettext
477 self.npgettext = gettext.npgettext
478
479
480 class GNUTranslationsWithDomainPluralFormsTestCase(PluralFormsTests, GettextBaseTest):
481 def setUp(self):
482 GettextBaseTest.setUp(self)
483 # Set up the bindings
484 gettext.bindtextdomain('gettext', os.curdir)
485
486 self.gettext = partial(gettext.dgettext, 'gettext')
487 self.ngettext = partial(gettext.dngettext, 'gettext')
488 self.pgettext = partial(gettext.dpgettext, 'gettext')
489 self.npgettext = partial(gettext.dnpgettext, 'gettext')
490
491 def test_plural_forms_wrong_domain(self):
492 self._test_plural_forms(
493 partial(gettext.dngettext, 'unknown'),
494 partial(gettext.dgettext, 'unknown'),
495 'There is %s file', 'There are %s files',
496 'There is %s file', 'There are %s files',
497 numbers_only=False)
498
499 def test_plural_context_forms_wrong_domain(self):
500 self._test_plural_forms(
501 partial(gettext.dnpgettext, 'unknown', 'With context'),
502 partial(gettext.dpgettext, 'unknown', 'With context'),
503 'There is %s file', 'There are %s files',
504 'There is %s file', 'There are %s files',
505 numbers_only=False)
506
507
508 class GNUTranslationsClassPluralFormsTestCase(PluralFormsTests, GettextBaseTest):
509 def setUp(self):
510 GettextBaseTest.setUp(self)
511 with open(MOFILE, 'rb') as fp:
512 t = gettext.GNUTranslations(fp)
513
514 self.gettext = t.gettext
515 self.ngettext = t.ngettext
516 self.pgettext = t.pgettext
517 self.npgettext = t.npgettext
518
519 def test_plural_forms_null_translations(self):
520 t = gettext.NullTranslations()
521 self._test_plural_forms(
522 t.ngettext, t.gettext,
523 'There is %s file', 'There are %s files',
524 'There is %s file', 'There are %s files',
525 numbers_only=False)
526
527 def test_plural_context_forms_null_translations(self):
528 t = gettext.NullTranslations()
529 self._test_plural_forms(
530 partial(t.npgettext, 'With context'),
531 partial(t.pgettext, 'With context'),
532 'There is %s file', 'There are %s files',
533 'There is %s file', 'There are %s files',
534 numbers_only=False)
535
536
537 class PluralFormsInternalTestCase(unittest.TestCase):
538 # Examples from http://www.gnu.org/software/gettext/manual/gettext.html
539
540 def test_ja(self):
541 eq = self.assertEqual
542 f = gettext.c2py('0')
543 s = ''.join([ str(f(x)) for x in range(200) ])
544 eq(s, "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000")
545
546 def test_de(self):
547 eq = self.assertEqual
548 f = gettext.c2py('n != 1')
549 s = ''.join([ str(f(x)) for x in range(200) ])
550 eq(s, "10111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111")
551
552 def test_fr(self):
553 eq = self.assertEqual
554 f = gettext.c2py('n>1')
555 s = ''.join([ str(f(x)) for x in range(200) ])
556 eq(s, "00111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111")
557
558 def test_lv(self):
559 eq = self.assertEqual
560 f = gettext.c2py('n%10==1 && n%100!=11 ? 0 : n != 0 ? 1 : 2')
561 s = ''.join([ str(f(x)) for x in range(200) ])
562 eq(s, "20111111111111111111101111111110111111111011111111101111111110111111111011111111101111111110111111111011111111111111111110111111111011111111101111111110111111111011111111101111111110111111111011111111")
563
564 def test_gd(self):
565 eq = self.assertEqual
566 f = gettext.c2py('n==1 ? 0 : n==2 ? 1 : 2')
567 s = ''.join([ str(f(x)) for x in range(200) ])
568 eq(s, "20122222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222")
569
570 def test_gd2(self):
571 eq = self.assertEqual
572 # Tests the combination of parentheses and "?:"
573 f = gettext.c2py('n==1 ? 0 : (n==2 ? 1 : 2)')
574 s = ''.join([ str(f(x)) for x in range(200) ])
575 eq(s, "20122222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222")
576
577 def test_ro(self):
578 eq = self.assertEqual
579 f = gettext.c2py('n==1 ? 0 : (n==0 || (n%100 > 0 && n%100 < 20)) ? 1 : 2')
580 s = ''.join([ str(f(x)) for x in range(200) ])
581 eq(s, "10111111111111111111222222222222222222222222222222222222222222222222222222222222222222222222222222222111111111111111111122222222222222222222222222222222222222222222222222222222222222222222222222222222")
582
583 def test_lt(self):
584 eq = self.assertEqual
585 f = gettext.c2py('n%10==1 && n%100!=11 ? 0 : n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2')
586 s = ''.join([ str(f(x)) for x in range(200) ])
587 eq(s, "20111111112222222222201111111120111111112011111111201111111120111111112011111111201111111120111111112011111111222222222220111111112011111111201111111120111111112011111111201111111120111111112011111111")
588
589 def test_ru(self):
590 eq = self.assertEqual
591 f = gettext.c2py('n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2')
592 s = ''.join([ str(f(x)) for x in range(200) ])
593 eq(s, "20111222222222222222201112222220111222222011122222201112222220111222222011122222201112222220111222222011122222222222222220111222222011122222201112222220111222222011122222201112222220111222222011122222")
594
595 def test_cs(self):
596 eq = self.assertEqual
597 f = gettext.c2py('(n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2')
598 s = ''.join([ str(f(x)) for x in range(200) ])
599 eq(s, "20111222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222")
600
601 def test_pl(self):
602 eq = self.assertEqual
603 f = gettext.c2py('n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2')
604 s = ''.join([ str(f(x)) for x in range(200) ])
605 eq(s, "20111222222222222222221112222222111222222211122222221112222222111222222211122222221112222222111222222211122222222222222222111222222211122222221112222222111222222211122222221112222222111222222211122222")
606
607 def test_sl(self):
608 eq = self.assertEqual
609 f = gettext.c2py('n%100==1 ? 0 : n%100==2 ? 1 : n%100==3 || n%100==4 ? 2 : 3')
610 s = ''.join([ str(f(x)) for x in range(200) ])
611 eq(s, "30122333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333012233333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333")
612
613 def test_ar(self):
614 eq = self.assertEqual
615 f = gettext.c2py('n==0 ? 0 : n==1 ? 1 : n==2 ? 2 : n%100>=3 && n%100<=10 ? 3 : n%100>=11 ? 4 : 5')
616 s = ''.join([ str(f(x)) for x in range(200) ])
617 eq(s, "01233333333444444444444444444444444444444444444444444444444444444444444444444444444444444444444444445553333333344444444444444444444444444444444444444444444444444444444444444444444444444444444444444444")
618
619 def test_security(self):
620 raises = self.assertRaises
621 # Test for a dangerous expression
622 raises(ValueError, gettext.c2py, "os.chmod('/etc/passwd',0777)")
623 # issue28563
624 raises(ValueError, gettext.c2py, '"(eval(foo) && ""')
625 raises(ValueError, gettext.c2py, 'f"{os.system(\'sh\')}"')
626 # Maximum recursion depth exceeded during compilation
627 raises(ValueError, gettext.c2py, 'n+'*10000 + 'n')
628 self.assertEqual(gettext.c2py('n+'*100 + 'n')(1), 101)
629 # MemoryError during compilation
630 raises(ValueError, gettext.c2py, '('*100 + 'n' + ')'*100)
631 # Maximum recursion depth exceeded in C to Python translator
632 raises(ValueError, gettext.c2py, '('*10000 + 'n' + ')'*10000)
633 self.assertEqual(gettext.c2py('('*20 + 'n' + ')'*20)(1), 1)
634
635 def test_chained_comparison(self):
636 # C doesn't chain comparison as Python so 2 == 2 == 2 gets different results
637 f = gettext.c2py('n == n == n')
638 self.assertEqual(''.join(str(f(x)) for x in range(3)), '010')
639 f = gettext.c2py('1 < n == n')
640 self.assertEqual(''.join(str(f(x)) for x in range(3)), '100')
641 f = gettext.c2py('n == n < 2')
642 self.assertEqual(''.join(str(f(x)) for x in range(3)), '010')
643 f = gettext.c2py('0 < n < 2')
644 self.assertEqual(''.join(str(f(x)) for x in range(3)), '111')
645
646 def test_decimal_number(self):
647 self.assertEqual(gettext.c2py('0123')(1), 123)
648
649 def test_invalid_syntax(self):
650 invalid_expressions = [
651 'x>1', '(n>1', 'n>1)', '42**42**42', '0xa', '1.0', '1e2',
652 'n>0x1', '+n', '-n', 'n()', 'n(1)', '1+', 'nn', 'n n', 'n ? 1 2'
653 ]
654 for expr in invalid_expressions:
655 with self.assertRaises(ValueError):
656 gettext.c2py(expr)
657
658 def test_negation(self):
659 f = gettext.c2py('!!!n')
660 self.assertEqual(f(0), 1)
661 self.assertEqual(f(1), 0)
662 self.assertEqual(f(2), 0)
663
664 def test_nested_condition_operator(self):
665 self.assertEqual(gettext.c2py('n?1?2:3:4')(0), 4)
666 self.assertEqual(gettext.c2py('n?1?2:3:4')(1), 2)
667 self.assertEqual(gettext.c2py('n?1:3?4:5')(0), 4)
668 self.assertEqual(gettext.c2py('n?1:3?4:5')(1), 1)
669
670 def test_division(self):
671 f = gettext.c2py('2/n*3')
672 self.assertEqual(f(1), 6)
673 self.assertEqual(f(2), 3)
674 self.assertEqual(f(3), 0)
675 self.assertEqual(f(-1), -6)
676 self.assertRaises(ZeroDivisionError, f, 0)
677
678 def test_plural_number(self):
679 f = gettext.c2py('n != 1')
680 self.assertEqual(f(1), 0)
681 self.assertEqual(f(2), 1)
682 with self.assertWarns(DeprecationWarning):
683 self.assertEqual(f(1.0), 0)
684 with self.assertWarns(DeprecationWarning):
685 self.assertEqual(f(2.0), 1)
686 with self.assertWarns(DeprecationWarning):
687 self.assertEqual(f(1.1), 1)
688 self.assertRaises(TypeError, f, '2')
689 self.assertRaises(TypeError, f, b'2')
690 self.assertRaises(TypeError, f, [])
691 self.assertRaises(TypeError, f, object())
692
693
694 class GNUTranslationParsingTest(GettextBaseTest):
695 def test_plural_form_error_issue17898(self):
696 with open(MOFILE, 'wb') as fp:
697 fp.write(base64.decodebytes(GNU_MO_DATA_ISSUE_17898))
698 with open(MOFILE, 'rb') as fp:
699 # If this runs cleanly, the bug is fixed.
700 t = gettext.GNUTranslations(fp)
701
702 def test_ignore_comments_in_headers_issue36239(self):
703 """Checks that comments like:
704
705 #-#-#-#-# messages.po (EdX Studio) #-#-#-#-#
706
707 are ignored.
708 """
709 with open(MOFILE, 'wb') as fp:
710 fp.write(base64.decodebytes(GNU_MO_DATA_ISSUE_17898))
711 with open(MOFILE, 'rb') as fp:
712 t = gettext.GNUTranslations(fp)
713 self.assertEqual(t.info()["plural-forms"], "nplurals=2; plural=(n != 1);")
714
715
716 class UnicodeTranslationsTest(GettextBaseTest):
717 def setUp(self):
718 GettextBaseTest.setUp(self)
719 with open(UMOFILE, 'rb') as fp:
720 self.t = gettext.GNUTranslations(fp)
721 self._ = self.t.gettext
722 self.pgettext = self.t.pgettext
723
724 def test_unicode_msgid(self):
725 self.assertIsInstance(self._(''), str)
726
727 def test_unicode_msgstr(self):
728 self.assertEqual(self._('ab\xde'), '\xa4yz')
729
730 def test_unicode_context_msgstr(self):
731 t = self.pgettext('mycontext\xde', 'ab\xde')
732 self.assertTrue(isinstance(t, str))
733 self.assertEqual(t, '\xa4yz (context version)')
734
735
736 class UnicodeTranslationsPluralTest(GettextBaseTest):
737 def setUp(self):
738 GettextBaseTest.setUp(self)
739 with open(MOFILE, 'rb') as fp:
740 self.t = gettext.GNUTranslations(fp)
741 self.ngettext = self.t.ngettext
742 self.npgettext = self.t.npgettext
743
744 def test_unicode_msgid(self):
745 unless = self.assertTrue
746 unless(isinstance(self.ngettext('', '', 1), str))
747 unless(isinstance(self.ngettext('', '', 2), str))
748
749 def test_unicode_context_msgid(self):
750 unless = self.assertTrue
751 unless(isinstance(self.npgettext('', '', '', 1), str))
752 unless(isinstance(self.npgettext('', '', '', 2), str))
753
754 def test_unicode_msgstr(self):
755 eq = self.assertEqual
756 unless = self.assertTrue
757 t = self.ngettext("There is %s file", "There are %s files", 1)
758 unless(isinstance(t, str))
759 eq(t, "Hay %s fichero")
760 unless(isinstance(t, str))
761 t = self.ngettext("There is %s file", "There are %s files", 5)
762 unless(isinstance(t, str))
763 eq(t, "Hay %s ficheros")
764
765 def test_unicode_msgstr_with_context(self):
766 eq = self.assertEqual
767 unless = self.assertTrue
768 t = self.npgettext("With context",
769 "There is %s file", "There are %s files", 1)
770 unless(isinstance(t, str))
771 eq(t, "Hay %s fichero (context)")
772 t = self.npgettext("With context",
773 "There is %s file", "There are %s files", 5)
774 unless(isinstance(t, str))
775 eq(t, "Hay %s ficheros (context)")
776
777
778 class WeirdMetadataTest(GettextBaseTest):
779 def setUp(self):
780 GettextBaseTest.setUp(self)
781 with open(MMOFILE, 'rb') as fp:
782 try:
783 self.t = gettext.GNUTranslations(fp)
784 except:
785 self.tearDown()
786 raise
787
788 def test_weird_metadata(self):
789 info = self.t.info()
790 self.assertEqual(len(info), 9)
791 self.assertEqual(info['last-translator'],
792 'John Doe <[email protected]>\nJane Foobar <[email protected]>')
793
794
795 class DummyGNUTranslations(gettext.GNUTranslations):
796 def foo(self):
797 return 'foo'
798
799
800 class GettextCacheTestCase(GettextBaseTest):
801 def test_cache(self):
802 self.localedir = os.curdir
803 self.mofile = MOFILE
804
805 self.assertEqual(len(gettext._translations), 0)
806
807 t = gettext.translation('gettext', self.localedir)
808
809 self.assertEqual(len(gettext._translations), 1)
810
811 t = gettext.translation('gettext', self.localedir,
812 class_=DummyGNUTranslations)
813
814 self.assertEqual(len(gettext._translations), 2)
815 self.assertEqual(t.__class__, DummyGNUTranslations)
816
817 # Calling it again doesn't add to the cache
818
819 t = gettext.translation('gettext', self.localedir,
820 class_=DummyGNUTranslations)
821
822 self.assertEqual(len(gettext._translations), 2)
823 self.assertEqual(t.__class__, DummyGNUTranslations)
824
825
826 class FallbackTranslations(gettext.NullTranslations):
827 def gettext(self, message):
828 return f'gettext: {message}'
829
830 def ngettext(self, msgid1, msgid2, n):
831 return f'ngettext: {msgid1}, {msgid2}, {n}'
832
833 def pgettext(self, context, message):
834 return f'pgettext: {context}, {message}'
835
836 def npgettext(self, context, msgid1, msgid2, n):
837 return f'npgettext: {context}, {msgid1}, {msgid2}, {n}'
838
839
840 class FallbackTestCase(GettextBaseTest):
841 def test_null_translations_fallback(self):
842 t = gettext.NullTranslations()
843 t.add_fallback(FallbackTranslations())
844 self.assertEqual(t.gettext('foo'), 'gettext: foo')
845 self.assertEqual(t.ngettext('foo', 'foos', 1),
846 'ngettext: foo, foos, 1')
847 self.assertEqual(t.pgettext('context', 'foo'),
848 'pgettext: context, foo')
849 self.assertEqual(t.npgettext('context', 'foo', 'foos', 1),
850 'npgettext: context, foo, foos, 1')
851
852 def test_gnu_translations_fallback(self):
853 with open(MOFILE, 'rb') as fp:
854 t = gettext.GNUTranslations(fp)
855 t.add_fallback(FallbackTranslations())
856 self.assertEqual(t.gettext('foo'), 'gettext: foo')
857 self.assertEqual(t.ngettext('foo', 'foos', 1),
858 'ngettext: foo, foos, 1')
859 self.assertEqual(t.pgettext('context', 'foo'),
860 'pgettext: context, foo')
861 self.assertEqual(t.npgettext('context', 'foo', 'foos', 1),
862 'npgettext: context, foo, foos, 1')
863
864 def test_nested_fallbacks(self):
865 class NestedFallback(gettext.NullTranslations):
866 def gettext(self, message):
867 if message == 'foo':
868 return 'fallback'
869 return super().gettext(message)
870
871 fallback1 = NestedFallback()
872 fallback2 = FallbackTranslations()
873 t = gettext.NullTranslations()
874 t.add_fallback(fallback1)
875 t.add_fallback(fallback2)
876
877 self.assertEqual(fallback1.gettext('bar'), 'gettext: bar')
878 self.assertEqual(t.gettext('foo'), 'fallback')
879 self.assertEqual(t.gettext('bar'), 'gettext: bar')
880
881
882 class ExpandLangTestCase(unittest.TestCase):
883 def test_expand_lang(self):
884 # Test all combinations of territory, charset and
885 # modifier (locale extension)
886 locales = {
887 'cs': ['cs'],
888 'cs_CZ': ['cs_CZ', 'cs'],
889 'cs.ISO8859-2': ['cs.ISO8859-2', 'cs'],
890 'cs@euro': ['cs@euro', 'cs'],
891 'cs_CZ.ISO8859-2': ['cs_CZ.ISO8859-2', 'cs_CZ', 'cs.ISO8859-2',
892 'cs'],
893 'cs_CZ@euro': ['cs_CZ@euro', 'cs@euro', 'cs_CZ', 'cs'],
894 'cs.ISO8859-2@euro': ['cs.ISO8859-2@euro', 'cs@euro',
895 'cs.ISO8859-2', 'cs'],
896 'cs_CZ.ISO8859-2@euro': ['cs_CZ.ISO8859-2@euro', 'cs_CZ@euro',
897 'cs.ISO8859-2@euro', 'cs@euro',
898 'cs_CZ.ISO8859-2', 'cs_CZ',
899 'cs.ISO8859-2', 'cs'],
900 }
901 for locale, expanded in locales.items():
902 with self.subTest(locale=locale):
903 with unittest.mock.patch("locale.normalize",
904 return_value=locale):
905 self.assertEqual(gettext._expand_lang(locale), expanded)
906
907
908 class FindTestCase(unittest.TestCase):
909
910 def setUp(self):
911 self.env = self.enterContext(os_helper.EnvironmentVarGuard())
912 self.tempdir = self.enterContext(os_helper.temp_cwd())
913
914 for key in ('LANGUAGE', 'LC_ALL', 'LC_MESSAGES', 'LANG'):
915 self.env.unset(key)
916
917 def create_mo_file(self, lang):
918 locale_dir = os.path.join(self.tempdir, "locale")
919 mofile_dir = os.path.join(locale_dir, lang, "LC_MESSAGES")
920 os.makedirs(mofile_dir)
921 mo_file = os.path.join(mofile_dir, "mofile.mo")
922 with open(mo_file, "wb") as f:
923 f.write(GNU_MO_DATA)
924 return mo_file
925
926 def test_find_with_env_vars(self):
927 # test that find correctly finds the environment variables
928 # when languages are not supplied
929 mo_file = self.create_mo_file("ga_IE")
930 for var in ('LANGUAGE', 'LC_ALL', 'LC_MESSAGES', 'LANG'):
931 self.env.set(var, 'ga_IE')
932 result = gettext.find("mofile",
933 localedir=os.path.join(self.tempdir, "locale"))
934 self.assertEqual(result, mo_file)
935 self.env.unset(var)
936
937 def test_find_with_languages(self):
938 # test that passed languages are used
939 self.env.set('LANGUAGE', 'pt_BR')
940 mo_file = self.create_mo_file("ga_IE")
941
942 result = gettext.find("mofile",
943 localedir=os.path.join(self.tempdir, "locale"),
944 languages=['ga_IE'])
945 self.assertEqual(result, mo_file)
946
947 @unittest.mock.patch('gettext._expand_lang')
948 def test_find_with_no_lang(self, patch_expand_lang):
949 # no language can be found
950 gettext.find('foo')
951 patch_expand_lang.assert_called_with('C')
952
953 @unittest.mock.patch('gettext._expand_lang')
954 def test_find_with_c(self, patch_expand_lang):
955 # 'C' is already in languages
956 self.env.set('LANGUAGE', 'C')
957 gettext.find('foo')
958 patch_expand_lang.assert_called_with('C')
959
960 def test_find_all(self):
961 # test that all are returned when all is set
962 paths = []
963 for lang in ["ga_IE", "es_ES"]:
964 paths.append(self.create_mo_file(lang))
965 result = gettext.find('mofile',
966 localedir=os.path.join(self.tempdir, "locale"),
967 languages=["ga_IE", "es_ES"], all=True)
968 self.assertEqual(sorted(result), sorted(paths))
969
970 def test_find_deduplication(self):
971 # test that find removes duplicate languages
972 mo_file = [self.create_mo_file('ga_IE')]
973 result = gettext.find("mofile", localedir=os.path.join(self.tempdir, "locale"),
974 languages=['ga_IE', 'ga_IE'], all=True)
975 self.assertEqual(result, mo_file)
976
977
978 class MiscTestCase(unittest.TestCase):
979 def test__all__(self):
980 support.check__all__(self, gettext,
981 not_exported={'c2py', 'ENOENT'})
982
983
984 class TranslationFallbackTestCase(unittest.TestCase):
985 def test_translation_fallback(self):
986 with os_helper.temp_cwd() as tempdir:
987 t = gettext.translation('gettext', localedir=tempdir, fallback=True)
988 self.assertIsInstance(t, gettext.NullTranslations)
989
990
991 if __name__ == '__main__':
992 unittest.main()
993
994
995 # For reference, here's the .po file used to created the GNU_MO_DATA above.
996 #
997 # The original version was automatically generated from the sources with
998 # pygettext. Later it was manually modified to add plural forms support.
999
1000 b'''
1001 # Dummy translation for the Python test_gettext.py module.
1002 # Copyright (C) 2001 Python Software Foundation
1003 # Barry Warsaw <[email protected]>, 2000.
1004 #
1005 msgid ""
1006 msgstr ""
1007 "Project-Id-Version: 2.0\n"
1008 "PO-Revision-Date: 2003-04-11 14:32-0400\n"
1009 "Last-Translator: J. David Ibanez <[email protected]>\n"
1010 "Language-Team: XX <[email protected]>\n"
1011 "MIME-Version: 1.0\n"
1012 "Content-Type: text/plain; charset=iso-8859-1\n"
1013 "Content-Transfer-Encoding: 8bit\n"
1014 "Generated-By: pygettext.py 1.1\n"
1015 "Plural-Forms: nplurals=2; plural=n!=1;\n"
1016
1017 #: test_gettext.py:19 test_gettext.py:25 test_gettext.py:31 test_gettext.py:37
1018 #: test_gettext.py:51 test_gettext.py:80 test_gettext.py:86 test_gettext.py:92
1019 #: test_gettext.py:98
1020 msgid "nudge nudge"
1021 msgstr "wink wink"
1022
1023 msgctxt "my context"
1024 msgid "nudge nudge"
1025 msgstr "wink wink (in \"my context\")"
1026
1027 msgctxt "my other context"
1028 msgid "nudge nudge"
1029 msgstr "wink wink (in \"my other context\")"
1030
1031 #: test_gettext.py:16 test_gettext.py:22 test_gettext.py:28 test_gettext.py:34
1032 #: test_gettext.py:77 test_gettext.py:83 test_gettext.py:89 test_gettext.py:95
1033 msgid "albatross"
1034 msgstr ""
1035
1036 #: test_gettext.py:18 test_gettext.py:24 test_gettext.py:30 test_gettext.py:36
1037 #: test_gettext.py:79 test_gettext.py:85 test_gettext.py:91 test_gettext.py:97
1038 msgid "Raymond Luxury Yach-t"
1039 msgstr "Throatwobbler Mangrove"
1040
1041 #: test_gettext.py:17 test_gettext.py:23 test_gettext.py:29 test_gettext.py:35
1042 #: test_gettext.py:56 test_gettext.py:78 test_gettext.py:84 test_gettext.py:90
1043 #: test_gettext.py:96
1044 msgid "mullusk"
1045 msgstr "bacon"
1046
1047 #: test_gettext.py:40 test_gettext.py:101
1048 msgid ""
1049 "This module provides internationalization and localization\n"
1050 "support for your Python programs by providing an interface to the GNU\n"
1051 "gettext message catalog library."
1052 msgstr ""
1053 "Guvf zbqhyr cebivqrf vagreangvbanyvmngvba naq ybpnyvmngvba\n"
1054 "fhccbeg sbe lbhe Clguba cebtenzf ol cebivqvat na vagresnpr gb gur TAH\n"
1055 "trggrkg zrffntr pngnybt yvoenel."
1056
1057 # Manually added, as neither pygettext nor xgettext support plural forms
1058 # in Python.
1059 msgid "There is %s file"
1060 msgid_plural "There are %s files"
1061 msgstr[0] "Hay %s fichero"
1062 msgstr[1] "Hay %s ficheros"
1063
1064 # Manually added, as neither pygettext nor xgettext support plural forms
1065 # and context in Python.
1066 msgctxt "With context"
1067 msgid "There is %s file"
1068 msgid_plural "There are %s files"
1069 msgstr[0] "Hay %s fichero (context)"
1070 msgstr[1] "Hay %s ficheros (context)"
1071 '''
1072
1073 # Here's the second example po file example, used to generate the UMO_DATA
1074 # containing utf-8 encoded Unicode strings
1075
1076 b'''
1077 # Dummy translation for the Python test_gettext.py module.
1078 # Copyright (C) 2001 Python Software Foundation
1079 # Barry Warsaw <[email protected]>, 2000.
1080 #
1081 msgid ""
1082 msgstr ""
1083 "Project-Id-Version: 2.0\n"
1084 "PO-Revision-Date: 2003-04-11 12:42-0400\n"
1085 "Last-Translator: Barry A. WArsaw <[email protected]>\n"
1086 "Language-Team: XX <[email protected]>\n"
1087 "MIME-Version: 1.0\n"
1088 "Content-Type: text/plain; charset=utf-8\n"
1089 "Content-Transfer-Encoding: 7bit\n"
1090 "Generated-By: manually\n"
1091
1092 #: nofile:0
1093 msgid "ab\xc3\x9e"
1094 msgstr "\xc2\xa4yz"
1095
1096 #: nofile:1
1097 msgctxt "mycontext\xc3\x9e"
1098 msgid "ab\xc3\x9e"
1099 msgstr "\xc2\xa4yz (context version)"
1100 '''
1101
1102 # Here's the third example po file, used to generate MMO_DATA
1103
1104 b'''
1105 msgid ""
1106 msgstr ""
1107 "Project-Id-Version: No Project 0.0\n"
1108 "POT-Creation-Date: Wed Dec 11 07:44:15 2002\n"
1109 "PO-Revision-Date: 2002-08-14 01:18:58+00:00\n"
1110 "Last-Translator: John Doe <[email protected]>\n"
1111 "Jane Foobar <[email protected]>\n"
1112 "Language-Team: xx <[email protected]>\n"
1113 "MIME-Version: 1.0\n"
1114 "Content-Type: text/plain; charset=iso-8859-15\n"
1115 "Content-Transfer-Encoding: quoted-printable\n"
1116 "Generated-By: pygettext.py 1.3\n"
1117 '''
1118
1119 #
1120 # messages.po, used for bug 17898
1121 #
1122
1123 b'''
1124 # test file for http://bugs.python.org/issue17898
1125 msgid ""
1126 msgstr ""
1127 "Plural-Forms: nplurals=2; plural=(n != 1);\n"
1128 "#-#-#-#-# messages.po (EdX Studio) #-#-#-#-#\n"
1129 "Content-Type: text/plain; charset=UTF-8\n"
1130 '''