Skip to content

Type annotate some misc places #6734

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
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
29 changes: 17 additions & 12 deletions src/_pytest/config/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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:
Expand All @@ -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:
Expand All @@ -568,21 +568,21 @@ 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):
plugins = _get_plugin_specs_as_list(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.
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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)
Expand Down
7 changes: 4 additions & 3 deletions src/_pytest/mark/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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)

Expand Down
20 changes: 10 additions & 10 deletions src/_pytest/mark/structures.py
Original file line number Diff line number Diff line change
Expand Up @@ -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":
Expand Down Expand Up @@ -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

Expand All @@ -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 "<MarkDecorator {!r}>".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
Expand All @@ -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
"""
Expand All @@ -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
"""
Expand Down Expand Up @@ -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 "<NodeKeywords for node {}>".format(self.node)
3 changes: 2 additions & 1 deletion src/_pytest/nodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
20 changes: 10 additions & 10 deletions src/_pytest/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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:
Expand All @@ -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)]:
Expand All @@ -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()
Expand All @@ -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


Expand Down
2 changes: 1 addition & 1 deletion src/_pytest/warnings.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
"""
Expand Down