Add type annotations to _pytest.compat and _pytest._code.code#6205
Add type annotations to _pytest.compat and _pytest._code.code#6205bluetech merged 9 commits intopytest-dev:featuresfrom
Conversation
Add some Python 3.8 type: ignores; all are already fixed in the next mypy release, so can be removed once we upgrade. Also move some flake8 ignores which seem to have changed places.
pytest doesn't support these PyPy versions anymore, so no need to have checks for them.
It doesn't help much IMO, just adds indirection and makes it harder to type.
The previous test was better in that it used fakes to test all of the real code paths. The problem with that is that it makes it impossible to simplify the code with `isinstance` checks. So let's just simulate the issue directly with a monkeypatch.
Source was previously iterable because it implements `__getitem__()`, which is apparently a thing from before `__iter__()` was introduced. To reduce mypy's and my own confusion, implement `__iter__()` directly.
b512b9c to
51e3be2
Compare
|
|
||
| @overload # noqa: F811 | ||
| def __getitem__(self, key: slice) -> "Source": | ||
| def __getitem__(self, key: slice) -> "Source": # noqa: F811 |
There was a problem hiding this comment.
There seems to be a discrepancy between where CI flake8 and my flake8 report this - on the decorator or the def. Maybe because of Python 3.8? So for now I add it to both.
There was a problem hiding this comment.
Maybe because of Python 3.8?
Very likely, yes.
Isn't there a flake8 plugin to handle this automatically maybe?
There was a problem hiding this comment.
There seems to be some discussion regarding this here, I'm too lazy to read through it though...
| @@ -38,13 +46,12 @@ class Code: | |||
| def __init__(self, rawcode) -> None: | |||
There was a problem hiding this comment.
Can we type the rawcode arg here?
There was a problem hiding this comment.
Not really. I spent some time trying to type getrawcode but left it aside for now.
| return eval(code, self.f_globals, f_locals) | ||
|
|
||
| def exec_(self, code, **vars): | ||
| def exec_(self, code, **vars) -> None: |
There was a problem hiding this comment.
Can the args be typed here also?
There was a problem hiding this comment.
They can be anything really AFAIK, but I'm not entirely sure, so I left it out.
src/_pytest/_code/code.py
Outdated
|
|
||
| def __init__(self, tb, excinfo=None): | ||
| def __init__( | ||
| self, tb: Union[TracebackType, Iterable[TracebackEntry]], excinfo=None |
| path=None, | ||
| lineno: Optional[int] = None, | ||
| firstlineno: Optional[int] = None, | ||
| excludepath=None, |
There was a problem hiding this comment.
It's can be a py.path AFAIU, so I'm leaving it unannotated.
| # Type ignored because mypy thinks the slice is a List[TracebackEntry] | ||
| # instead of the Traceback subclass, even though we override __getitem__(). | ||
| # Should figure out why it does that. | ||
| traceback = traceback[:max_frames] + traceback[-max_frames:] # type: ignore |
There was a problem hiding this comment.
The slice is a Traceback, but only the expression traceback[:max_frames] + traceback[-max_frames:] is a List[…] then.
No idea how to fix it, but it might help you.. :)
There was a problem hiding this comment.
Right, I misunderstood the situation. Looks like a deficiency in mypy/typeshed for now. I'll update the comment.
src/_pytest/_code/code.py
Outdated
| reprfuncargs: Optional["ReprFuncArgs"], | ||
| reprlocals: Optional["ReprLocals"], | ||
| filelocrepr: Optional["ReprFileLocation"], | ||
| style: str, |
|
|
||
| def toterminal(self, tw) -> None: | ||
| if self.style == "short": | ||
| assert self.reprfileloc is not None |
There was a problem hiding this comment.
Could (additionally) be checked/validated in __init__? But it's fine like that also.
There was a problem hiding this comment.
Wouldn't happen unless the code is buggy; seems fine to only do it here.
| def get_cache_dir(file_path: Path) -> Path: | ||
| """Returns the cache directory to write .pyc files for the given .py file path""" | ||
| if sys.version_info >= (3, 8) and sys.pycache_prefix: | ||
| # Type ignored until added in next mypy release. |
There was a problem hiding this comment.
Would be good to link an issue in general, but ok for now.
There was a problem hiding this comment.
mypy can detect outdated type: ignores so it's easy to get rid of when updating mypy.
| warnings.warn(FUNCARGNAMES, stacklevel=2) | ||
| return self.fixturenames | ||
|
|
||
|
|
There was a problem hiding this comment.
I'm ok with inlining, but wondered how it made typing harder (from the commit message)?
There was a problem hiding this comment.
It's a mixin class, it uses fixturenames which is not defined in the class so mypy gets confused. There are ways to type this but it's not worth the bother in this case IMO.
testing/code/test_source.py
Outdated
| assert ex.value.lineno == 1 | ||
| assert ex.value.offset in {5, 7} # cpython: 7, pypy3.6 7.1.1: 5 | ||
| assert ex.value.text is not None | ||
| assert ex.value.text.strip(), "x x" |
There was a problem hiding this comment.
Could check the full expected text instead?
assert ex.value.text == "xyz xyz\n"
IIRC this ( |
Yes, that's an option to. The |
51e3be2 to
eaa34a9
Compare
This PR starts with some small prerequisite commits, and then adds type annotations to
_pytest.compatand_pytest._code.code.Let me know if this is too big for one PR, and I will split it. Note that some part of the diff is just adding
-> Noneto some test functions, so that mypy will check them withoutcheck_untyped_defs = True(which needs more work).