def test_doctests(module_name):
_, test_count = doctest.testmod(
import_module(module_name),
report=True,
verbose=True,
raise_on_error=True,
optionflags=doctest.NORMALIZE_WHITESPACE,
)
assert test_count > 0
python类NORMALIZE_WHITESPACE的实例源码
def _get_flag_lookup():
import doctest
return dict(DONT_ACCEPT_TRUE_FOR_1=doctest.DONT_ACCEPT_TRUE_FOR_1,
DONT_ACCEPT_BLANKLINE=doctest.DONT_ACCEPT_BLANKLINE,
NORMALIZE_WHITESPACE=doctest.NORMALIZE_WHITESPACE,
ELLIPSIS=doctest.ELLIPSIS,
IGNORE_EXCEPTION_DETAIL=doctest.IGNORE_EXCEPTION_DETAIL,
COMPARISON_FLAGS=doctest.COMPARISON_FLAGS,
ALLOW_UNICODE=_get_allow_unicode_flag())
def additional_tests(): # for setup.py
return doctest.DocTestSuite(optionflags=doctest.NORMALIZE_WHITESPACE,
checker=Checker())
def test():
import doctest
doctest.NORMALIZE_WHITESPACE = 1
doctest.testfile("README.txt", verbose=1)
def assertDocTestMatches(self, expected, observed):
return self.assertThat(observed, DocTestMatches(
dedent(expected), doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE))
def loadTestsFromModule(self, module):
#print '*** ipdoctest - lTM',module # dbg
if not self.matches(module.__name__):
log.debug("Doctest doesn't want module %s", module)
return
tests = self.finder.find(module,globs=self.globs,
extraglobs=self.extraglobs)
if not tests:
return
# always use whitespace and ellipsis options
optionflags = doctest.NORMALIZE_WHITESPACE | doctest.ELLIPSIS
tests.sort()
module_file = module.__file__
if module_file[-4:] in ('.pyc', '.pyo'):
module_file = module_file[:-1]
for test in tests:
if not test.examples:
continue
if not test.filename:
test.filename = module_file
yield DocTestCase(test,
optionflags=optionflags,
checker=self.checker)
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!")
def setup_optionflags(self):
if 'optionflags' not in self._kw:
self._kw['optionflags'] = (
doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE)
def setup_optionflags(self):
if 'optionflags' not in self._kw:
self._kw['optionflags'] = (
doctest.ELLIPSIS | doctest.REPORT_NDIFF |
doctest.NORMALIZE_WHITESPACE)
def load_tests(loader, tests, ignore):
import ibex
doctest_flags = doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE
tests.addTests(doctest.DocTestSuite(__import__('ibex'), optionflags=doctest_flags))
for mod_name in dir(ibex):
try:
mod =__import__('ibex.' + mod_name)
except ImportError:
continue
tests.addTests(doctest.DocTestSuite(mod, optionflags=doctest_flags))
f_name = os.path.join(_this_dir, '../ibex/sklearn/__init__.py')
tests.addTests(doctest.DocFileSuite(f_name, module_relative=False, optionflags=doctest_flags))
f_name = os.path.join(_this_dir, '../ibex/xgboost/__init__.py')
tests.addTests(doctest.DocFileSuite(f_name, module_relative=False, optionflags=doctest_flags))
f_name = os.path.join(_this_dir, '../ibex/tensorflow/contrib/keras/wrappers/scikit_learn/__init__.py')
tests.addTests(doctest.DocFileSuite(f_name, module_relative=False, optionflags=doctest_flags))
doc_f_names = list(glob(os.path.join(_this_dir, '../docs/source/*.rst')))
doc_f_names += [os.path.join(_this_dir, '../README.rst')]
tests.addTests(
doctest.DocFileSuite(*doc_f_names, module_relative=False, optionflags=doctest_flags))
doc_f_names = list(glob(os.path.join(_this_dir, '../docs/build/text/*.txt')))
tests.addTests(
doctest.DocFileSuite(*doc_f_names, module_relative=False, optionflags=doctest_flags))
return tests
def loadTestsFromModule(self, module):
#print '*** ipdoctest - lTM',module # dbg
if not self.matches(module.__name__):
log.debug("Doctest doesn't want module %s", module)
return
tests = self.finder.find(module,globs=self.globs,
extraglobs=self.extraglobs)
if not tests:
return
# always use whitespace and ellipsis options
optionflags = doctest.NORMALIZE_WHITESPACE | doctest.ELLIPSIS
tests.sort()
module_file = module.__file__
if module_file[-4:] in ('.pyc', '.pyo'):
module_file = module_file[:-1]
for test in tests:
if not test.examples:
continue
if not test.filename:
test.filename = module_file
yield DocTestCase(test,
optionflags=optionflags,
checker=self.checker)
def make_suite(): # pragma: no cover
from calmjs.parse.lexers import es5 as es5lexer
from calmjs.parse import walkers
from calmjs.parse import sourcemap
def open(p, flag='r'):
result = StringIO(examples[p] if flag == 'r' else '')
result.name = p
return result
parser = doctest.DocTestParser()
optflags = doctest.NORMALIZE_WHITESPACE | doctest.ELLIPSIS
dist = get_distribution('calmjs.parse')
if dist:
if dist.has_metadata('PKG-INFO'):
pkgdesc = dist.get_metadata('PKG-INFO').replace('\r', '')
elif dist.has_metadata('METADATA'):
pkgdesc = dist.get_metadata('METADATA').replace('\r', '')
else:
pkgdesc = ''
pkgdesc_tests = [
t for t in parser.parse(pkgdesc) if isinstance(t, doctest.Example)]
test_loader = unittest.TestLoader()
test_suite = test_loader.discover(
'calmjs.parse.tests', pattern='test_*.py',
top_level_dir=dirname(__file__)
)
test_suite.addTest(doctest.DocTestSuite(es5lexer, optionflags=optflags))
test_suite.addTest(doctest.DocTestSuite(walkers, optionflags=optflags))
test_suite.addTest(doctest.DocTestSuite(sourcemap, optionflags=optflags))
test_suite.addTest(doctest.DocTestCase(
# skipping all the error case tests which should all be in the
# troubleshooting section at the end; bump the index whenever
# more failure examples are added.
# also note that line number is unknown, as PKG_INFO has headers
# and also the counter is somehow inaccurate in this case.
doctest.DocTest(pkgdesc_tests[:-1], {
'open': open}, 'PKG_INFO', 'README.rst', None, pkgdesc),
optionflags=optflags,
))
return test_suite
def __init__(self):
"""
Uses :meth:`unittest.TestSuite.addTests` to add :obj:`doctest.DocFileSuite`
and :obj:`doctest.DocTestSuite` tests.
"""
readme_file_name = \
os.path.realpath(
os.path.join(os.path.dirname(__file__), "..", "README.rst")
)
examples_rst_file_name = \
os.path.realpath(
os.path.join(
os.path.dirname(__file__),
"..",
"docs",
"source",
"examples",
"index.rst"
)
)
suite = _unittest.TestSuite()
if os.path.exists(readme_file_name):
suite.addTests(
_doctest.DocFileSuite(
readme_file_name,
module_relative=False,
optionflags=_doctest.NORMALIZE_WHITESPACE
)
)
if os.path.exists(examples_rst_file_name):
suite.addTests(
_doctest.DocFileSuite(
examples_rst_file_name,
module_relative=False,
optionflags=_doctest.NORMALIZE_WHITESPACE
)
)
suite.addTests(
_doctest.DocTestSuite(
_array_split,
optionflags=_doctest.NORMALIZE_WHITESPACE
)
)
suite.addTests(
_doctest.DocTestSuite(
_split,
optionflags=_doctest.NORMALIZE_WHITESPACE
)
)
_unittest.TestSuite.__init__(self, suite)