Debian Codegraph @

testing/web-platform/tests/tools/third_party/pytest/src/_pytest/unittest.py

raw
1 # mypy: allow-untyped-defs
2 """Discover and run std-library "unittest" style tests."""
3
4 import sys
5 import traceback
6 import types
7 from typing import Any
8 from typing import Callable
9 from typing import Generator
10 from typing import Iterable
11 from typing import List
12 from typing import Optional
13 from typing import Tuple
14 from typing import Type
15 from typing import TYPE_CHECKING
16 from typing import Union
17
18 import _pytest._code
19 from _pytest.compat import is_async_function
20 from _pytest.config import hookimpl
21 from _pytest.fixtures import FixtureRequest
22 from _pytest.nodes import Collector
23 from _pytest.nodes import Item
24 from _pytest.outcomes import exit
25 from _pytest.outcomes import fail
26 from _pytest.outcomes import skip
27 from _pytest.outcomes import xfail
28 from _pytest.python import Class
29 from _pytest.python import Function
30 from _pytest.python import Module
31 from _pytest.runner import CallInfo
32 import pytest
33
34
35 if sys.version_info[:2] < (3, 11):
36 from exceptiongroup import ExceptionGroup
37
38 if TYPE_CHECKING:
39 import unittest
40
41 import twisted.trial.unittest
42
43 _SysExcInfoType = Union[
44 Tuple[Type[BaseException], BaseException, types.TracebackType],
45 Tuple[None, None, None],
46 ]
47
48
49 def pytest_pycollect_makeitem(
50 collector: Union[Module, Class], name: str, obj: object
51 ) -> Optional["UnitTestCase"]:
52 # Has unittest been imported and is obj a subclass of its TestCase?
53 try:
54 ut = sys.modules["unittest"]
55 # Type ignored because `ut` is an opaque module.
56 if not issubclass(obj, ut.TestCase): # type: ignore
57 return None
58 except Exception:
59 return None
60 # Yes, so let's collect it.
61 return UnitTestCase.from_parent(collector, name=name, obj=obj)
62
63
64 class UnitTestCase(Class):
65 # Marker for fixturemanger.getfixtureinfo()
66 # to declare that our children do not support funcargs.
67 nofuncargs = True
68
69 def newinstance(self):
70 # TestCase __init__ takes the method (test) name. The TestCase
71 # constructor treats the name "runTest" as a special no-op, so it can be
72 # used when a dummy instance is needed. While unittest.TestCase has a
73 # default, some subclasses omit the default (#9610), so always supply
74 # it.
75 return self.obj("runTest")
76
77 def collect(self) -> Iterable[Union[Item, Collector]]:
78 from unittest import TestLoader
79
80 cls = self.obj
81 if not getattr(cls, "__test__", True):
82 return
83
84 skipped = _is_skipped(cls)
85 if not skipped:
86 self._register_unittest_setup_method_fixture(cls)
87 self._register_unittest_setup_class_fixture(cls)
88 self._register_setup_class_fixture()
89
90 self.session._fixturemanager.parsefactories(self.newinstance(), self.nodeid)
91
92 loader = TestLoader()
93 foundsomething = False
94 for name in loader.getTestCaseNames(self.obj):
95 x = getattr(self.obj, name)
96 if not getattr(x, "__test__", True):
97 continue
98 yield TestCaseFunction.from_parent(self, name=name)
99 foundsomething = True
100
101 if not foundsomething:
102 runtest = getattr(self.obj, "runTest", None)
103 if runtest is not None:
104 ut = sys.modules.get("twisted.trial.unittest", None)
105 if ut is None or runtest != ut.TestCase.runTest:
106 yield TestCaseFunction.from_parent(self, name="runTest")
107
108 def _register_unittest_setup_class_fixture(self, cls: type) -> None:
109 """Register an auto-use fixture to invoke setUpClass and
110 tearDownClass (#517)."""
111 setup = getattr(cls, "setUpClass", None)
112 teardown = getattr(cls, "tearDownClass", None)
113 if setup is None and teardown is None:
114 return None
115 cleanup = getattr(cls, "doClassCleanups", lambda: None)
116
117 def process_teardown_exceptions() -> None:
118 # tearDown_exceptions is a list set in the class containing exc_infos for errors during
119 # teardown for the class.
120 exc_infos = getattr(cls, "tearDown_exceptions", None)
121 if not exc_infos:
122 return
123 exceptions = [exc for (_, exc, _) in exc_infos]
124 # If a single exception, raise it directly as this provides a more readable
125 # error (hopefully this will improve in #12255).
126 if len(exceptions) == 1:
127 raise exceptions[0]
128 else:
129 raise ExceptionGroup("Unittest class cleanup errors", exceptions)
130
131 def unittest_setup_class_fixture(
132 request: FixtureRequest,
133 ) -> Generator[None, None, None]:
134 cls = request.cls
135 if _is_skipped(cls):
136 reason = cls.__unittest_skip_why__
137 raise pytest.skip.Exception(reason, _use_item_location=True)
138 if setup is not None:
139 try:
140 setup()
141 # unittest does not call the cleanup function for every BaseException, so we
142 # follow this here.
143 except Exception:
144 cleanup()
145 process_teardown_exceptions()
146 raise
147 yield
148 try:
149 if teardown is not None:
150 teardown()
151 finally:
152 cleanup()
153 process_teardown_exceptions()
154
155 self.session._fixturemanager._register_fixture(
156 # Use a unique name to speed up lookup.
157 name=f"_unittest_setUpClass_fixture_{cls.__qualname__}",
158 func=unittest_setup_class_fixture,
159 nodeid=self.nodeid,
160 scope="class",
161 autouse=True,
162 )
163
164 def _register_unittest_setup_method_fixture(self, cls: type) -> None:
165 """Register an auto-use fixture to invoke setup_method and
166 teardown_method (#517)."""
167 setup = getattr(cls, "setup_method", None)
168 teardown = getattr(cls, "teardown_method", None)
169 if setup is None and teardown is None:
170 return None
171
172 def unittest_setup_method_fixture(
173 request: FixtureRequest,
174 ) -> Generator[None, None, None]:
175 self = request.instance
176 if _is_skipped(self):
177 reason = self.__unittest_skip_why__
178 raise pytest.skip.Exception(reason, _use_item_location=True)
179 if setup is not None:
180 setup(self, request.function)
181 yield
182 if teardown is not None:
183 teardown(self, request.function)
184
185 self.session._fixturemanager._register_fixture(
186 # Use a unique name to speed up lookup.
187 name=f"_unittest_setup_method_fixture_{cls.__qualname__}",
188 func=unittest_setup_method_fixture,
189 nodeid=self.nodeid,
190 scope="function",
191 autouse=True,
192 )
193
194
195 class TestCaseFunction(Function):
196 nofuncargs = True
197 _excinfo: Optional[List[_pytest._code.ExceptionInfo[BaseException]]] = None
198
199 def _getinstance(self):
200 assert isinstance(self.parent, UnitTestCase)
201 return self.parent.obj(self.name)
202
203 # Backward compat for pytest-django; can be removed after pytest-django
204 # updates + some slack.
205 @property
206 def _testcase(self):
207 return self.instance
208
209 def setup(self) -> None:
210 # A bound method to be called during teardown() if set (see 'runtest()').
211 self._explicit_tearDown: Optional[Callable[[], None]] = None
212 super().setup()
213
214 def teardown(self) -> None:
215 super().teardown()
216 if self._explicit_tearDown is not None:
217 self._explicit_tearDown()
218 self._explicit_tearDown = None
219 self._obj = None
220
221 def startTest(self, testcase: "unittest.TestCase") -> None:
222 pass
223
224 def _addexcinfo(self, rawexcinfo: "_SysExcInfoType") -> None:
225 # Unwrap potential exception info (see twisted trial support below).
226 rawexcinfo = getattr(rawexcinfo, "_rawexcinfo", rawexcinfo)
227 try:
228 excinfo = _pytest._code.ExceptionInfo[BaseException].from_exc_info(
229 rawexcinfo # type: ignore[arg-type]
230 )
231 # Invoke the attributes to trigger storing the traceback
232 # trial causes some issue there.
233 _ = excinfo.value
234 _ = excinfo.traceback
235 except TypeError:
236 try:
237 try:
238 values = traceback.format_exception(*rawexcinfo)
239 values.insert(
240 0,
241 "NOTE: Incompatible Exception Representation, "
242 "displaying natively:\n\n",
243 )
244 fail("".join(values), pytrace=False)
245 except (fail.Exception, KeyboardInterrupt):
246 raise
247 except BaseException:
248 fail(
249 "ERROR: Unknown Incompatible Exception "
250 f"representation:\n{rawexcinfo!r}",
251 pytrace=False,
252 )
253 except KeyboardInterrupt:
254 raise
255 except fail.Exception:
256 excinfo = _pytest._code.ExceptionInfo.from_current()
257 self.__dict__.setdefault("_excinfo", []).append(excinfo)
258
259 def addError(
260 self, testcase: "unittest.TestCase", rawexcinfo: "_SysExcInfoType"
261 ) -> None:
262 try:
263 if isinstance(rawexcinfo[1], exit.Exception):
264 exit(rawexcinfo[1].msg)
265 except TypeError:
266 pass
267 self._addexcinfo(rawexcinfo)
268
269 def addFailure(
270 self, testcase: "unittest.TestCase", rawexcinfo: "_SysExcInfoType"
271 ) -> None:
272 self._addexcinfo(rawexcinfo)
273
274 def addSkip(self, testcase: "unittest.TestCase", reason: str) -> None:
275 try:
276 raise pytest.skip.Exception(reason, _use_item_location=True)
277 except skip.Exception:
278 self._addexcinfo(sys.exc_info())
279
280 def addExpectedFailure(
281 self,
282 testcase: "unittest.TestCase",
283 rawexcinfo: "_SysExcInfoType",
284 reason: str = "",
285 ) -> None:
286 try:
287 xfail(str(reason))
288 except xfail.Exception:
289 self._addexcinfo(sys.exc_info())
290
291 def addUnexpectedSuccess(
292 self,
293 testcase: "unittest.TestCase",
294 reason: Optional["twisted.trial.unittest.Todo"] = None,
295 ) -> None:
296 msg = "Unexpected success"
297 if reason:
298 msg += f": {reason.reason}"
299 # Preserve unittest behaviour - fail the test. Explicitly not an XPASS.
300 try:
301 fail(msg, pytrace=False)
302 except fail.Exception:
303 self._addexcinfo(sys.exc_info())
304
305 def addSuccess(self, testcase: "unittest.TestCase") -> None:
306 pass
307
308 def stopTest(self, testcase: "unittest.TestCase") -> None:
309 pass
310
311 def addDuration(self, testcase: "unittest.TestCase", elapsed: float) -> None:
312 pass
313
314 def runtest(self) -> None:
315 from _pytest.debugging import maybe_wrap_pytest_function_for_tracing
316
317 testcase = self.instance
318 assert testcase is not None
319
320 maybe_wrap_pytest_function_for_tracing(self)
321
322 # Let the unittest framework handle async functions.
323 if is_async_function(self.obj):
324 testcase(result=self)
325 else:
326 # When --pdb is given, we want to postpone calling tearDown() otherwise
327 # when entering the pdb prompt, tearDown() would have probably cleaned up
328 # instance variables, which makes it difficult to debug.
329 # Arguably we could always postpone tearDown(), but this changes the moment where the
330 # TestCase instance interacts with the results object, so better to only do it
331 # when absolutely needed.
332 # We need to consider if the test itself is skipped, or the whole class.
333 assert isinstance(self.parent, UnitTestCase)
334 skipped = _is_skipped(self.obj) or _is_skipped(self.parent.obj)
335 if self.config.getoption("usepdb") and not skipped:
336 self._explicit_tearDown = testcase.tearDown
337 setattr(testcase, "tearDown", lambda *args: None)
338
339 # We need to update the actual bound method with self.obj, because
340 # wrap_pytest_function_for_tracing replaces self.obj by a wrapper.
341 setattr(testcase, self.name, self.obj)
342 try:
343 testcase(result=self)
344 finally:
345 delattr(testcase, self.name)
346
347 def _traceback_filter(
348 self, excinfo: _pytest._code.ExceptionInfo[BaseException]
349 ) -> _pytest._code.Traceback:
350 traceback = super()._traceback_filter(excinfo)
351 ntraceback = traceback.filter(
352 lambda x: not x.frame.f_globals.get("__unittest"),
353 )
354 if not ntraceback:
355 ntraceback = traceback
356 return ntraceback
357
358
359 @hookimpl(tryfirst=True)
360 def pytest_runtest_makereport(item: Item, call: CallInfo[None]) -> None:
361 if isinstance(item, TestCaseFunction):
362 if item._excinfo:
363 call.excinfo = item._excinfo.pop(0)
364 try:
365 del call.result
366 except AttributeError:
367 pass
368
369 # Convert unittest.SkipTest to pytest.skip.
370 # This is actually only needed for nose, which reuses unittest.SkipTest for
371 # its own nose.SkipTest. For unittest TestCases, SkipTest is already
372 # handled internally, and doesn't reach here.
373 unittest = sys.modules.get("unittest")
374 if unittest and call.excinfo and isinstance(call.excinfo.value, unittest.SkipTest):
375 excinfo = call.excinfo
376 call2 = CallInfo[None].from_call(
377 lambda: pytest.skip(str(excinfo.value)), call.when
378 )
379 call.excinfo = call2.excinfo
380
381
382 # Twisted trial support.
383 classImplements_has_run = False
384
385
386 @hookimpl(wrapper=True)
387 def pytest_runtest_protocol(item: Item) -> Generator[None, object, object]:
388 if isinstance(item, TestCaseFunction) and "twisted.trial.unittest" in sys.modules:
389 ut: Any = sys.modules["twisted.python.failure"]
390 global classImplements_has_run
391 Failure__init__ = ut.Failure.__init__
392 if not classImplements_has_run:
393 from twisted.trial.itrial import IReporter
394 from zope.interface import classImplements
395
396 classImplements(TestCaseFunction, IReporter)
397 classImplements_has_run = True
398
399 def excstore(
400 self, exc_value=None, exc_type=None, exc_tb=None, captureVars=None
401 ):
402 if exc_value is None:
403 self._rawexcinfo = sys.exc_info()
404 else:
405 if exc_type is None:
406 exc_type = type(exc_value)
407 self._rawexcinfo = (exc_type, exc_value, exc_tb)
408 try:
409 Failure__init__(
410 self, exc_value, exc_type, exc_tb, captureVars=captureVars
411 )
412 except TypeError:
413 Failure__init__(self, exc_value, exc_type, exc_tb)
414
415 ut.Failure.__init__ = excstore
416 try:
417 res = yield
418 finally:
419 ut.Failure.__init__ = Failure__init__
420 else:
421 res = yield
422 return res
423
424
425 def _is_skipped(obj) -> bool:
426 """Return True if the given object has been marked with @unittest.skip."""
427 return bool(getattr(obj, "__unittest_skip__", False))