Type annotate some misc places with no particular connection

This commit is contained in:
Ran Benita 2020-05-01 14:40:15 +03:00
parent e7c26a92d7
commit 43fa1ee8f9
5 changed files with 31 additions and 29 deletions

View File

@ -14,6 +14,7 @@ from types import TracebackType
from typing import Any from typing import Any
from typing import Callable from typing import Callable
from typing import Dict from typing import Dict
from typing import IO
from typing import List from typing import List
from typing import Optional from typing import Optional
from typing import Sequence from typing import Sequence
@ -295,7 +296,7 @@ class PytestPluginManager(PluginManager):
* ``conftest.py`` loading during start-up; * ``conftest.py`` loading during start-up;
""" """
def __init__(self): def __init__(self) -> None:
import _pytest.assertion import _pytest.assertion
super().__init__("pytest") super().__init__("pytest")
@ -315,7 +316,7 @@ class PytestPluginManager(PluginManager):
self.add_hookspecs(_pytest.hookspec) self.add_hookspecs(_pytest.hookspec)
self.register(self) self.register(self)
if os.environ.get("PYTEST_DEBUG"): if os.environ.get("PYTEST_DEBUG"):
err = sys.stderr err = sys.stderr # type: IO[str]
encoding = getattr(err, "encoding", "utf8") encoding = getattr(err, "encoding", "utf8")
try: try:
err = open( err = open(
@ -377,7 +378,7 @@ class PytestPluginManager(PluginManager):
} }
return opts 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: if name in _pytest.deprecated.DEPRECATED_EXTERNAL_PLUGINS:
warnings.warn( warnings.warn(
PytestConfigWarning( PytestConfigWarning(
@ -552,7 +553,7 @@ class PytestPluginManager(PluginManager):
# #
# #
def consider_preparse(self, args, *, exclude_only=False): def consider_preparse(self, args, *, exclude_only: bool = False) -> None:
i = 0 i = 0
n = len(args) n = len(args)
while i < n: while i < n:
@ -573,7 +574,7 @@ class PytestPluginManager(PluginManager):
continue continue
self.consider_pluginarg(parg) self.consider_pluginarg(parg)
def consider_pluginarg(self, arg): def consider_pluginarg(self, arg) -> None:
if arg.startswith("no:"): if arg.startswith("no:"):
name = arg[3:] name = arg[3:]
if name in essential_plugins: if name in essential_plugins:
@ -598,13 +599,13 @@ class PytestPluginManager(PluginManager):
del self._name2plugin["pytest_" + name] del self._name2plugin["pytest_" + name]
self.import_plugin(arg, consider_entry_points=True) 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__) self.register(conftestmodule, name=conftestmodule.__file__)
def consider_env(self): def consider_env(self) -> None:
self._import_plugin_specs(os.environ.get("PYTEST_PLUGINS")) 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", [])) self._import_plugin_specs(getattr(mod, "pytest_plugins", []))
def _import_plugin_specs(self, spec): def _import_plugin_specs(self, spec):
@ -612,7 +613,7 @@ class PytestPluginManager(PluginManager):
for import_spec in plugins: for import_spec in plugins:
self.import_plugin(import_spec) 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 Imports a plugin with ``modname``. If ``consider_entry_points`` is True, entry point
names are also considered to find a plugin. names are also considered to find a plugin.
@ -843,19 +844,19 @@ class Config:
"""Backward compatibility""" """Backward compatibility"""
return py.path.local(str(self.invocation_params.dir)) 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 """ Add a function to be called when the config object gets out of
use (usually coninciding with pytest_unconfigure).""" use (usually coninciding with pytest_unconfigure)."""
self._cleanup.append(func) self._cleanup.append(func)
def _do_configure(self): def _do_configure(self) -> None:
assert not self._configured assert not self._configured
self._configured = True self._configured = True
with warnings.catch_warnings(): with warnings.catch_warnings():
warnings.simplefilter("default") warnings.simplefilter("default")
self.hook.pytest_configure.call_historic(kwargs=dict(config=self)) self.hook.pytest_configure.call_historic(kwargs=dict(config=self))
def _ensure_unconfigure(self): def _ensure_unconfigure(self) -> None:
if self._configured: if self._configured:
self._configured = False self._configured = False
self.hook.pytest_unconfigure(config=self) self.hook.pytest_unconfigure(config=self)

View File

@ -162,7 +162,7 @@ class KeywordMatcher:
return False return False
def deselect_by_keyword(items, config): def deselect_by_keyword(items, config: Config) -> None:
keywordexpr = config.option.keyword.lstrip() keywordexpr = config.option.keyword.lstrip()
if not keywordexpr: if not keywordexpr:
return return
@ -218,7 +218,7 @@ class MarkMatcher:
return name in self.own_mark_names return name in self.own_mark_names
def deselect_by_mark(items, config): def deselect_by_mark(items, config: Config) -> None:
matchexpr = config.option.markexpr matchexpr = config.option.markexpr
if not matchexpr: if not matchexpr:
return return
@ -243,7 +243,7 @@ def deselect_by_mark(items, config):
items[:] = remaining items[:] = remaining
def pytest_collection_modifyitems(items, config): def pytest_collection_modifyitems(items, config: Config) -> None:
deselect_by_keyword(items, config) deselect_by_keyword(items, config)
deselect_by_mark(items, config) deselect_by_mark(items, config)

View File

@ -271,7 +271,7 @@ class MarkDecorator:
return self.with_args(*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 obtain the unpacked marks that are stored on an object
""" """
@ -400,8 +400,8 @@ class NodeKeywords(MutableMapping):
seen.update(self.parent.keywords) seen.update(self.parent.keywords)
return seen return seen
def __len__(self): def __len__(self) -> int:
return len(self._seen()) return len(self._seen())
def __repr__(self): def __repr__(self) -> str:
return "<NodeKeywords for node {}>".format(self.node) return "<NodeKeywords for node {}>".format(self.node)

View File

@ -2,6 +2,7 @@ import os
import warnings import warnings
from functools import lru_cache from functools import lru_cache
from typing import Any from typing import Any
from typing import Callable
from typing import Dict from typing import Dict
from typing import List from typing import List
from typing import Optional from typing import Optional
@ -312,7 +313,7 @@ class Node(metaclass=NodeMeta):
def listnames(self): def listnames(self):
return [x.name for x in self.listchain()] 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. """ register a function to be called when this node is finalized.
This method can only be called when this node is active This method can only be called when this node is active

View File

@ -321,9 +321,9 @@ class SetupState:
def __init__(self): def __init__(self):
self.stack = [] # type: List[Node] 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. """ """ attach a finalizer to the given colitem. """
assert colitem and not isinstance(colitem, tuple) assert colitem and not isinstance(colitem, tuple)
assert callable(finalizer) assert callable(finalizer)
@ -334,7 +334,7 @@ class SetupState:
colitem = self.stack.pop() colitem = self.stack.pop()
self._teardown_with_finalization(colitem) self._teardown_with_finalization(colitem)
def _callfinalizers(self, colitem): def _callfinalizers(self, colitem) -> None:
finalizers = self._finalizers.pop(colitem, None) finalizers = self._finalizers.pop(colitem, None)
exc = None exc = None
while finalizers: while finalizers:
@ -349,24 +349,24 @@ class SetupState:
if exc: if exc:
raise exc raise exc
def _teardown_with_finalization(self, colitem): def _teardown_with_finalization(self, colitem) -> None:
self._callfinalizers(colitem) self._callfinalizers(colitem)
colitem.teardown() colitem.teardown()
for colitem in self._finalizers: for colitem in self._finalizers:
assert colitem in self.stack assert colitem in self.stack
def teardown_all(self): def teardown_all(self) -> None:
while self.stack: while self.stack:
self._pop_and_teardown() self._pop_and_teardown()
for key in list(self._finalizers): for key in list(self._finalizers):
self._teardown_with_finalization(key) self._teardown_with_finalization(key)
assert not self._finalizers assert not self._finalizers
def teardown_exact(self, item, nextitem): def teardown_exact(self, item, nextitem) -> None:
needed_collectors = nextitem and nextitem.listchain() or [] needed_collectors = nextitem and nextitem.listchain() or []
self._teardown_towards(needed_collectors) self._teardown_towards(needed_collectors)
def _teardown_towards(self, needed_collectors): def _teardown_towards(self, needed_collectors) -> None:
exc = None exc = None
while self.stack: while self.stack:
if self.stack == needed_collectors[: len(self.stack)]: if self.stack == needed_collectors[: len(self.stack)]:
@ -381,7 +381,7 @@ class SetupState:
if exc: if exc:
raise exc raise exc
def prepare(self, colitem): def prepare(self, colitem) -> None:
""" setup objects along the collector chain to the test-method """ setup objects along the collector chain to the test-method
and teardown previously setup objects.""" and teardown previously setup objects."""
needed_collectors = colitem.listchain() needed_collectors = colitem.listchain()
@ -390,14 +390,14 @@ class SetupState:
# check if the last collection node has raised an error # check if the last collection node has raised an error
for col in self.stack: for col in self.stack:
if hasattr(col, "_prepare_exc"): if hasattr(col, "_prepare_exc"):
exc = col._prepare_exc exc = col._prepare_exc # type: ignore[attr-defined] # noqa: F821
raise exc raise exc
for col in needed_collectors[len(self.stack) :]: for col in needed_collectors[len(self.stack) :]:
self.stack.append(col) self.stack.append(col)
try: try:
col.setup() col.setup()
except TEST_OUTCOME as e: except TEST_OUTCOME as e:
col._prepare_exc = e col._prepare_exc = e # type: ignore[attr-defined] # noqa: F821
raise e raise e