Skip to content

An unwritable --junit-xml path is a usage error, not an internal error - #22551

Open
qianeric-backup wants to merge 1 commit into
python:masterfrom
qianeric-backup:fix/junit-xml-unwritable-path
Open

qianeric-backup wants to merge 1 commit into
python:masterfrom
qianeric-backup:fix/junit-xml-unwritable-path

Conversation

@qianeric-backup

Copy link
Copy Markdown
$ mypy --junit-xml /nope/junit.xml ok.py
error: INTERNAL ERROR -- Please try using mypy master on GitHub:
https://mypy.readthedocs.io/en/stable/common_issues.html#using-a-development-mypy-build
If this issue continues with mypy master, please report a bug at https://github.com/python/mypy/issues
version: 2.5.0+dev
note: please use --show-traceback to print a traceback when reporting a bug

Nothing is wrong with mypy there: util.write_junit_xml() calls os.makedirs() and open() on
a path the user cannot write, the OSError escapes run_build(), and the top-level handler
reports it as an internal error and asks for a bug report.

Options that name a bad path are reported normally elsewhere:

$ mypy --config-file /nope.ini ok.py
mypy: error: Cannot find config file '/nope.ini'

Change

mypy/main.py, around the maybe_write_junit_xml() call which sits outside the
except CompileError in run_build():

         py_version = f"{options.python_version[0]}_{options.python_version[1]}"
-        if options.junit_format == "global":
-            util.write_junit_xml(...)
-        else:
-            # per_file
-            util.write_junit_xml(...)
+        try:
+            if options.junit_format == "global":
+                util.write_junit_xml(...)
+            else:
+                # per_file
+                util.write_junit_xml(...)
+        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)
invocation before after
--junit-xml /nope/junit.xml error: INTERNAL ERROR -- Please try using mypy master ... please report a bug, exit 2 error: Cannot write junit-xml to /nope/junit.xml: [Errno 13] Permission denied: '/nope', exit 2
--junit-xml junit.xml report written unchanged
--junit-xml sub/junit.xml (missing dir) dirs created unchanged
mypy errors + a bad --junit-xml the error report is lost behind the internal error the mypy messages are printed as usual, then the path error

Exit 2 is what mypy already uses for serious errors (fail()), and sys.exit(2) after a
message is the same shape as the existing --exclude regex check in modulefinder.py.

The other report writers (--linecoverage-report, --any-exprs-report, --html-report)
take the same internal-error route today; this change deliberately covers --junit-xml
only, since it is the one written from main().

Test

mypy/test/testutil.py, next to the other maybe_write_junit_xml tests:

    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()

pytest mypy/test/testutil.py: 8 passed. The new test fails on an unmodified checkout with
FileExistsError from os.makedirs() (the "file used as a directory" trick keeps it
root-proof).

```
$ mypy --junit-xml /nope/junit.xml ok.py
error: INTERNAL ERROR -- Please try using mypy master on GitHub:
https://mypy.readthedocs.io/en/stable/common_issues.html#using-a-development-mypy-build
If this issue continues with mypy master, please report a bug at https://github.com/python/mypy/issues
version: 2.5.0+dev
note: please use --show-traceback to print a traceback when reporting a bug
```

Nothing is wrong with mypy there: `util.write_junit_xml()` calls `os.makedirs()` and `open()` on
a path the user cannot write, the `OSError` escapes `run_build()`, and the top-level handler
reports it as an internal error and asks for a bug report.

Options that name a bad path are reported normally elsewhere:

```
$ mypy --config-file /nope.ini ok.py
mypy: error: Cannot find config file '/nope.ini'
```

## Change

`mypy/main.py`, around the `maybe_write_junit_xml()` call which sits outside the
`except CompileError` in `run_build()`:

```python
         py_version = f"{options.python_version[0]}_{options.python_version[1]}"
-        if options.junit_format == "global":
-            util.write_junit_xml(...)
-        else:
-            # per_file
-            util.write_junit_xml(...)
+        try:
+            if options.junit_format == "global":
+                util.write_junit_xml(...)
+            else:
+                # per_file
+                util.write_junit_xml(...)
+        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)
```

| invocation | before | after |
|---|---|---|
| `--junit-xml /nope/junit.xml` | `error: INTERNAL ERROR -- Please try using mypy master ... please report a bug`, exit 2 | `error: Cannot write junit-xml to /nope/junit.xml: [Errno 13] Permission denied: '/nope'`, exit 2 |
| `--junit-xml junit.xml` | report written | unchanged |
| `--junit-xml sub/junit.xml` (missing dir) | dirs created | unchanged |
| mypy errors + a bad `--junit-xml` | the error report is lost behind the internal error | the mypy messages are printed as usual, then the path error |

Exit 2 is what mypy already uses for serious errors (`fail()`), and `sys.exit(2)` after a
message is the same shape as the existing `--exclude` regex check in `modulefinder.py`.

The other report writers (`--linecoverage-report`, `--any-exprs-report`, `--html-report`)
take the same internal-error route today; this change deliberately covers `--junit-xml`
only, since it is the one written from `main()`.

## Test

`mypy/test/testutil.py`, next to the other `maybe_write_junit_xml` tests:

```python
    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()
```

`pytest mypy/test/testutil.py`: 8 passed. The new test fails on an unmodified checkout with
`FileExistsError` from `os.makedirs()` (the "file used as a directory" trick keeps it
root-proof).
@github-actions

Copy link
Copy Markdown
Contributor

According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

1 participant