blob: a304f5cb27d5a396a06ef3a1c2c0caacb9d0b060 [file] [log] [blame]
Tim Peters8485b562004-08-04 18:46:34 +00001"""
2Test script for doctest.
3"""
4
Barry Warsaw04f357c2002-07-23 19:04:11 +00005from test import test_support
Tim Peters8485b562004-08-04 18:46:34 +00006import doctest
Tim Petersa7def722004-08-23 22:13:22 +00007import warnings
Tim Peters8485b562004-08-04 18:46:34 +00008
9######################################################################
10## Sample Objects (used by test cases)
11######################################################################
12
13def sample_func(v):
14 """
Tim Peters19397e52004-08-06 22:02:59 +000015 Blah blah
16
Tim Peters8485b562004-08-04 18:46:34 +000017 >>> print sample_func(22)
18 44
Tim Peters19397e52004-08-06 22:02:59 +000019
20 Yee ha!
Tim Peters8485b562004-08-04 18:46:34 +000021 """
22 return v+v
23
24class SampleClass:
25 """
26 >>> print 1
27 1
28 """
29 def __init__(self, val):
30 """
31 >>> print SampleClass(12).get()
32 12
33 """
34 self.val = val
35
36 def double(self):
37 """
38 >>> print SampleClass(12).double().get()
39 24
40 """
41 return SampleClass(self.val + self.val)
42
43 def get(self):
44 """
45 >>> print SampleClass(-5).get()
46 -5
47 """
48 return self.val
49
50 def a_staticmethod(v):
51 """
52 >>> print SampleClass.a_staticmethod(10)
53 11
54 """
55 return v+1
56 a_staticmethod = staticmethod(a_staticmethod)
57
58 def a_classmethod(cls, v):
59 """
60 >>> print SampleClass.a_classmethod(10)
61 12
62 >>> print SampleClass(0).a_classmethod(10)
63 12
64 """
65 return v+2
66 a_classmethod = classmethod(a_classmethod)
67
68 a_property = property(get, doc="""
69 >>> print SampleClass(22).a_property
70 22
71 """)
72
73 class NestedClass:
74 """
75 >>> x = SampleClass.NestedClass(5)
76 >>> y = x.square()
77 >>> print y.get()
78 25
79 """
80 def __init__(self, val=0):
81 """
82 >>> print SampleClass.NestedClass().get()
83 0
84 """
85 self.val = val
86 def square(self):
87 return SampleClass.NestedClass(self.val*self.val)
88 def get(self):
89 return self.val
90
91class SampleNewStyleClass(object):
92 r"""
93 >>> print '1\n2\n3'
94 1
95 2
96 3
97 """
98 def __init__(self, val):
99 """
100 >>> print SampleNewStyleClass(12).get()
101 12
102 """
103 self.val = val
104
105 def double(self):
106 """
107 >>> print SampleNewStyleClass(12).double().get()
108 24
109 """
110 return SampleNewStyleClass(self.val + self.val)
111
112 def get(self):
113 """
114 >>> print SampleNewStyleClass(-5).get()
115 -5
116 """
117 return self.val
118
119######################################################################
Edward Loper2de91ba2004-08-27 02:07:46 +0000120## Fake stdin (for testing interactive debugging)
121######################################################################
122
123class _FakeInput:
124 """
125 A fake input stream for pdb's interactive debugger. Whenever a
126 line is read, print it (to simulate the user typing it), and then
127 return it. The set of lines to return is specified in the
128 constructor; they should not have trailing newlines.
129 """
130 def __init__(self, lines):
131 self.lines = lines
132
133 def readline(self):
134 line = self.lines.pop(0)
135 print line
136 return line+'\n'
137
138######################################################################
Tim Peters8485b562004-08-04 18:46:34 +0000139## Test Cases
140######################################################################
141
142def test_Example(): r"""
143Unit tests for the `Example` class.
144
Edward Lopera6b68322004-08-26 00:05:43 +0000145Example is a simple container class that holds:
146 - `source`: A source string.
147 - `want`: An expected output string.
148 - `exc_msg`: An expected exception message string (or None if no
149 exception is expected).
150 - `lineno`: A line number (within the docstring).
151 - `indent`: The example's indentation in the input string.
152 - `options`: An option dictionary, mapping option flags to True or
153 False.
Tim Peters8485b562004-08-04 18:46:34 +0000154
Edward Lopera6b68322004-08-26 00:05:43 +0000155These attributes are set by the constructor. `source` and `want` are
156required; the other attributes all have default values:
Tim Peters8485b562004-08-04 18:46:34 +0000157
Edward Lopera6b68322004-08-26 00:05:43 +0000158 >>> example = doctest.Example('print 1', '1\n')
159 >>> (example.source, example.want, example.exc_msg,
160 ... example.lineno, example.indent, example.options)
161 ('print 1\n', '1\n', None, 0, 0, {})
162
163The first three attributes (`source`, `want`, and `exc_msg`) may be
164specified positionally; the remaining arguments should be specified as
165keyword arguments:
166
167 >>> exc_msg = 'IndexError: pop from an empty list'
168 >>> example = doctest.Example('[].pop()', '', exc_msg,
169 ... lineno=5, indent=4,
170 ... options={doctest.ELLIPSIS: True})
171 >>> (example.source, example.want, example.exc_msg,
172 ... example.lineno, example.indent, example.options)
173 ('[].pop()\n', '', 'IndexError: pop from an empty list\n', 5, 4, {8: True})
174
175The constructor normalizes the `source` string to end in a newline:
Tim Peters8485b562004-08-04 18:46:34 +0000176
Tim Petersbb431472004-08-09 03:51:46 +0000177 Source spans a single line: no terminating newline.
Edward Lopera6b68322004-08-26 00:05:43 +0000178 >>> e = doctest.Example('print 1', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000179 >>> e.source, e.want
180 ('print 1\n', '1\n')
181
Edward Lopera6b68322004-08-26 00:05:43 +0000182 >>> e = doctest.Example('print 1\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000183 >>> e.source, e.want
184 ('print 1\n', '1\n')
Tim Peters8485b562004-08-04 18:46:34 +0000185
Tim Petersbb431472004-08-09 03:51:46 +0000186 Source spans multiple lines: require terminating newline.
Edward Lopera6b68322004-08-26 00:05:43 +0000187 >>> e = doctest.Example('print 1;\nprint 2\n', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000188 >>> e.source, e.want
189 ('print 1;\nprint 2\n', '1\n2\n')
Tim Peters8485b562004-08-04 18:46:34 +0000190
Edward Lopera6b68322004-08-26 00:05:43 +0000191 >>> e = doctest.Example('print 1;\nprint 2', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000192 >>> e.source, e.want
193 ('print 1;\nprint 2\n', '1\n2\n')
194
Edward Lopera6b68322004-08-26 00:05:43 +0000195 Empty source string (which should never appear in real examples)
196 >>> e = doctest.Example('', '')
197 >>> e.source, e.want
198 ('\n', '')
Tim Peters8485b562004-08-04 18:46:34 +0000199
Edward Lopera6b68322004-08-26 00:05:43 +0000200The constructor normalizes the `want` string to end in a newline,
201unless it's the empty string:
202
203 >>> e = doctest.Example('print 1', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000204 >>> e.source, e.want
205 ('print 1\n', '1\n')
206
Edward Lopera6b68322004-08-26 00:05:43 +0000207 >>> e = doctest.Example('print 1', '1')
Tim Petersbb431472004-08-09 03:51:46 +0000208 >>> e.source, e.want
209 ('print 1\n', '1\n')
210
Edward Lopera6b68322004-08-26 00:05:43 +0000211 >>> e = doctest.Example('print', '')
Tim Petersbb431472004-08-09 03:51:46 +0000212 >>> e.source, e.want
213 ('print\n', '')
Edward Lopera6b68322004-08-26 00:05:43 +0000214
215The constructor normalizes the `exc_msg` string to end in a newline,
216unless it's `None`:
217
218 Message spans one line
219 >>> exc_msg = 'IndexError: pop from an empty list'
220 >>> e = doctest.Example('[].pop()', '', exc_msg)
221 >>> e.exc_msg
222 'IndexError: pop from an empty list\n'
223
224 >>> exc_msg = 'IndexError: pop from an empty list\n'
225 >>> e = doctest.Example('[].pop()', '', exc_msg)
226 >>> e.exc_msg
227 'IndexError: pop from an empty list\n'
228
229 Message spans multiple lines
230 >>> exc_msg = 'ValueError: 1\n 2'
231 >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
232 >>> e.exc_msg
233 'ValueError: 1\n 2\n'
234
235 >>> exc_msg = 'ValueError: 1\n 2\n'
236 >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
237 >>> e.exc_msg
238 'ValueError: 1\n 2\n'
239
240 Empty (but non-None) exception message (which should never appear
241 in real examples)
242 >>> exc_msg = ''
243 >>> e = doctest.Example('raise X()', '', exc_msg)
244 >>> e.exc_msg
245 '\n'
Tim Peters8485b562004-08-04 18:46:34 +0000246"""
247
248def test_DocTest(): r"""
249Unit tests for the `DocTest` class.
250
251DocTest is a collection of examples, extracted from a docstring, along
252with information about where the docstring comes from (a name,
253filename, and line number). The docstring is parsed by the `DocTest`
254constructor:
255
256 >>> docstring = '''
257 ... >>> print 12
258 ... 12
259 ...
260 ... Non-example text.
261 ...
262 ... >>> print 'another\example'
263 ... another
264 ... example
265 ... '''
266 >>> globs = {} # globals to run the test in.
Edward Lopera1ef6112004-08-09 16:14:41 +0000267 >>> parser = doctest.DocTestParser()
268 >>> test = parser.get_doctest(docstring, globs, 'some_test',
269 ... 'some_file', 20)
Tim Peters8485b562004-08-04 18:46:34 +0000270 >>> print test
271 <DocTest some_test from some_file:20 (2 examples)>
272 >>> len(test.examples)
273 2
274 >>> e1, e2 = test.examples
275 >>> (e1.source, e1.want, e1.lineno)
Tim Petersbb431472004-08-09 03:51:46 +0000276 ('print 12\n', '12\n', 1)
Tim Peters8485b562004-08-04 18:46:34 +0000277 >>> (e2.source, e2.want, e2.lineno)
Tim Petersbb431472004-08-09 03:51:46 +0000278 ("print 'another\\example'\n", 'another\nexample\n', 6)
Tim Peters8485b562004-08-04 18:46:34 +0000279
280Source information (name, filename, and line number) is available as
281attributes on the doctest object:
282
283 >>> (test.name, test.filename, test.lineno)
284 ('some_test', 'some_file', 20)
285
286The line number of an example within its containing file is found by
287adding the line number of the example and the line number of its
288containing test:
289
290 >>> test.lineno + e1.lineno
291 21
292 >>> test.lineno + e2.lineno
293 26
294
295If the docstring contains inconsistant leading whitespace in the
296expected output of an example, then `DocTest` will raise a ValueError:
297
298 >>> docstring = r'''
299 ... >>> print 'bad\nindentation'
300 ... bad
301 ... indentation
302 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000303 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000304 Traceback (most recent call last):
Edward Loper00f8da72004-08-26 18:05:07 +0000305 ValueError: line 4 of the docstring for some_test has inconsistent leading whitespace: 'indentation'
Tim Peters8485b562004-08-04 18:46:34 +0000306
307If the docstring contains inconsistent leading whitespace on
308continuation lines, then `DocTest` will raise a ValueError:
309
310 >>> docstring = r'''
311 ... >>> print ('bad indentation',
312 ... ... 2)
313 ... ('bad', 'indentation')
314 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000315 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000316 Traceback (most recent call last):
Edward Loper00f8da72004-08-26 18:05:07 +0000317 ValueError: line 2 of the docstring for some_test has inconsistent leading whitespace: '... 2)'
Tim Peters8485b562004-08-04 18:46:34 +0000318
319If there's no blank space after a PS1 prompt ('>>>'), then `DocTest`
320will raise a ValueError:
321
322 >>> docstring = '>>>print 1\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000323 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000324 Traceback (most recent call last):
Edward Loper7c748462004-08-09 02:06:06 +0000325 ValueError: line 1 of the docstring for some_test lacks blank after >>>: '>>>print 1'
326
327If there's no blank space after a PS2 prompt ('...'), then `DocTest`
328will raise a ValueError:
329
330 >>> docstring = '>>> if 1:\n...print 1\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000331 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Edward Loper7c748462004-08-09 02:06:06 +0000332 Traceback (most recent call last):
333 ValueError: line 2 of the docstring for some_test lacks blank after ...: '...print 1'
334
Tim Peters8485b562004-08-04 18:46:34 +0000335"""
336
Tim Peters8485b562004-08-04 18:46:34 +0000337def test_DocTestFinder(): r"""
338Unit tests for the `DocTestFinder` class.
339
340DocTestFinder is used to extract DocTests from an object's docstring
341and the docstrings of its contained objects. It can be used with
342modules, functions, classes, methods, staticmethods, classmethods, and
343properties.
344
345Finding Tests in Functions
346~~~~~~~~~~~~~~~~~~~~~~~~~~
347For a function whose docstring contains examples, DocTestFinder.find()
348will return a single test (for that function's docstring):
349
Tim Peters8485b562004-08-04 18:46:34 +0000350 >>> finder = doctest.DocTestFinder()
Jim Fulton07a349c2004-08-22 14:10:00 +0000351
352We'll simulate a __file__ attr that ends in pyc:
353
354 >>> import test.test_doctest
355 >>> old = test.test_doctest.__file__
356 >>> test.test_doctest.__file__ = 'test_doctest.pyc'
357
Tim Peters8485b562004-08-04 18:46:34 +0000358 >>> tests = finder.find(sample_func)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000359
Edward Loper74bca7a2004-08-12 02:27:44 +0000360 >>> print tests # doctest: +ELLIPSIS
Tim Petersa7def722004-08-23 22:13:22 +0000361 [<DocTest sample_func from ...:13 (1 example)>]
Edward Loper8e4a34b2004-08-12 02:34:27 +0000362
Tim Peters4de7c5c2004-08-23 22:38:05 +0000363The exact name depends on how test_doctest was invoked, so allow for
364leading path components.
365
366 >>> tests[0].filename # doctest: +ELLIPSIS
367 '...test_doctest.py'
Jim Fulton07a349c2004-08-22 14:10:00 +0000368
369 >>> test.test_doctest.__file__ = old
Tim Petersc6cbab02004-08-22 19:43:28 +0000370
Jim Fulton07a349c2004-08-22 14:10:00 +0000371
Tim Peters8485b562004-08-04 18:46:34 +0000372 >>> e = tests[0].examples[0]
Tim Petersbb431472004-08-09 03:51:46 +0000373 >>> (e.source, e.want, e.lineno)
374 ('print sample_func(22)\n', '44\n', 3)
Tim Peters8485b562004-08-04 18:46:34 +0000375
Edward Loper32ddbf72004-09-13 05:47:24 +0000376By default, tests are created for objects with no docstring:
Tim Peters8485b562004-08-04 18:46:34 +0000377
378 >>> def no_docstring(v):
379 ... pass
Edward Loper32ddbf72004-09-13 05:47:24 +0000380 >>> finder.find(no_docstring) # doctest: +ELLIPSIS
381 [<DocTest no_docstring from ... (no examples)>]
382
383However, the optional argument `exclude_empty` to the DocTestFinder
384constructor can be used to exclude tests for objects with empty
385docstrings:
386
387 >>> def no_docstring(v):
388 ... pass
389 >>> excl_empty_finder = doctest.DocTestFinder(exclude_empty=True)
390 >>> excl_empty_finder.find(no_docstring)
Tim Peters8485b562004-08-04 18:46:34 +0000391 []
392
393If the function has a docstring with no examples, then a test with no
394examples is returned. (This lets `DocTestRunner` collect statistics
395about which functions have no tests -- but is that useful? And should
396an empty test also be created when there's no docstring?)
397
398 >>> def no_examples(v):
399 ... ''' no doctest examples '''
Tim Peters17b56372004-09-11 17:33:27 +0000400 >>> finder.find(no_examples) # doctest: +ELLIPSIS
401 [<DocTest no_examples from ...:1 (no examples)>]
Tim Peters8485b562004-08-04 18:46:34 +0000402
403Finding Tests in Classes
404~~~~~~~~~~~~~~~~~~~~~~~~
405For a class, DocTestFinder will create a test for the class's
406docstring, and will recursively explore its contents, including
407methods, classmethods, staticmethods, properties, and nested classes.
408
409 >>> finder = doctest.DocTestFinder()
410 >>> tests = finder.find(SampleClass)
411 >>> tests.sort()
412 >>> for t in tests:
413 ... print '%2s %s' % (len(t.examples), t.name)
414 1 SampleClass
415 3 SampleClass.NestedClass
416 1 SampleClass.NestedClass.__init__
Edward Loper32ddbf72004-09-13 05:47:24 +0000417 0 SampleClass.NestedClass.get
418 0 SampleClass.NestedClass.square
Tim Peters8485b562004-08-04 18:46:34 +0000419 1 SampleClass.__init__
420 2 SampleClass.a_classmethod
421 1 SampleClass.a_property
422 1 SampleClass.a_staticmethod
423 1 SampleClass.double
424 1 SampleClass.get
425
426New-style classes are also supported:
427
428 >>> tests = finder.find(SampleNewStyleClass)
429 >>> tests.sort()
430 >>> for t in tests:
431 ... print '%2s %s' % (len(t.examples), t.name)
432 1 SampleNewStyleClass
433 1 SampleNewStyleClass.__init__
434 1 SampleNewStyleClass.double
435 1 SampleNewStyleClass.get
436
437Finding Tests in Modules
438~~~~~~~~~~~~~~~~~~~~~~~~
439For a module, DocTestFinder will create a test for the class's
440docstring, and will recursively explore its contents, including
441functions, classes, and the `__test__` dictionary, if it exists:
442
443 >>> # A module
444 >>> import new
445 >>> m = new.module('some_module')
446 >>> def triple(val):
447 ... '''
448 ... >>> print tripple(11)
449 ... 33
450 ... '''
451 ... return val*3
452 >>> m.__dict__.update({
453 ... 'sample_func': sample_func,
454 ... 'SampleClass': SampleClass,
455 ... '__doc__': '''
456 ... Module docstring.
457 ... >>> print 'module'
458 ... module
459 ... ''',
460 ... '__test__': {
461 ... 'd': '>>> print 6\n6\n>>> print 7\n7\n',
462 ... 'c': triple}})
463
464 >>> finder = doctest.DocTestFinder()
465 >>> # Use module=test.test_doctest, to prevent doctest from
466 >>> # ignoring the objects since they weren't defined in m.
467 >>> import test.test_doctest
468 >>> tests = finder.find(m, module=test.test_doctest)
469 >>> tests.sort()
470 >>> for t in tests:
471 ... print '%2s %s' % (len(t.examples), t.name)
472 1 some_module
473 1 some_module.SampleClass
474 3 some_module.SampleClass.NestedClass
475 1 some_module.SampleClass.NestedClass.__init__
Edward Loper32ddbf72004-09-13 05:47:24 +0000476 0 some_module.SampleClass.NestedClass.get
477 0 some_module.SampleClass.NestedClass.square
Tim Peters8485b562004-08-04 18:46:34 +0000478 1 some_module.SampleClass.__init__
479 2 some_module.SampleClass.a_classmethod
480 1 some_module.SampleClass.a_property
481 1 some_module.SampleClass.a_staticmethod
482 1 some_module.SampleClass.double
483 1 some_module.SampleClass.get
Tim Petersc5684782004-09-13 01:07:12 +0000484 1 some_module.__test__.c
485 2 some_module.__test__.d
Tim Peters8485b562004-08-04 18:46:34 +0000486 1 some_module.sample_func
487
488Duplicate Removal
489~~~~~~~~~~~~~~~~~
490If a single object is listed twice (under different names), then tests
491will only be generated for it once:
492
Tim Petersf3f57472004-08-08 06:11:48 +0000493 >>> from test import doctest_aliases
Edward Loper32ddbf72004-09-13 05:47:24 +0000494 >>> tests = excl_empty_finder.find(doctest_aliases)
Tim Peters8485b562004-08-04 18:46:34 +0000495 >>> tests.sort()
496 >>> print len(tests)
497 2
498 >>> print tests[0].name
Tim Petersf3f57472004-08-08 06:11:48 +0000499 test.doctest_aliases.TwoNames
500
501 TwoNames.f and TwoNames.g are bound to the same object.
502 We can't guess which will be found in doctest's traversal of
503 TwoNames.__dict__ first, so we have to allow for either.
504
505 >>> tests[1].name.split('.')[-1] in ['f', 'g']
Tim Peters8485b562004-08-04 18:46:34 +0000506 True
507
508Filter Functions
509~~~~~~~~~~~~~~~~
Tim Petersf727c6c2004-08-08 01:48:59 +0000510A filter function can be used to restrict which objects get examined,
511but this is temporary, undocumented internal support for testmod's
512deprecated isprivate gimmick.
Tim Peters8485b562004-08-04 18:46:34 +0000513
514 >>> def namefilter(prefix, base):
515 ... return base.startswith('a_')
Tim Petersf727c6c2004-08-08 01:48:59 +0000516 >>> tests = doctest.DocTestFinder(_namefilter=namefilter).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000517 >>> tests.sort()
518 >>> for t in tests:
519 ... print '%2s %s' % (len(t.examples), t.name)
520 1 SampleClass
521 3 SampleClass.NestedClass
522 1 SampleClass.NestedClass.__init__
Edward Loper32ddbf72004-09-13 05:47:24 +0000523 0 SampleClass.NestedClass.get
524 0 SampleClass.NestedClass.square
Tim Peters8485b562004-08-04 18:46:34 +0000525 1 SampleClass.__init__
526 1 SampleClass.double
527 1 SampleClass.get
528
Tim Peters8485b562004-08-04 18:46:34 +0000529If a given object is filtered out, then none of the objects that it
530contains will be added either:
531
532 >>> def namefilter(prefix, base):
533 ... return base == 'NestedClass'
Tim Petersf727c6c2004-08-08 01:48:59 +0000534 >>> tests = doctest.DocTestFinder(_namefilter=namefilter).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000535 >>> tests.sort()
536 >>> for t in tests:
537 ... print '%2s %s' % (len(t.examples), t.name)
538 1 SampleClass
539 1 SampleClass.__init__
540 2 SampleClass.a_classmethod
541 1 SampleClass.a_property
542 1 SampleClass.a_staticmethod
543 1 SampleClass.double
544 1 SampleClass.get
545
Tim Petersf727c6c2004-08-08 01:48:59 +0000546The filter function apply to contained objects, and *not* to the
Tim Peters8485b562004-08-04 18:46:34 +0000547object explicitly passed to DocTestFinder:
548
549 >>> def namefilter(prefix, base):
550 ... return base == 'SampleClass'
Tim Petersf727c6c2004-08-08 01:48:59 +0000551 >>> tests = doctest.DocTestFinder(_namefilter=namefilter).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000552 >>> len(tests)
Edward Loper32ddbf72004-09-13 05:47:24 +0000553 11
Tim Peters8485b562004-08-04 18:46:34 +0000554
555Turning off Recursion
556~~~~~~~~~~~~~~~~~~~~~
557DocTestFinder can be told not to look for tests in contained objects
558using the `recurse` flag:
559
560 >>> tests = doctest.DocTestFinder(recurse=False).find(SampleClass)
561 >>> tests.sort()
562 >>> for t in tests:
563 ... print '%2s %s' % (len(t.examples), t.name)
564 1 SampleClass
Edward Loperb51b2342004-08-17 16:37:12 +0000565
566Line numbers
567~~~~~~~~~~~~
568DocTestFinder finds the line number of each example:
569
570 >>> def f(x):
571 ... '''
572 ... >>> x = 12
573 ...
574 ... some text
575 ...
576 ... >>> # examples are not created for comments & bare prompts.
577 ... >>>
578 ... ...
579 ...
580 ... >>> for x in range(10):
581 ... ... print x,
582 ... 0 1 2 3 4 5 6 7 8 9
583 ... >>> x/2
584 ... 6
585 ... '''
586 >>> test = doctest.DocTestFinder().find(f)[0]
587 >>> [e.lineno for e in test.examples]
588 [1, 9, 12]
Tim Peters8485b562004-08-04 18:46:34 +0000589"""
590
Edward Loper00f8da72004-08-26 18:05:07 +0000591def test_DocTestParser(): r"""
592Unit tests for the `DocTestParser` class.
593
594DocTestParser is used to parse docstrings containing doctest examples.
595
596The `parse` method divides a docstring into examples and intervening
597text:
598
599 >>> s = '''
600 ... >>> x, y = 2, 3 # no output expected
601 ... >>> if 1:
602 ... ... print x
603 ... ... print y
604 ... 2
605 ... 3
606 ...
607 ... Some text.
608 ... >>> x+y
609 ... 5
610 ... '''
611 >>> parser = doctest.DocTestParser()
612 >>> for piece in parser.parse(s):
613 ... if isinstance(piece, doctest.Example):
614 ... print 'Example:', (piece.source, piece.want, piece.lineno)
615 ... else:
616 ... print ' Text:', `piece`
617 Text: '\n'
618 Example: ('x, y = 2, 3 # no output expected\n', '', 1)
619 Text: ''
620 Example: ('if 1:\n print x\n print y\n', '2\n3\n', 2)
621 Text: '\nSome text.\n'
622 Example: ('x+y\n', '5\n', 9)
623 Text: ''
624
625The `get_examples` method returns just the examples:
626
627 >>> for piece in parser.get_examples(s):
628 ... print (piece.source, piece.want, piece.lineno)
629 ('x, y = 2, 3 # no output expected\n', '', 1)
630 ('if 1:\n print x\n print y\n', '2\n3\n', 2)
631 ('x+y\n', '5\n', 9)
632
633The `get_doctest` method creates a Test from the examples, along with the
634given arguments:
635
636 >>> test = parser.get_doctest(s, {}, 'name', 'filename', lineno=5)
637 >>> (test.name, test.filename, test.lineno)
638 ('name', 'filename', 5)
639 >>> for piece in test.examples:
640 ... print (piece.source, piece.want, piece.lineno)
641 ('x, y = 2, 3 # no output expected\n', '', 1)
642 ('if 1:\n print x\n print y\n', '2\n3\n', 2)
643 ('x+y\n', '5\n', 9)
644"""
645
Tim Peters8485b562004-08-04 18:46:34 +0000646class test_DocTestRunner:
647 def basics(): r"""
648Unit tests for the `DocTestRunner` class.
649
650DocTestRunner is used to run DocTest test cases, and to accumulate
651statistics. Here's a simple DocTest case we can use:
652
653 >>> def f(x):
654 ... '''
655 ... >>> x = 12
656 ... >>> print x
657 ... 12
658 ... >>> x/2
659 ... 6
660 ... '''
661 >>> test = doctest.DocTestFinder().find(f)[0]
662
663The main DocTestRunner interface is the `run` method, which runs a
664given DocTest case in a given namespace (globs). It returns a tuple
665`(f,t)`, where `f` is the number of failed tests and `t` is the number
666of tried tests.
667
668 >>> doctest.DocTestRunner(verbose=False).run(test)
669 (0, 3)
670
671If any example produces incorrect output, then the test runner reports
672the failure and proceeds to the next example:
673
674 >>> def f(x):
675 ... '''
676 ... >>> x = 12
677 ... >>> print x
678 ... 14
679 ... >>> x/2
680 ... 6
681 ... '''
682 >>> test = doctest.DocTestFinder().find(f)[0]
683 >>> doctest.DocTestRunner(verbose=True).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000684 ... # doctest: +ELLIPSIS
Edward Loperaacf0832004-08-26 01:19:50 +0000685 Trying:
686 x = 12
687 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000688 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000689 Trying:
690 print x
691 Expecting:
692 14
Tim Peters8485b562004-08-04 18:46:34 +0000693 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000694 File ..., line 4, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000695 Failed example:
696 print x
697 Expected:
698 14
699 Got:
700 12
Edward Loperaacf0832004-08-26 01:19:50 +0000701 Trying:
702 x/2
703 Expecting:
704 6
Tim Peters8485b562004-08-04 18:46:34 +0000705 ok
706 (1, 3)
707"""
708 def verbose_flag(): r"""
709The `verbose` flag makes the test runner generate more detailed
710output:
711
712 >>> def f(x):
713 ... '''
714 ... >>> x = 12
715 ... >>> print x
716 ... 12
717 ... >>> x/2
718 ... 6
719 ... '''
720 >>> test = doctest.DocTestFinder().find(f)[0]
721
722 >>> doctest.DocTestRunner(verbose=True).run(test)
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:
728 print x
729 Expecting:
730 12
Tim Peters8485b562004-08-04 18:46:34 +0000731 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000732 Trying:
733 x/2
734 Expecting:
735 6
Tim Peters8485b562004-08-04 18:46:34 +0000736 ok
737 (0, 3)
738
739If the `verbose` flag is unspecified, then the output will be verbose
740iff `-v` appears in sys.argv:
741
742 >>> # Save the real sys.argv list.
743 >>> old_argv = sys.argv
744
745 >>> # If -v does not appear in sys.argv, then output isn't verbose.
746 >>> sys.argv = ['test']
747 >>> doctest.DocTestRunner().run(test)
748 (0, 3)
749
750 >>> # If -v does appear in sys.argv, then output is verbose.
751 >>> sys.argv = ['test', '-v']
752 >>> doctest.DocTestRunner().run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000753 Trying:
754 x = 12
755 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000756 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000757 Trying:
758 print x
759 Expecting:
760 12
Tim Peters8485b562004-08-04 18:46:34 +0000761 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000762 Trying:
763 x/2
764 Expecting:
765 6
Tim Peters8485b562004-08-04 18:46:34 +0000766 ok
767 (0, 3)
768
769 >>> # Restore sys.argv
770 >>> sys.argv = old_argv
771
772In the remaining examples, the test runner's verbosity will be
773explicitly set, to ensure that the test behavior is consistent.
774 """
775 def exceptions(): r"""
776Tests of `DocTestRunner`'s exception handling.
777
778An expected exception is specified with a traceback message. The
779lines between the first line and the type/value may be omitted or
780replaced with any other string:
781
782 >>> def f(x):
783 ... '''
784 ... >>> x = 12
785 ... >>> print x/0
786 ... Traceback (most recent call last):
787 ... ZeroDivisionError: integer division or modulo by zero
788 ... '''
789 >>> test = doctest.DocTestFinder().find(f)[0]
790 >>> doctest.DocTestRunner(verbose=False).run(test)
791 (0, 2)
792
Edward Loper19b19582004-08-25 23:07:03 +0000793An example may not generate output before it raises an exception; if
794it does, then the traceback message will not be recognized as
795signaling an expected exception, so the example will be reported as an
796unexpected exception:
Tim Peters8485b562004-08-04 18:46:34 +0000797
798 >>> def f(x):
799 ... '''
800 ... >>> x = 12
801 ... >>> print 'pre-exception output', x/0
802 ... pre-exception output
803 ... Traceback (most recent call last):
804 ... ZeroDivisionError: integer division or modulo by zero
805 ... '''
806 >>> test = doctest.DocTestFinder().find(f)[0]
807 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper19b19582004-08-25 23:07:03 +0000808 ... # doctest: +ELLIPSIS
809 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000810 File ..., line 4, in f
Edward Loper19b19582004-08-25 23:07:03 +0000811 Failed example:
812 print 'pre-exception output', x/0
813 Exception raised:
814 ...
815 ZeroDivisionError: integer division or modulo by zero
816 (1, 2)
Tim Peters8485b562004-08-04 18:46:34 +0000817
818Exception messages may contain newlines:
819
820 >>> def f(x):
821 ... r'''
822 ... >>> raise ValueError, 'multi\nline\nmessage'
823 ... Traceback (most recent call last):
824 ... ValueError: multi
825 ... line
826 ... message
827 ... '''
828 >>> test = doctest.DocTestFinder().find(f)[0]
829 >>> doctest.DocTestRunner(verbose=False).run(test)
830 (0, 1)
831
832If an exception is expected, but an exception with the wrong type or
833message is raised, then it is reported as a failure:
834
835 >>> def f(x):
836 ... r'''
837 ... >>> raise ValueError, 'message'
838 ... Traceback (most recent call last):
839 ... ValueError: wrong message
840 ... '''
841 >>> test = doctest.DocTestFinder().find(f)[0]
842 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000843 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000844 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000845 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000846 Failed example:
847 raise ValueError, 'message'
Tim Peters8485b562004-08-04 18:46:34 +0000848 Expected:
849 Traceback (most recent call last):
850 ValueError: wrong message
851 Got:
852 Traceback (most recent call last):
Edward Loper8e4a34b2004-08-12 02:34:27 +0000853 ...
Tim Peters8485b562004-08-04 18:46:34 +0000854 ValueError: message
855 (1, 1)
856
Tim Peters1fbf9c52004-09-04 17:21:02 +0000857However, IGNORE_EXCEPTION_DETAIL can be used to allow a mismatch in the
858detail:
859
860 >>> def f(x):
861 ... r'''
862 ... >>> raise ValueError, 'message' #doctest: +IGNORE_EXCEPTION_DETAIL
863 ... Traceback (most recent call last):
864 ... ValueError: wrong message
865 ... '''
866 >>> test = doctest.DocTestFinder().find(f)[0]
867 >>> doctest.DocTestRunner(verbose=False).run(test)
868 (0, 1)
869
870But IGNORE_EXCEPTION_DETAIL does not allow a mismatch in the exception type:
871
872 >>> def f(x):
873 ... r'''
874 ... >>> raise ValueError, 'message' #doctest: +IGNORE_EXCEPTION_DETAIL
875 ... Traceback (most recent call last):
876 ... TypeError: wrong type
877 ... '''
878 >>> test = doctest.DocTestFinder().find(f)[0]
879 >>> doctest.DocTestRunner(verbose=False).run(test)
880 ... # doctest: +ELLIPSIS
881 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000882 File ..., line 3, in f
Tim Peters1fbf9c52004-09-04 17:21:02 +0000883 Failed example:
884 raise ValueError, 'message' #doctest: +IGNORE_EXCEPTION_DETAIL
885 Expected:
886 Traceback (most recent call last):
887 TypeError: wrong type
888 Got:
889 Traceback (most recent call last):
890 ...
891 ValueError: message
892 (1, 1)
893
Tim Peters8485b562004-08-04 18:46:34 +0000894If an exception is raised but not expected, then it is reported as an
895unexpected exception:
896
Tim Peters8485b562004-08-04 18:46:34 +0000897 >>> def f(x):
898 ... r'''
899 ... >>> 1/0
900 ... 0
901 ... '''
902 >>> test = doctest.DocTestFinder().find(f)[0]
903 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper74bca7a2004-08-12 02:27:44 +0000904 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000905 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000906 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000907 Failed example:
908 1/0
Tim Peters8485b562004-08-04 18:46:34 +0000909 Exception raised:
910 Traceback (most recent call last):
Jim Fulton07a349c2004-08-22 14:10:00 +0000911 ...
Tim Peters8485b562004-08-04 18:46:34 +0000912 ZeroDivisionError: integer division or modulo by zero
913 (1, 1)
Tim Peters8485b562004-08-04 18:46:34 +0000914"""
915 def optionflags(): r"""
916Tests of `DocTestRunner`'s option flag handling.
917
918Several option flags can be used to customize the behavior of the test
919runner. These are defined as module constants in doctest, and passed
920to the DocTestRunner constructor (multiple constants should be or-ed
921together).
922
923The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
924and 1/0:
925
926 >>> def f(x):
927 ... '>>> True\n1\n'
928
929 >>> # Without the flag:
930 >>> test = doctest.DocTestFinder().find(f)[0]
931 >>> doctest.DocTestRunner(verbose=False).run(test)
932 (0, 1)
933
934 >>> # With the flag:
935 >>> test = doctest.DocTestFinder().find(f)[0]
936 >>> flags = doctest.DONT_ACCEPT_TRUE_FOR_1
937 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000938 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000939 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000940 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000941 Failed example:
942 True
943 Expected:
944 1
945 Got:
946 True
Tim Peters8485b562004-08-04 18:46:34 +0000947 (1, 1)
948
949The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines
950and the '<BLANKLINE>' marker:
951
952 >>> def f(x):
953 ... '>>> print "a\\n\\nb"\na\n<BLANKLINE>\nb\n'
954
955 >>> # Without the flag:
956 >>> test = doctest.DocTestFinder().find(f)[0]
957 >>> doctest.DocTestRunner(verbose=False).run(test)
958 (0, 1)
959
960 >>> # With the flag:
961 >>> test = doctest.DocTestFinder().find(f)[0]
962 >>> flags = doctest.DONT_ACCEPT_BLANKLINE
963 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000964 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000965 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000966 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000967 Failed example:
968 print "a\n\nb"
Tim Peters8485b562004-08-04 18:46:34 +0000969 Expected:
970 a
971 <BLANKLINE>
972 b
973 Got:
974 a
975 <BLANKLINE>
976 b
977 (1, 1)
978
979The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be
980treated as equal:
981
982 >>> def f(x):
983 ... '>>> print 1, 2, 3\n 1 2\n 3'
984
985 >>> # Without the flag:
986 >>> test = doctest.DocTestFinder().find(f)[0]
987 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000988 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000989 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000990 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000991 Failed example:
992 print 1, 2, 3
Tim Peters8485b562004-08-04 18:46:34 +0000993 Expected:
994 1 2
995 3
Jim Fulton07a349c2004-08-22 14:10:00 +0000996 Got:
997 1 2 3
Tim Peters8485b562004-08-04 18:46:34 +0000998 (1, 1)
999
1000 >>> # With the flag:
1001 >>> test = doctest.DocTestFinder().find(f)[0]
1002 >>> flags = doctest.NORMALIZE_WHITESPACE
1003 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1004 (0, 1)
1005
Tim Peters026f8dc2004-08-19 16:38:58 +00001006 An example from the docs:
1007 >>> print range(20) #doctest: +NORMALIZE_WHITESPACE
1008 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
1009 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
1010
Tim Peters8485b562004-08-04 18:46:34 +00001011The ELLIPSIS flag causes ellipsis marker ("...") in the expected
1012output to match any substring in the actual output:
1013
1014 >>> def f(x):
1015 ... '>>> print range(15)\n[0, 1, 2, ..., 14]\n'
1016
1017 >>> # Without the flag:
1018 >>> test = doctest.DocTestFinder().find(f)[0]
1019 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001020 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001021 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001022 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001023 Failed example:
1024 print range(15)
1025 Expected:
1026 [0, 1, 2, ..., 14]
1027 Got:
1028 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
Tim Peters8485b562004-08-04 18:46:34 +00001029 (1, 1)
1030
1031 >>> # With the flag:
1032 >>> test = doctest.DocTestFinder().find(f)[0]
1033 >>> flags = doctest.ELLIPSIS
1034 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1035 (0, 1)
1036
Tim Peterse594bee2004-08-22 01:47:51 +00001037 ... also matches nothing:
Tim Peters1cf3aa62004-08-19 06:49:33 +00001038
1039 >>> for i in range(100):
Tim Peterse594bee2004-08-22 01:47:51 +00001040 ... print i**2, #doctest: +ELLIPSIS
1041 0 1...4...9 16 ... 36 49 64 ... 9801
Tim Peters1cf3aa62004-08-19 06:49:33 +00001042
Tim Peters026f8dc2004-08-19 16:38:58 +00001043 ... can be surprising; e.g., this test passes:
Tim Peters26b3ebb2004-08-19 08:10:08 +00001044
1045 >>> for i in range(21): #doctest: +ELLIPSIS
Tim Peterse594bee2004-08-22 01:47:51 +00001046 ... print i,
1047 0 1 2 ...1...2...0
Tim Peters26b3ebb2004-08-19 08:10:08 +00001048
Tim Peters026f8dc2004-08-19 16:38:58 +00001049 Examples from the docs:
1050
1051 >>> print range(20) # doctest:+ELLIPSIS
1052 [0, 1, ..., 18, 19]
1053
1054 >>> print range(20) # doctest: +ELLIPSIS
1055 ... # doctest: +NORMALIZE_WHITESPACE
1056 [0, 1, ..., 18, 19]
1057
Edward Loper71f55af2004-08-26 01:41:51 +00001058The REPORT_UDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001059and actual outputs to be displayed using a unified diff:
1060
1061 >>> def f(x):
1062 ... r'''
1063 ... >>> print '\n'.join('abcdefg')
1064 ... a
1065 ... B
1066 ... c
1067 ... d
1068 ... f
1069 ... g
1070 ... h
1071 ... '''
1072
1073 >>> # Without the flag:
1074 >>> test = doctest.DocTestFinder().find(f)[0]
1075 >>> doctest.DocTestRunner(verbose=False).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 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001079 Failed example:
1080 print '\n'.join('abcdefg')
Tim Peters8485b562004-08-04 18:46:34 +00001081 Expected:
1082 a
1083 B
1084 c
1085 d
1086 f
1087 g
1088 h
1089 Got:
1090 a
1091 b
1092 c
1093 d
1094 e
1095 f
1096 g
1097 (1, 1)
1098
1099 >>> # With the flag:
1100 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001101 >>> flags = doctest.REPORT_UDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001102 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001103 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001104 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001105 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001106 Failed example:
1107 print '\n'.join('abcdefg')
Edward Loper56629292004-08-26 01:31:56 +00001108 Differences (unified diff with -expected +actual):
Tim Peterse7edcb82004-08-26 05:44:27 +00001109 @@ -1,7 +1,7 @@
Tim Peters8485b562004-08-04 18:46:34 +00001110 a
1111 -B
1112 +b
1113 c
1114 d
1115 +e
1116 f
1117 g
1118 -h
Tim Peters8485b562004-08-04 18:46:34 +00001119 (1, 1)
1120
Edward Loper71f55af2004-08-26 01:41:51 +00001121The REPORT_CDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001122and actual outputs to be displayed using a context diff:
1123
Edward Loper71f55af2004-08-26 01:41:51 +00001124 >>> # Reuse f() from the REPORT_UDIFF example, above.
Tim Peters8485b562004-08-04 18:46:34 +00001125 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001126 >>> flags = doctest.REPORT_CDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001127 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001128 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001129 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001130 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001131 Failed example:
1132 print '\n'.join('abcdefg')
Edward Loper56629292004-08-26 01:31:56 +00001133 Differences (context diff with expected followed by actual):
Tim Peters8485b562004-08-04 18:46:34 +00001134 ***************
Tim Peterse7edcb82004-08-26 05:44:27 +00001135 *** 1,7 ****
Tim Peters8485b562004-08-04 18:46:34 +00001136 a
1137 ! B
1138 c
1139 d
1140 f
1141 g
1142 - h
Tim Peterse7edcb82004-08-26 05:44:27 +00001143 --- 1,7 ----
Tim Peters8485b562004-08-04 18:46:34 +00001144 a
1145 ! b
1146 c
1147 d
1148 + e
1149 f
1150 g
Tim Peters8485b562004-08-04 18:46:34 +00001151 (1, 1)
Tim Petersc6cbab02004-08-22 19:43:28 +00001152
1153
Edward Loper71f55af2004-08-26 01:41:51 +00001154The REPORT_NDIFF flag causes failures to use the difflib.Differ algorithm
Tim Petersc6cbab02004-08-22 19:43:28 +00001155used by the popular ndiff.py utility. This does intraline difference
1156marking, as well as interline differences.
1157
1158 >>> def f(x):
1159 ... r'''
1160 ... >>> print "a b c d e f g h i j k l m"
1161 ... a b c d e f g h i j k 1 m
1162 ... '''
1163 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001164 >>> flags = doctest.REPORT_NDIFF
Tim Petersc6cbab02004-08-22 19:43:28 +00001165 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001166 ... # doctest: +ELLIPSIS
Tim Petersc6cbab02004-08-22 19:43:28 +00001167 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001168 File ..., line 3, in f
Tim Petersc6cbab02004-08-22 19:43:28 +00001169 Failed example:
1170 print "a b c d e f g h i j k l m"
1171 Differences (ndiff with -expected +actual):
1172 - a b c d e f g h i j k 1 m
1173 ? ^
1174 + a b c d e f g h i j k l m
1175 ? + ++ ^
Tim Petersc6cbab02004-08-22 19:43:28 +00001176 (1, 1)
Edward Lopera89f88d2004-08-26 02:45:51 +00001177
1178The REPORT_ONLY_FIRST_FAILURE supresses result output after the first
1179failing example:
1180
1181 >>> def f(x):
1182 ... r'''
1183 ... >>> print 1 # first success
1184 ... 1
1185 ... >>> print 2 # first failure
1186 ... 200
1187 ... >>> print 3 # second failure
1188 ... 300
1189 ... >>> print 4 # second success
1190 ... 4
1191 ... >>> print 5 # third failure
1192 ... 500
1193 ... '''
1194 >>> test = doctest.DocTestFinder().find(f)[0]
1195 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1196 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001197 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001198 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001199 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001200 Failed example:
1201 print 2 # first failure
1202 Expected:
1203 200
1204 Got:
1205 2
1206 (3, 5)
1207
1208However, output from `report_start` is not supressed:
1209
1210 >>> doctest.DocTestRunner(verbose=True, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001211 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001212 Trying:
1213 print 1 # first success
1214 Expecting:
1215 1
1216 ok
1217 Trying:
1218 print 2 # first failure
1219 Expecting:
1220 200
1221 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001222 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001223 Failed example:
1224 print 2 # first failure
1225 Expected:
1226 200
1227 Got:
1228 2
1229 (3, 5)
1230
1231For the purposes of REPORT_ONLY_FIRST_FAILURE, unexpected exceptions
1232count as failures:
1233
1234 >>> def f(x):
1235 ... r'''
1236 ... >>> print 1 # first success
1237 ... 1
1238 ... >>> raise ValueError(2) # first failure
1239 ... 200
1240 ... >>> print 3 # second failure
1241 ... 300
1242 ... >>> print 4 # second success
1243 ... 4
1244 ... >>> print 5 # third failure
1245 ... 500
1246 ... '''
1247 >>> test = doctest.DocTestFinder().find(f)[0]
1248 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1249 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1250 ... # doctest: +ELLIPSIS
1251 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001252 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001253 Failed example:
1254 raise ValueError(2) # first failure
1255 Exception raised:
1256 ...
1257 ValueError: 2
1258 (3, 5)
1259
Tim Petersc6cbab02004-08-22 19:43:28 +00001260 """
1261
Tim Peters8485b562004-08-04 18:46:34 +00001262 def option_directives(): r"""
1263Tests of `DocTestRunner`'s option directive mechanism.
1264
Edward Loper74bca7a2004-08-12 02:27:44 +00001265Option directives can be used to turn option flags on or off for a
1266single example. To turn an option on for an example, follow that
1267example with a comment of the form ``# doctest: +OPTION``:
Tim Peters8485b562004-08-04 18:46:34 +00001268
1269 >>> def f(x): r'''
Edward Loper74bca7a2004-08-12 02:27:44 +00001270 ... >>> print range(10) # should fail: no ellipsis
1271 ... [0, 1, ..., 9]
1272 ...
1273 ... >>> print range(10) # doctest: +ELLIPSIS
1274 ... [0, 1, ..., 9]
1275 ... '''
1276 >>> test = doctest.DocTestFinder().find(f)[0]
1277 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001278 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001279 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001280 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001281 Failed example:
1282 print range(10) # should fail: no ellipsis
1283 Expected:
1284 [0, 1, ..., 9]
1285 Got:
1286 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001287 (1, 2)
1288
1289To turn an option off for an example, follow that example with a
1290comment of the form ``# doctest: -OPTION``:
1291
1292 >>> def f(x): r'''
1293 ... >>> print range(10)
1294 ... [0, 1, ..., 9]
1295 ...
1296 ... >>> # should fail: no ellipsis
1297 ... >>> print range(10) # doctest: -ELLIPSIS
1298 ... [0, 1, ..., 9]
1299 ... '''
1300 >>> test = doctest.DocTestFinder().find(f)[0]
1301 >>> doctest.DocTestRunner(verbose=False,
1302 ... optionflags=doctest.ELLIPSIS).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001303 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001304 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001305 File ..., line 6, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001306 Failed example:
1307 print range(10) # doctest: -ELLIPSIS
1308 Expected:
1309 [0, 1, ..., 9]
1310 Got:
1311 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001312 (1, 2)
1313
1314Option directives affect only the example that they appear with; they
1315do not change the options for surrounding examples:
Edward Loper8e4a34b2004-08-12 02:34:27 +00001316
Edward Loper74bca7a2004-08-12 02:27:44 +00001317 >>> def f(x): r'''
Tim Peters8485b562004-08-04 18:46:34 +00001318 ... >>> print range(10) # Should fail: no ellipsis
1319 ... [0, 1, ..., 9]
1320 ...
Edward Loper74bca7a2004-08-12 02:27:44 +00001321 ... >>> print range(10) # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001322 ... [0, 1, ..., 9]
1323 ...
Tim Peters8485b562004-08-04 18:46:34 +00001324 ... >>> print range(10) # Should fail: no ellipsis
1325 ... [0, 1, ..., 9]
1326 ... '''
1327 >>> test = doctest.DocTestFinder().find(f)[0]
1328 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001329 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001330 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001331 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001332 Failed example:
1333 print range(10) # Should fail: no ellipsis
1334 Expected:
1335 [0, 1, ..., 9]
1336 Got:
1337 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001338 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001339 File ..., line 8, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001340 Failed example:
1341 print range(10) # Should fail: no ellipsis
1342 Expected:
1343 [0, 1, ..., 9]
1344 Got:
1345 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001346 (2, 3)
1347
Edward Loper74bca7a2004-08-12 02:27:44 +00001348Multiple options may be modified by a single option directive. They
1349may be separated by whitespace, commas, or both:
Tim Peters8485b562004-08-04 18:46:34 +00001350
1351 >>> def f(x): r'''
1352 ... >>> print range(10) # Should fail
1353 ... [0, 1, ..., 9]
Tim Peters8485b562004-08-04 18:46:34 +00001354 ... >>> print range(10) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001355 ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001356 ... [0, 1, ..., 9]
1357 ... '''
1358 >>> test = doctest.DocTestFinder().find(f)[0]
1359 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001360 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001361 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001362 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001363 Failed example:
1364 print range(10) # Should fail
1365 Expected:
1366 [0, 1, ..., 9]
1367 Got:
1368 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001369 (1, 2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001370
1371 >>> def f(x): r'''
1372 ... >>> print range(10) # Should fail
1373 ... [0, 1, ..., 9]
1374 ... >>> print range(10) # Should succeed
1375 ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
1376 ... [0, 1, ..., 9]
1377 ... '''
1378 >>> test = doctest.DocTestFinder().find(f)[0]
1379 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001380 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001381 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001382 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001383 Failed example:
1384 print range(10) # Should fail
1385 Expected:
1386 [0, 1, ..., 9]
1387 Got:
1388 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001389 (1, 2)
1390
1391 >>> def f(x): r'''
1392 ... >>> print range(10) # Should fail
1393 ... [0, 1, ..., 9]
1394 ... >>> print range(10) # Should succeed
1395 ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1396 ... [0, 1, ..., 9]
1397 ... '''
1398 >>> test = doctest.DocTestFinder().find(f)[0]
1399 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001400 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001401 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001402 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001403 Failed example:
1404 print range(10) # Should fail
1405 Expected:
1406 [0, 1, ..., 9]
1407 Got:
1408 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001409 (1, 2)
1410
1411The option directive may be put on the line following the source, as
1412long as a continuation prompt is used:
1413
1414 >>> def f(x): r'''
1415 ... >>> print range(10)
1416 ... ... # doctest: +ELLIPSIS
1417 ... [0, 1, ..., 9]
1418 ... '''
1419 >>> test = doctest.DocTestFinder().find(f)[0]
1420 >>> doctest.DocTestRunner(verbose=False).run(test)
1421 (0, 1)
Edward Loper8e4a34b2004-08-12 02:34:27 +00001422
Edward Loper74bca7a2004-08-12 02:27:44 +00001423For examples with multi-line source, the option directive may appear
1424at the end of any line:
1425
1426 >>> def f(x): r'''
1427 ... >>> for x in range(10): # doctest: +ELLIPSIS
1428 ... ... print x,
1429 ... 0 1 2 ... 9
1430 ...
1431 ... >>> for x in range(10):
1432 ... ... print x, # doctest: +ELLIPSIS
1433 ... 0 1 2 ... 9
1434 ... '''
1435 >>> test = doctest.DocTestFinder().find(f)[0]
1436 >>> doctest.DocTestRunner(verbose=False).run(test)
1437 (0, 2)
1438
1439If more than one line of an example with multi-line source has an
1440option directive, then they are combined:
1441
1442 >>> def f(x): r'''
1443 ... Should fail (option directive not on the last line):
1444 ... >>> for x in range(10): # doctest: +ELLIPSIS
1445 ... ... print x, # doctest: +NORMALIZE_WHITESPACE
1446 ... 0 1 2...9
1447 ... '''
1448 >>> test = doctest.DocTestFinder().find(f)[0]
1449 >>> doctest.DocTestRunner(verbose=False).run(test)
1450 (0, 1)
1451
1452It is an error to have a comment of the form ``# doctest:`` that is
1453*not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
1454``OPTION`` is an option that has been registered with
1455`register_option`:
1456
1457 >>> # Error: Option not registered
1458 >>> s = '>>> print 12 #doctest: +BADOPTION'
1459 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1460 Traceback (most recent call last):
1461 ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
1462
1463 >>> # Error: No + or - prefix
1464 >>> s = '>>> print 12 #doctest: ELLIPSIS'
1465 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1466 Traceback (most recent call last):
1467 ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
1468
1469It is an error to use an option directive on a line that contains no
1470source:
1471
1472 >>> s = '>>> # doctest: +ELLIPSIS'
1473 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1474 Traceback (most recent call last):
1475 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 +00001476"""
1477
1478def test_testsource(): r"""
1479Unit tests for `testsource()`.
1480
1481The testsource() function takes a module and a name, finds the (first)
Tim Peters19397e52004-08-06 22:02:59 +00001482test with that name in that module, and converts it to a script. The
1483example code is converted to regular Python code. The surrounding
1484words and expected output are converted to comments:
Tim Peters8485b562004-08-04 18:46:34 +00001485
1486 >>> import test.test_doctest
1487 >>> name = 'test.test_doctest.sample_func'
1488 >>> print doctest.testsource(test.test_doctest, name)
Edward Lopera5db6002004-08-12 02:41:30 +00001489 # Blah blah
Tim Peters19397e52004-08-06 22:02:59 +00001490 #
Tim Peters8485b562004-08-04 18:46:34 +00001491 print sample_func(22)
1492 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001493 ## 44
Tim Peters19397e52004-08-06 22:02:59 +00001494 #
Edward Lopera5db6002004-08-12 02:41:30 +00001495 # Yee ha!
Tim Peters8485b562004-08-04 18:46:34 +00001496
1497 >>> name = 'test.test_doctest.SampleNewStyleClass'
1498 >>> print doctest.testsource(test.test_doctest, name)
1499 print '1\n2\n3'
1500 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001501 ## 1
1502 ## 2
1503 ## 3
Tim Peters8485b562004-08-04 18:46:34 +00001504
1505 >>> name = 'test.test_doctest.SampleClass.a_classmethod'
1506 >>> print doctest.testsource(test.test_doctest, name)
1507 print SampleClass.a_classmethod(10)
1508 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001509 ## 12
Tim Peters8485b562004-08-04 18:46:34 +00001510 print SampleClass(0).a_classmethod(10)
1511 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001512 ## 12
Tim Peters8485b562004-08-04 18:46:34 +00001513"""
1514
1515def test_debug(): r"""
1516
1517Create a docstring that we want to debug:
1518
1519 >>> s = '''
1520 ... >>> x = 12
1521 ... >>> print x
1522 ... 12
1523 ... '''
1524
1525Create some fake stdin input, to feed to the debugger:
1526
1527 >>> import tempfile
Tim Peters8485b562004-08-04 18:46:34 +00001528 >>> real_stdin = sys.stdin
Edward Loper2de91ba2004-08-27 02:07:46 +00001529 >>> sys.stdin = _FakeInput(['next', 'print x', 'continue'])
Tim Peters8485b562004-08-04 18:46:34 +00001530
1531Run the debugger on the docstring, and then restore sys.stdin.
1532
Edward Loper2de91ba2004-08-27 02:07:46 +00001533 >>> try: doctest.debug_src(s)
1534 ... finally: sys.stdin = real_stdin
Tim Peters8485b562004-08-04 18:46:34 +00001535 > <string>(1)?()
Edward Loper2de91ba2004-08-27 02:07:46 +00001536 (Pdb) next
1537 12
Tim Peters8485b562004-08-04 18:46:34 +00001538 --Return--
1539 > <string>(1)?()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001540 (Pdb) print x
1541 12
1542 (Pdb) continue
Tim Peters8485b562004-08-04 18:46:34 +00001543
1544"""
1545
Jim Fulton356fd192004-08-09 11:34:47 +00001546def test_pdb_set_trace():
Edward Loper2de91ba2004-08-27 02:07:46 +00001547 """Using pdb.set_trace from a doctest
Jim Fulton356fd192004-08-09 11:34:47 +00001548
Tim Peters413ced62004-08-09 15:43:47 +00001549 You can use pdb.set_trace from a doctest. To do so, you must
Jim Fulton356fd192004-08-09 11:34:47 +00001550 retrieve the set_trace function from the pdb module at the time
Tim Peters413ced62004-08-09 15:43:47 +00001551 you use it. The doctest module changes sys.stdout so that it can
1552 capture program output. It also temporarily replaces pdb.set_trace
1553 with a version that restores stdout. This is necessary for you to
Jim Fulton356fd192004-08-09 11:34:47 +00001554 see debugger output.
1555
1556 >>> doc = '''
1557 ... >>> x = 42
1558 ... >>> import pdb; pdb.set_trace()
1559 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001560 >>> parser = doctest.DocTestParser()
1561 >>> test = parser.get_doctest(doc, {}, "foo", "foo.py", 0)
Jim Fulton356fd192004-08-09 11:34:47 +00001562 >>> runner = doctest.DocTestRunner(verbose=False)
1563
1564 To demonstrate this, we'll create a fake standard input that
1565 captures our debugger input:
1566
1567 >>> import tempfile
Edward Loper2de91ba2004-08-27 02:07:46 +00001568 >>> real_stdin = sys.stdin
1569 >>> sys.stdin = _FakeInput([
Jim Fulton356fd192004-08-09 11:34:47 +00001570 ... 'print x', # print data defined by the example
1571 ... 'continue', # stop debugging
Edward Loper2de91ba2004-08-27 02:07:46 +00001572 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001573
Edward Loper2de91ba2004-08-27 02:07:46 +00001574 >>> try: runner.run(test)
1575 ... finally: sys.stdin = real_stdin
Jim Fulton356fd192004-08-09 11:34:47 +00001576 --Return--
Edward Loper2de91ba2004-08-27 02:07:46 +00001577 > <doctest foo[1]>(1)?()->None
1578 -> import pdb; pdb.set_trace()
1579 (Pdb) print x
1580 42
1581 (Pdb) continue
1582 (0, 2)
Jim Fulton356fd192004-08-09 11:34:47 +00001583
1584 You can also put pdb.set_trace in a function called from a test:
1585
1586 >>> def calls_set_trace():
1587 ... y=2
1588 ... import pdb; pdb.set_trace()
1589
1590 >>> doc = '''
1591 ... >>> x=1
1592 ... >>> calls_set_trace()
1593 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001594 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
Edward Loper2de91ba2004-08-27 02:07:46 +00001595 >>> real_stdin = sys.stdin
1596 >>> sys.stdin = _FakeInput([
Jim Fulton356fd192004-08-09 11:34:47 +00001597 ... 'print y', # print data defined in the function
1598 ... 'up', # out of function
1599 ... 'print x', # print data defined by the example
1600 ... 'continue', # stop debugging
Edward Loper2de91ba2004-08-27 02:07:46 +00001601 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001602
Edward Loper2de91ba2004-08-27 02:07:46 +00001603 >>> try: runner.run(test)
1604 ... finally: sys.stdin = real_stdin
Jim Fulton356fd192004-08-09 11:34:47 +00001605 --Return--
Edward Loper2de91ba2004-08-27 02:07:46 +00001606 > <doctest test.test_doctest.test_pdb_set_trace[8]>(3)calls_set_trace()->None
1607 -> import pdb; pdb.set_trace()
1608 (Pdb) print y
1609 2
1610 (Pdb) up
1611 > <doctest foo[1]>(1)?()
1612 -> calls_set_trace()
1613 (Pdb) print x
1614 1
1615 (Pdb) continue
1616 (0, 2)
1617
1618 During interactive debugging, source code is shown, even for
1619 doctest examples:
1620
1621 >>> doc = '''
1622 ... >>> def f(x):
1623 ... ... g(x*2)
1624 ... >>> def g(x):
1625 ... ... print x+3
1626 ... ... import pdb; pdb.set_trace()
1627 ... >>> f(3)
1628 ... '''
1629 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
1630 >>> real_stdin = sys.stdin
1631 >>> sys.stdin = _FakeInput([
1632 ... 'list', # list source from example 2
1633 ... 'next', # return from g()
1634 ... 'list', # list source from example 1
1635 ... 'next', # return from f()
1636 ... 'list', # list source from example 3
1637 ... 'continue', # stop debugging
1638 ... ''])
1639 >>> try: runner.run(test)
1640 ... finally: sys.stdin = real_stdin
1641 ... # doctest: +NORMALIZE_WHITESPACE
1642 --Return--
1643 > <doctest foo[1]>(3)g()->None
1644 -> import pdb; pdb.set_trace()
1645 (Pdb) list
1646 1 def g(x):
1647 2 print x+3
1648 3 -> import pdb; pdb.set_trace()
1649 [EOF]
1650 (Pdb) next
1651 --Return--
1652 > <doctest foo[0]>(2)f()->None
1653 -> g(x*2)
1654 (Pdb) list
1655 1 def f(x):
1656 2 -> g(x*2)
1657 [EOF]
1658 (Pdb) next
1659 --Return--
1660 > <doctest foo[2]>(1)?()->None
1661 -> f(3)
1662 (Pdb) list
1663 1 -> f(3)
1664 [EOF]
1665 (Pdb) continue
1666 **********************************************************************
1667 File "foo.py", line 7, in foo
1668 Failed example:
1669 f(3)
1670 Expected nothing
1671 Got:
1672 9
1673 (1, 3)
Jim Fulton356fd192004-08-09 11:34:47 +00001674 """
1675
Tim Peters19397e52004-08-06 22:02:59 +00001676def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +00001677 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +00001678
1679 We create a Suite by providing a module. A module can be provided
1680 by passing a module object:
1681
1682 >>> import unittest
1683 >>> import test.sample_doctest
1684 >>> suite = doctest.DocTestSuite(test.sample_doctest)
1685 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001686 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001687
1688 We can also supply the module by name:
1689
1690 >>> suite = doctest.DocTestSuite('test.sample_doctest')
1691 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001692 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001693
1694 We can use the current module:
1695
1696 >>> suite = test.sample_doctest.test_suite()
1697 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001698 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001699
1700 We can supply global variables. If we pass globs, they will be
1701 used instead of the module globals. Here we'll pass an empty
1702 globals, triggering an extra error:
1703
1704 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
1705 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001706 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001707
1708 Alternatively, we can provide extra globals. Here we'll make an
1709 error go away by providing an extra global variable:
1710
1711 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1712 ... extraglobs={'y': 1})
1713 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001714 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001715
1716 You can pass option flags. Here we'll cause an extra error
1717 by disabling the blank-line feature:
1718
1719 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00001720 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00001721 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001722 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001723
Tim Peters1e277ee2004-08-07 05:37:52 +00001724 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00001725
Jim Fultonf54bad42004-08-28 14:57:56 +00001726 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00001727 ... import test.test_doctest
1728 ... test.test_doctest.sillySetup = True
1729
Jim Fultonf54bad42004-08-28 14:57:56 +00001730 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00001731 ... import test.test_doctest
1732 ... del test.test_doctest.sillySetup
1733
1734 Here, we installed a silly variable that the test expects:
1735
1736 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1737 ... setUp=setUp, tearDown=tearDown)
1738 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001739 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001740
1741 But the tearDown restores sanity:
1742
1743 >>> import test.test_doctest
1744 >>> test.test_doctest.sillySetup
1745 Traceback (most recent call last):
1746 ...
1747 AttributeError: 'module' object has no attribute 'sillySetup'
1748
Jim Fultonf54bad42004-08-28 14:57:56 +00001749 The setUp and tearDown funtions are passed test objects. Here
1750 we'll use the setUp function to supply the missing variable y:
1751
1752 >>> def setUp(test):
1753 ... test.globs['y'] = 1
1754
1755 >>> suite = doctest.DocTestSuite('test.sample_doctest', setUp=setUp)
1756 >>> suite.run(unittest.TestResult())
1757 <unittest.TestResult run=9 errors=0 failures=3>
1758
1759 Here, we didn't need to use a tearDown function because we
1760 modified the test globals, which are a copy of the
1761 sample_doctest module dictionary. The test globals are
1762 automatically cleared for us after a test.
1763
Tim Peters19397e52004-08-06 22:02:59 +00001764 Finally, you can provide an alternate test finder. Here we'll
Tim Peters1e277ee2004-08-07 05:37:52 +00001765 use a custom test_finder to to run just the test named bar.
1766 However, the test in the module docstring, and the two tests
1767 in the module __test__ dict, aren't filtered, so we actually
1768 run three tests besides bar's. The filtering mechanisms are
1769 poorly conceived, and will go away someday.
Tim Peters19397e52004-08-06 22:02:59 +00001770
1771 >>> finder = doctest.DocTestFinder(
Tim Petersf727c6c2004-08-08 01:48:59 +00001772 ... _namefilter=lambda prefix, base: base!='bar')
Tim Peters19397e52004-08-06 22:02:59 +00001773 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1774 ... test_finder=finder)
1775 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001776 <unittest.TestResult run=4 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00001777 """
1778
1779def test_DocFileSuite():
1780 """We can test tests found in text files using a DocFileSuite.
1781
1782 We create a suite by providing the names of one or more text
1783 files that include examples:
1784
1785 >>> import unittest
1786 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1787 ... 'test_doctest2.txt')
1788 >>> suite.run(unittest.TestResult())
1789 <unittest.TestResult run=2 errors=0 failures=2>
1790
1791 The test files are looked for in the directory containing the
1792 calling module. A package keyword argument can be provided to
1793 specify a different relative location.
1794
1795 >>> import unittest
1796 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1797 ... 'test_doctest2.txt',
1798 ... package='test')
1799 >>> suite.run(unittest.TestResult())
1800 <unittest.TestResult run=2 errors=0 failures=2>
1801
1802 Note that '/' should be used as a path separator. It will be
1803 converted to a native separator at run time:
1804
1805
1806 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
1807 >>> suite.run(unittest.TestResult())
1808 <unittest.TestResult run=1 errors=0 failures=1>
1809
1810 You can specify initial global variables:
1811
1812 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1813 ... 'test_doctest2.txt',
1814 ... globs={'favorite_color': 'blue'})
1815 >>> suite.run(unittest.TestResult())
1816 <unittest.TestResult run=2 errors=0 failures=1>
1817
1818 In this case, we supplied a missing favorite color. You can
1819 provide doctest options:
1820
1821 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1822 ... 'test_doctest2.txt',
1823 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
1824 ... globs={'favorite_color': 'blue'})
1825 >>> suite.run(unittest.TestResult())
1826 <unittest.TestResult run=2 errors=0 failures=2>
1827
1828 And, you can provide setUp and tearDown functions:
1829
1830 You can supply setUp and teatDoen functions:
1831
Jim Fultonf54bad42004-08-28 14:57:56 +00001832 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00001833 ... import test.test_doctest
1834 ... test.test_doctest.sillySetup = True
1835
Jim Fultonf54bad42004-08-28 14:57:56 +00001836 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00001837 ... import test.test_doctest
1838 ... del test.test_doctest.sillySetup
1839
1840 Here, we installed a silly variable that the test expects:
1841
1842 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1843 ... 'test_doctest2.txt',
1844 ... setUp=setUp, tearDown=tearDown)
1845 >>> suite.run(unittest.TestResult())
1846 <unittest.TestResult run=2 errors=0 failures=1>
1847
1848 But the tearDown restores sanity:
1849
1850 >>> import test.test_doctest
1851 >>> test.test_doctest.sillySetup
1852 Traceback (most recent call last):
1853 ...
1854 AttributeError: 'module' object has no attribute 'sillySetup'
1855
Jim Fultonf54bad42004-08-28 14:57:56 +00001856 The setUp and tearDown funtions are passed test objects.
1857 Here, we'll use a setUp function to set the favorite color in
1858 test_doctest.txt:
1859
1860 >>> def setUp(test):
1861 ... test.globs['favorite_color'] = 'blue'
1862
1863 >>> suite = doctest.DocFileSuite('test_doctest.txt', setUp=setUp)
1864 >>> suite.run(unittest.TestResult())
1865 <unittest.TestResult run=1 errors=0 failures=0>
1866
1867 Here, we didn't need to use a tearDown function because we
1868 modified the test globals. The test globals are
1869 automatically cleared for us after a test.
Tim Petersdf7a2082004-08-29 00:38:17 +00001870
Jim Fultonf54bad42004-08-28 14:57:56 +00001871 """
Tim Peters19397e52004-08-06 22:02:59 +00001872
Jim Fulton07a349c2004-08-22 14:10:00 +00001873def test_trailing_space_in_test():
1874 """
Tim Petersa7def722004-08-23 22:13:22 +00001875 Trailing spaces in expected output are significant:
Tim Petersc6cbab02004-08-22 19:43:28 +00001876
Jim Fulton07a349c2004-08-22 14:10:00 +00001877 >>> x, y = 'foo', ''
1878 >>> print x, y
1879 foo \n
1880 """
Tim Peters19397e52004-08-06 22:02:59 +00001881
Jim Fultonf54bad42004-08-28 14:57:56 +00001882
1883def test_unittest_reportflags():
1884 """Default unittest reporting flags can be set to control reporting
1885
1886 Here, we'll set the REPORT_ONLY_FIRST_FAILURE option so we see
1887 only the first failure of each test. First, we'll look at the
1888 output without the flag. The file test_doctest.txt file has two
1889 tests. They both fail if blank lines are disabled:
1890
1891 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1892 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
1893 >>> import unittest
1894 >>> result = suite.run(unittest.TestResult())
1895 >>> print result.failures[0][1] # doctest: +ELLIPSIS
1896 Traceback ...
1897 Failed example:
1898 favorite_color
1899 ...
1900 Failed example:
1901 if 1:
1902 ...
1903
1904 Note that we see both failures displayed.
1905
1906 >>> old = doctest.set_unittest_reportflags(
1907 ... doctest.REPORT_ONLY_FIRST_FAILURE)
1908
1909 Now, when we run the test:
1910
1911 >>> result = suite.run(unittest.TestResult())
1912 >>> print result.failures[0][1] # doctest: +ELLIPSIS
1913 Traceback ...
1914 Failed example:
1915 favorite_color
1916 Exception raised:
1917 ...
1918 NameError: name 'favorite_color' is not defined
1919 <BLANKLINE>
1920 <BLANKLINE>
Tim Petersdf7a2082004-08-29 00:38:17 +00001921
Jim Fultonf54bad42004-08-28 14:57:56 +00001922 We get only the first failure.
1923
1924 If we give any reporting options when we set up the tests,
1925 however:
1926
1927 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1928 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE | doctest.REPORT_NDIFF)
1929
1930 Then the default eporting options are ignored:
1931
1932 >>> result = suite.run(unittest.TestResult())
1933 >>> print result.failures[0][1] # doctest: +ELLIPSIS
1934 Traceback ...
1935 Failed example:
1936 favorite_color
1937 ...
1938 Failed example:
1939 if 1:
1940 print 'a'
1941 print
1942 print 'b'
1943 Differences (ndiff with -expected +actual):
1944 a
1945 - <BLANKLINE>
1946 +
1947 b
1948 <BLANKLINE>
1949 <BLANKLINE>
1950
1951
1952 Test runners can restore the formatting flags after they run:
1953
1954 >>> ignored = doctest.set_unittest_reportflags(old)
1955
1956 """
1957
Tim Petersa7def722004-08-23 22:13:22 +00001958# old_test1, ... used to live in doctest.py, but cluttered it. Note
1959# that these use the deprecated doctest.Tester, so should go away (or
1960# be rewritten) someday.
1961
1962# Ignore all warnings about the use of class Tester in this module.
1963# Note that the name of this module may differ depending on how it's
1964# imported, so the use of __name__ is important.
1965warnings.filterwarnings("ignore", "class Tester", DeprecationWarning,
1966 __name__, 0)
1967
1968def old_test1(): r"""
1969>>> from doctest import Tester
1970>>> t = Tester(globs={'x': 42}, verbose=0)
1971>>> t.runstring(r'''
1972... >>> x = x * 2
1973... >>> print x
1974... 42
1975... ''', 'XYZ')
1976**********************************************************************
1977Line 3, in XYZ
1978Failed example:
1979 print x
1980Expected:
1981 42
1982Got:
1983 84
1984(1, 2)
1985>>> t.runstring(">>> x = x * 2\n>>> print x\n84\n", 'example2')
1986(0, 2)
1987>>> t.summarize()
1988**********************************************************************
19891 items had failures:
1990 1 of 2 in XYZ
1991***Test Failed*** 1 failures.
1992(1, 4)
1993>>> t.summarize(verbose=1)
19941 items passed all tests:
1995 2 tests in example2
1996**********************************************************************
19971 items had failures:
1998 1 of 2 in XYZ
19994 tests in 2 items.
20003 passed and 1 failed.
2001***Test Failed*** 1 failures.
2002(1, 4)
2003"""
2004
2005def old_test2(): r"""
2006 >>> from doctest import Tester
2007 >>> t = Tester(globs={}, verbose=1)
2008 >>> test = r'''
2009 ... # just an example
2010 ... >>> x = 1 + 2
2011 ... >>> x
2012 ... 3
2013 ... '''
2014 >>> t.runstring(test, "Example")
2015 Running string Example
Edward Loperaacf0832004-08-26 01:19:50 +00002016 Trying:
2017 x = 1 + 2
2018 Expecting nothing
Tim Petersa7def722004-08-23 22:13:22 +00002019 ok
Edward Loperaacf0832004-08-26 01:19:50 +00002020 Trying:
2021 x
2022 Expecting:
2023 3
Tim Petersa7def722004-08-23 22:13:22 +00002024 ok
2025 0 of 2 examples failed in string Example
2026 (0, 2)
2027"""
2028
2029def old_test3(): r"""
2030 >>> from doctest import Tester
2031 >>> t = Tester(globs={}, verbose=0)
2032 >>> def _f():
2033 ... '''Trivial docstring example.
2034 ... >>> assert 2 == 2
2035 ... '''
2036 ... return 32
2037 ...
2038 >>> t.rundoc(_f) # expect 0 failures in 1 example
2039 (0, 1)
2040"""
2041
2042def old_test4(): """
2043 >>> import new
2044 >>> m1 = new.module('_m1')
2045 >>> m2 = new.module('_m2')
2046 >>> test_data = \"""
2047 ... def _f():
2048 ... '''>>> assert 1 == 1
2049 ... '''
2050 ... def g():
2051 ... '''>>> assert 2 != 1
2052 ... '''
2053 ... class H:
2054 ... '''>>> assert 2 > 1
2055 ... '''
2056 ... def bar(self):
2057 ... '''>>> assert 1 < 2
2058 ... '''
2059 ... \"""
2060 >>> exec test_data in m1.__dict__
2061 >>> exec test_data in m2.__dict__
2062 >>> m1.__dict__.update({"f2": m2._f, "g2": m2.g, "h2": m2.H})
2063
2064 Tests that objects outside m1 are excluded:
2065
2066 >>> from doctest import Tester
2067 >>> t = Tester(globs={}, verbose=0)
2068 >>> t.rundict(m1.__dict__, "rundict_test", m1) # f2 and g2 and h2 skipped
2069 (0, 4)
2070
2071 Once more, not excluding stuff outside m1:
2072
2073 >>> t = Tester(globs={}, verbose=0)
2074 >>> t.rundict(m1.__dict__, "rundict_test_pvt") # None are skipped.
2075 (0, 8)
2076
2077 The exclusion of objects from outside the designated module is
2078 meant to be invoked automagically by testmod.
2079
2080 >>> doctest.testmod(m1, verbose=False)
2081 (0, 4)
2082"""
2083
Tim Peters8485b562004-08-04 18:46:34 +00002084######################################################################
2085## Main
2086######################################################################
2087
2088def test_main():
2089 # Check the doctest cases in doctest itself:
2090 test_support.run_doctest(doctest, verbosity=True)
2091 # Check the doctest cases defined here:
2092 from test import test_doctest
2093 test_support.run_doctest(test_doctest, verbosity=True)
2094
2095import trace, sys, re, StringIO
2096def test_coverage(coverdir):
2097 tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
2098 trace=0, count=1)
2099 tracer.run('reload(doctest); test_main()')
2100 r = tracer.results()
2101 print 'Writing coverage results...'
2102 r.write_results(show_missing=True, summary=True,
2103 coverdir=coverdir)
2104
2105if __name__ == '__main__':
2106 if '-c' in sys.argv:
2107 test_coverage('/tmp/doctest.cover')
2108 else:
2109 test_main()