mirror of
https://github.com/pre-commit/pre-commit-hooks.git
synced 2026-04-10 13:24:18 +00:00
[pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
This commit is contained in:
parent
72ad6dc953
commit
f4cd1ba0d6
813 changed files with 66015 additions and 58839 deletions
|
|
@ -1,5 +1,7 @@
|
|||
# mypy: allow-untyped-defs
|
||||
"""Discover and run std-library "unittest" style tests."""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import traceback
|
||||
import types
|
||||
|
|
@ -15,6 +17,7 @@ from typing import TYPE_CHECKING
|
|||
from typing import Union
|
||||
|
||||
import _pytest._code
|
||||
import pytest
|
||||
from _pytest.compat import getimfunc
|
||||
from _pytest.compat import is_async_function
|
||||
from _pytest.config import hookimpl
|
||||
|
|
@ -29,7 +32,6 @@ from _pytest.python import Class
|
|||
from _pytest.python import Function
|
||||
from _pytest.python import Module
|
||||
from _pytest.runner import CallInfo
|
||||
import pytest
|
||||
|
||||
|
||||
if TYPE_CHECKING:
|
||||
|
|
@ -44,11 +46,11 @@ if TYPE_CHECKING:
|
|||
|
||||
|
||||
def pytest_pycollect_makeitem(
|
||||
collector: Union[Module, Class], name: str, obj: object
|
||||
) -> Optional["UnitTestCase"]:
|
||||
collector: Module | Class, name: str, obj: object,
|
||||
) -> UnitTestCase | None:
|
||||
# Has unittest been imported and is obj a subclass of its TestCase?
|
||||
try:
|
||||
ut = sys.modules["unittest"]
|
||||
ut = sys.modules['unittest']
|
||||
# Type ignored because `ut` is an opaque module.
|
||||
if not issubclass(obj, ut.TestCase): # type: ignore
|
||||
return None
|
||||
|
|
@ -63,11 +65,11 @@ class UnitTestCase(Class):
|
|||
# to declare that our children do not support funcargs.
|
||||
nofuncargs = True
|
||||
|
||||
def collect(self) -> Iterable[Union[Item, Collector]]:
|
||||
def collect(self) -> Iterable[Item | Collector]:
|
||||
from unittest import TestLoader
|
||||
|
||||
cls = self.obj
|
||||
if not getattr(cls, "__test__", True):
|
||||
if not getattr(cls, '__test__', True):
|
||||
return
|
||||
|
||||
skipped = _is_skipped(cls)
|
||||
|
|
@ -81,28 +83,28 @@ class UnitTestCase(Class):
|
|||
foundsomething = False
|
||||
for name in loader.getTestCaseNames(self.obj):
|
||||
x = getattr(self.obj, name)
|
||||
if not getattr(x, "__test__", True):
|
||||
if not getattr(x, '__test__', True):
|
||||
continue
|
||||
funcobj = getimfunc(x)
|
||||
yield TestCaseFunction.from_parent(self, name=name, callobj=funcobj)
|
||||
foundsomething = True
|
||||
|
||||
if not foundsomething:
|
||||
runtest = getattr(self.obj, "runTest", None)
|
||||
runtest = getattr(self.obj, 'runTest', None)
|
||||
if runtest is not None:
|
||||
ut = sys.modules.get("twisted.trial.unittest", None)
|
||||
ut = sys.modules.get('twisted.trial.unittest', None)
|
||||
# Type ignored because `ut` is an opaque module.
|
||||
if ut is None or runtest != ut.TestCase.runTest: # type: ignore
|
||||
yield TestCaseFunction.from_parent(self, name="runTest")
|
||||
yield TestCaseFunction.from_parent(self, name='runTest')
|
||||
|
||||
def _register_unittest_setup_class_fixture(self, cls: type) -> None:
|
||||
"""Register an auto-use fixture to invoke setUpClass and
|
||||
tearDownClass (#517)."""
|
||||
setup = getattr(cls, "setUpClass", None)
|
||||
teardown = getattr(cls, "tearDownClass", None)
|
||||
setup = getattr(cls, 'setUpClass', None)
|
||||
teardown = getattr(cls, 'tearDownClass', None)
|
||||
if setup is None and teardown is None:
|
||||
return None
|
||||
cleanup = getattr(cls, "doClassCleanups", lambda: None)
|
||||
cleanup = getattr(cls, 'doClassCleanups', lambda: None)
|
||||
|
||||
def unittest_setup_class_fixture(
|
||||
request: FixtureRequest,
|
||||
|
|
@ -128,18 +130,18 @@ class UnitTestCase(Class):
|
|||
|
||||
self.session._fixturemanager._register_fixture(
|
||||
# Use a unique name to speed up lookup.
|
||||
name=f"_unittest_setUpClass_fixture_{cls.__qualname__}",
|
||||
name=f'_unittest_setUpClass_fixture_{cls.__qualname__}',
|
||||
func=unittest_setup_class_fixture,
|
||||
nodeid=self.nodeid,
|
||||
scope="class",
|
||||
scope='class',
|
||||
autouse=True,
|
||||
)
|
||||
|
||||
def _register_unittest_setup_method_fixture(self, cls: type) -> None:
|
||||
"""Register an auto-use fixture to invoke setup_method and
|
||||
teardown_method (#517)."""
|
||||
setup = getattr(cls, "setup_method", None)
|
||||
teardown = getattr(cls, "teardown_method", None)
|
||||
setup = getattr(cls, 'setup_method', None)
|
||||
teardown = getattr(cls, 'teardown_method', None)
|
||||
if setup is None and teardown is None:
|
||||
return None
|
||||
|
||||
|
|
@ -158,18 +160,18 @@ class UnitTestCase(Class):
|
|||
|
||||
self.session._fixturemanager._register_fixture(
|
||||
# Use a unique name to speed up lookup.
|
||||
name=f"_unittest_setup_method_fixture_{cls.__qualname__}",
|
||||
name=f'_unittest_setup_method_fixture_{cls.__qualname__}',
|
||||
func=unittest_setup_method_fixture,
|
||||
nodeid=self.nodeid,
|
||||
scope="function",
|
||||
scope='function',
|
||||
autouse=True,
|
||||
)
|
||||
|
||||
|
||||
class TestCaseFunction(Function):
|
||||
nofuncargs = True
|
||||
_excinfo: Optional[List[_pytest._code.ExceptionInfo[BaseException]]] = None
|
||||
_testcase: Optional["unittest.TestCase"] = None
|
||||
_excinfo: list[_pytest._code.ExceptionInfo[BaseException]] | None = None
|
||||
_testcase: unittest.TestCase | None = None
|
||||
|
||||
def _getobj(self):
|
||||
assert self.parent is not None
|
||||
|
|
@ -182,7 +184,7 @@ class TestCaseFunction(Function):
|
|||
|
||||
def setup(self) -> None:
|
||||
# A bound method to be called during teardown() if set (see 'runtest()').
|
||||
self._explicit_tearDown: Optional[Callable[[], None]] = None
|
||||
self._explicit_tearDown: Callable[[], None] | None = None
|
||||
assert self.parent is not None
|
||||
self._testcase = self.parent.obj(self.name) # type: ignore[attr-defined]
|
||||
self._obj = getattr(self._testcase, self.name)
|
||||
|
|
@ -196,15 +198,15 @@ class TestCaseFunction(Function):
|
|||
self._testcase = None
|
||||
self._obj = None
|
||||
|
||||
def startTest(self, testcase: "unittest.TestCase") -> None:
|
||||
def startTest(self, testcase: unittest.TestCase) -> None:
|
||||
pass
|
||||
|
||||
def _addexcinfo(self, rawexcinfo: "_SysExcInfoType") -> None:
|
||||
def _addexcinfo(self, rawexcinfo: _SysExcInfoType) -> None:
|
||||
# Unwrap potential exception info (see twisted trial support below).
|
||||
rawexcinfo = getattr(rawexcinfo, "_rawexcinfo", rawexcinfo)
|
||||
rawexcinfo = getattr(rawexcinfo, '_rawexcinfo', rawexcinfo)
|
||||
try:
|
||||
excinfo = _pytest._code.ExceptionInfo[BaseException].from_exc_info(
|
||||
rawexcinfo # type: ignore[arg-type]
|
||||
rawexcinfo, # type: ignore[arg-type]
|
||||
)
|
||||
# Invoke the attributes to trigger storing the traceback
|
||||
# trial causes some issue there.
|
||||
|
|
@ -216,26 +218,26 @@ class TestCaseFunction(Function):
|
|||
values = traceback.format_exception(*rawexcinfo)
|
||||
values.insert(
|
||||
0,
|
||||
"NOTE: Incompatible Exception Representation, "
|
||||
"displaying natively:\n\n",
|
||||
'NOTE: Incompatible Exception Representation, '
|
||||
'displaying natively:\n\n',
|
||||
)
|
||||
fail("".join(values), pytrace=False)
|
||||
fail(''.join(values), pytrace=False)
|
||||
except (fail.Exception, KeyboardInterrupt):
|
||||
raise
|
||||
except BaseException:
|
||||
fail(
|
||||
"ERROR: Unknown Incompatible Exception "
|
||||
f"representation:\n{rawexcinfo!r}",
|
||||
'ERROR: Unknown Incompatible Exception '
|
||||
f'representation:\n{rawexcinfo!r}',
|
||||
pytrace=False,
|
||||
)
|
||||
except KeyboardInterrupt:
|
||||
raise
|
||||
except fail.Exception:
|
||||
excinfo = _pytest._code.ExceptionInfo.from_current()
|
||||
self.__dict__.setdefault("_excinfo", []).append(excinfo)
|
||||
self.__dict__.setdefault('_excinfo', []).append(excinfo)
|
||||
|
||||
def addError(
|
||||
self, testcase: "unittest.TestCase", rawexcinfo: "_SysExcInfoType"
|
||||
self, testcase: unittest.TestCase, rawexcinfo: _SysExcInfoType,
|
||||
) -> None:
|
||||
try:
|
||||
if isinstance(rawexcinfo[1], exit.Exception):
|
||||
|
|
@ -245,11 +247,11 @@ class TestCaseFunction(Function):
|
|||
self._addexcinfo(rawexcinfo)
|
||||
|
||||
def addFailure(
|
||||
self, testcase: "unittest.TestCase", rawexcinfo: "_SysExcInfoType"
|
||||
self, testcase: unittest.TestCase, rawexcinfo: _SysExcInfoType,
|
||||
) -> None:
|
||||
self._addexcinfo(rawexcinfo)
|
||||
|
||||
def addSkip(self, testcase: "unittest.TestCase", reason: str) -> None:
|
||||
def addSkip(self, testcase: unittest.TestCase, reason: str) -> None:
|
||||
try:
|
||||
raise pytest.skip.Exception(reason, _use_item_location=True)
|
||||
except skip.Exception:
|
||||
|
|
@ -257,9 +259,9 @@ class TestCaseFunction(Function):
|
|||
|
||||
def addExpectedFailure(
|
||||
self,
|
||||
testcase: "unittest.TestCase",
|
||||
rawexcinfo: "_SysExcInfoType",
|
||||
reason: str = "",
|
||||
testcase: unittest.TestCase,
|
||||
rawexcinfo: _SysExcInfoType,
|
||||
reason: str = '',
|
||||
) -> None:
|
||||
try:
|
||||
xfail(str(reason))
|
||||
|
|
@ -268,25 +270,25 @@ class TestCaseFunction(Function):
|
|||
|
||||
def addUnexpectedSuccess(
|
||||
self,
|
||||
testcase: "unittest.TestCase",
|
||||
reason: Optional["twisted.trial.unittest.Todo"] = None,
|
||||
testcase: unittest.TestCase,
|
||||
reason: twisted.trial.unittest.Todo | None = None,
|
||||
) -> None:
|
||||
msg = "Unexpected success"
|
||||
msg = 'Unexpected success'
|
||||
if reason:
|
||||
msg += f": {reason.reason}"
|
||||
msg += f': {reason.reason}'
|
||||
# Preserve unittest behaviour - fail the test. Explicitly not an XPASS.
|
||||
try:
|
||||
fail(msg, pytrace=False)
|
||||
except fail.Exception:
|
||||
self._addexcinfo(sys.exc_info())
|
||||
|
||||
def addSuccess(self, testcase: "unittest.TestCase") -> None:
|
||||
def addSuccess(self, testcase: unittest.TestCase) -> None:
|
||||
pass
|
||||
|
||||
def stopTest(self, testcase: "unittest.TestCase") -> None:
|
||||
def stopTest(self, testcase: unittest.TestCase) -> None:
|
||||
pass
|
||||
|
||||
def addDuration(self, testcase: "unittest.TestCase", elapsed: float) -> None:
|
||||
def addDuration(self, testcase: unittest.TestCase, elapsed: float) -> None:
|
||||
pass
|
||||
|
||||
def runtest(self) -> None:
|
||||
|
|
@ -310,9 +312,9 @@ class TestCaseFunction(Function):
|
|||
# We need to consider if the test itself is skipped, or the whole class.
|
||||
assert isinstance(self.parent, UnitTestCase)
|
||||
skipped = _is_skipped(self.obj) or _is_skipped(self.parent.obj)
|
||||
if self.config.getoption("usepdb") and not skipped:
|
||||
if self.config.getoption('usepdb') and not skipped:
|
||||
self._explicit_tearDown = self._testcase.tearDown
|
||||
setattr(self._testcase, "tearDown", lambda *args: None)
|
||||
setattr(self._testcase, 'tearDown', lambda *args: None)
|
||||
|
||||
# We need to update the actual bound method with self.obj, because
|
||||
# wrap_pytest_function_for_tracing replaces self.obj by a wrapper.
|
||||
|
|
@ -323,11 +325,11 @@ class TestCaseFunction(Function):
|
|||
delattr(self._testcase, self.name)
|
||||
|
||||
def _traceback_filter(
|
||||
self, excinfo: _pytest._code.ExceptionInfo[BaseException]
|
||||
self, excinfo: _pytest._code.ExceptionInfo[BaseException],
|
||||
) -> _pytest._code.Traceback:
|
||||
traceback = super()._traceback_filter(excinfo)
|
||||
ntraceback = traceback.filter(
|
||||
lambda x: not x.frame.f_globals.get("__unittest"),
|
||||
lambda x: not x.frame.f_globals.get('__unittest'),
|
||||
)
|
||||
if not ntraceback:
|
||||
ntraceback = traceback
|
||||
|
|
@ -348,13 +350,13 @@ def pytest_runtest_makereport(item: Item, call: CallInfo[None]) -> None:
|
|||
# This is actually only needed for nose, which reuses unittest.SkipTest for
|
||||
# its own nose.SkipTest. For unittest TestCases, SkipTest is already
|
||||
# handled internally, and doesn't reach here.
|
||||
unittest = sys.modules.get("unittest")
|
||||
unittest = sys.modules.get('unittest')
|
||||
if (
|
||||
unittest and call.excinfo and isinstance(call.excinfo.value, unittest.SkipTest) # type: ignore[attr-defined]
|
||||
):
|
||||
excinfo = call.excinfo
|
||||
call2 = CallInfo[None].from_call(
|
||||
lambda: pytest.skip(str(excinfo.value)), call.when
|
||||
lambda: pytest.skip(str(excinfo.value)), call.when,
|
||||
)
|
||||
call.excinfo = call2.excinfo
|
||||
|
||||
|
|
@ -365,8 +367,8 @@ classImplements_has_run = False
|
|||
|
||||
@hookimpl(wrapper=True)
|
||||
def pytest_runtest_protocol(item: Item) -> Generator[None, object, object]:
|
||||
if isinstance(item, TestCaseFunction) and "twisted.trial.unittest" in sys.modules:
|
||||
ut: Any = sys.modules["twisted.python.failure"]
|
||||
if isinstance(item, TestCaseFunction) and 'twisted.trial.unittest' in sys.modules:
|
||||
ut: Any = sys.modules['twisted.python.failure']
|
||||
global classImplements_has_run
|
||||
Failure__init__ = ut.Failure.__init__
|
||||
if not classImplements_has_run:
|
||||
|
|
@ -377,7 +379,7 @@ def pytest_runtest_protocol(item: Item) -> Generator[None, object, object]:
|
|||
classImplements_has_run = True
|
||||
|
||||
def excstore(
|
||||
self, exc_value=None, exc_type=None, exc_tb=None, captureVars=None
|
||||
self, exc_value=None, exc_type=None, exc_tb=None, captureVars=None,
|
||||
):
|
||||
if exc_value is None:
|
||||
self._rawexcinfo = sys.exc_info()
|
||||
|
|
@ -387,7 +389,7 @@ def pytest_runtest_protocol(item: Item) -> Generator[None, object, object]:
|
|||
self._rawexcinfo = (exc_type, exc_value, exc_tb)
|
||||
try:
|
||||
Failure__init__(
|
||||
self, exc_value, exc_type, exc_tb, captureVars=captureVars
|
||||
self, exc_value, exc_type, exc_tb, captureVars=captureVars,
|
||||
)
|
||||
except TypeError:
|
||||
Failure__init__(self, exc_value, exc_type, exc_tb)
|
||||
|
|
@ -404,4 +406,4 @@ def pytest_runtest_protocol(item: Item) -> Generator[None, object, object]:
|
|||
|
||||
def _is_skipped(obj) -> bool:
|
||||
"""Return True if the given object has been marked with @unittest.skip."""
|
||||
return bool(getattr(obj, "__unittest_skip__", False))
|
||||
return bool(getattr(obj, '__unittest_skip__', False))
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue