blob: 6f715779dc61d6e9bd0ddaba55f433c1ce5fb0f7 [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 '''
390 >>> finder.find(no_examples)
391 [<DocTest no_examples from None:1 (no examples)>]
392
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)
Edward Loperaacf0832004-08-26 01:19:50 +0000668 Trying:
669 x = 12
670 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000671 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000672 Trying:
673 print x
674 Expecting:
675 14
Tim Peters8485b562004-08-04 18:46:34 +0000676 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000677 Line 3, in f
678 Failed example:
679 print x
680 Expected:
681 14
682 Got:
683 12
Edward Loperaacf0832004-08-26 01:19:50 +0000684 Trying:
685 x/2
686 Expecting:
687 6
Tim Peters8485b562004-08-04 18:46:34 +0000688 ok
689 (1, 3)
690"""
691 def verbose_flag(): r"""
692The `verbose` flag makes the test runner generate more detailed
693output:
694
695 >>> def f(x):
696 ... '''
697 ... >>> x = 12
698 ... >>> print x
699 ... 12
700 ... >>> x/2
701 ... 6
702 ... '''
703 >>> test = doctest.DocTestFinder().find(f)[0]
704
705 >>> doctest.DocTestRunner(verbose=True).run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000706 Trying:
707 x = 12
708 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000709 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000710 Trying:
711 print x
712 Expecting:
713 12
Tim Peters8485b562004-08-04 18:46:34 +0000714 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000715 Trying:
716 x/2
717 Expecting:
718 6
Tim Peters8485b562004-08-04 18:46:34 +0000719 ok
720 (0, 3)
721
722If the `verbose` flag is unspecified, then the output will be verbose
723iff `-v` appears in sys.argv:
724
725 >>> # Save the real sys.argv list.
726 >>> old_argv = sys.argv
727
728 >>> # If -v does not appear in sys.argv, then output isn't verbose.
729 >>> sys.argv = ['test']
730 >>> doctest.DocTestRunner().run(test)
731 (0, 3)
732
733 >>> # If -v does appear in sys.argv, then output is verbose.
734 >>> sys.argv = ['test', '-v']
735 >>> doctest.DocTestRunner().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
752 >>> # Restore sys.argv
753 >>> sys.argv = old_argv
754
755In the remaining examples, the test runner's verbosity will be
756explicitly set, to ensure that the test behavior is consistent.
757 """
758 def exceptions(): r"""
759Tests of `DocTestRunner`'s exception handling.
760
761An expected exception is specified with a traceback message. The
762lines between the first line and the type/value may be omitted or
763replaced with any other string:
764
765 >>> def f(x):
766 ... '''
767 ... >>> x = 12
768 ... >>> print x/0
769 ... Traceback (most recent call last):
770 ... ZeroDivisionError: integer division or modulo by zero
771 ... '''
772 >>> test = doctest.DocTestFinder().find(f)[0]
773 >>> doctest.DocTestRunner(verbose=False).run(test)
774 (0, 2)
775
Edward Loper19b19582004-08-25 23:07:03 +0000776An example may not generate output before it raises an exception; if
777it does, then the traceback message will not be recognized as
778signaling an expected exception, so the example will be reported as an
779unexpected exception:
Tim Peters8485b562004-08-04 18:46:34 +0000780
781 >>> def f(x):
782 ... '''
783 ... >>> x = 12
784 ... >>> print 'pre-exception output', x/0
785 ... pre-exception output
786 ... Traceback (most recent call last):
787 ... ZeroDivisionError: integer division or modulo by zero
788 ... '''
789 >>> test = doctest.DocTestFinder().find(f)[0]
790 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper19b19582004-08-25 23:07:03 +0000791 ... # doctest: +ELLIPSIS
792 **********************************************************************
793 Line 3, in f
794 Failed example:
795 print 'pre-exception output', x/0
796 Exception raised:
797 ...
798 ZeroDivisionError: integer division or modulo by zero
799 (1, 2)
Tim Peters8485b562004-08-04 18:46:34 +0000800
801Exception messages may contain newlines:
802
803 >>> def f(x):
804 ... r'''
805 ... >>> raise ValueError, 'multi\nline\nmessage'
806 ... Traceback (most recent call last):
807 ... ValueError: multi
808 ... line
809 ... message
810 ... '''
811 >>> test = doctest.DocTestFinder().find(f)[0]
812 >>> doctest.DocTestRunner(verbose=False).run(test)
813 (0, 1)
814
815If an exception is expected, but an exception with the wrong type or
816message is raised, then it is reported as a failure:
817
818 >>> def f(x):
819 ... r'''
820 ... >>> raise ValueError, 'message'
821 ... Traceback (most recent call last):
822 ... ValueError: wrong message
823 ... '''
824 >>> test = doctest.DocTestFinder().find(f)[0]
825 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000826 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000827 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000828 Line 2, in f
829 Failed example:
830 raise ValueError, 'message'
Tim Peters8485b562004-08-04 18:46:34 +0000831 Expected:
832 Traceback (most recent call last):
833 ValueError: wrong message
834 Got:
835 Traceback (most recent call last):
Edward Loper8e4a34b2004-08-12 02:34:27 +0000836 ...
Tim Peters8485b562004-08-04 18:46:34 +0000837 ValueError: message
838 (1, 1)
839
840If an exception is raised but not expected, then it is reported as an
841unexpected exception:
842
Tim Peters8485b562004-08-04 18:46:34 +0000843 >>> def f(x):
844 ... r'''
845 ... >>> 1/0
846 ... 0
847 ... '''
848 >>> test = doctest.DocTestFinder().find(f)[0]
849 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper74bca7a2004-08-12 02:27:44 +0000850 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000851 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000852 Line 2, in f
853 Failed example:
854 1/0
Tim Peters8485b562004-08-04 18:46:34 +0000855 Exception raised:
856 Traceback (most recent call last):
Jim Fulton07a349c2004-08-22 14:10:00 +0000857 ...
Tim Peters8485b562004-08-04 18:46:34 +0000858 ZeroDivisionError: integer division or modulo by zero
859 (1, 1)
Tim Peters8485b562004-08-04 18:46:34 +0000860"""
861 def optionflags(): r"""
862Tests of `DocTestRunner`'s option flag handling.
863
864Several option flags can be used to customize the behavior of the test
865runner. These are defined as module constants in doctest, and passed
866to the DocTestRunner constructor (multiple constants should be or-ed
867together).
868
869The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
870and 1/0:
871
872 >>> def f(x):
873 ... '>>> True\n1\n'
874
875 >>> # Without the flag:
876 >>> test = doctest.DocTestFinder().find(f)[0]
877 >>> doctest.DocTestRunner(verbose=False).run(test)
878 (0, 1)
879
880 >>> # With the flag:
881 >>> test = doctest.DocTestFinder().find(f)[0]
882 >>> flags = doctest.DONT_ACCEPT_TRUE_FOR_1
883 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
884 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000885 Line 1, in f
886 Failed example:
887 True
888 Expected:
889 1
890 Got:
891 True
Tim Peters8485b562004-08-04 18:46:34 +0000892 (1, 1)
893
894The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines
895and the '<BLANKLINE>' marker:
896
897 >>> def f(x):
898 ... '>>> print "a\\n\\nb"\na\n<BLANKLINE>\nb\n'
899
900 >>> # Without the flag:
901 >>> test = doctest.DocTestFinder().find(f)[0]
902 >>> doctest.DocTestRunner(verbose=False).run(test)
903 (0, 1)
904
905 >>> # With the flag:
906 >>> test = doctest.DocTestFinder().find(f)[0]
907 >>> flags = doctest.DONT_ACCEPT_BLANKLINE
908 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
909 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000910 Line 1, in f
911 Failed example:
912 print "a\n\nb"
Tim Peters8485b562004-08-04 18:46:34 +0000913 Expected:
914 a
915 <BLANKLINE>
916 b
917 Got:
918 a
919 <BLANKLINE>
920 b
921 (1, 1)
922
923The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be
924treated as equal:
925
926 >>> def f(x):
927 ... '>>> print 1, 2, 3\n 1 2\n 3'
928
929 >>> # Without the flag:
930 >>> test = doctest.DocTestFinder().find(f)[0]
931 >>> doctest.DocTestRunner(verbose=False).run(test)
932 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000933 Line 1, in f
934 Failed example:
935 print 1, 2, 3
Tim Peters8485b562004-08-04 18:46:34 +0000936 Expected:
937 1 2
938 3
Jim Fulton07a349c2004-08-22 14:10:00 +0000939 Got:
940 1 2 3
Tim Peters8485b562004-08-04 18:46:34 +0000941 (1, 1)
942
943 >>> # With the flag:
944 >>> test = doctest.DocTestFinder().find(f)[0]
945 >>> flags = doctest.NORMALIZE_WHITESPACE
946 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
947 (0, 1)
948
Tim Peters026f8dc2004-08-19 16:38:58 +0000949 An example from the docs:
950 >>> print range(20) #doctest: +NORMALIZE_WHITESPACE
951 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
952 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
953
Tim Peters8485b562004-08-04 18:46:34 +0000954The ELLIPSIS flag causes ellipsis marker ("...") in the expected
955output to match any substring in the actual output:
956
957 >>> def f(x):
958 ... '>>> print range(15)\n[0, 1, 2, ..., 14]\n'
959
960 >>> # Without the flag:
961 >>> test = doctest.DocTestFinder().find(f)[0]
962 >>> doctest.DocTestRunner(verbose=False).run(test)
963 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +0000964 Line 1, in f
965 Failed example:
966 print range(15)
967 Expected:
968 [0, 1, 2, ..., 14]
969 Got:
970 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
Tim Peters8485b562004-08-04 18:46:34 +0000971 (1, 1)
972
973 >>> # With the flag:
974 >>> test = doctest.DocTestFinder().find(f)[0]
975 >>> flags = doctest.ELLIPSIS
976 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
977 (0, 1)
978
Tim Peterse594bee2004-08-22 01:47:51 +0000979 ... also matches nothing:
Tim Peters1cf3aa62004-08-19 06:49:33 +0000980
981 >>> for i in range(100):
Tim Peterse594bee2004-08-22 01:47:51 +0000982 ... print i**2, #doctest: +ELLIPSIS
983 0 1...4...9 16 ... 36 49 64 ... 9801
Tim Peters1cf3aa62004-08-19 06:49:33 +0000984
Tim Peters026f8dc2004-08-19 16:38:58 +0000985 ... can be surprising; e.g., this test passes:
Tim Peters26b3ebb2004-08-19 08:10:08 +0000986
987 >>> for i in range(21): #doctest: +ELLIPSIS
Tim Peterse594bee2004-08-22 01:47:51 +0000988 ... print i,
989 0 1 2 ...1...2...0
Tim Peters26b3ebb2004-08-19 08:10:08 +0000990
Tim Peters026f8dc2004-08-19 16:38:58 +0000991 Examples from the docs:
992
993 >>> print range(20) # doctest:+ELLIPSIS
994 [0, 1, ..., 18, 19]
995
996 >>> print range(20) # doctest: +ELLIPSIS
997 ... # doctest: +NORMALIZE_WHITESPACE
998 [0, 1, ..., 18, 19]
999
Edward Loper71f55af2004-08-26 01:41:51 +00001000The REPORT_UDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001001and actual outputs to be displayed using a unified diff:
1002
1003 >>> def f(x):
1004 ... r'''
1005 ... >>> print '\n'.join('abcdefg')
1006 ... a
1007 ... B
1008 ... c
1009 ... d
1010 ... f
1011 ... g
1012 ... h
1013 ... '''
1014
1015 >>> # Without the flag:
1016 >>> test = doctest.DocTestFinder().find(f)[0]
1017 >>> doctest.DocTestRunner(verbose=False).run(test)
1018 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001019 Line 2, in f
1020 Failed example:
1021 print '\n'.join('abcdefg')
Tim Peters8485b562004-08-04 18:46:34 +00001022 Expected:
1023 a
1024 B
1025 c
1026 d
1027 f
1028 g
1029 h
1030 Got:
1031 a
1032 b
1033 c
1034 d
1035 e
1036 f
1037 g
1038 (1, 1)
1039
1040 >>> # With the flag:
1041 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001042 >>> flags = doctest.REPORT_UDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001043 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1044 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001045 Line 2, in f
1046 Failed example:
1047 print '\n'.join('abcdefg')
Edward Loper56629292004-08-26 01:31:56 +00001048 Differences (unified diff with -expected +actual):
Tim Peterse7edcb82004-08-26 05:44:27 +00001049 @@ -1,7 +1,7 @@
Tim Peters8485b562004-08-04 18:46:34 +00001050 a
1051 -B
1052 +b
1053 c
1054 d
1055 +e
1056 f
1057 g
1058 -h
Tim Peters8485b562004-08-04 18:46:34 +00001059 (1, 1)
1060
Edward Loper71f55af2004-08-26 01:41:51 +00001061The REPORT_CDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001062and actual outputs to be displayed using a context diff:
1063
Edward Loper71f55af2004-08-26 01:41:51 +00001064 >>> # Reuse f() from the REPORT_UDIFF example, above.
Tim Peters8485b562004-08-04 18:46:34 +00001065 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001066 >>> flags = doctest.REPORT_CDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001067 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1068 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001069 Line 2, in f
1070 Failed example:
1071 print '\n'.join('abcdefg')
Edward Loper56629292004-08-26 01:31:56 +00001072 Differences (context diff with expected followed by actual):
Tim Peters8485b562004-08-04 18:46:34 +00001073 ***************
Tim Peterse7edcb82004-08-26 05:44:27 +00001074 *** 1,7 ****
Tim Peters8485b562004-08-04 18:46:34 +00001075 a
1076 ! B
1077 c
1078 d
1079 f
1080 g
1081 - h
Tim Peterse7edcb82004-08-26 05:44:27 +00001082 --- 1,7 ----
Tim Peters8485b562004-08-04 18:46:34 +00001083 a
1084 ! b
1085 c
1086 d
1087 + e
1088 f
1089 g
Tim Peters8485b562004-08-04 18:46:34 +00001090 (1, 1)
Tim Petersc6cbab02004-08-22 19:43:28 +00001091
1092
Edward Loper71f55af2004-08-26 01:41:51 +00001093The REPORT_NDIFF flag causes failures to use the difflib.Differ algorithm
Tim Petersc6cbab02004-08-22 19:43:28 +00001094used by the popular ndiff.py utility. This does intraline difference
1095marking, as well as interline differences.
1096
1097 >>> def f(x):
1098 ... r'''
1099 ... >>> print "a b c d e f g h i j k l m"
1100 ... a b c d e f g h i j k 1 m
1101 ... '''
1102 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001103 >>> flags = doctest.REPORT_NDIFF
Tim Petersc6cbab02004-08-22 19:43:28 +00001104 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1105 **********************************************************************
1106 Line 2, in f
1107 Failed example:
1108 print "a b c d e f g h i j k l m"
1109 Differences (ndiff with -expected +actual):
1110 - a b c d e f g h i j k 1 m
1111 ? ^
1112 + a b c d e f g h i j k l m
1113 ? + ++ ^
Tim Petersc6cbab02004-08-22 19:43:28 +00001114 (1, 1)
Edward Lopera89f88d2004-08-26 02:45:51 +00001115
1116The REPORT_ONLY_FIRST_FAILURE supresses result output after the first
1117failing example:
1118
1119 >>> def f(x):
1120 ... r'''
1121 ... >>> print 1 # first success
1122 ... 1
1123 ... >>> print 2 # first failure
1124 ... 200
1125 ... >>> print 3 # second failure
1126 ... 300
1127 ... >>> print 4 # second success
1128 ... 4
1129 ... >>> print 5 # third failure
1130 ... 500
1131 ... '''
1132 >>> test = doctest.DocTestFinder().find(f)[0]
1133 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1134 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1135 **********************************************************************
1136 Line 4, in f
1137 Failed example:
1138 print 2 # first failure
1139 Expected:
1140 200
1141 Got:
1142 2
1143 (3, 5)
1144
1145However, output from `report_start` is not supressed:
1146
1147 >>> doctest.DocTestRunner(verbose=True, optionflags=flags).run(test)
1148 Trying:
1149 print 1 # first success
1150 Expecting:
1151 1
1152 ok
1153 Trying:
1154 print 2 # first failure
1155 Expecting:
1156 200
1157 **********************************************************************
1158 Line 4, in f
1159 Failed example:
1160 print 2 # first failure
1161 Expected:
1162 200
1163 Got:
1164 2
1165 (3, 5)
1166
1167For the purposes of REPORT_ONLY_FIRST_FAILURE, unexpected exceptions
1168count as failures:
1169
1170 >>> def f(x):
1171 ... r'''
1172 ... >>> print 1 # first success
1173 ... 1
1174 ... >>> raise ValueError(2) # first failure
1175 ... 200
1176 ... >>> print 3 # second failure
1177 ... 300
1178 ... >>> print 4 # second success
1179 ... 4
1180 ... >>> print 5 # third failure
1181 ... 500
1182 ... '''
1183 >>> test = doctest.DocTestFinder().find(f)[0]
1184 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1185 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1186 ... # doctest: +ELLIPSIS
1187 **********************************************************************
1188 Line 4, in f
1189 Failed example:
1190 raise ValueError(2) # first failure
1191 Exception raised:
1192 ...
1193 ValueError: 2
1194 (3, 5)
1195
Tim Petersc6cbab02004-08-22 19:43:28 +00001196 """
1197
Tim Peters8485b562004-08-04 18:46:34 +00001198 def option_directives(): r"""
1199Tests of `DocTestRunner`'s option directive mechanism.
1200
Edward Loper74bca7a2004-08-12 02:27:44 +00001201Option directives can be used to turn option flags on or off for a
1202single example. To turn an option on for an example, follow that
1203example with a comment of the form ``# doctest: +OPTION``:
Tim Peters8485b562004-08-04 18:46:34 +00001204
1205 >>> def f(x): r'''
Edward Loper74bca7a2004-08-12 02:27:44 +00001206 ... >>> print range(10) # should fail: no ellipsis
1207 ... [0, 1, ..., 9]
1208 ...
1209 ... >>> print range(10) # doctest: +ELLIPSIS
1210 ... [0, 1, ..., 9]
1211 ... '''
1212 >>> test = doctest.DocTestFinder().find(f)[0]
1213 >>> doctest.DocTestRunner(verbose=False).run(test)
1214 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001215 Line 2, in f
1216 Failed example:
1217 print range(10) # should fail: no ellipsis
1218 Expected:
1219 [0, 1, ..., 9]
1220 Got:
1221 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001222 (1, 2)
1223
1224To turn an option off for an example, follow that example with a
1225comment of the form ``# doctest: -OPTION``:
1226
1227 >>> def f(x): r'''
1228 ... >>> print range(10)
1229 ... [0, 1, ..., 9]
1230 ...
1231 ... >>> # should fail: no ellipsis
1232 ... >>> print range(10) # doctest: -ELLIPSIS
1233 ... [0, 1, ..., 9]
1234 ... '''
1235 >>> test = doctest.DocTestFinder().find(f)[0]
1236 >>> doctest.DocTestRunner(verbose=False,
1237 ... optionflags=doctest.ELLIPSIS).run(test)
1238 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001239 Line 6, in f
1240 Failed example:
1241 print range(10) # doctest: -ELLIPSIS
1242 Expected:
1243 [0, 1, ..., 9]
1244 Got:
1245 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001246 (1, 2)
1247
1248Option directives affect only the example that they appear with; they
1249do not change the options for surrounding examples:
Edward Loper8e4a34b2004-08-12 02:34:27 +00001250
Edward Loper74bca7a2004-08-12 02:27:44 +00001251 >>> def f(x): r'''
Tim Peters8485b562004-08-04 18:46:34 +00001252 ... >>> print range(10) # Should fail: no ellipsis
1253 ... [0, 1, ..., 9]
1254 ...
Edward Loper74bca7a2004-08-12 02:27:44 +00001255 ... >>> print range(10) # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001256 ... [0, 1, ..., 9]
1257 ...
Tim Peters8485b562004-08-04 18:46:34 +00001258 ... >>> print range(10) # Should fail: no ellipsis
1259 ... [0, 1, ..., 9]
1260 ... '''
1261 >>> test = doctest.DocTestFinder().find(f)[0]
1262 >>> doctest.DocTestRunner(verbose=False).run(test)
1263 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001264 Line 2, in f
1265 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]
Tim Peters8485b562004-08-04 18:46:34 +00001271 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001272 Line 8, in f
1273 Failed example:
1274 print range(10) # Should fail: no ellipsis
1275 Expected:
1276 [0, 1, ..., 9]
1277 Got:
1278 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001279 (2, 3)
1280
Edward Loper74bca7a2004-08-12 02:27:44 +00001281Multiple options may be modified by a single option directive. They
1282may be separated by whitespace, commas, or both:
Tim Peters8485b562004-08-04 18:46:34 +00001283
1284 >>> def f(x): r'''
1285 ... >>> print range(10) # Should fail
1286 ... [0, 1, ..., 9]
Tim Peters8485b562004-08-04 18:46:34 +00001287 ... >>> print range(10) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001288 ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001289 ... [0, 1, ..., 9]
1290 ... '''
1291 >>> test = doctest.DocTestFinder().find(f)[0]
1292 >>> doctest.DocTestRunner(verbose=False).run(test)
1293 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001294 Line 2, in f
1295 Failed example:
1296 print range(10) # Should fail
1297 Expected:
1298 [0, 1, ..., 9]
1299 Got:
1300 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001301 (1, 2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001302
1303 >>> def f(x): r'''
1304 ... >>> print range(10) # Should fail
1305 ... [0, 1, ..., 9]
1306 ... >>> print range(10) # Should succeed
1307 ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
1308 ... [0, 1, ..., 9]
1309 ... '''
1310 >>> test = doctest.DocTestFinder().find(f)[0]
1311 >>> doctest.DocTestRunner(verbose=False).run(test)
1312 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001313 Line 2, in f
1314 Failed example:
1315 print range(10) # Should fail
1316 Expected:
1317 [0, 1, ..., 9]
1318 Got:
1319 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001320 (1, 2)
1321
1322 >>> def f(x): r'''
1323 ... >>> print range(10) # Should fail
1324 ... [0, 1, ..., 9]
1325 ... >>> print range(10) # Should succeed
1326 ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1327 ... [0, 1, ..., 9]
1328 ... '''
1329 >>> test = doctest.DocTestFinder().find(f)[0]
1330 >>> doctest.DocTestRunner(verbose=False).run(test)
1331 **********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00001332 Line 2, in f
1333 Failed example:
1334 print range(10) # Should fail
1335 Expected:
1336 [0, 1, ..., 9]
1337 Got:
1338 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001339 (1, 2)
1340
1341The option directive may be put on the line following the source, as
1342long as a continuation prompt is used:
1343
1344 >>> def f(x): r'''
1345 ... >>> print range(10)
1346 ... ... # doctest: +ELLIPSIS
1347 ... [0, 1, ..., 9]
1348 ... '''
1349 >>> test = doctest.DocTestFinder().find(f)[0]
1350 >>> doctest.DocTestRunner(verbose=False).run(test)
1351 (0, 1)
Edward Loper8e4a34b2004-08-12 02:34:27 +00001352
Edward Loper74bca7a2004-08-12 02:27:44 +00001353For examples with multi-line source, the option directive may appear
1354at the end of any line:
1355
1356 >>> def f(x): r'''
1357 ... >>> for x in range(10): # doctest: +ELLIPSIS
1358 ... ... print x,
1359 ... 0 1 2 ... 9
1360 ...
1361 ... >>> for x in range(10):
1362 ... ... print x, # doctest: +ELLIPSIS
1363 ... 0 1 2 ... 9
1364 ... '''
1365 >>> test = doctest.DocTestFinder().find(f)[0]
1366 >>> doctest.DocTestRunner(verbose=False).run(test)
1367 (0, 2)
1368
1369If more than one line of an example with multi-line source has an
1370option directive, then they are combined:
1371
1372 >>> def f(x): r'''
1373 ... Should fail (option directive not on the last line):
1374 ... >>> for x in range(10): # doctest: +ELLIPSIS
1375 ... ... print x, # doctest: +NORMALIZE_WHITESPACE
1376 ... 0 1 2...9
1377 ... '''
1378 >>> test = doctest.DocTestFinder().find(f)[0]
1379 >>> doctest.DocTestRunner(verbose=False).run(test)
1380 (0, 1)
1381
1382It is an error to have a comment of the form ``# doctest:`` that is
1383*not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
1384``OPTION`` is an option that has been registered with
1385`register_option`:
1386
1387 >>> # Error: Option not registered
1388 >>> s = '>>> print 12 #doctest: +BADOPTION'
1389 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1390 Traceback (most recent call last):
1391 ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
1392
1393 >>> # Error: No + or - prefix
1394 >>> s = '>>> print 12 #doctest: ELLIPSIS'
1395 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1396 Traceback (most recent call last):
1397 ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
1398
1399It is an error to use an option directive on a line that contains no
1400source:
1401
1402 >>> s = '>>> # doctest: +ELLIPSIS'
1403 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1404 Traceback (most recent call last):
1405 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 +00001406"""
1407
1408def test_testsource(): r"""
1409Unit tests for `testsource()`.
1410
1411The testsource() function takes a module and a name, finds the (first)
Tim Peters19397e52004-08-06 22:02:59 +00001412test with that name in that module, and converts it to a script. The
1413example code is converted to regular Python code. The surrounding
1414words and expected output are converted to comments:
Tim Peters8485b562004-08-04 18:46:34 +00001415
1416 >>> import test.test_doctest
1417 >>> name = 'test.test_doctest.sample_func'
1418 >>> print doctest.testsource(test.test_doctest, name)
Edward Lopera5db6002004-08-12 02:41:30 +00001419 # Blah blah
Tim Peters19397e52004-08-06 22:02:59 +00001420 #
Tim Peters8485b562004-08-04 18:46:34 +00001421 print sample_func(22)
1422 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001423 ## 44
Tim Peters19397e52004-08-06 22:02:59 +00001424 #
Edward Lopera5db6002004-08-12 02:41:30 +00001425 # Yee ha!
Tim Peters8485b562004-08-04 18:46:34 +00001426
1427 >>> name = 'test.test_doctest.SampleNewStyleClass'
1428 >>> print doctest.testsource(test.test_doctest, name)
1429 print '1\n2\n3'
1430 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001431 ## 1
1432 ## 2
1433 ## 3
Tim Peters8485b562004-08-04 18:46:34 +00001434
1435 >>> name = 'test.test_doctest.SampleClass.a_classmethod'
1436 >>> print doctest.testsource(test.test_doctest, name)
1437 print SampleClass.a_classmethod(10)
1438 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001439 ## 12
Tim Peters8485b562004-08-04 18:46:34 +00001440 print SampleClass(0).a_classmethod(10)
1441 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001442 ## 12
Tim Peters8485b562004-08-04 18:46:34 +00001443"""
1444
1445def test_debug(): r"""
1446
1447Create a docstring that we want to debug:
1448
1449 >>> s = '''
1450 ... >>> x = 12
1451 ... >>> print x
1452 ... 12
1453 ... '''
1454
1455Create some fake stdin input, to feed to the debugger:
1456
1457 >>> import tempfile
Tim Peters8485b562004-08-04 18:46:34 +00001458 >>> real_stdin = sys.stdin
Edward Loper2de91ba2004-08-27 02:07:46 +00001459 >>> sys.stdin = _FakeInput(['next', 'print x', 'continue'])
Tim Peters8485b562004-08-04 18:46:34 +00001460
1461Run the debugger on the docstring, and then restore sys.stdin.
1462
Edward Loper2de91ba2004-08-27 02:07:46 +00001463 >>> try: doctest.debug_src(s)
1464 ... finally: sys.stdin = real_stdin
Tim Peters8485b562004-08-04 18:46:34 +00001465 > <string>(1)?()
Edward Loper2de91ba2004-08-27 02:07:46 +00001466 (Pdb) next
1467 12
Tim Peters8485b562004-08-04 18:46:34 +00001468 --Return--
1469 > <string>(1)?()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001470 (Pdb) print x
1471 12
1472 (Pdb) continue
Tim Peters8485b562004-08-04 18:46:34 +00001473
1474"""
1475
Jim Fulton356fd192004-08-09 11:34:47 +00001476def test_pdb_set_trace():
Edward Loper2de91ba2004-08-27 02:07:46 +00001477 # Note: this should *not* be an r'...' string, because we need
1478 # to use '\t' for the output of ...
1479 """Using pdb.set_trace from a doctest
Jim Fulton356fd192004-08-09 11:34:47 +00001480
Tim Peters413ced62004-08-09 15:43:47 +00001481 You can use pdb.set_trace from a doctest. To do so, you must
Jim Fulton356fd192004-08-09 11:34:47 +00001482 retrieve the set_trace function from the pdb module at the time
Tim Peters413ced62004-08-09 15:43:47 +00001483 you use it. The doctest module changes sys.stdout so that it can
1484 capture program output. It also temporarily replaces pdb.set_trace
1485 with a version that restores stdout. This is necessary for you to
Jim Fulton356fd192004-08-09 11:34:47 +00001486 see debugger output.
1487
1488 >>> doc = '''
1489 ... >>> x = 42
1490 ... >>> import pdb; pdb.set_trace()
1491 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001492 >>> parser = doctest.DocTestParser()
1493 >>> test = parser.get_doctest(doc, {}, "foo", "foo.py", 0)
Jim Fulton356fd192004-08-09 11:34:47 +00001494 >>> runner = doctest.DocTestRunner(verbose=False)
1495
1496 To demonstrate this, we'll create a fake standard input that
1497 captures our debugger input:
1498
1499 >>> import tempfile
Edward Loper2de91ba2004-08-27 02:07:46 +00001500 >>> real_stdin = sys.stdin
1501 >>> sys.stdin = _FakeInput([
Jim Fulton356fd192004-08-09 11:34:47 +00001502 ... 'print x', # print data defined by the example
1503 ... 'continue', # stop debugging
Edward Loper2de91ba2004-08-27 02:07:46 +00001504 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001505
Edward Loper2de91ba2004-08-27 02:07:46 +00001506 >>> try: runner.run(test)
1507 ... finally: sys.stdin = real_stdin
Jim Fulton356fd192004-08-09 11:34:47 +00001508 --Return--
Edward Loper2de91ba2004-08-27 02:07:46 +00001509 > <doctest foo[1]>(1)?()->None
1510 -> import pdb; pdb.set_trace()
1511 (Pdb) print x
1512 42
1513 (Pdb) continue
1514 (0, 2)
Jim Fulton356fd192004-08-09 11:34:47 +00001515
1516 You can also put pdb.set_trace in a function called from a test:
1517
1518 >>> def calls_set_trace():
1519 ... y=2
1520 ... import pdb; pdb.set_trace()
1521
1522 >>> doc = '''
1523 ... >>> x=1
1524 ... >>> calls_set_trace()
1525 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001526 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
Edward Loper2de91ba2004-08-27 02:07:46 +00001527 >>> real_stdin = sys.stdin
1528 >>> sys.stdin = _FakeInput([
Jim Fulton356fd192004-08-09 11:34:47 +00001529 ... 'print y', # print data defined in the function
1530 ... 'up', # out of function
1531 ... 'print x', # print data defined by the example
1532 ... 'continue', # stop debugging
Edward Loper2de91ba2004-08-27 02:07:46 +00001533 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001534
Edward Loper2de91ba2004-08-27 02:07:46 +00001535 >>> try: runner.run(test)
1536 ... finally: sys.stdin = real_stdin
Jim Fulton356fd192004-08-09 11:34:47 +00001537 --Return--
Edward Loper2de91ba2004-08-27 02:07:46 +00001538 > <doctest test.test_doctest.test_pdb_set_trace[8]>(3)calls_set_trace()->None
1539 -> import pdb; pdb.set_trace()
1540 (Pdb) print y
1541 2
1542 (Pdb) up
1543 > <doctest foo[1]>(1)?()
1544 -> calls_set_trace()
1545 (Pdb) print x
1546 1
1547 (Pdb) continue
1548 (0, 2)
1549
1550 During interactive debugging, source code is shown, even for
1551 doctest examples:
1552
1553 >>> doc = '''
1554 ... >>> def f(x):
1555 ... ... g(x*2)
1556 ... >>> def g(x):
1557 ... ... print x+3
1558 ... ... import pdb; pdb.set_trace()
1559 ... >>> f(3)
1560 ... '''
1561 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
1562 >>> real_stdin = sys.stdin
1563 >>> sys.stdin = _FakeInput([
1564 ... 'list', # list source from example 2
1565 ... 'next', # return from g()
1566 ... 'list', # list source from example 1
1567 ... 'next', # return from f()
1568 ... 'list', # list source from example 3
1569 ... 'continue', # stop debugging
1570 ... ''])
1571 >>> try: runner.run(test)
1572 ... finally: sys.stdin = real_stdin
1573 ... # doctest: +NORMALIZE_WHITESPACE
1574 --Return--
1575 > <doctest foo[1]>(3)g()->None
1576 -> import pdb; pdb.set_trace()
1577 (Pdb) list
1578 1 def g(x):
1579 2 print x+3
1580 3 -> import pdb; pdb.set_trace()
1581 [EOF]
1582 (Pdb) next
1583 --Return--
1584 > <doctest foo[0]>(2)f()->None
1585 -> g(x*2)
1586 (Pdb) list
1587 1 def f(x):
1588 2 -> g(x*2)
1589 [EOF]
1590 (Pdb) next
1591 --Return--
1592 > <doctest foo[2]>(1)?()->None
1593 -> f(3)
1594 (Pdb) list
1595 1 -> f(3)
1596 [EOF]
1597 (Pdb) continue
1598 **********************************************************************
1599 File "foo.py", line 7, in foo
1600 Failed example:
1601 f(3)
1602 Expected nothing
1603 Got:
1604 9
1605 (1, 3)
Jim Fulton356fd192004-08-09 11:34:47 +00001606 """
1607
Tim Peters19397e52004-08-06 22:02:59 +00001608def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +00001609 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +00001610
1611 We create a Suite by providing a module. A module can be provided
1612 by passing a module object:
1613
1614 >>> import unittest
1615 >>> import test.sample_doctest
1616 >>> suite = doctest.DocTestSuite(test.sample_doctest)
1617 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001618 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001619
1620 We can also supply the module by name:
1621
1622 >>> suite = doctest.DocTestSuite('test.sample_doctest')
1623 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001624 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001625
1626 We can use the current module:
1627
1628 >>> suite = test.sample_doctest.test_suite()
1629 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001630 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001631
1632 We can supply global variables. If we pass globs, they will be
1633 used instead of the module globals. Here we'll pass an empty
1634 globals, triggering an extra error:
1635
1636 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
1637 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001638 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001639
1640 Alternatively, we can provide extra globals. Here we'll make an
1641 error go away by providing an extra global variable:
1642
1643 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1644 ... extraglobs={'y': 1})
1645 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001646 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001647
1648 You can pass option flags. Here we'll cause an extra error
1649 by disabling the blank-line feature:
1650
1651 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00001652 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00001653 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001654 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001655
Tim Peters1e277ee2004-08-07 05:37:52 +00001656 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00001657
1658 >>> def setUp():
1659 ... import test.test_doctest
1660 ... test.test_doctest.sillySetup = True
1661
1662 >>> def tearDown():
1663 ... import test.test_doctest
1664 ... del test.test_doctest.sillySetup
1665
1666 Here, we installed a silly variable that the test expects:
1667
1668 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1669 ... setUp=setUp, tearDown=tearDown)
1670 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001671 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001672
1673 But the tearDown restores sanity:
1674
1675 >>> import test.test_doctest
1676 >>> test.test_doctest.sillySetup
1677 Traceback (most recent call last):
1678 ...
1679 AttributeError: 'module' object has no attribute 'sillySetup'
1680
1681 Finally, you can provide an alternate test finder. Here we'll
Tim Peters1e277ee2004-08-07 05:37:52 +00001682 use a custom test_finder to to run just the test named bar.
1683 However, the test in the module docstring, and the two tests
1684 in the module __test__ dict, aren't filtered, so we actually
1685 run three tests besides bar's. The filtering mechanisms are
1686 poorly conceived, and will go away someday.
Tim Peters19397e52004-08-06 22:02:59 +00001687
1688 >>> finder = doctest.DocTestFinder(
Tim Petersf727c6c2004-08-08 01:48:59 +00001689 ... _namefilter=lambda prefix, base: base!='bar')
Tim Peters19397e52004-08-06 22:02:59 +00001690 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1691 ... test_finder=finder)
1692 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001693 <unittest.TestResult run=4 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00001694 """
1695
1696def test_DocFileSuite():
1697 """We can test tests found in text files using a DocFileSuite.
1698
1699 We create a suite by providing the names of one or more text
1700 files that include examples:
1701
1702 >>> import unittest
1703 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1704 ... 'test_doctest2.txt')
1705 >>> suite.run(unittest.TestResult())
1706 <unittest.TestResult run=2 errors=0 failures=2>
1707
1708 The test files are looked for in the directory containing the
1709 calling module. A package keyword argument can be provided to
1710 specify a different relative location.
1711
1712 >>> import unittest
1713 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1714 ... 'test_doctest2.txt',
1715 ... package='test')
1716 >>> suite.run(unittest.TestResult())
1717 <unittest.TestResult run=2 errors=0 failures=2>
1718
1719 Note that '/' should be used as a path separator. It will be
1720 converted to a native separator at run time:
1721
1722
1723 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
1724 >>> suite.run(unittest.TestResult())
1725 <unittest.TestResult run=1 errors=0 failures=1>
1726
1727 You can specify initial global variables:
1728
1729 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1730 ... 'test_doctest2.txt',
1731 ... globs={'favorite_color': 'blue'})
1732 >>> suite.run(unittest.TestResult())
1733 <unittest.TestResult run=2 errors=0 failures=1>
1734
1735 In this case, we supplied a missing favorite color. You can
1736 provide doctest options:
1737
1738 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1739 ... 'test_doctest2.txt',
1740 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
1741 ... globs={'favorite_color': 'blue'})
1742 >>> suite.run(unittest.TestResult())
1743 <unittest.TestResult run=2 errors=0 failures=2>
1744
1745 And, you can provide setUp and tearDown functions:
1746
1747 You can supply setUp and teatDoen functions:
1748
1749 >>> def setUp():
1750 ... import test.test_doctest
1751 ... test.test_doctest.sillySetup = True
1752
1753 >>> def tearDown():
1754 ... import test.test_doctest
1755 ... del test.test_doctest.sillySetup
1756
1757 Here, we installed a silly variable that the test expects:
1758
1759 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1760 ... 'test_doctest2.txt',
1761 ... setUp=setUp, tearDown=tearDown)
1762 >>> suite.run(unittest.TestResult())
1763 <unittest.TestResult run=2 errors=0 failures=1>
1764
1765 But the tearDown restores sanity:
1766
1767 >>> import test.test_doctest
1768 >>> test.test_doctest.sillySetup
1769 Traceback (most recent call last):
1770 ...
1771 AttributeError: 'module' object has no attribute 'sillySetup'
1772
1773 """
1774
Jim Fulton07a349c2004-08-22 14:10:00 +00001775def test_trailing_space_in_test():
1776 """
Tim Petersa7def722004-08-23 22:13:22 +00001777 Trailing spaces in expected output are significant:
Tim Petersc6cbab02004-08-22 19:43:28 +00001778
Jim Fulton07a349c2004-08-22 14:10:00 +00001779 >>> x, y = 'foo', ''
1780 >>> print x, y
1781 foo \n
1782 """
Tim Peters19397e52004-08-06 22:02:59 +00001783
Tim Petersa7def722004-08-23 22:13:22 +00001784# old_test1, ... used to live in doctest.py, but cluttered it. Note
1785# that these use the deprecated doctest.Tester, so should go away (or
1786# be rewritten) someday.
1787
1788# Ignore all warnings about the use of class Tester in this module.
1789# Note that the name of this module may differ depending on how it's
1790# imported, so the use of __name__ is important.
1791warnings.filterwarnings("ignore", "class Tester", DeprecationWarning,
1792 __name__, 0)
1793
1794def old_test1(): r"""
1795>>> from doctest import Tester
1796>>> t = Tester(globs={'x': 42}, verbose=0)
1797>>> t.runstring(r'''
1798... >>> x = x * 2
1799... >>> print x
1800... 42
1801... ''', 'XYZ')
1802**********************************************************************
1803Line 3, in XYZ
1804Failed example:
1805 print x
1806Expected:
1807 42
1808Got:
1809 84
1810(1, 2)
1811>>> t.runstring(">>> x = x * 2\n>>> print x\n84\n", 'example2')
1812(0, 2)
1813>>> t.summarize()
1814**********************************************************************
18151 items had failures:
1816 1 of 2 in XYZ
1817***Test Failed*** 1 failures.
1818(1, 4)
1819>>> t.summarize(verbose=1)
18201 items passed all tests:
1821 2 tests in example2
1822**********************************************************************
18231 items had failures:
1824 1 of 2 in XYZ
18254 tests in 2 items.
18263 passed and 1 failed.
1827***Test Failed*** 1 failures.
1828(1, 4)
1829"""
1830
1831def old_test2(): r"""
1832 >>> from doctest import Tester
1833 >>> t = Tester(globs={}, verbose=1)
1834 >>> test = r'''
1835 ... # just an example
1836 ... >>> x = 1 + 2
1837 ... >>> x
1838 ... 3
1839 ... '''
1840 >>> t.runstring(test, "Example")
1841 Running string Example
Edward Loperaacf0832004-08-26 01:19:50 +00001842 Trying:
1843 x = 1 + 2
1844 Expecting nothing
Tim Petersa7def722004-08-23 22:13:22 +00001845 ok
Edward Loperaacf0832004-08-26 01:19:50 +00001846 Trying:
1847 x
1848 Expecting:
1849 3
Tim Petersa7def722004-08-23 22:13:22 +00001850 ok
1851 0 of 2 examples failed in string Example
1852 (0, 2)
1853"""
1854
1855def old_test3(): r"""
1856 >>> from doctest import Tester
1857 >>> t = Tester(globs={}, verbose=0)
1858 >>> def _f():
1859 ... '''Trivial docstring example.
1860 ... >>> assert 2 == 2
1861 ... '''
1862 ... return 32
1863 ...
1864 >>> t.rundoc(_f) # expect 0 failures in 1 example
1865 (0, 1)
1866"""
1867
1868def old_test4(): """
1869 >>> import new
1870 >>> m1 = new.module('_m1')
1871 >>> m2 = new.module('_m2')
1872 >>> test_data = \"""
1873 ... def _f():
1874 ... '''>>> assert 1 == 1
1875 ... '''
1876 ... def g():
1877 ... '''>>> assert 2 != 1
1878 ... '''
1879 ... class H:
1880 ... '''>>> assert 2 > 1
1881 ... '''
1882 ... def bar(self):
1883 ... '''>>> assert 1 < 2
1884 ... '''
1885 ... \"""
1886 >>> exec test_data in m1.__dict__
1887 >>> exec test_data in m2.__dict__
1888 >>> m1.__dict__.update({"f2": m2._f, "g2": m2.g, "h2": m2.H})
1889
1890 Tests that objects outside m1 are excluded:
1891
1892 >>> from doctest import Tester
1893 >>> t = Tester(globs={}, verbose=0)
1894 >>> t.rundict(m1.__dict__, "rundict_test", m1) # f2 and g2 and h2 skipped
1895 (0, 4)
1896
1897 Once more, not excluding stuff outside m1:
1898
1899 >>> t = Tester(globs={}, verbose=0)
1900 >>> t.rundict(m1.__dict__, "rundict_test_pvt") # None are skipped.
1901 (0, 8)
1902
1903 The exclusion of objects from outside the designated module is
1904 meant to be invoked automagically by testmod.
1905
1906 >>> doctest.testmod(m1, verbose=False)
1907 (0, 4)
1908"""
1909
Tim Peters8485b562004-08-04 18:46:34 +00001910######################################################################
1911## Main
1912######################################################################
1913
1914def test_main():
1915 # Check the doctest cases in doctest itself:
1916 test_support.run_doctest(doctest, verbosity=True)
1917 # Check the doctest cases defined here:
1918 from test import test_doctest
1919 test_support.run_doctest(test_doctest, verbosity=True)
1920
1921import trace, sys, re, StringIO
1922def test_coverage(coverdir):
1923 tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
1924 trace=0, count=1)
1925 tracer.run('reload(doctest); test_main()')
1926 r = tracer.results()
1927 print 'Writing coverage results...'
1928 r.write_results(show_missing=True, summary=True,
1929 coverdir=coverdir)
1930
1931if __name__ == '__main__':
1932 if '-c' in sys.argv:
1933 test_coverage('/tmp/doctest.cover')
1934 else:
1935 test_main()