Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 41a65ea

Browse files
committed
Doctest has new traceback gimmicks in 2.4. While trying to document
them (which they are now), I had to rewrite the code to understand it. This has got to be the most DWIM part of doctest -- but in context is really necessary.
1 parent f076953 commit 41a65ea

2 files changed

Lines changed: 106 additions & 34 deletions

File tree

Doc/lib/libdoctest.tex

Lines changed: 80 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,8 @@ \section{\module{doctest} ---
108108
ok
109109
Trying: [factorial(long(n)) for n in range(6)]
110110
Expecting: [1, 1, 2, 6, 24, 120]
111-
ok\end{verbatim}
111+
ok
112+
\end{verbatim}
112113

113114
And so on, eventually ending with:
114115

@@ -129,12 +130,14 @@ \section{\module{doctest} ---
129130
\end{verbatim}
130131

131132
That's all you need to know to start making productive use of
132-
\module{doctest}! Jump in.
133+
\module{doctest}! Jump in. The following sections provide full
134+
details. Note that there are many examples of doctests in
135+
the standard Python test suite and libraries.
133136

134137
\subsection{Simple Usage}
135138

136-
The simplest (not necessarily the best) way to start using doctest is to
137-
end each module \module{M} with:
139+
The simplest way to start using doctest (but not necessarily the way
140+
you'll continue to do it) is to end each module \module{M} with:
138141

139142
\begin{verbatim}
140143
def _test():
@@ -146,8 +149,7 @@ \subsection{Simple Usage}
146149
\end{verbatim}
147150

148151
\module{doctest} then examines docstrings in the module calling
149-
\function{testmod()}. If you want to test a different module, you can
150-
pass that module object to \function{testmod()}.
152+
\function{testmod()}.
151153

152154
Running the module as a script causes the examples in the docstrings
153155
to get executed and verified:
@@ -292,35 +294,95 @@ \subsection{Which Docstrings Are Examined?}
292294

293295
\subsection{What's the Execution Context?}
294296

295-
By default, each time \function{testmod()} finds a docstring to test, it uses
296-
a \emph{copy} of \module{M}'s globals, so that running tests on a module
297+
By default, each time \function{testmod()} finds a docstring to test, it
298+
uses a \emph{shallow copy} of \module{M}'s globals, so that running tests
297299
doesn't change the module's real globals, and so that one test in
298300
\module{M} can't leave behind crumbs that accidentally allow another test
299301
to work. This means examples can freely use any names defined at top-level
300302
in \module{M}, and names defined earlier in the docstring being run.
303+
Examples cannot see names defined in other docstrings.
301304

302305
You can force use of your own dict as the execution context by passing
303-
\code{globs=your_dict} to \function{testmod()} instead. Presumably this
304-
would be a copy of \code{M.__dict__} merged with the globals from other
305-
imported modules.
306+
\code{globs=your_dict} to \function{testmod()} instead.
306307

307308
\subsection{What About Exceptions?}
308309

309-
No problem, as long as the only output generated by the example is the
310-
traceback itself. For example:
310+
No problem: just paste in the expected traceback. Since
311+
tracebacks contain details that are likely to change
312+
rapidly (for example, exact file paths and line numbers), this is one
313+
case where doctest works hard to be flexible in what it accepts.
314+
This makes the full story involved, but you really don't have
315+
to remember much. Simple example:
311316

312317
\begin{verbatim}
313318
>>> [1, 2, 3].remove(42)
314319
Traceback (most recent call last):
315320
File "<stdin>", line 1, in ?
316321
ValueError: list.remove(x): x not in list
317-
>>>
318322
\end{verbatim}
319323

320-
Note that only the exception type and value are compared (specifically,
321-
only the last line in the traceback). The various ``File'' lines in
322-
between can be left out (unless they add significantly to the documentation
323-
value of the example).
324+
That doctest succeeds if, and only if, \exception{ValueError} is raised,
325+
with the \samp{list.remove(x): x not in list} detail as shown.
326+
327+
The expected output for an exception is divided into four parts.
328+
First, an example may produce some normal output before an exception
329+
is raised, although that's unusual. The "normal output" is taken to
330+
be everything until the first "Traceback" line, and is usually an
331+
empty string. Next, the traceback line must be one of these two, and
332+
indented the same as the first line in the example:
333+
334+
\begin{verbatim}
335+
Traceback (most recent call last):
336+
Traceback (innermost last):
337+
\end{verbatim}
338+
339+
The most interesting part is the last part: the line(s) starting with the
340+
exception type and detail. This is usually the last line of a traceback,
341+
but can extend across any number of lines. After the "Traceback" line,
342+
doctest simply ignores everything until the first line indented the same as
343+
the first line of the example, \emph{and} starting with an alphanumeric
344+
character. This example illustrates the complexities that are possible:
345+
346+
\begin{verbatim}
347+
>>> print 1, 2; raise ValueError('printed 1\nand 2\n but not 3')
348+
1 2
349+
Traceback (most recent call last):
350+
... indented the same, but doesn't start with an alphanumeric
351+
not indented the same, so ignored too
352+
File "/Python23/lib/doctest.py", line 442, in _run_examples_inner
353+
compileflags, 1) in globs
354+
File "<string>", line 1, in ? # and all these are ignored
355+
ValueError: printed 1
356+
and 2
357+
but not 3
358+
\end{verbatim}
359+
360+
The first (\samp{1 2}) and last three (starting with
361+
\exception{ValueError}) lines are compared, and the rest are ignored.
362+
363+
Best practice is to omit the ``File'' lines, unless they add
364+
significant documentation value to the example. So the example above
365+
is probably better as:
366+
367+
\begin{verbatim}
368+
>>> print 1, 2; raise ValueError('printed 1\nand 2\n but not 3')
369+
1 2
370+
Traceback (most recent call last):
371+
...
372+
ValueError: printed 1
373+
and 2
374+
but not 3
375+
\end{verbatim}
376+
377+
Note the tracebacks are treated very specially. In particular, in the
378+
rewritten example, the use of \samp{...} is independent of doctest's
379+
\constant{ELLIPSIS} option. The ellipsis in that example could
380+
be left out, or could just as well be three (or three hundred) commas.
381+
382+
\versionchanged[The abilities to check both normal output and an
383+
exception in a single example, and to have a multi-line
384+
exception detail, were added]{2.4}
385+
324386

325387
\subsection{Option Flags and Directive Names\label{doctest-options}}
326388

Lib/doctest.py

Lines changed: 26 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1191,16 +1191,27 @@ def _failure_header(self, test, example):
11911191
#/////////////////////////////////////////////////////////////////
11921192

11931193
# A regular expression for handling `want` strings that contain
1194-
# expected exceptions. It divides `want` into two pieces: the
1195-
# pre-exception output (`out`) and the exception message (`exc`),
1196-
# as generated by traceback.format_exception_only(). (I assume
1197-
# that the exception_only message is the first non-indented line
1198-
# starting with word characters after the "Traceback ...".)
1199-
_EXCEPTION_RE = re.compile(('^(?P<out>.*)'
1200-
'^(?P<hdr>Traceback \((?:%s|%s)\):)\s*$.*?'
1201-
'^(?P<exc>\w+.*)') %
1202-
('most recent call last', 'innermost last'),
1203-
re.MULTILINE | re.DOTALL)
1194+
# expected exceptions. It divides `want` into three pieces:
1195+
# - the pre-exception output (`want`)
1196+
# - the traceback header line (`hdr`)
1197+
# - the exception message (`msg`), as generated by
1198+
# traceback.format_exception_only()
1199+
# `msg` may have multiple lines. We assume/require that the
1200+
# exception message is the first non-indented line starting with a word
1201+
# character following the traceback header line.
1202+
_EXCEPTION_RE = re.compile(r"""
1203+
(?P<want> .*?) # suck up everything until traceback header
1204+
# Grab the traceback header. Different versions of Python have
1205+
# said different things on the first traceback line.
1206+
^(?P<hdr> Traceback\ \(
1207+
(?: most\ recent\ call\ last
1208+
| innermost\ last
1209+
) \) :
1210+
)
1211+
\s* $ # toss trailing whitespace on traceback header
1212+
.*? # don't blink: absorb stuff until a line *starts* with \w
1213+
^ (?P<msg> \w+ .*)
1214+
""", re.VERBOSE | re.MULTILINE | re.DOTALL)
12041215

12051216
def __run(self, test, compileflags, out):
12061217
"""
@@ -1274,20 +1285,19 @@ def __run(self, test, compileflags, out):
12741285
exc_info)
12751286
failures += 1
12761287
else:
1277-
exc_hdr = m.group('hdr')+'\n' # Exception header
1288+
e_want, e_msg = m.group('want', 'msg')
12781289
# The test passes iff the pre-exception output and
12791290
# the exception description match the values given
12801291
# in `want`.
1281-
if (self._checker.check_output(m.group('out'), got,
1292+
if (self._checker.check_output(e_want, got,
12821293
self.optionflags) and
1283-
self._checker.check_output(m.group('exc'), exc_msg,
1294+
self._checker.check_output(e_msg, exc_msg,
12841295
self.optionflags)):
1285-
# Is +exc_msg the right thing here??
12861296
self.report_success(out, test, example,
1287-
got+_exception_traceback(exc_info))
1297+
got + _exception_traceback(exc_info))
12881298
else:
12891299
self.report_failure(out, test, example,
1290-
got+_exception_traceback(exc_info))
1300+
got + _exception_traceback(exc_info))
12911301
failures += 1
12921302

12931303
# Restore the option flags (in case they were modified)

0 commit comments

Comments
 (0)