typeddjango / pytest-mypy-plugins

pytest plugin for testing mypy types, stubs, and plugins
https://pypi.org/project/pytest-mypy-plugins/
MIT License
99 stars 26 forks source link

UnboundLocalError when --mypy-testing-base is not valid #86

Closed zero323 closed 2 years ago

zero323 commented 2 years ago

If tests are invoked with --mypy-testing-base that is not valid (doesn't exist, is a file, user has no permissions to write) we fail and escalate to UnboundLocalError:

Traceback (most recent call last):
  File "/path/to/pytest-mypy-plugins/pytest_mypy_plugins/item.py", line 231, in runtest
    temp_dir = tempfile.TemporaryDirectory(prefix="pytest-mypy-", dir=self.root_directory)
  File "/usr/lib/python3.9/tempfile.py", line 918, in __init__
    self.name = mkdtemp(suffix, prefix, dir)
  File "/usr/lib/python3.9/tempfile.py", line 498, in mkdtemp
    _os.mkdir(file, 0o700)
NotADirectoryError: [Errno 20] Not a directory: '/tmp/foo/pytest-mypy-k7frqt99'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/path/to/lib/python3.9/site-packages/_pytest/runner.py", line 311, in from_call
    result: Optional[TResult] = func()
  File "/path/to/lib/python3.9/site-packages/_pytest/runner.py", line 255, in <lambda>
    lambda: ihook(item=item, **kwds), when=when, reraise=reraise
  File "/path/to/lib/python3.9/site-packages/pluggy/_hooks.py", line 265, in __call__
    return self._hookexec(self.name, self.get_hookimpls(), kwargs, firstresult)
  File "/path/to/lib/python3.9/site-packages/pluggy/_manager.py", line 80, in _hookexec
    return self._inner_hookexec(hook_name, methods, kwargs, firstresult)
  File "/path/to/lib/python3.9/site-packages/pluggy/_callers.py", line 60, in _multicall
    return outcome.get_result()
  File "/path/to/lib/python3.9/site-packages/pluggy/_result.py", line 60, in get_result
    raise ex[1].with_traceback(ex[2])
  File "/path/to/lib/python3.9/site-packages/pluggy/_callers.py", line 39, in _multicall
    res = hook_impl.function(*args)
  File "/path/to/lib/python3.9/site-packages/_pytest/runner.py", line 170, in pytest_runtest_call
    raise e
  File "/path/to/lib/python3.9/site-packages/_pytest/runner.py", line 162, in pytest_runtest_call
    item.runtest()
  File "/path/to/pytest-mypy-plugins/pytest_mypy_plugins/item.py", line 276, in runtest
    temp_dir.cleanup()
UnboundLocalError: local variable 'temp_dir' referenced before assignm

This is because we create temp directory in a try block

https://github.com/typeddjango/pytest-mypy-plugins/blob/1ad40a97b70c4e15410adf72eed41fbeef69ff45/pytest_mypy_plugins/item.py#L230-L231

that corresponds finally block responsible for cleanup

https://github.com/typeddjango/pytest-mypy-plugins/blob/1ad40a97b70c4e15410adf72eed41fbeef69ff45/pytest_mypy_plugins/item.py#L275-L276