blob: 3e36f1906f32841dddb7cbdec3ddcc66a86b8d51 [file] [log] [blame]
Tim Peters8485b562004-08-04 18:46:34 +00001"""
2Test script for doctest.
3"""
4
Benjamin Petersonee8712c2008-05-20 21:35:26 +00005from test import support
Tim Peters8485b562004-08-04 18:46:34 +00006import doctest
Victor Stinner9d396392010-10-16 21:54:59 +00007import os
Brett Cannon31f59292011-02-21 19:29:56 +00008import sys
Tim Peters8485b562004-08-04 18:46:34 +00009
Florent Xiclunadc6f2d02010-04-02 19:25:32 +000010
Nick Coghlanf088e5e2008-12-14 11:50:48 +000011# NOTE: There are some additional tests relating to interaction with
12# zipimport in the test_zipimport_support test module.
13
Tim Peters8485b562004-08-04 18:46:34 +000014######################################################################
15## Sample Objects (used by test cases)
16######################################################################
17
18def sample_func(v):
19 """
Tim Peters19397e52004-08-06 22:02:59 +000020 Blah blah
21
Guido van Rossum7131f842007-02-09 20:13:25 +000022 >>> print(sample_func(22))
Tim Peters8485b562004-08-04 18:46:34 +000023 44
Tim Peters19397e52004-08-06 22:02:59 +000024
25 Yee ha!
Tim Peters8485b562004-08-04 18:46:34 +000026 """
27 return v+v
28
29class SampleClass:
30 """
Guido van Rossum7131f842007-02-09 20:13:25 +000031 >>> print(1)
Tim Peters8485b562004-08-04 18:46:34 +000032 1
Edward Loper4ae900f2004-09-21 03:20:34 +000033
34 >>> # comments get ignored. so are empty PS1 and PS2 prompts:
35 >>>
36 ...
37
38 Multiline example:
39 >>> sc = SampleClass(3)
40 >>> for i in range(10):
41 ... sc = sc.double()
Guido van Rossum805365e2007-05-07 22:24:25 +000042 ... print(' ', sc.get(), sep='', end='')
43 6 12 24 48 96 192 384 768 1536 3072
Tim Peters8485b562004-08-04 18:46:34 +000044 """
45 def __init__(self, val):
46 """
Guido van Rossum7131f842007-02-09 20:13:25 +000047 >>> print(SampleClass(12).get())
Tim Peters8485b562004-08-04 18:46:34 +000048 12
49 """
50 self.val = val
51
52 def double(self):
53 """
Guido van Rossum7131f842007-02-09 20:13:25 +000054 >>> print(SampleClass(12).double().get())
Tim Peters8485b562004-08-04 18:46:34 +000055 24
56 """
57 return SampleClass(self.val + self.val)
58
59 def get(self):
60 """
Guido van Rossum7131f842007-02-09 20:13:25 +000061 >>> print(SampleClass(-5).get())
Tim Peters8485b562004-08-04 18:46:34 +000062 -5
63 """
64 return self.val
65
66 def a_staticmethod(v):
67 """
Guido van Rossum7131f842007-02-09 20:13:25 +000068 >>> print(SampleClass.a_staticmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +000069 11
70 """
71 return v+1
72 a_staticmethod = staticmethod(a_staticmethod)
73
74 def a_classmethod(cls, v):
75 """
Guido van Rossum7131f842007-02-09 20:13:25 +000076 >>> print(SampleClass.a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +000077 12
Guido van Rossum7131f842007-02-09 20:13:25 +000078 >>> print(SampleClass(0).a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +000079 12
80 """
81 return v+2
82 a_classmethod = classmethod(a_classmethod)
83
84 a_property = property(get, doc="""
Guido van Rossum7131f842007-02-09 20:13:25 +000085 >>> print(SampleClass(22).a_property)
Tim Peters8485b562004-08-04 18:46:34 +000086 22
87 """)
88
89 class NestedClass:
90 """
91 >>> x = SampleClass.NestedClass(5)
92 >>> y = x.square()
Guido van Rossum7131f842007-02-09 20:13:25 +000093 >>> print(y.get())
Tim Peters8485b562004-08-04 18:46:34 +000094 25
95 """
96 def __init__(self, val=0):
97 """
Guido van Rossum7131f842007-02-09 20:13:25 +000098 >>> print(SampleClass.NestedClass().get())
Tim Peters8485b562004-08-04 18:46:34 +000099 0
100 """
101 self.val = val
102 def square(self):
103 return SampleClass.NestedClass(self.val*self.val)
104 def get(self):
105 return self.val
106
107class SampleNewStyleClass(object):
108 r"""
Guido van Rossum7131f842007-02-09 20:13:25 +0000109 >>> print('1\n2\n3')
Tim Peters8485b562004-08-04 18:46:34 +0000110 1
111 2
112 3
113 """
114 def __init__(self, val):
115 """
Guido van Rossum7131f842007-02-09 20:13:25 +0000116 >>> print(SampleNewStyleClass(12).get())
Tim Peters8485b562004-08-04 18:46:34 +0000117 12
118 """
119 self.val = val
120
121 def double(self):
122 """
Guido van Rossum7131f842007-02-09 20:13:25 +0000123 >>> print(SampleNewStyleClass(12).double().get())
Tim Peters8485b562004-08-04 18:46:34 +0000124 24
125 """
126 return SampleNewStyleClass(self.val + self.val)
127
128 def get(self):
129 """
Guido van Rossum7131f842007-02-09 20:13:25 +0000130 >>> print(SampleNewStyleClass(-5).get())
Tim Peters8485b562004-08-04 18:46:34 +0000131 -5
132 """
133 return self.val
134
135######################################################################
Edward Loper2de91ba2004-08-27 02:07:46 +0000136## Fake stdin (for testing interactive debugging)
137######################################################################
138
139class _FakeInput:
140 """
141 A fake input stream for pdb's interactive debugger. Whenever a
142 line is read, print it (to simulate the user typing it), and then
143 return it. The set of lines to return is specified in the
144 constructor; they should not have trailing newlines.
145 """
146 def __init__(self, lines):
147 self.lines = lines
148
149 def readline(self):
150 line = self.lines.pop(0)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000151 print(line)
Edward Loper2de91ba2004-08-27 02:07:46 +0000152 return line+'\n'
153
154######################################################################
Tim Peters8485b562004-08-04 18:46:34 +0000155## Test Cases
156######################################################################
157
158def test_Example(): r"""
159Unit tests for the `Example` class.
160
Edward Lopera6b68322004-08-26 00:05:43 +0000161Example is a simple container class that holds:
162 - `source`: A source string.
163 - `want`: An expected output string.
164 - `exc_msg`: An expected exception message string (or None if no
165 exception is expected).
166 - `lineno`: A line number (within the docstring).
167 - `indent`: The example's indentation in the input string.
168 - `options`: An option dictionary, mapping option flags to True or
169 False.
Tim Peters8485b562004-08-04 18:46:34 +0000170
Edward Lopera6b68322004-08-26 00:05:43 +0000171These attributes are set by the constructor. `source` and `want` are
172required; the other attributes all have default values:
Tim Peters8485b562004-08-04 18:46:34 +0000173
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000174 >>> example = doctest.Example('print(1)', '1\n')
Edward Lopera6b68322004-08-26 00:05:43 +0000175 >>> (example.source, example.want, example.exc_msg,
176 ... example.lineno, example.indent, example.options)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000177 ('print(1)\n', '1\n', None, 0, 0, {})
Edward Lopera6b68322004-08-26 00:05:43 +0000178
179The first three attributes (`source`, `want`, and `exc_msg`) may be
180specified positionally; the remaining arguments should be specified as
181keyword arguments:
182
183 >>> exc_msg = 'IndexError: pop from an empty list'
184 >>> example = doctest.Example('[].pop()', '', exc_msg,
185 ... lineno=5, indent=4,
186 ... options={doctest.ELLIPSIS: True})
187 >>> (example.source, example.want, example.exc_msg,
188 ... example.lineno, example.indent, example.options)
189 ('[].pop()\n', '', 'IndexError: pop from an empty list\n', 5, 4, {8: True})
190
191The constructor normalizes the `source` string to end in a newline:
Tim Peters8485b562004-08-04 18:46:34 +0000192
Tim Petersbb431472004-08-09 03:51:46 +0000193 Source spans a single line: no terminating newline.
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000194 >>> e = doctest.Example('print(1)', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000195 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000196 ('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000197
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000198 >>> e = doctest.Example('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000199 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000200 ('print(1)\n', '1\n')
Tim Peters8485b562004-08-04 18:46:34 +0000201
Tim Petersbb431472004-08-09 03:51:46 +0000202 Source spans multiple lines: require terminating newline.
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000203 >>> e = doctest.Example('print(1);\nprint(2)\n', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000204 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000205 ('print(1);\nprint(2)\n', '1\n2\n')
Tim Peters8485b562004-08-04 18:46:34 +0000206
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000207 >>> e = doctest.Example('print(1);\nprint(2)', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000208 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000209 ('print(1);\nprint(2)\n', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000210
Edward Lopera6b68322004-08-26 00:05:43 +0000211 Empty source string (which should never appear in real examples)
212 >>> e = doctest.Example('', '')
213 >>> e.source, e.want
214 ('\n', '')
Tim Peters8485b562004-08-04 18:46:34 +0000215
Edward Lopera6b68322004-08-26 00:05:43 +0000216The constructor normalizes the `want` string to end in a newline,
217unless it's the empty string:
218
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000219 >>> e = doctest.Example('print(1)', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000220 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000221 ('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000222
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000223 >>> e = doctest.Example('print(1)', '1')
Tim Petersbb431472004-08-09 03:51:46 +0000224 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000225 ('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000226
Edward Lopera6b68322004-08-26 00:05:43 +0000227 >>> e = doctest.Example('print', '')
Tim Petersbb431472004-08-09 03:51:46 +0000228 >>> e.source, e.want
229 ('print\n', '')
Edward Lopera6b68322004-08-26 00:05:43 +0000230
231The constructor normalizes the `exc_msg` string to end in a newline,
232unless it's `None`:
233
234 Message spans one line
235 >>> exc_msg = 'IndexError: pop from an empty list'
236 >>> e = doctest.Example('[].pop()', '', exc_msg)
237 >>> e.exc_msg
238 'IndexError: pop from an empty list\n'
239
240 >>> exc_msg = 'IndexError: pop from an empty list\n'
241 >>> e = doctest.Example('[].pop()', '', exc_msg)
242 >>> e.exc_msg
243 'IndexError: pop from an empty list\n'
244
245 Message spans multiple lines
246 >>> exc_msg = 'ValueError: 1\n 2'
247 >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
248 >>> e.exc_msg
249 'ValueError: 1\n 2\n'
250
251 >>> exc_msg = 'ValueError: 1\n 2\n'
252 >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
253 >>> e.exc_msg
254 'ValueError: 1\n 2\n'
255
256 Empty (but non-None) exception message (which should never appear
257 in real examples)
258 >>> exc_msg = ''
259 >>> e = doctest.Example('raise X()', '', exc_msg)
260 >>> e.exc_msg
261 '\n'
Antoine Pitrou165b1282011-12-18 20:20:17 +0100262
263Compare `Example`:
264 >>> example = doctest.Example('print 1', '1\n')
265 >>> same_example = doctest.Example('print 1', '1\n')
266 >>> other_example = doctest.Example('print 42', '42\n')
267 >>> example == same_example
268 True
269 >>> example != same_example
270 False
271 >>> hash(example) == hash(same_example)
272 True
273 >>> example == other_example
274 False
275 >>> example != other_example
276 True
Tim Peters8485b562004-08-04 18:46:34 +0000277"""
278
279def test_DocTest(): r"""
280Unit tests for the `DocTest` class.
281
282DocTest is a collection of examples, extracted from a docstring, along
283with information about where the docstring comes from (a name,
284filename, and line number). The docstring is parsed by the `DocTest`
285constructor:
286
287 >>> docstring = '''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000288 ... >>> print(12)
Tim Peters8485b562004-08-04 18:46:34 +0000289 ... 12
290 ...
291 ... Non-example text.
292 ...
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000293 ... >>> print('another\example')
Tim Peters8485b562004-08-04 18:46:34 +0000294 ... another
295 ... example
296 ... '''
297 >>> globs = {} # globals to run the test in.
Edward Lopera1ef6112004-08-09 16:14:41 +0000298 >>> parser = doctest.DocTestParser()
299 >>> test = parser.get_doctest(docstring, globs, 'some_test',
300 ... 'some_file', 20)
Guido van Rossum7131f842007-02-09 20:13:25 +0000301 >>> print(test)
Tim Peters8485b562004-08-04 18:46:34 +0000302 <DocTest some_test from some_file:20 (2 examples)>
303 >>> len(test.examples)
304 2
305 >>> e1, e2 = test.examples
306 >>> (e1.source, e1.want, e1.lineno)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000307 ('print(12)\n', '12\n', 1)
Tim Peters8485b562004-08-04 18:46:34 +0000308 >>> (e2.source, e2.want, e2.lineno)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000309 ("print('another\\example')\n", 'another\nexample\n', 6)
Tim Peters8485b562004-08-04 18:46:34 +0000310
311Source information (name, filename, and line number) is available as
312attributes on the doctest object:
313
314 >>> (test.name, test.filename, test.lineno)
315 ('some_test', 'some_file', 20)
316
317The line number of an example within its containing file is found by
318adding the line number of the example and the line number of its
319containing test:
320
321 >>> test.lineno + e1.lineno
322 21
323 >>> test.lineno + e2.lineno
324 26
325
326If the docstring contains inconsistant leading whitespace in the
327expected output of an example, then `DocTest` will raise a ValueError:
328
329 >>> docstring = r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000330 ... >>> print('bad\nindentation')
Tim Peters8485b562004-08-04 18:46:34 +0000331 ... bad
332 ... indentation
333 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000334 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000335 Traceback (most recent call last):
Edward Loper00f8da72004-08-26 18:05:07 +0000336 ValueError: line 4 of the docstring for some_test has inconsistent leading whitespace: 'indentation'
Tim Peters8485b562004-08-04 18:46:34 +0000337
338If the docstring contains inconsistent leading whitespace on
339continuation lines, then `DocTest` will raise a ValueError:
340
341 >>> docstring = r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000342 ... >>> print(('bad indentation',
343 ... ... 2))
Tim Peters8485b562004-08-04 18:46:34 +0000344 ... ('bad', 'indentation')
345 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000346 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000347 Traceback (most recent call last):
Guido van Rossume0192e52007-02-09 23:39:59 +0000348 ValueError: line 2 of the docstring for some_test has inconsistent leading whitespace: '... 2))'
Tim Peters8485b562004-08-04 18:46:34 +0000349
350If there's no blank space after a PS1 prompt ('>>>'), then `DocTest`
351will raise a ValueError:
352
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000353 >>> docstring = '>>>print(1)\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000354 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000355 Traceback (most recent call last):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000356 ValueError: line 1 of the docstring for some_test lacks blank after >>>: '>>>print(1)'
Edward Loper7c748462004-08-09 02:06:06 +0000357
358If there's no blank space after a PS2 prompt ('...'), then `DocTest`
359will raise a ValueError:
360
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000361 >>> docstring = '>>> if 1:\n...print(1)\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000362 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Edward Loper7c748462004-08-09 02:06:06 +0000363 Traceback (most recent call last):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000364 ValueError: line 2 of the docstring for some_test lacks blank after ...: '...print(1)'
Edward Loper7c748462004-08-09 02:06:06 +0000365
Antoine Pitrou2bc801c2011-12-18 19:27:45 +0100366Compare `DocTest`:
367
368 >>> docstring = '''
369 ... >>> print 12
370 ... 12
371 ... '''
372 >>> test = parser.get_doctest(docstring, globs, 'some_test',
373 ... 'some_test', 20)
374 >>> same_test = parser.get_doctest(docstring, globs, 'some_test',
375 ... 'some_test', 20)
376 >>> test == same_test
377 True
378 >>> test != same_test
379 False
Antoine Pitrou165b1282011-12-18 20:20:17 +0100380 >>> hash(test) == hash(same_test)
381 True
Antoine Pitrou2bc801c2011-12-18 19:27:45 +0100382 >>> docstring = '''
383 ... >>> print 42
384 ... 42
385 ... '''
386 >>> other_test = parser.get_doctest(docstring, globs, 'other_test',
387 ... 'other_file', 10)
388 >>> test == other_test
389 False
390 >>> test != other_test
391 True
392
393Compare `DocTestCase`:
394
395 >>> DocTestCase = doctest.DocTestCase
396 >>> test_case = DocTestCase(test)
397 >>> same_test_case = DocTestCase(same_test)
398 >>> other_test_case = DocTestCase(other_test)
399 >>> test_case == same_test_case
400 True
401 >>> test_case != same_test_case
402 False
Antoine Pitrou165b1282011-12-18 20:20:17 +0100403 >>> hash(test_case) == hash(same_test_case)
404 True
Antoine Pitrou2bc801c2011-12-18 19:27:45 +0100405 >>> test == other_test_case
406 False
407 >>> test != other_test_case
408 True
409
Tim Peters8485b562004-08-04 18:46:34 +0000410"""
411
Tim Peters8485b562004-08-04 18:46:34 +0000412def test_DocTestFinder(): r"""
413Unit tests for the `DocTestFinder` class.
414
415DocTestFinder is used to extract DocTests from an object's docstring
416and the docstrings of its contained objects. It can be used with
417modules, functions, classes, methods, staticmethods, classmethods, and
418properties.
419
420Finding Tests in Functions
421~~~~~~~~~~~~~~~~~~~~~~~~~~
422For a function whose docstring contains examples, DocTestFinder.find()
423will return a single test (for that function's docstring):
424
Tim Peters8485b562004-08-04 18:46:34 +0000425 >>> finder = doctest.DocTestFinder()
Jim Fulton07a349c2004-08-22 14:10:00 +0000426
427We'll simulate a __file__ attr that ends in pyc:
428
429 >>> import test.test_doctest
430 >>> old = test.test_doctest.__file__
431 >>> test.test_doctest.__file__ = 'test_doctest.pyc'
432
Tim Peters8485b562004-08-04 18:46:34 +0000433 >>> tests = finder.find(sample_func)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000434
Guido van Rossum7131f842007-02-09 20:13:25 +0000435 >>> print(tests) # doctest: +ELLIPSIS
Brett Cannon31f59292011-02-21 19:29:56 +0000436 [<DocTest sample_func from ...:18 (1 example)>]
Edward Loper8e4a34b2004-08-12 02:34:27 +0000437
Tim Peters4de7c5c2004-08-23 22:38:05 +0000438The exact name depends on how test_doctest was invoked, so allow for
439leading path components.
440
441 >>> tests[0].filename # doctest: +ELLIPSIS
442 '...test_doctest.py'
Jim Fulton07a349c2004-08-22 14:10:00 +0000443
444 >>> test.test_doctest.__file__ = old
Tim Petersc6cbab02004-08-22 19:43:28 +0000445
Jim Fulton07a349c2004-08-22 14:10:00 +0000446
Tim Peters8485b562004-08-04 18:46:34 +0000447 >>> e = tests[0].examples[0]
Tim Petersbb431472004-08-09 03:51:46 +0000448 >>> (e.source, e.want, e.lineno)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000449 ('print(sample_func(22))\n', '44\n', 3)
Tim Peters8485b562004-08-04 18:46:34 +0000450
Edward Loper32ddbf72004-09-13 05:47:24 +0000451By default, tests are created for objects with no docstring:
Tim Peters8485b562004-08-04 18:46:34 +0000452
453 >>> def no_docstring(v):
454 ... pass
Tim Peters958cc892004-09-13 14:53:28 +0000455 >>> finder.find(no_docstring)
456 []
Edward Loper32ddbf72004-09-13 05:47:24 +0000457
458However, the optional argument `exclude_empty` to the DocTestFinder
459constructor can be used to exclude tests for objects with empty
460docstrings:
461
462 >>> def no_docstring(v):
463 ... pass
464 >>> excl_empty_finder = doctest.DocTestFinder(exclude_empty=True)
465 >>> excl_empty_finder.find(no_docstring)
Tim Peters8485b562004-08-04 18:46:34 +0000466 []
467
468If the function has a docstring with no examples, then a test with no
469examples is returned. (This lets `DocTestRunner` collect statistics
470about which functions have no tests -- but is that useful? And should
471an empty test also be created when there's no docstring?)
472
473 >>> def no_examples(v):
474 ... ''' no doctest examples '''
Tim Peters17b56372004-09-11 17:33:27 +0000475 >>> finder.find(no_examples) # doctest: +ELLIPSIS
476 [<DocTest no_examples from ...:1 (no examples)>]
Tim Peters8485b562004-08-04 18:46:34 +0000477
478Finding Tests in Classes
479~~~~~~~~~~~~~~~~~~~~~~~~
480For a class, DocTestFinder will create a test for the class's
481docstring, and will recursively explore its contents, including
482methods, classmethods, staticmethods, properties, and nested classes.
483
484 >>> finder = doctest.DocTestFinder()
485 >>> tests = finder.find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000486 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000487 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000488 3 SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000489 3 SampleClass.NestedClass
490 1 SampleClass.NestedClass.__init__
491 1 SampleClass.__init__
492 2 SampleClass.a_classmethod
493 1 SampleClass.a_property
494 1 SampleClass.a_staticmethod
495 1 SampleClass.double
496 1 SampleClass.get
497
498New-style classes are also supported:
499
500 >>> tests = finder.find(SampleNewStyleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000501 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000502 ... print('%2s %s' % (len(t.examples), t.name))
Tim Peters8485b562004-08-04 18:46:34 +0000503 1 SampleNewStyleClass
504 1 SampleNewStyleClass.__init__
505 1 SampleNewStyleClass.double
506 1 SampleNewStyleClass.get
507
508Finding Tests in Modules
509~~~~~~~~~~~~~~~~~~~~~~~~
510For a module, DocTestFinder will create a test for the class's
511docstring, and will recursively explore its contents, including
512functions, classes, and the `__test__` dictionary, if it exists:
513
514 >>> # A module
Christian Heimes45f9af32007-11-27 21:50:00 +0000515 >>> import types
516 >>> m = types.ModuleType('some_module')
Tim Peters8485b562004-08-04 18:46:34 +0000517 >>> def triple(val):
518 ... '''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000519 ... >>> print(triple(11))
Tim Peters8485b562004-08-04 18:46:34 +0000520 ... 33
521 ... '''
522 ... return val*3
523 >>> m.__dict__.update({
524 ... 'sample_func': sample_func,
525 ... 'SampleClass': SampleClass,
526 ... '__doc__': '''
527 ... Module docstring.
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000528 ... >>> print('module')
Tim Peters8485b562004-08-04 18:46:34 +0000529 ... module
530 ... ''',
531 ... '__test__': {
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000532 ... 'd': '>>> print(6)\n6\n>>> print(7)\n7\n',
Tim Peters8485b562004-08-04 18:46:34 +0000533 ... 'c': triple}})
534
535 >>> finder = doctest.DocTestFinder()
536 >>> # Use module=test.test_doctest, to prevent doctest from
537 >>> # ignoring the objects since they weren't defined in m.
538 >>> import test.test_doctest
539 >>> tests = finder.find(m, module=test.test_doctest)
Tim Peters8485b562004-08-04 18:46:34 +0000540 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000541 ... print('%2s %s' % (len(t.examples), t.name))
Tim Peters8485b562004-08-04 18:46:34 +0000542 1 some_module
Edward Loper4ae900f2004-09-21 03:20:34 +0000543 3 some_module.SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000544 3 some_module.SampleClass.NestedClass
545 1 some_module.SampleClass.NestedClass.__init__
546 1 some_module.SampleClass.__init__
547 2 some_module.SampleClass.a_classmethod
548 1 some_module.SampleClass.a_property
549 1 some_module.SampleClass.a_staticmethod
550 1 some_module.SampleClass.double
551 1 some_module.SampleClass.get
Tim Petersc5684782004-09-13 01:07:12 +0000552 1 some_module.__test__.c
553 2 some_module.__test__.d
Tim Peters8485b562004-08-04 18:46:34 +0000554 1 some_module.sample_func
555
556Duplicate Removal
557~~~~~~~~~~~~~~~~~
558If a single object is listed twice (under different names), then tests
559will only be generated for it once:
560
Tim Petersf3f57472004-08-08 06:11:48 +0000561 >>> from test import doctest_aliases
Benjamin Peterson78565b22009-06-28 19:19:51 +0000562 >>> assert doctest_aliases.TwoNames.f
563 >>> assert doctest_aliases.TwoNames.g
Edward Loper32ddbf72004-09-13 05:47:24 +0000564 >>> tests = excl_empty_finder.find(doctest_aliases)
Guido van Rossum7131f842007-02-09 20:13:25 +0000565 >>> print(len(tests))
Tim Peters8485b562004-08-04 18:46:34 +0000566 2
Guido van Rossum7131f842007-02-09 20:13:25 +0000567 >>> print(tests[0].name)
Tim Petersf3f57472004-08-08 06:11:48 +0000568 test.doctest_aliases.TwoNames
569
570 TwoNames.f and TwoNames.g are bound to the same object.
571 We can't guess which will be found in doctest's traversal of
572 TwoNames.__dict__ first, so we have to allow for either.
573
574 >>> tests[1].name.split('.')[-1] in ['f', 'g']
Tim Peters8485b562004-08-04 18:46:34 +0000575 True
576
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000577Empty Tests
578~~~~~~~~~~~
579By default, an object with no doctests doesn't create any tests:
Tim Peters8485b562004-08-04 18:46:34 +0000580
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000581 >>> tests = doctest.DocTestFinder().find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000582 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000583 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000584 3 SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000585 3 SampleClass.NestedClass
586 1 SampleClass.NestedClass.__init__
Tim Peters958cc892004-09-13 14:53:28 +0000587 1 SampleClass.__init__
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000588 2 SampleClass.a_classmethod
589 1 SampleClass.a_property
590 1 SampleClass.a_staticmethod
Tim Peters958cc892004-09-13 14:53:28 +0000591 1 SampleClass.double
592 1 SampleClass.get
593
594By default, that excluded objects with no doctests. exclude_empty=False
595tells it to include (empty) tests for objects with no doctests. This feature
596is really to support backward compatibility in what doctest.master.summarize()
597displays.
598
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000599 >>> tests = doctest.DocTestFinder(exclude_empty=False).find(SampleClass)
Tim Peters958cc892004-09-13 14:53:28 +0000600 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000601 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000602 3 SampleClass
Tim Peters958cc892004-09-13 14:53:28 +0000603 3 SampleClass.NestedClass
604 1 SampleClass.NestedClass.__init__
Edward Loper32ddbf72004-09-13 05:47:24 +0000605 0 SampleClass.NestedClass.get
606 0 SampleClass.NestedClass.square
Tim Peters8485b562004-08-04 18:46:34 +0000607 1 SampleClass.__init__
Tim Peters8485b562004-08-04 18:46:34 +0000608 2 SampleClass.a_classmethod
609 1 SampleClass.a_property
610 1 SampleClass.a_staticmethod
611 1 SampleClass.double
612 1 SampleClass.get
613
Tim Peters8485b562004-08-04 18:46:34 +0000614Turning off Recursion
615~~~~~~~~~~~~~~~~~~~~~
616DocTestFinder can be told not to look for tests in contained objects
617using the `recurse` flag:
618
619 >>> tests = doctest.DocTestFinder(recurse=False).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000620 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000621 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000622 3 SampleClass
Edward Loperb51b2342004-08-17 16:37:12 +0000623
624Line numbers
625~~~~~~~~~~~~
626DocTestFinder finds the line number of each example:
627
628 >>> def f(x):
629 ... '''
630 ... >>> x = 12
631 ...
632 ... some text
633 ...
634 ... >>> # examples are not created for comments & bare prompts.
635 ... >>>
636 ... ...
637 ...
638 ... >>> for x in range(10):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000639 ... ... print(x, end=' ')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000640 ... 0 1 2 3 4 5 6 7 8 9
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000641 ... >>> x//2
642 ... 6
Edward Loperb51b2342004-08-17 16:37:12 +0000643 ... '''
644 >>> test = doctest.DocTestFinder().find(f)[0]
645 >>> [e.lineno for e in test.examples]
646 [1, 9, 12]
Tim Peters8485b562004-08-04 18:46:34 +0000647"""
648
Edward Loper00f8da72004-08-26 18:05:07 +0000649def test_DocTestParser(): r"""
650Unit tests for the `DocTestParser` class.
651
652DocTestParser is used to parse docstrings containing doctest examples.
653
654The `parse` method divides a docstring into examples and intervening
655text:
656
657 >>> s = '''
658 ... >>> x, y = 2, 3 # no output expected
659 ... >>> if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000660 ... ... print(x)
661 ... ... print(y)
Edward Loper00f8da72004-08-26 18:05:07 +0000662 ... 2
663 ... 3
664 ...
665 ... Some text.
666 ... >>> x+y
667 ... 5
668 ... '''
669 >>> parser = doctest.DocTestParser()
670 >>> for piece in parser.parse(s):
671 ... if isinstance(piece, doctest.Example):
Guido van Rossum7131f842007-02-09 20:13:25 +0000672 ... print('Example:', (piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000673 ... else:
Guido van Rossum7131f842007-02-09 20:13:25 +0000674 ... print(' Text:', repr(piece))
Edward Loper00f8da72004-08-26 18:05:07 +0000675 Text: '\n'
676 Example: ('x, y = 2, 3 # no output expected\n', '', 1)
677 Text: ''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000678 Example: ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000679 Text: '\nSome text.\n'
680 Example: ('x+y\n', '5\n', 9)
681 Text: ''
682
683The `get_examples` method returns just the examples:
684
685 >>> for piece in parser.get_examples(s):
Guido van Rossum7131f842007-02-09 20:13:25 +0000686 ... print((piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000687 ('x, y = 2, 3 # no output expected\n', '', 1)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000688 ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000689 ('x+y\n', '5\n', 9)
690
691The `get_doctest` method creates a Test from the examples, along with the
692given arguments:
693
694 >>> test = parser.get_doctest(s, {}, 'name', 'filename', lineno=5)
695 >>> (test.name, test.filename, test.lineno)
696 ('name', 'filename', 5)
697 >>> for piece in test.examples:
Guido van Rossum7131f842007-02-09 20:13:25 +0000698 ... print((piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000699 ('x, y = 2, 3 # no output expected\n', '', 1)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000700 ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000701 ('x+y\n', '5\n', 9)
702"""
703
Tim Peters8485b562004-08-04 18:46:34 +0000704class test_DocTestRunner:
705 def basics(): r"""
706Unit tests for the `DocTestRunner` class.
707
708DocTestRunner is used to run DocTest test cases, and to accumulate
709statistics. Here's a simple DocTest case we can use:
710
711 >>> def f(x):
712 ... '''
713 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000714 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000715 ... 12
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000716 ... >>> x//2
717 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000718 ... '''
719 >>> test = doctest.DocTestFinder().find(f)[0]
720
721The main DocTestRunner interface is the `run` method, which runs a
722given DocTest case in a given namespace (globs). It returns a tuple
723`(f,t)`, where `f` is the number of failed tests and `t` is the number
724of tried tests.
725
726 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000727 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000728
729If any example produces incorrect output, then the test runner reports
730the failure and proceeds to the next example:
731
732 >>> def f(x):
733 ... '''
734 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000735 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000736 ... 14
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000737 ... >>> x//2
738 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000739 ... '''
740 >>> test = doctest.DocTestFinder().find(f)[0]
741 >>> doctest.DocTestRunner(verbose=True).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000742 ... # doctest: +ELLIPSIS
Edward Loperaacf0832004-08-26 01:19:50 +0000743 Trying:
744 x = 12
745 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000746 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000747 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000748 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000749 Expecting:
750 14
Tim Peters8485b562004-08-04 18:46:34 +0000751 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000752 File ..., line 4, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000753 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000754 print(x)
Jim Fulton07a349c2004-08-22 14:10:00 +0000755 Expected:
756 14
757 Got:
758 12
Edward Loperaacf0832004-08-26 01:19:50 +0000759 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000760 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000761 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000762 6
Tim Peters8485b562004-08-04 18:46:34 +0000763 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000764 TestResults(failed=1, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000765"""
766 def verbose_flag(): r"""
767The `verbose` flag makes the test runner generate more detailed
768output:
769
770 >>> def f(x):
771 ... '''
772 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000773 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000774 ... 12
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000775 ... >>> x//2
776 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000777 ... '''
778 >>> test = doctest.DocTestFinder().find(f)[0]
779
780 >>> doctest.DocTestRunner(verbose=True).run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000781 Trying:
782 x = 12
783 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000784 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000785 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000786 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000787 Expecting:
788 12
Tim Peters8485b562004-08-04 18:46:34 +0000789 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000790 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000791 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000792 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000793 6
Tim Peters8485b562004-08-04 18:46:34 +0000794 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000795 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000796
797If the `verbose` flag is unspecified, then the output will be verbose
798iff `-v` appears in sys.argv:
799
800 >>> # Save the real sys.argv list.
801 >>> old_argv = sys.argv
802
803 >>> # If -v does not appear in sys.argv, then output isn't verbose.
804 >>> sys.argv = ['test']
805 >>> doctest.DocTestRunner().run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000806 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000807
808 >>> # If -v does appear in sys.argv, then output is verbose.
809 >>> sys.argv = ['test', '-v']
810 >>> doctest.DocTestRunner().run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000811 Trying:
812 x = 12
813 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000814 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000815 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000816 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000817 Expecting:
818 12
Tim Peters8485b562004-08-04 18:46:34 +0000819 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000820 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000821 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000822 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000823 6
Tim Peters8485b562004-08-04 18:46:34 +0000824 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000825 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000826
827 >>> # Restore sys.argv
828 >>> sys.argv = old_argv
829
830In the remaining examples, the test runner's verbosity will be
831explicitly set, to ensure that the test behavior is consistent.
832 """
833 def exceptions(): r"""
834Tests of `DocTestRunner`'s exception handling.
835
836An expected exception is specified with a traceback message. The
837lines between the first line and the type/value may be omitted or
838replaced with any other string:
839
840 >>> def f(x):
841 ... '''
842 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000843 ... >>> print(x//0)
Tim Peters8485b562004-08-04 18:46:34 +0000844 ... Traceback (most recent call last):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000845 ... ZeroDivisionError: integer division or modulo by zero
Tim Peters8485b562004-08-04 18:46:34 +0000846 ... '''
847 >>> test = doctest.DocTestFinder().find(f)[0]
848 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000849 TestResults(failed=0, attempted=2)
Tim Peters8485b562004-08-04 18:46:34 +0000850
Edward Loper19b19582004-08-25 23:07:03 +0000851An example may not generate output before it raises an exception; if
852it does, then the traceback message will not be recognized as
853signaling an expected exception, so the example will be reported as an
854unexpected exception:
Tim Peters8485b562004-08-04 18:46:34 +0000855
856 >>> def f(x):
857 ... '''
858 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000859 ... >>> print('pre-exception output', x//0)
Tim Peters8485b562004-08-04 18:46:34 +0000860 ... pre-exception output
861 ... Traceback (most recent call last):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000862 ... ZeroDivisionError: integer division or modulo by zero
Tim Peters8485b562004-08-04 18:46:34 +0000863 ... '''
864 >>> test = doctest.DocTestFinder().find(f)[0]
865 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper19b19582004-08-25 23:07:03 +0000866 ... # doctest: +ELLIPSIS
867 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000868 File ..., line 4, in f
Edward Loper19b19582004-08-25 23:07:03 +0000869 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000870 print('pre-exception output', x//0)
Edward Loper19b19582004-08-25 23:07:03 +0000871 Exception raised:
872 ...
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000873 ZeroDivisionError: integer division or modulo by zero
Christian Heimes25bb7832008-01-11 16:17:00 +0000874 TestResults(failed=1, attempted=2)
Tim Peters8485b562004-08-04 18:46:34 +0000875
876Exception messages may contain newlines:
877
878 >>> def f(x):
879 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000880 ... >>> raise ValueError('multi\nline\nmessage')
Tim Peters8485b562004-08-04 18:46:34 +0000881 ... Traceback (most recent call last):
882 ... ValueError: multi
883 ... line
884 ... message
885 ... '''
886 >>> test = doctest.DocTestFinder().find(f)[0]
887 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000888 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000889
890If an exception is expected, but an exception with the wrong type or
891message is raised, then it is reported as a failure:
892
893 >>> def f(x):
894 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000895 ... >>> raise ValueError('message')
Tim Peters8485b562004-08-04 18:46:34 +0000896 ... Traceback (most recent call last):
897 ... ValueError: wrong message
898 ... '''
899 >>> test = doctest.DocTestFinder().find(f)[0]
900 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000901 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000902 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000903 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000904 Failed example:
Collin Winter3add4d72007-08-29 23:37:32 +0000905 raise ValueError('message')
Tim Peters8485b562004-08-04 18:46:34 +0000906 Expected:
907 Traceback (most recent call last):
908 ValueError: wrong message
909 Got:
910 Traceback (most recent call last):
Edward Loper8e4a34b2004-08-12 02:34:27 +0000911 ...
Tim Peters8485b562004-08-04 18:46:34 +0000912 ValueError: message
Christian Heimes25bb7832008-01-11 16:17:00 +0000913 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000914
Tim Peters1fbf9c52004-09-04 17:21:02 +0000915However, IGNORE_EXCEPTION_DETAIL can be used to allow a mismatch in the
916detail:
917
918 >>> def f(x):
919 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000920 ... >>> raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +0000921 ... Traceback (most recent call last):
922 ... ValueError: wrong message
923 ... '''
924 >>> test = doctest.DocTestFinder().find(f)[0]
925 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000926 TestResults(failed=0, attempted=1)
Tim Peters1fbf9c52004-09-04 17:21:02 +0000927
Nick Coghlan5e76e942010-06-12 13:42:46 +0000928IGNORE_EXCEPTION_DETAIL also ignores difference in exception formatting
929between Python versions. For example, in Python 2.x, the module path of
930the exception is not in the output, but this will fail under Python 3:
931
932 >>> def f(x):
933 ... r'''
934 ... >>> from http.client import HTTPException
935 ... >>> raise HTTPException('message')
936 ... Traceback (most recent call last):
937 ... HTTPException: message
938 ... '''
939 >>> test = doctest.DocTestFinder().find(f)[0]
940 >>> doctest.DocTestRunner(verbose=False).run(test)
941 ... # doctest: +ELLIPSIS
942 **********************************************************************
943 File ..., line 4, in f
944 Failed example:
945 raise HTTPException('message')
946 Expected:
947 Traceback (most recent call last):
948 HTTPException: message
949 Got:
950 Traceback (most recent call last):
951 ...
952 http.client.HTTPException: message
953 TestResults(failed=1, attempted=2)
954
955But in Python 3 the module path is included, and therefore a test must look
956like the following test to succeed in Python 3. But that test will fail under
957Python 2.
958
959 >>> def f(x):
960 ... r'''
961 ... >>> from http.client import HTTPException
962 ... >>> raise HTTPException('message')
963 ... Traceback (most recent call last):
964 ... http.client.HTTPException: message
965 ... '''
966 >>> test = doctest.DocTestFinder().find(f)[0]
967 >>> doctest.DocTestRunner(verbose=False).run(test)
968 TestResults(failed=0, attempted=2)
969
970However, with IGNORE_EXCEPTION_DETAIL, the module name of the exception
971(or its unexpected absence) will be ignored:
972
973 >>> def f(x):
974 ... r'''
975 ... >>> from http.client import HTTPException
976 ... >>> raise HTTPException('message') #doctest: +IGNORE_EXCEPTION_DETAIL
977 ... Traceback (most recent call last):
978 ... HTTPException: message
979 ... '''
980 >>> test = doctest.DocTestFinder().find(f)[0]
981 >>> doctest.DocTestRunner(verbose=False).run(test)
982 TestResults(failed=0, attempted=2)
983
984The module path will be completely ignored, so two different module paths will
985still pass if IGNORE_EXCEPTION_DETAIL is given. This is intentional, so it can
986be used when exceptions have changed module.
987
988 >>> def f(x):
989 ... r'''
990 ... >>> from http.client import HTTPException
991 ... >>> raise HTTPException('message') #doctest: +IGNORE_EXCEPTION_DETAIL
992 ... Traceback (most recent call last):
993 ... foo.bar.HTTPException: message
994 ... '''
995 >>> test = doctest.DocTestFinder().find(f)[0]
996 >>> doctest.DocTestRunner(verbose=False).run(test)
997 TestResults(failed=0, attempted=2)
998
Tim Peters1fbf9c52004-09-04 17:21:02 +0000999But IGNORE_EXCEPTION_DETAIL does not allow a mismatch in the exception type:
1000
1001 >>> def f(x):
1002 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +00001003 ... >>> raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +00001004 ... Traceback (most recent call last):
1005 ... TypeError: wrong type
1006 ... '''
1007 >>> test = doctest.DocTestFinder().find(f)[0]
1008 >>> doctest.DocTestRunner(verbose=False).run(test)
1009 ... # doctest: +ELLIPSIS
1010 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001011 File ..., line 3, in f
Tim Peters1fbf9c52004-09-04 17:21:02 +00001012 Failed example:
Collin Winter3add4d72007-08-29 23:37:32 +00001013 raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +00001014 Expected:
1015 Traceback (most recent call last):
1016 TypeError: wrong type
1017 Got:
1018 Traceback (most recent call last):
1019 ...
1020 ValueError: message
Christian Heimes25bb7832008-01-11 16:17:00 +00001021 TestResults(failed=1, attempted=1)
Tim Peters1fbf9c52004-09-04 17:21:02 +00001022
Tim Peters8485b562004-08-04 18:46:34 +00001023If an exception is raised but not expected, then it is reported as an
1024unexpected exception:
1025
Tim Peters8485b562004-08-04 18:46:34 +00001026 >>> def f(x):
1027 ... r'''
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001028 ... >>> 1//0
Tim Peters8485b562004-08-04 18:46:34 +00001029 ... 0
1030 ... '''
1031 >>> test = doctest.DocTestFinder().find(f)[0]
1032 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper74bca7a2004-08-12 02:27:44 +00001033 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001034 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001035 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001036 Failed example:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001037 1//0
Tim Peters8485b562004-08-04 18:46:34 +00001038 Exception raised:
1039 Traceback (most recent call last):
Jim Fulton07a349c2004-08-22 14:10:00 +00001040 ...
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001041 ZeroDivisionError: integer division or modulo by zero
Christian Heimes25bb7832008-01-11 16:17:00 +00001042 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001043"""
Georg Brandl25fbb892010-07-30 09:23:23 +00001044 def displayhook(): r"""
1045Test that changing sys.displayhook doesn't matter for doctest.
1046
1047 >>> import sys
1048 >>> orig_displayhook = sys.displayhook
1049 >>> def my_displayhook(x):
1050 ... print('hi!')
1051 >>> sys.displayhook = my_displayhook
1052 >>> def f():
1053 ... '''
1054 ... >>> 3
1055 ... 3
1056 ... '''
1057 >>> test = doctest.DocTestFinder().find(f)[0]
1058 >>> r = doctest.DocTestRunner(verbose=False).run(test)
1059 >>> post_displayhook = sys.displayhook
1060
1061 We need to restore sys.displayhook now, so that we'll be able to test
1062 results.
1063
1064 >>> sys.displayhook = orig_displayhook
1065
1066 Ok, now we can check that everything is ok.
1067
1068 >>> r
1069 TestResults(failed=0, attempted=1)
1070 >>> post_displayhook is my_displayhook
1071 True
1072"""
Tim Peters8485b562004-08-04 18:46:34 +00001073 def optionflags(): r"""
1074Tests of `DocTestRunner`'s option flag handling.
1075
1076Several option flags can be used to customize the behavior of the test
1077runner. These are defined as module constants in doctest, and passed
Christian Heimesfaf2f632008-01-06 16:59:19 +00001078to the DocTestRunner constructor (multiple constants should be ORed
Tim Peters8485b562004-08-04 18:46:34 +00001079together).
1080
1081The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
1082and 1/0:
1083
1084 >>> def f(x):
1085 ... '>>> True\n1\n'
1086
1087 >>> # Without the flag:
1088 >>> test = doctest.DocTestFinder().find(f)[0]
1089 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001090 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001091
1092 >>> # With the flag:
1093 >>> test = doctest.DocTestFinder().find(f)[0]
1094 >>> flags = doctest.DONT_ACCEPT_TRUE_FOR_1
1095 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001096 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001097 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001098 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001099 Failed example:
1100 True
1101 Expected:
1102 1
1103 Got:
1104 True
Christian Heimes25bb7832008-01-11 16:17:00 +00001105 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001106
1107The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines
1108and the '<BLANKLINE>' marker:
1109
1110 >>> def f(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001111 ... '>>> print("a\\n\\nb")\na\n<BLANKLINE>\nb\n'
Tim Peters8485b562004-08-04 18:46:34 +00001112
1113 >>> # Without the flag:
1114 >>> test = doctest.DocTestFinder().find(f)[0]
1115 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001116 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001117
1118 >>> # With the flag:
1119 >>> test = doctest.DocTestFinder().find(f)[0]
1120 >>> flags = doctest.DONT_ACCEPT_BLANKLINE
1121 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001122 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001123 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001124 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001125 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001126 print("a\n\nb")
Tim Peters8485b562004-08-04 18:46:34 +00001127 Expected:
1128 a
1129 <BLANKLINE>
1130 b
1131 Got:
1132 a
1133 <BLANKLINE>
1134 b
Christian Heimes25bb7832008-01-11 16:17:00 +00001135 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001136
1137The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be
1138treated as equal:
1139
1140 >>> def f(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001141 ... '>>> print(1, 2, 3)\n 1 2\n 3'
Tim Peters8485b562004-08-04 18:46:34 +00001142
1143 >>> # Without the flag:
1144 >>> test = doctest.DocTestFinder().find(f)[0]
1145 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001146 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001147 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001148 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001149 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001150 print(1, 2, 3)
Tim Peters8485b562004-08-04 18:46:34 +00001151 Expected:
1152 1 2
1153 3
Jim Fulton07a349c2004-08-22 14:10:00 +00001154 Got:
1155 1 2 3
Christian Heimes25bb7832008-01-11 16:17:00 +00001156 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001157
1158 >>> # With the flag:
1159 >>> test = doctest.DocTestFinder().find(f)[0]
1160 >>> flags = doctest.NORMALIZE_WHITESPACE
1161 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001162 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001163
Tim Peters026f8dc2004-08-19 16:38:58 +00001164 An example from the docs:
Guido van Rossum805365e2007-05-07 22:24:25 +00001165 >>> print(list(range(20))) #doctest: +NORMALIZE_WHITESPACE
Tim Peters026f8dc2004-08-19 16:38:58 +00001166 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
1167 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
1168
Tim Peters8485b562004-08-04 18:46:34 +00001169The ELLIPSIS flag causes ellipsis marker ("...") in the expected
1170output to match any substring in the actual output:
1171
1172 >>> def f(x):
Guido van Rossum805365e2007-05-07 22:24:25 +00001173 ... '>>> print(list(range(15)))\n[0, 1, 2, ..., 14]\n'
Tim Peters8485b562004-08-04 18:46:34 +00001174
1175 >>> # Without the flag:
1176 >>> test = doctest.DocTestFinder().find(f)[0]
1177 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001178 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001179 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001180 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001181 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001182 print(list(range(15)))
Jim Fulton07a349c2004-08-22 14:10:00 +00001183 Expected:
1184 [0, 1, 2, ..., 14]
1185 Got:
1186 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
Christian Heimes25bb7832008-01-11 16:17:00 +00001187 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001188
1189 >>> # With the flag:
1190 >>> test = doctest.DocTestFinder().find(f)[0]
1191 >>> flags = doctest.ELLIPSIS
1192 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001193 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001194
Tim Peterse594bee2004-08-22 01:47:51 +00001195 ... also matches nothing:
Tim Peters1cf3aa62004-08-19 06:49:33 +00001196
Guido van Rossume0192e52007-02-09 23:39:59 +00001197 >>> if 1:
1198 ... for i in range(100):
1199 ... print(i**2, end=' ') #doctest: +ELLIPSIS
1200 ... print('!')
1201 0 1...4...9 16 ... 36 49 64 ... 9801 !
Tim Peters1cf3aa62004-08-19 06:49:33 +00001202
Tim Peters026f8dc2004-08-19 16:38:58 +00001203 ... can be surprising; e.g., this test passes:
Tim Peters26b3ebb2004-08-19 08:10:08 +00001204
Guido van Rossume0192e52007-02-09 23:39:59 +00001205 >>> if 1: #doctest: +ELLIPSIS
1206 ... for i in range(20):
1207 ... print(i, end=' ')
1208 ... print(20)
Tim Peterse594bee2004-08-22 01:47:51 +00001209 0 1 2 ...1...2...0
Tim Peters26b3ebb2004-08-19 08:10:08 +00001210
Tim Peters026f8dc2004-08-19 16:38:58 +00001211 Examples from the docs:
1212
Guido van Rossum805365e2007-05-07 22:24:25 +00001213 >>> print(list(range(20))) # doctest:+ELLIPSIS
Tim Peters026f8dc2004-08-19 16:38:58 +00001214 [0, 1, ..., 18, 19]
1215
Guido van Rossum805365e2007-05-07 22:24:25 +00001216 >>> print(list(range(20))) # doctest: +ELLIPSIS
Tim Peters026f8dc2004-08-19 16:38:58 +00001217 ... # doctest: +NORMALIZE_WHITESPACE
1218 [0, 1, ..., 18, 19]
1219
Thomas Wouters477c8d52006-05-27 19:21:47 +00001220The SKIP flag causes an example to be skipped entirely. I.e., the
1221example is not run. It can be useful in contexts where doctest
1222examples serve as both documentation and test cases, and an example
1223should be included for documentation purposes, but should not be
1224checked (e.g., because its output is random, or depends on resources
1225which would be unavailable.) The SKIP flag can also be used for
1226'commenting out' broken examples.
1227
1228 >>> import unavailable_resource # doctest: +SKIP
1229 >>> unavailable_resource.do_something() # doctest: +SKIP
1230 >>> unavailable_resource.blow_up() # doctest: +SKIP
1231 Traceback (most recent call last):
1232 ...
1233 UncheckedBlowUpError: Nobody checks me.
1234
1235 >>> import random
Guido van Rossum7131f842007-02-09 20:13:25 +00001236 >>> print(random.random()) # doctest: +SKIP
Thomas Wouters477c8d52006-05-27 19:21:47 +00001237 0.721216923889
1238
Edward Loper71f55af2004-08-26 01:41:51 +00001239The REPORT_UDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001240and actual outputs to be displayed using a unified diff:
1241
1242 >>> def f(x):
1243 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001244 ... >>> print('\n'.join('abcdefg'))
Tim Peters8485b562004-08-04 18:46:34 +00001245 ... a
1246 ... B
1247 ... c
1248 ... d
1249 ... f
1250 ... g
1251 ... h
1252 ... '''
1253
1254 >>> # Without the flag:
1255 >>> test = doctest.DocTestFinder().find(f)[0]
1256 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001257 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001258 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001259 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001260 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001261 print('\n'.join('abcdefg'))
Tim Peters8485b562004-08-04 18:46:34 +00001262 Expected:
1263 a
1264 B
1265 c
1266 d
1267 f
1268 g
1269 h
1270 Got:
1271 a
1272 b
1273 c
1274 d
1275 e
1276 f
1277 g
Christian Heimes25bb7832008-01-11 16:17:00 +00001278 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001279
1280 >>> # With the flag:
1281 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001282 >>> flags = doctest.REPORT_UDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001283 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001284 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001285 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001286 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001287 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001288 print('\n'.join('abcdefg'))
Edward Loper56629292004-08-26 01:31:56 +00001289 Differences (unified diff with -expected +actual):
Tim Peterse7edcb82004-08-26 05:44:27 +00001290 @@ -1,7 +1,7 @@
Tim Peters8485b562004-08-04 18:46:34 +00001291 a
1292 -B
1293 +b
1294 c
1295 d
1296 +e
1297 f
1298 g
1299 -h
Christian Heimes25bb7832008-01-11 16:17:00 +00001300 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001301
Edward Loper71f55af2004-08-26 01:41:51 +00001302The REPORT_CDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001303and actual outputs to be displayed using a context diff:
1304
Edward Loper71f55af2004-08-26 01:41:51 +00001305 >>> # Reuse f() from the REPORT_UDIFF example, above.
Tim Peters8485b562004-08-04 18:46:34 +00001306 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001307 >>> flags = doctest.REPORT_CDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001308 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001309 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001310 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001311 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001312 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001313 print('\n'.join('abcdefg'))
Edward Loper56629292004-08-26 01:31:56 +00001314 Differences (context diff with expected followed by actual):
Tim Peters8485b562004-08-04 18:46:34 +00001315 ***************
Tim Peterse7edcb82004-08-26 05:44:27 +00001316 *** 1,7 ****
Tim Peters8485b562004-08-04 18:46:34 +00001317 a
1318 ! B
1319 c
1320 d
1321 f
1322 g
1323 - h
Tim Peterse7edcb82004-08-26 05:44:27 +00001324 --- 1,7 ----
Tim Peters8485b562004-08-04 18:46:34 +00001325 a
1326 ! b
1327 c
1328 d
1329 + e
1330 f
1331 g
Christian Heimes25bb7832008-01-11 16:17:00 +00001332 TestResults(failed=1, attempted=1)
Tim Petersc6cbab02004-08-22 19:43:28 +00001333
1334
Edward Loper71f55af2004-08-26 01:41:51 +00001335The REPORT_NDIFF flag causes failures to use the difflib.Differ algorithm
Tim Petersc6cbab02004-08-22 19:43:28 +00001336used by the popular ndiff.py utility. This does intraline difference
1337marking, as well as interline differences.
1338
1339 >>> def f(x):
1340 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001341 ... >>> print("a b c d e f g h i j k l m")
Tim Petersc6cbab02004-08-22 19:43:28 +00001342 ... a b c d e f g h i j k 1 m
1343 ... '''
1344 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001345 >>> flags = doctest.REPORT_NDIFF
Tim Petersc6cbab02004-08-22 19:43:28 +00001346 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001347 ... # doctest: +ELLIPSIS
Tim Petersc6cbab02004-08-22 19:43:28 +00001348 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001349 File ..., line 3, in f
Tim Petersc6cbab02004-08-22 19:43:28 +00001350 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001351 print("a b c d e f g h i j k l m")
Tim Petersc6cbab02004-08-22 19:43:28 +00001352 Differences (ndiff with -expected +actual):
1353 - a b c d e f g h i j k 1 m
1354 ? ^
1355 + a b c d e f g h i j k l m
1356 ? + ++ ^
Christian Heimes25bb7832008-01-11 16:17:00 +00001357 TestResults(failed=1, attempted=1)
Edward Lopera89f88d2004-08-26 02:45:51 +00001358
Ezio Melotti13925002011-03-16 11:05:33 +02001359The REPORT_ONLY_FIRST_FAILURE suppresses result output after the first
Edward Lopera89f88d2004-08-26 02:45:51 +00001360failing example:
1361
1362 >>> def f(x):
1363 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001364 ... >>> print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001365 ... 1
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001366 ... >>> print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001367 ... 200
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001368 ... >>> print(3) # second failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001369 ... 300
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001370 ... >>> print(4) # second success
Edward Lopera89f88d2004-08-26 02:45:51 +00001371 ... 4
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001372 ... >>> print(5) # third failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001373 ... 500
1374 ... '''
1375 >>> test = doctest.DocTestFinder().find(f)[0]
1376 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1377 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001378 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001379 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001380 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001381 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001382 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001383 Expected:
1384 200
1385 Got:
1386 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001387 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001388
Ezio Melotti13925002011-03-16 11:05:33 +02001389However, output from `report_start` is not suppressed:
Edward Lopera89f88d2004-08-26 02:45:51 +00001390
1391 >>> doctest.DocTestRunner(verbose=True, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001392 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001393 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001394 print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001395 Expecting:
1396 1
1397 ok
1398 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001399 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001400 Expecting:
1401 200
1402 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001403 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001404 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001405 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001406 Expected:
1407 200
1408 Got:
1409 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001410 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001411
R David Murray5a9d7062012-11-21 15:09:21 -05001412The FAIL_FAST flag causes the runner to exit after the first failing example,
1413so subsequent examples are not even attempted:
1414
1415 >>> flags = doctest.FAIL_FAST
1416 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1417 ... # doctest: +ELLIPSIS
1418 **********************************************************************
1419 File ..., line 5, in f
1420 Failed example:
1421 print(2) # first failure
1422 Expected:
1423 200
1424 Got:
1425 2
1426 TestResults(failed=1, attempted=2)
1427
1428Specifying both FAIL_FAST and REPORT_ONLY_FIRST_FAILURE is equivalent to
1429FAIL_FAST only:
1430
1431 >>> flags = doctest.FAIL_FAST | doctest.REPORT_ONLY_FIRST_FAILURE
1432 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1433 ... # doctest: +ELLIPSIS
1434 **********************************************************************
1435 File ..., line 5, in f
1436 Failed example:
1437 print(2) # first failure
1438 Expected:
1439 200
1440 Got:
1441 2
1442 TestResults(failed=1, attempted=2)
1443
1444For the purposes of both REPORT_ONLY_FIRST_FAILURE and FAIL_FAST, unexpected
1445exceptions count as failures:
Edward Lopera89f88d2004-08-26 02:45:51 +00001446
1447 >>> def f(x):
1448 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001449 ... >>> print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001450 ... 1
1451 ... >>> raise ValueError(2) # first failure
1452 ... 200
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001453 ... >>> print(3) # second failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001454 ... 300
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001455 ... >>> print(4) # second success
Edward Lopera89f88d2004-08-26 02:45:51 +00001456 ... 4
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001457 ... >>> print(5) # third failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001458 ... 500
1459 ... '''
1460 >>> test = doctest.DocTestFinder().find(f)[0]
1461 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1462 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1463 ... # doctest: +ELLIPSIS
1464 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001465 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001466 Failed example:
1467 raise ValueError(2) # first failure
1468 Exception raised:
1469 ...
1470 ValueError: 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001471 TestResults(failed=3, attempted=5)
R David Murray5a9d7062012-11-21 15:09:21 -05001472 >>> flags = doctest.FAIL_FAST
1473 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1474 ... # doctest: +ELLIPSIS
1475 **********************************************************************
1476 File ..., line 5, in f
1477 Failed example:
1478 raise ValueError(2) # first failure
1479 Exception raised:
1480 ...
1481 ValueError: 2
1482 TestResults(failed=1, attempted=2)
Edward Lopera89f88d2004-08-26 02:45:51 +00001483
Thomas Wouters477c8d52006-05-27 19:21:47 +00001484New option flags can also be registered, via register_optionflag(). Here
1485we reach into doctest's internals a bit.
1486
1487 >>> unlikely = "UNLIKELY_OPTION_NAME"
1488 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1489 False
1490 >>> new_flag_value = doctest.register_optionflag(unlikely)
1491 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1492 True
1493
1494Before 2.4.4/2.5, registering a name more than once erroneously created
1495more than one flag value. Here we verify that's fixed:
1496
1497 >>> redundant_flag_value = doctest.register_optionflag(unlikely)
1498 >>> redundant_flag_value == new_flag_value
1499 True
1500
1501Clean up.
1502 >>> del doctest.OPTIONFLAGS_BY_NAME[unlikely]
1503
Tim Petersc6cbab02004-08-22 19:43:28 +00001504 """
1505
Tim Peters8485b562004-08-04 18:46:34 +00001506 def option_directives(): r"""
1507Tests of `DocTestRunner`'s option directive mechanism.
1508
Edward Loper74bca7a2004-08-12 02:27:44 +00001509Option directives can be used to turn option flags on or off for a
1510single example. To turn an option on for an example, follow that
1511example with a comment of the form ``# doctest: +OPTION``:
Tim Peters8485b562004-08-04 18:46:34 +00001512
1513 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001514 ... >>> print(list(range(10))) # should fail: no ellipsis
Edward Loper74bca7a2004-08-12 02:27:44 +00001515 ... [0, 1, ..., 9]
1516 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001517 ... >>> print(list(range(10))) # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001518 ... [0, 1, ..., 9]
1519 ... '''
1520 >>> test = doctest.DocTestFinder().find(f)[0]
1521 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001522 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001523 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001524 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001525 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001526 print(list(range(10))) # should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001527 Expected:
1528 [0, 1, ..., 9]
1529 Got:
1530 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001531 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001532
1533To turn an option off for an example, follow that example with a
1534comment of the form ``# doctest: -OPTION``:
1535
1536 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001537 ... >>> print(list(range(10)))
Edward Loper74bca7a2004-08-12 02:27:44 +00001538 ... [0, 1, ..., 9]
1539 ...
1540 ... >>> # should fail: no ellipsis
Guido van Rossum805365e2007-05-07 22:24:25 +00001541 ... >>> print(list(range(10))) # doctest: -ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001542 ... [0, 1, ..., 9]
1543 ... '''
1544 >>> test = doctest.DocTestFinder().find(f)[0]
1545 >>> doctest.DocTestRunner(verbose=False,
1546 ... optionflags=doctest.ELLIPSIS).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001547 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001548 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001549 File ..., line 6, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001550 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001551 print(list(range(10))) # doctest: -ELLIPSIS
Jim Fulton07a349c2004-08-22 14:10:00 +00001552 Expected:
1553 [0, 1, ..., 9]
1554 Got:
1555 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001556 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001557
1558Option directives affect only the example that they appear with; they
1559do not change the options for surrounding examples:
Edward Loper8e4a34b2004-08-12 02:34:27 +00001560
Edward Loper74bca7a2004-08-12 02:27:44 +00001561 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001562 ... >>> print(list(range(10))) # Should fail: no ellipsis
Tim Peters8485b562004-08-04 18:46:34 +00001563 ... [0, 1, ..., 9]
1564 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001565 ... >>> print(list(range(10))) # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001566 ... [0, 1, ..., 9]
1567 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001568 ... >>> print(list(range(10))) # Should fail: no ellipsis
Tim Peters8485b562004-08-04 18:46:34 +00001569 ... [0, 1, ..., 9]
1570 ... '''
1571 >>> test = doctest.DocTestFinder().find(f)[0]
1572 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001573 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001574 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001575 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001576 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001577 print(list(range(10))) # Should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001578 Expected:
1579 [0, 1, ..., 9]
1580 Got:
1581 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001582 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001583 File ..., line 8, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001584 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001585 print(list(range(10))) # Should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001586 Expected:
1587 [0, 1, ..., 9]
1588 Got:
1589 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001590 TestResults(failed=2, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +00001591
Edward Loper74bca7a2004-08-12 02:27:44 +00001592Multiple options may be modified by a single option directive. They
1593may be separated by whitespace, commas, or both:
Tim Peters8485b562004-08-04 18:46:34 +00001594
1595 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001596 ... >>> print(list(range(10))) # Should fail
Tim Peters8485b562004-08-04 18:46:34 +00001597 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001598 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001599 ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001600 ... [0, 1, ..., 9]
1601 ... '''
1602 >>> test = doctest.DocTestFinder().find(f)[0]
1603 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001604 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001605 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001606 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001607 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001608 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001609 Expected:
1610 [0, 1, ..., 9]
1611 Got:
1612 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001613 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001614
1615 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001616 ... >>> print(list(range(10))) # Should fail
Edward Loper74bca7a2004-08-12 02:27:44 +00001617 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001618 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001619 ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
1620 ... [0, 1, ..., 9]
1621 ... '''
1622 >>> test = doctest.DocTestFinder().find(f)[0]
1623 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001624 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001625 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001626 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001627 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001628 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001629 Expected:
1630 [0, 1, ..., 9]
1631 Got:
1632 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001633 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001634
1635 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001636 ... >>> print(list(range(10))) # Should fail
Edward Loper74bca7a2004-08-12 02:27:44 +00001637 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001638 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001639 ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1640 ... [0, 1, ..., 9]
1641 ... '''
1642 >>> test = doctest.DocTestFinder().find(f)[0]
1643 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001644 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001645 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001646 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001647 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001648 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001649 Expected:
1650 [0, 1, ..., 9]
1651 Got:
1652 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001653 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001654
1655The option directive may be put on the line following the source, as
1656long as a continuation prompt is used:
1657
1658 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001659 ... >>> print(list(range(10)))
Edward Loper74bca7a2004-08-12 02:27:44 +00001660 ... ... # doctest: +ELLIPSIS
1661 ... [0, 1, ..., 9]
1662 ... '''
1663 >>> test = doctest.DocTestFinder().find(f)[0]
1664 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001665 TestResults(failed=0, attempted=1)
Edward Loper8e4a34b2004-08-12 02:34:27 +00001666
Edward Loper74bca7a2004-08-12 02:27:44 +00001667For examples with multi-line source, the option directive may appear
1668at the end of any line:
1669
1670 >>> def f(x): r'''
1671 ... >>> for x in range(10): # doctest: +ELLIPSIS
Guido van Rossum805365e2007-05-07 22:24:25 +00001672 ... ... print(' ', x, end='', sep='')
1673 ... 0 1 2 ... 9
Edward Loper74bca7a2004-08-12 02:27:44 +00001674 ...
1675 ... >>> for x in range(10):
Guido van Rossum805365e2007-05-07 22:24:25 +00001676 ... ... print(' ', x, end='', sep='') # doctest: +ELLIPSIS
1677 ... 0 1 2 ... 9
Edward Loper74bca7a2004-08-12 02:27:44 +00001678 ... '''
1679 >>> test = doctest.DocTestFinder().find(f)[0]
1680 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001681 TestResults(failed=0, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001682
1683If more than one line of an example with multi-line source has an
1684option directive, then they are combined:
1685
1686 >>> def f(x): r'''
1687 ... Should fail (option directive not on the last line):
1688 ... >>> for x in range(10): # doctest: +ELLIPSIS
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001689 ... ... print(x, end=' ') # doctest: +NORMALIZE_WHITESPACE
Guido van Rossumd8faa362007-04-27 19:54:29 +00001690 ... 0 1 2...9
Edward Loper74bca7a2004-08-12 02:27:44 +00001691 ... '''
1692 >>> test = doctest.DocTestFinder().find(f)[0]
1693 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001694 TestResults(failed=0, attempted=1)
Edward Loper74bca7a2004-08-12 02:27:44 +00001695
1696It is an error to have a comment of the form ``# doctest:`` that is
1697*not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
1698``OPTION`` is an option that has been registered with
1699`register_option`:
1700
1701 >>> # Error: Option not registered
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001702 >>> s = '>>> print(12) #doctest: +BADOPTION'
Edward Loper74bca7a2004-08-12 02:27:44 +00001703 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1704 Traceback (most recent call last):
1705 ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
1706
1707 >>> # Error: No + or - prefix
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001708 >>> s = '>>> print(12) #doctest: ELLIPSIS'
Edward Loper74bca7a2004-08-12 02:27:44 +00001709 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1710 Traceback (most recent call last):
1711 ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
1712
1713It is an error to use an option directive on a line that contains no
1714source:
1715
1716 >>> s = '>>> # doctest: +ELLIPSIS'
1717 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1718 Traceback (most recent call last):
1719 ValueError: line 0 of the doctest for s has an option directive on a line with no example: '# doctest: +ELLIPSIS'
Tim Peters8485b562004-08-04 18:46:34 +00001720"""
1721
1722def test_testsource(): r"""
1723Unit tests for `testsource()`.
1724
1725The testsource() function takes a module and a name, finds the (first)
Tim Peters19397e52004-08-06 22:02:59 +00001726test with that name in that module, and converts it to a script. The
1727example code is converted to regular Python code. The surrounding
1728words and expected output are converted to comments:
Tim Peters8485b562004-08-04 18:46:34 +00001729
1730 >>> import test.test_doctest
1731 >>> name = 'test.test_doctest.sample_func'
Guido van Rossum7131f842007-02-09 20:13:25 +00001732 >>> print(doctest.testsource(test.test_doctest, name))
Edward Lopera5db6002004-08-12 02:41:30 +00001733 # Blah blah
Tim Peters19397e52004-08-06 22:02:59 +00001734 #
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001735 print(sample_func(22))
Tim Peters8485b562004-08-04 18:46:34 +00001736 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001737 ## 44
Tim Peters19397e52004-08-06 22:02:59 +00001738 #
Edward Lopera5db6002004-08-12 02:41:30 +00001739 # Yee ha!
Georg Brandlecf93c72005-06-26 23:09:51 +00001740 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001741
1742 >>> name = 'test.test_doctest.SampleNewStyleClass'
Guido van Rossum7131f842007-02-09 20:13:25 +00001743 >>> print(doctest.testsource(test.test_doctest, name))
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001744 print('1\n2\n3')
Tim Peters8485b562004-08-04 18:46:34 +00001745 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001746 ## 1
1747 ## 2
1748 ## 3
Georg Brandlecf93c72005-06-26 23:09:51 +00001749 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001750
1751 >>> name = 'test.test_doctest.SampleClass.a_classmethod'
Guido van Rossum7131f842007-02-09 20:13:25 +00001752 >>> print(doctest.testsource(test.test_doctest, name))
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001753 print(SampleClass.a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +00001754 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001755 ## 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001756 print(SampleClass(0).a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +00001757 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001758 ## 12
Georg Brandlecf93c72005-06-26 23:09:51 +00001759 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001760"""
1761
1762def test_debug(): r"""
1763
1764Create a docstring that we want to debug:
1765
1766 >>> s = '''
1767 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001768 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +00001769 ... 12
1770 ... '''
1771
1772Create some fake stdin input, to feed to the debugger:
1773
Tim Peters8485b562004-08-04 18:46:34 +00001774 >>> real_stdin = sys.stdin
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001775 >>> sys.stdin = _FakeInput(['next', 'print(x)', 'continue'])
Tim Peters8485b562004-08-04 18:46:34 +00001776
1777Run the debugger on the docstring, and then restore sys.stdin.
1778
Edward Loper2de91ba2004-08-27 02:07:46 +00001779 >>> try: doctest.debug_src(s)
1780 ... finally: sys.stdin = real_stdin
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001781 > <string>(1)<module>()
Edward Loper2de91ba2004-08-27 02:07:46 +00001782 (Pdb) next
1783 12
Tim Peters8485b562004-08-04 18:46:34 +00001784 --Return--
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001785 > <string>(1)<module>()->None
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001786 (Pdb) print(x)
Edward Loper2de91ba2004-08-27 02:07:46 +00001787 12
1788 (Pdb) continue
Tim Peters8485b562004-08-04 18:46:34 +00001789
1790"""
1791
Brett Cannon31f59292011-02-21 19:29:56 +00001792if not hasattr(sys, 'gettrace') or not sys.gettrace():
1793 def test_pdb_set_trace():
1794 """Using pdb.set_trace from a doctest.
Jim Fulton356fd192004-08-09 11:34:47 +00001795
Brett Cannon31f59292011-02-21 19:29:56 +00001796 You can use pdb.set_trace from a doctest. To do so, you must
1797 retrieve the set_trace function from the pdb module at the time
1798 you use it. The doctest module changes sys.stdout so that it can
1799 capture program output. It also temporarily replaces pdb.set_trace
1800 with a version that restores stdout. This is necessary for you to
1801 see debugger output.
Jim Fulton356fd192004-08-09 11:34:47 +00001802
Brett Cannon31f59292011-02-21 19:29:56 +00001803 >>> doc = '''
1804 ... >>> x = 42
1805 ... >>> raise Exception('clé')
1806 ... Traceback (most recent call last):
1807 ... Exception: clé
1808 ... >>> import pdb; pdb.set_trace()
1809 ... '''
1810 >>> parser = doctest.DocTestParser()
1811 >>> test = parser.get_doctest(doc, {}, "foo-bar@baz", "foo-bar@baz.py", 0)
1812 >>> runner = doctest.DocTestRunner(verbose=False)
Jim Fulton356fd192004-08-09 11:34:47 +00001813
Brett Cannon31f59292011-02-21 19:29:56 +00001814 To demonstrate this, we'll create a fake standard input that
1815 captures our debugger input:
Jim Fulton356fd192004-08-09 11:34:47 +00001816
Brett Cannon31f59292011-02-21 19:29:56 +00001817 >>> import tempfile
1818 >>> real_stdin = sys.stdin
1819 >>> sys.stdin = _FakeInput([
1820 ... 'print(x)', # print data defined by the example
1821 ... 'continue', # stop debugging
1822 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001823
Brett Cannon31f59292011-02-21 19:29:56 +00001824 >>> try: runner.run(test)
1825 ... finally: sys.stdin = real_stdin
1826 --Return--
1827 > <doctest foo-bar@baz[2]>(1)<module>()->None
1828 -> import pdb; pdb.set_trace()
1829 (Pdb) print(x)
1830 42
1831 (Pdb) continue
1832 TestResults(failed=0, attempted=3)
Jim Fulton356fd192004-08-09 11:34:47 +00001833
Brett Cannon31f59292011-02-21 19:29:56 +00001834 You can also put pdb.set_trace in a function called from a test:
Jim Fulton356fd192004-08-09 11:34:47 +00001835
Brett Cannon31f59292011-02-21 19:29:56 +00001836 >>> def calls_set_trace():
1837 ... y=2
1838 ... import pdb; pdb.set_trace()
Jim Fulton356fd192004-08-09 11:34:47 +00001839
Brett Cannon31f59292011-02-21 19:29:56 +00001840 >>> doc = '''
1841 ... >>> x=1
1842 ... >>> calls_set_trace()
1843 ... '''
1844 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
1845 >>> real_stdin = sys.stdin
1846 >>> sys.stdin = _FakeInput([
1847 ... 'print(y)', # print data defined in the function
1848 ... 'up', # out of function
1849 ... 'print(x)', # print data defined by the example
1850 ... 'continue', # stop debugging
1851 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001852
Brett Cannon31f59292011-02-21 19:29:56 +00001853 >>> try:
1854 ... runner.run(test)
1855 ... finally:
1856 ... sys.stdin = real_stdin
1857 --Return--
1858 > <doctest test.test_doctest.test_pdb_set_trace[8]>(3)calls_set_trace()->None
1859 -> import pdb; pdb.set_trace()
1860 (Pdb) print(y)
1861 2
1862 (Pdb) up
1863 > <doctest foo-bar@baz[1]>(1)<module>()
1864 -> calls_set_trace()
1865 (Pdb) print(x)
1866 1
1867 (Pdb) continue
1868 TestResults(failed=0, attempted=2)
Edward Loper2de91ba2004-08-27 02:07:46 +00001869
Brett Cannon31f59292011-02-21 19:29:56 +00001870 During interactive debugging, source code is shown, even for
1871 doctest examples:
Edward Loper2de91ba2004-08-27 02:07:46 +00001872
Brett Cannon31f59292011-02-21 19:29:56 +00001873 >>> doc = '''
1874 ... >>> def f(x):
1875 ... ... g(x*2)
1876 ... >>> def g(x):
1877 ... ... print(x+3)
1878 ... ... import pdb; pdb.set_trace()
1879 ... >>> f(3)
1880 ... '''
1881 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
1882 >>> real_stdin = sys.stdin
1883 >>> sys.stdin = _FakeInput([
1884 ... 'list', # list source from example 2
1885 ... 'next', # return from g()
1886 ... 'list', # list source from example 1
1887 ... 'next', # return from f()
1888 ... 'list', # list source from example 3
1889 ... 'continue', # stop debugging
1890 ... ''])
1891 >>> try: runner.run(test)
1892 ... finally: sys.stdin = real_stdin
1893 ... # doctest: +NORMALIZE_WHITESPACE
1894 --Return--
1895 > <doctest foo-bar@baz[1]>(3)g()->None
1896 -> import pdb; pdb.set_trace()
1897 (Pdb) list
1898 1 def g(x):
1899 2 print(x+3)
1900 3 -> import pdb; pdb.set_trace()
1901 [EOF]
1902 (Pdb) next
1903 --Return--
1904 > <doctest foo-bar@baz[0]>(2)f()->None
1905 -> g(x*2)
1906 (Pdb) list
1907 1 def f(x):
1908 2 -> g(x*2)
1909 [EOF]
1910 (Pdb) next
1911 --Return--
1912 > <doctest foo-bar@baz[2]>(1)<module>()->None
1913 -> f(3)
1914 (Pdb) list
1915 1 -> f(3)
1916 [EOF]
1917 (Pdb) continue
1918 **********************************************************************
1919 File "foo-bar@baz.py", line 7, in foo-bar@baz
1920 Failed example:
1921 f(3)
1922 Expected nothing
1923 Got:
1924 9
1925 TestResults(failed=1, attempted=3)
1926 """
Jim Fulton356fd192004-08-09 11:34:47 +00001927
Brett Cannon31f59292011-02-21 19:29:56 +00001928 def test_pdb_set_trace_nested():
1929 """This illustrates more-demanding use of set_trace with nested functions.
Tim Peters50c6bdb2004-11-08 22:07:37 +00001930
Brett Cannon31f59292011-02-21 19:29:56 +00001931 >>> class C(object):
1932 ... def calls_set_trace(self):
1933 ... y = 1
1934 ... import pdb; pdb.set_trace()
1935 ... self.f1()
1936 ... y = 2
1937 ... def f1(self):
1938 ... x = 1
1939 ... self.f2()
1940 ... x = 2
1941 ... def f2(self):
1942 ... z = 1
1943 ... z = 2
Tim Peters50c6bdb2004-11-08 22:07:37 +00001944
Brett Cannon31f59292011-02-21 19:29:56 +00001945 >>> calls_set_trace = C().calls_set_trace
Tim Peters50c6bdb2004-11-08 22:07:37 +00001946
Brett Cannon31f59292011-02-21 19:29:56 +00001947 >>> doc = '''
1948 ... >>> a = 1
1949 ... >>> calls_set_trace()
1950 ... '''
1951 >>> parser = doctest.DocTestParser()
1952 >>> runner = doctest.DocTestRunner(verbose=False)
1953 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
1954 >>> real_stdin = sys.stdin
1955 >>> sys.stdin = _FakeInput([
1956 ... 'print(y)', # print data defined in the function
1957 ... 'step', 'step', 'step', 'step', 'step', 'step', 'print(z)',
1958 ... 'up', 'print(x)',
1959 ... 'up', 'print(y)',
1960 ... 'up', 'print(foo)',
1961 ... 'continue', # stop debugging
1962 ... ''])
Tim Peters50c6bdb2004-11-08 22:07:37 +00001963
Brett Cannon31f59292011-02-21 19:29:56 +00001964 >>> try:
1965 ... runner.run(test)
1966 ... finally:
1967 ... sys.stdin = real_stdin
1968 ... # doctest: +REPORT_NDIFF
1969 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
1970 -> self.f1()
1971 (Pdb) print(y)
1972 1
1973 (Pdb) step
1974 --Call--
1975 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(7)f1()
1976 -> def f1(self):
1977 (Pdb) step
1978 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(8)f1()
1979 -> x = 1
1980 (Pdb) step
1981 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
1982 -> self.f2()
1983 (Pdb) step
1984 --Call--
1985 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(11)f2()
1986 -> def f2(self):
1987 (Pdb) step
1988 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(12)f2()
1989 -> z = 1
1990 (Pdb) step
1991 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(13)f2()
1992 -> z = 2
1993 (Pdb) print(z)
1994 1
1995 (Pdb) up
1996 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
1997 -> self.f2()
1998 (Pdb) print(x)
1999 1
2000 (Pdb) up
2001 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
2002 -> self.f1()
2003 (Pdb) print(y)
2004 1
2005 (Pdb) up
2006 > <doctest foo-bar@baz[1]>(1)<module>()
2007 -> calls_set_trace()
2008 (Pdb) print(foo)
2009 *** NameError: name 'foo' is not defined
2010 (Pdb) continue
2011 TestResults(failed=0, attempted=2)
2012 """
Tim Peters50c6bdb2004-11-08 22:07:37 +00002013
Tim Peters19397e52004-08-06 22:02:59 +00002014def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +00002015 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +00002016
2017 We create a Suite by providing a module. A module can be provided
2018 by passing a module object:
2019
2020 >>> import unittest
2021 >>> import test.sample_doctest
2022 >>> suite = doctest.DocTestSuite(test.sample_doctest)
2023 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002024 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00002025
2026 We can also supply the module by name:
2027
2028 >>> suite = doctest.DocTestSuite('test.sample_doctest')
2029 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002030 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00002031
R David Murray5abd76a2012-09-10 10:15:58 -04002032 The module need not contain any doctest examples:
2033
2034 >>> suite = doctest.DocTestSuite('test.sample_doctest_no_doctests')
2035 >>> suite.run(unittest.TestResult())
2036 <unittest.result.TestResult run=0 errors=0 failures=0>
2037
2038 However, if DocTestSuite finds no docstrings, it raises an error:
2039
2040 >>> try:
2041 ... doctest.DocTestSuite('test.sample_doctest_no_docstrings')
2042 ... except ValueError as e:
2043 ... error = e
2044
2045 >>> print(error.args[1])
2046 has no docstrings
2047
2048 You can prevent this error by passing a DocTestFinder instance with
2049 the `exclude_empty` keyword argument set to False:
2050
2051 >>> finder = doctest.DocTestFinder(exclude_empty=False)
2052 >>> suite = doctest.DocTestSuite('test.sample_doctest_no_docstrings',
2053 ... test_finder=finder)
2054 >>> suite.run(unittest.TestResult())
2055 <unittest.result.TestResult run=0 errors=0 failures=0>
2056
Tim Peters19397e52004-08-06 22:02:59 +00002057 We can use the current module:
2058
2059 >>> suite = test.sample_doctest.test_suite()
2060 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002061 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00002062
2063 We can supply global variables. If we pass globs, they will be
2064 used instead of the module globals. Here we'll pass an empty
2065 globals, triggering an extra error:
2066
2067 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
2068 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002069 <unittest.result.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00002070
2071 Alternatively, we can provide extra globals. Here we'll make an
2072 error go away by providing an extra global variable:
2073
2074 >>> suite = doctest.DocTestSuite('test.sample_doctest',
2075 ... extraglobs={'y': 1})
2076 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002077 <unittest.result.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00002078
2079 You can pass option flags. Here we'll cause an extra error
2080 by disabling the blank-line feature:
2081
2082 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00002083 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00002084 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002085 <unittest.result.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00002086
Tim Peters1e277ee2004-08-07 05:37:52 +00002087 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00002088
Jim Fultonf54bad42004-08-28 14:57:56 +00002089 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00002090 ... import test.test_doctest
2091 ... test.test_doctest.sillySetup = True
2092
Jim Fultonf54bad42004-08-28 14:57:56 +00002093 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00002094 ... import test.test_doctest
2095 ... del test.test_doctest.sillySetup
2096
2097 Here, we installed a silly variable that the test expects:
2098
2099 >>> suite = doctest.DocTestSuite('test.sample_doctest',
2100 ... setUp=setUp, tearDown=tearDown)
2101 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002102 <unittest.result.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00002103
2104 But the tearDown restores sanity:
2105
2106 >>> import test.test_doctest
2107 >>> test.test_doctest.sillySetup
2108 Traceback (most recent call last):
2109 ...
2110 AttributeError: 'module' object has no attribute 'sillySetup'
2111
Jim Fultonf54bad42004-08-28 14:57:56 +00002112 The setUp and tearDown funtions are passed test objects. Here
2113 we'll use the setUp function to supply the missing variable y:
2114
2115 >>> def setUp(test):
2116 ... test.globs['y'] = 1
2117
2118 >>> suite = doctest.DocTestSuite('test.sample_doctest', setUp=setUp)
2119 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002120 <unittest.result.TestResult run=9 errors=0 failures=3>
Jim Fultonf54bad42004-08-28 14:57:56 +00002121
2122 Here, we didn't need to use a tearDown function because we
2123 modified the test globals, which are a copy of the
2124 sample_doctest module dictionary. The test globals are
2125 automatically cleared for us after a test.
Tim Peters19397e52004-08-06 22:02:59 +00002126 """
2127
2128def test_DocFileSuite():
2129 """We can test tests found in text files using a DocFileSuite.
2130
2131 We create a suite by providing the names of one or more text
2132 files that include examples:
2133
2134 >>> import unittest
2135 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002136 ... 'test_doctest2.txt',
2137 ... 'test_doctest4.txt')
Tim Peters19397e52004-08-06 22:02:59 +00002138 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002139 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002140
2141 The test files are looked for in the directory containing the
2142 calling module. A package keyword argument can be provided to
2143 specify a different relative location.
2144
2145 >>> import unittest
2146 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2147 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002148 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002149 ... package='test')
2150 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002151 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002152
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002153 Support for using a package's __loader__.get_data() is also
2154 provided.
2155
2156 >>> import unittest, pkgutil, test
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002157 >>> added_loader = False
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002158 >>> if not hasattr(test, '__loader__'):
2159 ... test.__loader__ = pkgutil.get_loader(test)
2160 ... added_loader = True
2161 >>> try:
2162 ... suite = doctest.DocFileSuite('test_doctest.txt',
2163 ... 'test_doctest2.txt',
2164 ... 'test_doctest4.txt',
2165 ... package='test')
2166 ... suite.run(unittest.TestResult())
2167 ... finally:
2168 ... if added_loader:
2169 ... del test.__loader__
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002170 <unittest.result.TestResult run=3 errors=0 failures=2>
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002171
Edward Loper0273f5b2004-09-18 20:27:04 +00002172 '/' should be used as a path separator. It will be converted
2173 to a native separator at run time:
Tim Peters19397e52004-08-06 22:02:59 +00002174
2175 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
2176 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002177 <unittest.result.TestResult run=1 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002178
Edward Loper0273f5b2004-09-18 20:27:04 +00002179 If DocFileSuite is used from an interactive session, then files
2180 are resolved relative to the directory of sys.argv[0]:
2181
Christian Heimes45f9af32007-11-27 21:50:00 +00002182 >>> import types, os.path, test.test_doctest
Edward Loper0273f5b2004-09-18 20:27:04 +00002183 >>> save_argv = sys.argv
2184 >>> sys.argv = [test.test_doctest.__file__]
2185 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Christian Heimes45f9af32007-11-27 21:50:00 +00002186 ... package=types.ModuleType('__main__'))
Edward Loper0273f5b2004-09-18 20:27:04 +00002187 >>> sys.argv = save_argv
2188
Edward Loper052d0cd2004-09-19 17:19:33 +00002189 By setting `module_relative=False`, os-specific paths may be
2190 used (including absolute paths and paths relative to the
2191 working directory):
Edward Loper0273f5b2004-09-18 20:27:04 +00002192
2193 >>> # Get the absolute path of the test package.
2194 >>> test_doctest_path = os.path.abspath(test.test_doctest.__file__)
2195 >>> test_pkg_path = os.path.split(test_doctest_path)[0]
2196
2197 >>> # Use it to find the absolute path of test_doctest.txt.
2198 >>> test_file = os.path.join(test_pkg_path, 'test_doctest.txt')
2199
Edward Loper052d0cd2004-09-19 17:19:33 +00002200 >>> suite = doctest.DocFileSuite(test_file, module_relative=False)
Edward Loper0273f5b2004-09-18 20:27:04 +00002201 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002202 <unittest.result.TestResult run=1 errors=0 failures=1>
Edward Loper0273f5b2004-09-18 20:27:04 +00002203
Edward Loper052d0cd2004-09-19 17:19:33 +00002204 It is an error to specify `package` when `module_relative=False`:
2205
2206 >>> suite = doctest.DocFileSuite(test_file, module_relative=False,
2207 ... package='test')
2208 Traceback (most recent call last):
2209 ValueError: Package may only be specified for module-relative paths.
2210
Tim Peters19397e52004-08-06 22:02:59 +00002211 You can specify initial global variables:
2212
2213 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2214 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002215 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002216 ... globs={'favorite_color': 'blue'})
2217 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002218 <unittest.result.TestResult run=3 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002219
2220 In this case, we supplied a missing favorite color. You can
2221 provide doctest options:
2222
2223 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2224 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002225 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002226 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
2227 ... globs={'favorite_color': 'blue'})
2228 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002229 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002230
2231 And, you can provide setUp and tearDown functions:
2232
Jim Fultonf54bad42004-08-28 14:57:56 +00002233 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00002234 ... import test.test_doctest
2235 ... test.test_doctest.sillySetup = True
2236
Jim Fultonf54bad42004-08-28 14:57:56 +00002237 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00002238 ... import test.test_doctest
2239 ... del test.test_doctest.sillySetup
2240
2241 Here, we installed a silly variable that the test expects:
2242
2243 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2244 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002245 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002246 ... setUp=setUp, tearDown=tearDown)
2247 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002248 <unittest.result.TestResult run=3 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002249
2250 But the tearDown restores sanity:
2251
2252 >>> import test.test_doctest
2253 >>> test.test_doctest.sillySetup
2254 Traceback (most recent call last):
2255 ...
2256 AttributeError: 'module' object has no attribute 'sillySetup'
2257
Jim Fultonf54bad42004-08-28 14:57:56 +00002258 The setUp and tearDown funtions are passed test objects.
2259 Here, we'll use a setUp function to set the favorite color in
2260 test_doctest.txt:
2261
2262 >>> def setUp(test):
2263 ... test.globs['favorite_color'] = 'blue'
2264
2265 >>> suite = doctest.DocFileSuite('test_doctest.txt', setUp=setUp)
2266 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002267 <unittest.result.TestResult run=1 errors=0 failures=0>
Jim Fultonf54bad42004-08-28 14:57:56 +00002268
2269 Here, we didn't need to use a tearDown function because we
2270 modified the test globals. The test globals are
2271 automatically cleared for us after a test.
Tim Petersdf7a2082004-08-29 00:38:17 +00002272
Fred Drake7c404a42004-12-21 23:46:34 +00002273 Tests in a file run using `DocFileSuite` can also access the
2274 `__file__` global, which is set to the name of the file
2275 containing the tests:
2276
2277 >>> suite = doctest.DocFileSuite('test_doctest3.txt')
2278 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002279 <unittest.result.TestResult run=1 errors=0 failures=0>
Fred Drake7c404a42004-12-21 23:46:34 +00002280
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002281 If the tests contain non-ASCII characters, we have to specify which
2282 encoding the file is encoded with. We do so by using the `encoding`
2283 parameter:
2284
2285 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2286 ... 'test_doctest2.txt',
2287 ... 'test_doctest4.txt',
2288 ... encoding='utf-8')
2289 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002290 <unittest.result.TestResult run=3 errors=0 failures=2>
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002291
Jim Fultonf54bad42004-08-28 14:57:56 +00002292 """
Tim Peters19397e52004-08-06 22:02:59 +00002293
Jim Fulton07a349c2004-08-22 14:10:00 +00002294def test_trailing_space_in_test():
2295 """
Tim Petersa7def722004-08-23 22:13:22 +00002296 Trailing spaces in expected output are significant:
Tim Petersc6cbab02004-08-22 19:43:28 +00002297
Jim Fulton07a349c2004-08-22 14:10:00 +00002298 >>> x, y = 'foo', ''
Guido van Rossum7131f842007-02-09 20:13:25 +00002299 >>> print(x, y)
Jim Fulton07a349c2004-08-22 14:10:00 +00002300 foo \n
2301 """
Tim Peters19397e52004-08-06 22:02:59 +00002302
Jim Fultonf54bad42004-08-28 14:57:56 +00002303
2304def test_unittest_reportflags():
2305 """Default unittest reporting flags can be set to control reporting
2306
2307 Here, we'll set the REPORT_ONLY_FIRST_FAILURE option so we see
2308 only the first failure of each test. First, we'll look at the
2309 output without the flag. The file test_doctest.txt file has two
2310 tests. They both fail if blank lines are disabled:
2311
2312 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2313 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
2314 >>> import unittest
2315 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002316 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002317 Traceback ...
2318 Failed example:
2319 favorite_color
2320 ...
2321 Failed example:
2322 if 1:
2323 ...
2324
2325 Note that we see both failures displayed.
2326
2327 >>> old = doctest.set_unittest_reportflags(
2328 ... doctest.REPORT_ONLY_FIRST_FAILURE)
2329
2330 Now, when we run the test:
2331
2332 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002333 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002334 Traceback ...
2335 Failed example:
2336 favorite_color
2337 Exception raised:
2338 ...
2339 NameError: name 'favorite_color' is not defined
2340 <BLANKLINE>
2341 <BLANKLINE>
Tim Petersdf7a2082004-08-29 00:38:17 +00002342
Jim Fultonf54bad42004-08-28 14:57:56 +00002343 We get only the first failure.
2344
2345 If we give any reporting options when we set up the tests,
2346 however:
2347
2348 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2349 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE | doctest.REPORT_NDIFF)
2350
2351 Then the default eporting options are ignored:
2352
2353 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002354 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002355 Traceback ...
2356 Failed example:
2357 favorite_color
2358 ...
2359 Failed example:
2360 if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00002361 print('a')
2362 print()
2363 print('b')
Jim Fultonf54bad42004-08-28 14:57:56 +00002364 Differences (ndiff with -expected +actual):
2365 a
2366 - <BLANKLINE>
2367 +
2368 b
2369 <BLANKLINE>
2370 <BLANKLINE>
2371
2372
2373 Test runners can restore the formatting flags after they run:
2374
2375 >>> ignored = doctest.set_unittest_reportflags(old)
2376
2377 """
2378
Edward Loper052d0cd2004-09-19 17:19:33 +00002379def test_testfile(): r"""
2380Tests for the `testfile()` function. This function runs all the
2381doctest examples in a given file. In its simple invokation, it is
2382called with the name of a file, which is taken to be relative to the
2383calling module. The return value is (#failures, #tests).
2384
Florent Xicluna59250852010-02-27 14:21:57 +00002385We don't want `-v` in sys.argv for these tests.
2386
2387 >>> save_argv = sys.argv
2388 >>> if '-v' in sys.argv:
2389 ... sys.argv = [arg for arg in save_argv if arg != '-v']
2390
2391
Edward Loper052d0cd2004-09-19 17:19:33 +00002392 >>> doctest.testfile('test_doctest.txt') # doctest: +ELLIPSIS
2393 **********************************************************************
2394 File "...", line 6, in test_doctest.txt
2395 Failed example:
2396 favorite_color
2397 Exception raised:
2398 ...
2399 NameError: name 'favorite_color' is not defined
2400 **********************************************************************
2401 1 items had failures:
2402 1 of 2 in test_doctest.txt
2403 ***Test Failed*** 1 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002404 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002405 >>> doctest.master = None # Reset master.
2406
2407(Note: we'll be clearing doctest.master after each call to
Ezio Melotti13925002011-03-16 11:05:33 +02002408`doctest.testfile`, to suppress warnings about multiple tests with the
Edward Loper052d0cd2004-09-19 17:19:33 +00002409same name.)
2410
2411Globals may be specified with the `globs` and `extraglobs` parameters:
2412
2413 >>> globs = {'favorite_color': 'blue'}
2414 >>> doctest.testfile('test_doctest.txt', globs=globs)
Christian Heimes25bb7832008-01-11 16:17:00 +00002415 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002416 >>> doctest.master = None # Reset master.
2417
2418 >>> extraglobs = {'favorite_color': 'red'}
2419 >>> doctest.testfile('test_doctest.txt', globs=globs,
2420 ... extraglobs=extraglobs) # doctest: +ELLIPSIS
2421 **********************************************************************
2422 File "...", line 6, in test_doctest.txt
2423 Failed example:
2424 favorite_color
2425 Expected:
2426 'blue'
2427 Got:
2428 'red'
2429 **********************************************************************
2430 1 items had failures:
2431 1 of 2 in test_doctest.txt
2432 ***Test Failed*** 1 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002433 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002434 >>> doctest.master = None # Reset master.
2435
2436The file may be made relative to a given module or package, using the
2437optional `module_relative` parameter:
2438
2439 >>> doctest.testfile('test_doctest.txt', globs=globs,
2440 ... module_relative='test')
Christian Heimes25bb7832008-01-11 16:17:00 +00002441 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002442 >>> doctest.master = None # Reset master.
2443
Ezio Melotti13925002011-03-16 11:05:33 +02002444Verbosity can be increased with the optional `verbose` parameter:
Edward Loper052d0cd2004-09-19 17:19:33 +00002445
2446 >>> doctest.testfile('test_doctest.txt', globs=globs, verbose=True)
2447 Trying:
2448 favorite_color
2449 Expecting:
2450 'blue'
2451 ok
2452 Trying:
2453 if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00002454 print('a')
2455 print()
2456 print('b')
Edward Loper052d0cd2004-09-19 17:19:33 +00002457 Expecting:
2458 a
2459 <BLANKLINE>
2460 b
2461 ok
2462 1 items passed all tests:
2463 2 tests in test_doctest.txt
2464 2 tests in 1 items.
2465 2 passed and 0 failed.
2466 Test passed.
Christian Heimes25bb7832008-01-11 16:17:00 +00002467 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002468 >>> doctest.master = None # Reset master.
2469
2470The name of the test may be specified with the optional `name`
2471parameter:
2472
2473 >>> doctest.testfile('test_doctest.txt', name='newname')
2474 ... # doctest: +ELLIPSIS
2475 **********************************************************************
2476 File "...", line 6, in newname
2477 ...
Christian Heimes25bb7832008-01-11 16:17:00 +00002478 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002479 >>> doctest.master = None # Reset master.
2480
Ezio Melotti13925002011-03-16 11:05:33 +02002481The summary report may be suppressed with the optional `report`
Edward Loper052d0cd2004-09-19 17:19:33 +00002482parameter:
2483
2484 >>> doctest.testfile('test_doctest.txt', report=False)
2485 ... # doctest: +ELLIPSIS
2486 **********************************************************************
2487 File "...", line 6, in test_doctest.txt
2488 Failed example:
2489 favorite_color
2490 Exception raised:
2491 ...
2492 NameError: name 'favorite_color' is not defined
Christian Heimes25bb7832008-01-11 16:17:00 +00002493 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002494 >>> doctest.master = None # Reset master.
2495
2496The optional keyword argument `raise_on_error` can be used to raise an
2497exception on the first error (which may be useful for postmortem
2498debugging):
2499
2500 >>> doctest.testfile('test_doctest.txt', raise_on_error=True)
2501 ... # doctest: +ELLIPSIS
2502 Traceback (most recent call last):
Guido van Rossum6a2a2a02006-08-26 20:37:44 +00002503 doctest.UnexpectedException: ...
Edward Loper052d0cd2004-09-19 17:19:33 +00002504 >>> doctest.master = None # Reset master.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002505
2506If the tests contain non-ASCII characters, the tests might fail, since
2507it's unknown which encoding is used. The encoding can be specified
2508using the optional keyword argument `encoding`:
2509
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002510 >>> doctest.testfile('test_doctest4.txt', encoding='latin-1') # doctest: +ELLIPSIS
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002511 **********************************************************************
2512 File "...", line 7, in test_doctest4.txt
2513 Failed example:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002514 '...'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002515 Expected:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002516 'f\xf6\xf6'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002517 Got:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002518 'f\xc3\xb6\xc3\xb6'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002519 **********************************************************************
2520 ...
2521 **********************************************************************
2522 1 items had failures:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002523 2 of 2 in test_doctest4.txt
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002524 ***Test Failed*** 2 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002525 TestResults(failed=2, attempted=2)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002526 >>> doctest.master = None # Reset master.
2527
2528 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8')
Christian Heimes25bb7832008-01-11 16:17:00 +00002529 TestResults(failed=0, attempted=2)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002530 >>> doctest.master = None # Reset master.
Florent Xicluna59250852010-02-27 14:21:57 +00002531
2532Test the verbose output:
2533
2534 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8', verbose=True)
2535 Trying:
2536 'föö'
2537 Expecting:
2538 'f\xf6\xf6'
2539 ok
2540 Trying:
2541 'bąr'
2542 Expecting:
2543 'b\u0105r'
2544 ok
2545 1 items passed all tests:
2546 2 tests in test_doctest4.txt
2547 2 tests in 1 items.
2548 2 passed and 0 failed.
2549 Test passed.
2550 TestResults(failed=0, attempted=2)
2551 >>> doctest.master = None # Reset master.
2552 >>> sys.argv = save_argv
Edward Loper052d0cd2004-09-19 17:19:33 +00002553"""
2554
R. David Murray58641de2009-06-12 15:33:19 +00002555def test_testmod(): r"""
2556Tests for the testmod function. More might be useful, but for now we're just
2557testing the case raised by Issue 6195, where trying to doctest a C module would
2558fail with a UnicodeDecodeError because doctest tried to read the "source" lines
2559out of the binary module.
2560
2561 >>> import unicodedata
Florent Xicluna59250852010-02-27 14:21:57 +00002562 >>> doctest.testmod(unicodedata, verbose=False)
R. David Murray58641de2009-06-12 15:33:19 +00002563 TestResults(failed=0, attempted=0)
2564"""
2565
Victor Stinner9d396392010-10-16 21:54:59 +00002566try:
2567 os.fsencode("foo-bär@baz.py")
2568except UnicodeEncodeError:
2569 # Skip the test: the filesystem encoding is unable to encode the filename
2570 pass
2571else:
2572 def test_unicode(): """
2573Check doctest with a non-ascii filename:
2574
2575 >>> doc = '''
2576 ... >>> raise Exception('clé')
2577 ... '''
2578 ...
2579 >>> parser = doctest.DocTestParser()
2580 >>> test = parser.get_doctest(doc, {}, "foo-bär@baz", "foo-bär@baz.py", 0)
2581 >>> test
2582 <DocTest foo-bär@baz from foo-bär@baz.py:0 (1 example)>
2583 >>> runner = doctest.DocTestRunner(verbose=False)
2584 >>> runner.run(test) # doctest: +ELLIPSIS
2585 **********************************************************************
2586 File "foo-bär@baz.py", line 2, in foo-bär@baz
2587 Failed example:
2588 raise Exception('clé')
2589 Exception raised:
2590 Traceback (most recent call last):
2591 File ...
2592 compileflags, 1), test.globs)
2593 File "<doctest foo-bär@baz[0]>", line 1, in <module>
2594 raise Exception('clé')
2595 Exception: clé
2596 TestResults(failed=1, attempted=1)
2597 """
2598
Tim Peters8485b562004-08-04 18:46:34 +00002599######################################################################
2600## Main
2601######################################################################
2602
2603def test_main():
2604 # Check the doctest cases in doctest itself:
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002605 support.run_doctest(doctest, verbosity=True)
Tim Peters8485b562004-08-04 18:46:34 +00002606 # Check the doctest cases defined here:
2607 from test import test_doctest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002608 support.run_doctest(test_doctest, verbosity=True)
Tim Peters8485b562004-08-04 18:46:34 +00002609
Victor Stinner45df8202010-04-28 22:31:17 +00002610import sys, re, io
2611
Tim Peters8485b562004-08-04 18:46:34 +00002612def test_coverage(coverdir):
Victor Stinner45df8202010-04-28 22:31:17 +00002613 trace = support.import_module('trace')
Vinay Sajip7ded1f02012-05-26 03:45:29 +01002614 tracer = trace.Trace(ignoredirs=[sys.base_prefix, sys.base_exec_prefix,],
Tim Peters8485b562004-08-04 18:46:34 +00002615 trace=0, count=1)
Guido van Rossume7ba4952007-06-06 23:52:48 +00002616 tracer.run('test_main()')
Tim Peters8485b562004-08-04 18:46:34 +00002617 r = tracer.results()
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002618 print('Writing coverage results...')
Tim Peters8485b562004-08-04 18:46:34 +00002619 r.write_results(show_missing=True, summary=True,
2620 coverdir=coverdir)
2621
2622if __name__ == '__main__':
2623 if '-c' in sys.argv:
2624 test_coverage('/tmp/doctest.cover')
2625 else:
2626 test_main()