blob: f5a328eaad176635407e4b7128b851ec06bc2267 [file] [log] [blame]
Florent Xiclunab6d80cc2010-02-27 14:34:41 +00001# -*- coding: utf-8 -*-
Tim Peters8485b562004-08-04 18:46:34 +00002"""
3Test script for doctest.
4"""
5
Barry Warsaw04f357c2002-07-23 19:04:11 +00006from test import test_support
Tim Peters8485b562004-08-04 18:46:34 +00007import doctest
Tim Petersa7def722004-08-23 22:13:22 +00008import warnings
Tim Peters8485b562004-08-04 18:46:34 +00009
Nick Coghlan30327242008-12-14 11:30:16 +000010# NOTE: There are some additional tests relating to interaction with
11# zipimport in the test_zipimport_support test module.
12
Tim Peters8485b562004-08-04 18:46:34 +000013######################################################################
14## Sample Objects (used by test cases)
15######################################################################
16
17def sample_func(v):
18 """
Tim Peters19397e52004-08-06 22:02:59 +000019 Blah blah
20
Tim Peters8485b562004-08-04 18:46:34 +000021 >>> print sample_func(22)
22 44
Tim Peters19397e52004-08-06 22:02:59 +000023
24 Yee ha!
Tim Peters8485b562004-08-04 18:46:34 +000025 """
26 return v+v
27
28class SampleClass:
29 """
30 >>> print 1
31 1
Edward Loper4ae900f2004-09-21 03:20:34 +000032
33 >>> # comments get ignored. so are empty PS1 and PS2 prompts:
34 >>>
35 ...
36
37 Multiline example:
38 >>> sc = SampleClass(3)
39 >>> for i in range(10):
40 ... sc = sc.double()
41 ... print sc.get(),
42 6 12 24 48 96 192 384 768 1536 3072
Tim Peters8485b562004-08-04 18:46:34 +000043 """
44 def __init__(self, val):
45 """
46 >>> print SampleClass(12).get()
47 12
48 """
49 self.val = val
50
51 def double(self):
52 """
53 >>> print SampleClass(12).double().get()
54 24
55 """
56 return SampleClass(self.val + self.val)
57
58 def get(self):
59 """
60 >>> print SampleClass(-5).get()
61 -5
62 """
63 return self.val
64
65 def a_staticmethod(v):
66 """
67 >>> print SampleClass.a_staticmethod(10)
68 11
69 """
70 return v+1
71 a_staticmethod = staticmethod(a_staticmethod)
72
73 def a_classmethod(cls, v):
74 """
75 >>> print SampleClass.a_classmethod(10)
76 12
77 >>> print SampleClass(0).a_classmethod(10)
78 12
79 """
80 return v+2
81 a_classmethod = classmethod(a_classmethod)
82
83 a_property = property(get, doc="""
84 >>> print SampleClass(22).a_property
85 22
86 """)
87
88 class NestedClass:
89 """
90 >>> x = SampleClass.NestedClass(5)
91 >>> y = x.square()
92 >>> print y.get()
93 25
94 """
95 def __init__(self, val=0):
96 """
97 >>> print SampleClass.NestedClass().get()
98 0
99 """
100 self.val = val
101 def square(self):
102 return SampleClass.NestedClass(self.val*self.val)
103 def get(self):
104 return self.val
105
106class SampleNewStyleClass(object):
107 r"""
108 >>> print '1\n2\n3'
109 1
110 2
111 3
112 """
113 def __init__(self, val):
114 """
115 >>> print SampleNewStyleClass(12).get()
116 12
117 """
118 self.val = val
119
120 def double(self):
121 """
122 >>> print SampleNewStyleClass(12).double().get()
123 24
124 """
125 return SampleNewStyleClass(self.val + self.val)
126
127 def get(self):
128 """
129 >>> print SampleNewStyleClass(-5).get()
130 -5
131 """
132 return self.val
133
134######################################################################
Edward Loper2de91ba2004-08-27 02:07:46 +0000135## Fake stdin (for testing interactive debugging)
136######################################################################
137
138class _FakeInput:
139 """
140 A fake input stream for pdb's interactive debugger. Whenever a
141 line is read, print it (to simulate the user typing it), and then
142 return it. The set of lines to return is specified in the
143 constructor; they should not have trailing newlines.
144 """
145 def __init__(self, lines):
146 self.lines = lines
147
148 def readline(self):
149 line = self.lines.pop(0)
150 print line
151 return line+'\n'
152
153######################################################################
Tim Peters8485b562004-08-04 18:46:34 +0000154## Test Cases
155######################################################################
156
157def test_Example(): r"""
158Unit tests for the `Example` class.
159
Edward Lopera6b68322004-08-26 00:05:43 +0000160Example is a simple container class that holds:
161 - `source`: A source string.
162 - `want`: An expected output string.
163 - `exc_msg`: An expected exception message string (or None if no
164 exception is expected).
165 - `lineno`: A line number (within the docstring).
166 - `indent`: The example's indentation in the input string.
167 - `options`: An option dictionary, mapping option flags to True or
168 False.
Tim Peters8485b562004-08-04 18:46:34 +0000169
Edward Lopera6b68322004-08-26 00:05:43 +0000170These attributes are set by the constructor. `source` and `want` are
171required; the other attributes all have default values:
Tim Peters8485b562004-08-04 18:46:34 +0000172
Edward Lopera6b68322004-08-26 00:05:43 +0000173 >>> example = doctest.Example('print 1', '1\n')
174 >>> (example.source, example.want, example.exc_msg,
175 ... example.lineno, example.indent, example.options)
176 ('print 1\n', '1\n', None, 0, 0, {})
177
178The first three attributes (`source`, `want`, and `exc_msg`) may be
179specified positionally; the remaining arguments should be specified as
180keyword arguments:
181
182 >>> exc_msg = 'IndexError: pop from an empty list'
183 >>> example = doctest.Example('[].pop()', '', exc_msg,
184 ... lineno=5, indent=4,
185 ... options={doctest.ELLIPSIS: True})
186 >>> (example.source, example.want, example.exc_msg,
187 ... example.lineno, example.indent, example.options)
188 ('[].pop()\n', '', 'IndexError: pop from an empty list\n', 5, 4, {8: True})
189
190The constructor normalizes the `source` string to end in a newline:
Tim Peters8485b562004-08-04 18:46:34 +0000191
Tim Petersbb431472004-08-09 03:51:46 +0000192 Source spans a single line: no terminating newline.
Edward Lopera6b68322004-08-26 00:05:43 +0000193 >>> e = doctest.Example('print 1', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000194 >>> e.source, e.want
195 ('print 1\n', '1\n')
196
Edward Lopera6b68322004-08-26 00:05:43 +0000197 >>> e = doctest.Example('print 1\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000198 >>> e.source, e.want
199 ('print 1\n', '1\n')
Tim Peters8485b562004-08-04 18:46:34 +0000200
Tim Petersbb431472004-08-09 03:51:46 +0000201 Source spans multiple lines: require terminating newline.
Edward Lopera6b68322004-08-26 00:05:43 +0000202 >>> e = doctest.Example('print 1;\nprint 2\n', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000203 >>> e.source, e.want
204 ('print 1;\nprint 2\n', '1\n2\n')
Tim Peters8485b562004-08-04 18:46:34 +0000205
Edward Lopera6b68322004-08-26 00:05:43 +0000206 >>> e = doctest.Example('print 1;\nprint 2', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000207 >>> e.source, e.want
208 ('print 1;\nprint 2\n', '1\n2\n')
209
Edward Lopera6b68322004-08-26 00:05:43 +0000210 Empty source string (which should never appear in real examples)
211 >>> e = doctest.Example('', '')
212 >>> e.source, e.want
213 ('\n', '')
Tim Peters8485b562004-08-04 18:46:34 +0000214
Edward Lopera6b68322004-08-26 00:05:43 +0000215The constructor normalizes the `want` string to end in a newline,
216unless it's the empty string:
217
218 >>> e = doctest.Example('print 1', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000219 >>> e.source, e.want
220 ('print 1\n', '1\n')
221
Edward Lopera6b68322004-08-26 00:05:43 +0000222 >>> e = doctest.Example('print 1', '1')
Tim Petersbb431472004-08-09 03:51:46 +0000223 >>> e.source, e.want
224 ('print 1\n', '1\n')
225
Edward Lopera6b68322004-08-26 00:05:43 +0000226 >>> e = doctest.Example('print', '')
Tim Petersbb431472004-08-09 03:51:46 +0000227 >>> e.source, e.want
228 ('print\n', '')
Edward Lopera6b68322004-08-26 00:05:43 +0000229
230The constructor normalizes the `exc_msg` string to end in a newline,
231unless it's `None`:
232
233 Message spans one line
234 >>> exc_msg = 'IndexError: pop from an empty list'
235 >>> e = doctest.Example('[].pop()', '', exc_msg)
236 >>> e.exc_msg
237 'IndexError: pop from an empty list\n'
238
239 >>> exc_msg = 'IndexError: pop from an empty list\n'
240 >>> e = doctest.Example('[].pop()', '', exc_msg)
241 >>> e.exc_msg
242 'IndexError: pop from an empty list\n'
243
244 Message spans multiple lines
245 >>> exc_msg = 'ValueError: 1\n 2'
246 >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
247 >>> e.exc_msg
248 'ValueError: 1\n 2\n'
249
250 >>> exc_msg = 'ValueError: 1\n 2\n'
251 >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
252 >>> e.exc_msg
253 'ValueError: 1\n 2\n'
254
255 Empty (but non-None) exception message (which should never appear
256 in real examples)
257 >>> exc_msg = ''
258 >>> e = doctest.Example('raise X()', '', exc_msg)
259 >>> e.exc_msg
260 '\n'
Tim Peters8485b562004-08-04 18:46:34 +0000261"""
262
263def test_DocTest(): r"""
264Unit tests for the `DocTest` class.
265
266DocTest is a collection of examples, extracted from a docstring, along
267with information about where the docstring comes from (a name,
268filename, and line number). The docstring is parsed by the `DocTest`
269constructor:
270
271 >>> docstring = '''
272 ... >>> print 12
273 ... 12
274 ...
275 ... Non-example text.
276 ...
277 ... >>> print 'another\example'
278 ... another
279 ... example
280 ... '''
281 >>> globs = {} # globals to run the test in.
Edward Lopera1ef6112004-08-09 16:14:41 +0000282 >>> parser = doctest.DocTestParser()
283 >>> test = parser.get_doctest(docstring, globs, 'some_test',
284 ... 'some_file', 20)
Tim Peters8485b562004-08-04 18:46:34 +0000285 >>> print test
286 <DocTest some_test from some_file:20 (2 examples)>
287 >>> len(test.examples)
288 2
289 >>> e1, e2 = test.examples
290 >>> (e1.source, e1.want, e1.lineno)
Tim Petersbb431472004-08-09 03:51:46 +0000291 ('print 12\n', '12\n', 1)
Tim Peters8485b562004-08-04 18:46:34 +0000292 >>> (e2.source, e2.want, e2.lineno)
Tim Petersbb431472004-08-09 03:51:46 +0000293 ("print 'another\\example'\n", 'another\nexample\n', 6)
Tim Peters8485b562004-08-04 18:46:34 +0000294
295Source information (name, filename, and line number) is available as
296attributes on the doctest object:
297
298 >>> (test.name, test.filename, test.lineno)
299 ('some_test', 'some_file', 20)
300
301The line number of an example within its containing file is found by
302adding the line number of the example and the line number of its
303containing test:
304
305 >>> test.lineno + e1.lineno
306 21
307 >>> test.lineno + e2.lineno
308 26
309
310If the docstring contains inconsistant leading whitespace in the
311expected output of an example, then `DocTest` will raise a ValueError:
312
313 >>> docstring = r'''
314 ... >>> print 'bad\nindentation'
315 ... bad
316 ... indentation
317 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000318 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000319 Traceback (most recent call last):
Edward Loper00f8da72004-08-26 18:05:07 +0000320 ValueError: line 4 of the docstring for some_test has inconsistent leading whitespace: 'indentation'
Tim Peters8485b562004-08-04 18:46:34 +0000321
322If the docstring contains inconsistent leading whitespace on
323continuation lines, then `DocTest` will raise a ValueError:
324
325 >>> docstring = r'''
326 ... >>> print ('bad indentation',
327 ... ... 2)
328 ... ('bad', 'indentation')
329 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000330 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000331 Traceback (most recent call last):
Edward Loper00f8da72004-08-26 18:05:07 +0000332 ValueError: line 2 of the docstring for some_test has inconsistent leading whitespace: '... 2)'
Tim Peters8485b562004-08-04 18:46:34 +0000333
334If there's no blank space after a PS1 prompt ('>>>'), then `DocTest`
335will raise a ValueError:
336
337 >>> docstring = '>>>print 1\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000338 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000339 Traceback (most recent call last):
Edward Loper7c748462004-08-09 02:06:06 +0000340 ValueError: line 1 of the docstring for some_test lacks blank after >>>: '>>>print 1'
341
342If there's no blank space after a PS2 prompt ('...'), then `DocTest`
343will raise a ValueError:
344
345 >>> docstring = '>>> if 1:\n...print 1\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000346 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Edward Loper7c748462004-08-09 02:06:06 +0000347 Traceback (most recent call last):
348 ValueError: line 2 of the docstring for some_test lacks blank after ...: '...print 1'
349
Tim Peters8485b562004-08-04 18:46:34 +0000350"""
351
Tim Peters8485b562004-08-04 18:46:34 +0000352def test_DocTestFinder(): r"""
353Unit tests for the `DocTestFinder` class.
354
355DocTestFinder is used to extract DocTests from an object's docstring
356and the docstrings of its contained objects. It can be used with
357modules, functions, classes, methods, staticmethods, classmethods, and
358properties.
359
360Finding Tests in Functions
361~~~~~~~~~~~~~~~~~~~~~~~~~~
362For a function whose docstring contains examples, DocTestFinder.find()
363will return a single test (for that function's docstring):
364
Tim Peters8485b562004-08-04 18:46:34 +0000365 >>> finder = doctest.DocTestFinder()
Jim Fulton07a349c2004-08-22 14:10:00 +0000366
367We'll simulate a __file__ attr that ends in pyc:
368
369 >>> import test.test_doctest
370 >>> old = test.test_doctest.__file__
371 >>> test.test_doctest.__file__ = 'test_doctest.pyc'
372
Tim Peters8485b562004-08-04 18:46:34 +0000373 >>> tests = finder.find(sample_func)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000374
Edward Loper74bca7a2004-08-12 02:27:44 +0000375 >>> print tests # doctest: +ELLIPSIS
Florent Xiclunab6d80cc2010-02-27 14:34:41 +0000376 [<DocTest sample_func from ...:17 (1 example)>]
Edward Loper8e4a34b2004-08-12 02:34:27 +0000377
Tim Peters4de7c5c2004-08-23 22:38:05 +0000378The exact name depends on how test_doctest was invoked, so allow for
379leading path components.
380
381 >>> tests[0].filename # doctest: +ELLIPSIS
382 '...test_doctest.py'
Jim Fulton07a349c2004-08-22 14:10:00 +0000383
384 >>> test.test_doctest.__file__ = old
Tim Petersc6cbab02004-08-22 19:43:28 +0000385
Jim Fulton07a349c2004-08-22 14:10:00 +0000386
Tim Peters8485b562004-08-04 18:46:34 +0000387 >>> e = tests[0].examples[0]
Tim Petersbb431472004-08-09 03:51:46 +0000388 >>> (e.source, e.want, e.lineno)
389 ('print sample_func(22)\n', '44\n', 3)
Tim Peters8485b562004-08-04 18:46:34 +0000390
Edward Loper32ddbf72004-09-13 05:47:24 +0000391By default, tests are created for objects with no docstring:
Tim Peters8485b562004-08-04 18:46:34 +0000392
393 >>> def no_docstring(v):
394 ... pass
Tim Peters958cc892004-09-13 14:53:28 +0000395 >>> finder.find(no_docstring)
396 []
Edward Loper32ddbf72004-09-13 05:47:24 +0000397
398However, the optional argument `exclude_empty` to the DocTestFinder
399constructor can be used to exclude tests for objects with empty
400docstrings:
401
402 >>> def no_docstring(v):
403 ... pass
404 >>> excl_empty_finder = doctest.DocTestFinder(exclude_empty=True)
405 >>> excl_empty_finder.find(no_docstring)
Tim Peters8485b562004-08-04 18:46:34 +0000406 []
407
408If the function has a docstring with no examples, then a test with no
409examples is returned. (This lets `DocTestRunner` collect statistics
410about which functions have no tests -- but is that useful? And should
411an empty test also be created when there's no docstring?)
412
413 >>> def no_examples(v):
414 ... ''' no doctest examples '''
Tim Peters17b56372004-09-11 17:33:27 +0000415 >>> finder.find(no_examples) # doctest: +ELLIPSIS
416 [<DocTest no_examples from ...:1 (no examples)>]
Tim Peters8485b562004-08-04 18:46:34 +0000417
418Finding Tests in Classes
419~~~~~~~~~~~~~~~~~~~~~~~~
420For a class, DocTestFinder will create a test for the class's
421docstring, and will recursively explore its contents, including
422methods, classmethods, staticmethods, properties, and nested classes.
423
424 >>> finder = doctest.DocTestFinder()
425 >>> tests = finder.find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000426 >>> for t in tests:
427 ... print '%2s %s' % (len(t.examples), t.name)
Edward Loper4ae900f2004-09-21 03:20:34 +0000428 3 SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000429 3 SampleClass.NestedClass
430 1 SampleClass.NestedClass.__init__
431 1 SampleClass.__init__
432 2 SampleClass.a_classmethod
433 1 SampleClass.a_property
434 1 SampleClass.a_staticmethod
435 1 SampleClass.double
436 1 SampleClass.get
437
438New-style classes are also supported:
439
440 >>> tests = finder.find(SampleNewStyleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000441 >>> for t in tests:
442 ... print '%2s %s' % (len(t.examples), t.name)
443 1 SampleNewStyleClass
444 1 SampleNewStyleClass.__init__
445 1 SampleNewStyleClass.double
446 1 SampleNewStyleClass.get
447
448Finding Tests in Modules
449~~~~~~~~~~~~~~~~~~~~~~~~
450For a module, DocTestFinder will create a test for the class's
451docstring, and will recursively explore its contents, including
452functions, classes, and the `__test__` dictionary, if it exists:
453
454 >>> # A module
Christian Heimesc756d002007-11-27 21:34:01 +0000455 >>> import types
456 >>> m = types.ModuleType('some_module')
Tim Peters8485b562004-08-04 18:46:34 +0000457 >>> def triple(val):
458 ... '''
Edward Loper4ae900f2004-09-21 03:20:34 +0000459 ... >>> print triple(11)
Tim Peters8485b562004-08-04 18:46:34 +0000460 ... 33
461 ... '''
462 ... return val*3
463 >>> m.__dict__.update({
464 ... 'sample_func': sample_func,
465 ... 'SampleClass': SampleClass,
466 ... '__doc__': '''
467 ... Module docstring.
468 ... >>> print 'module'
469 ... module
470 ... ''',
471 ... '__test__': {
472 ... 'd': '>>> print 6\n6\n>>> print 7\n7\n',
473 ... 'c': triple}})
474
475 >>> finder = doctest.DocTestFinder()
476 >>> # Use module=test.test_doctest, to prevent doctest from
477 >>> # ignoring the objects since they weren't defined in m.
478 >>> import test.test_doctest
479 >>> tests = finder.find(m, module=test.test_doctest)
Tim Peters8485b562004-08-04 18:46:34 +0000480 >>> for t in tests:
481 ... print '%2s %s' % (len(t.examples), t.name)
482 1 some_module
Edward Loper4ae900f2004-09-21 03:20:34 +0000483 3 some_module.SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000484 3 some_module.SampleClass.NestedClass
485 1 some_module.SampleClass.NestedClass.__init__
486 1 some_module.SampleClass.__init__
487 2 some_module.SampleClass.a_classmethod
488 1 some_module.SampleClass.a_property
489 1 some_module.SampleClass.a_staticmethod
490 1 some_module.SampleClass.double
491 1 some_module.SampleClass.get
Tim Petersc5684782004-09-13 01:07:12 +0000492 1 some_module.__test__.c
493 2 some_module.__test__.d
Tim Peters8485b562004-08-04 18:46:34 +0000494 1 some_module.sample_func
495
496Duplicate Removal
497~~~~~~~~~~~~~~~~~
498If a single object is listed twice (under different names), then tests
499will only be generated for it once:
500
Tim Petersf3f57472004-08-08 06:11:48 +0000501 >>> from test import doctest_aliases
Edward Loper32ddbf72004-09-13 05:47:24 +0000502 >>> tests = excl_empty_finder.find(doctest_aliases)
Tim Peters8485b562004-08-04 18:46:34 +0000503 >>> print len(tests)
504 2
505 >>> print tests[0].name
Tim Petersf3f57472004-08-08 06:11:48 +0000506 test.doctest_aliases.TwoNames
507
508 TwoNames.f and TwoNames.g are bound to the same object.
509 We can't guess which will be found in doctest's traversal of
510 TwoNames.__dict__ first, so we have to allow for either.
511
512 >>> tests[1].name.split('.')[-1] in ['f', 'g']
Tim Peters8485b562004-08-04 18:46:34 +0000513 True
514
Tim Petersbf0400a2006-06-05 01:43:03 +0000515Empty Tests
516~~~~~~~~~~~
517By default, an object with no doctests doesn't create any tests:
Tim Peters8485b562004-08-04 18:46:34 +0000518
Tim Petersbf0400a2006-06-05 01:43:03 +0000519 >>> tests = doctest.DocTestFinder().find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000520 >>> for t in tests:
521 ... print '%2s %s' % (len(t.examples), t.name)
Edward Loper4ae900f2004-09-21 03:20:34 +0000522 3 SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000523 3 SampleClass.NestedClass
524 1 SampleClass.NestedClass.__init__
Tim Peters958cc892004-09-13 14:53:28 +0000525 1 SampleClass.__init__
Tim Petersbf0400a2006-06-05 01:43:03 +0000526 2 SampleClass.a_classmethod
527 1 SampleClass.a_property
528 1 SampleClass.a_staticmethod
Tim Peters958cc892004-09-13 14:53:28 +0000529 1 SampleClass.double
530 1 SampleClass.get
531
532By default, that excluded objects with no doctests. exclude_empty=False
533tells it to include (empty) tests for objects with no doctests. This feature
534is really to support backward compatibility in what doctest.master.summarize()
535displays.
536
Tim Petersbf0400a2006-06-05 01:43:03 +0000537 >>> tests = doctest.DocTestFinder(exclude_empty=False).find(SampleClass)
Tim Peters958cc892004-09-13 14:53:28 +0000538 >>> for t in tests:
539 ... print '%2s %s' % (len(t.examples), t.name)
Edward Loper4ae900f2004-09-21 03:20:34 +0000540 3 SampleClass
Tim Peters958cc892004-09-13 14:53:28 +0000541 3 SampleClass.NestedClass
542 1 SampleClass.NestedClass.__init__
Edward Loper32ddbf72004-09-13 05:47:24 +0000543 0 SampleClass.NestedClass.get
544 0 SampleClass.NestedClass.square
Tim Peters8485b562004-08-04 18:46:34 +0000545 1 SampleClass.__init__
Tim Peters8485b562004-08-04 18:46:34 +0000546 2 SampleClass.a_classmethod
547 1 SampleClass.a_property
548 1 SampleClass.a_staticmethod
549 1 SampleClass.double
550 1 SampleClass.get
551
Tim Peters8485b562004-08-04 18:46:34 +0000552Turning off Recursion
553~~~~~~~~~~~~~~~~~~~~~
554DocTestFinder can be told not to look for tests in contained objects
555using the `recurse` flag:
556
557 >>> tests = doctest.DocTestFinder(recurse=False).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000558 >>> for t in tests:
559 ... print '%2s %s' % (len(t.examples), t.name)
Edward Loper4ae900f2004-09-21 03:20:34 +0000560 3 SampleClass
Edward Loperb51b2342004-08-17 16:37:12 +0000561
562Line numbers
563~~~~~~~~~~~~
564DocTestFinder finds the line number of each example:
565
566 >>> def f(x):
567 ... '''
568 ... >>> x = 12
569 ...
570 ... some text
571 ...
572 ... >>> # examples are not created for comments & bare prompts.
573 ... >>>
574 ... ...
575 ...
576 ... >>> for x in range(10):
577 ... ... print x,
578 ... 0 1 2 3 4 5 6 7 8 9
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000579 ... >>> x//2
Edward Loperb51b2342004-08-17 16:37:12 +0000580 ... 6
581 ... '''
582 >>> test = doctest.DocTestFinder().find(f)[0]
583 >>> [e.lineno for e in test.examples]
584 [1, 9, 12]
Tim Peters8485b562004-08-04 18:46:34 +0000585"""
586
Edward Loper00f8da72004-08-26 18:05:07 +0000587def test_DocTestParser(): r"""
588Unit tests for the `DocTestParser` class.
589
590DocTestParser is used to parse docstrings containing doctest examples.
591
592The `parse` method divides a docstring into examples and intervening
593text:
594
595 >>> s = '''
596 ... >>> x, y = 2, 3 # no output expected
597 ... >>> if 1:
598 ... ... print x
599 ... ... print y
600 ... 2
601 ... 3
602 ...
603 ... Some text.
604 ... >>> x+y
605 ... 5
606 ... '''
607 >>> parser = doctest.DocTestParser()
608 >>> for piece in parser.parse(s):
609 ... if isinstance(piece, doctest.Example):
610 ... print 'Example:', (piece.source, piece.want, piece.lineno)
611 ... else:
612 ... print ' Text:', `piece`
613 Text: '\n'
614 Example: ('x, y = 2, 3 # no output expected\n', '', 1)
615 Text: ''
616 Example: ('if 1:\n print x\n print y\n', '2\n3\n', 2)
617 Text: '\nSome text.\n'
618 Example: ('x+y\n', '5\n', 9)
619 Text: ''
620
621The `get_examples` method returns just the examples:
622
623 >>> for piece in parser.get_examples(s):
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
629The `get_doctest` method creates a Test from the examples, along with the
630given arguments:
631
632 >>> test = parser.get_doctest(s, {}, 'name', 'filename', lineno=5)
633 >>> (test.name, test.filename, test.lineno)
634 ('name', 'filename', 5)
635 >>> for piece in test.examples:
636 ... print (piece.source, piece.want, piece.lineno)
637 ('x, y = 2, 3 # no output expected\n', '', 1)
638 ('if 1:\n print x\n print y\n', '2\n3\n', 2)
639 ('x+y\n', '5\n', 9)
640"""
641
Tim Peters8485b562004-08-04 18:46:34 +0000642class test_DocTestRunner:
643 def basics(): r"""
644Unit tests for the `DocTestRunner` class.
645
646DocTestRunner is used to run DocTest test cases, and to accumulate
647statistics. Here's a simple DocTest case we can use:
648
649 >>> def f(x):
650 ... '''
651 ... >>> x = 12
652 ... >>> print x
653 ... 12
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000654 ... >>> x//2
Tim Peters8485b562004-08-04 18:46:34 +0000655 ... 6
656 ... '''
657 >>> test = doctest.DocTestFinder().find(f)[0]
658
659The main DocTestRunner interface is the `run` method, which runs a
660given DocTest case in a given namespace (globs). It returns a tuple
661`(f,t)`, where `f` is the number of failed tests and `t` is the number
662of tried tests.
663
664 >>> doctest.DocTestRunner(verbose=False).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000665 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000666
667If any example produces incorrect output, then the test runner reports
668the failure and proceeds to the next example:
669
670 >>> def f(x):
671 ... '''
672 ... >>> x = 12
673 ... >>> print x
674 ... 14
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000675 ... >>> x//2
Tim Peters8485b562004-08-04 18:46:34 +0000676 ... 6
677 ... '''
678 >>> test = doctest.DocTestFinder().find(f)[0]
679 >>> doctest.DocTestRunner(verbose=True).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000680 ... # doctest: +ELLIPSIS
Edward Loperaacf0832004-08-26 01:19:50 +0000681 Trying:
682 x = 12
683 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000684 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000685 Trying:
686 print x
687 Expecting:
688 14
Tim Peters8485b562004-08-04 18:46:34 +0000689 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000690 File ..., line 4, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000691 Failed example:
692 print x
693 Expected:
694 14
695 Got:
696 12
Edward Loperaacf0832004-08-26 01:19:50 +0000697 Trying:
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000698 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000699 Expecting:
700 6
Tim Peters8485b562004-08-04 18:46:34 +0000701 ok
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000702 TestResults(failed=1, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000703"""
704 def verbose_flag(): r"""
705The `verbose` flag makes the test runner generate more detailed
706output:
707
708 >>> def f(x):
709 ... '''
710 ... >>> x = 12
711 ... >>> print x
712 ... 12
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000713 ... >>> x//2
Tim Peters8485b562004-08-04 18:46:34 +0000714 ... 6
715 ... '''
716 >>> test = doctest.DocTestFinder().find(f)[0]
717
718 >>> doctest.DocTestRunner(verbose=True).run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000719 Trying:
720 x = 12
721 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000722 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000723 Trying:
724 print x
725 Expecting:
726 12
Tim Peters8485b562004-08-04 18:46:34 +0000727 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000728 Trying:
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000729 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000730 Expecting:
731 6
Tim Peters8485b562004-08-04 18:46:34 +0000732 ok
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000733 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000734
735If the `verbose` flag is unspecified, then the output will be verbose
736iff `-v` appears in sys.argv:
737
738 >>> # Save the real sys.argv list.
739 >>> old_argv = sys.argv
740
741 >>> # If -v does not appear in sys.argv, then output isn't verbose.
742 >>> sys.argv = ['test']
743 >>> doctest.DocTestRunner().run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000744 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000745
746 >>> # If -v does appear in sys.argv, then output is verbose.
747 >>> sys.argv = ['test', '-v']
748 >>> doctest.DocTestRunner().run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000749 Trying:
750 x = 12
751 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000752 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000753 Trying:
754 print x
755 Expecting:
756 12
Tim Peters8485b562004-08-04 18:46:34 +0000757 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000758 Trying:
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000759 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000760 Expecting:
761 6
Tim Peters8485b562004-08-04 18:46:34 +0000762 ok
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000763 TestResults(failed=0, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +0000764
765 >>> # Restore sys.argv
766 >>> sys.argv = old_argv
767
768In the remaining examples, the test runner's verbosity will be
769explicitly set, to ensure that the test behavior is consistent.
770 """
771 def exceptions(): r"""
772Tests of `DocTestRunner`'s exception handling.
773
774An expected exception is specified with a traceback message. The
775lines between the first line and the type/value may be omitted or
776replaced with any other string:
777
778 >>> def f(x):
779 ... '''
780 ... >>> x = 12
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000781 ... >>> print x//0
Tim Peters8485b562004-08-04 18:46:34 +0000782 ... Traceback (most recent call last):
783 ... ZeroDivisionError: integer division or modulo by zero
784 ... '''
785 >>> test = doctest.DocTestFinder().find(f)[0]
786 >>> doctest.DocTestRunner(verbose=False).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000787 TestResults(failed=0, attempted=2)
Tim Peters8485b562004-08-04 18:46:34 +0000788
Edward Loper19b19582004-08-25 23:07:03 +0000789An example may not generate output before it raises an exception; if
790it does, then the traceback message will not be recognized as
791signaling an expected exception, so the example will be reported as an
792unexpected exception:
Tim Peters8485b562004-08-04 18:46:34 +0000793
794 >>> def f(x):
795 ... '''
796 ... >>> x = 12
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000797 ... >>> print 'pre-exception output', x//0
Tim Peters8485b562004-08-04 18:46:34 +0000798 ... pre-exception output
799 ... Traceback (most recent call last):
800 ... ZeroDivisionError: integer division or modulo by zero
801 ... '''
802 >>> test = doctest.DocTestFinder().find(f)[0]
803 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper19b19582004-08-25 23:07:03 +0000804 ... # doctest: +ELLIPSIS
805 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000806 File ..., line 4, in f
Edward Loper19b19582004-08-25 23:07:03 +0000807 Failed example:
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000808 print 'pre-exception output', x//0
Edward Loper19b19582004-08-25 23:07:03 +0000809 Exception raised:
810 ...
811 ZeroDivisionError: integer division or modulo by zero
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000812 TestResults(failed=1, attempted=2)
Tim Peters8485b562004-08-04 18:46:34 +0000813
814Exception messages may contain newlines:
815
816 >>> def f(x):
817 ... r'''
818 ... >>> raise ValueError, 'multi\nline\nmessage'
819 ... Traceback (most recent call last):
820 ... ValueError: multi
821 ... line
822 ... message
823 ... '''
824 >>> test = doctest.DocTestFinder().find(f)[0]
825 >>> doctest.DocTestRunner(verbose=False).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000826 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000827
828If an exception is expected, but an exception with the wrong type or
829message is raised, then it is reported as a failure:
830
831 >>> def f(x):
832 ... r'''
833 ... >>> raise ValueError, 'message'
834 ... Traceback (most recent call last):
835 ... ValueError: wrong message
836 ... '''
837 >>> test = doctest.DocTestFinder().find(f)[0]
838 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000839 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000840 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000841 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000842 Failed example:
843 raise ValueError, 'message'
Tim Peters8485b562004-08-04 18:46:34 +0000844 Expected:
845 Traceback (most recent call last):
846 ValueError: wrong message
847 Got:
848 Traceback (most recent call last):
Edward Loper8e4a34b2004-08-12 02:34:27 +0000849 ...
Tim Peters8485b562004-08-04 18:46:34 +0000850 ValueError: message
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000851 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000852
Tim Peters1fbf9c52004-09-04 17:21:02 +0000853However, IGNORE_EXCEPTION_DETAIL can be used to allow a mismatch in the
854detail:
855
856 >>> def f(x):
857 ... r'''
858 ... >>> raise ValueError, 'message' #doctest: +IGNORE_EXCEPTION_DETAIL
859 ... Traceback (most recent call last):
860 ... ValueError: wrong message
861 ... '''
862 >>> test = doctest.DocTestFinder().find(f)[0]
863 >>> doctest.DocTestRunner(verbose=False).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000864 TestResults(failed=0, attempted=1)
Tim Peters1fbf9c52004-09-04 17:21:02 +0000865
866But IGNORE_EXCEPTION_DETAIL does not allow a mismatch in the exception type:
867
868 >>> def f(x):
869 ... r'''
870 ... >>> raise ValueError, 'message' #doctest: +IGNORE_EXCEPTION_DETAIL
871 ... Traceback (most recent call last):
872 ... TypeError: wrong type
873 ... '''
874 >>> test = doctest.DocTestFinder().find(f)[0]
875 >>> doctest.DocTestRunner(verbose=False).run(test)
876 ... # doctest: +ELLIPSIS
877 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000878 File ..., line 3, in f
Tim Peters1fbf9c52004-09-04 17:21:02 +0000879 Failed example:
880 raise ValueError, 'message' #doctest: +IGNORE_EXCEPTION_DETAIL
881 Expected:
882 Traceback (most recent call last):
883 TypeError: wrong type
884 Got:
885 Traceback (most recent call last):
886 ...
887 ValueError: message
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000888 TestResults(failed=1, attempted=1)
Tim Peters1fbf9c52004-09-04 17:21:02 +0000889
Tim Peters8485b562004-08-04 18:46:34 +0000890If an exception is raised but not expected, then it is reported as an
891unexpected exception:
892
Tim Peters8485b562004-08-04 18:46:34 +0000893 >>> def f(x):
894 ... r'''
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000895 ... >>> 1//0
Tim Peters8485b562004-08-04 18:46:34 +0000896 ... 0
897 ... '''
898 >>> test = doctest.DocTestFinder().find(f)[0]
899 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper74bca7a2004-08-12 02:27:44 +0000900 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000901 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000902 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000903 Failed example:
Tim Peters1c5bc1c2006-03-28 07:28:40 +0000904 1//0
Tim Peters8485b562004-08-04 18:46:34 +0000905 Exception raised:
906 Traceback (most recent call last):
Jim Fulton07a349c2004-08-22 14:10:00 +0000907 ...
Tim Peters8485b562004-08-04 18:46:34 +0000908 ZeroDivisionError: integer division or modulo by zero
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000909 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000910"""
911 def optionflags(): r"""
912Tests of `DocTestRunner`'s option flag handling.
913
914Several option flags can be used to customize the behavior of the test
915runner. These are defined as module constants in doctest, and passed
Georg Brandlf725b952008-01-05 19:44:22 +0000916to the DocTestRunner constructor (multiple constants should be ORed
Tim Peters8485b562004-08-04 18:46:34 +0000917together).
918
919The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
920and 1/0:
921
922 >>> def f(x):
923 ... '>>> True\n1\n'
924
925 >>> # Without the flag:
926 >>> test = doctest.DocTestFinder().find(f)[0]
927 >>> doctest.DocTestRunner(verbose=False).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000928 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000929
930 >>> # With the flag:
931 >>> test = doctest.DocTestFinder().find(f)[0]
932 >>> flags = doctest.DONT_ACCEPT_TRUE_FOR_1
933 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000934 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000935 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000936 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000937 Failed example:
938 True
939 Expected:
940 1
941 Got:
942 True
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000943 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000944
945The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines
946and the '<BLANKLINE>' marker:
947
948 >>> def f(x):
949 ... '>>> print "a\\n\\nb"\na\n<BLANKLINE>\nb\n'
950
951 >>> # Without the flag:
952 >>> test = doctest.DocTestFinder().find(f)[0]
953 >>> doctest.DocTestRunner(verbose=False).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000954 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000955
956 >>> # With the flag:
957 >>> test = doctest.DocTestFinder().find(f)[0]
958 >>> flags = doctest.DONT_ACCEPT_BLANKLINE
959 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000960 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000961 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000962 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000963 Failed example:
964 print "a\n\nb"
Tim Peters8485b562004-08-04 18:46:34 +0000965 Expected:
966 a
967 <BLANKLINE>
968 b
969 Got:
970 a
971 <BLANKLINE>
972 b
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000973 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000974
975The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be
976treated as equal:
977
978 >>> def f(x):
979 ... '>>> print 1, 2, 3\n 1 2\n 3'
980
981 >>> # Without the flag:
982 >>> test = doctest.DocTestFinder().find(f)[0]
983 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000984 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000985 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000986 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000987 Failed example:
988 print 1, 2, 3
Tim Peters8485b562004-08-04 18:46:34 +0000989 Expected:
990 1 2
991 3
Jim Fulton07a349c2004-08-22 14:10:00 +0000992 Got:
993 1 2 3
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000994 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000995
996 >>> # With the flag:
997 >>> test = doctest.DocTestFinder().find(f)[0]
998 >>> flags = doctest.NORMALIZE_WHITESPACE
999 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001000 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001001
Tim Peters026f8dc2004-08-19 16:38:58 +00001002 An example from the docs:
1003 >>> print range(20) #doctest: +NORMALIZE_WHITESPACE
1004 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
1005 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
1006
Tim Peters8485b562004-08-04 18:46:34 +00001007The ELLIPSIS flag causes ellipsis marker ("...") in the expected
1008output to match any substring in the actual output:
1009
1010 >>> def f(x):
1011 ... '>>> print range(15)\n[0, 1, 2, ..., 14]\n'
1012
1013 >>> # Without the flag:
1014 >>> test = doctest.DocTestFinder().find(f)[0]
1015 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001016 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001017 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001018 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001019 Failed example:
1020 print range(15)
1021 Expected:
1022 [0, 1, 2, ..., 14]
1023 Got:
1024 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001025 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001026
1027 >>> # With the flag:
1028 >>> test = doctest.DocTestFinder().find(f)[0]
1029 >>> flags = doctest.ELLIPSIS
1030 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001031 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001032
Tim Peterse594bee2004-08-22 01:47:51 +00001033 ... also matches nothing:
Tim Peters1cf3aa62004-08-19 06:49:33 +00001034
1035 >>> for i in range(100):
Tim Peterse594bee2004-08-22 01:47:51 +00001036 ... print i**2, #doctest: +ELLIPSIS
1037 0 1...4...9 16 ... 36 49 64 ... 9801
Tim Peters1cf3aa62004-08-19 06:49:33 +00001038
Tim Peters026f8dc2004-08-19 16:38:58 +00001039 ... can be surprising; e.g., this test passes:
Tim Peters26b3ebb2004-08-19 08:10:08 +00001040
1041 >>> for i in range(21): #doctest: +ELLIPSIS
Tim Peterse594bee2004-08-22 01:47:51 +00001042 ... print i,
1043 0 1 2 ...1...2...0
Tim Peters26b3ebb2004-08-19 08:10:08 +00001044
Tim Peters026f8dc2004-08-19 16:38:58 +00001045 Examples from the docs:
1046
1047 >>> print range(20) # doctest:+ELLIPSIS
1048 [0, 1, ..., 18, 19]
1049
1050 >>> print range(20) # doctest: +ELLIPSIS
1051 ... # doctest: +NORMALIZE_WHITESPACE
1052 [0, 1, ..., 18, 19]
1053
Tim Peters711bf302006-04-25 03:31:36 +00001054The SKIP flag causes an example to be skipped entirely. I.e., the
1055example is not run. It can be useful in contexts where doctest
1056examples serve as both documentation and test cases, and an example
1057should be included for documentation purposes, but should not be
1058checked (e.g., because its output is random, or depends on resources
1059which would be unavailable.) The SKIP flag can also be used for
1060'commenting out' broken examples.
1061
1062 >>> import unavailable_resource # doctest: +SKIP
1063 >>> unavailable_resource.do_something() # doctest: +SKIP
1064 >>> unavailable_resource.blow_up() # doctest: +SKIP
1065 Traceback (most recent call last):
1066 ...
1067 UncheckedBlowUpError: Nobody checks me.
1068
1069 >>> import random
1070 >>> print random.random() # doctest: +SKIP
1071 0.721216923889
1072
Edward Loper71f55af2004-08-26 01:41:51 +00001073The REPORT_UDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001074and actual outputs to be displayed using a unified diff:
1075
1076 >>> def f(x):
1077 ... r'''
1078 ... >>> print '\n'.join('abcdefg')
1079 ... a
1080 ... B
1081 ... c
1082 ... d
1083 ... f
1084 ... g
1085 ... h
1086 ... '''
1087
1088 >>> # Without the flag:
1089 >>> test = doctest.DocTestFinder().find(f)[0]
1090 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001091 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001092 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001093 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001094 Failed example:
1095 print '\n'.join('abcdefg')
Tim Peters8485b562004-08-04 18:46:34 +00001096 Expected:
1097 a
1098 B
1099 c
1100 d
1101 f
1102 g
1103 h
1104 Got:
1105 a
1106 b
1107 c
1108 d
1109 e
1110 f
1111 g
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001112 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001113
1114 >>> # With the flag:
1115 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001116 >>> flags = doctest.REPORT_UDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001117 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001118 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001119 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001120 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001121 Failed example:
1122 print '\n'.join('abcdefg')
Edward Loper56629292004-08-26 01:31:56 +00001123 Differences (unified diff with -expected +actual):
Tim Peterse7edcb82004-08-26 05:44:27 +00001124 @@ -1,7 +1,7 @@
Tim Peters8485b562004-08-04 18:46:34 +00001125 a
1126 -B
1127 +b
1128 c
1129 d
1130 +e
1131 f
1132 g
1133 -h
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001134 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001135
Edward Loper71f55af2004-08-26 01:41:51 +00001136The REPORT_CDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001137and actual outputs to be displayed using a context diff:
1138
Edward Loper71f55af2004-08-26 01:41:51 +00001139 >>> # Reuse f() from the REPORT_UDIFF example, above.
Tim Peters8485b562004-08-04 18:46:34 +00001140 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001141 >>> flags = doctest.REPORT_CDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001142 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001143 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001144 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001145 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001146 Failed example:
1147 print '\n'.join('abcdefg')
Edward Loper56629292004-08-26 01:31:56 +00001148 Differences (context diff with expected followed by actual):
Tim Peters8485b562004-08-04 18:46:34 +00001149 ***************
Tim Peterse7edcb82004-08-26 05:44:27 +00001150 *** 1,7 ****
Tim Peters8485b562004-08-04 18:46:34 +00001151 a
1152 ! B
1153 c
1154 d
1155 f
1156 g
1157 - h
Tim Peterse7edcb82004-08-26 05:44:27 +00001158 --- 1,7 ----
Tim Peters8485b562004-08-04 18:46:34 +00001159 a
1160 ! b
1161 c
1162 d
1163 + e
1164 f
1165 g
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001166 TestResults(failed=1, attempted=1)
Tim Petersc6cbab02004-08-22 19:43:28 +00001167
1168
Edward Loper71f55af2004-08-26 01:41:51 +00001169The REPORT_NDIFF flag causes failures to use the difflib.Differ algorithm
Tim Petersc6cbab02004-08-22 19:43:28 +00001170used by the popular ndiff.py utility. This does intraline difference
1171marking, as well as interline differences.
1172
1173 >>> def f(x):
1174 ... r'''
1175 ... >>> print "a b c d e f g h i j k l m"
1176 ... a b c d e f g h i j k 1 m
1177 ... '''
1178 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001179 >>> flags = doctest.REPORT_NDIFF
Tim Petersc6cbab02004-08-22 19:43:28 +00001180 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001181 ... # doctest: +ELLIPSIS
Tim Petersc6cbab02004-08-22 19:43:28 +00001182 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001183 File ..., line 3, in f
Tim Petersc6cbab02004-08-22 19:43:28 +00001184 Failed example:
1185 print "a b c d e f g h i j k l m"
1186 Differences (ndiff with -expected +actual):
1187 - a b c d e f g h i j k 1 m
1188 ? ^
1189 + a b c d e f g h i j k l m
1190 ? + ++ ^
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001191 TestResults(failed=1, attempted=1)
Edward Lopera89f88d2004-08-26 02:45:51 +00001192
1193The REPORT_ONLY_FIRST_FAILURE supresses result output after the first
1194failing example:
1195
1196 >>> def f(x):
1197 ... r'''
1198 ... >>> print 1 # first success
1199 ... 1
1200 ... >>> print 2 # first failure
1201 ... 200
1202 ... >>> print 3 # second failure
1203 ... 300
1204 ... >>> print 4 # second success
1205 ... 4
1206 ... >>> print 5 # third failure
1207 ... 500
1208 ... '''
1209 >>> test = doctest.DocTestFinder().find(f)[0]
1210 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1211 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001212 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001213 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001214 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001215 Failed example:
1216 print 2 # first failure
1217 Expected:
1218 200
1219 Got:
1220 2
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001221 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001222
1223However, output from `report_start` is not supressed:
1224
1225 >>> doctest.DocTestRunner(verbose=True, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001226 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001227 Trying:
1228 print 1 # first success
1229 Expecting:
1230 1
1231 ok
1232 Trying:
1233 print 2 # first failure
1234 Expecting:
1235 200
1236 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001237 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001238 Failed example:
1239 print 2 # first failure
1240 Expected:
1241 200
1242 Got:
1243 2
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001244 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001245
1246For the purposes of REPORT_ONLY_FIRST_FAILURE, unexpected exceptions
1247count as failures:
1248
1249 >>> def f(x):
1250 ... r'''
1251 ... >>> print 1 # first success
1252 ... 1
1253 ... >>> raise ValueError(2) # first failure
1254 ... 200
1255 ... >>> print 3 # second failure
1256 ... 300
1257 ... >>> print 4 # second success
1258 ... 4
1259 ... >>> print 5 # third failure
1260 ... 500
1261 ... '''
1262 >>> test = doctest.DocTestFinder().find(f)[0]
1263 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1264 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1265 ... # doctest: +ELLIPSIS
1266 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001267 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001268 Failed example:
1269 raise ValueError(2) # first failure
1270 Exception raised:
1271 ...
1272 ValueError: 2
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001273 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001274
Tim Petersad2ef332006-05-10 02:43:01 +00001275New option flags can also be registered, via register_optionflag(). Here
1276we reach into doctest's internals a bit.
1277
1278 >>> unlikely = "UNLIKELY_OPTION_NAME"
1279 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1280 False
1281 >>> new_flag_value = doctest.register_optionflag(unlikely)
1282 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1283 True
1284
1285Before 2.4.4/2.5, registering a name more than once erroneously created
1286more than one flag value. Here we verify that's fixed:
1287
1288 >>> redundant_flag_value = doctest.register_optionflag(unlikely)
1289 >>> redundant_flag_value == new_flag_value
1290 True
1291
1292Clean up.
1293 >>> del doctest.OPTIONFLAGS_BY_NAME[unlikely]
1294
Tim Petersc6cbab02004-08-22 19:43:28 +00001295 """
1296
Tim Peters8485b562004-08-04 18:46:34 +00001297 def option_directives(): r"""
1298Tests of `DocTestRunner`'s option directive mechanism.
1299
Edward Loper74bca7a2004-08-12 02:27:44 +00001300Option directives can be used to turn option flags on or off for a
1301single example. To turn an option on for an example, follow that
1302example with a comment of the form ``# doctest: +OPTION``:
Tim Peters8485b562004-08-04 18:46:34 +00001303
1304 >>> def f(x): r'''
Edward Loper74bca7a2004-08-12 02:27:44 +00001305 ... >>> print range(10) # should fail: no ellipsis
1306 ... [0, 1, ..., 9]
1307 ...
1308 ... >>> print range(10) # doctest: +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
Edward Loper74bca7a2004-08-12 02:27:44 +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]
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001322 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001323
1324To turn an option off for an example, follow that example with a
1325comment of the form ``# doctest: -OPTION``:
1326
1327 >>> def f(x): r'''
1328 ... >>> print range(10)
1329 ... [0, 1, ..., 9]
1330 ...
1331 ... >>> # should fail: no ellipsis
1332 ... >>> print range(10) # doctest: -ELLIPSIS
1333 ... [0, 1, ..., 9]
1334 ... '''
1335 >>> test = doctest.DocTestFinder().find(f)[0]
1336 >>> doctest.DocTestRunner(verbose=False,
1337 ... optionflags=doctest.ELLIPSIS).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001338 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001339 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001340 File ..., line 6, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001341 Failed example:
1342 print range(10) # doctest: -ELLIPSIS
1343 Expected:
1344 [0, 1, ..., 9]
1345 Got:
1346 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001347 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001348
1349Option directives affect only the example that they appear with; they
1350do not change the options for surrounding examples:
Edward Loper8e4a34b2004-08-12 02:34:27 +00001351
Edward Loper74bca7a2004-08-12 02:27:44 +00001352 >>> def f(x): r'''
Tim Peters8485b562004-08-04 18:46:34 +00001353 ... >>> print range(10) # Should fail: no ellipsis
1354 ... [0, 1, ..., 9]
1355 ...
Edward Loper74bca7a2004-08-12 02:27:44 +00001356 ... >>> print range(10) # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001357 ... [0, 1, ..., 9]
1358 ...
Tim Peters8485b562004-08-04 18:46:34 +00001359 ... >>> print range(10) # Should fail: no ellipsis
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
Tim Peters8485b562004-08-04 18:46:34 +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: no ellipsis
1369 Expected:
1370 [0, 1, ..., 9]
1371 Got:
1372 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001373 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001374 File ..., line 8, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001375 Failed example:
1376 print range(10) # Should fail: no ellipsis
1377 Expected:
1378 [0, 1, ..., 9]
1379 Got:
1380 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001381 TestResults(failed=2, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +00001382
Edward Loper74bca7a2004-08-12 02:27:44 +00001383Multiple options may be modified by a single option directive. They
1384may be separated by whitespace, commas, or both:
Tim Peters8485b562004-08-04 18:46:34 +00001385
1386 >>> def f(x): r'''
1387 ... >>> print range(10) # Should fail
1388 ... [0, 1, ..., 9]
Tim Peters8485b562004-08-04 18:46:34 +00001389 ... >>> print range(10) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001390 ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001391 ... [0, 1, ..., 9]
1392 ... '''
1393 >>> test = doctest.DocTestFinder().find(f)[0]
1394 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001395 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001396 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001397 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001398 Failed example:
1399 print range(10) # Should fail
1400 Expected:
1401 [0, 1, ..., 9]
1402 Got:
1403 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001404 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001405
1406 >>> def f(x): r'''
1407 ... >>> print range(10) # Should fail
1408 ... [0, 1, ..., 9]
1409 ... >>> print range(10) # Should succeed
1410 ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
1411 ... [0, 1, ..., 9]
1412 ... '''
1413 >>> test = doctest.DocTestFinder().find(f)[0]
1414 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001415 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001416 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001417 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001418 Failed example:
1419 print range(10) # Should fail
1420 Expected:
1421 [0, 1, ..., 9]
1422 Got:
1423 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001424 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001425
1426 >>> def f(x): r'''
1427 ... >>> print range(10) # Should fail
1428 ... [0, 1, ..., 9]
1429 ... >>> print range(10) # Should succeed
1430 ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1431 ... [0, 1, ..., 9]
1432 ... '''
1433 >>> test = doctest.DocTestFinder().find(f)[0]
1434 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001435 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001436 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001437 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001438 Failed example:
1439 print range(10) # Should fail
1440 Expected:
1441 [0, 1, ..., 9]
1442 Got:
1443 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001444 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001445
1446The option directive may be put on the line following the source, as
1447long as a continuation prompt is used:
1448
1449 >>> def f(x): r'''
1450 ... >>> print range(10)
1451 ... ... # doctest: +ELLIPSIS
1452 ... [0, 1, ..., 9]
1453 ... '''
1454 >>> test = doctest.DocTestFinder().find(f)[0]
1455 >>> doctest.DocTestRunner(verbose=False).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001456 TestResults(failed=0, attempted=1)
Edward Loper8e4a34b2004-08-12 02:34:27 +00001457
Edward Loper74bca7a2004-08-12 02:27:44 +00001458For examples with multi-line source, the option directive may appear
1459at the end of any line:
1460
1461 >>> def f(x): r'''
1462 ... >>> for x in range(10): # doctest: +ELLIPSIS
1463 ... ... print x,
1464 ... 0 1 2 ... 9
1465 ...
1466 ... >>> for x in range(10):
1467 ... ... print x, # doctest: +ELLIPSIS
1468 ... 0 1 2 ... 9
1469 ... '''
1470 >>> test = doctest.DocTestFinder().find(f)[0]
1471 >>> doctest.DocTestRunner(verbose=False).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001472 TestResults(failed=0, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001473
1474If more than one line of an example with multi-line source has an
1475option directive, then they are combined:
1476
1477 >>> def f(x): r'''
1478 ... Should fail (option directive not on the last line):
1479 ... >>> for x in range(10): # doctest: +ELLIPSIS
1480 ... ... print x, # doctest: +NORMALIZE_WHITESPACE
1481 ... 0 1 2...9
1482 ... '''
1483 >>> test = doctest.DocTestFinder().find(f)[0]
1484 >>> doctest.DocTestRunner(verbose=False).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001485 TestResults(failed=0, attempted=1)
Edward Loper74bca7a2004-08-12 02:27:44 +00001486
1487It is an error to have a comment of the form ``# doctest:`` that is
1488*not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
1489``OPTION`` is an option that has been registered with
1490`register_option`:
1491
1492 >>> # Error: Option not registered
1493 >>> s = '>>> print 12 #doctest: +BADOPTION'
1494 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1495 Traceback (most recent call last):
1496 ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
1497
1498 >>> # Error: No + or - prefix
1499 >>> s = '>>> print 12 #doctest: ELLIPSIS'
1500 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1501 Traceback (most recent call last):
1502 ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
1503
1504It is an error to use an option directive on a line that contains no
1505source:
1506
1507 >>> s = '>>> # doctest: +ELLIPSIS'
1508 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1509 Traceback (most recent call last):
1510 ValueError: line 0 of the doctest for s has an option directive on a line with no example: '# doctest: +ELLIPSIS'
Georg Brandl03c1cff2010-08-01 22:05:31 +00001511
1512 """
1513
1514 def test_unicode_output(self): r"""
1515
1516Check that unicode output works:
1517
1518 >>> u'\xe9'
1519 u'\xe9'
1520
1521If we return unicode, SpoofOut's buf variable becomes automagically
1522converted to unicode. This means all subsequent output becomes converted
1523to unicode, and if the output contains non-ascii characters that failed.
1524It used to be that this state change carried on between tests, meaning
1525tests would fail if unicode has been output previously in the testrun.
1526This test tests that this is no longer so:
1527
1528 >>> print u'abc'
1529 abc
1530
1531And then return a string with non-ascii characters:
1532
1533 >>> print u'\xe9'.encode('utf-8')
1534 é
1535
1536 """
1537
Tim Peters8485b562004-08-04 18:46:34 +00001538
1539def test_testsource(): r"""
1540Unit tests for `testsource()`.
1541
1542The testsource() function takes a module and a name, finds the (first)
Tim Peters19397e52004-08-06 22:02:59 +00001543test with that name in that module, and converts it to a script. The
1544example code is converted to regular Python code. The surrounding
1545words and expected output are converted to comments:
Tim Peters8485b562004-08-04 18:46:34 +00001546
1547 >>> import test.test_doctest
1548 >>> name = 'test.test_doctest.sample_func'
1549 >>> print doctest.testsource(test.test_doctest, name)
Edward Lopera5db6002004-08-12 02:41:30 +00001550 # Blah blah
Tim Peters19397e52004-08-06 22:02:59 +00001551 #
Tim Peters8485b562004-08-04 18:46:34 +00001552 print sample_func(22)
1553 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001554 ## 44
Tim Peters19397e52004-08-06 22:02:59 +00001555 #
Edward Lopera5db6002004-08-12 02:41:30 +00001556 # Yee ha!
Georg Brandlecf93c72005-06-26 23:09:51 +00001557 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001558
1559 >>> name = 'test.test_doctest.SampleNewStyleClass'
1560 >>> print doctest.testsource(test.test_doctest, name)
1561 print '1\n2\n3'
1562 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001563 ## 1
1564 ## 2
1565 ## 3
Georg Brandlecf93c72005-06-26 23:09:51 +00001566 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001567
1568 >>> name = 'test.test_doctest.SampleClass.a_classmethod'
1569 >>> print doctest.testsource(test.test_doctest, name)
1570 print SampleClass.a_classmethod(10)
1571 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001572 ## 12
Tim Peters8485b562004-08-04 18:46:34 +00001573 print SampleClass(0).a_classmethod(10)
1574 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001575 ## 12
Georg Brandlecf93c72005-06-26 23:09:51 +00001576 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001577"""
1578
1579def test_debug(): r"""
1580
1581Create a docstring that we want to debug:
1582
1583 >>> s = '''
1584 ... >>> x = 12
1585 ... >>> print x
1586 ... 12
1587 ... '''
1588
1589Create some fake stdin input, to feed to the debugger:
1590
1591 >>> import tempfile
Tim Peters8485b562004-08-04 18:46:34 +00001592 >>> real_stdin = sys.stdin
Edward Loper2de91ba2004-08-27 02:07:46 +00001593 >>> sys.stdin = _FakeInput(['next', 'print x', 'continue'])
Tim Peters8485b562004-08-04 18:46:34 +00001594
1595Run the debugger on the docstring, and then restore sys.stdin.
1596
Edward Loper2de91ba2004-08-27 02:07:46 +00001597 >>> try: doctest.debug_src(s)
1598 ... finally: sys.stdin = real_stdin
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001599 > <string>(1)<module>()
Edward Loper2de91ba2004-08-27 02:07:46 +00001600 (Pdb) next
1601 12
Tim Peters8485b562004-08-04 18:46:34 +00001602 --Return--
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001603 > <string>(1)<module>()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001604 (Pdb) print x
1605 12
1606 (Pdb) continue
Tim Peters8485b562004-08-04 18:46:34 +00001607
1608"""
1609
Jim Fulton356fd192004-08-09 11:34:47 +00001610def test_pdb_set_trace():
Tim Peters50c6bdb2004-11-08 22:07:37 +00001611 """Using pdb.set_trace from a doctest.
Jim Fulton356fd192004-08-09 11:34:47 +00001612
Tim Peters413ced62004-08-09 15:43:47 +00001613 You can use pdb.set_trace from a doctest. To do so, you must
Jim Fulton356fd192004-08-09 11:34:47 +00001614 retrieve the set_trace function from the pdb module at the time
Tim Peters413ced62004-08-09 15:43:47 +00001615 you use it. The doctest module changes sys.stdout so that it can
1616 capture program output. It also temporarily replaces pdb.set_trace
1617 with a version that restores stdout. This is necessary for you to
Jim Fulton356fd192004-08-09 11:34:47 +00001618 see debugger output.
1619
1620 >>> doc = '''
1621 ... >>> x = 42
1622 ... >>> import pdb; pdb.set_trace()
1623 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001624 >>> parser = doctest.DocTestParser()
1625 >>> test = parser.get_doctest(doc, {}, "foo", "foo.py", 0)
Jim Fulton356fd192004-08-09 11:34:47 +00001626 >>> runner = doctest.DocTestRunner(verbose=False)
1627
1628 To demonstrate this, we'll create a fake standard input that
1629 captures our debugger input:
1630
1631 >>> import tempfile
Edward Loper2de91ba2004-08-27 02:07:46 +00001632 >>> real_stdin = sys.stdin
1633 >>> sys.stdin = _FakeInput([
Jim Fulton356fd192004-08-09 11:34:47 +00001634 ... 'print x', # print data defined by the example
1635 ... 'continue', # stop debugging
Edward Loper2de91ba2004-08-27 02:07:46 +00001636 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001637
Edward Loper2de91ba2004-08-27 02:07:46 +00001638 >>> try: runner.run(test)
1639 ... finally: sys.stdin = real_stdin
Jim Fulton356fd192004-08-09 11:34:47 +00001640 --Return--
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001641 > <doctest foo[1]>(1)<module>()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001642 -> import pdb; pdb.set_trace()
1643 (Pdb) print x
1644 42
1645 (Pdb) continue
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001646 TestResults(failed=0, attempted=2)
Jim Fulton356fd192004-08-09 11:34:47 +00001647
1648 You can also put pdb.set_trace in a function called from a test:
1649
1650 >>> def calls_set_trace():
1651 ... y=2
1652 ... import pdb; pdb.set_trace()
1653
1654 >>> doc = '''
1655 ... >>> x=1
1656 ... >>> calls_set_trace()
1657 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001658 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
Edward Loper2de91ba2004-08-27 02:07:46 +00001659 >>> real_stdin = sys.stdin
1660 >>> sys.stdin = _FakeInput([
Jim Fulton356fd192004-08-09 11:34:47 +00001661 ... 'print y', # print data defined in the function
1662 ... 'up', # out of function
1663 ... 'print x', # print data defined by the example
1664 ... 'continue', # stop debugging
Edward Loper2de91ba2004-08-27 02:07:46 +00001665 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001666
Tim Peters50c6bdb2004-11-08 22:07:37 +00001667 >>> try:
1668 ... runner.run(test)
1669 ... finally:
1670 ... sys.stdin = real_stdin
Jim Fulton356fd192004-08-09 11:34:47 +00001671 --Return--
Edward Loper2de91ba2004-08-27 02:07:46 +00001672 > <doctest test.test_doctest.test_pdb_set_trace[8]>(3)calls_set_trace()->None
1673 -> import pdb; pdb.set_trace()
1674 (Pdb) print y
1675 2
1676 (Pdb) up
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001677 > <doctest foo[1]>(1)<module>()
Edward Loper2de91ba2004-08-27 02:07:46 +00001678 -> calls_set_trace()
1679 (Pdb) print x
1680 1
1681 (Pdb) continue
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001682 TestResults(failed=0, attempted=2)
Edward Loper2de91ba2004-08-27 02:07:46 +00001683
1684 During interactive debugging, source code is shown, even for
1685 doctest examples:
1686
1687 >>> doc = '''
1688 ... >>> def f(x):
1689 ... ... g(x*2)
1690 ... >>> def g(x):
1691 ... ... print x+3
1692 ... ... import pdb; pdb.set_trace()
1693 ... >>> f(3)
1694 ... '''
1695 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
1696 >>> real_stdin = sys.stdin
1697 >>> sys.stdin = _FakeInput([
1698 ... 'list', # list source from example 2
1699 ... 'next', # return from g()
1700 ... 'list', # list source from example 1
1701 ... 'next', # return from f()
1702 ... 'list', # list source from example 3
1703 ... 'continue', # stop debugging
1704 ... ''])
1705 >>> try: runner.run(test)
1706 ... finally: sys.stdin = real_stdin
1707 ... # doctest: +NORMALIZE_WHITESPACE
1708 --Return--
1709 > <doctest foo[1]>(3)g()->None
1710 -> import pdb; pdb.set_trace()
1711 (Pdb) list
1712 1 def g(x):
1713 2 print x+3
1714 3 -> import pdb; pdb.set_trace()
1715 [EOF]
1716 (Pdb) next
1717 --Return--
1718 > <doctest foo[0]>(2)f()->None
1719 -> g(x*2)
1720 (Pdb) list
1721 1 def f(x):
1722 2 -> g(x*2)
1723 [EOF]
1724 (Pdb) next
1725 --Return--
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001726 > <doctest foo[2]>(1)<module>()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001727 -> f(3)
1728 (Pdb) list
1729 1 -> f(3)
1730 [EOF]
1731 (Pdb) continue
1732 **********************************************************************
1733 File "foo.py", line 7, in foo
1734 Failed example:
1735 f(3)
1736 Expected nothing
1737 Got:
1738 9
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001739 TestResults(failed=1, attempted=3)
Jim Fulton356fd192004-08-09 11:34:47 +00001740 """
1741
Tim Peters50c6bdb2004-11-08 22:07:37 +00001742def test_pdb_set_trace_nested():
1743 """This illustrates more-demanding use of set_trace with nested functions.
1744
1745 >>> class C(object):
1746 ... def calls_set_trace(self):
1747 ... y = 1
1748 ... import pdb; pdb.set_trace()
1749 ... self.f1()
1750 ... y = 2
1751 ... def f1(self):
1752 ... x = 1
1753 ... self.f2()
1754 ... x = 2
1755 ... def f2(self):
1756 ... z = 1
1757 ... z = 2
1758
1759 >>> calls_set_trace = C().calls_set_trace
1760
1761 >>> doc = '''
1762 ... >>> a = 1
1763 ... >>> calls_set_trace()
1764 ... '''
1765 >>> parser = doctest.DocTestParser()
1766 >>> runner = doctest.DocTestRunner(verbose=False)
1767 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
1768 >>> real_stdin = sys.stdin
1769 >>> sys.stdin = _FakeInput([
1770 ... 'print y', # print data defined in the function
1771 ... 'step', 'step', 'step', 'step', 'step', 'step', 'print z',
1772 ... 'up', 'print x',
1773 ... 'up', 'print y',
1774 ... 'up', 'print foo',
1775 ... 'continue', # stop debugging
1776 ... ''])
1777
1778 >>> try:
1779 ... runner.run(test)
1780 ... finally:
1781 ... sys.stdin = real_stdin
1782 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
1783 -> self.f1()
1784 (Pdb) print y
1785 1
1786 (Pdb) step
1787 --Call--
1788 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(7)f1()
1789 -> def f1(self):
1790 (Pdb) step
1791 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(8)f1()
1792 -> x = 1
1793 (Pdb) step
1794 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
1795 -> self.f2()
1796 (Pdb) step
1797 --Call--
1798 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(11)f2()
1799 -> def f2(self):
1800 (Pdb) step
1801 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(12)f2()
1802 -> z = 1
1803 (Pdb) step
1804 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(13)f2()
1805 -> z = 2
1806 (Pdb) print z
1807 1
1808 (Pdb) up
1809 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
1810 -> self.f2()
1811 (Pdb) print x
1812 1
1813 (Pdb) up
1814 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
1815 -> self.f1()
1816 (Pdb) print y
1817 1
1818 (Pdb) up
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001819 > <doctest foo[1]>(1)<module>()
Tim Peters50c6bdb2004-11-08 22:07:37 +00001820 -> calls_set_trace()
1821 (Pdb) print foo
1822 *** NameError: name 'foo' is not defined
1823 (Pdb) continue
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001824 TestResults(failed=0, attempted=2)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001825"""
1826
Tim Peters19397e52004-08-06 22:02:59 +00001827def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +00001828 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +00001829
1830 We create a Suite by providing a module. A module can be provided
1831 by passing a module object:
1832
1833 >>> import unittest
1834 >>> import test.sample_doctest
1835 >>> suite = doctest.DocTestSuite(test.sample_doctest)
1836 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001837 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001838
1839 We can also supply the module by name:
1840
1841 >>> suite = doctest.DocTestSuite('test.sample_doctest')
1842 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001843 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001844
1845 We can use the current module:
1846
1847 >>> suite = test.sample_doctest.test_suite()
1848 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001849 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001850
1851 We can supply global variables. If we pass globs, they will be
1852 used instead of the module globals. Here we'll pass an empty
1853 globals, triggering an extra error:
1854
1855 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
1856 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001857 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001858
1859 Alternatively, we can provide extra globals. Here we'll make an
1860 error go away by providing an extra global variable:
1861
1862 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1863 ... extraglobs={'y': 1})
1864 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001865 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001866
1867 You can pass option flags. Here we'll cause an extra error
1868 by disabling the blank-line feature:
1869
1870 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00001871 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00001872 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001873 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001874
Tim Peters1e277ee2004-08-07 05:37:52 +00001875 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00001876
Jim Fultonf54bad42004-08-28 14:57:56 +00001877 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00001878 ... import test.test_doctest
1879 ... test.test_doctest.sillySetup = True
1880
Jim Fultonf54bad42004-08-28 14:57:56 +00001881 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00001882 ... import test.test_doctest
1883 ... del test.test_doctest.sillySetup
1884
1885 Here, we installed a silly variable that the test expects:
1886
1887 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1888 ... setUp=setUp, tearDown=tearDown)
1889 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001890 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001891
1892 But the tearDown restores sanity:
1893
1894 >>> import test.test_doctest
1895 >>> test.test_doctest.sillySetup
1896 Traceback (most recent call last):
1897 ...
1898 AttributeError: 'module' object has no attribute 'sillySetup'
1899
Jim Fultonf54bad42004-08-28 14:57:56 +00001900 The setUp and tearDown funtions are passed test objects. Here
1901 we'll use the setUp function to supply the missing variable y:
1902
1903 >>> def setUp(test):
1904 ... test.globs['y'] = 1
1905
1906 >>> suite = doctest.DocTestSuite('test.sample_doctest', setUp=setUp)
1907 >>> suite.run(unittest.TestResult())
1908 <unittest.TestResult run=9 errors=0 failures=3>
1909
1910 Here, we didn't need to use a tearDown function because we
1911 modified the test globals, which are a copy of the
1912 sample_doctest module dictionary. The test globals are
1913 automatically cleared for us after a test.
Tim Peters19397e52004-08-06 22:02:59 +00001914 """
1915
1916def test_DocFileSuite():
1917 """We can test tests found in text files using a DocFileSuite.
1918
1919 We create a suite by providing the names of one or more text
1920 files that include examples:
1921
1922 >>> import unittest
1923 >>> suite = doctest.DocFileSuite('test_doctest.txt',
George Yoshidaf3c65de2006-05-28 16:39:09 +00001924 ... 'test_doctest2.txt',
1925 ... 'test_doctest4.txt')
Tim Peters19397e52004-08-06 22:02:59 +00001926 >>> suite.run(unittest.TestResult())
George Yoshidaf3c65de2006-05-28 16:39:09 +00001927 <unittest.TestResult run=3 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001928
1929 The test files are looked for in the directory containing the
1930 calling module. A package keyword argument can be provided to
1931 specify a different relative location.
1932
1933 >>> import unittest
1934 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1935 ... 'test_doctest2.txt',
George Yoshidaf3c65de2006-05-28 16:39:09 +00001936 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00001937 ... package='test')
1938 >>> suite.run(unittest.TestResult())
George Yoshidaf3c65de2006-05-28 16:39:09 +00001939 <unittest.TestResult run=3 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001940
Brett Cannon43e53f82007-11-21 00:47:36 +00001941 Support for using a package's __loader__.get_data() is also
1942 provided.
1943
1944 >>> import unittest, pkgutil, test
Brett Cannoneaa2c982007-11-23 00:06:51 +00001945 >>> added_loader = False
Brett Cannon43e53f82007-11-21 00:47:36 +00001946 >>> if not hasattr(test, '__loader__'):
1947 ... test.__loader__ = pkgutil.get_loader(test)
1948 ... added_loader = True
1949 >>> try:
1950 ... suite = doctest.DocFileSuite('test_doctest.txt',
1951 ... 'test_doctest2.txt',
1952 ... 'test_doctest4.txt',
1953 ... package='test')
1954 ... suite.run(unittest.TestResult())
1955 ... finally:
Brett Cannon9db1d5a2007-11-21 00:58:03 +00001956 ... if added_loader:
1957 ... del test.__loader__
Brett Cannon43e53f82007-11-21 00:47:36 +00001958 <unittest.TestResult run=3 errors=0 failures=3>
1959
Edward Loper0273f5b2004-09-18 20:27:04 +00001960 '/' should be used as a path separator. It will be converted
1961 to a native separator at run time:
Tim Peters19397e52004-08-06 22:02:59 +00001962
1963 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
1964 >>> suite.run(unittest.TestResult())
1965 <unittest.TestResult run=1 errors=0 failures=1>
1966
Edward Loper0273f5b2004-09-18 20:27:04 +00001967 If DocFileSuite is used from an interactive session, then files
1968 are resolved relative to the directory of sys.argv[0]:
1969
Christian Heimesc756d002007-11-27 21:34:01 +00001970 >>> import types, os.path, test.test_doctest
Edward Loper0273f5b2004-09-18 20:27:04 +00001971 >>> save_argv = sys.argv
1972 >>> sys.argv = [test.test_doctest.__file__]
1973 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Christian Heimesc756d002007-11-27 21:34:01 +00001974 ... package=types.ModuleType('__main__'))
Edward Loper0273f5b2004-09-18 20:27:04 +00001975 >>> sys.argv = save_argv
1976
Edward Loper052d0cd2004-09-19 17:19:33 +00001977 By setting `module_relative=False`, os-specific paths may be
1978 used (including absolute paths and paths relative to the
1979 working directory):
Edward Loper0273f5b2004-09-18 20:27:04 +00001980
1981 >>> # Get the absolute path of the test package.
1982 >>> test_doctest_path = os.path.abspath(test.test_doctest.__file__)
1983 >>> test_pkg_path = os.path.split(test_doctest_path)[0]
1984
1985 >>> # Use it to find the absolute path of test_doctest.txt.
1986 >>> test_file = os.path.join(test_pkg_path, 'test_doctest.txt')
1987
Edward Loper052d0cd2004-09-19 17:19:33 +00001988 >>> suite = doctest.DocFileSuite(test_file, module_relative=False)
Edward Loper0273f5b2004-09-18 20:27:04 +00001989 >>> suite.run(unittest.TestResult())
1990 <unittest.TestResult run=1 errors=0 failures=1>
1991
Edward Loper052d0cd2004-09-19 17:19:33 +00001992 It is an error to specify `package` when `module_relative=False`:
1993
1994 >>> suite = doctest.DocFileSuite(test_file, module_relative=False,
1995 ... package='test')
1996 Traceback (most recent call last):
1997 ValueError: Package may only be specified for module-relative paths.
1998
Tim Peters19397e52004-08-06 22:02:59 +00001999 You can specify initial global variables:
2000
2001 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2002 ... 'test_doctest2.txt',
George Yoshidaf3c65de2006-05-28 16:39:09 +00002003 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002004 ... globs={'favorite_color': 'blue'})
2005 >>> suite.run(unittest.TestResult())
George Yoshidaf3c65de2006-05-28 16:39:09 +00002006 <unittest.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002007
2008 In this case, we supplied a missing favorite color. You can
2009 provide doctest options:
2010
2011 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2012 ... 'test_doctest2.txt',
George Yoshidaf3c65de2006-05-28 16:39:09 +00002013 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002014 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
2015 ... globs={'favorite_color': 'blue'})
2016 >>> suite.run(unittest.TestResult())
George Yoshidaf3c65de2006-05-28 16:39:09 +00002017 <unittest.TestResult run=3 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00002018
2019 And, you can provide setUp and tearDown functions:
2020
Jim Fultonf54bad42004-08-28 14:57:56 +00002021 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00002022 ... import test.test_doctest
2023 ... test.test_doctest.sillySetup = True
2024
Jim Fultonf54bad42004-08-28 14:57:56 +00002025 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00002026 ... import test.test_doctest
2027 ... del test.test_doctest.sillySetup
2028
2029 Here, we installed a silly variable that the test expects:
2030
2031 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2032 ... 'test_doctest2.txt',
George Yoshidaf3c65de2006-05-28 16:39:09 +00002033 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002034 ... setUp=setUp, tearDown=tearDown)
2035 >>> suite.run(unittest.TestResult())
George Yoshidaf3c65de2006-05-28 16:39:09 +00002036 <unittest.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002037
2038 But the tearDown restores sanity:
2039
2040 >>> import test.test_doctest
2041 >>> test.test_doctest.sillySetup
2042 Traceback (most recent call last):
2043 ...
2044 AttributeError: 'module' object has no attribute 'sillySetup'
2045
Jim Fultonf54bad42004-08-28 14:57:56 +00002046 The setUp and tearDown funtions are passed test objects.
2047 Here, we'll use a setUp function to set the favorite color in
2048 test_doctest.txt:
2049
2050 >>> def setUp(test):
2051 ... test.globs['favorite_color'] = 'blue'
2052
2053 >>> suite = doctest.DocFileSuite('test_doctest.txt', setUp=setUp)
2054 >>> suite.run(unittest.TestResult())
2055 <unittest.TestResult run=1 errors=0 failures=0>
2056
2057 Here, we didn't need to use a tearDown function because we
2058 modified the test globals. The test globals are
2059 automatically cleared for us after a test.
Tim Petersdf7a2082004-08-29 00:38:17 +00002060
Fred Drake7c404a42004-12-21 23:46:34 +00002061 Tests in a file run using `DocFileSuite` can also access the
2062 `__file__` global, which is set to the name of the file
2063 containing the tests:
2064
2065 >>> suite = doctest.DocFileSuite('test_doctest3.txt')
2066 >>> suite.run(unittest.TestResult())
2067 <unittest.TestResult run=1 errors=0 failures=0>
2068
George Yoshidaf3c65de2006-05-28 16:39:09 +00002069 If the tests contain non-ASCII characters, we have to specify which
2070 encoding the file is encoded with. We do so by using the `encoding`
2071 parameter:
2072
2073 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2074 ... 'test_doctest2.txt',
2075 ... 'test_doctest4.txt',
2076 ... encoding='utf-8')
2077 >>> suite.run(unittest.TestResult())
2078 <unittest.TestResult run=3 errors=0 failures=2>
2079
Jim Fultonf54bad42004-08-28 14:57:56 +00002080 """
Tim Peters19397e52004-08-06 22:02:59 +00002081
Jim Fulton07a349c2004-08-22 14:10:00 +00002082def test_trailing_space_in_test():
2083 """
Tim Petersa7def722004-08-23 22:13:22 +00002084 Trailing spaces in expected output are significant:
Tim Petersc6cbab02004-08-22 19:43:28 +00002085
Jim Fulton07a349c2004-08-22 14:10:00 +00002086 >>> x, y = 'foo', ''
2087 >>> print x, y
2088 foo \n
2089 """
Tim Peters19397e52004-08-06 22:02:59 +00002090
Jim Fultonf54bad42004-08-28 14:57:56 +00002091
2092def test_unittest_reportflags():
2093 """Default unittest reporting flags can be set to control reporting
2094
2095 Here, we'll set the REPORT_ONLY_FIRST_FAILURE option so we see
2096 only the first failure of each test. First, we'll look at the
2097 output without the flag. The file test_doctest.txt file has two
2098 tests. They both fail if blank lines are disabled:
2099
2100 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2101 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
2102 >>> import unittest
2103 >>> result = suite.run(unittest.TestResult())
2104 >>> print result.failures[0][1] # doctest: +ELLIPSIS
2105 Traceback ...
2106 Failed example:
2107 favorite_color
2108 ...
2109 Failed example:
2110 if 1:
2111 ...
2112
2113 Note that we see both failures displayed.
2114
2115 >>> old = doctest.set_unittest_reportflags(
2116 ... doctest.REPORT_ONLY_FIRST_FAILURE)
2117
2118 Now, when we run the test:
2119
2120 >>> result = suite.run(unittest.TestResult())
2121 >>> print result.failures[0][1] # doctest: +ELLIPSIS
2122 Traceback ...
2123 Failed example:
2124 favorite_color
2125 Exception raised:
2126 ...
2127 NameError: name 'favorite_color' is not defined
2128 <BLANKLINE>
2129 <BLANKLINE>
Tim Petersdf7a2082004-08-29 00:38:17 +00002130
Jim Fultonf54bad42004-08-28 14:57:56 +00002131 We get only the first failure.
2132
2133 If we give any reporting options when we set up the tests,
2134 however:
2135
2136 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2137 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE | doctest.REPORT_NDIFF)
2138
2139 Then the default eporting options are ignored:
2140
2141 >>> result = suite.run(unittest.TestResult())
2142 >>> print result.failures[0][1] # doctest: +ELLIPSIS
2143 Traceback ...
2144 Failed example:
2145 favorite_color
2146 ...
2147 Failed example:
2148 if 1:
2149 print 'a'
2150 print
2151 print 'b'
2152 Differences (ndiff with -expected +actual):
2153 a
2154 - <BLANKLINE>
2155 +
2156 b
2157 <BLANKLINE>
2158 <BLANKLINE>
2159
2160
2161 Test runners can restore the formatting flags after they run:
2162
2163 >>> ignored = doctest.set_unittest_reportflags(old)
2164
2165 """
2166
Edward Loper052d0cd2004-09-19 17:19:33 +00002167def test_testfile(): r"""
2168Tests for the `testfile()` function. This function runs all the
2169doctest examples in a given file. In its simple invokation, it is
2170called with the name of a file, which is taken to be relative to the
2171calling module. The return value is (#failures, #tests).
2172
Florent Xiclunab6d80cc2010-02-27 14:34:41 +00002173We don't want `-v` in sys.argv for these tests.
2174
2175 >>> save_argv = sys.argv
2176 >>> if '-v' in sys.argv:
2177 ... sys.argv = [arg for arg in save_argv if arg != '-v']
2178
2179
Edward Loper052d0cd2004-09-19 17:19:33 +00002180 >>> doctest.testfile('test_doctest.txt') # doctest: +ELLIPSIS
2181 **********************************************************************
2182 File "...", line 6, in test_doctest.txt
2183 Failed example:
2184 favorite_color
2185 Exception raised:
2186 ...
2187 NameError: name 'favorite_color' is not defined
2188 **********************************************************************
2189 1 items had failures:
2190 1 of 2 in test_doctest.txt
2191 ***Test Failed*** 1 failures.
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002192 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002193 >>> doctest.master = None # Reset master.
2194
2195(Note: we'll be clearing doctest.master after each call to
2196`doctest.testfile`, to supress warnings about multiple tests with the
2197same name.)
2198
2199Globals may be specified with the `globs` and `extraglobs` parameters:
2200
2201 >>> globs = {'favorite_color': 'blue'}
2202 >>> doctest.testfile('test_doctest.txt', globs=globs)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002203 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002204 >>> doctest.master = None # Reset master.
2205
2206 >>> extraglobs = {'favorite_color': 'red'}
2207 >>> doctest.testfile('test_doctest.txt', globs=globs,
2208 ... extraglobs=extraglobs) # doctest: +ELLIPSIS
2209 **********************************************************************
2210 File "...", line 6, in test_doctest.txt
2211 Failed example:
2212 favorite_color
2213 Expected:
2214 'blue'
2215 Got:
2216 'red'
2217 **********************************************************************
2218 1 items had failures:
2219 1 of 2 in test_doctest.txt
2220 ***Test Failed*** 1 failures.
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002221 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002222 >>> doctest.master = None # Reset master.
2223
2224The file may be made relative to a given module or package, using the
2225optional `module_relative` parameter:
2226
2227 >>> doctest.testfile('test_doctest.txt', globs=globs,
2228 ... module_relative='test')
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002229 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002230 >>> doctest.master = None # Reset master.
2231
2232Verbosity can be increased with the optional `verbose` paremter:
2233
2234 >>> doctest.testfile('test_doctest.txt', globs=globs, verbose=True)
2235 Trying:
2236 favorite_color
2237 Expecting:
2238 'blue'
2239 ok
2240 Trying:
2241 if 1:
2242 print 'a'
2243 print
2244 print 'b'
2245 Expecting:
2246 a
2247 <BLANKLINE>
2248 b
2249 ok
2250 1 items passed all tests:
2251 2 tests in test_doctest.txt
2252 2 tests in 1 items.
2253 2 passed and 0 failed.
2254 Test passed.
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002255 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002256 >>> doctest.master = None # Reset master.
2257
2258The name of the test may be specified with the optional `name`
2259parameter:
2260
2261 >>> doctest.testfile('test_doctest.txt', name='newname')
2262 ... # doctest: +ELLIPSIS
2263 **********************************************************************
2264 File "...", line 6, in newname
2265 ...
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002266 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002267 >>> doctest.master = None # Reset master.
2268
2269The summary report may be supressed with the optional `report`
2270parameter:
2271
2272 >>> doctest.testfile('test_doctest.txt', report=False)
2273 ... # doctest: +ELLIPSIS
2274 **********************************************************************
2275 File "...", line 6, in test_doctest.txt
2276 Failed example:
2277 favorite_color
2278 Exception raised:
2279 ...
2280 NameError: name 'favorite_color' is not defined
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002281 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002282 >>> doctest.master = None # Reset master.
2283
2284The optional keyword argument `raise_on_error` can be used to raise an
2285exception on the first error (which may be useful for postmortem
2286debugging):
2287
2288 >>> doctest.testfile('test_doctest.txt', raise_on_error=True)
2289 ... # doctest: +ELLIPSIS
2290 Traceback (most recent call last):
2291 UnexpectedException: ...
2292 >>> doctest.master = None # Reset master.
George Yoshidaf3c65de2006-05-28 16:39:09 +00002293
2294If the tests contain non-ASCII characters, the tests might fail, since
2295it's unknown which encoding is used. The encoding can be specified
2296using the optional keyword argument `encoding`:
2297
2298 >>> doctest.testfile('test_doctest4.txt') # doctest: +ELLIPSIS
2299 **********************************************************************
2300 File "...", line 7, in test_doctest4.txt
2301 Failed example:
2302 u'...'
2303 Expected:
2304 u'f\xf6\xf6'
2305 Got:
2306 u'f\xc3\xb6\xc3\xb6'
2307 **********************************************************************
2308 ...
2309 **********************************************************************
2310 1 items had failures:
2311 2 of 4 in test_doctest4.txt
2312 ***Test Failed*** 2 failures.
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002313 TestResults(failed=2, attempted=4)
George Yoshidaf3c65de2006-05-28 16:39:09 +00002314 >>> doctest.master = None # Reset master.
2315
2316 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8')
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002317 TestResults(failed=0, attempted=4)
George Yoshidaf3c65de2006-05-28 16:39:09 +00002318 >>> doctest.master = None # Reset master.
Florent Xiclunab6d80cc2010-02-27 14:34:41 +00002319
2320Switch the module encoding to 'utf-8' to test the verbose output without
2321bothering with the current sys.stdout encoding.
2322
2323 >>> doctest._encoding, saved_encoding = 'utf-8', doctest._encoding
2324 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8', verbose=True)
2325 Trying:
2326 u'föö'
2327 Expecting:
2328 u'f\xf6\xf6'
2329 ok
2330 Trying:
2331 u'bąr'
2332 Expecting:
2333 u'b\u0105r'
2334 ok
2335 Trying:
2336 'föö'
2337 Expecting:
2338 'f\xc3\xb6\xc3\xb6'
2339 ok
2340 Trying:
2341 'bąr'
2342 Expecting:
2343 'b\xc4\x85r'
2344 ok
2345 1 items passed all tests:
2346 4 tests in test_doctest4.txt
2347 4 tests in 1 items.
2348 4 passed and 0 failed.
2349 Test passed.
2350 TestResults(failed=0, attempted=4)
2351 >>> doctest._encoding = saved_encoding
2352 >>> doctest.master = None # Reset master.
2353 >>> sys.argv = save_argv
Edward Loper052d0cd2004-09-19 17:19:33 +00002354"""
2355
Tim Petersa7def722004-08-23 22:13:22 +00002356# old_test1, ... used to live in doctest.py, but cluttered it. Note
2357# that these use the deprecated doctest.Tester, so should go away (or
2358# be rewritten) someday.
2359
2360# Ignore all warnings about the use of class Tester in this module.
2361# Note that the name of this module may differ depending on how it's
2362# imported, so the use of __name__ is important.
2363warnings.filterwarnings("ignore", "class Tester", DeprecationWarning,
2364 __name__, 0)
2365
2366def old_test1(): r"""
2367>>> from doctest import Tester
2368>>> t = Tester(globs={'x': 42}, verbose=0)
2369>>> t.runstring(r'''
2370... >>> x = x * 2
2371... >>> print x
2372... 42
2373... ''', 'XYZ')
2374**********************************************************************
2375Line 3, in XYZ
2376Failed example:
2377 print x
2378Expected:
2379 42
2380Got:
2381 84
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002382TestResults(failed=1, attempted=2)
Tim Petersa7def722004-08-23 22:13:22 +00002383>>> t.runstring(">>> x = x * 2\n>>> print x\n84\n", 'example2')
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002384TestResults(failed=0, attempted=2)
Tim Petersa7def722004-08-23 22:13:22 +00002385>>> t.summarize()
2386**********************************************************************
23871 items had failures:
2388 1 of 2 in XYZ
2389***Test Failed*** 1 failures.
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002390TestResults(failed=1, attempted=4)
Tim Petersa7def722004-08-23 22:13:22 +00002391>>> t.summarize(verbose=1)
23921 items passed all tests:
2393 2 tests in example2
2394**********************************************************************
23951 items had failures:
2396 1 of 2 in XYZ
23974 tests in 2 items.
23983 passed and 1 failed.
2399***Test Failed*** 1 failures.
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002400TestResults(failed=1, attempted=4)
Tim Petersa7def722004-08-23 22:13:22 +00002401"""
2402
2403def old_test2(): r"""
2404 >>> from doctest import Tester
2405 >>> t = Tester(globs={}, verbose=1)
2406 >>> test = r'''
2407 ... # just an example
2408 ... >>> x = 1 + 2
2409 ... >>> x
2410 ... 3
2411 ... '''
2412 >>> t.runstring(test, "Example")
2413 Running string Example
Edward Loperaacf0832004-08-26 01:19:50 +00002414 Trying:
2415 x = 1 + 2
2416 Expecting nothing
Tim Petersa7def722004-08-23 22:13:22 +00002417 ok
Edward Loperaacf0832004-08-26 01:19:50 +00002418 Trying:
2419 x
2420 Expecting:
2421 3
Tim Petersa7def722004-08-23 22:13:22 +00002422 ok
2423 0 of 2 examples failed in string Example
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002424 TestResults(failed=0, attempted=2)
Tim Petersa7def722004-08-23 22:13:22 +00002425"""
2426
2427def old_test3(): r"""
2428 >>> from doctest import Tester
2429 >>> t = Tester(globs={}, verbose=0)
2430 >>> def _f():
2431 ... '''Trivial docstring example.
2432 ... >>> assert 2 == 2
2433 ... '''
2434 ... return 32
2435 ...
2436 >>> t.rundoc(_f) # expect 0 failures in 1 example
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002437 TestResults(failed=0, attempted=1)
Tim Petersa7def722004-08-23 22:13:22 +00002438"""
2439
2440def old_test4(): """
Christian Heimesc756d002007-11-27 21:34:01 +00002441 >>> import types
2442 >>> m1 = types.ModuleType('_m1')
2443 >>> m2 = types.ModuleType('_m2')
Tim Petersa7def722004-08-23 22:13:22 +00002444 >>> test_data = \"""
2445 ... def _f():
2446 ... '''>>> assert 1 == 1
2447 ... '''
2448 ... def g():
2449 ... '''>>> assert 2 != 1
2450 ... '''
2451 ... class H:
2452 ... '''>>> assert 2 > 1
2453 ... '''
2454 ... def bar(self):
2455 ... '''>>> assert 1 < 2
2456 ... '''
2457 ... \"""
2458 >>> exec test_data in m1.__dict__
2459 >>> exec test_data in m2.__dict__
2460 >>> m1.__dict__.update({"f2": m2._f, "g2": m2.g, "h2": m2.H})
2461
2462 Tests that objects outside m1 are excluded:
2463
2464 >>> from doctest import Tester
2465 >>> t = Tester(globs={}, verbose=0)
2466 >>> t.rundict(m1.__dict__, "rundict_test", m1) # f2 and g2 and h2 skipped
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002467 TestResults(failed=0, attempted=4)
Tim Petersa7def722004-08-23 22:13:22 +00002468
2469 Once more, not excluding stuff outside m1:
2470
2471 >>> t = Tester(globs={}, verbose=0)
2472 >>> t.rundict(m1.__dict__, "rundict_test_pvt") # None are skipped.
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002473 TestResults(failed=0, attempted=8)
Tim Petersa7def722004-08-23 22:13:22 +00002474
2475 The exclusion of objects from outside the designated module is
2476 meant to be invoked automagically by testmod.
2477
2478 >>> doctest.testmod(m1, verbose=False)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002479 TestResults(failed=0, attempted=4)
Tim Petersa7def722004-08-23 22:13:22 +00002480"""
2481
Tim Peters8485b562004-08-04 18:46:34 +00002482######################################################################
2483## Main
2484######################################################################
2485
2486def test_main():
2487 # Check the doctest cases in doctest itself:
2488 test_support.run_doctest(doctest, verbosity=True)
2489 # Check the doctest cases defined here:
2490 from test import test_doctest
2491 test_support.run_doctest(test_doctest, verbosity=True)
2492
Christian Heimesc5f05e42008-02-23 17:40:11 +00002493import trace, sys
Tim Peters8485b562004-08-04 18:46:34 +00002494def test_coverage(coverdir):
2495 tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
2496 trace=0, count=1)
2497 tracer.run('reload(doctest); test_main()')
2498 r = tracer.results()
2499 print 'Writing coverage results...'
2500 r.write_results(show_missing=True, summary=True,
2501 coverdir=coverdir)
2502
2503if __name__ == '__main__':
2504 if '-c' in sys.argv:
2505 test_coverage('/tmp/doctest.cover')
2506 else:
2507 test_main()