blob: 17842c9a08e80a5c96787def277a97d3230fe492 [file] [log] [blame]
Tim Peters8485b562004-08-04 18:46:34 +00001"""
2Test script for doctest.
3"""
4
Benjamin Petersonee8712c2008-05-20 21:35:26 +00005from test import support
Tim Peters8485b562004-08-04 18:46:34 +00006import doctest
Tim Petersa7def722004-08-23 22:13:22 +00007import warnings
Tim Peters8485b562004-08-04 18:46:34 +00008
Nick Coghlanf088e5e2008-12-14 11:50:48 +00009# NOTE: There are some additional tests relating to interaction with
10# zipimport in the test_zipimport_support test module.
11
Tim Peters8485b562004-08-04 18:46:34 +000012######################################################################
13## Sample Objects (used by test cases)
14######################################################################
15
16def sample_func(v):
17 """
Tim Peters19397e52004-08-06 22:02:59 +000018 Blah blah
19
Guido van Rossum7131f842007-02-09 20:13:25 +000020 >>> print(sample_func(22))
Tim Peters8485b562004-08-04 18:46:34 +000021 44
Tim Peters19397e52004-08-06 22:02:59 +000022
23 Yee ha!
Tim Peters8485b562004-08-04 18:46:34 +000024 """
25 return v+v
26
27class SampleClass:
28 """
Guido van Rossum7131f842007-02-09 20:13:25 +000029 >>> print(1)
Tim Peters8485b562004-08-04 18:46:34 +000030 1
Edward Loper4ae900f2004-09-21 03:20:34 +000031
32 >>> # comments get ignored. so are empty PS1 and PS2 prompts:
33 >>>
34 ...
35
36 Multiline example:
37 >>> sc = SampleClass(3)
38 >>> for i in range(10):
39 ... sc = sc.double()
Guido van Rossum805365e2007-05-07 22:24:25 +000040 ... print(' ', sc.get(), sep='', end='')
41 6 12 24 48 96 192 384 768 1536 3072
Tim Peters8485b562004-08-04 18:46:34 +000042 """
43 def __init__(self, val):
44 """
Guido van Rossum7131f842007-02-09 20:13:25 +000045 >>> print(SampleClass(12).get())
Tim Peters8485b562004-08-04 18:46:34 +000046 12
47 """
48 self.val = val
49
50 def double(self):
51 """
Guido van Rossum7131f842007-02-09 20:13:25 +000052 >>> print(SampleClass(12).double().get())
Tim Peters8485b562004-08-04 18:46:34 +000053 24
54 """
55 return SampleClass(self.val + self.val)
56
57 def get(self):
58 """
Guido van Rossum7131f842007-02-09 20:13:25 +000059 >>> print(SampleClass(-5).get())
Tim Peters8485b562004-08-04 18:46:34 +000060 -5
61 """
62 return self.val
63
64 def a_staticmethod(v):
65 """
Guido van Rossum7131f842007-02-09 20:13:25 +000066 >>> print(SampleClass.a_staticmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +000067 11
68 """
69 return v+1
70 a_staticmethod = staticmethod(a_staticmethod)
71
72 def a_classmethod(cls, v):
73 """
Guido van Rossum7131f842007-02-09 20:13:25 +000074 >>> print(SampleClass.a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +000075 12
Guido van Rossum7131f842007-02-09 20:13:25 +000076 >>> print(SampleClass(0).a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +000077 12
78 """
79 return v+2
80 a_classmethod = classmethod(a_classmethod)
81
82 a_property = property(get, doc="""
Guido van Rossum7131f842007-02-09 20:13:25 +000083 >>> print(SampleClass(22).a_property)
Tim Peters8485b562004-08-04 18:46:34 +000084 22
85 """)
86
87 class NestedClass:
88 """
89 >>> x = SampleClass.NestedClass(5)
90 >>> y = x.square()
Guido van Rossum7131f842007-02-09 20:13:25 +000091 >>> print(y.get())
Tim Peters8485b562004-08-04 18:46:34 +000092 25
93 """
94 def __init__(self, val=0):
95 """
Guido van Rossum7131f842007-02-09 20:13:25 +000096 >>> print(SampleClass.NestedClass().get())
Tim Peters8485b562004-08-04 18:46:34 +000097 0
98 """
99 self.val = val
100 def square(self):
101 return SampleClass.NestedClass(self.val*self.val)
102 def get(self):
103 return self.val
104
105class SampleNewStyleClass(object):
106 r"""
Guido van Rossum7131f842007-02-09 20:13:25 +0000107 >>> print('1\n2\n3')
Tim Peters8485b562004-08-04 18:46:34 +0000108 1
109 2
110 3
111 """
112 def __init__(self, val):
113 """
Guido van Rossum7131f842007-02-09 20:13:25 +0000114 >>> print(SampleNewStyleClass(12).get())
Tim Peters8485b562004-08-04 18:46:34 +0000115 12
116 """
117 self.val = val
118
119 def double(self):
120 """
Guido van Rossum7131f842007-02-09 20:13:25 +0000121 >>> print(SampleNewStyleClass(12).double().get())
Tim Peters8485b562004-08-04 18:46:34 +0000122 24
123 """
124 return SampleNewStyleClass(self.val + self.val)
125
126 def get(self):
127 """
Guido van Rossum7131f842007-02-09 20:13:25 +0000128 >>> print(SampleNewStyleClass(-5).get())
Tim Peters8485b562004-08-04 18:46:34 +0000129 -5
130 """
131 return self.val
132
133######################################################################
Edward Loper2de91ba2004-08-27 02:07:46 +0000134## Fake stdin (for testing interactive debugging)
135######################################################################
136
137class _FakeInput:
138 """
139 A fake input stream for pdb's interactive debugger. Whenever a
140 line is read, print it (to simulate the user typing it), and then
141 return it. The set of lines to return is specified in the
142 constructor; they should not have trailing newlines.
143 """
144 def __init__(self, lines):
145 self.lines = lines
146
147 def readline(self):
148 line = self.lines.pop(0)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000149 print(line)
Edward Loper2de91ba2004-08-27 02:07:46 +0000150 return line+'\n'
151
152######################################################################
Tim Peters8485b562004-08-04 18:46:34 +0000153## Test Cases
154######################################################################
155
156def test_Example(): r"""
157Unit tests for the `Example` class.
158
Edward Lopera6b68322004-08-26 00:05:43 +0000159Example is a simple container class that holds:
160 - `source`: A source string.
161 - `want`: An expected output string.
162 - `exc_msg`: An expected exception message string (or None if no
163 exception is expected).
164 - `lineno`: A line number (within the docstring).
165 - `indent`: The example's indentation in the input string.
166 - `options`: An option dictionary, mapping option flags to True or
167 False.
Tim Peters8485b562004-08-04 18:46:34 +0000168
Edward Lopera6b68322004-08-26 00:05:43 +0000169These attributes are set by the constructor. `source` and `want` are
170required; the other attributes all have default values:
Tim Peters8485b562004-08-04 18:46:34 +0000171
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000172 >>> example = doctest.Example('print(1)', '1\n')
Edward Lopera6b68322004-08-26 00:05:43 +0000173 >>> (example.source, example.want, example.exc_msg,
174 ... example.lineno, example.indent, example.options)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000175 ('print(1)\n', '1\n', None, 0, 0, {})
Edward Lopera6b68322004-08-26 00:05:43 +0000176
177The first three attributes (`source`, `want`, and `exc_msg`) may be
178specified positionally; the remaining arguments should be specified as
179keyword arguments:
180
181 >>> exc_msg = 'IndexError: pop from an empty list'
182 >>> example = doctest.Example('[].pop()', '', exc_msg,
183 ... lineno=5, indent=4,
184 ... options={doctest.ELLIPSIS: True})
185 >>> (example.source, example.want, example.exc_msg,
186 ... example.lineno, example.indent, example.options)
187 ('[].pop()\n', '', 'IndexError: pop from an empty list\n', 5, 4, {8: True})
188
189The constructor normalizes the `source` string to end in a newline:
Tim Peters8485b562004-08-04 18:46:34 +0000190
Tim Petersbb431472004-08-09 03:51:46 +0000191 Source spans a single line: no terminating newline.
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000192 >>> e = doctest.Example('print(1)', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000193 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000194 ('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000195
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000196 >>> e = doctest.Example('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000197 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000198 ('print(1)\n', '1\n')
Tim Peters8485b562004-08-04 18:46:34 +0000199
Tim Petersbb431472004-08-09 03:51:46 +0000200 Source spans multiple lines: require terminating newline.
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000201 >>> e = doctest.Example('print(1);\nprint(2)\n', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000202 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000203 ('print(1);\nprint(2)\n', '1\n2\n')
Tim Peters8485b562004-08-04 18:46:34 +0000204
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000205 >>> e = doctest.Example('print(1);\nprint(2)', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000206 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000207 ('print(1);\nprint(2)\n', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000208
Edward Lopera6b68322004-08-26 00:05:43 +0000209 Empty source string (which should never appear in real examples)
210 >>> e = doctest.Example('', '')
211 >>> e.source, e.want
212 ('\n', '')
Tim Peters8485b562004-08-04 18:46:34 +0000213
Edward Lopera6b68322004-08-26 00:05:43 +0000214The constructor normalizes the `want` string to end in a newline,
215unless it's the empty string:
216
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000217 >>> e = doctest.Example('print(1)', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000218 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000219 ('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000220
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000221 >>> e = doctest.Example('print(1)', '1')
Tim Petersbb431472004-08-09 03:51:46 +0000222 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000223 ('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000224
Edward Lopera6b68322004-08-26 00:05:43 +0000225 >>> e = doctest.Example('print', '')
Tim Petersbb431472004-08-09 03:51:46 +0000226 >>> e.source, e.want
227 ('print\n', '')
Edward Lopera6b68322004-08-26 00:05:43 +0000228
229The constructor normalizes the `exc_msg` string to end in a newline,
230unless it's `None`:
231
232 Message spans one line
233 >>> exc_msg = 'IndexError: pop from an empty list'
234 >>> e = doctest.Example('[].pop()', '', exc_msg)
235 >>> e.exc_msg
236 'IndexError: pop from an empty list\n'
237
238 >>> exc_msg = 'IndexError: pop from an empty list\n'
239 >>> e = doctest.Example('[].pop()', '', exc_msg)
240 >>> e.exc_msg
241 'IndexError: pop from an empty list\n'
242
243 Message spans multiple lines
244 >>> exc_msg = 'ValueError: 1\n 2'
245 >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
246 >>> e.exc_msg
247 'ValueError: 1\n 2\n'
248
249 >>> exc_msg = 'ValueError: 1\n 2\n'
250 >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
251 >>> e.exc_msg
252 'ValueError: 1\n 2\n'
253
254 Empty (but non-None) exception message (which should never appear
255 in real examples)
256 >>> exc_msg = ''
257 >>> e = doctest.Example('raise X()', '', exc_msg)
258 >>> e.exc_msg
259 '\n'
Tim Peters8485b562004-08-04 18:46:34 +0000260"""
261
262def test_DocTest(): r"""
263Unit tests for the `DocTest` class.
264
265DocTest is a collection of examples, extracted from a docstring, along
266with information about where the docstring comes from (a name,
267filename, and line number). The docstring is parsed by the `DocTest`
268constructor:
269
270 >>> docstring = '''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000271 ... >>> print(12)
Tim Peters8485b562004-08-04 18:46:34 +0000272 ... 12
273 ...
274 ... Non-example text.
275 ...
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000276 ... >>> print('another\example')
Tim Peters8485b562004-08-04 18:46:34 +0000277 ... another
278 ... example
279 ... '''
280 >>> globs = {} # globals to run the test in.
Edward Lopera1ef6112004-08-09 16:14:41 +0000281 >>> parser = doctest.DocTestParser()
282 >>> test = parser.get_doctest(docstring, globs, 'some_test',
283 ... 'some_file', 20)
Guido van Rossum7131f842007-02-09 20:13:25 +0000284 >>> print(test)
Tim Peters8485b562004-08-04 18:46:34 +0000285 <DocTest some_test from some_file:20 (2 examples)>
286 >>> len(test.examples)
287 2
288 >>> e1, e2 = test.examples
289 >>> (e1.source, e1.want, e1.lineno)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000290 ('print(12)\n', '12\n', 1)
Tim Peters8485b562004-08-04 18:46:34 +0000291 >>> (e2.source, e2.want, e2.lineno)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000292 ("print('another\\example')\n", 'another\nexample\n', 6)
Tim Peters8485b562004-08-04 18:46:34 +0000293
294Source information (name, filename, and line number) is available as
295attributes on the doctest object:
296
297 >>> (test.name, test.filename, test.lineno)
298 ('some_test', 'some_file', 20)
299
300The line number of an example within its containing file is found by
301adding the line number of the example and the line number of its
302containing test:
303
304 >>> test.lineno + e1.lineno
305 21
306 >>> test.lineno + e2.lineno
307 26
308
309If the docstring contains inconsistant leading whitespace in the
310expected output of an example, then `DocTest` will raise a ValueError:
311
312 >>> docstring = r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000313 ... >>> print('bad\nindentation')
Tim Peters8485b562004-08-04 18:46:34 +0000314 ... bad
315 ... indentation
316 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000317 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000318 Traceback (most recent call last):
Edward Loper00f8da72004-08-26 18:05:07 +0000319 ValueError: line 4 of the docstring for some_test has inconsistent leading whitespace: 'indentation'
Tim Peters8485b562004-08-04 18:46:34 +0000320
321If the docstring contains inconsistent leading whitespace on
322continuation lines, then `DocTest` will raise a ValueError:
323
324 >>> docstring = r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000325 ... >>> print(('bad indentation',
326 ... ... 2))
Tim Peters8485b562004-08-04 18:46:34 +0000327 ... ('bad', 'indentation')
328 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000329 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000330 Traceback (most recent call last):
Guido van Rossume0192e52007-02-09 23:39:59 +0000331 ValueError: line 2 of the docstring for some_test has inconsistent leading whitespace: '... 2))'
Tim Peters8485b562004-08-04 18:46:34 +0000332
333If there's no blank space after a PS1 prompt ('>>>'), then `DocTest`
334will raise a ValueError:
335
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000336 >>> docstring = '>>>print(1)\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000337 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000338 Traceback (most recent call last):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000339 ValueError: line 1 of the docstring for some_test lacks blank after >>>: '>>>print(1)'
Edward Loper7c748462004-08-09 02:06:06 +0000340
341If there's no blank space after a PS2 prompt ('...'), then `DocTest`
342will raise a ValueError:
343
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000344 >>> docstring = '>>> if 1:\n...print(1)\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000345 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Edward Loper7c748462004-08-09 02:06:06 +0000346 Traceback (most recent call last):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000347 ValueError: line 2 of the docstring for some_test lacks blank after ...: '...print(1)'
Edward Loper7c748462004-08-09 02:06:06 +0000348
Tim Peters8485b562004-08-04 18:46:34 +0000349"""
350
Tim Peters8485b562004-08-04 18:46:34 +0000351def test_DocTestFinder(): r"""
352Unit tests for the `DocTestFinder` class.
353
354DocTestFinder is used to extract DocTests from an object's docstring
355and the docstrings of its contained objects. It can be used with
356modules, functions, classes, methods, staticmethods, classmethods, and
357properties.
358
359Finding Tests in Functions
360~~~~~~~~~~~~~~~~~~~~~~~~~~
361For a function whose docstring contains examples, DocTestFinder.find()
362will return a single test (for that function's docstring):
363
Tim Peters8485b562004-08-04 18:46:34 +0000364 >>> finder = doctest.DocTestFinder()
Jim Fulton07a349c2004-08-22 14:10:00 +0000365
366We'll simulate a __file__ attr that ends in pyc:
367
368 >>> import test.test_doctest
369 >>> old = test.test_doctest.__file__
370 >>> test.test_doctest.__file__ = 'test_doctest.pyc'
371
Tim Peters8485b562004-08-04 18:46:34 +0000372 >>> tests = finder.find(sample_func)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000373
Guido van Rossum7131f842007-02-09 20:13:25 +0000374 >>> print(tests) # doctest: +ELLIPSIS
Nick Coghlanf088e5e2008-12-14 11:50:48 +0000375 [<DocTest sample_func from ...:16 (1 example)>]
Edward Loper8e4a34b2004-08-12 02:34:27 +0000376
Tim Peters4de7c5c2004-08-23 22:38:05 +0000377The exact name depends on how test_doctest was invoked, so allow for
378leading path components.
379
380 >>> tests[0].filename # doctest: +ELLIPSIS
381 '...test_doctest.py'
Jim Fulton07a349c2004-08-22 14:10:00 +0000382
383 >>> test.test_doctest.__file__ = old
Tim Petersc6cbab02004-08-22 19:43:28 +0000384
Jim Fulton07a349c2004-08-22 14:10:00 +0000385
Tim Peters8485b562004-08-04 18:46:34 +0000386 >>> e = tests[0].examples[0]
Tim Petersbb431472004-08-09 03:51:46 +0000387 >>> (e.source, e.want, e.lineno)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000388 ('print(sample_func(22))\n', '44\n', 3)
Tim Peters8485b562004-08-04 18:46:34 +0000389
Edward Loper32ddbf72004-09-13 05:47:24 +0000390By default, tests are created for objects with no docstring:
Tim Peters8485b562004-08-04 18:46:34 +0000391
392 >>> def no_docstring(v):
393 ... pass
Tim Peters958cc892004-09-13 14:53:28 +0000394 >>> finder.find(no_docstring)
395 []
Edward Loper32ddbf72004-09-13 05:47:24 +0000396
397However, the optional argument `exclude_empty` to the DocTestFinder
398constructor can be used to exclude tests for objects with empty
399docstrings:
400
401 >>> def no_docstring(v):
402 ... pass
403 >>> excl_empty_finder = doctest.DocTestFinder(exclude_empty=True)
404 >>> excl_empty_finder.find(no_docstring)
Tim Peters8485b562004-08-04 18:46:34 +0000405 []
406
407If the function has a docstring with no examples, then a test with no
408examples is returned. (This lets `DocTestRunner` collect statistics
409about which functions have no tests -- but is that useful? And should
410an empty test also be created when there's no docstring?)
411
412 >>> def no_examples(v):
413 ... ''' no doctest examples '''
Tim Peters17b56372004-09-11 17:33:27 +0000414 >>> finder.find(no_examples) # doctest: +ELLIPSIS
415 [<DocTest no_examples from ...:1 (no examples)>]
Tim Peters8485b562004-08-04 18:46:34 +0000416
417Finding Tests in Classes
418~~~~~~~~~~~~~~~~~~~~~~~~
419For a class, DocTestFinder will create a test for the class's
420docstring, and will recursively explore its contents, including
421methods, classmethods, staticmethods, properties, and nested classes.
422
423 >>> finder = doctest.DocTestFinder()
424 >>> tests = finder.find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000425 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000426 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000427 3 SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000428 3 SampleClass.NestedClass
429 1 SampleClass.NestedClass.__init__
430 1 SampleClass.__init__
431 2 SampleClass.a_classmethod
432 1 SampleClass.a_property
433 1 SampleClass.a_staticmethod
434 1 SampleClass.double
435 1 SampleClass.get
436
437New-style classes are also supported:
438
439 >>> tests = finder.find(SampleNewStyleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000440 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000441 ... print('%2s %s' % (len(t.examples), t.name))
Tim Peters8485b562004-08-04 18:46:34 +0000442 1 SampleNewStyleClass
443 1 SampleNewStyleClass.__init__
444 1 SampleNewStyleClass.double
445 1 SampleNewStyleClass.get
446
447Finding Tests in Modules
448~~~~~~~~~~~~~~~~~~~~~~~~
449For a module, DocTestFinder will create a test for the class's
450docstring, and will recursively explore its contents, including
451functions, classes, and the `__test__` dictionary, if it exists:
452
453 >>> # A module
Christian Heimes45f9af32007-11-27 21:50:00 +0000454 >>> import types
455 >>> m = types.ModuleType('some_module')
Tim Peters8485b562004-08-04 18:46:34 +0000456 >>> def triple(val):
457 ... '''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000458 ... >>> print(triple(11))
Tim Peters8485b562004-08-04 18:46:34 +0000459 ... 33
460 ... '''
461 ... return val*3
462 >>> m.__dict__.update({
463 ... 'sample_func': sample_func,
464 ... 'SampleClass': SampleClass,
465 ... '__doc__': '''
466 ... Module docstring.
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000467 ... >>> print('module')
Tim Peters8485b562004-08-04 18:46:34 +0000468 ... module
469 ... ''',
470 ... '__test__': {
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000471 ... 'd': '>>> print(6)\n6\n>>> print(7)\n7\n',
Tim Peters8485b562004-08-04 18:46:34 +0000472 ... 'c': triple}})
473
474 >>> finder = doctest.DocTestFinder()
475 >>> # Use module=test.test_doctest, to prevent doctest from
476 >>> # ignoring the objects since they weren't defined in m.
477 >>> import test.test_doctest
478 >>> tests = finder.find(m, module=test.test_doctest)
Tim Peters8485b562004-08-04 18:46:34 +0000479 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000480 ... print('%2s %s' % (len(t.examples), t.name))
Tim Peters8485b562004-08-04 18:46:34 +0000481 1 some_module
Edward Loper4ae900f2004-09-21 03:20:34 +0000482 3 some_module.SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000483 3 some_module.SampleClass.NestedClass
484 1 some_module.SampleClass.NestedClass.__init__
485 1 some_module.SampleClass.__init__
486 2 some_module.SampleClass.a_classmethod
487 1 some_module.SampleClass.a_property
488 1 some_module.SampleClass.a_staticmethod
489 1 some_module.SampleClass.double
490 1 some_module.SampleClass.get
Tim Petersc5684782004-09-13 01:07:12 +0000491 1 some_module.__test__.c
492 2 some_module.__test__.d
Tim Peters8485b562004-08-04 18:46:34 +0000493 1 some_module.sample_func
494
495Duplicate Removal
496~~~~~~~~~~~~~~~~~
497If a single object is listed twice (under different names), then tests
498will only be generated for it once:
499
Tim Petersf3f57472004-08-08 06:11:48 +0000500 >>> from test import doctest_aliases
Benjamin Peterson78565b22009-06-28 19:19:51 +0000501 >>> assert doctest_aliases.TwoNames.f
502 >>> assert doctest_aliases.TwoNames.g
Edward Loper32ddbf72004-09-13 05:47:24 +0000503 >>> tests = excl_empty_finder.find(doctest_aliases)
Guido van Rossum7131f842007-02-09 20:13:25 +0000504 >>> print(len(tests))
Tim Peters8485b562004-08-04 18:46:34 +0000505 2
Guido van Rossum7131f842007-02-09 20:13:25 +0000506 >>> print(tests[0].name)
Tim Petersf3f57472004-08-08 06:11:48 +0000507 test.doctest_aliases.TwoNames
508
509 TwoNames.f and TwoNames.g are bound to the same object.
510 We can't guess which will be found in doctest's traversal of
511 TwoNames.__dict__ first, so we have to allow for either.
512
513 >>> tests[1].name.split('.')[-1] in ['f', 'g']
Tim Peters8485b562004-08-04 18:46:34 +0000514 True
515
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000516Empty Tests
517~~~~~~~~~~~
518By default, an object with no doctests doesn't create any tests:
Tim Peters8485b562004-08-04 18:46:34 +0000519
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000520 >>> tests = doctest.DocTestFinder().find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000521 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000522 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000523 3 SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000524 3 SampleClass.NestedClass
525 1 SampleClass.NestedClass.__init__
Tim Peters958cc892004-09-13 14:53:28 +0000526 1 SampleClass.__init__
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000527 2 SampleClass.a_classmethod
528 1 SampleClass.a_property
529 1 SampleClass.a_staticmethod
Tim Peters958cc892004-09-13 14:53:28 +0000530 1 SampleClass.double
531 1 SampleClass.get
532
533By default, that excluded objects with no doctests. exclude_empty=False
534tells it to include (empty) tests for objects with no doctests. This feature
535is really to support backward compatibility in what doctest.master.summarize()
536displays.
537
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000538 >>> tests = doctest.DocTestFinder(exclude_empty=False).find(SampleClass)
Tim Peters958cc892004-09-13 14:53:28 +0000539 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000540 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000541 3 SampleClass
Tim Peters958cc892004-09-13 14:53:28 +0000542 3 SampleClass.NestedClass
543 1 SampleClass.NestedClass.__init__
Edward Loper32ddbf72004-09-13 05:47:24 +0000544 0 SampleClass.NestedClass.get
545 0 SampleClass.NestedClass.square
Tim Peters8485b562004-08-04 18:46:34 +0000546 1 SampleClass.__init__
Tim Peters8485b562004-08-04 18:46:34 +0000547 2 SampleClass.a_classmethod
548 1 SampleClass.a_property
549 1 SampleClass.a_staticmethod
550 1 SampleClass.double
551 1 SampleClass.get
552
Tim Peters8485b562004-08-04 18:46:34 +0000553Turning off Recursion
554~~~~~~~~~~~~~~~~~~~~~
555DocTestFinder can be told not to look for tests in contained objects
556using the `recurse` flag:
557
558 >>> tests = doctest.DocTestFinder(recurse=False).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000559 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000560 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000561 3 SampleClass
Edward Loperb51b2342004-08-17 16:37:12 +0000562
563Line numbers
564~~~~~~~~~~~~
565DocTestFinder finds the line number of each example:
566
567 >>> def f(x):
568 ... '''
569 ... >>> x = 12
570 ...
571 ... some text
572 ...
573 ... >>> # examples are not created for comments & bare prompts.
574 ... >>>
575 ... ...
576 ...
577 ... >>> for x in range(10):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000578 ... ... print(x, end=' ')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000579 ... 0 1 2 3 4 5 6 7 8 9
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000580 ... >>> x//2
581 ... 6
Edward Loperb51b2342004-08-17 16:37:12 +0000582 ... '''
583 >>> test = doctest.DocTestFinder().find(f)[0]
584 >>> [e.lineno for e in test.examples]
585 [1, 9, 12]
Tim Peters8485b562004-08-04 18:46:34 +0000586"""
587
Edward Loper00f8da72004-08-26 18:05:07 +0000588def test_DocTestParser(): r"""
589Unit tests for the `DocTestParser` class.
590
591DocTestParser is used to parse docstrings containing doctest examples.
592
593The `parse` method divides a docstring into examples and intervening
594text:
595
596 >>> s = '''
597 ... >>> x, y = 2, 3 # no output expected
598 ... >>> if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000599 ... ... print(x)
600 ... ... print(y)
Edward Loper00f8da72004-08-26 18:05:07 +0000601 ... 2
602 ... 3
603 ...
604 ... Some text.
605 ... >>> x+y
606 ... 5
607 ... '''
608 >>> parser = doctest.DocTestParser()
609 >>> for piece in parser.parse(s):
610 ... if isinstance(piece, doctest.Example):
Guido van Rossum7131f842007-02-09 20:13:25 +0000611 ... print('Example:', (piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000612 ... else:
Guido van Rossum7131f842007-02-09 20:13:25 +0000613 ... print(' Text:', repr(piece))
Edward Loper00f8da72004-08-26 18:05:07 +0000614 Text: '\n'
615 Example: ('x, y = 2, 3 # no output expected\n', '', 1)
616 Text: ''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000617 Example: ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000618 Text: '\nSome text.\n'
619 Example: ('x+y\n', '5\n', 9)
620 Text: ''
621
622The `get_examples` method returns just the examples:
623
624 >>> for piece in parser.get_examples(s):
Guido van Rossum7131f842007-02-09 20:13:25 +0000625 ... print((piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000626 ('x, y = 2, 3 # no output expected\n', '', 1)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000627 ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000628 ('x+y\n', '5\n', 9)
629
630The `get_doctest` method creates a Test from the examples, along with the
631given arguments:
632
633 >>> test = parser.get_doctest(s, {}, 'name', 'filename', lineno=5)
634 >>> (test.name, test.filename, test.lineno)
635 ('name', 'filename', 5)
636 >>> for piece in test.examples:
Guido van Rossum7131f842007-02-09 20:13:25 +0000637 ... print((piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000638 ('x, y = 2, 3 # no output expected\n', '', 1)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000639 ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000640 ('x+y\n', '5\n', 9)
641"""
642
Tim Peters8485b562004-08-04 18:46:34 +0000643class test_DocTestRunner:
644 def basics(): r"""
645Unit tests for the `DocTestRunner` class.
646
647DocTestRunner is used to run DocTest test cases, and to accumulate
648statistics. Here's a simple DocTest case we can use:
649
650 >>> def f(x):
651 ... '''
652 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000653 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000654 ... 12
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000655 ... >>> x//2
656 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000657 ... '''
658 >>> test = doctest.DocTestFinder().find(f)[0]
659
660The main DocTestRunner interface is the `run` method, which runs a
661given DocTest case in a given namespace (globs). It returns a tuple
662`(f,t)`, where `f` is the number of failed tests and `t` is the number
663of tried tests.
664
665 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000666 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000667
668If any example produces incorrect output, then the test runner reports
669the failure and proceeds to the next example:
670
671 >>> def f(x):
672 ... '''
673 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000674 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000675 ... 14
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000676 ... >>> x//2
677 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000678 ... '''
679 >>> test = doctest.DocTestFinder().find(f)[0]
680 >>> doctest.DocTestRunner(verbose=True).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000681 ... # doctest: +ELLIPSIS
Edward Loperaacf0832004-08-26 01:19:50 +0000682 Trying:
683 x = 12
684 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000685 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000686 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000687 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000688 Expecting:
689 14
Tim Peters8485b562004-08-04 18:46:34 +0000690 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000691 File ..., line 4, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000692 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000693 print(x)
Jim Fulton07a349c2004-08-22 14:10:00 +0000694 Expected:
695 14
696 Got:
697 12
Edward Loperaacf0832004-08-26 01:19:50 +0000698 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000699 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000700 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000701 6
Tim Peters8485b562004-08-04 18:46:34 +0000702 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000703 TestResults(failed=1, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000704"""
705 def verbose_flag(): r"""
706The `verbose` flag makes the test runner generate more detailed
707output:
708
709 >>> def f(x):
710 ... '''
711 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000712 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000713 ... 12
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000714 ... >>> x//2
715 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000716 ... '''
717 >>> test = doctest.DocTestFinder().find(f)[0]
718
719 >>> doctest.DocTestRunner(verbose=True).run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000720 Trying:
721 x = 12
722 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000723 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000724 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000725 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000726 Expecting:
727 12
Tim Peters8485b562004-08-04 18:46:34 +0000728 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000729 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000730 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000731 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000732 6
Tim Peters8485b562004-08-04 18:46:34 +0000733 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000734 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000735
736If the `verbose` flag is unspecified, then the output will be verbose
737iff `-v` appears in sys.argv:
738
739 >>> # Save the real sys.argv list.
740 >>> old_argv = sys.argv
741
742 >>> # If -v does not appear in sys.argv, then output isn't verbose.
743 >>> sys.argv = ['test']
744 >>> doctest.DocTestRunner().run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000745 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000746
747 >>> # If -v does appear in sys.argv, then output is verbose.
748 >>> sys.argv = ['test', '-v']
749 >>> doctest.DocTestRunner().run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000750 Trying:
751 x = 12
752 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000753 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000754 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000755 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000756 Expecting:
757 12
Tim Peters8485b562004-08-04 18:46:34 +0000758 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000759 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000760 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000761 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000762 6
Tim Peters8485b562004-08-04 18:46:34 +0000763 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000764 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000765
766 >>> # Restore sys.argv
767 >>> sys.argv = old_argv
768
769In the remaining examples, the test runner's verbosity will be
770explicitly set, to ensure that the test behavior is consistent.
771 """
772 def exceptions(): r"""
773Tests of `DocTestRunner`'s exception handling.
774
775An expected exception is specified with a traceback message. The
776lines between the first line and the type/value may be omitted or
777replaced with any other string:
778
779 >>> def f(x):
780 ... '''
781 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000782 ... >>> print(x//0)
Tim Peters8485b562004-08-04 18:46:34 +0000783 ... Traceback (most recent call last):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000784 ... ZeroDivisionError: integer division or modulo by zero
Tim Peters8485b562004-08-04 18:46:34 +0000785 ... '''
786 >>> test = doctest.DocTestFinder().find(f)[0]
787 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000788 TestResults(failed=0, attempted=2)
Tim Peters8485b562004-08-04 18:46:34 +0000789
Edward Loper19b19582004-08-25 23:07:03 +0000790An example may not generate output before it raises an exception; if
791it does, then the traceback message will not be recognized as
792signaling an expected exception, so the example will be reported as an
793unexpected exception:
Tim Peters8485b562004-08-04 18:46:34 +0000794
795 >>> def f(x):
796 ... '''
797 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000798 ... >>> print('pre-exception output', x//0)
Tim Peters8485b562004-08-04 18:46:34 +0000799 ... pre-exception output
800 ... Traceback (most recent call last):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000801 ... ZeroDivisionError: integer division or modulo by zero
Tim Peters8485b562004-08-04 18:46:34 +0000802 ... '''
803 >>> test = doctest.DocTestFinder().find(f)[0]
804 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper19b19582004-08-25 23:07:03 +0000805 ... # doctest: +ELLIPSIS
806 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000807 File ..., line 4, in f
Edward Loper19b19582004-08-25 23:07:03 +0000808 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000809 print('pre-exception output', x//0)
Edward Loper19b19582004-08-25 23:07:03 +0000810 Exception raised:
811 ...
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000812 ZeroDivisionError: integer division or modulo by zero
Christian Heimes25bb7832008-01-11 16:17:00 +0000813 TestResults(failed=1, attempted=2)
Tim Peters8485b562004-08-04 18:46:34 +0000814
815Exception messages may contain newlines:
816
817 >>> def f(x):
818 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000819 ... >>> raise ValueError('multi\nline\nmessage')
Tim Peters8485b562004-08-04 18:46:34 +0000820 ... Traceback (most recent call last):
821 ... ValueError: multi
822 ... line
823 ... message
824 ... '''
825 >>> test = doctest.DocTestFinder().find(f)[0]
826 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000827 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000828
829If an exception is expected, but an exception with the wrong type or
830message is raised, then it is reported as a failure:
831
832 >>> def f(x):
833 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000834 ... >>> raise ValueError('message')
Tim Peters8485b562004-08-04 18:46:34 +0000835 ... Traceback (most recent call last):
836 ... ValueError: wrong message
837 ... '''
838 >>> test = doctest.DocTestFinder().find(f)[0]
839 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000840 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000841 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000842 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000843 Failed example:
Collin Winter3add4d72007-08-29 23:37:32 +0000844 raise ValueError('message')
Tim Peters8485b562004-08-04 18:46:34 +0000845 Expected:
846 Traceback (most recent call last):
847 ValueError: wrong message
848 Got:
849 Traceback (most recent call last):
Edward Loper8e4a34b2004-08-12 02:34:27 +0000850 ...
Tim Peters8485b562004-08-04 18:46:34 +0000851 ValueError: message
Christian Heimes25bb7832008-01-11 16:17:00 +0000852 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000853
Tim Peters1fbf9c52004-09-04 17:21:02 +0000854However, IGNORE_EXCEPTION_DETAIL can be used to allow a mismatch in the
855detail:
856
857 >>> def f(x):
858 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000859 ... >>> raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +0000860 ... Traceback (most recent call last):
861 ... ValueError: wrong message
862 ... '''
863 >>> test = doctest.DocTestFinder().find(f)[0]
864 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000865 TestResults(failed=0, attempted=1)
Tim Peters1fbf9c52004-09-04 17:21:02 +0000866
867But IGNORE_EXCEPTION_DETAIL does not allow a mismatch in the exception type:
868
869 >>> def f(x):
870 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000871 ... >>> raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +0000872 ... Traceback (most recent call last):
873 ... TypeError: wrong type
874 ... '''
875 >>> test = doctest.DocTestFinder().find(f)[0]
876 >>> doctest.DocTestRunner(verbose=False).run(test)
877 ... # doctest: +ELLIPSIS
878 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000879 File ..., line 3, in f
Tim Peters1fbf9c52004-09-04 17:21:02 +0000880 Failed example:
Collin Winter3add4d72007-08-29 23:37:32 +0000881 raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +0000882 Expected:
883 Traceback (most recent call last):
884 TypeError: wrong type
885 Got:
886 Traceback (most recent call last):
887 ...
888 ValueError: message
Christian Heimes25bb7832008-01-11 16:17:00 +0000889 TestResults(failed=1, attempted=1)
Tim Peters1fbf9c52004-09-04 17:21:02 +0000890
Tim Peters8485b562004-08-04 18:46:34 +0000891If an exception is raised but not expected, then it is reported as an
892unexpected exception:
893
Tim Peters8485b562004-08-04 18:46:34 +0000894 >>> def f(x):
895 ... r'''
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000896 ... >>> 1//0
Tim Peters8485b562004-08-04 18:46:34 +0000897 ... 0
898 ... '''
899 >>> test = doctest.DocTestFinder().find(f)[0]
900 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper74bca7a2004-08-12 02:27:44 +0000901 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000902 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000903 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000904 Failed example:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000905 1//0
Tim Peters8485b562004-08-04 18:46:34 +0000906 Exception raised:
907 Traceback (most recent call last):
Jim Fulton07a349c2004-08-22 14:10:00 +0000908 ...
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000909 ZeroDivisionError: integer division or modulo by zero
Christian Heimes25bb7832008-01-11 16:17:00 +0000910 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000911"""
912 def optionflags(): r"""
913Tests of `DocTestRunner`'s option flag handling.
914
915Several option flags can be used to customize the behavior of the test
916runner. These are defined as module constants in doctest, and passed
Christian Heimesfaf2f632008-01-06 16:59:19 +0000917to the DocTestRunner constructor (multiple constants should be ORed
Tim Peters8485b562004-08-04 18:46:34 +0000918together).
919
920The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
921and 1/0:
922
923 >>> def f(x):
924 ... '>>> True\n1\n'
925
926 >>> # Without the flag:
927 >>> test = doctest.DocTestFinder().find(f)[0]
928 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000929 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000930
931 >>> # With the flag:
932 >>> test = doctest.DocTestFinder().find(f)[0]
933 >>> flags = doctest.DONT_ACCEPT_TRUE_FOR_1
934 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000935 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000936 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000937 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000938 Failed example:
939 True
940 Expected:
941 1
942 Got:
943 True
Christian Heimes25bb7832008-01-11 16:17:00 +0000944 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000945
946The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines
947and the '<BLANKLINE>' marker:
948
949 >>> def f(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000950 ... '>>> print("a\\n\\nb")\na\n<BLANKLINE>\nb\n'
Tim Peters8485b562004-08-04 18:46:34 +0000951
952 >>> # Without the flag:
953 >>> test = doctest.DocTestFinder().find(f)[0]
954 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000955 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000956
957 >>> # With the flag:
958 >>> test = doctest.DocTestFinder().find(f)[0]
959 >>> flags = doctest.DONT_ACCEPT_BLANKLINE
960 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000961 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000962 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000963 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000964 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000965 print("a\n\nb")
Tim Peters8485b562004-08-04 18:46:34 +0000966 Expected:
967 a
968 <BLANKLINE>
969 b
970 Got:
971 a
972 <BLANKLINE>
973 b
Christian Heimes25bb7832008-01-11 16:17:00 +0000974 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000975
976The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be
977treated as equal:
978
979 >>> def f(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000980 ... '>>> print(1, 2, 3)\n 1 2\n 3'
Tim Peters8485b562004-08-04 18:46:34 +0000981
982 >>> # Without the flag:
983 >>> test = doctest.DocTestFinder().find(f)[0]
984 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000985 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000986 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000987 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000988 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000989 print(1, 2, 3)
Tim Peters8485b562004-08-04 18:46:34 +0000990 Expected:
991 1 2
992 3
Jim Fulton07a349c2004-08-22 14:10:00 +0000993 Got:
994 1 2 3
Christian Heimes25bb7832008-01-11 16:17:00 +0000995 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000996
997 >>> # With the flag:
998 >>> test = doctest.DocTestFinder().find(f)[0]
999 >>> flags = doctest.NORMALIZE_WHITESPACE
1000 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001001 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001002
Tim Peters026f8dc2004-08-19 16:38:58 +00001003 An example from the docs:
Guido van Rossum805365e2007-05-07 22:24:25 +00001004 >>> print(list(range(20))) #doctest: +NORMALIZE_WHITESPACE
Tim Peters026f8dc2004-08-19 16:38:58 +00001005 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
1006 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
1007
Tim Peters8485b562004-08-04 18:46:34 +00001008The ELLIPSIS flag causes ellipsis marker ("...") in the expected
1009output to match any substring in the actual output:
1010
1011 >>> def f(x):
Guido van Rossum805365e2007-05-07 22:24:25 +00001012 ... '>>> print(list(range(15)))\n[0, 1, 2, ..., 14]\n'
Tim Peters8485b562004-08-04 18:46:34 +00001013
1014 >>> # Without the flag:
1015 >>> test = doctest.DocTestFinder().find(f)[0]
1016 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001017 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001018 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001019 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001020 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001021 print(list(range(15)))
Jim Fulton07a349c2004-08-22 14:10:00 +00001022 Expected:
1023 [0, 1, 2, ..., 14]
1024 Got:
1025 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
Christian Heimes25bb7832008-01-11 16:17:00 +00001026 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001027
1028 >>> # With the flag:
1029 >>> test = doctest.DocTestFinder().find(f)[0]
1030 >>> flags = doctest.ELLIPSIS
1031 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001032 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001033
Tim Peterse594bee2004-08-22 01:47:51 +00001034 ... also matches nothing:
Tim Peters1cf3aa62004-08-19 06:49:33 +00001035
Guido van Rossume0192e52007-02-09 23:39:59 +00001036 >>> if 1:
1037 ... for i in range(100):
1038 ... print(i**2, end=' ') #doctest: +ELLIPSIS
1039 ... print('!')
1040 0 1...4...9 16 ... 36 49 64 ... 9801 !
Tim Peters1cf3aa62004-08-19 06:49:33 +00001041
Tim Peters026f8dc2004-08-19 16:38:58 +00001042 ... can be surprising; e.g., this test passes:
Tim Peters26b3ebb2004-08-19 08:10:08 +00001043
Guido van Rossume0192e52007-02-09 23:39:59 +00001044 >>> if 1: #doctest: +ELLIPSIS
1045 ... for i in range(20):
1046 ... print(i, end=' ')
1047 ... print(20)
Tim Peterse594bee2004-08-22 01:47:51 +00001048 0 1 2 ...1...2...0
Tim Peters26b3ebb2004-08-19 08:10:08 +00001049
Tim Peters026f8dc2004-08-19 16:38:58 +00001050 Examples from the docs:
1051
Guido van Rossum805365e2007-05-07 22:24:25 +00001052 >>> print(list(range(20))) # doctest:+ELLIPSIS
Tim Peters026f8dc2004-08-19 16:38:58 +00001053 [0, 1, ..., 18, 19]
1054
Guido van Rossum805365e2007-05-07 22:24:25 +00001055 >>> print(list(range(20))) # doctest: +ELLIPSIS
Tim Peters026f8dc2004-08-19 16:38:58 +00001056 ... # doctest: +NORMALIZE_WHITESPACE
1057 [0, 1, ..., 18, 19]
1058
Thomas Wouters477c8d52006-05-27 19:21:47 +00001059The SKIP flag causes an example to be skipped entirely. I.e., the
1060example is not run. It can be useful in contexts where doctest
1061examples serve as both documentation and test cases, and an example
1062should be included for documentation purposes, but should not be
1063checked (e.g., because its output is random, or depends on resources
1064which would be unavailable.) The SKIP flag can also be used for
1065'commenting out' broken examples.
1066
1067 >>> import unavailable_resource # doctest: +SKIP
1068 >>> unavailable_resource.do_something() # doctest: +SKIP
1069 >>> unavailable_resource.blow_up() # doctest: +SKIP
1070 Traceback (most recent call last):
1071 ...
1072 UncheckedBlowUpError: Nobody checks me.
1073
1074 >>> import random
Guido van Rossum7131f842007-02-09 20:13:25 +00001075 >>> print(random.random()) # doctest: +SKIP
Thomas Wouters477c8d52006-05-27 19:21:47 +00001076 0.721216923889
1077
Edward Loper71f55af2004-08-26 01:41:51 +00001078The REPORT_UDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001079and actual outputs to be displayed using a unified diff:
1080
1081 >>> def f(x):
1082 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001083 ... >>> print('\n'.join('abcdefg'))
Tim Peters8485b562004-08-04 18:46:34 +00001084 ... a
1085 ... B
1086 ... c
1087 ... d
1088 ... f
1089 ... g
1090 ... h
1091 ... '''
1092
1093 >>> # Without the flag:
1094 >>> test = doctest.DocTestFinder().find(f)[0]
1095 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001096 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001097 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001098 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001099 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001100 print('\n'.join('abcdefg'))
Tim Peters8485b562004-08-04 18:46:34 +00001101 Expected:
1102 a
1103 B
1104 c
1105 d
1106 f
1107 g
1108 h
1109 Got:
1110 a
1111 b
1112 c
1113 d
1114 e
1115 f
1116 g
Christian Heimes25bb7832008-01-11 16:17:00 +00001117 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001118
1119 >>> # With the flag:
1120 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001121 >>> flags = doctest.REPORT_UDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001122 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001123 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001124 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001125 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001126 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001127 print('\n'.join('abcdefg'))
Edward Loper56629292004-08-26 01:31:56 +00001128 Differences (unified diff with -expected +actual):
Tim Peterse7edcb82004-08-26 05:44:27 +00001129 @@ -1,7 +1,7 @@
Tim Peters8485b562004-08-04 18:46:34 +00001130 a
1131 -B
1132 +b
1133 c
1134 d
1135 +e
1136 f
1137 g
1138 -h
Christian Heimes25bb7832008-01-11 16:17:00 +00001139 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001140
Edward Loper71f55af2004-08-26 01:41:51 +00001141The REPORT_CDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001142and actual outputs to be displayed using a context diff:
1143
Edward Loper71f55af2004-08-26 01:41:51 +00001144 >>> # Reuse f() from the REPORT_UDIFF example, above.
Tim Peters8485b562004-08-04 18:46:34 +00001145 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001146 >>> flags = doctest.REPORT_CDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001147 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001148 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001149 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001150 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001151 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001152 print('\n'.join('abcdefg'))
Edward Loper56629292004-08-26 01:31:56 +00001153 Differences (context diff with expected followed by actual):
Tim Peters8485b562004-08-04 18:46:34 +00001154 ***************
Tim Peterse7edcb82004-08-26 05:44:27 +00001155 *** 1,7 ****
Tim Peters8485b562004-08-04 18:46:34 +00001156 a
1157 ! B
1158 c
1159 d
1160 f
1161 g
1162 - h
Tim Peterse7edcb82004-08-26 05:44:27 +00001163 --- 1,7 ----
Tim Peters8485b562004-08-04 18:46:34 +00001164 a
1165 ! b
1166 c
1167 d
1168 + e
1169 f
1170 g
Christian Heimes25bb7832008-01-11 16:17:00 +00001171 TestResults(failed=1, attempted=1)
Tim Petersc6cbab02004-08-22 19:43:28 +00001172
1173
Edward Loper71f55af2004-08-26 01:41:51 +00001174The REPORT_NDIFF flag causes failures to use the difflib.Differ algorithm
Tim Petersc6cbab02004-08-22 19:43:28 +00001175used by the popular ndiff.py utility. This does intraline difference
1176marking, as well as interline differences.
1177
1178 >>> def f(x):
1179 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001180 ... >>> print("a b c d e f g h i j k l m")
Tim Petersc6cbab02004-08-22 19:43:28 +00001181 ... a b c d e f g h i j k 1 m
1182 ... '''
1183 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001184 >>> flags = doctest.REPORT_NDIFF
Tim Petersc6cbab02004-08-22 19:43:28 +00001185 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001186 ... # doctest: +ELLIPSIS
Tim Petersc6cbab02004-08-22 19:43:28 +00001187 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001188 File ..., line 3, in f
Tim Petersc6cbab02004-08-22 19:43:28 +00001189 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001190 print("a b c d e f g h i j k l m")
Tim Petersc6cbab02004-08-22 19:43:28 +00001191 Differences (ndiff with -expected +actual):
1192 - a b c d e f g h i j k 1 m
1193 ? ^
1194 + a b c d e f g h i j k l m
1195 ? + ++ ^
Christian Heimes25bb7832008-01-11 16:17:00 +00001196 TestResults(failed=1, attempted=1)
Edward Lopera89f88d2004-08-26 02:45:51 +00001197
1198The REPORT_ONLY_FIRST_FAILURE supresses result output after the first
1199failing example:
1200
1201 >>> def f(x):
1202 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001203 ... >>> print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001204 ... 1
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001205 ... >>> print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001206 ... 200
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001207 ... >>> print(3) # second failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001208 ... 300
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001209 ... >>> print(4) # second success
Edward Lopera89f88d2004-08-26 02:45:51 +00001210 ... 4
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001211 ... >>> print(5) # third failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001212 ... 500
1213 ... '''
1214 >>> test = doctest.DocTestFinder().find(f)[0]
1215 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1216 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001217 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001218 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001219 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001220 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001221 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001222 Expected:
1223 200
1224 Got:
1225 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001226 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001227
1228However, output from `report_start` is not supressed:
1229
1230 >>> doctest.DocTestRunner(verbose=True, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001231 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001232 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001233 print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001234 Expecting:
1235 1
1236 ok
1237 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001238 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001239 Expecting:
1240 200
1241 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001242 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001243 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001244 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001245 Expected:
1246 200
1247 Got:
1248 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001249 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001250
1251For the purposes of REPORT_ONLY_FIRST_FAILURE, unexpected exceptions
1252count as failures:
1253
1254 >>> def f(x):
1255 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001256 ... >>> print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001257 ... 1
1258 ... >>> raise ValueError(2) # first failure
1259 ... 200
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001260 ... >>> print(3) # second failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001261 ... 300
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001262 ... >>> print(4) # second success
Edward Lopera89f88d2004-08-26 02:45:51 +00001263 ... 4
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001264 ... >>> print(5) # third failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001265 ... 500
1266 ... '''
1267 >>> test = doctest.DocTestFinder().find(f)[0]
1268 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1269 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1270 ... # doctest: +ELLIPSIS
1271 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001272 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001273 Failed example:
1274 raise ValueError(2) # first failure
1275 Exception raised:
1276 ...
1277 ValueError: 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001278 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001279
Thomas Wouters477c8d52006-05-27 19:21:47 +00001280New option flags can also be registered, via register_optionflag(). Here
1281we reach into doctest's internals a bit.
1282
1283 >>> unlikely = "UNLIKELY_OPTION_NAME"
1284 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1285 False
1286 >>> new_flag_value = doctest.register_optionflag(unlikely)
1287 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1288 True
1289
1290Before 2.4.4/2.5, registering a name more than once erroneously created
1291more than one flag value. Here we verify that's fixed:
1292
1293 >>> redundant_flag_value = doctest.register_optionflag(unlikely)
1294 >>> redundant_flag_value == new_flag_value
1295 True
1296
1297Clean up.
1298 >>> del doctest.OPTIONFLAGS_BY_NAME[unlikely]
1299
Tim Petersc6cbab02004-08-22 19:43:28 +00001300 """
1301
Tim Peters8485b562004-08-04 18:46:34 +00001302 def option_directives(): r"""
1303Tests of `DocTestRunner`'s option directive mechanism.
1304
Edward Loper74bca7a2004-08-12 02:27:44 +00001305Option directives can be used to turn option flags on or off for a
1306single example. To turn an option on for an example, follow that
1307example with a comment of the form ``# doctest: +OPTION``:
Tim Peters8485b562004-08-04 18:46:34 +00001308
1309 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001310 ... >>> print(list(range(10))) # should fail: no ellipsis
Edward Loper74bca7a2004-08-12 02:27:44 +00001311 ... [0, 1, ..., 9]
1312 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001313 ... >>> print(list(range(10))) # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001314 ... [0, 1, ..., 9]
1315 ... '''
1316 >>> test = doctest.DocTestFinder().find(f)[0]
1317 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001318 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001319 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001320 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001321 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001322 print(list(range(10))) # should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001323 Expected:
1324 [0, 1, ..., 9]
1325 Got:
1326 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001327 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001328
1329To turn an option off for an example, follow that example with a
1330comment of the form ``# doctest: -OPTION``:
1331
1332 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001333 ... >>> print(list(range(10)))
Edward Loper74bca7a2004-08-12 02:27:44 +00001334 ... [0, 1, ..., 9]
1335 ...
1336 ... >>> # should fail: no ellipsis
Guido van Rossum805365e2007-05-07 22:24:25 +00001337 ... >>> print(list(range(10))) # doctest: -ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001338 ... [0, 1, ..., 9]
1339 ... '''
1340 >>> test = doctest.DocTestFinder().find(f)[0]
1341 >>> doctest.DocTestRunner(verbose=False,
1342 ... optionflags=doctest.ELLIPSIS).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001343 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001344 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001345 File ..., line 6, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001346 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001347 print(list(range(10))) # doctest: -ELLIPSIS
Jim Fulton07a349c2004-08-22 14:10:00 +00001348 Expected:
1349 [0, 1, ..., 9]
1350 Got:
1351 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001352 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001353
1354Option directives affect only the example that they appear with; they
1355do not change the options for surrounding examples:
Edward Loper8e4a34b2004-08-12 02:34:27 +00001356
Edward Loper74bca7a2004-08-12 02:27:44 +00001357 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001358 ... >>> print(list(range(10))) # Should fail: no ellipsis
Tim Peters8485b562004-08-04 18:46:34 +00001359 ... [0, 1, ..., 9]
1360 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001361 ... >>> print(list(range(10))) # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001362 ... [0, 1, ..., 9]
1363 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001364 ... >>> print(list(range(10))) # Should fail: no ellipsis
Tim Peters8485b562004-08-04 18:46:34 +00001365 ... [0, 1, ..., 9]
1366 ... '''
1367 >>> test = doctest.DocTestFinder().find(f)[0]
1368 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001369 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001370 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001371 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001372 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001373 print(list(range(10))) # Should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001374 Expected:
1375 [0, 1, ..., 9]
1376 Got:
1377 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001378 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001379 File ..., line 8, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001380 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001381 print(list(range(10))) # Should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001382 Expected:
1383 [0, 1, ..., 9]
1384 Got:
1385 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001386 TestResults(failed=2, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +00001387
Edward Loper74bca7a2004-08-12 02:27:44 +00001388Multiple options may be modified by a single option directive. They
1389may be separated by whitespace, commas, or both:
Tim Peters8485b562004-08-04 18:46:34 +00001390
1391 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001392 ... >>> print(list(range(10))) # Should fail
Tim Peters8485b562004-08-04 18:46:34 +00001393 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001394 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001395 ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001396 ... [0, 1, ..., 9]
1397 ... '''
1398 >>> test = doctest.DocTestFinder().find(f)[0]
1399 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001400 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001401 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001402 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001403 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001404 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001405 Expected:
1406 [0, 1, ..., 9]
1407 Got:
1408 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001409 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001410
1411 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001412 ... >>> print(list(range(10))) # Should fail
Edward Loper74bca7a2004-08-12 02:27:44 +00001413 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001414 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001415 ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
1416 ... [0, 1, ..., 9]
1417 ... '''
1418 >>> test = doctest.DocTestFinder().find(f)[0]
1419 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001420 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001421 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001422 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001423 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001424 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001425 Expected:
1426 [0, 1, ..., 9]
1427 Got:
1428 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001429 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001430
1431 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001432 ... >>> print(list(range(10))) # Should fail
Edward Loper74bca7a2004-08-12 02:27:44 +00001433 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001434 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001435 ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1436 ... [0, 1, ..., 9]
1437 ... '''
1438 >>> test = doctest.DocTestFinder().find(f)[0]
1439 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001440 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001441 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001442 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001443 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001444 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001445 Expected:
1446 [0, 1, ..., 9]
1447 Got:
1448 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001449 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001450
1451The option directive may be put on the line following the source, as
1452long as a continuation prompt is used:
1453
1454 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001455 ... >>> print(list(range(10)))
Edward Loper74bca7a2004-08-12 02:27:44 +00001456 ... ... # doctest: +ELLIPSIS
1457 ... [0, 1, ..., 9]
1458 ... '''
1459 >>> test = doctest.DocTestFinder().find(f)[0]
1460 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001461 TestResults(failed=0, attempted=1)
Edward Loper8e4a34b2004-08-12 02:34:27 +00001462
Edward Loper74bca7a2004-08-12 02:27:44 +00001463For examples with multi-line source, the option directive may appear
1464at the end of any line:
1465
1466 >>> def f(x): r'''
1467 ... >>> for x in range(10): # doctest: +ELLIPSIS
Guido van Rossum805365e2007-05-07 22:24:25 +00001468 ... ... print(' ', x, end='', sep='')
1469 ... 0 1 2 ... 9
Edward Loper74bca7a2004-08-12 02:27:44 +00001470 ...
1471 ... >>> for x in range(10):
Guido van Rossum805365e2007-05-07 22:24:25 +00001472 ... ... print(' ', x, end='', sep='') # doctest: +ELLIPSIS
1473 ... 0 1 2 ... 9
Edward Loper74bca7a2004-08-12 02:27:44 +00001474 ... '''
1475 >>> test = doctest.DocTestFinder().find(f)[0]
1476 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001477 TestResults(failed=0, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001478
1479If more than one line of an example with multi-line source has an
1480option directive, then they are combined:
1481
1482 >>> def f(x): r'''
1483 ... Should fail (option directive not on the last line):
1484 ... >>> for x in range(10): # doctest: +ELLIPSIS
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001485 ... ... print(x, end=' ') # doctest: +NORMALIZE_WHITESPACE
Guido van Rossumd8faa362007-04-27 19:54:29 +00001486 ... 0 1 2...9
Edward Loper74bca7a2004-08-12 02:27:44 +00001487 ... '''
1488 >>> test = doctest.DocTestFinder().find(f)[0]
1489 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001490 TestResults(failed=0, attempted=1)
Edward Loper74bca7a2004-08-12 02:27:44 +00001491
1492It is an error to have a comment of the form ``# doctest:`` that is
1493*not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
1494``OPTION`` is an option that has been registered with
1495`register_option`:
1496
1497 >>> # Error: Option not registered
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001498 >>> s = '>>> print(12) #doctest: +BADOPTION'
Edward Loper74bca7a2004-08-12 02:27:44 +00001499 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1500 Traceback (most recent call last):
1501 ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
1502
1503 >>> # Error: No + or - prefix
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001504 >>> s = '>>> print(12) #doctest: ELLIPSIS'
Edward Loper74bca7a2004-08-12 02:27:44 +00001505 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1506 Traceback (most recent call last):
1507 ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
1508
1509It is an error to use an option directive on a line that contains no
1510source:
1511
1512 >>> s = '>>> # doctest: +ELLIPSIS'
1513 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1514 Traceback (most recent call last):
1515 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 +00001516"""
1517
1518def test_testsource(): r"""
1519Unit tests for `testsource()`.
1520
1521The testsource() function takes a module and a name, finds the (first)
Tim Peters19397e52004-08-06 22:02:59 +00001522test with that name in that module, and converts it to a script. The
1523example code is converted to regular Python code. The surrounding
1524words and expected output are converted to comments:
Tim Peters8485b562004-08-04 18:46:34 +00001525
1526 >>> import test.test_doctest
1527 >>> name = 'test.test_doctest.sample_func'
Guido van Rossum7131f842007-02-09 20:13:25 +00001528 >>> print(doctest.testsource(test.test_doctest, name))
Edward Lopera5db6002004-08-12 02:41:30 +00001529 # Blah blah
Tim Peters19397e52004-08-06 22:02:59 +00001530 #
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001531 print(sample_func(22))
Tim Peters8485b562004-08-04 18:46:34 +00001532 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001533 ## 44
Tim Peters19397e52004-08-06 22:02:59 +00001534 #
Edward Lopera5db6002004-08-12 02:41:30 +00001535 # Yee ha!
Georg Brandlecf93c72005-06-26 23:09:51 +00001536 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001537
1538 >>> name = 'test.test_doctest.SampleNewStyleClass'
Guido van Rossum7131f842007-02-09 20:13:25 +00001539 >>> print(doctest.testsource(test.test_doctest, name))
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001540 print('1\n2\n3')
Tim Peters8485b562004-08-04 18:46:34 +00001541 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001542 ## 1
1543 ## 2
1544 ## 3
Georg Brandlecf93c72005-06-26 23:09:51 +00001545 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001546
1547 >>> name = 'test.test_doctest.SampleClass.a_classmethod'
Guido van Rossum7131f842007-02-09 20:13:25 +00001548 >>> print(doctest.testsource(test.test_doctest, name))
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001549 print(SampleClass.a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +00001550 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001551 ## 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001552 print(SampleClass(0).a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +00001553 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001554 ## 12
Georg Brandlecf93c72005-06-26 23:09:51 +00001555 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001556"""
1557
1558def test_debug(): r"""
1559
1560Create a docstring that we want to debug:
1561
1562 >>> s = '''
1563 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001564 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +00001565 ... 12
1566 ... '''
1567
1568Create some fake stdin input, to feed to the debugger:
1569
Tim Peters8485b562004-08-04 18:46:34 +00001570 >>> real_stdin = sys.stdin
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001571 >>> sys.stdin = _FakeInput(['next', 'print(x)', 'continue'])
Tim Peters8485b562004-08-04 18:46:34 +00001572
1573Run the debugger on the docstring, and then restore sys.stdin.
1574
Edward Loper2de91ba2004-08-27 02:07:46 +00001575 >>> try: doctest.debug_src(s)
1576 ... finally: sys.stdin = real_stdin
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001577 > <string>(1)<module>()
Edward Loper2de91ba2004-08-27 02:07:46 +00001578 (Pdb) next
1579 12
Tim Peters8485b562004-08-04 18:46:34 +00001580 --Return--
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001581 > <string>(1)<module>()->None
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001582 (Pdb) print(x)
Edward Loper2de91ba2004-08-27 02:07:46 +00001583 12
1584 (Pdb) continue
Tim Peters8485b562004-08-04 18:46:34 +00001585
1586"""
1587
Jim Fulton356fd192004-08-09 11:34:47 +00001588def test_pdb_set_trace():
Tim Peters50c6bdb2004-11-08 22:07:37 +00001589 """Using pdb.set_trace from a doctest.
Jim Fulton356fd192004-08-09 11:34:47 +00001590
Tim Peters413ced62004-08-09 15:43:47 +00001591 You can use pdb.set_trace from a doctest. To do so, you must
Jim Fulton356fd192004-08-09 11:34:47 +00001592 retrieve the set_trace function from the pdb module at the time
Tim Peters413ced62004-08-09 15:43:47 +00001593 you use it. The doctest module changes sys.stdout so that it can
1594 capture program output. It also temporarily replaces pdb.set_trace
1595 with a version that restores stdout. This is necessary for you to
Jim Fulton356fd192004-08-09 11:34:47 +00001596 see debugger output.
1597
1598 >>> doc = '''
1599 ... >>> x = 42
1600 ... >>> import pdb; pdb.set_trace()
1601 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001602 >>> parser = doctest.DocTestParser()
1603 >>> test = parser.get_doctest(doc, {}, "foo", "foo.py", 0)
Jim Fulton356fd192004-08-09 11:34:47 +00001604 >>> runner = doctest.DocTestRunner(verbose=False)
1605
1606 To demonstrate this, we'll create a fake standard input that
1607 captures our debugger input:
1608
1609 >>> import tempfile
Edward Loper2de91ba2004-08-27 02:07:46 +00001610 >>> real_stdin = sys.stdin
1611 >>> sys.stdin = _FakeInput([
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001612 ... 'print(x)', # print data defined by the example
Jim Fulton356fd192004-08-09 11:34:47 +00001613 ... 'continue', # stop debugging
Edward Loper2de91ba2004-08-27 02:07:46 +00001614 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001615
Edward Loper2de91ba2004-08-27 02:07:46 +00001616 >>> try: runner.run(test)
1617 ... finally: sys.stdin = real_stdin
Jim Fulton356fd192004-08-09 11:34:47 +00001618 --Return--
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001619 > <doctest foo[1]>(1)<module>()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001620 -> import pdb; pdb.set_trace()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001621 (Pdb) print(x)
Edward Loper2de91ba2004-08-27 02:07:46 +00001622 42
1623 (Pdb) continue
Christian Heimes25bb7832008-01-11 16:17:00 +00001624 TestResults(failed=0, attempted=2)
Jim Fulton356fd192004-08-09 11:34:47 +00001625
1626 You can also put pdb.set_trace in a function called from a test:
1627
1628 >>> def calls_set_trace():
1629 ... y=2
1630 ... import pdb; pdb.set_trace()
1631
1632 >>> doc = '''
1633 ... >>> x=1
1634 ... >>> calls_set_trace()
1635 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001636 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
Edward Loper2de91ba2004-08-27 02:07:46 +00001637 >>> real_stdin = sys.stdin
1638 >>> sys.stdin = _FakeInput([
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001639 ... 'print(y)', # print data defined in the function
Jim Fulton356fd192004-08-09 11:34:47 +00001640 ... 'up', # out of function
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001641 ... 'print(x)', # print data defined by the example
Jim Fulton356fd192004-08-09 11:34:47 +00001642 ... 'continue', # stop debugging
Edward Loper2de91ba2004-08-27 02:07:46 +00001643 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001644
Tim Peters50c6bdb2004-11-08 22:07:37 +00001645 >>> try:
1646 ... runner.run(test)
1647 ... finally:
1648 ... sys.stdin = real_stdin
Jim Fulton356fd192004-08-09 11:34:47 +00001649 --Return--
Edward Loper2de91ba2004-08-27 02:07:46 +00001650 > <doctest test.test_doctest.test_pdb_set_trace[8]>(3)calls_set_trace()->None
1651 -> import pdb; pdb.set_trace()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001652 (Pdb) print(y)
Edward Loper2de91ba2004-08-27 02:07:46 +00001653 2
1654 (Pdb) up
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001655 > <doctest foo[1]>(1)<module>()
Edward Loper2de91ba2004-08-27 02:07:46 +00001656 -> calls_set_trace()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001657 (Pdb) print(x)
Edward Loper2de91ba2004-08-27 02:07:46 +00001658 1
1659 (Pdb) continue
Christian Heimes25bb7832008-01-11 16:17:00 +00001660 TestResults(failed=0, attempted=2)
Edward Loper2de91ba2004-08-27 02:07:46 +00001661
1662 During interactive debugging, source code is shown, even for
1663 doctest examples:
1664
1665 >>> doc = '''
1666 ... >>> def f(x):
1667 ... ... g(x*2)
1668 ... >>> def g(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001669 ... ... print(x+3)
Edward Loper2de91ba2004-08-27 02:07:46 +00001670 ... ... import pdb; pdb.set_trace()
1671 ... >>> f(3)
1672 ... '''
1673 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
1674 >>> real_stdin = sys.stdin
1675 >>> sys.stdin = _FakeInput([
1676 ... 'list', # list source from example 2
1677 ... 'next', # return from g()
1678 ... 'list', # list source from example 1
1679 ... 'next', # return from f()
1680 ... 'list', # list source from example 3
1681 ... 'continue', # stop debugging
1682 ... ''])
1683 >>> try: runner.run(test)
1684 ... finally: sys.stdin = real_stdin
1685 ... # doctest: +NORMALIZE_WHITESPACE
1686 --Return--
1687 > <doctest foo[1]>(3)g()->None
1688 -> import pdb; pdb.set_trace()
1689 (Pdb) list
1690 1 def g(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001691 2 print(x+3)
Edward Loper2de91ba2004-08-27 02:07:46 +00001692 3 -> import pdb; pdb.set_trace()
1693 [EOF]
1694 (Pdb) next
1695 --Return--
1696 > <doctest foo[0]>(2)f()->None
1697 -> g(x*2)
1698 (Pdb) list
1699 1 def f(x):
1700 2 -> g(x*2)
1701 [EOF]
1702 (Pdb) next
1703 --Return--
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001704 > <doctest foo[2]>(1)<module>()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001705 -> f(3)
1706 (Pdb) list
1707 1 -> f(3)
1708 [EOF]
1709 (Pdb) continue
1710 **********************************************************************
1711 File "foo.py", line 7, in foo
1712 Failed example:
1713 f(3)
1714 Expected nothing
1715 Got:
1716 9
Christian Heimes25bb7832008-01-11 16:17:00 +00001717 TestResults(failed=1, attempted=3)
Jim Fulton356fd192004-08-09 11:34:47 +00001718 """
1719
Tim Peters50c6bdb2004-11-08 22:07:37 +00001720def test_pdb_set_trace_nested():
1721 """This illustrates more-demanding use of set_trace with nested functions.
1722
1723 >>> class C(object):
1724 ... def calls_set_trace(self):
1725 ... y = 1
1726 ... import pdb; pdb.set_trace()
1727 ... self.f1()
1728 ... y = 2
1729 ... def f1(self):
1730 ... x = 1
1731 ... self.f2()
1732 ... x = 2
1733 ... def f2(self):
1734 ... z = 1
1735 ... z = 2
1736
1737 >>> calls_set_trace = C().calls_set_trace
1738
1739 >>> doc = '''
1740 ... >>> a = 1
1741 ... >>> calls_set_trace()
1742 ... '''
1743 >>> parser = doctest.DocTestParser()
1744 >>> runner = doctest.DocTestRunner(verbose=False)
1745 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
1746 >>> real_stdin = sys.stdin
1747 >>> sys.stdin = _FakeInput([
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001748 ... 'print(y)', # print data defined in the function
1749 ... 'step', 'step', 'step', 'step', 'step', 'step', 'print(z)',
1750 ... 'up', 'print(x)',
1751 ... 'up', 'print(y)',
1752 ... 'up', 'print(foo)',
Tim Peters50c6bdb2004-11-08 22:07:37 +00001753 ... 'continue', # stop debugging
1754 ... ''])
1755
1756 >>> try:
1757 ... runner.run(test)
1758 ... finally:
1759 ... sys.stdin = real_stdin
Guido van Rossum4a625c32007-09-08 16:05:25 +00001760 ... # doctest: +REPORT_NDIFF
Tim Peters50c6bdb2004-11-08 22:07:37 +00001761 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
1762 -> self.f1()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001763 (Pdb) print(y)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001764 1
1765 (Pdb) step
1766 --Call--
1767 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(7)f1()
1768 -> def f1(self):
1769 (Pdb) step
1770 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(8)f1()
1771 -> x = 1
1772 (Pdb) step
1773 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
1774 -> self.f2()
1775 (Pdb) step
1776 --Call--
1777 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(11)f2()
1778 -> def f2(self):
1779 (Pdb) step
1780 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(12)f2()
1781 -> z = 1
1782 (Pdb) step
1783 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(13)f2()
1784 -> z = 2
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001785 (Pdb) print(z)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001786 1
1787 (Pdb) up
1788 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
1789 -> self.f2()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001790 (Pdb) print(x)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001791 1
1792 (Pdb) up
1793 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
1794 -> self.f1()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001795 (Pdb) print(y)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001796 1
1797 (Pdb) up
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001798 > <doctest foo[1]>(1)<module>()
Tim Peters50c6bdb2004-11-08 22:07:37 +00001799 -> calls_set_trace()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001800 (Pdb) print(foo)
Guido van Rossumfd4a7de2007-09-05 03:26:38 +00001801 *** NameError: NameError("name 'foo' is not defined",)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001802 (Pdb) continue
Christian Heimes25bb7832008-01-11 16:17:00 +00001803 TestResults(failed=0, attempted=2)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001804"""
1805
Tim Peters19397e52004-08-06 22:02:59 +00001806def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +00001807 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +00001808
1809 We create a Suite by providing a module. A module can be provided
1810 by passing a module object:
1811
1812 >>> import unittest
1813 >>> import test.sample_doctest
1814 >>> suite = doctest.DocTestSuite(test.sample_doctest)
1815 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001816 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001817
1818 We can also supply the module by name:
1819
1820 >>> suite = doctest.DocTestSuite('test.sample_doctest')
1821 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001822 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001823
1824 We can use the current module:
1825
1826 >>> suite = test.sample_doctest.test_suite()
1827 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001828 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001829
1830 We can supply global variables. If we pass globs, they will be
1831 used instead of the module globals. Here we'll pass an empty
1832 globals, triggering an extra error:
1833
1834 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
1835 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001836 <unittest.result.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001837
1838 Alternatively, we can provide extra globals. Here we'll make an
1839 error go away by providing an extra global variable:
1840
1841 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1842 ... extraglobs={'y': 1})
1843 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001844 <unittest.result.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001845
1846 You can pass option flags. Here we'll cause an extra error
1847 by disabling the blank-line feature:
1848
1849 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00001850 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00001851 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001852 <unittest.result.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001853
Tim Peters1e277ee2004-08-07 05:37:52 +00001854 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00001855
Jim Fultonf54bad42004-08-28 14:57:56 +00001856 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00001857 ... import test.test_doctest
1858 ... test.test_doctest.sillySetup = True
1859
Jim Fultonf54bad42004-08-28 14:57:56 +00001860 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00001861 ... import test.test_doctest
1862 ... del test.test_doctest.sillySetup
1863
1864 Here, we installed a silly variable that the test expects:
1865
1866 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1867 ... setUp=setUp, tearDown=tearDown)
1868 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001869 <unittest.result.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001870
1871 But the tearDown restores sanity:
1872
1873 >>> import test.test_doctest
1874 >>> test.test_doctest.sillySetup
1875 Traceback (most recent call last):
1876 ...
1877 AttributeError: 'module' object has no attribute 'sillySetup'
1878
Jim Fultonf54bad42004-08-28 14:57:56 +00001879 The setUp and tearDown funtions are passed test objects. Here
1880 we'll use the setUp function to supply the missing variable y:
1881
1882 >>> def setUp(test):
1883 ... test.globs['y'] = 1
1884
1885 >>> suite = doctest.DocTestSuite('test.sample_doctest', setUp=setUp)
1886 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001887 <unittest.result.TestResult run=9 errors=0 failures=3>
Jim Fultonf54bad42004-08-28 14:57:56 +00001888
1889 Here, we didn't need to use a tearDown function because we
1890 modified the test globals, which are a copy of the
1891 sample_doctest module dictionary. The test globals are
1892 automatically cleared for us after a test.
Tim Peters19397e52004-08-06 22:02:59 +00001893 """
1894
1895def test_DocFileSuite():
1896 """We can test tests found in text files using a DocFileSuite.
1897
1898 We create a suite by providing the names of one or more text
1899 files that include examples:
1900
1901 >>> import unittest
1902 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001903 ... 'test_doctest2.txt',
1904 ... 'test_doctest4.txt')
Tim Peters19397e52004-08-06 22:02:59 +00001905 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001906 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00001907
1908 The test files are looked for in the directory containing the
1909 calling module. A package keyword argument can be provided to
1910 specify a different relative location.
1911
1912 >>> import unittest
1913 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1914 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001915 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00001916 ... package='test')
1917 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001918 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00001919
Guido van Rossumcd4d4522007-11-22 00:30:02 +00001920 Support for using a package's __loader__.get_data() is also
1921 provided.
1922
1923 >>> import unittest, pkgutil, test
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001924 >>> added_loader = False
Guido van Rossumcd4d4522007-11-22 00:30:02 +00001925 >>> if not hasattr(test, '__loader__'):
1926 ... test.__loader__ = pkgutil.get_loader(test)
1927 ... added_loader = True
1928 >>> try:
1929 ... suite = doctest.DocFileSuite('test_doctest.txt',
1930 ... 'test_doctest2.txt',
1931 ... 'test_doctest4.txt',
1932 ... package='test')
1933 ... suite.run(unittest.TestResult())
1934 ... finally:
1935 ... if added_loader:
1936 ... del test.__loader__
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001937 <unittest.result.TestResult run=3 errors=0 failures=2>
Guido van Rossumcd4d4522007-11-22 00:30:02 +00001938
Edward Loper0273f5b2004-09-18 20:27:04 +00001939 '/' should be used as a path separator. It will be converted
1940 to a native separator at run time:
Tim Peters19397e52004-08-06 22:02:59 +00001941
1942 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
1943 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001944 <unittest.result.TestResult run=1 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00001945
Edward Loper0273f5b2004-09-18 20:27:04 +00001946 If DocFileSuite is used from an interactive session, then files
1947 are resolved relative to the directory of sys.argv[0]:
1948
Christian Heimes45f9af32007-11-27 21:50:00 +00001949 >>> import types, os.path, test.test_doctest
Edward Loper0273f5b2004-09-18 20:27:04 +00001950 >>> save_argv = sys.argv
1951 >>> sys.argv = [test.test_doctest.__file__]
1952 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Christian Heimes45f9af32007-11-27 21:50:00 +00001953 ... package=types.ModuleType('__main__'))
Edward Loper0273f5b2004-09-18 20:27:04 +00001954 >>> sys.argv = save_argv
1955
Edward Loper052d0cd2004-09-19 17:19:33 +00001956 By setting `module_relative=False`, os-specific paths may be
1957 used (including absolute paths and paths relative to the
1958 working directory):
Edward Loper0273f5b2004-09-18 20:27:04 +00001959
1960 >>> # Get the absolute path of the test package.
1961 >>> test_doctest_path = os.path.abspath(test.test_doctest.__file__)
1962 >>> test_pkg_path = os.path.split(test_doctest_path)[0]
1963
1964 >>> # Use it to find the absolute path of test_doctest.txt.
1965 >>> test_file = os.path.join(test_pkg_path, 'test_doctest.txt')
1966
Edward Loper052d0cd2004-09-19 17:19:33 +00001967 >>> suite = doctest.DocFileSuite(test_file, module_relative=False)
Edward Loper0273f5b2004-09-18 20:27:04 +00001968 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001969 <unittest.result.TestResult run=1 errors=0 failures=1>
Edward Loper0273f5b2004-09-18 20:27:04 +00001970
Edward Loper052d0cd2004-09-19 17:19:33 +00001971 It is an error to specify `package` when `module_relative=False`:
1972
1973 >>> suite = doctest.DocFileSuite(test_file, module_relative=False,
1974 ... package='test')
1975 Traceback (most recent call last):
1976 ValueError: Package may only be specified for module-relative paths.
1977
Tim Peters19397e52004-08-06 22:02:59 +00001978 You can specify initial global variables:
1979
1980 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1981 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001982 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00001983 ... globs={'favorite_color': 'blue'})
1984 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001985 <unittest.result.TestResult run=3 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00001986
1987 In this case, we supplied a missing favorite color. You can
1988 provide doctest options:
1989
1990 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1991 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001992 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00001993 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
1994 ... globs={'favorite_color': 'blue'})
1995 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001996 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00001997
1998 And, you can provide setUp and tearDown functions:
1999
Jim Fultonf54bad42004-08-28 14:57:56 +00002000 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00002001 ... import test.test_doctest
2002 ... test.test_doctest.sillySetup = True
2003
Jim Fultonf54bad42004-08-28 14:57:56 +00002004 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00002005 ... import test.test_doctest
2006 ... del test.test_doctest.sillySetup
2007
2008 Here, we installed a silly variable that the test expects:
2009
2010 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2011 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002012 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002013 ... setUp=setUp, tearDown=tearDown)
2014 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002015 <unittest.result.TestResult run=3 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002016
2017 But the tearDown restores sanity:
2018
2019 >>> import test.test_doctest
2020 >>> test.test_doctest.sillySetup
2021 Traceback (most recent call last):
2022 ...
2023 AttributeError: 'module' object has no attribute 'sillySetup'
2024
Jim Fultonf54bad42004-08-28 14:57:56 +00002025 The setUp and tearDown funtions are passed test objects.
2026 Here, we'll use a setUp function to set the favorite color in
2027 test_doctest.txt:
2028
2029 >>> def setUp(test):
2030 ... test.globs['favorite_color'] = 'blue'
2031
2032 >>> suite = doctest.DocFileSuite('test_doctest.txt', setUp=setUp)
2033 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002034 <unittest.result.TestResult run=1 errors=0 failures=0>
Jim Fultonf54bad42004-08-28 14:57:56 +00002035
2036 Here, we didn't need to use a tearDown function because we
2037 modified the test globals. The test globals are
2038 automatically cleared for us after a test.
Tim Petersdf7a2082004-08-29 00:38:17 +00002039
Fred Drake7c404a42004-12-21 23:46:34 +00002040 Tests in a file run using `DocFileSuite` can also access the
2041 `__file__` global, which is set to the name of the file
2042 containing the tests:
2043
2044 >>> suite = doctest.DocFileSuite('test_doctest3.txt')
2045 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002046 <unittest.result.TestResult run=1 errors=0 failures=0>
Fred Drake7c404a42004-12-21 23:46:34 +00002047
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002048 If the tests contain non-ASCII characters, we have to specify which
2049 encoding the file is encoded with. We do so by using the `encoding`
2050 parameter:
2051
2052 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2053 ... 'test_doctest2.txt',
2054 ... 'test_doctest4.txt',
2055 ... encoding='utf-8')
2056 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002057 <unittest.result.TestResult run=3 errors=0 failures=2>
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002058
Jim Fultonf54bad42004-08-28 14:57:56 +00002059 """
Tim Peters19397e52004-08-06 22:02:59 +00002060
Jim Fulton07a349c2004-08-22 14:10:00 +00002061def test_trailing_space_in_test():
2062 """
Tim Petersa7def722004-08-23 22:13:22 +00002063 Trailing spaces in expected output are significant:
Tim Petersc6cbab02004-08-22 19:43:28 +00002064
Jim Fulton07a349c2004-08-22 14:10:00 +00002065 >>> x, y = 'foo', ''
Guido van Rossum7131f842007-02-09 20:13:25 +00002066 >>> print(x, y)
Jim Fulton07a349c2004-08-22 14:10:00 +00002067 foo \n
2068 """
Tim Peters19397e52004-08-06 22:02:59 +00002069
Jim Fultonf54bad42004-08-28 14:57:56 +00002070
2071def test_unittest_reportflags():
2072 """Default unittest reporting flags can be set to control reporting
2073
2074 Here, we'll set the REPORT_ONLY_FIRST_FAILURE option so we see
2075 only the first failure of each test. First, we'll look at the
2076 output without the flag. The file test_doctest.txt file has two
2077 tests. They both fail if blank lines are disabled:
2078
2079 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2080 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
2081 >>> import unittest
2082 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002083 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002084 Traceback ...
2085 Failed example:
2086 favorite_color
2087 ...
2088 Failed example:
2089 if 1:
2090 ...
2091
2092 Note that we see both failures displayed.
2093
2094 >>> old = doctest.set_unittest_reportflags(
2095 ... doctest.REPORT_ONLY_FIRST_FAILURE)
2096
2097 Now, when we run the test:
2098
2099 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002100 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002101 Traceback ...
2102 Failed example:
2103 favorite_color
2104 Exception raised:
2105 ...
2106 NameError: name 'favorite_color' is not defined
2107 <BLANKLINE>
2108 <BLANKLINE>
Tim Petersdf7a2082004-08-29 00:38:17 +00002109
Jim Fultonf54bad42004-08-28 14:57:56 +00002110 We get only the first failure.
2111
2112 If we give any reporting options when we set up the tests,
2113 however:
2114
2115 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2116 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE | doctest.REPORT_NDIFF)
2117
2118 Then the default eporting options are ignored:
2119
2120 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002121 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002122 Traceback ...
2123 Failed example:
2124 favorite_color
2125 ...
2126 Failed example:
2127 if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00002128 print('a')
2129 print()
2130 print('b')
Jim Fultonf54bad42004-08-28 14:57:56 +00002131 Differences (ndiff with -expected +actual):
2132 a
2133 - <BLANKLINE>
2134 +
2135 b
2136 <BLANKLINE>
2137 <BLANKLINE>
2138
2139
2140 Test runners can restore the formatting flags after they run:
2141
2142 >>> ignored = doctest.set_unittest_reportflags(old)
2143
2144 """
2145
Edward Loper052d0cd2004-09-19 17:19:33 +00002146def test_testfile(): r"""
2147Tests for the `testfile()` function. This function runs all the
2148doctest examples in a given file. In its simple invokation, it is
2149called with the name of a file, which is taken to be relative to the
2150calling module. The return value is (#failures, #tests).
2151
Florent Xicluna59250852010-02-27 14:21:57 +00002152We don't want `-v` in sys.argv for these tests.
2153
2154 >>> save_argv = sys.argv
2155 >>> if '-v' in sys.argv:
2156 ... sys.argv = [arg for arg in save_argv if arg != '-v']
2157
2158
Edward Loper052d0cd2004-09-19 17:19:33 +00002159 >>> doctest.testfile('test_doctest.txt') # doctest: +ELLIPSIS
2160 **********************************************************************
2161 File "...", line 6, in test_doctest.txt
2162 Failed example:
2163 favorite_color
2164 Exception raised:
2165 ...
2166 NameError: name 'favorite_color' is not defined
2167 **********************************************************************
2168 1 items had failures:
2169 1 of 2 in test_doctest.txt
2170 ***Test Failed*** 1 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002171 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002172 >>> doctest.master = None # Reset master.
2173
2174(Note: we'll be clearing doctest.master after each call to
2175`doctest.testfile`, to supress warnings about multiple tests with the
2176same name.)
2177
2178Globals may be specified with the `globs` and `extraglobs` parameters:
2179
2180 >>> globs = {'favorite_color': 'blue'}
2181 >>> doctest.testfile('test_doctest.txt', globs=globs)
Christian Heimes25bb7832008-01-11 16:17:00 +00002182 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002183 >>> doctest.master = None # Reset master.
2184
2185 >>> extraglobs = {'favorite_color': 'red'}
2186 >>> doctest.testfile('test_doctest.txt', globs=globs,
2187 ... extraglobs=extraglobs) # doctest: +ELLIPSIS
2188 **********************************************************************
2189 File "...", line 6, in test_doctest.txt
2190 Failed example:
2191 favorite_color
2192 Expected:
2193 'blue'
2194 Got:
2195 'red'
2196 **********************************************************************
2197 1 items had failures:
2198 1 of 2 in test_doctest.txt
2199 ***Test Failed*** 1 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002200 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002201 >>> doctest.master = None # Reset master.
2202
2203The file may be made relative to a given module or package, using the
2204optional `module_relative` parameter:
2205
2206 >>> doctest.testfile('test_doctest.txt', globs=globs,
2207 ... module_relative='test')
Christian Heimes25bb7832008-01-11 16:17:00 +00002208 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002209 >>> doctest.master = None # Reset master.
2210
2211Verbosity can be increased with the optional `verbose` paremter:
2212
2213 >>> doctest.testfile('test_doctest.txt', globs=globs, verbose=True)
2214 Trying:
2215 favorite_color
2216 Expecting:
2217 'blue'
2218 ok
2219 Trying:
2220 if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00002221 print('a')
2222 print()
2223 print('b')
Edward Loper052d0cd2004-09-19 17:19:33 +00002224 Expecting:
2225 a
2226 <BLANKLINE>
2227 b
2228 ok
2229 1 items passed all tests:
2230 2 tests in test_doctest.txt
2231 2 tests in 1 items.
2232 2 passed and 0 failed.
2233 Test passed.
Christian Heimes25bb7832008-01-11 16:17:00 +00002234 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002235 >>> doctest.master = None # Reset master.
2236
2237The name of the test may be specified with the optional `name`
2238parameter:
2239
2240 >>> doctest.testfile('test_doctest.txt', name='newname')
2241 ... # doctest: +ELLIPSIS
2242 **********************************************************************
2243 File "...", line 6, in newname
2244 ...
Christian Heimes25bb7832008-01-11 16:17:00 +00002245 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002246 >>> doctest.master = None # Reset master.
2247
2248The summary report may be supressed with the optional `report`
2249parameter:
2250
2251 >>> doctest.testfile('test_doctest.txt', report=False)
2252 ... # doctest: +ELLIPSIS
2253 **********************************************************************
2254 File "...", line 6, in test_doctest.txt
2255 Failed example:
2256 favorite_color
2257 Exception raised:
2258 ...
2259 NameError: name 'favorite_color' is not defined
Christian Heimes25bb7832008-01-11 16:17:00 +00002260 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002261 >>> doctest.master = None # Reset master.
2262
2263The optional keyword argument `raise_on_error` can be used to raise an
2264exception on the first error (which may be useful for postmortem
2265debugging):
2266
2267 >>> doctest.testfile('test_doctest.txt', raise_on_error=True)
2268 ... # doctest: +ELLIPSIS
2269 Traceback (most recent call last):
Guido van Rossum6a2a2a02006-08-26 20:37:44 +00002270 doctest.UnexpectedException: ...
Edward Loper052d0cd2004-09-19 17:19:33 +00002271 >>> doctest.master = None # Reset master.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002272
2273If the tests contain non-ASCII characters, the tests might fail, since
2274it's unknown which encoding is used. The encoding can be specified
2275using the optional keyword argument `encoding`:
2276
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002277 >>> doctest.testfile('test_doctest4.txt', encoding='latin-1') # doctest: +ELLIPSIS
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002278 **********************************************************************
2279 File "...", line 7, in test_doctest4.txt
2280 Failed example:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002281 '...'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002282 Expected:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002283 'f\xf6\xf6'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002284 Got:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002285 'f\xc3\xb6\xc3\xb6'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002286 **********************************************************************
2287 ...
2288 **********************************************************************
2289 1 items had failures:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002290 2 of 2 in test_doctest4.txt
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002291 ***Test Failed*** 2 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002292 TestResults(failed=2, attempted=2)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002293 >>> doctest.master = None # Reset master.
2294
2295 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8')
Christian Heimes25bb7832008-01-11 16:17:00 +00002296 TestResults(failed=0, attempted=2)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002297 >>> doctest.master = None # Reset master.
Florent Xicluna59250852010-02-27 14:21:57 +00002298
2299Test the verbose output:
2300
2301 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8', verbose=True)
2302 Trying:
2303 'föö'
2304 Expecting:
2305 'f\xf6\xf6'
2306 ok
2307 Trying:
2308 'bąr'
2309 Expecting:
2310 'b\u0105r'
2311 ok
2312 1 items passed all tests:
2313 2 tests in test_doctest4.txt
2314 2 tests in 1 items.
2315 2 passed and 0 failed.
2316 Test passed.
2317 TestResults(failed=0, attempted=2)
2318 >>> doctest.master = None # Reset master.
2319 >>> sys.argv = save_argv
Edward Loper052d0cd2004-09-19 17:19:33 +00002320"""
2321
R. David Murray58641de2009-06-12 15:33:19 +00002322def test_testmod(): r"""
2323Tests for the testmod function. More might be useful, but for now we're just
2324testing the case raised by Issue 6195, where trying to doctest a C module would
2325fail with a UnicodeDecodeError because doctest tried to read the "source" lines
2326out of the binary module.
2327
2328 >>> import unicodedata
Florent Xicluna59250852010-02-27 14:21:57 +00002329 >>> doctest.testmod(unicodedata, verbose=False)
R. David Murray58641de2009-06-12 15:33:19 +00002330 TestResults(failed=0, attempted=0)
2331"""
2332
Tim Peters8485b562004-08-04 18:46:34 +00002333######################################################################
2334## Main
2335######################################################################
2336
2337def test_main():
2338 # Check the doctest cases in doctest itself:
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002339 support.run_doctest(doctest, verbosity=True)
Tim Peters8485b562004-08-04 18:46:34 +00002340 # Check the doctest cases defined here:
2341 from test import test_doctest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002342 support.run_doctest(test_doctest, verbosity=True)
Tim Peters8485b562004-08-04 18:46:34 +00002343
Guido van Rossum34d19282007-08-09 01:03:29 +00002344import trace, sys, re, io
Tim Peters8485b562004-08-04 18:46:34 +00002345def test_coverage(coverdir):
2346 tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
2347 trace=0, count=1)
Guido van Rossume7ba4952007-06-06 23:52:48 +00002348 tracer.run('test_main()')
Tim Peters8485b562004-08-04 18:46:34 +00002349 r = tracer.results()
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002350 print('Writing coverage results...')
Tim Peters8485b562004-08-04 18:46:34 +00002351 r.write_results(show_missing=True, summary=True,
2352 coverdir=coverdir)
2353
2354if __name__ == '__main__':
2355 if '-c' in sys.argv:
2356 test_coverage('/tmp/doctest.cover')
2357 else:
2358 test_main()