blob: 2b287ed19620f6844ade6982591d7a0d89df8292 [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
Tim Peters8485b562004-08-04 18:46:34 +0000376If an object has no docstring, then a test is not created for it:
377
378 >>> def no_docstring(v):
379 ... pass
380 >>> finder.find(no_docstring)
381 []
382
383If the function has a docstring with no examples, then a test with no
384examples is returned. (This lets `DocTestRunner` collect statistics
385about which functions have no tests -- but is that useful? And should
386an empty test also be created when there's no docstring?)
387
388 >>> def no_examples(v):
389 ... ''' no doctest examples '''
Tim Peters17b56372004-09-11 17:33:27 +0000390 >>> finder.find(no_examples) # doctest: +ELLIPSIS
391 [<DocTest no_examples from ...:1 (no examples)>]
Tim Peters8485b562004-08-04 18:46:34 +0000392
393Finding Tests in Classes
394~~~~~~~~~~~~~~~~~~~~~~~~
395For a class, DocTestFinder will create a test for the class's
396docstring, and will recursively explore its contents, including
397methods, classmethods, staticmethods, properties, and nested classes.
398
399 >>> finder = doctest.DocTestFinder()
400 >>> tests = finder.find(SampleClass)
401 >>> tests.sort()
402 >>> for t in tests:
403 ... print '%2s %s' % (len(t.examples), t.name)
404 1 SampleClass
405 3 SampleClass.NestedClass
406 1 SampleClass.NestedClass.__init__
407 1 SampleClass.__init__
408 2 SampleClass.a_classmethod
409 1 SampleClass.a_property
410 1 SampleClass.a_staticmethod
411 1 SampleClass.double
412 1 SampleClass.get
413
414New-style classes are also supported:
415
416 >>> tests = finder.find(SampleNewStyleClass)
417 >>> tests.sort()
418 >>> for t in tests:
419 ... print '%2s %s' % (len(t.examples), t.name)
420 1 SampleNewStyleClass
421 1 SampleNewStyleClass.__init__
422 1 SampleNewStyleClass.double
423 1 SampleNewStyleClass.get
424
425Finding Tests in Modules
426~~~~~~~~~~~~~~~~~~~~~~~~
427For a module, DocTestFinder will create a test for the class's
428docstring, and will recursively explore its contents, including
429functions, classes, and the `__test__` dictionary, if it exists:
430
431 >>> # A module
432 >>> import new
433 >>> m = new.module('some_module')
434 >>> def triple(val):
435 ... '''
436 ... >>> print tripple(11)
437 ... 33
438 ... '''
439 ... return val*3
440 >>> m.__dict__.update({
441 ... 'sample_func': sample_func,
442 ... 'SampleClass': SampleClass,
443 ... '__doc__': '''
444 ... Module docstring.
445 ... >>> print 'module'
446 ... module
447 ... ''',
448 ... '__test__': {
449 ... 'd': '>>> print 6\n6\n>>> print 7\n7\n',
450 ... 'c': triple}})
451
452 >>> finder = doctest.DocTestFinder()
453 >>> # Use module=test.test_doctest, to prevent doctest from
454 >>> # ignoring the objects since they weren't defined in m.
455 >>> import test.test_doctest
456 >>> tests = finder.find(m, module=test.test_doctest)
457 >>> tests.sort()
458 >>> for t in tests:
459 ... print '%2s %s' % (len(t.examples), t.name)
460 1 some_module
461 1 some_module.SampleClass
462 3 some_module.SampleClass.NestedClass
463 1 some_module.SampleClass.NestedClass.__init__
464 1 some_module.SampleClass.__init__
465 2 some_module.SampleClass.a_classmethod
466 1 some_module.SampleClass.a_property
467 1 some_module.SampleClass.a_staticmethod
468 1 some_module.SampleClass.double
469 1 some_module.SampleClass.get
470 1 some_module.c
471 2 some_module.d
472 1 some_module.sample_func
473
474Duplicate Removal
475~~~~~~~~~~~~~~~~~
476If a single object is listed twice (under different names), then tests
477will only be generated for it once:
478
Tim Petersf3f57472004-08-08 06:11:48 +0000479 >>> from test import doctest_aliases
480 >>> tests = finder.find(doctest_aliases)
Tim Peters8485b562004-08-04 18:46:34 +0000481 >>> tests.sort()
482 >>> print len(tests)
483 2
484 >>> print tests[0].name
Tim Petersf3f57472004-08-08 06:11:48 +0000485 test.doctest_aliases.TwoNames
486
487 TwoNames.f and TwoNames.g are bound to the same object.
488 We can't guess which will be found in doctest's traversal of
489 TwoNames.__dict__ first, so we have to allow for either.
490
491 >>> tests[1].name.split('.')[-1] in ['f', 'g']
Tim Peters8485b562004-08-04 18:46:34 +0000492 True
493
494Filter Functions
495~~~~~~~~~~~~~~~~
Tim Petersf727c6c2004-08-08 01:48:59 +0000496A filter function can be used to restrict which objects get examined,
497but this is temporary, undocumented internal support for testmod's
498deprecated isprivate gimmick.
Tim Peters8485b562004-08-04 18:46:34 +0000499
500 >>> def namefilter(prefix, base):
501 ... return base.startswith('a_')
Tim Petersf727c6c2004-08-08 01:48:59 +0000502 >>> tests = doctest.DocTestFinder(_namefilter=namefilter).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000503 >>> tests.sort()
504 >>> for t in tests:
505 ... print '%2s %s' % (len(t.examples), t.name)
506 1 SampleClass
507 3 SampleClass.NestedClass
508 1 SampleClass.NestedClass.__init__
509 1 SampleClass.__init__
510 1 SampleClass.double
511 1 SampleClass.get
512
Tim Peters8485b562004-08-04 18:46:34 +0000513If a given object is filtered out, then none of the objects that it
514contains will be added either:
515
516 >>> def namefilter(prefix, base):
517 ... return base == 'NestedClass'
Tim Petersf727c6c2004-08-08 01:48:59 +0000518 >>> tests = doctest.DocTestFinder(_namefilter=namefilter).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000519 >>> tests.sort()
520 >>> for t in tests:
521 ... print '%2s %s' % (len(t.examples), t.name)
522 1 SampleClass
523 1 SampleClass.__init__
524 2 SampleClass.a_classmethod
525 1 SampleClass.a_property
526 1 SampleClass.a_staticmethod
527 1 SampleClass.double
528 1 SampleClass.get
529
Tim Petersf727c6c2004-08-08 01:48:59 +0000530The filter function apply to contained objects, and *not* to the
Tim Peters8485b562004-08-04 18:46:34 +0000531object explicitly passed to DocTestFinder:
532
533 >>> def namefilter(prefix, base):
534 ... return base == 'SampleClass'
Tim Petersf727c6c2004-08-08 01:48:59 +0000535 >>> tests = doctest.DocTestFinder(_namefilter=namefilter).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000536 >>> len(tests)
537 9
538
539Turning off Recursion
540~~~~~~~~~~~~~~~~~~~~~
541DocTestFinder can be told not to look for tests in contained objects
542using the `recurse` flag:
543
544 >>> tests = doctest.DocTestFinder(recurse=False).find(SampleClass)
545 >>> tests.sort()
546 >>> for t in tests:
547 ... print '%2s %s' % (len(t.examples), t.name)
548 1 SampleClass
Edward Loperb51b2342004-08-17 16:37:12 +0000549
550Line numbers
551~~~~~~~~~~~~
552DocTestFinder finds the line number of each example:
553
554 >>> def f(x):
555 ... '''
556 ... >>> x = 12
557 ...
558 ... some text
559 ...
560 ... >>> # examples are not created for comments & bare prompts.
561 ... >>>
562 ... ...
563 ...
564 ... >>> for x in range(10):
565 ... ... print x,
566 ... 0 1 2 3 4 5 6 7 8 9
567 ... >>> x/2
568 ... 6
569 ... '''
570 >>> test = doctest.DocTestFinder().find(f)[0]
571 >>> [e.lineno for e in test.examples]
572 [1, 9, 12]
Tim Peters8485b562004-08-04 18:46:34 +0000573"""
574
Edward Loper00f8da72004-08-26 18:05:07 +0000575def test_DocTestParser(): r"""
576Unit tests for the `DocTestParser` class.
577
578DocTestParser is used to parse docstrings containing doctest examples.
579
580The `parse` method divides a docstring into examples and intervening
581text:
582
583 >>> s = '''
584 ... >>> x, y = 2, 3 # no output expected
585 ... >>> if 1:
586 ... ... print x
587 ... ... print y
588 ... 2
589 ... 3
590 ...
591 ... Some text.
592 ... >>> x+y
593 ... 5
594 ... '''
595 >>> parser = doctest.DocTestParser()
596 >>> for piece in parser.parse(s):
597 ... if isinstance(piece, doctest.Example):
598 ... print 'Example:', (piece.source, piece.want, piece.lineno)
599 ... else:
600 ... print ' Text:', `piece`
601 Text: '\n'
602 Example: ('x, y = 2, 3 # no output expected\n', '', 1)
603 Text: ''
604 Example: ('if 1:\n print x\n print y\n', '2\n3\n', 2)
605 Text: '\nSome text.\n'
606 Example: ('x+y\n', '5\n', 9)
607 Text: ''
608
609The `get_examples` method returns just the examples:
610
611 >>> for piece in parser.get_examples(s):
612 ... print (piece.source, piece.want, piece.lineno)
613 ('x, y = 2, 3 # no output expected\n', '', 1)
614 ('if 1:\n print x\n print y\n', '2\n3\n', 2)
615 ('x+y\n', '5\n', 9)
616
617The `get_doctest` method creates a Test from the examples, along with the
618given arguments:
619
620 >>> test = parser.get_doctest(s, {}, 'name', 'filename', lineno=5)
621 >>> (test.name, test.filename, test.lineno)
622 ('name', 'filename', 5)
623 >>> for piece in test.examples:
624 ... print (piece.source, piece.want, piece.lineno)
625 ('x, y = 2, 3 # no output expected\n', '', 1)
626 ('if 1:\n print x\n print y\n', '2\n3\n', 2)
627 ('x+y\n', '5\n', 9)
628"""
629
Tim Peters8485b562004-08-04 18:46:34 +0000630class test_DocTestRunner:
631 def basics(): r"""
632Unit tests for the `DocTestRunner` class.
633
634DocTestRunner is used to run DocTest test cases, and to accumulate
635statistics. Here's a simple DocTest case we can use:
636
637 >>> def f(x):
638 ... '''
639 ... >>> x = 12
640 ... >>> print x
641 ... 12
642 ... >>> x/2
643 ... 6
644 ... '''
645 >>> test = doctest.DocTestFinder().find(f)[0]
646
647The main DocTestRunner interface is the `run` method, which runs a
648given DocTest case in a given namespace (globs). It returns a tuple
649`(f,t)`, where `f` is the number of failed tests and `t` is the number
650of tried tests.
651
652 >>> doctest.DocTestRunner(verbose=False).run(test)
653 (0, 3)
654
655If any example produces incorrect output, then the test runner reports
656the failure and proceeds to the next example:
657
658 >>> def f(x):
659 ... '''
660 ... >>> x = 12
661 ... >>> print x
662 ... 14
663 ... >>> x/2
664 ... 6
665 ... '''
666 >>> test = doctest.DocTestFinder().find(f)[0]
667 >>> doctest.DocTestRunner(verbose=True).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000668 ... # doctest: +ELLIPSIS
Edward Loperaacf0832004-08-26 01:19:50 +0000669 Trying:
670 x = 12
671 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000672 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000673 Trying:
674 print x
675 Expecting:
676 14
Tim Peters8485b562004-08-04 18:46:34 +0000677 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000678 File ..., line 4, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000679 Failed example:
680 print x
681 Expected:
682 14
683 Got:
684 12
Edward Loperaacf0832004-08-26 01:19:50 +0000685 Trying:
686 x/2
687 Expecting:
688 6
Tim Peters8485b562004-08-04 18:46:34 +0000689 ok
690 (1, 3)
691"""
692 def verbose_flag(): r"""
693The `verbose` flag makes the test runner generate more detailed
694output:
695
696 >>> def f(x):
697 ... '''
698 ... >>> x = 12
699 ... >>> print x
700 ... 12
701 ... >>> x/2
702 ... 6
703 ... '''
704 >>> test = doctest.DocTestFinder().find(f)[0]
705
706 >>> doctest.DocTestRunner(verbose=True).run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000707 Trying:
708 x = 12
709 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000710 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000711 Trying:
712 print x
713 Expecting:
714 12
Tim Peters8485b562004-08-04 18:46:34 +0000715 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000716 Trying:
717 x/2
718 Expecting:
719 6
Tim Peters8485b562004-08-04 18:46:34 +0000720 ok
721 (0, 3)
722
723If the `verbose` flag is unspecified, then the output will be verbose
724iff `-v` appears in sys.argv:
725
726 >>> # Save the real sys.argv list.
727 >>> old_argv = sys.argv
728
729 >>> # If -v does not appear in sys.argv, then output isn't verbose.
730 >>> sys.argv = ['test']
731 >>> doctest.DocTestRunner().run(test)
732 (0, 3)
733
734 >>> # If -v does appear in sys.argv, then output is verbose.
735 >>> sys.argv = ['test', '-v']
736 >>> doctest.DocTestRunner().run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000737 Trying:
738 x = 12
739 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000740 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000741 Trying:
742 print x
743 Expecting:
744 12
Tim Peters8485b562004-08-04 18:46:34 +0000745 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000746 Trying:
747 x/2
748 Expecting:
749 6
Tim Peters8485b562004-08-04 18:46:34 +0000750 ok
751 (0, 3)
752
753 >>> # Restore sys.argv
754 >>> sys.argv = old_argv
755
756In the remaining examples, the test runner's verbosity will be
757explicitly set, to ensure that the test behavior is consistent.
758 """
759 def exceptions(): r"""
760Tests of `DocTestRunner`'s exception handling.
761
762An expected exception is specified with a traceback message. The
763lines between the first line and the type/value may be omitted or
764replaced with any other string:
765
766 >>> def f(x):
767 ... '''
768 ... >>> x = 12
769 ... >>> print x/0
770 ... Traceback (most recent call last):
771 ... ZeroDivisionError: integer division or modulo by zero
772 ... '''
773 >>> test = doctest.DocTestFinder().find(f)[0]
774 >>> doctest.DocTestRunner(verbose=False).run(test)
775 (0, 2)
776
Edward Loper19b19582004-08-25 23:07:03 +0000777An example may not generate output before it raises an exception; if
778it does, then the traceback message will not be recognized as
779signaling an expected exception, so the example will be reported as an
780unexpected exception:
Tim Peters8485b562004-08-04 18:46:34 +0000781
782 >>> def f(x):
783 ... '''
784 ... >>> x = 12
785 ... >>> print 'pre-exception output', x/0
786 ... pre-exception output
787 ... Traceback (most recent call last):
788 ... ZeroDivisionError: integer division or modulo by zero
789 ... '''
790 >>> test = doctest.DocTestFinder().find(f)[0]
791 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper19b19582004-08-25 23:07:03 +0000792 ... # doctest: +ELLIPSIS
793 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000794 File ..., line 4, in f
Edward Loper19b19582004-08-25 23:07:03 +0000795 Failed example:
796 print 'pre-exception output', x/0
797 Exception raised:
798 ...
799 ZeroDivisionError: integer division or modulo by zero
800 (1, 2)
Tim Peters8485b562004-08-04 18:46:34 +0000801
802Exception messages may contain newlines:
803
804 >>> def f(x):
805 ... r'''
806 ... >>> raise ValueError, 'multi\nline\nmessage'
807 ... Traceback (most recent call last):
808 ... ValueError: multi
809 ... line
810 ... message
811 ... '''
812 >>> test = doctest.DocTestFinder().find(f)[0]
813 >>> doctest.DocTestRunner(verbose=False).run(test)
814 (0, 1)
815
816If an exception is expected, but an exception with the wrong type or
817message is raised, then it is reported as a failure:
818
819 >>> def f(x):
820 ... r'''
821 ... >>> raise ValueError, 'message'
822 ... Traceback (most recent call last):
823 ... ValueError: wrong message
824 ... '''
825 >>> test = doctest.DocTestFinder().find(f)[0]
826 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000827 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000828 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000829 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000830 Failed example:
831 raise ValueError, 'message'
Tim Peters8485b562004-08-04 18:46:34 +0000832 Expected:
833 Traceback (most recent call last):
834 ValueError: wrong message
835 Got:
836 Traceback (most recent call last):
Edward Loper8e4a34b2004-08-12 02:34:27 +0000837 ...
Tim Peters8485b562004-08-04 18:46:34 +0000838 ValueError: message
839 (1, 1)
840
Tim Peters1fbf9c52004-09-04 17:21:02 +0000841However, IGNORE_EXCEPTION_DETAIL can be used to allow a mismatch in the
842detail:
843
844 >>> def f(x):
845 ... r'''
846 ... >>> raise ValueError, 'message' #doctest: +IGNORE_EXCEPTION_DETAIL
847 ... Traceback (most recent call last):
848 ... ValueError: wrong message
849 ... '''
850 >>> test = doctest.DocTestFinder().find(f)[0]
851 >>> doctest.DocTestRunner(verbose=False).run(test)
852 (0, 1)
853
854But IGNORE_EXCEPTION_DETAIL does not allow a mismatch in the exception type:
855
856 >>> def f(x):
857 ... r'''
858 ... >>> raise ValueError, 'message' #doctest: +IGNORE_EXCEPTION_DETAIL
859 ... Traceback (most recent call last):
860 ... TypeError: wrong type
861 ... '''
862 >>> test = doctest.DocTestFinder().find(f)[0]
863 >>> doctest.DocTestRunner(verbose=False).run(test)
864 ... # doctest: +ELLIPSIS
865 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000866 File ..., line 3, in f
Tim Peters1fbf9c52004-09-04 17:21:02 +0000867 Failed example:
868 raise ValueError, 'message' #doctest: +IGNORE_EXCEPTION_DETAIL
869 Expected:
870 Traceback (most recent call last):
871 TypeError: wrong type
872 Got:
873 Traceback (most recent call last):
874 ...
875 ValueError: message
876 (1, 1)
877
Tim Peters8485b562004-08-04 18:46:34 +0000878If an exception is raised but not expected, then it is reported as an
879unexpected exception:
880
Tim Peters8485b562004-08-04 18:46:34 +0000881 >>> def f(x):
882 ... r'''
883 ... >>> 1/0
884 ... 0
885 ... '''
886 >>> test = doctest.DocTestFinder().find(f)[0]
887 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper74bca7a2004-08-12 02:27:44 +0000888 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000889 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000890 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000891 Failed example:
892 1/0
Tim Peters8485b562004-08-04 18:46:34 +0000893 Exception raised:
894 Traceback (most recent call last):
Jim Fulton07a349c2004-08-22 14:10:00 +0000895 ...
Tim Peters8485b562004-08-04 18:46:34 +0000896 ZeroDivisionError: integer division or modulo by zero
897 (1, 1)
Tim Peters8485b562004-08-04 18:46:34 +0000898"""
899 def optionflags(): r"""
900Tests of `DocTestRunner`'s option flag handling.
901
902Several option flags can be used to customize the behavior of the test
903runner. These are defined as module constants in doctest, and passed
904to the DocTestRunner constructor (multiple constants should be or-ed
905together).
906
907The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
908and 1/0:
909
910 >>> def f(x):
911 ... '>>> True\n1\n'
912
913 >>> # Without the flag:
914 >>> test = doctest.DocTestFinder().find(f)[0]
915 >>> doctest.DocTestRunner(verbose=False).run(test)
916 (0, 1)
917
918 >>> # With the flag:
919 >>> test = doctest.DocTestFinder().find(f)[0]
920 >>> flags = doctest.DONT_ACCEPT_TRUE_FOR_1
921 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000922 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000923 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000924 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000925 Failed example:
926 True
927 Expected:
928 1
929 Got:
930 True
Tim Peters8485b562004-08-04 18:46:34 +0000931 (1, 1)
932
933The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines
934and the '<BLANKLINE>' marker:
935
936 >>> def f(x):
937 ... '>>> print "a\\n\\nb"\na\n<BLANKLINE>\nb\n'
938
939 >>> # Without the flag:
940 >>> test = doctest.DocTestFinder().find(f)[0]
941 >>> doctest.DocTestRunner(verbose=False).run(test)
942 (0, 1)
943
944 >>> # With the flag:
945 >>> test = doctest.DocTestFinder().find(f)[0]
946 >>> flags = doctest.DONT_ACCEPT_BLANKLINE
947 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000948 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000949 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000950 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000951 Failed example:
952 print "a\n\nb"
Tim Peters8485b562004-08-04 18:46:34 +0000953 Expected:
954 a
955 <BLANKLINE>
956 b
957 Got:
958 a
959 <BLANKLINE>
960 b
961 (1, 1)
962
963The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be
964treated as equal:
965
966 >>> def f(x):
967 ... '>>> print 1, 2, 3\n 1 2\n 3'
968
969 >>> # Without the flag:
970 >>> test = doctest.DocTestFinder().find(f)[0]
971 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000972 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000973 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000974 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000975 Failed example:
976 print 1, 2, 3
Tim Peters8485b562004-08-04 18:46:34 +0000977 Expected:
978 1 2
979 3
Jim Fulton07a349c2004-08-22 14:10:00 +0000980 Got:
981 1 2 3
Tim Peters8485b562004-08-04 18:46:34 +0000982 (1, 1)
983
984 >>> # With the flag:
985 >>> test = doctest.DocTestFinder().find(f)[0]
986 >>> flags = doctest.NORMALIZE_WHITESPACE
987 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
988 (0, 1)
989
Tim Peters026f8dc2004-08-19 16:38:58 +0000990 An example from the docs:
991 >>> print range(20) #doctest: +NORMALIZE_WHITESPACE
992 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
993 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
994
Tim Peters8485b562004-08-04 18:46:34 +0000995The ELLIPSIS flag causes ellipsis marker ("...") in the expected
996output to match any substring in the actual output:
997
998 >>> def f(x):
999 ... '>>> print range(15)\n[0, 1, 2, ..., 14]\n'
1000
1001 >>> # Without the flag:
1002 >>> test = doctest.DocTestFinder().find(f)[0]
1003 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001004 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001005 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001006 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001007 Failed example:
1008 print range(15)
1009 Expected:
1010 [0, 1, 2, ..., 14]
1011 Got:
1012 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
Tim Peters8485b562004-08-04 18:46:34 +00001013 (1, 1)
1014
1015 >>> # With the flag:
1016 >>> test = doctest.DocTestFinder().find(f)[0]
1017 >>> flags = doctest.ELLIPSIS
1018 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1019 (0, 1)
1020
Tim Peterse594bee2004-08-22 01:47:51 +00001021 ... also matches nothing:
Tim Peters1cf3aa62004-08-19 06:49:33 +00001022
1023 >>> for i in range(100):
Tim Peterse594bee2004-08-22 01:47:51 +00001024 ... print i**2, #doctest: +ELLIPSIS
1025 0 1...4...9 16 ... 36 49 64 ... 9801
Tim Peters1cf3aa62004-08-19 06:49:33 +00001026
Tim Peters026f8dc2004-08-19 16:38:58 +00001027 ... can be surprising; e.g., this test passes:
Tim Peters26b3ebb2004-08-19 08:10:08 +00001028
1029 >>> for i in range(21): #doctest: +ELLIPSIS
Tim Peterse594bee2004-08-22 01:47:51 +00001030 ... print i,
1031 0 1 2 ...1...2...0
Tim Peters26b3ebb2004-08-19 08:10:08 +00001032
Tim Peters026f8dc2004-08-19 16:38:58 +00001033 Examples from the docs:
1034
1035 >>> print range(20) # doctest:+ELLIPSIS
1036 [0, 1, ..., 18, 19]
1037
1038 >>> print range(20) # doctest: +ELLIPSIS
1039 ... # doctest: +NORMALIZE_WHITESPACE
1040 [0, 1, ..., 18, 19]
1041
Edward Loper71f55af2004-08-26 01:41:51 +00001042The REPORT_UDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001043and actual outputs to be displayed using a unified diff:
1044
1045 >>> def f(x):
1046 ... r'''
1047 ... >>> print '\n'.join('abcdefg')
1048 ... a
1049 ... B
1050 ... c
1051 ... d
1052 ... f
1053 ... g
1054 ... h
1055 ... '''
1056
1057 >>> # Without the flag:
1058 >>> test = doctest.DocTestFinder().find(f)[0]
1059 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001060 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001061 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001062 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001063 Failed example:
1064 print '\n'.join('abcdefg')
Tim Peters8485b562004-08-04 18:46:34 +00001065 Expected:
1066 a
1067 B
1068 c
1069 d
1070 f
1071 g
1072 h
1073 Got:
1074 a
1075 b
1076 c
1077 d
1078 e
1079 f
1080 g
1081 (1, 1)
1082
1083 >>> # With the flag:
1084 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001085 >>> flags = doctest.REPORT_UDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001086 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001087 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001088 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001089 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001090 Failed example:
1091 print '\n'.join('abcdefg')
Edward Loper56629292004-08-26 01:31:56 +00001092 Differences (unified diff with -expected +actual):
Tim Peterse7edcb82004-08-26 05:44:27 +00001093 @@ -1,7 +1,7 @@
Tim Peters8485b562004-08-04 18:46:34 +00001094 a
1095 -B
1096 +b
1097 c
1098 d
1099 +e
1100 f
1101 g
1102 -h
Tim Peters8485b562004-08-04 18:46:34 +00001103 (1, 1)
1104
Edward Loper71f55af2004-08-26 01:41:51 +00001105The REPORT_CDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001106and actual outputs to be displayed using a context diff:
1107
Edward Loper71f55af2004-08-26 01:41:51 +00001108 >>> # Reuse f() from the REPORT_UDIFF example, above.
Tim Peters8485b562004-08-04 18:46:34 +00001109 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001110 >>> flags = doctest.REPORT_CDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001111 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001112 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001113 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001114 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001115 Failed example:
1116 print '\n'.join('abcdefg')
Edward Loper56629292004-08-26 01:31:56 +00001117 Differences (context diff with expected followed by actual):
Tim Peters8485b562004-08-04 18:46:34 +00001118 ***************
Tim Peterse7edcb82004-08-26 05:44:27 +00001119 *** 1,7 ****
Tim Peters8485b562004-08-04 18:46:34 +00001120 a
1121 ! B
1122 c
1123 d
1124 f
1125 g
1126 - h
Tim Peterse7edcb82004-08-26 05:44:27 +00001127 --- 1,7 ----
Tim Peters8485b562004-08-04 18:46:34 +00001128 a
1129 ! b
1130 c
1131 d
1132 + e
1133 f
1134 g
Tim Peters8485b562004-08-04 18:46:34 +00001135 (1, 1)
Tim Petersc6cbab02004-08-22 19:43:28 +00001136
1137
Edward Loper71f55af2004-08-26 01:41:51 +00001138The REPORT_NDIFF flag causes failures to use the difflib.Differ algorithm
Tim Petersc6cbab02004-08-22 19:43:28 +00001139used by the popular ndiff.py utility. This does intraline difference
1140marking, as well as interline differences.
1141
1142 >>> def f(x):
1143 ... r'''
1144 ... >>> print "a b c d e f g h i j k l m"
1145 ... a b c d e f g h i j k 1 m
1146 ... '''
1147 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001148 >>> flags = doctest.REPORT_NDIFF
Tim Petersc6cbab02004-08-22 19:43:28 +00001149 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001150 ... # doctest: +ELLIPSIS
Tim Petersc6cbab02004-08-22 19:43:28 +00001151 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001152 File ..., line 3, in f
Tim Petersc6cbab02004-08-22 19:43:28 +00001153 Failed example:
1154 print "a b c d e f g h i j k l m"
1155 Differences (ndiff with -expected +actual):
1156 - a b c d e f g h i j k 1 m
1157 ? ^
1158 + a b c d e f g h i j k l m
1159 ? + ++ ^
Tim Petersc6cbab02004-08-22 19:43:28 +00001160 (1, 1)
Edward Lopera89f88d2004-08-26 02:45:51 +00001161
1162The REPORT_ONLY_FIRST_FAILURE supresses result output after the first
1163failing example:
1164
1165 >>> def f(x):
1166 ... r'''
1167 ... >>> print 1 # first success
1168 ... 1
1169 ... >>> print 2 # first failure
1170 ... 200
1171 ... >>> print 3 # second failure
1172 ... 300
1173 ... >>> print 4 # second success
1174 ... 4
1175 ... >>> print 5 # third failure
1176 ... 500
1177 ... '''
1178 >>> test = doctest.DocTestFinder().find(f)[0]
1179 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1180 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001181 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001182 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001183 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001184 Failed example:
1185 print 2 # first failure
1186 Expected:
1187 200
1188 Got:
1189 2
1190 (3, 5)
1191
1192However, output from `report_start` is not supressed:
1193
1194 >>> doctest.DocTestRunner(verbose=True, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001195 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001196 Trying:
1197 print 1 # first success
1198 Expecting:
1199 1
1200 ok
1201 Trying:
1202 print 2 # first failure
1203 Expecting:
1204 200
1205 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001206 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001207 Failed example:
1208 print 2 # first failure
1209 Expected:
1210 200
1211 Got:
1212 2
1213 (3, 5)
1214
1215For the purposes of REPORT_ONLY_FIRST_FAILURE, unexpected exceptions
1216count as failures:
1217
1218 >>> def f(x):
1219 ... r'''
1220 ... >>> print 1 # first success
1221 ... 1
1222 ... >>> raise ValueError(2) # first failure
1223 ... 200
1224 ... >>> print 3 # second failure
1225 ... 300
1226 ... >>> print 4 # second success
1227 ... 4
1228 ... >>> print 5 # third failure
1229 ... 500
1230 ... '''
1231 >>> test = doctest.DocTestFinder().find(f)[0]
1232 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1233 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1234 ... # doctest: +ELLIPSIS
1235 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001236 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001237 Failed example:
1238 raise ValueError(2) # first failure
1239 Exception raised:
1240 ...
1241 ValueError: 2
1242 (3, 5)
1243
Tim Petersc6cbab02004-08-22 19:43:28 +00001244 """
1245
Tim Peters8485b562004-08-04 18:46:34 +00001246 def option_directives(): r"""
1247Tests of `DocTestRunner`'s option directive mechanism.
1248
Edward Loper74bca7a2004-08-12 02:27:44 +00001249Option directives can be used to turn option flags on or off for a
1250single example. To turn an option on for an example, follow that
1251example with a comment of the form ``# doctest: +OPTION``:
Tim Peters8485b562004-08-04 18:46:34 +00001252
1253 >>> def f(x): r'''
Edward Loper74bca7a2004-08-12 02:27:44 +00001254 ... >>> print range(10) # should fail: no ellipsis
1255 ... [0, 1, ..., 9]
1256 ...
1257 ... >>> print range(10) # doctest: +ELLIPSIS
1258 ... [0, 1, ..., 9]
1259 ... '''
1260 >>> test = doctest.DocTestFinder().find(f)[0]
1261 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001262 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001263 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001264 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001265 Failed example:
1266 print range(10) # should fail: no ellipsis
1267 Expected:
1268 [0, 1, ..., 9]
1269 Got:
1270 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001271 (1, 2)
1272
1273To turn an option off for an example, follow that example with a
1274comment of the form ``# doctest: -OPTION``:
1275
1276 >>> def f(x): r'''
1277 ... >>> print range(10)
1278 ... [0, 1, ..., 9]
1279 ...
1280 ... >>> # should fail: no ellipsis
1281 ... >>> print range(10) # doctest: -ELLIPSIS
1282 ... [0, 1, ..., 9]
1283 ... '''
1284 >>> test = doctest.DocTestFinder().find(f)[0]
1285 >>> doctest.DocTestRunner(verbose=False,
1286 ... optionflags=doctest.ELLIPSIS).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001287 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001288 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001289 File ..., line 6, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001290 Failed example:
1291 print range(10) # doctest: -ELLIPSIS
1292 Expected:
1293 [0, 1, ..., 9]
1294 Got:
1295 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001296 (1, 2)
1297
1298Option directives affect only the example that they appear with; they
1299do not change the options for surrounding examples:
Edward Loper8e4a34b2004-08-12 02:34:27 +00001300
Edward Loper74bca7a2004-08-12 02:27:44 +00001301 >>> def f(x): r'''
Tim Peters8485b562004-08-04 18:46:34 +00001302 ... >>> print range(10) # Should fail: no ellipsis
1303 ... [0, 1, ..., 9]
1304 ...
Edward Loper74bca7a2004-08-12 02:27:44 +00001305 ... >>> print range(10) # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001306 ... [0, 1, ..., 9]
1307 ...
Tim Peters8485b562004-08-04 18:46:34 +00001308 ... >>> print range(10) # Should fail: no ellipsis
1309 ... [0, 1, ..., 9]
1310 ... '''
1311 >>> test = doctest.DocTestFinder().find(f)[0]
1312 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001313 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001314 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001315 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001316 Failed example:
1317 print range(10) # Should fail: no ellipsis
1318 Expected:
1319 [0, 1, ..., 9]
1320 Got:
1321 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001322 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001323 File ..., line 8, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001324 Failed example:
1325 print range(10) # Should fail: no ellipsis
1326 Expected:
1327 [0, 1, ..., 9]
1328 Got:
1329 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001330 (2, 3)
1331
Edward Loper74bca7a2004-08-12 02:27:44 +00001332Multiple options may be modified by a single option directive. They
1333may be separated by whitespace, commas, or both:
Tim Peters8485b562004-08-04 18:46:34 +00001334
1335 >>> def f(x): r'''
1336 ... >>> print range(10) # Should fail
1337 ... [0, 1, ..., 9]
Tim Peters8485b562004-08-04 18:46:34 +00001338 ... >>> print range(10) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001339 ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001340 ... [0, 1, ..., 9]
1341 ... '''
1342 >>> test = doctest.DocTestFinder().find(f)[0]
1343 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001344 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001345 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001346 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001347 Failed example:
1348 print range(10) # Should fail
1349 Expected:
1350 [0, 1, ..., 9]
1351 Got:
1352 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001353 (1, 2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001354
1355 >>> def f(x): r'''
1356 ... >>> print range(10) # Should fail
1357 ... [0, 1, ..., 9]
1358 ... >>> print range(10) # Should succeed
1359 ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
1360 ... [0, 1, ..., 9]
1361 ... '''
1362 >>> test = doctest.DocTestFinder().find(f)[0]
1363 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001364 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001365 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001366 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001367 Failed example:
1368 print range(10) # Should fail
1369 Expected:
1370 [0, 1, ..., 9]
1371 Got:
1372 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001373 (1, 2)
1374
1375 >>> def f(x): r'''
1376 ... >>> print range(10) # Should fail
1377 ... [0, 1, ..., 9]
1378 ... >>> print range(10) # Should succeed
1379 ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1380 ... [0, 1, ..., 9]
1381 ... '''
1382 >>> test = doctest.DocTestFinder().find(f)[0]
1383 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001384 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001385 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001386 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001387 Failed example:
1388 print range(10) # Should fail
1389 Expected:
1390 [0, 1, ..., 9]
1391 Got:
1392 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001393 (1, 2)
1394
1395The option directive may be put on the line following the source, as
1396long as a continuation prompt is used:
1397
1398 >>> def f(x): r'''
1399 ... >>> print range(10)
1400 ... ... # doctest: +ELLIPSIS
1401 ... [0, 1, ..., 9]
1402 ... '''
1403 >>> test = doctest.DocTestFinder().find(f)[0]
1404 >>> doctest.DocTestRunner(verbose=False).run(test)
1405 (0, 1)
Edward Loper8e4a34b2004-08-12 02:34:27 +00001406
Edward Loper74bca7a2004-08-12 02:27:44 +00001407For examples with multi-line source, the option directive may appear
1408at the end of any line:
1409
1410 >>> def f(x): r'''
1411 ... >>> for x in range(10): # doctest: +ELLIPSIS
1412 ... ... print x,
1413 ... 0 1 2 ... 9
1414 ...
1415 ... >>> for x in range(10):
1416 ... ... print x, # doctest: +ELLIPSIS
1417 ... 0 1 2 ... 9
1418 ... '''
1419 >>> test = doctest.DocTestFinder().find(f)[0]
1420 >>> doctest.DocTestRunner(verbose=False).run(test)
1421 (0, 2)
1422
1423If more than one line of an example with multi-line source has an
1424option directive, then they are combined:
1425
1426 >>> def f(x): r'''
1427 ... Should fail (option directive not on the last line):
1428 ... >>> for x in range(10): # doctest: +ELLIPSIS
1429 ... ... print x, # doctest: +NORMALIZE_WHITESPACE
1430 ... 0 1 2...9
1431 ... '''
1432 >>> test = doctest.DocTestFinder().find(f)[0]
1433 >>> doctest.DocTestRunner(verbose=False).run(test)
1434 (0, 1)
1435
1436It is an error to have a comment of the form ``# doctest:`` that is
1437*not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
1438``OPTION`` is an option that has been registered with
1439`register_option`:
1440
1441 >>> # Error: Option not registered
1442 >>> s = '>>> print 12 #doctest: +BADOPTION'
1443 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1444 Traceback (most recent call last):
1445 ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
1446
1447 >>> # Error: No + or - prefix
1448 >>> s = '>>> print 12 #doctest: ELLIPSIS'
1449 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1450 Traceback (most recent call last):
1451 ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
1452
1453It is an error to use an option directive on a line that contains no
1454source:
1455
1456 >>> s = '>>> # doctest: +ELLIPSIS'
1457 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1458 Traceback (most recent call last):
1459 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 +00001460"""
1461
1462def test_testsource(): r"""
1463Unit tests for `testsource()`.
1464
1465The testsource() function takes a module and a name, finds the (first)
Tim Peters19397e52004-08-06 22:02:59 +00001466test with that name in that module, and converts it to a script. The
1467example code is converted to regular Python code. The surrounding
1468words and expected output are converted to comments:
Tim Peters8485b562004-08-04 18:46:34 +00001469
1470 >>> import test.test_doctest
1471 >>> name = 'test.test_doctest.sample_func'
1472 >>> print doctest.testsource(test.test_doctest, name)
Edward Lopera5db6002004-08-12 02:41:30 +00001473 # Blah blah
Tim Peters19397e52004-08-06 22:02:59 +00001474 #
Tim Peters8485b562004-08-04 18:46:34 +00001475 print sample_func(22)
1476 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001477 ## 44
Tim Peters19397e52004-08-06 22:02:59 +00001478 #
Edward Lopera5db6002004-08-12 02:41:30 +00001479 # Yee ha!
Tim Peters8485b562004-08-04 18:46:34 +00001480
1481 >>> name = 'test.test_doctest.SampleNewStyleClass'
1482 >>> print doctest.testsource(test.test_doctest, name)
1483 print '1\n2\n3'
1484 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001485 ## 1
1486 ## 2
1487 ## 3
Tim Peters8485b562004-08-04 18:46:34 +00001488
1489 >>> name = 'test.test_doctest.SampleClass.a_classmethod'
1490 >>> print doctest.testsource(test.test_doctest, name)
1491 print SampleClass.a_classmethod(10)
1492 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001493 ## 12
Tim Peters8485b562004-08-04 18:46:34 +00001494 print SampleClass(0).a_classmethod(10)
1495 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001496 ## 12
Tim Peters8485b562004-08-04 18:46:34 +00001497"""
1498
1499def test_debug(): r"""
1500
1501Create a docstring that we want to debug:
1502
1503 >>> s = '''
1504 ... >>> x = 12
1505 ... >>> print x
1506 ... 12
1507 ... '''
1508
1509Create some fake stdin input, to feed to the debugger:
1510
1511 >>> import tempfile
Tim Peters8485b562004-08-04 18:46:34 +00001512 >>> real_stdin = sys.stdin
Edward Loper2de91ba2004-08-27 02:07:46 +00001513 >>> sys.stdin = _FakeInput(['next', 'print x', 'continue'])
Tim Peters8485b562004-08-04 18:46:34 +00001514
1515Run the debugger on the docstring, and then restore sys.stdin.
1516
Edward Loper2de91ba2004-08-27 02:07:46 +00001517 >>> try: doctest.debug_src(s)
1518 ... finally: sys.stdin = real_stdin
Tim Peters8485b562004-08-04 18:46:34 +00001519 > <string>(1)?()
Edward Loper2de91ba2004-08-27 02:07:46 +00001520 (Pdb) next
1521 12
Tim Peters8485b562004-08-04 18:46:34 +00001522 --Return--
1523 > <string>(1)?()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001524 (Pdb) print x
1525 12
1526 (Pdb) continue
Tim Peters8485b562004-08-04 18:46:34 +00001527
1528"""
1529
Jim Fulton356fd192004-08-09 11:34:47 +00001530def test_pdb_set_trace():
Edward Loper2de91ba2004-08-27 02:07:46 +00001531 """Using pdb.set_trace from a doctest
Jim Fulton356fd192004-08-09 11:34:47 +00001532
Tim Peters413ced62004-08-09 15:43:47 +00001533 You can use pdb.set_trace from a doctest. To do so, you must
Jim Fulton356fd192004-08-09 11:34:47 +00001534 retrieve the set_trace function from the pdb module at the time
Tim Peters413ced62004-08-09 15:43:47 +00001535 you use it. The doctest module changes sys.stdout so that it can
1536 capture program output. It also temporarily replaces pdb.set_trace
1537 with a version that restores stdout. This is necessary for you to
Jim Fulton356fd192004-08-09 11:34:47 +00001538 see debugger output.
1539
1540 >>> doc = '''
1541 ... >>> x = 42
1542 ... >>> import pdb; pdb.set_trace()
1543 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001544 >>> parser = doctest.DocTestParser()
1545 >>> test = parser.get_doctest(doc, {}, "foo", "foo.py", 0)
Jim Fulton356fd192004-08-09 11:34:47 +00001546 >>> runner = doctest.DocTestRunner(verbose=False)
1547
1548 To demonstrate this, we'll create a fake standard input that
1549 captures our debugger input:
1550
1551 >>> import tempfile
Edward Loper2de91ba2004-08-27 02:07:46 +00001552 >>> real_stdin = sys.stdin
1553 >>> sys.stdin = _FakeInput([
Jim Fulton356fd192004-08-09 11:34:47 +00001554 ... 'print x', # print data defined by the example
1555 ... 'continue', # stop debugging
Edward Loper2de91ba2004-08-27 02:07:46 +00001556 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001557
Edward Loper2de91ba2004-08-27 02:07:46 +00001558 >>> try: runner.run(test)
1559 ... finally: sys.stdin = real_stdin
Jim Fulton356fd192004-08-09 11:34:47 +00001560 --Return--
Edward Loper2de91ba2004-08-27 02:07:46 +00001561 > <doctest foo[1]>(1)?()->None
1562 -> import pdb; pdb.set_trace()
1563 (Pdb) print x
1564 42
1565 (Pdb) continue
1566 (0, 2)
Jim Fulton356fd192004-08-09 11:34:47 +00001567
1568 You can also put pdb.set_trace in a function called from a test:
1569
1570 >>> def calls_set_trace():
1571 ... y=2
1572 ... import pdb; pdb.set_trace()
1573
1574 >>> doc = '''
1575 ... >>> x=1
1576 ... >>> calls_set_trace()
1577 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001578 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
Edward Loper2de91ba2004-08-27 02:07:46 +00001579 >>> real_stdin = sys.stdin
1580 >>> sys.stdin = _FakeInput([
Jim Fulton356fd192004-08-09 11:34:47 +00001581 ... 'print y', # print data defined in the function
1582 ... 'up', # out of function
1583 ... '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 test.test_doctest.test_pdb_set_trace[8]>(3)calls_set_trace()->None
1591 -> import pdb; pdb.set_trace()
1592 (Pdb) print y
1593 2
1594 (Pdb) up
1595 > <doctest foo[1]>(1)?()
1596 -> calls_set_trace()
1597 (Pdb) print x
1598 1
1599 (Pdb) continue
1600 (0, 2)
1601
1602 During interactive debugging, source code is shown, even for
1603 doctest examples:
1604
1605 >>> doc = '''
1606 ... >>> def f(x):
1607 ... ... g(x*2)
1608 ... >>> def g(x):
1609 ... ... print x+3
1610 ... ... import pdb; pdb.set_trace()
1611 ... >>> f(3)
1612 ... '''
1613 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
1614 >>> real_stdin = sys.stdin
1615 >>> sys.stdin = _FakeInput([
1616 ... 'list', # list source from example 2
1617 ... 'next', # return from g()
1618 ... 'list', # list source from example 1
1619 ... 'next', # return from f()
1620 ... 'list', # list source from example 3
1621 ... 'continue', # stop debugging
1622 ... ''])
1623 >>> try: runner.run(test)
1624 ... finally: sys.stdin = real_stdin
1625 ... # doctest: +NORMALIZE_WHITESPACE
1626 --Return--
1627 > <doctest foo[1]>(3)g()->None
1628 -> import pdb; pdb.set_trace()
1629 (Pdb) list
1630 1 def g(x):
1631 2 print x+3
1632 3 -> import pdb; pdb.set_trace()
1633 [EOF]
1634 (Pdb) next
1635 --Return--
1636 > <doctest foo[0]>(2)f()->None
1637 -> g(x*2)
1638 (Pdb) list
1639 1 def f(x):
1640 2 -> g(x*2)
1641 [EOF]
1642 (Pdb) next
1643 --Return--
1644 > <doctest foo[2]>(1)?()->None
1645 -> f(3)
1646 (Pdb) list
1647 1 -> f(3)
1648 [EOF]
1649 (Pdb) continue
1650 **********************************************************************
1651 File "foo.py", line 7, in foo
1652 Failed example:
1653 f(3)
1654 Expected nothing
1655 Got:
1656 9
1657 (1, 3)
Jim Fulton356fd192004-08-09 11:34:47 +00001658 """
1659
Tim Peters19397e52004-08-06 22:02:59 +00001660def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +00001661 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +00001662
1663 We create a Suite by providing a module. A module can be provided
1664 by passing a module object:
1665
1666 >>> import unittest
1667 >>> import test.sample_doctest
1668 >>> suite = doctest.DocTestSuite(test.sample_doctest)
1669 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001670 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001671
1672 We can also supply the module by name:
1673
1674 >>> suite = doctest.DocTestSuite('test.sample_doctest')
1675 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001676 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001677
1678 We can use the current module:
1679
1680 >>> suite = test.sample_doctest.test_suite()
1681 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001682 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001683
1684 We can supply global variables. If we pass globs, they will be
1685 used instead of the module globals. Here we'll pass an empty
1686 globals, triggering an extra error:
1687
1688 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
1689 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001690 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001691
1692 Alternatively, we can provide extra globals. Here we'll make an
1693 error go away by providing an extra global variable:
1694
1695 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1696 ... extraglobs={'y': 1})
1697 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001698 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001699
1700 You can pass option flags. Here we'll cause an extra error
1701 by disabling the blank-line feature:
1702
1703 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00001704 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00001705 >>> 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
Tim Peters1e277ee2004-08-07 05:37:52 +00001708 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00001709
Jim Fultonf54bad42004-08-28 14:57:56 +00001710 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00001711 ... import test.test_doctest
1712 ... test.test_doctest.sillySetup = True
1713
Jim Fultonf54bad42004-08-28 14:57:56 +00001714 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00001715 ... import test.test_doctest
1716 ... del test.test_doctest.sillySetup
1717
1718 Here, we installed a silly variable that the test expects:
1719
1720 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1721 ... setUp=setUp, tearDown=tearDown)
1722 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001723 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001724
1725 But the tearDown restores sanity:
1726
1727 >>> import test.test_doctest
1728 >>> test.test_doctest.sillySetup
1729 Traceback (most recent call last):
1730 ...
1731 AttributeError: 'module' object has no attribute 'sillySetup'
1732
Jim Fultonf54bad42004-08-28 14:57:56 +00001733 The setUp and tearDown funtions are passed test objects. Here
1734 we'll use the setUp function to supply the missing variable y:
1735
1736 >>> def setUp(test):
1737 ... test.globs['y'] = 1
1738
1739 >>> suite = doctest.DocTestSuite('test.sample_doctest', setUp=setUp)
1740 >>> suite.run(unittest.TestResult())
1741 <unittest.TestResult run=9 errors=0 failures=3>
1742
1743 Here, we didn't need to use a tearDown function because we
1744 modified the test globals, which are a copy of the
1745 sample_doctest module dictionary. The test globals are
1746 automatically cleared for us after a test.
1747
Tim Peters19397e52004-08-06 22:02:59 +00001748 Finally, you can provide an alternate test finder. Here we'll
Tim Peters1e277ee2004-08-07 05:37:52 +00001749 use a custom test_finder to to run just the test named bar.
1750 However, the test in the module docstring, and the two tests
1751 in the module __test__ dict, aren't filtered, so we actually
1752 run three tests besides bar's. The filtering mechanisms are
1753 poorly conceived, and will go away someday.
Tim Peters19397e52004-08-06 22:02:59 +00001754
1755 >>> finder = doctest.DocTestFinder(
Tim Petersf727c6c2004-08-08 01:48:59 +00001756 ... _namefilter=lambda prefix, base: base!='bar')
Tim Peters19397e52004-08-06 22:02:59 +00001757 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1758 ... test_finder=finder)
1759 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001760 <unittest.TestResult run=4 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00001761 """
1762
1763def test_DocFileSuite():
1764 """We can test tests found in text files using a DocFileSuite.
1765
1766 We create a suite by providing the names of one or more text
1767 files that include examples:
1768
1769 >>> import unittest
1770 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1771 ... 'test_doctest2.txt')
1772 >>> suite.run(unittest.TestResult())
1773 <unittest.TestResult run=2 errors=0 failures=2>
1774
1775 The test files are looked for in the directory containing the
1776 calling module. A package keyword argument can be provided to
1777 specify a different relative location.
1778
1779 >>> import unittest
1780 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1781 ... 'test_doctest2.txt',
1782 ... package='test')
1783 >>> suite.run(unittest.TestResult())
1784 <unittest.TestResult run=2 errors=0 failures=2>
1785
1786 Note that '/' should be used as a path separator. It will be
1787 converted to a native separator at run time:
1788
1789
1790 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
1791 >>> suite.run(unittest.TestResult())
1792 <unittest.TestResult run=1 errors=0 failures=1>
1793
1794 You can specify initial global variables:
1795
1796 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1797 ... 'test_doctest2.txt',
1798 ... globs={'favorite_color': 'blue'})
1799 >>> suite.run(unittest.TestResult())
1800 <unittest.TestResult run=2 errors=0 failures=1>
1801
1802 In this case, we supplied a missing favorite color. You can
1803 provide doctest options:
1804
1805 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1806 ... 'test_doctest2.txt',
1807 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
1808 ... globs={'favorite_color': 'blue'})
1809 >>> suite.run(unittest.TestResult())
1810 <unittest.TestResult run=2 errors=0 failures=2>
1811
1812 And, you can provide setUp and tearDown functions:
1813
1814 You can supply setUp and teatDoen functions:
1815
Jim Fultonf54bad42004-08-28 14:57:56 +00001816 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00001817 ... import test.test_doctest
1818 ... test.test_doctest.sillySetup = True
1819
Jim Fultonf54bad42004-08-28 14:57:56 +00001820 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00001821 ... import test.test_doctest
1822 ... del test.test_doctest.sillySetup
1823
1824 Here, we installed a silly variable that the test expects:
1825
1826 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1827 ... 'test_doctest2.txt',
1828 ... setUp=setUp, tearDown=tearDown)
1829 >>> suite.run(unittest.TestResult())
1830 <unittest.TestResult run=2 errors=0 failures=1>
1831
1832 But the tearDown restores sanity:
1833
1834 >>> import test.test_doctest
1835 >>> test.test_doctest.sillySetup
1836 Traceback (most recent call last):
1837 ...
1838 AttributeError: 'module' object has no attribute 'sillySetup'
1839
Jim Fultonf54bad42004-08-28 14:57:56 +00001840 The setUp and tearDown funtions are passed test objects.
1841 Here, we'll use a setUp function to set the favorite color in
1842 test_doctest.txt:
1843
1844 >>> def setUp(test):
1845 ... test.globs['favorite_color'] = 'blue'
1846
1847 >>> suite = doctest.DocFileSuite('test_doctest.txt', setUp=setUp)
1848 >>> suite.run(unittest.TestResult())
1849 <unittest.TestResult run=1 errors=0 failures=0>
1850
1851 Here, we didn't need to use a tearDown function because we
1852 modified the test globals. The test globals are
1853 automatically cleared for us after a test.
Tim Petersdf7a2082004-08-29 00:38:17 +00001854
Jim Fultonf54bad42004-08-28 14:57:56 +00001855 """
Tim Peters19397e52004-08-06 22:02:59 +00001856
Jim Fulton07a349c2004-08-22 14:10:00 +00001857def test_trailing_space_in_test():
1858 """
Tim Petersa7def722004-08-23 22:13:22 +00001859 Trailing spaces in expected output are significant:
Tim Petersc6cbab02004-08-22 19:43:28 +00001860
Jim Fulton07a349c2004-08-22 14:10:00 +00001861 >>> x, y = 'foo', ''
1862 >>> print x, y
1863 foo \n
1864 """
Tim Peters19397e52004-08-06 22:02:59 +00001865
Jim Fultonf54bad42004-08-28 14:57:56 +00001866
1867def test_unittest_reportflags():
1868 """Default unittest reporting flags can be set to control reporting
1869
1870 Here, we'll set the REPORT_ONLY_FIRST_FAILURE option so we see
1871 only the first failure of each test. First, we'll look at the
1872 output without the flag. The file test_doctest.txt file has two
1873 tests. They both fail if blank lines are disabled:
1874
1875 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1876 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
1877 >>> import unittest
1878 >>> result = suite.run(unittest.TestResult())
1879 >>> print result.failures[0][1] # doctest: +ELLIPSIS
1880 Traceback ...
1881 Failed example:
1882 favorite_color
1883 ...
1884 Failed example:
1885 if 1:
1886 ...
1887
1888 Note that we see both failures displayed.
1889
1890 >>> old = doctest.set_unittest_reportflags(
1891 ... doctest.REPORT_ONLY_FIRST_FAILURE)
1892
1893 Now, when we run the test:
1894
1895 >>> result = suite.run(unittest.TestResult())
1896 >>> print result.failures[0][1] # doctest: +ELLIPSIS
1897 Traceback ...
1898 Failed example:
1899 favorite_color
1900 Exception raised:
1901 ...
1902 NameError: name 'favorite_color' is not defined
1903 <BLANKLINE>
1904 <BLANKLINE>
Tim Petersdf7a2082004-08-29 00:38:17 +00001905
Jim Fultonf54bad42004-08-28 14:57:56 +00001906 We get only the first failure.
1907
1908 If we give any reporting options when we set up the tests,
1909 however:
1910
1911 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1912 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE | doctest.REPORT_NDIFF)
1913
1914 Then the default eporting options are ignored:
1915
1916 >>> result = suite.run(unittest.TestResult())
1917 >>> print result.failures[0][1] # doctest: +ELLIPSIS
1918 Traceback ...
1919 Failed example:
1920 favorite_color
1921 ...
1922 Failed example:
1923 if 1:
1924 print 'a'
1925 print
1926 print 'b'
1927 Differences (ndiff with -expected +actual):
1928 a
1929 - <BLANKLINE>
1930 +
1931 b
1932 <BLANKLINE>
1933 <BLANKLINE>
1934
1935
1936 Test runners can restore the formatting flags after they run:
1937
1938 >>> ignored = doctest.set_unittest_reportflags(old)
1939
1940 """
1941
Tim Petersa7def722004-08-23 22:13:22 +00001942# old_test1, ... used to live in doctest.py, but cluttered it. Note
1943# that these use the deprecated doctest.Tester, so should go away (or
1944# be rewritten) someday.
1945
1946# Ignore all warnings about the use of class Tester in this module.
1947# Note that the name of this module may differ depending on how it's
1948# imported, so the use of __name__ is important.
1949warnings.filterwarnings("ignore", "class Tester", DeprecationWarning,
1950 __name__, 0)
1951
1952def old_test1(): r"""
1953>>> from doctest import Tester
1954>>> t = Tester(globs={'x': 42}, verbose=0)
1955>>> t.runstring(r'''
1956... >>> x = x * 2
1957... >>> print x
1958... 42
1959... ''', 'XYZ')
1960**********************************************************************
1961Line 3, in XYZ
1962Failed example:
1963 print x
1964Expected:
1965 42
1966Got:
1967 84
1968(1, 2)
1969>>> t.runstring(">>> x = x * 2\n>>> print x\n84\n", 'example2')
1970(0, 2)
1971>>> t.summarize()
1972**********************************************************************
19731 items had failures:
1974 1 of 2 in XYZ
1975***Test Failed*** 1 failures.
1976(1, 4)
1977>>> t.summarize(verbose=1)
19781 items passed all tests:
1979 2 tests in example2
1980**********************************************************************
19811 items had failures:
1982 1 of 2 in XYZ
19834 tests in 2 items.
19843 passed and 1 failed.
1985***Test Failed*** 1 failures.
1986(1, 4)
1987"""
1988
1989def old_test2(): r"""
1990 >>> from doctest import Tester
1991 >>> t = Tester(globs={}, verbose=1)
1992 >>> test = r'''
1993 ... # just an example
1994 ... >>> x = 1 + 2
1995 ... >>> x
1996 ... 3
1997 ... '''
1998 >>> t.runstring(test, "Example")
1999 Running string Example
Edward Loperaacf0832004-08-26 01:19:50 +00002000 Trying:
2001 x = 1 + 2
2002 Expecting nothing
Tim Petersa7def722004-08-23 22:13:22 +00002003 ok
Edward Loperaacf0832004-08-26 01:19:50 +00002004 Trying:
2005 x
2006 Expecting:
2007 3
Tim Petersa7def722004-08-23 22:13:22 +00002008 ok
2009 0 of 2 examples failed in string Example
2010 (0, 2)
2011"""
2012
2013def old_test3(): r"""
2014 >>> from doctest import Tester
2015 >>> t = Tester(globs={}, verbose=0)
2016 >>> def _f():
2017 ... '''Trivial docstring example.
2018 ... >>> assert 2 == 2
2019 ... '''
2020 ... return 32
2021 ...
2022 >>> t.rundoc(_f) # expect 0 failures in 1 example
2023 (0, 1)
2024"""
2025
2026def old_test4(): """
2027 >>> import new
2028 >>> m1 = new.module('_m1')
2029 >>> m2 = new.module('_m2')
2030 >>> test_data = \"""
2031 ... def _f():
2032 ... '''>>> assert 1 == 1
2033 ... '''
2034 ... def g():
2035 ... '''>>> assert 2 != 1
2036 ... '''
2037 ... class H:
2038 ... '''>>> assert 2 > 1
2039 ... '''
2040 ... def bar(self):
2041 ... '''>>> assert 1 < 2
2042 ... '''
2043 ... \"""
2044 >>> exec test_data in m1.__dict__
2045 >>> exec test_data in m2.__dict__
2046 >>> m1.__dict__.update({"f2": m2._f, "g2": m2.g, "h2": m2.H})
2047
2048 Tests that objects outside m1 are excluded:
2049
2050 >>> from doctest import Tester
2051 >>> t = Tester(globs={}, verbose=0)
2052 >>> t.rundict(m1.__dict__, "rundict_test", m1) # f2 and g2 and h2 skipped
2053 (0, 4)
2054
2055 Once more, not excluding stuff outside m1:
2056
2057 >>> t = Tester(globs={}, verbose=0)
2058 >>> t.rundict(m1.__dict__, "rundict_test_pvt") # None are skipped.
2059 (0, 8)
2060
2061 The exclusion of objects from outside the designated module is
2062 meant to be invoked automagically by testmod.
2063
2064 >>> doctest.testmod(m1, verbose=False)
2065 (0, 4)
2066"""
2067
Tim Peters8485b562004-08-04 18:46:34 +00002068######################################################################
2069## Main
2070######################################################################
2071
2072def test_main():
2073 # Check the doctest cases in doctest itself:
2074 test_support.run_doctest(doctest, verbosity=True)
2075 # Check the doctest cases defined here:
2076 from test import test_doctest
2077 test_support.run_doctest(test_doctest, verbosity=True)
2078
2079import trace, sys, re, StringIO
2080def test_coverage(coverdir):
2081 tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
2082 trace=0, count=1)
2083 tracer.run('reload(doctest); test_main()')
2084 r = tracer.results()
2085 print 'Writing coverage results...'
2086 r.write_results(show_missing=True, summary=True,
2087 coverdir=coverdir)
2088
2089if __name__ == '__main__':
2090 if '-c' in sys.argv:
2091 test_coverage('/tmp/doctest.cover')
2092 else:
2093 test_main()