Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
43fa1ee
Type annotate some misc places with no particular connection
bluetech May 1, 2020
ff8b788
Type annotate ParameterSet
bluetech May 1, 2020
0fb081a
Type annotate some hookspecs & impls
bluetech May 1, 2020
f8de424
Type annotate CallSpec2
bluetech May 1, 2020
be00e12
Type annotate main.py and some parts related to collection
bluetech May 1, 2020
ef34729
Type annotate fixtures.py & related
bluetech May 1, 2020
247c4c0
Type annotate some more hooks & impls
bluetech May 1, 2020
30e3d47
Type annotate _pytest._io.saferepr
bluetech May 1, 2020
d951321
Type annotate _pytest.assertion
bluetech May 1, 2020
e68a261
Type annotate misc functions
bluetech May 1, 2020
387d9d0
Type annotate tricky reorder_items() function in fixtures.py
bluetech May 1, 2020
32dd0e8
Type annotate _pytest.doctest
bluetech May 1, 2020
fc325bc
Type annotate more of _pytest.nodes
bluetech May 1, 2020
709bcbf
Type annotate _pytest.mark.evaluate
bluetech May 1, 2020
90e58f8
Type annotate some parts related to runner & reports
bluetech May 1, 2020
db52928
Type annotate _pytest.logging
bluetech May 1, 2020
b51ea4f
Type annotate _pytest.unittest
bluetech May 1, 2020
3e351af
Type annotate _pytest.capture
bluetech May 1, 2020
216a010
Type annotate _pytest.junitxml
bluetech May 1, 2020
01797e6
Type annotate _pytest.debugging (a bit)
bluetech May 1, 2020
f8bb61a
Type annotate _pytest.warnings
bluetech May 1, 2020
1bd7d02
Type annotate more of _pytest.fixtures
bluetech May 1, 2020
8bcf1d6
Remove duplicated conversion of pytest.fixture() params argument
bluetech May 1, 2020
2833884
Type annotate pytest.fixture and more improvements to _pytest.fixtures
bluetech May 1, 2020
c0af19d
Type annotate more of _pytest.terminal
bluetech May 1, 2020
848ab00
Type annotate `@pytest.mark.foo`
bluetech May 1, 2020
71dfdca
Enable check_untyped_defs mypy option for src/
bluetech May 1, 2020
54ad048
Enable check_untyped_defs mypy option for testing/ too
bluetech May 1, 2020
2b05faf
Improve types around repr_failure()
bluetech May 1, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ repos:
args: [--remove]
- id: check-yaml
- id: debug-statements
exclude: _pytest/debugging.py
exclude: _pytest/(debugging|hookspec).py
language_version: python3
- repo: https://gitlab.com/pycqa/flake8
rev: 3.8.2
Expand Down
1 change: 1 addition & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ formats = sdist.tgz,bdist_wheel

[mypy]
mypy_path = src
check_untyped_defs = True
ignore_missing_imports = True
no_implicit_optional = True
show_error_codes = True
Expand Down
5 changes: 3 additions & 2 deletions src/_pytest/_code/code.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from typing import Generic
from typing import Iterable
from typing import List
from typing import Mapping
from typing import Optional
from typing import Pattern
from typing import Sequence
Expand Down Expand Up @@ -46,7 +47,7 @@
from typing_extensions import Literal
from weakref import ReferenceType

_TracebackStyle = Literal["long", "short", "line", "no", "native", "value"]
_TracebackStyle = Literal["long", "short", "line", "no", "native", "value", "auto"]


class Code:
Expand Down Expand Up @@ -728,7 +729,7 @@ def get_exconly(
failindent = indentstr
return lines

def repr_locals(self, locals: Dict[str, object]) -> Optional["ReprLocals"]:
def repr_locals(self, locals: Mapping[str, object]) -> Optional["ReprLocals"]:
if self.showlocals:
lines = []
keys = [loc for loc in locals if loc[0] != "@"]
Expand Down
43 changes: 33 additions & 10 deletions src/_pytest/_io/saferepr.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import pprint
import reprlib
from typing import Any
from typing import Dict
from typing import IO
from typing import Optional


def _try_repr_or_str(obj):
def _try_repr_or_str(obj: object) -> str:
try:
return repr(obj)
except (KeyboardInterrupt, SystemExit):
Expand All @@ -12,7 +15,7 @@ def _try_repr_or_str(obj):
return '{}("{}")'.format(type(obj).__name__, obj)


def _format_repr_exception(exc: BaseException, obj: Any) -> str:
def _format_repr_exception(exc: BaseException, obj: object) -> str:
try:
exc_info = _try_repr_or_str(exc)
except (KeyboardInterrupt, SystemExit):
Expand Down Expand Up @@ -42,7 +45,7 @@ def __init__(self, maxsize: int) -> None:
self.maxstring = maxsize
self.maxsize = maxsize

def repr(self, x: Any) -> str:
def repr(self, x: object) -> str:
try:
s = super().repr(x)
except (KeyboardInterrupt, SystemExit):
Expand All @@ -51,7 +54,7 @@ def repr(self, x: Any) -> str:
s = _format_repr_exception(exc, x)
return _ellipsize(s, self.maxsize)

def repr_instance(self, x: Any, level: int) -> str:
def repr_instance(self, x: object, level: int) -> str:
try:
s = repr(x)
except (KeyboardInterrupt, SystemExit):
Expand All @@ -61,7 +64,7 @@ def repr_instance(self, x: Any, level: int) -> str:
return _ellipsize(s, self.maxsize)


def safeformat(obj: Any) -> str:
def safeformat(obj: object) -> str:
"""return a pretty printed string for the given object.
Failing __repr__ functions of user instances will be represented
with a short exception info.
Expand All @@ -72,7 +75,7 @@ def safeformat(obj: Any) -> str:
return _format_repr_exception(exc, obj)


def saferepr(obj: Any, maxsize: int = 240) -> str:
def saferepr(obj: object, maxsize: int = 240) -> str:
"""return a size-limited safe repr-string for the given object.
Failing __repr__ functions of user instances will be represented
with a short exception info and 'saferepr' generally takes
Expand All @@ -85,19 +88,39 @@ def saferepr(obj: Any, maxsize: int = 240) -> str:
class AlwaysDispatchingPrettyPrinter(pprint.PrettyPrinter):
"""PrettyPrinter that always dispatches (regardless of width)."""

def _format(self, object, stream, indent, allowance, context, level):
p = self._dispatch.get(type(object).__repr__, None)
def _format(
self,
object: object,
stream: IO[str],
indent: int,
allowance: int,
context: Dict[int, Any],
level: int,
) -> None:
# Type ignored because _dispatch is private.
p = self._dispatch.get(type(object).__repr__, None) # type: ignore[attr-defined] # noqa: F821

objid = id(object)
if objid in context or p is None:
return super()._format(object, stream, indent, allowance, context, level)
# Type ignored because _format is private.
super()._format( # type: ignore[misc] # noqa: F821
object, stream, indent, allowance, context, level,
)
return

context[objid] = 1
p(self, object, stream, indent, allowance, context, level + 1)
del context[objid]


def _pformat_dispatch(object, indent=1, width=80, depth=None, *, compact=False):
def _pformat_dispatch(
object: object,
indent: int = 1,
width: int = 80,
depth: Optional[int] = None,
*,
compact: bool = False
) -> str:
return AlwaysDispatchingPrettyPrinter(
indent=indent, width=width, depth=depth, compact=compact
).pformat(object)
24 changes: 13 additions & 11 deletions src/_pytest/assertion/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"""
import sys
from typing import Any
from typing import Generator
from typing import List
from typing import Optional

Expand All @@ -13,12 +14,14 @@
from _pytest.compat import TYPE_CHECKING
from _pytest.config import Config
from _pytest.config import hookimpl
from _pytest.config.argparsing import Parser
from _pytest.nodes import Item

if TYPE_CHECKING:
from _pytest.main import Session


def pytest_addoption(parser):
def pytest_addoption(parser: Parser) -> None:
group = parser.getgroup("debugconfig")
group.addoption(
"--assert",
Expand All @@ -43,7 +46,7 @@ def pytest_addoption(parser):
)


def register_assert_rewrite(*names) -> None:
def register_assert_rewrite(*names: str) -> None:
"""Register one or more module names to be rewritten on import.

This function will make sure that this module or all modules inside
Expand Down Expand Up @@ -72,27 +75,27 @@ def register_assert_rewrite(*names) -> None:
class DummyRewriteHook:
"""A no-op import hook for when rewriting is disabled."""

def mark_rewrite(self, *names):
def mark_rewrite(self, *names: str) -> None:
pass


class AssertionState:
"""State for the assertion plugin."""

def __init__(self, config, mode):
def __init__(self, config: Config, mode) -> None:
self.mode = mode
self.trace = config.trace.root.get("assertion")
self.hook = None # type: Optional[rewrite.AssertionRewritingHook]


def install_importhook(config):
def install_importhook(config: Config) -> rewrite.AssertionRewritingHook:
"""Try to install the rewrite hook, raise SystemError if it fails."""
config._store[assertstate_key] = AssertionState(config, "rewrite")
config._store[assertstate_key].hook = hook = rewrite.AssertionRewritingHook(config)
sys.meta_path.insert(0, hook)
config._store[assertstate_key].trace("installed rewrite import hook")

def undo():
def undo() -> None:
hook = config._store[assertstate_key].hook
if hook is not None and hook in sys.meta_path:
sys.meta_path.remove(hook)
Expand All @@ -112,7 +115,7 @@ def pytest_collection(session: "Session") -> None:


@hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_protocol(item):
def pytest_runtest_protocol(item: Item) -> Generator[None, None, None]:
"""Setup the pytest_assertrepr_compare and pytest_assertion_pass hooks

The rewrite module will use util._reprcompare if
Expand All @@ -121,8 +124,7 @@ def pytest_runtest_protocol(item):
comparison for the test.
"""

def callbinrepr(op, left, right):
# type: (str, object, object) -> Optional[str]
def callbinrepr(op, left: object, right: object) -> Optional[str]:
"""Call the pytest_assertrepr_compare hook and prepare the result

This uses the first result from the hook and then ensures the
Expand Down Expand Up @@ -155,7 +157,7 @@ def callbinrepr(op, left, right):

if item.ihook.pytest_assertion_pass.get_hookimpls():

def call_assertion_pass_hook(lineno, orig, expl):
def call_assertion_pass_hook(lineno: int, orig: str, expl: str) -> None:
item.ihook.pytest_assertion_pass(
item=item, lineno=lineno, orig=orig, expl=expl
)
Expand All @@ -167,7 +169,7 @@ def call_assertion_pass_hook(lineno, orig, expl):
util._reprcompare, util._assertion_pass = saved_assert_hooks


def pytest_sessionfinish(session):
def pytest_sessionfinish(session: "Session") -> None:
assertstate = session.config._store.get(assertstate_key, None)
if assertstate:
if assertstate.hook is not None:
Expand Down
Loading