blob: cd871790d53ddcc2c5ed331abb67c9659ac8354c [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'
Tim Peters8485b562004-08-04 18:46:34 +0000262"""
263
264def test_DocTest(): r"""
265Unit tests for the `DocTest` class.
266
267DocTest is a collection of examples, extracted from a docstring, along
268with information about where the docstring comes from (a name,
269filename, and line number). The docstring is parsed by the `DocTest`
270constructor:
271
272 >>> docstring = '''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000273 ... >>> print(12)
Tim Peters8485b562004-08-04 18:46:34 +0000274 ... 12
275 ...
276 ... Non-example text.
277 ...
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000278 ... >>> print('another\example')
Tim Peters8485b562004-08-04 18:46:34 +0000279 ... another
280 ... example
281 ... '''
282 >>> globs = {} # globals to run the test in.
Edward Lopera1ef6112004-08-09 16:14:41 +0000283 >>> parser = doctest.DocTestParser()
284 >>> test = parser.get_doctest(docstring, globs, 'some_test',
285 ... 'some_file', 20)
Guido van Rossum7131f842007-02-09 20:13:25 +0000286 >>> print(test)
Tim Peters8485b562004-08-04 18:46:34 +0000287 <DocTest some_test from some_file:20 (2 examples)>
288 >>> len(test.examples)
289 2
290 >>> e1, e2 = test.examples
291 >>> (e1.source, e1.want, e1.lineno)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000292 ('print(12)\n', '12\n', 1)
Tim Peters8485b562004-08-04 18:46:34 +0000293 >>> (e2.source, e2.want, e2.lineno)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000294 ("print('another\\example')\n", 'another\nexample\n', 6)
Tim Peters8485b562004-08-04 18:46:34 +0000295
296Source information (name, filename, and line number) is available as
297attributes on the doctest object:
298
299 >>> (test.name, test.filename, test.lineno)
300 ('some_test', 'some_file', 20)
301
302The line number of an example within its containing file is found by
303adding the line number of the example and the line number of its
304containing test:
305
306 >>> test.lineno + e1.lineno
307 21
308 >>> test.lineno + e2.lineno
309 26
310
311If the docstring contains inconsistant leading whitespace in the
312expected output of an example, then `DocTest` will raise a ValueError:
313
314 >>> docstring = r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000315 ... >>> print('bad\nindentation')
Tim Peters8485b562004-08-04 18:46:34 +0000316 ... bad
317 ... indentation
318 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000319 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000320 Traceback (most recent call last):
Edward Loper00f8da72004-08-26 18:05:07 +0000321 ValueError: line 4 of the docstring for some_test has inconsistent leading whitespace: 'indentation'
Tim Peters8485b562004-08-04 18:46:34 +0000322
323If the docstring contains inconsistent leading whitespace on
324continuation lines, then `DocTest` will raise a ValueError:
325
326 >>> docstring = r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000327 ... >>> print(('bad indentation',
328 ... ... 2))
Tim Peters8485b562004-08-04 18:46:34 +0000329 ... ('bad', 'indentation')
330 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000331 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000332 Traceback (most recent call last):
Guido van Rossume0192e52007-02-09 23:39:59 +0000333 ValueError: line 2 of the docstring for some_test has inconsistent leading whitespace: '... 2))'
Tim Peters8485b562004-08-04 18:46:34 +0000334
335If there's no blank space after a PS1 prompt ('>>>'), then `DocTest`
336will raise a ValueError:
337
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000338 >>> docstring = '>>>print(1)\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000339 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000340 Traceback (most recent call last):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000341 ValueError: line 1 of the docstring for some_test lacks blank after >>>: '>>>print(1)'
Edward Loper7c748462004-08-09 02:06:06 +0000342
343If there's no blank space after a PS2 prompt ('...'), then `DocTest`
344will raise a ValueError:
345
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000346 >>> docstring = '>>> if 1:\n...print(1)\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000347 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Edward Loper7c748462004-08-09 02:06:06 +0000348 Traceback (most recent call last):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000349 ValueError: line 2 of the docstring for some_test lacks blank after ...: '...print(1)'
Edward Loper7c748462004-08-09 02:06:06 +0000350
Tim Peters8485b562004-08-04 18:46:34 +0000351"""
352
Tim Peters8485b562004-08-04 18:46:34 +0000353def test_DocTestFinder(): r"""
354Unit tests for the `DocTestFinder` class.
355
356DocTestFinder is used to extract DocTests from an object's docstring
357and the docstrings of its contained objects. It can be used with
358modules, functions, classes, methods, staticmethods, classmethods, and
359properties.
360
361Finding Tests in Functions
362~~~~~~~~~~~~~~~~~~~~~~~~~~
363For a function whose docstring contains examples, DocTestFinder.find()
364will return a single test (for that function's docstring):
365
Tim Peters8485b562004-08-04 18:46:34 +0000366 >>> finder = doctest.DocTestFinder()
Jim Fulton07a349c2004-08-22 14:10:00 +0000367
368We'll simulate a __file__ attr that ends in pyc:
369
370 >>> import test.test_doctest
371 >>> old = test.test_doctest.__file__
372 >>> test.test_doctest.__file__ = 'test_doctest.pyc'
373
Tim Peters8485b562004-08-04 18:46:34 +0000374 >>> tests = finder.find(sample_func)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000375
Guido van Rossum7131f842007-02-09 20:13:25 +0000376 >>> print(tests) # doctest: +ELLIPSIS
Brett Cannon31f59292011-02-21 19:29:56 +0000377 [<DocTest sample_func from ...:18 (1 example)>]
Edward Loper8e4a34b2004-08-12 02:34:27 +0000378
Tim Peters4de7c5c2004-08-23 22:38:05 +0000379The exact name depends on how test_doctest was invoked, so allow for
380leading path components.
381
382 >>> tests[0].filename # doctest: +ELLIPSIS
383 '...test_doctest.py'
Jim Fulton07a349c2004-08-22 14:10:00 +0000384
385 >>> test.test_doctest.__file__ = old
Tim Petersc6cbab02004-08-22 19:43:28 +0000386
Jim Fulton07a349c2004-08-22 14:10:00 +0000387
Tim Peters8485b562004-08-04 18:46:34 +0000388 >>> e = tests[0].examples[0]
Tim Petersbb431472004-08-09 03:51:46 +0000389 >>> (e.source, e.want, e.lineno)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000390 ('print(sample_func(22))\n', '44\n', 3)
Tim Peters8485b562004-08-04 18:46:34 +0000391
Edward Loper32ddbf72004-09-13 05:47:24 +0000392By default, tests are created for objects with no docstring:
Tim Peters8485b562004-08-04 18:46:34 +0000393
394 >>> def no_docstring(v):
395 ... pass
Tim Peters958cc892004-09-13 14:53:28 +0000396 >>> finder.find(no_docstring)
397 []
Edward Loper32ddbf72004-09-13 05:47:24 +0000398
399However, the optional argument `exclude_empty` to the DocTestFinder
400constructor can be used to exclude tests for objects with empty
401docstrings:
402
403 >>> def no_docstring(v):
404 ... pass
405 >>> excl_empty_finder = doctest.DocTestFinder(exclude_empty=True)
406 >>> excl_empty_finder.find(no_docstring)
Tim Peters8485b562004-08-04 18:46:34 +0000407 []
408
409If the function has a docstring with no examples, then a test with no
410examples is returned. (This lets `DocTestRunner` collect statistics
411about which functions have no tests -- but is that useful? And should
412an empty test also be created when there's no docstring?)
413
414 >>> def no_examples(v):
415 ... ''' no doctest examples '''
Tim Peters17b56372004-09-11 17:33:27 +0000416 >>> finder.find(no_examples) # doctest: +ELLIPSIS
417 [<DocTest no_examples from ...:1 (no examples)>]
Tim Peters8485b562004-08-04 18:46:34 +0000418
419Finding Tests in Classes
420~~~~~~~~~~~~~~~~~~~~~~~~
421For a class, DocTestFinder will create a test for the class's
422docstring, and will recursively explore its contents, including
423methods, classmethods, staticmethods, properties, and nested classes.
424
425 >>> finder = doctest.DocTestFinder()
426 >>> tests = finder.find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000427 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000428 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000429 3 SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000430 3 SampleClass.NestedClass
431 1 SampleClass.NestedClass.__init__
432 1 SampleClass.__init__
433 2 SampleClass.a_classmethod
434 1 SampleClass.a_property
435 1 SampleClass.a_staticmethod
436 1 SampleClass.double
437 1 SampleClass.get
438
439New-style classes are also supported:
440
441 >>> tests = finder.find(SampleNewStyleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000442 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000443 ... print('%2s %s' % (len(t.examples), t.name))
Tim Peters8485b562004-08-04 18:46:34 +0000444 1 SampleNewStyleClass
445 1 SampleNewStyleClass.__init__
446 1 SampleNewStyleClass.double
447 1 SampleNewStyleClass.get
448
449Finding Tests in Modules
450~~~~~~~~~~~~~~~~~~~~~~~~
451For a module, DocTestFinder will create a test for the class's
452docstring, and will recursively explore its contents, including
453functions, classes, and the `__test__` dictionary, if it exists:
454
455 >>> # A module
Christian Heimes45f9af32007-11-27 21:50:00 +0000456 >>> import types
457 >>> m = types.ModuleType('some_module')
Tim Peters8485b562004-08-04 18:46:34 +0000458 >>> def triple(val):
459 ... '''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000460 ... >>> print(triple(11))
Tim Peters8485b562004-08-04 18:46:34 +0000461 ... 33
462 ... '''
463 ... return val*3
464 >>> m.__dict__.update({
465 ... 'sample_func': sample_func,
466 ... 'SampleClass': SampleClass,
467 ... '__doc__': '''
468 ... Module docstring.
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000469 ... >>> print('module')
Tim Peters8485b562004-08-04 18:46:34 +0000470 ... module
471 ... ''',
472 ... '__test__': {
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000473 ... 'd': '>>> print(6)\n6\n>>> print(7)\n7\n',
Tim Peters8485b562004-08-04 18:46:34 +0000474 ... 'c': triple}})
475
476 >>> finder = doctest.DocTestFinder()
477 >>> # Use module=test.test_doctest, to prevent doctest from
478 >>> # ignoring the objects since they weren't defined in m.
479 >>> import test.test_doctest
480 >>> tests = finder.find(m, module=test.test_doctest)
Tim Peters8485b562004-08-04 18:46:34 +0000481 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000482 ... print('%2s %s' % (len(t.examples), t.name))
Tim Peters8485b562004-08-04 18:46:34 +0000483 1 some_module
Edward Loper4ae900f2004-09-21 03:20:34 +0000484 3 some_module.SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000485 3 some_module.SampleClass.NestedClass
486 1 some_module.SampleClass.NestedClass.__init__
487 1 some_module.SampleClass.__init__
488 2 some_module.SampleClass.a_classmethod
489 1 some_module.SampleClass.a_property
490 1 some_module.SampleClass.a_staticmethod
491 1 some_module.SampleClass.double
492 1 some_module.SampleClass.get
Tim Petersc5684782004-09-13 01:07:12 +0000493 1 some_module.__test__.c
494 2 some_module.__test__.d
Tim Peters8485b562004-08-04 18:46:34 +0000495 1 some_module.sample_func
496
497Duplicate Removal
498~~~~~~~~~~~~~~~~~
499If a single object is listed twice (under different names), then tests
500will only be generated for it once:
501
Tim Petersf3f57472004-08-08 06:11:48 +0000502 >>> from test import doctest_aliases
Benjamin Peterson78565b22009-06-28 19:19:51 +0000503 >>> assert doctest_aliases.TwoNames.f
504 >>> assert doctest_aliases.TwoNames.g
Edward Loper32ddbf72004-09-13 05:47:24 +0000505 >>> tests = excl_empty_finder.find(doctest_aliases)
Guido van Rossum7131f842007-02-09 20:13:25 +0000506 >>> print(len(tests))
Tim Peters8485b562004-08-04 18:46:34 +0000507 2
Guido van Rossum7131f842007-02-09 20:13:25 +0000508 >>> print(tests[0].name)
Tim Petersf3f57472004-08-08 06:11:48 +0000509 test.doctest_aliases.TwoNames
510
511 TwoNames.f and TwoNames.g are bound to the same object.
512 We can't guess which will be found in doctest's traversal of
513 TwoNames.__dict__ first, so we have to allow for either.
514
515 >>> tests[1].name.split('.')[-1] in ['f', 'g']
Tim Peters8485b562004-08-04 18:46:34 +0000516 True
517
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000518Empty Tests
519~~~~~~~~~~~
520By default, an object with no doctests doesn't create any tests:
Tim Peters8485b562004-08-04 18:46:34 +0000521
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000522 >>> tests = doctest.DocTestFinder().find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000523 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000524 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000525 3 SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000526 3 SampleClass.NestedClass
527 1 SampleClass.NestedClass.__init__
Tim Peters958cc892004-09-13 14:53:28 +0000528 1 SampleClass.__init__
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000529 2 SampleClass.a_classmethod
530 1 SampleClass.a_property
531 1 SampleClass.a_staticmethod
Tim Peters958cc892004-09-13 14:53:28 +0000532 1 SampleClass.double
533 1 SampleClass.get
534
535By default, that excluded objects with no doctests. exclude_empty=False
536tells it to include (empty) tests for objects with no doctests. This feature
537is really to support backward compatibility in what doctest.master.summarize()
538displays.
539
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000540 >>> tests = doctest.DocTestFinder(exclude_empty=False).find(SampleClass)
Tim Peters958cc892004-09-13 14:53:28 +0000541 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000542 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000543 3 SampleClass
Tim Peters958cc892004-09-13 14:53:28 +0000544 3 SampleClass.NestedClass
545 1 SampleClass.NestedClass.__init__
Edward Loper32ddbf72004-09-13 05:47:24 +0000546 0 SampleClass.NestedClass.get
547 0 SampleClass.NestedClass.square
Tim Peters8485b562004-08-04 18:46:34 +0000548 1 SampleClass.__init__
Tim Peters8485b562004-08-04 18:46:34 +0000549 2 SampleClass.a_classmethod
550 1 SampleClass.a_property
551 1 SampleClass.a_staticmethod
552 1 SampleClass.double
553 1 SampleClass.get
554
Tim Peters8485b562004-08-04 18:46:34 +0000555Turning off Recursion
556~~~~~~~~~~~~~~~~~~~~~
557DocTestFinder can be told not to look for tests in contained objects
558using the `recurse` flag:
559
560 >>> tests = doctest.DocTestFinder(recurse=False).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000561 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000562 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000563 3 SampleClass
Edward Loperb51b2342004-08-17 16:37:12 +0000564
565Line numbers
566~~~~~~~~~~~~
567DocTestFinder finds the line number of each example:
568
569 >>> def f(x):
570 ... '''
571 ... >>> x = 12
572 ...
573 ... some text
574 ...
575 ... >>> # examples are not created for comments & bare prompts.
576 ... >>>
577 ... ...
578 ...
579 ... >>> for x in range(10):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000580 ... ... print(x, end=' ')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000581 ... 0 1 2 3 4 5 6 7 8 9
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000582 ... >>> x//2
583 ... 6
Edward Loperb51b2342004-08-17 16:37:12 +0000584 ... '''
585 >>> test = doctest.DocTestFinder().find(f)[0]
586 >>> [e.lineno for e in test.examples]
587 [1, 9, 12]
Tim Peters8485b562004-08-04 18:46:34 +0000588"""
589
Edward Loper00f8da72004-08-26 18:05:07 +0000590def test_DocTestParser(): r"""
591Unit tests for the `DocTestParser` class.
592
593DocTestParser is used to parse docstrings containing doctest examples.
594
595The `parse` method divides a docstring into examples and intervening
596text:
597
598 >>> s = '''
599 ... >>> x, y = 2, 3 # no output expected
600 ... >>> if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000601 ... ... print(x)
602 ... ... print(y)
Edward Loper00f8da72004-08-26 18:05:07 +0000603 ... 2
604 ... 3
605 ...
606 ... Some text.
607 ... >>> x+y
608 ... 5
609 ... '''
610 >>> parser = doctest.DocTestParser()
611 >>> for piece in parser.parse(s):
612 ... if isinstance(piece, doctest.Example):
Guido van Rossum7131f842007-02-09 20:13:25 +0000613 ... print('Example:', (piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000614 ... else:
Guido van Rossum7131f842007-02-09 20:13:25 +0000615 ... print(' Text:', repr(piece))
Edward Loper00f8da72004-08-26 18:05:07 +0000616 Text: '\n'
617 Example: ('x, y = 2, 3 # no output expected\n', '', 1)
618 Text: ''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000619 Example: ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000620 Text: '\nSome text.\n'
621 Example: ('x+y\n', '5\n', 9)
622 Text: ''
623
624The `get_examples` method returns just the examples:
625
626 >>> for piece in parser.get_examples(s):
Guido van Rossum7131f842007-02-09 20:13:25 +0000627 ... print((piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000628 ('x, y = 2, 3 # no output expected\n', '', 1)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000629 ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000630 ('x+y\n', '5\n', 9)
631
632The `get_doctest` method creates a Test from the examples, along with the
633given arguments:
634
635 >>> test = parser.get_doctest(s, {}, 'name', 'filename', lineno=5)
636 >>> (test.name, test.filename, test.lineno)
637 ('name', 'filename', 5)
638 >>> for piece in test.examples:
Guido van Rossum7131f842007-02-09 20:13:25 +0000639 ... print((piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000640 ('x, y = 2, 3 # no output expected\n', '', 1)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000641 ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000642 ('x+y\n', '5\n', 9)
643"""
644
Tim Peters8485b562004-08-04 18:46:34 +0000645class test_DocTestRunner:
646 def basics(): r"""
647Unit tests for the `DocTestRunner` class.
648
649DocTestRunner is used to run DocTest test cases, and to accumulate
650statistics. Here's a simple DocTest case we can use:
651
652 >>> def f(x):
653 ... '''
654 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000655 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000656 ... 12
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000657 ... >>> x//2
658 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000659 ... '''
660 >>> test = doctest.DocTestFinder().find(f)[0]
661
662The main DocTestRunner interface is the `run` method, which runs a
663given DocTest case in a given namespace (globs). It returns a tuple
664`(f,t)`, where `f` is the number of failed tests and `t` is the number
665of tried tests.
666
667 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000668 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000669
670If any example produces incorrect output, then the test runner reports
671the failure and proceeds to the next example:
672
673 >>> def f(x):
674 ... '''
675 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000676 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000677 ... 14
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000678 ... >>> x//2
679 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000680 ... '''
681 >>> test = doctest.DocTestFinder().find(f)[0]
682 >>> doctest.DocTestRunner(verbose=True).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000683 ... # doctest: +ELLIPSIS
Edward Loperaacf0832004-08-26 01:19:50 +0000684 Trying:
685 x = 12
686 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000687 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000688 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000689 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000690 Expecting:
691 14
Tim Peters8485b562004-08-04 18:46:34 +0000692 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000693 File ..., line 4, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000694 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000695 print(x)
Jim Fulton07a349c2004-08-22 14:10:00 +0000696 Expected:
697 14
698 Got:
699 12
Edward Loperaacf0832004-08-26 01:19:50 +0000700 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000701 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000702 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000703 6
Tim Peters8485b562004-08-04 18:46:34 +0000704 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000705 TestResults(failed=1, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000706"""
707 def verbose_flag(): r"""
708The `verbose` flag makes the test runner generate more detailed
709output:
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
721 >>> doctest.DocTestRunner(verbose=True).run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000722 Trying:
723 x = 12
724 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000725 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000726 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000727 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000728 Expecting:
729 12
Tim Peters8485b562004-08-04 18:46:34 +0000730 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000731 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000732 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000733 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000734 6
Tim Peters8485b562004-08-04 18:46:34 +0000735 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000736 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000737
738If the `verbose` flag is unspecified, then the output will be verbose
739iff `-v` appears in sys.argv:
740
741 >>> # Save the real sys.argv list.
742 >>> old_argv = sys.argv
743
744 >>> # If -v does not appear in sys.argv, then output isn't verbose.
745 >>> sys.argv = ['test']
746 >>> doctest.DocTestRunner().run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000747 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000748
749 >>> # If -v does appear in sys.argv, then output is verbose.
750 >>> sys.argv = ['test', '-v']
751 >>> doctest.DocTestRunner().run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000752 Trying:
753 x = 12
754 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000755 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000756 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000757 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000758 Expecting:
759 12
Tim Peters8485b562004-08-04 18:46:34 +0000760 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000761 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000762 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000763 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000764 6
Tim Peters8485b562004-08-04 18:46:34 +0000765 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000766 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000767
768 >>> # Restore sys.argv
769 >>> sys.argv = old_argv
770
771In the remaining examples, the test runner's verbosity will be
772explicitly set, to ensure that the test behavior is consistent.
773 """
774 def exceptions(): r"""
775Tests of `DocTestRunner`'s exception handling.
776
777An expected exception is specified with a traceback message. The
778lines between the first line and the type/value may be omitted or
779replaced with any other string:
780
781 >>> def f(x):
782 ... '''
783 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000784 ... >>> print(x//0)
Tim Peters8485b562004-08-04 18:46:34 +0000785 ... Traceback (most recent call last):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000786 ... ZeroDivisionError: integer division or modulo by zero
Tim Peters8485b562004-08-04 18:46:34 +0000787 ... '''
788 >>> test = doctest.DocTestFinder().find(f)[0]
789 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000790 TestResults(failed=0, attempted=2)
Tim Peters8485b562004-08-04 18:46:34 +0000791
Edward Loper19b19582004-08-25 23:07:03 +0000792An example may not generate output before it raises an exception; if
793it does, then the traceback message will not be recognized as
794signaling an expected exception, so the example will be reported as an
795unexpected exception:
Tim Peters8485b562004-08-04 18:46:34 +0000796
797 >>> def f(x):
798 ... '''
799 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000800 ... >>> print('pre-exception output', x//0)
Tim Peters8485b562004-08-04 18:46:34 +0000801 ... pre-exception output
802 ... Traceback (most recent call last):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000803 ... ZeroDivisionError: integer division or modulo by zero
Tim Peters8485b562004-08-04 18:46:34 +0000804 ... '''
805 >>> test = doctest.DocTestFinder().find(f)[0]
806 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper19b19582004-08-25 23:07:03 +0000807 ... # doctest: +ELLIPSIS
808 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000809 File ..., line 4, in f
Edward Loper19b19582004-08-25 23:07:03 +0000810 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000811 print('pre-exception output', x//0)
Edward Loper19b19582004-08-25 23:07:03 +0000812 Exception raised:
813 ...
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000814 ZeroDivisionError: integer division or modulo by zero
Christian Heimes25bb7832008-01-11 16:17:00 +0000815 TestResults(failed=1, attempted=2)
Tim Peters8485b562004-08-04 18:46:34 +0000816
817Exception messages may contain newlines:
818
819 >>> def f(x):
820 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000821 ... >>> raise ValueError('multi\nline\nmessage')
Tim Peters8485b562004-08-04 18:46:34 +0000822 ... Traceback (most recent call last):
823 ... ValueError: multi
824 ... line
825 ... message
826 ... '''
827 >>> test = doctest.DocTestFinder().find(f)[0]
828 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000829 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000830
831If an exception is expected, but an exception with the wrong type or
832message is raised, then it is reported as a failure:
833
834 >>> def f(x):
835 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000836 ... >>> raise ValueError('message')
Tim Peters8485b562004-08-04 18:46:34 +0000837 ... Traceback (most recent call last):
838 ... ValueError: wrong message
839 ... '''
840 >>> test = doctest.DocTestFinder().find(f)[0]
841 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000842 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000843 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000844 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000845 Failed example:
Collin Winter3add4d72007-08-29 23:37:32 +0000846 raise ValueError('message')
Tim Peters8485b562004-08-04 18:46:34 +0000847 Expected:
848 Traceback (most recent call last):
849 ValueError: wrong message
850 Got:
851 Traceback (most recent call last):
Edward Loper8e4a34b2004-08-12 02:34:27 +0000852 ...
Tim Peters8485b562004-08-04 18:46:34 +0000853 ValueError: message
Christian Heimes25bb7832008-01-11 16:17:00 +0000854 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000855
Tim Peters1fbf9c52004-09-04 17:21:02 +0000856However, IGNORE_EXCEPTION_DETAIL can be used to allow a mismatch in the
857detail:
858
859 >>> def f(x):
860 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000861 ... >>> raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +0000862 ... Traceback (most recent call last):
863 ... ValueError: wrong message
864 ... '''
865 >>> test = doctest.DocTestFinder().find(f)[0]
866 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000867 TestResults(failed=0, attempted=1)
Tim Peters1fbf9c52004-09-04 17:21:02 +0000868
Nick Coghlan5e76e942010-06-12 13:42:46 +0000869IGNORE_EXCEPTION_DETAIL also ignores difference in exception formatting
870between Python versions. For example, in Python 2.x, the module path of
871the exception is not in the output, but this will fail under Python 3:
872
873 >>> def f(x):
874 ... r'''
875 ... >>> from http.client import HTTPException
876 ... >>> raise HTTPException('message')
877 ... Traceback (most recent call last):
878 ... HTTPException: message
879 ... '''
880 >>> test = doctest.DocTestFinder().find(f)[0]
881 >>> doctest.DocTestRunner(verbose=False).run(test)
882 ... # doctest: +ELLIPSIS
883 **********************************************************************
884 File ..., line 4, in f
885 Failed example:
886 raise HTTPException('message')
887 Expected:
888 Traceback (most recent call last):
889 HTTPException: message
890 Got:
891 Traceback (most recent call last):
892 ...
893 http.client.HTTPException: message
894 TestResults(failed=1, attempted=2)
895
896But in Python 3 the module path is included, and therefore a test must look
897like the following test to succeed in Python 3. But that test will fail under
898Python 2.
899
900 >>> def f(x):
901 ... r'''
902 ... >>> from http.client import HTTPException
903 ... >>> raise HTTPException('message')
904 ... Traceback (most recent call last):
905 ... http.client.HTTPException: message
906 ... '''
907 >>> test = doctest.DocTestFinder().find(f)[0]
908 >>> doctest.DocTestRunner(verbose=False).run(test)
909 TestResults(failed=0, attempted=2)
910
911However, with IGNORE_EXCEPTION_DETAIL, the module name of the exception
912(or its unexpected absence) will be ignored:
913
914 >>> def f(x):
915 ... r'''
916 ... >>> from http.client import HTTPException
917 ... >>> raise HTTPException('message') #doctest: +IGNORE_EXCEPTION_DETAIL
918 ... Traceback (most recent call last):
919 ... HTTPException: message
920 ... '''
921 >>> test = doctest.DocTestFinder().find(f)[0]
922 >>> doctest.DocTestRunner(verbose=False).run(test)
923 TestResults(failed=0, attempted=2)
924
925The module path will be completely ignored, so two different module paths will
926still pass if IGNORE_EXCEPTION_DETAIL is given. This is intentional, so it can
927be used when exceptions have changed module.
928
929 >>> def f(x):
930 ... r'''
931 ... >>> from http.client import HTTPException
932 ... >>> raise HTTPException('message') #doctest: +IGNORE_EXCEPTION_DETAIL
933 ... Traceback (most recent call last):
934 ... foo.bar.HTTPException: message
935 ... '''
936 >>> test = doctest.DocTestFinder().find(f)[0]
937 >>> doctest.DocTestRunner(verbose=False).run(test)
938 TestResults(failed=0, attempted=2)
939
Tim Peters1fbf9c52004-09-04 17:21:02 +0000940But IGNORE_EXCEPTION_DETAIL does not allow a mismatch in the exception type:
941
942 >>> def f(x):
943 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000944 ... >>> raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +0000945 ... Traceback (most recent call last):
946 ... TypeError: wrong type
947 ... '''
948 >>> test = doctest.DocTestFinder().find(f)[0]
949 >>> doctest.DocTestRunner(verbose=False).run(test)
950 ... # doctest: +ELLIPSIS
951 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000952 File ..., line 3, in f
Tim Peters1fbf9c52004-09-04 17:21:02 +0000953 Failed example:
Collin Winter3add4d72007-08-29 23:37:32 +0000954 raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +0000955 Expected:
956 Traceback (most recent call last):
957 TypeError: wrong type
958 Got:
959 Traceback (most recent call last):
960 ...
961 ValueError: message
Christian Heimes25bb7832008-01-11 16:17:00 +0000962 TestResults(failed=1, attempted=1)
Tim Peters1fbf9c52004-09-04 17:21:02 +0000963
Tim Peters8485b562004-08-04 18:46:34 +0000964If an exception is raised but not expected, then it is reported as an
965unexpected exception:
966
Tim Peters8485b562004-08-04 18:46:34 +0000967 >>> def f(x):
968 ... r'''
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000969 ... >>> 1//0
Tim Peters8485b562004-08-04 18:46:34 +0000970 ... 0
971 ... '''
972 >>> test = doctest.DocTestFinder().find(f)[0]
973 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper74bca7a2004-08-12 02:27:44 +0000974 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000975 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000976 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000977 Failed example:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000978 1//0
Tim Peters8485b562004-08-04 18:46:34 +0000979 Exception raised:
980 Traceback (most recent call last):
Jim Fulton07a349c2004-08-22 14:10:00 +0000981 ...
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000982 ZeroDivisionError: integer division or modulo by zero
Christian Heimes25bb7832008-01-11 16:17:00 +0000983 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000984"""
Georg Brandl25fbb892010-07-30 09:23:23 +0000985 def displayhook(): r"""
986Test that changing sys.displayhook doesn't matter for doctest.
987
988 >>> import sys
989 >>> orig_displayhook = sys.displayhook
990 >>> def my_displayhook(x):
991 ... print('hi!')
992 >>> sys.displayhook = my_displayhook
993 >>> def f():
994 ... '''
995 ... >>> 3
996 ... 3
997 ... '''
998 >>> test = doctest.DocTestFinder().find(f)[0]
999 >>> r = doctest.DocTestRunner(verbose=False).run(test)
1000 >>> post_displayhook = sys.displayhook
1001
1002 We need to restore sys.displayhook now, so that we'll be able to test
1003 results.
1004
1005 >>> sys.displayhook = orig_displayhook
1006
1007 Ok, now we can check that everything is ok.
1008
1009 >>> r
1010 TestResults(failed=0, attempted=1)
1011 >>> post_displayhook is my_displayhook
1012 True
1013"""
Tim Peters8485b562004-08-04 18:46:34 +00001014 def optionflags(): r"""
1015Tests of `DocTestRunner`'s option flag handling.
1016
1017Several option flags can be used to customize the behavior of the test
1018runner. These are defined as module constants in doctest, and passed
Christian Heimesfaf2f632008-01-06 16:59:19 +00001019to the DocTestRunner constructor (multiple constants should be ORed
Tim Peters8485b562004-08-04 18:46:34 +00001020together).
1021
1022The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
1023and 1/0:
1024
1025 >>> def f(x):
1026 ... '>>> True\n1\n'
1027
1028 >>> # Without the flag:
1029 >>> test = doctest.DocTestFinder().find(f)[0]
1030 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001031 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001032
1033 >>> # With the flag:
1034 >>> test = doctest.DocTestFinder().find(f)[0]
1035 >>> flags = doctest.DONT_ACCEPT_TRUE_FOR_1
1036 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001037 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001038 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001039 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001040 Failed example:
1041 True
1042 Expected:
1043 1
1044 Got:
1045 True
Christian Heimes25bb7832008-01-11 16:17:00 +00001046 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001047
1048The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines
1049and the '<BLANKLINE>' marker:
1050
1051 >>> def f(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001052 ... '>>> print("a\\n\\nb")\na\n<BLANKLINE>\nb\n'
Tim Peters8485b562004-08-04 18:46:34 +00001053
1054 >>> # Without the flag:
1055 >>> test = doctest.DocTestFinder().find(f)[0]
1056 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001057 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001058
1059 >>> # With the flag:
1060 >>> test = doctest.DocTestFinder().find(f)[0]
1061 >>> flags = doctest.DONT_ACCEPT_BLANKLINE
1062 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001063 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001064 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001065 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001066 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001067 print("a\n\nb")
Tim Peters8485b562004-08-04 18:46:34 +00001068 Expected:
1069 a
1070 <BLANKLINE>
1071 b
1072 Got:
1073 a
1074 <BLANKLINE>
1075 b
Christian Heimes25bb7832008-01-11 16:17:00 +00001076 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001077
1078The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be
1079treated as equal:
1080
1081 >>> def f(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001082 ... '>>> print(1, 2, 3)\n 1 2\n 3'
Tim Peters8485b562004-08-04 18:46:34 +00001083
1084 >>> # Without the flag:
1085 >>> test = doctest.DocTestFinder().find(f)[0]
1086 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001087 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001088 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001089 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001090 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001091 print(1, 2, 3)
Tim Peters8485b562004-08-04 18:46:34 +00001092 Expected:
1093 1 2
1094 3
Jim Fulton07a349c2004-08-22 14:10:00 +00001095 Got:
1096 1 2 3
Christian Heimes25bb7832008-01-11 16:17:00 +00001097 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001098
1099 >>> # With the flag:
1100 >>> test = doctest.DocTestFinder().find(f)[0]
1101 >>> flags = doctest.NORMALIZE_WHITESPACE
1102 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001103 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001104
Tim Peters026f8dc2004-08-19 16:38:58 +00001105 An example from the docs:
Guido van Rossum805365e2007-05-07 22:24:25 +00001106 >>> print(list(range(20))) #doctest: +NORMALIZE_WHITESPACE
Tim Peters026f8dc2004-08-19 16:38:58 +00001107 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
1108 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
1109
Tim Peters8485b562004-08-04 18:46:34 +00001110The ELLIPSIS flag causes ellipsis marker ("...") in the expected
1111output to match any substring in the actual output:
1112
1113 >>> def f(x):
Guido van Rossum805365e2007-05-07 22:24:25 +00001114 ... '>>> print(list(range(15)))\n[0, 1, 2, ..., 14]\n'
Tim Peters8485b562004-08-04 18:46:34 +00001115
1116 >>> # Without the flag:
1117 >>> test = doctest.DocTestFinder().find(f)[0]
1118 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001119 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001120 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001121 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001122 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001123 print(list(range(15)))
Jim Fulton07a349c2004-08-22 14:10:00 +00001124 Expected:
1125 [0, 1, 2, ..., 14]
1126 Got:
1127 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
Christian Heimes25bb7832008-01-11 16:17:00 +00001128 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001129
1130 >>> # With the flag:
1131 >>> test = doctest.DocTestFinder().find(f)[0]
1132 >>> flags = doctest.ELLIPSIS
1133 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001134 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001135
Tim Peterse594bee2004-08-22 01:47:51 +00001136 ... also matches nothing:
Tim Peters1cf3aa62004-08-19 06:49:33 +00001137
Guido van Rossume0192e52007-02-09 23:39:59 +00001138 >>> if 1:
1139 ... for i in range(100):
1140 ... print(i**2, end=' ') #doctest: +ELLIPSIS
1141 ... print('!')
1142 0 1...4...9 16 ... 36 49 64 ... 9801 !
Tim Peters1cf3aa62004-08-19 06:49:33 +00001143
Tim Peters026f8dc2004-08-19 16:38:58 +00001144 ... can be surprising; e.g., this test passes:
Tim Peters26b3ebb2004-08-19 08:10:08 +00001145
Guido van Rossume0192e52007-02-09 23:39:59 +00001146 >>> if 1: #doctest: +ELLIPSIS
1147 ... for i in range(20):
1148 ... print(i, end=' ')
1149 ... print(20)
Tim Peterse594bee2004-08-22 01:47:51 +00001150 0 1 2 ...1...2...0
Tim Peters26b3ebb2004-08-19 08:10:08 +00001151
Tim Peters026f8dc2004-08-19 16:38:58 +00001152 Examples from the docs:
1153
Guido van Rossum805365e2007-05-07 22:24:25 +00001154 >>> print(list(range(20))) # doctest:+ELLIPSIS
Tim Peters026f8dc2004-08-19 16:38:58 +00001155 [0, 1, ..., 18, 19]
1156
Guido van Rossum805365e2007-05-07 22:24:25 +00001157 >>> print(list(range(20))) # doctest: +ELLIPSIS
Tim Peters026f8dc2004-08-19 16:38:58 +00001158 ... # doctest: +NORMALIZE_WHITESPACE
1159 [0, 1, ..., 18, 19]
1160
Thomas Wouters477c8d52006-05-27 19:21:47 +00001161The SKIP flag causes an example to be skipped entirely. I.e., the
1162example is not run. It can be useful in contexts where doctest
1163examples serve as both documentation and test cases, and an example
1164should be included for documentation purposes, but should not be
1165checked (e.g., because its output is random, or depends on resources
1166which would be unavailable.) The SKIP flag can also be used for
1167'commenting out' broken examples.
1168
1169 >>> import unavailable_resource # doctest: +SKIP
1170 >>> unavailable_resource.do_something() # doctest: +SKIP
1171 >>> unavailable_resource.blow_up() # doctest: +SKIP
1172 Traceback (most recent call last):
1173 ...
1174 UncheckedBlowUpError: Nobody checks me.
1175
1176 >>> import random
Guido van Rossum7131f842007-02-09 20:13:25 +00001177 >>> print(random.random()) # doctest: +SKIP
Thomas Wouters477c8d52006-05-27 19:21:47 +00001178 0.721216923889
1179
Edward Loper71f55af2004-08-26 01:41:51 +00001180The REPORT_UDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001181and actual outputs to be displayed using a unified diff:
1182
1183 >>> def f(x):
1184 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001185 ... >>> print('\n'.join('abcdefg'))
Tim Peters8485b562004-08-04 18:46:34 +00001186 ... a
1187 ... B
1188 ... c
1189 ... d
1190 ... f
1191 ... g
1192 ... h
1193 ... '''
1194
1195 >>> # Without the flag:
1196 >>> test = doctest.DocTestFinder().find(f)[0]
1197 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001198 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001199 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001200 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001201 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001202 print('\n'.join('abcdefg'))
Tim Peters8485b562004-08-04 18:46:34 +00001203 Expected:
1204 a
1205 B
1206 c
1207 d
1208 f
1209 g
1210 h
1211 Got:
1212 a
1213 b
1214 c
1215 d
1216 e
1217 f
1218 g
Christian Heimes25bb7832008-01-11 16:17:00 +00001219 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001220
1221 >>> # With the flag:
1222 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001223 >>> flags = doctest.REPORT_UDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001224 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001225 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001226 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001227 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001228 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001229 print('\n'.join('abcdefg'))
Edward Loper56629292004-08-26 01:31:56 +00001230 Differences (unified diff with -expected +actual):
Tim Peterse7edcb82004-08-26 05:44:27 +00001231 @@ -1,7 +1,7 @@
Tim Peters8485b562004-08-04 18:46:34 +00001232 a
1233 -B
1234 +b
1235 c
1236 d
1237 +e
1238 f
1239 g
1240 -h
Christian Heimes25bb7832008-01-11 16:17:00 +00001241 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001242
Edward Loper71f55af2004-08-26 01:41:51 +00001243The REPORT_CDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001244and actual outputs to be displayed using a context diff:
1245
Edward Loper71f55af2004-08-26 01:41:51 +00001246 >>> # Reuse f() from the REPORT_UDIFF example, above.
Tim Peters8485b562004-08-04 18:46:34 +00001247 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001248 >>> flags = doctest.REPORT_CDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001249 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001250 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001251 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001252 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001253 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001254 print('\n'.join('abcdefg'))
Edward Loper56629292004-08-26 01:31:56 +00001255 Differences (context diff with expected followed by actual):
Tim Peters8485b562004-08-04 18:46:34 +00001256 ***************
Tim Peterse7edcb82004-08-26 05:44:27 +00001257 *** 1,7 ****
Tim Peters8485b562004-08-04 18:46:34 +00001258 a
1259 ! B
1260 c
1261 d
1262 f
1263 g
1264 - h
Tim Peterse7edcb82004-08-26 05:44:27 +00001265 --- 1,7 ----
Tim Peters8485b562004-08-04 18:46:34 +00001266 a
1267 ! b
1268 c
1269 d
1270 + e
1271 f
1272 g
Christian Heimes25bb7832008-01-11 16:17:00 +00001273 TestResults(failed=1, attempted=1)
Tim Petersc6cbab02004-08-22 19:43:28 +00001274
1275
Edward Loper71f55af2004-08-26 01:41:51 +00001276The REPORT_NDIFF flag causes failures to use the difflib.Differ algorithm
Tim Petersc6cbab02004-08-22 19:43:28 +00001277used by the popular ndiff.py utility. This does intraline difference
1278marking, as well as interline differences.
1279
1280 >>> def f(x):
1281 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001282 ... >>> print("a b c d e f g h i j k l m")
Tim Petersc6cbab02004-08-22 19:43:28 +00001283 ... a b c d e f g h i j k 1 m
1284 ... '''
1285 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001286 >>> flags = doctest.REPORT_NDIFF
Tim Petersc6cbab02004-08-22 19:43:28 +00001287 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001288 ... # doctest: +ELLIPSIS
Tim Petersc6cbab02004-08-22 19:43:28 +00001289 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001290 File ..., line 3, in f
Tim Petersc6cbab02004-08-22 19:43:28 +00001291 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001292 print("a b c d e f g h i j k l m")
Tim Petersc6cbab02004-08-22 19:43:28 +00001293 Differences (ndiff with -expected +actual):
1294 - a b c d e f g h i j k 1 m
1295 ? ^
1296 + a b c d e f g h i j k l m
1297 ? + ++ ^
Christian Heimes25bb7832008-01-11 16:17:00 +00001298 TestResults(failed=1, attempted=1)
Edward Lopera89f88d2004-08-26 02:45:51 +00001299
Ezio Melotti13925002011-03-16 11:05:33 +02001300The REPORT_ONLY_FIRST_FAILURE suppresses result output after the first
Edward Lopera89f88d2004-08-26 02:45:51 +00001301failing example:
1302
1303 >>> def f(x):
1304 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001305 ... >>> print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001306 ... 1
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001307 ... >>> print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001308 ... 200
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001309 ... >>> print(3) # second failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001310 ... 300
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001311 ... >>> print(4) # second success
Edward Lopera89f88d2004-08-26 02:45:51 +00001312 ... 4
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001313 ... >>> print(5) # third failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001314 ... 500
1315 ... '''
1316 >>> test = doctest.DocTestFinder().find(f)[0]
1317 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1318 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001319 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001320 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001321 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001322 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001323 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001324 Expected:
1325 200
1326 Got:
1327 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001328 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001329
Ezio Melotti13925002011-03-16 11:05:33 +02001330However, output from `report_start` is not suppressed:
Edward Lopera89f88d2004-08-26 02:45:51 +00001331
1332 >>> doctest.DocTestRunner(verbose=True, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001333 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001334 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001335 print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001336 Expecting:
1337 1
1338 ok
1339 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001340 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001341 Expecting:
1342 200
1343 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001344 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001345 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001346 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001347 Expected:
1348 200
1349 Got:
1350 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001351 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001352
1353For the purposes of REPORT_ONLY_FIRST_FAILURE, unexpected exceptions
1354count as failures:
1355
1356 >>> def f(x):
1357 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001358 ... >>> print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001359 ... 1
1360 ... >>> raise ValueError(2) # first failure
1361 ... 200
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001362 ... >>> print(3) # second failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001363 ... 300
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001364 ... >>> print(4) # second success
Edward Lopera89f88d2004-08-26 02:45:51 +00001365 ... 4
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001366 ... >>> print(5) # third failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001367 ... 500
1368 ... '''
1369 >>> test = doctest.DocTestFinder().find(f)[0]
1370 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1371 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1372 ... # doctest: +ELLIPSIS
1373 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001374 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001375 Failed example:
1376 raise ValueError(2) # first failure
1377 Exception raised:
1378 ...
1379 ValueError: 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001380 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001381
Thomas Wouters477c8d52006-05-27 19:21:47 +00001382New option flags can also be registered, via register_optionflag(). Here
1383we reach into doctest's internals a bit.
1384
1385 >>> unlikely = "UNLIKELY_OPTION_NAME"
1386 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1387 False
1388 >>> new_flag_value = doctest.register_optionflag(unlikely)
1389 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1390 True
1391
1392Before 2.4.4/2.5, registering a name more than once erroneously created
1393more than one flag value. Here we verify that's fixed:
1394
1395 >>> redundant_flag_value = doctest.register_optionflag(unlikely)
1396 >>> redundant_flag_value == new_flag_value
1397 True
1398
1399Clean up.
1400 >>> del doctest.OPTIONFLAGS_BY_NAME[unlikely]
1401
Tim Petersc6cbab02004-08-22 19:43:28 +00001402 """
1403
Tim Peters8485b562004-08-04 18:46:34 +00001404 def option_directives(): r"""
1405Tests of `DocTestRunner`'s option directive mechanism.
1406
Edward Loper74bca7a2004-08-12 02:27:44 +00001407Option directives can be used to turn option flags on or off for a
1408single example. To turn an option on for an example, follow that
1409example with a comment of the form ``# doctest: +OPTION``:
Tim Peters8485b562004-08-04 18:46:34 +00001410
1411 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001412 ... >>> print(list(range(10))) # should fail: no ellipsis
Edward Loper74bca7a2004-08-12 02:27:44 +00001413 ... [0, 1, ..., 9]
1414 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001415 ... >>> print(list(range(10))) # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001416 ... [0, 1, ..., 9]
1417 ... '''
1418 >>> test = doctest.DocTestFinder().find(f)[0]
1419 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001420 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001421 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001422 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001423 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001424 print(list(range(10))) # should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001425 Expected:
1426 [0, 1, ..., 9]
1427 Got:
1428 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001429 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001430
1431To turn an option off for an example, follow that example with a
1432comment of the form ``# doctest: -OPTION``:
1433
1434 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001435 ... >>> print(list(range(10)))
Edward Loper74bca7a2004-08-12 02:27:44 +00001436 ... [0, 1, ..., 9]
1437 ...
1438 ... >>> # should fail: no ellipsis
Guido van Rossum805365e2007-05-07 22:24:25 +00001439 ... >>> print(list(range(10))) # doctest: -ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001440 ... [0, 1, ..., 9]
1441 ... '''
1442 >>> test = doctest.DocTestFinder().find(f)[0]
1443 >>> doctest.DocTestRunner(verbose=False,
1444 ... optionflags=doctest.ELLIPSIS).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001445 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001446 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001447 File ..., line 6, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001448 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001449 print(list(range(10))) # doctest: -ELLIPSIS
Jim Fulton07a349c2004-08-22 14:10:00 +00001450 Expected:
1451 [0, 1, ..., 9]
1452 Got:
1453 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001454 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001455
1456Option directives affect only the example that they appear with; they
1457do not change the options for surrounding examples:
Edward Loper8e4a34b2004-08-12 02:34:27 +00001458
Edward Loper74bca7a2004-08-12 02:27:44 +00001459 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001460 ... >>> print(list(range(10))) # Should fail: no ellipsis
Tim Peters8485b562004-08-04 18:46:34 +00001461 ... [0, 1, ..., 9]
1462 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001463 ... >>> print(list(range(10))) # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001464 ... [0, 1, ..., 9]
1465 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001466 ... >>> print(list(range(10))) # Should fail: no ellipsis
Tim Peters8485b562004-08-04 18:46:34 +00001467 ... [0, 1, ..., 9]
1468 ... '''
1469 >>> test = doctest.DocTestFinder().find(f)[0]
1470 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001471 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001472 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001473 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001474 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001475 print(list(range(10))) # Should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001476 Expected:
1477 [0, 1, ..., 9]
1478 Got:
1479 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001480 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001481 File ..., line 8, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001482 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001483 print(list(range(10))) # Should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001484 Expected:
1485 [0, 1, ..., 9]
1486 Got:
1487 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001488 TestResults(failed=2, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +00001489
Edward Loper74bca7a2004-08-12 02:27:44 +00001490Multiple options may be modified by a single option directive. They
1491may be separated by whitespace, commas, or both:
Tim Peters8485b562004-08-04 18:46:34 +00001492
1493 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001494 ... >>> print(list(range(10))) # Should fail
Tim Peters8485b562004-08-04 18:46:34 +00001495 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001496 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001497 ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001498 ... [0, 1, ..., 9]
1499 ... '''
1500 >>> test = doctest.DocTestFinder().find(f)[0]
1501 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001502 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001503 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001504 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001505 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001506 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001507 Expected:
1508 [0, 1, ..., 9]
1509 Got:
1510 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001511 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001512
1513 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001514 ... >>> print(list(range(10))) # Should fail
Edward Loper74bca7a2004-08-12 02:27:44 +00001515 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001516 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001517 ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
1518 ... [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
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
1533 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001534 ... >>> print(list(range(10))) # Should fail
Edward Loper74bca7a2004-08-12 02:27:44 +00001535 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001536 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001537 ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1538 ... [0, 1, ..., 9]
1539 ... '''
1540 >>> test = doctest.DocTestFinder().find(f)[0]
1541 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001542 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001543 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001544 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001545 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001546 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001547 Expected:
1548 [0, 1, ..., 9]
1549 Got:
1550 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001551 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001552
1553The option directive may be put on the line following the source, as
1554long as a continuation prompt is used:
1555
1556 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001557 ... >>> print(list(range(10)))
Edward Loper74bca7a2004-08-12 02:27:44 +00001558 ... ... # doctest: +ELLIPSIS
1559 ... [0, 1, ..., 9]
1560 ... '''
1561 >>> test = doctest.DocTestFinder().find(f)[0]
1562 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001563 TestResults(failed=0, attempted=1)
Edward Loper8e4a34b2004-08-12 02:34:27 +00001564
Edward Loper74bca7a2004-08-12 02:27:44 +00001565For examples with multi-line source, the option directive may appear
1566at the end of any line:
1567
1568 >>> def f(x): r'''
1569 ... >>> for x in range(10): # doctest: +ELLIPSIS
Guido van Rossum805365e2007-05-07 22:24:25 +00001570 ... ... print(' ', x, end='', sep='')
1571 ... 0 1 2 ... 9
Edward Loper74bca7a2004-08-12 02:27:44 +00001572 ...
1573 ... >>> for x in range(10):
Guido van Rossum805365e2007-05-07 22:24:25 +00001574 ... ... print(' ', x, end='', sep='') # doctest: +ELLIPSIS
1575 ... 0 1 2 ... 9
Edward Loper74bca7a2004-08-12 02:27:44 +00001576 ... '''
1577 >>> test = doctest.DocTestFinder().find(f)[0]
1578 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001579 TestResults(failed=0, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001580
1581If more than one line of an example with multi-line source has an
1582option directive, then they are combined:
1583
1584 >>> def f(x): r'''
1585 ... Should fail (option directive not on the last line):
1586 ... >>> for x in range(10): # doctest: +ELLIPSIS
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001587 ... ... print(x, end=' ') # doctest: +NORMALIZE_WHITESPACE
Guido van Rossumd8faa362007-04-27 19:54:29 +00001588 ... 0 1 2...9
Edward Loper74bca7a2004-08-12 02:27:44 +00001589 ... '''
1590 >>> test = doctest.DocTestFinder().find(f)[0]
1591 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001592 TestResults(failed=0, attempted=1)
Edward Loper74bca7a2004-08-12 02:27:44 +00001593
1594It is an error to have a comment of the form ``# doctest:`` that is
1595*not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
1596``OPTION`` is an option that has been registered with
1597`register_option`:
1598
1599 >>> # Error: Option not registered
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001600 >>> s = '>>> print(12) #doctest: +BADOPTION'
Edward Loper74bca7a2004-08-12 02:27:44 +00001601 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1602 Traceback (most recent call last):
1603 ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
1604
1605 >>> # Error: No + or - prefix
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001606 >>> s = '>>> print(12) #doctest: ELLIPSIS'
Edward Loper74bca7a2004-08-12 02:27:44 +00001607 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1608 Traceback (most recent call last):
1609 ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
1610
1611It is an error to use an option directive on a line that contains no
1612source:
1613
1614 >>> s = '>>> # doctest: +ELLIPSIS'
1615 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1616 Traceback (most recent call last):
1617 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 +00001618"""
1619
1620def test_testsource(): r"""
1621Unit tests for `testsource()`.
1622
1623The testsource() function takes a module and a name, finds the (first)
Tim Peters19397e52004-08-06 22:02:59 +00001624test with that name in that module, and converts it to a script. The
1625example code is converted to regular Python code. The surrounding
1626words and expected output are converted to comments:
Tim Peters8485b562004-08-04 18:46:34 +00001627
1628 >>> import test.test_doctest
1629 >>> name = 'test.test_doctest.sample_func'
Guido van Rossum7131f842007-02-09 20:13:25 +00001630 >>> print(doctest.testsource(test.test_doctest, name))
Edward Lopera5db6002004-08-12 02:41:30 +00001631 # Blah blah
Tim Peters19397e52004-08-06 22:02:59 +00001632 #
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001633 print(sample_func(22))
Tim Peters8485b562004-08-04 18:46:34 +00001634 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001635 ## 44
Tim Peters19397e52004-08-06 22:02:59 +00001636 #
Edward Lopera5db6002004-08-12 02:41:30 +00001637 # Yee ha!
Georg Brandlecf93c72005-06-26 23:09:51 +00001638 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001639
1640 >>> name = 'test.test_doctest.SampleNewStyleClass'
Guido van Rossum7131f842007-02-09 20:13:25 +00001641 >>> print(doctest.testsource(test.test_doctest, name))
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001642 print('1\n2\n3')
Tim Peters8485b562004-08-04 18:46:34 +00001643 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001644 ## 1
1645 ## 2
1646 ## 3
Georg Brandlecf93c72005-06-26 23:09:51 +00001647 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001648
1649 >>> name = 'test.test_doctest.SampleClass.a_classmethod'
Guido van Rossum7131f842007-02-09 20:13:25 +00001650 >>> print(doctest.testsource(test.test_doctest, name))
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001651 print(SampleClass.a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +00001652 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001653 ## 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001654 print(SampleClass(0).a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +00001655 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001656 ## 12
Georg Brandlecf93c72005-06-26 23:09:51 +00001657 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001658"""
1659
1660def test_debug(): r"""
1661
1662Create a docstring that we want to debug:
1663
1664 >>> s = '''
1665 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001666 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +00001667 ... 12
1668 ... '''
1669
1670Create some fake stdin input, to feed to the debugger:
1671
Tim Peters8485b562004-08-04 18:46:34 +00001672 >>> real_stdin = sys.stdin
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001673 >>> sys.stdin = _FakeInput(['next', 'print(x)', 'continue'])
Tim Peters8485b562004-08-04 18:46:34 +00001674
1675Run the debugger on the docstring, and then restore sys.stdin.
1676
Edward Loper2de91ba2004-08-27 02:07:46 +00001677 >>> try: doctest.debug_src(s)
1678 ... finally: sys.stdin = real_stdin
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001679 > <string>(1)<module>()
Edward Loper2de91ba2004-08-27 02:07:46 +00001680 (Pdb) next
1681 12
Tim Peters8485b562004-08-04 18:46:34 +00001682 --Return--
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001683 > <string>(1)<module>()->None
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001684 (Pdb) print(x)
Edward Loper2de91ba2004-08-27 02:07:46 +00001685 12
1686 (Pdb) continue
Tim Peters8485b562004-08-04 18:46:34 +00001687
1688"""
1689
Brett Cannon31f59292011-02-21 19:29:56 +00001690if not hasattr(sys, 'gettrace') or not sys.gettrace():
1691 def test_pdb_set_trace():
1692 """Using pdb.set_trace from a doctest.
Jim Fulton356fd192004-08-09 11:34:47 +00001693
Brett Cannon31f59292011-02-21 19:29:56 +00001694 You can use pdb.set_trace from a doctest. To do so, you must
1695 retrieve the set_trace function from the pdb module at the time
1696 you use it. The doctest module changes sys.stdout so that it can
1697 capture program output. It also temporarily replaces pdb.set_trace
1698 with a version that restores stdout. This is necessary for you to
1699 see debugger output.
Jim Fulton356fd192004-08-09 11:34:47 +00001700
Brett Cannon31f59292011-02-21 19:29:56 +00001701 >>> doc = '''
1702 ... >>> x = 42
1703 ... >>> raise Exception('clé')
1704 ... Traceback (most recent call last):
1705 ... Exception: clé
1706 ... >>> import pdb; pdb.set_trace()
1707 ... '''
1708 >>> parser = doctest.DocTestParser()
1709 >>> test = parser.get_doctest(doc, {}, "foo-bar@baz", "foo-bar@baz.py", 0)
1710 >>> runner = doctest.DocTestRunner(verbose=False)
Jim Fulton356fd192004-08-09 11:34:47 +00001711
Brett Cannon31f59292011-02-21 19:29:56 +00001712 To demonstrate this, we'll create a fake standard input that
1713 captures our debugger input:
Jim Fulton356fd192004-08-09 11:34:47 +00001714
Brett Cannon31f59292011-02-21 19:29:56 +00001715 >>> import tempfile
1716 >>> real_stdin = sys.stdin
1717 >>> sys.stdin = _FakeInput([
1718 ... 'print(x)', # print data defined by the example
1719 ... 'continue', # stop debugging
1720 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001721
Brett Cannon31f59292011-02-21 19:29:56 +00001722 >>> try: runner.run(test)
1723 ... finally: sys.stdin = real_stdin
1724 --Return--
1725 > <doctest foo-bar@baz[2]>(1)<module>()->None
1726 -> import pdb; pdb.set_trace()
1727 (Pdb) print(x)
1728 42
1729 (Pdb) continue
1730 TestResults(failed=0, attempted=3)
Jim Fulton356fd192004-08-09 11:34:47 +00001731
Brett Cannon31f59292011-02-21 19:29:56 +00001732 You can also put pdb.set_trace in a function called from a test:
Jim Fulton356fd192004-08-09 11:34:47 +00001733
Brett Cannon31f59292011-02-21 19:29:56 +00001734 >>> def calls_set_trace():
1735 ... y=2
1736 ... import pdb; pdb.set_trace()
Jim Fulton356fd192004-08-09 11:34:47 +00001737
Brett Cannon31f59292011-02-21 19:29:56 +00001738 >>> doc = '''
1739 ... >>> x=1
1740 ... >>> calls_set_trace()
1741 ... '''
1742 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
1743 >>> real_stdin = sys.stdin
1744 >>> sys.stdin = _FakeInput([
1745 ... 'print(y)', # print data defined in the function
1746 ... 'up', # out of function
1747 ... 'print(x)', # print data defined by the example
1748 ... 'continue', # stop debugging
1749 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001750
Brett Cannon31f59292011-02-21 19:29:56 +00001751 >>> try:
1752 ... runner.run(test)
1753 ... finally:
1754 ... sys.stdin = real_stdin
1755 --Return--
1756 > <doctest test.test_doctest.test_pdb_set_trace[8]>(3)calls_set_trace()->None
1757 -> import pdb; pdb.set_trace()
1758 (Pdb) print(y)
1759 2
1760 (Pdb) up
1761 > <doctest foo-bar@baz[1]>(1)<module>()
1762 -> calls_set_trace()
1763 (Pdb) print(x)
1764 1
1765 (Pdb) continue
1766 TestResults(failed=0, attempted=2)
Edward Loper2de91ba2004-08-27 02:07:46 +00001767
Brett Cannon31f59292011-02-21 19:29:56 +00001768 During interactive debugging, source code is shown, even for
1769 doctest examples:
Edward Loper2de91ba2004-08-27 02:07:46 +00001770
Brett Cannon31f59292011-02-21 19:29:56 +00001771 >>> doc = '''
1772 ... >>> def f(x):
1773 ... ... g(x*2)
1774 ... >>> def g(x):
1775 ... ... print(x+3)
1776 ... ... import pdb; pdb.set_trace()
1777 ... >>> f(3)
1778 ... '''
1779 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
1780 >>> real_stdin = sys.stdin
1781 >>> sys.stdin = _FakeInput([
1782 ... 'list', # list source from example 2
1783 ... 'next', # return from g()
1784 ... 'list', # list source from example 1
1785 ... 'next', # return from f()
1786 ... 'list', # list source from example 3
1787 ... 'continue', # stop debugging
1788 ... ''])
1789 >>> try: runner.run(test)
1790 ... finally: sys.stdin = real_stdin
1791 ... # doctest: +NORMALIZE_WHITESPACE
1792 --Return--
1793 > <doctest foo-bar@baz[1]>(3)g()->None
1794 -> import pdb; pdb.set_trace()
1795 (Pdb) list
1796 1 def g(x):
1797 2 print(x+3)
1798 3 -> import pdb; pdb.set_trace()
1799 [EOF]
1800 (Pdb) next
1801 --Return--
1802 > <doctest foo-bar@baz[0]>(2)f()->None
1803 -> g(x*2)
1804 (Pdb) list
1805 1 def f(x):
1806 2 -> g(x*2)
1807 [EOF]
1808 (Pdb) next
1809 --Return--
1810 > <doctest foo-bar@baz[2]>(1)<module>()->None
1811 -> f(3)
1812 (Pdb) list
1813 1 -> f(3)
1814 [EOF]
1815 (Pdb) continue
1816 **********************************************************************
1817 File "foo-bar@baz.py", line 7, in foo-bar@baz
1818 Failed example:
1819 f(3)
1820 Expected nothing
1821 Got:
1822 9
1823 TestResults(failed=1, attempted=3)
1824 """
Jim Fulton356fd192004-08-09 11:34:47 +00001825
Brett Cannon31f59292011-02-21 19:29:56 +00001826 def test_pdb_set_trace_nested():
1827 """This illustrates more-demanding use of set_trace with nested functions.
Tim Peters50c6bdb2004-11-08 22:07:37 +00001828
Brett Cannon31f59292011-02-21 19:29:56 +00001829 >>> class C(object):
1830 ... def calls_set_trace(self):
1831 ... y = 1
1832 ... import pdb; pdb.set_trace()
1833 ... self.f1()
1834 ... y = 2
1835 ... def f1(self):
1836 ... x = 1
1837 ... self.f2()
1838 ... x = 2
1839 ... def f2(self):
1840 ... z = 1
1841 ... z = 2
Tim Peters50c6bdb2004-11-08 22:07:37 +00001842
Brett Cannon31f59292011-02-21 19:29:56 +00001843 >>> calls_set_trace = C().calls_set_trace
Tim Peters50c6bdb2004-11-08 22:07:37 +00001844
Brett Cannon31f59292011-02-21 19:29:56 +00001845 >>> doc = '''
1846 ... >>> a = 1
1847 ... >>> calls_set_trace()
1848 ... '''
1849 >>> parser = doctest.DocTestParser()
1850 >>> runner = doctest.DocTestRunner(verbose=False)
1851 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
1852 >>> real_stdin = sys.stdin
1853 >>> sys.stdin = _FakeInput([
1854 ... 'print(y)', # print data defined in the function
1855 ... 'step', 'step', 'step', 'step', 'step', 'step', 'print(z)',
1856 ... 'up', 'print(x)',
1857 ... 'up', 'print(y)',
1858 ... 'up', 'print(foo)',
1859 ... 'continue', # stop debugging
1860 ... ''])
Tim Peters50c6bdb2004-11-08 22:07:37 +00001861
Brett Cannon31f59292011-02-21 19:29:56 +00001862 >>> try:
1863 ... runner.run(test)
1864 ... finally:
1865 ... sys.stdin = real_stdin
1866 ... # doctest: +REPORT_NDIFF
1867 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
1868 -> self.f1()
1869 (Pdb) print(y)
1870 1
1871 (Pdb) step
1872 --Call--
1873 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(7)f1()
1874 -> def f1(self):
1875 (Pdb) step
1876 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(8)f1()
1877 -> x = 1
1878 (Pdb) step
1879 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
1880 -> self.f2()
1881 (Pdb) step
1882 --Call--
1883 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(11)f2()
1884 -> def f2(self):
1885 (Pdb) step
1886 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(12)f2()
1887 -> z = 1
1888 (Pdb) step
1889 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(13)f2()
1890 -> z = 2
1891 (Pdb) print(z)
1892 1
1893 (Pdb) up
1894 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
1895 -> self.f2()
1896 (Pdb) print(x)
1897 1
1898 (Pdb) up
1899 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
1900 -> self.f1()
1901 (Pdb) print(y)
1902 1
1903 (Pdb) up
1904 > <doctest foo-bar@baz[1]>(1)<module>()
1905 -> calls_set_trace()
1906 (Pdb) print(foo)
1907 *** NameError: name 'foo' is not defined
1908 (Pdb) continue
1909 TestResults(failed=0, attempted=2)
1910 """
Tim Peters50c6bdb2004-11-08 22:07:37 +00001911
Tim Peters19397e52004-08-06 22:02:59 +00001912def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +00001913 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +00001914
1915 We create a Suite by providing a module. A module can be provided
1916 by passing a module object:
1917
1918 >>> import unittest
1919 >>> import test.sample_doctest
1920 >>> suite = doctest.DocTestSuite(test.sample_doctest)
1921 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001922 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001923
1924 We can also supply the module by name:
1925
1926 >>> suite = doctest.DocTestSuite('test.sample_doctest')
1927 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001928 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001929
1930 We can use the current module:
1931
1932 >>> suite = test.sample_doctest.test_suite()
1933 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001934 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001935
1936 We can supply global variables. If we pass globs, they will be
1937 used instead of the module globals. Here we'll pass an empty
1938 globals, triggering an extra error:
1939
1940 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
1941 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001942 <unittest.result.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001943
1944 Alternatively, we can provide extra globals. Here we'll make an
1945 error go away by providing an extra global variable:
1946
1947 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1948 ... extraglobs={'y': 1})
1949 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001950 <unittest.result.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001951
1952 You can pass option flags. Here we'll cause an extra error
1953 by disabling the blank-line feature:
1954
1955 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00001956 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00001957 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001958 <unittest.result.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001959
Tim Peters1e277ee2004-08-07 05:37:52 +00001960 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00001961
Jim Fultonf54bad42004-08-28 14:57:56 +00001962 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00001963 ... import test.test_doctest
1964 ... test.test_doctest.sillySetup = True
1965
Jim Fultonf54bad42004-08-28 14:57:56 +00001966 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00001967 ... import test.test_doctest
1968 ... del test.test_doctest.sillySetup
1969
1970 Here, we installed a silly variable that the test expects:
1971
1972 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1973 ... setUp=setUp, tearDown=tearDown)
1974 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001975 <unittest.result.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001976
1977 But the tearDown restores sanity:
1978
1979 >>> import test.test_doctest
1980 >>> test.test_doctest.sillySetup
1981 Traceback (most recent call last):
1982 ...
1983 AttributeError: 'module' object has no attribute 'sillySetup'
1984
Jim Fultonf54bad42004-08-28 14:57:56 +00001985 The setUp and tearDown funtions are passed test objects. Here
1986 we'll use the setUp function to supply the missing variable y:
1987
1988 >>> def setUp(test):
1989 ... test.globs['y'] = 1
1990
1991 >>> suite = doctest.DocTestSuite('test.sample_doctest', setUp=setUp)
1992 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001993 <unittest.result.TestResult run=9 errors=0 failures=3>
Jim Fultonf54bad42004-08-28 14:57:56 +00001994
1995 Here, we didn't need to use a tearDown function because we
1996 modified the test globals, which are a copy of the
1997 sample_doctest module dictionary. The test globals are
1998 automatically cleared for us after a test.
Tim Peters19397e52004-08-06 22:02:59 +00001999 """
2000
2001def test_DocFileSuite():
2002 """We can test tests found in text files using a DocFileSuite.
2003
2004 We create a suite by providing the names of one or more text
2005 files that include examples:
2006
2007 >>> import unittest
2008 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002009 ... 'test_doctest2.txt',
2010 ... 'test_doctest4.txt')
Tim Peters19397e52004-08-06 22:02:59 +00002011 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002012 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002013
2014 The test files are looked for in the directory containing the
2015 calling module. A package keyword argument can be provided to
2016 specify a different relative location.
2017
2018 >>> import unittest
2019 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2020 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002021 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002022 ... package='test')
2023 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002024 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002025
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002026 Support for using a package's __loader__.get_data() is also
2027 provided.
2028
2029 >>> import unittest, pkgutil, test
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002030 >>> added_loader = False
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002031 >>> if not hasattr(test, '__loader__'):
2032 ... test.__loader__ = pkgutil.get_loader(test)
2033 ... added_loader = True
2034 >>> try:
2035 ... suite = doctest.DocFileSuite('test_doctest.txt',
2036 ... 'test_doctest2.txt',
2037 ... 'test_doctest4.txt',
2038 ... package='test')
2039 ... suite.run(unittest.TestResult())
2040 ... finally:
2041 ... if added_loader:
2042 ... del test.__loader__
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002043 <unittest.result.TestResult run=3 errors=0 failures=2>
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002044
Edward Loper0273f5b2004-09-18 20:27:04 +00002045 '/' should be used as a path separator. It will be converted
2046 to a native separator at run time:
Tim Peters19397e52004-08-06 22:02:59 +00002047
2048 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
2049 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002050 <unittest.result.TestResult run=1 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002051
Edward Loper0273f5b2004-09-18 20:27:04 +00002052 If DocFileSuite is used from an interactive session, then files
2053 are resolved relative to the directory of sys.argv[0]:
2054
Christian Heimes45f9af32007-11-27 21:50:00 +00002055 >>> import types, os.path, test.test_doctest
Edward Loper0273f5b2004-09-18 20:27:04 +00002056 >>> save_argv = sys.argv
2057 >>> sys.argv = [test.test_doctest.__file__]
2058 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Christian Heimes45f9af32007-11-27 21:50:00 +00002059 ... package=types.ModuleType('__main__'))
Edward Loper0273f5b2004-09-18 20:27:04 +00002060 >>> sys.argv = save_argv
2061
Edward Loper052d0cd2004-09-19 17:19:33 +00002062 By setting `module_relative=False`, os-specific paths may be
2063 used (including absolute paths and paths relative to the
2064 working directory):
Edward Loper0273f5b2004-09-18 20:27:04 +00002065
2066 >>> # Get the absolute path of the test package.
2067 >>> test_doctest_path = os.path.abspath(test.test_doctest.__file__)
2068 >>> test_pkg_path = os.path.split(test_doctest_path)[0]
2069
2070 >>> # Use it to find the absolute path of test_doctest.txt.
2071 >>> test_file = os.path.join(test_pkg_path, 'test_doctest.txt')
2072
Edward Loper052d0cd2004-09-19 17:19:33 +00002073 >>> suite = doctest.DocFileSuite(test_file, module_relative=False)
Edward Loper0273f5b2004-09-18 20:27:04 +00002074 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002075 <unittest.result.TestResult run=1 errors=0 failures=1>
Edward Loper0273f5b2004-09-18 20:27:04 +00002076
Edward Loper052d0cd2004-09-19 17:19:33 +00002077 It is an error to specify `package` when `module_relative=False`:
2078
2079 >>> suite = doctest.DocFileSuite(test_file, module_relative=False,
2080 ... package='test')
2081 Traceback (most recent call last):
2082 ValueError: Package may only be specified for module-relative paths.
2083
Tim Peters19397e52004-08-06 22:02:59 +00002084 You can specify initial global variables:
2085
2086 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2087 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002088 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002089 ... globs={'favorite_color': 'blue'})
2090 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002091 <unittest.result.TestResult run=3 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002092
2093 In this case, we supplied a missing favorite color. You can
2094 provide doctest options:
2095
2096 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2097 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002098 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002099 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
2100 ... globs={'favorite_color': 'blue'})
2101 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002102 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002103
2104 And, you can provide setUp and tearDown functions:
2105
Jim Fultonf54bad42004-08-28 14:57:56 +00002106 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00002107 ... import test.test_doctest
2108 ... test.test_doctest.sillySetup = True
2109
Jim Fultonf54bad42004-08-28 14:57:56 +00002110 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00002111 ... import test.test_doctest
2112 ... del test.test_doctest.sillySetup
2113
2114 Here, we installed a silly variable that the test expects:
2115
2116 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2117 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002118 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002119 ... setUp=setUp, tearDown=tearDown)
2120 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002121 <unittest.result.TestResult run=3 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002122
2123 But the tearDown restores sanity:
2124
2125 >>> import test.test_doctest
2126 >>> test.test_doctest.sillySetup
2127 Traceback (most recent call last):
2128 ...
2129 AttributeError: 'module' object has no attribute 'sillySetup'
2130
Jim Fultonf54bad42004-08-28 14:57:56 +00002131 The setUp and tearDown funtions are passed test objects.
2132 Here, we'll use a setUp function to set the favorite color in
2133 test_doctest.txt:
2134
2135 >>> def setUp(test):
2136 ... test.globs['favorite_color'] = 'blue'
2137
2138 >>> suite = doctest.DocFileSuite('test_doctest.txt', setUp=setUp)
2139 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002140 <unittest.result.TestResult run=1 errors=0 failures=0>
Jim Fultonf54bad42004-08-28 14:57:56 +00002141
2142 Here, we didn't need to use a tearDown function because we
2143 modified the test globals. The test globals are
2144 automatically cleared for us after a test.
Tim Petersdf7a2082004-08-29 00:38:17 +00002145
Fred Drake7c404a42004-12-21 23:46:34 +00002146 Tests in a file run using `DocFileSuite` can also access the
2147 `__file__` global, which is set to the name of the file
2148 containing the tests:
2149
2150 >>> suite = doctest.DocFileSuite('test_doctest3.txt')
2151 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002152 <unittest.result.TestResult run=1 errors=0 failures=0>
Fred Drake7c404a42004-12-21 23:46:34 +00002153
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002154 If the tests contain non-ASCII characters, we have to specify which
2155 encoding the file is encoded with. We do so by using the `encoding`
2156 parameter:
2157
2158 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2159 ... 'test_doctest2.txt',
2160 ... 'test_doctest4.txt',
2161 ... encoding='utf-8')
2162 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002163 <unittest.result.TestResult run=3 errors=0 failures=2>
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002164
Jim Fultonf54bad42004-08-28 14:57:56 +00002165 """
Tim Peters19397e52004-08-06 22:02:59 +00002166
Jim Fulton07a349c2004-08-22 14:10:00 +00002167def test_trailing_space_in_test():
2168 """
Tim Petersa7def722004-08-23 22:13:22 +00002169 Trailing spaces in expected output are significant:
Tim Petersc6cbab02004-08-22 19:43:28 +00002170
Jim Fulton07a349c2004-08-22 14:10:00 +00002171 >>> x, y = 'foo', ''
Guido van Rossum7131f842007-02-09 20:13:25 +00002172 >>> print(x, y)
Jim Fulton07a349c2004-08-22 14:10:00 +00002173 foo \n
2174 """
Tim Peters19397e52004-08-06 22:02:59 +00002175
Jim Fultonf54bad42004-08-28 14:57:56 +00002176
2177def test_unittest_reportflags():
2178 """Default unittest reporting flags can be set to control reporting
2179
2180 Here, we'll set the REPORT_ONLY_FIRST_FAILURE option so we see
2181 only the first failure of each test. First, we'll look at the
2182 output without the flag. The file test_doctest.txt file has two
2183 tests. They both fail if blank lines are disabled:
2184
2185 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2186 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
2187 >>> import unittest
2188 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002189 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002190 Traceback ...
2191 Failed example:
2192 favorite_color
2193 ...
2194 Failed example:
2195 if 1:
2196 ...
2197
2198 Note that we see both failures displayed.
2199
2200 >>> old = doctest.set_unittest_reportflags(
2201 ... doctest.REPORT_ONLY_FIRST_FAILURE)
2202
2203 Now, when we run the test:
2204
2205 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002206 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002207 Traceback ...
2208 Failed example:
2209 favorite_color
2210 Exception raised:
2211 ...
2212 NameError: name 'favorite_color' is not defined
2213 <BLANKLINE>
2214 <BLANKLINE>
Tim Petersdf7a2082004-08-29 00:38:17 +00002215
Jim Fultonf54bad42004-08-28 14:57:56 +00002216 We get only the first failure.
2217
2218 If we give any reporting options when we set up the tests,
2219 however:
2220
2221 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2222 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE | doctest.REPORT_NDIFF)
2223
2224 Then the default eporting options are ignored:
2225
2226 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002227 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002228 Traceback ...
2229 Failed example:
2230 favorite_color
2231 ...
2232 Failed example:
2233 if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00002234 print('a')
2235 print()
2236 print('b')
Jim Fultonf54bad42004-08-28 14:57:56 +00002237 Differences (ndiff with -expected +actual):
2238 a
2239 - <BLANKLINE>
2240 +
2241 b
2242 <BLANKLINE>
2243 <BLANKLINE>
2244
2245
2246 Test runners can restore the formatting flags after they run:
2247
2248 >>> ignored = doctest.set_unittest_reportflags(old)
2249
2250 """
2251
Edward Loper052d0cd2004-09-19 17:19:33 +00002252def test_testfile(): r"""
2253Tests for the `testfile()` function. This function runs all the
2254doctest examples in a given file. In its simple invokation, it is
2255called with the name of a file, which is taken to be relative to the
2256calling module. The return value is (#failures, #tests).
2257
Florent Xicluna59250852010-02-27 14:21:57 +00002258We don't want `-v` in sys.argv for these tests.
2259
2260 >>> save_argv = sys.argv
2261 >>> if '-v' in sys.argv:
2262 ... sys.argv = [arg for arg in save_argv if arg != '-v']
2263
2264
Edward Loper052d0cd2004-09-19 17:19:33 +00002265 >>> doctest.testfile('test_doctest.txt') # doctest: +ELLIPSIS
2266 **********************************************************************
2267 File "...", line 6, in test_doctest.txt
2268 Failed example:
2269 favorite_color
2270 Exception raised:
2271 ...
2272 NameError: name 'favorite_color' is not defined
2273 **********************************************************************
2274 1 items had failures:
2275 1 of 2 in test_doctest.txt
2276 ***Test Failed*** 1 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002277 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002278 >>> doctest.master = None # Reset master.
2279
2280(Note: we'll be clearing doctest.master after each call to
Ezio Melotti13925002011-03-16 11:05:33 +02002281`doctest.testfile`, to suppress warnings about multiple tests with the
Edward Loper052d0cd2004-09-19 17:19:33 +00002282same name.)
2283
2284Globals may be specified with the `globs` and `extraglobs` parameters:
2285
2286 >>> globs = {'favorite_color': 'blue'}
2287 >>> doctest.testfile('test_doctest.txt', globs=globs)
Christian Heimes25bb7832008-01-11 16:17:00 +00002288 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002289 >>> doctest.master = None # Reset master.
2290
2291 >>> extraglobs = {'favorite_color': 'red'}
2292 >>> doctest.testfile('test_doctest.txt', globs=globs,
2293 ... extraglobs=extraglobs) # doctest: +ELLIPSIS
2294 **********************************************************************
2295 File "...", line 6, in test_doctest.txt
2296 Failed example:
2297 favorite_color
2298 Expected:
2299 'blue'
2300 Got:
2301 'red'
2302 **********************************************************************
2303 1 items had failures:
2304 1 of 2 in test_doctest.txt
2305 ***Test Failed*** 1 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002306 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002307 >>> doctest.master = None # Reset master.
2308
2309The file may be made relative to a given module or package, using the
2310optional `module_relative` parameter:
2311
2312 >>> doctest.testfile('test_doctest.txt', globs=globs,
2313 ... module_relative='test')
Christian Heimes25bb7832008-01-11 16:17:00 +00002314 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002315 >>> doctest.master = None # Reset master.
2316
Ezio Melotti13925002011-03-16 11:05:33 +02002317Verbosity can be increased with the optional `verbose` parameter:
Edward Loper052d0cd2004-09-19 17:19:33 +00002318
2319 >>> doctest.testfile('test_doctest.txt', globs=globs, verbose=True)
2320 Trying:
2321 favorite_color
2322 Expecting:
2323 'blue'
2324 ok
2325 Trying:
2326 if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00002327 print('a')
2328 print()
2329 print('b')
Edward Loper052d0cd2004-09-19 17:19:33 +00002330 Expecting:
2331 a
2332 <BLANKLINE>
2333 b
2334 ok
2335 1 items passed all tests:
2336 2 tests in test_doctest.txt
2337 2 tests in 1 items.
2338 2 passed and 0 failed.
2339 Test passed.
Christian Heimes25bb7832008-01-11 16:17:00 +00002340 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002341 >>> doctest.master = None # Reset master.
2342
2343The name of the test may be specified with the optional `name`
2344parameter:
2345
2346 >>> doctest.testfile('test_doctest.txt', name='newname')
2347 ... # doctest: +ELLIPSIS
2348 **********************************************************************
2349 File "...", line 6, in newname
2350 ...
Christian Heimes25bb7832008-01-11 16:17:00 +00002351 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002352 >>> doctest.master = None # Reset master.
2353
Ezio Melotti13925002011-03-16 11:05:33 +02002354The summary report may be suppressed with the optional `report`
Edward Loper052d0cd2004-09-19 17:19:33 +00002355parameter:
2356
2357 >>> doctest.testfile('test_doctest.txt', report=False)
2358 ... # doctest: +ELLIPSIS
2359 **********************************************************************
2360 File "...", line 6, in test_doctest.txt
2361 Failed example:
2362 favorite_color
2363 Exception raised:
2364 ...
2365 NameError: name 'favorite_color' is not defined
Christian Heimes25bb7832008-01-11 16:17:00 +00002366 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002367 >>> doctest.master = None # Reset master.
2368
2369The optional keyword argument `raise_on_error` can be used to raise an
2370exception on the first error (which may be useful for postmortem
2371debugging):
2372
2373 >>> doctest.testfile('test_doctest.txt', raise_on_error=True)
2374 ... # doctest: +ELLIPSIS
2375 Traceback (most recent call last):
Guido van Rossum6a2a2a02006-08-26 20:37:44 +00002376 doctest.UnexpectedException: ...
Edward Loper052d0cd2004-09-19 17:19:33 +00002377 >>> doctest.master = None # Reset master.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002378
2379If the tests contain non-ASCII characters, the tests might fail, since
2380it's unknown which encoding is used. The encoding can be specified
2381using the optional keyword argument `encoding`:
2382
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002383 >>> doctest.testfile('test_doctest4.txt', encoding='latin-1') # doctest: +ELLIPSIS
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002384 **********************************************************************
2385 File "...", line 7, in test_doctest4.txt
2386 Failed example:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002387 '...'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002388 Expected:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002389 'f\xf6\xf6'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002390 Got:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002391 'f\xc3\xb6\xc3\xb6'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002392 **********************************************************************
2393 ...
2394 **********************************************************************
2395 1 items had failures:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002396 2 of 2 in test_doctest4.txt
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002397 ***Test Failed*** 2 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002398 TestResults(failed=2, attempted=2)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002399 >>> doctest.master = None # Reset master.
2400
2401 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8')
Christian Heimes25bb7832008-01-11 16:17:00 +00002402 TestResults(failed=0, attempted=2)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002403 >>> doctest.master = None # Reset master.
Florent Xicluna59250852010-02-27 14:21:57 +00002404
2405Test the verbose output:
2406
2407 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8', verbose=True)
2408 Trying:
2409 'föö'
2410 Expecting:
2411 'f\xf6\xf6'
2412 ok
2413 Trying:
2414 'bąr'
2415 Expecting:
2416 'b\u0105r'
2417 ok
2418 1 items passed all tests:
2419 2 tests in test_doctest4.txt
2420 2 tests in 1 items.
2421 2 passed and 0 failed.
2422 Test passed.
2423 TestResults(failed=0, attempted=2)
2424 >>> doctest.master = None # Reset master.
2425 >>> sys.argv = save_argv
Edward Loper052d0cd2004-09-19 17:19:33 +00002426"""
2427
R. David Murray58641de2009-06-12 15:33:19 +00002428def test_testmod(): r"""
2429Tests for the testmod function. More might be useful, but for now we're just
2430testing the case raised by Issue 6195, where trying to doctest a C module would
2431fail with a UnicodeDecodeError because doctest tried to read the "source" lines
2432out of the binary module.
2433
2434 >>> import unicodedata
Florent Xicluna59250852010-02-27 14:21:57 +00002435 >>> doctest.testmod(unicodedata, verbose=False)
R. David Murray58641de2009-06-12 15:33:19 +00002436 TestResults(failed=0, attempted=0)
2437"""
2438
Victor Stinner9d396392010-10-16 21:54:59 +00002439try:
2440 os.fsencode("foo-bär@baz.py")
2441except UnicodeEncodeError:
2442 # Skip the test: the filesystem encoding is unable to encode the filename
2443 pass
2444else:
2445 def test_unicode(): """
2446Check doctest with a non-ascii filename:
2447
2448 >>> doc = '''
2449 ... >>> raise Exception('clé')
2450 ... '''
2451 ...
2452 >>> parser = doctest.DocTestParser()
2453 >>> test = parser.get_doctest(doc, {}, "foo-bär@baz", "foo-bär@baz.py", 0)
2454 >>> test
2455 <DocTest foo-bär@baz from foo-bär@baz.py:0 (1 example)>
2456 >>> runner = doctest.DocTestRunner(verbose=False)
2457 >>> runner.run(test) # doctest: +ELLIPSIS
2458 **********************************************************************
2459 File "foo-bär@baz.py", line 2, in foo-bär@baz
2460 Failed example:
2461 raise Exception('clé')
2462 Exception raised:
2463 Traceback (most recent call last):
2464 File ...
2465 compileflags, 1), test.globs)
2466 File "<doctest foo-bär@baz[0]>", line 1, in <module>
2467 raise Exception('clé')
2468 Exception: clé
2469 TestResults(failed=1, attempted=1)
2470 """
2471
Tim Peters8485b562004-08-04 18:46:34 +00002472######################################################################
2473## Main
2474######################################################################
2475
2476def test_main():
2477 # Check the doctest cases in doctest itself:
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002478 support.run_doctest(doctest, verbosity=True)
Tim Peters8485b562004-08-04 18:46:34 +00002479 # Check the doctest cases defined here:
2480 from test import test_doctest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002481 support.run_doctest(test_doctest, verbosity=True)
Tim Peters8485b562004-08-04 18:46:34 +00002482
Victor Stinner45df8202010-04-28 22:31:17 +00002483import sys, re, io
2484
Tim Peters8485b562004-08-04 18:46:34 +00002485def test_coverage(coverdir):
Victor Stinner45df8202010-04-28 22:31:17 +00002486 trace = support.import_module('trace')
Tim Peters8485b562004-08-04 18:46:34 +00002487 tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
2488 trace=0, count=1)
Guido van Rossume7ba4952007-06-06 23:52:48 +00002489 tracer.run('test_main()')
Tim Peters8485b562004-08-04 18:46:34 +00002490 r = tracer.results()
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002491 print('Writing coverage results...')
Tim Peters8485b562004-08-04 18:46:34 +00002492 r.write_results(show_missing=True, summary=True,
2493 coverdir=coverdir)
2494
2495if __name__ == '__main__':
2496 if '-c' in sys.argv:
2497 test_coverage('/tmp/doctest.cover')
2498 else:
2499 test_main()