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