test_extraction.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  1. import os
  2. import re
  3. import shutil
  4. import time
  5. import warnings
  6. from io import StringIO
  7. from unittest import mock, skipUnless
  8. from admin_scripts.tests import AdminScriptTestCase
  9. from django.core import management
  10. from django.core.management import execute_from_command_line
  11. from django.core.management.base import CommandError
  12. from django.core.management.commands.makemessages import \
  13. Command as MakeMessagesCommand
  14. from django.core.management.utils import find_command
  15. from django.test import SimpleTestCase, override_settings
  16. from django.test.utils import captured_stderr, captured_stdout
  17. from django.utils._os import symlinks_supported
  18. from django.utils.translation import TranslatorCommentWarning
  19. from .utils import POFileAssertionMixin, RunInTmpDirMixin, copytree
  20. LOCALE = 'de'
  21. has_xgettext = find_command('xgettext')
  22. @skipUnless(has_xgettext, 'xgettext is mandatory for extraction tests')
  23. class ExtractorTests(POFileAssertionMixin, RunInTmpDirMixin, SimpleTestCase):
  24. work_subdir = 'commands'
  25. PO_FILE = 'locale/%s/LC_MESSAGES/django.po' % LOCALE
  26. def _run_makemessages(self, **options):
  27. os.chdir(self.test_dir)
  28. out = StringIO()
  29. management.call_command('makemessages', locale=[LOCALE], verbosity=2, stdout=out, **options)
  30. output = out.getvalue()
  31. self.assertTrue(os.path.exists(self.PO_FILE))
  32. with open(self.PO_FILE, 'r') as fp:
  33. po_contents = fp.read()
  34. return output, po_contents
  35. def assertMsgIdPlural(self, msgid, haystack, use_quotes=True):
  36. return self._assertPoKeyword('msgid_plural', msgid, haystack, use_quotes=use_quotes)
  37. def assertMsgStr(self, msgstr, haystack, use_quotes=True):
  38. return self._assertPoKeyword('msgstr', msgstr, haystack, use_quotes=use_quotes)
  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. def _assertPoLocComment(self, assert_presence, po_filename, line_number, *comment_parts):
  45. with open(po_filename, 'r') as fp:
  46. po_contents = fp.read()
  47. if os.name == 'nt':
  48. # #: .\path\to\file.html:123
  49. cwd_prefix = '%s%s' % (os.curdir, os.sep)
  50. else:
  51. # #: path/to/file.html:123
  52. cwd_prefix = ''
  53. path = os.path.join(cwd_prefix, *comment_parts)
  54. parts = [path]
  55. if isinstance(line_number, str):
  56. line_number = self._get_token_line_number(path, line_number)
  57. if line_number is not None:
  58. parts.append(':%d' % line_number)
  59. needle = ''.join(parts)
  60. pattern = re.compile(r'^\#\:.*' + re.escape(needle), re.MULTILINE)
  61. if assert_presence:
  62. return self.assertRegex(po_contents, pattern, '"%s" not found in final .po file.' % needle)
  63. else:
  64. return self.assertNotRegex(po_contents, pattern, '"%s" shouldn\'t be in final .po file.' % needle)
  65. def _get_token_line_number(self, path, token):
  66. with open(path) as f:
  67. for line, content in enumerate(f, 1):
  68. if token in content:
  69. return line
  70. self.fail("The token '%s' could not be found in %s, please check the test config" % (token, path))
  71. def assertLocationCommentPresent(self, po_filename, line_number, *comment_parts):
  72. r"""
  73. self.assertLocationCommentPresent('django.po', 42, 'dirA', 'dirB', 'foo.py')
  74. verifies that the django.po file has a gettext-style location comment of the form
  75. `#: dirA/dirB/foo.py:42`
  76. (or `#: .\dirA\dirB\foo.py:42` on Windows)
  77. None can be passed for the line_number argument to skip checking of
  78. the :42 suffix part.
  79. A string token can also be passed as line_number, in which case it
  80. will be searched in the template, and its line number will be used.
  81. A msgid is a suitable candidate.
  82. """
  83. return self._assertPoLocComment(True, po_filename, line_number, *comment_parts)
  84. def assertLocationCommentNotPresent(self, po_filename, line_number, *comment_parts):
  85. """Check the opposite of assertLocationComment()"""
  86. return self._assertPoLocComment(False, po_filename, line_number, *comment_parts)
  87. def assertRecentlyModified(self, path):
  88. """
  89. Assert that file was recently modified (modification time was less than 10 seconds ago).
  90. """
  91. delta = time.time() - os.stat(path).st_mtime
  92. self.assertLess(delta, 10, "%s was recently modified" % path)
  93. def assertNotRecentlyModified(self, path):
  94. """
  95. Assert that file was not recently modified (modification time was more than 10 seconds ago).
  96. """
  97. delta = time.time() - os.stat(path).st_mtime
  98. self.assertGreater(delta, 10, "%s wasn't recently modified" % path)
  99. class BasicExtractorTests(ExtractorTests):
  100. @override_settings(USE_I18N=False)
  101. def test_use_i18n_false(self):
  102. """
  103. makemessages also runs successfully when USE_I18N is False.
  104. """
  105. management.call_command('makemessages', locale=[LOCALE], verbosity=0)
  106. self.assertTrue(os.path.exists(self.PO_FILE))
  107. with open(self.PO_FILE, 'r', encoding='utf-8') as fp:
  108. po_contents = fp.read()
  109. # Check two random strings
  110. self.assertIn('#. Translators: One-line translator comment #1', po_contents)
  111. self.assertIn('msgctxt "Special trans context #1"', po_contents)
  112. def test_comments_extractor(self):
  113. management.call_command('makemessages', locale=[LOCALE], verbosity=0)
  114. self.assertTrue(os.path.exists(self.PO_FILE))
  115. with open(self.PO_FILE, 'r', encoding='utf-8') as fp:
  116. po_contents = fp.read()
  117. self.assertNotIn('This comment should not be extracted', po_contents)
  118. # Comments in templates
  119. self.assertIn('#. Translators: This comment should be extracted', po_contents)
  120. self.assertIn(
  121. "#. Translators: Django comment block for translators\n#. "
  122. "string's meaning unveiled",
  123. po_contents
  124. )
  125. self.assertIn('#. Translators: One-line translator comment #1', po_contents)
  126. self.assertIn('#. Translators: Two-line translator comment #1\n#. continued here.', po_contents)
  127. self.assertIn('#. Translators: One-line translator comment #2', po_contents)
  128. self.assertIn('#. Translators: Two-line translator comment #2\n#. continued here.', po_contents)
  129. self.assertIn('#. Translators: One-line translator comment #3', po_contents)
  130. self.assertIn('#. Translators: Two-line translator comment #3\n#. continued here.', po_contents)
  131. self.assertIn('#. Translators: One-line translator comment #4', po_contents)
  132. self.assertIn('#. Translators: Two-line translator comment #4\n#. continued here.', po_contents)
  133. self.assertIn(
  134. '#. Translators: One-line translator comment #5 -- with '
  135. 'non ASCII characters: áéíóúö',
  136. po_contents
  137. )
  138. self.assertIn(
  139. '#. Translators: Two-line translator comment #5 -- with '
  140. 'non ASCII characters: áéíóúö\n#. continued here.',
  141. po_contents
  142. )
  143. def test_special_char_extracted(self):
  144. management.call_command('makemessages', locale=[LOCALE], verbosity=0)
  145. self.assertTrue(os.path.exists(self.PO_FILE))
  146. with open(self.PO_FILE, 'r', encoding='utf-8') as fp:
  147. po_contents = fp.read()
  148. self.assertMsgId("Non-breaking space\u00a0:", po_contents)
  149. def test_blocktrans_trimmed(self):
  150. management.call_command('makemessages', locale=[LOCALE], verbosity=0)
  151. self.assertTrue(os.path.exists(self.PO_FILE))
  152. with open(self.PO_FILE, 'r') as fp:
  153. po_contents = fp.read()
  154. # should not be trimmed
  155. self.assertNotMsgId('Text with a few line breaks.', po_contents)
  156. # should be trimmed
  157. self.assertMsgId("Again some text with a few line breaks, this time should be trimmed.", po_contents)
  158. # #21406 -- Should adjust for eaten line numbers
  159. self.assertMsgId("Get my line number", po_contents)
  160. self.assertLocationCommentPresent(self.PO_FILE, 'Get my line number', 'templates', 'test.html')
  161. def test_force_en_us_locale(self):
  162. """Value of locale-munging option used by the command is the right one"""
  163. self.assertTrue(MakeMessagesCommand.leave_locale_alone)
  164. def test_extraction_error(self):
  165. msg = (
  166. 'Translation blocks must not include other block tags: blocktrans '
  167. '(file %s, line 3)' % os.path.join('templates', 'template_with_error.tpl')
  168. )
  169. with self.assertRaisesMessage(SyntaxError, msg):
  170. management.call_command('makemessages', locale=[LOCALE], extensions=['tpl'], verbosity=0)
  171. # The temporary file was cleaned up
  172. self.assertFalse(os.path.exists('./templates/template_with_error.tpl.py'))
  173. def test_unicode_decode_error(self):
  174. shutil.copyfile('./not_utf8.sample', './not_utf8.txt')
  175. out = StringIO()
  176. management.call_command('makemessages', locale=[LOCALE], stdout=out)
  177. self.assertIn("UnicodeDecodeError: skipped file not_utf8.txt in .", out.getvalue())
  178. def test_unicode_file_name(self):
  179. open(os.path.join(self.test_dir, 'vidéo.txt'), 'a').close()
  180. management.call_command('makemessages', locale=[LOCALE], verbosity=0)
  181. def test_extraction_warning(self):
  182. """test xgettext warning about multiple bare interpolation placeholders"""
  183. shutil.copyfile('./code.sample', './code_sample.py')
  184. out = StringIO()
  185. management.call_command('makemessages', locale=[LOCALE], stdout=out)
  186. self.assertIn("code_sample.py:4", out.getvalue())
  187. def test_template_message_context_extractor(self):
  188. """
  189. Message contexts are correctly extracted for the {% trans %} and
  190. {% blocktrans %} template tags (#14806).
  191. """
  192. management.call_command('makemessages', locale=[LOCALE], verbosity=0)
  193. self.assertTrue(os.path.exists(self.PO_FILE))
  194. with open(self.PO_FILE, 'r') as fp:
  195. po_contents = fp.read()
  196. # {% trans %}
  197. self.assertIn('msgctxt "Special trans context #1"', po_contents)
  198. self.assertMsgId("Translatable literal #7a", po_contents)
  199. self.assertIn('msgctxt "Special trans context #2"', po_contents)
  200. self.assertMsgId("Translatable literal #7b", po_contents)
  201. self.assertIn('msgctxt "Special trans context #3"', po_contents)
  202. self.assertMsgId("Translatable literal #7c", po_contents)
  203. # {% trans %} with a filter
  204. for minor_part in 'abcdefgh': # Iterate from #7.1a to #7.1h template markers
  205. self.assertIn('msgctxt "context #7.1{}"'.format(minor_part), po_contents)
  206. self.assertMsgId('Translatable literal #7.1{}'.format(minor_part), po_contents)
  207. # {% blocktrans %}
  208. self.assertIn('msgctxt "Special blocktrans context #1"', po_contents)
  209. self.assertMsgId("Translatable literal #8a", po_contents)
  210. self.assertIn('msgctxt "Special blocktrans context #2"', po_contents)
  211. self.assertMsgId("Translatable literal #8b-singular", po_contents)
  212. self.assertIn("Translatable literal #8b-plural", po_contents)
  213. self.assertIn('msgctxt "Special blocktrans context #3"', po_contents)
  214. self.assertMsgId("Translatable literal #8c-singular", po_contents)
  215. self.assertIn("Translatable literal #8c-plural", po_contents)
  216. self.assertIn('msgctxt "Special blocktrans context #4"', po_contents)
  217. self.assertMsgId("Translatable literal #8d %(a)s", po_contents)
  218. def test_context_in_single_quotes(self):
  219. management.call_command('makemessages', locale=[LOCALE], verbosity=0)
  220. self.assertTrue(os.path.exists(self.PO_FILE))
  221. with open(self.PO_FILE, 'r') as fp:
  222. po_contents = fp.read()
  223. # {% trans %}
  224. self.assertIn('msgctxt "Context wrapped in double quotes"', po_contents)
  225. self.assertIn('msgctxt "Context wrapped in single quotes"', po_contents)
  226. # {% blocktrans %}
  227. self.assertIn('msgctxt "Special blocktrans context wrapped in double quotes"', po_contents)
  228. self.assertIn('msgctxt "Special blocktrans context wrapped in single quotes"', po_contents)
  229. def test_template_comments(self):
  230. """Template comment tags on the same line of other constructs (#19552)"""
  231. # Test detection/end user reporting of old, incorrect templates
  232. # translator comments syntax
  233. with warnings.catch_warnings(record=True) as ws:
  234. warnings.simplefilter('always')
  235. management.call_command('makemessages', locale=[LOCALE], extensions=['thtml'], verbosity=0)
  236. self.assertEqual(len(ws), 3)
  237. for w in ws:
  238. self.assertTrue(issubclass(w.category, TranslatorCommentWarning))
  239. self.assertRegex(
  240. str(ws[0].message),
  241. r"The translator-targeted comment 'Translators: ignored i18n "
  242. r"comment #1' \(file templates[/\\]comments.thtml, line 4\) "
  243. r"was ignored, because it wasn't the last item on the line\."
  244. )
  245. self.assertRegex(
  246. str(ws[1].message),
  247. r"The translator-targeted comment 'Translators: ignored i18n "
  248. r"comment #3' \(file templates[/\\]comments.thtml, line 6\) "
  249. r"was ignored, because it wasn't the last item on the line\."
  250. )
  251. self.assertRegex(
  252. str(ws[2].message),
  253. r"The translator-targeted comment 'Translators: ignored i18n "
  254. r"comment #4' \(file templates[/\\]comments.thtml, line 8\) "
  255. r"was ignored, because it wasn't the last item on the line\."
  256. )
  257. # Now test .po file contents
  258. self.assertTrue(os.path.exists(self.PO_FILE))
  259. with open(self.PO_FILE, 'r') as fp:
  260. po_contents = fp.read()
  261. self.assertMsgId('Translatable literal #9a', po_contents)
  262. self.assertNotIn('ignored comment #1', po_contents)
  263. self.assertNotIn('Translators: ignored i18n comment #1', po_contents)
  264. self.assertMsgId("Translatable literal #9b", po_contents)
  265. self.assertNotIn('ignored i18n comment #2', po_contents)
  266. self.assertNotIn('ignored comment #2', po_contents)
  267. self.assertMsgId('Translatable literal #9c', po_contents)
  268. self.assertNotIn('ignored comment #3', po_contents)
  269. self.assertNotIn('ignored i18n comment #3', po_contents)
  270. self.assertMsgId('Translatable literal #9d', po_contents)
  271. self.assertNotIn('ignored comment #4', po_contents)
  272. self.assertMsgId('Translatable literal #9e', po_contents)
  273. self.assertNotIn('ignored comment #5', po_contents)
  274. self.assertNotIn('ignored i18n comment #4', po_contents)
  275. self.assertMsgId('Translatable literal #9f', po_contents)
  276. self.assertIn('#. Translators: valid i18n comment #5', po_contents)
  277. self.assertMsgId('Translatable literal #9g', po_contents)
  278. self.assertIn('#. Translators: valid i18n comment #6', po_contents)
  279. self.assertMsgId('Translatable literal #9h', po_contents)
  280. self.assertIn('#. Translators: valid i18n comment #7', po_contents)
  281. self.assertMsgId('Translatable literal #9i', po_contents)
  282. self.assertRegex(po_contents, r'#\..+Translators: valid i18n comment #8')
  283. self.assertRegex(po_contents, r'#\..+Translators: valid i18n comment #9')
  284. self.assertMsgId("Translatable literal #9j", po_contents)
  285. def test_makemessages_find_files(self):
  286. """
  287. find_files only discover files having the proper extensions.
  288. """
  289. cmd = MakeMessagesCommand()
  290. cmd.ignore_patterns = ['CVS', '.*', '*~', '*.pyc']
  291. cmd.symlinks = False
  292. cmd.domain = 'django'
  293. cmd.extensions = ['html', 'txt', 'py']
  294. cmd.verbosity = 0
  295. cmd.locale_paths = []
  296. cmd.default_locale_path = os.path.join(self.test_dir, 'locale')
  297. found_files = cmd.find_files(self.test_dir)
  298. found_exts = set([os.path.splitext(tfile.file)[1] for tfile in found_files])
  299. self.assertEqual(found_exts.difference({'.py', '.html', '.txt'}), set())
  300. cmd.extensions = ['js']
  301. cmd.domain = 'djangojs'
  302. found_files = cmd.find_files(self.test_dir)
  303. found_exts = set([os.path.splitext(tfile.file)[1] for tfile in found_files])
  304. self.assertEqual(found_exts.difference({'.js'}), set())
  305. @mock.patch('django.core.management.commands.makemessages.popen_wrapper')
  306. def test_makemessages_gettext_version(self, mocked_popen_wrapper):
  307. # "Normal" output:
  308. mocked_popen_wrapper.return_value = (
  309. "xgettext (GNU gettext-tools) 0.18.1\n"
  310. "Copyright (C) 1995-1998, 2000-2010 Free Software Foundation, Inc.\n"
  311. "License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>\n"
  312. "This is free software: you are free to change and redistribute it.\n"
  313. "There is NO WARRANTY, to the extent permitted by law.\n"
  314. "Written by Ulrich Drepper.\n", '', 0)
  315. cmd = MakeMessagesCommand()
  316. self.assertEqual(cmd.gettext_version, (0, 18, 1))
  317. # Version number with only 2 parts (#23788)
  318. mocked_popen_wrapper.return_value = (
  319. "xgettext (GNU gettext-tools) 0.17\n", '', 0)
  320. cmd = MakeMessagesCommand()
  321. self.assertEqual(cmd.gettext_version, (0, 17))
  322. # Bad version output
  323. mocked_popen_wrapper.return_value = (
  324. "any other return value\n", '', 0)
  325. cmd = MakeMessagesCommand()
  326. with self.assertRaisesMessage(CommandError, "Unable to get gettext version. Is it installed?"):
  327. cmd.gettext_version
  328. def test_po_file_encoding_when_updating(self):
  329. """
  330. Update of PO file doesn't corrupt it with non-UTF-8 encoding on Windows
  331. (#23271).
  332. """
  333. BR_PO_BASE = 'locale/pt_BR/LC_MESSAGES/django'
  334. shutil.copyfile(BR_PO_BASE + '.pristine', BR_PO_BASE + '.po')
  335. management.call_command('makemessages', locale=['pt_BR'], verbosity=0)
  336. self.assertTrue(os.path.exists(BR_PO_BASE + '.po'))
  337. with open(BR_PO_BASE + '.po', 'r', encoding='utf-8') as fp:
  338. po_contents = fp.read()
  339. self.assertMsgStr("Größe", po_contents)
  340. class JavascriptExtractorTests(ExtractorTests):
  341. PO_FILE = 'locale/%s/LC_MESSAGES/djangojs.po' % LOCALE
  342. def test_javascript_literals(self):
  343. _, po_contents = self._run_makemessages(domain='djangojs')
  344. self.assertMsgId('This literal should be included.', po_contents)
  345. self.assertMsgId('gettext_noop should, too.', po_contents)
  346. self.assertMsgId('This one as well.', po_contents)
  347. self.assertMsgId(r'He said, \"hello\".', po_contents)
  348. self.assertMsgId("okkkk", po_contents)
  349. self.assertMsgId("TEXT", po_contents)
  350. self.assertMsgId("It's at http://example.com", po_contents)
  351. self.assertMsgId("String", po_contents)
  352. self.assertMsgId("/* but this one will be too */ 'cause there is no way of telling...", po_contents)
  353. self.assertMsgId("foo", po_contents)
  354. self.assertMsgId("bar", po_contents)
  355. self.assertMsgId("baz", po_contents)
  356. self.assertMsgId("quz", po_contents)
  357. self.assertMsgId("foobar", po_contents)
  358. def test_media_static_dirs_ignored(self):
  359. """
  360. Regression test for #23583.
  361. """
  362. with override_settings(STATIC_ROOT=os.path.join(self.test_dir, 'static/'),
  363. MEDIA_ROOT=os.path.join(self.test_dir, 'media_root/')):
  364. _, po_contents = self._run_makemessages(domain='djangojs')
  365. self.assertMsgId("Static content inside app should be included.", po_contents)
  366. self.assertNotMsgId("Content from STATIC_ROOT should not be included", po_contents)
  367. @override_settings(STATIC_ROOT=None, MEDIA_ROOT='')
  368. def test_default_root_settings(self):
  369. """
  370. Regression test for #23717.
  371. """
  372. _, po_contents = self._run_makemessages(domain='djangojs')
  373. self.assertMsgId("Static content inside app should be included.", po_contents)
  374. class IgnoredExtractorTests(ExtractorTests):
  375. def test_ignore_directory(self):
  376. out, po_contents = self._run_makemessages(ignore_patterns=[
  377. os.path.join('ignore_dir', '*'),
  378. ])
  379. self.assertIn("ignoring directory ignore_dir", out)
  380. self.assertMsgId('This literal should be included.', po_contents)
  381. self.assertNotMsgId('This should be ignored.', po_contents)
  382. def test_ignore_subdirectory(self):
  383. out, po_contents = self._run_makemessages(ignore_patterns=[
  384. 'templates/*/ignore.html',
  385. 'templates/subdir/*',
  386. ])
  387. self.assertIn("ignoring directory subdir", out)
  388. self.assertNotMsgId('This subdir should be ignored too.', po_contents)
  389. def test_ignore_file_patterns(self):
  390. out, po_contents = self._run_makemessages(ignore_patterns=[
  391. 'xxx_*',
  392. ])
  393. self.assertIn("ignoring file xxx_ignored.html", out)
  394. self.assertNotMsgId('This should be ignored too.', po_contents)
  395. def test_media_static_dirs_ignored(self):
  396. with override_settings(STATIC_ROOT=os.path.join(self.test_dir, 'static/'),
  397. MEDIA_ROOT=os.path.join(self.test_dir, 'media_root/')):
  398. out, _ = self._run_makemessages()
  399. self.assertIn("ignoring directory static", out)
  400. self.assertIn("ignoring directory media_root", out)
  401. class SymlinkExtractorTests(ExtractorTests):
  402. def setUp(self):
  403. super().setUp()
  404. self.symlinked_dir = os.path.join(self.test_dir, 'templates_symlinked')
  405. def test_symlink(self):
  406. if os.path.exists(self.symlinked_dir):
  407. self.assertTrue(os.path.islink(self.symlinked_dir))
  408. else:
  409. if symlinks_supported():
  410. os.symlink(os.path.join(self.test_dir, 'templates'), self.symlinked_dir)
  411. else:
  412. self.skipTest("os.symlink() not available on this OS + Python version combination.")
  413. os.chdir(self.test_dir)
  414. management.call_command('makemessages', locale=[LOCALE], verbosity=0, symlinks=True)
  415. self.assertTrue(os.path.exists(self.PO_FILE))
  416. with open(self.PO_FILE, 'r') as fp:
  417. po_contents = fp.read()
  418. self.assertMsgId('This literal should be included.', po_contents)
  419. self.assertLocationCommentPresent(self.PO_FILE, None, 'templates_symlinked', 'test.html')
  420. class CopyPluralFormsExtractorTests(ExtractorTests):
  421. PO_FILE_ES = 'locale/es/LC_MESSAGES/django.po'
  422. def test_copy_plural_forms(self):
  423. management.call_command('makemessages', locale=[LOCALE], verbosity=0)
  424. self.assertTrue(os.path.exists(self.PO_FILE))
  425. with open(self.PO_FILE, 'r') as fp:
  426. po_contents = fp.read()
  427. self.assertIn('Plural-Forms: nplurals=2; plural=(n != 1)', po_contents)
  428. def test_override_plural_forms(self):
  429. """Ticket #20311."""
  430. management.call_command('makemessages', locale=['es'], extensions=['djtpl'], verbosity=0)
  431. self.assertTrue(os.path.exists(self.PO_FILE_ES))
  432. with open(self.PO_FILE_ES, 'r', encoding='utf-8') as fp:
  433. po_contents = fp.read()
  434. found = re.findall(r'^(?P<value>"Plural-Forms.+?\\n")\s*$', po_contents, re.MULTILINE | re.DOTALL)
  435. self.assertEqual(1, len(found))
  436. def test_trans_and_plural_blocktrans_collision(self):
  437. """
  438. Ensures a correct workaround for the gettext bug when handling a literal
  439. found inside a {% trans %} tag and also in another file inside a
  440. {% blocktrans %} with a plural (#17375).
  441. """
  442. management.call_command('makemessages', locale=[LOCALE], extensions=['html', 'djtpl'], verbosity=0)
  443. self.assertTrue(os.path.exists(self.PO_FILE))
  444. with open(self.PO_FILE, 'r') as fp:
  445. po_contents = fp.read()
  446. self.assertNotIn("#-#-#-#-# django.pot (PACKAGE VERSION) #-#-#-#-#\\n", po_contents)
  447. self.assertMsgId('First `trans`, then `blocktrans` with a plural', po_contents)
  448. self.assertMsgIdPlural('Plural for a `trans` and `blocktrans` collision case', po_contents)
  449. class NoWrapExtractorTests(ExtractorTests):
  450. def test_no_wrap_enabled(self):
  451. management.call_command('makemessages', locale=[LOCALE], verbosity=0, no_wrap=True)
  452. self.assertTrue(os.path.exists(self.PO_FILE))
  453. with open(self.PO_FILE, 'r') as fp:
  454. po_contents = fp.read()
  455. self.assertMsgId(
  456. 'This literal should also be included wrapped or not wrapped '
  457. 'depending on the use of the --no-wrap option.',
  458. po_contents
  459. )
  460. def test_no_wrap_disabled(self):
  461. management.call_command('makemessages', locale=[LOCALE], verbosity=0, no_wrap=False)
  462. self.assertTrue(os.path.exists(self.PO_FILE))
  463. with open(self.PO_FILE, 'r') as fp:
  464. po_contents = fp.read()
  465. self.assertMsgId(
  466. '""\n"This literal should also be included wrapped or not '
  467. 'wrapped depending on the "\n"use of the --no-wrap option."',
  468. po_contents,
  469. use_quotes=False
  470. )
  471. class LocationCommentsTests(ExtractorTests):
  472. def test_no_location_enabled(self):
  473. """Behavior is correct if --no-location switch is specified. See #16903."""
  474. management.call_command('makemessages', locale=[LOCALE], verbosity=0, no_location=True)
  475. self.assertTrue(os.path.exists(self.PO_FILE))
  476. self.assertLocationCommentNotPresent(self.PO_FILE, None, 'test.html')
  477. def test_no_location_disabled(self):
  478. """Behavior is correct if --no-location switch isn't specified."""
  479. management.call_command('makemessages', locale=[LOCALE], verbosity=0, no_location=False)
  480. self.assertTrue(os.path.exists(self.PO_FILE))
  481. # #16903 -- Standard comment with source file relative path should be present
  482. self.assertLocationCommentPresent(self.PO_FILE, 'Translatable literal #6b', 'templates', 'test.html')
  483. def test_location_comments_for_templatized_files(self):
  484. """
  485. Ensure no leaky paths in comments, e.g. #: path\to\file.html.py:123
  486. Refs #21209/#26341.
  487. """
  488. management.call_command('makemessages', locale=[LOCALE], verbosity=0)
  489. self.assertTrue(os.path.exists(self.PO_FILE))
  490. with open(self.PO_FILE, 'r') as fp:
  491. po_contents = fp.read()
  492. self.assertMsgId('#: templates/test.html.py', po_contents)
  493. self.assertLocationCommentNotPresent(self.PO_FILE, None, '.html.py')
  494. self.assertLocationCommentPresent(self.PO_FILE, 5, 'templates', 'test.html')
  495. class KeepPotFileExtractorTests(ExtractorTests):
  496. POT_FILE = 'locale/django.pot'
  497. def test_keep_pot_disabled_by_default(self):
  498. management.call_command('makemessages', locale=[LOCALE], verbosity=0)
  499. self.assertFalse(os.path.exists(self.POT_FILE))
  500. def test_keep_pot_explicitly_disabled(self):
  501. management.call_command('makemessages', locale=[LOCALE], verbosity=0,
  502. keep_pot=False)
  503. self.assertFalse(os.path.exists(self.POT_FILE))
  504. def test_keep_pot_enabled(self):
  505. management.call_command('makemessages', locale=[LOCALE], verbosity=0,
  506. keep_pot=True)
  507. self.assertTrue(os.path.exists(self.POT_FILE))
  508. class MultipleLocaleExtractionTests(ExtractorTests):
  509. PO_FILE_PT = 'locale/pt/LC_MESSAGES/django.po'
  510. PO_FILE_DE = 'locale/de/LC_MESSAGES/django.po'
  511. LOCALES = ['pt', 'de', 'ch']
  512. def test_multiple_locales(self):
  513. management.call_command('makemessages', locale=['pt', 'de'], verbosity=0)
  514. self.assertTrue(os.path.exists(self.PO_FILE_PT))
  515. self.assertTrue(os.path.exists(self.PO_FILE_DE))
  516. class ExcludedLocaleExtractionTests(ExtractorTests):
  517. work_subdir = 'exclude'
  518. LOCALES = ['en', 'fr', 'it']
  519. PO_FILE = 'locale/%s/LC_MESSAGES/django.po'
  520. def _set_times_for_all_po_files(self):
  521. """
  522. Set access and modification times to the Unix epoch time for all the .po files.
  523. """
  524. for locale in self.LOCALES:
  525. os.utime(self.PO_FILE % locale, (0, 0))
  526. def setUp(self):
  527. super().setUp()
  528. copytree('canned_locale', 'locale')
  529. self._set_times_for_all_po_files()
  530. def test_command_help(self):
  531. with captured_stdout(), captured_stderr():
  532. # `call_command` bypasses the parser; by calling
  533. # `execute_from_command_line` with the help subcommand we
  534. # ensure that there are no issues with the parser itself.
  535. execute_from_command_line(['django-admin', 'help', 'makemessages'])
  536. def test_one_locale_excluded(self):
  537. management.call_command('makemessages', exclude=['it'], stdout=StringIO())
  538. self.assertRecentlyModified(self.PO_FILE % 'en')
  539. self.assertRecentlyModified(self.PO_FILE % 'fr')
  540. self.assertNotRecentlyModified(self.PO_FILE % 'it')
  541. def test_multiple_locales_excluded(self):
  542. management.call_command('makemessages', exclude=['it', 'fr'], stdout=StringIO())
  543. self.assertRecentlyModified(self.PO_FILE % 'en')
  544. self.assertNotRecentlyModified(self.PO_FILE % 'fr')
  545. self.assertNotRecentlyModified(self.PO_FILE % 'it')
  546. def test_one_locale_excluded_with_locale(self):
  547. management.call_command('makemessages', locale=['en', 'fr'], exclude=['fr'], stdout=StringIO())
  548. self.assertRecentlyModified(self.PO_FILE % 'en')
  549. self.assertNotRecentlyModified(self.PO_FILE % 'fr')
  550. self.assertNotRecentlyModified(self.PO_FILE % 'it')
  551. def test_multiple_locales_excluded_with_locale(self):
  552. management.call_command('makemessages', locale=['en', 'fr', 'it'], exclude=['fr', 'it'],
  553. stdout=StringIO())
  554. self.assertRecentlyModified(self.PO_FILE % 'en')
  555. self.assertNotRecentlyModified(self.PO_FILE % 'fr')
  556. self.assertNotRecentlyModified(self.PO_FILE % 'it')
  557. class CustomLayoutExtractionTests(ExtractorTests):
  558. work_subdir = 'project_dir'
  559. def test_no_locale_raises(self):
  560. msg = "Unable to find a locale path to store translations for file"
  561. with self.assertRaisesMessage(management.CommandError, msg):
  562. management.call_command('makemessages', locale=LOCALE, verbosity=0)
  563. def test_project_locale_paths(self):
  564. """
  565. * translations for an app containing a locale folder are stored in that folder
  566. * translations outside of that app are in LOCALE_PATHS[0]
  567. """
  568. with override_settings(LOCALE_PATHS=[os.path.join(self.test_dir, 'project_locale')]):
  569. management.call_command('makemessages', locale=[LOCALE], verbosity=0)
  570. project_de_locale = os.path.join(
  571. self.test_dir, 'project_locale', 'de', 'LC_MESSAGES', 'django.po')
  572. app_de_locale = os.path.join(
  573. self.test_dir, 'app_with_locale', 'locale', 'de', 'LC_MESSAGES', 'django.po')
  574. self.assertTrue(os.path.exists(project_de_locale))
  575. self.assertTrue(os.path.exists(app_de_locale))
  576. with open(project_de_locale, 'r') as fp:
  577. po_contents = fp.read()
  578. self.assertMsgId('This app has no locale directory', po_contents)
  579. self.assertMsgId('This is a project-level string', po_contents)
  580. with open(app_de_locale, 'r') as fp:
  581. po_contents = fp.read()
  582. self.assertMsgId('This app has a locale directory', po_contents)
  583. @skipUnless(has_xgettext, 'xgettext is mandatory for extraction tests')
  584. class NoSettingsExtractionTests(AdminScriptTestCase):
  585. def test_makemessages_no_settings(self):
  586. out, err = self.run_django_admin(['makemessages', '-l', 'en', '-v', '0'])
  587. self.assertNoOutput(err)
  588. self.assertNoOutput(out)