blob: 8c96b2122305f01a3960493c6dd16d3e00e751af [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
Tim Peters958cc892004-09-13 14:53:28 +0000380 >>> finder.find(no_docstring)
381 []
Edward Loper32ddbf72004-09-13 05:47:24 +0000382
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__
417 1 SampleClass.__init__
418 2 SampleClass.a_classmethod
419 1 SampleClass.a_property
420 1 SampleClass.a_staticmethod
421 1 SampleClass.double
422 1 SampleClass.get
423
424New-style classes are also supported:
425
426 >>> tests = finder.find(SampleNewStyleClass)
427 >>> tests.sort()
428 >>> for t in tests:
429 ... print '%2s %s' % (len(t.examples), t.name)
430 1 SampleNewStyleClass
431 1 SampleNewStyleClass.__init__
432 1 SampleNewStyleClass.double
433 1 SampleNewStyleClass.get
434
435Finding Tests in Modules
436~~~~~~~~~~~~~~~~~~~~~~~~
437For a module, DocTestFinder will create a test for the class's
438docstring, and will recursively explore its contents, including
439functions, classes, and the `__test__` dictionary, if it exists:
440
441 >>> # A module
442 >>> import new
443 >>> m = new.module('some_module')
444 >>> def triple(val):
445 ... '''
446 ... >>> print tripple(11)
447 ... 33
448 ... '''
449 ... return val*3
450 >>> m.__dict__.update({
451 ... 'sample_func': sample_func,
452 ... 'SampleClass': SampleClass,
453 ... '__doc__': '''
454 ... Module docstring.
455 ... >>> print 'module'
456 ... module
457 ... ''',
458 ... '__test__': {
459 ... 'd': '>>> print 6\n6\n>>> print 7\n7\n',
460 ... 'c': triple}})
461
462 >>> finder = doctest.DocTestFinder()
463 >>> # Use module=test.test_doctest, to prevent doctest from
464 >>> # ignoring the objects since they weren't defined in m.
465 >>> import test.test_doctest
466 >>> tests = finder.find(m, module=test.test_doctest)
467 >>> tests.sort()
468 >>> for t in tests:
469 ... print '%2s %s' % (len(t.examples), t.name)
470 1 some_module
471 1 some_module.SampleClass
472 3 some_module.SampleClass.NestedClass
473 1 some_module.SampleClass.NestedClass.__init__
474 1 some_module.SampleClass.__init__
475 2 some_module.SampleClass.a_classmethod
476 1 some_module.SampleClass.a_property
477 1 some_module.SampleClass.a_staticmethod
478 1 some_module.SampleClass.double
479 1 some_module.SampleClass.get
Tim Petersc5684782004-09-13 01:07:12 +0000480 1 some_module.__test__.c
481 2 some_module.__test__.d
Tim Peters8485b562004-08-04 18:46:34 +0000482 1 some_module.sample_func
483
484Duplicate Removal
485~~~~~~~~~~~~~~~~~
486If a single object is listed twice (under different names), then tests
487will only be generated for it once:
488
Tim Petersf3f57472004-08-08 06:11:48 +0000489 >>> from test import doctest_aliases
Edward Loper32ddbf72004-09-13 05:47:24 +0000490 >>> tests = excl_empty_finder.find(doctest_aliases)
Tim Peters8485b562004-08-04 18:46:34 +0000491 >>> tests.sort()
492 >>> print len(tests)
493 2
494 >>> print tests[0].name
Tim Petersf3f57472004-08-08 06:11:48 +0000495 test.doctest_aliases.TwoNames
496
497 TwoNames.f and TwoNames.g are bound to the same object.
498 We can't guess which will be found in doctest's traversal of
499 TwoNames.__dict__ first, so we have to allow for either.
500
501 >>> tests[1].name.split('.')[-1] in ['f', 'g']
Tim Peters8485b562004-08-04 18:46:34 +0000502 True
503
504Filter Functions
505~~~~~~~~~~~~~~~~
Tim Petersf727c6c2004-08-08 01:48:59 +0000506A filter function can be used to restrict which objects get examined,
507but this is temporary, undocumented internal support for testmod's
508deprecated isprivate gimmick.
Tim Peters8485b562004-08-04 18:46:34 +0000509
510 >>> def namefilter(prefix, base):
511 ... return base.startswith('a_')
Tim Petersf727c6c2004-08-08 01:48:59 +0000512 >>> tests = doctest.DocTestFinder(_namefilter=namefilter).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000513 >>> tests.sort()
514 >>> for t in tests:
515 ... print '%2s %s' % (len(t.examples), t.name)
516 1 SampleClass
517 3 SampleClass.NestedClass
518 1 SampleClass.NestedClass.__init__
Tim Peters958cc892004-09-13 14:53:28 +0000519 1 SampleClass.__init__
520 1 SampleClass.double
521 1 SampleClass.get
522
523By default, that excluded objects with no doctests. exclude_empty=False
524tells it to include (empty) tests for objects with no doctests. This feature
525is really to support backward compatibility in what doctest.master.summarize()
526displays.
527
528 >>> tests = doctest.DocTestFinder(_namefilter=namefilter,
529 ... exclude_empty=False).find(SampleClass)
530 >>> tests.sort()
531 >>> for t in tests:
532 ... print '%2s %s' % (len(t.examples), t.name)
533 1 SampleClass
534 3 SampleClass.NestedClass
535 1 SampleClass.NestedClass.__init__
Edward Loper32ddbf72004-09-13 05:47:24 +0000536 0 SampleClass.NestedClass.get
537 0 SampleClass.NestedClass.square
Tim Peters8485b562004-08-04 18:46:34 +0000538 1 SampleClass.__init__
539 1 SampleClass.double
540 1 SampleClass.get
541
Tim Peters8485b562004-08-04 18:46:34 +0000542If a given object is filtered out, then none of the objects that it
543contains will be added either:
544
545 >>> def namefilter(prefix, base):
546 ... return base == 'NestedClass'
Tim Petersf727c6c2004-08-08 01:48:59 +0000547 >>> tests = doctest.DocTestFinder(_namefilter=namefilter).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000548 >>> tests.sort()
549 >>> for t in tests:
550 ... print '%2s %s' % (len(t.examples), t.name)
551 1 SampleClass
552 1 SampleClass.__init__
553 2 SampleClass.a_classmethod
554 1 SampleClass.a_property
555 1 SampleClass.a_staticmethod
556 1 SampleClass.double
557 1 SampleClass.get
558
Tim Petersf727c6c2004-08-08 01:48:59 +0000559The filter function apply to contained objects, and *not* to the
Tim Peters8485b562004-08-04 18:46:34 +0000560object explicitly passed to DocTestFinder:
561
562 >>> def namefilter(prefix, base):
563 ... return base == 'SampleClass'
Tim Petersf727c6c2004-08-08 01:48:59 +0000564 >>> tests = doctest.DocTestFinder(_namefilter=namefilter).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000565 >>> len(tests)
Tim Peters958cc892004-09-13 14:53:28 +0000566 9
Tim Peters8485b562004-08-04 18:46:34 +0000567
568Turning off Recursion
569~~~~~~~~~~~~~~~~~~~~~
570DocTestFinder can be told not to look for tests in contained objects
571using the `recurse` flag:
572
573 >>> tests = doctest.DocTestFinder(recurse=False).find(SampleClass)
574 >>> tests.sort()
575 >>> for t in tests:
576 ... print '%2s %s' % (len(t.examples), t.name)
577 1 SampleClass
Edward Loperb51b2342004-08-17 16:37:12 +0000578
579Line numbers
580~~~~~~~~~~~~
581DocTestFinder finds the line number of each example:
582
583 >>> def f(x):
584 ... '''
585 ... >>> x = 12
586 ...
587 ... some text
588 ...
589 ... >>> # examples are not created for comments & bare prompts.
590 ... >>>
591 ... ...
592 ...
593 ... >>> for x in range(10):
594 ... ... print x,
595 ... 0 1 2 3 4 5 6 7 8 9
596 ... >>> x/2
597 ... 6
598 ... '''
599 >>> test = doctest.DocTestFinder().find(f)[0]
600 >>> [e.lineno for e in test.examples]
601 [1, 9, 12]
Tim Peters8485b562004-08-04 18:46:34 +0000602"""
603
Edward Loper00f8da72004-08-26 18:05:07 +0000604def test_DocTestParser(): r"""
605Unit tests for the `DocTestParser` class.
606
607DocTestParser is used to parse docstrings containing doctest examples.
608
609The `parse` method divides a docstring into examples and intervening
610text:
611
612 >>> s = '''
613 ... >>> x, y = 2, 3 # no output expected
614 ... >>> if 1:
615 ... ... print x
616 ... ... print y
617 ... 2
618 ... 3
619 ...
620 ... Some text.
621 ... >>> x+y
622 ... 5
623 ... '''
624 >>> parser = doctest.DocTestParser()
625 >>> for piece in parser.parse(s):
626 ... if isinstance(piece, doctest.Example):
627 ... print 'Example:', (piece.source, piece.want, piece.lineno)
628 ... else:
629 ... print ' Text:', `piece`
630 Text: '\n'
631 Example: ('x, y = 2, 3 # no output expected\n', '', 1)
632 Text: ''
633 Example: ('if 1:\n print x\n print y\n', '2\n3\n', 2)
634 Text: '\nSome text.\n'
635 Example: ('x+y\n', '5\n', 9)
636 Text: ''
637
638The `get_examples` method returns just the examples:
639
640 >>> for piece in parser.get_examples(s):
641 ... print (piece.source, piece.want, piece.lineno)
642 ('x, y = 2, 3 # no output expected\n', '', 1)
643 ('if 1:\n print x\n print y\n', '2\n3\n', 2)
644 ('x+y\n', '5\n', 9)
645
646The `get_doctest` method creates a Test from the examples, along with the
647given arguments:
648
649 >>> test = parser.get_doctest(s, {}, 'name', 'filename', lineno=5)
650 >>> (test.name, test.filename, test.lineno)
651 ('name', 'filename', 5)
652 >>> for piece in test.examples:
653 ... print (piece.source, piece.want, piece.lineno)
654 ('x, y = 2, 3 # no output expected\n', '', 1)
655 ('if 1:\n print x\n print y\n', '2\n3\n', 2)
656 ('x+y\n', '5\n', 9)
657"""
658
Tim Peters8485b562004-08-04 18:46:34 +0000659class test_DocTestRunner:
660 def basics(): r"""
661Unit tests for the `DocTestRunner` class.
662
663DocTestRunner is used to run DocTest test cases, and to accumulate
664statistics. Here's a simple DocTest case we can use:
665
666 >>> def f(x):
667 ... '''
668 ... >>> x = 12
669 ... >>> print x
670 ... 12
671 ... >>> x/2
672 ... 6
673 ... '''
674 >>> test = doctest.DocTestFinder().find(f)[0]
675
676The main DocTestRunner interface is the `run` method, which runs a
677given DocTest case in a given namespace (globs). It returns a tuple
678`(f,t)`, where `f` is the number of failed tests and `t` is the number
679of tried tests.
680
681 >>> doctest.DocTestRunner(verbose=False).run(test)
682 (0, 3)
683
684If any example produces incorrect output, then the test runner reports
685the failure and proceeds to the next example:
686
687 >>> def f(x):
688 ... '''
689 ... >>> x = 12
690 ... >>> print x
691 ... 14
692 ... >>> x/2
693 ... 6
694 ... '''
695 >>> test = doctest.DocTestFinder().find(f)[0]
696 >>> doctest.DocTestRunner(verbose=True).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000697 ... # doctest: +ELLIPSIS
Edward Loperaacf0832004-08-26 01:19:50 +0000698 Trying:
699 x = 12
700 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000701 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000702 Trying:
703 print x
704 Expecting:
705 14
Tim Peters8485b562004-08-04 18:46:34 +0000706 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000707 File ..., line 4, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000708 Failed example:
709 print x
710 Expected:
711 14
712 Got:
713 12
Edward Loperaacf0832004-08-26 01:19:50 +0000714 Trying:
715 x/2
716 Expecting:
717 6
Tim Peters8485b562004-08-04 18:46:34 +0000718 ok
719 (1, 3)
720"""
721 def verbose_flag(): r"""
722The `verbose` flag makes the test runner generate more detailed
723output:
724
725 >>> def f(x):
726 ... '''
727 ... >>> x = 12
728 ... >>> print x
729 ... 12
730 ... >>> x/2
731 ... 6
732 ... '''
733 >>> test = doctest.DocTestFinder().find(f)[0]
734
735 >>> doctest.DocTestRunner(verbose=True).run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000736 Trying:
737 x = 12
738 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000739 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000740 Trying:
741 print x
742 Expecting:
743 12
Tim Peters8485b562004-08-04 18:46:34 +0000744 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000745 Trying:
746 x/2
747 Expecting:
748 6
Tim Peters8485b562004-08-04 18:46:34 +0000749 ok
750 (0, 3)
751
752If the `verbose` flag is unspecified, then the output will be verbose
753iff `-v` appears in sys.argv:
754
755 >>> # Save the real sys.argv list.
756 >>> old_argv = sys.argv
757
758 >>> # If -v does not appear in sys.argv, then output isn't verbose.
759 >>> sys.argv = ['test']
760 >>> doctest.DocTestRunner().run(test)
761 (0, 3)
762
763 >>> # If -v does appear in sys.argv, then output is verbose.
764 >>> sys.argv = ['test', '-v']
765 >>> doctest.DocTestRunner().run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000766 Trying:
767 x = 12
768 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000769 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000770 Trying:
771 print x
772 Expecting:
773 12
Tim Peters8485b562004-08-04 18:46:34 +0000774 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000775 Trying:
776 x/2
777 Expecting:
778 6
Tim Peters8485b562004-08-04 18:46:34 +0000779 ok
780 (0, 3)
781
782 >>> # Restore sys.argv
783 >>> sys.argv = old_argv
784
785In the remaining examples, the test runner's verbosity will be
786explicitly set, to ensure that the test behavior is consistent.
787 """
788 def exceptions(): r"""
789Tests of `DocTestRunner`'s exception handling.
790
791An expected exception is specified with a traceback message. The
792lines between the first line and the type/value may be omitted or
793replaced with any other string:
794
795 >>> def f(x):
796 ... '''
797 ... >>> x = 12
798 ... >>> print x/0
799 ... Traceback (most recent call last):
800 ... ZeroDivisionError: integer division or modulo by zero
801 ... '''
802 >>> test = doctest.DocTestFinder().find(f)[0]
803 >>> doctest.DocTestRunner(verbose=False).run(test)
804 (0, 2)
805
Edward Loper19b19582004-08-25 23:07:03 +0000806An example may not generate output before it raises an exception; if
807it does, then the traceback message will not be recognized as
808signaling an expected exception, so the example will be reported as an
809unexpected exception:
Tim Peters8485b562004-08-04 18:46:34 +0000810
811 >>> def f(x):
812 ... '''
813 ... >>> x = 12
814 ... >>> print 'pre-exception output', x/0
815 ... pre-exception output
816 ... Traceback (most recent call last):
817 ... ZeroDivisionError: integer division or modulo by zero
818 ... '''
819 >>> test = doctest.DocTestFinder().find(f)[0]
820 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper19b19582004-08-25 23:07:03 +0000821 ... # doctest: +ELLIPSIS
822 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000823 File ..., line 4, in f
Edward Loper19b19582004-08-25 23:07:03 +0000824 Failed example:
825 print 'pre-exception output', x/0
826 Exception raised:
827 ...
828 ZeroDivisionError: integer division or modulo by zero
829 (1, 2)
Tim Peters8485b562004-08-04 18:46:34 +0000830
831Exception messages may contain newlines:
832
833 >>> def f(x):
834 ... r'''
835 ... >>> raise ValueError, 'multi\nline\nmessage'
836 ... Traceback (most recent call last):
837 ... ValueError: multi
838 ... line
839 ... message
840 ... '''
841 >>> test = doctest.DocTestFinder().find(f)[0]
842 >>> doctest.DocTestRunner(verbose=False).run(test)
843 (0, 1)
844
845If an exception is expected, but an exception with the wrong type or
846message is raised, then it is reported as a failure:
847
848 >>> def f(x):
849 ... r'''
850 ... >>> raise ValueError, 'message'
851 ... Traceback (most recent call last):
852 ... ValueError: wrong message
853 ... '''
854 >>> test = doctest.DocTestFinder().find(f)[0]
855 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000856 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000857 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000858 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000859 Failed example:
860 raise ValueError, 'message'
Tim Peters8485b562004-08-04 18:46:34 +0000861 Expected:
862 Traceback (most recent call last):
863 ValueError: wrong message
864 Got:
865 Traceback (most recent call last):
Edward Loper8e4a34b2004-08-12 02:34:27 +0000866 ...
Tim Peters8485b562004-08-04 18:46:34 +0000867 ValueError: message
868 (1, 1)
869
Tim Peters1fbf9c52004-09-04 17:21:02 +0000870However, IGNORE_EXCEPTION_DETAIL can be used to allow a mismatch in the
871detail:
872
873 >>> def f(x):
874 ... r'''
875 ... >>> raise ValueError, 'message' #doctest: +IGNORE_EXCEPTION_DETAIL
876 ... Traceback (most recent call last):
877 ... ValueError: wrong message
878 ... '''
879 >>> test = doctest.DocTestFinder().find(f)[0]
880 >>> doctest.DocTestRunner(verbose=False).run(test)
881 (0, 1)
882
883But IGNORE_EXCEPTION_DETAIL does not allow a mismatch in the exception type:
884
885 >>> def f(x):
886 ... r'''
887 ... >>> raise ValueError, 'message' #doctest: +IGNORE_EXCEPTION_DETAIL
888 ... Traceback (most recent call last):
889 ... TypeError: wrong type
890 ... '''
891 >>> test = doctest.DocTestFinder().find(f)[0]
892 >>> doctest.DocTestRunner(verbose=False).run(test)
893 ... # doctest: +ELLIPSIS
894 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000895 File ..., line 3, in f
Tim Peters1fbf9c52004-09-04 17:21:02 +0000896 Failed example:
897 raise ValueError, 'message' #doctest: +IGNORE_EXCEPTION_DETAIL
898 Expected:
899 Traceback (most recent call last):
900 TypeError: wrong type
901 Got:
902 Traceback (most recent call last):
903 ...
904 ValueError: message
905 (1, 1)
906
Tim Peters8485b562004-08-04 18:46:34 +0000907If an exception is raised but not expected, then it is reported as an
908unexpected exception:
909
Tim Peters8485b562004-08-04 18:46:34 +0000910 >>> def f(x):
911 ... r'''
912 ... >>> 1/0
913 ... 0
914 ... '''
915 >>> test = doctest.DocTestFinder().find(f)[0]
916 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper74bca7a2004-08-12 02:27:44 +0000917 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000918 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000919 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000920 Failed example:
921 1/0
Tim Peters8485b562004-08-04 18:46:34 +0000922 Exception raised:
923 Traceback (most recent call last):
Jim Fulton07a349c2004-08-22 14:10:00 +0000924 ...
Tim Peters8485b562004-08-04 18:46:34 +0000925 ZeroDivisionError: integer division or modulo by zero
926 (1, 1)
Tim Peters8485b562004-08-04 18:46:34 +0000927"""
928 def optionflags(): r"""
929Tests of `DocTestRunner`'s option flag handling.
930
931Several option flags can be used to customize the behavior of the test
932runner. These are defined as module constants in doctest, and passed
933to the DocTestRunner constructor (multiple constants should be or-ed
934together).
935
936The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
937and 1/0:
938
939 >>> def f(x):
940 ... '>>> True\n1\n'
941
942 >>> # Without the flag:
943 >>> test = doctest.DocTestFinder().find(f)[0]
944 >>> doctest.DocTestRunner(verbose=False).run(test)
945 (0, 1)
946
947 >>> # With the flag:
948 >>> test = doctest.DocTestFinder().find(f)[0]
949 >>> flags = doctest.DONT_ACCEPT_TRUE_FOR_1
950 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000951 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000952 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000953 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000954 Failed example:
955 True
956 Expected:
957 1
958 Got:
959 True
Tim Peters8485b562004-08-04 18:46:34 +0000960 (1, 1)
961
962The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines
963and the '<BLANKLINE>' marker:
964
965 >>> def f(x):
966 ... '>>> print "a\\n\\nb"\na\n<BLANKLINE>\nb\n'
967
968 >>> # Without the flag:
969 >>> test = doctest.DocTestFinder().find(f)[0]
970 >>> doctest.DocTestRunner(verbose=False).run(test)
971 (0, 1)
972
973 >>> # With the flag:
974 >>> test = doctest.DocTestFinder().find(f)[0]
975 >>> flags = doctest.DONT_ACCEPT_BLANKLINE
976 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000977 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000978 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000979 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000980 Failed example:
981 print "a\n\nb"
Tim Peters8485b562004-08-04 18:46:34 +0000982 Expected:
983 a
984 <BLANKLINE>
985 b
986 Got:
987 a
988 <BLANKLINE>
989 b
990 (1, 1)
991
992The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be
993treated as equal:
994
995 >>> def f(x):
996 ... '>>> print 1, 2, 3\n 1 2\n 3'
997
998 >>> # Without the flag:
999 >>> test = doctest.DocTestFinder().find(f)[0]
1000 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001001 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001002 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001003 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001004 Failed example:
1005 print 1, 2, 3
Tim Peters8485b562004-08-04 18:46:34 +00001006 Expected:
1007 1 2
1008 3
Jim Fulton07a349c2004-08-22 14:10:00 +00001009 Got:
1010 1 2 3
Tim Peters8485b562004-08-04 18:46:34 +00001011 (1, 1)
1012
1013 >>> # With the flag:
1014 >>> test = doctest.DocTestFinder().find(f)[0]
1015 >>> flags = doctest.NORMALIZE_WHITESPACE
1016 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1017 (0, 1)
1018
Tim Peters026f8dc2004-08-19 16:38:58 +00001019 An example from the docs:
1020 >>> print range(20) #doctest: +NORMALIZE_WHITESPACE
1021 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
1022 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
1023
Tim Peters8485b562004-08-04 18:46:34 +00001024The ELLIPSIS flag causes ellipsis marker ("...") in the expected
1025output to match any substring in the actual output:
1026
1027 >>> def f(x):
1028 ... '>>> print range(15)\n[0, 1, 2, ..., 14]\n'
1029
1030 >>> # Without the flag:
1031 >>> test = doctest.DocTestFinder().find(f)[0]
1032 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001033 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001034 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001035 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001036 Failed example:
1037 print range(15)
1038 Expected:
1039 [0, 1, 2, ..., 14]
1040 Got:
1041 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
Tim Peters8485b562004-08-04 18:46:34 +00001042 (1, 1)
1043
1044 >>> # With the flag:
1045 >>> test = doctest.DocTestFinder().find(f)[0]
1046 >>> flags = doctest.ELLIPSIS
1047 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1048 (0, 1)
1049
Tim Peterse594bee2004-08-22 01:47:51 +00001050 ... also matches nothing:
Tim Peters1cf3aa62004-08-19 06:49:33 +00001051
1052 >>> for i in range(100):
Tim Peterse594bee2004-08-22 01:47:51 +00001053 ... print i**2, #doctest: +ELLIPSIS
1054 0 1...4...9 16 ... 36 49 64 ... 9801
Tim Peters1cf3aa62004-08-19 06:49:33 +00001055
Tim Peters026f8dc2004-08-19 16:38:58 +00001056 ... can be surprising; e.g., this test passes:
Tim Peters26b3ebb2004-08-19 08:10:08 +00001057
1058 >>> for i in range(21): #doctest: +ELLIPSIS
Tim Peterse594bee2004-08-22 01:47:51 +00001059 ... print i,
1060 0 1 2 ...1...2...0
Tim Peters26b3ebb2004-08-19 08:10:08 +00001061
Tim Peters026f8dc2004-08-19 16:38:58 +00001062 Examples from the docs:
1063
1064 >>> print range(20) # doctest:+ELLIPSIS
1065 [0, 1, ..., 18, 19]
1066
1067 >>> print range(20) # doctest: +ELLIPSIS
1068 ... # doctest: +NORMALIZE_WHITESPACE
1069 [0, 1, ..., 18, 19]
1070
Edward Loper71f55af2004-08-26 01:41:51 +00001071The REPORT_UDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001072and actual outputs to be displayed using a unified diff:
1073
1074 >>> def f(x):
1075 ... r'''
1076 ... >>> print '\n'.join('abcdefg')
1077 ... a
1078 ... B
1079 ... c
1080 ... d
1081 ... f
1082 ... g
1083 ... h
1084 ... '''
1085
1086 >>> # Without the flag:
1087 >>> test = doctest.DocTestFinder().find(f)[0]
1088 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001089 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001090 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001091 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001092 Failed example:
1093 print '\n'.join('abcdefg')
Tim Peters8485b562004-08-04 18:46:34 +00001094 Expected:
1095 a
1096 B
1097 c
1098 d
1099 f
1100 g
1101 h
1102 Got:
1103 a
1104 b
1105 c
1106 d
1107 e
1108 f
1109 g
1110 (1, 1)
1111
1112 >>> # With the flag:
1113 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001114 >>> flags = doctest.REPORT_UDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001115 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001116 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001117 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001118 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001119 Failed example:
1120 print '\n'.join('abcdefg')
Edward Loper56629292004-08-26 01:31:56 +00001121 Differences (unified diff with -expected +actual):
Tim Peterse7edcb82004-08-26 05:44:27 +00001122 @@ -1,7 +1,7 @@
Tim Peters8485b562004-08-04 18:46:34 +00001123 a
1124 -B
1125 +b
1126 c
1127 d
1128 +e
1129 f
1130 g
1131 -h
Tim Peters8485b562004-08-04 18:46:34 +00001132 (1, 1)
1133
Edward Loper71f55af2004-08-26 01:41:51 +00001134The REPORT_CDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001135and actual outputs to be displayed using a context diff:
1136
Edward Loper71f55af2004-08-26 01:41:51 +00001137 >>> # Reuse f() from the REPORT_UDIFF example, above.
Tim Peters8485b562004-08-04 18:46:34 +00001138 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001139 >>> flags = doctest.REPORT_CDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001140 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001141 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001142 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001143 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001144 Failed example:
1145 print '\n'.join('abcdefg')
Edward Loper56629292004-08-26 01:31:56 +00001146 Differences (context diff with expected followed by actual):
Tim Peters8485b562004-08-04 18:46:34 +00001147 ***************
Tim Peterse7edcb82004-08-26 05:44:27 +00001148 *** 1,7 ****
Tim Peters8485b562004-08-04 18:46:34 +00001149 a
1150 ! B
1151 c
1152 d
1153 f
1154 g
1155 - h
Tim Peterse7edcb82004-08-26 05:44:27 +00001156 --- 1,7 ----
Tim Peters8485b562004-08-04 18:46:34 +00001157 a
1158 ! b
1159 c
1160 d
1161 + e
1162 f
1163 g
Tim Peters8485b562004-08-04 18:46:34 +00001164 (1, 1)
Tim Petersc6cbab02004-08-22 19:43:28 +00001165
1166
Edward Loper71f55af2004-08-26 01:41:51 +00001167The REPORT_NDIFF flag causes failures to use the difflib.Differ algorithm
Tim Petersc6cbab02004-08-22 19:43:28 +00001168used by the popular ndiff.py utility. This does intraline difference
1169marking, as well as interline differences.
1170
1171 >>> def f(x):
1172 ... r'''
1173 ... >>> print "a b c d e f g h i j k l m"
1174 ... a b c d e f g h i j k 1 m
1175 ... '''
1176 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001177 >>> flags = doctest.REPORT_NDIFF
Tim Petersc6cbab02004-08-22 19:43:28 +00001178 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001179 ... # doctest: +ELLIPSIS
Tim Petersc6cbab02004-08-22 19:43:28 +00001180 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001181 File ..., line 3, in f
Tim Petersc6cbab02004-08-22 19:43:28 +00001182 Failed example:
1183 print "a b c d e f g h i j k l m"
1184 Differences (ndiff with -expected +actual):
1185 - a b c d e f g h i j k 1 m
1186 ? ^
1187 + a b c d e f g h i j k l m
1188 ? + ++ ^
Tim Petersc6cbab02004-08-22 19:43:28 +00001189 (1, 1)
Edward Lopera89f88d2004-08-26 02:45:51 +00001190
1191The REPORT_ONLY_FIRST_FAILURE supresses result output after the first
1192failing example:
1193
1194 >>> def f(x):
1195 ... r'''
1196 ... >>> print 1 # first success
1197 ... 1
1198 ... >>> print 2 # first failure
1199 ... 200
1200 ... >>> print 3 # second failure
1201 ... 300
1202 ... >>> print 4 # second success
1203 ... 4
1204 ... >>> print 5 # third failure
1205 ... 500
1206 ... '''
1207 >>> test = doctest.DocTestFinder().find(f)[0]
1208 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1209 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001210 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001211 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001212 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001213 Failed example:
1214 print 2 # first failure
1215 Expected:
1216 200
1217 Got:
1218 2
1219 (3, 5)
1220
1221However, output from `report_start` is not supressed:
1222
1223 >>> doctest.DocTestRunner(verbose=True, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001224 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001225 Trying:
1226 print 1 # first success
1227 Expecting:
1228 1
1229 ok
1230 Trying:
1231 print 2 # first failure
1232 Expecting:
1233 200
1234 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001235 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001236 Failed example:
1237 print 2 # first failure
1238 Expected:
1239 200
1240 Got:
1241 2
1242 (3, 5)
1243
1244For the purposes of REPORT_ONLY_FIRST_FAILURE, unexpected exceptions
1245count as failures:
1246
1247 >>> def f(x):
1248 ... r'''
1249 ... >>> print 1 # first success
1250 ... 1
1251 ... >>> raise ValueError(2) # first failure
1252 ... 200
1253 ... >>> print 3 # second failure
1254 ... 300
1255 ... >>> print 4 # second success
1256 ... 4
1257 ... >>> print 5 # third failure
1258 ... 500
1259 ... '''
1260 >>> test = doctest.DocTestFinder().find(f)[0]
1261 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1262 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1263 ... # doctest: +ELLIPSIS
1264 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001265 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001266 Failed example:
1267 raise ValueError(2) # first failure
1268 Exception raised:
1269 ...
1270 ValueError: 2
1271 (3, 5)
1272
Tim Petersc6cbab02004-08-22 19:43:28 +00001273 """
1274
Tim Peters8485b562004-08-04 18:46:34 +00001275 def option_directives(): r"""
1276Tests of `DocTestRunner`'s option directive mechanism.
1277
Edward Loper74bca7a2004-08-12 02:27:44 +00001278Option directives can be used to turn option flags on or off for a
1279single example. To turn an option on for an example, follow that
1280example with a comment of the form ``# doctest: +OPTION``:
Tim Peters8485b562004-08-04 18:46:34 +00001281
1282 >>> def f(x): r'''
Edward Loper74bca7a2004-08-12 02:27:44 +00001283 ... >>> print range(10) # should fail: no ellipsis
1284 ... [0, 1, ..., 9]
1285 ...
1286 ... >>> print range(10) # doctest: +ELLIPSIS
1287 ... [0, 1, ..., 9]
1288 ... '''
1289 >>> test = doctest.DocTestFinder().find(f)[0]
1290 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001291 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001292 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001293 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001294 Failed example:
1295 print range(10) # should fail: no ellipsis
1296 Expected:
1297 [0, 1, ..., 9]
1298 Got:
1299 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001300 (1, 2)
1301
1302To turn an option off for an example, follow that example with a
1303comment of the form ``# doctest: -OPTION``:
1304
1305 >>> def f(x): r'''
1306 ... >>> print range(10)
1307 ... [0, 1, ..., 9]
1308 ...
1309 ... >>> # should fail: no ellipsis
1310 ... >>> print range(10) # doctest: -ELLIPSIS
1311 ... [0, 1, ..., 9]
1312 ... '''
1313 >>> test = doctest.DocTestFinder().find(f)[0]
1314 >>> doctest.DocTestRunner(verbose=False,
1315 ... optionflags=doctest.ELLIPSIS).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001316 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001317 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001318 File ..., line 6, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001319 Failed example:
1320 print range(10) # doctest: -ELLIPSIS
1321 Expected:
1322 [0, 1, ..., 9]
1323 Got:
1324 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001325 (1, 2)
1326
1327Option directives affect only the example that they appear with; they
1328do not change the options for surrounding examples:
Edward Loper8e4a34b2004-08-12 02:34:27 +00001329
Edward Loper74bca7a2004-08-12 02:27:44 +00001330 >>> def f(x): r'''
Tim Peters8485b562004-08-04 18:46:34 +00001331 ... >>> print range(10) # Should fail: no ellipsis
1332 ... [0, 1, ..., 9]
1333 ...
Edward Loper74bca7a2004-08-12 02:27:44 +00001334 ... >>> print range(10) # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001335 ... [0, 1, ..., 9]
1336 ...
Tim Peters8485b562004-08-04 18:46:34 +00001337 ... >>> print range(10) # Should fail: no ellipsis
1338 ... [0, 1, ..., 9]
1339 ... '''
1340 >>> test = doctest.DocTestFinder().find(f)[0]
1341 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001342 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001343 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001344 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001345 Failed example:
1346 print range(10) # Should fail: no ellipsis
1347 Expected:
1348 [0, 1, ..., 9]
1349 Got:
1350 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001351 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001352 File ..., line 8, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001353 Failed example:
1354 print range(10) # Should fail: no ellipsis
1355 Expected:
1356 [0, 1, ..., 9]
1357 Got:
1358 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001359 (2, 3)
1360
Edward Loper74bca7a2004-08-12 02:27:44 +00001361Multiple options may be modified by a single option directive. They
1362may be separated by whitespace, commas, or both:
Tim Peters8485b562004-08-04 18:46:34 +00001363
1364 >>> def f(x): r'''
1365 ... >>> print range(10) # Should fail
1366 ... [0, 1, ..., 9]
Tim Peters8485b562004-08-04 18:46:34 +00001367 ... >>> print range(10) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001368 ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001369 ... [0, 1, ..., 9]
1370 ... '''
1371 >>> test = doctest.DocTestFinder().find(f)[0]
1372 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001373 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001374 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001375 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001376 Failed example:
1377 print range(10) # Should fail
1378 Expected:
1379 [0, 1, ..., 9]
1380 Got:
1381 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001382 (1, 2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001383
1384 >>> def f(x): r'''
1385 ... >>> print range(10) # Should fail
1386 ... [0, 1, ..., 9]
1387 ... >>> print range(10) # Should succeed
1388 ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
1389 ... [0, 1, ..., 9]
1390 ... '''
1391 >>> test = doctest.DocTestFinder().find(f)[0]
1392 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001393 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001394 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001395 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001396 Failed example:
1397 print range(10) # Should fail
1398 Expected:
1399 [0, 1, ..., 9]
1400 Got:
1401 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001402 (1, 2)
1403
1404 >>> def f(x): r'''
1405 ... >>> print range(10) # Should fail
1406 ... [0, 1, ..., 9]
1407 ... >>> print range(10) # Should succeed
1408 ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1409 ... [0, 1, ..., 9]
1410 ... '''
1411 >>> test = doctest.DocTestFinder().find(f)[0]
1412 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001413 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001414 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001415 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001416 Failed example:
1417 print range(10) # Should fail
1418 Expected:
1419 [0, 1, ..., 9]
1420 Got:
1421 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001422 (1, 2)
1423
1424The option directive may be put on the line following the source, as
1425long as a continuation prompt is used:
1426
1427 >>> def f(x): r'''
1428 ... >>> print range(10)
1429 ... ... # doctest: +ELLIPSIS
1430 ... [0, 1, ..., 9]
1431 ... '''
1432 >>> test = doctest.DocTestFinder().find(f)[0]
1433 >>> doctest.DocTestRunner(verbose=False).run(test)
1434 (0, 1)
Edward Loper8e4a34b2004-08-12 02:34:27 +00001435
Edward Loper74bca7a2004-08-12 02:27:44 +00001436For examples with multi-line source, the option directive may appear
1437at the end of any line:
1438
1439 >>> def f(x): r'''
1440 ... >>> for x in range(10): # doctest: +ELLIPSIS
1441 ... ... print x,
1442 ... 0 1 2 ... 9
1443 ...
1444 ... >>> for x in range(10):
1445 ... ... print x, # doctest: +ELLIPSIS
1446 ... 0 1 2 ... 9
1447 ... '''
1448 >>> test = doctest.DocTestFinder().find(f)[0]
1449 >>> doctest.DocTestRunner(verbose=False).run(test)
1450 (0, 2)
1451
1452If more than one line of an example with multi-line source has an
1453option directive, then they are combined:
1454
1455 >>> def f(x): r'''
1456 ... Should fail (option directive not on the last line):
1457 ... >>> for x in range(10): # doctest: +ELLIPSIS
1458 ... ... print x, # doctest: +NORMALIZE_WHITESPACE
1459 ... 0 1 2...9
1460 ... '''
1461 >>> test = doctest.DocTestFinder().find(f)[0]
1462 >>> doctest.DocTestRunner(verbose=False).run(test)
1463 (0, 1)
1464
1465It is an error to have a comment of the form ``# doctest:`` that is
1466*not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
1467``OPTION`` is an option that has been registered with
1468`register_option`:
1469
1470 >>> # Error: Option not registered
1471 >>> s = '>>> print 12 #doctest: +BADOPTION'
1472 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1473 Traceback (most recent call last):
1474 ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
1475
1476 >>> # Error: No + or - prefix
1477 >>> s = '>>> print 12 #doctest: ELLIPSIS'
1478 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1479 Traceback (most recent call last):
1480 ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
1481
1482It is an error to use an option directive on a line that contains no
1483source:
1484
1485 >>> s = '>>> # doctest: +ELLIPSIS'
1486 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1487 Traceback (most recent call last):
1488 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 +00001489"""
1490
1491def test_testsource(): r"""
1492Unit tests for `testsource()`.
1493
1494The testsource() function takes a module and a name, finds the (first)
Tim Peters19397e52004-08-06 22:02:59 +00001495test with that name in that module, and converts it to a script. The
1496example code is converted to regular Python code. The surrounding
1497words and expected output are converted to comments:
Tim Peters8485b562004-08-04 18:46:34 +00001498
1499 >>> import test.test_doctest
1500 >>> name = 'test.test_doctest.sample_func'
1501 >>> print doctest.testsource(test.test_doctest, name)
Edward Lopera5db6002004-08-12 02:41:30 +00001502 # Blah blah
Tim Peters19397e52004-08-06 22:02:59 +00001503 #
Tim Peters8485b562004-08-04 18:46:34 +00001504 print sample_func(22)
1505 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001506 ## 44
Tim Peters19397e52004-08-06 22:02:59 +00001507 #
Edward Lopera5db6002004-08-12 02:41:30 +00001508 # Yee ha!
Tim Peters8485b562004-08-04 18:46:34 +00001509
1510 >>> name = 'test.test_doctest.SampleNewStyleClass'
1511 >>> print doctest.testsource(test.test_doctest, name)
1512 print '1\n2\n3'
1513 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001514 ## 1
1515 ## 2
1516 ## 3
Tim Peters8485b562004-08-04 18:46:34 +00001517
1518 >>> name = 'test.test_doctest.SampleClass.a_classmethod'
1519 >>> print doctest.testsource(test.test_doctest, name)
1520 print SampleClass.a_classmethod(10)
1521 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001522 ## 12
Tim Peters8485b562004-08-04 18:46:34 +00001523 print SampleClass(0).a_classmethod(10)
1524 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001525 ## 12
Tim Peters8485b562004-08-04 18:46:34 +00001526"""
1527
1528def test_debug(): r"""
1529
1530Create a docstring that we want to debug:
1531
1532 >>> s = '''
1533 ... >>> x = 12
1534 ... >>> print x
1535 ... 12
1536 ... '''
1537
1538Create some fake stdin input, to feed to the debugger:
1539
1540 >>> import tempfile
Tim Peters8485b562004-08-04 18:46:34 +00001541 >>> real_stdin = sys.stdin
Edward Loper2de91ba2004-08-27 02:07:46 +00001542 >>> sys.stdin = _FakeInput(['next', 'print x', 'continue'])
Tim Peters8485b562004-08-04 18:46:34 +00001543
1544Run the debugger on the docstring, and then restore sys.stdin.
1545
Edward Loper2de91ba2004-08-27 02:07:46 +00001546 >>> try: doctest.debug_src(s)
1547 ... finally: sys.stdin = real_stdin
Tim Peters8485b562004-08-04 18:46:34 +00001548 > <string>(1)?()
Edward Loper2de91ba2004-08-27 02:07:46 +00001549 (Pdb) next
1550 12
Tim Peters8485b562004-08-04 18:46:34 +00001551 --Return--
1552 > <string>(1)?()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001553 (Pdb) print x
1554 12
1555 (Pdb) continue
Tim Peters8485b562004-08-04 18:46:34 +00001556
1557"""
1558
Jim Fulton356fd192004-08-09 11:34:47 +00001559def test_pdb_set_trace():
Edward Loper2de91ba2004-08-27 02:07:46 +00001560 """Using pdb.set_trace from a doctest
Jim Fulton356fd192004-08-09 11:34:47 +00001561
Tim Peters413ced62004-08-09 15:43:47 +00001562 You can use pdb.set_trace from a doctest. To do so, you must
Jim Fulton356fd192004-08-09 11:34:47 +00001563 retrieve the set_trace function from the pdb module at the time
Tim Peters413ced62004-08-09 15:43:47 +00001564 you use it. The doctest module changes sys.stdout so that it can
1565 capture program output. It also temporarily replaces pdb.set_trace
1566 with a version that restores stdout. This is necessary for you to
Jim Fulton356fd192004-08-09 11:34:47 +00001567 see debugger output.
1568
1569 >>> doc = '''
1570 ... >>> x = 42
1571 ... >>> import pdb; pdb.set_trace()
1572 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001573 >>> parser = doctest.DocTestParser()
1574 >>> test = parser.get_doctest(doc, {}, "foo", "foo.py", 0)
Jim Fulton356fd192004-08-09 11:34:47 +00001575 >>> runner = doctest.DocTestRunner(verbose=False)
1576
1577 To demonstrate this, we'll create a fake standard input that
1578 captures our debugger input:
1579
1580 >>> import tempfile
Edward Loper2de91ba2004-08-27 02:07:46 +00001581 >>> real_stdin = sys.stdin
1582 >>> sys.stdin = _FakeInput([
Jim Fulton356fd192004-08-09 11:34:47 +00001583 ... 'print x', # print data defined by the example
1584 ... 'continue', # stop debugging
Edward Loper2de91ba2004-08-27 02:07:46 +00001585 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001586
Edward Loper2de91ba2004-08-27 02:07:46 +00001587 >>> try: runner.run(test)
1588 ... finally: sys.stdin = real_stdin
Jim Fulton356fd192004-08-09 11:34:47 +00001589 --Return--
Edward Loper2de91ba2004-08-27 02:07:46 +00001590 > <doctest foo[1]>(1)?()->None
1591 -> import pdb; pdb.set_trace()
1592 (Pdb) print x
1593 42
1594 (Pdb) continue
1595 (0, 2)
Jim Fulton356fd192004-08-09 11:34:47 +00001596
1597 You can also put pdb.set_trace in a function called from a test:
1598
1599 >>> def calls_set_trace():
1600 ... y=2
1601 ... import pdb; pdb.set_trace()
1602
1603 >>> doc = '''
1604 ... >>> x=1
1605 ... >>> calls_set_trace()
1606 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001607 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
Edward Loper2de91ba2004-08-27 02:07:46 +00001608 >>> real_stdin = sys.stdin
1609 >>> sys.stdin = _FakeInput([
Jim Fulton356fd192004-08-09 11:34:47 +00001610 ... 'print y', # print data defined in the function
1611 ... 'up', # out of function
1612 ... 'print x', # print data defined by the example
1613 ... 'continue', # stop debugging
Edward Loper2de91ba2004-08-27 02:07:46 +00001614 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001615
Edward Loper2de91ba2004-08-27 02:07:46 +00001616 >>> try: runner.run(test)
1617 ... finally: sys.stdin = real_stdin
Jim Fulton356fd192004-08-09 11:34:47 +00001618 --Return--
Edward Loper2de91ba2004-08-27 02:07:46 +00001619 > <doctest test.test_doctest.test_pdb_set_trace[8]>(3)calls_set_trace()->None
1620 -> import pdb; pdb.set_trace()
1621 (Pdb) print y
1622 2
1623 (Pdb) up
1624 > <doctest foo[1]>(1)?()
1625 -> calls_set_trace()
1626 (Pdb) print x
1627 1
1628 (Pdb) continue
1629 (0, 2)
1630
1631 During interactive debugging, source code is shown, even for
1632 doctest examples:
1633
1634 >>> doc = '''
1635 ... >>> def f(x):
1636 ... ... g(x*2)
1637 ... >>> def g(x):
1638 ... ... print x+3
1639 ... ... import pdb; pdb.set_trace()
1640 ... >>> f(3)
1641 ... '''
1642 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
1643 >>> real_stdin = sys.stdin
1644 >>> sys.stdin = _FakeInput([
1645 ... 'list', # list source from example 2
1646 ... 'next', # return from g()
1647 ... 'list', # list source from example 1
1648 ... 'next', # return from f()
1649 ... 'list', # list source from example 3
1650 ... 'continue', # stop debugging
1651 ... ''])
1652 >>> try: runner.run(test)
1653 ... finally: sys.stdin = real_stdin
1654 ... # doctest: +NORMALIZE_WHITESPACE
1655 --Return--
1656 > <doctest foo[1]>(3)g()->None
1657 -> import pdb; pdb.set_trace()
1658 (Pdb) list
1659 1 def g(x):
1660 2 print x+3
1661 3 -> import pdb; pdb.set_trace()
1662 [EOF]
1663 (Pdb) next
1664 --Return--
1665 > <doctest foo[0]>(2)f()->None
1666 -> g(x*2)
1667 (Pdb) list
1668 1 def f(x):
1669 2 -> g(x*2)
1670 [EOF]
1671 (Pdb) next
1672 --Return--
1673 > <doctest foo[2]>(1)?()->None
1674 -> f(3)
1675 (Pdb) list
1676 1 -> f(3)
1677 [EOF]
1678 (Pdb) continue
1679 **********************************************************************
1680 File "foo.py", line 7, in foo
1681 Failed example:
1682 f(3)
1683 Expected nothing
1684 Got:
1685 9
1686 (1, 3)
Jim Fulton356fd192004-08-09 11:34:47 +00001687 """
1688
Tim Peters19397e52004-08-06 22:02:59 +00001689def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +00001690 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +00001691
1692 We create a Suite by providing a module. A module can be provided
1693 by passing a module object:
1694
1695 >>> import unittest
1696 >>> import test.sample_doctest
1697 >>> suite = doctest.DocTestSuite(test.sample_doctest)
1698 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001699 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001700
1701 We can also supply the module by name:
1702
1703 >>> suite = doctest.DocTestSuite('test.sample_doctest')
1704 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001705 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001706
1707 We can use the current module:
1708
1709 >>> suite = test.sample_doctest.test_suite()
1710 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001711 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001712
1713 We can supply global variables. If we pass globs, they will be
1714 used instead of the module globals. Here we'll pass an empty
1715 globals, triggering an extra error:
1716
1717 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
1718 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001719 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001720
1721 Alternatively, we can provide extra globals. Here we'll make an
1722 error go away by providing an extra global variable:
1723
1724 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1725 ... extraglobs={'y': 1})
1726 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001727 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001728
1729 You can pass option flags. Here we'll cause an extra error
1730 by disabling the blank-line feature:
1731
1732 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00001733 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00001734 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001735 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001736
Tim Peters1e277ee2004-08-07 05:37:52 +00001737 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00001738
Jim Fultonf54bad42004-08-28 14:57:56 +00001739 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00001740 ... import test.test_doctest
1741 ... test.test_doctest.sillySetup = True
1742
Jim Fultonf54bad42004-08-28 14:57:56 +00001743 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00001744 ... import test.test_doctest
1745 ... del test.test_doctest.sillySetup
1746
1747 Here, we installed a silly variable that the test expects:
1748
1749 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1750 ... setUp=setUp, tearDown=tearDown)
1751 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001752 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001753
1754 But the tearDown restores sanity:
1755
1756 >>> import test.test_doctest
1757 >>> test.test_doctest.sillySetup
1758 Traceback (most recent call last):
1759 ...
1760 AttributeError: 'module' object has no attribute 'sillySetup'
1761
Jim Fultonf54bad42004-08-28 14:57:56 +00001762 The setUp and tearDown funtions are passed test objects. Here
1763 we'll use the setUp function to supply the missing variable y:
1764
1765 >>> def setUp(test):
1766 ... test.globs['y'] = 1
1767
1768 >>> suite = doctest.DocTestSuite('test.sample_doctest', setUp=setUp)
1769 >>> suite.run(unittest.TestResult())
1770 <unittest.TestResult run=9 errors=0 failures=3>
1771
1772 Here, we didn't need to use a tearDown function because we
1773 modified the test globals, which are a copy of the
1774 sample_doctest module dictionary. The test globals are
1775 automatically cleared for us after a test.
1776
Tim Peters19397e52004-08-06 22:02:59 +00001777 Finally, you can provide an alternate test finder. Here we'll
Tim Peters1e277ee2004-08-07 05:37:52 +00001778 use a custom test_finder to to run just the test named bar.
1779 However, the test in the module docstring, and the two tests
1780 in the module __test__ dict, aren't filtered, so we actually
1781 run three tests besides bar's. The filtering mechanisms are
1782 poorly conceived, and will go away someday.
Tim Peters19397e52004-08-06 22:02:59 +00001783
1784 >>> finder = doctest.DocTestFinder(
Tim Petersf727c6c2004-08-08 01:48:59 +00001785 ... _namefilter=lambda prefix, base: base!='bar')
Tim Peters19397e52004-08-06 22:02:59 +00001786 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1787 ... test_finder=finder)
1788 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001789 <unittest.TestResult run=4 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00001790 """
1791
1792def test_DocFileSuite():
1793 """We can test tests found in text files using a DocFileSuite.
1794
1795 We create a suite by providing the names of one or more text
1796 files that include examples:
1797
1798 >>> import unittest
1799 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1800 ... 'test_doctest2.txt')
1801 >>> suite.run(unittest.TestResult())
1802 <unittest.TestResult run=2 errors=0 failures=2>
1803
1804 The test files are looked for in the directory containing the
1805 calling module. A package keyword argument can be provided to
1806 specify a different relative location.
1807
1808 >>> import unittest
1809 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1810 ... 'test_doctest2.txt',
1811 ... package='test')
1812 >>> suite.run(unittest.TestResult())
1813 <unittest.TestResult run=2 errors=0 failures=2>
1814
Edward Loper0273f5b2004-09-18 20:27:04 +00001815 '/' should be used as a path separator. It will be converted
1816 to a native separator at run time:
Tim Peters19397e52004-08-06 22:02:59 +00001817
1818 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
1819 >>> suite.run(unittest.TestResult())
1820 <unittest.TestResult run=1 errors=0 failures=1>
1821
Edward Loper0273f5b2004-09-18 20:27:04 +00001822 If DocFileSuite is used from an interactive session, then files
1823 are resolved relative to the directory of sys.argv[0]:
1824
1825 >>> import new, os.path, test.test_doctest
1826 >>> save_argv = sys.argv
1827 >>> sys.argv = [test.test_doctest.__file__]
1828 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1829 ... package=new.module('__main__'))
1830 >>> sys.argv = save_argv
1831
1832 Absolute paths may also be used; they should use the native
1833 path separator (*not* '/').
1834
1835 >>> # Get the absolute path of the test package.
1836 >>> test_doctest_path = os.path.abspath(test.test_doctest.__file__)
1837 >>> test_pkg_path = os.path.split(test_doctest_path)[0]
1838
1839 >>> # Use it to find the absolute path of test_doctest.txt.
1840 >>> test_file = os.path.join(test_pkg_path, 'test_doctest.txt')
1841
1842 >>> suite = doctest.DocFileSuite(test_file)
1843 >>> suite.run(unittest.TestResult())
1844 <unittest.TestResult run=1 errors=0 failures=1>
1845
Tim Peters19397e52004-08-06 22:02:59 +00001846 You can specify initial global variables:
1847
1848 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1849 ... 'test_doctest2.txt',
1850 ... globs={'favorite_color': 'blue'})
1851 >>> suite.run(unittest.TestResult())
1852 <unittest.TestResult run=2 errors=0 failures=1>
1853
1854 In this case, we supplied a missing favorite color. You can
1855 provide doctest options:
1856
1857 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1858 ... 'test_doctest2.txt',
1859 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
1860 ... globs={'favorite_color': 'blue'})
1861 >>> suite.run(unittest.TestResult())
1862 <unittest.TestResult run=2 errors=0 failures=2>
1863
1864 And, you can provide setUp and tearDown functions:
1865
1866 You can supply setUp and teatDoen functions:
1867
Jim Fultonf54bad42004-08-28 14:57:56 +00001868 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00001869 ... import test.test_doctest
1870 ... test.test_doctest.sillySetup = True
1871
Jim Fultonf54bad42004-08-28 14:57:56 +00001872 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00001873 ... import test.test_doctest
1874 ... del test.test_doctest.sillySetup
1875
1876 Here, we installed a silly variable that the test expects:
1877
1878 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1879 ... 'test_doctest2.txt',
1880 ... setUp=setUp, tearDown=tearDown)
1881 >>> suite.run(unittest.TestResult())
1882 <unittest.TestResult run=2 errors=0 failures=1>
1883
1884 But the tearDown restores sanity:
1885
1886 >>> import test.test_doctest
1887 >>> test.test_doctest.sillySetup
1888 Traceback (most recent call last):
1889 ...
1890 AttributeError: 'module' object has no attribute 'sillySetup'
1891
Jim Fultonf54bad42004-08-28 14:57:56 +00001892 The setUp and tearDown funtions are passed test objects.
1893 Here, we'll use a setUp function to set the favorite color in
1894 test_doctest.txt:
1895
1896 >>> def setUp(test):
1897 ... test.globs['favorite_color'] = 'blue'
1898
1899 >>> suite = doctest.DocFileSuite('test_doctest.txt', setUp=setUp)
1900 >>> suite.run(unittest.TestResult())
1901 <unittest.TestResult run=1 errors=0 failures=0>
1902
1903 Here, we didn't need to use a tearDown function because we
1904 modified the test globals. The test globals are
1905 automatically cleared for us after a test.
Tim Petersdf7a2082004-08-29 00:38:17 +00001906
Jim Fultonf54bad42004-08-28 14:57:56 +00001907 """
Tim Peters19397e52004-08-06 22:02:59 +00001908
Jim Fulton07a349c2004-08-22 14:10:00 +00001909def test_trailing_space_in_test():
1910 """
Tim Petersa7def722004-08-23 22:13:22 +00001911 Trailing spaces in expected output are significant:
Tim Petersc6cbab02004-08-22 19:43:28 +00001912
Jim Fulton07a349c2004-08-22 14:10:00 +00001913 >>> x, y = 'foo', ''
1914 >>> print x, y
1915 foo \n
1916 """
Tim Peters19397e52004-08-06 22:02:59 +00001917
Jim Fultonf54bad42004-08-28 14:57:56 +00001918
1919def test_unittest_reportflags():
1920 """Default unittest reporting flags can be set to control reporting
1921
1922 Here, we'll set the REPORT_ONLY_FIRST_FAILURE option so we see
1923 only the first failure of each test. First, we'll look at the
1924 output without the flag. The file test_doctest.txt file has two
1925 tests. They both fail if blank lines are disabled:
1926
1927 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1928 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
1929 >>> import unittest
1930 >>> result = suite.run(unittest.TestResult())
1931 >>> print result.failures[0][1] # doctest: +ELLIPSIS
1932 Traceback ...
1933 Failed example:
1934 favorite_color
1935 ...
1936 Failed example:
1937 if 1:
1938 ...
1939
1940 Note that we see both failures displayed.
1941
1942 >>> old = doctest.set_unittest_reportflags(
1943 ... doctest.REPORT_ONLY_FIRST_FAILURE)
1944
1945 Now, when we run the test:
1946
1947 >>> result = suite.run(unittest.TestResult())
1948 >>> print result.failures[0][1] # doctest: +ELLIPSIS
1949 Traceback ...
1950 Failed example:
1951 favorite_color
1952 Exception raised:
1953 ...
1954 NameError: name 'favorite_color' is not defined
1955 <BLANKLINE>
1956 <BLANKLINE>
Tim Petersdf7a2082004-08-29 00:38:17 +00001957
Jim Fultonf54bad42004-08-28 14:57:56 +00001958 We get only the first failure.
1959
1960 If we give any reporting options when we set up the tests,
1961 however:
1962
1963 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1964 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE | doctest.REPORT_NDIFF)
1965
1966 Then the default eporting options are ignored:
1967
1968 >>> result = suite.run(unittest.TestResult())
1969 >>> print result.failures[0][1] # doctest: +ELLIPSIS
1970 Traceback ...
1971 Failed example:
1972 favorite_color
1973 ...
1974 Failed example:
1975 if 1:
1976 print 'a'
1977 print
1978 print 'b'
1979 Differences (ndiff with -expected +actual):
1980 a
1981 - <BLANKLINE>
1982 +
1983 b
1984 <BLANKLINE>
1985 <BLANKLINE>
1986
1987
1988 Test runners can restore the formatting flags after they run:
1989
1990 >>> ignored = doctest.set_unittest_reportflags(old)
1991
1992 """
1993
Tim Petersa7def722004-08-23 22:13:22 +00001994# old_test1, ... used to live in doctest.py, but cluttered it. Note
1995# that these use the deprecated doctest.Tester, so should go away (or
1996# be rewritten) someday.
1997
1998# Ignore all warnings about the use of class Tester in this module.
1999# Note that the name of this module may differ depending on how it's
2000# imported, so the use of __name__ is important.
2001warnings.filterwarnings("ignore", "class Tester", DeprecationWarning,
2002 __name__, 0)
2003
2004def old_test1(): r"""
2005>>> from doctest import Tester
2006>>> t = Tester(globs={'x': 42}, verbose=0)
2007>>> t.runstring(r'''
2008... >>> x = x * 2
2009... >>> print x
2010... 42
2011... ''', 'XYZ')
2012**********************************************************************
2013Line 3, in XYZ
2014Failed example:
2015 print x
2016Expected:
2017 42
2018Got:
2019 84
2020(1, 2)
2021>>> t.runstring(">>> x = x * 2\n>>> print x\n84\n", 'example2')
2022(0, 2)
2023>>> t.summarize()
2024**********************************************************************
20251 items had failures:
2026 1 of 2 in XYZ
2027***Test Failed*** 1 failures.
2028(1, 4)
2029>>> t.summarize(verbose=1)
20301 items passed all tests:
2031 2 tests in example2
2032**********************************************************************
20331 items had failures:
2034 1 of 2 in XYZ
20354 tests in 2 items.
20363 passed and 1 failed.
2037***Test Failed*** 1 failures.
2038(1, 4)
2039"""
2040
2041def old_test2(): r"""
2042 >>> from doctest import Tester
2043 >>> t = Tester(globs={}, verbose=1)
2044 >>> test = r'''
2045 ... # just an example
2046 ... >>> x = 1 + 2
2047 ... >>> x
2048 ... 3
2049 ... '''
2050 >>> t.runstring(test, "Example")
2051 Running string Example
Edward Loperaacf0832004-08-26 01:19:50 +00002052 Trying:
2053 x = 1 + 2
2054 Expecting nothing
Tim Petersa7def722004-08-23 22:13:22 +00002055 ok
Edward Loperaacf0832004-08-26 01:19:50 +00002056 Trying:
2057 x
2058 Expecting:
2059 3
Tim Petersa7def722004-08-23 22:13:22 +00002060 ok
2061 0 of 2 examples failed in string Example
2062 (0, 2)
2063"""
2064
2065def old_test3(): r"""
2066 >>> from doctest import Tester
2067 >>> t = Tester(globs={}, verbose=0)
2068 >>> def _f():
2069 ... '''Trivial docstring example.
2070 ... >>> assert 2 == 2
2071 ... '''
2072 ... return 32
2073 ...
2074 >>> t.rundoc(_f) # expect 0 failures in 1 example
2075 (0, 1)
2076"""
2077
2078def old_test4(): """
2079 >>> import new
2080 >>> m1 = new.module('_m1')
2081 >>> m2 = new.module('_m2')
2082 >>> test_data = \"""
2083 ... def _f():
2084 ... '''>>> assert 1 == 1
2085 ... '''
2086 ... def g():
2087 ... '''>>> assert 2 != 1
2088 ... '''
2089 ... class H:
2090 ... '''>>> assert 2 > 1
2091 ... '''
2092 ... def bar(self):
2093 ... '''>>> assert 1 < 2
2094 ... '''
2095 ... \"""
2096 >>> exec test_data in m1.__dict__
2097 >>> exec test_data in m2.__dict__
2098 >>> m1.__dict__.update({"f2": m2._f, "g2": m2.g, "h2": m2.H})
2099
2100 Tests that objects outside m1 are excluded:
2101
2102 >>> from doctest import Tester
2103 >>> t = Tester(globs={}, verbose=0)
2104 >>> t.rundict(m1.__dict__, "rundict_test", m1) # f2 and g2 and h2 skipped
2105 (0, 4)
2106
2107 Once more, not excluding stuff outside m1:
2108
2109 >>> t = Tester(globs={}, verbose=0)
2110 >>> t.rundict(m1.__dict__, "rundict_test_pvt") # None are skipped.
2111 (0, 8)
2112
2113 The exclusion of objects from outside the designated module is
2114 meant to be invoked automagically by testmod.
2115
2116 >>> doctest.testmod(m1, verbose=False)
2117 (0, 4)
2118"""
2119
Tim Peters8485b562004-08-04 18:46:34 +00002120######################################################################
2121## Main
2122######################################################################
2123
2124def test_main():
2125 # Check the doctest cases in doctest itself:
2126 test_support.run_doctest(doctest, verbosity=True)
2127 # Check the doctest cases defined here:
2128 from test import test_doctest
2129 test_support.run_doctest(test_doctest, verbosity=True)
2130
2131import trace, sys, re, StringIO
2132def test_coverage(coverdir):
2133 tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
2134 trace=0, count=1)
2135 tracer.run('reload(doctest); test_main()')
2136 r = tracer.results()
2137 print 'Writing coverage results...'
2138 r.write_results(show_missing=True, summary=True,
2139 coverdir=coverdir)
2140
2141if __name__ == '__main__':
2142 if '-c' in sys.argv:
2143 test_coverage('/tmp/doctest.cover')
2144 else:
2145 test_main()