Debian Codegraph @

lib-python/3/test/test_gettext.py

raw symbols SCIP
1 import os
2 import base64
3 import gettext
4 import unittest
5 from functools import partial
6
7 from test import support
8 from test.support import os_helper
9
10
11 # TODO:
12 # - Add new tests, for example for "dgettext"
13 # - Remove dummy tests, for example testing for single and double quotes
14 # has no sense, it would have if we were testing a parser (i.e. pygettext)
15 # - Tests should have only one assert.
16
17 GNU_MO_DATA = b'''\
18 3hIElQAAAAAJAAAAHAAAAGQAAAAAAAAArAAAAAAAAACsAAAAFQAAAK0AAAAjAAAAwwAAAKEAAADn
19 AAAAMAAAAIkBAAAHAAAAugEAABYAAADCAQAAHAAAANkBAAALAAAA9gEAAEIBAAACAgAAFgAAAEUD
20 AAAeAAAAXAMAAKEAAAB7AwAAMgAAAB0EAAAFAAAAUAQAABsAAABWBAAAIQAAAHIEAAAJAAAAlAQA
21 AABSYXltb25kIEx1eHVyeSBZYWNoLXQAVGhlcmUgaXMgJXMgZmlsZQBUaGVyZSBhcmUgJXMgZmls
22 ZXMAVGhpcyBtb2R1bGUgcHJvdmlkZXMgaW50ZXJuYXRpb25hbGl6YXRpb24gYW5kIGxvY2FsaXph
23 dGlvbgpzdXBwb3J0IGZvciB5b3VyIFB5dGhvbiBwcm9ncmFtcyBieSBwcm92aWRpbmcgYW4gaW50
24 ZXJmYWNlIHRvIHRoZSBHTlUKZ2V0dGV4dCBtZXNzYWdlIGNhdGFsb2cgbGlicmFyeS4AV2l0aCBj
25 b250ZXh0BFRoZXJlIGlzICVzIGZpbGUAVGhlcmUgYXJlICVzIGZpbGVzAG11bGx1c2sAbXkgY29u
26 dGV4dARudWRnZSBudWRnZQBteSBvdGhlciBjb250ZXh0BG51ZGdlIG51ZGdlAG51ZGdlIG51ZGdl
27 AFByb2plY3QtSWQtVmVyc2lvbjogMi4wClBPLVJldmlzaW9uLURhdGU6IDIwMDMtMDQtMTEgMTQ6
28 MzItMDQwMApMYXN0LVRyYW5zbGF0b3I6IEouIERhdmlkIEliYW5leiA8ai1kYXZpZEBub29zLmZy
29 PgpMYW5ndWFnZS1UZWFtOiBYWCA8cHl0aG9uLWRldkBweXRob24ub3JnPgpNSU1FLVZlcnNpb246
30 IDEuMApDb250ZW50LVR5cGU6IHRleHQvcGxhaW47IGNoYXJzZXQ9aXNvLTg4NTktMQpDb250ZW50
31 LVRyYW5zZmVyLUVuY29kaW5nOiA4Yml0CkdlbmVyYXRlZC1CeTogcHlnZXR0ZXh0LnB5IDEuMQpQ
32 bHVyYWwtRm9ybXM6IG5wbHVyYWxzPTI7IHBsdXJhbD1uIT0xOwoAVGhyb2F0d29iYmxlciBNYW5n
33 cm92ZQBIYXkgJXMgZmljaGVybwBIYXkgJXMgZmljaGVyb3MAR3V2ZiB6YnFoeXIgY2ViaXZxcmYg
34 dmFncmVhbmd2YmFueXZtbmd2YmEgbmFxIHlicG55dm1uZ3ZiYQpmaGNjYmVnIHNiZSBsYmhlIENs
35 Z3ViYSBjZWJ0ZW56ZiBvbCBjZWJpdnF2YXQgbmEgdmFncmVzbnByIGdiIGd1ciBUQUgKdHJnZ3Jr
36 ZyB6cmZmbnRyIHBuZ255YnQgeXZvZW5lbC4ASGF5ICVzIGZpY2hlcm8gKGNvbnRleHQpAEhheSAl
37 cyBmaWNoZXJvcyAoY29udGV4dCkAYmFjb24Ad2luayB3aW5rIChpbiAibXkgY29udGV4dCIpAHdp
38 bmsgd2luayAoaW4gIm15IG90aGVyIGNvbnRleHQiKQB3aW5rIHdpbmsA
39 '''
40
41 # This data contains an invalid major version number (5)
42 # An unexpected major version number should be treated as an error when
43 # parsing a .mo file
44
45 GNU_MO_DATA_BAD_MAJOR_VERSION = b'''\
46 3hIElQAABQAGAAAAHAAAAEwAAAALAAAAfAAAAAAAAACoAAAAFQAAAKkAAAAjAAAAvwAAAKEAAADj
47 AAAABwAAAIUBAAALAAAAjQEAAEUBAACZAQAAFgAAAN8CAAAeAAAA9gIAAKEAAAAVAwAABQAAALcD
48 AAAJAAAAvQMAAAEAAAADAAAAAAAAAAA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ncmVzbnByIGdiIGd1
62 ciBUQUgKdHJnZ3JrZyB6cmZmbnRyIHBuZ255YnQgeXZvZW5lbC4AYmFjb24Ad2luayB3aW5rAA==
63 '''
64
65 # This data contains an invalid minor version number (7)
66 # An unexpected minor version number only indicates that some of the file's
67 # contents may not be able to be read. It does not indicate an error.
68
69 GNU_MO_DATA_BAD_MINOR_VERSION = b'''\
70 3hIElQcAAAAGAAAAHAAAAEwAAAALAAAAfAAAAAAAAACoAAAAFQAAAKkAAAAjAAAAvwAAAKEAAADj
71 AAAABwAAAIUBAAALAAAAjQEAAEUBAACZAQAAFgAAAN8CAAAeAAAA9gIAAKEAAAAVAwAABQAAALcD
72 AAAJAAAAvQMAAAEAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAABQAAAAYAAAACAAAAAFJh
73 eW1vbmQgTHV4dXJ5IFlhY2gtdABUaGVyZSBpcyAlcyBmaWxlAFRoZXJlIGFyZSAlcyBmaWxlcwBU
74 aGlzIG1vZHVsZSBwcm92aWRlcyBpbnRlcm5hdGlvbmFsaXphdGlvbiBhbmQgbG9jYWxpemF0aW9u
75 CnN1cHBvcnQgZm9yIHlvdXIgUHl0aG9uIHByb2dyYW1zIGJ5IHByb3ZpZGluZyBhbiBpbnRlcmZh
76 Y2UgdG8gdGhlIEdOVQpnZXR0ZXh0IG1lc3NhZ2UgY2F0YWxvZyBsaWJyYXJ5LgBtdWxsdXNrAG51
77 ZGdlIG51ZGdlAFByb2plY3QtSWQtVmVyc2lvbjogMi4wClBPLVJldmlzaW9uLURhdGU6IDIwMDAt
78 MDgtMjkgMTI6MTktMDQ6MDAKTGFzdC1UcmFuc2xhdG9yOiBKLiBEYXZpZCBJYsOhw7FleiA8ai1k
79 YXZpZEBub29zLmZyPgpMYW5ndWFnZS1UZWFtOiBYWCA8cHl0aG9uLWRldkBweXRob24ub3JnPgpN
80 SU1FLVZlcnNpb246IDEuMApDb250ZW50LVR5cGU6IHRleHQvcGxhaW47IGNoYXJzZX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MMO_DATA = b'''\
101 3hIElQAAAAABAAAAHAAAACQAAAADAAAALAAAAAAAAAA4AAAAeAEAADkAAAABAAAAAAAAAAAAAAAA
102 UHJvamVjdC1JZC1WZXJzaW9uOiBObyBQcm9qZWN0IDAuMApQT1QtQ3JlYXRpb24tRGF0ZTogV2Vk
103 IERlYyAxMSAwNzo0NDoxNSAyMDAyClBPLVJldmlzaW9uLURhdGU6IDIwMDItMDgtMTQgMDE6MTg6
104 NTgrMDA6MDAKTGFzdC1UcmFuc2xhdG9yOiBKb2huIERvZSA8amRvZUBleGFtcGxlLmNvbT4KSmFu
105 ZSBGb29iYXIgPGpmb29iYXJAZXhhbXBsZS5jb20+Ckxhbmd1YWdlLVRlYW06IHh4IDx4eEBleGFt
106 cGxlLmNvbT4KTUlNRS1WZXJzaW9uOiAxLjAKQ29udGVudC1UeXBlOiB0ZXh0L3BsYWluOyBjaGFy
107 c2V0PWlzby04ODU5LTE1CkNvbnRlbnQtVHJhbnNmZXItRW5jb2Rpbmc6IHF1b3RlZC1wcmludGFi
108 bGUKR2VuZXJhdGVkLUJ5OiBweWdldHRleHQucHkgMS4zCgA=
109 '''
110
111 LOCALEDIR = os.path.join('xx', 'LC_MESSAGES')
112 MOFILE = os.path.join(LOCALEDIR, 'gettext.mo')
113 MOFILE_BAD_MAJOR_VERSION = os.path.join(LOCALEDIR, 'gettext_bad_major_version.mo')
114 MOFILE_BAD_MINOR_VERSION = os.path.join(LOCALEDIR, 'gettext_bad_minor_version.mo')
115 UMOFILE = os.path.join(LOCALEDIR, 'ugettext.mo')
116 MMOFILE = os.path.join(LOCALEDIR, 'metadata.mo')
117
118
119 def reset_gettext():
120 gettext._localedirs.clear()
121 gettext._current_domain = 'messages'
122 gettext._translations.clear()
123
124
125 class GettextBaseTest(unittest.TestCase):
126 @classmethod
127 def setUpClass(cls):
128 cls.addClassCleanup(os_helper.rmtree, os.path.split(LOCALEDIR)[0])
129 if not os.path.isdir(LOCALEDIR):
130 os.makedirs(LOCALEDIR)
131 with open(MOFILE, 'wb') as fp:
132 fp.write(base64.decodebytes(GNU_MO_DATA))
133 with open(MOFILE_BAD_MAJOR_VERSION, 'wb') as fp:
134 fp.write(base64.decodebytes(GNU_MO_DATA_BAD_MAJOR_VERSION))
135 with open(MOFILE_BAD_MINOR_VERSION, 'wb') as fp:
136 fp.write(base64.decodebytes(GNU_MO_DATA_BAD_MINOR_VERSION))
137 with open(UMOFILE, 'wb') as fp:
138 fp.write(base64.decodebytes(UMO_DATA))
139 with open(MMOFILE, 'wb') as fp:
140 fp.write(base64.decodebytes(MMO_DATA))
141
142 def setUp(self):
143 self.env = self.enterContext(os_helper.EnvironmentVarGuard())
144 self.env['LANGUAGE'] = 'xx'
145 reset_gettext()
146 self.addCleanup(reset_gettext)
147
148
149 GNU_MO_DATA_ISSUE_17898 = b'''\
150 3hIElQAAAAABAAAAHAAAACQAAAAAAAAAAAAAAAAAAAAsAAAAggAAAC0AAAAAUGx1cmFsLUZvcm1z
151 OiBucGx1cmFscz0yOyBwbHVyYWw9KG4gIT0gMSk7CiMtIy0jLSMtIyAgbWVzc2FnZXMucG8gKEVk
152 WCBTdHVkaW8pICAjLSMtIy0jLSMKQ29udGVudC1UeXBlOiB0ZXh0L3BsYWluOyBjaGFyc2V0PVVU
153 Ri04CgA=
154 '''
155
156 class GettextTestCase1(GettextBaseTest):
157 def setUp(self):
158 GettextBaseTest.setUp(self)
159 self.localedir = os.curdir
160 self.mofile = MOFILE
161 gettext.install('gettext', self.localedir, names=['pgettext'])
162
163 def test_some_translations(self):
164 eq = self.assertEqual
165 # test some translations
166 eq(_('albatross'), 'albatross')
167 eq(_('mullusk'), 'bacon')
168 eq(_(r'Raymond Luxury Yach-t'), 'Throatwobbler Mangrove')
169 eq(_(r'nudge nudge'), 'wink wink')
170
171 def test_some_translations_with_context(self):
172 eq = self.assertEqual
173 eq(pgettext('my context', 'nudge nudge'),
174 'wink wink (in "my context")')
175 eq(pgettext('my other context', 'nudge nudge'),
176 'wink wink (in "my other context")')
177
178 def test_double_quotes(self):
179 eq = self.assertEqual
180 # double quotes
181 eq(_("albatross"), 'albatross')
182 eq(_("mullusk"), 'bacon')
183 eq(_(r"Raymond Luxury Yach-t"), 'Throatwobbler Mangrove')
184 eq(_(r"nudge nudge"), 'wink wink')
185
186 def test_triple_single_quotes(self):
187 eq = self.assertEqual
188 # triple single quotes
189 eq(_('''albatross'''), 'albatross')
190 eq(_('''mullusk'''), 'bacon')
191 eq(_(r'''Raymond Luxury Yach-t'''), 'Throatwobbler Mangrove')
192 eq(_(r'''nudge nudge'''), 'wink wink')
193
194 def test_triple_double_quotes(self):
195 eq = self.assertEqual
196 # triple double quotes
197 eq(_("""albatross"""), 'albatross')
198 eq(_("""mullusk"""), 'bacon')
199 eq(_(r"""Raymond Luxury Yach-t"""), 'Throatwobbler Mangrove')
200 eq(_(r"""nudge nudge"""), 'wink wink')
201
202 def test_multiline_strings(self):
203 eq = self.assertEqual
204 # multiline strings
205 eq(_('''This module provides internationalization and localization
206 support for your Python programs by providing an interface to the GNU
207 gettext message catalog library.'''),
208 '''Guvf zbqhyr cebivqrf vagreangvbanyvmngvba naq ybpnyvmngvba
209 fhccbeg sbe lbhe Clguba cebtenzf ol cebivqvat na vagresnpr gb gur TAH
210 trggrkg zrffntr pngnybt yvoenel.''')
211
212 def test_the_alternative_interface(self):
213 eq = self.assertEqual
214 neq = self.assertNotEqual
215 # test the alternative interface
216 with open(self.mofile, 'rb') as fp:
217 t = gettext.GNUTranslations(fp)
218 # Install the translation object
219 t.install()
220 eq(_('nudge nudge'), 'wink wink')
221 # Try unicode return type
222 t.install()
223 eq(_('mullusk'), 'bacon')
224 # Test installation of other methods
225 import builtins
226 t.install(names=["gettext", "ngettext"])
227 eq(_, t.gettext)
228 eq(builtins.gettext, t.gettext)
229 eq(ngettext, t.ngettext)
230 neq(pgettext, t.pgettext)
231 del builtins.gettext
232 del builtins.ngettext
233
234
235 class GettextTestCase2(GettextBaseTest):
236 def setUp(self):
237 GettextBaseTest.setUp(self)
238 self.localedir = os.curdir
239 # Set up the bindings
240 gettext.bindtextdomain('gettext', self.localedir)
241 gettext.textdomain('gettext')
242 # For convenience
243 self._ = gettext.gettext
244
245 def test_bindtextdomain(self):
246 self.assertEqual(gettext.bindtextdomain('gettext'), self.localedir)
247
248 def test_textdomain(self):
249 self.assertEqual(gettext.textdomain(), 'gettext')
250
251 def test_bad_major_version(self):
252 with open(MOFILE_BAD_MAJOR_VERSION, 'rb') as fp:
253 with self.assertRaises(OSError) as cm:
254 gettext.GNUTranslations(fp)
255
256 exception = cm.exception
257 self.assertEqual(exception.errno, 0)
258 self.assertEqual(exception.strerror, "Bad version number 5")
259 self.assertEqual(exception.filename, MOFILE_BAD_MAJOR_VERSION)
260
261 def test_bad_minor_version(self):
262 with open(MOFILE_BAD_MINOR_VERSION, 'rb') as fp:
263 # Check that no error is thrown with a bad minor version number
264 gettext.GNUTranslations(fp)
265
266 def test_some_translations(self):
267 eq = self.assertEqual
268 # test some translations
269 eq(self._('albatross'), 'albatross')
270 eq(self._('mullusk'), 'bacon')
271 eq(self._(r'Raymond Luxury Yach-t'), 'Throatwobbler Mangrove')
272 eq(self._(r'nudge nudge'), 'wink wink')
273
274 def test_some_translations_with_context(self):
275 eq = self.assertEqual
276 eq(gettext.pgettext('my context', 'nudge nudge'),
277 'wink wink (in "my context")')
278 eq(gettext.pgettext('my other context', 'nudge nudge'),
279 'wink wink (in "my other context")')
280
281 def test_some_translations_with_context_and_domain(self):
282 eq = self.assertEqual
283 eq(gettext.dpgettext('gettext', 'my context', 'nudge nudge'),
284 'wink wink (in "my context")')
285 eq(gettext.dpgettext('gettext', 'my other context', 'nudge nudge'),
286 'wink wink (in "my other context")')
287
288 def test_double_quotes(self):
289 eq = self.assertEqual
290 # double quotes
291 eq(self._("albatross"), 'albatross')
292 eq(self._("mullusk"), 'bacon')
293 eq(self._(r"Raymond Luxury Yach-t"), 'Throatwobbler Mangrove')
294 eq(self._(r"nudge nudge"), 'wink wink')
295
296 def test_triple_single_quotes(self):
297 eq = self.assertEqual
298 # triple single quotes
299 eq(self._('''albatross'''), 'albatross')
300 eq(self._('''mullusk'''), 'bacon')
301 eq(self._(r'''Raymond Luxury Yach-t'''), 'Throatwobbler Mangrove')
302 eq(self._(r'''nudge nudge'''), 'wink wink')
303
304 def test_triple_double_quotes(self):
305 eq = self.assertEqual
306 # triple double quotes
307 eq(self._("""albatross"""), 'albatross')
308 eq(self._("""mullusk"""), 'bacon')
309 eq(self._(r"""Raymond Luxury Yach-t"""), 'Throatwobbler Mangrove')
310 eq(self._(r"""nudge nudge"""), 'wink wink')
311
312 def test_multiline_strings(self):
313 eq = self.assertEqual
314 # multiline strings
315 eq(self._('''This module provides internationalization and localization
316 support for your Python programs by providing an interface to the GNU
317 gettext message catalog library.'''),
318 '''Guvf zbqhyr cebivqrf vagreangvbanyvmngvba naq ybpnyvmngvba
319 fhccbeg sbe lbhe Clguba cebtenzf ol cebivqvat na vagresnpr gb gur TAH
320 trggrkg zrffntr pngnybt yvoenel.''')
321
322
323 class PluralFormsTests:
324
325 def _test_plural_forms(self, ngettext, gettext,
326 singular, plural, tsingular, tplural,
327 numbers_only=True):
328 x = ngettext(singular, plural, 1)
329 self.assertEqual(x, tsingular)
330 x = ngettext(singular, plural, 2)
331 self.assertEqual(x, tplural)
332 x = gettext(singular)
333 self.assertEqual(x, tsingular)
334
335 if numbers_only:
336 lineno = self._test_plural_forms.__code__.co_firstlineno + 9
337 with self.assertWarns(DeprecationWarning) as cm:
338 x = ngettext(singular, plural, 1.0)
339 self.assertEqual(cm.filename, __file__)
340 self.assertEqual(cm.lineno, lineno + 4)
341 self.assertEqual(x, tsingular)
342 with self.assertWarns(DeprecationWarning) as cm:
343 x = ngettext(singular, plural, 1.1)
344 self.assertEqual(cm.filename, __file__)
345 self.assertEqual(cm.lineno, lineno + 9)
346 self.assertEqual(x, tplural)
347 with self.assertRaises(TypeError):
348 ngettext(singular, plural, None)
349 else:
350 x = ngettext(singular, plural, None)
351 self.assertEqual(x, tplural)
352
353 def test_plural_forms(self):
354 self._test_plural_forms(
355 self.ngettext, self.gettext,
356 'There is %s file', 'There are %s files',
357 'Hay %s fichero', 'Hay %s ficheros')
358 self._test_plural_forms(
359 self.ngettext, self.gettext,
360 '%d file deleted', '%d files deleted',
361 '%d file deleted', '%d files deleted')
362
363 def test_plural_context_forms(self):
364 ngettext = partial(self.npgettext, 'With context')
365 gettext = partial(self.pgettext, 'With context')
366 self._test_plural_forms(
367 ngettext, gettext,
368 'There is %s file', 'There are %s files',
369 'Hay %s fichero (context)', 'Hay %s ficheros (context)')
370 self._test_plural_forms(
371 ngettext, gettext,
372 '%d file deleted', '%d files deleted',
373 '%d file deleted', '%d files deleted')
374
375 def test_plural_wrong_context_forms(self):
376 self._test_plural_forms(
377 partial(self.npgettext, 'Unknown context'),
378 partial(self.pgettext, 'Unknown context'),
379 'There is %s file', 'There are %s files',
380 'There is %s file', 'There are %s files')
381
382
383 class GNUTranslationsPluralFormsTestCase(PluralFormsTests, GettextBaseTest):
384 def setUp(self):
385 GettextBaseTest.setUp(self)
386 # Set up the bindings
387 gettext.bindtextdomain('gettext', os.curdir)
388 gettext.textdomain('gettext')
389
390 self.gettext = gettext.gettext
391 self.ngettext = gettext.ngettext
392 self.pgettext = gettext.pgettext
393 self.npgettext = gettext.npgettext
394
395
396 class GNUTranslationsWithDomainPluralFormsTestCase(PluralFormsTests, GettextBaseTest):
397 def setUp(self):
398 GettextBaseTest.setUp(self)
399 # Set up the bindings
400 gettext.bindtextdomain('gettext', os.curdir)
401
402 self.gettext = partial(gettext.dgettext, 'gettext')
403 self.ngettext = partial(gettext.dngettext, 'gettext')
404 self.pgettext = partial(gettext.dpgettext, 'gettext')
405 self.npgettext = partial(gettext.dnpgettext, 'gettext')
406
407 def test_plural_forms_wrong_domain(self):
408 self._test_plural_forms(
409 partial(gettext.dngettext, 'unknown'),
410 partial(gettext.dgettext, 'unknown'),
411 'There is %s file', 'There are %s files',
412 'There is %s file', 'There are %s files',
413 numbers_only=False)
414
415 def test_plural_context_forms_wrong_domain(self):
416 self._test_plural_forms(
417 partial(gettext.dnpgettext, 'unknown', 'With context'),
418 partial(gettext.dpgettext, 'unknown', 'With context'),
419 'There is %s file', 'There are %s files',
420 'There is %s file', 'There are %s files',
421 numbers_only=False)
422
423
424 class GNUTranslationsClassPluralFormsTestCase(PluralFormsTests, GettextBaseTest):
425 def setUp(self):
426 GettextBaseTest.setUp(self)
427 with open(MOFILE, 'rb') as fp:
428 t = gettext.GNUTranslations(fp)
429
430 self.gettext = t.gettext
431 self.ngettext = t.ngettext
432 self.pgettext = t.pgettext
433 self.npgettext = t.npgettext
434
435 def test_plural_forms_null_translations(self):
436 t = gettext.NullTranslations()
437 self._test_plural_forms(
438 t.ngettext, t.gettext,
439 'There is %s file', 'There are %s files',
440 'There is %s file', 'There are %s files',
441 numbers_only=False)
442
443 def test_plural_context_forms_null_translations(self):
444 t = gettext.NullTranslations()
445 self._test_plural_forms(
446 partial(t.npgettext, 'With context'),
447 partial(t.pgettext, 'With context'),
448 'There is %s file', 'There are %s files',
449 'There is %s file', 'There are %s files',
450 numbers_only=False)
451
452
453 class PluralFormsInternalTestCase:
454 # Examples from http://www.gnu.org/software/gettext/manual/gettext.html
455
456 def test_ja(self):
457 eq = self.assertEqual
458 f = gettext.c2py('0')
459 s = ''.join([ str(f(x)) for x in range(200) ])
460 eq(s, "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000")
461
462 def test_de(self):
463 eq = self.assertEqual
464 f = gettext.c2py('n != 1')
465 s = ''.join([ str(f(x)) for x in range(200) ])
466 eq(s, "10111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111")
467
468 def test_fr(self):
469 eq = self.assertEqual
470 f = gettext.c2py('n>1')
471 s = ''.join([ str(f(x)) for x in range(200) ])
472 eq(s, "00111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111")
473
474 def test_lv(self):
475 eq = self.assertEqual
476 f = gettext.c2py('n%10==1 && n%100!=11 ? 0 : n != 0 ? 1 : 2')
477 s = ''.join([ str(f(x)) for x in range(200) ])
478 eq(s, "20111111111111111111101111111110111111111011111111101111111110111111111011111111101111111110111111111011111111111111111110111111111011111111101111111110111111111011111111101111111110111111111011111111")
479
480 def test_gd(self):
481 eq = self.assertEqual
482 f = gettext.c2py('n==1 ? 0 : n==2 ? 1 : 2')
483 s = ''.join([ str(f(x)) for x in range(200) ])
484 eq(s, "20122222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222")
485
486 def test_gd2(self):
487 eq = self.assertEqual
488 # Tests the combination of parentheses and "?:"
489 f = gettext.c2py('n==1 ? 0 : (n==2 ? 1 : 2)')
490 s = ''.join([ str(f(x)) for x in range(200) ])
491 eq(s, "20122222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222")
492
493 def test_ro(self):
494 eq = self.assertEqual
495 f = gettext.c2py('n==1 ? 0 : (n==0 || (n%100 > 0 && n%100 < 20)) ? 1 : 2')
496 s = ''.join([ str(f(x)) for x in range(200) ])
497 eq(s, "10111111111111111111222222222222222222222222222222222222222222222222222222222222222222222222222222222111111111111111111122222222222222222222222222222222222222222222222222222222222222222222222222222222")
498
499 def test_lt(self):
500 eq = self.assertEqual
501 f = gettext.c2py('n%10==1 && n%100!=11 ? 0 : n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2')
502 s = ''.join([ str(f(x)) for x in range(200) ])
503 eq(s, "20111111112222222222201111111120111111112011111111201111111120111111112011111111201111111120111111112011111111222222222220111111112011111111201111111120111111112011111111201111111120111111112011111111")
504
505 def test_ru(self):
506 eq = self.assertEqual
507 f = gettext.c2py('n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2')
508 s = ''.join([ str(f(x)) for x in range(200) ])
509 eq(s, "20111222222222222222201112222220111222222011122222201112222220111222222011122222201112222220111222222011122222222222222220111222222011122222201112222220111222222011122222201112222220111222222011122222")
510
511 def test_cs(self):
512 eq = self.assertEqual
513 f = gettext.c2py('(n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2')
514 s = ''.join([ str(f(x)) for x in range(200) ])
515 eq(s, "20111222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222")
516
517 def test_pl(self):
518 eq = self.assertEqual
519 f = gettext.c2py('n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2')
520 s = ''.join([ str(f(x)) for x in range(200) ])
521 eq(s, "20111222222222222222221112222222111222222211122222221112222222111222222211122222221112222222111222222211122222222222222222111222222211122222221112222222111222222211122222221112222222111222222211122222")
522
523 def test_sl(self):
524 eq = self.assertEqual
525 f = gettext.c2py('n%100==1 ? 0 : n%100==2 ? 1 : n%100==3 || n%100==4 ? 2 : 3')
526 s = ''.join([ str(f(x)) for x in range(200) ])
527 eq(s, "30122333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333012233333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333")
528
529 def test_ar(self):
530 eq = self.assertEqual
531 f = gettext.c2py('n==0 ? 0 : n==1 ? 1 : n==2 ? 2 : n%100>=3 && n%100<=10 ? 3 : n%100>=11 ? 4 : 5')
532 s = ''.join([ str(f(x)) for x in range(200) ])
533 eq(s, "01233333333444444444444444444444444444444444444444444444444444444444444444444444444444444444444444445553333333344444444444444444444444444444444444444444444444444444444444444444444444444444444444444444")
534
535 def test_security(self):
536 raises = self.assertRaises
537 # Test for a dangerous expression
538 raises(ValueError, gettext.c2py, "os.chmod('/etc/passwd',0777)")
539 # issue28563
540 raises(ValueError, gettext.c2py, '"(eval(foo) && ""')
541 raises(ValueError, gettext.c2py, 'f"{os.system(\'sh\')}"')
542 # Maximum recursion depth exceeded during compilation
543 raises(ValueError, gettext.c2py, 'n+'*10000 + 'n')
544 self.assertEqual(gettext.c2py('n+'*100 + 'n')(1), 101)
545 # MemoryError during compilation
546 raises(ValueError, gettext.c2py, '('*100 + 'n' + ')'*100)
547 # Maximum recursion depth exceeded in C to Python translator
548 raises(ValueError, gettext.c2py, '('*10000 + 'n' + ')'*10000)
549 self.assertEqual(gettext.c2py('('*20 + 'n' + ')'*20)(1), 1)
550
551 def test_chained_comparison(self):
552 # C doesn't chain comparison as Python so 2 == 2 == 2 gets different results
553 f = gettext.c2py('n == n == n')
554 self.assertEqual(''.join(str(f(x)) for x in range(3)), '010')
555 f = gettext.c2py('1 < n == n')
556 self.assertEqual(''.join(str(f(x)) for x in range(3)), '100')
557 f = gettext.c2py('n == n < 2')
558 self.assertEqual(''.join(str(f(x)) for x in range(3)), '010')
559 f = gettext.c2py('0 < n < 2')
560 self.assertEqual(''.join(str(f(x)) for x in range(3)), '111')
561
562 def test_decimal_number(self):
563 self.assertEqual(gettext.c2py('0123')(1), 123)
564
565 def test_invalid_syntax(self):
566 invalid_expressions = [
567 'x>1', '(n>1', 'n>1)', '42**42**42', '0xa', '1.0', '1e2',
568 'n>0x1', '+n', '-n', 'n()', 'n(1)', '1+', 'nn', 'n n',
569 ]
570 for expr in invalid_expressions:
571 with self.assertRaises(ValueError):
572 gettext.c2py(expr)
573
574 def test_nested_condition_operator(self):
575 self.assertEqual(gettext.c2py('n?1?2:3:4')(0), 4)
576 self.assertEqual(gettext.c2py('n?1?2:3:4')(1), 2)
577 self.assertEqual(gettext.c2py('n?1:3?4:5')(0), 4)
578 self.assertEqual(gettext.c2py('n?1:3?4:5')(1), 1)
579
580 def test_division(self):
581 f = gettext.c2py('2/n*3')
582 self.assertEqual(f(1), 6)
583 self.assertEqual(f(2), 3)
584 self.assertEqual(f(3), 0)
585 self.assertEqual(f(-1), -6)
586 self.assertRaises(ZeroDivisionError, f, 0)
587
588 def test_plural_number(self):
589 f = gettext.c2py('n != 1')
590 self.assertEqual(f(1), 0)
591 self.assertEqual(f(2), 1)
592 with self.assertWarns(DeprecationWarning):
593 self.assertEqual(f(1.0), 0)
594 with self.assertWarns(DeprecationWarning):
595 self.assertEqual(f(2.0), 1)
596 with self.assertWarns(DeprecationWarning):
597 self.assertEqual(f(1.1), 1)
598 self.assertRaises(TypeError, f, '2')
599 self.assertRaises(TypeError, f, b'2')
600 self.assertRaises(TypeError, f, [])
601 self.assertRaises(TypeError, f, object())
602
603
604 class GNUTranslationParsingTest(GettextBaseTest):
605 def test_plural_form_error_issue17898(self):
606 with open(MOFILE, 'wb') as fp:
607 fp.write(base64.decodebytes(GNU_MO_DATA_ISSUE_17898))
608 with open(MOFILE, 'rb') as fp:
609 # If this runs cleanly, the bug is fixed.
610 t = gettext.GNUTranslations(fp)
611
612 def test_ignore_comments_in_headers_issue36239(self):
613 """Checks that comments like:
614
615 #-#-#-#-# messages.po (EdX Studio) #-#-#-#-#
616
617 are ignored.
618 """
619 with open(MOFILE, 'wb') as fp:
620 fp.write(base64.decodebytes(GNU_MO_DATA_ISSUE_17898))
621 with open(MOFILE, 'rb') as fp:
622 t = gettext.GNUTranslations(fp)
623 self.assertEqual(t.info()["plural-forms"], "nplurals=2; plural=(n != 1);")
624
625
626 class UnicodeTranslationsTest(GettextBaseTest):
627 def setUp(self):
628 GettextBaseTest.setUp(self)
629 with open(UMOFILE, 'rb') as fp:
630 self.t = gettext.GNUTranslations(fp)
631 self._ = self.t.gettext
632 self.pgettext = self.t.pgettext
633
634 def test_unicode_msgid(self):
635 self.assertIsInstance(self._(''), str)
636
637 def test_unicode_msgstr(self):
638 self.assertEqual(self._('ab\xde'), '\xa4yz')
639
640 def test_unicode_context_msgstr(self):
641 t = self.pgettext('mycontext\xde', 'ab\xde')
642 self.assertTrue(isinstance(t, str))
643 self.assertEqual(t, '\xa4yz (context version)')
644
645
646 class UnicodeTranslationsPluralTest(GettextBaseTest):
647 def setUp(self):
648 GettextBaseTest.setUp(self)
649 with open(MOFILE, 'rb') as fp:
650 self.t = gettext.GNUTranslations(fp)
651 self.ngettext = self.t.ngettext
652 self.npgettext = self.t.npgettext
653
654 def test_unicode_msgid(self):
655 unless = self.assertTrue
656 unless(isinstance(self.ngettext('', '', 1), str))
657 unless(isinstance(self.ngettext('', '', 2), str))
658
659 def test_unicode_context_msgid(self):
660 unless = self.assertTrue
661 unless(isinstance(self.npgettext('', '', '', 1), str))
662 unless(isinstance(self.npgettext('', '', '', 2), str))
663
664 def test_unicode_msgstr(self):
665 eq = self.assertEqual
666 unless = self.assertTrue
667 t = self.ngettext("There is %s file", "There are %s files", 1)
668 unless(isinstance(t, str))
669 eq(t, "Hay %s fichero")
670 unless(isinstance(t, str))
671 t = self.ngettext("There is %s file", "There are %s files", 5)
672 unless(isinstance(t, str))
673 eq(t, "Hay %s ficheros")
674
675 def test_unicode_msgstr_with_context(self):
676 eq = self.assertEqual
677 unless = self.assertTrue
678 t = self.npgettext("With context",
679 "There is %s file", "There are %s files", 1)
680 unless(isinstance(t, str))
681 eq(t, "Hay %s fichero (context)")
682 t = self.npgettext("With context",
683 "There is %s file", "There are %s files", 5)
684 unless(isinstance(t, str))
685 eq(t, "Hay %s ficheros (context)")
686
687
688 class WeirdMetadataTest(GettextBaseTest):
689 def setUp(self):
690 GettextBaseTest.setUp(self)
691 with open(MMOFILE, 'rb') as fp:
692 try:
693 self.t = gettext.GNUTranslations(fp)
694 except:
695 self.tearDown()
696 raise
697
698 def test_weird_metadata(self):
699 info = self.t.info()
700 self.assertEqual(len(info), 9)
701 self.assertEqual(info['last-translator'],
702 'John Doe <[email protected]>\nJane Foobar <[email protected]>')
703
704
705 class DummyGNUTranslations(gettext.GNUTranslations):
706 def foo(self):
707 return 'foo'
708
709
710 class GettextCacheTestCase(GettextBaseTest):
711 def test_cache(self):
712 self.localedir = os.curdir
713 self.mofile = MOFILE
714
715 self.assertEqual(len(gettext._translations), 0)
716
717 t = gettext.translation('gettext', self.localedir)
718
719 self.assertEqual(len(gettext._translations), 1)
720
721 t = gettext.translation('gettext', self.localedir,
722 class_=DummyGNUTranslations)
723
724 self.assertEqual(len(gettext._translations), 2)
725 self.assertEqual(t.__class__, DummyGNUTranslations)
726
727 # Calling it again doesn't add to the cache
728
729 t = gettext.translation('gettext', self.localedir,
730 class_=DummyGNUTranslations)
731
732 self.assertEqual(len(gettext._translations), 2)
733 self.assertEqual(t.__class__, DummyGNUTranslations)
734
735
736 class MiscTestCase(unittest.TestCase):
737 def test__all__(self):
738 support.check__all__(self, gettext,
739 not_exported={'c2py', 'ENOENT'})
740
741
742 if __name__ == '__main__':
743 unittest.main()
744
745
746 # For reference, here's the .po file used to created the GNU_MO_DATA above.
747 #
748 # The original version was automatically generated from the sources with
749 # pygettext. Later it was manually modified to add plural forms support.
750
751 b'''
752 # Dummy translation for the Python test_gettext.py module.
753 # Copyright (C) 2001 Python Software Foundation
754 # Barry Warsaw <[email protected]>, 2000.
755 #
756 msgid ""
757 msgstr ""
758 "Project-Id-Version: 2.0\n"
759 "PO-Revision-Date: 2003-04-11 14:32-0400\n"
760 "Last-Translator: J. David Ibanez <[email protected]>\n"
761 "Language-Team: XX <[email protected]>\n"
762 "MIME-Version: 1.0\n"
763 "Content-Type: text/plain; charset=iso-8859-1\n"
764 "Content-Transfer-Encoding: 8bit\n"
765 "Generated-By: pygettext.py 1.1\n"
766 "Plural-Forms: nplurals=2; plural=n!=1;\n"
767
768 #: test_gettext.py:19 test_gettext.py:25 test_gettext.py:31 test_gettext.py:37
769 #: test_gettext.py:51 test_gettext.py:80 test_gettext.py:86 test_gettext.py:92
770 #: test_gettext.py:98
771 msgid "nudge nudge"
772 msgstr "wink wink"
773
774 msgctxt "my context"
775 msgid "nudge nudge"
776 msgstr "wink wink (in \"my context\")"
777
778 msgctxt "my other context"
779 msgid "nudge nudge"
780 msgstr "wink wink (in \"my other context\")"
781
782 #: test_gettext.py:16 test_gettext.py:22 test_gettext.py:28 test_gettext.py:34
783 #: test_gettext.py:77 test_gettext.py:83 test_gettext.py:89 test_gettext.py:95
784 msgid "albatross"
785 msgstr ""
786
787 #: test_gettext.py:18 test_gettext.py:24 test_gettext.py:30 test_gettext.py:36
788 #: test_gettext.py:79 test_gettext.py:85 test_gettext.py:91 test_gettext.py:97
789 msgid "Raymond Luxury Yach-t"
790 msgstr "Throatwobbler Mangrove"
791
792 #: test_gettext.py:17 test_gettext.py:23 test_gettext.py:29 test_gettext.py:35
793 #: test_gettext.py:56 test_gettext.py:78 test_gettext.py:84 test_gettext.py:90
794 #: test_gettext.py:96
795 msgid "mullusk"
796 msgstr "bacon"
797
798 #: test_gettext.py:40 test_gettext.py:101
799 msgid ""
800 "This module provides internationalization and localization\n"
801 "support for your Python programs by providing an interface to the GNU\n"
802 "gettext message catalog library."
803 msgstr ""
804 "Guvf zbqhyr cebivqrf vagreangvbanyvmngvba naq ybpnyvmngvba\n"
805 "fhccbeg sbe lbhe Clguba cebtenzf ol cebivqvat na vagresnpr gb gur TAH\n"
806 "trggrkg zrffntr pngnybt yvoenel."
807
808 # Manually added, as neither pygettext nor xgettext support plural forms
809 # in Python.
810 msgid "There is %s file"
811 msgid_plural "There are %s files"
812 msgstr[0] "Hay %s fichero"
813 msgstr[1] "Hay %s ficheros"
814
815 # Manually added, as neither pygettext nor xgettext support plural forms
816 # and context in Python.
817 msgctxt "With context"
818 msgid "There is %s file"
819 msgid_plural "There are %s files"
820 msgstr[0] "Hay %s fichero (context)"
821 msgstr[1] "Hay %s ficheros (context)"
822 '''
823
824 # Here's the second example po file example, used to generate the UMO_DATA
825 # containing utf-8 encoded Unicode strings
826
827 b'''
828 # Dummy translation for the Python test_gettext.py module.
829 # Copyright (C) 2001 Python Software Foundation
830 # Barry Warsaw <[email protected]>, 2000.
831 #
832 msgid ""
833 msgstr ""
834 "Project-Id-Version: 2.0\n"
835 "PO-Revision-Date: 2003-04-11 12:42-0400\n"
836 "Last-Translator: Barry A. WArsaw <[email protected]>\n"
837 "Language-Team: XX <[email protected]>\n"
838 "MIME-Version: 1.0\n"
839 "Content-Type: text/plain; charset=utf-8\n"
840 "Content-Transfer-Encoding: 7bit\n"
841 "Generated-By: manually\n"
842
843 #: nofile:0
844 msgid "ab\xc3\x9e"
845 msgstr "\xc2\xa4yz"
846
847 #: nofile:1
848 msgctxt "mycontext\xc3\x9e"
849 msgid "ab\xc3\x9e"
850 msgstr "\xc2\xa4yz (context version)"
851 '''
852
853 # Here's the third example po file, used to generate MMO_DATA
854
855 b'''
856 msgid ""
857 msgstr ""
858 "Project-Id-Version: No Project 0.0\n"
859 "POT-Creation-Date: Wed Dec 11 07:44:15 2002\n"
860 "PO-Revision-Date: 2002-08-14 01:18:58+00:00\n"
861 "Last-Translator: John Doe <[email protected]>\n"
862 "Jane Foobar <[email protected]>\n"
863 "Language-Team: xx <[email protected]>\n"
864 "MIME-Version: 1.0\n"
865 "Content-Type: text/plain; charset=iso-8859-15\n"
866 "Content-Transfer-Encoding: quoted-printable\n"
867 "Generated-By: pygettext.py 1.3\n"
868 '''
869
870 #
871 # messages.po, used for bug 17898
872 #
873
874 b'''
875 # test file for http://bugs.python.org/issue17898
876 msgid ""
877 msgstr ""
878 "Plural-Forms: nplurals=2; plural=(n != 1);\n"
879 "#-#-#-#-# messages.po (EdX Studio) #-#-#-#-#\n"
880 "Content-Type: text/plain; charset=UTF-8\n"
881 '''