blob: 676d5de6f7a6522d5362ba662f6931e61fb9473a [file] [log] [blame]
Tim Peters8485b562004-08-04 18:46:34 +00001"""
2Test script for doctest.
3"""
4
Benjamin Petersonee8712c2008-05-20 21:35:26 +00005from test import support
Tim Peters8485b562004-08-04 18:46:34 +00006import doctest
Victor Stinner9d396392010-10-16 21:54:59 +00007import os
Tim Peters8485b562004-08-04 18:46:34 +00008
Florent Xiclunadc6f2d02010-04-02 19:25:32 +00009
Nick Coghlanf088e5e2008-12-14 11:50:48 +000010# NOTE: There are some additional tests relating to interaction with
11# zipimport in the test_zipimport_support test module.
12
Tim Peters8485b562004-08-04 18:46:34 +000013######################################################################
14## Sample Objects (used by test cases)
15######################################################################
16
17def sample_func(v):
18 """
Tim Peters19397e52004-08-06 22:02:59 +000019 Blah blah
20
Guido van Rossum7131f842007-02-09 20:13:25 +000021 >>> print(sample_func(22))
Tim Peters8485b562004-08-04 18:46:34 +000022 44
Tim Peters19397e52004-08-06 22:02:59 +000023
24 Yee ha!
Tim Peters8485b562004-08-04 18:46:34 +000025 """
26 return v+v
27
28class SampleClass:
29 """
Guido van Rossum7131f842007-02-09 20:13:25 +000030 >>> print(1)
Tim Peters8485b562004-08-04 18:46:34 +000031 1
Edward Loper4ae900f2004-09-21 03:20:34 +000032
33 >>> # comments get ignored. so are empty PS1 and PS2 prompts:
34 >>>
35 ...
36
37 Multiline example:
38 >>> sc = SampleClass(3)
39 >>> for i in range(10):
40 ... sc = sc.double()
Guido van Rossum805365e2007-05-07 22:24:25 +000041 ... print(' ', sc.get(), sep='', end='')
42 6 12 24 48 96 192 384 768 1536 3072
Tim Peters8485b562004-08-04 18:46:34 +000043 """
44 def __init__(self, val):
45 """
Guido van Rossum7131f842007-02-09 20:13:25 +000046 >>> print(SampleClass(12).get())
Tim Peters8485b562004-08-04 18:46:34 +000047 12
48 """
49 self.val = val
50
51 def double(self):
52 """
Guido van Rossum7131f842007-02-09 20:13:25 +000053 >>> print(SampleClass(12).double().get())
Tim Peters8485b562004-08-04 18:46:34 +000054 24
55 """
56 return SampleClass(self.val + self.val)
57
58 def get(self):
59 """
Guido van Rossum7131f842007-02-09 20:13:25 +000060 >>> print(SampleClass(-5).get())
Tim Peters8485b562004-08-04 18:46:34 +000061 -5
62 """
63 return self.val
64
65 def a_staticmethod(v):
66 """
Guido van Rossum7131f842007-02-09 20:13:25 +000067 >>> print(SampleClass.a_staticmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +000068 11
69 """
70 return v+1
71 a_staticmethod = staticmethod(a_staticmethod)
72
73 def a_classmethod(cls, v):
74 """
Guido van Rossum7131f842007-02-09 20:13:25 +000075 >>> print(SampleClass.a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +000076 12
Guido van Rossum7131f842007-02-09 20:13:25 +000077 >>> print(SampleClass(0).a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +000078 12
79 """
80 return v+2
81 a_classmethod = classmethod(a_classmethod)
82
83 a_property = property(get, doc="""
Guido van Rossum7131f842007-02-09 20:13:25 +000084 >>> print(SampleClass(22).a_property)
Tim Peters8485b562004-08-04 18:46:34 +000085 22
86 """)
87
88 class NestedClass:
89 """
90 >>> x = SampleClass.NestedClass(5)
91 >>> y = x.square()
Guido van Rossum7131f842007-02-09 20:13:25 +000092 >>> print(y.get())
Tim Peters8485b562004-08-04 18:46:34 +000093 25
94 """
95 def __init__(self, val=0):
96 """
Guido van Rossum7131f842007-02-09 20:13:25 +000097 >>> print(SampleClass.NestedClass().get())
Tim Peters8485b562004-08-04 18:46:34 +000098 0
99 """
100 self.val = val
101 def square(self):
102 return SampleClass.NestedClass(self.val*self.val)
103 def get(self):
104 return self.val
105
106class SampleNewStyleClass(object):
107 r"""
Guido van Rossum7131f842007-02-09 20:13:25 +0000108 >>> print('1\n2\n3')
Tim Peters8485b562004-08-04 18:46:34 +0000109 1
110 2
111 3
112 """
113 def __init__(self, val):
114 """
Guido van Rossum7131f842007-02-09 20:13:25 +0000115 >>> print(SampleNewStyleClass(12).get())
Tim Peters8485b562004-08-04 18:46:34 +0000116 12
117 """
118 self.val = val
119
120 def double(self):
121 """
Guido van Rossum7131f842007-02-09 20:13:25 +0000122 >>> print(SampleNewStyleClass(12).double().get())
Tim Peters8485b562004-08-04 18:46:34 +0000123 24
124 """
125 return SampleNewStyleClass(self.val + self.val)
126
127 def get(self):
128 """
Guido van Rossum7131f842007-02-09 20:13:25 +0000129 >>> print(SampleNewStyleClass(-5).get())
Tim Peters8485b562004-08-04 18:46:34 +0000130 -5
131 """
132 return self.val
133
134######################################################################
Edward Loper2de91ba2004-08-27 02:07:46 +0000135## Fake stdin (for testing interactive debugging)
136######################################################################
137
138class _FakeInput:
139 """
140 A fake input stream for pdb's interactive debugger. Whenever a
141 line is read, print it (to simulate the user typing it), and then
142 return it. The set of lines to return is specified in the
143 constructor; they should not have trailing newlines.
144 """
145 def __init__(self, lines):
146 self.lines = lines
147
148 def readline(self):
149 line = self.lines.pop(0)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000150 print(line)
Edward Loper2de91ba2004-08-27 02:07:46 +0000151 return line+'\n'
152
153######################################################################
Tim Peters8485b562004-08-04 18:46:34 +0000154## Test Cases
155######################################################################
156
157def test_Example(): r"""
158Unit tests for the `Example` class.
159
Edward Lopera6b68322004-08-26 00:05:43 +0000160Example is a simple container class that holds:
161 - `source`: A source string.
162 - `want`: An expected output string.
163 - `exc_msg`: An expected exception message string (or None if no
164 exception is expected).
165 - `lineno`: A line number (within the docstring).
166 - `indent`: The example's indentation in the input string.
167 - `options`: An option dictionary, mapping option flags to True or
168 False.
Tim Peters8485b562004-08-04 18:46:34 +0000169
Edward Lopera6b68322004-08-26 00:05:43 +0000170These attributes are set by the constructor. `source` and `want` are
171required; the other attributes all have default values:
Tim Peters8485b562004-08-04 18:46:34 +0000172
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000173 >>> example = doctest.Example('print(1)', '1\n')
Edward Lopera6b68322004-08-26 00:05:43 +0000174 >>> (example.source, example.want, example.exc_msg,
175 ... example.lineno, example.indent, example.options)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000176 ('print(1)\n', '1\n', None, 0, 0, {})
Edward Lopera6b68322004-08-26 00:05:43 +0000177
178The first three attributes (`source`, `want`, and `exc_msg`) may be
179specified positionally; the remaining arguments should be specified as
180keyword arguments:
181
182 >>> exc_msg = 'IndexError: pop from an empty list'
183 >>> example = doctest.Example('[].pop()', '', exc_msg,
184 ... lineno=5, indent=4,
185 ... options={doctest.ELLIPSIS: True})
186 >>> (example.source, example.want, example.exc_msg,
187 ... example.lineno, example.indent, example.options)
188 ('[].pop()\n', '', 'IndexError: pop from an empty list\n', 5, 4, {8: True})
189
190The constructor normalizes the `source` string to end in a newline:
Tim Peters8485b562004-08-04 18:46:34 +0000191
Tim Petersbb431472004-08-09 03:51:46 +0000192 Source spans a single line: no terminating newline.
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000193 >>> e = doctest.Example('print(1)', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000194 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000195 ('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000196
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000197 >>> e = doctest.Example('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000198 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000199 ('print(1)\n', '1\n')
Tim Peters8485b562004-08-04 18:46:34 +0000200
Tim Petersbb431472004-08-09 03:51:46 +0000201 Source spans multiple lines: require terminating newline.
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000202 >>> e = doctest.Example('print(1);\nprint(2)\n', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000203 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000204 ('print(1);\nprint(2)\n', '1\n2\n')
Tim Peters8485b562004-08-04 18:46:34 +0000205
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000206 >>> e = doctest.Example('print(1);\nprint(2)', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000207 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000208 ('print(1);\nprint(2)\n', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000209
Edward Lopera6b68322004-08-26 00:05:43 +0000210 Empty source string (which should never appear in real examples)
211 >>> e = doctest.Example('', '')
212 >>> e.source, e.want
213 ('\n', '')
Tim Peters8485b562004-08-04 18:46:34 +0000214
Edward Lopera6b68322004-08-26 00:05:43 +0000215The constructor normalizes the `want` string to end in a newline,
216unless it's the empty string:
217
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000218 >>> e = doctest.Example('print(1)', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000219 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000220 ('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000221
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000222 >>> e = doctest.Example('print(1)', '1')
Tim Petersbb431472004-08-09 03:51:46 +0000223 >>> e.source, e.want
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000224 ('print(1)\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000225
Edward Lopera6b68322004-08-26 00:05:43 +0000226 >>> e = doctest.Example('print', '')
Tim Petersbb431472004-08-09 03:51:46 +0000227 >>> e.source, e.want
228 ('print\n', '')
Edward Lopera6b68322004-08-26 00:05:43 +0000229
230The constructor normalizes the `exc_msg` string to end in a newline,
231unless it's `None`:
232
233 Message spans one line
234 >>> exc_msg = 'IndexError: pop from an empty list'
235 >>> e = doctest.Example('[].pop()', '', exc_msg)
236 >>> e.exc_msg
237 'IndexError: pop from an empty list\n'
238
239 >>> exc_msg = 'IndexError: pop from an empty list\n'
240 >>> e = doctest.Example('[].pop()', '', exc_msg)
241 >>> e.exc_msg
242 'IndexError: pop from an empty list\n'
243
244 Message spans multiple lines
245 >>> exc_msg = 'ValueError: 1\n 2'
246 >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
247 >>> e.exc_msg
248 'ValueError: 1\n 2\n'
249
250 >>> exc_msg = 'ValueError: 1\n 2\n'
251 >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
252 >>> e.exc_msg
253 'ValueError: 1\n 2\n'
254
255 Empty (but non-None) exception message (which should never appear
256 in real examples)
257 >>> exc_msg = ''
258 >>> e = doctest.Example('raise X()', '', exc_msg)
259 >>> e.exc_msg
260 '\n'
Tim Peters8485b562004-08-04 18:46:34 +0000261"""
262
263def test_DocTest(): r"""
264Unit tests for the `DocTest` class.
265
266DocTest is a collection of examples, extracted from a docstring, along
267with information about where the docstring comes from (a name,
268filename, and line number). The docstring is parsed by the `DocTest`
269constructor:
270
271 >>> docstring = '''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000272 ... >>> print(12)
Tim Peters8485b562004-08-04 18:46:34 +0000273 ... 12
274 ...
275 ... Non-example text.
276 ...
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000277 ... >>> print('another\example')
Tim Peters8485b562004-08-04 18:46:34 +0000278 ... another
279 ... example
280 ... '''
281 >>> globs = {} # globals to run the test in.
Edward Lopera1ef6112004-08-09 16:14:41 +0000282 >>> parser = doctest.DocTestParser()
283 >>> test = parser.get_doctest(docstring, globs, 'some_test',
284 ... 'some_file', 20)
Guido van Rossum7131f842007-02-09 20:13:25 +0000285 >>> print(test)
Tim Peters8485b562004-08-04 18:46:34 +0000286 <DocTest some_test from some_file:20 (2 examples)>
287 >>> len(test.examples)
288 2
289 >>> e1, e2 = test.examples
290 >>> (e1.source, e1.want, e1.lineno)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000291 ('print(12)\n', '12\n', 1)
Tim Peters8485b562004-08-04 18:46:34 +0000292 >>> (e2.source, e2.want, e2.lineno)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000293 ("print('another\\example')\n", 'another\nexample\n', 6)
Tim Peters8485b562004-08-04 18:46:34 +0000294
295Source information (name, filename, and line number) is available as
296attributes on the doctest object:
297
298 >>> (test.name, test.filename, test.lineno)
299 ('some_test', 'some_file', 20)
300
301The line number of an example within its containing file is found by
302adding the line number of the example and the line number of its
303containing test:
304
305 >>> test.lineno + e1.lineno
306 21
307 >>> test.lineno + e2.lineno
308 26
309
310If the docstring contains inconsistant leading whitespace in the
311expected output of an example, then `DocTest` will raise a ValueError:
312
313 >>> docstring = r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000314 ... >>> print('bad\nindentation')
Tim Peters8485b562004-08-04 18:46:34 +0000315 ... bad
316 ... indentation
317 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000318 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000319 Traceback (most recent call last):
Edward Loper00f8da72004-08-26 18:05:07 +0000320 ValueError: line 4 of the docstring for some_test has inconsistent leading whitespace: 'indentation'
Tim Peters8485b562004-08-04 18:46:34 +0000321
322If the docstring contains inconsistent leading whitespace on
323continuation lines, then `DocTest` will raise a ValueError:
324
325 >>> docstring = r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000326 ... >>> print(('bad indentation',
327 ... ... 2))
Tim Peters8485b562004-08-04 18:46:34 +0000328 ... ('bad', 'indentation')
329 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000330 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000331 Traceback (most recent call last):
Guido van Rossume0192e52007-02-09 23:39:59 +0000332 ValueError: line 2 of the docstring for some_test has inconsistent leading whitespace: '... 2))'
Tim Peters8485b562004-08-04 18:46:34 +0000333
334If there's no blank space after a PS1 prompt ('>>>'), then `DocTest`
335will raise a ValueError:
336
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000337 >>> docstring = '>>>print(1)\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000338 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000339 Traceback (most recent call last):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000340 ValueError: line 1 of the docstring for some_test lacks blank after >>>: '>>>print(1)'
Edward Loper7c748462004-08-09 02:06:06 +0000341
342If there's no blank space after a PS2 prompt ('...'), then `DocTest`
343will raise a ValueError:
344
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000345 >>> docstring = '>>> if 1:\n...print(1)\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000346 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Edward Loper7c748462004-08-09 02:06:06 +0000347 Traceback (most recent call last):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000348 ValueError: line 2 of the docstring for some_test lacks blank after ...: '...print(1)'
Edward Loper7c748462004-08-09 02:06:06 +0000349
Antoine Pitrou2bc801c2011-12-18 19:27:45 +0100350Compare `DocTest`:
351
352 >>> docstring = '''
353 ... >>> print 12
354 ... 12
355 ... '''
356 >>> test = parser.get_doctest(docstring, globs, 'some_test',
357 ... 'some_test', 20)
358 >>> same_test = parser.get_doctest(docstring, globs, 'some_test',
359 ... 'some_test', 20)
360 >>> test == same_test
361 True
362 >>> test != same_test
363 False
364 >>> docstring = '''
365 ... >>> print 42
366 ... 42
367 ... '''
368 >>> other_test = parser.get_doctest(docstring, globs, 'other_test',
369 ... 'other_file', 10)
370 >>> test == other_test
371 False
372 >>> test != other_test
373 True
374
375Compare `DocTestCase`:
376
377 >>> DocTestCase = doctest.DocTestCase
378 >>> test_case = DocTestCase(test)
379 >>> same_test_case = DocTestCase(same_test)
380 >>> other_test_case = DocTestCase(other_test)
381 >>> test_case == same_test_case
382 True
383 >>> test_case != same_test_case
384 False
385 >>> test == other_test_case
386 False
387 >>> test != other_test_case
388 True
389
Tim Peters8485b562004-08-04 18:46:34 +0000390"""
391
Tim Peters8485b562004-08-04 18:46:34 +0000392def test_DocTestFinder(): r"""
393Unit tests for the `DocTestFinder` class.
394
395DocTestFinder is used to extract DocTests from an object's docstring
396and the docstrings of its contained objects. It can be used with
397modules, functions, classes, methods, staticmethods, classmethods, and
398properties.
399
400Finding Tests in Functions
401~~~~~~~~~~~~~~~~~~~~~~~~~~
402For a function whose docstring contains examples, DocTestFinder.find()
403will return a single test (for that function's docstring):
404
Tim Peters8485b562004-08-04 18:46:34 +0000405 >>> finder = doctest.DocTestFinder()
Jim Fulton07a349c2004-08-22 14:10:00 +0000406
407We'll simulate a __file__ attr that ends in pyc:
408
409 >>> import test.test_doctest
410 >>> old = test.test_doctest.__file__
411 >>> test.test_doctest.__file__ = 'test_doctest.pyc'
412
Tim Peters8485b562004-08-04 18:46:34 +0000413 >>> tests = finder.find(sample_func)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000414
Guido van Rossum7131f842007-02-09 20:13:25 +0000415 >>> print(tests) # doctest: +ELLIPSIS
Victor Stinner9d396392010-10-16 21:54:59 +0000416 [<DocTest sample_func from ...:17 (1 example)>]
Edward Loper8e4a34b2004-08-12 02:34:27 +0000417
Tim Peters4de7c5c2004-08-23 22:38:05 +0000418The exact name depends on how test_doctest was invoked, so allow for
419leading path components.
420
421 >>> tests[0].filename # doctest: +ELLIPSIS
422 '...test_doctest.py'
Jim Fulton07a349c2004-08-22 14:10:00 +0000423
424 >>> test.test_doctest.__file__ = old
Tim Petersc6cbab02004-08-22 19:43:28 +0000425
Jim Fulton07a349c2004-08-22 14:10:00 +0000426
Tim Peters8485b562004-08-04 18:46:34 +0000427 >>> e = tests[0].examples[0]
Tim Petersbb431472004-08-09 03:51:46 +0000428 >>> (e.source, e.want, e.lineno)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000429 ('print(sample_func(22))\n', '44\n', 3)
Tim Peters8485b562004-08-04 18:46:34 +0000430
Edward Loper32ddbf72004-09-13 05:47:24 +0000431By default, tests are created for objects with no docstring:
Tim Peters8485b562004-08-04 18:46:34 +0000432
433 >>> def no_docstring(v):
434 ... pass
Tim Peters958cc892004-09-13 14:53:28 +0000435 >>> finder.find(no_docstring)
436 []
Edward Loper32ddbf72004-09-13 05:47:24 +0000437
438However, the optional argument `exclude_empty` to the DocTestFinder
439constructor can be used to exclude tests for objects with empty
440docstrings:
441
442 >>> def no_docstring(v):
443 ... pass
444 >>> excl_empty_finder = doctest.DocTestFinder(exclude_empty=True)
445 >>> excl_empty_finder.find(no_docstring)
Tim Peters8485b562004-08-04 18:46:34 +0000446 []
447
448If the function has a docstring with no examples, then a test with no
449examples is returned. (This lets `DocTestRunner` collect statistics
450about which functions have no tests -- but is that useful? And should
451an empty test also be created when there's no docstring?)
452
453 >>> def no_examples(v):
454 ... ''' no doctest examples '''
Tim Peters17b56372004-09-11 17:33:27 +0000455 >>> finder.find(no_examples) # doctest: +ELLIPSIS
456 [<DocTest no_examples from ...:1 (no examples)>]
Tim Peters8485b562004-08-04 18:46:34 +0000457
458Finding Tests in Classes
459~~~~~~~~~~~~~~~~~~~~~~~~
460For a class, DocTestFinder will create a test for the class's
461docstring, and will recursively explore its contents, including
462methods, classmethods, staticmethods, properties, and nested classes.
463
464 >>> finder = doctest.DocTestFinder()
465 >>> tests = finder.find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000466 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000467 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000468 3 SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000469 3 SampleClass.NestedClass
470 1 SampleClass.NestedClass.__init__
471 1 SampleClass.__init__
472 2 SampleClass.a_classmethod
473 1 SampleClass.a_property
474 1 SampleClass.a_staticmethod
475 1 SampleClass.double
476 1 SampleClass.get
477
478New-style classes are also supported:
479
480 >>> tests = finder.find(SampleNewStyleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000481 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000482 ... print('%2s %s' % (len(t.examples), t.name))
Tim Peters8485b562004-08-04 18:46:34 +0000483 1 SampleNewStyleClass
484 1 SampleNewStyleClass.__init__
485 1 SampleNewStyleClass.double
486 1 SampleNewStyleClass.get
487
488Finding Tests in Modules
489~~~~~~~~~~~~~~~~~~~~~~~~
490For a module, DocTestFinder will create a test for the class's
491docstring, and will recursively explore its contents, including
492functions, classes, and the `__test__` dictionary, if it exists:
493
494 >>> # A module
Christian Heimes45f9af32007-11-27 21:50:00 +0000495 >>> import types
496 >>> m = types.ModuleType('some_module')
Tim Peters8485b562004-08-04 18:46:34 +0000497 >>> def triple(val):
498 ... '''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000499 ... >>> print(triple(11))
Tim Peters8485b562004-08-04 18:46:34 +0000500 ... 33
501 ... '''
502 ... return val*3
503 >>> m.__dict__.update({
504 ... 'sample_func': sample_func,
505 ... 'SampleClass': SampleClass,
506 ... '__doc__': '''
507 ... Module docstring.
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000508 ... >>> print('module')
Tim Peters8485b562004-08-04 18:46:34 +0000509 ... module
510 ... ''',
511 ... '__test__': {
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000512 ... 'd': '>>> print(6)\n6\n>>> print(7)\n7\n',
Tim Peters8485b562004-08-04 18:46:34 +0000513 ... 'c': triple}})
514
515 >>> finder = doctest.DocTestFinder()
516 >>> # Use module=test.test_doctest, to prevent doctest from
517 >>> # ignoring the objects since they weren't defined in m.
518 >>> import test.test_doctest
519 >>> tests = finder.find(m, module=test.test_doctest)
Tim Peters8485b562004-08-04 18:46:34 +0000520 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000521 ... print('%2s %s' % (len(t.examples), t.name))
Tim Peters8485b562004-08-04 18:46:34 +0000522 1 some_module
Edward Loper4ae900f2004-09-21 03:20:34 +0000523 3 some_module.SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000524 3 some_module.SampleClass.NestedClass
525 1 some_module.SampleClass.NestedClass.__init__
526 1 some_module.SampleClass.__init__
527 2 some_module.SampleClass.a_classmethod
528 1 some_module.SampleClass.a_property
529 1 some_module.SampleClass.a_staticmethod
530 1 some_module.SampleClass.double
531 1 some_module.SampleClass.get
Tim Petersc5684782004-09-13 01:07:12 +0000532 1 some_module.__test__.c
533 2 some_module.__test__.d
Tim Peters8485b562004-08-04 18:46:34 +0000534 1 some_module.sample_func
535
536Duplicate Removal
537~~~~~~~~~~~~~~~~~
538If a single object is listed twice (under different names), then tests
539will only be generated for it once:
540
Tim Petersf3f57472004-08-08 06:11:48 +0000541 >>> from test import doctest_aliases
Benjamin Peterson78565b22009-06-28 19:19:51 +0000542 >>> assert doctest_aliases.TwoNames.f
543 >>> assert doctest_aliases.TwoNames.g
Edward Loper32ddbf72004-09-13 05:47:24 +0000544 >>> tests = excl_empty_finder.find(doctest_aliases)
Guido van Rossum7131f842007-02-09 20:13:25 +0000545 >>> print(len(tests))
Tim Peters8485b562004-08-04 18:46:34 +0000546 2
Guido van Rossum7131f842007-02-09 20:13:25 +0000547 >>> print(tests[0].name)
Tim Petersf3f57472004-08-08 06:11:48 +0000548 test.doctest_aliases.TwoNames
549
550 TwoNames.f and TwoNames.g are bound to the same object.
551 We can't guess which will be found in doctest's traversal of
552 TwoNames.__dict__ first, so we have to allow for either.
553
554 >>> tests[1].name.split('.')[-1] in ['f', 'g']
Tim Peters8485b562004-08-04 18:46:34 +0000555 True
556
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000557Empty Tests
558~~~~~~~~~~~
559By default, an object with no doctests doesn't create any tests:
Tim Peters8485b562004-08-04 18:46:34 +0000560
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000561 >>> tests = doctest.DocTestFinder().find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000562 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000563 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000564 3 SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000565 3 SampleClass.NestedClass
566 1 SampleClass.NestedClass.__init__
Tim Peters958cc892004-09-13 14:53:28 +0000567 1 SampleClass.__init__
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000568 2 SampleClass.a_classmethod
569 1 SampleClass.a_property
570 1 SampleClass.a_staticmethod
Tim Peters958cc892004-09-13 14:53:28 +0000571 1 SampleClass.double
572 1 SampleClass.get
573
574By default, that excluded objects with no doctests. exclude_empty=False
575tells it to include (empty) tests for objects with no doctests. This feature
576is really to support backward compatibility in what doctest.master.summarize()
577displays.
578
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000579 >>> tests = doctest.DocTestFinder(exclude_empty=False).find(SampleClass)
Tim Peters958cc892004-09-13 14:53:28 +0000580 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000581 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000582 3 SampleClass
Tim Peters958cc892004-09-13 14:53:28 +0000583 3 SampleClass.NestedClass
584 1 SampleClass.NestedClass.__init__
Edward Loper32ddbf72004-09-13 05:47:24 +0000585 0 SampleClass.NestedClass.get
586 0 SampleClass.NestedClass.square
Tim Peters8485b562004-08-04 18:46:34 +0000587 1 SampleClass.__init__
Tim Peters8485b562004-08-04 18:46:34 +0000588 2 SampleClass.a_classmethod
589 1 SampleClass.a_property
590 1 SampleClass.a_staticmethod
591 1 SampleClass.double
592 1 SampleClass.get
593
Tim Peters8485b562004-08-04 18:46:34 +0000594Turning off Recursion
595~~~~~~~~~~~~~~~~~~~~~
596DocTestFinder can be told not to look for tests in contained objects
597using the `recurse` flag:
598
599 >>> tests = doctest.DocTestFinder(recurse=False).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000600 >>> for t in tests:
Guido van Rossum7131f842007-02-09 20:13:25 +0000601 ... print('%2s %s' % (len(t.examples), t.name))
Edward Loper4ae900f2004-09-21 03:20:34 +0000602 3 SampleClass
Edward Loperb51b2342004-08-17 16:37:12 +0000603
604Line numbers
605~~~~~~~~~~~~
606DocTestFinder finds the line number of each example:
607
608 >>> def f(x):
609 ... '''
610 ... >>> x = 12
611 ...
612 ... some text
613 ...
614 ... >>> # examples are not created for comments & bare prompts.
615 ... >>>
616 ... ...
617 ...
618 ... >>> for x in range(10):
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000619 ... ... print(x, end=' ')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000620 ... 0 1 2 3 4 5 6 7 8 9
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000621 ... >>> x//2
622 ... 6
Edward Loperb51b2342004-08-17 16:37:12 +0000623 ... '''
624 >>> test = doctest.DocTestFinder().find(f)[0]
625 >>> [e.lineno for e in test.examples]
626 [1, 9, 12]
Tim Peters8485b562004-08-04 18:46:34 +0000627"""
628
Edward Loper00f8da72004-08-26 18:05:07 +0000629def test_DocTestParser(): r"""
630Unit tests for the `DocTestParser` class.
631
632DocTestParser is used to parse docstrings containing doctest examples.
633
634The `parse` method divides a docstring into examples and intervening
635text:
636
637 >>> s = '''
638 ... >>> x, y = 2, 3 # no output expected
639 ... >>> if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000640 ... ... print(x)
641 ... ... print(y)
Edward Loper00f8da72004-08-26 18:05:07 +0000642 ... 2
643 ... 3
644 ...
645 ... Some text.
646 ... >>> x+y
647 ... 5
648 ... '''
649 >>> parser = doctest.DocTestParser()
650 >>> for piece in parser.parse(s):
651 ... if isinstance(piece, doctest.Example):
Guido van Rossum7131f842007-02-09 20:13:25 +0000652 ... print('Example:', (piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000653 ... else:
Guido van Rossum7131f842007-02-09 20:13:25 +0000654 ... print(' Text:', repr(piece))
Edward Loper00f8da72004-08-26 18:05:07 +0000655 Text: '\n'
656 Example: ('x, y = 2, 3 # no output expected\n', '', 1)
657 Text: ''
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000658 Example: ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000659 Text: '\nSome text.\n'
660 Example: ('x+y\n', '5\n', 9)
661 Text: ''
662
663The `get_examples` method returns just the examples:
664
665 >>> for piece in parser.get_examples(s):
Guido van Rossum7131f842007-02-09 20:13:25 +0000666 ... print((piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000667 ('x, y = 2, 3 # no output expected\n', '', 1)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000668 ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000669 ('x+y\n', '5\n', 9)
670
671The `get_doctest` method creates a Test from the examples, along with the
672given arguments:
673
674 >>> test = parser.get_doctest(s, {}, 'name', 'filename', lineno=5)
675 >>> (test.name, test.filename, test.lineno)
676 ('name', 'filename', 5)
677 >>> for piece in test.examples:
Guido van Rossum7131f842007-02-09 20:13:25 +0000678 ... print((piece.source, piece.want, piece.lineno))
Edward Loper00f8da72004-08-26 18:05:07 +0000679 ('x, y = 2, 3 # no output expected\n', '', 1)
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000680 ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Edward Loper00f8da72004-08-26 18:05:07 +0000681 ('x+y\n', '5\n', 9)
682"""
683
Tim Peters8485b562004-08-04 18:46:34 +0000684class test_DocTestRunner:
685 def basics(): r"""
686Unit tests for the `DocTestRunner` class.
687
688DocTestRunner is used to run DocTest test cases, and to accumulate
689statistics. Here's a simple DocTest case we can use:
690
691 >>> def f(x):
692 ... '''
693 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000694 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000695 ... 12
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000696 ... >>> x//2
697 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000698 ... '''
699 >>> test = doctest.DocTestFinder().find(f)[0]
700
701The main DocTestRunner interface is the `run` method, which runs a
702given DocTest case in a given namespace (globs). It returns a tuple
703`(f,t)`, where `f` is the number of failed tests and `t` is the number
704of tried tests.
705
706 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000707 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000708
709If any example produces incorrect output, then the test runner reports
710the failure and proceeds to the next example:
711
712 >>> def f(x):
713 ... '''
714 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000715 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000716 ... 14
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000717 ... >>> x//2
718 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000719 ... '''
720 >>> test = doctest.DocTestFinder().find(f)[0]
721 >>> doctest.DocTestRunner(verbose=True).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000722 ... # doctest: +ELLIPSIS
Edward Loperaacf0832004-08-26 01:19:50 +0000723 Trying:
724 x = 12
725 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000726 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000727 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000728 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000729 Expecting:
730 14
Tim Peters8485b562004-08-04 18:46:34 +0000731 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000732 File ..., line 4, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000733 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000734 print(x)
Jim Fulton07a349c2004-08-22 14:10:00 +0000735 Expected:
736 14
737 Got:
738 12
Edward Loperaacf0832004-08-26 01:19:50 +0000739 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000740 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000741 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000742 6
Tim Peters8485b562004-08-04 18:46:34 +0000743 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000744 TestResults(failed=1, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000745"""
746 def verbose_flag(): r"""
747The `verbose` flag makes the test runner generate more detailed
748output:
749
750 >>> def f(x):
751 ... '''
752 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000753 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +0000754 ... 12
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000755 ... >>> x//2
756 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000757 ... '''
758 >>> test = doctest.DocTestFinder().find(f)[0]
759
760 >>> doctest.DocTestRunner(verbose=True).run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000761 Trying:
762 x = 12
763 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000764 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000765 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000766 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000767 Expecting:
768 12
Tim Peters8485b562004-08-04 18:46:34 +0000769 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000770 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000771 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000772 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000773 6
Tim Peters8485b562004-08-04 18:46:34 +0000774 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000775 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000776
777If the `verbose` flag is unspecified, then the output will be verbose
778iff `-v` appears in sys.argv:
779
780 >>> # Save the real sys.argv list.
781 >>> old_argv = sys.argv
782
783 >>> # If -v does not appear in sys.argv, then output isn't verbose.
784 >>> sys.argv = ['test']
785 >>> doctest.DocTestRunner().run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000786 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000787
788 >>> # If -v does appear in sys.argv, then output is verbose.
789 >>> sys.argv = ['test', '-v']
790 >>> doctest.DocTestRunner().run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000791 Trying:
792 x = 12
793 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000794 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000795 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000796 print(x)
Edward Loperaacf0832004-08-26 01:19:50 +0000797 Expecting:
798 12
Tim Peters8485b562004-08-04 18:46:34 +0000799 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000800 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000801 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000802 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000803 6
Tim Peters8485b562004-08-04 18:46:34 +0000804 ok
Christian Heimes25bb7832008-01-11 16:17:00 +0000805 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000806
807 >>> # Restore sys.argv
808 >>> sys.argv = old_argv
809
810In the remaining examples, the test runner's verbosity will be
811explicitly set, to ensure that the test behavior is consistent.
812 """
813 def exceptions(): r"""
814Tests of `DocTestRunner`'s exception handling.
815
816An expected exception is specified with a traceback message. The
817lines between the first line and the type/value may be omitted or
818replaced with any other string:
819
820 >>> def f(x):
821 ... '''
822 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000823 ... >>> print(x//0)
Tim Peters8485b562004-08-04 18:46:34 +0000824 ... Traceback (most recent call last):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000825 ... ZeroDivisionError: integer division or modulo by zero
Tim Peters8485b562004-08-04 18:46:34 +0000826 ... '''
827 >>> test = doctest.DocTestFinder().find(f)[0]
828 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000829 TestResults(failed=0, attempted=2)
Tim Peters8485b562004-08-04 18:46:34 +0000830
Edward Loper19b19582004-08-25 23:07:03 +0000831An example may not generate output before it raises an exception; if
832it does, then the traceback message will not be recognized as
833signaling an expected exception, so the example will be reported as an
834unexpected exception:
Tim Peters8485b562004-08-04 18:46:34 +0000835
836 >>> def f(x):
837 ... '''
838 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000839 ... >>> print('pre-exception output', x//0)
Tim Peters8485b562004-08-04 18:46:34 +0000840 ... pre-exception output
841 ... Traceback (most recent call last):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000842 ... ZeroDivisionError: integer division or modulo by zero
Tim Peters8485b562004-08-04 18:46:34 +0000843 ... '''
844 >>> test = doctest.DocTestFinder().find(f)[0]
845 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper19b19582004-08-25 23:07:03 +0000846 ... # doctest: +ELLIPSIS
847 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000848 File ..., line 4, in f
Edward Loper19b19582004-08-25 23:07:03 +0000849 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +0000850 print('pre-exception output', x//0)
Edward Loper19b19582004-08-25 23:07:03 +0000851 Exception raised:
852 ...
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000853 ZeroDivisionError: integer division or modulo by zero
Christian Heimes25bb7832008-01-11 16:17:00 +0000854 TestResults(failed=1, attempted=2)
Tim Peters8485b562004-08-04 18:46:34 +0000855
856Exception messages may contain newlines:
857
858 >>> def f(x):
859 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000860 ... >>> raise ValueError('multi\nline\nmessage')
Tim Peters8485b562004-08-04 18:46:34 +0000861 ... Traceback (most recent call last):
862 ... ValueError: multi
863 ... line
864 ... message
865 ... '''
866 >>> test = doctest.DocTestFinder().find(f)[0]
867 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000868 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000869
870If an exception is expected, but an exception with the wrong type or
871message is raised, then it is reported as a failure:
872
873 >>> def f(x):
874 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000875 ... >>> raise ValueError('message')
Tim Peters8485b562004-08-04 18:46:34 +0000876 ... Traceback (most recent call last):
877 ... ValueError: wrong message
878 ... '''
879 >>> test = doctest.DocTestFinder().find(f)[0]
880 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000881 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000882 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000883 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000884 Failed example:
Collin Winter3add4d72007-08-29 23:37:32 +0000885 raise ValueError('message')
Tim Peters8485b562004-08-04 18:46:34 +0000886 Expected:
887 Traceback (most recent call last):
888 ValueError: wrong message
889 Got:
890 Traceback (most recent call last):
Edward Loper8e4a34b2004-08-12 02:34:27 +0000891 ...
Tim Peters8485b562004-08-04 18:46:34 +0000892 ValueError: message
Christian Heimes25bb7832008-01-11 16:17:00 +0000893 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000894
Tim Peters1fbf9c52004-09-04 17:21:02 +0000895However, IGNORE_EXCEPTION_DETAIL can be used to allow a mismatch in the
896detail:
897
898 >>> def f(x):
899 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000900 ... >>> raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +0000901 ... Traceback (most recent call last):
902 ... ValueError: wrong message
903 ... '''
904 >>> test = doctest.DocTestFinder().find(f)[0]
905 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +0000906 TestResults(failed=0, attempted=1)
Tim Peters1fbf9c52004-09-04 17:21:02 +0000907
Nick Coghlan5e76e942010-06-12 13:42:46 +0000908IGNORE_EXCEPTION_DETAIL also ignores difference in exception formatting
909between Python versions. For example, in Python 2.x, the module path of
910the exception is not in the output, but this will fail under Python 3:
911
912 >>> def f(x):
913 ... r'''
914 ... >>> from http.client import HTTPException
915 ... >>> raise HTTPException('message')
916 ... Traceback (most recent call last):
917 ... HTTPException: message
918 ... '''
919 >>> test = doctest.DocTestFinder().find(f)[0]
920 >>> doctest.DocTestRunner(verbose=False).run(test)
921 ... # doctest: +ELLIPSIS
922 **********************************************************************
923 File ..., line 4, in f
924 Failed example:
925 raise HTTPException('message')
926 Expected:
927 Traceback (most recent call last):
928 HTTPException: message
929 Got:
930 Traceback (most recent call last):
931 ...
932 http.client.HTTPException: message
933 TestResults(failed=1, attempted=2)
934
935But in Python 3 the module path is included, and therefore a test must look
936like the following test to succeed in Python 3. But that test will fail under
937Python 2.
938
939 >>> def f(x):
940 ... r'''
941 ... >>> from http.client import HTTPException
942 ... >>> raise HTTPException('message')
943 ... Traceback (most recent call last):
944 ... http.client.HTTPException: message
945 ... '''
946 >>> test = doctest.DocTestFinder().find(f)[0]
947 >>> doctest.DocTestRunner(verbose=False).run(test)
948 TestResults(failed=0, attempted=2)
949
950However, with IGNORE_EXCEPTION_DETAIL, the module name of the exception
951(or its unexpected absence) will be ignored:
952
953 >>> def f(x):
954 ... r'''
955 ... >>> from http.client import HTTPException
956 ... >>> raise HTTPException('message') #doctest: +IGNORE_EXCEPTION_DETAIL
957 ... Traceback (most recent call last):
958 ... HTTPException: message
959 ... '''
960 >>> test = doctest.DocTestFinder().find(f)[0]
961 >>> doctest.DocTestRunner(verbose=False).run(test)
962 TestResults(failed=0, attempted=2)
963
964The module path will be completely ignored, so two different module paths will
965still pass if IGNORE_EXCEPTION_DETAIL is given. This is intentional, so it can
966be used when exceptions have changed module.
967
968 >>> def f(x):
969 ... r'''
970 ... >>> from http.client import HTTPException
971 ... >>> raise HTTPException('message') #doctest: +IGNORE_EXCEPTION_DETAIL
972 ... Traceback (most recent call last):
973 ... foo.bar.HTTPException: message
974 ... '''
975 >>> test = doctest.DocTestFinder().find(f)[0]
976 >>> doctest.DocTestRunner(verbose=False).run(test)
977 TestResults(failed=0, attempted=2)
978
Tim Peters1fbf9c52004-09-04 17:21:02 +0000979But IGNORE_EXCEPTION_DETAIL does not allow a mismatch in the exception type:
980
981 >>> def f(x):
982 ... r'''
Collin Winter3add4d72007-08-29 23:37:32 +0000983 ... >>> raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +0000984 ... Traceback (most recent call last):
985 ... TypeError: wrong type
986 ... '''
987 >>> test = doctest.DocTestFinder().find(f)[0]
988 >>> doctest.DocTestRunner(verbose=False).run(test)
989 ... # doctest: +ELLIPSIS
990 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000991 File ..., line 3, in f
Tim Peters1fbf9c52004-09-04 17:21:02 +0000992 Failed example:
Collin Winter3add4d72007-08-29 23:37:32 +0000993 raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
Tim Peters1fbf9c52004-09-04 17:21:02 +0000994 Expected:
995 Traceback (most recent call last):
996 TypeError: wrong type
997 Got:
998 Traceback (most recent call last):
999 ...
1000 ValueError: message
Christian Heimes25bb7832008-01-11 16:17:00 +00001001 TestResults(failed=1, attempted=1)
Tim Peters1fbf9c52004-09-04 17:21:02 +00001002
Tim Peters8485b562004-08-04 18:46:34 +00001003If an exception is raised but not expected, then it is reported as an
1004unexpected exception:
1005
Tim Peters8485b562004-08-04 18:46:34 +00001006 >>> def f(x):
1007 ... r'''
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001008 ... >>> 1//0
Tim Peters8485b562004-08-04 18:46:34 +00001009 ... 0
1010 ... '''
1011 >>> test = doctest.DocTestFinder().find(f)[0]
1012 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper74bca7a2004-08-12 02:27:44 +00001013 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001014 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001015 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001016 Failed example:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001017 1//0
Tim Peters8485b562004-08-04 18:46:34 +00001018 Exception raised:
1019 Traceback (most recent call last):
Jim Fulton07a349c2004-08-22 14:10:00 +00001020 ...
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001021 ZeroDivisionError: integer division or modulo by zero
Christian Heimes25bb7832008-01-11 16:17:00 +00001022 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001023"""
Georg Brandl25fbb892010-07-30 09:23:23 +00001024 def displayhook(): r"""
1025Test that changing sys.displayhook doesn't matter for doctest.
1026
1027 >>> import sys
1028 >>> orig_displayhook = sys.displayhook
1029 >>> def my_displayhook(x):
1030 ... print('hi!')
1031 >>> sys.displayhook = my_displayhook
1032 >>> def f():
1033 ... '''
1034 ... >>> 3
1035 ... 3
1036 ... '''
1037 >>> test = doctest.DocTestFinder().find(f)[0]
1038 >>> r = doctest.DocTestRunner(verbose=False).run(test)
1039 >>> post_displayhook = sys.displayhook
1040
1041 We need to restore sys.displayhook now, so that we'll be able to test
1042 results.
1043
1044 >>> sys.displayhook = orig_displayhook
1045
1046 Ok, now we can check that everything is ok.
1047
1048 >>> r
1049 TestResults(failed=0, attempted=1)
1050 >>> post_displayhook is my_displayhook
1051 True
1052"""
Tim Peters8485b562004-08-04 18:46:34 +00001053 def optionflags(): r"""
1054Tests of `DocTestRunner`'s option flag handling.
1055
1056Several option flags can be used to customize the behavior of the test
1057runner. These are defined as module constants in doctest, and passed
Christian Heimesfaf2f632008-01-06 16:59:19 +00001058to the DocTestRunner constructor (multiple constants should be ORed
Tim Peters8485b562004-08-04 18:46:34 +00001059together).
1060
1061The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
1062and 1/0:
1063
1064 >>> def f(x):
1065 ... '>>> True\n1\n'
1066
1067 >>> # Without the flag:
1068 >>> test = doctest.DocTestFinder().find(f)[0]
1069 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001070 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001071
1072 >>> # With the flag:
1073 >>> test = doctest.DocTestFinder().find(f)[0]
1074 >>> flags = doctest.DONT_ACCEPT_TRUE_FOR_1
1075 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001076 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001077 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001078 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001079 Failed example:
1080 True
1081 Expected:
1082 1
1083 Got:
1084 True
Christian Heimes25bb7832008-01-11 16:17:00 +00001085 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001086
1087The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines
1088and the '<BLANKLINE>' marker:
1089
1090 >>> def f(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001091 ... '>>> print("a\\n\\nb")\na\n<BLANKLINE>\nb\n'
Tim Peters8485b562004-08-04 18:46:34 +00001092
1093 >>> # Without the flag:
1094 >>> test = doctest.DocTestFinder().find(f)[0]
1095 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001096 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001097
1098 >>> # With the flag:
1099 >>> test = doctest.DocTestFinder().find(f)[0]
1100 >>> flags = doctest.DONT_ACCEPT_BLANKLINE
1101 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001102 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001103 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001104 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001105 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001106 print("a\n\nb")
Tim Peters8485b562004-08-04 18:46:34 +00001107 Expected:
1108 a
1109 <BLANKLINE>
1110 b
1111 Got:
1112 a
1113 <BLANKLINE>
1114 b
Christian Heimes25bb7832008-01-11 16:17:00 +00001115 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001116
1117The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be
1118treated as equal:
1119
1120 >>> def f(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001121 ... '>>> print(1, 2, 3)\n 1 2\n 3'
Tim Peters8485b562004-08-04 18:46:34 +00001122
1123 >>> # Without the flag:
1124 >>> test = doctest.DocTestFinder().find(f)[0]
1125 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001126 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001127 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001128 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001129 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001130 print(1, 2, 3)
Tim Peters8485b562004-08-04 18:46:34 +00001131 Expected:
1132 1 2
1133 3
Jim Fulton07a349c2004-08-22 14:10:00 +00001134 Got:
1135 1 2 3
Christian Heimes25bb7832008-01-11 16:17:00 +00001136 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001137
1138 >>> # With the flag:
1139 >>> test = doctest.DocTestFinder().find(f)[0]
1140 >>> flags = doctest.NORMALIZE_WHITESPACE
1141 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001142 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001143
Tim Peters026f8dc2004-08-19 16:38:58 +00001144 An example from the docs:
Guido van Rossum805365e2007-05-07 22:24:25 +00001145 >>> print(list(range(20))) #doctest: +NORMALIZE_WHITESPACE
Tim Peters026f8dc2004-08-19 16:38:58 +00001146 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
1147 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
1148
Tim Peters8485b562004-08-04 18:46:34 +00001149The ELLIPSIS flag causes ellipsis marker ("...") in the expected
1150output to match any substring in the actual output:
1151
1152 >>> def f(x):
Guido van Rossum805365e2007-05-07 22:24:25 +00001153 ... '>>> print(list(range(15)))\n[0, 1, 2, ..., 14]\n'
Tim Peters8485b562004-08-04 18:46:34 +00001154
1155 >>> # Without the flag:
1156 >>> test = doctest.DocTestFinder().find(f)[0]
1157 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001158 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001159 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001160 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001161 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001162 print(list(range(15)))
Jim Fulton07a349c2004-08-22 14:10:00 +00001163 Expected:
1164 [0, 1, 2, ..., 14]
1165 Got:
1166 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
Christian Heimes25bb7832008-01-11 16:17:00 +00001167 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001168
1169 >>> # With the flag:
1170 >>> test = doctest.DocTestFinder().find(f)[0]
1171 >>> flags = doctest.ELLIPSIS
1172 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001173 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001174
Tim Peterse594bee2004-08-22 01:47:51 +00001175 ... also matches nothing:
Tim Peters1cf3aa62004-08-19 06:49:33 +00001176
Guido van Rossume0192e52007-02-09 23:39:59 +00001177 >>> if 1:
1178 ... for i in range(100):
1179 ... print(i**2, end=' ') #doctest: +ELLIPSIS
1180 ... print('!')
1181 0 1...4...9 16 ... 36 49 64 ... 9801 !
Tim Peters1cf3aa62004-08-19 06:49:33 +00001182
Tim Peters026f8dc2004-08-19 16:38:58 +00001183 ... can be surprising; e.g., this test passes:
Tim Peters26b3ebb2004-08-19 08:10:08 +00001184
Guido van Rossume0192e52007-02-09 23:39:59 +00001185 >>> if 1: #doctest: +ELLIPSIS
1186 ... for i in range(20):
1187 ... print(i, end=' ')
1188 ... print(20)
Tim Peterse594bee2004-08-22 01:47:51 +00001189 0 1 2 ...1...2...0
Tim Peters26b3ebb2004-08-19 08:10:08 +00001190
Tim Peters026f8dc2004-08-19 16:38:58 +00001191 Examples from the docs:
1192
Guido van Rossum805365e2007-05-07 22:24:25 +00001193 >>> print(list(range(20))) # doctest:+ELLIPSIS
Tim Peters026f8dc2004-08-19 16:38:58 +00001194 [0, 1, ..., 18, 19]
1195
Guido van Rossum805365e2007-05-07 22:24:25 +00001196 >>> print(list(range(20))) # doctest: +ELLIPSIS
Tim Peters026f8dc2004-08-19 16:38:58 +00001197 ... # doctest: +NORMALIZE_WHITESPACE
1198 [0, 1, ..., 18, 19]
1199
Thomas Wouters477c8d52006-05-27 19:21:47 +00001200The SKIP flag causes an example to be skipped entirely. I.e., the
1201example is not run. It can be useful in contexts where doctest
1202examples serve as both documentation and test cases, and an example
1203should be included for documentation purposes, but should not be
1204checked (e.g., because its output is random, or depends on resources
1205which would be unavailable.) The SKIP flag can also be used for
1206'commenting out' broken examples.
1207
1208 >>> import unavailable_resource # doctest: +SKIP
1209 >>> unavailable_resource.do_something() # doctest: +SKIP
1210 >>> unavailable_resource.blow_up() # doctest: +SKIP
1211 Traceback (most recent call last):
1212 ...
1213 UncheckedBlowUpError: Nobody checks me.
1214
1215 >>> import random
Guido van Rossum7131f842007-02-09 20:13:25 +00001216 >>> print(random.random()) # doctest: +SKIP
Thomas Wouters477c8d52006-05-27 19:21:47 +00001217 0.721216923889
1218
Edward Loper71f55af2004-08-26 01:41:51 +00001219The REPORT_UDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001220and actual outputs to be displayed using a unified diff:
1221
1222 >>> def f(x):
1223 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001224 ... >>> print('\n'.join('abcdefg'))
Tim Peters8485b562004-08-04 18:46:34 +00001225 ... a
1226 ... B
1227 ... c
1228 ... d
1229 ... f
1230 ... g
1231 ... h
1232 ... '''
1233
1234 >>> # Without the flag:
1235 >>> test = doctest.DocTestFinder().find(f)[0]
1236 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001237 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001238 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001239 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001240 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001241 print('\n'.join('abcdefg'))
Tim Peters8485b562004-08-04 18:46:34 +00001242 Expected:
1243 a
1244 B
1245 c
1246 d
1247 f
1248 g
1249 h
1250 Got:
1251 a
1252 b
1253 c
1254 d
1255 e
1256 f
1257 g
Christian Heimes25bb7832008-01-11 16:17:00 +00001258 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001259
1260 >>> # With the flag:
1261 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001262 >>> flags = doctest.REPORT_UDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001263 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001264 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001265 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001266 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001267 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001268 print('\n'.join('abcdefg'))
Edward Loper56629292004-08-26 01:31:56 +00001269 Differences (unified diff with -expected +actual):
Tim Peterse7edcb82004-08-26 05:44:27 +00001270 @@ -1,7 +1,7 @@
Tim Peters8485b562004-08-04 18:46:34 +00001271 a
1272 -B
1273 +b
1274 c
1275 d
1276 +e
1277 f
1278 g
1279 -h
Christian Heimes25bb7832008-01-11 16:17:00 +00001280 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001281
Edward Loper71f55af2004-08-26 01:41:51 +00001282The REPORT_CDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001283and actual outputs to be displayed using a context diff:
1284
Edward Loper71f55af2004-08-26 01:41:51 +00001285 >>> # Reuse f() from the REPORT_UDIFF example, above.
Tim Peters8485b562004-08-04 18:46:34 +00001286 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001287 >>> flags = doctest.REPORT_CDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001288 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001289 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001290 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001291 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001292 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001293 print('\n'.join('abcdefg'))
Edward Loper56629292004-08-26 01:31:56 +00001294 Differences (context diff with expected followed by actual):
Tim Peters8485b562004-08-04 18:46:34 +00001295 ***************
Tim Peterse7edcb82004-08-26 05:44:27 +00001296 *** 1,7 ****
Tim Peters8485b562004-08-04 18:46:34 +00001297 a
1298 ! B
1299 c
1300 d
1301 f
1302 g
1303 - h
Tim Peterse7edcb82004-08-26 05:44:27 +00001304 --- 1,7 ----
Tim Peters8485b562004-08-04 18:46:34 +00001305 a
1306 ! b
1307 c
1308 d
1309 + e
1310 f
1311 g
Christian Heimes25bb7832008-01-11 16:17:00 +00001312 TestResults(failed=1, attempted=1)
Tim Petersc6cbab02004-08-22 19:43:28 +00001313
1314
Edward Loper71f55af2004-08-26 01:41:51 +00001315The REPORT_NDIFF flag causes failures to use the difflib.Differ algorithm
Tim Petersc6cbab02004-08-22 19:43:28 +00001316used by the popular ndiff.py utility. This does intraline difference
1317marking, as well as interline differences.
1318
1319 >>> def f(x):
1320 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001321 ... >>> print("a b c d e f g h i j k l m")
Tim Petersc6cbab02004-08-22 19:43:28 +00001322 ... a b c d e f g h i j k 1 m
1323 ... '''
1324 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001325 >>> flags = doctest.REPORT_NDIFF
Tim Petersc6cbab02004-08-22 19:43:28 +00001326 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001327 ... # doctest: +ELLIPSIS
Tim Petersc6cbab02004-08-22 19:43:28 +00001328 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001329 File ..., line 3, in f
Tim Petersc6cbab02004-08-22 19:43:28 +00001330 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001331 print("a b c d e f g h i j k l m")
Tim Petersc6cbab02004-08-22 19:43:28 +00001332 Differences (ndiff with -expected +actual):
1333 - a b c d e f g h i j k 1 m
1334 ? ^
1335 + a b c d e f g h i j k l m
1336 ? + ++ ^
Christian Heimes25bb7832008-01-11 16:17:00 +00001337 TestResults(failed=1, attempted=1)
Edward Lopera89f88d2004-08-26 02:45:51 +00001338
Ezio Melotti13925002011-03-16 11:05:33 +02001339The REPORT_ONLY_FIRST_FAILURE suppresses result output after the first
Edward Lopera89f88d2004-08-26 02:45:51 +00001340failing example:
1341
1342 >>> def f(x):
1343 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001344 ... >>> print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001345 ... 1
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001346 ... >>> print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001347 ... 200
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001348 ... >>> print(3) # second failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001349 ... 300
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001350 ... >>> print(4) # second success
Edward Lopera89f88d2004-08-26 02:45:51 +00001351 ... 4
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001352 ... >>> print(5) # third failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001353 ... 500
1354 ... '''
1355 >>> test = doctest.DocTestFinder().find(f)[0]
1356 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1357 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001358 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001359 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001360 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001361 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001362 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001363 Expected:
1364 200
1365 Got:
1366 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001367 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001368
Ezio Melotti13925002011-03-16 11:05:33 +02001369However, output from `report_start` is not suppressed:
Edward Lopera89f88d2004-08-26 02:45:51 +00001370
1371 >>> doctest.DocTestRunner(verbose=True, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001372 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001373 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001374 print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001375 Expecting:
1376 1
1377 ok
1378 Trying:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001379 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001380 Expecting:
1381 200
1382 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001383 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001384 Failed example:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001385 print(2) # first failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001386 Expected:
1387 200
1388 Got:
1389 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001390 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001391
1392For the purposes of REPORT_ONLY_FIRST_FAILURE, unexpected exceptions
1393count as failures:
1394
1395 >>> def f(x):
1396 ... r'''
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001397 ... >>> print(1) # first success
Edward Lopera89f88d2004-08-26 02:45:51 +00001398 ... 1
1399 ... >>> raise ValueError(2) # first failure
1400 ... 200
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001401 ... >>> print(3) # second failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001402 ... 300
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001403 ... >>> print(4) # second success
Edward Lopera89f88d2004-08-26 02:45:51 +00001404 ... 4
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001405 ... >>> print(5) # third failure
Edward Lopera89f88d2004-08-26 02:45:51 +00001406 ... 500
1407 ... '''
1408 >>> test = doctest.DocTestFinder().find(f)[0]
1409 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1410 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1411 ... # doctest: +ELLIPSIS
1412 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001413 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001414 Failed example:
1415 raise ValueError(2) # first failure
1416 Exception raised:
1417 ...
1418 ValueError: 2
Christian Heimes25bb7832008-01-11 16:17:00 +00001419 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001420
Thomas Wouters477c8d52006-05-27 19:21:47 +00001421New option flags can also be registered, via register_optionflag(). Here
1422we reach into doctest's internals a bit.
1423
1424 >>> unlikely = "UNLIKELY_OPTION_NAME"
1425 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1426 False
1427 >>> new_flag_value = doctest.register_optionflag(unlikely)
1428 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1429 True
1430
1431Before 2.4.4/2.5, registering a name more than once erroneously created
1432more than one flag value. Here we verify that's fixed:
1433
1434 >>> redundant_flag_value = doctest.register_optionflag(unlikely)
1435 >>> redundant_flag_value == new_flag_value
1436 True
1437
1438Clean up.
1439 >>> del doctest.OPTIONFLAGS_BY_NAME[unlikely]
1440
Tim Petersc6cbab02004-08-22 19:43:28 +00001441 """
1442
Tim Peters8485b562004-08-04 18:46:34 +00001443 def option_directives(): r"""
1444Tests of `DocTestRunner`'s option directive mechanism.
1445
Edward Loper74bca7a2004-08-12 02:27:44 +00001446Option directives can be used to turn option flags on or off for a
1447single example. To turn an option on for an example, follow that
1448example with a comment of the form ``# doctest: +OPTION``:
Tim Peters8485b562004-08-04 18:46:34 +00001449
1450 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001451 ... >>> print(list(range(10))) # should fail: no ellipsis
Edward Loper74bca7a2004-08-12 02:27:44 +00001452 ... [0, 1, ..., 9]
1453 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001454 ... >>> print(list(range(10))) # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001455 ... [0, 1, ..., 9]
1456 ... '''
1457 >>> test = doctest.DocTestFinder().find(f)[0]
1458 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001459 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001460 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001461 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001462 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001463 print(list(range(10))) # should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001464 Expected:
1465 [0, 1, ..., 9]
1466 Got:
1467 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001468 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001469
1470To turn an option off for an example, follow that example with a
1471comment of the form ``# doctest: -OPTION``:
1472
1473 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001474 ... >>> print(list(range(10)))
Edward Loper74bca7a2004-08-12 02:27:44 +00001475 ... [0, 1, ..., 9]
1476 ...
1477 ... >>> # should fail: no ellipsis
Guido van Rossum805365e2007-05-07 22:24:25 +00001478 ... >>> print(list(range(10))) # doctest: -ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001479 ... [0, 1, ..., 9]
1480 ... '''
1481 >>> test = doctest.DocTestFinder().find(f)[0]
1482 >>> doctest.DocTestRunner(verbose=False,
1483 ... optionflags=doctest.ELLIPSIS).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001484 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001485 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001486 File ..., line 6, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001487 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001488 print(list(range(10))) # doctest: -ELLIPSIS
Jim Fulton07a349c2004-08-22 14:10:00 +00001489 Expected:
1490 [0, 1, ..., 9]
1491 Got:
1492 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001493 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001494
1495Option directives affect only the example that they appear with; they
1496do not change the options for surrounding examples:
Edward Loper8e4a34b2004-08-12 02:34:27 +00001497
Edward Loper74bca7a2004-08-12 02:27:44 +00001498 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001499 ... >>> print(list(range(10))) # Should fail: no ellipsis
Tim Peters8485b562004-08-04 18:46:34 +00001500 ... [0, 1, ..., 9]
1501 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001502 ... >>> print(list(range(10))) # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001503 ... [0, 1, ..., 9]
1504 ...
Guido van Rossum805365e2007-05-07 22:24:25 +00001505 ... >>> print(list(range(10))) # Should fail: no ellipsis
Tim Peters8485b562004-08-04 18:46:34 +00001506 ... [0, 1, ..., 9]
1507 ... '''
1508 >>> test = doctest.DocTestFinder().find(f)[0]
1509 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001510 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001511 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001512 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001513 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001514 print(list(range(10))) # Should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001515 Expected:
1516 [0, 1, ..., 9]
1517 Got:
1518 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001519 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001520 File ..., line 8, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001521 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001522 print(list(range(10))) # Should fail: no ellipsis
Jim Fulton07a349c2004-08-22 14:10:00 +00001523 Expected:
1524 [0, 1, ..., 9]
1525 Got:
1526 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001527 TestResults(failed=2, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +00001528
Edward Loper74bca7a2004-08-12 02:27:44 +00001529Multiple options may be modified by a single option directive. They
1530may be separated by whitespace, commas, or both:
Tim Peters8485b562004-08-04 18:46:34 +00001531
1532 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001533 ... >>> print(list(range(10))) # Should fail
Tim Peters8485b562004-08-04 18:46:34 +00001534 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001535 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001536 ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001537 ... [0, 1, ..., 9]
1538 ... '''
1539 >>> test = doctest.DocTestFinder().find(f)[0]
1540 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001541 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001542 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001543 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001544 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001545 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001546 Expected:
1547 [0, 1, ..., 9]
1548 Got:
1549 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001550 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001551
1552 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001553 ... >>> print(list(range(10))) # Should fail
Edward Loper74bca7a2004-08-12 02:27:44 +00001554 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001555 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001556 ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
1557 ... [0, 1, ..., 9]
1558 ... '''
1559 >>> test = doctest.DocTestFinder().find(f)[0]
1560 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001561 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001562 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001563 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001564 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001565 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001566 Expected:
1567 [0, 1, ..., 9]
1568 Got:
1569 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001570 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001571
1572 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001573 ... >>> print(list(range(10))) # Should fail
Edward Loper74bca7a2004-08-12 02:27:44 +00001574 ... [0, 1, ..., 9]
Guido van Rossum805365e2007-05-07 22:24:25 +00001575 ... >>> print(list(range(10))) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001576 ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1577 ... [0, 1, ..., 9]
1578 ... '''
1579 >>> test = doctest.DocTestFinder().find(f)[0]
1580 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001581 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001582 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001583 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001584 Failed example:
Guido van Rossum805365e2007-05-07 22:24:25 +00001585 print(list(range(10))) # Should fail
Jim Fulton07a349c2004-08-22 14:10:00 +00001586 Expected:
1587 [0, 1, ..., 9]
1588 Got:
1589 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Christian Heimes25bb7832008-01-11 16:17:00 +00001590 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001591
1592The option directive may be put on the line following the source, as
1593long as a continuation prompt is used:
1594
1595 >>> def f(x): r'''
Guido van Rossum805365e2007-05-07 22:24:25 +00001596 ... >>> print(list(range(10)))
Edward Loper74bca7a2004-08-12 02:27:44 +00001597 ... ... # doctest: +ELLIPSIS
1598 ... [0, 1, ..., 9]
1599 ... '''
1600 >>> test = doctest.DocTestFinder().find(f)[0]
1601 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001602 TestResults(failed=0, attempted=1)
Edward Loper8e4a34b2004-08-12 02:34:27 +00001603
Edward Loper74bca7a2004-08-12 02:27:44 +00001604For examples with multi-line source, the option directive may appear
1605at the end of any line:
1606
1607 >>> def f(x): r'''
1608 ... >>> for x in range(10): # doctest: +ELLIPSIS
Guido van Rossum805365e2007-05-07 22:24:25 +00001609 ... ... print(' ', x, end='', sep='')
1610 ... 0 1 2 ... 9
Edward Loper74bca7a2004-08-12 02:27:44 +00001611 ...
1612 ... >>> for x in range(10):
Guido van Rossum805365e2007-05-07 22:24:25 +00001613 ... ... print(' ', x, end='', sep='') # doctest: +ELLIPSIS
1614 ... 0 1 2 ... 9
Edward Loper74bca7a2004-08-12 02:27:44 +00001615 ... '''
1616 >>> test = doctest.DocTestFinder().find(f)[0]
1617 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001618 TestResults(failed=0, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001619
1620If more than one line of an example with multi-line source has an
1621option directive, then they are combined:
1622
1623 >>> def f(x): r'''
1624 ... Should fail (option directive not on the last line):
1625 ... >>> for x in range(10): # doctest: +ELLIPSIS
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001626 ... ... print(x, end=' ') # doctest: +NORMALIZE_WHITESPACE
Guido van Rossumd8faa362007-04-27 19:54:29 +00001627 ... 0 1 2...9
Edward Loper74bca7a2004-08-12 02:27:44 +00001628 ... '''
1629 >>> test = doctest.DocTestFinder().find(f)[0]
1630 >>> doctest.DocTestRunner(verbose=False).run(test)
Christian Heimes25bb7832008-01-11 16:17:00 +00001631 TestResults(failed=0, attempted=1)
Edward Loper74bca7a2004-08-12 02:27:44 +00001632
1633It is an error to have a comment of the form ``# doctest:`` that is
1634*not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
1635``OPTION`` is an option that has been registered with
1636`register_option`:
1637
1638 >>> # Error: Option not registered
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001639 >>> s = '>>> print(12) #doctest: +BADOPTION'
Edward Loper74bca7a2004-08-12 02:27:44 +00001640 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1641 Traceback (most recent call last):
1642 ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
1643
1644 >>> # Error: No + or - prefix
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001645 >>> s = '>>> print(12) #doctest: ELLIPSIS'
Edward Loper74bca7a2004-08-12 02:27:44 +00001646 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1647 Traceback (most recent call last):
1648 ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
1649
1650It is an error to use an option directive on a line that contains no
1651source:
1652
1653 >>> s = '>>> # doctest: +ELLIPSIS'
1654 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1655 Traceback (most recent call last):
1656 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 +00001657"""
1658
1659def test_testsource(): r"""
1660Unit tests for `testsource()`.
1661
1662The testsource() function takes a module and a name, finds the (first)
Tim Peters19397e52004-08-06 22:02:59 +00001663test with that name in that module, and converts it to a script. The
1664example code is converted to regular Python code. The surrounding
1665words and expected output are converted to comments:
Tim Peters8485b562004-08-04 18:46:34 +00001666
1667 >>> import test.test_doctest
1668 >>> name = 'test.test_doctest.sample_func'
Guido van Rossum7131f842007-02-09 20:13:25 +00001669 >>> print(doctest.testsource(test.test_doctest, name))
Edward Lopera5db6002004-08-12 02:41:30 +00001670 # Blah blah
Tim Peters19397e52004-08-06 22:02:59 +00001671 #
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001672 print(sample_func(22))
Tim Peters8485b562004-08-04 18:46:34 +00001673 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001674 ## 44
Tim Peters19397e52004-08-06 22:02:59 +00001675 #
Edward Lopera5db6002004-08-12 02:41:30 +00001676 # Yee ha!
Georg Brandlecf93c72005-06-26 23:09:51 +00001677 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001678
1679 >>> name = 'test.test_doctest.SampleNewStyleClass'
Guido van Rossum7131f842007-02-09 20:13:25 +00001680 >>> print(doctest.testsource(test.test_doctest, name))
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001681 print('1\n2\n3')
Tim Peters8485b562004-08-04 18:46:34 +00001682 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001683 ## 1
1684 ## 2
1685 ## 3
Georg Brandlecf93c72005-06-26 23:09:51 +00001686 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001687
1688 >>> name = 'test.test_doctest.SampleClass.a_classmethod'
Guido van Rossum7131f842007-02-09 20:13:25 +00001689 >>> print(doctest.testsource(test.test_doctest, name))
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001690 print(SampleClass.a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +00001691 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001692 ## 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001693 print(SampleClass(0).a_classmethod(10))
Tim Peters8485b562004-08-04 18:46:34 +00001694 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001695 ## 12
Georg Brandlecf93c72005-06-26 23:09:51 +00001696 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001697"""
1698
1699def test_debug(): r"""
1700
1701Create a docstring that we want to debug:
1702
1703 >>> s = '''
1704 ... >>> x = 12
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001705 ... >>> print(x)
Tim Peters8485b562004-08-04 18:46:34 +00001706 ... 12
1707 ... '''
1708
1709Create some fake stdin input, to feed to the debugger:
1710
Tim Peters8485b562004-08-04 18:46:34 +00001711 >>> real_stdin = sys.stdin
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001712 >>> sys.stdin = _FakeInput(['next', 'print(x)', 'continue'])
Tim Peters8485b562004-08-04 18:46:34 +00001713
1714Run the debugger on the docstring, and then restore sys.stdin.
1715
Edward Loper2de91ba2004-08-27 02:07:46 +00001716 >>> try: doctest.debug_src(s)
1717 ... finally: sys.stdin = real_stdin
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001718 > <string>(1)<module>()
Edward Loper2de91ba2004-08-27 02:07:46 +00001719 (Pdb) next
1720 12
Tim Peters8485b562004-08-04 18:46:34 +00001721 --Return--
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001722 > <string>(1)<module>()->None
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001723 (Pdb) print(x)
Edward Loper2de91ba2004-08-27 02:07:46 +00001724 12
1725 (Pdb) continue
Tim Peters8485b562004-08-04 18:46:34 +00001726
1727"""
1728
Jim Fulton356fd192004-08-09 11:34:47 +00001729def test_pdb_set_trace():
Tim Peters50c6bdb2004-11-08 22:07:37 +00001730 """Using pdb.set_trace from a doctest.
Jim Fulton356fd192004-08-09 11:34:47 +00001731
Tim Peters413ced62004-08-09 15:43:47 +00001732 You can use pdb.set_trace from a doctest. To do so, you must
Jim Fulton356fd192004-08-09 11:34:47 +00001733 retrieve the set_trace function from the pdb module at the time
Tim Peters413ced62004-08-09 15:43:47 +00001734 you use it. The doctest module changes sys.stdout so that it can
1735 capture program output. It also temporarily replaces pdb.set_trace
1736 with a version that restores stdout. This is necessary for you to
Jim Fulton356fd192004-08-09 11:34:47 +00001737 see debugger output.
1738
1739 >>> doc = '''
1740 ... >>> x = 42
Florent Xicluna35049442010-10-14 21:35:58 +00001741 ... >>> raise Exception('clé')
1742 ... Traceback (most recent call last):
1743 ... Exception: clé
Jim Fulton356fd192004-08-09 11:34:47 +00001744 ... >>> import pdb; pdb.set_trace()
1745 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001746 >>> parser = doctest.DocTestParser()
Victor Stinner9d396392010-10-16 21:54:59 +00001747 >>> test = parser.get_doctest(doc, {}, "foo-bar@baz", "foo-bar@baz.py", 0)
Jim Fulton356fd192004-08-09 11:34:47 +00001748 >>> runner = doctest.DocTestRunner(verbose=False)
1749
1750 To demonstrate this, we'll create a fake standard input that
1751 captures our debugger input:
1752
1753 >>> import tempfile
Edward Loper2de91ba2004-08-27 02:07:46 +00001754 >>> real_stdin = sys.stdin
1755 >>> sys.stdin = _FakeInput([
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001756 ... 'print(x)', # print data defined by the example
Jim Fulton356fd192004-08-09 11:34:47 +00001757 ... 'continue', # stop debugging
Edward Loper2de91ba2004-08-27 02:07:46 +00001758 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001759
Edward Loper2de91ba2004-08-27 02:07:46 +00001760 >>> try: runner.run(test)
1761 ... finally: sys.stdin = real_stdin
Jim Fulton356fd192004-08-09 11:34:47 +00001762 --Return--
Victor Stinner9d396392010-10-16 21:54:59 +00001763 > <doctest foo-bar@baz[2]>(1)<module>()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001764 -> import pdb; pdb.set_trace()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001765 (Pdb) print(x)
Edward Loper2de91ba2004-08-27 02:07:46 +00001766 42
1767 (Pdb) continue
Florent Xicluna35049442010-10-14 21:35:58 +00001768 TestResults(failed=0, attempted=3)
Jim Fulton356fd192004-08-09 11:34:47 +00001769
1770 You can also put pdb.set_trace in a function called from a test:
1771
1772 >>> def calls_set_trace():
1773 ... y=2
1774 ... import pdb; pdb.set_trace()
1775
1776 >>> doc = '''
1777 ... >>> x=1
1778 ... >>> calls_set_trace()
1779 ... '''
Victor Stinner9d396392010-10-16 21:54:59 +00001780 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
Edward Loper2de91ba2004-08-27 02:07:46 +00001781 >>> real_stdin = sys.stdin
1782 >>> sys.stdin = _FakeInput([
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001783 ... 'print(y)', # print data defined in the function
Jim Fulton356fd192004-08-09 11:34:47 +00001784 ... 'up', # out of function
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001785 ... 'print(x)', # print data defined by the example
Jim Fulton356fd192004-08-09 11:34:47 +00001786 ... 'continue', # stop debugging
Edward Loper2de91ba2004-08-27 02:07:46 +00001787 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001788
Tim Peters50c6bdb2004-11-08 22:07:37 +00001789 >>> try:
1790 ... runner.run(test)
1791 ... finally:
1792 ... sys.stdin = real_stdin
Jim Fulton356fd192004-08-09 11:34:47 +00001793 --Return--
Edward Loper2de91ba2004-08-27 02:07:46 +00001794 > <doctest test.test_doctest.test_pdb_set_trace[8]>(3)calls_set_trace()->None
1795 -> import pdb; pdb.set_trace()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001796 (Pdb) print(y)
Edward Loper2de91ba2004-08-27 02:07:46 +00001797 2
1798 (Pdb) up
Victor Stinner9d396392010-10-16 21:54:59 +00001799 > <doctest foo-bar@baz[1]>(1)<module>()
Edward Loper2de91ba2004-08-27 02:07:46 +00001800 -> calls_set_trace()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001801 (Pdb) print(x)
Edward Loper2de91ba2004-08-27 02:07:46 +00001802 1
1803 (Pdb) continue
Christian Heimes25bb7832008-01-11 16:17:00 +00001804 TestResults(failed=0, attempted=2)
Edward Loper2de91ba2004-08-27 02:07:46 +00001805
1806 During interactive debugging, source code is shown, even for
1807 doctest examples:
1808
1809 >>> doc = '''
1810 ... >>> def f(x):
1811 ... ... g(x*2)
1812 ... >>> def g(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001813 ... ... print(x+3)
Edward Loper2de91ba2004-08-27 02:07:46 +00001814 ... ... import pdb; pdb.set_trace()
1815 ... >>> f(3)
1816 ... '''
Victor Stinner9d396392010-10-16 21:54:59 +00001817 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
Edward Loper2de91ba2004-08-27 02:07:46 +00001818 >>> real_stdin = sys.stdin
1819 >>> sys.stdin = _FakeInput([
1820 ... 'list', # list source from example 2
1821 ... 'next', # return from g()
1822 ... 'list', # list source from example 1
1823 ... 'next', # return from f()
1824 ... 'list', # list source from example 3
1825 ... 'continue', # stop debugging
1826 ... ''])
1827 >>> try: runner.run(test)
1828 ... finally: sys.stdin = real_stdin
1829 ... # doctest: +NORMALIZE_WHITESPACE
1830 --Return--
Victor Stinner9d396392010-10-16 21:54:59 +00001831 > <doctest foo-bar@baz[1]>(3)g()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001832 -> import pdb; pdb.set_trace()
1833 (Pdb) list
1834 1 def g(x):
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001835 2 print(x+3)
Edward Loper2de91ba2004-08-27 02:07:46 +00001836 3 -> import pdb; pdb.set_trace()
1837 [EOF]
1838 (Pdb) next
1839 --Return--
Victor Stinner9d396392010-10-16 21:54:59 +00001840 > <doctest foo-bar@baz[0]>(2)f()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001841 -> g(x*2)
1842 (Pdb) list
1843 1 def f(x):
1844 2 -> g(x*2)
1845 [EOF]
1846 (Pdb) next
1847 --Return--
Victor Stinner9d396392010-10-16 21:54:59 +00001848 > <doctest foo-bar@baz[2]>(1)<module>()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001849 -> f(3)
1850 (Pdb) list
1851 1 -> f(3)
1852 [EOF]
1853 (Pdb) continue
1854 **********************************************************************
Victor Stinner9d396392010-10-16 21:54:59 +00001855 File "foo-bar@baz.py", line 7, in foo-bar@baz
Edward Loper2de91ba2004-08-27 02:07:46 +00001856 Failed example:
1857 f(3)
1858 Expected nothing
1859 Got:
1860 9
Christian Heimes25bb7832008-01-11 16:17:00 +00001861 TestResults(failed=1, attempted=3)
Jim Fulton356fd192004-08-09 11:34:47 +00001862 """
1863
Tim Peters50c6bdb2004-11-08 22:07:37 +00001864def test_pdb_set_trace_nested():
1865 """This illustrates more-demanding use of set_trace with nested functions.
1866
1867 >>> class C(object):
1868 ... def calls_set_trace(self):
1869 ... y = 1
1870 ... import pdb; pdb.set_trace()
1871 ... self.f1()
1872 ... y = 2
1873 ... def f1(self):
1874 ... x = 1
1875 ... self.f2()
1876 ... x = 2
1877 ... def f2(self):
1878 ... z = 1
1879 ... z = 2
1880
1881 >>> calls_set_trace = C().calls_set_trace
1882
1883 >>> doc = '''
1884 ... >>> a = 1
1885 ... >>> calls_set_trace()
1886 ... '''
1887 >>> parser = doctest.DocTestParser()
1888 >>> runner = doctest.DocTestRunner(verbose=False)
Victor Stinner9d396392010-10-16 21:54:59 +00001889 >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001890 >>> real_stdin = sys.stdin
1891 >>> sys.stdin = _FakeInput([
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001892 ... 'print(y)', # print data defined in the function
1893 ... 'step', 'step', 'step', 'step', 'step', 'step', 'print(z)',
1894 ... 'up', 'print(x)',
1895 ... 'up', 'print(y)',
1896 ... 'up', 'print(foo)',
Tim Peters50c6bdb2004-11-08 22:07:37 +00001897 ... 'continue', # stop debugging
1898 ... ''])
1899
1900 >>> try:
1901 ... runner.run(test)
1902 ... finally:
1903 ... sys.stdin = real_stdin
Guido van Rossum4a625c32007-09-08 16:05:25 +00001904 ... # doctest: +REPORT_NDIFF
Tim Peters50c6bdb2004-11-08 22:07:37 +00001905 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
1906 -> self.f1()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001907 (Pdb) print(y)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001908 1
1909 (Pdb) step
1910 --Call--
1911 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(7)f1()
1912 -> def f1(self):
1913 (Pdb) step
1914 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(8)f1()
1915 -> x = 1
1916 (Pdb) step
1917 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
1918 -> self.f2()
1919 (Pdb) step
1920 --Call--
1921 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(11)f2()
1922 -> def f2(self):
1923 (Pdb) step
1924 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(12)f2()
1925 -> z = 1
1926 (Pdb) step
1927 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(13)f2()
1928 -> z = 2
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001929 (Pdb) print(z)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001930 1
1931 (Pdb) up
1932 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
1933 -> self.f2()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001934 (Pdb) print(x)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001935 1
1936 (Pdb) up
1937 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
1938 -> self.f1()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001939 (Pdb) print(y)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001940 1
1941 (Pdb) up
Victor Stinner9d396392010-10-16 21:54:59 +00001942 > <doctest foo-bar@baz[1]>(1)<module>()
Tim Peters50c6bdb2004-11-08 22:07:37 +00001943 -> calls_set_trace()
Guido van Rossumbdc36e42007-02-09 22:43:47 +00001944 (Pdb) print(foo)
Georg Brandl0d089622010-07-30 16:00:46 +00001945 *** NameError: name 'foo' is not defined
Tim Peters50c6bdb2004-11-08 22:07:37 +00001946 (Pdb) continue
Christian Heimes25bb7832008-01-11 16:17:00 +00001947 TestResults(failed=0, attempted=2)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001948"""
1949
Tim Peters19397e52004-08-06 22:02:59 +00001950def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +00001951 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +00001952
1953 We create a Suite by providing a module. A module can be provided
1954 by passing a module object:
1955
1956 >>> import unittest
1957 >>> import test.sample_doctest
1958 >>> suite = doctest.DocTestSuite(test.sample_doctest)
1959 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001960 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001961
1962 We can also supply the module by name:
1963
1964 >>> suite = doctest.DocTestSuite('test.sample_doctest')
1965 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001966 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001967
1968 We can use the current module:
1969
1970 >>> suite = test.sample_doctest.test_suite()
1971 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001972 <unittest.result.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001973
1974 We can supply global variables. If we pass globs, they will be
1975 used instead of the module globals. Here we'll pass an empty
1976 globals, triggering an extra error:
1977
1978 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
1979 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001980 <unittest.result.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001981
1982 Alternatively, we can provide extra globals. Here we'll make an
1983 error go away by providing an extra global variable:
1984
1985 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1986 ... extraglobs={'y': 1})
1987 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001988 <unittest.result.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001989
1990 You can pass option flags. Here we'll cause an extra error
1991 by disabling the blank-line feature:
1992
1993 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00001994 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00001995 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001996 <unittest.result.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001997
Tim Peters1e277ee2004-08-07 05:37:52 +00001998 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00001999
Jim Fultonf54bad42004-08-28 14:57:56 +00002000 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00002001 ... import test.test_doctest
2002 ... test.test_doctest.sillySetup = True
2003
Jim Fultonf54bad42004-08-28 14:57:56 +00002004 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00002005 ... import test.test_doctest
2006 ... del test.test_doctest.sillySetup
2007
2008 Here, we installed a silly variable that the test expects:
2009
2010 >>> suite = doctest.DocTestSuite('test.sample_doctest',
2011 ... setUp=setUp, tearDown=tearDown)
2012 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002013 <unittest.result.TestResult run=9 errors=0 failures=3>
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. Here
2024 we'll use the setUp function to supply the missing variable y:
2025
2026 >>> def setUp(test):
2027 ... test.globs['y'] = 1
2028
2029 >>> suite = doctest.DocTestSuite('test.sample_doctest', setUp=setUp)
2030 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002031 <unittest.result.TestResult run=9 errors=0 failures=3>
Jim Fultonf54bad42004-08-28 14:57:56 +00002032
2033 Here, we didn't need to use a tearDown function because we
2034 modified the test globals, which are a copy of the
2035 sample_doctest module dictionary. The test globals are
2036 automatically cleared for us after a test.
Tim Peters19397e52004-08-06 22:02:59 +00002037 """
2038
2039def test_DocFileSuite():
2040 """We can test tests found in text files using a DocFileSuite.
2041
2042 We create a suite by providing the names of one or more text
2043 files that include examples:
2044
2045 >>> import unittest
2046 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002047 ... 'test_doctest2.txt',
2048 ... 'test_doctest4.txt')
Tim Peters19397e52004-08-06 22:02:59 +00002049 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002050 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002051
2052 The test files are looked for in the directory containing the
2053 calling module. A package keyword argument can be provided to
2054 specify a different relative location.
2055
2056 >>> import unittest
2057 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2058 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002059 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002060 ... package='test')
2061 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002062 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002063
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002064 Support for using a package's __loader__.get_data() is also
2065 provided.
2066
2067 >>> import unittest, pkgutil, test
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002068 >>> added_loader = False
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002069 >>> if not hasattr(test, '__loader__'):
2070 ... test.__loader__ = pkgutil.get_loader(test)
2071 ... added_loader = True
2072 >>> try:
2073 ... suite = doctest.DocFileSuite('test_doctest.txt',
2074 ... 'test_doctest2.txt',
2075 ... 'test_doctest4.txt',
2076 ... package='test')
2077 ... suite.run(unittest.TestResult())
2078 ... finally:
2079 ... if added_loader:
2080 ... del test.__loader__
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002081 <unittest.result.TestResult run=3 errors=0 failures=2>
Guido van Rossumcd4d4522007-11-22 00:30:02 +00002082
Edward Loper0273f5b2004-09-18 20:27:04 +00002083 '/' should be used as a path separator. It will be converted
2084 to a native separator at run time:
Tim Peters19397e52004-08-06 22:02:59 +00002085
2086 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
2087 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002088 <unittest.result.TestResult run=1 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002089
Edward Loper0273f5b2004-09-18 20:27:04 +00002090 If DocFileSuite is used from an interactive session, then files
2091 are resolved relative to the directory of sys.argv[0]:
2092
Christian Heimes45f9af32007-11-27 21:50:00 +00002093 >>> import types, os.path, test.test_doctest
Edward Loper0273f5b2004-09-18 20:27:04 +00002094 >>> save_argv = sys.argv
2095 >>> sys.argv = [test.test_doctest.__file__]
2096 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Christian Heimes45f9af32007-11-27 21:50:00 +00002097 ... package=types.ModuleType('__main__'))
Edward Loper0273f5b2004-09-18 20:27:04 +00002098 >>> sys.argv = save_argv
2099
Edward Loper052d0cd2004-09-19 17:19:33 +00002100 By setting `module_relative=False`, os-specific paths may be
2101 used (including absolute paths and paths relative to the
2102 working directory):
Edward Loper0273f5b2004-09-18 20:27:04 +00002103
2104 >>> # Get the absolute path of the test package.
2105 >>> test_doctest_path = os.path.abspath(test.test_doctest.__file__)
2106 >>> test_pkg_path = os.path.split(test_doctest_path)[0]
2107
2108 >>> # Use it to find the absolute path of test_doctest.txt.
2109 >>> test_file = os.path.join(test_pkg_path, 'test_doctest.txt')
2110
Edward Loper052d0cd2004-09-19 17:19:33 +00002111 >>> suite = doctest.DocFileSuite(test_file, module_relative=False)
Edward Loper0273f5b2004-09-18 20:27:04 +00002112 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002113 <unittest.result.TestResult run=1 errors=0 failures=1>
Edward Loper0273f5b2004-09-18 20:27:04 +00002114
Edward Loper052d0cd2004-09-19 17:19:33 +00002115 It is an error to specify `package` when `module_relative=False`:
2116
2117 >>> suite = doctest.DocFileSuite(test_file, module_relative=False,
2118 ... package='test')
2119 Traceback (most recent call last):
2120 ValueError: Package may only be specified for module-relative paths.
2121
Tim Peters19397e52004-08-06 22:02:59 +00002122 You can specify initial global variables:
2123
2124 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2125 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002126 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002127 ... globs={'favorite_color': 'blue'})
2128 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002129 <unittest.result.TestResult run=3 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002130
2131 In this case, we supplied a missing favorite color. You can
2132 provide doctest options:
2133
2134 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2135 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002136 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002137 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
2138 ... globs={'favorite_color': 'blue'})
2139 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002140 <unittest.result.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002141
2142 And, you can provide setUp and tearDown functions:
2143
Jim Fultonf54bad42004-08-28 14:57:56 +00002144 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00002145 ... import test.test_doctest
2146 ... test.test_doctest.sillySetup = True
2147
Jim Fultonf54bad42004-08-28 14:57:56 +00002148 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00002149 ... import test.test_doctest
2150 ... del test.test_doctest.sillySetup
2151
2152 Here, we installed a silly variable that the test expects:
2153
2154 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2155 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002156 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002157 ... setUp=setUp, tearDown=tearDown)
2158 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002159 <unittest.result.TestResult run=3 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00002160
2161 But the tearDown restores sanity:
2162
2163 >>> import test.test_doctest
2164 >>> test.test_doctest.sillySetup
2165 Traceback (most recent call last):
2166 ...
2167 AttributeError: 'module' object has no attribute 'sillySetup'
2168
Jim Fultonf54bad42004-08-28 14:57:56 +00002169 The setUp and tearDown funtions are passed test objects.
2170 Here, we'll use a setUp function to set the favorite color in
2171 test_doctest.txt:
2172
2173 >>> def setUp(test):
2174 ... test.globs['favorite_color'] = 'blue'
2175
2176 >>> suite = doctest.DocFileSuite('test_doctest.txt', setUp=setUp)
2177 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002178 <unittest.result.TestResult run=1 errors=0 failures=0>
Jim Fultonf54bad42004-08-28 14:57:56 +00002179
2180 Here, we didn't need to use a tearDown function because we
2181 modified the test globals. The test globals are
2182 automatically cleared for us after a test.
Tim Petersdf7a2082004-08-29 00:38:17 +00002183
Fred Drake7c404a42004-12-21 23:46:34 +00002184 Tests in a file run using `DocFileSuite` can also access the
2185 `__file__` global, which is set to the name of the file
2186 containing the tests:
2187
2188 >>> suite = doctest.DocFileSuite('test_doctest3.txt')
2189 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002190 <unittest.result.TestResult run=1 errors=0 failures=0>
Fred Drake7c404a42004-12-21 23:46:34 +00002191
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002192 If the tests contain non-ASCII characters, we have to specify which
2193 encoding the file is encoded with. We do so by using the `encoding`
2194 parameter:
2195
2196 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2197 ... 'test_doctest2.txt',
2198 ... 'test_doctest4.txt',
2199 ... encoding='utf-8')
2200 >>> suite.run(unittest.TestResult())
Benjamin Petersonbed7d042009-07-19 21:01:52 +00002201 <unittest.result.TestResult run=3 errors=0 failures=2>
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002202
Jim Fultonf54bad42004-08-28 14:57:56 +00002203 """
Tim Peters19397e52004-08-06 22:02:59 +00002204
Jim Fulton07a349c2004-08-22 14:10:00 +00002205def test_trailing_space_in_test():
2206 """
Tim Petersa7def722004-08-23 22:13:22 +00002207 Trailing spaces in expected output are significant:
Tim Petersc6cbab02004-08-22 19:43:28 +00002208
Jim Fulton07a349c2004-08-22 14:10:00 +00002209 >>> x, y = 'foo', ''
Guido van Rossum7131f842007-02-09 20:13:25 +00002210 >>> print(x, y)
Jim Fulton07a349c2004-08-22 14:10:00 +00002211 foo \n
2212 """
Tim Peters19397e52004-08-06 22:02:59 +00002213
Jim Fultonf54bad42004-08-28 14:57:56 +00002214
2215def test_unittest_reportflags():
2216 """Default unittest reporting flags can be set to control reporting
2217
2218 Here, we'll set the REPORT_ONLY_FIRST_FAILURE option so we see
2219 only the first failure of each test. First, we'll look at the
2220 output without the flag. The file test_doctest.txt file has two
2221 tests. They both fail if blank lines are disabled:
2222
2223 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2224 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
2225 >>> import unittest
2226 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002227 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002228 Traceback ...
2229 Failed example:
2230 favorite_color
2231 ...
2232 Failed example:
2233 if 1:
2234 ...
2235
2236 Note that we see both failures displayed.
2237
2238 >>> old = doctest.set_unittest_reportflags(
2239 ... doctest.REPORT_ONLY_FIRST_FAILURE)
2240
2241 Now, when we run the test:
2242
2243 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002244 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002245 Traceback ...
2246 Failed example:
2247 favorite_color
2248 Exception raised:
2249 ...
2250 NameError: name 'favorite_color' is not defined
2251 <BLANKLINE>
2252 <BLANKLINE>
Tim Petersdf7a2082004-08-29 00:38:17 +00002253
Jim Fultonf54bad42004-08-28 14:57:56 +00002254 We get only the first failure.
2255
2256 If we give any reporting options when we set up the tests,
2257 however:
2258
2259 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2260 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE | doctest.REPORT_NDIFF)
2261
2262 Then the default eporting options are ignored:
2263
2264 >>> result = suite.run(unittest.TestResult())
Guido van Rossum7131f842007-02-09 20:13:25 +00002265 >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Jim Fultonf54bad42004-08-28 14:57:56 +00002266 Traceback ...
2267 Failed example:
2268 favorite_color
2269 ...
2270 Failed example:
2271 if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00002272 print('a')
2273 print()
2274 print('b')
Jim Fultonf54bad42004-08-28 14:57:56 +00002275 Differences (ndiff with -expected +actual):
2276 a
2277 - <BLANKLINE>
2278 +
2279 b
2280 <BLANKLINE>
2281 <BLANKLINE>
2282
2283
2284 Test runners can restore the formatting flags after they run:
2285
2286 >>> ignored = doctest.set_unittest_reportflags(old)
2287
2288 """
2289
Edward Loper052d0cd2004-09-19 17:19:33 +00002290def test_testfile(): r"""
2291Tests for the `testfile()` function. This function runs all the
2292doctest examples in a given file. In its simple invokation, it is
2293called with the name of a file, which is taken to be relative to the
2294calling module. The return value is (#failures, #tests).
2295
Florent Xicluna59250852010-02-27 14:21:57 +00002296We don't want `-v` in sys.argv for these tests.
2297
2298 >>> save_argv = sys.argv
2299 >>> if '-v' in sys.argv:
2300 ... sys.argv = [arg for arg in save_argv if arg != '-v']
2301
2302
Edward Loper052d0cd2004-09-19 17:19:33 +00002303 >>> doctest.testfile('test_doctest.txt') # doctest: +ELLIPSIS
2304 **********************************************************************
2305 File "...", line 6, in test_doctest.txt
2306 Failed example:
2307 favorite_color
2308 Exception raised:
2309 ...
2310 NameError: name 'favorite_color' is not defined
2311 **********************************************************************
2312 1 items had failures:
2313 1 of 2 in test_doctest.txt
2314 ***Test Failed*** 1 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002315 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002316 >>> doctest.master = None # Reset master.
2317
2318(Note: we'll be clearing doctest.master after each call to
Ezio Melotti13925002011-03-16 11:05:33 +02002319`doctest.testfile`, to suppress warnings about multiple tests with the
Edward Loper052d0cd2004-09-19 17:19:33 +00002320same name.)
2321
2322Globals may be specified with the `globs` and `extraglobs` parameters:
2323
2324 >>> globs = {'favorite_color': 'blue'}
2325 >>> doctest.testfile('test_doctest.txt', globs=globs)
Christian Heimes25bb7832008-01-11 16:17:00 +00002326 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002327 >>> doctest.master = None # Reset master.
2328
2329 >>> extraglobs = {'favorite_color': 'red'}
2330 >>> doctest.testfile('test_doctest.txt', globs=globs,
2331 ... extraglobs=extraglobs) # doctest: +ELLIPSIS
2332 **********************************************************************
2333 File "...", line 6, in test_doctest.txt
2334 Failed example:
2335 favorite_color
2336 Expected:
2337 'blue'
2338 Got:
2339 'red'
2340 **********************************************************************
2341 1 items had failures:
2342 1 of 2 in test_doctest.txt
2343 ***Test Failed*** 1 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002344 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002345 >>> doctest.master = None # Reset master.
2346
2347The file may be made relative to a given module or package, using the
2348optional `module_relative` parameter:
2349
2350 >>> doctest.testfile('test_doctest.txt', globs=globs,
2351 ... module_relative='test')
Christian Heimes25bb7832008-01-11 16:17:00 +00002352 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002353 >>> doctest.master = None # Reset master.
2354
Ezio Melotti13925002011-03-16 11:05:33 +02002355Verbosity can be increased with the optional `verbose` parameter:
Edward Loper052d0cd2004-09-19 17:19:33 +00002356
2357 >>> doctest.testfile('test_doctest.txt', globs=globs, verbose=True)
2358 Trying:
2359 favorite_color
2360 Expecting:
2361 'blue'
2362 ok
2363 Trying:
2364 if 1:
Guido van Rossumbdc36e42007-02-09 22:43:47 +00002365 print('a')
2366 print()
2367 print('b')
Edward Loper052d0cd2004-09-19 17:19:33 +00002368 Expecting:
2369 a
2370 <BLANKLINE>
2371 b
2372 ok
2373 1 items passed all tests:
2374 2 tests in test_doctest.txt
2375 2 tests in 1 items.
2376 2 passed and 0 failed.
2377 Test passed.
Christian Heimes25bb7832008-01-11 16:17:00 +00002378 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002379 >>> doctest.master = None # Reset master.
2380
2381The name of the test may be specified with the optional `name`
2382parameter:
2383
2384 >>> doctest.testfile('test_doctest.txt', name='newname')
2385 ... # doctest: +ELLIPSIS
2386 **********************************************************************
2387 File "...", line 6, in newname
2388 ...
Christian Heimes25bb7832008-01-11 16:17:00 +00002389 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002390 >>> doctest.master = None # Reset master.
2391
Ezio Melotti13925002011-03-16 11:05:33 +02002392The summary report may be suppressed with the optional `report`
Edward Loper052d0cd2004-09-19 17:19:33 +00002393parameter:
2394
2395 >>> doctest.testfile('test_doctest.txt', report=False)
2396 ... # doctest: +ELLIPSIS
2397 **********************************************************************
2398 File "...", line 6, in test_doctest.txt
2399 Failed example:
2400 favorite_color
2401 Exception raised:
2402 ...
2403 NameError: name 'favorite_color' is not defined
Christian Heimes25bb7832008-01-11 16:17:00 +00002404 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002405 >>> doctest.master = None # Reset master.
2406
2407The optional keyword argument `raise_on_error` can be used to raise an
2408exception on the first error (which may be useful for postmortem
2409debugging):
2410
2411 >>> doctest.testfile('test_doctest.txt', raise_on_error=True)
2412 ... # doctest: +ELLIPSIS
2413 Traceback (most recent call last):
Guido van Rossum6a2a2a02006-08-26 20:37:44 +00002414 doctest.UnexpectedException: ...
Edward Loper052d0cd2004-09-19 17:19:33 +00002415 >>> doctest.master = None # Reset master.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002416
2417If the tests contain non-ASCII characters, the tests might fail, since
2418it's unknown which encoding is used. The encoding can be specified
2419using the optional keyword argument `encoding`:
2420
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002421 >>> doctest.testfile('test_doctest4.txt', encoding='latin-1') # doctest: +ELLIPSIS
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002422 **********************************************************************
2423 File "...", line 7, in test_doctest4.txt
2424 Failed example:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002425 '...'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002426 Expected:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002427 'f\xf6\xf6'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002428 Got:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002429 'f\xc3\xb6\xc3\xb6'
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002430 **********************************************************************
2431 ...
2432 **********************************************************************
2433 1 items had failures:
Martin v. Löwisb1a9f272007-07-20 07:13:39 +00002434 2 of 2 in test_doctest4.txt
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002435 ***Test Failed*** 2 failures.
Christian Heimes25bb7832008-01-11 16:17:00 +00002436 TestResults(failed=2, attempted=2)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002437 >>> doctest.master = None # Reset master.
2438
2439 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8')
Christian Heimes25bb7832008-01-11 16:17:00 +00002440 TestResults(failed=0, attempted=2)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002441 >>> doctest.master = None # Reset master.
Florent Xicluna59250852010-02-27 14:21:57 +00002442
2443Test the verbose output:
2444
2445 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8', verbose=True)
2446 Trying:
2447 'föö'
2448 Expecting:
2449 'f\xf6\xf6'
2450 ok
2451 Trying:
2452 'bąr'
2453 Expecting:
2454 'b\u0105r'
2455 ok
2456 1 items passed all tests:
2457 2 tests in test_doctest4.txt
2458 2 tests in 1 items.
2459 2 passed and 0 failed.
2460 Test passed.
2461 TestResults(failed=0, attempted=2)
2462 >>> doctest.master = None # Reset master.
2463 >>> sys.argv = save_argv
Edward Loper052d0cd2004-09-19 17:19:33 +00002464"""
2465
R. David Murray58641de2009-06-12 15:33:19 +00002466def test_testmod(): r"""
2467Tests for the testmod function. More might be useful, but for now we're just
2468testing the case raised by Issue 6195, where trying to doctest a C module would
2469fail with a UnicodeDecodeError because doctest tried to read the "source" lines
2470out of the binary module.
2471
2472 >>> import unicodedata
Florent Xicluna59250852010-02-27 14:21:57 +00002473 >>> doctest.testmod(unicodedata, verbose=False)
R. David Murray58641de2009-06-12 15:33:19 +00002474 TestResults(failed=0, attempted=0)
2475"""
2476
Victor Stinner9d396392010-10-16 21:54:59 +00002477try:
2478 os.fsencode("foo-bär@baz.py")
2479except UnicodeEncodeError:
2480 # Skip the test: the filesystem encoding is unable to encode the filename
2481 pass
2482else:
2483 def test_unicode(): """
2484Check doctest with a non-ascii filename:
2485
2486 >>> doc = '''
2487 ... >>> raise Exception('clé')
2488 ... '''
2489 ...
2490 >>> parser = doctest.DocTestParser()
2491 >>> test = parser.get_doctest(doc, {}, "foo-bär@baz", "foo-bär@baz.py", 0)
2492 >>> test
2493 <DocTest foo-bär@baz from foo-bär@baz.py:0 (1 example)>
2494 >>> runner = doctest.DocTestRunner(verbose=False)
2495 >>> runner.run(test) # doctest: +ELLIPSIS
2496 **********************************************************************
2497 File "foo-bär@baz.py", line 2, in foo-bär@baz
2498 Failed example:
2499 raise Exception('clé')
2500 Exception raised:
2501 Traceback (most recent call last):
2502 File ...
2503 compileflags, 1), test.globs)
2504 File "<doctest foo-bär@baz[0]>", line 1, in <module>
2505 raise Exception('clé')
2506 Exception: clé
2507 TestResults(failed=1, attempted=1)
2508 """
2509
Tim Peters8485b562004-08-04 18:46:34 +00002510######################################################################
2511## Main
2512######################################################################
2513
2514def test_main():
2515 # Check the doctest cases in doctest itself:
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002516 support.run_doctest(doctest, verbosity=True)
Tim Peters8485b562004-08-04 18:46:34 +00002517 # Check the doctest cases defined here:
2518 from test import test_doctest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002519 support.run_doctest(test_doctest, verbosity=True)
Tim Peters8485b562004-08-04 18:46:34 +00002520
Victor Stinner45df8202010-04-28 22:31:17 +00002521import sys, re, io
2522
Tim Peters8485b562004-08-04 18:46:34 +00002523def test_coverage(coverdir):
Victor Stinner45df8202010-04-28 22:31:17 +00002524 trace = support.import_module('trace')
Tim Peters8485b562004-08-04 18:46:34 +00002525 tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
2526 trace=0, count=1)
Guido van Rossume7ba4952007-06-06 23:52:48 +00002527 tracer.run('test_main()')
Tim Peters8485b562004-08-04 18:46:34 +00002528 r = tracer.results()
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002529 print('Writing coverage results...')
Tim Peters8485b562004-08-04 18:46:34 +00002530 r.write_results(show_missing=True, summary=True,
2531 coverdir=coverdir)
2532
2533if __name__ == '__main__':
2534 if '-c' in sys.argv:
2535 test_coverage('/tmp/doctest.cover')
2536 else:
2537 test_main()