ยปCore Development>Code coverage>Lib/unittest/runner.py

Python code coverage for Lib/unittest/runner.py

#countcontent
1n/a"""Running tests"""
2n/a
3n/aimport sys
4n/aimport time
5n/aimport warnings
6n/a
7n/afrom . import result
8n/afrom .signals import registerResult
9n/a
10n/a__unittest = True
11n/a
12n/a
13n/aclass _WritelnDecorator(object):
14n/a """Used to decorate file-like objects with a handy 'writeln' method"""
15n/a def __init__(self,stream):
16n/a self.stream = stream
17n/a
18n/a def __getattr__(self, attr):
19n/a if attr in ('stream', '__getstate__'):
20n/a raise AttributeError(attr)
21n/a return getattr(self.stream,attr)
22n/a
23n/a def writeln(self, arg=None):
24n/a if arg:
25n/a self.write(arg)
26n/a self.write('\n') # text-mode streams translate to \r\n if needed
27n/a
28n/a
29n/aclass TextTestResult(result.TestResult):
30n/a """A test result class that can print formatted text results to a stream.
31n/a
32n/a Used by TextTestRunner.
33n/a """
34n/a separator1 = '=' * 70
35n/a separator2 = '-' * 70
36n/a
37n/a def __init__(self, stream, descriptions, verbosity):
38n/a super(TextTestResult, self).__init__(stream, descriptions, verbosity)
39n/a self.stream = stream
40n/a self.showAll = verbosity > 1
41n/a self.dots = verbosity == 1
42n/a self.descriptions = descriptions
43n/a
44n/a def getDescription(self, test):
45n/a doc_first_line = test.shortDescription()
46n/a if self.descriptions and doc_first_line:
47n/a return '\n'.join((str(test), doc_first_line))
48n/a else:
49n/a return str(test)
50n/a
51n/a def startTest(self, test):
52n/a super(TextTestResult, self).startTest(test)
53n/a if self.showAll:
54n/a self.stream.write(self.getDescription(test))
55n/a self.stream.write(" ... ")
56n/a self.stream.flush()
57n/a
58n/a def addSuccess(self, test):
59n/a super(TextTestResult, self).addSuccess(test)
60n/a if self.showAll:
61n/a self.stream.writeln("ok")
62n/a elif self.dots:
63n/a self.stream.write('.')
64n/a self.stream.flush()
65n/a
66n/a def addError(self, test, err):
67n/a super(TextTestResult, self).addError(test, err)
68n/a if self.showAll:
69n/a self.stream.writeln("ERROR")
70n/a elif self.dots:
71n/a self.stream.write('E')
72n/a self.stream.flush()
73n/a
74n/a def addFailure(self, test, err):
75n/a super(TextTestResult, self).addFailure(test, err)
76n/a if self.showAll:
77n/a self.stream.writeln("FAIL")
78n/a elif self.dots:
79n/a self.stream.write('F')
80n/a self.stream.flush()
81n/a
82n/a def addSkip(self, test, reason):
83n/a super(TextTestResult, self).addSkip(test, reason)
84n/a if self.showAll:
85n/a self.stream.writeln("skipped {0!r}".format(reason))
86n/a elif self.dots:
87n/a self.stream.write("s")
88n/a self.stream.flush()
89n/a
90n/a def addExpectedFailure(self, test, err):
91n/a super(TextTestResult, self).addExpectedFailure(test, err)
92n/a if self.showAll:
93n/a self.stream.writeln("expected failure")
94n/a elif self.dots:
95n/a self.stream.write("x")
96n/a self.stream.flush()
97n/a
98n/a def addUnexpectedSuccess(self, test):
99n/a super(TextTestResult, self).addUnexpectedSuccess(test)
100n/a if self.showAll:
101n/a self.stream.writeln("unexpected success")
102n/a elif self.dots:
103n/a self.stream.write("u")
104n/a self.stream.flush()
105n/a
106n/a def printErrors(self):
107n/a if self.dots or self.showAll:
108n/a self.stream.writeln()
109n/a self.printErrorList('ERROR', self.errors)
110n/a self.printErrorList('FAIL', self.failures)
111n/a
112n/a def printErrorList(self, flavour, errors):
113n/a for test, err in errors:
114n/a self.stream.writeln(self.separator1)
115n/a self.stream.writeln("%s: %s" % (flavour,self.getDescription(test)))
116n/a self.stream.writeln(self.separator2)
117n/a self.stream.writeln("%s" % err)
118n/a
119n/a
120n/aclass TextTestRunner(object):
121n/a """A test runner class that displays results in textual form.
122n/a
123n/a It prints out the names of tests as they are run, errors as they
124n/a occur, and a summary of the results at the end of the test run.
125n/a """
126n/a resultclass = TextTestResult
127n/a
128n/a def __init__(self, stream=None, descriptions=True, verbosity=1,
129n/a failfast=False, buffer=False, resultclass=None, warnings=None,
130n/a *, tb_locals=False):
131n/a """Construct a TextTestRunner.
132n/a
133n/a Subclasses should accept **kwargs to ensure compatibility as the
134n/a interface changes.
135n/a """
136n/a if stream is None:
137n/a stream = sys.stderr
138n/a self.stream = _WritelnDecorator(stream)
139n/a self.descriptions = descriptions
140n/a self.verbosity = verbosity
141n/a self.failfast = failfast
142n/a self.buffer = buffer
143n/a self.tb_locals = tb_locals
144n/a self.warnings = warnings
145n/a if resultclass is not None:
146n/a self.resultclass = resultclass
147n/a
148n/a def _makeResult(self):
149n/a return self.resultclass(self.stream, self.descriptions, self.verbosity)
150n/a
151n/a def run(self, test):
152n/a "Run the given test case or test suite."
153n/a result = self._makeResult()
154n/a registerResult(result)
155n/a result.failfast = self.failfast
156n/a result.buffer = self.buffer
157n/a result.tb_locals = self.tb_locals
158n/a with warnings.catch_warnings():
159n/a if self.warnings:
160n/a # if self.warnings is set, use it to filter all the warnings
161n/a warnings.simplefilter(self.warnings)
162n/a # if the filter is 'default' or 'always', special-case the
163n/a # warnings from the deprecated unittest methods to show them
164n/a # no more than once per module, because they can be fairly
165n/a # noisy. The -Wd and -Wa flags can be used to bypass this
166n/a # only when self.warnings is None.
167n/a if self.warnings in ['default', 'always']:
168n/a warnings.filterwarnings('module',
169n/a category=DeprecationWarning,
170n/a message=r'Please use assert\w+ instead.')
171n/a startTime = time.time()
172n/a startTestRun = getattr(result, 'startTestRun', None)
173n/a if startTestRun is not None:
174n/a startTestRun()
175n/a try:
176n/a test(result)
177n/a finally:
178n/a stopTestRun = getattr(result, 'stopTestRun', None)
179n/a if stopTestRun is not None:
180n/a stopTestRun()
181n/a stopTime = time.time()
182n/a timeTaken = stopTime - startTime
183n/a result.printErrors()
184n/a if hasattr(result, 'separator2'):
185n/a self.stream.writeln(result.separator2)
186n/a run = result.testsRun
187n/a self.stream.writeln("Ran %d test%s in %.3fs" %
188n/a (run, run != 1 and "s" or "", timeTaken))
189n/a self.stream.writeln()
190n/a
191n/a expectedFails = unexpectedSuccesses = skipped = 0
192n/a try:
193n/a results = map(len, (result.expectedFailures,
194n/a result.unexpectedSuccesses,
195n/a result.skipped))
196n/a except AttributeError:
197n/a pass
198n/a else:
199n/a expectedFails, unexpectedSuccesses, skipped = results
200n/a
201n/a infos = []
202n/a if not result.wasSuccessful():
203n/a self.stream.write("FAILED")
204n/a failed, errored = len(result.failures), len(result.errors)
205n/a if failed:
206n/a infos.append("failures=%d" % failed)
207n/a if errored:
208n/a infos.append("errors=%d" % errored)
209n/a else:
210n/a self.stream.write("OK")
211n/a if skipped:
212n/a infos.append("skipped=%d" % skipped)
213n/a if expectedFails:
214n/a infos.append("expected failures=%d" % expectedFails)
215n/a if unexpectedSuccesses:
216n/a infos.append("unexpected successes=%d" % unexpectedSuccesses)
217n/a if infos:
218n/a self.stream.writeln(" (%s)" % (", ".join(infos),))
219n/a else:
220n/a self.stream.write("\n")
221n/a return result