Debian Codegraph @

_pytest/unittest.py

raw symbols SCIP
1 """ discovery and running of std-library "unittest" style tests. """
2 from __future__ import absolute_import
3
4 import sys
5 import traceback
6
7 import pytest
8 # for transfering markers
9 import _pytest._code
10 from _pytest.python import transfer_markers
11 from _pytest.skipping import MarkEvaluator
12
13
14 def pytest_pycollect_makeitem(collector, name, obj):
15 # has unittest been imported and is obj a subclass of its TestCase?
16 try:
17 if not issubclass(obj, sys.modules["unittest"].TestCase):
18 return
19 except Exception:
20 return
21 # yes, so let's collect it
22 return UnitTestCase(name, parent=collector)
23
24
25 class UnitTestCase(pytest.Class):
26 # marker for fixturemanger.getfixtureinfo()
27 # to declare that our children do not support funcargs
28 nofuncargs = True
29
30 def setup(self):
31 cls = self.obj
32 if getattr(cls, '__unittest_skip__', False):
33 return # skipped
34 setup = getattr(cls, 'setUpClass', None)
35 if setup is not None:
36 setup()
37 teardown = getattr(cls, 'tearDownClass', None)
38 if teardown is not None:
39 self.addfinalizer(teardown)
40 super(UnitTestCase, self).setup()
41
42 def collect(self):
43 from unittest import TestLoader
44 cls = self.obj
45 if not getattr(cls, "__test__", True):
46 return
47 self.session._fixturemanager.parsefactories(self, unittest=True)
48 loader = TestLoader()
49 module = self.getparent(pytest.Module).obj
50 foundsomething = False
51 for name in loader.getTestCaseNames(self.obj):
52 x = getattr(self.obj, name)
53 funcobj = getattr(x, 'im_func', x)
54 transfer_markers(funcobj, cls, module)
55 yield TestCaseFunction(name, parent=self)
56 foundsomething = True
57
58 if not foundsomething:
59 runtest = getattr(self.obj, 'runTest', None)
60 if runtest is not None:
61 ut = sys.modules.get("twisted.trial.unittest", None)
62 if ut is None or runtest != ut.TestCase.runTest:
63 yield TestCaseFunction('runTest', parent=self)
64
65
66
67 class TestCaseFunction(pytest.Function):
68 _excinfo = None
69
70 def setup(self):
71 self._testcase = self.parent.obj(self.name)
72 self._fix_unittest_skip_decorator()
73 self._obj = getattr(self._testcase, self.name)
74 if hasattr(self._testcase, 'setup_method'):
75 self._testcase.setup_method(self._obj)
76 if hasattr(self, "_request"):
77 self._request._fillfixtures()
78
79 def _fix_unittest_skip_decorator(self):
80 """
81 The @unittest.skip decorator calls functools.wraps(self._testcase)
82 The call to functools.wraps() fails unless self._testcase
83 has a __name__ attribute. This is usually automatically supplied
84 if the test is a function or method, but we need to add manually
85 here.
86
87 See issue #1169
88 """
89 if sys.version_info[0] == 2:
90 setattr(self._testcase, "__name__", self.name)
91
92 def teardown(self):
93 if hasattr(self._testcase, 'teardown_method'):
94 self._testcase.teardown_method(self._obj)
95
96 def startTest(self, testcase):
97 pass
98
99 def _addexcinfo(self, rawexcinfo):
100 # unwrap potential exception info (see twisted trial support below)
101 rawexcinfo = getattr(rawexcinfo, '_rawexcinfo', rawexcinfo)
102 try:
103 excinfo = _pytest._code.ExceptionInfo(rawexcinfo)
104 except TypeError:
105 try:
106 try:
107 l = traceback.format_exception(*rawexcinfo)
108 l.insert(0, "NOTE: Incompatible Exception Representation, "
109 "displaying natively:\n\n")
110 pytest.fail("".join(l), pytrace=False)
111 except (pytest.fail.Exception, KeyboardInterrupt):
112 raise
113 except:
114 pytest.fail("ERROR: Unknown Incompatible Exception "
115 "representation:\n%r" %(rawexcinfo,), pytrace=False)
116 except KeyboardInterrupt:
117 raise
118 except pytest.fail.Exception:
119 excinfo = _pytest._code.ExceptionInfo()
120 self.__dict__.setdefault('_excinfo', []).append(excinfo)
121
122 def addError(self, testcase, rawexcinfo):
123 self._addexcinfo(rawexcinfo)
124 def addFailure(self, testcase, rawexcinfo):
125 self._addexcinfo(rawexcinfo)
126
127 def addSkip(self, testcase, reason):
128 try:
129 pytest.skip(reason)
130 except pytest.skip.Exception:
131 self._evalskip = MarkEvaluator(self, 'SkipTest')
132 self._evalskip.result = True
133 self._addexcinfo(sys.exc_info())
134
135 def addExpectedFailure(self, testcase, rawexcinfo, reason=""):
136 try:
137 pytest.xfail(str(reason))
138 except pytest.xfail.Exception:
139 self._addexcinfo(sys.exc_info())
140
141 def addUnexpectedSuccess(self, testcase, reason=""):
142 self._unexpectedsuccess = reason
143
144 def addSuccess(self, testcase):
145 pass
146
147 def stopTest(self, testcase):
148 pass
149
150 def runtest(self):
151 self._testcase(result=self)
152
153 def _prunetraceback(self, excinfo):
154 pytest.Function._prunetraceback(self, excinfo)
155 traceback = excinfo.traceback.filter(
156 lambda x:not x.frame.f_globals.get('__unittest'))
157 if traceback:
158 excinfo.traceback = traceback
159
160 @pytest.hookimpl(tryfirst=True)
161 def pytest_runtest_makereport(item, call):
162 if isinstance(item, TestCaseFunction):
163 if item._excinfo:
164 call.excinfo = item._excinfo.pop(0)
165 try:
166 del call.result
167 except AttributeError:
168 pass
169
170 # twisted trial support
171
172 @pytest.hookimpl(hookwrapper=True)
173 def pytest_runtest_protocol(item):
174 if isinstance(item, TestCaseFunction) and \
175 'twisted.trial.unittest' in sys.modules:
176 ut = sys.modules['twisted.python.failure']
177 Failure__init__ = ut.Failure.__init__
178 check_testcase_implements_trial_reporter()
179 def excstore(self, exc_value=None, exc_type=None, exc_tb=None,
180 captureVars=None):
181 if exc_value is None:
182 self._rawexcinfo = sys.exc_info()
183 else:
184 if exc_type is None:
185 exc_type = type(exc_value)
186 self._rawexcinfo = (exc_type, exc_value, exc_tb)
187 try:
188 Failure__init__(self, exc_value, exc_type, exc_tb,
189 captureVars=captureVars)
190 except TypeError:
191 Failure__init__(self, exc_value, exc_type, exc_tb)
192 ut.Failure.__init__ = excstore
193 yield
194 ut.Failure.__init__ = Failure__init__
195 else:
196 yield
197
198
199 def check_testcase_implements_trial_reporter(done=[]):
200 if done:
201 return
202 from zope.interface import classImplements
203 from twisted.trial.itrial import IReporter
204 classImplements(TestCaseFunction, IReporter)
205 done.append(1)