blob: 8dcc8a4f45854e2104e8cef59f8e130d54752aff [file] [log] [blame]
Tim Peters8485b562004-08-04 18:46:34 +00001"""
2Test script for doctest.
3"""
4
Benjamin Petersonee8712c2008-05-20 21:35:26 +00005from test import support
Tim Peters8485b562004-08-04 18:46:34 +00006import doctest
Tim Petersa7def722004-08-23 22:13:22 +00007import warnings
Tim Peters8485b562004-08-04 18:46:34 +00008
Nick Coghlanf088e5e2008-12-14 11:50:48 +00009# NOTE: There are some additional tests relating to interaction with
10# zipimport in the test_zipimport_support test module.
11
Tim Peters8485b562004-08-04 18:46:34 +000012######################################################################
13## Sample Objects (used by test cases)
14######################################################################
15
16def sample_func(v):
17 """
Tim Peters19397e52004-08-06 22:02:59 +000018 Blah blah
19
Guido van Rossum7131f842007-02-09 20:13:25 +000020 >>> print(sample_func(22))
Tim Peters8485b562004-08-04 18:46:34 +000021 44
Tim Peters19397e52004-08-06 22:02:59 +000022
23 Yee ha!
Tim Peters8485b562004-08-04 18:46:34 +000024 """
25 return v+v
26
27class SampleClass:
28 """
Guido van Rossum7131f842007-02-09 20:13:25 +000029 >>> print(1)
Tim Peters8485b562004-08-04 18:46:34 +000030 1
Edward Loper4ae900f2004-09-21 03:20:34 +000031
32 >>> # comments get ignored. so are empty PS1 and PS2 prompts:
33 >>>
34 ...
35
36 Multiline example:
37 >>> sc = SampleClass(3)
38 >>> for i in range(10):
39 ... sc = sc.double()
Guido van Rossum805365e2007-05-07 22:24:25 +000040 ... print(' ', sc.get(), sep='', end='')
41 6 12 24 48 96 192 384 768 1536 3072
Tim Peters8485b562004-08-04 18:46:34 +000042 """
43 def __init__(self, val):
44 """
Guido van Rossum7131f842007-02-09 20:13:25 +000045 >>> print(SampleClass(12).get())
Tim Peters8485b562004-08-04 18:46:34 +000046 12
47 """
48 self.val = val
49
50 def double(self):
51 """
Guido van Rossum7131f842007-02-09 20:13:25 +000052 >>> print(SampleClass(12).double().get())
Tim Peters8485b562004-08-04 18:46:34 +000053 24
54 """
55 return SampleClass(self.val + self.val)
56
57 def get(self):
58 """
Guido van Rossum7131f842007-02-09 20:13:25 +000059 >>> print(SampleClass(-5).get())
Tim Peters8485b562004-08-04 18:46:34 +000060 -5
61 """
62 return self.val
63
64 def a_staticmethod(v):
65 """
Guido van Rossum7131f842007-02-09 20:13:25 +000066 >>> print(SampleClass.a_staticmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +000067 11
68 """
69 return v+1
70 a_staticmethod = staticmethod(a_staticmethod)
71
72 def a_classmethod(cls, v):
73 """
Guido van Rossum7131f842007-02-09 20:13:25 +000074 >>> print(SampleClass.a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +000075 12
Guido van Rossum7131f842007-02-09 20:13:25 +000076 >>> print(SampleClass(0).a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +000077 12
78 """
79 return v+2
80 a_classmethod = classmethod(a_classmethod)
81
82 a_property = property(get, doc="""
Guido van Rossum7131f842007-02-09 20:13:25 +000083 >>> print(SampleClass(22).a_property)
Tim Peters8485b562004-08-04 18:46:34 +000084 22
85 """)
86
87 class NestedClass:
88 """
89 >>> x = SampleClass.NestedClass(5)
90 >>> y = x.square()
Guido van Rossum7131f842007-02-09 20:13:25 +000091 >>> print(y.get())
Tim Peters8485b562004-08-04 18:46:34 +000092 25
93 """
94 def __init__(self, val=0):
95 """
Guido van Rossum7131f842007-02-09 20:13:25 +000096 >>> print(SampleClass.NestedClass().get())
Tim Peters8485b562004-08-04 18:46:34 +000097 0
98 """
99 self.val = val
100 def square(self):
101 return SampleClass.NestedClass(self.val*self.val)
102 def get(self):
103 return self.val
104
105class SampleNewStyleClass(object):
106 r"""
Guido van Rossum7131f842007-02-09 20:13:25 +0000107 >>> print('1\n2\n3')
Tim Peters8485b562004-08-04 18:46:34 +0000108 1
109 2
110 3
111 """
112 def __init__(self, val):
113 """
Guido van Rossum7131f842007-02-09 20:13:25 +0000114 >>> print(SampleNewStyleClass(12).get())
Tim Peters8485b562004-08-04 18:46:34 +0000115 12
116 """
117 self.val = val
118
119 def double(self):
120 """
Guido van Rossum7131f842007-02-09 20:13:25 +0000121 >>> print(SampleNewStyleClass(12).double().get())
Tim Peters8485b562004-08-04 18:46:34 +0000122 24
123 """
124 return SampleNewStyleClass(self.val + self.val)
125
126 def get(self):
127 """
Guido van Rossum7131f842007-02-09 20:13:25 +0000128 >>> print(SampleNewStyleClass(-5).get())
Tim Peters8485b562004-08-04 18:46:34 +0000129 -5
130 """
131 return self.val
132
133######################################################################
Edward Loper2de91ba2004-08-27 02:07:46 +0000134## Fake stdin (for testing interactive debugging)
135######################################################################
136
137class _FakeInput:
138 """
139 A fake input stream for pdb's interactive debugger. Whenever a
140 line is read, print it (to simulate the user typing it), and then
141 return it. The set of lines to return is specified in the
142 constructor; they should not have trailing newlines.
143 """
144 def __init__(self, lines):
145 self.lines = lines
146
147 def readline(self):
148 line = self.lines.pop(0)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000149 print(line)
Edward Loper2de91ba2004-08-27 02:07:46 +0000150 return line+'\n'
151
152######################################################################
Tim Peters8485b562004-08-04 18:46:34 +0000153## Test Cases
154######################################################################
155
156def test_Example(): r"""
157Unit tests for the `Example` class.
158
Edward Lopera6b68322004-08-26 00:05:43 +0000159Example is a simple container class that holds:
160 - `source`: A source string.
161 - `want`: An expected output string.
162 - `exc_msg`: An expected exception message string (or None if no
163 exception is expected).
164 - `lineno`: A line number (within the docstring).
165 - `indent`: The example's indentation in the input string.
166 - `options`: An option dictionary, mapping option flags to True or
167 False.
Tim Peters8485b562004-08-04 18:46:34 +0000168
Edward Lopera6b68322004-08-26 00:05:43 +0000169These attributes are set by the constructor. `source` and `want` are
170required; the other attributes all have default values:
Tim Peters8485b562004-08-04 18:46:34 +0000171
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000172 >>> example = doctest.Example('print(1)', '1\n')
Edward Lopera6b68322004-08-26 00:05:43 +0000173 >>> (example.source, example.want, example.exc_msg,
174 ... example.lineno, example.indent, example.options)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000175 ('print(1)\n', '1\n', None, 0, 0, {})
Edward Lopera6b68322004-08-26 00:05:43 +0000176
177The first three attributes (`source`, `want`, and `exc_msg`) may be
178specified positionally; the remaining arguments should be specified as
179keyword arguments:
180
181 >>> exc_msg = 'IndexError: pop from an empty list'
182 >>> example = doctest.Example('[].pop()', '', exc_msg,
183 ... lineno=5, indent=4,
184 ... options={doctest.ELLIPSIS: True})
185 >>> (example.source, example.want, example.exc_msg,
186 ... example.lineno, example.indent, example.options)
187 ('[].pop()\n', '', 'IndexError: pop from an empty list\n', 5, 4, {8: True})
188
189The constructor normalizes the `source` string to end in a newline:
Tim Peters8485b562004-08-04 18:46:34 +0000190
Tim Petersbb431472004-08-09 03:51:46 +0000191 Source spans a single line: no terminating newline.
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000192 >>> e = doctest.Example('print(1)', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000193 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000194 ('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000195
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000196 >>> e = doctest.Example('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000197 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000198 ('print(1)\n', '1\n')
Tim Peters8485b562004-08-04 18:46:34 +0000199
Tim Petersbb431472004-08-09 03:51:46 +0000200 Source spans multiple lines: require terminating newline.
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000201 >>> e = doctest.Example('print(1);\nprint(2)\n', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000202 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000203 ('print(1);\nprint(2)\n', '1\n2\n')
Tim Peters8485b562004-08-04 18:46:34 +0000204
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000205 >>> e = doctest.Example('print(1);\nprint(2)', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000206 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000207 ('print(1);\nprint(2)\n', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000208
Edward Lopera6b68322004-08-26 00:05:43 +0000209 Empty source string (which should never appear in real examples)
210 >>> e = doctest.Example('', '')
211 >>> e.source, e.want
212 ('\n', '')
Tim Peters8485b562004-08-04 18:46:34 +0000213
Edward Lopera6b68322004-08-26 00:05:43 +0000214The constructor normalizes the `want` string to end in a newline,
215unless it's the empty string:
216
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000217 >>> e = doctest.Example('print(1)', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000218 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000219 ('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000220
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000221 >>> e = doctest.Example('print(1)', '1')
Tim Petersbb431472004-08-09 03:51:46 +0000222 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000223 ('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000224
Edward Lopera6b68322004-08-26 00:05:43 +0000225 >>> e = doctest.Example('print', '')
Tim Petersbb431472004-08-09 03:51:46 +0000226 >>> e.source, e.want
227 ('print\n', '')
Edward Lopera6b68322004-08-26 00:05:43 +0000228
229The constructor normalizes the `exc_msg` string to end in a newline,
230unless it's `None`:
231
232 Message spans one line
233 >>> exc_msg = 'IndexError: pop from an empty list'
234 >>> e = doctest.Example('[].pop()', '', exc_msg)
235 >>> e.exc_msg
236 'IndexError: pop from an empty list\n'
237
238 >>> exc_msg = 'IndexError: pop from an empty list\n'
239 >>> e = doctest.Example('[].pop()', '', exc_msg)
240 >>> e.exc_msg
241 'IndexError: pop from an empty list\n'
242
243 Message spans multiple lines
244 >>> exc_msg = 'ValueError: 1\n 2'
245 >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
246 >>> e.exc_msg
247 'ValueError: 1\n 2\n'
248
249 >>> exc_msg = 'ValueError: 1\n 2\n'
250 >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
251 >>> e.exc_msg
252 'ValueError: 1\n 2\n'
253
254 Empty (but non-None) exception message (which should never appear
255 in real examples)
256 >>> exc_msg = ''
257 >>> e = doctest.Example('raise X()', '', exc_msg)
258 >>> e.exc_msg
259 '\n'
Tim Peters8485b562004-08-04 18:46:34 +0000260"""
261
262def test_DocTest(): r"""
263Unit tests for the `DocTest` class.
264
265DocTest is a collection of examples, extracted from a docstring, along
266with information about where the docstring comes from (a name,
267filename, and line number). The docstring is parsed by the `DocTest`
268constructor:
269
270 >>> docstring = '''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000271 ... >>> print(12)
Tim Peters8485b562004-08-04 18:46:34 +0000272 ... 12
273 ...
274 ... Non-example text.
275 ...
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000276 ... >>> print('another\example')
Tim Peters8485b562004-08-04 18:46:34 +0000277 ... another
278 ... example
279 ... '''
280 >>> globs = {} # globals to run the test in.
Edward Lopera1ef6112004-08-09 16:14:41 +0000281 >>> parser = doctest.DocTestParser()
282 >>> test = parser.get_doctest(docstring, globs, 'some_test',
283 ... 'some_file', 20)
Guido van Rossum7131f842007-02-09 20:13:25 +0000284 >>> print(test)
Tim Peters8485b562004-08-04 18:46:34 +0000285 <DocTest some_test from some_file:20 (2 examples)>
286 >>> len(test.examples)
287 2
288 >>> e1, e2 = test.examples
289 >>> (e1.source, e1.want, e1.lineno)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000290 ('print(12)\n', '12\n', 1)
Tim Peters8485b562004-08-04 18:46:34 +0000291 >>> (e2.source, e2.want, e2.lineno)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000292 ("print('another\\example')\n", 'another\nexample\n', 6)
Tim Peters8485b562004-08-04 18:46:34 +0000293
294Source information (name, filename, and line number) is available as
295attributes on the doctest object:
296
297 >>> (test.name, test.filename, test.lineno)
298 ('some_test', 'some_file', 20)
299
300The line number of an example within its containing file is found by
301adding the line number of the example and the line number of its
302containing test:
303
304 >>> test.lineno + e1.lineno
305 21
306 >>> test.lineno + e2.lineno
307 26
308
309If the docstring contains inconsistant leading whitespace in the
310expected output of an example, then `DocTest` will raise a ValueError:
311
312 >>> docstring = r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000313 ... >>> print('bad\nindentation')
Tim Peters8485b562004-08-04 18:46:34 +0000314 ... bad
315 ... indentation
316 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000317 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000318 Traceback (most recent call last):
Edward Loper00f8da72004-08-26 18:05:07 +0000319 ValueError: line 4 of the docstring for some_test has inconsistent leading whitespace: 'indentation'
Tim Peters8485b562004-08-04 18:46:34 +0000320
321If the docstring contains inconsistent leading whitespace on
322continuation lines, then `DocTest` will raise a ValueError:
323
324 >>> docstring = r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000325 ... >>> print(('bad indentation',
326 ... ... 2))
Tim Peters8485b562004-08-04 18:46:34 +0000327 ... ('bad', 'indentation')
328 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000329 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000330 Traceback (most recent call last):
Guido van Rossume0192e52007-02-09 23:39:59 +0000331 ValueError: line 2 of the docstring for some_test has inconsistent leading whitespace: '... 2))'
Tim Peters8485b562004-08-04 18:46:34 +0000332
333If there's no blank space after a PS1 prompt ('>>>'), then `DocTest`
334will raise a ValueError:
335
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000336 >>> docstring = '>>>print(1)\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000337 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000338 Traceback (most recent call last):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000339 ValueError: line 1 of the docstring for some_test lacks blank after >>>: '>>>print(1)'
Edward Loper7c748462004-08-09 02:06:06 +0000340
341If there's no blank space after a PS2 prompt ('...'), then `DocTest`
342will raise a ValueError:
343
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000344 >>> docstring = '>>> if 1:\n...print(1)\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000345 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Edward Loper7c748462004-08-09 02:06:06 +0000346 Traceback (most recent call last):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000347 ValueError: line 2 of the docstring for some_test lacks blank after ...: '...print(1)'
Edward Loper7c748462004-08-09 02:06:06 +0000348
Tim Peters8485b562004-08-04 18:46:34 +0000349"""
350
Tim Peters8485b562004-08-04 18:46:34 +0000351def test_DocTestFinder(): r"""
352Unit tests for the `DocTestFinder` class.
353
354DocTestFinder is used to extract DocTests from an object's docstring
355and the docstrings of its contained objects. It can be used with
356modules, functions, classes, methods, staticmethods, classmethods, and
357properties.
358
359Finding Tests in Functions
360~~~~~~~~~~~~~~~~~~~~~~~~~~
361For a function whose docstring contains examples, DocTestFinder.find()
362will return a single test (for that function's docstring):
363
Tim Peters8485b562004-08-04 18:46:34 +0000364 >>> finder = doctest.DocTestFinder()
Jim Fulton07a349c2004-08-22 14:10:00 +0000365
366We'll simulate a __file__ attr that ends in pyc:
367
368 >>> import test.test_doctest
369 >>> old = test.test_doctest.__file__
370 >>> test.test_doctest.__file__ = 'test_doctest.pyc'
371
Tim Peters8485b562004-08-04 18:46:34 +0000372 >>> tests = finder.find(sample_func)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000373
Guido van Rossum7131f842007-02-09 20:13:25 +0000374 >>> print(tests) # doctest: +ELLIPSIS
Nick Coghlanf088e5e2008-12-14 11:50:48 +0000375 [<DocTest sample_func from ...:16 (1 example)>]
Edward Loper8e4a34b2004-08-12 02:34:27 +0000376
Tim Peters4de7c5c2004-08-23 22:38:05 +0000377The exact name depends on how test_doctest was invoked, so allow for
378leading path components.
379
380 >>> tests[0].filename # doctest: +ELLIPSIS
381 '...test_doctest.py'
Jim Fulton07a349c2004-08-22 14:10:00 +0000382
383 >>> test.test_doctest.__file__ = old
Tim Petersc6cbab02004-08-22 19:43:28 +0000384
Jim Fulton07a349c2004-08-22 14:10:00 +0000385
Tim Peters8485b562004-08-04 18:46:34 +0000386 >>> e = tests[0].examples[0]
Tim Petersbb431472004-08-09 03:51:46 +0000387 >>> (e.source, e.want, e.lineno)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000388 ('print(sample_func(22))\n', '44\n', 3)
Tim Peters8485b562004-08-04 18:46:34 +0000389
Edward Loper32ddbf72004-09-13 05:47:24 +0000390By default, tests are created for objects with no docstring:
Tim Peters8485b562004-08-04 18:46:34 +0000391
392 >>> def no_docstring(v):
393 ... pass
Tim Peters958cc892004-09-13 14:53:28 +0000394 >>> finder.find(no_docstring)
395 []
Edward Loper32ddbf72004-09-13 05:47:24 +0000396
397However, the optional argument `exclude_empty` to the DocTestFinder
398constructor can be used to exclude tests for objects with empty
399docstrings:
400
401 >>> def no_docstring(v):
402 ... pass
403 >>> excl_empty_finder = doctest.DocTestFinder(exclude_empty=True)
404 >>> excl_empty_finder.find(no_docstring)
Tim Peters8485b562004-08-04 18:46:34 +0000405 []
406
407If the function has a docstring with no examples, then a test with no
408examples is returned. (This lets `DocTestRunner` collect statistics
409about which functions have no tests -- but is that useful? And should
410an empty test also be created when there's no docstring?)
411
412 >>> def no_examples(v):
413 ... ''' no doctest examples '''
Tim Peters17b56372004-09-11 17:33:27 +0000414 >>> finder.find(no_examples) # doctest: +ELLIPSIS
415 [<DocTest no_examples from ...:1 (no examples)>]
Tim Peters8485b562004-08-04 18:46:34 +0000416
417Finding Tests in Classes
418~~~~~~~~~~~~~~~~~~~~~~~~
419For a class, DocTestFinder will create a test for the class's
420docstring, and will recursively explore its contents, including
421methods, classmethods, staticmethods, properties, and nested classes.
422
423 >>> finder = doctest.DocTestFinder()
424 >>> tests = finder.find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000425 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000426 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000427 3 SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000428 3 SampleClass.NestedClass
429 1 SampleClass.NestedClass.__init__
430 1 SampleClass.__init__
431 2 SampleClass.a_classmethod
432 1 SampleClass.a_property
433 1 SampleClass.a_staticmethod
434 1 SampleClass.double
435 1 SampleClass.get
436
437New-style classes are also supported:
438
439 >>> tests = finder.find(SampleNewStyleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000440 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000441 ... print('%2s %s' % (len(t.examples), t.name))
Tim Peters8485b562004-08-04 18:46:34 +0000442 1 SampleNewStyleClass
443 1 SampleNewStyleClass.__init__
444 1 SampleNewStyleClass.double
445 1 SampleNewStyleClass.get
446
447Finding Tests in Modules
448~~~~~~~~~~~~~~~~~~~~~~~~
449For a module, DocTestFinder will create a test for the class's
450docstring, and will recursively explore its contents, including
451functions, classes, and the `__test__` dictionary, if it exists:
452
453 >>> # A module
Christian Heimes45f9af32007-11-27 21:50:00 +0000454 >>> import types
455 >>> m = types.ModuleType('some_module')
Tim Peters8485b562004-08-04 18:46:34 +0000456 >>> def triple(val):
457 ... '''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000458 ... >>> print(triple(11))
Tim Peters8485b562004-08-04 18:46:34 +0000459 ... 33
460 ... '''
461 ... return val*3
462 >>> m.__dict__.update({
463 ... 'sample_func': sample_func,
464 ... 'SampleClass': SampleClass,
465 ... '__doc__': '''
466 ... Module docstring.
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000467 ... >>> print('module')
Tim Peters8485b562004-08-04 18:46:34 +0000468 ... module
469 ... ''',
470 ... '__test__': {
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000471 ... 'd': '>>> print(6)\n6\n>>> print(7)\n7\n',
Tim Peters8485b562004-08-04 18:46:34 +0000472 ... 'c': triple}})
473
474 >>> finder = doctest.DocTestFinder()
475 >>> # Use module=test.test_doctest, to prevent doctest from
476 >>> # ignoring the objects since they weren't defined in m.
477 >>> import test.test_doctest
478 >>> tests = finder.find(m, module=test.test_doctest)
Tim Peters8485b562004-08-04 18:46:34 +0000479 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000480 ... print('%2s %s' % (len(t.examples), t.name))
Tim Peters8485b562004-08-04 18:46:34 +0000481 1 some_module
Edward Loper4ae900f2004-09-21 03:20:34 +0000482 3 some_module.SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000483 3 some_module.SampleClass.NestedClass
484 1 some_module.SampleClass.NestedClass.__init__
485 1 some_module.SampleClass.__init__
486 2 some_module.SampleClass.a_classmethod
487 1 some_module.SampleClass.a_property
488 1 some_module.SampleClass.a_staticmethod
489 1 some_module.SampleClass.double
490 1 some_module.SampleClass.get
Tim Petersc5684782004-09-13 01:07:12 +0000491 1 some_module.__test__.c
492 2 some_module.__test__.d
Tim Peters8485b562004-08-04 18:46:34 +0000493 1 some_module.sample_func
494
495Duplicate Removal
496~~~~~~~~~~~~~~~~~
497If a single object is listed twice (under different names), then tests
498will only be generated for it once:
499
Tim Petersf3f57472004-08-08 06:11:48 +0000500 >>> from test import doctest_aliases
Edward Loper32ddbf72004-09-13 05:47:24 +0000501 >>> tests = excl_empty_finder.find(doctest_aliases)
Guido van Rossum7131f842007-02-09 20:13:25 +0000502 >>> print(len(tests))
Tim Peters8485b562004-08-04 18:46:34 +0000503 2
Guido van Rossum7131f842007-02-09 20:13:25 +0000504 >>> print(tests[0].name)
Tim Petersf3f57472004-08-08 06:11:48 +0000505 test.doctest_aliases.TwoNames
506
507 TwoNames.f and TwoNames.g are bound to the same object.
508 We can't guess which will be found in doctest's traversal of
509 TwoNames.__dict__ first, so we have to allow for either.
510
511 >>> tests[1].name.split('.')[-1] in ['f', 'g']
Tim Peters8485b562004-08-04 18:46:34 +0000512 True
513
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000514Empty Tests
515~~~~~~~~~~~
516By default, an object with no doctests doesn't create any tests:
Tim Peters8485b562004-08-04 18:46:34 +0000517
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000518 >>> tests = doctest.DocTestFinder().find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000519 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000520 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000521 3 SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000522 3 SampleClass.NestedClass
523 1 SampleClass.NestedClass.__init__
Tim Peters958cc892004-09-13 14:53:28 +0000524 1 SampleClass.__init__
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000525 2 SampleClass.a_classmethod
526 1 SampleClass.a_property
527 1 SampleClass.a_staticmethod
Tim Peters958cc892004-09-13 14:53:28 +0000528 1 SampleClass.double
529 1 SampleClass.get
530
531By default, that excluded objects with no doctests. exclude_empty=False
532tells it to include (empty) tests for objects with no doctests. This feature
533is really to support backward compatibility in what doctest.master.summarize()
534displays.
535
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000536 >>> tests = doctest.DocTestFinder(exclude_empty=False).find(SampleClass)
Tim Peters958cc892004-09-13 14:53:28 +0000537 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000538 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000539 3 SampleClass
Tim Peters958cc892004-09-13 14:53:28 +0000540 3 SampleClass.NestedClass
541 1 SampleClass.NestedClass.__init__
Edward Loper32ddbf72004-09-13 05:47:24 +0000542 0 SampleClass.NestedClass.get
543 0 SampleClass.NestedClass.square
Tim Peters8485b562004-08-04 18:46:34 +0000544 1 SampleClass.__init__
Tim Peters8485b562004-08-04 18:46:34 +0000545 2 SampleClass.a_classmethod
546 1 SampleClass.a_property
547 1 SampleClass.a_staticmethod
548 1 SampleClass.double
549 1 SampleClass.get
550
Tim Peters8485b562004-08-04 18:46:34 +0000551Turning off Recursion
552~~~~~~~~~~~~~~~~~~~~~
553DocTestFinder can be told not to look for tests in contained objects
554using the `recurse` flag:
555
556 >>> tests = doctest.DocTestFinder(recurse=False).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000557 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000558 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000559 3 SampleClass
Edward Loperb51b2342004-08-17 16:37:12 +0000560
561Line numbers
562~~~~~~~~~~~~
563DocTestFinder finds the line number of each example:
564
565 >>> def f(x):
566 ... '''
567 ... >>> x = 12
568 ...
569 ... some text
570 ...
571 ... >>> # examples are not created for comments & bare prompts.
572 ... >>>
573 ... ...
574 ...
575 ... >>> for x in range(10):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000576 ... ... print(x, end=' ')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000577 ... 0 1 2 3 4 5 6 7 8 9
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000578 ... >>> x//2
579 ... 6
Edward Loperb51b2342004-08-17 16:37:12 +0000580 ... '''
581 >>> test = doctest.DocTestFinder().find(f)[0]
582 >>> [e.lineno for e in test.examples]
583 [1, 9, 12]
Tim Peters8485b562004-08-04 18:46:34 +0000584"""
585
Edward Loper00f8da72004-08-26 18:05:07 +0000586def test_DocTestParser(): r"""
587Unit tests for the `DocTestParser` class.
588
589DocTestParser is used to parse docstrings containing doctest examples.
590
591The `parse` method divides a docstring into examples and intervening
592text:
593
594 >>> s = '''
595 ... >>> x, y = 2, 3 # no output expected
596 ... >>> if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000597 ... ... print(x)
598 ... ... print(y)
Edward Loper00f8da72004-08-26 18:05:07 +0000599 ... 2
600 ... 3
601 ...
602 ... Some text.
603 ... >>> x+y
604 ... 5
605 ... '''
606 >>> parser = doctest.DocTestParser()
607 >>> for piece in parser.parse(s):
608 ... if isinstance(piece, doctest.Example):
Guido van Rossum7131f842007-02-09 20:13:25 +0000609 ... print('Example:', (piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000610 ... else:
Guido van Rossum7131f842007-02-09 20:13:25 +0000611 ... print(' Text:', repr(piece))
Edward Loper00f8da72004-08-26 18:05:07 +0000612 Text: '\n'
613 Example: ('x, y = 2, 3 # no output expected\n', '', 1)
614 Text: ''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000615 Example: ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000616 Text: '\nSome text.\n'
617 Example: ('x+y\n', '5\n', 9)
618 Text: ''
619
620The `get_examples` method returns just the examples:
621
622 >>> for piece in parser.get_examples(s):
Guido van Rossum7131f842007-02-09 20:13:25 +0000623 ... print((piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000624 ('x, y = 2, 3 # no output expected\n', '', 1)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000625 ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000626 ('x+y\n', '5\n', 9)
627
628The `get_doctest` method creates a Test from the examples, along with the
629given arguments:
630
631 >>> test = parser.get_doctest(s, {}, 'name', 'filename', lineno=5)
632 >>> (test.name, test.filename, test.lineno)
633 ('name', 'filename', 5)
634 >>> for piece in test.examples:
Guido van Rossum7131f842007-02-09 20:13:25 +0000635 ... print((piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000636 ('x, y = 2, 3 # no output expected\n', '', 1)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000637 ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000638 ('x+y\n', '5\n', 9)
639"""
640
Tim Peters8485b562004-08-04 18:46:34 +0000641class test_DocTestRunner:
642 def basics(): r"""
643Unit tests for the `DocTestRunner` class.
644
645DocTestRunner is used to run DocTest test cases, and to accumulate
646statistics. Here's a simple DocTest case we can use:
647
648 >>> def f(x):
649 ... '''
650 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000651 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000652 ... 12
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000653 ... >>> x//2
654 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000655 ... '''
656 >>> test = doctest.DocTestFinder().find(f)[0]
657
658The main DocTestRunner interface is the `run` method, which runs a
659given DocTest case in a given namespace (globs). It returns a tuple
660`(f,t)`, where `f` is the number of failed tests and `t` is the number
661of tried tests.
662
663 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000664 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000665
666If any example produces incorrect output, then the test runner reports
667the failure and proceeds to the next example:
668
669 >>> def f(x):
670 ... '''
671 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000672 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000673 ... 14
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000674 ... >>> x//2
675 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000676 ... '''
677 >>> test = doctest.DocTestFinder().find(f)[0]
678 >>> doctest.DocTestRunner(verbose=True).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000679 ... # doctest: +ELLIPSIS
Edward Loperaacf0832004-08-26 01:19:50 +0000680 Trying:
681 x = 12
682 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000683 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000684 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000685 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000686 Expecting:
687 14
Tim Peters8485b562004-08-04 18:46:34 +0000688 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000689 File ..., line 4, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000690 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000691 print(x)
Jim Fulton07a349c2004-08-22 14:10:00 +0000692 Expected:
693 14
694 Got:
695 12
Edward Loperaacf0832004-08-26 01:19:50 +0000696 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000697 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000698 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000699 6
Tim Peters8485b562004-08-04 18:46:34 +0000700 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000701 TestResults(failed=1, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000702"""
703 def verbose_flag(): r"""
704The `verbose` flag makes the test runner generate more detailed
705output:
706
707 >>> def f(x):
708 ... '''
709 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000710 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000711 ... 12
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000712 ... >>> x//2
713 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000714 ... '''
715 >>> test = doctest.DocTestFinder().find(f)[0]
716
717 >>> doctest.DocTestRunner(verbose=True).run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000718 Trying:
719 x = 12
720 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000721 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000722 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000723 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000724 Expecting:
725 12
Tim Peters8485b562004-08-04 18:46:34 +0000726 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000727 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000728 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000729 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000730 6
Tim Peters8485b562004-08-04 18:46:34 +0000731 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000732 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000733
734If the `verbose` flag is unspecified, then the output will be verbose
735iff `-v` appears in sys.argv:
736
737 >>> # Save the real sys.argv list.
738 >>> old_argv = sys.argv
739
740 >>> # If -v does not appear in sys.argv, then output isn't verbose.
741 >>> sys.argv = ['test']
742 >>> doctest.DocTestRunner().run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000743 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000744
745 >>> # If -v does appear in sys.argv, then output is verbose.
746 >>> sys.argv = ['test', '-v']
747 >>> doctest.DocTestRunner().run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000748 Trying:
749 x = 12
750 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000751 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000752 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000753 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000754 Expecting:
755 12
Tim Peters8485b562004-08-04 18:46:34 +0000756 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000757 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000758 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000759 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000760 6
Tim Peters8485b562004-08-04 18:46:34 +0000761 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000762 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000763
764 >>> # Restore sys.argv
765 >>> sys.argv = old_argv
766
767In the remaining examples, the test runner's verbosity will be
768explicitly set, to ensure that the test behavior is consistent.
769 """
770 def exceptions(): r"""
771Tests of `DocTestRunner`'s exception handling.
772
773An expected exception is specified with a traceback message. The
774lines between the first line and the type/value may be omitted or
775replaced with any other string:
776
777 >>> def f(x):
778 ... '''
779 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000780 ... >>> print(x//0)
Tim Peters8485b562004-08-04 18:46:34 +0000781 ... Traceback (most recent call last):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000782 ... ZeroDivisionError: integer division or modulo by zero
Tim Peters8485b562004-08-04 18:46:34 +0000783 ... '''
784 >>> test = doctest.DocTestFinder().find(f)[0]
785 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000786 TestResults(failed=0, attempted=2)
Tim Peters8485b562004-08-04 18:46:34 +0000787
Edward Loper19b19582004-08-25 23:07:03 +0000788An example may not generate output before it raises an exception; if
789it does, then the traceback message will not be recognized as
790signaling an expected exception, so the example will be reported as an
791unexpected exception:
Tim Peters8485b562004-08-04 18:46:34 +0000792
793 >>> def f(x):
794 ... '''
795 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000796 ... >>> print('pre-exception output', x//0)
Tim Peters8485b562004-08-04 18:46:34 +0000797 ... pre-exception output
798 ... Traceback (most recent call last):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000799 ... ZeroDivisionError: integer division or modulo by zero
Tim Peters8485b562004-08-04 18:46:34 +0000800 ... '''
801 >>> test = doctest.DocTestFinder().find(f)[0]
802 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper19b19582004-08-25 23:07:03 +0000803 ... # doctest: +ELLIPSIS
804 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000805 File ..., line 4, in f
Edward Loper19b19582004-08-25 23:07:03 +0000806 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000807 print('pre-exception output', x//0)
Edward Loper19b19582004-08-25 23:07:03 +0000808 Exception raised:
809 ...
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000810 ZeroDivisionError: integer division or modulo by zero
Christian Heimes25bb7832008-01-11 16:17:00 +0000811 TestResults(failed=1, attempted=2)
Tim Peters8485b562004-08-04 18:46:34 +0000812
813Exception messages may contain newlines:
814
815 >>> def f(x):
816 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000817 ... >>> raise ValueError('multi\nline\nmessage')
Tim Peters8485b562004-08-04 18:46:34 +0000818 ... Traceback (most recent call last):
819 ... ValueError: multi
820 ... line
821 ... message
822 ... '''
823 >>> test = doctest.DocTestFinder().find(f)[0]
824 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000825 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000826
827If an exception is expected, but an exception with the wrong type or
828message is raised, then it is reported as a failure:
829
830 >>> def f(x):
831 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000832 ... >>> raise ValueError('message')
Tim Peters8485b562004-08-04 18:46:34 +0000833 ... Traceback (most recent call last):
834 ... ValueError: wrong message
835 ... '''
836 >>> test = doctest.DocTestFinder().find(f)[0]
837 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000838 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000839 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000840 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000841 Failed example:
Collin Winter3add4d72007-08-29 23:37:32 +0000842 raise ValueError('message')
Tim Peters8485b562004-08-04 18:46:34 +0000843 Expected:
844 Traceback (most recent call last):
845 ValueError: wrong message
846 Got:
847 Traceback (most recent call last):
Edward Loper8e4a34b2004-08-12 02:34:27 +0000848 ...
Tim Peters8485b562004-08-04 18:46:34 +0000849 ValueError: message
Christian Heimes25bb7832008-01-11 16:17:00 +0000850 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000851
Tim Peters1fbf9c52004-09-04 17:21:02 +0000852However, IGNORE_EXCEPTION_DETAIL can be used to allow a mismatch in the
853detail:
854
855 >>> def f(x):
856 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000857 ... >>> raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +0000858 ... Traceback (most recent call last):
859 ... ValueError: wrong message
860 ... '''
861 >>> test = doctest.DocTestFinder().find(f)[0]
862 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000863 TestResults(failed=0, attempted=1)
Tim Peters1fbf9c52004-09-04 17:21:02 +0000864
865But IGNORE_EXCEPTION_DETAIL does not allow a mismatch in the exception type:
866
867 >>> def f(x):
868 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000869 ... >>> raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +0000870 ... Traceback (most recent call last):
871 ... TypeError: wrong type
872 ... '''
873 >>> test = doctest.DocTestFinder().find(f)[0]
874 >>> doctest.DocTestRunner(verbose=False).run(test)
875 ... # doctest: +ELLIPSIS
876 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000877 File ..., line 3, in f
Tim Peters1fbf9c52004-09-04 17:21:02 +0000878 Failed example:
Collin Winter3add4d72007-08-29 23:37:32 +0000879 raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +0000880 Expected:
881 Traceback (most recent call last):
882 TypeError: wrong type
883 Got:
884 Traceback (most recent call last):
885 ...
886 ValueError: message
Christian Heimes25bb7832008-01-11 16:17:00 +0000887 TestResults(failed=1, attempted=1)
Tim Peters1fbf9c52004-09-04 17:21:02 +0000888
Tim Peters8485b562004-08-04 18:46:34 +0000889If an exception is raised but not expected, then it is reported as an
890unexpected exception:
891
Tim Peters8485b562004-08-04 18:46:34 +0000892 >>> def f(x):
893 ... r'''
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000894 ... >>> 1//0
Tim Peters8485b562004-08-04 18:46:34 +0000895 ... 0
896 ... '''
897 >>> test = doctest.DocTestFinder().find(f)[0]
898 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper74bca7a2004-08-12 02:27:44 +0000899 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000900 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000901 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000902 Failed example:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000903 1//0
Tim Peters8485b562004-08-04 18:46:34 +0000904 Exception raised:
905 Traceback (most recent call last):
Jim Fulton07a349c2004-08-22 14:10:00 +0000906 ...
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000907 ZeroDivisionError: integer division or modulo by zero
Christian Heimes25bb7832008-01-11 16:17:00 +0000908 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000909"""
910 def optionflags(): r"""
911Tests of `DocTestRunner`'s option flag handling.
912
913Several option flags can be used to customize the behavior of the test
914runner. These are defined as module constants in doctest, and passed
Christian Heimesfaf2f632008-01-06 16:59:19 +0000915to the DocTestRunner constructor (multiple constants should be ORed
Tim Peters8485b562004-08-04 18:46:34 +0000916together).
917
918The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
919and 1/0:
920
921 >>> def f(x):
922 ... '>>> True\n1\n'
923
924 >>> # Without the flag:
925 >>> test = doctest.DocTestFinder().find(f)[0]
926 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000927 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000928
929 >>> # With the flag:
930 >>> test = doctest.DocTestFinder().find(f)[0]
931 >>> flags = doctest.DONT_ACCEPT_TRUE_FOR_1
932 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000933 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000934 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000935 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000936 Failed example:
937 True
938 Expected:
939 1
940 Got:
941 True
Christian Heimes25bb7832008-01-11 16:17:00 +0000942 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000943
944The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines
945and the '<BLANKLINE>' marker:
946
947 >>> def f(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000948 ... '>>> print("a\\n\\nb")\na\n<BLANKLINE>\nb\n'
Tim Peters8485b562004-08-04 18:46:34 +0000949
950 >>> # Without the flag:
951 >>> test = doctest.DocTestFinder().find(f)[0]
952 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000953 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000954
955 >>> # With the flag:
956 >>> test = doctest.DocTestFinder().find(f)[0]
957 >>> flags = doctest.DONT_ACCEPT_BLANKLINE
958 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000959 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000960 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000961 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000962 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000963 print("a\n\nb")
Tim Peters8485b562004-08-04 18:46:34 +0000964 Expected:
965 a
966 <BLANKLINE>
967 b
968 Got:
969 a
970 <BLANKLINE>
971 b
Christian Heimes25bb7832008-01-11 16:17:00 +0000972 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000973
974The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be
975treated as equal:
976
977 >>> def f(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000978 ... '>>> print(1, 2, 3)\n 1 2\n 3'
Tim Peters8485b562004-08-04 18:46:34 +0000979
980 >>> # Without the flag:
981 >>> test = doctest.DocTestFinder().find(f)[0]
982 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000983 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000984 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000985 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000986 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000987 print(1, 2, 3)
Tim Peters8485b562004-08-04 18:46:34 +0000988 Expected:
989 1 2
990 3
Jim Fulton07a349c2004-08-22 14:10:00 +0000991 Got:
992 1 2 3
Christian Heimes25bb7832008-01-11 16:17:00 +0000993 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000994
995 >>> # With the flag:
996 >>> test = doctest.DocTestFinder().find(f)[0]
997 >>> flags = doctest.NORMALIZE_WHITESPACE
998 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000999 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001000
Tim Peters026f8dc2004-08-19 16:38:58 +00001001 An example from the docs:
Guido van Rossum805365e2007-05-07 22:24:25 +00001002 >>> print(list(range(20))) #doctest: +NORMALIZE_WHITESPACE
Tim Peters026f8dc2004-08-19 16:38:58 +00001003 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
1004 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
1005
Tim Peters8485b562004-08-04 18:46:34 +00001006The ELLIPSIS flag causes ellipsis marker ("...") in the expected
1007output to match any substring in the actual output:
1008
1009 >>> def f(x):
Guido van Rossum805365e2007-05-07 22:24:25 +00001010 ... '>>> print(list(range(15)))\n[0, 1, 2, ..., 14]\n'
Tim Peters8485b562004-08-04 18:46:34 +00001011
1012 >>> # Without the flag:
1013 >>> test = doctest.DocTestFinder().find(f)[0]
1014 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001015 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001016 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001017 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001018 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001019 print(list(range(15)))
Jim Fulton07a349c2004-08-22 14:10:00 +00001020 Expected:
1021 [0, 1, 2, ..., 14]
1022 Got:
1023 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
Christian Heimes25bb7832008-01-11 16:17:00 +00001024 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001025
1026 >>> # With the flag:
1027 >>> test = doctest.DocTestFinder().find(f)[0]
1028 >>> flags = doctest.ELLIPSIS
1029 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001030 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001031
Tim Peterse594bee2004-08-22 01:47:51 +00001032 ... also matches nothing:
Tim Peters1cf3aa62004-08-19 06:49:33 +00001033
Guido van Rossume0192e52007-02-09 23:39:59 +00001034 >>> if 1:
1035 ... for i in range(100):
1036 ... print(i**2, end=' ') #doctest: +ELLIPSIS
1037 ... print('!')
1038 0 1...4...9 16 ... 36 49 64 ... 9801 !
Tim Peters1cf3aa62004-08-19 06:49:33 +00001039
Tim Peters026f8dc2004-08-19 16:38:58 +00001040 ... can be surprising; e.g., this test passes:
Tim Peters26b3ebb2004-08-19 08:10:08 +00001041
Guido van Rossume0192e52007-02-09 23:39:59 +00001042 >>> if 1: #doctest: +ELLIPSIS
1043 ... for i in range(20):
1044 ... print(i, end=' ')
1045 ... print(20)
Tim Peterse594bee2004-08-22 01:47:51 +00001046 0 1 2 ...1...2...0
Tim Peters26b3ebb2004-08-19 08:10:08 +00001047
Tim Peters026f8dc2004-08-19 16:38:58 +00001048 Examples from the docs:
1049
Guido van Rossum805365e2007-05-07 22:24:25 +00001050 >>> print(list(range(20))) # doctest:+ELLIPSIS
Tim Peters026f8dc2004-08-19 16:38:58 +00001051 [0, 1, ..., 18, 19]
1052
Guido van Rossum805365e2007-05-07 22:24:25 +00001053 >>> print(list(range(20))) # doctest: +ELLIPSIS
Tim Peters026f8dc2004-08-19 16:38:58 +00001054 ... # doctest: +NORMALIZE_WHITESPACE
1055 [0, 1, ..., 18, 19]
1056
Thomas Wouters477c8d52006-05-27 19:21:47 +00001057The SKIP flag causes an example to be skipped entirely. I.e., the
1058example is not run. It can be useful in contexts where doctest
1059examples serve as both documentation and test cases, and an example
1060should be included for documentation purposes, but should not be
1061checked (e.g., because its output is random, or depends on resources
1062which would be unavailable.) The SKIP flag can also be used for
1063'commenting out' broken examples.
1064
1065 >>> import unavailable_resource # doctest: +SKIP
1066 >>> unavailable_resource.do_something() # doctest: +SKIP
1067 >>> unavailable_resource.blow_up() # doctest: +SKIP
1068 Traceback (most recent call last):
1069 ...
1070 UncheckedBlowUpError: Nobody checks me.
1071
1072 >>> import random
Guido van Rossum7131f842007-02-09 20:13:25 +00001073 >>> print(random.random()) # doctest: +SKIP
Thomas Wouters477c8d52006-05-27 19:21:47 +00001074 0.721216923889
1075
Edward Loper71f55af2004-08-26 01:41:51 +00001076The REPORT_UDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001077and actual outputs to be displayed using a unified diff:
1078
1079 >>> def f(x):
1080 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001081 ... >>> print('\n'.join('abcdefg'))
Tim Peters8485b562004-08-04 18:46:34 +00001082 ... a
1083 ... B
1084 ... c
1085 ... d
1086 ... f
1087 ... g
1088 ... h
1089 ... '''
1090
1091 >>> # Without the flag:
1092 >>> test = doctest.DocTestFinder().find(f)[0]
1093 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001094 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001095 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001096 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001097 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001098 print('\n'.join('abcdefg'))
Tim Peters8485b562004-08-04 18:46:34 +00001099 Expected:
1100 a
1101 B
1102 c
1103 d
1104 f
1105 g
1106 h
1107 Got:
1108 a
1109 b
1110 c
1111 d
1112 e
1113 f
1114 g
Christian Heimes25bb7832008-01-11 16:17:00 +00001115 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001116
1117 >>> # With the flag:
1118 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001119 >>> flags = doctest.REPORT_UDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001120 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001121 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001122 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001123 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001124 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001125 print('\n'.join('abcdefg'))
Edward Loper56629292004-08-26 01:31:56 +00001126 Differences (unified diff with -expected +actual):
Tim Peterse7edcb82004-08-26 05:44:27 +00001127 @@ -1,7 +1,7 @@
Tim Peters8485b562004-08-04 18:46:34 +00001128 a
1129 -B
1130 +b
1131 c
1132 d
1133 +e
1134 f
1135 g
1136 -h
Christian Heimes25bb7832008-01-11 16:17:00 +00001137 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001138
Edward Loper71f55af2004-08-26 01:41:51 +00001139The REPORT_CDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001140and actual outputs to be displayed using a context diff:
1141
Edward Loper71f55af2004-08-26 01:41:51 +00001142 >>> # Reuse f() from the REPORT_UDIFF example, above.
Tim Peters8485b562004-08-04 18:46:34 +00001143 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001144 >>> flags = doctest.REPORT_CDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001145 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001146 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001147 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001148 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001149 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001150 print('\n'.join('abcdefg'))
Edward Loper56629292004-08-26 01:31:56 +00001151 Differences (context diff with expected followed by actual):
Tim Peters8485b562004-08-04 18:46:34 +00001152 ***************
Tim Peterse7edcb82004-08-26 05:44:27 +00001153 *** 1,7 ****
Tim Peters8485b562004-08-04 18:46:34 +00001154 a
1155 ! B
1156 c
1157 d
1158 f
1159 g
1160 - h
Tim Peterse7edcb82004-08-26 05:44:27 +00001161 --- 1,7 ----
Tim Peters8485b562004-08-04 18:46:34 +00001162 a
1163 ! b
1164 c
1165 d
1166 + e
1167 f
1168 g
Christian Heimes25bb7832008-01-11 16:17:00 +00001169 TestResults(failed=1, attempted=1)
Tim Petersc6cbab02004-08-22 19:43:28 +00001170
1171
Edward Loper71f55af2004-08-26 01:41:51 +00001172The REPORT_NDIFF flag causes failures to use the difflib.Differ algorithm
Tim Petersc6cbab02004-08-22 19:43:28 +00001173used by the popular ndiff.py utility. This does intraline difference
1174marking, as well as interline differences.
1175
1176 >>> def f(x):
1177 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001178 ... >>> print("a b c d e f g h i j k l m")
Tim Petersc6cbab02004-08-22 19:43:28 +00001179 ... a b c d e f g h i j k 1 m
1180 ... '''
1181 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001182 >>> flags = doctest.REPORT_NDIFF
Tim Petersc6cbab02004-08-22 19:43:28 +00001183 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001184 ... # doctest: +ELLIPSIS
Tim Petersc6cbab02004-08-22 19:43:28 +00001185 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001186 File ..., line 3, in f
Tim Petersc6cbab02004-08-22 19:43:28 +00001187 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001188 print("a b c d e f g h i j k l m")
Tim Petersc6cbab02004-08-22 19:43:28 +00001189 Differences (ndiff with -expected +actual):
1190 - a b c d e f g h i j k 1 m
1191 ? ^
1192 + a b c d e f g h i j k l m
1193 ? + ++ ^
Christian Heimes25bb7832008-01-11 16:17:00 +00001194 TestResults(failed=1, attempted=1)
Edward Lopera89f88d2004-08-26 02:45:51 +00001195
1196The REPORT_ONLY_FIRST_FAILURE supresses result output after the first
1197failing example:
1198
1199 >>> def f(x):
1200 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001201 ... >>> print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001202 ... 1
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001203 ... >>> print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001204 ... 200
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001205 ... >>> print(3) # second failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001206 ... 300
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001207 ... >>> print(4) # second success
Edward Lopera89f88d2004-08-26 02:45:51 +00001208 ... 4
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001209 ... >>> print(5) # third failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001210 ... 500
1211 ... '''
1212 >>> test = doctest.DocTestFinder().find(f)[0]
1213 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1214 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001215 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001216 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001217 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001218 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001219 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001220 Expected:
1221 200
1222 Got:
1223 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001224 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001225
1226However, output from `report_start` is not supressed:
1227
1228 >>> doctest.DocTestRunner(verbose=True, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001229 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001230 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001231 print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001232 Expecting:
1233 1
1234 ok
1235 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001236 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001237 Expecting:
1238 200
1239 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001240 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001241 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001242 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001243 Expected:
1244 200
1245 Got:
1246 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001247 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001248
1249For the purposes of REPORT_ONLY_FIRST_FAILURE, unexpected exceptions
1250count as failures:
1251
1252 >>> def f(x):
1253 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001254 ... >>> print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001255 ... 1
1256 ... >>> raise ValueError(2) # first failure
1257 ... 200
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001258 ... >>> print(3) # second failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001259 ... 300
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001260 ... >>> print(4) # second success
Edward Lopera89f88d2004-08-26 02:45:51 +00001261 ... 4
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001262 ... >>> print(5) # third failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001263 ... 500
1264 ... '''
1265 >>> test = doctest.DocTestFinder().find(f)[0]
1266 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1267 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1268 ... # doctest: +ELLIPSIS
1269 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001270 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001271 Failed example:
1272 raise ValueError(2) # first failure
1273 Exception raised:
1274 ...
1275 ValueError: 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001276 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001277
Thomas Wouters477c8d52006-05-27 19:21:47 +00001278New option flags can also be registered, via register_optionflag(). Here
1279we reach into doctest's internals a bit.
1280
1281 >>> unlikely = "UNLIKELY_OPTION_NAME"
1282 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1283 False
1284 >>> new_flag_value = doctest.register_optionflag(unlikely)
1285 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1286 True
1287
1288Before 2.4.4/2.5, registering a name more than once erroneously created
1289more than one flag value. Here we verify that's fixed:
1290
1291 >>> redundant_flag_value = doctest.register_optionflag(unlikely)
1292 >>> redundant_flag_value == new_flag_value
1293 True
1294
1295Clean up.
1296 >>> del doctest.OPTIONFLAGS_BY_NAME[unlikely]
1297
Tim Petersc6cbab02004-08-22 19:43:28 +00001298 """
1299
Tim Peters8485b562004-08-04 18:46:34 +00001300 def option_directives(): r"""
1301Tests of `DocTestRunner`'s option directive mechanism.
1302
Edward Loper74bca7a2004-08-12 02:27:44 +00001303Option directives can be used to turn option flags on or off for a
1304single example. To turn an option on for an example, follow that
1305example with a comment of the form ``# doctest: +OPTION``:
Tim Peters8485b562004-08-04 18:46:34 +00001306
1307 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001308 ... >>> print(list(range(10))) # should fail: no ellipsis
Edward Loper74bca7a2004-08-12 02:27:44 +00001309 ... [0, 1, ..., 9]
1310 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001311 ... >>> print(list(range(10))) # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001312 ... [0, 1, ..., 9]
1313 ... '''
1314 >>> test = doctest.DocTestFinder().find(f)[0]
1315 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001316 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001317 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001318 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001319 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001320 print(list(range(10))) # should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001321 Expected:
1322 [0, 1, ..., 9]
1323 Got:
1324 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001325 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001326
1327To turn an option off for an example, follow that example with a
1328comment of the form ``# doctest: -OPTION``:
1329
1330 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001331 ... >>> print(list(range(10)))
Edward Loper74bca7a2004-08-12 02:27:44 +00001332 ... [0, 1, ..., 9]
1333 ...
1334 ... >>> # should fail: no ellipsis
Guido van Rossum805365e2007-05-07 22:24:25 +00001335 ... >>> print(list(range(10))) # doctest: -ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001336 ... [0, 1, ..., 9]
1337 ... '''
1338 >>> test = doctest.DocTestFinder().find(f)[0]
1339 >>> doctest.DocTestRunner(verbose=False,
1340 ... optionflags=doctest.ELLIPSIS).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001341 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001342 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001343 File ..., line 6, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001344 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001345 print(list(range(10))) # doctest: -ELLIPSIS
Jim Fulton07a349c2004-08-22 14:10:00 +00001346 Expected:
1347 [0, 1, ..., 9]
1348 Got:
1349 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001350 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001351
1352Option directives affect only the example that they appear with; they
1353do not change the options for surrounding examples:
Edward Loper8e4a34b2004-08-12 02:34:27 +00001354
Edward Loper74bca7a2004-08-12 02:27:44 +00001355 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001356 ... >>> print(list(range(10))) # Should fail: no ellipsis
Tim Peters8485b562004-08-04 18:46:34 +00001357 ... [0, 1, ..., 9]
1358 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001359 ... >>> print(list(range(10))) # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001360 ... [0, 1, ..., 9]
1361 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001362 ... >>> print(list(range(10))) # Should fail: no ellipsis
Tim Peters8485b562004-08-04 18:46:34 +00001363 ... [0, 1, ..., 9]
1364 ... '''
1365 >>> test = doctest.DocTestFinder().find(f)[0]
1366 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001367 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001368 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001369 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001370 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001371 print(list(range(10))) # Should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001372 Expected:
1373 [0, 1, ..., 9]
1374 Got:
1375 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001376 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001377 File ..., line 8, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001378 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001379 print(list(range(10))) # Should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001380 Expected:
1381 [0, 1, ..., 9]
1382 Got:
1383 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001384 TestResults(failed=2, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +00001385
Edward Loper74bca7a2004-08-12 02:27:44 +00001386Multiple options may be modified by a single option directive. They
1387may be separated by whitespace, commas, or both:
Tim Peters8485b562004-08-04 18:46:34 +00001388
1389 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001390 ... >>> print(list(range(10))) # Should fail
Tim Peters8485b562004-08-04 18:46:34 +00001391 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001392 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001393 ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001394 ... [0, 1, ..., 9]
1395 ... '''
1396 >>> test = doctest.DocTestFinder().find(f)[0]
1397 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001398 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001399 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001400 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001401 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001402 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001403 Expected:
1404 [0, 1, ..., 9]
1405 Got:
1406 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001407 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001408
1409 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001410 ... >>> print(list(range(10))) # Should fail
Edward Loper74bca7a2004-08-12 02:27:44 +00001411 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001412 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001413 ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
1414 ... [0, 1, ..., 9]
1415 ... '''
1416 >>> test = doctest.DocTestFinder().find(f)[0]
1417 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001418 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001419 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001420 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001421 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001422 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001423 Expected:
1424 [0, 1, ..., 9]
1425 Got:
1426 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001427 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001428
1429 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001430 ... >>> print(list(range(10))) # Should fail
Edward Loper74bca7a2004-08-12 02:27:44 +00001431 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001432 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001433 ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1434 ... [0, 1, ..., 9]
1435 ... '''
1436 >>> test = doctest.DocTestFinder().find(f)[0]
1437 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001438 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001439 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001440 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001441 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001442 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001443 Expected:
1444 [0, 1, ..., 9]
1445 Got:
1446 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001447 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001448
1449The option directive may be put on the line following the source, as
1450long as a continuation prompt is used:
1451
1452 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001453 ... >>> print(list(range(10)))
Edward Loper74bca7a2004-08-12 02:27:44 +00001454 ... ... # doctest: +ELLIPSIS
1455 ... [0, 1, ..., 9]
1456 ... '''
1457 >>> test = doctest.DocTestFinder().find(f)[0]
1458 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001459 TestResults(failed=0, attempted=1)
Edward Loper8e4a34b2004-08-12 02:34:27 +00001460
Edward Loper74bca7a2004-08-12 02:27:44 +00001461For examples with multi-line source, the option directive may appear
1462at the end of any line:
1463
1464 >>> def f(x): r'''
1465 ... >>> for x in range(10): # doctest: +ELLIPSIS
Guido van Rossum805365e2007-05-07 22:24:25 +00001466 ... ... print(' ', x, end='', sep='')
1467 ... 0 1 2 ... 9
Edward Loper74bca7a2004-08-12 02:27:44 +00001468 ...
1469 ... >>> for x in range(10):
Guido van Rossum805365e2007-05-07 22:24:25 +00001470 ... ... print(' ', x, end='', sep='') # doctest: +ELLIPSIS
1471 ... 0 1 2 ... 9
Edward Loper74bca7a2004-08-12 02:27:44 +00001472 ... '''
1473 >>> test = doctest.DocTestFinder().find(f)[0]
1474 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001475 TestResults(failed=0, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001476
1477If more than one line of an example with multi-line source has an
1478option directive, then they are combined:
1479
1480 >>> def f(x): r'''
1481 ... Should fail (option directive not on the last line):
1482 ... >>> for x in range(10): # doctest: +ELLIPSIS
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001483 ... ... print(x, end=' ') # doctest: +NORMALIZE_WHITESPACE
Guido van Rossumd8faa362007-04-27 19:54:29 +00001484 ... 0 1 2...9
Edward Loper74bca7a2004-08-12 02:27:44 +00001485 ... '''
1486 >>> test = doctest.DocTestFinder().find(f)[0]
1487 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001488 TestResults(failed=0, attempted=1)
Edward Loper74bca7a2004-08-12 02:27:44 +00001489
1490It is an error to have a comment of the form ``# doctest:`` that is
1491*not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
1492``OPTION`` is an option that has been registered with
1493`register_option`:
1494
1495 >>> # Error: Option not registered
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001496 >>> s = '>>> print(12) #doctest: +BADOPTION'
Edward Loper74bca7a2004-08-12 02:27:44 +00001497 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1498 Traceback (most recent call last):
1499 ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
1500
1501 >>> # Error: No + or - prefix
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001502 >>> s = '>>> print(12) #doctest: ELLIPSIS'
Edward Loper74bca7a2004-08-12 02:27:44 +00001503 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1504 Traceback (most recent call last):
1505 ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
1506
1507It is an error to use an option directive on a line that contains no
1508source:
1509
1510 >>> s = '>>> # doctest: +ELLIPSIS'
1511 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1512 Traceback (most recent call last):
1513 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 +00001514"""
1515
1516def test_testsource(): r"""
1517Unit tests for `testsource()`.
1518
1519The testsource() function takes a module and a name, finds the (first)
Tim Peters19397e52004-08-06 22:02:59 +00001520test with that name in that module, and converts it to a script. The
1521example code is converted to regular Python code. The surrounding
1522words and expected output are converted to comments:
Tim Peters8485b562004-08-04 18:46:34 +00001523
1524 >>> import test.test_doctest
1525 >>> name = 'test.test_doctest.sample_func'
Guido van Rossum7131f842007-02-09 20:13:25 +00001526 >>> print(doctest.testsource(test.test_doctest, name))
Edward Lopera5db6002004-08-12 02:41:30 +00001527 # Blah blah
Tim Peters19397e52004-08-06 22:02:59 +00001528 #
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001529 print(sample_func(22))
Tim Peters8485b562004-08-04 18:46:34 +00001530 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001531 ## 44
Tim Peters19397e52004-08-06 22:02:59 +00001532 #
Edward Lopera5db6002004-08-12 02:41:30 +00001533 # Yee ha!
Georg Brandlecf93c72005-06-26 23:09:51 +00001534 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001535
1536 >>> name = 'test.test_doctest.SampleNewStyleClass'
Guido van Rossum7131f842007-02-09 20:13:25 +00001537 >>> print(doctest.testsource(test.test_doctest, name))
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001538 print('1\n2\n3')
Tim Peters8485b562004-08-04 18:46:34 +00001539 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001540 ## 1
1541 ## 2
1542 ## 3
Georg Brandlecf93c72005-06-26 23:09:51 +00001543 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001544
1545 >>> name = 'test.test_doctest.SampleClass.a_classmethod'
Guido van Rossum7131f842007-02-09 20:13:25 +00001546 >>> print(doctest.testsource(test.test_doctest, name))
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001547 print(SampleClass.a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +00001548 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001549 ## 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001550 print(SampleClass(0).a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +00001551 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001552 ## 12
Georg Brandlecf93c72005-06-26 23:09:51 +00001553 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001554"""
1555
1556def test_debug(): r"""
1557
1558Create a docstring that we want to debug:
1559
1560 >>> s = '''
1561 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001562 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +00001563 ... 12
1564 ... '''
1565
1566Create some fake stdin input, to feed to the debugger:
1567
Tim Peters8485b562004-08-04 18:46:34 +00001568 >>> real_stdin = sys.stdin
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001569 >>> sys.stdin = _FakeInput(['next', 'print(x)', 'continue'])
Tim Peters8485b562004-08-04 18:46:34 +00001570
1571Run the debugger on the docstring, and then restore sys.stdin.
1572
Edward Loper2de91ba2004-08-27 02:07:46 +00001573 >>> try: doctest.debug_src(s)
1574 ... finally: sys.stdin = real_stdin
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001575 > <string>(1)<module>()
Edward Loper2de91ba2004-08-27 02:07:46 +00001576 (Pdb) next
1577 12
Tim Peters8485b562004-08-04 18:46:34 +00001578 --Return--
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001579 > <string>(1)<module>()->None
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001580 (Pdb) print(x)
Edward Loper2de91ba2004-08-27 02:07:46 +00001581 12
1582 (Pdb) continue
Tim Peters8485b562004-08-04 18:46:34 +00001583
1584"""
1585
Jim Fulton356fd192004-08-09 11:34:47 +00001586def test_pdb_set_trace():
Tim Peters50c6bdb2004-11-08 22:07:37 +00001587 """Using pdb.set_trace from a doctest.
Jim Fulton356fd192004-08-09 11:34:47 +00001588
Tim Peters413ced62004-08-09 15:43:47 +00001589 You can use pdb.set_trace from a doctest. To do so, you must
Jim Fulton356fd192004-08-09 11:34:47 +00001590 retrieve the set_trace function from the pdb module at the time
Tim Peters413ced62004-08-09 15:43:47 +00001591 you use it. The doctest module changes sys.stdout so that it can
1592 capture program output. It also temporarily replaces pdb.set_trace
1593 with a version that restores stdout. This is necessary for you to
Jim Fulton356fd192004-08-09 11:34:47 +00001594 see debugger output.
1595
1596 >>> doc = '''
1597 ... >>> x = 42
1598 ... >>> import pdb; pdb.set_trace()
1599 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001600 >>> parser = doctest.DocTestParser()
1601 >>> test = parser.get_doctest(doc, {}, "foo", "foo.py", 0)
Jim Fulton356fd192004-08-09 11:34:47 +00001602 >>> runner = doctest.DocTestRunner(verbose=False)
1603
1604 To demonstrate this, we'll create a fake standard input that
1605 captures our debugger input:
1606
1607 >>> import tempfile
Edward Loper2de91ba2004-08-27 02:07:46 +00001608 >>> real_stdin = sys.stdin
1609 >>> sys.stdin = _FakeInput([
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001610 ... 'print(x)', # print data defined by the example
Jim Fulton356fd192004-08-09 11:34:47 +00001611 ... 'continue', # stop debugging
Edward Loper2de91ba2004-08-27 02:07:46 +00001612 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001613
Edward Loper2de91ba2004-08-27 02:07:46 +00001614 >>> try: runner.run(test)
1615 ... finally: sys.stdin = real_stdin
Jim Fulton356fd192004-08-09 11:34:47 +00001616 --Return--
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001617 > <doctest foo[1]>(1)<module>()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001618 -> import pdb; pdb.set_trace()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001619 (Pdb) print(x)
Edward Loper2de91ba2004-08-27 02:07:46 +00001620 42
1621 (Pdb) continue
Christian Heimes25bb7832008-01-11 16:17:00 +00001622 TestResults(failed=0, attempted=2)
Jim Fulton356fd192004-08-09 11:34:47 +00001623
1624 You can also put pdb.set_trace in a function called from a test:
1625
1626 >>> def calls_set_trace():
1627 ... y=2
1628 ... import pdb; pdb.set_trace()
1629
1630 >>> doc = '''
1631 ... >>> x=1
1632 ... >>> calls_set_trace()
1633 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001634 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
Edward Loper2de91ba2004-08-27 02:07:46 +00001635 >>> real_stdin = sys.stdin
1636 >>> sys.stdin = _FakeInput([
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001637 ... 'print(y)', # print data defined in the function
Jim Fulton356fd192004-08-09 11:34:47 +00001638 ... 'up', # out of function
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001639 ... 'print(x)', # print data defined by the example
Jim Fulton356fd192004-08-09 11:34:47 +00001640 ... 'continue', # stop debugging
Edward Loper2de91ba2004-08-27 02:07:46 +00001641 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001642
Tim Peters50c6bdb2004-11-08 22:07:37 +00001643 >>> try:
1644 ... runner.run(test)
1645 ... finally:
1646 ... sys.stdin = real_stdin
Jim Fulton356fd192004-08-09 11:34:47 +00001647 --Return--
Edward Loper2de91ba2004-08-27 02:07:46 +00001648 > <doctest test.test_doctest.test_pdb_set_trace[8]>(3)calls_set_trace()->None
1649 -> import pdb; pdb.set_trace()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001650 (Pdb) print(y)
Edward Loper2de91ba2004-08-27 02:07:46 +00001651 2
1652 (Pdb) up
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001653 > <doctest foo[1]>(1)<module>()
Edward Loper2de91ba2004-08-27 02:07:46 +00001654 -> calls_set_trace()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001655 (Pdb) print(x)
Edward Loper2de91ba2004-08-27 02:07:46 +00001656 1
1657 (Pdb) continue
Christian Heimes25bb7832008-01-11 16:17:00 +00001658 TestResults(failed=0, attempted=2)
Edward Loper2de91ba2004-08-27 02:07:46 +00001659
1660 During interactive debugging, source code is shown, even for
1661 doctest examples:
1662
1663 >>> doc = '''
1664 ... >>> def f(x):
1665 ... ... g(x*2)
1666 ... >>> def g(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001667 ... ... print(x+3)
Edward Loper2de91ba2004-08-27 02:07:46 +00001668 ... ... import pdb; pdb.set_trace()
1669 ... >>> f(3)
1670 ... '''
1671 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
1672 >>> real_stdin = sys.stdin
1673 >>> sys.stdin = _FakeInput([
1674 ... 'list', # list source from example 2
1675 ... 'next', # return from g()
1676 ... 'list', # list source from example 1
1677 ... 'next', # return from f()
1678 ... 'list', # list source from example 3
1679 ... 'continue', # stop debugging
1680 ... ''])
1681 >>> try: runner.run(test)
1682 ... finally: sys.stdin = real_stdin
1683 ... # doctest: +NORMALIZE_WHITESPACE
1684 --Return--
1685 > <doctest foo[1]>(3)g()->None
1686 -> import pdb; pdb.set_trace()
1687 (Pdb) list
1688 1 def g(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001689 2 print(x+3)
Edward Loper2de91ba2004-08-27 02:07:46 +00001690 3 -> import pdb; pdb.set_trace()
1691 [EOF]
1692 (Pdb) next
1693 --Return--
1694 > <doctest foo[0]>(2)f()->None
1695 -> g(x*2)
1696 (Pdb) list
1697 1 def f(x):
1698 2 -> g(x*2)
1699 [EOF]
1700 (Pdb) next
1701 --Return--
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001702 > <doctest foo[2]>(1)<module>()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001703 -> f(3)
1704 (Pdb) list
1705 1 -> f(3)
1706 [EOF]
1707 (Pdb) continue
1708 **********************************************************************
1709 File "foo.py", line 7, in foo
1710 Failed example:
1711 f(3)
1712 Expected nothing
1713 Got:
1714 9
Christian Heimes25bb7832008-01-11 16:17:00 +00001715 TestResults(failed=1, attempted=3)
Jim Fulton356fd192004-08-09 11:34:47 +00001716 """
1717
Tim Peters50c6bdb2004-11-08 22:07:37 +00001718def test_pdb_set_trace_nested():
1719 """This illustrates more-demanding use of set_trace with nested functions.
1720
1721 >>> class C(object):
1722 ... def calls_set_trace(self):
1723 ... y = 1
1724 ... import pdb; pdb.set_trace()
1725 ... self.f1()
1726 ... y = 2
1727 ... def f1(self):
1728 ... x = 1
1729 ... self.f2()
1730 ... x = 2
1731 ... def f2(self):
1732 ... z = 1
1733 ... z = 2
1734
1735 >>> calls_set_trace = C().calls_set_trace
1736
1737 >>> doc = '''
1738 ... >>> a = 1
1739 ... >>> calls_set_trace()
1740 ... '''
1741 >>> parser = doctest.DocTestParser()
1742 >>> runner = doctest.DocTestRunner(verbose=False)
1743 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
1744 >>> real_stdin = sys.stdin
1745 >>> sys.stdin = _FakeInput([
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001746 ... 'print(y)', # print data defined in the function
1747 ... 'step', 'step', 'step', 'step', 'step', 'step', 'print(z)',
1748 ... 'up', 'print(x)',
1749 ... 'up', 'print(y)',
1750 ... 'up', 'print(foo)',
Tim Peters50c6bdb2004-11-08 22:07:37 +00001751 ... 'continue', # stop debugging
1752 ... ''])
1753
1754 >>> try:
1755 ... runner.run(test)
1756 ... finally:
1757 ... sys.stdin = real_stdin
Guido van Rossum4a625c32007-09-08 16:05:25 +00001758 ... # doctest: +REPORT_NDIFF
Tim Peters50c6bdb2004-11-08 22:07:37 +00001759 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
1760 -> self.f1()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001761 (Pdb) print(y)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001762 1
1763 (Pdb) step
1764 --Call--
1765 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(7)f1()
1766 -> def f1(self):
1767 (Pdb) step
1768 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(8)f1()
1769 -> x = 1
1770 (Pdb) step
1771 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
1772 -> self.f2()
1773 (Pdb) step
1774 --Call--
1775 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(11)f2()
1776 -> def f2(self):
1777 (Pdb) step
1778 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(12)f2()
1779 -> z = 1
1780 (Pdb) step
1781 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(13)f2()
1782 -> z = 2
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001783 (Pdb) print(z)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001784 1
1785 (Pdb) up
1786 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
1787 -> self.f2()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001788 (Pdb) print(x)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001789 1
1790 (Pdb) up
1791 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
1792 -> self.f1()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001793 (Pdb) print(y)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001794 1
1795 (Pdb) up
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001796 > <doctest foo[1]>(1)<module>()
Tim Peters50c6bdb2004-11-08 22:07:37 +00001797 -> calls_set_trace()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001798 (Pdb) print(foo)
Guido van Rossumfd4a7de2007-09-05 03:26:38 +00001799 *** NameError: NameError("name 'foo' is not defined",)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001800 (Pdb) continue
Christian Heimes25bb7832008-01-11 16:17:00 +00001801 TestResults(failed=0, attempted=2)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001802"""
1803
Tim Peters19397e52004-08-06 22:02:59 +00001804def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +00001805 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +00001806
1807 We create a Suite by providing a module. A module can be provided
1808 by passing a module object:
1809
1810 >>> import unittest
1811 >>> import test.sample_doctest
1812 >>> suite = doctest.DocTestSuite(test.sample_doctest)
1813 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001814 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001815
1816 We can also supply the module by name:
1817
1818 >>> suite = doctest.DocTestSuite('test.sample_doctest')
1819 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001820 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001821
1822 We can use the current module:
1823
1824 >>> suite = test.sample_doctest.test_suite()
1825 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001826 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001827
1828 We can supply global variables. If we pass globs, they will be
1829 used instead of the module globals. Here we'll pass an empty
1830 globals, triggering an extra error:
1831
1832 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
1833 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001834 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001835
1836 Alternatively, we can provide extra globals. Here we'll make an
1837 error go away by providing an extra global variable:
1838
1839 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1840 ... extraglobs={'y': 1})
1841 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001842 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001843
1844 You can pass option flags. Here we'll cause an extra error
1845 by disabling the blank-line feature:
1846
1847 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00001848 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00001849 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001850 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001851
Tim Peters1e277ee2004-08-07 05:37:52 +00001852 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00001853
Jim Fultonf54bad42004-08-28 14:57:56 +00001854 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00001855 ... import test.test_doctest
1856 ... test.test_doctest.sillySetup = True
1857
Jim Fultonf54bad42004-08-28 14:57:56 +00001858 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00001859 ... import test.test_doctest
1860 ... del test.test_doctest.sillySetup
1861
1862 Here, we installed a silly variable that the test expects:
1863
1864 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1865 ... setUp=setUp, tearDown=tearDown)
1866 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001867 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001868
1869 But the tearDown restores sanity:
1870
1871 >>> import test.test_doctest
1872 >>> test.test_doctest.sillySetup
1873 Traceback (most recent call last):
1874 ...
1875 AttributeError: 'module' object has no attribute 'sillySetup'
1876
Jim Fultonf54bad42004-08-28 14:57:56 +00001877 The setUp and tearDown funtions are passed test objects. Here
1878 we'll use the setUp function to supply the missing variable y:
1879
1880 >>> def setUp(test):
1881 ... test.globs['y'] = 1
1882
1883 >>> suite = doctest.DocTestSuite('test.sample_doctest', setUp=setUp)
1884 >>> suite.run(unittest.TestResult())
1885 <unittest.TestResult run=9 errors=0 failures=3>
1886
1887 Here, we didn't need to use a tearDown function because we
1888 modified the test globals, which are a copy of the
1889 sample_doctest module dictionary. The test globals are
1890 automatically cleared for us after a test.
Tim Peters19397e52004-08-06 22:02:59 +00001891 """
1892
1893def test_DocFileSuite():
1894 """We can test tests found in text files using a DocFileSuite.
1895
1896 We create a suite by providing the names of one or more text
1897 files that include examples:
1898
1899 >>> import unittest
1900 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001901 ... 'test_doctest2.txt',
1902 ... 'test_doctest4.txt')
Tim Peters19397e52004-08-06 22:02:59 +00001903 >>> suite.run(unittest.TestResult())
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00001904 <unittest.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00001905
1906 The test files are looked for in the directory containing the
1907 calling module. A package keyword argument can be provided to
1908 specify a different relative location.
1909
1910 >>> import unittest
1911 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1912 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001913 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00001914 ... package='test')
1915 >>> suite.run(unittest.TestResult())
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00001916 <unittest.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00001917
Guido van Rossumcd4d4522007-11-22 00:30:02 +00001918 Support for using a package's __loader__.get_data() is also
1919 provided.
1920
1921 >>> import unittest, pkgutil, test
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001922 >>> added_loader = False
Guido van Rossumcd4d4522007-11-22 00:30:02 +00001923 >>> if not hasattr(test, '__loader__'):
1924 ... test.__loader__ = pkgutil.get_loader(test)
1925 ... added_loader = True
1926 >>> try:
1927 ... suite = doctest.DocFileSuite('test_doctest.txt',
1928 ... 'test_doctest2.txt',
1929 ... 'test_doctest4.txt',
1930 ... package='test')
1931 ... suite.run(unittest.TestResult())
1932 ... finally:
1933 ... if added_loader:
1934 ... del test.__loader__
1935 <unittest.TestResult run=3 errors=0 failures=2>
1936
Edward Loper0273f5b2004-09-18 20:27:04 +00001937 '/' should be used as a path separator. It will be converted
1938 to a native separator at run time:
Tim Peters19397e52004-08-06 22:02:59 +00001939
1940 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
1941 >>> suite.run(unittest.TestResult())
1942 <unittest.TestResult run=1 errors=0 failures=1>
1943
Edward Loper0273f5b2004-09-18 20:27:04 +00001944 If DocFileSuite is used from an interactive session, then files
1945 are resolved relative to the directory of sys.argv[0]:
1946
Christian Heimes45f9af32007-11-27 21:50:00 +00001947 >>> import types, os.path, test.test_doctest
Edward Loper0273f5b2004-09-18 20:27:04 +00001948 >>> save_argv = sys.argv
1949 >>> sys.argv = [test.test_doctest.__file__]
1950 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Christian Heimes45f9af32007-11-27 21:50:00 +00001951 ... package=types.ModuleType('__main__'))
Edward Loper0273f5b2004-09-18 20:27:04 +00001952 >>> sys.argv = save_argv
1953
Edward Loper052d0cd2004-09-19 17:19:33 +00001954 By setting `module_relative=False`, os-specific paths may be
1955 used (including absolute paths and paths relative to the
1956 working directory):
Edward Loper0273f5b2004-09-18 20:27:04 +00001957
1958 >>> # Get the absolute path of the test package.
1959 >>> test_doctest_path = os.path.abspath(test.test_doctest.__file__)
1960 >>> test_pkg_path = os.path.split(test_doctest_path)[0]
1961
1962 >>> # Use it to find the absolute path of test_doctest.txt.
1963 >>> test_file = os.path.join(test_pkg_path, 'test_doctest.txt')
1964
Edward Loper052d0cd2004-09-19 17:19:33 +00001965 >>> suite = doctest.DocFileSuite(test_file, module_relative=False)
Edward Loper0273f5b2004-09-18 20:27:04 +00001966 >>> suite.run(unittest.TestResult())
1967 <unittest.TestResult run=1 errors=0 failures=1>
1968
Edward Loper052d0cd2004-09-19 17:19:33 +00001969 It is an error to specify `package` when `module_relative=False`:
1970
1971 >>> suite = doctest.DocFileSuite(test_file, module_relative=False,
1972 ... package='test')
1973 Traceback (most recent call last):
1974 ValueError: Package may only be specified for module-relative paths.
1975
Tim Peters19397e52004-08-06 22:02:59 +00001976 You can specify initial global variables:
1977
1978 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1979 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001980 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00001981 ... globs={'favorite_color': 'blue'})
1982 >>> suite.run(unittest.TestResult())
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00001983 <unittest.TestResult run=3 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00001984
1985 In this case, we supplied a missing favorite color. You can
1986 provide doctest options:
1987
1988 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1989 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001990 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00001991 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
1992 ... globs={'favorite_color': 'blue'})
1993 >>> suite.run(unittest.TestResult())
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00001994 <unittest.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00001995
1996 And, you can provide setUp and tearDown functions:
1997
Jim Fultonf54bad42004-08-28 14:57:56 +00001998 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00001999 ... import test.test_doctest
2000 ... test.test_doctest.sillySetup = True
2001
Jim Fultonf54bad42004-08-28 14:57:56 +00002002 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00002003 ... import test.test_doctest
2004 ... del test.test_doctest.sillySetup
2005
2006 Here, we installed a silly variable that the test expects:
2007
2008 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2009 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002010 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002011 ... setUp=setUp, tearDown=tearDown)
2012 >>> suite.run(unittest.TestResult())
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002013 <unittest.TestResult run=3 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002014
2015 But the tearDown restores sanity:
2016
2017 >>> import test.test_doctest
2018 >>> test.test_doctest.sillySetup
2019 Traceback (most recent call last):
2020 ...
2021 AttributeError: 'module' object has no attribute 'sillySetup'
2022
Jim Fultonf54bad42004-08-28 14:57:56 +00002023 The setUp and tearDown funtions are passed test objects.
2024 Here, we'll use a setUp function to set the favorite color in
2025 test_doctest.txt:
2026
2027 >>> def setUp(test):
2028 ... test.globs['favorite_color'] = 'blue'
2029
2030 >>> suite = doctest.DocFileSuite('test_doctest.txt', setUp=setUp)
2031 >>> suite.run(unittest.TestResult())
2032 <unittest.TestResult run=1 errors=0 failures=0>
2033
2034 Here, we didn't need to use a tearDown function because we
2035 modified the test globals. The test globals are
2036 automatically cleared for us after a test.
Tim Petersdf7a2082004-08-29 00:38:17 +00002037
Fred Drake7c404a42004-12-21 23:46:34 +00002038 Tests in a file run using `DocFileSuite` can also access the
2039 `__file__` global, which is set to the name of the file
2040 containing the tests:
2041
2042 >>> suite = doctest.DocFileSuite('test_doctest3.txt')
2043 >>> suite.run(unittest.TestResult())
2044 <unittest.TestResult run=1 errors=0 failures=0>
2045
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002046 If the tests contain non-ASCII characters, we have to specify which
2047 encoding the file is encoded with. We do so by using the `encoding`
2048 parameter:
2049
2050 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2051 ... 'test_doctest2.txt',
2052 ... 'test_doctest4.txt',
2053 ... encoding='utf-8')
2054 >>> suite.run(unittest.TestResult())
2055 <unittest.TestResult run=3 errors=0 failures=2>
2056
Jim Fultonf54bad42004-08-28 14:57:56 +00002057 """
Tim Peters19397e52004-08-06 22:02:59 +00002058
Jim Fulton07a349c2004-08-22 14:10:00 +00002059def test_trailing_space_in_test():
2060 """
Tim Petersa7def722004-08-23 22:13:22 +00002061 Trailing spaces in expected output are significant:
Tim Petersc6cbab02004-08-22 19:43:28 +00002062
Jim Fulton07a349c2004-08-22 14:10:00 +00002063 >>> x, y = 'foo', ''
Guido van Rossum7131f842007-02-09 20:13:25 +00002064 >>> print(x, y)
Jim Fulton07a349c2004-08-22 14:10:00 +00002065 foo \n
2066 """
Tim Peters19397e52004-08-06 22:02:59 +00002067
Jim Fultonf54bad42004-08-28 14:57:56 +00002068
2069def test_unittest_reportflags():
2070 """Default unittest reporting flags can be set to control reporting
2071
2072 Here, we'll set the REPORT_ONLY_FIRST_FAILURE option so we see
2073 only the first failure of each test. First, we'll look at the
2074 output without the flag. The file test_doctest.txt file has two
2075 tests. They both fail if blank lines are disabled:
2076
2077 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2078 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
2079 >>> import unittest
2080 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002081 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002082 Traceback ...
2083 Failed example:
2084 favorite_color
2085 ...
2086 Failed example:
2087 if 1:
2088 ...
2089
2090 Note that we see both failures displayed.
2091
2092 >>> old = doctest.set_unittest_reportflags(
2093 ... doctest.REPORT_ONLY_FIRST_FAILURE)
2094
2095 Now, when we run the test:
2096
2097 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002098 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002099 Traceback ...
2100 Failed example:
2101 favorite_color
2102 Exception raised:
2103 ...
2104 NameError: name 'favorite_color' is not defined
2105 <BLANKLINE>
2106 <BLANKLINE>
Tim Petersdf7a2082004-08-29 00:38:17 +00002107
Jim Fultonf54bad42004-08-28 14:57:56 +00002108 We get only the first failure.
2109
2110 If we give any reporting options when we set up the tests,
2111 however:
2112
2113 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2114 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE | doctest.REPORT_NDIFF)
2115
2116 Then the default eporting options are ignored:
2117
2118 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002119 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002120 Traceback ...
2121 Failed example:
2122 favorite_color
2123 ...
2124 Failed example:
2125 if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00002126 print('a')
2127 print()
2128 print('b')
Jim Fultonf54bad42004-08-28 14:57:56 +00002129 Differences (ndiff with -expected +actual):
2130 a
2131 - <BLANKLINE>
2132 +
2133 b
2134 <BLANKLINE>
2135 <BLANKLINE>
2136
2137
2138 Test runners can restore the formatting flags after they run:
2139
2140 >>> ignored = doctest.set_unittest_reportflags(old)
2141
2142 """
2143
Edward Loper052d0cd2004-09-19 17:19:33 +00002144def test_testfile(): r"""
2145Tests for the `testfile()` function. This function runs all the
2146doctest examples in a given file. In its simple invokation, it is
2147called with the name of a file, which is taken to be relative to the
2148calling module. The return value is (#failures, #tests).
2149
2150 >>> doctest.testfile('test_doctest.txt') # doctest: +ELLIPSIS
2151 **********************************************************************
2152 File "...", line 6, in test_doctest.txt
2153 Failed example:
2154 favorite_color
2155 Exception raised:
2156 ...
2157 NameError: name 'favorite_color' is not defined
2158 **********************************************************************
2159 1 items had failures:
2160 1 of 2 in test_doctest.txt
2161 ***Test Failed*** 1 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002162 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002163 >>> doctest.master = None # Reset master.
2164
2165(Note: we'll be clearing doctest.master after each call to
2166`doctest.testfile`, to supress warnings about multiple tests with the
2167same name.)
2168
2169Globals may be specified with the `globs` and `extraglobs` parameters:
2170
2171 >>> globs = {'favorite_color': 'blue'}
2172 >>> doctest.testfile('test_doctest.txt', globs=globs)
Christian Heimes25bb7832008-01-11 16:17:00 +00002173 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002174 >>> doctest.master = None # Reset master.
2175
2176 >>> extraglobs = {'favorite_color': 'red'}
2177 >>> doctest.testfile('test_doctest.txt', globs=globs,
2178 ... extraglobs=extraglobs) # doctest: +ELLIPSIS
2179 **********************************************************************
2180 File "...", line 6, in test_doctest.txt
2181 Failed example:
2182 favorite_color
2183 Expected:
2184 'blue'
2185 Got:
2186 'red'
2187 **********************************************************************
2188 1 items had failures:
2189 1 of 2 in test_doctest.txt
2190 ***Test Failed*** 1 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002191 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002192 >>> doctest.master = None # Reset master.
2193
2194The file may be made relative to a given module or package, using the
2195optional `module_relative` parameter:
2196
2197 >>> doctest.testfile('test_doctest.txt', globs=globs,
2198 ... module_relative='test')
Christian Heimes25bb7832008-01-11 16:17:00 +00002199 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002200 >>> doctest.master = None # Reset master.
2201
2202Verbosity can be increased with the optional `verbose` paremter:
2203
2204 >>> doctest.testfile('test_doctest.txt', globs=globs, verbose=True)
2205 Trying:
2206 favorite_color
2207 Expecting:
2208 'blue'
2209 ok
2210 Trying:
2211 if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00002212 print('a')
2213 print()
2214 print('b')
Edward Loper052d0cd2004-09-19 17:19:33 +00002215 Expecting:
2216 a
2217 <BLANKLINE>
2218 b
2219 ok
2220 1 items passed all tests:
2221 2 tests in test_doctest.txt
2222 2 tests in 1 items.
2223 2 passed and 0 failed.
2224 Test passed.
Christian Heimes25bb7832008-01-11 16:17:00 +00002225 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002226 >>> doctest.master = None # Reset master.
2227
2228The name of the test may be specified with the optional `name`
2229parameter:
2230
2231 >>> doctest.testfile('test_doctest.txt', name='newname')
2232 ... # doctest: +ELLIPSIS
2233 **********************************************************************
2234 File "...", line 6, in newname
2235 ...
Christian Heimes25bb7832008-01-11 16:17:00 +00002236 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002237 >>> doctest.master = None # Reset master.
2238
2239The summary report may be supressed with the optional `report`
2240parameter:
2241
2242 >>> doctest.testfile('test_doctest.txt', report=False)
2243 ... # doctest: +ELLIPSIS
2244 **********************************************************************
2245 File "...", line 6, in test_doctest.txt
2246 Failed example:
2247 favorite_color
2248 Exception raised:
2249 ...
2250 NameError: name 'favorite_color' is not defined
Christian Heimes25bb7832008-01-11 16:17:00 +00002251 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002252 >>> doctest.master = None # Reset master.
2253
2254The optional keyword argument `raise_on_error` can be used to raise an
2255exception on the first error (which may be useful for postmortem
2256debugging):
2257
2258 >>> doctest.testfile('test_doctest.txt', raise_on_error=True)
2259 ... # doctest: +ELLIPSIS
2260 Traceback (most recent call last):
Guido van Rossum6a2a2a02006-08-26 20:37:44 +00002261 doctest.UnexpectedException: ...
Edward Loper052d0cd2004-09-19 17:19:33 +00002262 >>> doctest.master = None # Reset master.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002263
2264If the tests contain non-ASCII characters, the tests might fail, since
2265it's unknown which encoding is used. The encoding can be specified
2266using the optional keyword argument `encoding`:
2267
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002268 >>> doctest.testfile('test_doctest4.txt', encoding='latin-1') # doctest: +ELLIPSIS
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002269 **********************************************************************
2270 File "...", line 7, in test_doctest4.txt
2271 Failed example:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002272 '...'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002273 Expected:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002274 'f\xf6\xf6'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002275 Got:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002276 'f\xc3\xb6\xc3\xb6'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002277 **********************************************************************
2278 ...
2279 **********************************************************************
2280 1 items had failures:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002281 2 of 2 in test_doctest4.txt
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002282 ***Test Failed*** 2 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002283 TestResults(failed=2, attempted=2)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002284 >>> doctest.master = None # Reset master.
2285
2286 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8')
Christian Heimes25bb7832008-01-11 16:17:00 +00002287 TestResults(failed=0, attempted=2)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002288 >>> doctest.master = None # Reset master.
Edward Loper052d0cd2004-09-19 17:19:33 +00002289"""
2290
R. David Murray58641de2009-06-12 15:33:19 +00002291def test_testmod(): r"""
2292Tests for the testmod function. More might be useful, but for now we're just
2293testing the case raised by Issue 6195, where trying to doctest a C module would
2294fail with a UnicodeDecodeError because doctest tried to read the "source" lines
2295out of the binary module.
2296
2297 >>> import unicodedata
2298 >>> doctest.testmod(unicodedata)
2299 TestResults(failed=0, attempted=0)
2300"""
2301
Tim Peters8485b562004-08-04 18:46:34 +00002302######################################################################
2303## Main
2304######################################################################
2305
2306def test_main():
2307 # Check the doctest cases in doctest itself:
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002308 support.run_doctest(doctest, verbosity=True)
Tim Peters8485b562004-08-04 18:46:34 +00002309 # Check the doctest cases defined here:
2310 from test import test_doctest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002311 support.run_doctest(test_doctest, verbosity=True)
Tim Peters8485b562004-08-04 18:46:34 +00002312
Guido van Rossum34d19282007-08-09 01:03:29 +00002313import trace, sys, re, io
Tim Peters8485b562004-08-04 18:46:34 +00002314def test_coverage(coverdir):
2315 tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
2316 trace=0, count=1)
Guido van Rossume7ba4952007-06-06 23:52:48 +00002317 tracer.run('test_main()')
Tim Peters8485b562004-08-04 18:46:34 +00002318 r = tracer.results()
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002319 print('Writing coverage results...')
Tim Peters8485b562004-08-04 18:46:34 +00002320 r.write_results(show_missing=True, summary=True,
2321 coverdir=coverdir)
2322
2323if __name__ == '__main__':
2324 if '-c' in sys.argv:
2325 test_coverage('/tmp/doctest.cover')
2326 else:
2327 test_main()