本文整理匯總了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