Skip to content

Commit 2f993af

Browse files
committed
Fix context output handling for doctests
Show full context of doctest source in the pytest output, if the lineno of failed example in the docstring is < 9.
1 parent 111d640 commit 2f993af

File tree

3 files changed

+30
-3
lines changed

3 files changed

+30
-3
lines changed

_pytest/doctest.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,7 @@ def repr_failure(self, excinfo):
120120
lines = ["%03d %s" % (i + test.lineno + 1, x)
121121
for (i, x) in enumerate(lines)]
122122
# trim docstring error lines to 10
123-
lines = lines[example.lineno - 9:example.lineno + 1]
123+
lines = lines[max(example.lineno - 9, 0):example.lineno + 1]
124124
else:
125125
lines = ['EXAMPLE LOCATION UNKNOWN, not showing all tests of that example']
126126
indent = '>>>'

changelog/2882.bugfix

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Show full context of doctest source in the pytest output, if the lineno of failed example in the docstring is < 9.

testing/test_doctest.py

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -173,7 +173,7 @@ def test_doctest_unexpected_exception(self, testdir):
173173
"*UNEXPECTED*ZeroDivision*",
174174
])
175175

176-
def test_docstring_context_around_error(self, testdir):
176+
def test_docstring_partial_context_around_error(self, testdir):
177177
"""Test that we show some context before the actual line of a failing
178178
doctest.
179179
"""
@@ -199,7 +199,7 @@ def foo():
199199
''')
200200
result = testdir.runpytest('--doctest-modules')
201201
result.stdout.fnmatch_lines([
202-
'*docstring_context_around_error*',
202+
'*docstring_partial_context_around_error*',
203203
'005*text-line-3',
204204
'006*text-line-4',
205205
'013*text-line-11',
@@ -213,6 +213,32 @@ def foo():
213213
assert 'text-line-2' not in result.stdout.str()
214214
assert 'text-line-after' not in result.stdout.str()
215215

216+
def test_docstring_full_context_around_error(self, testdir):
217+
"""Test that we show the whole context before the actual line of a failing
218+
doctest, provided that the context is up to 10 lines long.
219+
"""
220+
testdir.makepyfile('''
221+
def foo():
222+
"""
223+
text-line-1
224+
text-line-2
225+
226+
>>> 1 + 1
227+
3
228+
"""
229+
''')
230+
result = testdir.runpytest('--doctest-modules')
231+
result.stdout.fnmatch_lines([
232+
'*docstring_full_context_around_error*',
233+
'003*text-line-1',
234+
'004*text-line-2',
235+
'006*>>> 1 + 1',
236+
'Expected:',
237+
' 3',
238+
'Got:',
239+
' 2',
240+
])
241+
216242
def test_doctest_linedata_missing(self, testdir):
217243
testdir.tmpdir.join('hello.py').write(_pytest._code.Source("""
218244
class Fun(object):

0 commit comments

Comments
 (0)