diff --git a/mypy/main.py b/mypy/main.py index 9982d7a6eace..b31febe0d93d 100644 --- a/mypy/main.py +++ b/mypy/main.py @@ -1723,20 +1723,25 @@ def maybe_write_junit_xml( # Elapsed time would make the output non-reproducible. td = 0.0 py_version = f"{options.python_version[0]}_{options.python_version[1]}" - if options.junit_format == "global": - util.write_junit_xml( - td, - serious, - {None: all_messages} if all_messages else {}, - options.junit_xml, - py_version, - options.platform, - ) - else: - # per_file - util.write_junit_xml( - td, serious, messages_by_file, options.junit_xml, py_version, options.platform - ) + try: + if options.junit_format == "global": + util.write_junit_xml( + td, + serious, + {None: all_messages} if all_messages else {}, + options.junit_xml, + py_version, + options.platform, + ) + else: + # per_file + util.write_junit_xml( + td, serious, messages_by_file, options.junit_xml, py_version, options.platform + ) + except OSError as err: + # A path we cannot write to is a usage problem, not an internal error + sys.stderr.write(f"error: Cannot write junit-xml to {options.junit_xml}: {err}\n") + sys.exit(2) def fail(msg: str, stderr: TextIO, options: Options) -> NoReturn: diff --git a/mypy/test/testutil.py b/mypy/test/testutil.py index e8b0257ff2eb..e5a356690e70 100644 --- a/mypy/test/testutil.py +++ b/mypy/test/testutil.py @@ -1,9 +1,13 @@ from __future__ import annotations +import io import os +import sys import tempfile from unittest import TestCase, mock +import pytest + from mypy.inspections import parse_location from mypy.main import maybe_write_junit_xml from mypy.options import Options @@ -113,6 +117,20 @@ def test_serious_error(self) -> None: ) assert result == expected + def test_junit_xml_unwritable_path_is_a_reported_error(self) -> None: + with tempfile.TemporaryDirectory() as tmpdir: + blocker = os.path.join(tmpdir, "blocker") + with open(blocker, "w") as f: + f.write("this is a file, not a directory\n") + options = Options() + options.junit_xml = os.path.join(blocker, "junit.xml") + with mock.patch.object(sys, "stderr", new_callable=io.StringIO) as stderr: + with pytest.raises(SystemExit) as exc_info: + maybe_write_junit_xml(1.23, False, [], {}, options) + assert exc_info.value.code == 2 + assert "Cannot write junit-xml to" in stderr.getvalue() + assert "INTERNAL ERROR" not in stderr.getvalue() + def test_junit_time_is_zero_in_bazel_mode(self) -> None: # Output must be reproducible under Bazel, so elapsed time is not included. with tempfile.TemporaryDirectory() as tmpdir: