本文整理汇总了Python中doctest.DocTestRunner类的典型用法代码示例。如果您正苦于以下问题:Python DocTestRunner类的具体用法?Python DocTestRunner怎么用?Python DocTestRunner使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了DocTestRunner类的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: report_start
def report_start(self, out, test, example):
if 1 <= self._verbosity <= 2:
src = example.source.split('\n')[0]
if len(src) > 60: src = src[:57]+'...'
lineno = test.lineno + example.lineno + 1
if self._verbosity == 1:
if self._stderr_term.CLEAR_LINE:
sys.__stderr__.write(self._stderr_term.CLEAR_LINE)
else:
sys.__stderr__.write('\n')
sys.__stderr__.write('%s [Line %s] %s%s' %
(self._stderr_term.BOLD, lineno,
self._stderr_term.NORMAL, src))
if self._verbosity == 2:
sys.__stderr__.write('\n')
else:
DocTestRunner.report_start(self, out, test, example)
sys.__stdout__.flush()
self._current_test = (test, example)
# Total hack warning: This munges the original source to
# catch any keyboard interrupts, and turn them into special
# ValueError interrupts.
example.original_source = example.source
if self._kbinterrupt_continue:
example.source = ('try:\n%sexcept KeyboardInterrupt:\n '
'raise ValueError("KEYBOARD-INTERRUPT")\n' %
doctest._indent(example.source))
示例2: DTC_runTest
def DTC_runTest(self):
test = self._dt_test
old = sys.stdout
new = StringIO()
optionflags = self._dt_optionflags
if not (optionflags & REPORTING_FLAGS):
# The option flags don't include any reporting flags,
# so add the default reporting flags
optionflags |= _unittest_reportflags
# Patching doctestcase to enable verbose mode
global g_doctest_verbose
runner = DocTestRunner(optionflags=optionflags,
checker=self._dt_checker,
verbose=g_doctest_verbose)
# End of patch
try:
runner.DIVIDER = "-"*70
failures, tries = runner.run(
test, out=new.write, clear_globs=False)
finally:
sys.stdout = old
if failures:
raise self.failureException(self.format_failure(new.getvalue()))
elif g_doctest_verbose:
print new.getvalue()
示例3: __init__
def __init__(self, checker=None, verbosity=1, optionflags=0,
kbinterrupt_continue=False):
DocTestRunner.__init__(self, checker, (verbosity>2), optionflags)
self._verbosity = verbosity
self._current_test = None
self._term = TerminalController()
self._stderr_term = TerminalController(sys.__stderr__)
self._kbinterrupt_continue = kbinterrupt_continue
示例4: run_doctests
def run_doctests(module, examples):
from doctest import DocTest, DocTestRunner, ELLIPSIS
dt = DocTest(examples, module.__dict__, module.__file__, None, None, None)
dtr = DocTestRunner(optionflags=ELLIPSIS)
dtr.run(dt, clear_globs=False)
return dtr
示例5: run_examples
def run_examples(self):
from doctest import DocTest, DocTestRunner
examples = sum([part.examples for part in self.parts if isinstance(part, DocTestPart)],[])
dt = DocTest(examples, self.module.__dict__, self.filename, None, None, None)
dtr = DocTestRunner()
def tmp_out(message_to_throw_away):
# TODO capture error messages, warn
return
dtr.run(dt, out=tmp_out, clear_globs=False)
示例6: test
def test(self):
# Make a new runner per function to be tested
runner = DocTestRunner(verbose=d2u.verbose)
for the_test in d2u.finder.find(func, func.__name__):
runner.run(the_test)
failed = count_failures(runner)
if failed:
# Since we only looked at a single function's docstring,
# failed should contain at most one item. More than that
# is a case we can't handle and should error out on
if len(failed) > 1:
err = "Invalid number of test results:" % failed
raise ValueError(err)
# Report a normal failure.
self.fail('failed doctests: %s' % str(failed[0]))
示例7: run
def run(self, test, compileflags=None, out=None, clear_globs=True):
save_stderr = sys.stderr
sys.stderr = _SpoofOut()
if self._verbosity > 0:
print >>save_stderr, (
self._stderr_term.CYAN+self._stderr_term.BOLD+
'Testing %s...'%test.name+self._stderr_term.NORMAL)
try:
fails, tries = DocTestRunner.run(self, test, compileflags,
out, clear_globs)
except KeyboardInterrupt:
if self._current_test is None: raise
print >>save_stderr, self._failure_header(*self._current_test)
print >>save_stderr, (
self._stderr_term.RED+self._stderr_term.BOLD+
'Keyboard Interrupt!'+self._stderr_term.NORMAL)
if self._verbosity == 1:
save_stderr.write(self._stderr_term.CLEAR_LINE)
if self._verbosity > 0:
if fails:
print >>save_stderr, (
self._stderr_term.RED+self._stderr_term.BOLD+
' %d example(s) failed!'%fails+self._stderr_term.NORMAL)
else:
print >>save_stderr, (
self._stderr_term.GREEN+self._stderr_term.BOLD+
' All examples passed'+self._stderr_term.NORMAL)
print >>save_stderr
sys.stderr = save_stderr
示例8: __init__
def __init__(self, args, assignment):
super().__init__(args, assignment)
# The environment in which the doctests are run (global vars)
self.good_env = {}
self.verb = self.args.verbose
# Initialize the doctest module objects that will do the testing/parse
self.parser = DocTestParser()
self.runner = DocTestRunner(verbose=self.verb, optionflags=FAIL_FAST)
self.lines_exec = 0
self.lines_total = 0
示例9: _import_docstring
def _import_docstring(documenter):
code_content = _import_docstring_code_content(documenter)
if code_content:
# noinspection PyBroadException
try:
code, content = code_content
parser = DocTestParser()
runner = DocTestRunner(verbose=0,
optionflags=NORMALIZE_WHITESPACE | ELLIPSIS)
glob = {}
if documenter.modname:
exec('from %s import *\n' % documenter.modname, glob)
tests = parser.get_doctest(code, glob, '', '', 0)
runner.run(tests, clear_globs=False)
documenter.object = tests.globs[documenter.name]
documenter.code = content
documenter.is_doctest = True
return True
except Exception:
pass
示例10: run_test
def run_test(doctest):
summary = StringIO()
runner = DocTestRunner(optionflags=REPORT_NDIFF)
runner.run(doctest, out=summary.write)
assert runner.failures == 0, '\n' + summary.getvalue()
示例11: TestingProtocol
class TestingProtocol(models.Protocol):
"""A Protocol that executes doctests as lists of Example objects, supports
suite/case specificity, alternate file testing, and provides users with
details such as cases passed and test coverage.
"""
def __init__(self, args, assignment):
super().__init__(args, assignment)
# The environment in which the doctests are run (global vars)
self.good_env = {}
self.verb = self.args.verbose
# Initialize the doctest module objects that will do the testing/parse
self.parser = DocTestParser()
self.runner = DocTestRunner(verbose=self.verb, optionflags=FAIL_FAST)
self.lines_exec = 0
self.lines_total = 0
def test(self, good_env={}, suite=None, case=None):
test_results = {}
# all examples to be run will be put in exs
exs = collections.OrderedDict()
# use regex to get raw strings organized into suite/case
self.get_data()
try:
if suite:
exs = self.get_suite_examples(suite, case)
elif case:
# No support for cases without their suite
raise EarlyExit('python3 ok: error: '
'Please specify suite for given case ({}).'.format(case[0]))
else:
exs = self.get_all_examples()
# gets analytics to be returned
test_results[self.tstfile_name] = self.analyze(suite, case, exs)
except KeyError as e:
raise EarlyExit('python3 ok: error: '
'Suite/Case label must be valid.'
'(Suites: {}, Cases: {})'.format(self.num_suites, self.num_cases))
return test_results
def analyze(self, suite, case, examples):
failed, attempted = self.run_examples(examples)
self.cov.stop()
passed = attempted - failed
format.print_test_progress_bar( '{} summary'.format(self.tstfile_name),
passed, failed, verbose=self.verb)
# only support test coverage stats when running everything
if not suite:
self.print_coverage()
if self.args.coverage:
if self.lines_exec == self.lines_total:
print("Maximum coverage achieved! Great work!")
else:
self.give_suggestions()
return {'suites_total' : self.num_suites, 'cases_total': self.num_cases,
'exs_failed' : failed, 'exs_passed' : passed, 'attempted' : attempted,
'actual_cov' : self.lines_exec, 'total_cov' : self.lines_total}
def give_suggestions(self):
print("Consider adding tests for the following:")
for file in self.clean_src:
file += '.py'
cov_stats = self.cov.analysis2(file)
missing_cov = cov_stats[3]
if missing_cov:
print(' File: {}'.format(file))
missing_string = ' Line(s): ' + ','.join(map(str, missing_cov))
print(missing_string)
def get_suite_examples(self, suite, case):
# suite/case specified, so only parse relevant text into Examples
exs = collections.OrderedDict()
case_ex = collections.OrderedDict()
# get the shared lines that should impact all the cases in the suite.
shrd_txt = self.shared_case_data[suite]
if shrd_txt:
parse_shared = self.parser.parse(shrd_txt.group(0), self.tstfile_name)
shrd_ex = [i for i in parse_shared if isinstance(i, Example)]
if shrd_ex:
case_ex['shared'] = shrd_ex
if case:
if str(case[0]) not in self.data[suite]:
raise KeyError
parsed_temp_examples = self.parser.parse(self.data[suite][case[0]], self.tstfile_name)
case_examples = [i for i in parsed_temp_examples if isinstance(i, Example)]
case_ex[str(case[0])] = case_examples
else:
for itemcase in self.data[suite].keys():
parsed_temp_examples = self.parser.parse(self.data[suite][itemcase], self.tstfile_name)
case_examples = [i for i in parsed_temp_examples if isinstance(i, Example)]
case_ex[itemcase] = case_examples
exs[suite] = case_ex
return exs
def get_all_examples(self):
# no suite/case flag, so parses all text into Example objects
exs = collections.OrderedDict()
#.........这里部分代码省略.........