Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def _test_status(docstr):
docstr = utils.codeblock(docstr)
try:
temp = utils.util_misc.TempDoctest(docstr=docstr)
except Exception:
# pytest seems to load an older version of xdoctest for some reason
import xdoctest
import inspect
print('xdoctest.__version__ = {!r}'.format(xdoctest.__version__))
print('utils = {!r}'.format(utils))
print('utils.util_misc = {!r}'.format(utils.util_misc))
print('utils.TempDoctest = {!r}'.format(utils.TempDoctest))
print(inspect.getargspec(utils.TempDoctest))
raise
doctests = list(core.parse_doctestables(temp.modpath))
status = doctests[0].run(verbose=0, on_error='return')
return status
def _test_status(docstr):
docstr = utils.codeblock(docstr)
try:
temp = utils.util_misc.TempDoctest(docstr=docstr)
except Exception:
# pytest seems to load an older version of xdoctest for some reason
import xdoctest
import inspect
print('xdoctest.__version__ = {!r}'.format(xdoctest.__version__))
print('utils = {!r}'.format(utils))
print('utils.util_misc = {!r}'.format(utils.util_misc))
print('utils.TempDoctest = {!r}'.format(utils.TempDoctest))
print(inspect.getargspec(utils.TempDoctest))
raise
doctests = list(core.parse_doctestables(temp.modpath))
status = doctests[0].run(verbose=0, on_error='return')
return status
def extract_exc_want(want):
want_ = utils.codeblock(want)
m = _EXCEPTION_RE.search(want_)
exc_want = m.group('msg') if m else None
return exc_want
def _convert_to_test_module(enabled_examples):
"""
Converts all doctests to unit tests that can exist in a standalone module
"""
module_lines = []
for example in enabled_examples:
# Create a unit-testable function for this example
func_name = 'test_' + example.callname.replace('.', '_')
body_lines = []
for part in example._parts:
body_part = part.format_src(linenos=False, want=False,
prefix=False, colored=False,
partnos=False)
if part.want:
want_text = '# doctest want:\n'
want_text += utils.indent(part.want, '# ')
body_part += '\n' + want_text
body_lines.append(body_part)
body = '\n'.join(body_lines)
func_text = 'def {}():\n'.format(func_name) + utils.indent(body)
module_lines.append(func_text)
module_text = '\n\n\n'.join(module_lines)
return module_text
>>> got = "(0, 2, {'weight': 1})\n(0, 3, {'weight': 2})"
"""
if runstate is None:
runstate = directive.RuntimeState()
def remove_prefixes(regex, text):
return re.sub(regex, r'\1\2', text)
def visible_text(lines):
# TODO: backspaces
# Any lines that end with only a carrage return are erased
return [line for line in lines if not line.endswith('\r')]
# Remove terminal colors
if True:
got = utils.strip_ansi(got)
want = utils.strip_ansi(want)
if True:
# normalize python 2/3 byte/unicode prefixes
got = remove_prefixes(unicode_literal_re, got)
want = remove_prefixes(unicode_literal_re, want)
# Note: normalizing away prefixes can cause weird "got"
# results to print when there is a got-want mismatch.
# For instance, if you get {'b': 22} but you want {'b': 2}
# this will cause xdoctest to report that you wanted {'': 2}
# because it reports the normalized version of the want message
got = remove_prefixes(bytes_literal_re, got)
want = remove_prefixes(bytes_literal_re, want)
# Replace s if it is being used.
diff = list(diff)[2:] # strip the diff header
kind = 'context diff with expected followed by actual'
elif runstate['REPORT_NDIFF']:
# TODO: Is there a way to make Differ ignore whitespace if that
# runtime directive is specified?
engine = difflib.Differ(charjunk=difflib.IS_CHARACTER_JUNK)
diff = list(engine.compare(want_lines, got_lines))
kind = 'ndiff with -expected +actual'
else:
raise ValueError('Invalid difflib option')
# Remove trailing whitespace on diff output.
diff = [line.rstrip() + '\n' for line in diff]
diff_text = ''.join(diff)
if colored:
diff_text = utils.highlight_code(diff_text, lexer_name='diff')
text = 'Differences (%s):\n' % kind + utils.indent(diff_text)
else:
# If we're not using diff, then simply list the expected
# output followed by the actual output.
if want and got:
if colored:
got = utils.color_text(got, 'red')
want = utils.color_text(want, 'red')
text = 'Expected:\n{}\nGot:\n{}'.format(
utils.indent(self.want), utils.indent(self.got))
elif want:
if colored:
got = utils.color_text(got, 'red')
want = utils.color_text(want, 'red')
text = 'Expected:\n{}\nGot nothing\n'.format(utils.indent(want))
Example:
>>> from xdoctest import dynamic_analysis
>>> module = dynamic_analysis
>>> calldefs = parse_dynamic_calldefs(module.__file__)
>>> for key, calldef in sorted(calldefs.items()):
... print('key = {!r}'.format(key))
... print(' * calldef.callname = {}'.format(calldef.callname))
... if calldef.docstr is None:
... print(' * len(calldef.docstr) = {}'.format(calldef.docstr))
... else:
... print(' * len(calldef.docstr) = {}'.format(len(calldef.docstr)))
"""
from xdoctest import static_analysis as static
from xdoctest import utils # NOQA
# Possible option for dynamic parsing
module = utils.import_module_from_path(modpath)
calldefs = {}
if getattr(module, '__doc__'):
calldefs['__doc__'] = static.CallDefNode(
callname='__doc__',
docstr=module.__doc__,
lineno=0,
doclineno=1,
doclineno_end=1,
args=None
)
for key, val in iter_module_doctestables(module):
# if hasattr(val, '__doc__'):
if hasattr(val, '__doc__') and hasattr(val, '__name__'):
calldefs[key] = static.CallDefNode(
(p1) 1 >>> print(123)
123
Example:
>>> from xdoctest.parser import *
>>> self = DoctestPart(exec_lines=['print(123)'],
>>> want_lines=['123'], line_offset=0, partno=1)
>>> # xdoctest: -NORMALIZE_WHITESPACE
>>> print(self.format_part(partnos=False, prefix=False,
>>> linenos=False, want=False))
print(123)
"""
if prefix:
# Show the original line prefix when possible
if self.orig_lines is None:
src_text = utils.indent(self.source, '>>> ')
else:
src_text = '\n'.join(self.orig_lines)
else:
src_text = self.source
want_text = self.want if self.want else ''
if n_digits is None:
endline = startline + self.n_lines
n_digits = math.log(max(1, endline), 10)
n_digits = int(math.ceil(n_digits))
part_lines = src_text.splitlines()
n_spaces = 0
if linenos: