diff --git a/src/_pytest/config/__init__.py b/src/_pytest/config/__init__.py index 45aa4d9a824..8232a606538 100644 --- a/src/_pytest/config/__init__.py +++ b/src/_pytest/config/__init__.py @@ -282,7 +282,7 @@ class PytestPluginManager(PluginManager): * ``conftest.py`` loading during start-up; """ - def __init__(self): + def __init__(self) -> None: import _pytest.assertion super().__init__("pytest") @@ -362,7 +362,7 @@ def parse_hookspec_opts(self, module_or_class, name): } return opts - def register(self, plugin, name=None): + def register(self, plugin: _PluggyPlugin, name: Optional[str] = None): if name in _pytest.deprecated.DEPRECATED_EXTERNAL_PLUGINS: warnings.warn( PytestConfigWarning( @@ -522,7 +522,7 @@ def _importconftest(self, conftestpath): # # - def consider_preparse(self, args, *, exclude_only=False): + def consider_preparse(self, args, *, exclude_only: bool = False) -> None: i = 0 n = len(args) while i < n: @@ -543,7 +543,7 @@ def consider_preparse(self, args, *, exclude_only=False): continue self.consider_pluginarg(parg) - def consider_pluginarg(self, arg): + def consider_pluginarg(self, arg) -> None: if arg.startswith("no:"): name = arg[3:] if name in essential_plugins: @@ -568,13 +568,13 @@ def consider_pluginarg(self, arg): del self._name2plugin["pytest_" + name] self.import_plugin(arg, consider_entry_points=True) - def consider_conftest(self, conftestmodule): + def consider_conftest(self, conftestmodule) -> None: self.register(conftestmodule, name=conftestmodule.__file__) - def consider_env(self): + def consider_env(self) -> None: self._import_plugin_specs(os.environ.get("PYTEST_PLUGINS")) - def consider_module(self, mod): + def consider_module(self, mod: types.ModuleType) -> None: self._import_plugin_specs(getattr(mod, "pytest_plugins", [])) def _import_plugin_specs(self, spec): @@ -582,7 +582,7 @@ def _import_plugin_specs(self, spec): for import_spec in plugins: self.import_plugin(import_spec) - def import_plugin(self, modname, consider_entry_points=False): + def import_plugin(self, modname: str, consider_entry_points: bool = False) -> None: """ Imports a plugin with ``modname``. If ``consider_entry_points`` is True, entry point names are also considered to find a plugin. @@ -766,7 +766,12 @@ class InvocationParams: plugins = attr.ib() dir = attr.ib(type=Path) - def __init__(self, pluginmanager, *, invocation_params=None) -> None: + def __init__( + self, + pluginmanager: PytestPluginManager, + *, + invocation_params: Optional[InvocationParams] = None + ) -> None: from .argparsing import Parser, FILE_OR_DIR if invocation_params is None: @@ -800,19 +805,19 @@ def invocation_dir(self): """Backward compatibility""" return py.path.local(str(self.invocation_params.dir)) - def add_cleanup(self, func): + def add_cleanup(self, func) -> None: """ Add a function to be called when the config object gets out of use (usually coninciding with pytest_unconfigure).""" self._cleanup.append(func) - def _do_configure(self): + def _do_configure(self) -> None: assert not self._configured self._configured = True with warnings.catch_warnings(): warnings.simplefilter("default") self.hook.pytest_configure.call_historic(kwargs=dict(config=self)) - def _ensure_unconfigure(self): + def _ensure_unconfigure(self) -> None: if self._configured: self._configured = False self.hook.pytest_unconfigure(config=self) diff --git a/src/_pytest/mark/__init__.py b/src/_pytest/mark/__init__.py index f493bd839f1..0779ed14bd3 100644 --- a/src/_pytest/mark/__init__.py +++ b/src/_pytest/mark/__init__.py @@ -8,6 +8,7 @@ from .structures import MarkDecorator from .structures import MarkGenerator from .structures import ParameterSet +from _pytest.config import Config from _pytest.config import hookimpl from _pytest.config import UsageError @@ -94,7 +95,7 @@ def pytest_cmdline_main(config): return 0 -def deselect_by_keyword(items, config): +def deselect_by_keyword(items, config: Config) -> None: keywordexpr = config.option.keyword.lstrip() if not keywordexpr: return @@ -121,7 +122,7 @@ def deselect_by_keyword(items, config): items[:] = remaining -def deselect_by_mark(items, config): +def deselect_by_mark(items, config: Config) -> None: matchexpr = config.option.markexpr if not matchexpr: return @@ -139,7 +140,7 @@ def deselect_by_mark(items, config): items[:] = remaining -def pytest_collection_modifyitems(items, config): +def pytest_collection_modifyitems(items, config: Config) -> None: deselect_by_keyword(items, config) deselect_by_mark(items, config) diff --git a/src/_pytest/mark/structures.py b/src/_pytest/mark/structures.py index 1ab22b7c758..fec1f9c5902 100644 --- a/src/_pytest/mark/structures.py +++ b/src/_pytest/mark/structures.py @@ -152,7 +152,7 @@ class Mark: #: resolved/generated ids with parametrize Marks _param_ids_generated = attr.ib(type=Optional[List[str]], default=None, repr=False) - def _has_param_ids(self): + def _has_param_ids(self) -> bool: return "ids" in self.kwargs or len(self.args) >= 4 def combined_with(self, other: "Mark") -> "Mark": @@ -215,10 +215,10 @@ def test_function(): """ - mark = attr.ib(validator=attr.validators.instance_of(Mark)) + mark = attr.ib(type=Mark, validator=attr.validators.instance_of(Mark)) @property - def name(self): + def name(self) -> str: """alias for mark.name""" return self.mark.name @@ -233,13 +233,13 @@ def kwargs(self): return self.mark.kwargs @property - def markname(self): + def markname(self) -> str: return self.name # for backward-compat (2.4.1 had this attr) - def __repr__(self): + def __repr__(self) -> str: return "".format(self.mark) - def with_args(self, *args, **kwargs): + def with_args(self, *args, **kwargs) -> "MarkDecorator": """ return a MarkDecorator with extra arguments added unlike call this can be used even if the sole argument is a callable/class @@ -262,7 +262,7 @@ def __call__(self, *args, **kwargs): return self.with_args(*args, **kwargs) -def get_unpacked_marks(obj): +def get_unpacked_marks(obj) -> List[Mark]: """ obtain the unpacked marks that are stored on an object """ @@ -288,7 +288,7 @@ def normalize_mark_list(mark_list: Iterable[Union[Mark, MarkDecorator]]) -> List return [x for x in extracted if isinstance(x, Mark)] -def store_mark(obj, mark): +def store_mark(obj, mark: Mark) -> None: """store a Mark on an object this is used to implement the Mark declarations/decorators correctly """ @@ -387,8 +387,8 @@ def _seen(self): seen.update(self.parent.keywords) return seen - def __len__(self): + def __len__(self) -> int: return len(self._seen()) - def __repr__(self): + def __repr__(self) -> str: return "".format(self.node) diff --git a/src/_pytest/nodes.py b/src/_pytest/nodes.py index 81a25ddd5c2..a57503b4676 100644 --- a/src/_pytest/nodes.py +++ b/src/_pytest/nodes.py @@ -2,6 +2,7 @@ import warnings from functools import lru_cache from typing import Any +from typing import Callable from typing import Dict from typing import List from typing import Optional @@ -292,7 +293,7 @@ def listextrakeywords(self): def listnames(self): return [x.name for x in self.listchain()] - def addfinalizer(self, fin): + def addfinalizer(self, fin: Callable[[], object]) -> None: """ register a function to be called when this node is finalized. This method can only be called when this node is active diff --git a/src/_pytest/runner.py b/src/_pytest/runner.py index e10e4d8bdf0..325c6d9dcaf 100644 --- a/src/_pytest/runner.py +++ b/src/_pytest/runner.py @@ -289,9 +289,9 @@ class SetupState: def __init__(self): self.stack = [] # type: List[Node] - self._finalizers = {} # type: Dict[Node, List[Callable[[], None]]] + self._finalizers = {} # type: Dict[Node, List[Callable[[], object]]] - def addfinalizer(self, finalizer, colitem): + def addfinalizer(self, finalizer: Callable[[], object], colitem) -> None: """ attach a finalizer to the given colitem. """ assert colitem and not isinstance(colitem, tuple) assert callable(finalizer) @@ -302,7 +302,7 @@ def _pop_and_teardown(self): colitem = self.stack.pop() self._teardown_with_finalization(colitem) - def _callfinalizers(self, colitem): + def _callfinalizers(self, colitem) -> None: finalizers = self._finalizers.pop(colitem, None) exc = None while finalizers: @@ -319,24 +319,24 @@ def _callfinalizers(self, colitem): assert val is not None raise val.with_traceback(tb) - def _teardown_with_finalization(self, colitem): + def _teardown_with_finalization(self, colitem) -> None: self._callfinalizers(colitem) colitem.teardown() for colitem in self._finalizers: assert colitem in self.stack - def teardown_all(self): + def teardown_all(self) -> None: while self.stack: self._pop_and_teardown() for key in list(self._finalizers): self._teardown_with_finalization(key) assert not self._finalizers - def teardown_exact(self, item, nextitem): + def teardown_exact(self, item, nextitem) -> None: needed_collectors = nextitem and nextitem.listchain() or [] self._teardown_towards(needed_collectors) - def _teardown_towards(self, needed_collectors): + def _teardown_towards(self, needed_collectors) -> None: exc = None while self.stack: if self.stack == needed_collectors[: len(self.stack)]: @@ -353,7 +353,7 @@ def _teardown_towards(self, needed_collectors): assert val is not None raise val.with_traceback(tb) - def prepare(self, colitem): + def prepare(self, colitem) -> None: """ setup objects along the collector chain to the test-method and teardown previously setup objects.""" needed_collectors = colitem.listchain() @@ -362,14 +362,14 @@ def prepare(self, colitem): # check if the last collection node has raised an error for col in self.stack: if hasattr(col, "_prepare_exc"): - _, val, tb = col._prepare_exc + _, val, tb = col._prepare_exc # type: ignore[attr-defined] # noqa: F821 raise val.with_traceback(tb) for col in needed_collectors[len(self.stack) :]: self.stack.append(col) try: col.setup() except TEST_OUTCOME: - col._prepare_exc = sys.exc_info() + col._prepare_exc = sys.exc_info() # type: ignore[attr-defined] # noqa: F821 raise diff --git a/src/_pytest/warnings.py b/src/_pytest/warnings.py index 18e4def2116..ae82ed79f91 100644 --- a/src/_pytest/warnings.py +++ b/src/_pytest/warnings.py @@ -7,7 +7,7 @@ from _pytest.main import Session -def _setoption(wmod, arg): +def _setoption(wmod, arg) -> None: """ Copy of the warning._setoption function but does not escape arguments. """