blob: a7477f2c436a6782c626f70f6c2052bb592409b7 [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
Ezio Melotti1d55ec32010-08-02 23:34:49 +00006import sys
Barry Warsaw04f357c2002-07-23 19:04:11 +00007from test import test_support
Tim Peters8485b562004-08-04 18:46:34 +00008import doctest
9
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"""
Georg Brandle64de922010-08-01 22:10:15 +0000911 def displayhook(): r"""
912Test that changing sys.displayhook doesn't matter for doctest.
913
914 >>> import sys
915 >>> orig_displayhook = sys.displayhook
916 >>> def my_displayhook(x):
917 ... print('hi!')
918 >>> sys.displayhook = my_displayhook
919 >>> def f():
920 ... '''
921 ... >>> 3
922 ... 3
923 ... '''
924 >>> test = doctest.DocTestFinder().find(f)[0]
925 >>> r = doctest.DocTestRunner(verbose=False).run(test)
926 >>> post_displayhook = sys.displayhook
927
928 We need to restore sys.displayhook now, so that we'll be able to test
929 results.
930
931 >>> sys.displayhook = orig_displayhook
932
933 Ok, now we can check that everything is ok.
934
935 >>> r
936 TestResults(failed=0, attempted=1)
937 >>> post_displayhook is my_displayhook
938 True
939"""
Tim Peters8485b562004-08-04 18:46:34 +0000940 def optionflags(): r"""
941Tests of `DocTestRunner`'s option flag handling.
942
943Several option flags can be used to customize the behavior of the test
944runner. These are defined as module constants in doctest, and passed
Georg Brandlf725b952008-01-05 19:44:22 +0000945to the DocTestRunner constructor (multiple constants should be ORed
Tim Peters8485b562004-08-04 18:46:34 +0000946together).
947
948The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
949and 1/0:
950
951 >>> def f(x):
952 ... '>>> True\n1\n'
953
954 >>> # Without the flag:
955 >>> test = doctest.DocTestFinder().find(f)[0]
956 >>> doctest.DocTestRunner(verbose=False).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000957 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000958
959 >>> # With the flag:
960 >>> test = doctest.DocTestFinder().find(f)[0]
961 >>> flags = doctest.DONT_ACCEPT_TRUE_FOR_1
962 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000963 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000964 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000965 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000966 Failed example:
967 True
968 Expected:
969 1
970 Got:
971 True
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000972 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000973
974The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines
975and the '<BLANKLINE>' marker:
976
977 >>> def f(x):
978 ... '>>> print "a\\n\\nb"\na\n<BLANKLINE>\nb\n'
979
980 >>> # Without the flag:
981 >>> test = doctest.DocTestFinder().find(f)[0]
982 >>> doctest.DocTestRunner(verbose=False).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +0000983 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +0000984
985 >>> # With the flag:
986 >>> test = doctest.DocTestFinder().find(f)[0]
987 >>> flags = doctest.DONT_ACCEPT_BLANKLINE
988 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000989 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000990 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000991 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000992 Failed example:
993 print "a\n\nb"
Tim Peters8485b562004-08-04 18:46:34 +0000994 Expected:
995 a
996 <BLANKLINE>
997 b
998 Got:
999 a
1000 <BLANKLINE>
1001 b
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001002 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001003
1004The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be
1005treated as equal:
1006
1007 >>> def f(x):
1008 ... '>>> print 1, 2, 3\n 1 2\n 3'
1009
1010 >>> # Without the flag:
1011 >>> test = doctest.DocTestFinder().find(f)[0]
1012 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001013 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001014 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001015 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001016 Failed example:
1017 print 1, 2, 3
Tim Peters8485b562004-08-04 18:46:34 +00001018 Expected:
1019 1 2
1020 3
Jim Fulton07a349c2004-08-22 14:10:00 +00001021 Got:
1022 1 2 3
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001023 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001024
1025 >>> # With the flag:
1026 >>> test = doctest.DocTestFinder().find(f)[0]
1027 >>> flags = doctest.NORMALIZE_WHITESPACE
1028 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001029 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001030
Tim Peters026f8dc2004-08-19 16:38:58 +00001031 An example from the docs:
1032 >>> print range(20) #doctest: +NORMALIZE_WHITESPACE
1033 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
1034 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
1035
Tim Peters8485b562004-08-04 18:46:34 +00001036The ELLIPSIS flag causes ellipsis marker ("...") in the expected
1037output to match any substring in the actual output:
1038
1039 >>> def f(x):
1040 ... '>>> print range(15)\n[0, 1, 2, ..., 14]\n'
1041
1042 >>> # Without the flag:
1043 >>> test = doctest.DocTestFinder().find(f)[0]
1044 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001045 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001046 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001047 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001048 Failed example:
1049 print range(15)
1050 Expected:
1051 [0, 1, 2, ..., 14]
1052 Got:
1053 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001054 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001055
1056 >>> # With the flag:
1057 >>> test = doctest.DocTestFinder().find(f)[0]
1058 >>> flags = doctest.ELLIPSIS
1059 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001060 TestResults(failed=0, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001061
Tim Peterse594bee2004-08-22 01:47:51 +00001062 ... also matches nothing:
Tim Peters1cf3aa62004-08-19 06:49:33 +00001063
1064 >>> for i in range(100):
Tim Peterse594bee2004-08-22 01:47:51 +00001065 ... print i**2, #doctest: +ELLIPSIS
1066 0 1...4...9 16 ... 36 49 64 ... 9801
Tim Peters1cf3aa62004-08-19 06:49:33 +00001067
Tim Peters026f8dc2004-08-19 16:38:58 +00001068 ... can be surprising; e.g., this test passes:
Tim Peters26b3ebb2004-08-19 08:10:08 +00001069
1070 >>> for i in range(21): #doctest: +ELLIPSIS
Tim Peterse594bee2004-08-22 01:47:51 +00001071 ... print i,
1072 0 1 2 ...1...2...0
Tim Peters26b3ebb2004-08-19 08:10:08 +00001073
Tim Peters026f8dc2004-08-19 16:38:58 +00001074 Examples from the docs:
1075
1076 >>> print range(20) # doctest:+ELLIPSIS
1077 [0, 1, ..., 18, 19]
1078
1079 >>> print range(20) # doctest: +ELLIPSIS
1080 ... # doctest: +NORMALIZE_WHITESPACE
1081 [0, 1, ..., 18, 19]
1082
Tim Peters711bf302006-04-25 03:31:36 +00001083The SKIP flag causes an example to be skipped entirely. I.e., the
1084example is not run. It can be useful in contexts where doctest
1085examples serve as both documentation and test cases, and an example
1086should be included for documentation purposes, but should not be
1087checked (e.g., because its output is random, or depends on resources
1088which would be unavailable.) The SKIP flag can also be used for
1089'commenting out' broken examples.
1090
1091 >>> import unavailable_resource # doctest: +SKIP
1092 >>> unavailable_resource.do_something() # doctest: +SKIP
1093 >>> unavailable_resource.blow_up() # doctest: +SKIP
1094 Traceback (most recent call last):
1095 ...
1096 UncheckedBlowUpError: Nobody checks me.
1097
1098 >>> import random
1099 >>> print random.random() # doctest: +SKIP
1100 0.721216923889
1101
Edward Loper71f55af2004-08-26 01:41:51 +00001102The REPORT_UDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001103and actual outputs to be displayed using a unified diff:
1104
1105 >>> def f(x):
1106 ... r'''
1107 ... >>> print '\n'.join('abcdefg')
1108 ... a
1109 ... B
1110 ... c
1111 ... d
1112 ... f
1113 ... g
1114 ... h
1115 ... '''
1116
1117 >>> # Without the flag:
1118 >>> test = doctest.DocTestFinder().find(f)[0]
1119 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001120 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001121 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001122 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001123 Failed example:
1124 print '\n'.join('abcdefg')
Tim Peters8485b562004-08-04 18:46:34 +00001125 Expected:
1126 a
1127 B
1128 c
1129 d
1130 f
1131 g
1132 h
1133 Got:
1134 a
1135 b
1136 c
1137 d
1138 e
1139 f
1140 g
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001141 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001142
1143 >>> # With the flag:
1144 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001145 >>> flags = doctest.REPORT_UDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001146 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001147 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001148 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001149 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001150 Failed example:
1151 print '\n'.join('abcdefg')
Edward Loper56629292004-08-26 01:31:56 +00001152 Differences (unified diff with -expected +actual):
Tim Peterse7edcb82004-08-26 05:44:27 +00001153 @@ -1,7 +1,7 @@
Tim Peters8485b562004-08-04 18:46:34 +00001154 a
1155 -B
1156 +b
1157 c
1158 d
1159 +e
1160 f
1161 g
1162 -h
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001163 TestResults(failed=1, attempted=1)
Tim Peters8485b562004-08-04 18:46:34 +00001164
Edward Loper71f55af2004-08-26 01:41:51 +00001165The REPORT_CDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001166and actual outputs to be displayed using a context diff:
1167
Edward Loper71f55af2004-08-26 01:41:51 +00001168 >>> # Reuse f() from the REPORT_UDIFF example, above.
Tim Peters8485b562004-08-04 18:46:34 +00001169 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001170 >>> flags = doctest.REPORT_CDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001171 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001172 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001173 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001174 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001175 Failed example:
1176 print '\n'.join('abcdefg')
Edward Loper56629292004-08-26 01:31:56 +00001177 Differences (context diff with expected followed by actual):
Tim Peters8485b562004-08-04 18:46:34 +00001178 ***************
Tim Peterse7edcb82004-08-26 05:44:27 +00001179 *** 1,7 ****
Tim Peters8485b562004-08-04 18:46:34 +00001180 a
1181 ! B
1182 c
1183 d
1184 f
1185 g
1186 - h
Tim Peterse7edcb82004-08-26 05:44:27 +00001187 --- 1,7 ----
Tim Peters8485b562004-08-04 18:46:34 +00001188 a
1189 ! b
1190 c
1191 d
1192 + e
1193 f
1194 g
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001195 TestResults(failed=1, attempted=1)
Tim Petersc6cbab02004-08-22 19:43:28 +00001196
1197
Edward Loper71f55af2004-08-26 01:41:51 +00001198The REPORT_NDIFF flag causes failures to use the difflib.Differ algorithm
Tim Petersc6cbab02004-08-22 19:43:28 +00001199used by the popular ndiff.py utility. This does intraline difference
1200marking, as well as interline differences.
1201
1202 >>> def f(x):
1203 ... r'''
1204 ... >>> print "a b c d e f g h i j k l m"
1205 ... a b c d e f g h i j k 1 m
1206 ... '''
1207 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001208 >>> flags = doctest.REPORT_NDIFF
Tim Petersc6cbab02004-08-22 19:43:28 +00001209 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001210 ... # doctest: +ELLIPSIS
Tim Petersc6cbab02004-08-22 19:43:28 +00001211 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001212 File ..., line 3, in f
Tim Petersc6cbab02004-08-22 19:43:28 +00001213 Failed example:
1214 print "a b c d e f g h i j k l m"
1215 Differences (ndiff with -expected +actual):
1216 - a b c d e f g h i j k 1 m
1217 ? ^
1218 + a b c d e f g h i j k l m
1219 ? + ++ ^
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001220 TestResults(failed=1, attempted=1)
Edward Lopera89f88d2004-08-26 02:45:51 +00001221
1222The REPORT_ONLY_FIRST_FAILURE supresses result output after the first
1223failing example:
1224
1225 >>> def f(x):
1226 ... r'''
1227 ... >>> print 1 # first success
1228 ... 1
1229 ... >>> print 2 # first failure
1230 ... 200
1231 ... >>> print 3 # second failure
1232 ... 300
1233 ... >>> print 4 # second success
1234 ... 4
1235 ... >>> print 5 # third failure
1236 ... 500
1237 ... '''
1238 >>> test = doctest.DocTestFinder().find(f)[0]
1239 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1240 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001241 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001242 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001243 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001244 Failed example:
1245 print 2 # first failure
1246 Expected:
1247 200
1248 Got:
1249 2
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001250 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001251
1252However, output from `report_start` is not supressed:
1253
1254 >>> doctest.DocTestRunner(verbose=True, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001255 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001256 Trying:
1257 print 1 # first success
1258 Expecting:
1259 1
1260 ok
1261 Trying:
1262 print 2 # first failure
1263 Expecting:
1264 200
1265 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001266 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001267 Failed example:
1268 print 2 # first failure
1269 Expected:
1270 200
1271 Got:
1272 2
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001273 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001274
1275For the purposes of REPORT_ONLY_FIRST_FAILURE, unexpected exceptions
1276count as failures:
1277
1278 >>> def f(x):
1279 ... r'''
1280 ... >>> print 1 # first success
1281 ... 1
1282 ... >>> raise ValueError(2) # first failure
1283 ... 200
1284 ... >>> print 3 # second failure
1285 ... 300
1286 ... >>> print 4 # second success
1287 ... 4
1288 ... >>> print 5 # third failure
1289 ... 500
1290 ... '''
1291 >>> test = doctest.DocTestFinder().find(f)[0]
1292 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1293 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1294 ... # doctest: +ELLIPSIS
1295 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001296 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001297 Failed example:
1298 raise ValueError(2) # first failure
1299 Exception raised:
1300 ...
1301 ValueError: 2
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001302 TestResults(failed=3, attempted=5)
Edward Lopera89f88d2004-08-26 02:45:51 +00001303
Tim Petersad2ef332006-05-10 02:43:01 +00001304New option flags can also be registered, via register_optionflag(). Here
1305we reach into doctest's internals a bit.
1306
1307 >>> unlikely = "UNLIKELY_OPTION_NAME"
1308 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1309 False
1310 >>> new_flag_value = doctest.register_optionflag(unlikely)
1311 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1312 True
1313
1314Before 2.4.4/2.5, registering a name more than once erroneously created
1315more than one flag value. Here we verify that's fixed:
1316
1317 >>> redundant_flag_value = doctest.register_optionflag(unlikely)
1318 >>> redundant_flag_value == new_flag_value
1319 True
1320
1321Clean up.
1322 >>> del doctest.OPTIONFLAGS_BY_NAME[unlikely]
1323
Tim Petersc6cbab02004-08-22 19:43:28 +00001324 """
1325
Tim Peters8485b562004-08-04 18:46:34 +00001326 def option_directives(): r"""
1327Tests of `DocTestRunner`'s option directive mechanism.
1328
Edward Loper74bca7a2004-08-12 02:27:44 +00001329Option directives can be used to turn option flags on or off for a
1330single example. To turn an option on for an example, follow that
1331example with a comment of the form ``# doctest: +OPTION``:
Tim Peters8485b562004-08-04 18:46:34 +00001332
1333 >>> def f(x): r'''
Edward Loper74bca7a2004-08-12 02:27:44 +00001334 ... >>> print range(10) # should fail: no ellipsis
1335 ... [0, 1, ..., 9]
1336 ...
1337 ... >>> print range(10) # doctest: +ELLIPSIS
1338 ... [0, 1, ..., 9]
1339 ... '''
1340 >>> test = doctest.DocTestFinder().find(f)[0]
1341 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001342 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001343 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001344 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001345 Failed example:
1346 print range(10) # should fail: no ellipsis
1347 Expected:
1348 [0, 1, ..., 9]
1349 Got:
1350 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001351 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001352
1353To turn an option off for an example, follow that example with a
1354comment of the form ``# doctest: -OPTION``:
1355
1356 >>> def f(x): r'''
1357 ... >>> print range(10)
1358 ... [0, 1, ..., 9]
1359 ...
1360 ... >>> # should fail: no ellipsis
1361 ... >>> print range(10) # doctest: -ELLIPSIS
1362 ... [0, 1, ..., 9]
1363 ... '''
1364 >>> test = doctest.DocTestFinder().find(f)[0]
1365 >>> doctest.DocTestRunner(verbose=False,
1366 ... optionflags=doctest.ELLIPSIS).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001367 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001368 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001369 File ..., line 6, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001370 Failed example:
1371 print range(10) # doctest: -ELLIPSIS
1372 Expected:
1373 [0, 1, ..., 9]
1374 Got:
1375 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001376 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001377
1378Option directives affect only the example that they appear with; they
1379do not change the options for surrounding examples:
Edward Loper8e4a34b2004-08-12 02:34:27 +00001380
Edward Loper74bca7a2004-08-12 02:27:44 +00001381 >>> def f(x): r'''
Tim Peters8485b562004-08-04 18:46:34 +00001382 ... >>> print range(10) # Should fail: no ellipsis
1383 ... [0, 1, ..., 9]
1384 ...
Edward Loper74bca7a2004-08-12 02:27:44 +00001385 ... >>> print range(10) # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001386 ... [0, 1, ..., 9]
1387 ...
Tim Peters8485b562004-08-04 18:46:34 +00001388 ... >>> print range(10) # Should fail: no ellipsis
1389 ... [0, 1, ..., 9]
1390 ... '''
1391 >>> test = doctest.DocTestFinder().find(f)[0]
1392 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001393 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001394 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001395 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001396 Failed example:
1397 print range(10) # Should fail: no ellipsis
1398 Expected:
1399 [0, 1, ..., 9]
1400 Got:
1401 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001402 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001403 File ..., line 8, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001404 Failed example:
1405 print range(10) # Should fail: no ellipsis
1406 Expected:
1407 [0, 1, ..., 9]
1408 Got:
1409 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001410 TestResults(failed=2, attempted=3)
Tim Peters8485b562004-08-04 18:46:34 +00001411
Edward Loper74bca7a2004-08-12 02:27:44 +00001412Multiple options may be modified by a single option directive. They
1413may be separated by whitespace, commas, or both:
Tim Peters8485b562004-08-04 18:46:34 +00001414
1415 >>> def f(x): r'''
1416 ... >>> print range(10) # Should fail
1417 ... [0, 1, ..., 9]
Tim Peters8485b562004-08-04 18:46:34 +00001418 ... >>> print range(10) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001419 ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001420 ... [0, 1, ..., 9]
1421 ... '''
1422 >>> test = doctest.DocTestFinder().find(f)[0]
1423 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001424 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001425 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001426 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001427 Failed example:
1428 print range(10) # Should fail
1429 Expected:
1430 [0, 1, ..., 9]
1431 Got:
1432 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001433 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001434
1435 >>> def f(x): r'''
1436 ... >>> print range(10) # Should fail
1437 ... [0, 1, ..., 9]
1438 ... >>> print range(10) # Should succeed
1439 ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
1440 ... [0, 1, ..., 9]
1441 ... '''
1442 >>> test = doctest.DocTestFinder().find(f)[0]
1443 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001444 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001445 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001446 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001447 Failed example:
1448 print range(10) # Should fail
1449 Expected:
1450 [0, 1, ..., 9]
1451 Got:
1452 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001453 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001454
1455 >>> def f(x): r'''
1456 ... >>> print range(10) # Should fail
1457 ... [0, 1, ..., 9]
1458 ... >>> print range(10) # Should succeed
1459 ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1460 ... [0, 1, ..., 9]
1461 ... '''
1462 >>> test = doctest.DocTestFinder().find(f)[0]
1463 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001464 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001465 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001466 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001467 Failed example:
1468 print range(10) # Should fail
1469 Expected:
1470 [0, 1, ..., 9]
1471 Got:
1472 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001473 TestResults(failed=1, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001474
1475The option directive may be put on the line following the source, as
1476long as a continuation prompt is used:
1477
1478 >>> def f(x): r'''
1479 ... >>> print range(10)
1480 ... ... # doctest: +ELLIPSIS
1481 ... [0, 1, ..., 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 Loper8e4a34b2004-08-12 02:34:27 +00001486
Edward Loper74bca7a2004-08-12 02:27:44 +00001487For examples with multi-line source, the option directive may appear
1488at the end of any line:
1489
1490 >>> def f(x): r'''
1491 ... >>> for x in range(10): # doctest: +ELLIPSIS
1492 ... ... print x,
1493 ... 0 1 2 ... 9
1494 ...
1495 ... >>> for x in range(10):
1496 ... ... print x, # doctest: +ELLIPSIS
1497 ... 0 1 2 ... 9
1498 ... '''
1499 >>> test = doctest.DocTestFinder().find(f)[0]
1500 >>> doctest.DocTestRunner(verbose=False).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001501 TestResults(failed=0, attempted=2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001502
1503If more than one line of an example with multi-line source has an
1504option directive, then they are combined:
1505
1506 >>> def f(x): r'''
1507 ... Should fail (option directive not on the last line):
1508 ... >>> for x in range(10): # doctest: +ELLIPSIS
1509 ... ... print x, # doctest: +NORMALIZE_WHITESPACE
1510 ... 0 1 2...9
1511 ... '''
1512 >>> test = doctest.DocTestFinder().find(f)[0]
1513 >>> doctest.DocTestRunner(verbose=False).run(test)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001514 TestResults(failed=0, attempted=1)
Edward Loper74bca7a2004-08-12 02:27:44 +00001515
1516It is an error to have a comment of the form ``# doctest:`` that is
1517*not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
1518``OPTION`` is an option that has been registered with
1519`register_option`:
1520
1521 >>> # Error: Option not registered
1522 >>> s = '>>> print 12 #doctest: +BADOPTION'
1523 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1524 Traceback (most recent call last):
1525 ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
1526
1527 >>> # Error: No + or - prefix
1528 >>> s = '>>> print 12 #doctest: ELLIPSIS'
1529 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1530 Traceback (most recent call last):
1531 ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
1532
1533It is an error to use an option directive on a line that contains no
1534source:
1535
1536 >>> s = '>>> # doctest: +ELLIPSIS'
1537 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1538 Traceback (most recent call last):
1539 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 +00001540
1541 """
1542
1543 def test_unicode_output(self): r"""
1544
1545Check that unicode output works:
1546
1547 >>> u'\xe9'
1548 u'\xe9'
1549
1550If we return unicode, SpoofOut's buf variable becomes automagically
1551converted to unicode. This means all subsequent output becomes converted
1552to unicode, and if the output contains non-ascii characters that failed.
1553It used to be that this state change carried on between tests, meaning
1554tests would fail if unicode has been output previously in the testrun.
1555This test tests that this is no longer so:
1556
1557 >>> print u'abc'
1558 abc
1559
1560And then return a string with non-ascii characters:
1561
1562 >>> print u'\xe9'.encode('utf-8')
1563 é
1564
1565 """
1566
Tim Peters8485b562004-08-04 18:46:34 +00001567
1568def test_testsource(): r"""
1569Unit tests for `testsource()`.
1570
1571The testsource() function takes a module and a name, finds the (first)
Tim Peters19397e52004-08-06 22:02:59 +00001572test with that name in that module, and converts it to a script. The
1573example code is converted to regular Python code. The surrounding
1574words and expected output are converted to comments:
Tim Peters8485b562004-08-04 18:46:34 +00001575
1576 >>> import test.test_doctest
1577 >>> name = 'test.test_doctest.sample_func'
1578 >>> print doctest.testsource(test.test_doctest, name)
Edward Lopera5db6002004-08-12 02:41:30 +00001579 # Blah blah
Tim Peters19397e52004-08-06 22:02:59 +00001580 #
Tim Peters8485b562004-08-04 18:46:34 +00001581 print sample_func(22)
1582 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001583 ## 44
Tim Peters19397e52004-08-06 22:02:59 +00001584 #
Edward Lopera5db6002004-08-12 02:41:30 +00001585 # Yee ha!
Georg Brandlecf93c72005-06-26 23:09:51 +00001586 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001587
1588 >>> name = 'test.test_doctest.SampleNewStyleClass'
1589 >>> print doctest.testsource(test.test_doctest, name)
1590 print '1\n2\n3'
1591 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001592 ## 1
1593 ## 2
1594 ## 3
Georg Brandlecf93c72005-06-26 23:09:51 +00001595 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001596
1597 >>> name = 'test.test_doctest.SampleClass.a_classmethod'
1598 >>> print doctest.testsource(test.test_doctest, name)
1599 print SampleClass.a_classmethod(10)
1600 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001601 ## 12
Tim Peters8485b562004-08-04 18:46:34 +00001602 print SampleClass(0).a_classmethod(10)
1603 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001604 ## 12
Georg Brandlecf93c72005-06-26 23:09:51 +00001605 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001606"""
1607
1608def test_debug(): r"""
1609
1610Create a docstring that we want to debug:
1611
1612 >>> s = '''
1613 ... >>> x = 12
1614 ... >>> print x
1615 ... 12
1616 ... '''
1617
1618Create some fake stdin input, to feed to the debugger:
1619
1620 >>> import tempfile
Tim Peters8485b562004-08-04 18:46:34 +00001621 >>> real_stdin = sys.stdin
Edward Loper2de91ba2004-08-27 02:07:46 +00001622 >>> sys.stdin = _FakeInput(['next', 'print x', 'continue'])
Tim Peters8485b562004-08-04 18:46:34 +00001623
1624Run the debugger on the docstring, and then restore sys.stdin.
1625
Edward Loper2de91ba2004-08-27 02:07:46 +00001626 >>> try: doctest.debug_src(s)
1627 ... finally: sys.stdin = real_stdin
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001628 > <string>(1)<module>()
Edward Loper2de91ba2004-08-27 02:07:46 +00001629 (Pdb) next
1630 12
Tim Peters8485b562004-08-04 18:46:34 +00001631 --Return--
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001632 > <string>(1)<module>()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001633 (Pdb) print x
1634 12
1635 (Pdb) continue
Tim Peters8485b562004-08-04 18:46:34 +00001636
1637"""
1638
Jim Fulton356fd192004-08-09 11:34:47 +00001639def test_pdb_set_trace():
Tim Peters50c6bdb2004-11-08 22:07:37 +00001640 """Using pdb.set_trace from a doctest.
Jim Fulton356fd192004-08-09 11:34:47 +00001641
Tim Peters413ced62004-08-09 15:43:47 +00001642 You can use pdb.set_trace from a doctest. To do so, you must
Jim Fulton356fd192004-08-09 11:34:47 +00001643 retrieve the set_trace function from the pdb module at the time
Tim Peters413ced62004-08-09 15:43:47 +00001644 you use it. The doctest module changes sys.stdout so that it can
1645 capture program output. It also temporarily replaces pdb.set_trace
1646 with a version that restores stdout. This is necessary for you to
Jim Fulton356fd192004-08-09 11:34:47 +00001647 see debugger output.
1648
1649 >>> doc = '''
1650 ... >>> x = 42
1651 ... >>> import pdb; pdb.set_trace()
1652 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001653 >>> parser = doctest.DocTestParser()
1654 >>> test = parser.get_doctest(doc, {}, "foo", "foo.py", 0)
Jim Fulton356fd192004-08-09 11:34:47 +00001655 >>> runner = doctest.DocTestRunner(verbose=False)
1656
1657 To demonstrate this, we'll create a fake standard input that
1658 captures our debugger input:
1659
1660 >>> import tempfile
Edward Loper2de91ba2004-08-27 02:07:46 +00001661 >>> real_stdin = sys.stdin
1662 >>> sys.stdin = _FakeInput([
Jim Fulton356fd192004-08-09 11:34:47 +00001663 ... '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
Edward Loper2de91ba2004-08-27 02:07:46 +00001667 >>> try: runner.run(test)
1668 ... finally: sys.stdin = real_stdin
Jim Fulton356fd192004-08-09 11:34:47 +00001669 --Return--
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001670 > <doctest foo[1]>(1)<module>()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001671 -> import pdb; pdb.set_trace()
1672 (Pdb) print x
1673 42
1674 (Pdb) continue
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001675 TestResults(failed=0, attempted=2)
Jim Fulton356fd192004-08-09 11:34:47 +00001676
1677 You can also put pdb.set_trace in a function called from a test:
1678
1679 >>> def calls_set_trace():
1680 ... y=2
1681 ... import pdb; pdb.set_trace()
1682
1683 >>> doc = '''
1684 ... >>> x=1
1685 ... >>> calls_set_trace()
1686 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001687 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
Edward Loper2de91ba2004-08-27 02:07:46 +00001688 >>> real_stdin = sys.stdin
1689 >>> sys.stdin = _FakeInput([
Jim Fulton356fd192004-08-09 11:34:47 +00001690 ... 'print y', # print data defined in the function
1691 ... 'up', # out of function
1692 ... 'print x', # print data defined by the example
1693 ... 'continue', # stop debugging
Edward Loper2de91ba2004-08-27 02:07:46 +00001694 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001695
Tim Peters50c6bdb2004-11-08 22:07:37 +00001696 >>> try:
1697 ... runner.run(test)
1698 ... finally:
1699 ... sys.stdin = real_stdin
Jim Fulton356fd192004-08-09 11:34:47 +00001700 --Return--
Edward Loper2de91ba2004-08-27 02:07:46 +00001701 > <doctest test.test_doctest.test_pdb_set_trace[8]>(3)calls_set_trace()->None
1702 -> import pdb; pdb.set_trace()
1703 (Pdb) print y
1704 2
1705 (Pdb) up
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001706 > <doctest foo[1]>(1)<module>()
Edward Loper2de91ba2004-08-27 02:07:46 +00001707 -> calls_set_trace()
1708 (Pdb) print x
1709 1
1710 (Pdb) continue
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001711 TestResults(failed=0, attempted=2)
Edward Loper2de91ba2004-08-27 02:07:46 +00001712
1713 During interactive debugging, source code is shown, even for
1714 doctest examples:
1715
1716 >>> doc = '''
1717 ... >>> def f(x):
1718 ... ... g(x*2)
1719 ... >>> def g(x):
1720 ... ... print x+3
1721 ... ... import pdb; pdb.set_trace()
1722 ... >>> f(3)
1723 ... '''
1724 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
1725 >>> real_stdin = sys.stdin
1726 >>> sys.stdin = _FakeInput([
1727 ... 'list', # list source from example 2
1728 ... 'next', # return from g()
1729 ... 'list', # list source from example 1
1730 ... 'next', # return from f()
1731 ... 'list', # list source from example 3
1732 ... 'continue', # stop debugging
1733 ... ''])
1734 >>> try: runner.run(test)
1735 ... finally: sys.stdin = real_stdin
1736 ... # doctest: +NORMALIZE_WHITESPACE
1737 --Return--
1738 > <doctest foo[1]>(3)g()->None
1739 -> import pdb; pdb.set_trace()
1740 (Pdb) list
1741 1 def g(x):
1742 2 print x+3
1743 3 -> import pdb; pdb.set_trace()
1744 [EOF]
1745 (Pdb) next
1746 --Return--
1747 > <doctest foo[0]>(2)f()->None
1748 -> g(x*2)
1749 (Pdb) list
1750 1 def f(x):
1751 2 -> g(x*2)
1752 [EOF]
1753 (Pdb) next
1754 --Return--
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001755 > <doctest foo[2]>(1)<module>()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001756 -> f(3)
1757 (Pdb) list
1758 1 -> f(3)
1759 [EOF]
1760 (Pdb) continue
1761 **********************************************************************
1762 File "foo.py", line 7, in foo
1763 Failed example:
1764 f(3)
1765 Expected nothing
1766 Got:
1767 9
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001768 TestResults(failed=1, attempted=3)
Jim Fulton356fd192004-08-09 11:34:47 +00001769 """
1770
Tim Peters50c6bdb2004-11-08 22:07:37 +00001771def test_pdb_set_trace_nested():
1772 """This illustrates more-demanding use of set_trace with nested functions.
1773
1774 >>> class C(object):
1775 ... def calls_set_trace(self):
1776 ... y = 1
1777 ... import pdb; pdb.set_trace()
1778 ... self.f1()
1779 ... y = 2
1780 ... def f1(self):
1781 ... x = 1
1782 ... self.f2()
1783 ... x = 2
1784 ... def f2(self):
1785 ... z = 1
1786 ... z = 2
1787
1788 >>> calls_set_trace = C().calls_set_trace
1789
1790 >>> doc = '''
1791 ... >>> a = 1
1792 ... >>> calls_set_trace()
1793 ... '''
1794 >>> parser = doctest.DocTestParser()
1795 >>> runner = doctest.DocTestRunner(verbose=False)
1796 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
1797 >>> real_stdin = sys.stdin
1798 >>> sys.stdin = _FakeInput([
1799 ... 'print y', # print data defined in the function
1800 ... 'step', 'step', 'step', 'step', 'step', 'step', 'print z',
1801 ... 'up', 'print x',
1802 ... 'up', 'print y',
1803 ... 'up', 'print foo',
1804 ... 'continue', # stop debugging
1805 ... ''])
1806
1807 >>> try:
1808 ... runner.run(test)
1809 ... finally:
1810 ... sys.stdin = real_stdin
1811 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
1812 -> self.f1()
1813 (Pdb) print y
1814 1
1815 (Pdb) step
1816 --Call--
1817 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(7)f1()
1818 -> def f1(self):
1819 (Pdb) step
1820 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(8)f1()
1821 -> x = 1
1822 (Pdb) step
1823 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
1824 -> self.f2()
1825 (Pdb) step
1826 --Call--
1827 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(11)f2()
1828 -> def f2(self):
1829 (Pdb) step
1830 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(12)f2()
1831 -> z = 1
1832 (Pdb) step
1833 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(13)f2()
1834 -> z = 2
1835 (Pdb) print z
1836 1
1837 (Pdb) up
1838 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
1839 -> self.f2()
1840 (Pdb) print x
1841 1
1842 (Pdb) up
1843 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
1844 -> self.f1()
1845 (Pdb) print y
1846 1
1847 (Pdb) up
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001848 > <doctest foo[1]>(1)<module>()
Tim Peters50c6bdb2004-11-08 22:07:37 +00001849 -> calls_set_trace()
1850 (Pdb) print foo
1851 *** NameError: name 'foo' is not defined
1852 (Pdb) continue
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00001853 TestResults(failed=0, attempted=2)
Tim Peters50c6bdb2004-11-08 22:07:37 +00001854"""
1855
Tim Peters19397e52004-08-06 22:02:59 +00001856def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +00001857 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +00001858
1859 We create a Suite by providing a module. A module can be provided
1860 by passing a module object:
1861
1862 >>> import unittest
1863 >>> import test.sample_doctest
1864 >>> suite = doctest.DocTestSuite(test.sample_doctest)
1865 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001866 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001867
1868 We can also supply the module by name:
1869
1870 >>> suite = doctest.DocTestSuite('test.sample_doctest')
1871 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001872 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001873
1874 We can use the current module:
1875
1876 >>> suite = test.sample_doctest.test_suite()
1877 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001878 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001879
1880 We can supply global variables. If we pass globs, they will be
1881 used instead of the module globals. Here we'll pass an empty
1882 globals, triggering an extra error:
1883
1884 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
1885 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001886 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001887
1888 Alternatively, we can provide extra globals. Here we'll make an
1889 error go away by providing an extra global variable:
1890
1891 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1892 ... extraglobs={'y': 1})
1893 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001894 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001895
1896 You can pass option flags. Here we'll cause an extra error
1897 by disabling the blank-line feature:
1898
1899 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00001900 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00001901 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001902 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001903
Tim Peters1e277ee2004-08-07 05:37:52 +00001904 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00001905
Jim Fultonf54bad42004-08-28 14:57:56 +00001906 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00001907 ... import test.test_doctest
1908 ... test.test_doctest.sillySetup = True
1909
Jim Fultonf54bad42004-08-28 14:57:56 +00001910 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00001911 ... import test.test_doctest
1912 ... del test.test_doctest.sillySetup
1913
1914 Here, we installed a silly variable that the test expects:
1915
1916 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1917 ... setUp=setUp, tearDown=tearDown)
1918 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001919 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001920
1921 But the tearDown restores sanity:
1922
1923 >>> import test.test_doctest
1924 >>> test.test_doctest.sillySetup
1925 Traceback (most recent call last):
1926 ...
1927 AttributeError: 'module' object has no attribute 'sillySetup'
1928
Jim Fultonf54bad42004-08-28 14:57:56 +00001929 The setUp and tearDown funtions are passed test objects. Here
1930 we'll use the setUp function to supply the missing variable y:
1931
1932 >>> def setUp(test):
1933 ... test.globs['y'] = 1
1934
1935 >>> suite = doctest.DocTestSuite('test.sample_doctest', setUp=setUp)
1936 >>> suite.run(unittest.TestResult())
1937 <unittest.TestResult run=9 errors=0 failures=3>
1938
1939 Here, we didn't need to use a tearDown function because we
1940 modified the test globals, which are a copy of the
1941 sample_doctest module dictionary. The test globals are
1942 automatically cleared for us after a test.
Tim Peters19397e52004-08-06 22:02:59 +00001943 """
1944
1945def test_DocFileSuite():
1946 """We can test tests found in text files using a DocFileSuite.
1947
1948 We create a suite by providing the names of one or more text
1949 files that include examples:
1950
1951 >>> import unittest
1952 >>> suite = doctest.DocFileSuite('test_doctest.txt',
George Yoshidaf3c65de2006-05-28 16:39:09 +00001953 ... 'test_doctest2.txt',
1954 ... 'test_doctest4.txt')
Tim Peters19397e52004-08-06 22:02:59 +00001955 >>> suite.run(unittest.TestResult())
George Yoshidaf3c65de2006-05-28 16:39:09 +00001956 <unittest.TestResult run=3 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001957
1958 The test files are looked for in the directory containing the
1959 calling module. A package keyword argument can be provided to
1960 specify a different relative location.
1961
1962 >>> import unittest
1963 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1964 ... 'test_doctest2.txt',
George Yoshidaf3c65de2006-05-28 16:39:09 +00001965 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00001966 ... package='test')
1967 >>> suite.run(unittest.TestResult())
George Yoshidaf3c65de2006-05-28 16:39:09 +00001968 <unittest.TestResult run=3 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001969
Brett Cannon43e53f82007-11-21 00:47:36 +00001970 Support for using a package's __loader__.get_data() is also
1971 provided.
1972
1973 >>> import unittest, pkgutil, test
Brett Cannoneaa2c982007-11-23 00:06:51 +00001974 >>> added_loader = False
Brett Cannon43e53f82007-11-21 00:47:36 +00001975 >>> if not hasattr(test, '__loader__'):
1976 ... test.__loader__ = pkgutil.get_loader(test)
1977 ... added_loader = True
1978 >>> try:
1979 ... suite = doctest.DocFileSuite('test_doctest.txt',
1980 ... 'test_doctest2.txt',
1981 ... 'test_doctest4.txt',
1982 ... package='test')
1983 ... suite.run(unittest.TestResult())
1984 ... finally:
Brett Cannon9db1d5a2007-11-21 00:58:03 +00001985 ... if added_loader:
1986 ... del test.__loader__
Brett Cannon43e53f82007-11-21 00:47:36 +00001987 <unittest.TestResult run=3 errors=0 failures=3>
1988
Edward Loper0273f5b2004-09-18 20:27:04 +00001989 '/' should be used as a path separator. It will be converted
1990 to a native separator at run time:
Tim Peters19397e52004-08-06 22:02:59 +00001991
1992 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
1993 >>> suite.run(unittest.TestResult())
1994 <unittest.TestResult run=1 errors=0 failures=1>
1995
Edward Loper0273f5b2004-09-18 20:27:04 +00001996 If DocFileSuite is used from an interactive session, then files
1997 are resolved relative to the directory of sys.argv[0]:
1998
Christian Heimesc756d002007-11-27 21:34:01 +00001999 >>> import types, os.path, test.test_doctest
Edward Loper0273f5b2004-09-18 20:27:04 +00002000 >>> save_argv = sys.argv
2001 >>> sys.argv = [test.test_doctest.__file__]
2002 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Christian Heimesc756d002007-11-27 21:34:01 +00002003 ... package=types.ModuleType('__main__'))
Edward Loper0273f5b2004-09-18 20:27:04 +00002004 >>> sys.argv = save_argv
2005
Edward Loper052d0cd2004-09-19 17:19:33 +00002006 By setting `module_relative=False`, os-specific paths may be
2007 used (including absolute paths and paths relative to the
2008 working directory):
Edward Loper0273f5b2004-09-18 20:27:04 +00002009
2010 >>> # Get the absolute path of the test package.
2011 >>> test_doctest_path = os.path.abspath(test.test_doctest.__file__)
2012 >>> test_pkg_path = os.path.split(test_doctest_path)[0]
2013
2014 >>> # Use it to find the absolute path of test_doctest.txt.
2015 >>> test_file = os.path.join(test_pkg_path, 'test_doctest.txt')
2016
Edward Loper052d0cd2004-09-19 17:19:33 +00002017 >>> suite = doctest.DocFileSuite(test_file, module_relative=False)
Edward Loper0273f5b2004-09-18 20:27:04 +00002018 >>> suite.run(unittest.TestResult())
2019 <unittest.TestResult run=1 errors=0 failures=1>
2020
Edward Loper052d0cd2004-09-19 17:19:33 +00002021 It is an error to specify `package` when `module_relative=False`:
2022
2023 >>> suite = doctest.DocFileSuite(test_file, module_relative=False,
2024 ... package='test')
2025 Traceback (most recent call last):
2026 ValueError: Package may only be specified for module-relative paths.
2027
Tim Peters19397e52004-08-06 22:02:59 +00002028 You can specify initial global variables:
2029
2030 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2031 ... 'test_doctest2.txt',
George Yoshidaf3c65de2006-05-28 16:39:09 +00002032 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002033 ... globs={'favorite_color': 'blue'})
2034 >>> suite.run(unittest.TestResult())
George Yoshidaf3c65de2006-05-28 16:39:09 +00002035 <unittest.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002036
2037 In this case, we supplied a missing favorite color. You can
2038 provide doctest options:
2039
2040 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2041 ... 'test_doctest2.txt',
George Yoshidaf3c65de2006-05-28 16:39:09 +00002042 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002043 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
2044 ... globs={'favorite_color': 'blue'})
2045 >>> suite.run(unittest.TestResult())
George Yoshidaf3c65de2006-05-28 16:39:09 +00002046 <unittest.TestResult run=3 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00002047
2048 And, you can provide setUp and tearDown functions:
2049
Jim Fultonf54bad42004-08-28 14:57:56 +00002050 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00002051 ... import test.test_doctest
2052 ... test.test_doctest.sillySetup = True
2053
Jim Fultonf54bad42004-08-28 14:57:56 +00002054 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00002055 ... import test.test_doctest
2056 ... del test.test_doctest.sillySetup
2057
2058 Here, we installed a silly variable that the test expects:
2059
2060 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2061 ... 'test_doctest2.txt',
George Yoshidaf3c65de2006-05-28 16:39:09 +00002062 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00002063 ... setUp=setUp, tearDown=tearDown)
2064 >>> suite.run(unittest.TestResult())
George Yoshidaf3c65de2006-05-28 16:39:09 +00002065 <unittest.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00002066
2067 But the tearDown restores sanity:
2068
2069 >>> import test.test_doctest
2070 >>> test.test_doctest.sillySetup
2071 Traceback (most recent call last):
2072 ...
2073 AttributeError: 'module' object has no attribute 'sillySetup'
2074
Jim Fultonf54bad42004-08-28 14:57:56 +00002075 The setUp and tearDown funtions are passed test objects.
2076 Here, we'll use a setUp function to set the favorite color in
2077 test_doctest.txt:
2078
2079 >>> def setUp(test):
2080 ... test.globs['favorite_color'] = 'blue'
2081
2082 >>> suite = doctest.DocFileSuite('test_doctest.txt', setUp=setUp)
2083 >>> suite.run(unittest.TestResult())
2084 <unittest.TestResult run=1 errors=0 failures=0>
2085
2086 Here, we didn't need to use a tearDown function because we
2087 modified the test globals. The test globals are
2088 automatically cleared for us after a test.
Tim Petersdf7a2082004-08-29 00:38:17 +00002089
Fred Drake7c404a42004-12-21 23:46:34 +00002090 Tests in a file run using `DocFileSuite` can also access the
2091 `__file__` global, which is set to the name of the file
2092 containing the tests:
2093
2094 >>> suite = doctest.DocFileSuite('test_doctest3.txt')
2095 >>> suite.run(unittest.TestResult())
2096 <unittest.TestResult run=1 errors=0 failures=0>
2097
George Yoshidaf3c65de2006-05-28 16:39:09 +00002098 If the tests contain non-ASCII characters, we have to specify which
2099 encoding the file is encoded with. We do so by using the `encoding`
2100 parameter:
2101
2102 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2103 ... 'test_doctest2.txt',
2104 ... 'test_doctest4.txt',
2105 ... encoding='utf-8')
2106 >>> suite.run(unittest.TestResult())
2107 <unittest.TestResult run=3 errors=0 failures=2>
2108
Jim Fultonf54bad42004-08-28 14:57:56 +00002109 """
Tim Peters19397e52004-08-06 22:02:59 +00002110
Jim Fulton07a349c2004-08-22 14:10:00 +00002111def test_trailing_space_in_test():
2112 """
Tim Petersa7def722004-08-23 22:13:22 +00002113 Trailing spaces in expected output are significant:
Tim Petersc6cbab02004-08-22 19:43:28 +00002114
Jim Fulton07a349c2004-08-22 14:10:00 +00002115 >>> x, y = 'foo', ''
2116 >>> print x, y
2117 foo \n
2118 """
Tim Peters19397e52004-08-06 22:02:59 +00002119
Jim Fultonf54bad42004-08-28 14:57:56 +00002120
2121def test_unittest_reportflags():
2122 """Default unittest reporting flags can be set to control reporting
2123
2124 Here, we'll set the REPORT_ONLY_FIRST_FAILURE option so we see
2125 only the first failure of each test. First, we'll look at the
2126 output without the flag. The file test_doctest.txt file has two
2127 tests. They both fail if blank lines are disabled:
2128
2129 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2130 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
2131 >>> import unittest
2132 >>> result = suite.run(unittest.TestResult())
2133 >>> print result.failures[0][1] # doctest: +ELLIPSIS
2134 Traceback ...
2135 Failed example:
2136 favorite_color
2137 ...
2138 Failed example:
2139 if 1:
2140 ...
2141
2142 Note that we see both failures displayed.
2143
2144 >>> old = doctest.set_unittest_reportflags(
2145 ... doctest.REPORT_ONLY_FIRST_FAILURE)
2146
2147 Now, when we run the test:
2148
2149 >>> result = suite.run(unittest.TestResult())
2150 >>> print result.failures[0][1] # doctest: +ELLIPSIS
2151 Traceback ...
2152 Failed example:
2153 favorite_color
2154 Exception raised:
2155 ...
2156 NameError: name 'favorite_color' is not defined
2157 <BLANKLINE>
2158 <BLANKLINE>
Tim Petersdf7a2082004-08-29 00:38:17 +00002159
Jim Fultonf54bad42004-08-28 14:57:56 +00002160 We get only the first failure.
2161
2162 If we give any reporting options when we set up the tests,
2163 however:
2164
2165 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2166 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE | doctest.REPORT_NDIFF)
2167
2168 Then the default eporting options are ignored:
2169
2170 >>> result = suite.run(unittest.TestResult())
2171 >>> print result.failures[0][1] # doctest: +ELLIPSIS
2172 Traceback ...
2173 Failed example:
2174 favorite_color
2175 ...
2176 Failed example:
2177 if 1:
2178 print 'a'
2179 print
2180 print 'b'
2181 Differences (ndiff with -expected +actual):
2182 a
2183 - <BLANKLINE>
2184 +
2185 b
2186 <BLANKLINE>
2187 <BLANKLINE>
2188
2189
2190 Test runners can restore the formatting flags after they run:
2191
2192 >>> ignored = doctest.set_unittest_reportflags(old)
2193
2194 """
2195
Edward Loper052d0cd2004-09-19 17:19:33 +00002196def test_testfile(): r"""
2197Tests for the `testfile()` function. This function runs all the
2198doctest examples in a given file. In its simple invokation, it is
2199called with the name of a file, which is taken to be relative to the
2200calling module. The return value is (#failures, #tests).
2201
Florent Xiclunab6d80cc2010-02-27 14:34:41 +00002202We don't want `-v` in sys.argv for these tests.
2203
2204 >>> save_argv = sys.argv
2205 >>> if '-v' in sys.argv:
2206 ... sys.argv = [arg for arg in save_argv if arg != '-v']
2207
2208
Edward Loper052d0cd2004-09-19 17:19:33 +00002209 >>> doctest.testfile('test_doctest.txt') # doctest: +ELLIPSIS
2210 **********************************************************************
2211 File "...", line 6, in test_doctest.txt
2212 Failed example:
2213 favorite_color
2214 Exception raised:
2215 ...
2216 NameError: name 'favorite_color' is not defined
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
2224(Note: we'll be clearing doctest.master after each call to
Ezio Melottia65e2af2010-08-02 19:56:05 +00002225`doctest.testfile`, to suppress warnings about multiple tests with the
Edward Loper052d0cd2004-09-19 17:19:33 +00002226same name.)
2227
2228Globals may be specified with the `globs` and `extraglobs` parameters:
2229
2230 >>> globs = {'favorite_color': 'blue'}
2231 >>> doctest.testfile('test_doctest.txt', globs=globs)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002232 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002233 >>> doctest.master = None # Reset master.
2234
2235 >>> extraglobs = {'favorite_color': 'red'}
2236 >>> doctest.testfile('test_doctest.txt', globs=globs,
2237 ... extraglobs=extraglobs) # doctest: +ELLIPSIS
2238 **********************************************************************
2239 File "...", line 6, in test_doctest.txt
2240 Failed example:
2241 favorite_color
2242 Expected:
2243 'blue'
2244 Got:
2245 'red'
2246 **********************************************************************
2247 1 items had failures:
2248 1 of 2 in test_doctest.txt
2249 ***Test Failed*** 1 failures.
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002250 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002251 >>> doctest.master = None # Reset master.
2252
2253The file may be made relative to a given module or package, using the
2254optional `module_relative` parameter:
2255
2256 >>> doctest.testfile('test_doctest.txt', globs=globs,
2257 ... module_relative='test')
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002258 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002259 >>> doctest.master = None # Reset master.
2260
2261Verbosity can be increased with the optional `verbose` paremter:
2262
2263 >>> doctest.testfile('test_doctest.txt', globs=globs, verbose=True)
2264 Trying:
2265 favorite_color
2266 Expecting:
2267 'blue'
2268 ok
2269 Trying:
2270 if 1:
2271 print 'a'
2272 print
2273 print 'b'
2274 Expecting:
2275 a
2276 <BLANKLINE>
2277 b
2278 ok
2279 1 items passed all tests:
2280 2 tests in test_doctest.txt
2281 2 tests in 1 items.
2282 2 passed and 0 failed.
2283 Test passed.
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002284 TestResults(failed=0, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002285 >>> doctest.master = None # Reset master.
2286
2287The name of the test may be specified with the optional `name`
2288parameter:
2289
2290 >>> doctest.testfile('test_doctest.txt', name='newname')
2291 ... # doctest: +ELLIPSIS
2292 **********************************************************************
2293 File "...", line 6, in newname
2294 ...
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002295 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002296 >>> doctest.master = None # Reset master.
2297
2298The summary report may be supressed with the optional `report`
2299parameter:
2300
2301 >>> doctest.testfile('test_doctest.txt', report=False)
2302 ... # doctest: +ELLIPSIS
2303 **********************************************************************
2304 File "...", line 6, in test_doctest.txt
2305 Failed example:
2306 favorite_color
2307 Exception raised:
2308 ...
2309 NameError: name 'favorite_color' is not defined
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002310 TestResults(failed=1, attempted=2)
Edward Loper052d0cd2004-09-19 17:19:33 +00002311 >>> doctest.master = None # Reset master.
2312
2313The optional keyword argument `raise_on_error` can be used to raise an
2314exception on the first error (which may be useful for postmortem
2315debugging):
2316
2317 >>> doctest.testfile('test_doctest.txt', raise_on_error=True)
2318 ... # doctest: +ELLIPSIS
2319 Traceback (most recent call last):
2320 UnexpectedException: ...
2321 >>> doctest.master = None # Reset master.
George Yoshidaf3c65de2006-05-28 16:39:09 +00002322
2323If the tests contain non-ASCII characters, the tests might fail, since
2324it's unknown which encoding is used. The encoding can be specified
2325using the optional keyword argument `encoding`:
2326
2327 >>> doctest.testfile('test_doctest4.txt') # doctest: +ELLIPSIS
2328 **********************************************************************
2329 File "...", line 7, in test_doctest4.txt
2330 Failed example:
2331 u'...'
2332 Expected:
2333 u'f\xf6\xf6'
2334 Got:
2335 u'f\xc3\xb6\xc3\xb6'
2336 **********************************************************************
2337 ...
2338 **********************************************************************
2339 1 items had failures:
2340 2 of 4 in test_doctest4.txt
2341 ***Test Failed*** 2 failures.
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002342 TestResults(failed=2, attempted=4)
George Yoshidaf3c65de2006-05-28 16:39:09 +00002343 >>> doctest.master = None # Reset master.
2344
2345 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8')
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002346 TestResults(failed=0, attempted=4)
George Yoshidaf3c65de2006-05-28 16:39:09 +00002347 >>> doctest.master = None # Reset master.
Florent Xiclunab6d80cc2010-02-27 14:34:41 +00002348
2349Switch the module encoding to 'utf-8' to test the verbose output without
2350bothering with the current sys.stdout encoding.
2351
2352 >>> doctest._encoding, saved_encoding = 'utf-8', doctest._encoding
2353 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8', verbose=True)
2354 Trying:
2355 u'föö'
2356 Expecting:
2357 u'f\xf6\xf6'
2358 ok
2359 Trying:
2360 u'bÄ…r'
2361 Expecting:
2362 u'b\u0105r'
2363 ok
2364 Trying:
2365 'föö'
2366 Expecting:
2367 'f\xc3\xb6\xc3\xb6'
2368 ok
2369 Trying:
2370 'bÄ…r'
2371 Expecting:
2372 'b\xc4\x85r'
2373 ok
2374 1 items passed all tests:
2375 4 tests in test_doctest4.txt
2376 4 tests in 1 items.
2377 4 passed and 0 failed.
2378 Test passed.
2379 TestResults(failed=0, attempted=4)
2380 >>> doctest._encoding = saved_encoding
2381 >>> doctest.master = None # Reset master.
2382 >>> sys.argv = save_argv
Edward Loper052d0cd2004-09-19 17:19:33 +00002383"""
2384
Tim Petersa7def722004-08-23 22:13:22 +00002385# old_test1, ... used to live in doctest.py, but cluttered it. Note
2386# that these use the deprecated doctest.Tester, so should go away (or
2387# be rewritten) someday.
2388
Tim Petersa7def722004-08-23 22:13:22 +00002389def old_test1(): r"""
2390>>> from doctest import Tester
2391>>> t = Tester(globs={'x': 42}, verbose=0)
2392>>> t.runstring(r'''
2393... >>> x = x * 2
2394... >>> print x
2395... 42
2396... ''', 'XYZ')
2397**********************************************************************
2398Line 3, in XYZ
2399Failed example:
2400 print x
2401Expected:
2402 42
2403Got:
2404 84
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002405TestResults(failed=1, attempted=2)
Tim Petersa7def722004-08-23 22:13:22 +00002406>>> t.runstring(">>> x = x * 2\n>>> print x\n84\n", 'example2')
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002407TestResults(failed=0, attempted=2)
Tim Petersa7def722004-08-23 22:13:22 +00002408>>> t.summarize()
2409**********************************************************************
24101 items had failures:
2411 1 of 2 in XYZ
2412***Test Failed*** 1 failures.
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002413TestResults(failed=1, attempted=4)
Tim Petersa7def722004-08-23 22:13:22 +00002414>>> t.summarize(verbose=1)
24151 items passed all tests:
2416 2 tests in example2
2417**********************************************************************
24181 items had failures:
2419 1 of 2 in XYZ
24204 tests in 2 items.
24213 passed and 1 failed.
2422***Test Failed*** 1 failures.
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002423TestResults(failed=1, attempted=4)
Tim Petersa7def722004-08-23 22:13:22 +00002424"""
2425
2426def old_test2(): r"""
2427 >>> from doctest import Tester
2428 >>> t = Tester(globs={}, verbose=1)
2429 >>> test = r'''
2430 ... # just an example
2431 ... >>> x = 1 + 2
2432 ... >>> x
2433 ... 3
2434 ... '''
2435 >>> t.runstring(test, "Example")
2436 Running string Example
Edward Loperaacf0832004-08-26 01:19:50 +00002437 Trying:
2438 x = 1 + 2
2439 Expecting nothing
Tim Petersa7def722004-08-23 22:13:22 +00002440 ok
Edward Loperaacf0832004-08-26 01:19:50 +00002441 Trying:
2442 x
2443 Expecting:
2444 3
Tim Petersa7def722004-08-23 22:13:22 +00002445 ok
2446 0 of 2 examples failed in string Example
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002447 TestResults(failed=0, attempted=2)
Tim Petersa7def722004-08-23 22:13:22 +00002448"""
2449
2450def old_test3(): r"""
2451 >>> from doctest import Tester
2452 >>> t = Tester(globs={}, verbose=0)
2453 >>> def _f():
2454 ... '''Trivial docstring example.
2455 ... >>> assert 2 == 2
2456 ... '''
2457 ... return 32
2458 ...
2459 >>> t.rundoc(_f) # expect 0 failures in 1 example
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002460 TestResults(failed=0, attempted=1)
Tim Petersa7def722004-08-23 22:13:22 +00002461"""
2462
2463def old_test4(): """
Christian Heimesc756d002007-11-27 21:34:01 +00002464 >>> import types
2465 >>> m1 = types.ModuleType('_m1')
2466 >>> m2 = types.ModuleType('_m2')
Tim Petersa7def722004-08-23 22:13:22 +00002467 >>> test_data = \"""
2468 ... def _f():
2469 ... '''>>> assert 1 == 1
2470 ... '''
2471 ... def g():
2472 ... '''>>> assert 2 != 1
2473 ... '''
2474 ... class H:
2475 ... '''>>> assert 2 > 1
2476 ... '''
2477 ... def bar(self):
2478 ... '''>>> assert 1 < 2
2479 ... '''
2480 ... \"""
2481 >>> exec test_data in m1.__dict__
2482 >>> exec test_data in m2.__dict__
2483 >>> m1.__dict__.update({"f2": m2._f, "g2": m2.g, "h2": m2.H})
2484
2485 Tests that objects outside m1 are excluded:
2486
2487 >>> from doctest import Tester
2488 >>> t = Tester(globs={}, verbose=0)
2489 >>> t.rundict(m1.__dict__, "rundict_test", m1) # f2 and g2 and h2 skipped
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002490 TestResults(failed=0, attempted=4)
Tim Petersa7def722004-08-23 22:13:22 +00002491
2492 Once more, not excluding stuff outside m1:
2493
2494 >>> t = Tester(globs={}, verbose=0)
2495 >>> t.rundict(m1.__dict__, "rundict_test_pvt") # None are skipped.
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002496 TestResults(failed=0, attempted=8)
Tim Petersa7def722004-08-23 22:13:22 +00002497
2498 The exclusion of objects from outside the designated module is
2499 meant to be invoked automagically by testmod.
2500
2501 >>> doctest.testmod(m1, verbose=False)
Raymond Hettingerfff4e6e2008-01-11 01:25:54 +00002502 TestResults(failed=0, attempted=4)
Tim Petersa7def722004-08-23 22:13:22 +00002503"""
2504
Tim Peters8485b562004-08-04 18:46:34 +00002505######################################################################
2506## Main
2507######################################################################
2508
2509def test_main():
2510 # Check the doctest cases in doctest itself:
2511 test_support.run_doctest(doctest, verbosity=True)
Ezio Melottia65e2af2010-08-02 19:56:05 +00002512
Tim Peters8485b562004-08-04 18:46:34 +00002513 from test import test_doctest
Ezio Melotti1d55ec32010-08-02 23:34:49 +00002514 # Ignore all warnings about the use of class Tester in this module.
2515 deprecations = [("class Tester is deprecated", DeprecationWarning)]
2516 if sys.py3kwarning:
2517 deprecations += [("backquote not supported", SyntaxWarning),
2518 ("execfile.. not supported", DeprecationWarning)]
2519 with test_support.check_warnings(*deprecations):
Ezio Melottia65e2af2010-08-02 19:56:05 +00002520 # Check the doctest cases defined here:
2521 test_support.run_doctest(test_doctest, verbosity=True)
Tim Peters8485b562004-08-04 18:46:34 +00002522
Christian Heimesc5f05e42008-02-23 17:40:11 +00002523import trace, sys
Tim Peters8485b562004-08-04 18:46:34 +00002524def test_coverage(coverdir):
2525 tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
2526 trace=0, count=1)
2527 tracer.run('reload(doctest); test_main()')
2528 r = tracer.results()
2529 print 'Writing coverage results...'
2530 r.write_results(show_missing=True, summary=True,
2531 coverdir=coverdir)
2532
2533if __name__ == '__main__':
2534 if '-c' in sys.argv:
2535 test_coverage('/tmp/doctest.cover')
2536 else:
2537 test_main()