blob: 484a9b8468a6bc05714457458ebd39fef3fd8706 [file] [log] [blame]
Tim Peters8485b562004-08-04 18:46:34 +00001"""
2Test script for doctest.
3"""
4
Benjamin Petersonee8712c2008-05-20 21:35:26 +00005from test import support
Tim Peters8485b562004-08-04 18:46:34 +00006import doctest
Victor Stinner9d396392010-10-16 21:54:59 +00007import os
Tim Peters8485b562004-08-04 18:46:34 +00008
Florent Xiclunadc6f2d02010-04-02 19:25:32 +00009
Nick Coghlanf088e5e2008-12-14 11:50:48 +000010# NOTE: There are some additional tests relating to interaction with
11# zipimport in the test_zipimport_support test module.
12
Tim Peters8485b562004-08-04 18:46:34 +000013######################################################################
14## Sample Objects (used by test cases)
15######################################################################
16
17def sample_func(v):
18 """
Tim Peters19397e52004-08-06 22:02:59 +000019 Blah blah
20
Guido van Rossum7131f842007-02-09 20:13:25 +000021 >>> print(sample_func(22))
Tim Peters8485b562004-08-04 18:46:34 +000022 44
Tim Peters19397e52004-08-06 22:02:59 +000023
24 Yee ha!
Tim Peters8485b562004-08-04 18:46:34 +000025 """
26 return v+v
27
28class SampleClass:
29 """
Guido van Rossum7131f842007-02-09 20:13:25 +000030 >>> print(1)
Tim Peters8485b562004-08-04 18:46:34 +000031 1
Edward Loper4ae900f2004-09-21 03:20:34 +000032
33 >>> # comments get ignored. so are empty PS1 and PS2 prompts:
34 >>>
35 ...
36
37 Multiline example:
38 >>> sc = SampleClass(3)
39 >>> for i in range(10):
40 ... sc = sc.double()
Guido van Rossum805365e2007-05-07 22:24:25 +000041 ... print(' ', sc.get(), sep='', end='')
42 6 12 24 48 96 192 384 768 1536 3072
Tim Peters8485b562004-08-04 18:46:34 +000043 """
44 def __init__(self, val):
45 """
Guido van Rossum7131f842007-02-09 20:13:25 +000046 >>> print(SampleClass(12).get())
Tim Peters8485b562004-08-04 18:46:34 +000047 12
48 """
49 self.val = val
50
51 def double(self):
52 """
Guido van Rossum7131f842007-02-09 20:13:25 +000053 >>> print(SampleClass(12).double().get())
Tim Peters8485b562004-08-04 18:46:34 +000054 24
55 """
56 return SampleClass(self.val + self.val)
57
58 def get(self):
59 """
Guido van Rossum7131f842007-02-09 20:13:25 +000060 >>> print(SampleClass(-5).get())
Tim Peters8485b562004-08-04 18:46:34 +000061 -5
62 """
63 return self.val
64
65 def a_staticmethod(v):
66 """
Guido van Rossum7131f842007-02-09 20:13:25 +000067 >>> print(SampleClass.a_staticmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +000068 11
69 """
70 return v+1
71 a_staticmethod = staticmethod(a_staticmethod)
72
73 def a_classmethod(cls, v):
74 """
Guido van Rossum7131f842007-02-09 20:13:25 +000075 >>> print(SampleClass.a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +000076 12
Guido van Rossum7131f842007-02-09 20:13:25 +000077 >>> print(SampleClass(0).a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +000078 12
79 """
80 return v+2
81 a_classmethod = classmethod(a_classmethod)
82
83 a_property = property(get, doc="""
Guido van Rossum7131f842007-02-09 20:13:25 +000084 >>> print(SampleClass(22).a_property)
Tim Peters8485b562004-08-04 18:46:34 +000085 22
86 """)
87
88 class NestedClass:
89 """
90 >>> x = SampleClass.NestedClass(5)
91 >>> y = x.square()
Guido van Rossum7131f842007-02-09 20:13:25 +000092 >>> print(y.get())
Tim Peters8485b562004-08-04 18:46:34 +000093 25
94 """
95 def __init__(self, val=0):
96 """
Guido van Rossum7131f842007-02-09 20:13:25 +000097 >>> print(SampleClass.NestedClass().get())
Tim Peters8485b562004-08-04 18:46:34 +000098 0
99 """
100 self.val = val
101 def square(self):
102 return SampleClass.NestedClass(self.val*self.val)
103 def get(self):
104 return self.val
105
106class SampleNewStyleClass(object):
107 r"""
Guido van Rossum7131f842007-02-09 20:13:25 +0000108 >>> print('1\n2\n3')
Tim Peters8485b562004-08-04 18:46:34 +0000109 1
110 2
111 3
112 """
113 def __init__(self, val):
114 """
Guido van Rossum7131f842007-02-09 20:13:25 +0000115 >>> print(SampleNewStyleClass(12).get())
Tim Peters8485b562004-08-04 18:46:34 +0000116 12
117 """
118 self.val = val
119
120 def double(self):
121 """
Guido van Rossum7131f842007-02-09 20:13:25 +0000122 >>> print(SampleNewStyleClass(12).double().get())
Tim Peters8485b562004-08-04 18:46:34 +0000123 24
124 """
125 return SampleNewStyleClass(self.val + self.val)
126
127 def get(self):
128 """
Guido van Rossum7131f842007-02-09 20:13:25 +0000129 >>> print(SampleNewStyleClass(-5).get())
Tim Peters8485b562004-08-04 18:46:34 +0000130 -5
131 """
132 return self.val
133
134######################################################################
Edward Loper2de91ba2004-08-27 02:07:46 +0000135## Fake stdin (for testing interactive debugging)
136######################################################################
137
138class _FakeInput:
139 """
140 A fake input stream for pdb's interactive debugger. Whenever a
141 line is read, print it (to simulate the user typing it), and then
142 return it. The set of lines to return is specified in the
143 constructor; they should not have trailing newlines.
144 """
145 def __init__(self, lines):
146 self.lines = lines
147
148 def readline(self):
149 line = self.lines.pop(0)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000150 print(line)
Edward Loper2de91ba2004-08-27 02:07:46 +0000151 return line+'\n'
152
153######################################################################
Tim Peters8485b562004-08-04 18:46:34 +0000154## Test Cases
155######################################################################
156
157def test_Example(): r"""
158Unit tests for the `Example` class.
159
Edward Lopera6b68322004-08-26 00:05:43 +0000160Example is a simple container class that holds:
161 - `source`: A source string.
162 - `want`: An expected output string.
163 - `exc_msg`: An expected exception message string (or None if no
164 exception is expected).
165 - `lineno`: A line number (within the docstring).
166 - `indent`: The example's indentation in the input string.
167 - `options`: An option dictionary, mapping option flags to True or
168 False.
Tim Peters8485b562004-08-04 18:46:34 +0000169
Edward Lopera6b68322004-08-26 00:05:43 +0000170These attributes are set by the constructor. `source` and `want` are
171required; the other attributes all have default values:
Tim Peters8485b562004-08-04 18:46:34 +0000172
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000173 >>> example = doctest.Example('print(1)', '1\n')
Edward Lopera6b68322004-08-26 00:05:43 +0000174 >>> (example.source, example.want, example.exc_msg,
175 ... example.lineno, example.indent, example.options)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000176 ('print(1)\n', '1\n', None, 0, 0, {})
Edward Lopera6b68322004-08-26 00:05:43 +0000177
178The first three attributes (`source`, `want`, and `exc_msg`) may be
179specified positionally; the remaining arguments should be specified as
180keyword arguments:
181
182 >>> exc_msg = 'IndexError: pop from an empty list'
183 >>> example = doctest.Example('[].pop()', '', exc_msg,
184 ... lineno=5, indent=4,
185 ... options={doctest.ELLIPSIS: True})
186 >>> (example.source, example.want, example.exc_msg,
187 ... example.lineno, example.indent, example.options)
188 ('[].pop()\n', '', 'IndexError: pop from an empty list\n', 5, 4, {8: True})
189
190The constructor normalizes the `source` string to end in a newline:
Tim Peters8485b562004-08-04 18:46:34 +0000191
Tim Petersbb431472004-08-09 03:51:46 +0000192 Source spans a single line: no terminating newline.
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000193 >>> e = doctest.Example('print(1)', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000194 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000195 ('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000196
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000197 >>> e = doctest.Example('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000198 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000199 ('print(1)\n', '1\n')
Tim Peters8485b562004-08-04 18:46:34 +0000200
Tim Petersbb431472004-08-09 03:51:46 +0000201 Source spans multiple lines: require terminating newline.
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000202 >>> e = doctest.Example('print(1);\nprint(2)\n', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000203 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000204 ('print(1);\nprint(2)\n', '1\n2\n')
Tim Peters8485b562004-08-04 18:46:34 +0000205
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000206 >>> e = doctest.Example('print(1);\nprint(2)', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000207 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000208 ('print(1);\nprint(2)\n', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000209
Edward Lopera6b68322004-08-26 00:05:43 +0000210 Empty source string (which should never appear in real examples)
211 >>> e = doctest.Example('', '')
212 >>> e.source, e.want
213 ('\n', '')
Tim Peters8485b562004-08-04 18:46:34 +0000214
Edward Lopera6b68322004-08-26 00:05:43 +0000215The constructor normalizes the `want` string to end in a newline,
216unless it's the empty string:
217
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000218 >>> e = doctest.Example('print(1)', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000219 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000220 ('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000221
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000222 >>> e = doctest.Example('print(1)', '1')
Tim Petersbb431472004-08-09 03:51:46 +0000223 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000224 ('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000225
Edward Lopera6b68322004-08-26 00:05:43 +0000226 >>> e = doctest.Example('print', '')
Tim Petersbb431472004-08-09 03:51:46 +0000227 >>> e.source, e.want
228 ('print\n', '')
Edward Lopera6b68322004-08-26 00:05:43 +0000229
230The constructor normalizes the `exc_msg` string to end in a newline,
231unless it's `None`:
232
233 Message spans one line
234 >>> exc_msg = 'IndexError: pop from an empty list'
235 >>> e = doctest.Example('[].pop()', '', exc_msg)
236 >>> e.exc_msg
237 'IndexError: pop from an empty list\n'
238
239 >>> exc_msg = 'IndexError: pop from an empty list\n'
240 >>> e = doctest.Example('[].pop()', '', exc_msg)
241 >>> e.exc_msg
242 'IndexError: pop from an empty list\n'
243
244 Message spans multiple lines
245 >>> exc_msg = 'ValueError: 1\n 2'
246 >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
247 >>> e.exc_msg
248 'ValueError: 1\n 2\n'
249
250 >>> exc_msg = 'ValueError: 1\n 2\n'
251 >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
252 >>> e.exc_msg
253 'ValueError: 1\n 2\n'
254
255 Empty (but non-None) exception message (which should never appear
256 in real examples)
257 >>> exc_msg = ''
258 >>> e = doctest.Example('raise X()', '', exc_msg)
259 >>> e.exc_msg
260 '\n'
Tim Peters8485b562004-08-04 18:46:34 +0000261"""
262
263def test_DocTest(): r"""
264Unit tests for the `DocTest` class.
265
266DocTest is a collection of examples, extracted from a docstring, along
267with information about where the docstring comes from (a name,
268filename, and line number). The docstring is parsed by the `DocTest`
269constructor:
270
271 >>> docstring = '''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000272 ... >>> print(12)
Tim Peters8485b562004-08-04 18:46:34 +0000273 ... 12
274 ...
275 ... Non-example text.
276 ...
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000277 ... >>> print('another\example')
Tim Peters8485b562004-08-04 18:46:34 +0000278 ... another
279 ... example
280 ... '''
281 >>> globs = {} # globals to run the test in.
Edward Lopera1ef6112004-08-09 16:14:41 +0000282 >>> parser = doctest.DocTestParser()
283 >>> test = parser.get_doctest(docstring, globs, 'some_test',
284 ... 'some_file', 20)
Guido van Rossum7131f842007-02-09 20:13:25 +0000285 >>> print(test)
Tim Peters8485b562004-08-04 18:46:34 +0000286 <DocTest some_test from some_file:20 (2 examples)>
287 >>> len(test.examples)
288 2
289 >>> e1, e2 = test.examples
290 >>> (e1.source, e1.want, e1.lineno)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000291 ('print(12)\n', '12\n', 1)
Tim Peters8485b562004-08-04 18:46:34 +0000292 >>> (e2.source, e2.want, e2.lineno)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000293 ("print('another\\example')\n", 'another\nexample\n', 6)
Tim Peters8485b562004-08-04 18:46:34 +0000294
295Source information (name, filename, and line number) is available as
296attributes on the doctest object:
297
298 >>> (test.name, test.filename, test.lineno)
299 ('some_test', 'some_file', 20)
300
301The line number of an example within its containing file is found by
302adding the line number of the example and the line number of its
303containing test:
304
305 >>> test.lineno + e1.lineno
306 21
307 >>> test.lineno + e2.lineno
308 26
309
310If the docstring contains inconsistant leading whitespace in the
311expected output of an example, then `DocTest` will raise a ValueError:
312
313 >>> docstring = r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000314 ... >>> print('bad\nindentation')
Tim Peters8485b562004-08-04 18:46:34 +0000315 ... bad
316 ... indentation
317 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000318 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000319 Traceback (most recent call last):
Edward Loper00f8da72004-08-26 18:05:07 +0000320 ValueError: line 4 of the docstring for some_test has inconsistent leading whitespace: 'indentation'
Tim Peters8485b562004-08-04 18:46:34 +0000321
322If the docstring contains inconsistent leading whitespace on
323continuation lines, then `DocTest` will raise a ValueError:
324
325 >>> docstring = r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000326 ... >>> print(('bad indentation',
327 ... ... 2))
Tim Peters8485b562004-08-04 18:46:34 +0000328 ... ('bad', 'indentation')
329 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000330 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000331 Traceback (most recent call last):
Guido van Rossume0192e52007-02-09 23:39:59 +0000332 ValueError: line 2 of the docstring for some_test has inconsistent leading whitespace: '... 2))'
Tim Peters8485b562004-08-04 18:46:34 +0000333
334If there's no blank space after a PS1 prompt ('>>>'), then `DocTest`
335will raise a ValueError:
336
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000337 >>> docstring = '>>>print(1)\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000338 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000339 Traceback (most recent call last):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000340 ValueError: line 1 of the docstring for some_test lacks blank after >>>: '>>>print(1)'
Edward Loper7c748462004-08-09 02:06:06 +0000341
342If there's no blank space after a PS2 prompt ('...'), then `DocTest`
343will raise a ValueError:
344
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000345 >>> docstring = '>>> if 1:\n...print(1)\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000346 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Edward Loper7c748462004-08-09 02:06:06 +0000347 Traceback (most recent call last):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000348 ValueError: line 2 of the docstring for some_test lacks blank after ...: '...print(1)'
Edward Loper7c748462004-08-09 02:06:06 +0000349
Tim Peters8485b562004-08-04 18:46:34 +0000350"""
351
Tim Peters8485b562004-08-04 18:46:34 +0000352def test_DocTestFinder(): r"""
353Unit tests for the `DocTestFinder` class.
354
355DocTestFinder is used to extract DocTests from an object's docstring
356and the docstrings of its contained objects. It can be used with
357modules, functions, classes, methods, staticmethods, classmethods, and
358properties.
359
360Finding Tests in Functions
361~~~~~~~~~~~~~~~~~~~~~~~~~~
362For a function whose docstring contains examples, DocTestFinder.find()
363will return a single test (for that function's docstring):
364
Tim Peters8485b562004-08-04 18:46:34 +0000365 >>> finder = doctest.DocTestFinder()
Jim Fulton07a349c2004-08-22 14:10:00 +0000366
367We'll simulate a __file__ attr that ends in pyc:
368
369 >>> import test.test_doctest
370 >>> old = test.test_doctest.__file__
371 >>> test.test_doctest.__file__ = 'test_doctest.pyc'
372
Tim Peters8485b562004-08-04 18:46:34 +0000373 >>> tests = finder.find(sample_func)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000374
Guido van Rossum7131f842007-02-09 20:13:25 +0000375 >>> print(tests) # doctest: +ELLIPSIS
Victor Stinner9d396392010-10-16 21:54:59 +0000376 [<DocTest sample_func from ...:17 (1 example)>]
Edward Loper8e4a34b2004-08-12 02:34:27 +0000377
Tim Peters4de7c5c2004-08-23 22:38:05 +0000378The exact name depends on how test_doctest was invoked, so allow for
379leading path components.
380
381 >>> tests[0].filename # doctest: +ELLIPSIS
382 '...test_doctest.py'
Jim Fulton07a349c2004-08-22 14:10:00 +0000383
384 >>> test.test_doctest.__file__ = old
Tim Petersc6cbab02004-08-22 19:43:28 +0000385
Jim Fulton07a349c2004-08-22 14:10:00 +0000386
Tim Peters8485b562004-08-04 18:46:34 +0000387 >>> e = tests[0].examples[0]
Tim Petersbb431472004-08-09 03:51:46 +0000388 >>> (e.source, e.want, e.lineno)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000389 ('print(sample_func(22))\n', '44\n', 3)
Tim Peters8485b562004-08-04 18:46:34 +0000390
Edward Loper32ddbf72004-09-13 05:47:24 +0000391By default, tests are created for objects with no docstring:
Tim Peters8485b562004-08-04 18:46:34 +0000392
393 >>> def no_docstring(v):
394 ... pass
Tim Peters958cc892004-09-13 14:53:28 +0000395 >>> finder.find(no_docstring)
396 []
Edward Loper32ddbf72004-09-13 05:47:24 +0000397
398However, the optional argument `exclude_empty` to the DocTestFinder
399constructor can be used to exclude tests for objects with empty
400docstrings:
401
402 >>> def no_docstring(v):
403 ... pass
404 >>> excl_empty_finder = doctest.DocTestFinder(exclude_empty=True)
405 >>> excl_empty_finder.find(no_docstring)
Tim Peters8485b562004-08-04 18:46:34 +0000406 []
407
408If the function has a docstring with no examples, then a test with no
409examples is returned. (This lets `DocTestRunner` collect statistics
410about which functions have no tests -- but is that useful? And should
411an empty test also be created when there's no docstring?)
412
413 >>> def no_examples(v):
414 ... ''' no doctest examples '''
Tim Peters17b56372004-09-11 17:33:27 +0000415 >>> finder.find(no_examples) # doctest: +ELLIPSIS
416 [<DocTest no_examples from ...:1 (no examples)>]
Tim Peters8485b562004-08-04 18:46:34 +0000417
418Finding Tests in Classes
419~~~~~~~~~~~~~~~~~~~~~~~~
420For a class, DocTestFinder will create a test for the class's
421docstring, and will recursively explore its contents, including
422methods, classmethods, staticmethods, properties, and nested classes.
423
424 >>> finder = doctest.DocTestFinder()
425 >>> tests = finder.find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000426 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000427 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000428 3 SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000429 3 SampleClass.NestedClass
430 1 SampleClass.NestedClass.__init__
431 1 SampleClass.__init__
432 2 SampleClass.a_classmethod
433 1 SampleClass.a_property
434 1 SampleClass.a_staticmethod
435 1 SampleClass.double
436 1 SampleClass.get
437
438New-style classes are also supported:
439
440 >>> tests = finder.find(SampleNewStyleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000441 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000442 ... print('%2s %s' % (len(t.examples), t.name))
Tim Peters8485b562004-08-04 18:46:34 +0000443 1 SampleNewStyleClass
444 1 SampleNewStyleClass.__init__
445 1 SampleNewStyleClass.double
446 1 SampleNewStyleClass.get
447
448Finding Tests in Modules
449~~~~~~~~~~~~~~~~~~~~~~~~
450For a module, DocTestFinder will create a test for the class's
451docstring, and will recursively explore its contents, including
452functions, classes, and the `__test__` dictionary, if it exists:
453
454 >>> # A module
Christian Heimes45f9af32007-11-27 21:50:00 +0000455 >>> import types
456 >>> m = types.ModuleType('some_module')
Tim Peters8485b562004-08-04 18:46:34 +0000457 >>> def triple(val):
458 ... '''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000459 ... >>> print(triple(11))
Tim Peters8485b562004-08-04 18:46:34 +0000460 ... 33
461 ... '''
462 ... return val*3
463 >>> m.__dict__.update({
464 ... 'sample_func': sample_func,
465 ... 'SampleClass': SampleClass,
466 ... '__doc__': '''
467 ... Module docstring.
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000468 ... >>> print('module')
Tim Peters8485b562004-08-04 18:46:34 +0000469 ... module
470 ... ''',
471 ... '__test__': {
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000472 ... 'd': '>>> print(6)\n6\n>>> print(7)\n7\n',
Tim Peters8485b562004-08-04 18:46:34 +0000473 ... 'c': triple}})
474
475 >>> finder = doctest.DocTestFinder()
476 >>> # Use module=test.test_doctest, to prevent doctest from
477 >>> # ignoring the objects since they weren't defined in m.
478 >>> import test.test_doctest
479 >>> tests = finder.find(m, module=test.test_doctest)
Tim Peters8485b562004-08-04 18:46:34 +0000480 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000481 ... print('%2s %s' % (len(t.examples), t.name))
Tim Peters8485b562004-08-04 18:46:34 +0000482 1 some_module
Edward Loper4ae900f2004-09-21 03:20:34 +0000483 3 some_module.SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000484 3 some_module.SampleClass.NestedClass
485 1 some_module.SampleClass.NestedClass.__init__
486 1 some_module.SampleClass.__init__
487 2 some_module.SampleClass.a_classmethod
488 1 some_module.SampleClass.a_property
489 1 some_module.SampleClass.a_staticmethod
490 1 some_module.SampleClass.double
491 1 some_module.SampleClass.get
Tim Petersc5684782004-09-13 01:07:12 +0000492 1 some_module.__test__.c
493 2 some_module.__test__.d
Tim Peters8485b562004-08-04 18:46:34 +0000494 1 some_module.sample_func
495
496Duplicate Removal
497~~~~~~~~~~~~~~~~~
498If a single object is listed twice (under different names), then tests
499will only be generated for it once:
500
Tim Petersf3f57472004-08-08 06:11:48 +0000501 >>> from test import doctest_aliases
Benjamin Peterson78565b22009-06-28 19:19:51 +0000502 >>> assert doctest_aliases.TwoNames.f
503 >>> assert doctest_aliases.TwoNames.g
Edward Loper32ddbf72004-09-13 05:47:24 +0000504 >>> tests = excl_empty_finder.find(doctest_aliases)
Guido van Rossum7131f842007-02-09 20:13:25 +0000505 >>> print(len(tests))
Tim Peters8485b562004-08-04 18:46:34 +0000506 2
Guido van Rossum7131f842007-02-09 20:13:25 +0000507 >>> print(tests[0].name)
Tim Petersf3f57472004-08-08 06:11:48 +0000508 test.doctest_aliases.TwoNames
509
510 TwoNames.f and TwoNames.g are bound to the same object.
511 We can't guess which will be found in doctest's traversal of
512 TwoNames.__dict__ first, so we have to allow for either.
513
514 >>> tests[1].name.split('.')[-1] in ['f', 'g']
Tim Peters8485b562004-08-04 18:46:34 +0000515 True
516
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000517Empty Tests
518~~~~~~~~~~~
519By default, an object with no doctests doesn't create any tests:
Tim Peters8485b562004-08-04 18:46:34 +0000520
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000521 >>> tests = doctest.DocTestFinder().find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000522 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000523 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000524 3 SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000525 3 SampleClass.NestedClass
526 1 SampleClass.NestedClass.__init__
Tim Peters958cc892004-09-13 14:53:28 +0000527 1 SampleClass.__init__
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000528 2 SampleClass.a_classmethod
529 1 SampleClass.a_property
530 1 SampleClass.a_staticmethod
Tim Peters958cc892004-09-13 14:53:28 +0000531 1 SampleClass.double
532 1 SampleClass.get
533
534By default, that excluded objects with no doctests. exclude_empty=False
535tells it to include (empty) tests for objects with no doctests. This feature
536is really to support backward compatibility in what doctest.master.summarize()
537displays.
538
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000539 >>> tests = doctest.DocTestFinder(exclude_empty=False).find(SampleClass)
Tim Peters958cc892004-09-13 14:53:28 +0000540 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000541 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000542 3 SampleClass
Tim Peters958cc892004-09-13 14:53:28 +0000543 3 SampleClass.NestedClass
544 1 SampleClass.NestedClass.__init__
Edward Loper32ddbf72004-09-13 05:47:24 +0000545 0 SampleClass.NestedClass.get
546 0 SampleClass.NestedClass.square
Tim Peters8485b562004-08-04 18:46:34 +0000547 1 SampleClass.__init__
Tim Peters8485b562004-08-04 18:46:34 +0000548 2 SampleClass.a_classmethod
549 1 SampleClass.a_property
550 1 SampleClass.a_staticmethod
551 1 SampleClass.double
552 1 SampleClass.get
553
Tim Peters8485b562004-08-04 18:46:34 +0000554Turning off Recursion
555~~~~~~~~~~~~~~~~~~~~~
556DocTestFinder can be told not to look for tests in contained objects
557using the `recurse` flag:
558
559 >>> tests = doctest.DocTestFinder(recurse=False).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000560 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000561 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000562 3 SampleClass
Edward Loperb51b2342004-08-17 16:37:12 +0000563
564Line numbers
565~~~~~~~~~~~~
566DocTestFinder finds the line number of each example:
567
568 >>> def f(x):
569 ... '''
570 ... >>> x = 12
571 ...
572 ... some text
573 ...
574 ... >>> # examples are not created for comments & bare prompts.
575 ... >>>
576 ... ...
577 ...
578 ... >>> for x in range(10):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000579 ... ... print(x, end=' ')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000580 ... 0 1 2 3 4 5 6 7 8 9
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000581 ... >>> x//2
582 ... 6
Edward Loperb51b2342004-08-17 16:37:12 +0000583 ... '''
584 >>> test = doctest.DocTestFinder().find(f)[0]
585 >>> [e.lineno for e in test.examples]
586 [1, 9, 12]
Tim Peters8485b562004-08-04 18:46:34 +0000587"""
588
Edward Loper00f8da72004-08-26 18:05:07 +0000589def test_DocTestParser(): r"""
590Unit tests for the `DocTestParser` class.
591
592DocTestParser is used to parse docstrings containing doctest examples.
593
594The `parse` method divides a docstring into examples and intervening
595text:
596
597 >>> s = '''
598 ... >>> x, y = 2, 3 # no output expected
599 ... >>> if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000600 ... ... print(x)
601 ... ... print(y)
Edward Loper00f8da72004-08-26 18:05:07 +0000602 ... 2
603 ... 3
604 ...
605 ... Some text.
606 ... >>> x+y
607 ... 5
608 ... '''
609 >>> parser = doctest.DocTestParser()
610 >>> for piece in parser.parse(s):
611 ... if isinstance(piece, doctest.Example):
Guido van Rossum7131f842007-02-09 20:13:25 +0000612 ... print('Example:', (piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000613 ... else:
Guido van Rossum7131f842007-02-09 20:13:25 +0000614 ... print(' Text:', repr(piece))
Edward Loper00f8da72004-08-26 18:05:07 +0000615 Text: '\n'
616 Example: ('x, y = 2, 3 # no output expected\n', '', 1)
617 Text: ''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000618 Example: ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000619 Text: '\nSome text.\n'
620 Example: ('x+y\n', '5\n', 9)
621 Text: ''
622
623The `get_examples` method returns just the examples:
624
625 >>> for piece in parser.get_examples(s):
Guido van Rossum7131f842007-02-09 20:13:25 +0000626 ... print((piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000627 ('x, y = 2, 3 # no output expected\n', '', 1)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000628 ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000629 ('x+y\n', '5\n', 9)
630
631The `get_doctest` method creates a Test from the examples, along with the
632given arguments:
633
634 >>> test = parser.get_doctest(s, {}, 'name', 'filename', lineno=5)
635 >>> (test.name, test.filename, test.lineno)
636 ('name', 'filename', 5)
637 >>> for piece in test.examples:
Guido van Rossum7131f842007-02-09 20:13:25 +0000638 ... print((piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000639 ('x, y = 2, 3 # no output expected\n', '', 1)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000640 ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000641 ('x+y\n', '5\n', 9)
642"""
643
Tim Peters8485b562004-08-04 18:46:34 +0000644class test_DocTestRunner:
645 def basics(): r"""
646Unit tests for the `DocTestRunner` class.
647
648DocTestRunner is used to run DocTest test cases, and to accumulate
649statistics. Here's a simple DocTest case we can use:
650
651 >>> def f(x):
652 ... '''
653 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000654 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000655 ... 12
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000656 ... >>> x//2
657 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000658 ... '''
659 >>> test = doctest.DocTestFinder().find(f)[0]
660
661The main DocTestRunner interface is the `run` method, which runs a
662given DocTest case in a given namespace (globs). It returns a tuple
663`(f,t)`, where `f` is the number of failed tests and `t` is the number
664of tried tests.
665
666 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000667 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000668
669If any example produces incorrect output, then the test runner reports
670the failure and proceeds to the next example:
671
672 >>> def f(x):
673 ... '''
674 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000675 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000676 ... 14
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000677 ... >>> x//2
678 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000679 ... '''
680 >>> test = doctest.DocTestFinder().find(f)[0]
681 >>> doctest.DocTestRunner(verbose=True).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000682 ... # doctest: +ELLIPSIS
Edward Loperaacf0832004-08-26 01:19:50 +0000683 Trying:
684 x = 12
685 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000686 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000687 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000688 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000689 Expecting:
690 14
Tim Peters8485b562004-08-04 18:46:34 +0000691 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000692 File ..., line 4, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000693 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000694 print(x)
Jim Fulton07a349c2004-08-22 14:10:00 +0000695 Expected:
696 14
697 Got:
698 12
Edward Loperaacf0832004-08-26 01:19:50 +0000699 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000700 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000701 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000702 6
Tim Peters8485b562004-08-04 18:46:34 +0000703 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000704 TestResults(failed=1, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000705"""
706 def verbose_flag(): r"""
707The `verbose` flag makes the test runner generate more detailed
708output:
709
710 >>> def f(x):
711 ... '''
712 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000713 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000714 ... 12
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000715 ... >>> x//2
716 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000717 ... '''
718 >>> test = doctest.DocTestFinder().find(f)[0]
719
720 >>> doctest.DocTestRunner(verbose=True).run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000721 Trying:
722 x = 12
723 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000724 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000725 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000726 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000727 Expecting:
728 12
Tim Peters8485b562004-08-04 18:46:34 +0000729 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000730 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000731 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000732 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000733 6
Tim Peters8485b562004-08-04 18:46:34 +0000734 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000735 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000736
737If the `verbose` flag is unspecified, then the output will be verbose
738iff `-v` appears in sys.argv:
739
740 >>> # Save the real sys.argv list.
741 >>> old_argv = sys.argv
742
743 >>> # If -v does not appear in sys.argv, then output isn't verbose.
744 >>> sys.argv = ['test']
745 >>> doctest.DocTestRunner().run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000746 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000747
748 >>> # If -v does appear in sys.argv, then output is verbose.
749 >>> sys.argv = ['test', '-v']
750 >>> doctest.DocTestRunner().run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000751 Trying:
752 x = 12
753 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000754 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000755 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000756 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000757 Expecting:
758 12
Tim Peters8485b562004-08-04 18:46:34 +0000759 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000760 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000761 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000762 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000763 6
Tim Peters8485b562004-08-04 18:46:34 +0000764 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000765 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000766
767 >>> # Restore sys.argv
768 >>> sys.argv = old_argv
769
770In the remaining examples, the test runner's verbosity will be
771explicitly set, to ensure that the test behavior is consistent.
772 """
773 def exceptions(): r"""
774Tests of `DocTestRunner`'s exception handling.
775
776An expected exception is specified with a traceback message. The
777lines between the first line and the type/value may be omitted or
778replaced with any other string:
779
780 >>> def f(x):
781 ... '''
782 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000783 ... >>> print(x//0)
Tim Peters8485b562004-08-04 18:46:34 +0000784 ... Traceback (most recent call last):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000785 ... ZeroDivisionError: integer division or modulo by zero
Tim Peters8485b562004-08-04 18:46:34 +0000786 ... '''
787 >>> test = doctest.DocTestFinder().find(f)[0]
788 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000789 TestResults(failed=0, attempted=2)
Tim Peters8485b562004-08-04 18:46:34 +0000790
Edward Loper19b19582004-08-25 23:07:03 +0000791An example may not generate output before it raises an exception; if
792it does, then the traceback message will not be recognized as
793signaling an expected exception, so the example will be reported as an
794unexpected exception:
Tim Peters8485b562004-08-04 18:46:34 +0000795
796 >>> def f(x):
797 ... '''
798 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000799 ... >>> print('pre-exception output', x//0)
Tim Peters8485b562004-08-04 18:46:34 +0000800 ... pre-exception output
801 ... Traceback (most recent call last):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000802 ... ZeroDivisionError: integer division or modulo by zero
Tim Peters8485b562004-08-04 18:46:34 +0000803 ... '''
804 >>> test = doctest.DocTestFinder().find(f)[0]
805 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper19b19582004-08-25 23:07:03 +0000806 ... # doctest: +ELLIPSIS
807 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000808 File ..., line 4, in f
Edward Loper19b19582004-08-25 23:07:03 +0000809 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000810 print('pre-exception output', x//0)
Edward Loper19b19582004-08-25 23:07:03 +0000811 Exception raised:
812 ...
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000813 ZeroDivisionError: integer division or modulo by zero
Christian Heimes25bb7832008-01-11 16:17:00 +0000814 TestResults(failed=1, attempted=2)
Tim Peters8485b562004-08-04 18:46:34 +0000815
816Exception messages may contain newlines:
817
818 >>> def f(x):
819 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000820 ... >>> raise ValueError('multi\nline\nmessage')
Tim Peters8485b562004-08-04 18:46:34 +0000821 ... Traceback (most recent call last):
822 ... ValueError: multi
823 ... line
824 ... message
825 ... '''
826 >>> test = doctest.DocTestFinder().find(f)[0]
827 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000828 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000829
830If an exception is expected, but an exception with the wrong type or
831message is raised, then it is reported as a failure:
832
833 >>> def f(x):
834 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000835 ... >>> raise ValueError('message')
Tim Peters8485b562004-08-04 18:46:34 +0000836 ... Traceback (most recent call last):
837 ... ValueError: wrong message
838 ... '''
839 >>> test = doctest.DocTestFinder().find(f)[0]
840 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000841 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000842 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000843 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000844 Failed example:
Collin Winter3add4d72007-08-29 23:37:32 +0000845 raise ValueError('message')
Tim Peters8485b562004-08-04 18:46:34 +0000846 Expected:
847 Traceback (most recent call last):
848 ValueError: wrong message
849 Got:
850 Traceback (most recent call last):
Edward Loper8e4a34b2004-08-12 02:34:27 +0000851 ...
Tim Peters8485b562004-08-04 18:46:34 +0000852 ValueError: message
Christian Heimes25bb7832008-01-11 16:17:00 +0000853 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000854
Tim Peters1fbf9c52004-09-04 17:21:02 +0000855However, IGNORE_EXCEPTION_DETAIL can be used to allow a mismatch in the
856detail:
857
858 >>> def f(x):
859 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000860 ... >>> raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +0000861 ... Traceback (most recent call last):
862 ... ValueError: wrong message
863 ... '''
864 >>> test = doctest.DocTestFinder().find(f)[0]
865 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000866 TestResults(failed=0, attempted=1)
Tim Peters1fbf9c52004-09-04 17:21:02 +0000867
Nick Coghlan5e76e942010-06-12 13:42:46 +0000868IGNORE_EXCEPTION_DETAIL also ignores difference in exception formatting
869between Python versions. For example, in Python 2.x, the module path of
870the exception is not in the output, but this will fail under Python 3:
871
872 >>> def f(x):
873 ... r'''
874 ... >>> from http.client import HTTPException
875 ... >>> raise HTTPException('message')
876 ... Traceback (most recent call last):
877 ... HTTPException: message
878 ... '''
879 >>> test = doctest.DocTestFinder().find(f)[0]
880 >>> doctest.DocTestRunner(verbose=False).run(test)
881 ... # doctest: +ELLIPSIS
882 **********************************************************************
883 File ..., line 4, in f
884 Failed example:
885 raise HTTPException('message')
886 Expected:
887 Traceback (most recent call last):
888 HTTPException: message
889 Got:
890 Traceback (most recent call last):
891 ...
892 http.client.HTTPException: message
893 TestResults(failed=1, attempted=2)
894
895But in Python 3 the module path is included, and therefore a test must look
896like the following test to succeed in Python 3. But that test will fail under
897Python 2.
898
899 >>> def f(x):
900 ... r'''
901 ... >>> from http.client import HTTPException
902 ... >>> raise HTTPException('message')
903 ... Traceback (most recent call last):
904 ... http.client.HTTPException: message
905 ... '''
906 >>> test = doctest.DocTestFinder().find(f)[0]
907 >>> doctest.DocTestRunner(verbose=False).run(test)
908 TestResults(failed=0, attempted=2)
909
910However, with IGNORE_EXCEPTION_DETAIL, the module name of the exception
911(or its unexpected absence) will be ignored:
912
913 >>> def f(x):
914 ... r'''
915 ... >>> from http.client import HTTPException
916 ... >>> raise HTTPException('message') #doctest: +IGNORE_EXCEPTION_DETAIL
917 ... Traceback (most recent call last):
918 ... HTTPException: message
919 ... '''
920 >>> test = doctest.DocTestFinder().find(f)[0]
921 >>> doctest.DocTestRunner(verbose=False).run(test)
922 TestResults(failed=0, attempted=2)
923
924The module path will be completely ignored, so two different module paths will
925still pass if IGNORE_EXCEPTION_DETAIL is given. This is intentional, so it can
926be used when exceptions have changed module.
927
928 >>> def f(x):
929 ... r'''
930 ... >>> from http.client import HTTPException
931 ... >>> raise HTTPException('message') #doctest: +IGNORE_EXCEPTION_DETAIL
932 ... Traceback (most recent call last):
933 ... foo.bar.HTTPException: message
934 ... '''
935 >>> test = doctest.DocTestFinder().find(f)[0]
936 >>> doctest.DocTestRunner(verbose=False).run(test)
937 TestResults(failed=0, attempted=2)
938
Tim Peters1fbf9c52004-09-04 17:21:02 +0000939But IGNORE_EXCEPTION_DETAIL does not allow a mismatch in the exception type:
940
941 >>> def f(x):
942 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000943 ... >>> raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +0000944 ... Traceback (most recent call last):
945 ... TypeError: wrong type
946 ... '''
947 >>> test = doctest.DocTestFinder().find(f)[0]
948 >>> doctest.DocTestRunner(verbose=False).run(test)
949 ... # doctest: +ELLIPSIS
950 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000951 File ..., line 3, in f
Tim Peters1fbf9c52004-09-04 17:21:02 +0000952 Failed example:
Collin Winter3add4d72007-08-29 23:37:32 +0000953 raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +0000954 Expected:
955 Traceback (most recent call last):
956 TypeError: wrong type
957 Got:
958 Traceback (most recent call last):
959 ...
960 ValueError: message
Christian Heimes25bb7832008-01-11 16:17:00 +0000961 TestResults(failed=1, attempted=1)
Tim Peters1fbf9c52004-09-04 17:21:02 +0000962
Tim Peters8485b562004-08-04 18:46:34 +0000963If an exception is raised but not expected, then it is reported as an
964unexpected exception:
965
Tim Peters8485b562004-08-04 18:46:34 +0000966 >>> def f(x):
967 ... r'''
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000968 ... >>> 1//0
Tim Peters8485b562004-08-04 18:46:34 +0000969 ... 0
970 ... '''
971 >>> test = doctest.DocTestFinder().find(f)[0]
972 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper74bca7a2004-08-12 02:27:44 +0000973 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000974 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000975 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000976 Failed example:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000977 1//0
Tim Peters8485b562004-08-04 18:46:34 +0000978 Exception raised:
979 Traceback (most recent call last):
Jim Fulton07a349c2004-08-22 14:10:00 +0000980 ...
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000981 ZeroDivisionError: integer division or modulo by zero
Christian Heimes25bb7832008-01-11 16:17:00 +0000982 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000983"""
Georg Brandl25fbb892010-07-30 09:23:23 +0000984 def displayhook(): r"""
985Test that changing sys.displayhook doesn't matter for doctest.
986
987 >>> import sys
988 >>> orig_displayhook = sys.displayhook
989 >>> def my_displayhook(x):
990 ... print('hi!')
991 >>> sys.displayhook = my_displayhook
992 >>> def f():
993 ... '''
994 ... >>> 3
995 ... 3
996 ... '''
997 >>> test = doctest.DocTestFinder().find(f)[0]
998 >>> r = doctest.DocTestRunner(verbose=False).run(test)
999 >>> post_displayhook = sys.displayhook
1000
1001 We need to restore sys.displayhook now, so that we'll be able to test
1002 results.
1003
1004 >>> sys.displayhook = orig_displayhook
1005
1006 Ok, now we can check that everything is ok.
1007
1008 >>> r
1009 TestResults(failed=0, attempted=1)
1010 >>> post_displayhook is my_displayhook
1011 True
1012"""
Tim Peters8485b562004-08-04 18:46:34 +00001013 def optionflags(): r"""
1014Tests of `DocTestRunner`'s option flag handling.
1015
1016Several option flags can be used to customize the behavior of the test
1017runner. These are defined as module constants in doctest, and passed
Christian Heimesfaf2f632008-01-06 16:59:19 +00001018to the DocTestRunner constructor (multiple constants should be ORed
Tim Peters8485b562004-08-04 18:46:34 +00001019together).
1020
1021The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
1022and 1/0:
1023
1024 >>> def f(x):
1025 ... '>>> True\n1\n'
1026
1027 >>> # Without the flag:
1028 >>> test = doctest.DocTestFinder().find(f)[0]
1029 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001030 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001031
1032 >>> # With the flag:
1033 >>> test = doctest.DocTestFinder().find(f)[0]
1034 >>> flags = doctest.DONT_ACCEPT_TRUE_FOR_1
1035 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001036 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001037 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001038 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001039 Failed example:
1040 True
1041 Expected:
1042 1
1043 Got:
1044 True
Christian Heimes25bb7832008-01-11 16:17:00 +00001045 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001046
1047The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines
1048and the '<BLANKLINE>' marker:
1049
1050 >>> def f(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001051 ... '>>> print("a\\n\\nb")\na\n<BLANKLINE>\nb\n'
Tim Peters8485b562004-08-04 18:46:34 +00001052
1053 >>> # Without the flag:
1054 >>> test = doctest.DocTestFinder().find(f)[0]
1055 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001056 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001057
1058 >>> # With the flag:
1059 >>> test = doctest.DocTestFinder().find(f)[0]
1060 >>> flags = doctest.DONT_ACCEPT_BLANKLINE
1061 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001062 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001063 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001064 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001065 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001066 print("a\n\nb")
Tim Peters8485b562004-08-04 18:46:34 +00001067 Expected:
1068 a
1069 <BLANKLINE>
1070 b
1071 Got:
1072 a
1073 <BLANKLINE>
1074 b
Christian Heimes25bb7832008-01-11 16:17:00 +00001075 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001076
1077The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be
1078treated as equal:
1079
1080 >>> def f(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001081 ... '>>> print(1, 2, 3)\n 1 2\n 3'
Tim Peters8485b562004-08-04 18:46:34 +00001082
1083 >>> # Without the flag:
1084 >>> test = doctest.DocTestFinder().find(f)[0]
1085 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001086 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001087 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001088 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001089 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001090 print(1, 2, 3)
Tim Peters8485b562004-08-04 18:46:34 +00001091 Expected:
1092 1 2
1093 3
Jim Fulton07a349c2004-08-22 14:10:00 +00001094 Got:
1095 1 2 3
Christian Heimes25bb7832008-01-11 16:17:00 +00001096 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001097
1098 >>> # With the flag:
1099 >>> test = doctest.DocTestFinder().find(f)[0]
1100 >>> flags = doctest.NORMALIZE_WHITESPACE
1101 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001102 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001103
Tim Peters026f8dc2004-08-19 16:38:58 +00001104 An example from the docs:
Guido van Rossum805365e2007-05-07 22:24:25 +00001105 >>> print(list(range(20))) #doctest: +NORMALIZE_WHITESPACE
Tim Peters026f8dc2004-08-19 16:38:58 +00001106 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
1107 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
1108
Tim Peters8485b562004-08-04 18:46:34 +00001109The ELLIPSIS flag causes ellipsis marker ("...") in the expected
1110output to match any substring in the actual output:
1111
1112 >>> def f(x):
Guido van Rossum805365e2007-05-07 22:24:25 +00001113 ... '>>> print(list(range(15)))\n[0, 1, 2, ..., 14]\n'
Tim Peters8485b562004-08-04 18:46:34 +00001114
1115 >>> # Without the flag:
1116 >>> test = doctest.DocTestFinder().find(f)[0]
1117 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001118 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001119 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001120 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001121 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001122 print(list(range(15)))
Jim Fulton07a349c2004-08-22 14:10:00 +00001123 Expected:
1124 [0, 1, 2, ..., 14]
1125 Got:
1126 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
Christian Heimes25bb7832008-01-11 16:17:00 +00001127 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001128
1129 >>> # With the flag:
1130 >>> test = doctest.DocTestFinder().find(f)[0]
1131 >>> flags = doctest.ELLIPSIS
1132 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001133 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001134
Tim Peterse594bee2004-08-22 01:47:51 +00001135 ... also matches nothing:
Tim Peters1cf3aa62004-08-19 06:49:33 +00001136
Guido van Rossume0192e52007-02-09 23:39:59 +00001137 >>> if 1:
1138 ... for i in range(100):
1139 ... print(i**2, end=' ') #doctest: +ELLIPSIS
1140 ... print('!')
1141 0 1...4...9 16 ... 36 49 64 ... 9801 !
Tim Peters1cf3aa62004-08-19 06:49:33 +00001142
Tim Peters026f8dc2004-08-19 16:38:58 +00001143 ... can be surprising; e.g., this test passes:
Tim Peters26b3ebb2004-08-19 08:10:08 +00001144
Guido van Rossume0192e52007-02-09 23:39:59 +00001145 >>> if 1: #doctest: +ELLIPSIS
1146 ... for i in range(20):
1147 ... print(i, end=' ')
1148 ... print(20)
Tim Peterse594bee2004-08-22 01:47:51 +00001149 0 1 2 ...1...2...0
Tim Peters26b3ebb2004-08-19 08:10:08 +00001150
Tim Peters026f8dc2004-08-19 16:38:58 +00001151 Examples from the docs:
1152
Guido van Rossum805365e2007-05-07 22:24:25 +00001153 >>> print(list(range(20))) # doctest:+ELLIPSIS
Tim Peters026f8dc2004-08-19 16:38:58 +00001154 [0, 1, ..., 18, 19]
1155
Guido van Rossum805365e2007-05-07 22:24:25 +00001156 >>> print(list(range(20))) # doctest: +ELLIPSIS
Tim Peters026f8dc2004-08-19 16:38:58 +00001157 ... # doctest: +NORMALIZE_WHITESPACE
1158 [0, 1, ..., 18, 19]
1159
Thomas Wouters477c8d52006-05-27 19:21:47 +00001160The SKIP flag causes an example to be skipped entirely. I.e., the
1161example is not run. It can be useful in contexts where doctest
1162examples serve as both documentation and test cases, and an example
1163should be included for documentation purposes, but should not be
1164checked (e.g., because its output is random, or depends on resources
1165which would be unavailable.) The SKIP flag can also be used for
1166'commenting out' broken examples.
1167
1168 >>> import unavailable_resource # doctest: +SKIP
1169 >>> unavailable_resource.do_something() # doctest: +SKIP
1170 >>> unavailable_resource.blow_up() # doctest: +SKIP
1171 Traceback (most recent call last):
1172 ...
1173 UncheckedBlowUpError: Nobody checks me.
1174
1175 >>> import random
Guido van Rossum7131f842007-02-09 20:13:25 +00001176 >>> print(random.random()) # doctest: +SKIP
Thomas Wouters477c8d52006-05-27 19:21:47 +00001177 0.721216923889
1178
Edward Loper71f55af2004-08-26 01:41:51 +00001179The REPORT_UDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001180and actual outputs to be displayed using a unified diff:
1181
1182 >>> def f(x):
1183 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001184 ... >>> print('\n'.join('abcdefg'))
Tim Peters8485b562004-08-04 18:46:34 +00001185 ... a
1186 ... B
1187 ... c
1188 ... d
1189 ... f
1190 ... g
1191 ... h
1192 ... '''
1193
1194 >>> # Without the flag:
1195 >>> test = doctest.DocTestFinder().find(f)[0]
1196 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001197 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001198 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001199 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001200 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001201 print('\n'.join('abcdefg'))
Tim Peters8485b562004-08-04 18:46:34 +00001202 Expected:
1203 a
1204 B
1205 c
1206 d
1207 f
1208 g
1209 h
1210 Got:
1211 a
1212 b
1213 c
1214 d
1215 e
1216 f
1217 g
Christian Heimes25bb7832008-01-11 16:17:00 +00001218 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001219
1220 >>> # With the flag:
1221 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001222 >>> flags = doctest.REPORT_UDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001223 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001224 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001225 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001226 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001227 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001228 print('\n'.join('abcdefg'))
Edward Loper56629292004-08-26 01:31:56 +00001229 Differences (unified diff with -expected +actual):
Tim Peterse7edcb82004-08-26 05:44:27 +00001230 @@ -1,7 +1,7 @@
Tim Peters8485b562004-08-04 18:46:34 +00001231 a
1232 -B
1233 +b
1234 c
1235 d
1236 +e
1237 f
1238 g
1239 -h
Christian Heimes25bb7832008-01-11 16:17:00 +00001240 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001241
Edward Loper71f55af2004-08-26 01:41:51 +00001242The REPORT_CDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001243and actual outputs to be displayed using a context diff:
1244
Edward Loper71f55af2004-08-26 01:41:51 +00001245 >>> # Reuse f() from the REPORT_UDIFF example, above.
Tim Peters8485b562004-08-04 18:46:34 +00001246 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001247 >>> flags = doctest.REPORT_CDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001248 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001249 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001250 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001251 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001252 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001253 print('\n'.join('abcdefg'))
Edward Loper56629292004-08-26 01:31:56 +00001254 Differences (context diff with expected followed by actual):
Tim Peters8485b562004-08-04 18:46:34 +00001255 ***************
Tim Peterse7edcb82004-08-26 05:44:27 +00001256 *** 1,7 ****
Tim Peters8485b562004-08-04 18:46:34 +00001257 a
1258 ! B
1259 c
1260 d
1261 f
1262 g
1263 - h
Tim Peterse7edcb82004-08-26 05:44:27 +00001264 --- 1,7 ----
Tim Peters8485b562004-08-04 18:46:34 +00001265 a
1266 ! b
1267 c
1268 d
1269 + e
1270 f
1271 g
Christian Heimes25bb7832008-01-11 16:17:00 +00001272 TestResults(failed=1, attempted=1)
Tim Petersc6cbab02004-08-22 19:43:28 +00001273
1274
Edward Loper71f55af2004-08-26 01:41:51 +00001275The REPORT_NDIFF flag causes failures to use the difflib.Differ algorithm
Tim Petersc6cbab02004-08-22 19:43:28 +00001276used by the popular ndiff.py utility. This does intraline difference
1277marking, as well as interline differences.
1278
1279 >>> def f(x):
1280 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001281 ... >>> print("a b c d e f g h i j k l m")
Tim Petersc6cbab02004-08-22 19:43:28 +00001282 ... a b c d e f g h i j k 1 m
1283 ... '''
1284 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001285 >>> flags = doctest.REPORT_NDIFF
Tim Petersc6cbab02004-08-22 19:43:28 +00001286 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001287 ... # doctest: +ELLIPSIS
Tim Petersc6cbab02004-08-22 19:43:28 +00001288 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001289 File ..., line 3, in f
Tim Petersc6cbab02004-08-22 19:43:28 +00001290 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001291 print("a b c d e f g h i j k l m")
Tim Petersc6cbab02004-08-22 19:43:28 +00001292 Differences (ndiff with -expected +actual):
1293 - a b c d e f g h i j k 1 m
1294 ? ^
1295 + a b c d e f g h i j k l m
1296 ? + ++ ^
Christian Heimes25bb7832008-01-11 16:17:00 +00001297 TestResults(failed=1, attempted=1)
Edward Lopera89f88d2004-08-26 02:45:51 +00001298
1299The REPORT_ONLY_FIRST_FAILURE supresses result output after the first
1300failing example:
1301
1302 >>> def f(x):
1303 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001304 ... >>> print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001305 ... 1
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001306 ... >>> print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001307 ... 200
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001308 ... >>> print(3) # second failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001309 ... 300
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001310 ... >>> print(4) # second success
Edward Lopera89f88d2004-08-26 02:45:51 +00001311 ... 4
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001312 ... >>> print(5) # third failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001313 ... 500
1314 ... '''
1315 >>> test = doctest.DocTestFinder().find(f)[0]
1316 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1317 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001318 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001319 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001320 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001321 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001322 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001323 Expected:
1324 200
1325 Got:
1326 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001327 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001328
1329However, output from `report_start` is not supressed:
1330
1331 >>> doctest.DocTestRunner(verbose=True, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001332 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001333 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001334 print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001335 Expecting:
1336 1
1337 ok
1338 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001339 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001340 Expecting:
1341 200
1342 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001343 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001344 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001345 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001346 Expected:
1347 200
1348 Got:
1349 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001350 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001351
1352For the purposes of REPORT_ONLY_FIRST_FAILURE, unexpected exceptions
1353count as failures:
1354
1355 >>> def f(x):
1356 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001357 ... >>> print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001358 ... 1
1359 ... >>> raise ValueError(2) # first failure
1360 ... 200
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001361 ... >>> print(3) # second failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001362 ... 300
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001363 ... >>> print(4) # second success
Edward Lopera89f88d2004-08-26 02:45:51 +00001364 ... 4
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001365 ... >>> print(5) # third failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001366 ... 500
1367 ... '''
1368 >>> test = doctest.DocTestFinder().find(f)[0]
1369 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1370 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1371 ... # doctest: +ELLIPSIS
1372 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001373 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001374 Failed example:
1375 raise ValueError(2) # first failure
1376 Exception raised:
1377 ...
1378 ValueError: 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001379 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001380
Thomas Wouters477c8d52006-05-27 19:21:47 +00001381New option flags can also be registered, via register_optionflag(). Here
1382we reach into doctest's internals a bit.
1383
1384 >>> unlikely = "UNLIKELY_OPTION_NAME"
1385 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1386 False
1387 >>> new_flag_value = doctest.register_optionflag(unlikely)
1388 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1389 True
1390
1391Before 2.4.4/2.5, registering a name more than once erroneously created
1392more than one flag value. Here we verify that's fixed:
1393
1394 >>> redundant_flag_value = doctest.register_optionflag(unlikely)
1395 >>> redundant_flag_value == new_flag_value
1396 True
1397
1398Clean up.
1399 >>> del doctest.OPTIONFLAGS_BY_NAME[unlikely]
1400
Tim Petersc6cbab02004-08-22 19:43:28 +00001401 """
1402
Tim Peters8485b562004-08-04 18:46:34 +00001403 def option_directives(): r"""
1404Tests of `DocTestRunner`'s option directive mechanism.
1405
Edward Loper74bca7a2004-08-12 02:27:44 +00001406Option directives can be used to turn option flags on or off for a
1407single example. To turn an option on for an example, follow that
1408example with a comment of the form ``# doctest: +OPTION``:
Tim Peters8485b562004-08-04 18:46:34 +00001409
1410 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001411 ... >>> print(list(range(10))) # should fail: no ellipsis
Edward Loper74bca7a2004-08-12 02:27:44 +00001412 ... [0, 1, ..., 9]
1413 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001414 ... >>> print(list(range(10))) # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001415 ... [0, 1, ..., 9]
1416 ... '''
1417 >>> test = doctest.DocTestFinder().find(f)[0]
1418 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001419 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001420 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001421 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001422 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001423 print(list(range(10))) # should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001424 Expected:
1425 [0, 1, ..., 9]
1426 Got:
1427 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001428 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001429
1430To turn an option off for an example, follow that example with a
1431comment of the form ``# doctest: -OPTION``:
1432
1433 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001434 ... >>> print(list(range(10)))
Edward Loper74bca7a2004-08-12 02:27:44 +00001435 ... [0, 1, ..., 9]
1436 ...
1437 ... >>> # should fail: no ellipsis
Guido van Rossum805365e2007-05-07 22:24:25 +00001438 ... >>> print(list(range(10))) # doctest: -ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001439 ... [0, 1, ..., 9]
1440 ... '''
1441 >>> test = doctest.DocTestFinder().find(f)[0]
1442 >>> doctest.DocTestRunner(verbose=False,
1443 ... optionflags=doctest.ELLIPSIS).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001444 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001445 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001446 File ..., line 6, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001447 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001448 print(list(range(10))) # doctest: -ELLIPSIS
Jim Fulton07a349c2004-08-22 14:10:00 +00001449 Expected:
1450 [0, 1, ..., 9]
1451 Got:
1452 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001453 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001454
1455Option directives affect only the example that they appear with; they
1456do not change the options for surrounding examples:
Edward Loper8e4a34b2004-08-12 02:34:27 +00001457
Edward Loper74bca7a2004-08-12 02:27:44 +00001458 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001459 ... >>> print(list(range(10))) # Should fail: no ellipsis
Tim Peters8485b562004-08-04 18:46:34 +00001460 ... [0, 1, ..., 9]
1461 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001462 ... >>> print(list(range(10))) # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001463 ... [0, 1, ..., 9]
1464 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001465 ... >>> print(list(range(10))) # Should fail: no ellipsis
Tim Peters8485b562004-08-04 18:46:34 +00001466 ... [0, 1, ..., 9]
1467 ... '''
1468 >>> test = doctest.DocTestFinder().find(f)[0]
1469 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001470 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001471 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001472 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001473 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001474 print(list(range(10))) # Should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001475 Expected:
1476 [0, 1, ..., 9]
1477 Got:
1478 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001479 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001480 File ..., line 8, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001481 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001482 print(list(range(10))) # Should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001483 Expected:
1484 [0, 1, ..., 9]
1485 Got:
1486 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001487 TestResults(failed=2, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +00001488
Edward Loper74bca7a2004-08-12 02:27:44 +00001489Multiple options may be modified by a single option directive. They
1490may be separated by whitespace, commas, or both:
Tim Peters8485b562004-08-04 18:46:34 +00001491
1492 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001493 ... >>> print(list(range(10))) # Should fail
Tim Peters8485b562004-08-04 18:46:34 +00001494 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001495 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001496 ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001497 ... [0, 1, ..., 9]
1498 ... '''
1499 >>> test = doctest.DocTestFinder().find(f)[0]
1500 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001501 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001502 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001503 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001504 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001505 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001506 Expected:
1507 [0, 1, ..., 9]
1508 Got:
1509 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001510 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001511
1512 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001513 ... >>> print(list(range(10))) # Should fail
Edward Loper74bca7a2004-08-12 02:27:44 +00001514 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001515 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001516 ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
1517 ... [0, 1, ..., 9]
1518 ... '''
1519 >>> test = doctest.DocTestFinder().find(f)[0]
1520 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001521 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001522 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001523 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001524 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001525 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001526 Expected:
1527 [0, 1, ..., 9]
1528 Got:
1529 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001530 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001531
1532 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001533 ... >>> print(list(range(10))) # Should fail
Edward Loper74bca7a2004-08-12 02:27:44 +00001534 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001535 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001536 ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1537 ... [0, 1, ..., 9]
1538 ... '''
1539 >>> test = doctest.DocTestFinder().find(f)[0]
1540 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001541 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001542 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001543 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001544 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001545 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001546 Expected:
1547 [0, 1, ..., 9]
1548 Got:
1549 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001550 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001551
1552The option directive may be put on the line following the source, as
1553long as a continuation prompt is used:
1554
1555 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001556 ... >>> print(list(range(10)))
Edward Loper74bca7a2004-08-12 02:27:44 +00001557 ... ... # doctest: +ELLIPSIS
1558 ... [0, 1, ..., 9]
1559 ... '''
1560 >>> test = doctest.DocTestFinder().find(f)[0]
1561 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001562 TestResults(failed=0, attempted=1)
Edward Loper8e4a34b2004-08-12 02:34:27 +00001563
Edward Loper74bca7a2004-08-12 02:27:44 +00001564For examples with multi-line source, the option directive may appear
1565at the end of any line:
1566
1567 >>> def f(x): r'''
1568 ... >>> for x in range(10): # doctest: +ELLIPSIS
Guido van Rossum805365e2007-05-07 22:24:25 +00001569 ... ... print(' ', x, end='', sep='')
1570 ... 0 1 2 ... 9
Edward Loper74bca7a2004-08-12 02:27:44 +00001571 ...
1572 ... >>> for x in range(10):
Guido van Rossum805365e2007-05-07 22:24:25 +00001573 ... ... print(' ', x, end='', sep='') # doctest: +ELLIPSIS
1574 ... 0 1 2 ... 9
Edward Loper74bca7a2004-08-12 02:27:44 +00001575 ... '''
1576 >>> test = doctest.DocTestFinder().find(f)[0]
1577 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001578 TestResults(failed=0, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001579
1580If more than one line of an example with multi-line source has an
1581option directive, then they are combined:
1582
1583 >>> def f(x): r'''
1584 ... Should fail (option directive not on the last line):
1585 ... >>> for x in range(10): # doctest: +ELLIPSIS
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001586 ... ... print(x, end=' ') # doctest: +NORMALIZE_WHITESPACE
Guido van Rossumd8faa362007-04-27 19:54:29 +00001587 ... 0 1 2...9
Edward Loper74bca7a2004-08-12 02:27:44 +00001588 ... '''
1589 >>> test = doctest.DocTestFinder().find(f)[0]
1590 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001591 TestResults(failed=0, attempted=1)
Edward Loper74bca7a2004-08-12 02:27:44 +00001592
1593It is an error to have a comment of the form ``# doctest:`` that is
1594*not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
1595``OPTION`` is an option that has been registered with
1596`register_option`:
1597
1598 >>> # Error: Option not registered
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001599 >>> s = '>>> print(12) #doctest: +BADOPTION'
Edward Loper74bca7a2004-08-12 02:27:44 +00001600 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1601 Traceback (most recent call last):
1602 ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
1603
1604 >>> # Error: No + or - prefix
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001605 >>> s = '>>> print(12) #doctest: ELLIPSIS'
Edward Loper74bca7a2004-08-12 02:27:44 +00001606 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1607 Traceback (most recent call last):
1608 ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
1609
1610It is an error to use an option directive on a line that contains no
1611source:
1612
1613 >>> s = '>>> # doctest: +ELLIPSIS'
1614 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1615 Traceback (most recent call last):
1616 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 +00001617"""
1618
1619def test_testsource(): r"""
1620Unit tests for `testsource()`.
1621
1622The testsource() function takes a module and a name, finds the (first)
Tim Peters19397e52004-08-06 22:02:59 +00001623test with that name in that module, and converts it to a script. The
1624example code is converted to regular Python code. The surrounding
1625words and expected output are converted to comments:
Tim Peters8485b562004-08-04 18:46:34 +00001626
1627 >>> import test.test_doctest
1628 >>> name = 'test.test_doctest.sample_func'
Guido van Rossum7131f842007-02-09 20:13:25 +00001629 >>> print(doctest.testsource(test.test_doctest, name))
Edward Lopera5db6002004-08-12 02:41:30 +00001630 # Blah blah
Tim Peters19397e52004-08-06 22:02:59 +00001631 #
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001632 print(sample_func(22))
Tim Peters8485b562004-08-04 18:46:34 +00001633 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001634 ## 44
Tim Peters19397e52004-08-06 22:02:59 +00001635 #
Edward Lopera5db6002004-08-12 02:41:30 +00001636 # Yee ha!
Georg Brandlecf93c72005-06-26 23:09:51 +00001637 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001638
1639 >>> name = 'test.test_doctest.SampleNewStyleClass'
Guido van Rossum7131f842007-02-09 20:13:25 +00001640 >>> print(doctest.testsource(test.test_doctest, name))
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001641 print('1\n2\n3')
Tim Peters8485b562004-08-04 18:46:34 +00001642 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001643 ## 1
1644 ## 2
1645 ## 3
Georg Brandlecf93c72005-06-26 23:09:51 +00001646 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001647
1648 >>> name = 'test.test_doctest.SampleClass.a_classmethod'
Guido van Rossum7131f842007-02-09 20:13:25 +00001649 >>> print(doctest.testsource(test.test_doctest, name))
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001650 print(SampleClass.a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +00001651 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001652 ## 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001653 print(SampleClass(0).a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +00001654 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001655 ## 12
Georg Brandlecf93c72005-06-26 23:09:51 +00001656 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001657"""
1658
1659def test_debug(): r"""
1660
1661Create a docstring that we want to debug:
1662
1663 >>> s = '''
1664 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001665 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +00001666 ... 12
1667 ... '''
1668
1669Create some fake stdin input, to feed to the debugger:
1670
Tim Peters8485b562004-08-04 18:46:34 +00001671 >>> real_stdin = sys.stdin
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001672 >>> sys.stdin = _FakeInput(['next', 'print(x)', 'continue'])
Tim Peters8485b562004-08-04 18:46:34 +00001673
1674Run the debugger on the docstring, and then restore sys.stdin.
1675
Edward Loper2de91ba2004-08-27 02:07:46 +00001676 >>> try: doctest.debug_src(s)
1677 ... finally: sys.stdin = real_stdin
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001678 > <string>(1)<module>()
Edward Loper2de91ba2004-08-27 02:07:46 +00001679 (Pdb) next
1680 12
Tim Peters8485b562004-08-04 18:46:34 +00001681 --Return--
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001682 > <string>(1)<module>()->None
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001683 (Pdb) print(x)
Edward Loper2de91ba2004-08-27 02:07:46 +00001684 12
1685 (Pdb) continue
Tim Peters8485b562004-08-04 18:46:34 +00001686
1687"""
1688
Jim Fulton356fd192004-08-09 11:34:47 +00001689def test_pdb_set_trace():
Tim Peters50c6bdb2004-11-08 22:07:37 +00001690 """Using pdb.set_trace from a doctest.
Jim Fulton356fd192004-08-09 11:34:47 +00001691
Tim Peters413ced62004-08-09 15:43:47 +00001692 You can use pdb.set_trace from a doctest. To do so, you must
Jim Fulton356fd192004-08-09 11:34:47 +00001693 retrieve the set_trace function from the pdb module at the time
Tim Peters413ced62004-08-09 15:43:47 +00001694 you use it. The doctest module changes sys.stdout so that it can
1695 capture program output. It also temporarily replaces pdb.set_trace
1696 with a version that restores stdout. This is necessary for you to
Jim Fulton356fd192004-08-09 11:34:47 +00001697 see debugger output.
1698
1699 >>> doc = '''
1700 ... >>> x = 42
Florent Xicluna35049442010-10-14 21:35:58 +00001701 ... >>> raise Exception('clé')
1702 ... Traceback (most recent call last):
1703 ... Exception: clé
Jim Fulton356fd192004-08-09 11:34:47 +00001704 ... >>> import pdb; pdb.set_trace()
1705 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001706 >>> parser = doctest.DocTestParser()
Victor Stinner9d396392010-10-16 21:54:59 +00001707 >>> test = parser.get_doctest(doc, {}, "foo-bar@baz", "foo-bar@baz.py", 0)
Jim Fulton356fd192004-08-09 11:34:47 +00001708 >>> runner = doctest.DocTestRunner(verbose=False)
1709
1710 To demonstrate this, we'll create a fake standard input that
1711 captures our debugger input:
1712
1713 >>> import tempfile
Edward Loper2de91ba2004-08-27 02:07:46 +00001714 >>> real_stdin = sys.stdin
1715 >>> sys.stdin = _FakeInput([
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001716 ... 'print(x)', # print data defined by the example
Jim Fulton356fd192004-08-09 11:34:47 +00001717 ... 'continue', # stop debugging
Edward Loper2de91ba2004-08-27 02:07:46 +00001718 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001719
Edward Loper2de91ba2004-08-27 02:07:46 +00001720 >>> try: runner.run(test)
1721 ... finally: sys.stdin = real_stdin
Jim Fulton356fd192004-08-09 11:34:47 +00001722 --Return--
Victor Stinner9d396392010-10-16 21:54:59 +00001723 > <doctest foo-bar@baz[2]>(1)<module>()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001724 -> import pdb; pdb.set_trace()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001725 (Pdb) print(x)
Edward Loper2de91ba2004-08-27 02:07:46 +00001726 42
1727 (Pdb) continue
Florent Xicluna35049442010-10-14 21:35:58 +00001728 TestResults(failed=0, attempted=3)
Jim Fulton356fd192004-08-09 11:34:47 +00001729
1730 You can also put pdb.set_trace in a function called from a test:
1731
1732 >>> def calls_set_trace():
1733 ... y=2
1734 ... import pdb; pdb.set_trace()
1735
1736 >>> doc = '''
1737 ... >>> x=1
1738 ... >>> calls_set_trace()
1739 ... '''
Victor Stinner9d396392010-10-16 21:54:59 +00001740 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
Edward Loper2de91ba2004-08-27 02:07:46 +00001741 >>> real_stdin = sys.stdin
1742 >>> sys.stdin = _FakeInput([
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001743 ... 'print(y)', # print data defined in the function
Jim Fulton356fd192004-08-09 11:34:47 +00001744 ... 'up', # out of function
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001745 ... 'print(x)', # print data defined by the example
Jim Fulton356fd192004-08-09 11:34:47 +00001746 ... 'continue', # stop debugging
Edward Loper2de91ba2004-08-27 02:07:46 +00001747 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001748
Tim Peters50c6bdb2004-11-08 22:07:37 +00001749 >>> try:
1750 ... runner.run(test)
1751 ... finally:
1752 ... sys.stdin = real_stdin
Jim Fulton356fd192004-08-09 11:34:47 +00001753 --Return--
Edward Loper2de91ba2004-08-27 02:07:46 +00001754 > <doctest test.test_doctest.test_pdb_set_trace[8]>(3)calls_set_trace()->None
1755 -> import pdb; pdb.set_trace()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001756 (Pdb) print(y)
Edward Loper2de91ba2004-08-27 02:07:46 +00001757 2
1758 (Pdb) up
Victor Stinner9d396392010-10-16 21:54:59 +00001759 > <doctest foo-bar@baz[1]>(1)<module>()
Edward Loper2de91ba2004-08-27 02:07:46 +00001760 -> calls_set_trace()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001761 (Pdb) print(x)
Edward Loper2de91ba2004-08-27 02:07:46 +00001762 1
1763 (Pdb) continue
Christian Heimes25bb7832008-01-11 16:17:00 +00001764 TestResults(failed=0, attempted=2)
Edward Loper2de91ba2004-08-27 02:07:46 +00001765
1766 During interactive debugging, source code is shown, even for
1767 doctest examples:
1768
1769 >>> doc = '''
1770 ... >>> def f(x):
1771 ... ... g(x*2)
1772 ... >>> def g(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001773 ... ... print(x+3)
Edward Loper2de91ba2004-08-27 02:07:46 +00001774 ... ... import pdb; pdb.set_trace()
1775 ... >>> f(3)
1776 ... '''
Victor Stinner9d396392010-10-16 21:54:59 +00001777 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
Edward Loper2de91ba2004-08-27 02:07:46 +00001778 >>> real_stdin = sys.stdin
1779 >>> sys.stdin = _FakeInput([
1780 ... 'list', # list source from example 2
1781 ... 'next', # return from g()
1782 ... 'list', # list source from example 1
1783 ... 'next', # return from f()
1784 ... 'list', # list source from example 3
1785 ... 'continue', # stop debugging
1786 ... ''])
1787 >>> try: runner.run(test)
1788 ... finally: sys.stdin = real_stdin
1789 ... # doctest: +NORMALIZE_WHITESPACE
1790 --Return--
Victor Stinner9d396392010-10-16 21:54:59 +00001791 > <doctest foo-bar@baz[1]>(3)g()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001792 -> import pdb; pdb.set_trace()
1793 (Pdb) list
1794 1 def g(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001795 2 print(x+3)
Edward Loper2de91ba2004-08-27 02:07:46 +00001796 3 -> import pdb; pdb.set_trace()
1797 [EOF]
1798 (Pdb) next
1799 --Return--
Victor Stinner9d396392010-10-16 21:54:59 +00001800 > <doctest foo-bar@baz[0]>(2)f()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001801 -> g(x*2)
1802 (Pdb) list
1803 1 def f(x):
1804 2 -> g(x*2)
1805 [EOF]
1806 (Pdb) next
1807 --Return--
Victor Stinner9d396392010-10-16 21:54:59 +00001808 > <doctest foo-bar@baz[2]>(1)<module>()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001809 -> f(3)
1810 (Pdb) list
1811 1 -> f(3)
1812 [EOF]
1813 (Pdb) continue
1814 **********************************************************************
Victor Stinner9d396392010-10-16 21:54:59 +00001815 File "foo-bar@baz.py", line 7, in foo-bar@baz
Edward Loper2de91ba2004-08-27 02:07:46 +00001816 Failed example:
1817 f(3)
1818 Expected nothing
1819 Got:
1820 9
Christian Heimes25bb7832008-01-11 16:17:00 +00001821 TestResults(failed=1, attempted=3)
Jim Fulton356fd192004-08-09 11:34:47 +00001822 """
1823
Tim Peters50c6bdb2004-11-08 22:07:37 +00001824def test_pdb_set_trace_nested():
1825 """This illustrates more-demanding use of set_trace with nested functions.
1826
1827 >>> class C(object):
1828 ... def calls_set_trace(self):
1829 ... y = 1
1830 ... import pdb; pdb.set_trace()
1831 ... self.f1()
1832 ... y = 2
1833 ... def f1(self):
1834 ... x = 1
1835 ... self.f2()
1836 ... x = 2
1837 ... def f2(self):
1838 ... z = 1
1839 ... z = 2
1840
1841 >>> calls_set_trace = C().calls_set_trace
1842
1843 >>> doc = '''
1844 ... >>> a = 1
1845 ... >>> calls_set_trace()
1846 ... '''
1847 >>> parser = doctest.DocTestParser()
1848 >>> runner = doctest.DocTestRunner(verbose=False)
Victor Stinner9d396392010-10-16 21:54:59 +00001849 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001850 >>> real_stdin = sys.stdin
1851 >>> sys.stdin = _FakeInput([
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001852 ... 'print(y)', # print data defined in the function
1853 ... 'step', 'step', 'step', 'step', 'step', 'step', 'print(z)',
1854 ... 'up', 'print(x)',
1855 ... 'up', 'print(y)',
1856 ... 'up', 'print(foo)',
Tim Peters50c6bdb2004-11-08 22:07:37 +00001857 ... 'continue', # stop debugging
1858 ... ''])
1859
1860 >>> try:
1861 ... runner.run(test)
1862 ... finally:
1863 ... sys.stdin = real_stdin
Guido van Rossum4a625c32007-09-08 16:05:25 +00001864 ... # doctest: +REPORT_NDIFF
Tim Peters50c6bdb2004-11-08 22:07:37 +00001865 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
1866 -> self.f1()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001867 (Pdb) print(y)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001868 1
1869 (Pdb) step
1870 --Call--
1871 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(7)f1()
1872 -> def f1(self):
1873 (Pdb) step
1874 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(8)f1()
1875 -> x = 1
1876 (Pdb) step
1877 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
1878 -> self.f2()
1879 (Pdb) step
1880 --Call--
1881 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(11)f2()
1882 -> def f2(self):
1883 (Pdb) step
1884 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(12)f2()
1885 -> z = 1
1886 (Pdb) step
1887 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(13)f2()
1888 -> z = 2
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001889 (Pdb) print(z)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001890 1
1891 (Pdb) up
1892 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
1893 -> self.f2()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001894 (Pdb) print(x)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001895 1
1896 (Pdb) up
1897 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
1898 -> self.f1()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001899 (Pdb) print(y)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001900 1
1901 (Pdb) up
Victor Stinner9d396392010-10-16 21:54:59 +00001902 > <doctest foo-bar@baz[1]>(1)<module>()
Tim Peters50c6bdb2004-11-08 22:07:37 +00001903 -> calls_set_trace()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001904 (Pdb) print(foo)
Georg Brandl0d089622010-07-30 16:00:46 +00001905 *** NameError: name 'foo' is not defined
Tim Peters50c6bdb2004-11-08 22:07:37 +00001906 (Pdb) continue
Christian Heimes25bb7832008-01-11 16:17:00 +00001907 TestResults(failed=0, attempted=2)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001908"""
1909
Tim Peters19397e52004-08-06 22:02:59 +00001910def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +00001911 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +00001912
1913 We create a Suite by providing a module. A module can be provided
1914 by passing a module object:
1915
1916 >>> import unittest
1917 >>> import test.sample_doctest
1918 >>> suite = doctest.DocTestSuite(test.sample_doctest)
1919 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001920 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001921
1922 We can also supply the module by name:
1923
1924 >>> suite = doctest.DocTestSuite('test.sample_doctest')
1925 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001926 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001927
1928 We can use the current module:
1929
1930 >>> suite = test.sample_doctest.test_suite()
1931 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001932 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001933
1934 We can supply global variables. If we pass globs, they will be
1935 used instead of the module globals. Here we'll pass an empty
1936 globals, triggering an extra error:
1937
1938 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
1939 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001940 <unittest.result.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001941
1942 Alternatively, we can provide extra globals. Here we'll make an
1943 error go away by providing an extra global variable:
1944
1945 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1946 ... extraglobs={'y': 1})
1947 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001948 <unittest.result.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001949
1950 You can pass option flags. Here we'll cause an extra error
1951 by disabling the blank-line feature:
1952
1953 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00001954 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00001955 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001956 <unittest.result.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001957
Tim Peters1e277ee2004-08-07 05:37:52 +00001958 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00001959
Jim Fultonf54bad42004-08-28 14:57:56 +00001960 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00001961 ... import test.test_doctest
1962 ... test.test_doctest.sillySetup = True
1963
Jim Fultonf54bad42004-08-28 14:57:56 +00001964 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00001965 ... import test.test_doctest
1966 ... del test.test_doctest.sillySetup
1967
1968 Here, we installed a silly variable that the test expects:
1969
1970 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1971 ... setUp=setUp, tearDown=tearDown)
1972 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001973 <unittest.result.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001974
1975 But the tearDown restores sanity:
1976
1977 >>> import test.test_doctest
1978 >>> test.test_doctest.sillySetup
1979 Traceback (most recent call last):
1980 ...
1981 AttributeError: 'module' object has no attribute 'sillySetup'
1982
Jim Fultonf54bad42004-08-28 14:57:56 +00001983 The setUp and tearDown funtions are passed test objects. Here
1984 we'll use the setUp function to supply the missing variable y:
1985
1986 >>> def setUp(test):
1987 ... test.globs['y'] = 1
1988
1989 >>> suite = doctest.DocTestSuite('test.sample_doctest', setUp=setUp)
1990 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001991 <unittest.result.TestResult run=9 errors=0 failures=3>
Jim Fultonf54bad42004-08-28 14:57:56 +00001992
1993 Here, we didn't need to use a tearDown function because we
1994 modified the test globals, which are a copy of the
1995 sample_doctest module dictionary. The test globals are
1996 automatically cleared for us after a test.
Tim Peters19397e52004-08-06 22:02:59 +00001997 """
1998
1999def test_DocFileSuite():
2000 """We can test tests found in text files using a DocFileSuite.
2001
2002 We create a suite by providing the names of one or more text
2003 files that include examples:
2004
2005 >>> import unittest
2006 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002007 ... 'test_doctest2.txt',
2008 ... 'test_doctest4.txt')
Tim Peters19397e52004-08-06 22:02:59 +00002009 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002010 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002011
2012 The test files are looked for in the directory containing the
2013 calling module. A package keyword argument can be provided to
2014 specify a different relative location.
2015
2016 >>> import unittest
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 ... package='test')
2021 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002022 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002023
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002024 Support for using a package's __loader__.get_data() is also
2025 provided.
2026
2027 >>> import unittest, pkgutil, test
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002028 >>> added_loader = False
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002029 >>> if not hasattr(test, '__loader__'):
2030 ... test.__loader__ = pkgutil.get_loader(test)
2031 ... added_loader = True
2032 >>> try:
2033 ... suite = doctest.DocFileSuite('test_doctest.txt',
2034 ... 'test_doctest2.txt',
2035 ... 'test_doctest4.txt',
2036 ... package='test')
2037 ... suite.run(unittest.TestResult())
2038 ... finally:
2039 ... if added_loader:
2040 ... del test.__loader__
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002041 <unittest.result.TestResult run=3 errors=0 failures=2>
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002042
Edward Loper0273f5b2004-09-18 20:27:04 +00002043 '/' should be used as a path separator. It will be converted
2044 to a native separator at run time:
Tim Peters19397e52004-08-06 22:02:59 +00002045
2046 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
2047 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002048 <unittest.result.TestResult run=1 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002049
Edward Loper0273f5b2004-09-18 20:27:04 +00002050 If DocFileSuite is used from an interactive session, then files
2051 are resolved relative to the directory of sys.argv[0]:
2052
Christian Heimes45f9af32007-11-27 21:50:00 +00002053 >>> import types, os.path, test.test_doctest
Edward Loper0273f5b2004-09-18 20:27:04 +00002054 >>> save_argv = sys.argv
2055 >>> sys.argv = [test.test_doctest.__file__]
2056 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Christian Heimes45f9af32007-11-27 21:50:00 +00002057 ... package=types.ModuleType('__main__'))
Edward Loper0273f5b2004-09-18 20:27:04 +00002058 >>> sys.argv = save_argv
2059
Edward Loper052d0cd2004-09-19 17:19:33 +00002060 By setting `module_relative=False`, os-specific paths may be
2061 used (including absolute paths and paths relative to the
2062 working directory):
Edward Loper0273f5b2004-09-18 20:27:04 +00002063
2064 >>> # Get the absolute path of the test package.
2065 >>> test_doctest_path = os.path.abspath(test.test_doctest.__file__)
2066 >>> test_pkg_path = os.path.split(test_doctest_path)[0]
2067
2068 >>> # Use it to find the absolute path of test_doctest.txt.
2069 >>> test_file = os.path.join(test_pkg_path, 'test_doctest.txt')
2070
Edward Loper052d0cd2004-09-19 17:19:33 +00002071 >>> suite = doctest.DocFileSuite(test_file, module_relative=False)
Edward Loper0273f5b2004-09-18 20:27:04 +00002072 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002073 <unittest.result.TestResult run=1 errors=0 failures=1>
Edward Loper0273f5b2004-09-18 20:27:04 +00002074
Edward Loper052d0cd2004-09-19 17:19:33 +00002075 It is an error to specify `package` when `module_relative=False`:
2076
2077 >>> suite = doctest.DocFileSuite(test_file, module_relative=False,
2078 ... package='test')
2079 Traceback (most recent call last):
2080 ValueError: Package may only be specified for module-relative paths.
2081
Tim Peters19397e52004-08-06 22:02:59 +00002082 You can specify initial global variables:
2083
2084 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2085 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002086 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002087 ... globs={'favorite_color': 'blue'})
2088 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002089 <unittest.result.TestResult run=3 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002090
2091 In this case, we supplied a missing favorite color. You can
2092 provide doctest options:
2093
2094 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2095 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002096 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002097 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
2098 ... globs={'favorite_color': 'blue'})
2099 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002100 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002101
2102 And, you can provide setUp and tearDown functions:
2103
Jim Fultonf54bad42004-08-28 14:57:56 +00002104 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00002105 ... import test.test_doctest
2106 ... test.test_doctest.sillySetup = True
2107
Jim Fultonf54bad42004-08-28 14:57:56 +00002108 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00002109 ... import test.test_doctest
2110 ... del test.test_doctest.sillySetup
2111
2112 Here, we installed a silly variable that the test expects:
2113
2114 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2115 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002116 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002117 ... setUp=setUp, tearDown=tearDown)
2118 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002119 <unittest.result.TestResult run=3 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002120
2121 But the tearDown restores sanity:
2122
2123 >>> import test.test_doctest
2124 >>> test.test_doctest.sillySetup
2125 Traceback (most recent call last):
2126 ...
2127 AttributeError: 'module' object has no attribute 'sillySetup'
2128
Jim Fultonf54bad42004-08-28 14:57:56 +00002129 The setUp and tearDown funtions are passed test objects.
2130 Here, we'll use a setUp function to set the favorite color in
2131 test_doctest.txt:
2132
2133 >>> def setUp(test):
2134 ... test.globs['favorite_color'] = 'blue'
2135
2136 >>> suite = doctest.DocFileSuite('test_doctest.txt', setUp=setUp)
2137 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002138 <unittest.result.TestResult run=1 errors=0 failures=0>
Jim Fultonf54bad42004-08-28 14:57:56 +00002139
2140 Here, we didn't need to use a tearDown function because we
2141 modified the test globals. The test globals are
2142 automatically cleared for us after a test.
Tim Petersdf7a2082004-08-29 00:38:17 +00002143
Fred Drake7c404a42004-12-21 23:46:34 +00002144 Tests in a file run using `DocFileSuite` can also access the
2145 `__file__` global, which is set to the name of the file
2146 containing the tests:
2147
2148 >>> suite = doctest.DocFileSuite('test_doctest3.txt')
2149 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002150 <unittest.result.TestResult run=1 errors=0 failures=0>
Fred Drake7c404a42004-12-21 23:46:34 +00002151
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002152 If the tests contain non-ASCII characters, we have to specify which
2153 encoding the file is encoded with. We do so by using the `encoding`
2154 parameter:
2155
2156 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2157 ... 'test_doctest2.txt',
2158 ... 'test_doctest4.txt',
2159 ... encoding='utf-8')
2160 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002161 <unittest.result.TestResult run=3 errors=0 failures=2>
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002162
Jim Fultonf54bad42004-08-28 14:57:56 +00002163 """
Tim Peters19397e52004-08-06 22:02:59 +00002164
Jim Fulton07a349c2004-08-22 14:10:00 +00002165def test_trailing_space_in_test():
2166 """
Tim Petersa7def722004-08-23 22:13:22 +00002167 Trailing spaces in expected output are significant:
Tim Petersc6cbab02004-08-22 19:43:28 +00002168
Jim Fulton07a349c2004-08-22 14:10:00 +00002169 >>> x, y = 'foo', ''
Guido van Rossum7131f842007-02-09 20:13:25 +00002170 >>> print(x, y)
Jim Fulton07a349c2004-08-22 14:10:00 +00002171 foo \n
2172 """
Tim Peters19397e52004-08-06 22:02:59 +00002173
Jim Fultonf54bad42004-08-28 14:57:56 +00002174
2175def test_unittest_reportflags():
2176 """Default unittest reporting flags can be set to control reporting
2177
2178 Here, we'll set the REPORT_ONLY_FIRST_FAILURE option so we see
2179 only the first failure of each test. First, we'll look at the
2180 output without the flag. The file test_doctest.txt file has two
2181 tests. They both fail if blank lines are disabled:
2182
2183 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2184 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
2185 >>> import unittest
2186 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002187 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002188 Traceback ...
2189 Failed example:
2190 favorite_color
2191 ...
2192 Failed example:
2193 if 1:
2194 ...
2195
2196 Note that we see both failures displayed.
2197
2198 >>> old = doctest.set_unittest_reportflags(
2199 ... doctest.REPORT_ONLY_FIRST_FAILURE)
2200
2201 Now, when we run the test:
2202
2203 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002204 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002205 Traceback ...
2206 Failed example:
2207 favorite_color
2208 Exception raised:
2209 ...
2210 NameError: name 'favorite_color' is not defined
2211 <BLANKLINE>
2212 <BLANKLINE>
Tim Petersdf7a2082004-08-29 00:38:17 +00002213
Jim Fultonf54bad42004-08-28 14:57:56 +00002214 We get only the first failure.
2215
2216 If we give any reporting options when we set up the tests,
2217 however:
2218
2219 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2220 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE | doctest.REPORT_NDIFF)
2221
2222 Then the default eporting options are ignored:
2223
2224 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002225 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002226 Traceback ...
2227 Failed example:
2228 favorite_color
2229 ...
2230 Failed example:
2231 if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00002232 print('a')
2233 print()
2234 print('b')
Jim Fultonf54bad42004-08-28 14:57:56 +00002235 Differences (ndiff with -expected +actual):
2236 a
2237 - <BLANKLINE>
2238 +
2239 b
2240 <BLANKLINE>
2241 <BLANKLINE>
2242
2243
2244 Test runners can restore the formatting flags after they run:
2245
2246 >>> ignored = doctest.set_unittest_reportflags(old)
2247
2248 """
2249
Edward Loper052d0cd2004-09-19 17:19:33 +00002250def test_testfile(): r"""
2251Tests for the `testfile()` function. This function runs all the
2252doctest examples in a given file. In its simple invokation, it is
2253called with the name of a file, which is taken to be relative to the
2254calling module. The return value is (#failures, #tests).
2255
Florent Xicluna59250852010-02-27 14:21:57 +00002256We don't want `-v` in sys.argv for these tests.
2257
2258 >>> save_argv = sys.argv
2259 >>> if '-v' in sys.argv:
2260 ... sys.argv = [arg for arg in save_argv if arg != '-v']
2261
2262
Edward Loper052d0cd2004-09-19 17:19:33 +00002263 >>> doctest.testfile('test_doctest.txt') # doctest: +ELLIPSIS
2264 **********************************************************************
2265 File "...", line 6, in test_doctest.txt
2266 Failed example:
2267 favorite_color
2268 Exception raised:
2269 ...
2270 NameError: name 'favorite_color' is not defined
2271 **********************************************************************
2272 1 items had failures:
2273 1 of 2 in test_doctest.txt
2274 ***Test Failed*** 1 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002275 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002276 >>> doctest.master = None # Reset master.
2277
2278(Note: we'll be clearing doctest.master after each call to
2279`doctest.testfile`, to supress warnings about multiple tests with the
2280same name.)
2281
2282Globals may be specified with the `globs` and `extraglobs` parameters:
2283
2284 >>> globs = {'favorite_color': 'blue'}
2285 >>> doctest.testfile('test_doctest.txt', globs=globs)
Christian Heimes25bb7832008-01-11 16:17:00 +00002286 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002287 >>> doctest.master = None # Reset master.
2288
2289 >>> extraglobs = {'favorite_color': 'red'}
2290 >>> doctest.testfile('test_doctest.txt', globs=globs,
2291 ... extraglobs=extraglobs) # doctest: +ELLIPSIS
2292 **********************************************************************
2293 File "...", line 6, in test_doctest.txt
2294 Failed example:
2295 favorite_color
2296 Expected:
2297 'blue'
2298 Got:
2299 'red'
2300 **********************************************************************
2301 1 items had failures:
2302 1 of 2 in test_doctest.txt
2303 ***Test Failed*** 1 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002304 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002305 >>> doctest.master = None # Reset master.
2306
2307The file may be made relative to a given module or package, using the
2308optional `module_relative` parameter:
2309
2310 >>> doctest.testfile('test_doctest.txt', globs=globs,
2311 ... module_relative='test')
Christian Heimes25bb7832008-01-11 16:17:00 +00002312 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002313 >>> doctest.master = None # Reset master.
2314
2315Verbosity can be increased with the optional `verbose` paremter:
2316
2317 >>> doctest.testfile('test_doctest.txt', globs=globs, verbose=True)
2318 Trying:
2319 favorite_color
2320 Expecting:
2321 'blue'
2322 ok
2323 Trying:
2324 if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00002325 print('a')
2326 print()
2327 print('b')
Edward Loper052d0cd2004-09-19 17:19:33 +00002328 Expecting:
2329 a
2330 <BLANKLINE>
2331 b
2332 ok
2333 1 items passed all tests:
2334 2 tests in test_doctest.txt
2335 2 tests in 1 items.
2336 2 passed and 0 failed.
2337 Test passed.
Christian Heimes25bb7832008-01-11 16:17:00 +00002338 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002339 >>> doctest.master = None # Reset master.
2340
2341The name of the test may be specified with the optional `name`
2342parameter:
2343
2344 >>> doctest.testfile('test_doctest.txt', name='newname')
2345 ... # doctest: +ELLIPSIS
2346 **********************************************************************
2347 File "...", line 6, in newname
2348 ...
Christian Heimes25bb7832008-01-11 16:17:00 +00002349 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002350 >>> doctest.master = None # Reset master.
2351
2352The summary report may be supressed with the optional `report`
2353parameter:
2354
2355 >>> doctest.testfile('test_doctest.txt', report=False)
2356 ... # doctest: +ELLIPSIS
2357 **********************************************************************
2358 File "...", line 6, in test_doctest.txt
2359 Failed example:
2360 favorite_color
2361 Exception raised:
2362 ...
2363 NameError: name 'favorite_color' is not defined
Christian Heimes25bb7832008-01-11 16:17:00 +00002364 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002365 >>> doctest.master = None # Reset master.
2366
2367The optional keyword argument `raise_on_error` can be used to raise an
2368exception on the first error (which may be useful for postmortem
2369debugging):
2370
2371 >>> doctest.testfile('test_doctest.txt', raise_on_error=True)
2372 ... # doctest: +ELLIPSIS
2373 Traceback (most recent call last):
Guido van Rossum6a2a2a02006-08-26 20:37:44 +00002374 doctest.UnexpectedException: ...
Edward Loper052d0cd2004-09-19 17:19:33 +00002375 >>> doctest.master = None # Reset master.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002376
2377If the tests contain non-ASCII characters, the tests might fail, since
2378it's unknown which encoding is used. The encoding can be specified
2379using the optional keyword argument `encoding`:
2380
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002381 >>> doctest.testfile('test_doctest4.txt', encoding='latin-1') # doctest: +ELLIPSIS
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002382 **********************************************************************
2383 File "...", line 7, in test_doctest4.txt
2384 Failed example:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002385 '...'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002386 Expected:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002387 'f\xf6\xf6'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002388 Got:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002389 'f\xc3\xb6\xc3\xb6'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002390 **********************************************************************
2391 ...
2392 **********************************************************************
2393 1 items had failures:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002394 2 of 2 in test_doctest4.txt
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002395 ***Test Failed*** 2 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002396 TestResults(failed=2, attempted=2)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002397 >>> doctest.master = None # Reset master.
2398
2399 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8')
Christian Heimes25bb7832008-01-11 16:17:00 +00002400 TestResults(failed=0, attempted=2)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002401 >>> doctest.master = None # Reset master.
Florent Xicluna59250852010-02-27 14:21:57 +00002402
2403Test the verbose output:
2404
2405 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8', verbose=True)
2406 Trying:
2407 'föö'
2408 Expecting:
2409 'f\xf6\xf6'
2410 ok
2411 Trying:
2412 'bąr'
2413 Expecting:
2414 'b\u0105r'
2415 ok
2416 1 items passed all tests:
2417 2 tests in test_doctest4.txt
2418 2 tests in 1 items.
2419 2 passed and 0 failed.
2420 Test passed.
2421 TestResults(failed=0, attempted=2)
2422 >>> doctest.master = None # Reset master.
2423 >>> sys.argv = save_argv
Edward Loper052d0cd2004-09-19 17:19:33 +00002424"""
2425
R. David Murray58641de2009-06-12 15:33:19 +00002426def test_testmod(): r"""
2427Tests for the testmod function. More might be useful, but for now we're just
2428testing the case raised by Issue 6195, where trying to doctest a C module would
2429fail with a UnicodeDecodeError because doctest tried to read the "source" lines
2430out of the binary module.
2431
2432 >>> import unicodedata
Florent Xicluna59250852010-02-27 14:21:57 +00002433 >>> doctest.testmod(unicodedata, verbose=False)
R. David Murray58641de2009-06-12 15:33:19 +00002434 TestResults(failed=0, attempted=0)
2435"""
2436
Victor Stinner9d396392010-10-16 21:54:59 +00002437try:
2438 os.fsencode("foo-bär@baz.py")
2439except UnicodeEncodeError:
2440 # Skip the test: the filesystem encoding is unable to encode the filename
2441 pass
2442else:
2443 def test_unicode(): """
2444Check doctest with a non-ascii filename:
2445
2446 >>> doc = '''
2447 ... >>> raise Exception('clé')
2448 ... '''
2449 ...
2450 >>> parser = doctest.DocTestParser()
2451 >>> test = parser.get_doctest(doc, {}, "foo-bär@baz", "foo-bär@baz.py", 0)
2452 >>> test
2453 <DocTest foo-bär@baz from foo-bär@baz.py:0 (1 example)>
2454 >>> runner = doctest.DocTestRunner(verbose=False)
2455 >>> runner.run(test) # doctest: +ELLIPSIS
2456 **********************************************************************
2457 File "foo-bär@baz.py", line 2, in foo-bär@baz
2458 Failed example:
2459 raise Exception('clé')
2460 Exception raised:
2461 Traceback (most recent call last):
2462 File ...
2463 compileflags, 1), test.globs)
2464 File "<doctest foo-bär@baz[0]>", line 1, in <module>
2465 raise Exception('clé')
2466 Exception: clé
2467 TestResults(failed=1, attempted=1)
2468 """
2469
Tim Peters8485b562004-08-04 18:46:34 +00002470######################################################################
2471## Main
2472######################################################################
2473
2474def test_main():
2475 # Check the doctest cases in doctest itself:
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002476 support.run_doctest(doctest, verbosity=True)
Tim Peters8485b562004-08-04 18:46:34 +00002477 # Check the doctest cases defined here:
2478 from test import test_doctest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002479 support.run_doctest(test_doctest, verbosity=True)
Tim Peters8485b562004-08-04 18:46:34 +00002480
Victor Stinner45df8202010-04-28 22:31:17 +00002481import sys, re, io
2482
Tim Peters8485b562004-08-04 18:46:34 +00002483def test_coverage(coverdir):
Victor Stinner45df8202010-04-28 22:31:17 +00002484 trace = support.import_module('trace')
Tim Peters8485b562004-08-04 18:46:34 +00002485 tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
2486 trace=0, count=1)
Guido van Rossume7ba4952007-06-06 23:52:48 +00002487 tracer.run('test_main()')
Tim Peters8485b562004-08-04 18:46:34 +00002488 r = tracer.results()
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002489 print('Writing coverage results...')
Tim Peters8485b562004-08-04 18:46:34 +00002490 r.write_results(show_missing=True, summary=True,
2491 coverdir=coverdir)
2492
2493if __name__ == '__main__':
2494 if '-c' in sys.argv:
2495 test_coverage('/tmp/doctest.cover')
2496 else:
2497 test_main()