extraction.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. # -*- encoding: utf-8 -*-
  2. from __future__ import unicode_literals
  3. import os
  4. import re
  5. import shutil
  6. import warnings
  7. from django.core import management
  8. from django.test import SimpleTestCase
  9. from django.utils.encoding import force_text
  10. from django.utils._os import upath
  11. from django.utils import six
  12. from django.utils.six import StringIO
  13. from django.utils.translation import TranslatorCommentWarning
  14. LOCALE='de'
  15. class ExtractorTests(SimpleTestCase):
  16. PO_FILE='locale/%s/LC_MESSAGES/django.po' % LOCALE
  17. def setUp(self):
  18. self._cwd = os.getcwd()
  19. self.test_dir = os.path.abspath(os.path.dirname(upath(__file__)))
  20. def _rmrf(self, dname):
  21. if os.path.commonprefix([self.test_dir, os.path.abspath(dname)]) != self.test_dir:
  22. return
  23. shutil.rmtree(dname)
  24. def tearDown(self):
  25. os.chdir(self.test_dir)
  26. try:
  27. self._rmrf('locale/%s' % LOCALE)
  28. except OSError:
  29. pass
  30. os.chdir(self._cwd)
  31. def assertMsgId(self, msgid, s, use_quotes=True):
  32. q = '"'
  33. if use_quotes:
  34. msgid = '"%s"' % msgid
  35. q = "'"
  36. needle = 'msgid %s' % msgid
  37. msgid = re.escape(msgid)
  38. return self.assertTrue(re.search('^msgid %s' % msgid, s, re.MULTILINE), 'Could not find %(q)s%(n)s%(q)s in generated PO file' % {'n':needle, 'q':q})
  39. def assertNotMsgId(self, msgid, s, use_quotes=True):
  40. if use_quotes:
  41. msgid = '"%s"' % msgid
  42. msgid = re.escape(msgid)
  43. return self.assertTrue(not re.search('^msgid %s' % msgid, s, re.MULTILINE))
  44. class BasicExtractorTests(ExtractorTests):
  45. def test_comments_extractor(self):
  46. os.chdir(self.test_dir)
  47. management.call_command('makemessages', locale=LOCALE, verbosity=0)
  48. self.assertTrue(os.path.exists(self.PO_FILE))
  49. with open(self.PO_FILE, 'r') as fp:
  50. po_contents = force_text(fp.read())
  51. self.assertTrue('#. Translators: This comment should be extracted' in po_contents)
  52. self.assertTrue('This comment should not be extracted' not in po_contents)
  53. # Comments in templates
  54. self.assertTrue('#. Translators: Django template comment for translators' in po_contents)
  55. self.assertTrue("#. Translators: Django comment block for translators\n#. string's meaning unveiled" in po_contents)
  56. self.assertTrue('#. Translators: One-line translator comment #1' in po_contents)
  57. self.assertTrue('#. Translators: Two-line translator comment #1\n#. continued here.' in po_contents)
  58. self.assertTrue('#. Translators: One-line translator comment #2' in po_contents)
  59. self.assertTrue('#. Translators: Two-line translator comment #2\n#. continued here.' in po_contents)
  60. self.assertTrue('#. Translators: One-line translator comment #3' in po_contents)
  61. self.assertTrue('#. Translators: Two-line translator comment #3\n#. continued here.' in po_contents)
  62. self.assertTrue('#. Translators: One-line translator comment #4' in po_contents)
  63. self.assertTrue('#. Translators: Two-line translator comment #4\n#. continued here.' in po_contents)
  64. self.assertTrue('#. Translators: One-line translator comment #5 -- with non ASCII characters: áéíóúö' in po_contents)
  65. self.assertTrue('#. Translators: Two-line translator comment #5 -- with non ASCII characters: áéíóúö\n#. continued here.' in po_contents)
  66. def test_templatize_trans_tag(self):
  67. # ticket #11240
  68. os.chdir(self.test_dir)
  69. management.call_command('makemessages', locale=LOCALE, verbosity=0)
  70. self.assertTrue(os.path.exists(self.PO_FILE))
  71. with open(self.PO_FILE, 'r') as fp:
  72. po_contents = force_text(fp.read())
  73. self.assertMsgId('Literal with a percent symbol at the end %%', po_contents)
  74. self.assertMsgId('Literal with a percent %% symbol in the middle', po_contents)
  75. self.assertMsgId('Completed 50%% of all the tasks', po_contents)
  76. self.assertMsgId('Completed 99%% of all the tasks', po_contents)
  77. self.assertMsgId("Shouldn't double escape this sequence: %% (two percent signs)", po_contents)
  78. self.assertMsgId("Shouldn't double escape this sequence %% either", po_contents)
  79. self.assertMsgId("Looks like a str fmt spec %%s but shouldn't be interpreted as such", po_contents)
  80. self.assertMsgId("Looks like a str fmt spec %% o but shouldn't be interpreted as such", po_contents)
  81. def test_templatize_blocktrans_tag(self):
  82. # ticket #11966
  83. os.chdir(self.test_dir)
  84. management.call_command('makemessages', locale=LOCALE, verbosity=0)
  85. self.assertTrue(os.path.exists(self.PO_FILE))
  86. with open(self.PO_FILE, 'r') as fp:
  87. po_contents = force_text(fp.read())
  88. self.assertMsgId('I think that 100%% is more that 50%% of anything.', po_contents)
  89. self.assertMsgId('I think that 100%% is more that 50%% of %(obj)s.', po_contents)
  90. self.assertMsgId("Blocktrans extraction shouldn't double escape this: %%, a=%(a)s", po_contents)
  91. def test_extraction_error(self):
  92. os.chdir(self.test_dir)
  93. self.assertRaises(SyntaxError, management.call_command, 'makemessages', locale=LOCALE, extensions=['tpl'], verbosity=0)
  94. with self.assertRaises(SyntaxError) as context_manager:
  95. management.call_command('makemessages', locale=LOCALE, extensions=['tpl'], verbosity=0)
  96. six.assertRegex(self, str(context_manager.exception),
  97. r'Translation blocks must not include other block tags: blocktrans \(file templates[/\\]template_with_error\.tpl, line 3\)'
  98. )
  99. # Check that the temporary file was cleaned up
  100. self.assertFalse(os.path.exists('./templates/template_with_error.tpl.py'))
  101. def test_extraction_warning(self):
  102. """test xgettext warning about multiple bare interpolation placeholders"""
  103. os.chdir(self.test_dir)
  104. shutil.copyfile('./code.sample', './code_sample.py')
  105. stdout = StringIO()
  106. management.call_command('makemessages', locale=LOCALE, stdout=stdout)
  107. os.remove('./code_sample.py')
  108. self.assertIn("code_sample.py:4", force_text(stdout.getvalue()))
  109. def test_template_message_context_extractor(self):
  110. """
  111. Ensure that message contexts are correctly extracted for the
  112. {% trans %} and {% blocktrans %} template tags.
  113. Refs #14806.
  114. """
  115. os.chdir(self.test_dir)
  116. management.call_command('makemessages', locale=LOCALE, verbosity=0)
  117. self.assertTrue(os.path.exists(self.PO_FILE))
  118. with open(self.PO_FILE, 'r') as fp:
  119. po_contents = force_text(fp.read())
  120. # {% trans %}
  121. self.assertTrue('msgctxt "Special trans context #1"' in po_contents)
  122. self.assertMsgId("Translatable literal #7a", po_contents)
  123. self.assertTrue('msgctxt "Special trans context #2"' in po_contents)
  124. self.assertMsgId("Translatable literal #7b", po_contents)
  125. self.assertTrue('msgctxt "Special trans context #3"' in po_contents)
  126. self.assertMsgId("Translatable literal #7c", po_contents)
  127. # {% blocktrans %}
  128. self.assertTrue('msgctxt "Special blocktrans context #1"' in po_contents)
  129. self.assertMsgId("Translatable literal #8a", po_contents)
  130. self.assertTrue('msgctxt "Special blocktrans context #2"' in po_contents)
  131. self.assertMsgId("Translatable literal #8b-singular", po_contents)
  132. self.assertTrue("Translatable literal #8b-plural" in po_contents)
  133. self.assertTrue('msgctxt "Special blocktrans context #3"' in po_contents)
  134. self.assertMsgId("Translatable literal #8c-singular", po_contents)
  135. self.assertTrue("Translatable literal #8c-plural" in po_contents)
  136. self.assertTrue('msgctxt "Special blocktrans context #4"' in po_contents)
  137. self.assertMsgId("Translatable literal #8d %(a)s", po_contents)
  138. def test_context_in_single_quotes(self):
  139. os.chdir(self.test_dir)
  140. management.call_command('makemessages', locale=LOCALE, verbosity=0)
  141. self.assertTrue(os.path.exists(self.PO_FILE))
  142. with open(self.PO_FILE, 'r') as fp:
  143. po_contents = force_text(fp.read())
  144. # {% trans %}
  145. self.assertTrue('msgctxt "Context wrapped in double quotes"' in po_contents)
  146. self.assertTrue('msgctxt "Context wrapped in single quotes"' in po_contents)
  147. # {% blocktrans %}
  148. self.assertTrue('msgctxt "Special blocktrans context wrapped in double quotes"' in po_contents)
  149. self.assertTrue('msgctxt "Special blocktrans context wrapped in single quotes"' in po_contents)
  150. def test_template_comments(self):
  151. """Template comment tags on the same line of other constructs (#19552)"""
  152. os.chdir(self.test_dir)
  153. # Test detection/end user reporting of old, incorrect templates
  154. # translator comments syntax
  155. with warnings.catch_warnings(record=True) as ws:
  156. warnings.simplefilter('always')
  157. management.call_command('makemessages', locale=LOCALE, extensions=['thtml'], verbosity=0)
  158. self.assertEqual(len(ws), 3)
  159. for w in ws:
  160. self.assertTrue(issubclass(w.category, TranslatorCommentWarning))
  161. six.assertRegex(self, str(ws[0].message),
  162. r"The translator-targeted comment 'Translators: ignored i18n comment #1' \(file templates/comments.thtml, line 4\) was ignored, because it wasn't the last item on the line\."
  163. )
  164. six.assertRegex(self, str(ws[1].message),
  165. r"The translator-targeted comment 'Translators: ignored i18n comment #3' \(file templates/comments.thtml, line 6\) was ignored, because it wasn't the last item on the line\."
  166. )
  167. six.assertRegex(self, str(ws[2].message),
  168. r"The translator-targeted comment 'Translators: ignored i18n comment #4' \(file templates/comments.thtml, line 8\) was ignored, because it wasn't the last item on the line\."
  169. )
  170. # Now test .po file contents
  171. self.assertTrue(os.path.exists(self.PO_FILE))
  172. with open(self.PO_FILE, 'r') as fp:
  173. po_contents = force_text(fp.read())
  174. self.assertMsgId('Translatable literal #9a', po_contents)
  175. self.assertFalse('ignored comment #1' in po_contents)
  176. self.assertFalse('Translators: ignored i18n comment #1' in po_contents)
  177. self.assertMsgId("Translatable literal #9b", po_contents)
  178. self.assertFalse('ignored i18n comment #2' in po_contents)
  179. self.assertFalse('ignored comment #2' in po_contents)
  180. self.assertMsgId('Translatable literal #9c', po_contents)
  181. self.assertFalse('ignored comment #3' in po_contents)
  182. self.assertFalse('ignored i18n comment #3' in po_contents)
  183. self.assertMsgId('Translatable literal #9d', po_contents)
  184. self.assertFalse('ignored comment #4' in po_contents)
  185. self.assertMsgId('Translatable literal #9e', po_contents)
  186. self.assertFalse('ignored comment #5' in po_contents)
  187. self.assertFalse('ignored i18n comment #4' in po_contents)
  188. self.assertMsgId('Translatable literal #9f', po_contents)
  189. self.assertTrue('#. Translators: valid i18n comment #5' in po_contents)
  190. self.assertMsgId('Translatable literal #9g', po_contents)
  191. self.assertTrue('#. Translators: valid i18n comment #6' in po_contents)
  192. self.assertMsgId('Translatable literal #9h', po_contents)
  193. self.assertTrue('#. Translators: valid i18n comment #7' in po_contents)
  194. self.assertMsgId('Translatable literal #9i', po_contents)
  195. six.assertRegex(self, po_contents, r'#\..+Translators: valid i18n comment #8')
  196. six.assertRegex(self, po_contents, r'#\..+Translators: valid i18n comment #9')
  197. self.assertMsgId("Translatable literal #9j", po_contents)
  198. class JavascriptExtractorTests(ExtractorTests):
  199. PO_FILE='locale/%s/LC_MESSAGES/djangojs.po' % LOCALE
  200. def test_javascript_literals(self):
  201. os.chdir(self.test_dir)
  202. management.call_command('makemessages', domain='djangojs', locale=LOCALE, verbosity=0)
  203. self.assertTrue(os.path.exists(self.PO_FILE))
  204. with open(self.PO_FILE, 'r') as fp:
  205. po_contents = fp.read()
  206. self.assertMsgId('This literal should be included.', po_contents)
  207. self.assertMsgId('This one as well.', po_contents)
  208. self.assertMsgId(r'He said, \"hello\".', po_contents)
  209. self.assertMsgId("okkkk", po_contents)
  210. self.assertMsgId("TEXT", po_contents)
  211. self.assertMsgId("It's at http://example.com", po_contents)
  212. self.assertMsgId("String", po_contents)
  213. self.assertMsgId("/* but this one will be too */ 'cause there is no way of telling...", po_contents)
  214. self.assertMsgId("foo", po_contents)
  215. self.assertMsgId("bar", po_contents)
  216. self.assertMsgId("baz", po_contents)
  217. self.assertMsgId("quz", po_contents)
  218. self.assertMsgId("foobar", po_contents)
  219. class IgnoredExtractorTests(ExtractorTests):
  220. def test_ignore_option(self):
  221. os.chdir(self.test_dir)
  222. pattern1 = os.path.join('ignore_dir', '*')
  223. stdout = StringIO()
  224. management.call_command('makemessages', locale=LOCALE, verbosity=2,
  225. ignore_patterns=[pattern1], stdout=stdout)
  226. data = stdout.getvalue()
  227. self.assertTrue("ignoring directory ignore_dir" in data)
  228. self.assertTrue(os.path.exists(self.PO_FILE))
  229. with open(self.PO_FILE, 'r') as fp:
  230. po_contents = fp.read()
  231. self.assertMsgId('This literal should be included.', po_contents)
  232. self.assertNotMsgId('This should be ignored.', po_contents)
  233. class SymlinkExtractorTests(ExtractorTests):
  234. def setUp(self):
  235. self._cwd = os.getcwd()
  236. self.test_dir = os.path.abspath(os.path.dirname(upath(__file__)))
  237. self.symlinked_dir = os.path.join(self.test_dir, 'templates_symlinked')
  238. def tearDown(self):
  239. super(SymlinkExtractorTests, self).tearDown()
  240. os.chdir(self.test_dir)
  241. try:
  242. os.remove(self.symlinked_dir)
  243. except OSError:
  244. pass
  245. os.chdir(self._cwd)
  246. def test_symlink(self):
  247. if hasattr(os, 'symlink'):
  248. if os.path.exists(self.symlinked_dir):
  249. self.assertTrue(os.path.islink(self.symlinked_dir))
  250. else:
  251. os.symlink(os.path.join(self.test_dir, 'templates'), self.symlinked_dir)
  252. os.chdir(self.test_dir)
  253. management.call_command('makemessages', locale=LOCALE, verbosity=0, symlinks=True)
  254. self.assertTrue(os.path.exists(self.PO_FILE))
  255. with open(self.PO_FILE, 'r') as fp:
  256. po_contents = force_text(fp.read())
  257. self.assertMsgId('This literal should be included.', po_contents)
  258. self.assertTrue('templates_symlinked/test.html' in po_contents)
  259. class CopyPluralFormsExtractorTests(ExtractorTests):
  260. def test_copy_plural_forms(self):
  261. os.chdir(self.test_dir)
  262. management.call_command('makemessages', locale=LOCALE, verbosity=0)
  263. self.assertTrue(os.path.exists(self.PO_FILE))
  264. with open(self.PO_FILE, 'r') as fp:
  265. po_contents = force_text(fp.read())
  266. self.assertTrue('Plural-Forms: nplurals=2; plural=(n != 1)' in po_contents)
  267. class NoWrapExtractorTests(ExtractorTests):
  268. def test_no_wrap_enabled(self):
  269. os.chdir(self.test_dir)
  270. management.call_command('makemessages', locale=LOCALE, verbosity=0, no_wrap=True)
  271. self.assertTrue(os.path.exists(self.PO_FILE))
  272. with open(self.PO_FILE, 'r') as fp:
  273. po_contents = force_text(fp.read())
  274. self.assertMsgId('This literal should also be included wrapped or not wrapped depending on the use of the --no-wrap option.', po_contents)
  275. def test_no_wrap_disabled(self):
  276. os.chdir(self.test_dir)
  277. management.call_command('makemessages', locale=LOCALE, verbosity=0, no_wrap=False)
  278. self.assertTrue(os.path.exists(self.PO_FILE))
  279. with open(self.PO_FILE, 'r') as fp:
  280. po_contents = force_text(fp.read())
  281. self.assertMsgId('""\n"This literal should also be included wrapped or not wrapped depending on the "\n"use of the --no-wrap option."', po_contents, use_quotes=False)
  282. class NoLocationExtractorTests(ExtractorTests):
  283. def test_no_location_enabled(self):
  284. os.chdir(self.test_dir)
  285. management.call_command('makemessages', locale=LOCALE, verbosity=0, no_location=True)
  286. self.assertTrue(os.path.exists(self.PO_FILE))
  287. with open(self.PO_FILE, 'r') as fp:
  288. po_contents = force_text(fp.read())
  289. self.assertFalse('#: templates/test.html:55' in po_contents)
  290. def test_no_location_disabled(self):
  291. os.chdir(self.test_dir)
  292. management.call_command('makemessages', locale=LOCALE, verbosity=0, no_location=False)
  293. self.assertTrue(os.path.exists(self.PO_FILE))
  294. with open(self.PO_FILE, 'r') as fp:
  295. po_contents = force_text(fp.read())
  296. self.assertTrue('#: templates/test.html:55' in po_contents)
  297. class KeepPotFileExtractorTests(ExtractorTests):
  298. POT_FILE='locale/django.pot'
  299. def setUp(self):
  300. super(KeepPotFileExtractorTests, self).setUp()
  301. def tearDown(self):
  302. super(KeepPotFileExtractorTests, self).tearDown()
  303. os.chdir(self.test_dir)
  304. try:
  305. os.unlink(self.POT_FILE)
  306. except OSError:
  307. pass
  308. os.chdir(self._cwd)
  309. def test_keep_pot_disabled_by_default(self):
  310. os.chdir(self.test_dir)
  311. management.call_command('makemessages', locale=LOCALE, verbosity=0)
  312. self.assertFalse(os.path.exists(self.POT_FILE))
  313. def test_keep_pot_explicitly_disabled(self):
  314. os.chdir(self.test_dir)
  315. management.call_command('makemessages', locale=LOCALE, verbosity=0,
  316. keep_pot=False)
  317. self.assertFalse(os.path.exists(self.POT_FILE))
  318. def test_keep_pot_enabled(self):
  319. os.chdir(self.test_dir)
  320. management.call_command('makemessages', locale=LOCALE, verbosity=0,
  321. keep_pot=True)
  322. self.assertTrue(os.path.exists(self.POT_FILE))
  323. class MultipleLocaleExtractionTests(ExtractorTests):
  324. PO_FILE_PT = 'locale/pt/LC_MESSAGES/django.po'
  325. PO_FILE_DE = 'locale/de/LC_MESSAGES/django.po'
  326. LOCALES = ['pt', 'de', 'ch']
  327. def tearDown(self):
  328. os.chdir(self.test_dir)
  329. for locale in self.LOCALES:
  330. try:
  331. self._rmrf('locale/%s' % locale)
  332. except OSError:
  333. pass
  334. os.chdir(self._cwd)
  335. def test_multiple_locales(self):
  336. os.chdir(self.test_dir)
  337. management.call_command('makemessages', locale=['pt','de'], verbosity=0)
  338. self.assertTrue(os.path.exists(self.PO_FILE_PT))
  339. self.assertTrue(os.path.exists(self.PO_FILE_DE))
  340. def test_comma_separated_locales(self):
  341. os.chdir(self.test_dir)
  342. management.call_command('makemessages', locale='pt,de,ch', verbosity=0)
  343. self.assertTrue(os.path.exists(self.PO_FILE_PT))
  344. self.assertTrue(os.path.exists(self.PO_FILE_DE))