Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 29 additions & 12 deletions Lib/doctest.py
Original file line number Diff line number Diff line change
Expand Up @@ -578,18 +578,23 @@ class DocTestParser:
# (including leading indentation and prompts); `indent` is the
# indentation of the first (PS1) line of the source code; and
# `want` is the expected output (including leading indentation).
_EXAMPLE_RE = re.compile(r'''
_EXAMPLE_RE_TPL = r'''
# Source consists of a PS1 line followed by zero or more PS2 lines.
(?P<source>
(?:^(?P<indent> [ ]*) >>> .*) # PS1 line
(?:\n [ ]* \.\.\. .*)*) # PS2 lines
(?:^(?P<indent> [ ]*) (?P<ps1> %s) .*) # PS1 line
(?:\n [ ]* (?P<ps2> %s) .*)*) # PS2 lines
\n?
# Want consists of any non-blank lines that do not start with PS1.
(?P<want> (?:(?![ ]*$) # Not a blank line
(?![ ]*>>>) # Not a line starting with PS1
.+$\n? # But any other line
(?![ ]*%s) # Not a line starting with PS1
.*$\n? # But any other line
)*)
''', re.MULTILINE | re.VERBOSE)
'''

def __init__(self, ps1=r'>>>', ps2=r'\.\.\.', pout=''):
self.pout = pout
self._EXAMPLE_RE = re.compile(self._EXAMPLE_RE_TPL % (ps1, ps2, ps1),
re.MULTILINE | re.VERBOSE)

# A regular expression for handling `want` strings that contain
# expected exceptions. It divides `want` into three pieces:
Expand Down Expand Up @@ -696,12 +701,18 @@ def _parse_example(self, m, name, lineno):
# Get the example's indentation level.
indent = len(m.group('indent'))

# We're using variable-length input prompts
ps1, ps2 = m.group('ps1'), m.group('ps2')
ps1_len = len(ps1)

# Divide source into lines; check that they're properly
# indented; and then strip their indentation & prompts.
source_lines = m.group('source').split('\n')
self._check_prompt_blank(source_lines, indent, name, lineno)
self._check_prefix(source_lines[1:], ' '*indent + '.', name, lineno)
source = '\n'.join([sl[indent+4:] for sl in source_lines])

self._check_prompt_blank(source_lines, indent, name, lineno, ps1_len)
if ps2:
self._check_prefix(source_lines[1:], ' '*indent + ps2, name, lineno)
source = '\n'.join([sl[indent + ps1_len + 1:] for sl in source_lines])

# Divide want into lines; check that it's properly indented; and
# then strip the indentation. Spaces before the last newline should
Expand All @@ -712,6 +723,10 @@ def _parse_example(self, m, name, lineno):
del want_lines[-1] # forget final newline & spaces after it
self._check_prefix(want_lines, ' '*indent, name,
lineno + len(source_lines))

# Remove ipython output prompt that might be present in the first line
want_lines[0] = re.sub(self.pout, '', want_lines[0])

want = '\n'.join([wl[indent:] for wl in want_lines])

# If `want` contains a traceback message, then extract it.
Expand Down Expand Up @@ -774,19 +789,21 @@ def _min_indent(self, s):
else:
return 0

def _check_prompt_blank(self, lines, indent, name, lineno):
def _check_prompt_blank(self, lines, indent, name, lineno, ps1_len):
"""
Given the lines of a source string (including prompts and
leading indentation), check to make sure that every prompt is
followed by a space character. If any line is not followed by
a space character, then raise ValueError.
"""
space_idx = indent + ps1_len
min_len = space_idx + 1
for i, line in enumerate(lines):
if len(line) >= indent+4 and line[indent+3] != ' ':
if len(line) >= min_len and line[space_idx] != ' ':
raise ValueError('line %r of the docstring for %s '
'lacks blank after %s: %r' %
(lineno+i+1, name,
line[indent:indent+3], line))
line[indent:space_idx], line))

def _check_prefix(self, lines, prefix, name, lineno):
"""
Expand Down
37 changes: 37 additions & 0 deletions Lib/test/test_doctest.py
Original file line number Diff line number Diff line change
Expand Up @@ -734,6 +734,43 @@ def test_DocTestParser(): r"""
Example: ('x+y\n', '5\n', 9)
Text: ''

`ps1` and `ps2` arguments override primary and secondary prompts, `pout`
argument change default output prefix. For example, to parse IPython-like
input and output:

>>> s2 = '''
... In [1]: 1
... Out[1]: 1
...
... In [2]: a = 42 # no output expected
...
... In [3]: for i in range(3):
... ...: print(i)
... ...:
... 0
... 1
... 2
...
... In [4]: print(4)
... 4
... '''
>>> parser2 = doctest.DocTestParser(ps1=r'In\ \[\d+\]:', ps2=r'\ \ \ \.\.\.+:',
... pout=r'Out\[\d+\]: \s*?\n?')
>>> for piece in parser2.parse(s2):
... if isinstance(piece, doctest.Example):
... print('Example:', (piece.source, piece.want, piece.lineno))
... else:
... print(' Text:', repr(piece))
Text: '\n'
Example: ('1\n', '1\n', 1)
Text: '\n'
Example: ('a = 42 # no output expected\n', '', 4)
Text: '\n'
Example: ('for i in range(3):\n print(i)\n', '0\n1\n2\n', 6)
Text: '\n'
Example: ('print(4)\n', '4\n', 13)
Text: ''

The `get_examples` method returns just the examples:

>>> for piece in parser.get_examples(s):
Expand Down