test_compilation.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. import gettext as gettext_module
  2. import os
  3. import stat
  4. import unittest
  5. from io import StringIO
  6. from pathlib import Path
  7. from subprocess import run
  8. from unittest import mock
  9. from django.core.management import (
  10. CommandError, call_command, execute_from_command_line,
  11. )
  12. from django.core.management.commands.makemessages import (
  13. Command as MakeMessagesCommand,
  14. )
  15. from django.core.management.utils import find_command
  16. from django.test import SimpleTestCase, override_settings
  17. from django.test.utils import captured_stderr, captured_stdout
  18. from django.utils import translation
  19. from django.utils.translation import gettext
  20. from .utils import RunInTmpDirMixin, copytree
  21. has_msgfmt = find_command('msgfmt')
  22. @unittest.skipUnless(has_msgfmt, 'msgfmt is mandatory for compilation tests')
  23. class MessageCompilationTests(RunInTmpDirMixin, SimpleTestCase):
  24. work_subdir = 'commands'
  25. class PoFileTests(MessageCompilationTests):
  26. LOCALE = 'es_AR'
  27. MO_FILE = 'locale/%s/LC_MESSAGES/django.mo' % LOCALE
  28. def test_bom_rejection(self):
  29. stderr = StringIO()
  30. with self.assertRaisesMessage(CommandError, 'compilemessages generated one or more errors.'):
  31. call_command('compilemessages', locale=[self.LOCALE], stdout=StringIO(), stderr=stderr)
  32. self.assertIn('file has a BOM (Byte Order Mark)', stderr.getvalue())
  33. self.assertFalse(os.path.exists(self.MO_FILE))
  34. def test_no_write_access(self):
  35. mo_file_en = 'locale/en/LC_MESSAGES/django.mo'
  36. err_buffer = StringIO()
  37. # put file in read-only mode
  38. old_mode = os.stat(mo_file_en).st_mode
  39. os.chmod(mo_file_en, stat.S_IREAD)
  40. try:
  41. with self.assertRaisesMessage(CommandError, 'compilemessages generated one or more errors.'):
  42. call_command('compilemessages', locale=['en'], stderr=err_buffer, verbosity=0)
  43. self.assertIn('not writable location', err_buffer.getvalue())
  44. finally:
  45. os.chmod(mo_file_en, old_mode)
  46. class PoFileContentsTests(MessageCompilationTests):
  47. # Ticket #11240
  48. LOCALE = 'fr'
  49. MO_FILE = 'locale/%s/LC_MESSAGES/django.mo' % LOCALE
  50. def test_percent_symbol_in_po_file(self):
  51. call_command('compilemessages', locale=[self.LOCALE], stdout=StringIO())
  52. self.assertTrue(os.path.exists(self.MO_FILE))
  53. class MultipleLocaleCompilationTests(MessageCompilationTests):
  54. MO_FILE_HR = None
  55. MO_FILE_FR = None
  56. def setUp(self):
  57. super().setUp()
  58. localedir = os.path.join(self.test_dir, 'locale')
  59. self.MO_FILE_HR = os.path.join(localedir, 'hr/LC_MESSAGES/django.mo')
  60. self.MO_FILE_FR = os.path.join(localedir, 'fr/LC_MESSAGES/django.mo')
  61. def test_one_locale(self):
  62. with override_settings(LOCALE_PATHS=[os.path.join(self.test_dir, 'locale')]):
  63. call_command('compilemessages', locale=['hr'], stdout=StringIO())
  64. self.assertTrue(os.path.exists(self.MO_FILE_HR))
  65. def test_multiple_locales(self):
  66. with override_settings(LOCALE_PATHS=[os.path.join(self.test_dir, 'locale')]):
  67. call_command('compilemessages', locale=['hr', 'fr'], stdout=StringIO())
  68. self.assertTrue(os.path.exists(self.MO_FILE_HR))
  69. self.assertTrue(os.path.exists(self.MO_FILE_FR))
  70. class ExcludedLocaleCompilationTests(MessageCompilationTests):
  71. work_subdir = 'exclude'
  72. MO_FILE = 'locale/%s/LC_MESSAGES/django.mo'
  73. def setUp(self):
  74. super().setUp()
  75. copytree('canned_locale', 'locale')
  76. def test_command_help(self):
  77. with captured_stdout(), captured_stderr():
  78. # `call_command` bypasses the parser; by calling
  79. # `execute_from_command_line` with the help subcommand we
  80. # ensure that there are no issues with the parser itself.
  81. execute_from_command_line(['django-admin', 'help', 'compilemessages'])
  82. def test_one_locale_excluded(self):
  83. call_command('compilemessages', exclude=['it'], stdout=StringIO())
  84. self.assertTrue(os.path.exists(self.MO_FILE % 'en'))
  85. self.assertTrue(os.path.exists(self.MO_FILE % 'fr'))
  86. self.assertFalse(os.path.exists(self.MO_FILE % 'it'))
  87. def test_multiple_locales_excluded(self):
  88. call_command('compilemessages', exclude=['it', 'fr'], stdout=StringIO())
  89. self.assertTrue(os.path.exists(self.MO_FILE % 'en'))
  90. self.assertFalse(os.path.exists(self.MO_FILE % 'fr'))
  91. self.assertFalse(os.path.exists(self.MO_FILE % 'it'))
  92. def test_one_locale_excluded_with_locale(self):
  93. call_command('compilemessages', locale=['en', 'fr'], exclude=['fr'], stdout=StringIO())
  94. self.assertTrue(os.path.exists(self.MO_FILE % 'en'))
  95. self.assertFalse(os.path.exists(self.MO_FILE % 'fr'))
  96. self.assertFalse(os.path.exists(self.MO_FILE % 'it'))
  97. def test_multiple_locales_excluded_with_locale(self):
  98. call_command('compilemessages', locale=['en', 'fr', 'it'], exclude=['fr', 'it'],
  99. stdout=StringIO())
  100. self.assertTrue(os.path.exists(self.MO_FILE % 'en'))
  101. self.assertFalse(os.path.exists(self.MO_FILE % 'fr'))
  102. self.assertFalse(os.path.exists(self.MO_FILE % 'it'))
  103. class IgnoreDirectoryCompilationTests(MessageCompilationTests):
  104. # Reuse the exclude directory since it contains some locale fixtures.
  105. work_subdir = 'exclude'
  106. MO_FILE = '%s/%s/LC_MESSAGES/django.mo'
  107. CACHE_DIR = Path('cache') / 'locale'
  108. NESTED_DIR = Path('outdated') / 'v1' / 'locale'
  109. def setUp(self):
  110. super().setUp()
  111. copytree('canned_locale', 'locale')
  112. copytree('canned_locale', self.CACHE_DIR)
  113. copytree('canned_locale', self.NESTED_DIR)
  114. def assertAllExist(self, dir, langs):
  115. self.assertTrue(all(Path(self.MO_FILE % (dir, lang)).exists() for lang in langs))
  116. def assertNoneExist(self, dir, langs):
  117. self.assertTrue(all(Path(self.MO_FILE % (dir, lang)).exists() is False for lang in langs))
  118. def test_one_locale_dir_ignored(self):
  119. call_command('compilemessages', ignore=['cache'], verbosity=0)
  120. self.assertAllExist('locale', ['en', 'fr', 'it'])
  121. self.assertNoneExist(self.CACHE_DIR, ['en', 'fr', 'it'])
  122. self.assertAllExist(self.NESTED_DIR, ['en', 'fr', 'it'])
  123. def test_multiple_locale_dirs_ignored(self):
  124. call_command('compilemessages', ignore=['cache/locale', 'outdated'], verbosity=0)
  125. self.assertAllExist('locale', ['en', 'fr', 'it'])
  126. self.assertNoneExist(self.CACHE_DIR, ['en', 'fr', 'it'])
  127. self.assertNoneExist(self.NESTED_DIR, ['en', 'fr', 'it'])
  128. def test_ignores_based_on_pattern(self):
  129. call_command('compilemessages', ignore=['*/locale'], verbosity=0)
  130. self.assertAllExist('locale', ['en', 'fr', 'it'])
  131. self.assertNoneExist(self.CACHE_DIR, ['en', 'fr', 'it'])
  132. self.assertNoneExist(self.NESTED_DIR, ['en', 'fr', 'it'])
  133. class CompilationErrorHandling(MessageCompilationTests):
  134. def test_error_reported_by_msgfmt(self):
  135. # po file contains wrong po formatting.
  136. with self.assertRaises(CommandError):
  137. call_command('compilemessages', locale=['ja'], verbosity=0, stderr=StringIO())
  138. def test_msgfmt_error_including_non_ascii(self):
  139. # po file contains invalid msgstr content (triggers non-ascii error content).
  140. # Make sure the output of msgfmt is unaffected by the current locale.
  141. env = os.environ.copy()
  142. env.update({'LANG': 'C'})
  143. with mock.patch('django.core.management.utils.run', lambda *args, **kwargs: run(*args, env=env, **kwargs)):
  144. cmd = MakeMessagesCommand()
  145. if cmd.gettext_version < (0, 18, 3):
  146. self.skipTest("python-brace-format is a recent gettext addition.")
  147. stderr = StringIO()
  148. with self.assertRaisesMessage(CommandError, 'compilemessages generated one or more errors'):
  149. call_command('compilemessages', locale=['ko'], stdout=StringIO(), stderr=stderr)
  150. self.assertIn("' cannot start a field name", stderr.getvalue())
  151. class ProjectAndAppTests(MessageCompilationTests):
  152. LOCALE = 'ru'
  153. PROJECT_MO_FILE = 'locale/%s/LC_MESSAGES/django.mo' % LOCALE
  154. APP_MO_FILE = 'app_with_locale/locale/%s/LC_MESSAGES/django.mo' % LOCALE
  155. class FuzzyTranslationTest(ProjectAndAppTests):
  156. def setUp(self):
  157. super().setUp()
  158. gettext_module._translations = {} # flush cache or test will be useless
  159. def test_nofuzzy_compiling(self):
  160. with override_settings(LOCALE_PATHS=[os.path.join(self.test_dir, 'locale')]):
  161. call_command('compilemessages', locale=[self.LOCALE], stdout=StringIO())
  162. with translation.override(self.LOCALE):
  163. self.assertEqual(gettext('Lenin'), 'Ленин')
  164. self.assertEqual(gettext('Vodka'), 'Vodka')
  165. def test_fuzzy_compiling(self):
  166. with override_settings(LOCALE_PATHS=[os.path.join(self.test_dir, 'locale')]):
  167. call_command('compilemessages', locale=[self.LOCALE], fuzzy=True, stdout=StringIO())
  168. with translation.override(self.LOCALE):
  169. self.assertEqual(gettext('Lenin'), 'Ленин')
  170. self.assertEqual(gettext('Vodka'), 'Водка')
  171. class AppCompilationTest(ProjectAndAppTests):
  172. def test_app_locale_compiled(self):
  173. call_command('compilemessages', locale=[self.LOCALE], stdout=StringIO())
  174. self.assertTrue(os.path.exists(self.PROJECT_MO_FILE))
  175. self.assertTrue(os.path.exists(self.APP_MO_FILE))