blob: de85758ac50eb16d3daa191446c65ac94a2c2672 [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
Tim Petersa7def722004-08-23 22:13:22 +00007import warnings
Tim Peters8485b562004-08-04 18:46:34 +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
Edward Loper32ddbf72004-09-13 05:47:24 +0000501 >>> tests = excl_empty_finder.find(doctest_aliases)
Guido van Rossum7131f842007-02-09 20:13:25 +0000502 >>> print(len(tests))
Tim Peters8485b562004-08-04 18:46:34 +0000503 2
Guido van Rossum7131f842007-02-09 20:13:25 +0000504 >>> print(tests[0].name)
Tim Petersf3f57472004-08-08 06:11:48 +0000505 test.doctest_aliases.TwoNames
506
507 TwoNames.f and TwoNames.g are bound to the same object.
508 We can't guess which will be found in doctest's traversal of
509 TwoNames.__dict__ first, so we have to allow for either.
510
511 >>> tests[1].name.split('.')[-1] in ['f', 'g']
Tim Peters8485b562004-08-04 18:46:34 +0000512 True
513
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000514Empty Tests
515~~~~~~~~~~~
516By default, an object with no doctests doesn't create any tests:
Tim Peters8485b562004-08-04 18:46:34 +0000517
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000518 >>> tests = doctest.DocTestFinder().find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000519 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000520 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000521 3 SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000522 3 SampleClass.NestedClass
523 1 SampleClass.NestedClass.__init__
Tim Peters958cc892004-09-13 14:53:28 +0000524 1 SampleClass.__init__
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000525 2 SampleClass.a_classmethod
526 1 SampleClass.a_property
527 1 SampleClass.a_staticmethod
Tim Peters958cc892004-09-13 14:53:28 +0000528 1 SampleClass.double
529 1 SampleClass.get
530
531By default, that excluded objects with no doctests. exclude_empty=False
532tells it to include (empty) tests for objects with no doctests. This feature
533is really to support backward compatibility in what doctest.master.summarize()
534displays.
535
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000536 >>> tests = doctest.DocTestFinder(exclude_empty=False).find(SampleClass)
Tim Peters958cc892004-09-13 14:53:28 +0000537 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000538 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000539 3 SampleClass
Tim Peters958cc892004-09-13 14:53:28 +0000540 3 SampleClass.NestedClass
541 1 SampleClass.NestedClass.__init__
Edward Loper32ddbf72004-09-13 05:47:24 +0000542 0 SampleClass.NestedClass.get
543 0 SampleClass.NestedClass.square
Tim Peters8485b562004-08-04 18:46:34 +0000544 1 SampleClass.__init__
Tim Peters8485b562004-08-04 18:46:34 +0000545 2 SampleClass.a_classmethod
546 1 SampleClass.a_property
547 1 SampleClass.a_staticmethod
548 1 SampleClass.double
549 1 SampleClass.get
550
Tim Peters8485b562004-08-04 18:46:34 +0000551Turning off Recursion
552~~~~~~~~~~~~~~~~~~~~~
553DocTestFinder can be told not to look for tests in contained objects
554using the `recurse` flag:
555
556 >>> tests = doctest.DocTestFinder(recurse=False).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000557 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000558 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000559 3 SampleClass
Edward Loperb51b2342004-08-17 16:37:12 +0000560
561Line numbers
562~~~~~~~~~~~~
563DocTestFinder finds the line number of each example:
564
565 >>> def f(x):
566 ... '''
567 ... >>> x = 12
568 ...
569 ... some text
570 ...
571 ... >>> # examples are not created for comments & bare prompts.
572 ... >>>
573 ... ...
574 ...
575 ... >>> for x in range(10):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000576 ... ... print(x, end=' ')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000577 ... 0 1 2 3 4 5 6 7 8 9
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000578 ... >>> x//2
579 ... 6
Edward Loperb51b2342004-08-17 16:37:12 +0000580 ... '''
581 >>> test = doctest.DocTestFinder().find(f)[0]
582 >>> [e.lineno for e in test.examples]
583 [1, 9, 12]
Tim Peters8485b562004-08-04 18:46:34 +0000584"""
585
Edward Loper00f8da72004-08-26 18:05:07 +0000586def test_DocTestParser(): r"""
587Unit tests for the `DocTestParser` class.
588
589DocTestParser is used to parse docstrings containing doctest examples.
590
591The `parse` method divides a docstring into examples and intervening
592text:
593
594 >>> s = '''
595 ... >>> x, y = 2, 3 # no output expected
596 ... >>> if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000597 ... ... print(x)
598 ... ... print(y)
Edward Loper00f8da72004-08-26 18:05:07 +0000599 ... 2
600 ... 3
601 ...
602 ... Some text.
603 ... >>> x+y
604 ... 5
605 ... '''
606 >>> parser = doctest.DocTestParser()
607 >>> for piece in parser.parse(s):
608 ... if isinstance(piece, doctest.Example):
Guido van Rossum7131f842007-02-09 20:13:25 +0000609 ... print('Example:', (piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000610 ... else:
Guido van Rossum7131f842007-02-09 20:13:25 +0000611 ... print(' Text:', repr(piece))
Edward Loper00f8da72004-08-26 18:05:07 +0000612 Text: '\n'
613 Example: ('x, y = 2, 3 # no output expected\n', '', 1)
614 Text: ''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000615 Example: ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000616 Text: '\nSome text.\n'
617 Example: ('x+y\n', '5\n', 9)
618 Text: ''
619
620The `get_examples` method returns just the examples:
621
622 >>> for piece in parser.get_examples(s):
Guido van Rossum7131f842007-02-09 20:13:25 +0000623 ... print((piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000624 ('x, y = 2, 3 # no output expected\n', '', 1)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000625 ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000626 ('x+y\n', '5\n', 9)
627
628The `get_doctest` method creates a Test from the examples, along with the
629given arguments:
630
631 >>> test = parser.get_doctest(s, {}, 'name', 'filename', lineno=5)
632 >>> (test.name, test.filename, test.lineno)
633 ('name', 'filename', 5)
634 >>> for piece in test.examples:
Guido van Rossum7131f842007-02-09 20:13:25 +0000635 ... print((piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000636 ('x, y = 2, 3 # no output expected\n', '', 1)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000637 ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000638 ('x+y\n', '5\n', 9)
639"""
640
Tim Peters8485b562004-08-04 18:46:34 +0000641class test_DocTestRunner:
642 def basics(): r"""
643Unit tests for the `DocTestRunner` class.
644
645DocTestRunner is used to run DocTest test cases, and to accumulate
646statistics. Here's a simple DocTest case we can use:
647
648 >>> def f(x):
649 ... '''
650 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000651 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000652 ... 12
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000653 ... >>> x//2
654 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000655 ... '''
656 >>> test = doctest.DocTestFinder().find(f)[0]
657
658The main DocTestRunner interface is the `run` method, which runs a
659given DocTest case in a given namespace (globs). It returns a tuple
660`(f,t)`, where `f` is the number of failed tests and `t` is the number
661of tried tests.
662
663 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000664 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000665
666If any example produces incorrect output, then the test runner reports
667the failure and proceeds to the next example:
668
669 >>> def f(x):
670 ... '''
671 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000672 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000673 ... 14
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000674 ... >>> x//2
675 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000676 ... '''
677 >>> test = doctest.DocTestFinder().find(f)[0]
678 >>> doctest.DocTestRunner(verbose=True).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000679 ... # doctest: +ELLIPSIS
Edward Loperaacf0832004-08-26 01:19:50 +0000680 Trying:
681 x = 12
682 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000683 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000684 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000685 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000686 Expecting:
687 14
Tim Peters8485b562004-08-04 18:46:34 +0000688 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000689 File ..., line 4, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000690 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000691 print(x)
Jim Fulton07a349c2004-08-22 14:10:00 +0000692 Expected:
693 14
694 Got:
695 12
Edward Loperaacf0832004-08-26 01:19:50 +0000696 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000697 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000698 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000699 6
Tim Peters8485b562004-08-04 18:46:34 +0000700 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000701 TestResults(failed=1, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000702"""
703 def verbose_flag(): r"""
704The `verbose` flag makes the test runner generate more detailed
705output:
706
707 >>> def f(x):
708 ... '''
709 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000710 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000711 ... 12
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000712 ... >>> x//2
713 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000714 ... '''
715 >>> test = doctest.DocTestFinder().find(f)[0]
716
717 >>> doctest.DocTestRunner(verbose=True).run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000718 Trying:
719 x = 12
720 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000721 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000722 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000723 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000724 Expecting:
725 12
Tim Peters8485b562004-08-04 18:46:34 +0000726 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000727 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000728 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000729 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000730 6
Tim Peters8485b562004-08-04 18:46:34 +0000731 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000732 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000733
734If the `verbose` flag is unspecified, then the output will be verbose
735iff `-v` appears in sys.argv:
736
737 >>> # Save the real sys.argv list.
738 >>> old_argv = sys.argv
739
740 >>> # If -v does not appear in sys.argv, then output isn't verbose.
741 >>> sys.argv = ['test']
742 >>> doctest.DocTestRunner().run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000743 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000744
745 >>> # If -v does appear in sys.argv, then output is verbose.
746 >>> sys.argv = ['test', '-v']
747 >>> doctest.DocTestRunner().run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000748 Trying:
749 x = 12
750 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000751 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000752 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000753 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000754 Expecting:
755 12
Tim Peters8485b562004-08-04 18:46:34 +0000756 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000757 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000758 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000759 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000760 6
Tim Peters8485b562004-08-04 18:46:34 +0000761 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000762 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000763
764 >>> # Restore sys.argv
765 >>> sys.argv = old_argv
766
767In the remaining examples, the test runner's verbosity will be
768explicitly set, to ensure that the test behavior is consistent.
769 """
770 def exceptions(): r"""
771Tests of `DocTestRunner`'s exception handling.
772
773An expected exception is specified with a traceback message. The
774lines between the first line and the type/value may be omitted or
775replaced with any other string:
776
777 >>> def f(x):
778 ... '''
779 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000780 ... >>> print(x//0)
Tim Peters8485b562004-08-04 18:46:34 +0000781 ... Traceback (most recent call last):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000782 ... ZeroDivisionError: integer division or modulo by zero
Tim Peters8485b562004-08-04 18:46:34 +0000783 ... '''
784 >>> test = doctest.DocTestFinder().find(f)[0]
785 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000786 TestResults(failed=0, attempted=2)
Tim Peters8485b562004-08-04 18:46:34 +0000787
Edward Loper19b19582004-08-25 23:07:03 +0000788An example may not generate output before it raises an exception; if
789it does, then the traceback message will not be recognized as
790signaling an expected exception, so the example will be reported as an
791unexpected exception:
Tim Peters8485b562004-08-04 18:46:34 +0000792
793 >>> def f(x):
794 ... '''
795 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000796 ... >>> print('pre-exception output', x//0)
Tim Peters8485b562004-08-04 18:46:34 +0000797 ... pre-exception output
798 ... Traceback (most recent call last):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000799 ... ZeroDivisionError: integer division or modulo by zero
Tim Peters8485b562004-08-04 18:46:34 +0000800 ... '''
801 >>> test = doctest.DocTestFinder().find(f)[0]
802 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper19b19582004-08-25 23:07:03 +0000803 ... # doctest: +ELLIPSIS
804 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000805 File ..., line 4, in f
Edward Loper19b19582004-08-25 23:07:03 +0000806 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000807 print('pre-exception output', x//0)
Edward Loper19b19582004-08-25 23:07:03 +0000808 Exception raised:
809 ...
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000810 ZeroDivisionError: integer division or modulo by zero
Christian Heimes25bb7832008-01-11 16:17:00 +0000811 TestResults(failed=1, attempted=2)
Tim Peters8485b562004-08-04 18:46:34 +0000812
813Exception messages may contain newlines:
814
815 >>> def f(x):
816 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000817 ... >>> raise ValueError('multi\nline\nmessage')
Tim Peters8485b562004-08-04 18:46:34 +0000818 ... Traceback (most recent call last):
819 ... ValueError: multi
820 ... line
821 ... message
822 ... '''
823 >>> test = doctest.DocTestFinder().find(f)[0]
824 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000825 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000826
827If an exception is expected, but an exception with the wrong type or
828message is raised, then it is reported as a failure:
829
830 >>> def f(x):
831 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000832 ... >>> raise ValueError('message')
Tim Peters8485b562004-08-04 18:46:34 +0000833 ... Traceback (most recent call last):
834 ... ValueError: wrong message
835 ... '''
836 >>> test = doctest.DocTestFinder().find(f)[0]
837 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000838 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000839 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000840 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000841 Failed example:
Collin Winter3add4d72007-08-29 23:37:32 +0000842 raise ValueError('message')
Tim Peters8485b562004-08-04 18:46:34 +0000843 Expected:
844 Traceback (most recent call last):
845 ValueError: wrong message
846 Got:
847 Traceback (most recent call last):
Edward Loper8e4a34b2004-08-12 02:34:27 +0000848 ...
Tim Peters8485b562004-08-04 18:46:34 +0000849 ValueError: message
Christian Heimes25bb7832008-01-11 16:17:00 +0000850 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000851
Tim Peters1fbf9c52004-09-04 17:21:02 +0000852However, IGNORE_EXCEPTION_DETAIL can be used to allow a mismatch in the
853detail:
854
855 >>> def f(x):
856 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000857 ... >>> raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +0000858 ... Traceback (most recent call last):
859 ... ValueError: wrong message
860 ... '''
861 >>> test = doctest.DocTestFinder().find(f)[0]
862 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000863 TestResults(failed=0, attempted=1)
Tim Peters1fbf9c52004-09-04 17:21:02 +0000864
865But IGNORE_EXCEPTION_DETAIL does not allow a mismatch in the exception type:
866
867 >>> def f(x):
868 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000869 ... >>> raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +0000870 ... Traceback (most recent call last):
871 ... TypeError: wrong type
872 ... '''
873 >>> test = doctest.DocTestFinder().find(f)[0]
874 >>> doctest.DocTestRunner(verbose=False).run(test)
875 ... # doctest: +ELLIPSIS
876 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000877 File ..., line 3, in f
Tim Peters1fbf9c52004-09-04 17:21:02 +0000878 Failed example:
Collin Winter3add4d72007-08-29 23:37:32 +0000879 raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +0000880 Expected:
881 Traceback (most recent call last):
882 TypeError: wrong type
883 Got:
884 Traceback (most recent call last):
885 ...
886 ValueError: message
Christian Heimes25bb7832008-01-11 16:17:00 +0000887 TestResults(failed=1, attempted=1)
Tim Peters1fbf9c52004-09-04 17:21:02 +0000888
Tim Peters8485b562004-08-04 18:46:34 +0000889If an exception is raised but not expected, then it is reported as an
890unexpected exception:
891
Tim Peters8485b562004-08-04 18:46:34 +0000892 >>> def f(x):
893 ... r'''
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000894 ... >>> 1//0
Tim Peters8485b562004-08-04 18:46:34 +0000895 ... 0
896 ... '''
897 >>> test = doctest.DocTestFinder().find(f)[0]
898 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper74bca7a2004-08-12 02:27:44 +0000899 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000900 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000901 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000902 Failed example:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000903 1//0
Tim Peters8485b562004-08-04 18:46:34 +0000904 Exception raised:
905 Traceback (most recent call last):
Jim Fulton07a349c2004-08-22 14:10:00 +0000906 ...
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000907 ZeroDivisionError: integer division or modulo by zero
Christian Heimes25bb7832008-01-11 16:17:00 +0000908 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000909"""
Georg Brandl469d3e72010-08-01 19:35:16 +0000910 def displayhook(): r"""
911Test that changing sys.displayhook doesn't matter for doctest.
912
913 >>> import sys
914 >>> orig_displayhook = sys.displayhook
915 >>> def my_displayhook(x):
916 ... print('hi!')
917 >>> sys.displayhook = my_displayhook
918 >>> def f():
919 ... '''
920 ... >>> 3
921 ... 3
922 ... '''
923 >>> test = doctest.DocTestFinder().find(f)[0]
924 >>> r = doctest.DocTestRunner(verbose=False).run(test)
925 >>> post_displayhook = sys.displayhook
926
927 We need to restore sys.displayhook now, so that we'll be able to test
928 results.
929
930 >>> sys.displayhook = orig_displayhook
931
932 Ok, now we can check that everything is ok.
933
934 >>> r
935 TestResults(failed=0, attempted=1)
936 >>> post_displayhook is my_displayhook
937 True
938"""
Tim Peters8485b562004-08-04 18:46:34 +0000939 def optionflags(): r"""
940Tests of `DocTestRunner`'s option flag handling.
941
942Several option flags can be used to customize the behavior of the test
943runner. These are defined as module constants in doctest, and passed
Christian Heimesfaf2f632008-01-06 16:59:19 +0000944to the DocTestRunner constructor (multiple constants should be ORed
Tim Peters8485b562004-08-04 18:46:34 +0000945together).
946
947The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
948and 1/0:
949
950 >>> def f(x):
951 ... '>>> True\n1\n'
952
953 >>> # Without the flag:
954 >>> test = doctest.DocTestFinder().find(f)[0]
955 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000956 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000957
958 >>> # With the flag:
959 >>> test = doctest.DocTestFinder().find(f)[0]
960 >>> flags = doctest.DONT_ACCEPT_TRUE_FOR_1
961 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000962 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000963 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000964 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000965 Failed example:
966 True
967 Expected:
968 1
969 Got:
970 True
Christian Heimes25bb7832008-01-11 16:17:00 +0000971 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000972
973The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines
974and the '<BLANKLINE>' marker:
975
976 >>> def f(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000977 ... '>>> print("a\\n\\nb")\na\n<BLANKLINE>\nb\n'
Tim Peters8485b562004-08-04 18:46:34 +0000978
979 >>> # Without the flag:
980 >>> test = doctest.DocTestFinder().find(f)[0]
981 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000982 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000983
984 >>> # With the flag:
985 >>> test = doctest.DocTestFinder().find(f)[0]
986 >>> flags = doctest.DONT_ACCEPT_BLANKLINE
987 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000988 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000989 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000990 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000991 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000992 print("a\n\nb")
Tim Peters8485b562004-08-04 18:46:34 +0000993 Expected:
994 a
995 <BLANKLINE>
996 b
997 Got:
998 a
999 <BLANKLINE>
1000 b
Christian Heimes25bb7832008-01-11 16:17:00 +00001001 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001002
1003The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be
1004treated as equal:
1005
1006 >>> def f(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001007 ... '>>> print(1, 2, 3)\n 1 2\n 3'
Tim Peters8485b562004-08-04 18:46:34 +00001008
1009 >>> # Without the flag:
1010 >>> test = doctest.DocTestFinder().find(f)[0]
1011 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001012 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001013 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001014 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001015 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001016 print(1, 2, 3)
Tim Peters8485b562004-08-04 18:46:34 +00001017 Expected:
1018 1 2
1019 3
Jim Fulton07a349c2004-08-22 14:10:00 +00001020 Got:
1021 1 2 3
Christian Heimes25bb7832008-01-11 16:17:00 +00001022 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001023
1024 >>> # With the flag:
1025 >>> test = doctest.DocTestFinder().find(f)[0]
1026 >>> flags = doctest.NORMALIZE_WHITESPACE
1027 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001028 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001029
Tim Peters026f8dc2004-08-19 16:38:58 +00001030 An example from the docs:
Guido van Rossum805365e2007-05-07 22:24:25 +00001031 >>> print(list(range(20))) #doctest: +NORMALIZE_WHITESPACE
Tim Peters026f8dc2004-08-19 16:38:58 +00001032 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
1033 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
1034
Tim Peters8485b562004-08-04 18:46:34 +00001035The ELLIPSIS flag causes ellipsis marker ("...") in the expected
1036output to match any substring in the actual output:
1037
1038 >>> def f(x):
Guido van Rossum805365e2007-05-07 22:24:25 +00001039 ... '>>> print(list(range(15)))\n[0, 1, 2, ..., 14]\n'
Tim Peters8485b562004-08-04 18:46:34 +00001040
1041 >>> # Without the flag:
1042 >>> test = doctest.DocTestFinder().find(f)[0]
1043 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001044 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001045 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001046 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001047 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001048 print(list(range(15)))
Jim Fulton07a349c2004-08-22 14:10:00 +00001049 Expected:
1050 [0, 1, 2, ..., 14]
1051 Got:
1052 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
Christian Heimes25bb7832008-01-11 16:17:00 +00001053 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001054
1055 >>> # With the flag:
1056 >>> test = doctest.DocTestFinder().find(f)[0]
1057 >>> flags = doctest.ELLIPSIS
1058 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001059 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001060
Tim Peterse594bee2004-08-22 01:47:51 +00001061 ... also matches nothing:
Tim Peters1cf3aa62004-08-19 06:49:33 +00001062
Guido van Rossume0192e52007-02-09 23:39:59 +00001063 >>> if 1:
1064 ... for i in range(100):
1065 ... print(i**2, end=' ') #doctest: +ELLIPSIS
1066 ... print('!')
1067 0 1...4...9 16 ... 36 49 64 ... 9801 !
Tim Peters1cf3aa62004-08-19 06:49:33 +00001068
Tim Peters026f8dc2004-08-19 16:38:58 +00001069 ... can be surprising; e.g., this test passes:
Tim Peters26b3ebb2004-08-19 08:10:08 +00001070
Guido van Rossume0192e52007-02-09 23:39:59 +00001071 >>> if 1: #doctest: +ELLIPSIS
1072 ... for i in range(20):
1073 ... print(i, end=' ')
1074 ... print(20)
Tim Peterse594bee2004-08-22 01:47:51 +00001075 0 1 2 ...1...2...0
Tim Peters26b3ebb2004-08-19 08:10:08 +00001076
Tim Peters026f8dc2004-08-19 16:38:58 +00001077 Examples from the docs:
1078
Guido van Rossum805365e2007-05-07 22:24:25 +00001079 >>> print(list(range(20))) # doctest:+ELLIPSIS
Tim Peters026f8dc2004-08-19 16:38:58 +00001080 [0, 1, ..., 18, 19]
1081
Guido van Rossum805365e2007-05-07 22:24:25 +00001082 >>> print(list(range(20))) # doctest: +ELLIPSIS
Tim Peters026f8dc2004-08-19 16:38:58 +00001083 ... # doctest: +NORMALIZE_WHITESPACE
1084 [0, 1, ..., 18, 19]
1085
Thomas Wouters477c8d52006-05-27 19:21:47 +00001086The SKIP flag causes an example to be skipped entirely. I.e., the
1087example is not run. It can be useful in contexts where doctest
1088examples serve as both documentation and test cases, and an example
1089should be included for documentation purposes, but should not be
1090checked (e.g., because its output is random, or depends on resources
1091which would be unavailable.) The SKIP flag can also be used for
1092'commenting out' broken examples.
1093
1094 >>> import unavailable_resource # doctest: +SKIP
1095 >>> unavailable_resource.do_something() # doctest: +SKIP
1096 >>> unavailable_resource.blow_up() # doctest: +SKIP
1097 Traceback (most recent call last):
1098 ...
1099 UncheckedBlowUpError: Nobody checks me.
1100
1101 >>> import random
Guido van Rossum7131f842007-02-09 20:13:25 +00001102 >>> print(random.random()) # doctest: +SKIP
Thomas Wouters477c8d52006-05-27 19:21:47 +00001103 0.721216923889
1104
Edward Loper71f55af2004-08-26 01:41:51 +00001105The REPORT_UDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001106and actual outputs to be displayed using a unified diff:
1107
1108 >>> def f(x):
1109 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001110 ... >>> print('\n'.join('abcdefg'))
Tim Peters8485b562004-08-04 18:46:34 +00001111 ... a
1112 ... B
1113 ... c
1114 ... d
1115 ... f
1116 ... g
1117 ... h
1118 ... '''
1119
1120 >>> # Without the flag:
1121 >>> test = doctest.DocTestFinder().find(f)[0]
1122 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001123 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001124 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001125 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001126 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001127 print('\n'.join('abcdefg'))
Tim Peters8485b562004-08-04 18:46:34 +00001128 Expected:
1129 a
1130 B
1131 c
1132 d
1133 f
1134 g
1135 h
1136 Got:
1137 a
1138 b
1139 c
1140 d
1141 e
1142 f
1143 g
Christian Heimes25bb7832008-01-11 16:17:00 +00001144 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001145
1146 >>> # With the flag:
1147 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001148 >>> flags = doctest.REPORT_UDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001149 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001150 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001151 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001152 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001153 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001154 print('\n'.join('abcdefg'))
Edward Loper56629292004-08-26 01:31:56 +00001155 Differences (unified diff with -expected +actual):
Tim Peterse7edcb82004-08-26 05:44:27 +00001156 @@ -1,7 +1,7 @@
Tim Peters8485b562004-08-04 18:46:34 +00001157 a
1158 -B
1159 +b
1160 c
1161 d
1162 +e
1163 f
1164 g
1165 -h
Christian Heimes25bb7832008-01-11 16:17:00 +00001166 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001167
Edward Loper71f55af2004-08-26 01:41:51 +00001168The REPORT_CDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001169and actual outputs to be displayed using a context diff:
1170
Edward Loper71f55af2004-08-26 01:41:51 +00001171 >>> # Reuse f() from the REPORT_UDIFF example, above.
Tim Peters8485b562004-08-04 18:46:34 +00001172 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001173 >>> flags = doctest.REPORT_CDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001174 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001175 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001176 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001177 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001178 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001179 print('\n'.join('abcdefg'))
Edward Loper56629292004-08-26 01:31:56 +00001180 Differences (context diff with expected followed by actual):
Tim Peters8485b562004-08-04 18:46:34 +00001181 ***************
Tim Peterse7edcb82004-08-26 05:44:27 +00001182 *** 1,7 ****
Tim Peters8485b562004-08-04 18:46:34 +00001183 a
1184 ! B
1185 c
1186 d
1187 f
1188 g
1189 - h
Tim Peterse7edcb82004-08-26 05:44:27 +00001190 --- 1,7 ----
Tim Peters8485b562004-08-04 18:46:34 +00001191 a
1192 ! b
1193 c
1194 d
1195 + e
1196 f
1197 g
Christian Heimes25bb7832008-01-11 16:17:00 +00001198 TestResults(failed=1, attempted=1)
Tim Petersc6cbab02004-08-22 19:43:28 +00001199
1200
Edward Loper71f55af2004-08-26 01:41:51 +00001201The REPORT_NDIFF flag causes failures to use the difflib.Differ algorithm
Tim Petersc6cbab02004-08-22 19:43:28 +00001202used by the popular ndiff.py utility. This does intraline difference
1203marking, as well as interline differences.
1204
1205 >>> def f(x):
1206 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001207 ... >>> print("a b c d e f g h i j k l m")
Tim Petersc6cbab02004-08-22 19:43:28 +00001208 ... a b c d e f g h i j k 1 m
1209 ... '''
1210 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001211 >>> flags = doctest.REPORT_NDIFF
Tim Petersc6cbab02004-08-22 19:43:28 +00001212 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001213 ... # doctest: +ELLIPSIS
Tim Petersc6cbab02004-08-22 19:43:28 +00001214 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001215 File ..., line 3, in f
Tim Petersc6cbab02004-08-22 19:43:28 +00001216 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001217 print("a b c d e f g h i j k l m")
Tim Petersc6cbab02004-08-22 19:43:28 +00001218 Differences (ndiff with -expected +actual):
1219 - a b c d e f g h i j k 1 m
1220 ? ^
1221 + a b c d e f g h i j k l m
1222 ? + ++ ^
Christian Heimes25bb7832008-01-11 16:17:00 +00001223 TestResults(failed=1, attempted=1)
Edward Lopera89f88d2004-08-26 02:45:51 +00001224
Ezio Melotti13925002011-03-16 11:05:33 +02001225The REPORT_ONLY_FIRST_FAILURE suppresses result output after the first
Edward Lopera89f88d2004-08-26 02:45:51 +00001226failing example:
1227
1228 >>> def f(x):
1229 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001230 ... >>> print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001231 ... 1
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001232 ... >>> print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001233 ... 200
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001234 ... >>> print(3) # second failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001235 ... 300
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001236 ... >>> print(4) # second success
Edward Lopera89f88d2004-08-26 02:45:51 +00001237 ... 4
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001238 ... >>> print(5) # third failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001239 ... 500
1240 ... '''
1241 >>> test = doctest.DocTestFinder().find(f)[0]
1242 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1243 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001244 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001245 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001246 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001247 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001248 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001249 Expected:
1250 200
1251 Got:
1252 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001253 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001254
Ezio Melotti13925002011-03-16 11:05:33 +02001255However, output from `report_start` is not suppressed:
Edward Lopera89f88d2004-08-26 02:45:51 +00001256
1257 >>> doctest.DocTestRunner(verbose=True, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001258 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001259 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001260 print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001261 Expecting:
1262 1
1263 ok
1264 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001265 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001266 Expecting:
1267 200
1268 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001269 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001270 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001271 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001272 Expected:
1273 200
1274 Got:
1275 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001276 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001277
1278For the purposes of REPORT_ONLY_FIRST_FAILURE, unexpected exceptions
1279count as failures:
1280
1281 >>> def f(x):
1282 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001283 ... >>> print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001284 ... 1
1285 ... >>> raise ValueError(2) # first failure
1286 ... 200
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001287 ... >>> print(3) # second failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001288 ... 300
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001289 ... >>> print(4) # second success
Edward Lopera89f88d2004-08-26 02:45:51 +00001290 ... 4
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001291 ... >>> print(5) # third failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001292 ... 500
1293 ... '''
1294 >>> test = doctest.DocTestFinder().find(f)[0]
1295 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1296 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1297 ... # doctest: +ELLIPSIS
1298 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001299 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001300 Failed example:
1301 raise ValueError(2) # first failure
1302 Exception raised:
1303 ...
1304 ValueError: 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001305 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001306
Thomas Wouters477c8d52006-05-27 19:21:47 +00001307New option flags can also be registered, via register_optionflag(). Here
1308we reach into doctest's internals a bit.
1309
1310 >>> unlikely = "UNLIKELY_OPTION_NAME"
1311 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1312 False
1313 >>> new_flag_value = doctest.register_optionflag(unlikely)
1314 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1315 True
1316
1317Before 2.4.4/2.5, registering a name more than once erroneously created
1318more than one flag value. Here we verify that's fixed:
1319
1320 >>> redundant_flag_value = doctest.register_optionflag(unlikely)
1321 >>> redundant_flag_value == new_flag_value
1322 True
1323
1324Clean up.
1325 >>> del doctest.OPTIONFLAGS_BY_NAME[unlikely]
1326
Tim Petersc6cbab02004-08-22 19:43:28 +00001327 """
1328
Tim Peters8485b562004-08-04 18:46:34 +00001329 def option_directives(): r"""
1330Tests of `DocTestRunner`'s option directive mechanism.
1331
Edward Loper74bca7a2004-08-12 02:27:44 +00001332Option directives can be used to turn option flags on or off for a
1333single example. To turn an option on for an example, follow that
1334example with a comment of the form ``# doctest: +OPTION``:
Tim Peters8485b562004-08-04 18:46:34 +00001335
1336 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001337 ... >>> print(list(range(10))) # should fail: no ellipsis
Edward Loper74bca7a2004-08-12 02:27:44 +00001338 ... [0, 1, ..., 9]
1339 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001340 ... >>> print(list(range(10))) # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001341 ... [0, 1, ..., 9]
1342 ... '''
1343 >>> test = doctest.DocTestFinder().find(f)[0]
1344 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001345 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001346 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001347 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001348 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001349 print(list(range(10))) # should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001350 Expected:
1351 [0, 1, ..., 9]
1352 Got:
1353 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001354 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001355
1356To turn an option off for an example, follow that example with a
1357comment of the form ``# doctest: -OPTION``:
1358
1359 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001360 ... >>> print(list(range(10)))
Edward Loper74bca7a2004-08-12 02:27:44 +00001361 ... [0, 1, ..., 9]
1362 ...
1363 ... >>> # should fail: no ellipsis
Guido van Rossum805365e2007-05-07 22:24:25 +00001364 ... >>> print(list(range(10))) # doctest: -ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001365 ... [0, 1, ..., 9]
1366 ... '''
1367 >>> test = doctest.DocTestFinder().find(f)[0]
1368 >>> doctest.DocTestRunner(verbose=False,
1369 ... optionflags=doctest.ELLIPSIS).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001370 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001371 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001372 File ..., line 6, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001373 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001374 print(list(range(10))) # doctest: -ELLIPSIS
Jim Fulton07a349c2004-08-22 14:10:00 +00001375 Expected:
1376 [0, 1, ..., 9]
1377 Got:
1378 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001379 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001380
1381Option directives affect only the example that they appear with; they
1382do not change the options for surrounding examples:
Edward Loper8e4a34b2004-08-12 02:34:27 +00001383
Edward Loper74bca7a2004-08-12 02:27:44 +00001384 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001385 ... >>> print(list(range(10))) # Should fail: no ellipsis
Tim Peters8485b562004-08-04 18:46:34 +00001386 ... [0, 1, ..., 9]
1387 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001388 ... >>> print(list(range(10))) # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001389 ... [0, 1, ..., 9]
1390 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001391 ... >>> print(list(range(10))) # Should fail: no ellipsis
Tim Peters8485b562004-08-04 18:46:34 +00001392 ... [0, 1, ..., 9]
1393 ... '''
1394 >>> test = doctest.DocTestFinder().find(f)[0]
1395 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001396 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001397 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001398 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001399 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001400 print(list(range(10))) # Should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001401 Expected:
1402 [0, 1, ..., 9]
1403 Got:
1404 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001405 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001406 File ..., line 8, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001407 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001408 print(list(range(10))) # Should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001409 Expected:
1410 [0, 1, ..., 9]
1411 Got:
1412 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001413 TestResults(failed=2, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +00001414
Edward Loper74bca7a2004-08-12 02:27:44 +00001415Multiple options may be modified by a single option directive. They
1416may be separated by whitespace, commas, or both:
Tim Peters8485b562004-08-04 18:46:34 +00001417
1418 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001419 ... >>> print(list(range(10))) # Should fail
Tim Peters8485b562004-08-04 18:46:34 +00001420 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001421 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001422 ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001423 ... [0, 1, ..., 9]
1424 ... '''
1425 >>> test = doctest.DocTestFinder().find(f)[0]
1426 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001427 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001428 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001429 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001430 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001431 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001432 Expected:
1433 [0, 1, ..., 9]
1434 Got:
1435 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001436 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001437
1438 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001439 ... >>> print(list(range(10))) # Should fail
Edward Loper74bca7a2004-08-12 02:27:44 +00001440 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001441 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001442 ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
1443 ... [0, 1, ..., 9]
1444 ... '''
1445 >>> test = doctest.DocTestFinder().find(f)[0]
1446 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001447 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001448 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001449 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001450 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001451 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001452 Expected:
1453 [0, 1, ..., 9]
1454 Got:
1455 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001456 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001457
1458 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001459 ... >>> print(list(range(10))) # Should fail
Edward Loper74bca7a2004-08-12 02:27:44 +00001460 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001461 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001462 ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1463 ... [0, 1, ..., 9]
1464 ... '''
1465 >>> test = doctest.DocTestFinder().find(f)[0]
1466 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001467 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001468 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001469 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001470 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001471 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001472 Expected:
1473 [0, 1, ..., 9]
1474 Got:
1475 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001476 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001477
1478The option directive may be put on the line following the source, as
1479long as a continuation prompt is used:
1480
1481 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001482 ... >>> print(list(range(10)))
Edward Loper74bca7a2004-08-12 02:27:44 +00001483 ... ... # doctest: +ELLIPSIS
1484 ... [0, 1, ..., 9]
1485 ... '''
1486 >>> test = doctest.DocTestFinder().find(f)[0]
1487 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001488 TestResults(failed=0, attempted=1)
Edward Loper8e4a34b2004-08-12 02:34:27 +00001489
Edward Loper74bca7a2004-08-12 02:27:44 +00001490For examples with multi-line source, the option directive may appear
1491at the end of any line:
1492
1493 >>> def f(x): r'''
1494 ... >>> for x in range(10): # doctest: +ELLIPSIS
Guido van Rossum805365e2007-05-07 22:24:25 +00001495 ... ... print(' ', x, end='', sep='')
1496 ... 0 1 2 ... 9
Edward Loper74bca7a2004-08-12 02:27:44 +00001497 ...
1498 ... >>> for x in range(10):
Guido van Rossum805365e2007-05-07 22:24:25 +00001499 ... ... print(' ', x, end='', sep='') # doctest: +ELLIPSIS
1500 ... 0 1 2 ... 9
Edward Loper74bca7a2004-08-12 02:27:44 +00001501 ... '''
1502 >>> test = doctest.DocTestFinder().find(f)[0]
1503 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001504 TestResults(failed=0, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001505
1506If more than one line of an example with multi-line source has an
1507option directive, then they are combined:
1508
1509 >>> def f(x): r'''
1510 ... Should fail (option directive not on the last line):
1511 ... >>> for x in range(10): # doctest: +ELLIPSIS
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001512 ... ... print(x, end=' ') # doctest: +NORMALIZE_WHITESPACE
Guido van Rossumd8faa362007-04-27 19:54:29 +00001513 ... 0 1 2...9
Edward Loper74bca7a2004-08-12 02:27:44 +00001514 ... '''
1515 >>> test = doctest.DocTestFinder().find(f)[0]
1516 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001517 TestResults(failed=0, attempted=1)
Edward Loper74bca7a2004-08-12 02:27:44 +00001518
1519It is an error to have a comment of the form ``# doctest:`` that is
1520*not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
1521``OPTION`` is an option that has been registered with
1522`register_option`:
1523
1524 >>> # Error: Option not registered
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001525 >>> s = '>>> print(12) #doctest: +BADOPTION'
Edward Loper74bca7a2004-08-12 02:27:44 +00001526 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1527 Traceback (most recent call last):
1528 ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
1529
1530 >>> # Error: No + or - prefix
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001531 >>> s = '>>> print(12) #doctest: ELLIPSIS'
Edward Loper74bca7a2004-08-12 02:27:44 +00001532 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1533 Traceback (most recent call last):
1534 ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
1535
1536It is an error to use an option directive on a line that contains no
1537source:
1538
1539 >>> s = '>>> # doctest: +ELLIPSIS'
1540 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1541 Traceback (most recent call last):
1542 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 +00001543"""
1544
1545def test_testsource(): r"""
1546Unit tests for `testsource()`.
1547
1548The testsource() function takes a module and a name, finds the (first)
Tim Peters19397e52004-08-06 22:02:59 +00001549test with that name in that module, and converts it to a script. The
1550example code is converted to regular Python code. The surrounding
1551words and expected output are converted to comments:
Tim Peters8485b562004-08-04 18:46:34 +00001552
1553 >>> import test.test_doctest
1554 >>> name = 'test.test_doctest.sample_func'
Guido van Rossum7131f842007-02-09 20:13:25 +00001555 >>> print(doctest.testsource(test.test_doctest, name))
Edward Lopera5db6002004-08-12 02:41:30 +00001556 # Blah blah
Tim Peters19397e52004-08-06 22:02:59 +00001557 #
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001558 print(sample_func(22))
Tim Peters8485b562004-08-04 18:46:34 +00001559 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001560 ## 44
Tim Peters19397e52004-08-06 22:02:59 +00001561 #
Edward Lopera5db6002004-08-12 02:41:30 +00001562 # Yee ha!
Georg Brandlecf93c72005-06-26 23:09:51 +00001563 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001564
1565 >>> name = 'test.test_doctest.SampleNewStyleClass'
Guido van Rossum7131f842007-02-09 20:13:25 +00001566 >>> print(doctest.testsource(test.test_doctest, name))
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001567 print('1\n2\n3')
Tim Peters8485b562004-08-04 18:46:34 +00001568 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001569 ## 1
1570 ## 2
1571 ## 3
Georg Brandlecf93c72005-06-26 23:09:51 +00001572 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001573
1574 >>> name = 'test.test_doctest.SampleClass.a_classmethod'
Guido van Rossum7131f842007-02-09 20:13:25 +00001575 >>> print(doctest.testsource(test.test_doctest, name))
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001576 print(SampleClass.a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +00001577 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001578 ## 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001579 print(SampleClass(0).a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +00001580 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001581 ## 12
Georg Brandlecf93c72005-06-26 23:09:51 +00001582 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001583"""
1584
1585def test_debug(): r"""
1586
1587Create a docstring that we want to debug:
1588
1589 >>> s = '''
1590 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001591 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +00001592 ... 12
1593 ... '''
1594
1595Create some fake stdin input, to feed to the debugger:
1596
Tim Peters8485b562004-08-04 18:46:34 +00001597 >>> real_stdin = sys.stdin
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001598 >>> sys.stdin = _FakeInput(['next', 'print(x)', 'continue'])
Tim Peters8485b562004-08-04 18:46:34 +00001599
1600Run the debugger on the docstring, and then restore sys.stdin.
1601
Edward Loper2de91ba2004-08-27 02:07:46 +00001602 >>> try: doctest.debug_src(s)
1603 ... finally: sys.stdin = real_stdin
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001604 > <string>(1)<module>()
Edward Loper2de91ba2004-08-27 02:07:46 +00001605 (Pdb) next
1606 12
Tim Peters8485b562004-08-04 18:46:34 +00001607 --Return--
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001608 > <string>(1)<module>()->None
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001609 (Pdb) print(x)
Edward Loper2de91ba2004-08-27 02:07:46 +00001610 12
1611 (Pdb) continue
Tim Peters8485b562004-08-04 18:46:34 +00001612
1613"""
1614
Jim Fulton356fd192004-08-09 11:34:47 +00001615def test_pdb_set_trace():
Tim Peters50c6bdb2004-11-08 22:07:37 +00001616 """Using pdb.set_trace from a doctest.
Jim Fulton356fd192004-08-09 11:34:47 +00001617
Tim Peters413ced62004-08-09 15:43:47 +00001618 You can use pdb.set_trace from a doctest. To do so, you must
Jim Fulton356fd192004-08-09 11:34:47 +00001619 retrieve the set_trace function from the pdb module at the time
Tim Peters413ced62004-08-09 15:43:47 +00001620 you use it. The doctest module changes sys.stdout so that it can
1621 capture program output. It also temporarily replaces pdb.set_trace
1622 with a version that restores stdout. This is necessary for you to
Jim Fulton356fd192004-08-09 11:34:47 +00001623 see debugger output.
1624
1625 >>> doc = '''
1626 ... >>> x = 42
1627 ... >>> import pdb; pdb.set_trace()
1628 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001629 >>> parser = doctest.DocTestParser()
1630 >>> test = parser.get_doctest(doc, {}, "foo", "foo.py", 0)
Jim Fulton356fd192004-08-09 11:34:47 +00001631 >>> runner = doctest.DocTestRunner(verbose=False)
1632
1633 To demonstrate this, we'll create a fake standard input that
1634 captures our debugger input:
1635
1636 >>> import tempfile
Edward Loper2de91ba2004-08-27 02:07:46 +00001637 >>> real_stdin = sys.stdin
1638 >>> sys.stdin = _FakeInput([
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001639 ... 'print(x)', # print data defined by the example
Jim Fulton356fd192004-08-09 11:34:47 +00001640 ... 'continue', # stop debugging
Edward Loper2de91ba2004-08-27 02:07:46 +00001641 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001642
Edward Loper2de91ba2004-08-27 02:07:46 +00001643 >>> try: runner.run(test)
1644 ... finally: sys.stdin = real_stdin
Jim Fulton356fd192004-08-09 11:34:47 +00001645 --Return--
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001646 > <doctest foo[1]>(1)<module>()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001647 -> import pdb; pdb.set_trace()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001648 (Pdb) print(x)
Edward Loper2de91ba2004-08-27 02:07:46 +00001649 42
1650 (Pdb) continue
Christian Heimes25bb7832008-01-11 16:17:00 +00001651 TestResults(failed=0, attempted=2)
Jim Fulton356fd192004-08-09 11:34:47 +00001652
1653 You can also put pdb.set_trace in a function called from a test:
1654
1655 >>> def calls_set_trace():
1656 ... y=2
1657 ... import pdb; pdb.set_trace()
1658
1659 >>> doc = '''
1660 ... >>> x=1
1661 ... >>> calls_set_trace()
1662 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001663 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
Edward Loper2de91ba2004-08-27 02:07:46 +00001664 >>> real_stdin = sys.stdin
1665 >>> sys.stdin = _FakeInput([
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001666 ... 'print(y)', # print data defined in the function
Jim Fulton356fd192004-08-09 11:34:47 +00001667 ... 'up', # out of function
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001668 ... 'print(x)', # print data defined by the example
Jim Fulton356fd192004-08-09 11:34:47 +00001669 ... 'continue', # stop debugging
Edward Loper2de91ba2004-08-27 02:07:46 +00001670 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001671
Tim Peters50c6bdb2004-11-08 22:07:37 +00001672 >>> try:
1673 ... runner.run(test)
1674 ... finally:
1675 ... sys.stdin = real_stdin
Jim Fulton356fd192004-08-09 11:34:47 +00001676 --Return--
Edward Loper2de91ba2004-08-27 02:07:46 +00001677 > <doctest test.test_doctest.test_pdb_set_trace[8]>(3)calls_set_trace()->None
1678 -> import pdb; pdb.set_trace()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001679 (Pdb) print(y)
Edward Loper2de91ba2004-08-27 02:07:46 +00001680 2
1681 (Pdb) up
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001682 > <doctest foo[1]>(1)<module>()
Edward Loper2de91ba2004-08-27 02:07:46 +00001683 -> calls_set_trace()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001684 (Pdb) print(x)
Edward Loper2de91ba2004-08-27 02:07:46 +00001685 1
1686 (Pdb) continue
Christian Heimes25bb7832008-01-11 16:17:00 +00001687 TestResults(failed=0, attempted=2)
Edward Loper2de91ba2004-08-27 02:07:46 +00001688
1689 During interactive debugging, source code is shown, even for
1690 doctest examples:
1691
1692 >>> doc = '''
1693 ... >>> def f(x):
1694 ... ... g(x*2)
1695 ... >>> def g(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001696 ... ... print(x+3)
Edward Loper2de91ba2004-08-27 02:07:46 +00001697 ... ... import pdb; pdb.set_trace()
1698 ... >>> f(3)
1699 ... '''
1700 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
1701 >>> real_stdin = sys.stdin
1702 >>> sys.stdin = _FakeInput([
1703 ... 'list', # list source from example 2
1704 ... 'next', # return from g()
1705 ... 'list', # list source from example 1
1706 ... 'next', # return from f()
1707 ... 'list', # list source from example 3
1708 ... 'continue', # stop debugging
1709 ... ''])
1710 >>> try: runner.run(test)
1711 ... finally: sys.stdin = real_stdin
1712 ... # doctest: +NORMALIZE_WHITESPACE
1713 --Return--
1714 > <doctest foo[1]>(3)g()->None
1715 -> import pdb; pdb.set_trace()
1716 (Pdb) list
1717 1 def g(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001718 2 print(x+3)
Edward Loper2de91ba2004-08-27 02:07:46 +00001719 3 -> import pdb; pdb.set_trace()
1720 [EOF]
1721 (Pdb) next
1722 --Return--
1723 > <doctest foo[0]>(2)f()->None
1724 -> g(x*2)
1725 (Pdb) list
1726 1 def f(x):
1727 2 -> g(x*2)
1728 [EOF]
1729 (Pdb) next
1730 --Return--
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001731 > <doctest foo[2]>(1)<module>()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001732 -> f(3)
1733 (Pdb) list
1734 1 -> f(3)
1735 [EOF]
1736 (Pdb) continue
1737 **********************************************************************
1738 File "foo.py", line 7, in foo
1739 Failed example:
1740 f(3)
1741 Expected nothing
1742 Got:
1743 9
Christian Heimes25bb7832008-01-11 16:17:00 +00001744 TestResults(failed=1, attempted=3)
Jim Fulton356fd192004-08-09 11:34:47 +00001745 """
1746
Tim Peters50c6bdb2004-11-08 22:07:37 +00001747def test_pdb_set_trace_nested():
1748 """This illustrates more-demanding use of set_trace with nested functions.
1749
1750 >>> class C(object):
1751 ... def calls_set_trace(self):
1752 ... y = 1
1753 ... import pdb; pdb.set_trace()
1754 ... self.f1()
1755 ... y = 2
1756 ... def f1(self):
1757 ... x = 1
1758 ... self.f2()
1759 ... x = 2
1760 ... def f2(self):
1761 ... z = 1
1762 ... z = 2
1763
1764 >>> calls_set_trace = C().calls_set_trace
1765
1766 >>> doc = '''
1767 ... >>> a = 1
1768 ... >>> calls_set_trace()
1769 ... '''
1770 >>> parser = doctest.DocTestParser()
1771 >>> runner = doctest.DocTestRunner(verbose=False)
1772 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
1773 >>> real_stdin = sys.stdin
1774 >>> sys.stdin = _FakeInput([
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001775 ... 'print(y)', # print data defined in the function
1776 ... 'step', 'step', 'step', 'step', 'step', 'step', 'print(z)',
1777 ... 'up', 'print(x)',
1778 ... 'up', 'print(y)',
1779 ... 'up', 'print(foo)',
Tim Peters50c6bdb2004-11-08 22:07:37 +00001780 ... 'continue', # stop debugging
1781 ... ''])
1782
1783 >>> try:
1784 ... runner.run(test)
1785 ... finally:
1786 ... sys.stdin = real_stdin
Guido van Rossum4a625c32007-09-08 16:05:25 +00001787 ... # doctest: +REPORT_NDIFF
Tim Peters50c6bdb2004-11-08 22:07:37 +00001788 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
1789 -> self.f1()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001790 (Pdb) print(y)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001791 1
1792 (Pdb) step
1793 --Call--
1794 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(7)f1()
1795 -> def f1(self):
1796 (Pdb) step
1797 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(8)f1()
1798 -> x = 1
1799 (Pdb) step
1800 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
1801 -> self.f2()
1802 (Pdb) step
1803 --Call--
1804 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(11)f2()
1805 -> def f2(self):
1806 (Pdb) step
1807 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(12)f2()
1808 -> z = 1
1809 (Pdb) step
1810 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(13)f2()
1811 -> z = 2
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001812 (Pdb) print(z)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001813 1
1814 (Pdb) up
1815 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
1816 -> self.f2()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001817 (Pdb) print(x)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001818 1
1819 (Pdb) up
1820 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
1821 -> self.f1()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001822 (Pdb) print(y)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001823 1
1824 (Pdb) up
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001825 > <doctest foo[1]>(1)<module>()
Tim Peters50c6bdb2004-11-08 22:07:37 +00001826 -> calls_set_trace()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001827 (Pdb) print(foo)
Guido van Rossumfd4a7de2007-09-05 03:26:38 +00001828 *** NameError: NameError("name 'foo' is not defined",)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001829 (Pdb) continue
Christian Heimes25bb7832008-01-11 16:17:00 +00001830 TestResults(failed=0, attempted=2)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001831"""
1832
Tim Peters19397e52004-08-06 22:02:59 +00001833def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +00001834 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +00001835
1836 We create a Suite by providing a module. A module can be provided
1837 by passing a module object:
1838
1839 >>> import unittest
1840 >>> import test.sample_doctest
1841 >>> suite = doctest.DocTestSuite(test.sample_doctest)
1842 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001843 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001844
1845 We can also supply the module by name:
1846
1847 >>> suite = doctest.DocTestSuite('test.sample_doctest')
1848 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001849 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001850
1851 We can use the current module:
1852
1853 >>> suite = test.sample_doctest.test_suite()
1854 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001855 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001856
1857 We can supply global variables. If we pass globs, they will be
1858 used instead of the module globals. Here we'll pass an empty
1859 globals, triggering an extra error:
1860
1861 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
1862 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001863 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001864
1865 Alternatively, we can provide extra globals. Here we'll make an
1866 error go away by providing an extra global variable:
1867
1868 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1869 ... extraglobs={'y': 1})
1870 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001871 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001872
1873 You can pass option flags. Here we'll cause an extra error
1874 by disabling the blank-line feature:
1875
1876 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00001877 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00001878 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001879 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001880
Tim Peters1e277ee2004-08-07 05:37:52 +00001881 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00001882
Jim Fultonf54bad42004-08-28 14:57:56 +00001883 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00001884 ... import test.test_doctest
1885 ... test.test_doctest.sillySetup = True
1886
Jim Fultonf54bad42004-08-28 14:57:56 +00001887 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00001888 ... import test.test_doctest
1889 ... del test.test_doctest.sillySetup
1890
1891 Here, we installed a silly variable that the test expects:
1892
1893 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1894 ... setUp=setUp, tearDown=tearDown)
1895 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001896 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001897
1898 But the tearDown restores sanity:
1899
1900 >>> import test.test_doctest
1901 >>> test.test_doctest.sillySetup
1902 Traceback (most recent call last):
1903 ...
1904 AttributeError: 'module' object has no attribute 'sillySetup'
1905
Jim Fultonf54bad42004-08-28 14:57:56 +00001906 The setUp and tearDown funtions are passed test objects. Here
1907 we'll use the setUp function to supply the missing variable y:
1908
1909 >>> def setUp(test):
1910 ... test.globs['y'] = 1
1911
1912 >>> suite = doctest.DocTestSuite('test.sample_doctest', setUp=setUp)
1913 >>> suite.run(unittest.TestResult())
1914 <unittest.TestResult run=9 errors=0 failures=3>
1915
1916 Here, we didn't need to use a tearDown function because we
1917 modified the test globals, which are a copy of the
1918 sample_doctest module dictionary. The test globals are
1919 automatically cleared for us after a test.
Tim Peters19397e52004-08-06 22:02:59 +00001920 """
1921
1922def test_DocFileSuite():
1923 """We can test tests found in text files using a DocFileSuite.
1924
1925 We create a suite by providing the names of one or more text
1926 files that include examples:
1927
1928 >>> import unittest
1929 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001930 ... 'test_doctest2.txt',
1931 ... 'test_doctest4.txt')
Tim Peters19397e52004-08-06 22:02:59 +00001932 >>> suite.run(unittest.TestResult())
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00001933 <unittest.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00001934
1935 The test files are looked for in the directory containing the
1936 calling module. A package keyword argument can be provided to
1937 specify a different relative location.
1938
1939 >>> import unittest
1940 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1941 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001942 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00001943 ... package='test')
1944 >>> suite.run(unittest.TestResult())
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00001945 <unittest.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00001946
Guido van Rossumcd4d4522007-11-22 00:30:02 +00001947 Support for using a package's __loader__.get_data() is also
1948 provided.
1949
1950 >>> import unittest, pkgutil, test
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001951 >>> added_loader = False
Guido van Rossumcd4d4522007-11-22 00:30:02 +00001952 >>> if not hasattr(test, '__loader__'):
1953 ... test.__loader__ = pkgutil.get_loader(test)
1954 ... added_loader = True
1955 >>> try:
1956 ... suite = doctest.DocFileSuite('test_doctest.txt',
1957 ... 'test_doctest2.txt',
1958 ... 'test_doctest4.txt',
1959 ... package='test')
1960 ... suite.run(unittest.TestResult())
1961 ... finally:
1962 ... if added_loader:
1963 ... del test.__loader__
1964 <unittest.TestResult run=3 errors=0 failures=2>
1965
Edward Loper0273f5b2004-09-18 20:27:04 +00001966 '/' should be used as a path separator. It will be converted
1967 to a native separator at run time:
Tim Peters19397e52004-08-06 22:02:59 +00001968
1969 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
1970 >>> suite.run(unittest.TestResult())
1971 <unittest.TestResult run=1 errors=0 failures=1>
1972
Edward Loper0273f5b2004-09-18 20:27:04 +00001973 If DocFileSuite is used from an interactive session, then files
1974 are resolved relative to the directory of sys.argv[0]:
1975
Christian Heimes45f9af32007-11-27 21:50:00 +00001976 >>> import types, os.path, test.test_doctest
Edward Loper0273f5b2004-09-18 20:27:04 +00001977 >>> save_argv = sys.argv
1978 >>> sys.argv = [test.test_doctest.__file__]
1979 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Christian Heimes45f9af32007-11-27 21:50:00 +00001980 ... package=types.ModuleType('__main__'))
Edward Loper0273f5b2004-09-18 20:27:04 +00001981 >>> sys.argv = save_argv
1982
Edward Loper052d0cd2004-09-19 17:19:33 +00001983 By setting `module_relative=False`, os-specific paths may be
1984 used (including absolute paths and paths relative to the
1985 working directory):
Edward Loper0273f5b2004-09-18 20:27:04 +00001986
1987 >>> # Get the absolute path of the test package.
1988 >>> test_doctest_path = os.path.abspath(test.test_doctest.__file__)
1989 >>> test_pkg_path = os.path.split(test_doctest_path)[0]
1990
1991 >>> # Use it to find the absolute path of test_doctest.txt.
1992 >>> test_file = os.path.join(test_pkg_path, 'test_doctest.txt')
1993
Edward Loper052d0cd2004-09-19 17:19:33 +00001994 >>> suite = doctest.DocFileSuite(test_file, module_relative=False)
Edward Loper0273f5b2004-09-18 20:27:04 +00001995 >>> suite.run(unittest.TestResult())
1996 <unittest.TestResult run=1 errors=0 failures=1>
1997
Edward Loper052d0cd2004-09-19 17:19:33 +00001998 It is an error to specify `package` when `module_relative=False`:
1999
2000 >>> suite = doctest.DocFileSuite(test_file, module_relative=False,
2001 ... package='test')
2002 Traceback (most recent call last):
2003 ValueError: Package may only be specified for module-relative paths.
2004
Tim Peters19397e52004-08-06 22:02:59 +00002005 You can specify initial global variables:
2006
2007 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2008 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002009 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002010 ... globs={'favorite_color': 'blue'})
2011 >>> suite.run(unittest.TestResult())
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002012 <unittest.TestResult run=3 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002013
2014 In this case, we supplied a missing favorite color. You can
2015 provide doctest options:
2016
2017 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2018 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002019 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002020 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
2021 ... globs={'favorite_color': 'blue'})
2022 >>> suite.run(unittest.TestResult())
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002023 <unittest.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002024
2025 And, you can provide setUp and tearDown functions:
2026
Jim Fultonf54bad42004-08-28 14:57:56 +00002027 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00002028 ... import test.test_doctest
2029 ... test.test_doctest.sillySetup = True
2030
Jim Fultonf54bad42004-08-28 14:57:56 +00002031 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00002032 ... import test.test_doctest
2033 ... del test.test_doctest.sillySetup
2034
2035 Here, we installed a silly variable that the test expects:
2036
2037 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2038 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002039 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002040 ... setUp=setUp, tearDown=tearDown)
2041 >>> suite.run(unittest.TestResult())
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002042 <unittest.TestResult run=3 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002043
2044 But the tearDown restores sanity:
2045
2046 >>> import test.test_doctest
2047 >>> test.test_doctest.sillySetup
2048 Traceback (most recent call last):
2049 ...
2050 AttributeError: 'module' object has no attribute 'sillySetup'
2051
Jim Fultonf54bad42004-08-28 14:57:56 +00002052 The setUp and tearDown funtions are passed test objects.
2053 Here, we'll use a setUp function to set the favorite color in
2054 test_doctest.txt:
2055
2056 >>> def setUp(test):
2057 ... test.globs['favorite_color'] = 'blue'
2058
2059 >>> suite = doctest.DocFileSuite('test_doctest.txt', setUp=setUp)
2060 >>> suite.run(unittest.TestResult())
2061 <unittest.TestResult run=1 errors=0 failures=0>
2062
2063 Here, we didn't need to use a tearDown function because we
2064 modified the test globals. The test globals are
2065 automatically cleared for us after a test.
Tim Petersdf7a2082004-08-29 00:38:17 +00002066
Fred Drake7c404a42004-12-21 23:46:34 +00002067 Tests in a file run using `DocFileSuite` can also access the
2068 `__file__` global, which is set to the name of the file
2069 containing the tests:
2070
2071 >>> suite = doctest.DocFileSuite('test_doctest3.txt')
2072 >>> suite.run(unittest.TestResult())
2073 <unittest.TestResult run=1 errors=0 failures=0>
2074
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002075 If the tests contain non-ASCII characters, we have to specify which
2076 encoding the file is encoded with. We do so by using the `encoding`
2077 parameter:
2078
2079 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2080 ... 'test_doctest2.txt',
2081 ... 'test_doctest4.txt',
2082 ... encoding='utf-8')
2083 >>> suite.run(unittest.TestResult())
2084 <unittest.TestResult run=3 errors=0 failures=2>
2085
Jim Fultonf54bad42004-08-28 14:57:56 +00002086 """
Tim Peters19397e52004-08-06 22:02:59 +00002087
Jim Fulton07a349c2004-08-22 14:10:00 +00002088def test_trailing_space_in_test():
2089 """
Tim Petersa7def722004-08-23 22:13:22 +00002090 Trailing spaces in expected output are significant:
Tim Petersc6cbab02004-08-22 19:43:28 +00002091
Jim Fulton07a349c2004-08-22 14:10:00 +00002092 >>> x, y = 'foo', ''
Guido van Rossum7131f842007-02-09 20:13:25 +00002093 >>> print(x, y)
Jim Fulton07a349c2004-08-22 14:10:00 +00002094 foo \n
2095 """
Tim Peters19397e52004-08-06 22:02:59 +00002096
Jim Fultonf54bad42004-08-28 14:57:56 +00002097
2098def test_unittest_reportflags():
2099 """Default unittest reporting flags can be set to control reporting
2100
2101 Here, we'll set the REPORT_ONLY_FIRST_FAILURE option so we see
2102 only the first failure of each test. First, we'll look at the
2103 output without the flag. The file test_doctest.txt file has two
2104 tests. They both fail if blank lines are disabled:
2105
2106 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2107 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
2108 >>> import unittest
2109 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002110 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002111 Traceback ...
2112 Failed example:
2113 favorite_color
2114 ...
2115 Failed example:
2116 if 1:
2117 ...
2118
2119 Note that we see both failures displayed.
2120
2121 >>> old = doctest.set_unittest_reportflags(
2122 ... doctest.REPORT_ONLY_FIRST_FAILURE)
2123
2124 Now, when we run the test:
2125
2126 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002127 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002128 Traceback ...
2129 Failed example:
2130 favorite_color
2131 Exception raised:
2132 ...
2133 NameError: name 'favorite_color' is not defined
2134 <BLANKLINE>
2135 <BLANKLINE>
Tim Petersdf7a2082004-08-29 00:38:17 +00002136
Jim Fultonf54bad42004-08-28 14:57:56 +00002137 We get only the first failure.
2138
2139 If we give any reporting options when we set up the tests,
2140 however:
2141
2142 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2143 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE | doctest.REPORT_NDIFF)
2144
2145 Then the default eporting options are ignored:
2146
2147 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002148 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002149 Traceback ...
2150 Failed example:
2151 favorite_color
2152 ...
2153 Failed example:
2154 if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00002155 print('a')
2156 print()
2157 print('b')
Jim Fultonf54bad42004-08-28 14:57:56 +00002158 Differences (ndiff with -expected +actual):
2159 a
2160 - <BLANKLINE>
2161 +
2162 b
2163 <BLANKLINE>
2164 <BLANKLINE>
2165
2166
2167 Test runners can restore the formatting flags after they run:
2168
2169 >>> ignored = doctest.set_unittest_reportflags(old)
2170
2171 """
2172
Edward Loper052d0cd2004-09-19 17:19:33 +00002173def test_testfile(): r"""
2174Tests for the `testfile()` function. This function runs all the
2175doctest examples in a given file. In its simple invokation, it is
2176called with the name of a file, which is taken to be relative to the
2177calling module. The return value is (#failures, #tests).
2178
Florent Xiclunae94b2212010-02-27 14:37:21 +00002179We don't want `-v` in sys.argv for these tests.
2180
2181 >>> save_argv = sys.argv
2182 >>> if '-v' in sys.argv:
2183 ... sys.argv = [arg for arg in save_argv if arg != '-v']
2184
2185
Edward Loper052d0cd2004-09-19 17:19:33 +00002186 >>> doctest.testfile('test_doctest.txt') # doctest: +ELLIPSIS
2187 **********************************************************************
2188 File "...", line 6, in test_doctest.txt
2189 Failed example:
2190 favorite_color
2191 Exception raised:
2192 ...
2193 NameError: name 'favorite_color' is not defined
2194 **********************************************************************
2195 1 items had failures:
2196 1 of 2 in test_doctest.txt
2197 ***Test Failed*** 1 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002198 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002199 >>> doctest.master = None # Reset master.
2200
2201(Note: we'll be clearing doctest.master after each call to
Ezio Melotti13925002011-03-16 11:05:33 +02002202`doctest.testfile`, to suppress warnings about multiple tests with the
Edward Loper052d0cd2004-09-19 17:19:33 +00002203same name.)
2204
2205Globals may be specified with the `globs` and `extraglobs` parameters:
2206
2207 >>> globs = {'favorite_color': 'blue'}
2208 >>> doctest.testfile('test_doctest.txt', globs=globs)
Christian Heimes25bb7832008-01-11 16:17:00 +00002209 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002210 >>> doctest.master = None # Reset master.
2211
2212 >>> extraglobs = {'favorite_color': 'red'}
2213 >>> doctest.testfile('test_doctest.txt', globs=globs,
2214 ... extraglobs=extraglobs) # doctest: +ELLIPSIS
2215 **********************************************************************
2216 File "...", line 6, in test_doctest.txt
2217 Failed example:
2218 favorite_color
2219 Expected:
2220 'blue'
2221 Got:
2222 'red'
2223 **********************************************************************
2224 1 items had failures:
2225 1 of 2 in test_doctest.txt
2226 ***Test Failed*** 1 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002227 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002228 >>> doctest.master = None # Reset master.
2229
2230The file may be made relative to a given module or package, using the
2231optional `module_relative` parameter:
2232
2233 >>> doctest.testfile('test_doctest.txt', globs=globs,
2234 ... module_relative='test')
Christian Heimes25bb7832008-01-11 16:17:00 +00002235 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002236 >>> doctest.master = None # Reset master.
2237
Ezio Melotti13925002011-03-16 11:05:33 +02002238Verbosity can be increased with the optional `verbose` parameter:
Edward Loper052d0cd2004-09-19 17:19:33 +00002239
2240 >>> doctest.testfile('test_doctest.txt', globs=globs, verbose=True)
2241 Trying:
2242 favorite_color
2243 Expecting:
2244 'blue'
2245 ok
2246 Trying:
2247 if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00002248 print('a')
2249 print()
2250 print('b')
Edward Loper052d0cd2004-09-19 17:19:33 +00002251 Expecting:
2252 a
2253 <BLANKLINE>
2254 b
2255 ok
2256 1 items passed all tests:
2257 2 tests in test_doctest.txt
2258 2 tests in 1 items.
2259 2 passed and 0 failed.
2260 Test passed.
Christian Heimes25bb7832008-01-11 16:17:00 +00002261 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002262 >>> doctest.master = None # Reset master.
2263
2264The name of the test may be specified with the optional `name`
2265parameter:
2266
2267 >>> doctest.testfile('test_doctest.txt', name='newname')
2268 ... # doctest: +ELLIPSIS
2269 **********************************************************************
2270 File "...", line 6, in newname
2271 ...
Christian Heimes25bb7832008-01-11 16:17:00 +00002272 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002273 >>> doctest.master = None # Reset master.
2274
Ezio Melotti13925002011-03-16 11:05:33 +02002275The summary report may be suppressed with the optional `report`
Edward Loper052d0cd2004-09-19 17:19:33 +00002276parameter:
2277
2278 >>> doctest.testfile('test_doctest.txt', report=False)
2279 ... # doctest: +ELLIPSIS
2280 **********************************************************************
2281 File "...", line 6, in test_doctest.txt
2282 Failed example:
2283 favorite_color
2284 Exception raised:
2285 ...
2286 NameError: name 'favorite_color' is not defined
Christian Heimes25bb7832008-01-11 16:17:00 +00002287 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002288 >>> doctest.master = None # Reset master.
2289
2290The optional keyword argument `raise_on_error` can be used to raise an
2291exception on the first error (which may be useful for postmortem
2292debugging):
2293
2294 >>> doctest.testfile('test_doctest.txt', raise_on_error=True)
2295 ... # doctest: +ELLIPSIS
2296 Traceback (most recent call last):
Guido van Rossum6a2a2a02006-08-26 20:37:44 +00002297 doctest.UnexpectedException: ...
Edward Loper052d0cd2004-09-19 17:19:33 +00002298 >>> doctest.master = None # Reset master.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002299
2300If the tests contain non-ASCII characters, the tests might fail, since
2301it's unknown which encoding is used. The encoding can be specified
2302using the optional keyword argument `encoding`:
2303
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002304 >>> doctest.testfile('test_doctest4.txt', encoding='latin-1') # doctest: +ELLIPSIS
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002305 **********************************************************************
2306 File "...", line 7, in test_doctest4.txt
2307 Failed example:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002308 '...'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002309 Expected:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002310 'f\xf6\xf6'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002311 Got:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002312 'f\xc3\xb6\xc3\xb6'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002313 **********************************************************************
2314 ...
2315 **********************************************************************
2316 1 items had failures:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002317 2 of 2 in test_doctest4.txt
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002318 ***Test Failed*** 2 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002319 TestResults(failed=2, attempted=2)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002320 >>> doctest.master = None # Reset master.
2321
2322 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8')
Christian Heimes25bb7832008-01-11 16:17:00 +00002323 TestResults(failed=0, attempted=2)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002324 >>> doctest.master = None # Reset master.
Florent Xiclunae94b2212010-02-27 14:37:21 +00002325
2326Test the verbose output:
2327
2328 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8', verbose=True)
2329 Trying:
2330 'föö'
2331 Expecting:
2332 'f\xf6\xf6'
2333 ok
2334 Trying:
2335 'bąr'
2336 Expecting:
2337 'b\u0105r'
2338 ok
2339 1 items passed all tests:
2340 2 tests in test_doctest4.txt
2341 2 tests in 1 items.
2342 2 passed and 0 failed.
2343 Test passed.
2344 TestResults(failed=0, attempted=2)
2345 >>> doctest.master = None # Reset master.
2346 >>> sys.argv = save_argv
Edward Loper052d0cd2004-09-19 17:19:33 +00002347"""
2348
R. David Murray58641de2009-06-12 15:33:19 +00002349def test_testmod(): r"""
2350Tests for the testmod function. More might be useful, but for now we're just
2351testing the case raised by Issue 6195, where trying to doctest a C module would
2352fail with a UnicodeDecodeError because doctest tried to read the "source" lines
2353out of the binary module.
2354
2355 >>> import unicodedata
Florent Xiclunae94b2212010-02-27 14:37:21 +00002356 >>> doctest.testmod(unicodedata, verbose=False)
R. David Murray58641de2009-06-12 15:33:19 +00002357 TestResults(failed=0, attempted=0)
2358"""
2359
Tim Peters8485b562004-08-04 18:46:34 +00002360######################################################################
2361## Main
2362######################################################################
2363
2364def test_main():
2365 # Check the doctest cases in doctest itself:
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002366 support.run_doctest(doctest, verbosity=True)
Tim Peters8485b562004-08-04 18:46:34 +00002367 # Check the doctest cases defined here:
2368 from test import test_doctest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002369 support.run_doctest(test_doctest, verbosity=True)
Tim Peters8485b562004-08-04 18:46:34 +00002370
Guido van Rossum34d19282007-08-09 01:03:29 +00002371import trace, sys, re, io
Tim Peters8485b562004-08-04 18:46:34 +00002372def test_coverage(coverdir):
2373 tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
2374 trace=0, count=1)
Guido van Rossume7ba4952007-06-06 23:52:48 +00002375 tracer.run('test_main()')
Tim Peters8485b562004-08-04 18:46:34 +00002376 r = tracer.results()
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002377 print('Writing coverage results...')
Tim Peters8485b562004-08-04 18:46:34 +00002378 r.write_results(show_missing=True, summary=True,
2379 coverdir=coverdir)
2380
2381if __name__ == '__main__':
2382 if '-c' in sys.argv:
2383 test_coverage('/tmp/doctest.cover')
2384 else:
2385 test_main()