"""Test result object"""import ioimport sysimport tracebackfrom . import utilfrom functools import wraps__unittest = Truedef failfast(method):@wraps(method)def inner(self, *args, **kw):if getattr(self, 'failfast', False):self.stop()return method(self, *args, **kw)return innerSTDOUT_LINE = '\nStdout:\n%s'STDERR_LINE = '\nStderr:\n%s'class TestResult(object):"""Holder for test result information.Test results are automatically managed by the TestCase and TestSuiteclasses, and do not need to be explicitly manipulated by writers of tests.Each instance holds the total number of tests run, and collections offailures and errors that occurred among those test runs. The collectionscontain tuples of (testcase, exceptioninfo), where exceptioninfo is theformatted traceback of the error that occurred."""_previousTestClass = None_testRunEntered = False_moduleSetUpFailed = Falsedef __init__(self, stream=None, descriptions=None, verbosity=None):self.failfast = Falseself.failures = []self.errors = []self.testsRun = 0self.skipped = []self.expectedFailures = []self.unexpectedSuccesses = []self.shouldStop = Falseself.buffer = Falseself.tb_locals = Falseself._stdout_buffer = Noneself._stderr_buffer = Noneself._original_stdout = sys.stdoutself._original_stderr = sys.stderrself._mirrorOutput = Falsedef printErrors(self):"Called by TestRunner after test run"def startTest(self, test):"Called when the given test is about to be run"self.testsRun += 1self._mirrorOutput = Falseself._setupStdout()def _setupStdout(self):if self.buffer:if self._stderr_buffer is None:self._stderr_buffer = io.StringIO()self._stdout_buffer = io.StringIO()sys.stdout = self._stdout_buffersys.stderr = self._stderr_bufferdef startTestRun(self):"""Called once before any tests are executed.See startTest for a method called before each test."""def stopTest(self, test):"""Called when the given test has been run"""self._restoreStdout()self._mirrorOutput = Falsedef _restoreStdout(self):if self.buffer:if self._mirrorOutput:output = sys.stdout.getvalue()error = sys.stderr.getvalue()if output:if not output.endswith('\n'):output += '\n'self._original_stdout.write(STDOUT_LINE % output)if error:if not error.endswith('\n'):error += '\n'self._original_stderr.write(STDERR_LINE % error)sys.stdout = self._original_stdoutsys.stderr = self._original_stderrself._stdout_buffer.seek(0)self._stdout_buffer.truncate()self._stderr_buffer.seek(0)self._stderr_buffer.truncate()def stopTestRun(self):"""Called once after all tests are executed.See stopTest for a method called after each test."""@failfastdef addError(self, test, err):"""Called when an error has occurred. 'err' is a tuple of values asreturned by sys.exc_info()."""self.errors.append((test, self._exc_info_to_string(err, test)))self._mirrorOutput = True@failfastdef addFailure(self, test, err):"""Called when an error has occurred. 'err' is a tuple of values asreturned by sys.exc_info()."""self.failures.append((test, self._exc_info_to_string(err, test)))self._mirrorOutput = Truedef addSubTest(self, test, subtest, err):"""Called at the end of a subtest.'err' is None if the subtest ended successfully, otherwise it's atuple of values as returned by sys.exc_info()."""# By default, we don't do anything with successful subtests, but# more sophisticated test results might want to record them.if err is not None:if getattr(self, 'failfast', False):self.stop()if issubclass(err[0], test.failureException):errors = self.failureselse:errors = self.errorserrors.append((subtest, self._exc_info_to_string(err, test)))self._mirrorOutput = Truedef addSuccess(self, test):"Called when a test has completed successfully"passdef addSkip(self, test, reason):"""Called when a test is skipped."""self.skipped.append((test, reason))def addExpectedFailure(self, test, err):"""Called when an expected failure/error occurred."""self.expectedFailures.append((test, self._exc_info_to_string(err, test)))@failfastdef addUnexpectedSuccess(self, test):"""Called when a test was expected to fail, but succeed."""self.unexpectedSuccesses.append(test)def wasSuccessful(self):"""Tells whether or not this result was a success."""# The hasattr check is for test_result's OldResult test. That# way this method works on objects that lack the attribute.# (where would such result intances come from? old stored pickles?)return ((len(self.failures) == len(self.errors) == 0) and(not hasattr(self, 'unexpectedSuccesses') orlen(self.unexpectedSuccesses) == 0))def stop(self):"""Indicates that the tests should be aborted."""self.shouldStop = Truedef _exc_info_to_string(self, err, test):"""Converts a sys.exc_info()-style tuple of values into a string."""exctype, value, tb = err# Skip test runner traceback levelswhile tb and self._is_relevant_tb_level(tb):tb = tb.tb_nextif exctype is test.failureException:# Skip assert*() traceback levelslength = self._count_relevant_tb_levels(tb)else:length = Nonetb_e = traceback.TracebackException(exctype, value, tb, limit=length, capture_locals=self.tb_locals)msgLines = list(tb_e.format())if self.buffer:output = sys.stdout.getvalue()error = sys.stderr.getvalue()if output:if not output.endswith('\n'):output += '\n'msgLines.append(STDOUT_LINE % output)if error:if not error.endswith('\n'):error += '\n'msgLines.append(STDERR_LINE % error)return ''.join(msgLines)def _is_relevant_tb_level(self, tb):return '__unittest' in tb.tb_frame.f_globalsdef _count_relevant_tb_levels(self, tb):length = 0while tb and not self._is_relevant_tb_level(tb):length += 1tb = tb.tb_nextreturn lengthdef __repr__(self):return ("<%s run=%i errors=%i failures=%i>" %(util.strclass(self.__class__), self.testsRun, len(self.errors),len(self.failures)))
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。