test_extraction.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711
  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.encoding import force_text
  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 = force_text(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 force_text(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 = force_text(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 .",
  178. force_text(out.getvalue()))
  179. def test_unicode_file_name(self):
  180. open(os.path.join(self.test_dir, 'vidéo.txt'), 'a').close()
  181. management.call_command('makemessages', locale=[LOCALE], verbosity=0)
  182. def test_extraction_warning(self):
  183. """test xgettext warning about multiple bare interpolation placeholders"""
  184. shutil.copyfile('./code.sample', './code_sample.py')
  185. out = StringIO()
  186. management.call_command('makemessages', locale=[LOCALE], stdout=out)
  187. self.assertIn("code_sample.py:4", force_text(out.getvalue()))
  188. def test_template_message_context_extractor(self):
  189. """
  190. Message contexts are correctly extracted for the {% trans %} and
  191. {% blocktrans %} template tags (#14806).
  192. """
  193. management.call_command('makemessages', locale=[LOCALE], verbosity=0)
  194. self.assertTrue(os.path.exists(self.PO_FILE))
  195. with open(self.PO_FILE, 'r') as fp:
  196. po_contents = force_text(fp.read())
  197. # {% trans %}
  198. self.assertIn('msgctxt "Special trans context #1"', po_contents)
  199. self.assertMsgId("Translatable literal #7a", po_contents)
  200. self.assertIn('msgctxt "Special trans context #2"', po_contents)
  201. self.assertMsgId("Translatable literal #7b", po_contents)
  202. self.assertIn('msgctxt "Special trans context #3"', po_contents)
  203. self.assertMsgId("Translatable literal #7c", po_contents)
  204. # {% trans %} with a filter
  205. for minor_part in 'abcdefgh': # Iterate from #7.1a to #7.1h template markers
  206. self.assertIn('msgctxt "context #7.1{}"'.format(minor_part), po_contents)
  207. self.assertMsgId('Translatable literal #7.1{}'.format(minor_part), po_contents)
  208. # {% blocktrans %}
  209. self.assertIn('msgctxt "Special blocktrans context #1"', po_contents)
  210. self.assertMsgId("Translatable literal #8a", po_contents)
  211. self.assertIn('msgctxt "Special blocktrans context #2"', po_contents)
  212. self.assertMsgId("Translatable literal #8b-singular", po_contents)
  213. self.assertIn("Translatable literal #8b-plural", po_contents)
  214. self.assertIn('msgctxt "Special blocktrans context #3"', po_contents)
  215. self.assertMsgId("Translatable literal #8c-singular", po_contents)
  216. self.assertIn("Translatable literal #8c-plural", po_contents)
  217. self.assertIn('msgctxt "Special blocktrans context #4"', po_contents)
  218. self.assertMsgId("Translatable literal #8d %(a)s", po_contents)
  219. def test_context_in_single_quotes(self):
  220. management.call_command('makemessages', locale=[LOCALE], verbosity=0)
  221. self.assertTrue(os.path.exists(self.PO_FILE))
  222. with open(self.PO_FILE, 'r') as fp:
  223. po_contents = force_text(fp.read())
  224. # {% trans %}
  225. self.assertIn('msgctxt "Context wrapped in double quotes"', po_contents)
  226. self.assertIn('msgctxt "Context wrapped in single quotes"', po_contents)
  227. # {% blocktrans %}
  228. self.assertIn('msgctxt "Special blocktrans context wrapped in double quotes"', po_contents)
  229. self.assertIn('msgctxt "Special blocktrans context wrapped in single quotes"', po_contents)
  230. def test_template_comments(self):
  231. """Template comment tags on the same line of other constructs (#19552)"""
  232. # Test detection/end user reporting of old, incorrect templates
  233. # translator comments syntax
  234. with warnings.catch_warnings(record=True) as ws:
  235. warnings.simplefilter('always')
  236. management.call_command('makemessages', locale=[LOCALE], extensions=['thtml'], verbosity=0)
  237. self.assertEqual(len(ws), 3)
  238. for w in ws:
  239. self.assertTrue(issubclass(w.category, TranslatorCommentWarning))
  240. self.assertRegex(
  241. str(ws[0].message),
  242. r"The translator-targeted comment 'Translators: ignored i18n "
  243. r"comment #1' \(file templates[/\\]comments.thtml, line 4\) "
  244. r"was ignored, because it wasn't the last item on the line\."
  245. )
  246. self.assertRegex(
  247. str(ws[1].message),
  248. r"The translator-targeted comment 'Translators: ignored i18n "
  249. r"comment #3' \(file templates[/\\]comments.thtml, line 6\) "
  250. r"was ignored, because it wasn't the last item on the line\."
  251. )
  252. self.assertRegex(
  253. str(ws[2].message),
  254. r"The translator-targeted comment 'Translators: ignored i18n "
  255. r"comment #4' \(file templates[/\\]comments.thtml, line 8\) "
  256. r"was ignored, because it wasn't the last item on the line\."
  257. )
  258. # Now test .po file contents
  259. self.assertTrue(os.path.exists(self.PO_FILE))
  260. with open(self.PO_FILE, 'r') as fp:
  261. po_contents = force_text(fp.read())
  262. self.assertMsgId('Translatable literal #9a', po_contents)
  263. self.assertNotIn('ignored comment #1', po_contents)
  264. self.assertNotIn('Translators: ignored i18n comment #1', po_contents)
  265. self.assertMsgId("Translatable literal #9b", po_contents)
  266. self.assertNotIn('ignored i18n comment #2', po_contents)
  267. self.assertNotIn('ignored comment #2', po_contents)
  268. self.assertMsgId('Translatable literal #9c', po_contents)
  269. self.assertNotIn('ignored comment #3', po_contents)
  270. self.assertNotIn('ignored i18n comment #3', po_contents)
  271. self.assertMsgId('Translatable literal #9d', po_contents)
  272. self.assertNotIn('ignored comment #4', po_contents)
  273. self.assertMsgId('Translatable literal #9e', po_contents)
  274. self.assertNotIn('ignored comment #5', po_contents)
  275. self.assertNotIn('ignored i18n comment #4', po_contents)
  276. self.assertMsgId('Translatable literal #9f', po_contents)
  277. self.assertIn('#. Translators: valid i18n comment #5', po_contents)
  278. self.assertMsgId('Translatable literal #9g', po_contents)
  279. self.assertIn('#. Translators: valid i18n comment #6', po_contents)
  280. self.assertMsgId('Translatable literal #9h', po_contents)
  281. self.assertIn('#. Translators: valid i18n comment #7', po_contents)
  282. self.assertMsgId('Translatable literal #9i', po_contents)
  283. self.assertRegex(po_contents, r'#\..+Translators: valid i18n comment #8')
  284. self.assertRegex(po_contents, r'#\..+Translators: valid i18n comment #9')
  285. self.assertMsgId("Translatable literal #9j", po_contents)
  286. def test_makemessages_find_files(self):
  287. """
  288. find_files only discover files having the proper extensions.
  289. """
  290. cmd = MakeMessagesCommand()
  291. cmd.ignore_patterns = ['CVS', '.*', '*~', '*.pyc']
  292. cmd.symlinks = False
  293. cmd.domain = 'django'
  294. cmd.extensions = ['html', 'txt', 'py']
  295. cmd.verbosity = 0
  296. cmd.locale_paths = []
  297. cmd.default_locale_path = os.path.join(self.test_dir, 'locale')
  298. found_files = cmd.find_files(self.test_dir)
  299. found_exts = set([os.path.splitext(tfile.file)[1] for tfile in found_files])
  300. self.assertEqual(found_exts.difference({'.py', '.html', '.txt'}), set())
  301. cmd.extensions = ['js']
  302. cmd.domain = 'djangojs'
  303. found_files = cmd.find_files(self.test_dir)
  304. found_exts = set([os.path.splitext(tfile.file)[1] for tfile in found_files])
  305. self.assertEqual(found_exts.difference({'.js'}), set())
  306. @mock.patch('django.core.management.commands.makemessages.popen_wrapper')
  307. def test_makemessages_gettext_version(self, mocked_popen_wrapper):
  308. # "Normal" output:
  309. mocked_popen_wrapper.return_value = (
  310. "xgettext (GNU gettext-tools) 0.18.1\n"
  311. "Copyright (C) 1995-1998, 2000-2010 Free Software Foundation, Inc.\n"
  312. "License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>\n"
  313. "This is free software: you are free to change and redistribute it.\n"
  314. "There is NO WARRANTY, to the extent permitted by law.\n"
  315. "Written by Ulrich Drepper.\n", '', 0)
  316. cmd = MakeMessagesCommand()
  317. self.assertEqual(cmd.gettext_version, (0, 18, 1))
  318. # Version number with only 2 parts (#23788)
  319. mocked_popen_wrapper.return_value = (
  320. "xgettext (GNU gettext-tools) 0.17\n", '', 0)
  321. cmd = MakeMessagesCommand()
  322. self.assertEqual(cmd.gettext_version, (0, 17))
  323. # Bad version output
  324. mocked_popen_wrapper.return_value = (
  325. "any other return value\n", '', 0)
  326. cmd = MakeMessagesCommand()
  327. with self.assertRaisesMessage(CommandError, "Unable to get gettext version. Is it installed?"):
  328. cmd.gettext_version
  329. def test_po_file_encoding_when_updating(self):
  330. """Update of PO file doesn't corrupt it with non-UTF-8 encoding on Python3+Windows (#23271)"""
  331. BR_PO_BASE = 'locale/pt_BR/LC_MESSAGES/django'
  332. shutil.copyfile(BR_PO_BASE + '.pristine', BR_PO_BASE + '.po')
  333. management.call_command('makemessages', locale=['pt_BR'], verbosity=0)
  334. self.assertTrue(os.path.exists(BR_PO_BASE + '.po'))
  335. with open(BR_PO_BASE + '.po', 'r', encoding='utf-8') as fp:
  336. po_contents = force_text(fp.read())
  337. self.assertMsgStr("Größe", po_contents)
  338. class JavascriptExtractorTests(ExtractorTests):
  339. PO_FILE = 'locale/%s/LC_MESSAGES/djangojs.po' % LOCALE
  340. def test_javascript_literals(self):
  341. _, po_contents = self._run_makemessages(domain='djangojs')
  342. self.assertMsgId('This literal should be included.', po_contents)
  343. self.assertMsgId('gettext_noop should, too.', po_contents)
  344. self.assertMsgId('This one as well.', po_contents)
  345. self.assertMsgId(r'He said, \"hello\".', po_contents)
  346. self.assertMsgId("okkkk", po_contents)
  347. self.assertMsgId("TEXT", po_contents)
  348. self.assertMsgId("It's at http://example.com", po_contents)
  349. self.assertMsgId("String", po_contents)
  350. self.assertMsgId("/* but this one will be too */ 'cause there is no way of telling...", po_contents)
  351. self.assertMsgId("foo", po_contents)
  352. self.assertMsgId("bar", po_contents)
  353. self.assertMsgId("baz", po_contents)
  354. self.assertMsgId("quz", po_contents)
  355. self.assertMsgId("foobar", po_contents)
  356. def test_media_static_dirs_ignored(self):
  357. """
  358. Regression test for #23583.
  359. """
  360. with override_settings(STATIC_ROOT=os.path.join(self.test_dir, 'static/'),
  361. MEDIA_ROOT=os.path.join(self.test_dir, 'media_root/')):
  362. _, po_contents = self._run_makemessages(domain='djangojs')
  363. self.assertMsgId("Static content inside app should be included.", po_contents)
  364. self.assertNotMsgId("Content from STATIC_ROOT should not be included", po_contents)
  365. @override_settings(STATIC_ROOT=None, MEDIA_ROOT='')
  366. def test_default_root_settings(self):
  367. """
  368. Regression test for #23717.
  369. """
  370. _, po_contents = self._run_makemessages(domain='djangojs')
  371. self.assertMsgId("Static content inside app should be included.", po_contents)
  372. class IgnoredExtractorTests(ExtractorTests):
  373. def test_ignore_directory(self):
  374. out, po_contents = self._run_makemessages(ignore_patterns=[
  375. os.path.join('ignore_dir', '*'),
  376. ])
  377. self.assertIn("ignoring directory ignore_dir", out)
  378. self.assertMsgId('This literal should be included.', po_contents)
  379. self.assertNotMsgId('This should be ignored.', po_contents)
  380. def test_ignore_subdirectory(self):
  381. out, po_contents = self._run_makemessages(ignore_patterns=[
  382. 'templates/*/ignore.html',
  383. 'templates/subdir/*',
  384. ])
  385. self.assertIn("ignoring directory subdir", out)
  386. self.assertNotMsgId('This subdir should be ignored too.', po_contents)
  387. def test_ignore_file_patterns(self):
  388. out, po_contents = self._run_makemessages(ignore_patterns=[
  389. 'xxx_*',
  390. ])
  391. self.assertIn("ignoring file xxx_ignored.html", out)
  392. self.assertNotMsgId('This should be ignored too.', po_contents)
  393. def test_media_static_dirs_ignored(self):
  394. with override_settings(STATIC_ROOT=os.path.join(self.test_dir, 'static/'),
  395. MEDIA_ROOT=os.path.join(self.test_dir, 'media_root/')):
  396. out, _ = self._run_makemessages()
  397. self.assertIn("ignoring directory static", out)
  398. self.assertIn("ignoring directory media_root", out)
  399. class SymlinkExtractorTests(ExtractorTests):
  400. def setUp(self):
  401. super(SymlinkExtractorTests, self).setUp()
  402. self.symlinked_dir = os.path.join(self.test_dir, 'templates_symlinked')
  403. def test_symlink(self):
  404. # On Python < 3.2 os.symlink() exists only on Unix
  405. if hasattr(os, 'symlink'):
  406. if os.path.exists(self.symlinked_dir):
  407. self.assertTrue(os.path.islink(self.symlinked_dir))
  408. else:
  409. # On Python >= 3.2) os.symlink() exists always but then can
  410. # fail at runtime when user hasn't the needed permissions on
  411. # Windows versions that support symbolink links (>= 6/Vista).
  412. # See Python issue 9333 (http://bugs.python.org/issue9333).
  413. # Skip the test in that case
  414. try:
  415. os.symlink(os.path.join(self.test_dir, 'templates'), self.symlinked_dir)
  416. except (OSError, NotImplementedError):
  417. self.skipTest("os.symlink() is available on this OS but can't be used by this user.")
  418. os.chdir(self.test_dir)
  419. management.call_command('makemessages', locale=[LOCALE], verbosity=0, symlinks=True)
  420. self.assertTrue(os.path.exists(self.PO_FILE))
  421. with open(self.PO_FILE, 'r') as fp:
  422. po_contents = force_text(fp.read())
  423. self.assertMsgId('This literal should be included.', po_contents)
  424. self.assertLocationCommentPresent(self.PO_FILE, None, 'templates_symlinked', 'test.html')
  425. else:
  426. self.skipTest("os.symlink() not available on this OS + Python version combination.")
  427. class CopyPluralFormsExtractorTests(ExtractorTests):
  428. PO_FILE_ES = 'locale/es/LC_MESSAGES/django.po'
  429. def test_copy_plural_forms(self):
  430. management.call_command('makemessages', locale=[LOCALE], verbosity=0)
  431. self.assertTrue(os.path.exists(self.PO_FILE))
  432. with open(self.PO_FILE, 'r') as fp:
  433. po_contents = force_text(fp.read())
  434. self.assertIn('Plural-Forms: nplurals=2; plural=(n != 1)', po_contents)
  435. def test_override_plural_forms(self):
  436. """Ticket #20311."""
  437. management.call_command('makemessages', locale=['es'], extensions=['djtpl'], verbosity=0)
  438. self.assertTrue(os.path.exists(self.PO_FILE_ES))
  439. with open(self.PO_FILE_ES, 'r', encoding='utf-8') as fp:
  440. po_contents = fp.read()
  441. found = re.findall(r'^(?P<value>"Plural-Forms.+?\\n")\s*$', po_contents, re.MULTILINE | re.DOTALL)
  442. self.assertEqual(1, len(found))
  443. def test_trans_and_plural_blocktrans_collision(self):
  444. """
  445. Ensures a correct workaround for the gettext bug when handling a literal
  446. found inside a {% trans %} tag and also in another file inside a
  447. {% blocktrans %} with a plural (#17375).
  448. """
  449. management.call_command('makemessages', locale=[LOCALE], extensions=['html', 'djtpl'], verbosity=0)
  450. self.assertTrue(os.path.exists(self.PO_FILE))
  451. with open(self.PO_FILE, 'r') as fp:
  452. po_contents = force_text(fp.read())
  453. self.assertNotIn("#-#-#-#-# django.pot (PACKAGE VERSION) #-#-#-#-#\\n", po_contents)
  454. self.assertMsgId('First `trans`, then `blocktrans` with a plural', po_contents)
  455. self.assertMsgIdPlural('Plural for a `trans` and `blocktrans` collision case', po_contents)
  456. class NoWrapExtractorTests(ExtractorTests):
  457. def test_no_wrap_enabled(self):
  458. management.call_command('makemessages', locale=[LOCALE], verbosity=0, no_wrap=True)
  459. self.assertTrue(os.path.exists(self.PO_FILE))
  460. with open(self.PO_FILE, 'r') as fp:
  461. po_contents = force_text(fp.read())
  462. self.assertMsgId(
  463. 'This literal should also be included wrapped or not wrapped '
  464. 'depending on the use of the --no-wrap option.',
  465. po_contents
  466. )
  467. def test_no_wrap_disabled(self):
  468. management.call_command('makemessages', locale=[LOCALE], verbosity=0, no_wrap=False)
  469. self.assertTrue(os.path.exists(self.PO_FILE))
  470. with open(self.PO_FILE, 'r') as fp:
  471. po_contents = force_text(fp.read())
  472. self.assertMsgId(
  473. '""\n"This literal should also be included wrapped or not '
  474. 'wrapped depending on the "\n"use of the --no-wrap option."',
  475. po_contents,
  476. use_quotes=False
  477. )
  478. class LocationCommentsTests(ExtractorTests):
  479. def test_no_location_enabled(self):
  480. """Behavior is correct if --no-location switch is specified. See #16903."""
  481. management.call_command('makemessages', locale=[LOCALE], verbosity=0, no_location=True)
  482. self.assertTrue(os.path.exists(self.PO_FILE))
  483. self.assertLocationCommentNotPresent(self.PO_FILE, None, 'test.html')
  484. def test_no_location_disabled(self):
  485. """Behavior is correct if --no-location switch isn't specified."""
  486. management.call_command('makemessages', locale=[LOCALE], verbosity=0, no_location=False)
  487. self.assertTrue(os.path.exists(self.PO_FILE))
  488. # #16903 -- Standard comment with source file relative path should be present
  489. self.assertLocationCommentPresent(self.PO_FILE, 'Translatable literal #6b', 'templates', 'test.html')
  490. def test_location_comments_for_templatized_files(self):
  491. """
  492. Ensure no leaky paths in comments, e.g. #: path\to\file.html.py:123
  493. Refs #21209/#26341.
  494. """
  495. management.call_command('makemessages', locale=[LOCALE], verbosity=0)
  496. self.assertTrue(os.path.exists(self.PO_FILE))
  497. with open(self.PO_FILE, 'r') as fp:
  498. po_contents = force_text(fp.read())
  499. self.assertMsgId('#: templates/test.html.py', po_contents)
  500. self.assertLocationCommentNotPresent(self.PO_FILE, None, '.html.py')
  501. self.assertLocationCommentPresent(self.PO_FILE, 5, 'templates', 'test.html')
  502. class KeepPotFileExtractorTests(ExtractorTests):
  503. POT_FILE = 'locale/django.pot'
  504. def test_keep_pot_disabled_by_default(self):
  505. management.call_command('makemessages', locale=[LOCALE], verbosity=0)
  506. self.assertFalse(os.path.exists(self.POT_FILE))
  507. def test_keep_pot_explicitly_disabled(self):
  508. management.call_command('makemessages', locale=[LOCALE], verbosity=0,
  509. keep_pot=False)
  510. self.assertFalse(os.path.exists(self.POT_FILE))
  511. def test_keep_pot_enabled(self):
  512. management.call_command('makemessages', locale=[LOCALE], verbosity=0,
  513. keep_pot=True)
  514. self.assertTrue(os.path.exists(self.POT_FILE))
  515. class MultipleLocaleExtractionTests(ExtractorTests):
  516. PO_FILE_PT = 'locale/pt/LC_MESSAGES/django.po'
  517. PO_FILE_DE = 'locale/de/LC_MESSAGES/django.po'
  518. LOCALES = ['pt', 'de', 'ch']
  519. def test_multiple_locales(self):
  520. management.call_command('makemessages', locale=['pt', 'de'], verbosity=0)
  521. self.assertTrue(os.path.exists(self.PO_FILE_PT))
  522. self.assertTrue(os.path.exists(self.PO_FILE_DE))
  523. class ExcludedLocaleExtractionTests(ExtractorTests):
  524. work_subdir = 'exclude'
  525. LOCALES = ['en', 'fr', 'it']
  526. PO_FILE = 'locale/%s/LC_MESSAGES/django.po'
  527. def _set_times_for_all_po_files(self):
  528. """
  529. Set access and modification times to the Unix epoch time for all the .po files.
  530. """
  531. for locale in self.LOCALES:
  532. os.utime(self.PO_FILE % locale, (0, 0))
  533. def setUp(self):
  534. super(ExcludedLocaleExtractionTests, self).setUp()
  535. copytree('canned_locale', 'locale')
  536. self._set_times_for_all_po_files()
  537. def test_command_help(self):
  538. with captured_stdout(), captured_stderr():
  539. # `call_command` bypasses the parser; by calling
  540. # `execute_from_command_line` with the help subcommand we
  541. # ensure that there are no issues with the parser itself.
  542. execute_from_command_line(['django-admin', 'help', 'makemessages'])
  543. def test_one_locale_excluded(self):
  544. management.call_command('makemessages', exclude=['it'], stdout=StringIO())
  545. self.assertRecentlyModified(self.PO_FILE % 'en')
  546. self.assertRecentlyModified(self.PO_FILE % 'fr')
  547. self.assertNotRecentlyModified(self.PO_FILE % 'it')
  548. def test_multiple_locales_excluded(self):
  549. management.call_command('makemessages', exclude=['it', 'fr'], stdout=StringIO())
  550. self.assertRecentlyModified(self.PO_FILE % 'en')
  551. self.assertNotRecentlyModified(self.PO_FILE % 'fr')
  552. self.assertNotRecentlyModified(self.PO_FILE % 'it')
  553. def test_one_locale_excluded_with_locale(self):
  554. management.call_command('makemessages', locale=['en', 'fr'], exclude=['fr'], stdout=StringIO())
  555. self.assertRecentlyModified(self.PO_FILE % 'en')
  556. self.assertNotRecentlyModified(self.PO_FILE % 'fr')
  557. self.assertNotRecentlyModified(self.PO_FILE % 'it')
  558. def test_multiple_locales_excluded_with_locale(self):
  559. management.call_command('makemessages', locale=['en', 'fr', 'it'], exclude=['fr', 'it'],
  560. stdout=StringIO())
  561. self.assertRecentlyModified(self.PO_FILE % 'en')
  562. self.assertNotRecentlyModified(self.PO_FILE % 'fr')
  563. self.assertNotRecentlyModified(self.PO_FILE % 'it')
  564. class CustomLayoutExtractionTests(ExtractorTests):
  565. work_subdir = 'project_dir'
  566. def test_no_locale_raises(self):
  567. msg = "Unable to find a locale path to store translations for file"
  568. with self.assertRaisesMessage(management.CommandError, msg):
  569. management.call_command('makemessages', locale=LOCALE, verbosity=0)
  570. def test_project_locale_paths(self):
  571. """
  572. * translations for an app containing a locale folder are stored in that folder
  573. * translations outside of that app are in LOCALE_PATHS[0]
  574. """
  575. with override_settings(LOCALE_PATHS=[os.path.join(self.test_dir, 'project_locale')]):
  576. management.call_command('makemessages', locale=[LOCALE], verbosity=0)
  577. project_de_locale = os.path.join(
  578. self.test_dir, 'project_locale', 'de', 'LC_MESSAGES', 'django.po')
  579. app_de_locale = os.path.join(
  580. self.test_dir, 'app_with_locale', 'locale', 'de', 'LC_MESSAGES', 'django.po')
  581. self.assertTrue(os.path.exists(project_de_locale))
  582. self.assertTrue(os.path.exists(app_de_locale))
  583. with open(project_de_locale, 'r') as fp:
  584. po_contents = force_text(fp.read())
  585. self.assertMsgId('This app has no locale directory', po_contents)
  586. self.assertMsgId('This is a project-level string', po_contents)
  587. with open(app_de_locale, 'r') as fp:
  588. po_contents = force_text(fp.read())
  589. self.assertMsgId('This app has a locale directory', po_contents)
  590. @skipUnless(has_xgettext, 'xgettext is mandatory for extraction tests')
  591. class NoSettingsExtractionTests(AdminScriptTestCase):
  592. def test_makemessages_no_settings(self):
  593. out, err = self.run_django_admin(['makemessages', '-l', 'en', '-v', '0'])
  594. self.assertNoOutput(err)
  595. self.assertNoOutput(out)