blob: a4b7e35a386e998266fb24b222a15d43cab5cc87 [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
7
Florent Xiclunadc6f2d02010-04-02 19:25:32 +00008
Nick Coghlanf088e5e2008-12-14 11:50:48 +00009# NOTE: There are some additional tests relating to interaction with
10# zipimport in the test_zipimport_support test module.
11
Tim Peters8485b562004-08-04 18:46:34 +000012######################################################################
13## Sample Objects (used by test cases)
14######################################################################
15
16def sample_func(v):
17 """
Tim Peters19397e52004-08-06 22:02:59 +000018 Blah blah
19
Guido van Rossum7131f842007-02-09 20:13:25 +000020 >>> print(sample_func(22))
Tim Peters8485b562004-08-04 18:46:34 +000021 44
Tim Peters19397e52004-08-06 22:02:59 +000022
23 Yee ha!
Tim Peters8485b562004-08-04 18:46:34 +000024 """
25 return v+v
26
27class SampleClass:
28 """
Guido van Rossum7131f842007-02-09 20:13:25 +000029 >>> print(1)
Tim Peters8485b562004-08-04 18:46:34 +000030 1
Edward Loper4ae900f2004-09-21 03:20:34 +000031
32 >>> # comments get ignored. so are empty PS1 and PS2 prompts:
33 >>>
34 ...
35
36 Multiline example:
37 >>> sc = SampleClass(3)
38 >>> for i in range(10):
39 ... sc = sc.double()
Guido van Rossum805365e2007-05-07 22:24:25 +000040 ... print(' ', sc.get(), sep='', end='')
41 6 12 24 48 96 192 384 768 1536 3072
Tim Peters8485b562004-08-04 18:46:34 +000042 """
43 def __init__(self, val):
44 """
Guido van Rossum7131f842007-02-09 20:13:25 +000045 >>> print(SampleClass(12).get())
Tim Peters8485b562004-08-04 18:46:34 +000046 12
47 """
48 self.val = val
49
50 def double(self):
51 """
Guido van Rossum7131f842007-02-09 20:13:25 +000052 >>> print(SampleClass(12).double().get())
Tim Peters8485b562004-08-04 18:46:34 +000053 24
54 """
55 return SampleClass(self.val + self.val)
56
57 def get(self):
58 """
Guido van Rossum7131f842007-02-09 20:13:25 +000059 >>> print(SampleClass(-5).get())
Tim Peters8485b562004-08-04 18:46:34 +000060 -5
61 """
62 return self.val
63
64 def a_staticmethod(v):
65 """
Guido van Rossum7131f842007-02-09 20:13:25 +000066 >>> print(SampleClass.a_staticmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +000067 11
68 """
69 return v+1
70 a_staticmethod = staticmethod(a_staticmethod)
71
72 def a_classmethod(cls, v):
73 """
Guido van Rossum7131f842007-02-09 20:13:25 +000074 >>> print(SampleClass.a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +000075 12
Guido van Rossum7131f842007-02-09 20:13:25 +000076 >>> print(SampleClass(0).a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +000077 12
78 """
79 return v+2
80 a_classmethod = classmethod(a_classmethod)
81
82 a_property = property(get, doc="""
Guido van Rossum7131f842007-02-09 20:13:25 +000083 >>> print(SampleClass(22).a_property)
Tim Peters8485b562004-08-04 18:46:34 +000084 22
85 """)
86
87 class NestedClass:
88 """
89 >>> x = SampleClass.NestedClass(5)
90 >>> y = x.square()
Guido van Rossum7131f842007-02-09 20:13:25 +000091 >>> print(y.get())
Tim Peters8485b562004-08-04 18:46:34 +000092 25
93 """
94 def __init__(self, val=0):
95 """
Guido van Rossum7131f842007-02-09 20:13:25 +000096 >>> print(SampleClass.NestedClass().get())
Tim Peters8485b562004-08-04 18:46:34 +000097 0
98 """
99 self.val = val
100 def square(self):
101 return SampleClass.NestedClass(self.val*self.val)
102 def get(self):
103 return self.val
104
105class SampleNewStyleClass(object):
106 r"""
Guido van Rossum7131f842007-02-09 20:13:25 +0000107 >>> print('1\n2\n3')
Tim Peters8485b562004-08-04 18:46:34 +0000108 1
109 2
110 3
111 """
112 def __init__(self, val):
113 """
Guido van Rossum7131f842007-02-09 20:13:25 +0000114 >>> print(SampleNewStyleClass(12).get())
Tim Peters8485b562004-08-04 18:46:34 +0000115 12
116 """
117 self.val = val
118
119 def double(self):
120 """
Guido van Rossum7131f842007-02-09 20:13:25 +0000121 >>> print(SampleNewStyleClass(12).double().get())
Tim Peters8485b562004-08-04 18:46:34 +0000122 24
123 """
124 return SampleNewStyleClass(self.val + self.val)
125
126 def get(self):
127 """
Guido van Rossum7131f842007-02-09 20:13:25 +0000128 >>> print(SampleNewStyleClass(-5).get())
Tim Peters8485b562004-08-04 18:46:34 +0000129 -5
130 """
131 return self.val
132
133######################################################################
Edward Loper2de91ba2004-08-27 02:07:46 +0000134## Fake stdin (for testing interactive debugging)
135######################################################################
136
137class _FakeInput:
138 """
139 A fake input stream for pdb's interactive debugger. Whenever a
140 line is read, print it (to simulate the user typing it), and then
141 return it. The set of lines to return is specified in the
142 constructor; they should not have trailing newlines.
143 """
144 def __init__(self, lines):
145 self.lines = lines
146
147 def readline(self):
148 line = self.lines.pop(0)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000149 print(line)
Edward Loper2de91ba2004-08-27 02:07:46 +0000150 return line+'\n'
151
152######################################################################
Tim Peters8485b562004-08-04 18:46:34 +0000153## Test Cases
154######################################################################
155
156def test_Example(): r"""
157Unit tests for the `Example` class.
158
Edward Lopera6b68322004-08-26 00:05:43 +0000159Example is a simple container class that holds:
160 - `source`: A source string.
161 - `want`: An expected output string.
162 - `exc_msg`: An expected exception message string (or None if no
163 exception is expected).
164 - `lineno`: A line number (within the docstring).
165 - `indent`: The example's indentation in the input string.
166 - `options`: An option dictionary, mapping option flags to True or
167 False.
Tim Peters8485b562004-08-04 18:46:34 +0000168
Edward Lopera6b68322004-08-26 00:05:43 +0000169These attributes are set by the constructor. `source` and `want` are
170required; the other attributes all have default values:
Tim Peters8485b562004-08-04 18:46:34 +0000171
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000172 >>> example = doctest.Example('print(1)', '1\n')
Edward Lopera6b68322004-08-26 00:05:43 +0000173 >>> (example.source, example.want, example.exc_msg,
174 ... example.lineno, example.indent, example.options)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000175 ('print(1)\n', '1\n', None, 0, 0, {})
Edward Lopera6b68322004-08-26 00:05:43 +0000176
177The first three attributes (`source`, `want`, and `exc_msg`) may be
178specified positionally; the remaining arguments should be specified as
179keyword arguments:
180
181 >>> exc_msg = 'IndexError: pop from an empty list'
182 >>> example = doctest.Example('[].pop()', '', exc_msg,
183 ... lineno=5, indent=4,
184 ... options={doctest.ELLIPSIS: True})
185 >>> (example.source, example.want, example.exc_msg,
186 ... example.lineno, example.indent, example.options)
187 ('[].pop()\n', '', 'IndexError: pop from an empty list\n', 5, 4, {8: True})
188
189The constructor normalizes the `source` string to end in a newline:
Tim Peters8485b562004-08-04 18:46:34 +0000190
Tim Petersbb431472004-08-09 03:51:46 +0000191 Source spans a single line: no terminating newline.
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000192 >>> e = doctest.Example('print(1)', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000193 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000194 ('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000195
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000196 >>> e = doctest.Example('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000197 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000198 ('print(1)\n', '1\n')
Tim Peters8485b562004-08-04 18:46:34 +0000199
Tim Petersbb431472004-08-09 03:51:46 +0000200 Source spans multiple lines: require terminating newline.
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000201 >>> e = doctest.Example('print(1);\nprint(2)\n', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000202 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000203 ('print(1);\nprint(2)\n', '1\n2\n')
Tim Peters8485b562004-08-04 18:46:34 +0000204
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000205 >>> e = doctest.Example('print(1);\nprint(2)', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000206 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000207 ('print(1);\nprint(2)\n', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000208
Edward Lopera6b68322004-08-26 00:05:43 +0000209 Empty source string (which should never appear in real examples)
210 >>> e = doctest.Example('', '')
211 >>> e.source, e.want
212 ('\n', '')
Tim Peters8485b562004-08-04 18:46:34 +0000213
Edward Lopera6b68322004-08-26 00:05:43 +0000214The constructor normalizes the `want` string to end in a newline,
215unless it's the empty string:
216
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000217 >>> e = doctest.Example('print(1)', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000218 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000219 ('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000220
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000221 >>> e = doctest.Example('print(1)', '1')
Tim Petersbb431472004-08-09 03:51:46 +0000222 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000223 ('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000224
Edward Lopera6b68322004-08-26 00:05:43 +0000225 >>> e = doctest.Example('print', '')
Tim Petersbb431472004-08-09 03:51:46 +0000226 >>> e.source, e.want
227 ('print\n', '')
Edward Lopera6b68322004-08-26 00:05:43 +0000228
229The constructor normalizes the `exc_msg` string to end in a newline,
230unless it's `None`:
231
232 Message spans one line
233 >>> exc_msg = 'IndexError: pop from an empty list'
234 >>> e = doctest.Example('[].pop()', '', exc_msg)
235 >>> e.exc_msg
236 'IndexError: pop from an empty list\n'
237
238 >>> exc_msg = 'IndexError: pop from an empty list\n'
239 >>> e = doctest.Example('[].pop()', '', exc_msg)
240 >>> e.exc_msg
241 'IndexError: pop from an empty list\n'
242
243 Message spans multiple lines
244 >>> exc_msg = 'ValueError: 1\n 2'
245 >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
246 >>> e.exc_msg
247 'ValueError: 1\n 2\n'
248
249 >>> exc_msg = 'ValueError: 1\n 2\n'
250 >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
251 >>> e.exc_msg
252 'ValueError: 1\n 2\n'
253
254 Empty (but non-None) exception message (which should never appear
255 in real examples)
256 >>> exc_msg = ''
257 >>> e = doctest.Example('raise X()', '', exc_msg)
258 >>> e.exc_msg
259 '\n'
Tim Peters8485b562004-08-04 18:46:34 +0000260"""
261
262def test_DocTest(): r"""
263Unit tests for the `DocTest` class.
264
265DocTest is a collection of examples, extracted from a docstring, along
266with information about where the docstring comes from (a name,
267filename, and line number). The docstring is parsed by the `DocTest`
268constructor:
269
270 >>> docstring = '''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000271 ... >>> print(12)
Tim Peters8485b562004-08-04 18:46:34 +0000272 ... 12
273 ...
274 ... Non-example text.
275 ...
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000276 ... >>> print('another\example')
Tim Peters8485b562004-08-04 18:46:34 +0000277 ... another
278 ... example
279 ... '''
280 >>> globs = {} # globals to run the test in.
Edward Lopera1ef6112004-08-09 16:14:41 +0000281 >>> parser = doctest.DocTestParser()
282 >>> test = parser.get_doctest(docstring, globs, 'some_test',
283 ... 'some_file', 20)
Guido van Rossum7131f842007-02-09 20:13:25 +0000284 >>> print(test)
Tim Peters8485b562004-08-04 18:46:34 +0000285 <DocTest some_test from some_file:20 (2 examples)>
286 >>> len(test.examples)
287 2
288 >>> e1, e2 = test.examples
289 >>> (e1.source, e1.want, e1.lineno)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000290 ('print(12)\n', '12\n', 1)
Tim Peters8485b562004-08-04 18:46:34 +0000291 >>> (e2.source, e2.want, e2.lineno)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000292 ("print('another\\example')\n", 'another\nexample\n', 6)
Tim Peters8485b562004-08-04 18:46:34 +0000293
294Source information (name, filename, and line number) is available as
295attributes on the doctest object:
296
297 >>> (test.name, test.filename, test.lineno)
298 ('some_test', 'some_file', 20)
299
300The line number of an example within its containing file is found by
301adding the line number of the example and the line number of its
302containing test:
303
304 >>> test.lineno + e1.lineno
305 21
306 >>> test.lineno + e2.lineno
307 26
308
309If the docstring contains inconsistant leading whitespace in the
310expected output of an example, then `DocTest` will raise a ValueError:
311
312 >>> docstring = r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000313 ... >>> print('bad\nindentation')
Tim Peters8485b562004-08-04 18:46:34 +0000314 ... bad
315 ... indentation
316 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000317 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000318 Traceback (most recent call last):
Edward Loper00f8da72004-08-26 18:05:07 +0000319 ValueError: line 4 of the docstring for some_test has inconsistent leading whitespace: 'indentation'
Tim Peters8485b562004-08-04 18:46:34 +0000320
321If the docstring contains inconsistent leading whitespace on
322continuation lines, then `DocTest` will raise a ValueError:
323
324 >>> docstring = r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000325 ... >>> print(('bad indentation',
326 ... ... 2))
Tim Peters8485b562004-08-04 18:46:34 +0000327 ... ('bad', 'indentation')
328 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000329 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000330 Traceback (most recent call last):
Guido van Rossume0192e52007-02-09 23:39:59 +0000331 ValueError: line 2 of the docstring for some_test has inconsistent leading whitespace: '... 2))'
Tim Peters8485b562004-08-04 18:46:34 +0000332
333If there's no blank space after a PS1 prompt ('>>>'), then `DocTest`
334will raise a ValueError:
335
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000336 >>> docstring = '>>>print(1)\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000337 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000338 Traceback (most recent call last):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000339 ValueError: line 1 of the docstring for some_test lacks blank after >>>: '>>>print(1)'
Edward Loper7c748462004-08-09 02:06:06 +0000340
341If there's no blank space after a PS2 prompt ('...'), then `DocTest`
342will raise a ValueError:
343
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000344 >>> docstring = '>>> if 1:\n...print(1)\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000345 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Edward Loper7c748462004-08-09 02:06:06 +0000346 Traceback (most recent call last):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000347 ValueError: line 2 of the docstring for some_test lacks blank after ...: '...print(1)'
Edward Loper7c748462004-08-09 02:06:06 +0000348
Tim Peters8485b562004-08-04 18:46:34 +0000349"""
350
Tim Peters8485b562004-08-04 18:46:34 +0000351def test_DocTestFinder(): r"""
352Unit tests for the `DocTestFinder` class.
353
354DocTestFinder is used to extract DocTests from an object's docstring
355and the docstrings of its contained objects. It can be used with
356modules, functions, classes, methods, staticmethods, classmethods, and
357properties.
358
359Finding Tests in Functions
360~~~~~~~~~~~~~~~~~~~~~~~~~~
361For a function whose docstring contains examples, DocTestFinder.find()
362will return a single test (for that function's docstring):
363
Tim Peters8485b562004-08-04 18:46:34 +0000364 >>> finder = doctest.DocTestFinder()
Jim Fulton07a349c2004-08-22 14:10:00 +0000365
366We'll simulate a __file__ attr that ends in pyc:
367
368 >>> import test.test_doctest
369 >>> old = test.test_doctest.__file__
370 >>> test.test_doctest.__file__ = 'test_doctest.pyc'
371
Tim Peters8485b562004-08-04 18:46:34 +0000372 >>> tests = finder.find(sample_func)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000373
Guido van Rossum7131f842007-02-09 20:13:25 +0000374 >>> print(tests) # doctest: +ELLIPSIS
Nick Coghlanf088e5e2008-12-14 11:50:48 +0000375 [<DocTest sample_func from ...:16 (1 example)>]
Edward Loper8e4a34b2004-08-12 02:34:27 +0000376
Tim Peters4de7c5c2004-08-23 22:38:05 +0000377The exact name depends on how test_doctest was invoked, so allow for
378leading path components.
379
380 >>> tests[0].filename # doctest: +ELLIPSIS
381 '...test_doctest.py'
Jim Fulton07a349c2004-08-22 14:10:00 +0000382
383 >>> test.test_doctest.__file__ = old
Tim Petersc6cbab02004-08-22 19:43:28 +0000384
Jim Fulton07a349c2004-08-22 14:10:00 +0000385
Tim Peters8485b562004-08-04 18:46:34 +0000386 >>> e = tests[0].examples[0]
Tim Petersbb431472004-08-09 03:51:46 +0000387 >>> (e.source, e.want, e.lineno)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000388 ('print(sample_func(22))\n', '44\n', 3)
Tim Peters8485b562004-08-04 18:46:34 +0000389
Edward Loper32ddbf72004-09-13 05:47:24 +0000390By default, tests are created for objects with no docstring:
Tim Peters8485b562004-08-04 18:46:34 +0000391
392 >>> def no_docstring(v):
393 ... pass
Tim Peters958cc892004-09-13 14:53:28 +0000394 >>> finder.find(no_docstring)
395 []
Edward Loper32ddbf72004-09-13 05:47:24 +0000396
397However, the optional argument `exclude_empty` to the DocTestFinder
398constructor can be used to exclude tests for objects with empty
399docstrings:
400
401 >>> def no_docstring(v):
402 ... pass
403 >>> excl_empty_finder = doctest.DocTestFinder(exclude_empty=True)
404 >>> excl_empty_finder.find(no_docstring)
Tim Peters8485b562004-08-04 18:46:34 +0000405 []
406
407If the function has a docstring with no examples, then a test with no
408examples is returned. (This lets `DocTestRunner` collect statistics
409about which functions have no tests -- but is that useful? And should
410an empty test also be created when there's no docstring?)
411
412 >>> def no_examples(v):
413 ... ''' no doctest examples '''
Tim Peters17b56372004-09-11 17:33:27 +0000414 >>> finder.find(no_examples) # doctest: +ELLIPSIS
415 [<DocTest no_examples from ...:1 (no examples)>]
Tim Peters8485b562004-08-04 18:46:34 +0000416
417Finding Tests in Classes
418~~~~~~~~~~~~~~~~~~~~~~~~
419For a class, DocTestFinder will create a test for the class's
420docstring, and will recursively explore its contents, including
421methods, classmethods, staticmethods, properties, and nested classes.
422
423 >>> finder = doctest.DocTestFinder()
424 >>> tests = finder.find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000425 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000426 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000427 3 SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000428 3 SampleClass.NestedClass
429 1 SampleClass.NestedClass.__init__
430 1 SampleClass.__init__
431 2 SampleClass.a_classmethod
432 1 SampleClass.a_property
433 1 SampleClass.a_staticmethod
434 1 SampleClass.double
435 1 SampleClass.get
436
437New-style classes are also supported:
438
439 >>> tests = finder.find(SampleNewStyleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000440 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000441 ... print('%2s %s' % (len(t.examples), t.name))
Tim Peters8485b562004-08-04 18:46:34 +0000442 1 SampleNewStyleClass
443 1 SampleNewStyleClass.__init__
444 1 SampleNewStyleClass.double
445 1 SampleNewStyleClass.get
446
447Finding Tests in Modules
448~~~~~~~~~~~~~~~~~~~~~~~~
449For a module, DocTestFinder will create a test for the class's
450docstring, and will recursively explore its contents, including
451functions, classes, and the `__test__` dictionary, if it exists:
452
453 >>> # A module
Christian Heimes45f9af32007-11-27 21:50:00 +0000454 >>> import types
455 >>> m = types.ModuleType('some_module')
Tim Peters8485b562004-08-04 18:46:34 +0000456 >>> def triple(val):
457 ... '''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000458 ... >>> print(triple(11))
Tim Peters8485b562004-08-04 18:46:34 +0000459 ... 33
460 ... '''
461 ... return val*3
462 >>> m.__dict__.update({
463 ... 'sample_func': sample_func,
464 ... 'SampleClass': SampleClass,
465 ... '__doc__': '''
466 ... Module docstring.
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000467 ... >>> print('module')
Tim Peters8485b562004-08-04 18:46:34 +0000468 ... module
469 ... ''',
470 ... '__test__': {
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000471 ... 'd': '>>> print(6)\n6\n>>> print(7)\n7\n',
Tim Peters8485b562004-08-04 18:46:34 +0000472 ... 'c': triple}})
473
474 >>> finder = doctest.DocTestFinder()
475 >>> # Use module=test.test_doctest, to prevent doctest from
476 >>> # ignoring the objects since they weren't defined in m.
477 >>> import test.test_doctest
478 >>> tests = finder.find(m, module=test.test_doctest)
Tim Peters8485b562004-08-04 18:46:34 +0000479 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000480 ... print('%2s %s' % (len(t.examples), t.name))
Tim Peters8485b562004-08-04 18:46:34 +0000481 1 some_module
Edward Loper4ae900f2004-09-21 03:20:34 +0000482 3 some_module.SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000483 3 some_module.SampleClass.NestedClass
484 1 some_module.SampleClass.NestedClass.__init__
485 1 some_module.SampleClass.__init__
486 2 some_module.SampleClass.a_classmethod
487 1 some_module.SampleClass.a_property
488 1 some_module.SampleClass.a_staticmethod
489 1 some_module.SampleClass.double
490 1 some_module.SampleClass.get
Tim Petersc5684782004-09-13 01:07:12 +0000491 1 some_module.__test__.c
492 2 some_module.__test__.d
Tim Peters8485b562004-08-04 18:46:34 +0000493 1 some_module.sample_func
494
495Duplicate Removal
496~~~~~~~~~~~~~~~~~
497If a single object is listed twice (under different names), then tests
498will only be generated for it once:
499
Tim Petersf3f57472004-08-08 06:11:48 +0000500 >>> from test import doctest_aliases
Benjamin Peterson78565b22009-06-28 19:19:51 +0000501 >>> assert doctest_aliases.TwoNames.f
502 >>> assert doctest_aliases.TwoNames.g
Edward Loper32ddbf72004-09-13 05:47:24 +0000503 >>> tests = excl_empty_finder.find(doctest_aliases)
Guido van Rossum7131f842007-02-09 20:13:25 +0000504 >>> print(len(tests))
Tim Peters8485b562004-08-04 18:46:34 +0000505 2
Guido van Rossum7131f842007-02-09 20:13:25 +0000506 >>> print(tests[0].name)
Tim Petersf3f57472004-08-08 06:11:48 +0000507 test.doctest_aliases.TwoNames
508
509 TwoNames.f and TwoNames.g are bound to the same object.
510 We can't guess which will be found in doctest's traversal of
511 TwoNames.__dict__ first, so we have to allow for either.
512
513 >>> tests[1].name.split('.')[-1] in ['f', 'g']
Tim Peters8485b562004-08-04 18:46:34 +0000514 True
515
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000516Empty Tests
517~~~~~~~~~~~
518By default, an object with no doctests doesn't create any tests:
Tim Peters8485b562004-08-04 18:46:34 +0000519
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000520 >>> tests = doctest.DocTestFinder().find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000521 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000522 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000523 3 SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000524 3 SampleClass.NestedClass
525 1 SampleClass.NestedClass.__init__
Tim Peters958cc892004-09-13 14:53:28 +0000526 1 SampleClass.__init__
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000527 2 SampleClass.a_classmethod
528 1 SampleClass.a_property
529 1 SampleClass.a_staticmethod
Tim Peters958cc892004-09-13 14:53:28 +0000530 1 SampleClass.double
531 1 SampleClass.get
532
533By default, that excluded objects with no doctests. exclude_empty=False
534tells it to include (empty) tests for objects with no doctests. This feature
535is really to support backward compatibility in what doctest.master.summarize()
536displays.
537
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000538 >>> tests = doctest.DocTestFinder(exclude_empty=False).find(SampleClass)
Tim Peters958cc892004-09-13 14:53:28 +0000539 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000540 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000541 3 SampleClass
Tim Peters958cc892004-09-13 14:53:28 +0000542 3 SampleClass.NestedClass
543 1 SampleClass.NestedClass.__init__
Edward Loper32ddbf72004-09-13 05:47:24 +0000544 0 SampleClass.NestedClass.get
545 0 SampleClass.NestedClass.square
Tim Peters8485b562004-08-04 18:46:34 +0000546 1 SampleClass.__init__
Tim Peters8485b562004-08-04 18:46:34 +0000547 2 SampleClass.a_classmethod
548 1 SampleClass.a_property
549 1 SampleClass.a_staticmethod
550 1 SampleClass.double
551 1 SampleClass.get
552
Tim Peters8485b562004-08-04 18:46:34 +0000553Turning off Recursion
554~~~~~~~~~~~~~~~~~~~~~
555DocTestFinder can be told not to look for tests in contained objects
556using the `recurse` flag:
557
558 >>> tests = doctest.DocTestFinder(recurse=False).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000559 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000560 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000561 3 SampleClass
Edward Loperb51b2342004-08-17 16:37:12 +0000562
563Line numbers
564~~~~~~~~~~~~
565DocTestFinder finds the line number of each example:
566
567 >>> def f(x):
568 ... '''
569 ... >>> x = 12
570 ...
571 ... some text
572 ...
573 ... >>> # examples are not created for comments & bare prompts.
574 ... >>>
575 ... ...
576 ...
577 ... >>> for x in range(10):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000578 ... ... print(x, end=' ')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000579 ... 0 1 2 3 4 5 6 7 8 9
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000580 ... >>> x//2
581 ... 6
Edward Loperb51b2342004-08-17 16:37:12 +0000582 ... '''
583 >>> test = doctest.DocTestFinder().find(f)[0]
584 >>> [e.lineno for e in test.examples]
585 [1, 9, 12]
Tim Peters8485b562004-08-04 18:46:34 +0000586"""
587
Edward Loper00f8da72004-08-26 18:05:07 +0000588def test_DocTestParser(): r"""
589Unit tests for the `DocTestParser` class.
590
591DocTestParser is used to parse docstrings containing doctest examples.
592
593The `parse` method divides a docstring into examples and intervening
594text:
595
596 >>> s = '''
597 ... >>> x, y = 2, 3 # no output expected
598 ... >>> if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000599 ... ... print(x)
600 ... ... print(y)
Edward Loper00f8da72004-08-26 18:05:07 +0000601 ... 2
602 ... 3
603 ...
604 ... Some text.
605 ... >>> x+y
606 ... 5
607 ... '''
608 >>> parser = doctest.DocTestParser()
609 >>> for piece in parser.parse(s):
610 ... if isinstance(piece, doctest.Example):
Guido van Rossum7131f842007-02-09 20:13:25 +0000611 ... print('Example:', (piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000612 ... else:
Guido van Rossum7131f842007-02-09 20:13:25 +0000613 ... print(' Text:', repr(piece))
Edward Loper00f8da72004-08-26 18:05:07 +0000614 Text: '\n'
615 Example: ('x, y = 2, 3 # no output expected\n', '', 1)
616 Text: ''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000617 Example: ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000618 Text: '\nSome text.\n'
619 Example: ('x+y\n', '5\n', 9)
620 Text: ''
621
622The `get_examples` method returns just the examples:
623
624 >>> for piece in parser.get_examples(s):
Guido van Rossum7131f842007-02-09 20:13:25 +0000625 ... print((piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000626 ('x, y = 2, 3 # no output expected\n', '', 1)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000627 ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000628 ('x+y\n', '5\n', 9)
629
630The `get_doctest` method creates a Test from the examples, along with the
631given arguments:
632
633 >>> test = parser.get_doctest(s, {}, 'name', 'filename', lineno=5)
634 >>> (test.name, test.filename, test.lineno)
635 ('name', 'filename', 5)
636 >>> for piece in test.examples:
Guido van Rossum7131f842007-02-09 20:13:25 +0000637 ... print((piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000638 ('x, y = 2, 3 # no output expected\n', '', 1)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000639 ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000640 ('x+y\n', '5\n', 9)
641"""
642
Tim Peters8485b562004-08-04 18:46:34 +0000643class test_DocTestRunner:
644 def basics(): r"""
645Unit tests for the `DocTestRunner` class.
646
647DocTestRunner is used to run DocTest test cases, and to accumulate
648statistics. Here's a simple DocTest case we can use:
649
650 >>> def f(x):
651 ... '''
652 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000653 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000654 ... 12
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000655 ... >>> x//2
656 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000657 ... '''
658 >>> test = doctest.DocTestFinder().find(f)[0]
659
660The main DocTestRunner interface is the `run` method, which runs a
661given DocTest case in a given namespace (globs). It returns a tuple
662`(f,t)`, where `f` is the number of failed tests and `t` is the number
663of tried tests.
664
665 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000666 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000667
668If any example produces incorrect output, then the test runner reports
669the failure and proceeds to the next example:
670
671 >>> def f(x):
672 ... '''
673 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000674 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000675 ... 14
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000676 ... >>> x//2
677 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000678 ... '''
679 >>> test = doctest.DocTestFinder().find(f)[0]
680 >>> doctest.DocTestRunner(verbose=True).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000681 ... # doctest: +ELLIPSIS
Edward Loperaacf0832004-08-26 01:19:50 +0000682 Trying:
683 x = 12
684 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000685 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000686 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000687 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000688 Expecting:
689 14
Tim Peters8485b562004-08-04 18:46:34 +0000690 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000691 File ..., line 4, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000692 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000693 print(x)
Jim Fulton07a349c2004-08-22 14:10:00 +0000694 Expected:
695 14
696 Got:
697 12
Edward Loperaacf0832004-08-26 01:19:50 +0000698 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000699 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000700 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000701 6
Tim Peters8485b562004-08-04 18:46:34 +0000702 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000703 TestResults(failed=1, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000704"""
705 def verbose_flag(): r"""
706The `verbose` flag makes the test runner generate more detailed
707output:
708
709 >>> def f(x):
710 ... '''
711 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000712 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000713 ... 12
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000714 ... >>> x//2
715 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000716 ... '''
717 >>> test = doctest.DocTestFinder().find(f)[0]
718
719 >>> doctest.DocTestRunner(verbose=True).run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000720 Trying:
721 x = 12
722 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000723 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000724 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000725 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000726 Expecting:
727 12
Tim Peters8485b562004-08-04 18:46:34 +0000728 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000729 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000730 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000731 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000732 6
Tim Peters8485b562004-08-04 18:46:34 +0000733 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000734 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000735
736If the `verbose` flag is unspecified, then the output will be verbose
737iff `-v` appears in sys.argv:
738
739 >>> # Save the real sys.argv list.
740 >>> old_argv = sys.argv
741
742 >>> # If -v does not appear in sys.argv, then output isn't verbose.
743 >>> sys.argv = ['test']
744 >>> doctest.DocTestRunner().run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000745 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000746
747 >>> # If -v does appear in sys.argv, then output is verbose.
748 >>> sys.argv = ['test', '-v']
749 >>> doctest.DocTestRunner().run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000750 Trying:
751 x = 12
752 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000753 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000754 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000755 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000756 Expecting:
757 12
Tim Peters8485b562004-08-04 18:46:34 +0000758 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000759 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000760 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000761 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000762 6
Tim Peters8485b562004-08-04 18:46:34 +0000763 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000764 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000765
766 >>> # Restore sys.argv
767 >>> sys.argv = old_argv
768
769In the remaining examples, the test runner's verbosity will be
770explicitly set, to ensure that the test behavior is consistent.
771 """
772 def exceptions(): r"""
773Tests of `DocTestRunner`'s exception handling.
774
775An expected exception is specified with a traceback message. The
776lines between the first line and the type/value may be omitted or
777replaced with any other string:
778
779 >>> def f(x):
780 ... '''
781 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000782 ... >>> print(x//0)
Tim Peters8485b562004-08-04 18:46:34 +0000783 ... Traceback (most recent call last):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000784 ... ZeroDivisionError: integer division or modulo by zero
Tim Peters8485b562004-08-04 18:46:34 +0000785 ... '''
786 >>> test = doctest.DocTestFinder().find(f)[0]
787 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000788 TestResults(failed=0, attempted=2)
Tim Peters8485b562004-08-04 18:46:34 +0000789
Edward Loper19b19582004-08-25 23:07:03 +0000790An example may not generate output before it raises an exception; if
791it does, then the traceback message will not be recognized as
792signaling an expected exception, so the example will be reported as an
793unexpected exception:
Tim Peters8485b562004-08-04 18:46:34 +0000794
795 >>> def f(x):
796 ... '''
797 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000798 ... >>> print('pre-exception output', x//0)
Tim Peters8485b562004-08-04 18:46:34 +0000799 ... pre-exception output
800 ... Traceback (most recent call last):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000801 ... ZeroDivisionError: integer division or modulo by zero
Tim Peters8485b562004-08-04 18:46:34 +0000802 ... '''
803 >>> test = doctest.DocTestFinder().find(f)[0]
804 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper19b19582004-08-25 23:07:03 +0000805 ... # doctest: +ELLIPSIS
806 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000807 File ..., line 4, in f
Edward Loper19b19582004-08-25 23:07:03 +0000808 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000809 print('pre-exception output', x//0)
Edward Loper19b19582004-08-25 23:07:03 +0000810 Exception raised:
811 ...
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000812 ZeroDivisionError: integer division or modulo by zero
Christian Heimes25bb7832008-01-11 16:17:00 +0000813 TestResults(failed=1, attempted=2)
Tim Peters8485b562004-08-04 18:46:34 +0000814
815Exception messages may contain newlines:
816
817 >>> def f(x):
818 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000819 ... >>> raise ValueError('multi\nline\nmessage')
Tim Peters8485b562004-08-04 18:46:34 +0000820 ... Traceback (most recent call last):
821 ... ValueError: multi
822 ... line
823 ... message
824 ... '''
825 >>> test = doctest.DocTestFinder().find(f)[0]
826 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000827 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000828
829If an exception is expected, but an exception with the wrong type or
830message is raised, then it is reported as a failure:
831
832 >>> def f(x):
833 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000834 ... >>> raise ValueError('message')
Tim Peters8485b562004-08-04 18:46:34 +0000835 ... Traceback (most recent call last):
836 ... ValueError: wrong message
837 ... '''
838 >>> test = doctest.DocTestFinder().find(f)[0]
839 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000840 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000841 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000842 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000843 Failed example:
Collin Winter3add4d72007-08-29 23:37:32 +0000844 raise ValueError('message')
Tim Peters8485b562004-08-04 18:46:34 +0000845 Expected:
846 Traceback (most recent call last):
847 ValueError: wrong message
848 Got:
849 Traceback (most recent call last):
Edward Loper8e4a34b2004-08-12 02:34:27 +0000850 ...
Tim Peters8485b562004-08-04 18:46:34 +0000851 ValueError: message
Christian Heimes25bb7832008-01-11 16:17:00 +0000852 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000853
Tim Peters1fbf9c52004-09-04 17:21:02 +0000854However, IGNORE_EXCEPTION_DETAIL can be used to allow a mismatch in the
855detail:
856
857 >>> def f(x):
858 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000859 ... >>> raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +0000860 ... Traceback (most recent call last):
861 ... ValueError: wrong message
862 ... '''
863 >>> test = doctest.DocTestFinder().find(f)[0]
864 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000865 TestResults(failed=0, attempted=1)
Tim Peters1fbf9c52004-09-04 17:21:02 +0000866
Nick Coghlan5e76e942010-06-12 13:42:46 +0000867IGNORE_EXCEPTION_DETAIL also ignores difference in exception formatting
868between Python versions. For example, in Python 2.x, the module path of
869the exception is not in the output, but this will fail under Python 3:
870
871 >>> def f(x):
872 ... r'''
873 ... >>> from http.client import HTTPException
874 ... >>> raise HTTPException('message')
875 ... Traceback (most recent call last):
876 ... HTTPException: message
877 ... '''
878 >>> test = doctest.DocTestFinder().find(f)[0]
879 >>> doctest.DocTestRunner(verbose=False).run(test)
880 ... # doctest: +ELLIPSIS
881 **********************************************************************
882 File ..., line 4, in f
883 Failed example:
884 raise HTTPException('message')
885 Expected:
886 Traceback (most recent call last):
887 HTTPException: message
888 Got:
889 Traceback (most recent call last):
890 ...
891 http.client.HTTPException: message
892 TestResults(failed=1, attempted=2)
893
894But in Python 3 the module path is included, and therefore a test must look
895like the following test to succeed in Python 3. But that test will fail under
896Python 2.
897
898 >>> def f(x):
899 ... r'''
900 ... >>> from http.client import HTTPException
901 ... >>> raise HTTPException('message')
902 ... Traceback (most recent call last):
903 ... http.client.HTTPException: message
904 ... '''
905 >>> test = doctest.DocTestFinder().find(f)[0]
906 >>> doctest.DocTestRunner(verbose=False).run(test)
907 TestResults(failed=0, attempted=2)
908
909However, with IGNORE_EXCEPTION_DETAIL, the module name of the exception
910(or its unexpected absence) will be ignored:
911
912 >>> def f(x):
913 ... r'''
914 ... >>> from http.client import HTTPException
915 ... >>> raise HTTPException('message') #doctest: +IGNORE_EXCEPTION_DETAIL
916 ... Traceback (most recent call last):
917 ... HTTPException: message
918 ... '''
919 >>> test = doctest.DocTestFinder().find(f)[0]
920 >>> doctest.DocTestRunner(verbose=False).run(test)
921 TestResults(failed=0, attempted=2)
922
923The module path will be completely ignored, so two different module paths will
924still pass if IGNORE_EXCEPTION_DETAIL is given. This is intentional, so it can
925be used when exceptions have changed module.
926
927 >>> def f(x):
928 ... r'''
929 ... >>> from http.client import HTTPException
930 ... >>> raise HTTPException('message') #doctest: +IGNORE_EXCEPTION_DETAIL
931 ... Traceback (most recent call last):
932 ... foo.bar.HTTPException: message
933 ... '''
934 >>> test = doctest.DocTestFinder().find(f)[0]
935 >>> doctest.DocTestRunner(verbose=False).run(test)
936 TestResults(failed=0, attempted=2)
937
Tim Peters1fbf9c52004-09-04 17:21:02 +0000938But IGNORE_EXCEPTION_DETAIL does not allow a mismatch in the exception type:
939
940 >>> def f(x):
941 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000942 ... >>> raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +0000943 ... Traceback (most recent call last):
944 ... TypeError: wrong type
945 ... '''
946 >>> test = doctest.DocTestFinder().find(f)[0]
947 >>> doctest.DocTestRunner(verbose=False).run(test)
948 ... # doctest: +ELLIPSIS
949 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000950 File ..., line 3, in f
Tim Peters1fbf9c52004-09-04 17:21:02 +0000951 Failed example:
Collin Winter3add4d72007-08-29 23:37:32 +0000952 raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +0000953 Expected:
954 Traceback (most recent call last):
955 TypeError: wrong type
956 Got:
957 Traceback (most recent call last):
958 ...
959 ValueError: message
Christian Heimes25bb7832008-01-11 16:17:00 +0000960 TestResults(failed=1, attempted=1)
Tim Peters1fbf9c52004-09-04 17:21:02 +0000961
Tim Peters8485b562004-08-04 18:46:34 +0000962If an exception is raised but not expected, then it is reported as an
963unexpected exception:
964
Tim Peters8485b562004-08-04 18:46:34 +0000965 >>> def f(x):
966 ... r'''
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000967 ... >>> 1//0
Tim Peters8485b562004-08-04 18:46:34 +0000968 ... 0
969 ... '''
970 >>> test = doctest.DocTestFinder().find(f)[0]
971 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper74bca7a2004-08-12 02:27:44 +0000972 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000973 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000974 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000975 Failed example:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000976 1//0
Tim Peters8485b562004-08-04 18:46:34 +0000977 Exception raised:
978 Traceback (most recent call last):
Jim Fulton07a349c2004-08-22 14:10:00 +0000979 ...
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000980 ZeroDivisionError: integer division or modulo by zero
Christian Heimes25bb7832008-01-11 16:17:00 +0000981 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000982"""
Georg Brandl25fbb892010-07-30 09:23:23 +0000983 def displayhook(): r"""
984Test that changing sys.displayhook doesn't matter for doctest.
985
986 >>> import sys
987 >>> orig_displayhook = sys.displayhook
988 >>> def my_displayhook(x):
989 ... print('hi!')
990 >>> sys.displayhook = my_displayhook
991 >>> def f():
992 ... '''
993 ... >>> 3
994 ... 3
995 ... '''
996 >>> test = doctest.DocTestFinder().find(f)[0]
997 >>> r = doctest.DocTestRunner(verbose=False).run(test)
998 >>> post_displayhook = sys.displayhook
999
1000 We need to restore sys.displayhook now, so that we'll be able to test
1001 results.
1002
1003 >>> sys.displayhook = orig_displayhook
1004
1005 Ok, now we can check that everything is ok.
1006
1007 >>> r
1008 TestResults(failed=0, attempted=1)
1009 >>> post_displayhook is my_displayhook
1010 True
1011"""
Tim Peters8485b562004-08-04 18:46:34 +00001012 def optionflags(): r"""
1013Tests of `DocTestRunner`'s option flag handling.
1014
1015Several option flags can be used to customize the behavior of the test
1016runner. These are defined as module constants in doctest, and passed
Christian Heimesfaf2f632008-01-06 16:59:19 +00001017to the DocTestRunner constructor (multiple constants should be ORed
Tim Peters8485b562004-08-04 18:46:34 +00001018together).
1019
1020The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
1021and 1/0:
1022
1023 >>> def f(x):
1024 ... '>>> True\n1\n'
1025
1026 >>> # Without the flag:
1027 >>> test = doctest.DocTestFinder().find(f)[0]
1028 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001029 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001030
1031 >>> # With the flag:
1032 >>> test = doctest.DocTestFinder().find(f)[0]
1033 >>> flags = doctest.DONT_ACCEPT_TRUE_FOR_1
1034 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001035 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001036 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001037 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001038 Failed example:
1039 True
1040 Expected:
1041 1
1042 Got:
1043 True
Christian Heimes25bb7832008-01-11 16:17:00 +00001044 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001045
1046The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines
1047and the '<BLANKLINE>' marker:
1048
1049 >>> def f(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001050 ... '>>> print("a\\n\\nb")\na\n<BLANKLINE>\nb\n'
Tim Peters8485b562004-08-04 18:46:34 +00001051
1052 >>> # Without the flag:
1053 >>> test = doctest.DocTestFinder().find(f)[0]
1054 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001055 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001056
1057 >>> # With the flag:
1058 >>> test = doctest.DocTestFinder().find(f)[0]
1059 >>> flags = doctest.DONT_ACCEPT_BLANKLINE
1060 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001061 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001062 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001063 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001064 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001065 print("a\n\nb")
Tim Peters8485b562004-08-04 18:46:34 +00001066 Expected:
1067 a
1068 <BLANKLINE>
1069 b
1070 Got:
1071 a
1072 <BLANKLINE>
1073 b
Christian Heimes25bb7832008-01-11 16:17:00 +00001074 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001075
1076The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be
1077treated as equal:
1078
1079 >>> def f(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001080 ... '>>> print(1, 2, 3)\n 1 2\n 3'
Tim Peters8485b562004-08-04 18:46:34 +00001081
1082 >>> # Without the flag:
1083 >>> test = doctest.DocTestFinder().find(f)[0]
1084 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001085 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001086 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001087 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001088 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001089 print(1, 2, 3)
Tim Peters8485b562004-08-04 18:46:34 +00001090 Expected:
1091 1 2
1092 3
Jim Fulton07a349c2004-08-22 14:10:00 +00001093 Got:
1094 1 2 3
Christian Heimes25bb7832008-01-11 16:17:00 +00001095 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001096
1097 >>> # With the flag:
1098 >>> test = doctest.DocTestFinder().find(f)[0]
1099 >>> flags = doctest.NORMALIZE_WHITESPACE
1100 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001101 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001102
Tim Peters026f8dc2004-08-19 16:38:58 +00001103 An example from the docs:
Guido van Rossum805365e2007-05-07 22:24:25 +00001104 >>> print(list(range(20))) #doctest: +NORMALIZE_WHITESPACE
Tim Peters026f8dc2004-08-19 16:38:58 +00001105 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
1106 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
1107
Tim Peters8485b562004-08-04 18:46:34 +00001108The ELLIPSIS flag causes ellipsis marker ("...") in the expected
1109output to match any substring in the actual output:
1110
1111 >>> def f(x):
Guido van Rossum805365e2007-05-07 22:24:25 +00001112 ... '>>> print(list(range(15)))\n[0, 1, 2, ..., 14]\n'
Tim Peters8485b562004-08-04 18:46:34 +00001113
1114 >>> # Without the flag:
1115 >>> test = doctest.DocTestFinder().find(f)[0]
1116 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001117 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001118 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001119 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001120 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001121 print(list(range(15)))
Jim Fulton07a349c2004-08-22 14:10:00 +00001122 Expected:
1123 [0, 1, 2, ..., 14]
1124 Got:
1125 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
Christian Heimes25bb7832008-01-11 16:17:00 +00001126 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001127
1128 >>> # With the flag:
1129 >>> test = doctest.DocTestFinder().find(f)[0]
1130 >>> flags = doctest.ELLIPSIS
1131 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001132 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001133
Tim Peterse594bee2004-08-22 01:47:51 +00001134 ... also matches nothing:
Tim Peters1cf3aa62004-08-19 06:49:33 +00001135
Guido van Rossume0192e52007-02-09 23:39:59 +00001136 >>> if 1:
1137 ... for i in range(100):
1138 ... print(i**2, end=' ') #doctest: +ELLIPSIS
1139 ... print('!')
1140 0 1...4...9 16 ... 36 49 64 ... 9801 !
Tim Peters1cf3aa62004-08-19 06:49:33 +00001141
Tim Peters026f8dc2004-08-19 16:38:58 +00001142 ... can be surprising; e.g., this test passes:
Tim Peters26b3ebb2004-08-19 08:10:08 +00001143
Guido van Rossume0192e52007-02-09 23:39:59 +00001144 >>> if 1: #doctest: +ELLIPSIS
1145 ... for i in range(20):
1146 ... print(i, end=' ')
1147 ... print(20)
Tim Peterse594bee2004-08-22 01:47:51 +00001148 0 1 2 ...1...2...0
Tim Peters26b3ebb2004-08-19 08:10:08 +00001149
Tim Peters026f8dc2004-08-19 16:38:58 +00001150 Examples from the docs:
1151
Guido van Rossum805365e2007-05-07 22:24:25 +00001152 >>> print(list(range(20))) # doctest:+ELLIPSIS
Tim Peters026f8dc2004-08-19 16:38:58 +00001153 [0, 1, ..., 18, 19]
1154
Guido van Rossum805365e2007-05-07 22:24:25 +00001155 >>> print(list(range(20))) # doctest: +ELLIPSIS
Tim Peters026f8dc2004-08-19 16:38:58 +00001156 ... # doctest: +NORMALIZE_WHITESPACE
1157 [0, 1, ..., 18, 19]
1158
Thomas Wouters477c8d52006-05-27 19:21:47 +00001159The SKIP flag causes an example to be skipped entirely. I.e., the
1160example is not run. It can be useful in contexts where doctest
1161examples serve as both documentation and test cases, and an example
1162should be included for documentation purposes, but should not be
1163checked (e.g., because its output is random, or depends on resources
1164which would be unavailable.) The SKIP flag can also be used for
1165'commenting out' broken examples.
1166
1167 >>> import unavailable_resource # doctest: +SKIP
1168 >>> unavailable_resource.do_something() # doctest: +SKIP
1169 >>> unavailable_resource.blow_up() # doctest: +SKIP
1170 Traceback (most recent call last):
1171 ...
1172 UncheckedBlowUpError: Nobody checks me.
1173
1174 >>> import random
Guido van Rossum7131f842007-02-09 20:13:25 +00001175 >>> print(random.random()) # doctest: +SKIP
Thomas Wouters477c8d52006-05-27 19:21:47 +00001176 0.721216923889
1177
Edward Loper71f55af2004-08-26 01:41:51 +00001178The REPORT_UDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001179and actual outputs to be displayed using a unified diff:
1180
1181 >>> def f(x):
1182 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001183 ... >>> print('\n'.join('abcdefg'))
Tim Peters8485b562004-08-04 18:46:34 +00001184 ... a
1185 ... B
1186 ... c
1187 ... d
1188 ... f
1189 ... g
1190 ... h
1191 ... '''
1192
1193 >>> # Without the flag:
1194 >>> test = doctest.DocTestFinder().find(f)[0]
1195 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001196 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001197 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001198 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001199 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001200 print('\n'.join('abcdefg'))
Tim Peters8485b562004-08-04 18:46:34 +00001201 Expected:
1202 a
1203 B
1204 c
1205 d
1206 f
1207 g
1208 h
1209 Got:
1210 a
1211 b
1212 c
1213 d
1214 e
1215 f
1216 g
Christian Heimes25bb7832008-01-11 16:17:00 +00001217 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001218
1219 >>> # With the flag:
1220 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001221 >>> flags = doctest.REPORT_UDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001222 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001223 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001224 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001225 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001226 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001227 print('\n'.join('abcdefg'))
Edward Loper56629292004-08-26 01:31:56 +00001228 Differences (unified diff with -expected +actual):
Tim Peterse7edcb82004-08-26 05:44:27 +00001229 @@ -1,7 +1,7 @@
Tim Peters8485b562004-08-04 18:46:34 +00001230 a
1231 -B
1232 +b
1233 c
1234 d
1235 +e
1236 f
1237 g
1238 -h
Christian Heimes25bb7832008-01-11 16:17:00 +00001239 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001240
Edward Loper71f55af2004-08-26 01:41:51 +00001241The REPORT_CDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001242and actual outputs to be displayed using a context diff:
1243
Edward Loper71f55af2004-08-26 01:41:51 +00001244 >>> # Reuse f() from the REPORT_UDIFF example, above.
Tim Peters8485b562004-08-04 18:46:34 +00001245 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001246 >>> flags = doctest.REPORT_CDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001247 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001248 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001249 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001250 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001251 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001252 print('\n'.join('abcdefg'))
Edward Loper56629292004-08-26 01:31:56 +00001253 Differences (context diff with expected followed by actual):
Tim Peters8485b562004-08-04 18:46:34 +00001254 ***************
Tim Peterse7edcb82004-08-26 05:44:27 +00001255 *** 1,7 ****
Tim Peters8485b562004-08-04 18:46:34 +00001256 a
1257 ! B
1258 c
1259 d
1260 f
1261 g
1262 - h
Tim Peterse7edcb82004-08-26 05:44:27 +00001263 --- 1,7 ----
Tim Peters8485b562004-08-04 18:46:34 +00001264 a
1265 ! b
1266 c
1267 d
1268 + e
1269 f
1270 g
Christian Heimes25bb7832008-01-11 16:17:00 +00001271 TestResults(failed=1, attempted=1)
Tim Petersc6cbab02004-08-22 19:43:28 +00001272
1273
Edward Loper71f55af2004-08-26 01:41:51 +00001274The REPORT_NDIFF flag causes failures to use the difflib.Differ algorithm
Tim Petersc6cbab02004-08-22 19:43:28 +00001275used by the popular ndiff.py utility. This does intraline difference
1276marking, as well as interline differences.
1277
1278 >>> def f(x):
1279 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001280 ... >>> print("a b c d e f g h i j k l m")
Tim Petersc6cbab02004-08-22 19:43:28 +00001281 ... a b c d e f g h i j k 1 m
1282 ... '''
1283 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001284 >>> flags = doctest.REPORT_NDIFF
Tim Petersc6cbab02004-08-22 19:43:28 +00001285 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001286 ... # doctest: +ELLIPSIS
Tim Petersc6cbab02004-08-22 19:43:28 +00001287 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001288 File ..., line 3, in f
Tim Petersc6cbab02004-08-22 19:43:28 +00001289 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001290 print("a b c d e f g h i j k l m")
Tim Petersc6cbab02004-08-22 19:43:28 +00001291 Differences (ndiff with -expected +actual):
1292 - a b c d e f g h i j k 1 m
1293 ? ^
1294 + a b c d e f g h i j k l m
1295 ? + ++ ^
Christian Heimes25bb7832008-01-11 16:17:00 +00001296 TestResults(failed=1, attempted=1)
Edward Lopera89f88d2004-08-26 02:45:51 +00001297
1298The REPORT_ONLY_FIRST_FAILURE supresses result output after the first
1299failing example:
1300
1301 >>> def f(x):
1302 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001303 ... >>> print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001304 ... 1
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001305 ... >>> print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001306 ... 200
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001307 ... >>> print(3) # second failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001308 ... 300
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001309 ... >>> print(4) # second success
Edward Lopera89f88d2004-08-26 02:45:51 +00001310 ... 4
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001311 ... >>> print(5) # third failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001312 ... 500
1313 ... '''
1314 >>> test = doctest.DocTestFinder().find(f)[0]
1315 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1316 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001317 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001318 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001319 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001320 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001321 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001322 Expected:
1323 200
1324 Got:
1325 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001326 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001327
1328However, output from `report_start` is not supressed:
1329
1330 >>> doctest.DocTestRunner(verbose=True, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001331 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001332 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001333 print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001334 Expecting:
1335 1
1336 ok
1337 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001338 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001339 Expecting:
1340 200
1341 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001342 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001343 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001344 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001345 Expected:
1346 200
1347 Got:
1348 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001349 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001350
1351For the purposes of REPORT_ONLY_FIRST_FAILURE, unexpected exceptions
1352count as failures:
1353
1354 >>> def f(x):
1355 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001356 ... >>> print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001357 ... 1
1358 ... >>> raise ValueError(2) # first failure
1359 ... 200
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001360 ... >>> print(3) # second failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001361 ... 300
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001362 ... >>> print(4) # second success
Edward Lopera89f88d2004-08-26 02:45:51 +00001363 ... 4
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001364 ... >>> print(5) # third failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001365 ... 500
1366 ... '''
1367 >>> test = doctest.DocTestFinder().find(f)[0]
1368 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1369 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1370 ... # doctest: +ELLIPSIS
1371 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001372 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001373 Failed example:
1374 raise ValueError(2) # first failure
1375 Exception raised:
1376 ...
1377 ValueError: 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001378 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001379
Thomas Wouters477c8d52006-05-27 19:21:47 +00001380New option flags can also be registered, via register_optionflag(). Here
1381we reach into doctest's internals a bit.
1382
1383 >>> unlikely = "UNLIKELY_OPTION_NAME"
1384 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1385 False
1386 >>> new_flag_value = doctest.register_optionflag(unlikely)
1387 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1388 True
1389
1390Before 2.4.4/2.5, registering a name more than once erroneously created
1391more than one flag value. Here we verify that's fixed:
1392
1393 >>> redundant_flag_value = doctest.register_optionflag(unlikely)
1394 >>> redundant_flag_value == new_flag_value
1395 True
1396
1397Clean up.
1398 >>> del doctest.OPTIONFLAGS_BY_NAME[unlikely]
1399
Tim Petersc6cbab02004-08-22 19:43:28 +00001400 """
1401
Tim Peters8485b562004-08-04 18:46:34 +00001402 def option_directives(): r"""
1403Tests of `DocTestRunner`'s option directive mechanism.
1404
Edward Loper74bca7a2004-08-12 02:27:44 +00001405Option directives can be used to turn option flags on or off for a
1406single example. To turn an option on for an example, follow that
1407example with a comment of the form ``# doctest: +OPTION``:
Tim Peters8485b562004-08-04 18:46:34 +00001408
1409 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001410 ... >>> print(list(range(10))) # should fail: no ellipsis
Edward Loper74bca7a2004-08-12 02:27:44 +00001411 ... [0, 1, ..., 9]
1412 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001413 ... >>> print(list(range(10))) # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001414 ... [0, 1, ..., 9]
1415 ... '''
1416 >>> test = doctest.DocTestFinder().find(f)[0]
1417 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001418 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001419 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001420 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001421 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001422 print(list(range(10))) # should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001423 Expected:
1424 [0, 1, ..., 9]
1425 Got:
1426 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001427 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001428
1429To turn an option off for an example, follow that example with a
1430comment of the form ``# doctest: -OPTION``:
1431
1432 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001433 ... >>> print(list(range(10)))
Edward Loper74bca7a2004-08-12 02:27:44 +00001434 ... [0, 1, ..., 9]
1435 ...
1436 ... >>> # should fail: no ellipsis
Guido van Rossum805365e2007-05-07 22:24:25 +00001437 ... >>> print(list(range(10))) # doctest: -ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001438 ... [0, 1, ..., 9]
1439 ... '''
1440 >>> test = doctest.DocTestFinder().find(f)[0]
1441 >>> doctest.DocTestRunner(verbose=False,
1442 ... optionflags=doctest.ELLIPSIS).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001443 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001444 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001445 File ..., line 6, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001446 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001447 print(list(range(10))) # doctest: -ELLIPSIS
Jim Fulton07a349c2004-08-22 14:10:00 +00001448 Expected:
1449 [0, 1, ..., 9]
1450 Got:
1451 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001452 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001453
1454Option directives affect only the example that they appear with; they
1455do not change the options for surrounding examples:
Edward Loper8e4a34b2004-08-12 02:34:27 +00001456
Edward Loper74bca7a2004-08-12 02:27:44 +00001457 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001458 ... >>> print(list(range(10))) # Should fail: no ellipsis
Tim Peters8485b562004-08-04 18:46:34 +00001459 ... [0, 1, ..., 9]
1460 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001461 ... >>> print(list(range(10))) # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001462 ... [0, 1, ..., 9]
1463 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001464 ... >>> print(list(range(10))) # Should fail: no ellipsis
Tim Peters8485b562004-08-04 18:46:34 +00001465 ... [0, 1, ..., 9]
1466 ... '''
1467 >>> test = doctest.DocTestFinder().find(f)[0]
1468 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001469 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001470 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001471 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001472 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001473 print(list(range(10))) # Should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001474 Expected:
1475 [0, 1, ..., 9]
1476 Got:
1477 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001478 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001479 File ..., line 8, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001480 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001481 print(list(range(10))) # Should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001482 Expected:
1483 [0, 1, ..., 9]
1484 Got:
1485 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001486 TestResults(failed=2, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +00001487
Edward Loper74bca7a2004-08-12 02:27:44 +00001488Multiple options may be modified by a single option directive. They
1489may be separated by whitespace, commas, or both:
Tim Peters8485b562004-08-04 18:46:34 +00001490
1491 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001492 ... >>> print(list(range(10))) # Should fail
Tim Peters8485b562004-08-04 18:46:34 +00001493 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001494 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001495 ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001496 ... [0, 1, ..., 9]
1497 ... '''
1498 >>> test = doctest.DocTestFinder().find(f)[0]
1499 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001500 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001501 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001502 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001503 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001504 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001505 Expected:
1506 [0, 1, ..., 9]
1507 Got:
1508 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001509 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001510
1511 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001512 ... >>> print(list(range(10))) # Should fail
Edward Loper74bca7a2004-08-12 02:27:44 +00001513 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001514 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001515 ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
1516 ... [0, 1, ..., 9]
1517 ... '''
1518 >>> test = doctest.DocTestFinder().find(f)[0]
1519 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001520 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001521 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001522 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001523 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001524 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001525 Expected:
1526 [0, 1, ..., 9]
1527 Got:
1528 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001529 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001530
1531 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001532 ... >>> print(list(range(10))) # Should fail
Edward Loper74bca7a2004-08-12 02:27:44 +00001533 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001534 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001535 ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1536 ... [0, 1, ..., 9]
1537 ... '''
1538 >>> test = doctest.DocTestFinder().find(f)[0]
1539 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001540 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001541 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001542 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001543 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001544 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001545 Expected:
1546 [0, 1, ..., 9]
1547 Got:
1548 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001549 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001550
1551The option directive may be put on the line following the source, as
1552long as a continuation prompt is used:
1553
1554 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001555 ... >>> print(list(range(10)))
Edward Loper74bca7a2004-08-12 02:27:44 +00001556 ... ... # doctest: +ELLIPSIS
1557 ... [0, 1, ..., 9]
1558 ... '''
1559 >>> test = doctest.DocTestFinder().find(f)[0]
1560 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001561 TestResults(failed=0, attempted=1)
Edward Loper8e4a34b2004-08-12 02:34:27 +00001562
Edward Loper74bca7a2004-08-12 02:27:44 +00001563For examples with multi-line source, the option directive may appear
1564at the end of any line:
1565
1566 >>> def f(x): r'''
1567 ... >>> for x in range(10): # doctest: +ELLIPSIS
Guido van Rossum805365e2007-05-07 22:24:25 +00001568 ... ... print(' ', x, end='', sep='')
1569 ... 0 1 2 ... 9
Edward Loper74bca7a2004-08-12 02:27:44 +00001570 ...
1571 ... >>> for x in range(10):
Guido van Rossum805365e2007-05-07 22:24:25 +00001572 ... ... print(' ', x, end='', sep='') # doctest: +ELLIPSIS
1573 ... 0 1 2 ... 9
Edward Loper74bca7a2004-08-12 02:27:44 +00001574 ... '''
1575 >>> test = doctest.DocTestFinder().find(f)[0]
1576 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001577 TestResults(failed=0, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001578
1579If more than one line of an example with multi-line source has an
1580option directive, then they are combined:
1581
1582 >>> def f(x): r'''
1583 ... Should fail (option directive not on the last line):
1584 ... >>> for x in range(10): # doctest: +ELLIPSIS
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001585 ... ... print(x, end=' ') # doctest: +NORMALIZE_WHITESPACE
Guido van Rossumd8faa362007-04-27 19:54:29 +00001586 ... 0 1 2...9
Edward Loper74bca7a2004-08-12 02:27:44 +00001587 ... '''
1588 >>> test = doctest.DocTestFinder().find(f)[0]
1589 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001590 TestResults(failed=0, attempted=1)
Edward Loper74bca7a2004-08-12 02:27:44 +00001591
1592It is an error to have a comment of the form ``# doctest:`` that is
1593*not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
1594``OPTION`` is an option that has been registered with
1595`register_option`:
1596
1597 >>> # Error: Option not registered
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001598 >>> s = '>>> print(12) #doctest: +BADOPTION'
Edward Loper74bca7a2004-08-12 02:27:44 +00001599 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1600 Traceback (most recent call last):
1601 ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
1602
1603 >>> # Error: No + or - prefix
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001604 >>> s = '>>> print(12) #doctest: ELLIPSIS'
Edward Loper74bca7a2004-08-12 02:27:44 +00001605 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1606 Traceback (most recent call last):
1607 ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
1608
1609It is an error to use an option directive on a line that contains no
1610source:
1611
1612 >>> s = '>>> # doctest: +ELLIPSIS'
1613 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1614 Traceback (most recent call last):
1615 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 +00001616"""
1617
1618def test_testsource(): r"""
1619Unit tests for `testsource()`.
1620
1621The testsource() function takes a module and a name, finds the (first)
Tim Peters19397e52004-08-06 22:02:59 +00001622test with that name in that module, and converts it to a script. The
1623example code is converted to regular Python code. The surrounding
1624words and expected output are converted to comments:
Tim Peters8485b562004-08-04 18:46:34 +00001625
1626 >>> import test.test_doctest
1627 >>> name = 'test.test_doctest.sample_func'
Guido van Rossum7131f842007-02-09 20:13:25 +00001628 >>> print(doctest.testsource(test.test_doctest, name))
Edward Lopera5db6002004-08-12 02:41:30 +00001629 # Blah blah
Tim Peters19397e52004-08-06 22:02:59 +00001630 #
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001631 print(sample_func(22))
Tim Peters8485b562004-08-04 18:46:34 +00001632 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001633 ## 44
Tim Peters19397e52004-08-06 22:02:59 +00001634 #
Edward Lopera5db6002004-08-12 02:41:30 +00001635 # Yee ha!
Georg Brandlecf93c72005-06-26 23:09:51 +00001636 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001637
1638 >>> name = 'test.test_doctest.SampleNewStyleClass'
Guido van Rossum7131f842007-02-09 20:13:25 +00001639 >>> print(doctest.testsource(test.test_doctest, name))
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001640 print('1\n2\n3')
Tim Peters8485b562004-08-04 18:46:34 +00001641 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001642 ## 1
1643 ## 2
1644 ## 3
Georg Brandlecf93c72005-06-26 23:09:51 +00001645 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001646
1647 >>> name = 'test.test_doctest.SampleClass.a_classmethod'
Guido van Rossum7131f842007-02-09 20:13:25 +00001648 >>> print(doctest.testsource(test.test_doctest, name))
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001649 print(SampleClass.a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +00001650 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001651 ## 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001652 print(SampleClass(0).a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +00001653 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001654 ## 12
Georg Brandlecf93c72005-06-26 23:09:51 +00001655 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001656"""
1657
1658def test_debug(): r"""
1659
1660Create a docstring that we want to debug:
1661
1662 >>> s = '''
1663 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001664 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +00001665 ... 12
1666 ... '''
1667
1668Create some fake stdin input, to feed to the debugger:
1669
Tim Peters8485b562004-08-04 18:46:34 +00001670 >>> real_stdin = sys.stdin
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001671 >>> sys.stdin = _FakeInput(['next', 'print(x)', 'continue'])
Tim Peters8485b562004-08-04 18:46:34 +00001672
1673Run the debugger on the docstring, and then restore sys.stdin.
1674
Edward Loper2de91ba2004-08-27 02:07:46 +00001675 >>> try: doctest.debug_src(s)
1676 ... finally: sys.stdin = real_stdin
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001677 > <string>(1)<module>()
Edward Loper2de91ba2004-08-27 02:07:46 +00001678 (Pdb) next
1679 12
Tim Peters8485b562004-08-04 18:46:34 +00001680 --Return--
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001681 > <string>(1)<module>()->None
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001682 (Pdb) print(x)
Edward Loper2de91ba2004-08-27 02:07:46 +00001683 12
1684 (Pdb) continue
Tim Peters8485b562004-08-04 18:46:34 +00001685
1686"""
1687
Jim Fulton356fd192004-08-09 11:34:47 +00001688def test_pdb_set_trace():
Tim Peters50c6bdb2004-11-08 22:07:37 +00001689 """Using pdb.set_trace from a doctest.
Jim Fulton356fd192004-08-09 11:34:47 +00001690
Tim Peters413ced62004-08-09 15:43:47 +00001691 You can use pdb.set_trace from a doctest. To do so, you must
Jim Fulton356fd192004-08-09 11:34:47 +00001692 retrieve the set_trace function from the pdb module at the time
Tim Peters413ced62004-08-09 15:43:47 +00001693 you use it. The doctest module changes sys.stdout so that it can
1694 capture program output. It also temporarily replaces pdb.set_trace
1695 with a version that restores stdout. This is necessary for you to
Jim Fulton356fd192004-08-09 11:34:47 +00001696 see debugger output.
1697
1698 >>> doc = '''
1699 ... >>> x = 42
Florent Xicluna35049442010-10-14 21:35:58 +00001700 ... >>> raise Exception('clé')
1701 ... Traceback (most recent call last):
1702 ... Exception: clé
Jim Fulton356fd192004-08-09 11:34:47 +00001703 ... >>> import pdb; pdb.set_trace()
1704 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001705 >>> parser = doctest.DocTestParser()
Florent Xiclunad9f57632010-10-14 20:56:20 +00001706 >>> test = parser.get_doctest(doc, {}, "foo-bär@baz", "foo-bär@baz.py", 0)
Jim Fulton356fd192004-08-09 11:34:47 +00001707 >>> runner = doctest.DocTestRunner(verbose=False)
1708
1709 To demonstrate this, we'll create a fake standard input that
1710 captures our debugger input:
1711
1712 >>> import tempfile
Edward Loper2de91ba2004-08-27 02:07:46 +00001713 >>> real_stdin = sys.stdin
1714 >>> sys.stdin = _FakeInput([
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001715 ... 'print(x)', # print data defined by the example
Jim Fulton356fd192004-08-09 11:34:47 +00001716 ... 'continue', # stop debugging
Edward Loper2de91ba2004-08-27 02:07:46 +00001717 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001718
Edward Loper2de91ba2004-08-27 02:07:46 +00001719 >>> try: runner.run(test)
1720 ... finally: sys.stdin = real_stdin
Jim Fulton356fd192004-08-09 11:34:47 +00001721 --Return--
Florent Xicluna35049442010-10-14 21:35:58 +00001722 > <doctest foo-bär@baz[2]>(1)<module>()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001723 -> import pdb; pdb.set_trace()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001724 (Pdb) print(x)
Edward Loper2de91ba2004-08-27 02:07:46 +00001725 42
1726 (Pdb) continue
Florent Xicluna35049442010-10-14 21:35:58 +00001727 TestResults(failed=0, attempted=3)
Jim Fulton356fd192004-08-09 11:34:47 +00001728
1729 You can also put pdb.set_trace in a function called from a test:
1730
1731 >>> def calls_set_trace():
1732 ... y=2
1733 ... import pdb; pdb.set_trace()
1734
1735 >>> doc = '''
1736 ... >>> x=1
1737 ... >>> calls_set_trace()
1738 ... '''
Florent Xiclunad9f57632010-10-14 20:56:20 +00001739 >>> test = parser.get_doctest(doc, globals(), "foo-bär@baz", "foo-bär@baz.py", 0)
Edward Loper2de91ba2004-08-27 02:07:46 +00001740 >>> real_stdin = sys.stdin
1741 >>> sys.stdin = _FakeInput([
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001742 ... 'print(y)', # print data defined in the function
Jim Fulton356fd192004-08-09 11:34:47 +00001743 ... 'up', # out of function
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001744 ... 'print(x)', # print data defined by the example
Jim Fulton356fd192004-08-09 11:34:47 +00001745 ... 'continue', # stop debugging
Edward Loper2de91ba2004-08-27 02:07:46 +00001746 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001747
Tim Peters50c6bdb2004-11-08 22:07:37 +00001748 >>> try:
1749 ... runner.run(test)
1750 ... finally:
1751 ... sys.stdin = real_stdin
Jim Fulton356fd192004-08-09 11:34:47 +00001752 --Return--
Edward Loper2de91ba2004-08-27 02:07:46 +00001753 > <doctest test.test_doctest.test_pdb_set_trace[8]>(3)calls_set_trace()->None
1754 -> import pdb; pdb.set_trace()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001755 (Pdb) print(y)
Edward Loper2de91ba2004-08-27 02:07:46 +00001756 2
1757 (Pdb) up
Florent Xiclunad9f57632010-10-14 20:56:20 +00001758 > <doctest foo-bär@baz[1]>(1)<module>()
Edward Loper2de91ba2004-08-27 02:07:46 +00001759 -> calls_set_trace()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001760 (Pdb) print(x)
Edward Loper2de91ba2004-08-27 02:07:46 +00001761 1
1762 (Pdb) continue
Christian Heimes25bb7832008-01-11 16:17:00 +00001763 TestResults(failed=0, attempted=2)
Edward Loper2de91ba2004-08-27 02:07:46 +00001764
1765 During interactive debugging, source code is shown, even for
1766 doctest examples:
1767
1768 >>> doc = '''
1769 ... >>> def f(x):
1770 ... ... g(x*2)
1771 ... >>> def g(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001772 ... ... print(x+3)
Edward Loper2de91ba2004-08-27 02:07:46 +00001773 ... ... import pdb; pdb.set_trace()
1774 ... >>> f(3)
1775 ... '''
Florent Xiclunad9f57632010-10-14 20:56:20 +00001776 >>> test = parser.get_doctest(doc, globals(), "foo-bär@baz", "foo-bär@baz.py", 0)
Edward Loper2de91ba2004-08-27 02:07:46 +00001777 >>> real_stdin = sys.stdin
1778 >>> sys.stdin = _FakeInput([
1779 ... 'list', # list source from example 2
1780 ... 'next', # return from g()
1781 ... 'list', # list source from example 1
1782 ... 'next', # return from f()
1783 ... 'list', # list source from example 3
1784 ... 'continue', # stop debugging
1785 ... ''])
1786 >>> try: runner.run(test)
1787 ... finally: sys.stdin = real_stdin
1788 ... # doctest: +NORMALIZE_WHITESPACE
1789 --Return--
Florent Xiclunad9f57632010-10-14 20:56:20 +00001790 > <doctest foo-bär@baz[1]>(3)g()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001791 -> import pdb; pdb.set_trace()
1792 (Pdb) list
1793 1 def g(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001794 2 print(x+3)
Edward Loper2de91ba2004-08-27 02:07:46 +00001795 3 -> import pdb; pdb.set_trace()
1796 [EOF]
1797 (Pdb) next
1798 --Return--
Florent Xiclunad9f57632010-10-14 20:56:20 +00001799 > <doctest foo-bär@baz[0]>(2)f()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001800 -> g(x*2)
1801 (Pdb) list
1802 1 def f(x):
1803 2 -> g(x*2)
1804 [EOF]
1805 (Pdb) next
1806 --Return--
Florent Xiclunad9f57632010-10-14 20:56:20 +00001807 > <doctest foo-bär@baz[2]>(1)<module>()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001808 -> f(3)
1809 (Pdb) list
1810 1 -> f(3)
1811 [EOF]
1812 (Pdb) continue
1813 **********************************************************************
Florent Xiclunad9f57632010-10-14 20:56:20 +00001814 File "foo-bär@baz.py", line 7, in foo-bär@baz
Edward Loper2de91ba2004-08-27 02:07:46 +00001815 Failed example:
1816 f(3)
1817 Expected nothing
1818 Got:
1819 9
Christian Heimes25bb7832008-01-11 16:17:00 +00001820 TestResults(failed=1, attempted=3)
Jim Fulton356fd192004-08-09 11:34:47 +00001821 """
1822
Tim Peters50c6bdb2004-11-08 22:07:37 +00001823def test_pdb_set_trace_nested():
1824 """This illustrates more-demanding use of set_trace with nested functions.
1825
1826 >>> class C(object):
1827 ... def calls_set_trace(self):
1828 ... y = 1
1829 ... import pdb; pdb.set_trace()
1830 ... self.f1()
1831 ... y = 2
1832 ... def f1(self):
1833 ... x = 1
1834 ... self.f2()
1835 ... x = 2
1836 ... def f2(self):
1837 ... z = 1
1838 ... z = 2
1839
1840 >>> calls_set_trace = C().calls_set_trace
1841
1842 >>> doc = '''
1843 ... >>> a = 1
1844 ... >>> calls_set_trace()
1845 ... '''
1846 >>> parser = doctest.DocTestParser()
1847 >>> runner = doctest.DocTestRunner(verbose=False)
Florent Xiclunad9f57632010-10-14 20:56:20 +00001848 >>> test = parser.get_doctest(doc, globals(), "foo-bär@baz", "foo-bär@baz.py", 0)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001849 >>> real_stdin = sys.stdin
1850 >>> sys.stdin = _FakeInput([
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001851 ... 'print(y)', # print data defined in the function
1852 ... 'step', 'step', 'step', 'step', 'step', 'step', 'print(z)',
1853 ... 'up', 'print(x)',
1854 ... 'up', 'print(y)',
1855 ... 'up', 'print(foo)',
Tim Peters50c6bdb2004-11-08 22:07:37 +00001856 ... 'continue', # stop debugging
1857 ... ''])
1858
1859 >>> try:
1860 ... runner.run(test)
1861 ... finally:
1862 ... sys.stdin = real_stdin
Guido van Rossum4a625c32007-09-08 16:05:25 +00001863 ... # doctest: +REPORT_NDIFF
Tim Peters50c6bdb2004-11-08 22:07:37 +00001864 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
1865 -> self.f1()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001866 (Pdb) print(y)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001867 1
1868 (Pdb) step
1869 --Call--
1870 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(7)f1()
1871 -> def f1(self):
1872 (Pdb) step
1873 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(8)f1()
1874 -> x = 1
1875 (Pdb) step
1876 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
1877 -> self.f2()
1878 (Pdb) step
1879 --Call--
1880 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(11)f2()
1881 -> def f2(self):
1882 (Pdb) step
1883 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(12)f2()
1884 -> z = 1
1885 (Pdb) step
1886 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(13)f2()
1887 -> z = 2
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001888 (Pdb) print(z)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001889 1
1890 (Pdb) up
1891 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
1892 -> self.f2()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001893 (Pdb) print(x)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001894 1
1895 (Pdb) up
1896 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
1897 -> self.f1()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001898 (Pdb) print(y)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001899 1
1900 (Pdb) up
Florent Xiclunad9f57632010-10-14 20:56:20 +00001901 > <doctest foo-bär@baz[1]>(1)<module>()
Tim Peters50c6bdb2004-11-08 22:07:37 +00001902 -> calls_set_trace()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001903 (Pdb) print(foo)
Georg Brandl0d089622010-07-30 16:00:46 +00001904 *** NameError: name 'foo' is not defined
Tim Peters50c6bdb2004-11-08 22:07:37 +00001905 (Pdb) continue
Christian Heimes25bb7832008-01-11 16:17:00 +00001906 TestResults(failed=0, attempted=2)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001907"""
1908
Tim Peters19397e52004-08-06 22:02:59 +00001909def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +00001910 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +00001911
1912 We create a Suite by providing a module. A module can be provided
1913 by passing a module object:
1914
1915 >>> import unittest
1916 >>> import test.sample_doctest
1917 >>> suite = doctest.DocTestSuite(test.sample_doctest)
1918 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001919 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001920
1921 We can also supply the module by name:
1922
1923 >>> suite = doctest.DocTestSuite('test.sample_doctest')
1924 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001925 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001926
1927 We can use the current module:
1928
1929 >>> suite = test.sample_doctest.test_suite()
1930 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001931 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001932
1933 We can supply global variables. If we pass globs, they will be
1934 used instead of the module globals. Here we'll pass an empty
1935 globals, triggering an extra error:
1936
1937 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
1938 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001939 <unittest.result.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001940
1941 Alternatively, we can provide extra globals. Here we'll make an
1942 error go away by providing an extra global variable:
1943
1944 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1945 ... extraglobs={'y': 1})
1946 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001947 <unittest.result.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001948
1949 You can pass option flags. Here we'll cause an extra error
1950 by disabling the blank-line feature:
1951
1952 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00001953 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00001954 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001955 <unittest.result.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001956
Tim Peters1e277ee2004-08-07 05:37:52 +00001957 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00001958
Jim Fultonf54bad42004-08-28 14:57:56 +00001959 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00001960 ... import test.test_doctest
1961 ... test.test_doctest.sillySetup = True
1962
Jim Fultonf54bad42004-08-28 14:57:56 +00001963 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00001964 ... import test.test_doctest
1965 ... del test.test_doctest.sillySetup
1966
1967 Here, we installed a silly variable that the test expects:
1968
1969 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1970 ... setUp=setUp, tearDown=tearDown)
1971 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001972 <unittest.result.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001973
1974 But the tearDown restores sanity:
1975
1976 >>> import test.test_doctest
1977 >>> test.test_doctest.sillySetup
1978 Traceback (most recent call last):
1979 ...
1980 AttributeError: 'module' object has no attribute 'sillySetup'
1981
Jim Fultonf54bad42004-08-28 14:57:56 +00001982 The setUp and tearDown funtions are passed test objects. Here
1983 we'll use the setUp function to supply the missing variable y:
1984
1985 >>> def setUp(test):
1986 ... test.globs['y'] = 1
1987
1988 >>> suite = doctest.DocTestSuite('test.sample_doctest', setUp=setUp)
1989 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001990 <unittest.result.TestResult run=9 errors=0 failures=3>
Jim Fultonf54bad42004-08-28 14:57:56 +00001991
1992 Here, we didn't need to use a tearDown function because we
1993 modified the test globals, which are a copy of the
1994 sample_doctest module dictionary. The test globals are
1995 automatically cleared for us after a test.
Tim Peters19397e52004-08-06 22:02:59 +00001996 """
1997
1998def test_DocFileSuite():
1999 """We can test tests found in text files using a DocFileSuite.
2000
2001 We create a suite by providing the names of one or more text
2002 files that include examples:
2003
2004 >>> import unittest
2005 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002006 ... 'test_doctest2.txt',
2007 ... 'test_doctest4.txt')
Tim Peters19397e52004-08-06 22:02:59 +00002008 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002009 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002010
2011 The test files are looked for in the directory containing the
2012 calling module. A package keyword argument can be provided to
2013 specify a different relative location.
2014
2015 >>> import unittest
2016 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2017 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002018 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002019 ... package='test')
2020 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002021 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002022
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002023 Support for using a package's __loader__.get_data() is also
2024 provided.
2025
2026 >>> import unittest, pkgutil, test
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002027 >>> added_loader = False
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002028 >>> if not hasattr(test, '__loader__'):
2029 ... test.__loader__ = pkgutil.get_loader(test)
2030 ... added_loader = True
2031 >>> try:
2032 ... suite = doctest.DocFileSuite('test_doctest.txt',
2033 ... 'test_doctest2.txt',
2034 ... 'test_doctest4.txt',
2035 ... package='test')
2036 ... suite.run(unittest.TestResult())
2037 ... finally:
2038 ... if added_loader:
2039 ... del test.__loader__
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002040 <unittest.result.TestResult run=3 errors=0 failures=2>
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002041
Edward Loper0273f5b2004-09-18 20:27:04 +00002042 '/' should be used as a path separator. It will be converted
2043 to a native separator at run time:
Tim Peters19397e52004-08-06 22:02:59 +00002044
2045 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
2046 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002047 <unittest.result.TestResult run=1 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002048
Edward Loper0273f5b2004-09-18 20:27:04 +00002049 If DocFileSuite is used from an interactive session, then files
2050 are resolved relative to the directory of sys.argv[0]:
2051
Christian Heimes45f9af32007-11-27 21:50:00 +00002052 >>> import types, os.path, test.test_doctest
Edward Loper0273f5b2004-09-18 20:27:04 +00002053 >>> save_argv = sys.argv
2054 >>> sys.argv = [test.test_doctest.__file__]
2055 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Christian Heimes45f9af32007-11-27 21:50:00 +00002056 ... package=types.ModuleType('__main__'))
Edward Loper0273f5b2004-09-18 20:27:04 +00002057 >>> sys.argv = save_argv
2058
Edward Loper052d0cd2004-09-19 17:19:33 +00002059 By setting `module_relative=False`, os-specific paths may be
2060 used (including absolute paths and paths relative to the
2061 working directory):
Edward Loper0273f5b2004-09-18 20:27:04 +00002062
2063 >>> # Get the absolute path of the test package.
2064 >>> test_doctest_path = os.path.abspath(test.test_doctest.__file__)
2065 >>> test_pkg_path = os.path.split(test_doctest_path)[0]
2066
2067 >>> # Use it to find the absolute path of test_doctest.txt.
2068 >>> test_file = os.path.join(test_pkg_path, 'test_doctest.txt')
2069
Edward Loper052d0cd2004-09-19 17:19:33 +00002070 >>> suite = doctest.DocFileSuite(test_file, module_relative=False)
Edward Loper0273f5b2004-09-18 20:27:04 +00002071 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002072 <unittest.result.TestResult run=1 errors=0 failures=1>
Edward Loper0273f5b2004-09-18 20:27:04 +00002073
Edward Loper052d0cd2004-09-19 17:19:33 +00002074 It is an error to specify `package` when `module_relative=False`:
2075
2076 >>> suite = doctest.DocFileSuite(test_file, module_relative=False,
2077 ... package='test')
2078 Traceback (most recent call last):
2079 ValueError: Package may only be specified for module-relative paths.
2080
Tim Peters19397e52004-08-06 22:02:59 +00002081 You can specify initial global variables:
2082
2083 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2084 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002085 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002086 ... globs={'favorite_color': 'blue'})
2087 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002088 <unittest.result.TestResult run=3 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002089
2090 In this case, we supplied a missing favorite color. You can
2091 provide doctest options:
2092
2093 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2094 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002095 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002096 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
2097 ... globs={'favorite_color': 'blue'})
2098 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002099 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002100
2101 And, you can provide setUp and tearDown functions:
2102
Jim Fultonf54bad42004-08-28 14:57:56 +00002103 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00002104 ... import test.test_doctest
2105 ... test.test_doctest.sillySetup = True
2106
Jim Fultonf54bad42004-08-28 14:57:56 +00002107 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00002108 ... import test.test_doctest
2109 ... del test.test_doctest.sillySetup
2110
2111 Here, we installed a silly variable that the test expects:
2112
2113 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2114 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002115 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002116 ... setUp=setUp, tearDown=tearDown)
2117 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002118 <unittest.result.TestResult run=3 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002119
2120 But the tearDown restores sanity:
2121
2122 >>> import test.test_doctest
2123 >>> test.test_doctest.sillySetup
2124 Traceback (most recent call last):
2125 ...
2126 AttributeError: 'module' object has no attribute 'sillySetup'
2127
Jim Fultonf54bad42004-08-28 14:57:56 +00002128 The setUp and tearDown funtions are passed test objects.
2129 Here, we'll use a setUp function to set the favorite color in
2130 test_doctest.txt:
2131
2132 >>> def setUp(test):
2133 ... test.globs['favorite_color'] = 'blue'
2134
2135 >>> suite = doctest.DocFileSuite('test_doctest.txt', setUp=setUp)
2136 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002137 <unittest.result.TestResult run=1 errors=0 failures=0>
Jim Fultonf54bad42004-08-28 14:57:56 +00002138
2139 Here, we didn't need to use a tearDown function because we
2140 modified the test globals. The test globals are
2141 automatically cleared for us after a test.
Tim Petersdf7a2082004-08-29 00:38:17 +00002142
Fred Drake7c404a42004-12-21 23:46:34 +00002143 Tests in a file run using `DocFileSuite` can also access the
2144 `__file__` global, which is set to the name of the file
2145 containing the tests:
2146
2147 >>> suite = doctest.DocFileSuite('test_doctest3.txt')
2148 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002149 <unittest.result.TestResult run=1 errors=0 failures=0>
Fred Drake7c404a42004-12-21 23:46:34 +00002150
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002151 If the tests contain non-ASCII characters, we have to specify which
2152 encoding the file is encoded with. We do so by using the `encoding`
2153 parameter:
2154
2155 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2156 ... 'test_doctest2.txt',
2157 ... 'test_doctest4.txt',
2158 ... encoding='utf-8')
2159 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002160 <unittest.result.TestResult run=3 errors=0 failures=2>
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002161
Jim Fultonf54bad42004-08-28 14:57:56 +00002162 """
Tim Peters19397e52004-08-06 22:02:59 +00002163
Jim Fulton07a349c2004-08-22 14:10:00 +00002164def test_trailing_space_in_test():
2165 """
Tim Petersa7def722004-08-23 22:13:22 +00002166 Trailing spaces in expected output are significant:
Tim Petersc6cbab02004-08-22 19:43:28 +00002167
Jim Fulton07a349c2004-08-22 14:10:00 +00002168 >>> x, y = 'foo', ''
Guido van Rossum7131f842007-02-09 20:13:25 +00002169 >>> print(x, y)
Jim Fulton07a349c2004-08-22 14:10:00 +00002170 foo \n
2171 """
Tim Peters19397e52004-08-06 22:02:59 +00002172
Jim Fultonf54bad42004-08-28 14:57:56 +00002173
2174def test_unittest_reportflags():
2175 """Default unittest reporting flags can be set to control reporting
2176
2177 Here, we'll set the REPORT_ONLY_FIRST_FAILURE option so we see
2178 only the first failure of each test. First, we'll look at the
2179 output without the flag. The file test_doctest.txt file has two
2180 tests. They both fail if blank lines are disabled:
2181
2182 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2183 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
2184 >>> import unittest
2185 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002186 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002187 Traceback ...
2188 Failed example:
2189 favorite_color
2190 ...
2191 Failed example:
2192 if 1:
2193 ...
2194
2195 Note that we see both failures displayed.
2196
2197 >>> old = doctest.set_unittest_reportflags(
2198 ... doctest.REPORT_ONLY_FIRST_FAILURE)
2199
2200 Now, when we run the test:
2201
2202 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002203 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002204 Traceback ...
2205 Failed example:
2206 favorite_color
2207 Exception raised:
2208 ...
2209 NameError: name 'favorite_color' is not defined
2210 <BLANKLINE>
2211 <BLANKLINE>
Tim Petersdf7a2082004-08-29 00:38:17 +00002212
Jim Fultonf54bad42004-08-28 14:57:56 +00002213 We get only the first failure.
2214
2215 If we give any reporting options when we set up the tests,
2216 however:
2217
2218 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2219 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE | doctest.REPORT_NDIFF)
2220
2221 Then the default eporting options are ignored:
2222
2223 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002224 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002225 Traceback ...
2226 Failed example:
2227 favorite_color
2228 ...
2229 Failed example:
2230 if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00002231 print('a')
2232 print()
2233 print('b')
Jim Fultonf54bad42004-08-28 14:57:56 +00002234 Differences (ndiff with -expected +actual):
2235 a
2236 - <BLANKLINE>
2237 +
2238 b
2239 <BLANKLINE>
2240 <BLANKLINE>
2241
2242
2243 Test runners can restore the formatting flags after they run:
2244
2245 >>> ignored = doctest.set_unittest_reportflags(old)
2246
2247 """
2248
Edward Loper052d0cd2004-09-19 17:19:33 +00002249def test_testfile(): r"""
2250Tests for the `testfile()` function. This function runs all the
2251doctest examples in a given file. In its simple invokation, it is
2252called with the name of a file, which is taken to be relative to the
2253calling module. The return value is (#failures, #tests).
2254
Florent Xicluna59250852010-02-27 14:21:57 +00002255We don't want `-v` in sys.argv for these tests.
2256
2257 >>> save_argv = sys.argv
2258 >>> if '-v' in sys.argv:
2259 ... sys.argv = [arg for arg in save_argv if arg != '-v']
2260
2261
Edward Loper052d0cd2004-09-19 17:19:33 +00002262 >>> doctest.testfile('test_doctest.txt') # doctest: +ELLIPSIS
2263 **********************************************************************
2264 File "...", line 6, in test_doctest.txt
2265 Failed example:
2266 favorite_color
2267 Exception raised:
2268 ...
2269 NameError: name 'favorite_color' is not defined
2270 **********************************************************************
2271 1 items had failures:
2272 1 of 2 in test_doctest.txt
2273 ***Test Failed*** 1 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002274 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002275 >>> doctest.master = None # Reset master.
2276
2277(Note: we'll be clearing doctest.master after each call to
2278`doctest.testfile`, to supress warnings about multiple tests with the
2279same name.)
2280
2281Globals may be specified with the `globs` and `extraglobs` parameters:
2282
2283 >>> globs = {'favorite_color': 'blue'}
2284 >>> doctest.testfile('test_doctest.txt', globs=globs)
Christian Heimes25bb7832008-01-11 16:17:00 +00002285 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002286 >>> doctest.master = None # Reset master.
2287
2288 >>> extraglobs = {'favorite_color': 'red'}
2289 >>> doctest.testfile('test_doctest.txt', globs=globs,
2290 ... extraglobs=extraglobs) # doctest: +ELLIPSIS
2291 **********************************************************************
2292 File "...", line 6, in test_doctest.txt
2293 Failed example:
2294 favorite_color
2295 Expected:
2296 'blue'
2297 Got:
2298 'red'
2299 **********************************************************************
2300 1 items had failures:
2301 1 of 2 in test_doctest.txt
2302 ***Test Failed*** 1 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002303 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002304 >>> doctest.master = None # Reset master.
2305
2306The file may be made relative to a given module or package, using the
2307optional `module_relative` parameter:
2308
2309 >>> doctest.testfile('test_doctest.txt', globs=globs,
2310 ... module_relative='test')
Christian Heimes25bb7832008-01-11 16:17:00 +00002311 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002312 >>> doctest.master = None # Reset master.
2313
2314Verbosity can be increased with the optional `verbose` paremter:
2315
2316 >>> doctest.testfile('test_doctest.txt', globs=globs, verbose=True)
2317 Trying:
2318 favorite_color
2319 Expecting:
2320 'blue'
2321 ok
2322 Trying:
2323 if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00002324 print('a')
2325 print()
2326 print('b')
Edward Loper052d0cd2004-09-19 17:19:33 +00002327 Expecting:
2328 a
2329 <BLANKLINE>
2330 b
2331 ok
2332 1 items passed all tests:
2333 2 tests in test_doctest.txt
2334 2 tests in 1 items.
2335 2 passed and 0 failed.
2336 Test passed.
Christian Heimes25bb7832008-01-11 16:17:00 +00002337 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002338 >>> doctest.master = None # Reset master.
2339
2340The name of the test may be specified with the optional `name`
2341parameter:
2342
2343 >>> doctest.testfile('test_doctest.txt', name='newname')
2344 ... # doctest: +ELLIPSIS
2345 **********************************************************************
2346 File "...", line 6, in newname
2347 ...
Christian Heimes25bb7832008-01-11 16:17:00 +00002348 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002349 >>> doctest.master = None # Reset master.
2350
2351The summary report may be supressed with the optional `report`
2352parameter:
2353
2354 >>> doctest.testfile('test_doctest.txt', report=False)
2355 ... # doctest: +ELLIPSIS
2356 **********************************************************************
2357 File "...", line 6, in test_doctest.txt
2358 Failed example:
2359 favorite_color
2360 Exception raised:
2361 ...
2362 NameError: name 'favorite_color' is not defined
Christian Heimes25bb7832008-01-11 16:17:00 +00002363 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002364 >>> doctest.master = None # Reset master.
2365
2366The optional keyword argument `raise_on_error` can be used to raise an
2367exception on the first error (which may be useful for postmortem
2368debugging):
2369
2370 >>> doctest.testfile('test_doctest.txt', raise_on_error=True)
2371 ... # doctest: +ELLIPSIS
2372 Traceback (most recent call last):
Guido van Rossum6a2a2a02006-08-26 20:37:44 +00002373 doctest.UnexpectedException: ...
Edward Loper052d0cd2004-09-19 17:19:33 +00002374 >>> doctest.master = None # Reset master.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002375
2376If the tests contain non-ASCII characters, the tests might fail, since
2377it's unknown which encoding is used. The encoding can be specified
2378using the optional keyword argument `encoding`:
2379
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002380 >>> doctest.testfile('test_doctest4.txt', encoding='latin-1') # doctest: +ELLIPSIS
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002381 **********************************************************************
2382 File "...", line 7, in test_doctest4.txt
2383 Failed example:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002384 '...'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002385 Expected:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002386 'f\xf6\xf6'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002387 Got:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002388 'f\xc3\xb6\xc3\xb6'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002389 **********************************************************************
2390 ...
2391 **********************************************************************
2392 1 items had failures:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002393 2 of 2 in test_doctest4.txt
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002394 ***Test Failed*** 2 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002395 TestResults(failed=2, attempted=2)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002396 >>> doctest.master = None # Reset master.
2397
2398 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8')
Christian Heimes25bb7832008-01-11 16:17:00 +00002399 TestResults(failed=0, attempted=2)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002400 >>> doctest.master = None # Reset master.
Florent Xicluna59250852010-02-27 14:21:57 +00002401
2402Test the verbose output:
2403
2404 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8', verbose=True)
2405 Trying:
2406 'föö'
2407 Expecting:
2408 'f\xf6\xf6'
2409 ok
2410 Trying:
2411 'bąr'
2412 Expecting:
2413 'b\u0105r'
2414 ok
2415 1 items passed all tests:
2416 2 tests in test_doctest4.txt
2417 2 tests in 1 items.
2418 2 passed and 0 failed.
2419 Test passed.
2420 TestResults(failed=0, attempted=2)
2421 >>> doctest.master = None # Reset master.
2422 >>> sys.argv = save_argv
Edward Loper052d0cd2004-09-19 17:19:33 +00002423"""
2424
R. David Murray58641de2009-06-12 15:33:19 +00002425def test_testmod(): r"""
2426Tests for the testmod function. More might be useful, but for now we're just
2427testing the case raised by Issue 6195, where trying to doctest a C module would
2428fail with a UnicodeDecodeError because doctest tried to read the "source" lines
2429out of the binary module.
2430
2431 >>> import unicodedata
Florent Xicluna59250852010-02-27 14:21:57 +00002432 >>> doctest.testmod(unicodedata, verbose=False)
R. David Murray58641de2009-06-12 15:33:19 +00002433 TestResults(failed=0, attempted=0)
2434"""
2435
Tim Peters8485b562004-08-04 18:46:34 +00002436######################################################################
2437## Main
2438######################################################################
2439
2440def test_main():
2441 # Check the doctest cases in doctest itself:
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002442 support.run_doctest(doctest, verbosity=True)
Tim Peters8485b562004-08-04 18:46:34 +00002443 # Check the doctest cases defined here:
2444 from test import test_doctest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002445 support.run_doctest(test_doctest, verbosity=True)
Tim Peters8485b562004-08-04 18:46:34 +00002446
Victor Stinner45df8202010-04-28 22:31:17 +00002447import sys, re, io
2448
Tim Peters8485b562004-08-04 18:46:34 +00002449def test_coverage(coverdir):
Victor Stinner45df8202010-04-28 22:31:17 +00002450 trace = support.import_module('trace')
Tim Peters8485b562004-08-04 18:46:34 +00002451 tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
2452 trace=0, count=1)
Guido van Rossume7ba4952007-06-06 23:52:48 +00002453 tracer.run('test_main()')
Tim Peters8485b562004-08-04 18:46:34 +00002454 r = tracer.results()
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002455 print('Writing coverage results...')
Tim Peters8485b562004-08-04 18:46:34 +00002456 r.write_results(show_missing=True, summary=True,
2457 coverdir=coverdir)
2458
2459if __name__ == '__main__':
2460 if '-c' in sys.argv:
2461 test_coverage('/tmp/doctest.cover')
2462 else:
2463 test_main()