test_compilation.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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 CommandError, call_command, execute_from_command_line
  10. from django.core.management.utils import find_command
  11. from django.test import SimpleTestCase, override_settings
  12. from django.test.utils import captured_stderr, captured_stdout
  13. from django.utils import translation
  14. from django.utils.translation import gettext
  15. from .utils import RunInTmpDirMixin, copytree
  16. has_msgfmt = find_command("msgfmt")
  17. @unittest.skipUnless(has_msgfmt, "msgfmt is mandatory for compilation tests")
  18. class MessageCompilationTests(RunInTmpDirMixin, SimpleTestCase):
  19. work_subdir = "commands"
  20. class PoFileTests(MessageCompilationTests):
  21. LOCALE = "es_AR"
  22. MO_FILE = "locale/%s/LC_MESSAGES/django.mo" % LOCALE
  23. MO_FILE_EN = "locale/en/LC_MESSAGES/django.mo"
  24. def test_bom_rejection(self):
  25. stderr = StringIO()
  26. with self.assertRaisesMessage(
  27. CommandError, "compilemessages generated one or more errors."
  28. ):
  29. call_command(
  30. "compilemessages", locale=[self.LOCALE], verbosity=0, stderr=stderr
  31. )
  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 = Path(self.MO_FILE_EN)
  36. err_buffer = StringIO()
  37. # Put file in read-only mode.
  38. old_mode = mo_file_en.stat().st_mode
  39. mo_file_en.chmod(stat.S_IREAD)
  40. # Ensure .po file is more recent than .mo file.
  41. mo_file_en.with_suffix(".po").touch()
  42. try:
  43. with self.assertRaisesMessage(
  44. CommandError, "compilemessages generated one or more errors."
  45. ):
  46. call_command(
  47. "compilemessages", locale=["en"], stderr=err_buffer, verbosity=0
  48. )
  49. self.assertIn("not writable location", err_buffer.getvalue())
  50. finally:
  51. mo_file_en.chmod(old_mode)
  52. def test_no_compile_when_unneeded(self):
  53. mo_file_en = Path(self.MO_FILE_EN)
  54. mo_file_en.touch()
  55. stdout = StringIO()
  56. call_command("compilemessages", locale=["en"], stdout=stdout, verbosity=1)
  57. msg = "%s” is already compiled and up to date." % mo_file_en.with_suffix(".po")
  58. self.assertIn(msg, stdout.getvalue())
  59. class PoFileContentsTests(MessageCompilationTests):
  60. # Ticket #11240
  61. LOCALE = "fr"
  62. MO_FILE = "locale/%s/LC_MESSAGES/django.mo" % LOCALE
  63. def test_percent_symbol_in_po_file(self):
  64. call_command("compilemessages", locale=[self.LOCALE], verbosity=0)
  65. self.assertTrue(os.path.exists(self.MO_FILE))
  66. class MultipleLocaleCompilationTests(MessageCompilationTests):
  67. MO_FILE_HR = None
  68. MO_FILE_FR = None
  69. def setUp(self):
  70. super().setUp()
  71. localedir = os.path.join(self.test_dir, "locale")
  72. self.MO_FILE_HR = os.path.join(localedir, "hr/LC_MESSAGES/django.mo")
  73. self.MO_FILE_FR = os.path.join(localedir, "fr/LC_MESSAGES/django.mo")
  74. def test_one_locale(self):
  75. with override_settings(LOCALE_PATHS=[os.path.join(self.test_dir, "locale")]):
  76. call_command("compilemessages", locale=["hr"], verbosity=0)
  77. self.assertTrue(os.path.exists(self.MO_FILE_HR))
  78. def test_multiple_locales(self):
  79. with override_settings(LOCALE_PATHS=[os.path.join(self.test_dir, "locale")]):
  80. call_command("compilemessages", locale=["hr", "fr"], verbosity=0)
  81. self.assertTrue(os.path.exists(self.MO_FILE_HR))
  82. self.assertTrue(os.path.exists(self.MO_FILE_FR))
  83. class ExcludedLocaleCompilationTests(MessageCompilationTests):
  84. work_subdir = "exclude"
  85. MO_FILE = "locale/%s/LC_MESSAGES/django.mo"
  86. def setUp(self):
  87. super().setUp()
  88. copytree("canned_locale", "locale")
  89. def test_command_help(self):
  90. with captured_stdout(), captured_stderr():
  91. # `call_command` bypasses the parser; by calling
  92. # `execute_from_command_line` with the help subcommand we
  93. # ensure that there are no issues with the parser itself.
  94. execute_from_command_line(["django-admin", "help", "compilemessages"])
  95. def test_one_locale_excluded(self):
  96. call_command("compilemessages", exclude=["it"], verbosity=0)
  97. self.assertTrue(os.path.exists(self.MO_FILE % "en"))
  98. self.assertTrue(os.path.exists(self.MO_FILE % "fr"))
  99. self.assertFalse(os.path.exists(self.MO_FILE % "it"))
  100. def test_multiple_locales_excluded(self):
  101. call_command("compilemessages", exclude=["it", "fr"], verbosity=0)
  102. self.assertTrue(os.path.exists(self.MO_FILE % "en"))
  103. self.assertFalse(os.path.exists(self.MO_FILE % "fr"))
  104. self.assertFalse(os.path.exists(self.MO_FILE % "it"))
  105. def test_one_locale_excluded_with_locale(self):
  106. call_command(
  107. "compilemessages", locale=["en", "fr"], exclude=["fr"], verbosity=0
  108. )
  109. self.assertTrue(os.path.exists(self.MO_FILE % "en"))
  110. self.assertFalse(os.path.exists(self.MO_FILE % "fr"))
  111. self.assertFalse(os.path.exists(self.MO_FILE % "it"))
  112. def test_multiple_locales_excluded_with_locale(self):
  113. call_command(
  114. "compilemessages",
  115. locale=["en", "fr", "it"],
  116. exclude=["fr", "it"],
  117. verbosity=0,
  118. )
  119. self.assertTrue(os.path.exists(self.MO_FILE % "en"))
  120. self.assertFalse(os.path.exists(self.MO_FILE % "fr"))
  121. self.assertFalse(os.path.exists(self.MO_FILE % "it"))
  122. class IgnoreDirectoryCompilationTests(MessageCompilationTests):
  123. # Reuse the exclude directory since it contains some locale fixtures.
  124. work_subdir = "exclude"
  125. MO_FILE = "%s/%s/LC_MESSAGES/django.mo"
  126. CACHE_DIR = Path("cache") / "locale"
  127. NESTED_DIR = Path("outdated") / "v1" / "locale"
  128. def setUp(self):
  129. super().setUp()
  130. copytree("canned_locale", "locale")
  131. copytree("canned_locale", self.CACHE_DIR)
  132. copytree("canned_locale", self.NESTED_DIR)
  133. def assertAllExist(self, dir, langs):
  134. self.assertTrue(
  135. all(Path(self.MO_FILE % (dir, lang)).exists() for lang in langs)
  136. )
  137. def assertNoneExist(self, dir, langs):
  138. self.assertTrue(
  139. all(Path(self.MO_FILE % (dir, lang)).exists() is False for lang in langs)
  140. )
  141. def test_one_locale_dir_ignored(self):
  142. call_command("compilemessages", ignore=["cache"], verbosity=0)
  143. self.assertAllExist("locale", ["en", "fr", "it"])
  144. self.assertNoneExist(self.CACHE_DIR, ["en", "fr", "it"])
  145. self.assertAllExist(self.NESTED_DIR, ["en", "fr", "it"])
  146. def test_multiple_locale_dirs_ignored(self):
  147. call_command(
  148. "compilemessages", ignore=["cache/locale", "outdated"], verbosity=0
  149. )
  150. self.assertAllExist("locale", ["en", "fr", "it"])
  151. self.assertNoneExist(self.CACHE_DIR, ["en", "fr", "it"])
  152. self.assertNoneExist(self.NESTED_DIR, ["en", "fr", "it"])
  153. def test_ignores_based_on_pattern(self):
  154. call_command("compilemessages", ignore=["*/locale"], verbosity=0)
  155. self.assertAllExist("locale", ["en", "fr", "it"])
  156. self.assertNoneExist(self.CACHE_DIR, ["en", "fr", "it"])
  157. self.assertNoneExist(self.NESTED_DIR, ["en", "fr", "it"])
  158. def test_no_dirs_accidentally_skipped(self):
  159. os_walk_results = [
  160. # To discover .po filepaths, compilemessages uses with a starting list of
  161. # basedirs to inspect, which in this scenario are:
  162. # ["conf/locale", "locale"]
  163. # Then os.walk is used to discover other locale dirs, ignoring dirs matching
  164. # `ignore_patterns`. Mock the results to place an ignored directory directly
  165. # before and after a directory named "locale".
  166. [("somedir", ["ignore", "locale", "ignore"], [])],
  167. # This will result in three basedirs discovered:
  168. # ["conf/locale", "locale", "somedir/locale"]
  169. # os.walk is called for each locale in each basedir looking for .po files.
  170. # In this scenario, we need to mock os.walk results for "en", "fr", and "it"
  171. # locales for each basedir:
  172. [("exclude/locale/LC_MESSAGES", [], ["en.po"])],
  173. [("exclude/locale/LC_MESSAGES", [], ["fr.po"])],
  174. [("exclude/locale/LC_MESSAGES", [], ["it.po"])],
  175. [("exclude/conf/locale/LC_MESSAGES", [], ["en.po"])],
  176. [("exclude/conf/locale/LC_MESSAGES", [], ["fr.po"])],
  177. [("exclude/conf/locale/LC_MESSAGES", [], ["it.po"])],
  178. [("exclude/somedir/locale/LC_MESSAGES", [], ["en.po"])],
  179. [("exclude/somedir/locale/LC_MESSAGES", [], ["fr.po"])],
  180. [("exclude/somedir/locale/LC_MESSAGES", [], ["it.po"])],
  181. ]
  182. module_path = "django.core.management.commands.compilemessages"
  183. with mock.patch(f"{module_path}.os.walk", side_effect=os_walk_results):
  184. with mock.patch(f"{module_path}.os.path.isdir", return_value=True):
  185. with mock.patch(
  186. f"{module_path}.Command.compile_messages"
  187. ) as mock_compile_messages:
  188. call_command("compilemessages", ignore=["ignore"], verbosity=4)
  189. expected = [
  190. (
  191. [
  192. ("exclude/locale/LC_MESSAGES", "en.po"),
  193. ("exclude/locale/LC_MESSAGES", "fr.po"),
  194. ("exclude/locale/LC_MESSAGES", "it.po"),
  195. ],
  196. ),
  197. (
  198. [
  199. ("exclude/conf/locale/LC_MESSAGES", "en.po"),
  200. ("exclude/conf/locale/LC_MESSAGES", "fr.po"),
  201. ("exclude/conf/locale/LC_MESSAGES", "it.po"),
  202. ],
  203. ),
  204. (
  205. [
  206. ("exclude/somedir/locale/LC_MESSAGES", "en.po"),
  207. ("exclude/somedir/locale/LC_MESSAGES", "fr.po"),
  208. ("exclude/somedir/locale/LC_MESSAGES", "it.po"),
  209. ],
  210. ),
  211. ]
  212. self.assertEqual([c.args for c in mock_compile_messages.mock_calls], expected)
  213. class CompilationErrorHandling(MessageCompilationTests):
  214. def test_error_reported_by_msgfmt(self):
  215. # po file contains wrong po formatting.
  216. with self.assertRaises(CommandError):
  217. call_command("compilemessages", locale=["ja"], verbosity=0)
  218. def test_msgfmt_error_including_non_ascii(self):
  219. # po file contains invalid msgstr content (triggers non-ascii error content).
  220. # Make sure the output of msgfmt is unaffected by the current locale.
  221. env = os.environ.copy()
  222. env.update({"LC_ALL": "C"})
  223. with mock.patch(
  224. "django.core.management.utils.run",
  225. lambda *args, **kwargs: run(*args, env=env, **kwargs),
  226. ):
  227. stderr = StringIO()
  228. with self.assertRaisesMessage(
  229. CommandError, "compilemessages generated one or more errors"
  230. ):
  231. call_command(
  232. "compilemessages", locale=["ko"], stdout=StringIO(), stderr=stderr
  233. )
  234. self.assertIn("' cannot start a field name", stderr.getvalue())
  235. class ProjectAndAppTests(MessageCompilationTests):
  236. LOCALE = "ru"
  237. PROJECT_MO_FILE = "locale/%s/LC_MESSAGES/django.mo" % LOCALE
  238. APP_MO_FILE = "app_with_locale/locale/%s/LC_MESSAGES/django.mo" % LOCALE
  239. class FuzzyTranslationTest(ProjectAndAppTests):
  240. def setUp(self):
  241. super().setUp()
  242. gettext_module._translations = {} # flush cache or test will be useless
  243. def test_nofuzzy_compiling(self):
  244. with override_settings(LOCALE_PATHS=[os.path.join(self.test_dir, "locale")]):
  245. call_command("compilemessages", locale=[self.LOCALE], verbosity=0)
  246. with translation.override(self.LOCALE):
  247. self.assertEqual(gettext("Lenin"), "Ленин")
  248. self.assertEqual(gettext("Vodka"), "Vodka")
  249. def test_fuzzy_compiling(self):
  250. with override_settings(LOCALE_PATHS=[os.path.join(self.test_dir, "locale")]):
  251. call_command(
  252. "compilemessages", locale=[self.LOCALE], fuzzy=True, verbosity=0
  253. )
  254. with translation.override(self.LOCALE):
  255. self.assertEqual(gettext("Lenin"), "Ленин")
  256. self.assertEqual(gettext("Vodka"), "Водка")
  257. class AppCompilationTest(ProjectAndAppTests):
  258. def test_app_locale_compiled(self):
  259. call_command("compilemessages", locale=[self.LOCALE], verbosity=0)
  260. self.assertTrue(os.path.exists(self.PROJECT_MO_FILE))
  261. self.assertTrue(os.path.exists(self.APP_MO_FILE))
  262. class PathLibLocaleCompilationTests(MessageCompilationTests):
  263. work_subdir = "exclude"
  264. def test_locale_paths_pathlib(self):
  265. with override_settings(LOCALE_PATHS=[Path(self.test_dir) / "canned_locale"]):
  266. call_command("compilemessages", locale=["fr"], verbosity=0)
  267. self.assertTrue(os.path.exists("canned_locale/fr/LC_MESSAGES/django.mo"))