本文整理汇总了Python中doctest.DocTestParser方法的典型用法代码示例。如果您正苦于以下问题:Python doctest.DocTestParser方法的具体用法?Python doctest.DocTestParser怎么用?Python doctest.DocTestParser使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类doctest
的用法示例。
在下文中一共展示了doctest.DocTestParser方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: collect
# 需要导入模块: import doctest [as 别名]
# 或者: from doctest import DocTestParser [as 别名]
def collect(self):
import doctest
# inspired by doctest.testfile; ideally we would use it directly,
# but it doesn't support passing a custom checker
encoding = self.config.getini("doctest_encoding")
text = self.fspath.read_text(encoding)
filename = str(self.fspath)
name = self.fspath.basename
globs = {"__name__": "__main__"}
optionflags = get_optionflags(self)
runner = _get_runner(
verbose=0,
optionflags=optionflags,
checker=_get_checker(),
continue_on_failure=_get_continue_on_failure(self.config),
)
parser = doctest.DocTestParser()
test = parser.get_doctest(text, globs, name, filename, 0)
if test.examples:
yield DoctestItem(test.name, self, runner, test)
示例2: test_doctest
# 需要导入模块: import doctest [as 别名]
# 或者: from doctest import DocTestParser [as 别名]
def test_doctest(self):
"""
If we parse a doctest, we get all the fields we need.
"""
test = """
>>> f()
42
"""
def f():
return 42
parser = doctest.DocTestParser()
dt = parser.get_doctest(test, {"f": f}, "doctest.name", "somefile.py", 20)
dt.__module__ = "somefile"
p = proto_test(doctest.DocTestCase(dt))
# short description
self.assertEqual(p.getDescription(2), "doctest.name")
# long description
description = p.getDescription(3)
self.assertIn("doctest.name", description)
self.assertIn("somefile.py", description)
self.assertIn("20", description)
# dotted name
self.assertEqual(p.dotted_name, "doctest.name")
示例3: _import_docstring
# 需要导入模块: import doctest [as 别名]
# 或者: from doctest import DocTestParser [as 别名]
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
示例4: _run_doctest_for_content
# 需要导入模块: import doctest [as 别名]
# 或者: from doctest import DocTestParser [as 别名]
def _run_doctest_for_content(self, name, content):
optionflags = (
doctest.ELLIPSIS
| doctest.NORMALIZE_WHITESPACE
| doctest.IGNORE_EXCEPTION_DETAIL
| _get_allow_unicode_flag()
)
runner = doctest.DocTestRunner(
verbose=None,
optionflags=optionflags,
checker=_get_unicode_checker(),
)
globs = {"print_function": print_function}
parser = doctest.DocTestParser()
test = parser.get_doctest(content, globs, name, name, 0)
runner.run(test)
runner.summarize()
assert not runner.failures
示例5: configure
# 需要导入模块: import doctest [as 别名]
# 或者: from doctest import DocTestParser [as 别名]
def configure(self, options, config):
# parent method sets enabled flag from command line --with-numpydoctest
Plugin.configure(self, options, config)
self.finder = self.test_finder_class()
self.parser = doctest.DocTestParser()
if self.enabled:
# Pull standard doctest out of plugin list; there's no reason to run
# both. In practice the Unplugger plugin above would cover us when
# run from a standard numpy.test() call; this is just in case
# someone wants to run our plugin outside the numpy.test() machinery
config.plugins.plugins = [p for p in config.plugins.plugins
if p.name != 'doctest']
示例6: run_func_docstring
# 需要导入模块: import doctest [as 别名]
# 或者: from doctest import DocTestParser [as 别名]
def run_func_docstring(tester, test_func, globs=None, verbose=False, compileflags=None, optionflags=doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE):
"""
Similar to doctest.run_docstring_examples, but takes a single function/bound method,
extracts it's singular docstring (no looking for subobjects with tests),
runs it, and most importantly raises an exception if the test doesn't pass.
tester should be an instance of dtest.Tester
test_func should be a function/bound method the docstring to be tested
"""
name = test_func.__name__
if globs is None:
globs = build_doc_context(tester, name)
# dumb function that remembers values that it is called with
# the DocTestRunner.run function called below accepts a callable for logging
# and this is a hacky but easy way to capture the nicely formatted value for reporting
def test_output_capturer(content):
if not hasattr(test_output_capturer, 'content'):
test_output_capturer.content = ''
test_output_capturer.content += content
test = doctest.DocTestParser().get_doctest(inspect.getdoc(test_func), globs, name, None, None)
runner = doctest.DocTestRunner(verbose=verbose, optionflags=optionflags)
runner.run(test, out=test_output_capturer, compileflags=compileflags)
failed, attempted = runner.summarize()
if failed > 0:
raise RuntimeError("Doctest failed! Captured output:\n{}".format(test_output_capturer.content))
if failed + attempted == 0:
raise RuntimeError("No tests were run!")
示例7: configure
# 需要导入模块: import doctest [as 别名]
# 或者: from doctest import DocTestParser [as 别名]
def configure(self, options, config):
Plugin.configure(self, options, config)
# Pull standard doctest plugin out of config; we will do doctesting
config.plugins.plugins = [p for p in config.plugins.plugins
if p.name != 'doctest']
self.doctest_tests = options.doctest_tests
self.extension = tolist(options.doctestExtension)
self.parser = doctest.DocTestParser()
self.finder = DocTestFinder()
self.checker = IPDoctestOutputChecker()
self.globs = None
self.extraglobs = None
示例8: collect
# 需要导入模块: import doctest [as 别名]
# 或者: from doctest import DocTestParser [as 别名]
def collect(self) -> Iterable[DoctestItem]:
import doctest
# inspired by doctest.testfile; ideally we would use it directly,
# but it doesn't support passing a custom checker
encoding = self.config.getini("doctest_encoding")
text = self.fspath.read_text(encoding)
filename = str(self.fspath)
name = self.fspath.basename
globs = {"__name__": "__main__"}
optionflags = get_optionflags(self)
runner = _get_runner(
verbose=False,
optionflags=optionflags,
checker=_get_checker(),
continue_on_failure=_get_continue_on_failure(self.config),
)
parser = doctest.DocTestParser()
test = parser.get_doctest(text, globs, name, filename, 0)
if test.examples:
yield DoctestItem.from_parent(
self, name=test.name, runner=runner, dtest=test
)
示例9: test_doctests
# 需要导入模块: import doctest [as 别名]
# 或者: from doctest import DocTestParser [as 别名]
def test_doctests(self, mocked_doctest_runner) -> None:
import doctest
parser = doctest.DocTestParser()
assert approx.__doc__ is not None
test = parser.get_doctest(
approx.__doc__, {"approx": approx}, approx.__name__, None, None
)
mocked_doctest_runner.run(test)
示例10: test_unicode
# 需要导入模块: import doctest [as 别名]
# 或者: from doctest import DocTestParser [as 别名]
def test_unicode(): """
Check doctest with a non-ascii filename:
>>> doc = '''
... >>> raise Exception('clé')
... '''
...
>>> parser = doctest.DocTestParser()
>>> test = parser.get_doctest(doc, {}, "foo-bär@baz", "foo-bär@baz.py", 0)
>>> test
<DocTest foo-bär@baz from foo-bär@baz.py:0 (1 example)>
>>> runner = doctest.DocTestRunner(verbose=False)
>>> runner.run(test) # doctest: +ELLIPSIS
**********************************************************************
File "foo-bär@baz.py", line 2, in foo-bär@baz
Failed example:
raise Exception('clé')
Exception raised:
Traceback (most recent call last):
File ...
compileflags, 1), test.globs)
File "<doctest foo-bär@baz[0]>", line 1, in <module>
raise Exception('clé')
Exception: clé
TestResults(failed=1, attempted=1)
"""
示例11: output
# 需要导入模块: import doctest [as 别名]
# 或者: from doctest import DocTestParser [as 别名]
def output(tests, test_vars):
dtst = doctest.DocTestParser().get_doctest(tests, test_vars, 0, '<string>', 0)
runner = ModifiedDocTestRunner()
runner.run(dtst)
return runner.results
开发者ID:baocongchen,项目名称:Coding-the-Matrix-Linear-Algebra-through-Computer-Science-Applications,代码行数:7,代码来源:coursera_submit.py
示例12: run_doctest
# 需要导入模块: import doctest [as 别名]
# 或者: from doctest import DocTestParser [as 别名]
def run_doctest(obj, name):
p = doctest.DocTestParser()
t = p.get_doctest(
obj.__doc__, sys.modules[obj.__module__].__dict__, name, '', 0)
r = doctest.DocTestRunner()
output = StringIO()
r.run(t, out=output.write)
return r.failures, output.getvalue()
示例13: _parse_docstring
# 需要导入模块: import doctest [as 别名]
# 或者: from doctest import DocTestParser [as 别名]
def _parse_docstring(node):
"""Extract code from docstring."""
docstring = ast.get_docstring(node)
if docstring:
parser = doctest.DocTestParser()
try:
dt = parser.get_doctest(docstring, {}, None, None, None)
except ValueError:
# >>> 'abc'
pass
else:
examples = dt.examples
return '\n'.join([example.source for example in examples])
return None
示例14: test
# 需要导入模块: import doctest [as 别名]
# 或者: from doctest import DocTestParser [as 别名]
def test(**kwargs):
import doctest
doctest.NORMALIZE_WHITESPACE = 1
verbosity = kwargs.get('verbose', 0)
if verbosity == 0:
print('Running doctests...')
# ignore py2-3 unicode differences
import re
class Py23DocChecker(doctest.OutputChecker):
def check_output(self, want, got, optionflags):
if sys.version_info[0] == 2:
got = re.sub("u'(.*?)'", "'\\1'", got)
got = re.sub('u"(.*?)"', '"\\1"', got)
res = doctest.OutputChecker.check_output(self, want, got, optionflags)
return res
def summarize(self):
doctest.OutputChecker.summarize(True)
# run tests
runner = doctest.DocTestRunner(checker=Py23DocChecker(), verbose=verbosity)
with open("README.md","rb") as fobj:
test = doctest.DocTestParser().get_doctest(string=fobj.read().decode("utf8").replace('\r\n','\n'), globs={}, name="README", filename="README.md", lineno=0)
failure_count, test_count = runner.run(test)
# print results
if verbosity:
runner.summarize(True)
else:
if failure_count == 0:
print('All test passed successfully')
elif failure_count > 0:
runner.summarize(verbosity)
return failure_count