test_extraction.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  1. # -*- encoding: utf-8 -*-
  2. from __future__ import unicode_literals
  3. import io
  4. import os
  5. import re
  6. import shutil
  7. import sys
  8. import time
  9. from unittest import SkipTest, skipUnless
  10. import warnings
  11. from django.conf import settings
  12. from django.core import management
  13. from django.core.management import execute_from_command_line
  14. from django.core.management.utils import find_command
  15. from django.test import SimpleTestCase
  16. from django.test import override_settings
  17. from django.utils.encoding import force_text
  18. from django.utils._os import upath
  19. from django.utils import six
  20. from django.utils.six import StringIO
  21. from django.utils.translation import TranslatorCommentWarning
  22. LOCALE = 'de'
  23. has_xgettext = find_command('xgettext')
  24. @skipUnless(has_xgettext, 'xgettext is mandatory for extraction tests')
  25. class ExtractorTests(SimpleTestCase):
  26. test_dir = os.path.abspath(os.path.join(os.path.dirname(upath(__file__)), 'commands'))
  27. PO_FILE = 'locale/%s/LC_MESSAGES/django.po' % LOCALE
  28. def setUp(self):
  29. self._cwd = os.getcwd()
  30. def _rmrf(self, dname):
  31. if os.path.commonprefix([self.test_dir, os.path.abspath(dname)]) != self.test_dir:
  32. return
  33. shutil.rmtree(dname)
  34. def rmfile(self, filepath):
  35. if os.path.exists(filepath):
  36. os.remove(filepath)
  37. def tearDown(self):
  38. os.chdir(self.test_dir)
  39. try:
  40. self._rmrf('locale/%s' % LOCALE)
  41. except OSError:
  42. pass
  43. os.chdir(self._cwd)
  44. def assertMsgId(self, msgid, s, use_quotes=True):
  45. q = '"'
  46. if use_quotes:
  47. msgid = '"%s"' % msgid
  48. q = "'"
  49. needle = 'msgid %s' % msgid
  50. msgid = re.escape(msgid)
  51. 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})
  52. def assertNotMsgId(self, msgid, s, use_quotes=True):
  53. if use_quotes:
  54. msgid = '"%s"' % msgid
  55. msgid = re.escape(msgid)
  56. return self.assertTrue(not re.search('^msgid %s' % msgid, s, re.MULTILINE))
  57. def _assertPoLocComment(self, assert_presence, po_filename, line_number, *comment_parts):
  58. with open(po_filename, 'r') as fp:
  59. po_contents = force_text(fp.read())
  60. if os.name == 'nt':
  61. # #: .\path\to\file.html:123
  62. cwd_prefix = '%s%s' % (os.curdir, os.sep)
  63. else:
  64. # #: path/to/file.html:123
  65. cwd_prefix = ''
  66. parts = ['#: ']
  67. parts.append(os.path.join(cwd_prefix, *comment_parts))
  68. if line_number is not None:
  69. parts.append(':%d' % line_number)
  70. needle = ''.join(parts)
  71. if assert_presence:
  72. return self.assertTrue(needle in po_contents, '"%s" not found in final .po file.' % needle)
  73. else:
  74. return self.assertFalse(needle in po_contents, '"%s" shouldn\'t be in final .po file.' % needle)
  75. def assertLocationCommentPresent(self, po_filename, line_number, *comment_parts):
  76. """
  77. self.assertLocationCommentPresent('django.po', 42, 'dirA', 'dirB', 'foo.py')
  78. verifies that the django.po file has a gettext-style location comment of the form
  79. `#: dirA/dirB/foo.py:42`
  80. (or `#: .\dirA\dirB\foo.py:42` on Windows)
  81. None can be passed for the line_number argument to skip checking of the :42 suffix part.
  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. def test_comments_extractor(self):
  101. os.chdir(self.test_dir)
  102. management.call_command('makemessages', locale=[LOCALE], verbosity=0)
  103. self.assertTrue(os.path.exists(self.PO_FILE))
  104. with io.open(self.PO_FILE, 'r', encoding='utf-8') as fp:
  105. po_contents = fp.read()
  106. self.assertTrue('#. Translators: This comment should be extracted' in po_contents)
  107. self.assertTrue('This comment should not be extracted' not in po_contents)
  108. # Comments in templates
  109. self.assertTrue('#. Translators: Django template comment for translators' in po_contents)
  110. self.assertTrue("#. Translators: Django comment block for translators\n#. string's meaning unveiled" in po_contents)
  111. self.assertTrue('#. Translators: One-line translator comment #1' in po_contents)
  112. self.assertTrue('#. Translators: Two-line translator comment #1\n#. continued here.' in po_contents)
  113. self.assertTrue('#. Translators: One-line translator comment #2' in po_contents)
  114. self.assertTrue('#. Translators: Two-line translator comment #2\n#. continued here.' in po_contents)
  115. self.assertTrue('#. Translators: One-line translator comment #3' in po_contents)
  116. self.assertTrue('#. Translators: Two-line translator comment #3\n#. continued here.' in po_contents)
  117. self.assertTrue('#. Translators: One-line translator comment #4' in po_contents)
  118. self.assertTrue('#. Translators: Two-line translator comment #4\n#. continued here.' in po_contents)
  119. self.assertTrue('#. Translators: One-line translator comment #5 -- with non ASCII characters: áéíóúö' in po_contents)
  120. self.assertTrue('#. Translators: Two-line translator comment #5 -- with non ASCII characters: áéíóúö\n#. continued here.' in po_contents)
  121. def test_templatize_trans_tag(self):
  122. # ticket #11240
  123. os.chdir(self.test_dir)
  124. management.call_command('makemessages', locale=[LOCALE], verbosity=0)
  125. self.assertTrue(os.path.exists(self.PO_FILE))
  126. with open(self.PO_FILE, 'r') as fp:
  127. po_contents = force_text(fp.read())
  128. self.assertMsgId('Literal with a percent symbol at the end %%', po_contents)
  129. self.assertMsgId('Literal with a percent %% symbol in the middle', po_contents)
  130. self.assertMsgId('Completed 50%% of all the tasks', po_contents)
  131. self.assertMsgId('Completed 99%% of all the tasks', po_contents)
  132. self.assertMsgId("Shouldn't double escape this sequence: %% (two percent signs)", po_contents)
  133. self.assertMsgId("Shouldn't double escape this sequence %% either", po_contents)
  134. self.assertMsgId("Looks like a str fmt spec %%s but shouldn't be interpreted as such", po_contents)
  135. self.assertMsgId("Looks like a str fmt spec %% o but shouldn't be interpreted as such", po_contents)
  136. def test_templatize_blocktrans_tag(self):
  137. # ticket #11966
  138. os.chdir(self.test_dir)
  139. management.call_command('makemessages', locale=[LOCALE], verbosity=0)
  140. self.assertTrue(os.path.exists(self.PO_FILE))
  141. with open(self.PO_FILE, 'r') as fp:
  142. po_contents = force_text(fp.read())
  143. self.assertMsgId('I think that 100%% is more that 50%% of anything.', po_contents)
  144. self.assertMsgId('I think that 100%% is more that 50%% of %(obj)s.', po_contents)
  145. self.assertMsgId("Blocktrans extraction shouldn't double escape this: %%, a=%(a)s", po_contents)
  146. def test_blocktrans_trimmed(self):
  147. os.chdir(self.test_dir)
  148. management.call_command('makemessages', locale=[LOCALE], verbosity=0)
  149. self.assertTrue(os.path.exists(self.PO_FILE))
  150. with open(self.PO_FILE, 'r') as fp:
  151. po_contents = force_text(fp.read())
  152. # should not be trimmed
  153. self.assertNotMsgId('Text with a few line breaks.', po_contents)
  154. # should be trimmed
  155. self.assertMsgId("Again some text with a few line breaks, this time should be trimmed.", po_contents)
  156. # #21406 -- Should adjust for eaten line numbers
  157. self.assertMsgId("I'm on line 97", po_contents)
  158. self.assertLocationCommentPresent(self.PO_FILE, 97, 'templates', 'test.html')
  159. def test_force_en_us_locale(self):
  160. """Value of locale-munging option used by the command is the right one"""
  161. from django.core.management.commands.makemessages import Command
  162. self.assertTrue(Command.leave_locale_alone)
  163. def test_extraction_error(self):
  164. os.chdir(self.test_dir)
  165. self.assertRaises(SyntaxError, management.call_command, 'makemessages', locale=[LOCALE], extensions=['tpl'], verbosity=0)
  166. with self.assertRaises(SyntaxError) as context_manager:
  167. management.call_command('makemessages', locale=[LOCALE], extensions=['tpl'], verbosity=0)
  168. six.assertRegex(
  169. self, str(context_manager.exception),
  170. r'Translation blocks must not include other block tags: blocktrans \(file templates[/\\]template_with_error\.tpl, line 3\)'
  171. )
  172. # Check that the temporary file was cleaned up
  173. self.assertFalse(os.path.exists('./templates/template_with_error.tpl.py'))
  174. def test_unicode_decode_error(self):
  175. os.chdir(self.test_dir)
  176. shutil.copyfile('./not_utf8.sample', './not_utf8.txt')
  177. self.addCleanup(self.rmfile, os.path.join(self.test_dir, 'not_utf8.txt'))
  178. stdout = StringIO()
  179. management.call_command('makemessages', locale=[LOCALE], stdout=stdout)
  180. self.assertIn("UnicodeDecodeError: skipped file not_utf8.txt in .",
  181. force_text(stdout.getvalue()))
  182. def test_extraction_warning(self):
  183. """test xgettext warning about multiple bare interpolation placeholders"""
  184. os.chdir(self.test_dir)
  185. shutil.copyfile('./code.sample', './code_sample.py')
  186. self.addCleanup(self.rmfile, os.path.join(self.test_dir, 'code_sample.py'))
  187. stdout = StringIO()
  188. management.call_command('makemessages', locale=[LOCALE], stdout=stdout)
  189. self.assertIn("code_sample.py:4", force_text(stdout.getvalue()))
  190. def test_template_message_context_extractor(self):
  191. """
  192. Ensure that message contexts are correctly extracted for the
  193. {% trans %} and {% blocktrans %} template tags.
  194. Refs #14806.
  195. """
  196. os.chdir(self.test_dir)
  197. management.call_command('makemessages', locale=[LOCALE], verbosity=0)
  198. self.assertTrue(os.path.exists(self.PO_FILE))
  199. with open(self.PO_FILE, 'r') as fp:
  200. po_contents = force_text(fp.read())
  201. # {% trans %}
  202. self.assertTrue('msgctxt "Special trans context #1"' in po_contents)
  203. self.assertMsgId("Translatable literal #7a", po_contents)
  204. self.assertTrue('msgctxt "Special trans context #2"' in po_contents)
  205. self.assertMsgId("Translatable literal #7b", po_contents)
  206. self.assertTrue('msgctxt "Special trans context #3"' in po_contents)
  207. self.assertMsgId("Translatable literal #7c", po_contents)
  208. # {% blocktrans %}
  209. self.assertTrue('msgctxt "Special blocktrans context #1"' in po_contents)
  210. self.assertMsgId("Translatable literal #8a", po_contents)
  211. self.assertTrue('msgctxt "Special blocktrans context #2"' in po_contents)
  212. self.assertMsgId("Translatable literal #8b-singular", po_contents)
  213. self.assertTrue("Translatable literal #8b-plural" in po_contents)
  214. self.assertTrue('msgctxt "Special blocktrans context #3"' in po_contents)
  215. self.assertMsgId("Translatable literal #8c-singular", po_contents)
  216. self.assertTrue("Translatable literal #8c-plural" in po_contents)
  217. self.assertTrue('msgctxt "Special blocktrans context #4"' in po_contents)
  218. self.assertMsgId("Translatable literal #8d %(a)s", po_contents)
  219. def test_context_in_single_quotes(self):
  220. os.chdir(self.test_dir)
  221. management.call_command('makemessages', locale=[LOCALE], verbosity=0)
  222. self.assertTrue(os.path.exists(self.PO_FILE))
  223. with open(self.PO_FILE, 'r') as fp:
  224. po_contents = force_text(fp.read())
  225. # {% trans %}
  226. self.assertTrue('msgctxt "Context wrapped in double quotes"' in po_contents)
  227. self.assertTrue('msgctxt "Context wrapped in single quotes"' in po_contents)
  228. # {% blocktrans %}
  229. self.assertTrue('msgctxt "Special blocktrans context wrapped in double quotes"' in po_contents)
  230. self.assertTrue('msgctxt "Special blocktrans context wrapped in single quotes"' in po_contents)
  231. def test_template_comments(self):
  232. """Template comment tags on the same line of other constructs (#19552)"""
  233. os.chdir(self.test_dir)
  234. # Test detection/end user reporting of old, incorrect templates
  235. # translator comments syntax
  236. with warnings.catch_warnings(record=True) as ws:
  237. warnings.simplefilter('always')
  238. management.call_command('makemessages', locale=[LOCALE], extensions=['thtml'], verbosity=0)
  239. self.assertEqual(len(ws), 3)
  240. for w in ws:
  241. self.assertTrue(issubclass(w.category, TranslatorCommentWarning))
  242. six.assertRegex(
  243. self, str(ws[0].message),
  244. 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\."
  245. )
  246. six.assertRegex(
  247. self, str(ws[1].message),
  248. 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\."
  249. )
  250. six.assertRegex(
  251. self, str(ws[2].message),
  252. 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\."
  253. )
  254. # Now test .po file contents
  255. self.assertTrue(os.path.exists(self.PO_FILE))
  256. with open(self.PO_FILE, 'r') as fp:
  257. po_contents = force_text(fp.read())
  258. self.assertMsgId('Translatable literal #9a', po_contents)
  259. self.assertFalse('ignored comment #1' in po_contents)
  260. self.assertFalse('Translators: ignored i18n comment #1' in po_contents)
  261. self.assertMsgId("Translatable literal #9b", po_contents)
  262. self.assertFalse('ignored i18n comment #2' in po_contents)
  263. self.assertFalse('ignored comment #2' in po_contents)
  264. self.assertMsgId('Translatable literal #9c', po_contents)
  265. self.assertFalse('ignored comment #3' in po_contents)
  266. self.assertFalse('ignored i18n comment #3' in po_contents)
  267. self.assertMsgId('Translatable literal #9d', po_contents)
  268. self.assertFalse('ignored comment #4' in po_contents)
  269. self.assertMsgId('Translatable literal #9e', po_contents)
  270. self.assertFalse('ignored comment #5' in po_contents)
  271. self.assertFalse('ignored i18n comment #4' in po_contents)
  272. self.assertMsgId('Translatable literal #9f', po_contents)
  273. self.assertTrue('#. Translators: valid i18n comment #5' in po_contents)
  274. self.assertMsgId('Translatable literal #9g', po_contents)
  275. self.assertTrue('#. Translators: valid i18n comment #6' in po_contents)
  276. self.assertMsgId('Translatable literal #9h', po_contents)
  277. self.assertTrue('#. Translators: valid i18n comment #7' in po_contents)
  278. self.assertMsgId('Translatable literal #9i', po_contents)
  279. six.assertRegex(self, po_contents, r'#\..+Translators: valid i18n comment #8')
  280. six.assertRegex(self, po_contents, r'#\..+Translators: valid i18n comment #9')
  281. self.assertMsgId("Translatable literal #9j", po_contents)
  282. class JavascriptExtractorTests(ExtractorTests):
  283. PO_FILE = 'locale/%s/LC_MESSAGES/djangojs.po' % LOCALE
  284. def test_javascript_literals(self):
  285. os.chdir(self.test_dir)
  286. management.call_command('makemessages', domain='djangojs', locale=[LOCALE], verbosity=0)
  287. self.assertTrue(os.path.exists(self.PO_FILE))
  288. with open(self.PO_FILE, 'r') as fp:
  289. po_contents = fp.read()
  290. self.assertMsgId('This literal should be included.', po_contents)
  291. self.assertMsgId('This one as well.', po_contents)
  292. self.assertMsgId(r'He said, \"hello\".', po_contents)
  293. self.assertMsgId("okkkk", po_contents)
  294. self.assertMsgId("TEXT", po_contents)
  295. self.assertMsgId("It's at http://example.com", po_contents)
  296. self.assertMsgId("String", po_contents)
  297. self.assertMsgId("/* but this one will be too */ 'cause there is no way of telling...", po_contents)
  298. self.assertMsgId("foo", po_contents)
  299. self.assertMsgId("bar", po_contents)
  300. self.assertMsgId("baz", po_contents)
  301. self.assertMsgId("quz", po_contents)
  302. self.assertMsgId("foobar", po_contents)
  303. class IgnoredExtractorTests(ExtractorTests):
  304. def test_ignore_option(self):
  305. os.chdir(self.test_dir)
  306. ignore_patterns = [
  307. os.path.join('ignore_dir', '*'),
  308. 'xxx_*',
  309. ]
  310. stdout = StringIO()
  311. management.call_command('makemessages', locale=[LOCALE], verbosity=2,
  312. ignore_patterns=ignore_patterns, stdout=stdout)
  313. data = stdout.getvalue()
  314. self.assertTrue("ignoring directory ignore_dir" in data)
  315. self.assertTrue("ignoring file xxx_ignored.html" in data)
  316. self.assertTrue(os.path.exists(self.PO_FILE))
  317. with open(self.PO_FILE, 'r') as fp:
  318. po_contents = fp.read()
  319. self.assertMsgId('This literal should be included.', po_contents)
  320. self.assertNotMsgId('This should be ignored.', po_contents)
  321. self.assertNotMsgId('This should be ignored too.', po_contents)
  322. class SymlinkExtractorTests(ExtractorTests):
  323. def setUp(self):
  324. super(SymlinkExtractorTests, self).setUp()
  325. self.symlinked_dir = os.path.join(self.test_dir, 'templates_symlinked')
  326. def tearDown(self):
  327. super(SymlinkExtractorTests, self).tearDown()
  328. os.chdir(self.test_dir)
  329. try:
  330. os.remove(self.symlinked_dir)
  331. except OSError:
  332. pass
  333. os.chdir(self._cwd)
  334. def test_symlink(self):
  335. # On Python < 3.2 os.symlink() exists only on Unix
  336. if hasattr(os, 'symlink'):
  337. if os.path.exists(self.symlinked_dir):
  338. self.assertTrue(os.path.islink(self.symlinked_dir))
  339. else:
  340. # On Python >= 3.2) os.symlink() exists always but then can
  341. # fail at runtime when user hasn't the needed permissions on
  342. # WIndows versions that support symbolink links (>= 6/Vista).
  343. # See Python issue 9333 (http://bugs.python.org/issue9333).
  344. # Skip the test in that case
  345. try:
  346. os.symlink(os.path.join(self.test_dir, 'templates'), self.symlinked_dir)
  347. except (OSError, NotImplementedError):
  348. raise SkipTest("os.symlink() is available on this OS but can't be used by this user.")
  349. os.chdir(self.test_dir)
  350. management.call_command('makemessages', locale=[LOCALE], verbosity=0, symlinks=True)
  351. self.assertTrue(os.path.exists(self.PO_FILE))
  352. with open(self.PO_FILE, 'r') as fp:
  353. po_contents = force_text(fp.read())
  354. self.assertMsgId('This literal should be included.', po_contents)
  355. self.assertTrue('templates_symlinked/test.html' in po_contents)
  356. class CopyPluralFormsExtractorTests(ExtractorTests):
  357. PO_FILE_ES = 'locale/es/LC_MESSAGES/django.po'
  358. def tearDown(self):
  359. super(CopyPluralFormsExtractorTests, self).tearDown()
  360. os.chdir(self.test_dir)
  361. try:
  362. self._rmrf('locale/es')
  363. except OSError:
  364. pass
  365. os.chdir(self._cwd)
  366. def test_copy_plural_forms(self):
  367. os.chdir(self.test_dir)
  368. management.call_command('makemessages', locale=[LOCALE], verbosity=0)
  369. self.assertTrue(os.path.exists(self.PO_FILE))
  370. with open(self.PO_FILE, 'r') as fp:
  371. po_contents = force_text(fp.read())
  372. self.assertTrue('Plural-Forms: nplurals=2; plural=(n != 1)' in po_contents)
  373. def test_override_plural_forms(self):
  374. """Ticket #20311."""
  375. os.chdir(self.test_dir)
  376. management.call_command('makemessages', locale=['es'], extensions=['djtpl'], verbosity=0)
  377. self.assertTrue(os.path.exists(self.PO_FILE_ES))
  378. with io.open(self.PO_FILE_ES, 'r', encoding='utf-8') as fp:
  379. po_contents = fp.read()
  380. found = re.findall(r'^(?P<value>"Plural-Forms.+?\\n")\s*$', po_contents, re.MULTILINE | re.DOTALL)
  381. self.assertEqual(1, len(found))
  382. class NoWrapExtractorTests(ExtractorTests):
  383. def test_no_wrap_enabled(self):
  384. os.chdir(self.test_dir)
  385. management.call_command('makemessages', locale=[LOCALE], verbosity=0, no_wrap=True)
  386. self.assertTrue(os.path.exists(self.PO_FILE))
  387. with open(self.PO_FILE, 'r') as fp:
  388. po_contents = force_text(fp.read())
  389. self.assertMsgId('This literal should also be included wrapped or not wrapped depending on the use of the --no-wrap option.', po_contents)
  390. def test_no_wrap_disabled(self):
  391. os.chdir(self.test_dir)
  392. management.call_command('makemessages', locale=[LOCALE], verbosity=0, no_wrap=False)
  393. self.assertTrue(os.path.exists(self.PO_FILE))
  394. with open(self.PO_FILE, 'r') as fp:
  395. po_contents = force_text(fp.read())
  396. 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)
  397. class LocationCommentsTests(ExtractorTests):
  398. def test_no_location_enabled(self):
  399. """Behavior is correct if --no-location switch is specified. See #16903."""
  400. os.chdir(self.test_dir)
  401. management.call_command('makemessages', locale=[LOCALE], verbosity=0, no_location=True)
  402. self.assertTrue(os.path.exists(self.PO_FILE))
  403. self.assertLocationCommentNotPresent(self.PO_FILE, 55, 'templates', 'test.html.py')
  404. def test_no_location_disabled(self):
  405. """Behavior is correct if --no-location switch isn't specified."""
  406. os.chdir(self.test_dir)
  407. management.call_command('makemessages', locale=[LOCALE], verbosity=0, no_location=False)
  408. self.assertTrue(os.path.exists(self.PO_FILE))
  409. # #16903 -- Standard comment with source file relative path should be present
  410. self.assertLocationCommentPresent(self.PO_FILE, 55, 'templates', 'test.html')
  411. # #21208 -- Leaky paths in comments on Windows e.g. #: path\to\file.html.py:123
  412. self.assertLocationCommentNotPresent(self.PO_FILE, None, 'templates', 'test.html.py')
  413. class KeepPotFileExtractorTests(ExtractorTests):
  414. POT_FILE = 'locale/django.pot'
  415. def setUp(self):
  416. super(KeepPotFileExtractorTests, self).setUp()
  417. def tearDown(self):
  418. super(KeepPotFileExtractorTests, self).tearDown()
  419. os.chdir(self.test_dir)
  420. try:
  421. os.unlink(self.POT_FILE)
  422. except OSError:
  423. pass
  424. os.chdir(self._cwd)
  425. def test_keep_pot_disabled_by_default(self):
  426. os.chdir(self.test_dir)
  427. management.call_command('makemessages', locale=[LOCALE], verbosity=0)
  428. self.assertFalse(os.path.exists(self.POT_FILE))
  429. def test_keep_pot_explicitly_disabled(self):
  430. os.chdir(self.test_dir)
  431. management.call_command('makemessages', locale=[LOCALE], verbosity=0,
  432. keep_pot=False)
  433. self.assertFalse(os.path.exists(self.POT_FILE))
  434. def test_keep_pot_enabled(self):
  435. os.chdir(self.test_dir)
  436. management.call_command('makemessages', locale=[LOCALE], verbosity=0,
  437. keep_pot=True)
  438. self.assertTrue(os.path.exists(self.POT_FILE))
  439. class MultipleLocaleExtractionTests(ExtractorTests):
  440. PO_FILE_PT = 'locale/pt/LC_MESSAGES/django.po'
  441. PO_FILE_DE = 'locale/de/LC_MESSAGES/django.po'
  442. LOCALES = ['pt', 'de', 'ch']
  443. def tearDown(self):
  444. os.chdir(self.test_dir)
  445. for locale in self.LOCALES:
  446. try:
  447. self._rmrf('locale/%s' % locale)
  448. except OSError:
  449. pass
  450. os.chdir(self._cwd)
  451. def test_multiple_locales(self):
  452. os.chdir(self.test_dir)
  453. management.call_command('makemessages', locale=['pt', 'de'], verbosity=0)
  454. self.assertTrue(os.path.exists(self.PO_FILE_PT))
  455. self.assertTrue(os.path.exists(self.PO_FILE_DE))
  456. class ExcludedLocaleExtractionTests(ExtractorTests):
  457. LOCALES = ['en', 'fr', 'it']
  458. PO_FILE = 'locale/%s/LC_MESSAGES/django.po'
  459. test_dir = os.path.abspath(os.path.join(os.path.dirname(upath(__file__)), 'exclude'))
  460. def _set_times_for_all_po_files(self):
  461. """
  462. Set access and modification times to the Unix epoch time for all the .po files.
  463. """
  464. for locale in self.LOCALES:
  465. os.utime(self.PO_FILE % locale, (0, 0))
  466. def setUp(self):
  467. super(ExcludedLocaleExtractionTests, self).setUp()
  468. os.chdir(self.test_dir) # ExtractorTests.tearDown() takes care of restoring.
  469. shutil.copytree('canned_locale', 'locale')
  470. self._set_times_for_all_po_files()
  471. self.addCleanup(self._rmrf, os.path.join(self.test_dir, 'locale'))
  472. def test_command_help(self):
  473. old_stdout, old_stderr = sys.stdout, sys.stderr
  474. sys.stdout, sys.stderr = StringIO(), StringIO()
  475. try:
  476. # `call_command` bypasses the parser; by calling
  477. # `execute_from_command_line` with the help subcommand we
  478. # ensure that there are no issues with the parser itself.
  479. execute_from_command_line(['django-admin', 'help', 'makemessages'])
  480. finally:
  481. sys.stdout, sys.stderr = old_stdout, old_stderr
  482. def test_one_locale_excluded(self):
  483. management.call_command('makemessages', exclude=['it'], stdout=StringIO())
  484. self.assertRecentlyModified(self.PO_FILE % 'en')
  485. self.assertRecentlyModified(self.PO_FILE % 'fr')
  486. self.assertNotRecentlyModified(self.PO_FILE % 'it')
  487. def test_multiple_locales_excluded(self):
  488. management.call_command('makemessages', exclude=['it', 'fr'], stdout=StringIO())
  489. self.assertRecentlyModified(self.PO_FILE % 'en')
  490. self.assertNotRecentlyModified(self.PO_FILE % 'fr')
  491. self.assertNotRecentlyModified(self.PO_FILE % 'it')
  492. def test_one_locale_excluded_with_locale(self):
  493. management.call_command('makemessages', locale=['en', 'fr'], exclude=['fr'], stdout=StringIO())
  494. self.assertRecentlyModified(self.PO_FILE % 'en')
  495. self.assertNotRecentlyModified(self.PO_FILE % 'fr')
  496. self.assertNotRecentlyModified(self.PO_FILE % 'it')
  497. def test_multiple_locales_excluded_with_locale(self):
  498. management.call_command('makemessages', locale=['en', 'fr', 'it'], exclude=['fr', 'it'],
  499. stdout=StringIO())
  500. self.assertRecentlyModified(self.PO_FILE % 'en')
  501. self.assertNotRecentlyModified(self.PO_FILE % 'fr')
  502. self.assertNotRecentlyModified(self.PO_FILE % 'it')
  503. class CustomLayoutExtractionTests(ExtractorTests):
  504. def setUp(self):
  505. self._cwd = os.getcwd()
  506. self.test_dir = os.path.join(os.path.dirname(upath(__file__)), 'project_dir')
  507. def test_no_locale_raises(self):
  508. os.chdir(self.test_dir)
  509. with six.assertRaisesRegex(self, management.CommandError,
  510. "Unable to find a locale path to store translations for file"):
  511. management.call_command('makemessages', locale=LOCALE, verbosity=0)
  512. @override_settings(
  513. LOCALE_PATHS=(os.path.join(
  514. os.path.dirname(upath(__file__)), 'project_dir', 'project_locale'),)
  515. )
  516. def test_project_locale_paths(self):
  517. """
  518. Test that:
  519. * translations for an app containing a locale folder are stored in that folder
  520. * translations outside of that app are in LOCALE_PATHS[0]
  521. """
  522. os.chdir(self.test_dir)
  523. self.addCleanup(shutil.rmtree,
  524. os.path.join(settings.LOCALE_PATHS[0], LOCALE), True)
  525. self.addCleanup(shutil.rmtree,
  526. os.path.join(self.test_dir, 'app_with_locale', 'locale', LOCALE), True)
  527. management.call_command('makemessages', locale=[LOCALE], verbosity=0)
  528. project_de_locale = os.path.join(
  529. self.test_dir, 'project_locale', 'de', 'LC_MESSAGES', 'django.po')
  530. app_de_locale = os.path.join(
  531. self.test_dir, 'app_with_locale', 'locale', 'de', 'LC_MESSAGES', 'django.po')
  532. self.assertTrue(os.path.exists(project_de_locale))
  533. self.assertTrue(os.path.exists(app_de_locale))
  534. with open(project_de_locale, 'r') as fp:
  535. po_contents = force_text(fp.read())
  536. self.assertMsgId('This app has no locale directory', po_contents)
  537. self.assertMsgId('This is a project-level string', po_contents)
  538. with open(app_de_locale, 'r') as fp:
  539. po_contents = force_text(fp.read())
  540. self.assertMsgId('This app has a locale directory', po_contents)