From 8389535eea71b9e4b5beabb8255cc151e977f95c Mon Sep 17 00:00:00 2001 From: nightcityblade Date: Thu, 13 Aug 2026 11:08:08 +0800 Subject: [PATCH] Fix extract_messages dry-run behavior --- babel/messages/frontend.py | 5 ++++- babel/messages/setuptools_frontend.py | 7 +++++++ tests/messages/test_setuptools_frontend.py | 20 ++++++++++++++++++++ 3 files changed, 31 insertions(+), 1 deletion(-) diff --git a/babel/messages/frontend.py b/babel/messages/frontend.py index 1df1e225f..6d4231d08 100644 --- a/babel/messages/frontend.py +++ b/babel/messages/frontend.py @@ -488,7 +488,7 @@ def callback(filename: str, method: str, options: dict): def run(self): mappings = self._get_mappings() - with open(self.output_file, 'wb') as outfile: + with self._open_output_file() as outfile: catalog = Catalog( project=self.project, version=self.version, @@ -550,6 +550,9 @@ def run(self): width=self.width, ) + def _open_output_file(self) -> BinaryIO: + return open(self.output_file, 'wb') + def _get_mappings(self): mappings = [] diff --git a/babel/messages/setuptools_frontend.py b/babel/messages/setuptools_frontend.py index 67b9f24e1..b19c36893 100644 --- a/babel/messages/setuptools_frontend.py +++ b/babel/messages/setuptools_frontend.py @@ -1,5 +1,7 @@ from __future__ import annotations +from io import BytesIO + from babel.messages import frontend try: @@ -65,6 +67,11 @@ class extract_messages(frontend.ExtractMessages, Command): ) """ + def _open_output_file(self): + if self.dry_run: + return BytesIO() + return super()._open_output_file() + class init_catalog(frontend.InitCatalog, Command): """New catalog initialization command for use in ``setup.py`` scripts. diff --git a/tests/messages/test_setuptools_frontend.py b/tests/messages/test_setuptools_frontend.py index 5c3f4433b..8536b8dcd 100644 --- a/tests/messages/test_setuptools_frontend.py +++ b/tests/messages/test_setuptools_frontend.py @@ -45,6 +45,26 @@ def test_extract_distutils_keyword_arg_388(kwarg, expected): assert set(cmdinst.add_comments) == {"Bar", "Foo"} +def test_extract_messages_dry_run(tmp_path, caplog): + from babel.messages import setuptools_frontend + + source_file = tmp_path / "source.py" + source_file.write_text("_('message')\n") + output_file = tmp_path / "messages.pot" + output_file.write_text("original contents\n") + + command = setuptools_frontend.extract_messages(Distribution()) + command.dry_run = True + command.input_paths = [str(source_file)] + command.output_file = str(output_file) + command.ensure_finalized() + with caplog.at_level("INFO"): + command.run() + + assert output_file.read_text() == "original contents\n" + assert f"extracting messages from {source_file}" in caplog.text + + @pytest.mark.xfail( # Python 3.10.16[pypy-7.3.19-final] in GHA fails with "unsupported locale setting" # in the subprocesses this test spawns. Hard to say why because it doesn't do that