Debian Codegraph @

src/_pytest/unittest.py

raw
1 # mypy: allow-untyped-defs
2 """Discover and run std-library "unittest" style tests."""
3
4 from __future__ import annotations
5
6 from collections.abc import Callable
7 from collections.abc import Generator
8 from collections.abc import Iterable
9 from collections.abc import Iterator
10 from enum import auto
11 from enum import Enum
12 import inspect
13 import sys
14 import traceback
15 import types
16 from typing import Any
17 from typing import TYPE_CHECKING
18 from unittest import TestCase
19
20 from _pytest import fixtures
21 import _pytest._code
22 from _pytest._code import ExceptionInfo
23 from _pytest.compat import assert_never
24 from _pytest.compat import is_async_function
25 from _pytest.config import hookimpl
26 from _pytest.fixtures import FixtureRequest
27 from _pytest.monkeypatch import MonkeyPatch
28 from _pytest.nodes import Collector
29 from _pytest.nodes import Item
30 from _pytest.outcomes import exit
31 from _pytest.outcomes import fail
32 from _pytest.outcomes import skip
33 from _pytest.outcomes import xfail
34 from _pytest.python import Class
35 from _pytest.python import Function
36 from _pytest.python import Module
37 from _pytest.runner import CallInfo
38 from _pytest.runner import check_interactive_exception
39 from _pytest.subtests import SubtestContext
40 from _pytest.subtests import SubtestReport
41
42
43 if sys.version_info[:2] < (3, 11):
44 from exceptiongroup import ExceptionGroup
45
46 if TYPE_CHECKING:
47 from types import TracebackType
48 import unittest
49
50 import twisted.trial.unittest
51
52
53 _SysExcInfoType = (
54 tuple[type[BaseException], BaseException, types.TracebackType]
55 | tuple[None, None, None]
56 )
57
58
59 def pytest_pycollect_makeitem(
60 collector: Module | Class, name: str, obj: object
61 ) -> UnitTestCase | None:
62 try:
63 # Has unittest been imported?
64 ut = sys.modules["unittest"]
65 # Is obj a subclass of unittest.TestCase?
66 # Type ignored because `ut` is an opaque module.
67 if not issubclass(obj, ut.TestCase): # type: ignore
68 return None
69 except Exception:
70 return None
71 # Is obj a concrete class?
72 # Abstract classes can't be instantiated so no point collecting them.
73 if inspect.isabstract(obj):
74 return None
75 # Yes, so let's collect it.
76 return UnitTestCase.from_parent(collector, name=name, obj=obj)
77
78
79 class UnitTestCase(Class):
80 # Marker for fixturemanger.getfixtureinfo()
81 # to declare that our children do not support funcargs.
82 nofuncargs = True
83
84 def newinstance(self):
85 # TestCase __init__ takes the method (test) name. The TestCase
86 # constructor treats the name "runTest" as a special no-op, so it can be
87 # used when a dummy instance is needed. While unittest.TestCase has a
88 # default, some subclasses omit the default (#9610), so always supply
89 # it.
90 return self.obj("runTest")
91
92 def collect(self) -> Iterable[Item | Collector]:
93 from unittest import TestLoader
94
95 cls = self.obj
96 if not getattr(cls, "__test__", True):
97 return
98
99 skipped = _is_skipped(cls)
100 if not skipped:
101 self._register_unittest_setup_method_fixture(cls)
102 self._register_unittest_setup_class_fixture(cls)
103 self._register_setup_class_fixture()
104 else:
105 self._register_unittest_skip_fixture(cls)
106
107 self.session._fixturemanager.parsefactories(
108 holder=self.newinstance(), node=self
109 )
110
111 loader = TestLoader()
112 foundsomething = False
113 for name in loader.getTestCaseNames(self.obj):
114 x = getattr(self.obj, name)
115 if not getattr(x, "__test__", True):
116 continue
117 yield TestCaseFunction.from_parent(self, name=name)
118 foundsomething = True
119
120 if not foundsomething:
121 runtest = getattr(self.obj, "runTest", None)
122 if runtest is not None:
123 ut = sys.modules.get("twisted.trial.unittest", None)
124 if ut is None or runtest != ut.TestCase.runTest:
125 yield TestCaseFunction.from_parent(self, name="runTest")
126
127 def _register_unittest_setup_class_fixture(self, cls: type) -> None:
128 """Register an auto-use fixture to invoke setUpClass and
129 tearDownClass (#517)."""
130 setup = getattr(cls, "setUpClass", None)
131 teardown = getattr(cls, "tearDownClass", None)
132 if setup is None and teardown is None:
133 return None
134 cleanup = getattr(cls, "doClassCleanups", lambda: None)
135
136 def process_teardown_exceptions() -> None:
137 # tearDown_exceptions is a list set in the class containing exc_infos for errors during
138 # teardown for the class.
139 exc_infos = getattr(cls, "tearDown_exceptions", None)
140 if not exc_infos:
141 return
142 exceptions = [exc for (_, exc, _) in exc_infos]
143 # If a single exception, raise it directly as this provides a more readable
144 # error (hopefully this will improve in #12255).
145 if len(exceptions) == 1:
146 raise exceptions[0]
147 else:
148 raise ExceptionGroup("Unittest class cleanup errors", exceptions)
149
150 def unittest_setup_class_fixture(
151 request: FixtureRequest,
152 ) -> Generator[None]:
153 cls = request.cls
154 if _is_skipped(cls):
155 reason = cls.__unittest_skip_why__
156 raise skip.Exception(reason, _use_item_location=True)
157 if setup is not None:
158 try:
159 setup()
160 # unittest does not call the cleanup function for every BaseException, so we
161 # follow this here.
162 except Exception:
163 cleanup()
164 process_teardown_exceptions()
165 raise
166 yield
167 try:
168 if teardown is not None:
169 teardown()
170 finally:
171 cleanup()
172 process_teardown_exceptions()
173
174 fixtures.register_fixture(
175 # Use a unique name to speed up lookup.
176 name=f"_unittest_setUpClass_fixture_{cls.__qualname__}",
177 func=unittest_setup_class_fixture,
178 node=self,
179 scope="class",
180 autouse=True,
181 )
182
183 def _register_unittest_skip_fixture(self, cls: type) -> None:
184 """Register an auto-use fixture to skip tests for a class decorated
185 with @unittest.skip or @unittest.skipIf (#13885)."""
186
187 def unittest_skip_fixture(request: FixtureRequest) -> None:
188 reason = getattr(cls, "__unittest_skip_why__", "")
189 raise skip.Exception(reason, _use_item_location=True)
190
191 fixtures.register_fixture(
192 name=f"_unittest_skip_fixture_{cls.__qualname__}",
193 func=unittest_skip_fixture,
194 node=self,
195 scope="class",
196 autouse=True,
197 )
198
199 def _register_unittest_setup_method_fixture(self, cls: type) -> None:
200 """Register an auto-use fixture to invoke setup_method and
201 teardown_method (#517)."""
202 setup = getattr(cls, "setup_method", None)
203 teardown = getattr(cls, "teardown_method", None)
204 if setup is None and teardown is None:
205 return None
206
207 def unittest_setup_method_fixture(
208 request: FixtureRequest,
209 ) -> Generator[None]:
210 self = request.instance
211 if _is_skipped(self):
212 reason = self.__unittest_skip_why__
213 raise skip.Exception(reason, _use_item_location=True)
214 if setup is not None:
215 setup(self, request.function)
216 yield
217 if teardown is not None:
218 teardown(self, request.function)
219
220 fixtures.register_fixture(
221 # Use a unique name to speed up lookup.
222 name=f"_unittest_setup_method_fixture_{cls.__qualname__}",
223 func=unittest_setup_method_fixture,
224 node=self,
225 scope="function",
226 autouse=True,
227 )
228
229
230 class TestCaseFunction(Function):
231 nofuncargs = True
232 failfast = False
233 _excinfo: list[_pytest._code.ExceptionInfo[BaseException]] | None = None
234
235 def _getinstance(self):
236 assert isinstance(self.parent, UnitTestCase)
237 return self.parent.obj(self.name)
238
239 # Backward compat for pytest-django; can be removed after pytest-django
240 # updates + some slack.
241 @property
242 def _testcase(self):
243 return self.instance
244
245 def setup(self) -> None:
246 # A bound method to be called during teardown() if set (see 'runtest()').
247 self._explicit_tearDown: Callable[[], None] | None = None
248 super().setup()
249 if sys.version_info < (3, 11):
250 # A cache of the subTest errors and non-subtest skips in self._outcome.
251 # Compute and cache these lists once, instead of computing them again and again for each subtest (#13965).
252 self._cached_errors_and_skips: tuple[list[Any], list[Any]] | None = None
253
254 def teardown(self) -> None:
255 if self._explicit_tearDown is not None:
256 self._explicit_tearDown()
257 self._explicit_tearDown = None
258 self._obj = None
259 del self._instance
260 super().teardown()
261
262 def startTest(self, testcase: unittest.TestCase) -> None:
263 pass
264
265 def _addexcinfo(self, rawexcinfo: _SysExcInfoType) -> None:
266 rawexcinfo = _handle_twisted_exc_info(rawexcinfo)
267 try:
268 excinfo = _pytest._code.ExceptionInfo[BaseException].from_exc_info(
269 rawexcinfo # type: ignore[arg-type]
270 )
271 # Invoke the attributes to trigger storing the traceback
272 # trial causes some issue there.
273 _ = excinfo.value
274 _ = excinfo.traceback
275 except TypeError:
276 try:
277 try:
278 values = traceback.format_exception(*rawexcinfo)
279 values.insert(
280 0,
281 "NOTE: Incompatible Exception Representation, "
282 "displaying natively:\n\n",
283 )
284 fail("".join(values), pytrace=False)
285 except (fail.Exception, KeyboardInterrupt):
286 raise
287 except BaseException:
288 fail(
289 "ERROR: Unknown Incompatible Exception "
290 f"representation:\n{rawexcinfo!r}",
291 pytrace=False,
292 )
293 except KeyboardInterrupt:
294 raise
295 except fail.Exception:
296 excinfo = _pytest._code.ExceptionInfo.from_current()
297 self.__dict__.setdefault("_excinfo", []).append(excinfo)
298
299 def addError(
300 self, testcase: unittest.TestCase, rawexcinfo: _SysExcInfoType
301 ) -> None:
302 try:
303 if isinstance(rawexcinfo[1], exit.Exception):
304 exit(rawexcinfo[1].msg)
305 except TypeError:
306 pass
307 self._addexcinfo(rawexcinfo)
308
309 def addFailure(
310 self, testcase: unittest.TestCase, rawexcinfo: _SysExcInfoType
311 ) -> None:
312 self._addexcinfo(rawexcinfo)
313
314 def addSkip(
315 self, testcase: unittest.TestCase, reason: str, *, handle_subtests: bool = True
316 ) -> None:
317 from unittest.case import _SubTest # type: ignore[attr-defined]
318
319 def add_skip() -> None:
320 try:
321 raise skip.Exception(reason, _use_item_location=True)
322 except skip.Exception:
323 self._addexcinfo(sys.exc_info())
324
325 if not handle_subtests:
326 add_skip()
327 return
328
329 if isinstance(testcase, _SubTest):
330 add_skip()
331 if self._excinfo is not None:
332 exc_info = self._excinfo[-1]
333 self.addSubTest(testcase.test_case, testcase, exc_info)
334 else:
335 # For python < 3.11: the non-subtest skips have to be added by `add_skip` only after all subtest
336 # failures are processed by `_addSubTest`: `self.instance._outcome` has no attribute
337 # `skipped/errors` anymore.
338 # We also need to check if `self.instance._outcome` is `None` (this happens if the test
339 # class/method is decorated with `unittest.skip`, see pytest-dev/pytest-subtests#173).
340 if sys.version_info < (3, 11) and self.instance._outcome is not None:
341 subtest_errors, _ = self._obtain_errors_and_skips()
342 if len(subtest_errors) == 0:
343 add_skip()
344 else:
345 add_skip()
346
347 def addExpectedFailure(
348 self,
349 testcase: unittest.TestCase,
350 rawexcinfo: _SysExcInfoType,
351 reason: str = "",
352 ) -> None:
353 try:
354 xfail(str(reason))
355 except xfail.Exception:
356 self._addexcinfo(sys.exc_info())
357
358 def addUnexpectedSuccess(
359 self,
360 testcase: unittest.TestCase,
361 reason: twisted.trial.unittest.Todo | None = None,
362 ) -> None:
363 msg = "Unexpected success"
364 if reason:
365 msg += f": {reason.reason}"
366 # Preserve unittest behaviour - fail the test. Explicitly not an XPASS.
367 try:
368 fail(msg, pytrace=False)
369 except fail.Exception:
370 self._addexcinfo(sys.exc_info())
371
372 def addSuccess(self, testcase: unittest.TestCase) -> None:
373 pass
374
375 def stopTest(self, testcase: unittest.TestCase) -> None:
376 pass
377
378 def addDuration(self, testcase: unittest.TestCase, elapsed: float) -> None:
379 pass
380
381 def runtest(self) -> None:
382 from _pytest.debugging import maybe_wrap_pytest_function_for_tracing
383
384 testcase = self.instance
385 assert testcase is not None
386
387 maybe_wrap_pytest_function_for_tracing(self)
388
389 # Let the unittest framework handle async functions.
390 if is_async_function(self.obj):
391 testcase(result=self)
392 else:
393 # When --pdb is given, we want to postpone calling tearDown() otherwise
394 # when entering the pdb prompt, tearDown() would have probably cleaned up
395 # instance variables, which makes it difficult to debug.
396 # Arguably we could always postpone tearDown(), but this changes the moment where the
397 # TestCase instance interacts with the results object, so better to only do it
398 # when absolutely needed.
399 # We need to consider if the test itself is skipped, or the whole class.
400 assert isinstance(self.parent, UnitTestCase)
401 skipped = _is_skipped(self.obj) or _is_skipped(self.parent.obj)
402 if self.config.getoption("usepdb") and not skipped:
403 self._explicit_tearDown = testcase.tearDown
404 setattr(testcase, "tearDown", lambda *args: None)
405
406 # We need to update the actual bound method with self.obj, because
407 # wrap_pytest_function_for_tracing replaces self.obj by a wrapper.
408 setattr(testcase, self.name, self.obj)
409 try:
410 testcase(result=self)
411 finally:
412 delattr(testcase, self.name)
413
414 def _traceback_filter(
415 self, excinfo: _pytest._code.ExceptionInfo[BaseException]
416 ) -> _pytest._code.Traceback:
417 traceback = super()._traceback_filter(excinfo)
418 ntraceback = traceback.filter(
419 lambda x: not x.frame.f_globals.get("__unittest"),
420 )
421 if not ntraceback:
422 ntraceback = traceback
423 return ntraceback
424
425 def addSubTest(
426 self,
427 test_case: Any,
428 test: TestCase,
429 exc_info: ExceptionInfo[BaseException]
430 | tuple[type[BaseException], BaseException, TracebackType]
431 | None,
432 ) -> None:
433 # Importing this private symbol locally in case this symbol is renamed/removed in the future; importing
434 # it globally would break pytest entirely, importing it locally only will break unittests using `addSubTest`.
435 from unittest.case import _subtest_msg_sentinel # type: ignore[attr-defined]
436
437 exception_info: ExceptionInfo[BaseException] | None
438 match exc_info:
439 case tuple():
440 exception_info = ExceptionInfo(exc_info, _ispytest=True)
441 case ExceptionInfo() | None:
442 exception_info = exc_info
443 case unreachable:
444 assert_never(unreachable)
445
446 call_info = CallInfo[None](
447 None,
448 exception_info,
449 start=0,
450 stop=0,
451 duration=0,
452 when="call",
453 _ispytest=True,
454 )
455 msg = None if test._message is _subtest_msg_sentinel else str(test._message) # type: ignore[attr-defined]
456 report = self.ihook.pytest_runtest_makereport(item=self, call=call_info)
457 sub_report = SubtestReport._new(
458 report,
459 SubtestContext(msg=msg, kwargs=dict(test.params)), # type: ignore[attr-defined]
460 captured_output=None,
461 captured_logs=None,
462 )
463 self.ihook.pytest_runtest_logreport(report=sub_report)
464 if check_interactive_exception(call_info, sub_report):
465 self.ihook.pytest_exception_interact(
466 node=self, call=call_info, report=sub_report
467 )
468
469 # For python < 3.11: add non-subtest skips once all subtest failures are processed by # `_addSubTest`.
470 if sys.version_info < (3, 11):
471 subtest_errors, non_subtest_skip = self._obtain_errors_and_skips()
472
473 # Check if we have non-subtest skips: if there are also sub failures, non-subtest skips are not treated in
474 # `_addSubTest` and have to be added using `add_skip` after all subtest failures are processed.
475 if len(non_subtest_skip) > 0 and len(subtest_errors) > 0:
476 # Make sure we have processed the last subtest failure
477 last_subset_error = subtest_errors[-1]
478 if exc_info is last_subset_error[-1]:
479 # Add non-subtest skips (as they could not be treated in `_addSkip`)
480 for testcase, reason in non_subtest_skip:
481 self.addSkip(testcase, reason, handle_subtests=False)
482
483 def _obtain_errors_and_skips(self) -> tuple[list[Any], list[Any]]:
484 """Compute or obtain the cached values for subtest errors and non-subtest skips."""
485 from unittest.case import _SubTest # type: ignore[attr-defined]
486
487 assert sys.version_info < (3, 11), (
488 "This workaround only should be used in Python 3.10"
489 )
490 if self._cached_errors_and_skips is not None:
491 return self._cached_errors_and_skips
492
493 subtest_errors = [
494 (x, y)
495 for x, y in self.instance._outcome.errors
496 if isinstance(x, _SubTest) and y is not None
497 ]
498
499 non_subtest_skips = [
500 (x, y)
501 for x, y in self.instance._outcome.skipped
502 if not isinstance(x, _SubTest)
503 ]
504 self._cached_errors_and_skips = (subtest_errors, non_subtest_skips)
505 return subtest_errors, non_subtest_skips
506
507
508 @hookimpl(tryfirst=True)
509 def pytest_runtest_makereport(item: Item, call: CallInfo[None]) -> None:
510 if isinstance(item, TestCaseFunction):
511 if item._excinfo:
512 call.excinfo = item._excinfo.pop(0)
513 try:
514 del call.result
515 except AttributeError:
516 pass
517
518 # Convert unittest.SkipTest to pytest.skip.
519 # This covers explicit `raise unittest.SkipTest`.
520 unittest = sys.modules.get("unittest")
521 if unittest and call.excinfo and isinstance(call.excinfo.value, unittest.SkipTest):
522 excinfo = call.excinfo
523 call2 = CallInfo[None].from_call(lambda: skip(str(excinfo.value)), call.when)
524 call.excinfo = call2.excinfo
525
526
527 def _is_skipped(obj) -> bool:
528 """Return True if the given object has been marked with @unittest.skip."""
529 return bool(getattr(obj, "__unittest_skip__", False))
530
531
532 def pytest_configure() -> None:
533 """Register the TestCaseFunction class as an IReporter if twisted.trial is available."""
534 if _get_twisted_version() is not TwistedVersion.NotInstalled:
535 from twisted.trial.itrial import IReporter
536 from zope.interface import classImplements
537
538 classImplements(TestCaseFunction, IReporter)
539
540
541 class TwistedVersion(Enum):
542 """
543 The Twisted version installed in the environment.
544
545 We have different workarounds in place for different versions of Twisted.
546 """
547
548 # Twisted version 24 or prior.
549 Version24 = auto()
550 # Twisted version 25 or later.
551 Version25 = auto()
552 # Twisted version is not available.
553 NotInstalled = auto()
554
555
556 def _get_twisted_version() -> TwistedVersion:
557 # We need to check if "twisted.trial.unittest" is specifically present in sys.modules.
558 # This is because we intend to integrate with Trial only when it's actively running
559 # the test suite, but not needed when only other Twisted components are in use.
560 if "twisted.trial.unittest" not in sys.modules:
561 return TwistedVersion.NotInstalled
562
563 import importlib.metadata
564
565 import packaging.version
566
567 version_str = importlib.metadata.version("twisted")
568 version = packaging.version.parse(version_str)
569 if version.major <= 24:
570 return TwistedVersion.Version24
571 else:
572 return TwistedVersion.Version25
573
574
575 # Name of the attribute in `twisted.python.Failure` instances that stores
576 # the `sys.exc_info()` tuple.
577 # See twisted.trial support in `pytest_runtest_protocol`.
578 TWISTED_RAW_EXCINFO_ATTR = "_twisted_raw_excinfo"
579
580
581 @hookimpl(wrapper=True)
582 def pytest_runtest_protocol(item: Item) -> Iterator[None]:
583 if _get_twisted_version() is TwistedVersion.Version24:
584 import twisted.python.failure as ut
585
586 # Monkeypatch `Failure.__init__` to store the raw exception info.
587 original__init__ = ut.Failure.__init__
588
589 def store_raw_exception_info(
590 self, exc_value=None, exc_type=None, exc_tb=None, captureVars=None
591 ): # pragma: no cover
592 if exc_value is None:
593 raw_exc_info = sys.exc_info()
594 else:
595 if exc_type is None:
596 exc_type = type(exc_value)
597 if exc_tb is None:
598 exc_tb = sys.exc_info()[2]
599 raw_exc_info = (exc_type, exc_value, exc_tb)
600 setattr(self, TWISTED_RAW_EXCINFO_ATTR, tuple(raw_exc_info))
601 try:
602 original__init__(
603 self, exc_value, exc_type, exc_tb, captureVars=captureVars
604 )
605 except TypeError: # pragma: no cover
606 original__init__(self, exc_value, exc_type, exc_tb)
607
608 with MonkeyPatch.context() as patcher:
609 patcher.setattr(ut.Failure, "__init__", store_raw_exception_info)
610 return (yield)
611 else:
612 return (yield)
613
614
615 def _handle_twisted_exc_info(
616 rawexcinfo: _SysExcInfoType | BaseException,
617 ) -> _SysExcInfoType:
618 """
619 Twisted passes a custom Failure instance to `addError()` instead of using `sys.exc_info()`.
620 Therefore, if `rawexcinfo` is a `Failure` instance, convert it into the equivalent `sys.exc_info()` tuple
621 as expected by pytest.
622 """
623 twisted_version = _get_twisted_version()
624 if twisted_version is TwistedVersion.NotInstalled:
625 # Unfortunately, because we cannot import `twisted.python.failure` at the top of the file
626 # and use it in the signature, we need to use `type:ignore` here because we cannot narrow
627 # the type properly in the `if` statement above.
628 return rawexcinfo # type:ignore[return-value]
629 elif twisted_version is TwistedVersion.Version24:
630 # Twisted calls addError() passing its own classes (like `twisted.python.Failure`), which violates
631 # the `addError()` signature, so we extract the original `sys.exc_info()` tuple which is stored
632 # in the object.
633 if hasattr(rawexcinfo, TWISTED_RAW_EXCINFO_ATTR):
634 saved_exc_info = getattr(rawexcinfo, TWISTED_RAW_EXCINFO_ATTR)
635 # Delete the attribute from the original object to avoid leaks.
636 delattr(rawexcinfo, TWISTED_RAW_EXCINFO_ATTR)
637 return saved_exc_info # type:ignore[no-any-return]
638 return rawexcinfo # type:ignore[return-value]
639 elif twisted_version is TwistedVersion.Version25:
640 if isinstance(rawexcinfo, BaseException):
641 import twisted.python.failure
642
643 if isinstance(rawexcinfo, twisted.python.failure.Failure):
644 tb = rawexcinfo.__traceback__
645 if tb is None:
646 tb = sys.exc_info()[2]
647 return type(rawexcinfo.value), rawexcinfo.value, tb
648
649 return rawexcinfo # type:ignore[return-value]
650 else:
651 # Ideally we would use assert_never() here, but it is not available in all Python versions
652 # we support, plus we do not require `type_extensions` currently.
653 assert False, f"Unexpected Twisted version: {twisted_version}"