blob: d17ca1a401511f4757091567850a52b9712d9c3e [file] [log] [blame]
Tim Peters8485b562004-08-04 18:46:34 +00001"""
2Test script for doctest.
3"""
4
Barry Warsaw04f357c2002-07-23 19:04:11 +00005from test import test_support
Tim Peters8485b562004-08-04 18:46:34 +00006import doctest
Tim Petersa7def722004-08-23 22:13:22 +00007import warnings
Tim Peters8485b562004-08-04 18:46:34 +00008
9######################################################################
10## Sample Objects (used by test cases)
11######################################################################
12
13def sample_func(v):
14 """
Tim Peters19397e52004-08-06 22:02:59 +000015 Blah blah
16
Tim Peters8485b562004-08-04 18:46:34 +000017 >>> print sample_func(22)
18 44
Tim Peters19397e52004-08-06 22:02:59 +000019
20 Yee ha!
Tim Peters8485b562004-08-04 18:46:34 +000021 """
22 return v+v
23
24class SampleClass:
25 """
26 >>> print 1
27 1
Edward Loper4ae900f2004-09-21 03:20:34 +000028
29 >>> # comments get ignored. so are empty PS1 and PS2 prompts:
30 >>>
31 ...
32
33 Multiline example:
34 >>> sc = SampleClass(3)
35 >>> for i in range(10):
36 ... sc = sc.double()
37 ... print sc.get(),
38 6 12 24 48 96 192 384 768 1536 3072
Tim Peters8485b562004-08-04 18:46:34 +000039 """
40 def __init__(self, val):
41 """
42 >>> print SampleClass(12).get()
43 12
44 """
45 self.val = val
46
47 def double(self):
48 """
49 >>> print SampleClass(12).double().get()
50 24
51 """
52 return SampleClass(self.val + self.val)
53
54 def get(self):
55 """
56 >>> print SampleClass(-5).get()
57 -5
58 """
59 return self.val
60
61 def a_staticmethod(v):
62 """
63 >>> print SampleClass.a_staticmethod(10)
64 11
65 """
66 return v+1
67 a_staticmethod = staticmethod(a_staticmethod)
68
69 def a_classmethod(cls, v):
70 """
71 >>> print SampleClass.a_classmethod(10)
72 12
73 >>> print SampleClass(0).a_classmethod(10)
74 12
75 """
76 return v+2
77 a_classmethod = classmethod(a_classmethod)
78
79 a_property = property(get, doc="""
80 >>> print SampleClass(22).a_property
81 22
82 """)
83
84 class NestedClass:
85 """
86 >>> x = SampleClass.NestedClass(5)
87 >>> y = x.square()
88 >>> print y.get()
89 25
90 """
91 def __init__(self, val=0):
92 """
93 >>> print SampleClass.NestedClass().get()
94 0
95 """
96 self.val = val
97 def square(self):
98 return SampleClass.NestedClass(self.val*self.val)
99 def get(self):
100 return self.val
101
102class SampleNewStyleClass(object):
103 r"""
104 >>> print '1\n2\n3'
105 1
106 2
107 3
108 """
109 def __init__(self, val):
110 """
111 >>> print SampleNewStyleClass(12).get()
112 12
113 """
114 self.val = val
115
116 def double(self):
117 """
118 >>> print SampleNewStyleClass(12).double().get()
119 24
120 """
121 return SampleNewStyleClass(self.val + self.val)
122
123 def get(self):
124 """
125 >>> print SampleNewStyleClass(-5).get()
126 -5
127 """
128 return self.val
129
130######################################################################
Edward Loper2de91ba2004-08-27 02:07:46 +0000131## Fake stdin (for testing interactive debugging)
132######################################################################
133
134class _FakeInput:
135 """
136 A fake input stream for pdb's interactive debugger. Whenever a
137 line is read, print it (to simulate the user typing it), and then
138 return it. The set of lines to return is specified in the
139 constructor; they should not have trailing newlines.
140 """
141 def __init__(self, lines):
142 self.lines = lines
143
144 def readline(self):
145 line = self.lines.pop(0)
146 print line
147 return line+'\n'
148
149######################################################################
Tim Peters8485b562004-08-04 18:46:34 +0000150## Test Cases
151######################################################################
152
153def test_Example(): r"""
154Unit tests for the `Example` class.
155
Edward Lopera6b68322004-08-26 00:05:43 +0000156Example is a simple container class that holds:
157 - `source`: A source string.
158 - `want`: An expected output string.
159 - `exc_msg`: An expected exception message string (or None if no
160 exception is expected).
161 - `lineno`: A line number (within the docstring).
162 - `indent`: The example's indentation in the input string.
163 - `options`: An option dictionary, mapping option flags to True or
164 False.
Tim Peters8485b562004-08-04 18:46:34 +0000165
Edward Lopera6b68322004-08-26 00:05:43 +0000166These attributes are set by the constructor. `source` and `want` are
167required; the other attributes all have default values:
Tim Peters8485b562004-08-04 18:46:34 +0000168
Edward Lopera6b68322004-08-26 00:05:43 +0000169 >>> example = doctest.Example('print 1', '1\n')
170 >>> (example.source, example.want, example.exc_msg,
171 ... example.lineno, example.indent, example.options)
172 ('print 1\n', '1\n', None, 0, 0, {})
173
174The first three attributes (`source`, `want`, and `exc_msg`) may be
175specified positionally; the remaining arguments should be specified as
176keyword arguments:
177
178 >>> exc_msg = 'IndexError: pop from an empty list'
179 >>> example = doctest.Example('[].pop()', '', exc_msg,
180 ... lineno=5, indent=4,
181 ... options={doctest.ELLIPSIS: True})
182 >>> (example.source, example.want, example.exc_msg,
183 ... example.lineno, example.indent, example.options)
184 ('[].pop()\n', '', 'IndexError: pop from an empty list\n', 5, 4, {8: True})
185
186The constructor normalizes the `source` string to end in a newline:
Tim Peters8485b562004-08-04 18:46:34 +0000187
Tim Petersbb431472004-08-09 03:51:46 +0000188 Source spans a single line: no terminating newline.
Edward Lopera6b68322004-08-26 00:05:43 +0000189 >>> e = doctest.Example('print 1', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000190 >>> e.source, e.want
191 ('print 1\n', '1\n')
192
Edward Lopera6b68322004-08-26 00:05:43 +0000193 >>> e = doctest.Example('print 1\n', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000194 >>> e.source, e.want
195 ('print 1\n', '1\n')
Tim Peters8485b562004-08-04 18:46:34 +0000196
Tim Petersbb431472004-08-09 03:51:46 +0000197 Source spans multiple lines: require terminating newline.
Edward Lopera6b68322004-08-26 00:05:43 +0000198 >>> e = doctest.Example('print 1;\nprint 2\n', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000199 >>> e.source, e.want
200 ('print 1;\nprint 2\n', '1\n2\n')
Tim Peters8485b562004-08-04 18:46:34 +0000201
Edward Lopera6b68322004-08-26 00:05:43 +0000202 >>> e = doctest.Example('print 1;\nprint 2', '1\n2\n')
Tim Petersbb431472004-08-09 03:51:46 +0000203 >>> e.source, e.want
204 ('print 1;\nprint 2\n', '1\n2\n')
205
Edward Lopera6b68322004-08-26 00:05:43 +0000206 Empty source string (which should never appear in real examples)
207 >>> e = doctest.Example('', '')
208 >>> e.source, e.want
209 ('\n', '')
Tim Peters8485b562004-08-04 18:46:34 +0000210
Edward Lopera6b68322004-08-26 00:05:43 +0000211The constructor normalizes the `want` string to end in a newline,
212unless it's the empty string:
213
214 >>> e = doctest.Example('print 1', '1\n')
Tim Petersbb431472004-08-09 03:51:46 +0000215 >>> e.source, e.want
216 ('print 1\n', '1\n')
217
Edward Lopera6b68322004-08-26 00:05:43 +0000218 >>> e = doctest.Example('print 1', '1')
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', '')
Tim Petersbb431472004-08-09 03:51:46 +0000223 >>> e.source, e.want
224 ('print\n', '')
Edward Lopera6b68322004-08-26 00:05:43 +0000225
226The constructor normalizes the `exc_msg` string to end in a newline,
227unless it's `None`:
228
229 Message spans one line
230 >>> exc_msg = 'IndexError: pop from an empty list'
231 >>> e = doctest.Example('[].pop()', '', exc_msg)
232 >>> e.exc_msg
233 'IndexError: pop from an empty list\n'
234
235 >>> exc_msg = 'IndexError: pop from an empty list\n'
236 >>> e = doctest.Example('[].pop()', '', exc_msg)
237 >>> e.exc_msg
238 'IndexError: pop from an empty list\n'
239
240 Message spans multiple lines
241 >>> exc_msg = 'ValueError: 1\n 2'
242 >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
243 >>> e.exc_msg
244 'ValueError: 1\n 2\n'
245
246 >>> exc_msg = 'ValueError: 1\n 2\n'
247 >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
248 >>> e.exc_msg
249 'ValueError: 1\n 2\n'
250
251 Empty (but non-None) exception message (which should never appear
252 in real examples)
253 >>> exc_msg = ''
254 >>> e = doctest.Example('raise X()', '', exc_msg)
255 >>> e.exc_msg
256 '\n'
Tim Peters8485b562004-08-04 18:46:34 +0000257"""
258
259def test_DocTest(): r"""
260Unit tests for the `DocTest` class.
261
262DocTest is a collection of examples, extracted from a docstring, along
263with information about where the docstring comes from (a name,
264filename, and line number). The docstring is parsed by the `DocTest`
265constructor:
266
267 >>> docstring = '''
268 ... >>> print 12
269 ... 12
270 ...
271 ... Non-example text.
272 ...
273 ... >>> print 'another\example'
274 ... another
275 ... example
276 ... '''
277 >>> globs = {} # globals to run the test in.
Edward Lopera1ef6112004-08-09 16:14:41 +0000278 >>> parser = doctest.DocTestParser()
279 >>> test = parser.get_doctest(docstring, globs, 'some_test',
280 ... 'some_file', 20)
Tim Peters8485b562004-08-04 18:46:34 +0000281 >>> print test
282 <DocTest some_test from some_file:20 (2 examples)>
283 >>> len(test.examples)
284 2
285 >>> e1, e2 = test.examples
286 >>> (e1.source, e1.want, e1.lineno)
Tim Petersbb431472004-08-09 03:51:46 +0000287 ('print 12\n', '12\n', 1)
Tim Peters8485b562004-08-04 18:46:34 +0000288 >>> (e2.source, e2.want, e2.lineno)
Tim Petersbb431472004-08-09 03:51:46 +0000289 ("print 'another\\example'\n", 'another\nexample\n', 6)
Tim Peters8485b562004-08-04 18:46:34 +0000290
291Source information (name, filename, and line number) is available as
292attributes on the doctest object:
293
294 >>> (test.name, test.filename, test.lineno)
295 ('some_test', 'some_file', 20)
296
297The line number of an example within its containing file is found by
298adding the line number of the example and the line number of its
299containing test:
300
301 >>> test.lineno + e1.lineno
302 21
303 >>> test.lineno + e2.lineno
304 26
305
306If the docstring contains inconsistant leading whitespace in the
307expected output of an example, then `DocTest` will raise a ValueError:
308
309 >>> docstring = r'''
310 ... >>> print 'bad\nindentation'
311 ... bad
312 ... indentation
313 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000314 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000315 Traceback (most recent call last):
Edward Loper00f8da72004-08-26 18:05:07 +0000316 ValueError: line 4 of the docstring for some_test has inconsistent leading whitespace: 'indentation'
Tim Peters8485b562004-08-04 18:46:34 +0000317
318If the docstring contains inconsistent leading whitespace on
319continuation lines, then `DocTest` will raise a ValueError:
320
321 >>> docstring = r'''
322 ... >>> print ('bad indentation',
323 ... ... 2)
324 ... ('bad', 'indentation')
325 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000326 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000327 Traceback (most recent call last):
Edward Loper00f8da72004-08-26 18:05:07 +0000328 ValueError: line 2 of the docstring for some_test has inconsistent leading whitespace: '... 2)'
Tim Peters8485b562004-08-04 18:46:34 +0000329
330If there's no blank space after a PS1 prompt ('>>>'), then `DocTest`
331will raise a ValueError:
332
333 >>> docstring = '>>>print 1\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000334 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Tim Peters8485b562004-08-04 18:46:34 +0000335 Traceback (most recent call last):
Edward Loper7c748462004-08-09 02:06:06 +0000336 ValueError: line 1 of the docstring for some_test lacks blank after >>>: '>>>print 1'
337
338If there's no blank space after a PS2 prompt ('...'), then `DocTest`
339will raise a ValueError:
340
341 >>> docstring = '>>> if 1:\n...print 1\n1'
Edward Lopera1ef6112004-08-09 16:14:41 +0000342 >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Edward Loper7c748462004-08-09 02:06:06 +0000343 Traceback (most recent call last):
344 ValueError: line 2 of the docstring for some_test lacks blank after ...: '...print 1'
345
Tim Peters8485b562004-08-04 18:46:34 +0000346"""
347
Tim Peters8485b562004-08-04 18:46:34 +0000348def test_DocTestFinder(): r"""
349Unit tests for the `DocTestFinder` class.
350
351DocTestFinder is used to extract DocTests from an object's docstring
352and the docstrings of its contained objects. It can be used with
353modules, functions, classes, methods, staticmethods, classmethods, and
354properties.
355
356Finding Tests in Functions
357~~~~~~~~~~~~~~~~~~~~~~~~~~
358For a function whose docstring contains examples, DocTestFinder.find()
359will return a single test (for that function's docstring):
360
Tim Peters8485b562004-08-04 18:46:34 +0000361 >>> finder = doctest.DocTestFinder()
Jim Fulton07a349c2004-08-22 14:10:00 +0000362
363We'll simulate a __file__ attr that ends in pyc:
364
365 >>> import test.test_doctest
366 >>> old = test.test_doctest.__file__
367 >>> test.test_doctest.__file__ = 'test_doctest.pyc'
368
Tim Peters8485b562004-08-04 18:46:34 +0000369 >>> tests = finder.find(sample_func)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000370
Edward Loper74bca7a2004-08-12 02:27:44 +0000371 >>> print tests # doctest: +ELLIPSIS
Tim Petersa7def722004-08-23 22:13:22 +0000372 [<DocTest sample_func from ...:13 (1 example)>]
Edward Loper8e4a34b2004-08-12 02:34:27 +0000373
Tim Peters4de7c5c2004-08-23 22:38:05 +0000374The exact name depends on how test_doctest was invoked, so allow for
375leading path components.
376
377 >>> tests[0].filename # doctest: +ELLIPSIS
378 '...test_doctest.py'
Jim Fulton07a349c2004-08-22 14:10:00 +0000379
380 >>> test.test_doctest.__file__ = old
Tim Petersc6cbab02004-08-22 19:43:28 +0000381
Jim Fulton07a349c2004-08-22 14:10:00 +0000382
Tim Peters8485b562004-08-04 18:46:34 +0000383 >>> e = tests[0].examples[0]
Tim Petersbb431472004-08-09 03:51:46 +0000384 >>> (e.source, e.want, e.lineno)
385 ('print sample_func(22)\n', '44\n', 3)
Tim Peters8485b562004-08-04 18:46:34 +0000386
Edward Loper32ddbf72004-09-13 05:47:24 +0000387By default, tests are created for objects with no docstring:
Tim Peters8485b562004-08-04 18:46:34 +0000388
389 >>> def no_docstring(v):
390 ... pass
Tim Peters958cc892004-09-13 14:53:28 +0000391 >>> finder.find(no_docstring)
392 []
Edward Loper32ddbf72004-09-13 05:47:24 +0000393
394However, the optional argument `exclude_empty` to the DocTestFinder
395constructor can be used to exclude tests for objects with empty
396docstrings:
397
398 >>> def no_docstring(v):
399 ... pass
400 >>> excl_empty_finder = doctest.DocTestFinder(exclude_empty=True)
401 >>> excl_empty_finder.find(no_docstring)
Tim Peters8485b562004-08-04 18:46:34 +0000402 []
403
404If the function has a docstring with no examples, then a test with no
405examples is returned. (This lets `DocTestRunner` collect statistics
406about which functions have no tests -- but is that useful? And should
407an empty test also be created when there's no docstring?)
408
409 >>> def no_examples(v):
410 ... ''' no doctest examples '''
Tim Peters17b56372004-09-11 17:33:27 +0000411 >>> finder.find(no_examples) # doctest: +ELLIPSIS
412 [<DocTest no_examples from ...:1 (no examples)>]
Tim Peters8485b562004-08-04 18:46:34 +0000413
414Finding Tests in Classes
415~~~~~~~~~~~~~~~~~~~~~~~~
416For a class, DocTestFinder will create a test for the class's
417docstring, and will recursively explore its contents, including
418methods, classmethods, staticmethods, properties, and nested classes.
419
420 >>> finder = doctest.DocTestFinder()
421 >>> tests = finder.find(SampleClass)
422 >>> tests.sort()
423 >>> for t in tests:
424 ... print '%2s %s' % (len(t.examples), t.name)
Edward Loper4ae900f2004-09-21 03:20:34 +0000425 3 SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000426 3 SampleClass.NestedClass
427 1 SampleClass.NestedClass.__init__
428 1 SampleClass.__init__
429 2 SampleClass.a_classmethod
430 1 SampleClass.a_property
431 1 SampleClass.a_staticmethod
432 1 SampleClass.double
433 1 SampleClass.get
434
435New-style classes are also supported:
436
437 >>> tests = finder.find(SampleNewStyleClass)
438 >>> tests.sort()
439 >>> for t in tests:
440 ... print '%2s %s' % (len(t.examples), t.name)
441 1 SampleNewStyleClass
442 1 SampleNewStyleClass.__init__
443 1 SampleNewStyleClass.double
444 1 SampleNewStyleClass.get
445
446Finding Tests in Modules
447~~~~~~~~~~~~~~~~~~~~~~~~
448For a module, DocTestFinder will create a test for the class's
449docstring, and will recursively explore its contents, including
450functions, classes, and the `__test__` dictionary, if it exists:
451
452 >>> # A module
453 >>> import new
454 >>> m = new.module('some_module')
455 >>> def triple(val):
456 ... '''
Edward Loper4ae900f2004-09-21 03:20:34 +0000457 ... >>> print triple(11)
Tim Peters8485b562004-08-04 18:46:34 +0000458 ... 33
459 ... '''
460 ... return val*3
461 >>> m.__dict__.update({
462 ... 'sample_func': sample_func,
463 ... 'SampleClass': SampleClass,
464 ... '__doc__': '''
465 ... Module docstring.
466 ... >>> print 'module'
467 ... module
468 ... ''',
469 ... '__test__': {
470 ... 'd': '>>> print 6\n6\n>>> print 7\n7\n',
471 ... 'c': triple}})
472
473 >>> finder = doctest.DocTestFinder()
474 >>> # Use module=test.test_doctest, to prevent doctest from
475 >>> # ignoring the objects since they weren't defined in m.
476 >>> import test.test_doctest
477 >>> tests = finder.find(m, module=test.test_doctest)
478 >>> tests.sort()
479 >>> for t in tests:
480 ... print '%2s %s' % (len(t.examples), t.name)
481 1 some_module
Edward Loper4ae900f2004-09-21 03:20:34 +0000482 3 some_module.SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000483 3 some_module.SampleClass.NestedClass
484 1 some_module.SampleClass.NestedClass.__init__
485 1 some_module.SampleClass.__init__
486 2 some_module.SampleClass.a_classmethod
487 1 some_module.SampleClass.a_property
488 1 some_module.SampleClass.a_staticmethod
489 1 some_module.SampleClass.double
490 1 some_module.SampleClass.get
Tim Petersc5684782004-09-13 01:07:12 +0000491 1 some_module.__test__.c
492 2 some_module.__test__.d
Tim Peters8485b562004-08-04 18:46:34 +0000493 1 some_module.sample_func
494
495Duplicate Removal
496~~~~~~~~~~~~~~~~~
497If a single object is listed twice (under different names), then tests
498will only be generated for it once:
499
Tim Petersf3f57472004-08-08 06:11:48 +0000500 >>> from test import doctest_aliases
Edward Loper32ddbf72004-09-13 05:47:24 +0000501 >>> tests = excl_empty_finder.find(doctest_aliases)
Tim Peters8485b562004-08-04 18:46:34 +0000502 >>> tests.sort()
503 >>> 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
515Filter Functions
516~~~~~~~~~~~~~~~~
Tim Petersf727c6c2004-08-08 01:48:59 +0000517A filter function can be used to restrict which objects get examined,
518but this is temporary, undocumented internal support for testmod's
519deprecated isprivate gimmick.
Tim Peters8485b562004-08-04 18:46:34 +0000520
521 >>> def namefilter(prefix, base):
522 ... return base.startswith('a_')
Tim Petersf727c6c2004-08-08 01:48:59 +0000523 >>> tests = doctest.DocTestFinder(_namefilter=namefilter).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000524 >>> tests.sort()
525 >>> for t in tests:
526 ... print '%2s %s' % (len(t.examples), t.name)
Edward Loper4ae900f2004-09-21 03:20:34 +0000527 3 SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000528 3 SampleClass.NestedClass
529 1 SampleClass.NestedClass.__init__
Tim Peters958cc892004-09-13 14:53:28 +0000530 1 SampleClass.__init__
531 1 SampleClass.double
532 1 SampleClass.get
533
534By default, that excluded objects with no doctests. exclude_empty=False
535tells it to include (empty) tests for objects with no doctests. This feature
536is really to support backward compatibility in what doctest.master.summarize()
537displays.
538
539 >>> tests = doctest.DocTestFinder(_namefilter=namefilter,
540 ... exclude_empty=False).find(SampleClass)
541 >>> tests.sort()
542 >>> for t in tests:
543 ... print '%2s %s' % (len(t.examples), t.name)
Edward Loper4ae900f2004-09-21 03:20:34 +0000544 3 SampleClass
Tim Peters958cc892004-09-13 14:53:28 +0000545 3 SampleClass.NestedClass
546 1 SampleClass.NestedClass.__init__
Edward Loper32ddbf72004-09-13 05:47:24 +0000547 0 SampleClass.NestedClass.get
548 0 SampleClass.NestedClass.square
Tim Peters8485b562004-08-04 18:46:34 +0000549 1 SampleClass.__init__
550 1 SampleClass.double
551 1 SampleClass.get
552
Tim Peters8485b562004-08-04 18:46:34 +0000553If a given object is filtered out, then none of the objects that it
554contains will be added either:
555
556 >>> def namefilter(prefix, base):
557 ... return base == 'NestedClass'
Tim Petersf727c6c2004-08-08 01:48:59 +0000558 >>> tests = doctest.DocTestFinder(_namefilter=namefilter).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000559 >>> tests.sort()
560 >>> for t in tests:
561 ... print '%2s %s' % (len(t.examples), t.name)
Edward Loper4ae900f2004-09-21 03:20:34 +0000562 3 SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000563 1 SampleClass.__init__
564 2 SampleClass.a_classmethod
565 1 SampleClass.a_property
566 1 SampleClass.a_staticmethod
567 1 SampleClass.double
568 1 SampleClass.get
569
Tim Petersf727c6c2004-08-08 01:48:59 +0000570The filter function apply to contained objects, and *not* to the
Tim Peters8485b562004-08-04 18:46:34 +0000571object explicitly passed to DocTestFinder:
572
573 >>> def namefilter(prefix, base):
574 ... return base == 'SampleClass'
Tim Petersf727c6c2004-08-08 01:48:59 +0000575 >>> tests = doctest.DocTestFinder(_namefilter=namefilter).find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000576 >>> len(tests)
Tim Peters958cc892004-09-13 14:53:28 +0000577 9
Tim Peters8485b562004-08-04 18:46:34 +0000578
579Turning off Recursion
580~~~~~~~~~~~~~~~~~~~~~
581DocTestFinder can be told not to look for tests in contained objects
582using the `recurse` flag:
583
584 >>> tests = doctest.DocTestFinder(recurse=False).find(SampleClass)
585 >>> tests.sort()
586 >>> for t in tests:
587 ... print '%2s %s' % (len(t.examples), t.name)
Edward Loper4ae900f2004-09-21 03:20:34 +0000588 3 SampleClass
Edward Loperb51b2342004-08-17 16:37:12 +0000589
590Line numbers
591~~~~~~~~~~~~
592DocTestFinder finds the line number of each example:
593
594 >>> def f(x):
595 ... '''
596 ... >>> x = 12
597 ...
598 ... some text
599 ...
600 ... >>> # examples are not created for comments & bare prompts.
601 ... >>>
602 ... ...
603 ...
604 ... >>> for x in range(10):
605 ... ... print x,
606 ... 0 1 2 3 4 5 6 7 8 9
607 ... >>> x/2
608 ... 6
609 ... '''
610 >>> test = doctest.DocTestFinder().find(f)[0]
611 >>> [e.lineno for e in test.examples]
612 [1, 9, 12]
Tim Peters8485b562004-08-04 18:46:34 +0000613"""
614
Edward Loper00f8da72004-08-26 18:05:07 +0000615def test_DocTestParser(): r"""
616Unit tests for the `DocTestParser` class.
617
618DocTestParser is used to parse docstrings containing doctest examples.
619
620The `parse` method divides a docstring into examples and intervening
621text:
622
623 >>> s = '''
624 ... >>> x, y = 2, 3 # no output expected
625 ... >>> if 1:
626 ... ... print x
627 ... ... print y
628 ... 2
629 ... 3
630 ...
631 ... Some text.
632 ... >>> x+y
633 ... 5
634 ... '''
635 >>> parser = doctest.DocTestParser()
636 >>> for piece in parser.parse(s):
637 ... if isinstance(piece, doctest.Example):
638 ... print 'Example:', (piece.source, piece.want, piece.lineno)
639 ... else:
640 ... print ' Text:', `piece`
641 Text: '\n'
642 Example: ('x, y = 2, 3 # no output expected\n', '', 1)
643 Text: ''
644 Example: ('if 1:\n print x\n print y\n', '2\n3\n', 2)
645 Text: '\nSome text.\n'
646 Example: ('x+y\n', '5\n', 9)
647 Text: ''
648
649The `get_examples` method returns just the examples:
650
651 >>> for piece in parser.get_examples(s):
652 ... print (piece.source, piece.want, piece.lineno)
653 ('x, y = 2, 3 # no output expected\n', '', 1)
654 ('if 1:\n print x\n print y\n', '2\n3\n', 2)
655 ('x+y\n', '5\n', 9)
656
657The `get_doctest` method creates a Test from the examples, along with the
658given arguments:
659
660 >>> test = parser.get_doctest(s, {}, 'name', 'filename', lineno=5)
661 >>> (test.name, test.filename, test.lineno)
662 ('name', 'filename', 5)
663 >>> for piece in test.examples:
664 ... print (piece.source, piece.want, piece.lineno)
665 ('x, y = 2, 3 # no output expected\n', '', 1)
666 ('if 1:\n print x\n print y\n', '2\n3\n', 2)
667 ('x+y\n', '5\n', 9)
668"""
669
Tim Peters8485b562004-08-04 18:46:34 +0000670class test_DocTestRunner:
671 def basics(): r"""
672Unit tests for the `DocTestRunner` class.
673
674DocTestRunner is used to run DocTest test cases, and to accumulate
675statistics. Here's a simple DocTest case we can use:
676
677 >>> def f(x):
678 ... '''
679 ... >>> x = 12
680 ... >>> print x
681 ... 12
682 ... >>> x/2
683 ... 6
684 ... '''
685 >>> test = doctest.DocTestFinder().find(f)[0]
686
687The main DocTestRunner interface is the `run` method, which runs a
688given DocTest case in a given namespace (globs). It returns a tuple
689`(f,t)`, where `f` is the number of failed tests and `t` is the number
690of tried tests.
691
692 >>> doctest.DocTestRunner(verbose=False).run(test)
693 (0, 3)
694
695If any example produces incorrect output, then the test runner reports
696the failure and proceeds to the next example:
697
698 >>> def f(x):
699 ... '''
700 ... >>> x = 12
701 ... >>> print x
702 ... 14
703 ... >>> x/2
704 ... 6
705 ... '''
706 >>> test = doctest.DocTestFinder().find(f)[0]
707 >>> doctest.DocTestRunner(verbose=True).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000708 ... # doctest: +ELLIPSIS
Edward Loperaacf0832004-08-26 01:19:50 +0000709 Trying:
710 x = 12
711 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000712 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000713 Trying:
714 print x
715 Expecting:
716 14
Tim Peters8485b562004-08-04 18:46:34 +0000717 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000718 File ..., line 4, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000719 Failed example:
720 print x
721 Expected:
722 14
723 Got:
724 12
Edward Loperaacf0832004-08-26 01:19:50 +0000725 Trying:
726 x/2
727 Expecting:
728 6
Tim Peters8485b562004-08-04 18:46:34 +0000729 ok
730 (1, 3)
731"""
732 def verbose_flag(): r"""
733The `verbose` flag makes the test runner generate more detailed
734output:
735
736 >>> def f(x):
737 ... '''
738 ... >>> x = 12
739 ... >>> print x
740 ... 12
741 ... >>> x/2
742 ... 6
743 ... '''
744 >>> test = doctest.DocTestFinder().find(f)[0]
745
746 >>> doctest.DocTestRunner(verbose=True).run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000747 Trying:
748 x = 12
749 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000750 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000751 Trying:
752 print x
753 Expecting:
754 12
Tim Peters8485b562004-08-04 18:46:34 +0000755 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000756 Trying:
757 x/2
758 Expecting:
759 6
Tim Peters8485b562004-08-04 18:46:34 +0000760 ok
761 (0, 3)
762
763If the `verbose` flag is unspecified, then the output will be verbose
764iff `-v` appears in sys.argv:
765
766 >>> # Save the real sys.argv list.
767 >>> old_argv = sys.argv
768
769 >>> # If -v does not appear in sys.argv, then output isn't verbose.
770 >>> sys.argv = ['test']
771 >>> doctest.DocTestRunner().run(test)
772 (0, 3)
773
774 >>> # If -v does appear in sys.argv, then output is verbose.
775 >>> sys.argv = ['test', '-v']
776 >>> doctest.DocTestRunner().run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000777 Trying:
778 x = 12
779 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000780 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000781 Trying:
782 print x
783 Expecting:
784 12
Tim Peters8485b562004-08-04 18:46:34 +0000785 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000786 Trying:
787 x/2
788 Expecting:
789 6
Tim Peters8485b562004-08-04 18:46:34 +0000790 ok
791 (0, 3)
792
793 >>> # Restore sys.argv
794 >>> sys.argv = old_argv
795
796In the remaining examples, the test runner's verbosity will be
797explicitly set, to ensure that the test behavior is consistent.
798 """
799 def exceptions(): r"""
800Tests of `DocTestRunner`'s exception handling.
801
802An expected exception is specified with a traceback message. The
803lines between the first line and the type/value may be omitted or
804replaced with any other string:
805
806 >>> def f(x):
807 ... '''
808 ... >>> x = 12
809 ... >>> print x/0
810 ... Traceback (most recent call last):
811 ... ZeroDivisionError: integer division or modulo by zero
812 ... '''
813 >>> test = doctest.DocTestFinder().find(f)[0]
814 >>> doctest.DocTestRunner(verbose=False).run(test)
815 (0, 2)
816
Edward Loper19b19582004-08-25 23:07:03 +0000817An example may not generate output before it raises an exception; if
818it does, then the traceback message will not be recognized as
819signaling an expected exception, so the example will be reported as an
820unexpected exception:
Tim Peters8485b562004-08-04 18:46:34 +0000821
822 >>> def f(x):
823 ... '''
824 ... >>> x = 12
825 ... >>> print 'pre-exception output', x/0
826 ... pre-exception output
827 ... Traceback (most recent call last):
828 ... ZeroDivisionError: integer division or modulo by zero
829 ... '''
830 >>> test = doctest.DocTestFinder().find(f)[0]
831 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper19b19582004-08-25 23:07:03 +0000832 ... # doctest: +ELLIPSIS
833 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000834 File ..., line 4, in f
Edward Loper19b19582004-08-25 23:07:03 +0000835 Failed example:
836 print 'pre-exception output', x/0
837 Exception raised:
838 ...
839 ZeroDivisionError: integer division or modulo by zero
840 (1, 2)
Tim Peters8485b562004-08-04 18:46:34 +0000841
842Exception messages may contain newlines:
843
844 >>> def f(x):
845 ... r'''
846 ... >>> raise ValueError, 'multi\nline\nmessage'
847 ... Traceback (most recent call last):
848 ... ValueError: multi
849 ... line
850 ... message
851 ... '''
852 >>> test = doctest.DocTestFinder().find(f)[0]
853 >>> doctest.DocTestRunner(verbose=False).run(test)
854 (0, 1)
855
856If an exception is expected, but an exception with the wrong type or
857message is raised, then it is reported as a failure:
858
859 >>> def f(x):
860 ... r'''
861 ... >>> raise ValueError, 'message'
862 ... Traceback (most recent call last):
863 ... ValueError: wrong message
864 ... '''
865 >>> test = doctest.DocTestFinder().find(f)[0]
866 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000867 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000868 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000869 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000870 Failed example:
871 raise ValueError, 'message'
Tim Peters8485b562004-08-04 18:46:34 +0000872 Expected:
873 Traceback (most recent call last):
874 ValueError: wrong message
875 Got:
876 Traceback (most recent call last):
Edward Loper8e4a34b2004-08-12 02:34:27 +0000877 ...
Tim Peters8485b562004-08-04 18:46:34 +0000878 ValueError: message
879 (1, 1)
880
Tim Peters1fbf9c52004-09-04 17:21:02 +0000881However, IGNORE_EXCEPTION_DETAIL can be used to allow a mismatch in the
882detail:
883
884 >>> def f(x):
885 ... r'''
886 ... >>> raise ValueError, 'message' #doctest: +IGNORE_EXCEPTION_DETAIL
887 ... Traceback (most recent call last):
888 ... ValueError: wrong message
889 ... '''
890 >>> test = doctest.DocTestFinder().find(f)[0]
891 >>> doctest.DocTestRunner(verbose=False).run(test)
892 (0, 1)
893
894But IGNORE_EXCEPTION_DETAIL does not allow a mismatch in the exception type:
895
896 >>> def f(x):
897 ... r'''
898 ... >>> raise ValueError, 'message' #doctest: +IGNORE_EXCEPTION_DETAIL
899 ... Traceback (most recent call last):
900 ... TypeError: wrong type
901 ... '''
902 >>> test = doctest.DocTestFinder().find(f)[0]
903 >>> doctest.DocTestRunner(verbose=False).run(test)
904 ... # doctest: +ELLIPSIS
905 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000906 File ..., line 3, in f
Tim Peters1fbf9c52004-09-04 17:21:02 +0000907 Failed example:
908 raise ValueError, 'message' #doctest: +IGNORE_EXCEPTION_DETAIL
909 Expected:
910 Traceback (most recent call last):
911 TypeError: wrong type
912 Got:
913 Traceback (most recent call last):
914 ...
915 ValueError: message
916 (1, 1)
917
Tim Peters8485b562004-08-04 18:46:34 +0000918If an exception is raised but not expected, then it is reported as an
919unexpected exception:
920
Tim Peters8485b562004-08-04 18:46:34 +0000921 >>> def f(x):
922 ... r'''
923 ... >>> 1/0
924 ... 0
925 ... '''
926 >>> test = doctest.DocTestFinder().find(f)[0]
927 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper74bca7a2004-08-12 02:27:44 +0000928 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000929 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000930 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000931 Failed example:
932 1/0
Tim Peters8485b562004-08-04 18:46:34 +0000933 Exception raised:
934 Traceback (most recent call last):
Jim Fulton07a349c2004-08-22 14:10:00 +0000935 ...
Tim Peters8485b562004-08-04 18:46:34 +0000936 ZeroDivisionError: integer division or modulo by zero
937 (1, 1)
Tim Peters8485b562004-08-04 18:46:34 +0000938"""
939 def optionflags(): r"""
940Tests of `DocTestRunner`'s option flag handling.
941
942Several option flags can be used to customize the behavior of the test
943runner. These are defined as module constants in doctest, and passed
944to the DocTestRunner constructor (multiple constants should be or-ed
945together).
946
947The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
948and 1/0:
949
950 >>> def f(x):
951 ... '>>> True\n1\n'
952
953 >>> # Without the flag:
954 >>> test = doctest.DocTestFinder().find(f)[0]
955 >>> doctest.DocTestRunner(verbose=False).run(test)
956 (0, 1)
957
958 >>> # With the flag:
959 >>> test = doctest.DocTestFinder().find(f)[0]
960 >>> flags = doctest.DONT_ACCEPT_TRUE_FOR_1
961 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000962 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000963 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000964 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000965 Failed example:
966 True
967 Expected:
968 1
969 Got:
970 True
Tim Peters8485b562004-08-04 18:46:34 +0000971 (1, 1)
972
973The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines
974and the '<BLANKLINE>' marker:
975
976 >>> def f(x):
977 ... '>>> print "a\\n\\nb"\na\n<BLANKLINE>\nb\n'
978
979 >>> # Without the flag:
980 >>> test = doctest.DocTestFinder().find(f)[0]
981 >>> doctest.DocTestRunner(verbose=False).run(test)
982 (0, 1)
983
984 >>> # With the flag:
985 >>> test = doctest.DocTestFinder().find(f)[0]
986 >>> flags = doctest.DONT_ACCEPT_BLANKLINE
987 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000988 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000989 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000990 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000991 Failed example:
992 print "a\n\nb"
Tim Peters8485b562004-08-04 18:46:34 +0000993 Expected:
994 a
995 <BLANKLINE>
996 b
997 Got:
998 a
999 <BLANKLINE>
1000 b
1001 (1, 1)
1002
1003The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be
1004treated as equal:
1005
1006 >>> def f(x):
1007 ... '>>> print 1, 2, 3\n 1 2\n 3'
1008
1009 >>> # Without the flag:
1010 >>> test = doctest.DocTestFinder().find(f)[0]
1011 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001012 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001013 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001014 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001015 Failed example:
1016 print 1, 2, 3
Tim Peters8485b562004-08-04 18:46:34 +00001017 Expected:
1018 1 2
1019 3
Jim Fulton07a349c2004-08-22 14:10:00 +00001020 Got:
1021 1 2 3
Tim Peters8485b562004-08-04 18:46:34 +00001022 (1, 1)
1023
1024 >>> # With the flag:
1025 >>> test = doctest.DocTestFinder().find(f)[0]
1026 >>> flags = doctest.NORMALIZE_WHITESPACE
1027 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1028 (0, 1)
1029
Tim Peters026f8dc2004-08-19 16:38:58 +00001030 An example from the docs:
1031 >>> print range(20) #doctest: +NORMALIZE_WHITESPACE
1032 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
1033 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
1034
Tim Peters8485b562004-08-04 18:46:34 +00001035The ELLIPSIS flag causes ellipsis marker ("...") in the expected
1036output to match any substring in the actual output:
1037
1038 >>> def f(x):
1039 ... '>>> print range(15)\n[0, 1, 2, ..., 14]\n'
1040
1041 >>> # Without the flag:
1042 >>> test = doctest.DocTestFinder().find(f)[0]
1043 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001044 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001045 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001046 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001047 Failed example:
1048 print range(15)
1049 Expected:
1050 [0, 1, 2, ..., 14]
1051 Got:
1052 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
Tim Peters8485b562004-08-04 18:46:34 +00001053 (1, 1)
1054
1055 >>> # With the flag:
1056 >>> test = doctest.DocTestFinder().find(f)[0]
1057 >>> flags = doctest.ELLIPSIS
1058 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1059 (0, 1)
1060
Tim Peterse594bee2004-08-22 01:47:51 +00001061 ... also matches nothing:
Tim Peters1cf3aa62004-08-19 06:49:33 +00001062
1063 >>> for i in range(100):
Tim Peterse594bee2004-08-22 01:47:51 +00001064 ... print i**2, #doctest: +ELLIPSIS
1065 0 1...4...9 16 ... 36 49 64 ... 9801
Tim Peters1cf3aa62004-08-19 06:49:33 +00001066
Tim Peters026f8dc2004-08-19 16:38:58 +00001067 ... can be surprising; e.g., this test passes:
Tim Peters26b3ebb2004-08-19 08:10:08 +00001068
1069 >>> for i in range(21): #doctest: +ELLIPSIS
Tim Peterse594bee2004-08-22 01:47:51 +00001070 ... print i,
1071 0 1 2 ...1...2...0
Tim Peters26b3ebb2004-08-19 08:10:08 +00001072
Tim Peters026f8dc2004-08-19 16:38:58 +00001073 Examples from the docs:
1074
1075 >>> print range(20) # doctest:+ELLIPSIS
1076 [0, 1, ..., 18, 19]
1077
1078 >>> print range(20) # doctest: +ELLIPSIS
1079 ... # doctest: +NORMALIZE_WHITESPACE
1080 [0, 1, ..., 18, 19]
1081
Edward Loper71f55af2004-08-26 01:41:51 +00001082The REPORT_UDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001083and actual outputs to be displayed using a unified diff:
1084
1085 >>> def f(x):
1086 ... r'''
1087 ... >>> print '\n'.join('abcdefg')
1088 ... a
1089 ... B
1090 ... c
1091 ... d
1092 ... f
1093 ... g
1094 ... h
1095 ... '''
1096
1097 >>> # Without the flag:
1098 >>> test = doctest.DocTestFinder().find(f)[0]
1099 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001100 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001101 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001102 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001103 Failed example:
1104 print '\n'.join('abcdefg')
Tim Peters8485b562004-08-04 18:46:34 +00001105 Expected:
1106 a
1107 B
1108 c
1109 d
1110 f
1111 g
1112 h
1113 Got:
1114 a
1115 b
1116 c
1117 d
1118 e
1119 f
1120 g
1121 (1, 1)
1122
1123 >>> # With the flag:
1124 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001125 >>> flags = doctest.REPORT_UDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001126 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001127 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001128 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001129 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001130 Failed example:
1131 print '\n'.join('abcdefg')
Edward Loper56629292004-08-26 01:31:56 +00001132 Differences (unified diff with -expected +actual):
Tim Peterse7edcb82004-08-26 05:44:27 +00001133 @@ -1,7 +1,7 @@
Tim Peters8485b562004-08-04 18:46:34 +00001134 a
1135 -B
1136 +b
1137 c
1138 d
1139 +e
1140 f
1141 g
1142 -h
Tim Peters8485b562004-08-04 18:46:34 +00001143 (1, 1)
1144
Edward Loper71f55af2004-08-26 01:41:51 +00001145The REPORT_CDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001146and actual outputs to be displayed using a context diff:
1147
Edward Loper71f55af2004-08-26 01:41:51 +00001148 >>> # Reuse f() from the REPORT_UDIFF example, above.
Tim Peters8485b562004-08-04 18:46:34 +00001149 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001150 >>> flags = doctest.REPORT_CDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001151 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001152 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001153 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001154 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001155 Failed example:
1156 print '\n'.join('abcdefg')
Edward Loper56629292004-08-26 01:31:56 +00001157 Differences (context diff with expected followed by actual):
Tim Peters8485b562004-08-04 18:46:34 +00001158 ***************
Tim Peterse7edcb82004-08-26 05:44:27 +00001159 *** 1,7 ****
Tim Peters8485b562004-08-04 18:46:34 +00001160 a
1161 ! B
1162 c
1163 d
1164 f
1165 g
1166 - h
Tim Peterse7edcb82004-08-26 05:44:27 +00001167 --- 1,7 ----
Tim Peters8485b562004-08-04 18:46:34 +00001168 a
1169 ! b
1170 c
1171 d
1172 + e
1173 f
1174 g
Tim Peters8485b562004-08-04 18:46:34 +00001175 (1, 1)
Tim Petersc6cbab02004-08-22 19:43:28 +00001176
1177
Edward Loper71f55af2004-08-26 01:41:51 +00001178The REPORT_NDIFF flag causes failures to use the difflib.Differ algorithm
Tim Petersc6cbab02004-08-22 19:43:28 +00001179used by the popular ndiff.py utility. This does intraline difference
1180marking, as well as interline differences.
1181
1182 >>> def f(x):
1183 ... r'''
1184 ... >>> print "a b c d e f g h i j k l m"
1185 ... a b c d e f g h i j k 1 m
1186 ... '''
1187 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001188 >>> flags = doctest.REPORT_NDIFF
Tim Petersc6cbab02004-08-22 19:43:28 +00001189 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001190 ... # doctest: +ELLIPSIS
Tim Petersc6cbab02004-08-22 19:43:28 +00001191 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001192 File ..., line 3, in f
Tim Petersc6cbab02004-08-22 19:43:28 +00001193 Failed example:
1194 print "a b c d e f g h i j k l m"
1195 Differences (ndiff with -expected +actual):
1196 - a b c d e f g h i j k 1 m
1197 ? ^
1198 + a b c d e f g h i j k l m
1199 ? + ++ ^
Tim Petersc6cbab02004-08-22 19:43:28 +00001200 (1, 1)
Edward Lopera89f88d2004-08-26 02:45:51 +00001201
1202The REPORT_ONLY_FIRST_FAILURE supresses result output after the first
1203failing example:
1204
1205 >>> def f(x):
1206 ... r'''
1207 ... >>> print 1 # first success
1208 ... 1
1209 ... >>> print 2 # first failure
1210 ... 200
1211 ... >>> print 3 # second failure
1212 ... 300
1213 ... >>> print 4 # second success
1214 ... 4
1215 ... >>> print 5 # third failure
1216 ... 500
1217 ... '''
1218 >>> test = doctest.DocTestFinder().find(f)[0]
1219 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1220 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001221 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001222 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001223 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001224 Failed example:
1225 print 2 # first failure
1226 Expected:
1227 200
1228 Got:
1229 2
1230 (3, 5)
1231
1232However, output from `report_start` is not supressed:
1233
1234 >>> doctest.DocTestRunner(verbose=True, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001235 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001236 Trying:
1237 print 1 # first success
1238 Expecting:
1239 1
1240 ok
1241 Trying:
1242 print 2 # first failure
1243 Expecting:
1244 200
1245 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001246 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001247 Failed example:
1248 print 2 # first failure
1249 Expected:
1250 200
1251 Got:
1252 2
1253 (3, 5)
1254
1255For the purposes of REPORT_ONLY_FIRST_FAILURE, unexpected exceptions
1256count as failures:
1257
1258 >>> def f(x):
1259 ... r'''
1260 ... >>> print 1 # first success
1261 ... 1
1262 ... >>> raise ValueError(2) # first failure
1263 ... 200
1264 ... >>> print 3 # second failure
1265 ... 300
1266 ... >>> print 4 # second success
1267 ... 4
1268 ... >>> print 5 # third failure
1269 ... 500
1270 ... '''
1271 >>> test = doctest.DocTestFinder().find(f)[0]
1272 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1273 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1274 ... # doctest: +ELLIPSIS
1275 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001276 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001277 Failed example:
1278 raise ValueError(2) # first failure
1279 Exception raised:
1280 ...
1281 ValueError: 2
1282 (3, 5)
1283
Tim Petersc6cbab02004-08-22 19:43:28 +00001284 """
1285
Tim Peters8485b562004-08-04 18:46:34 +00001286 def option_directives(): r"""
1287Tests of `DocTestRunner`'s option directive mechanism.
1288
Edward Loper74bca7a2004-08-12 02:27:44 +00001289Option directives can be used to turn option flags on or off for a
1290single example. To turn an option on for an example, follow that
1291example with a comment of the form ``# doctest: +OPTION``:
Tim Peters8485b562004-08-04 18:46:34 +00001292
1293 >>> def f(x): r'''
Edward Loper74bca7a2004-08-12 02:27:44 +00001294 ... >>> print range(10) # should fail: no ellipsis
1295 ... [0, 1, ..., 9]
1296 ...
1297 ... >>> print range(10) # doctest: +ELLIPSIS
1298 ... [0, 1, ..., 9]
1299 ... '''
1300 >>> test = doctest.DocTestFinder().find(f)[0]
1301 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001302 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001303 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001304 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001305 Failed example:
1306 print range(10) # should fail: no ellipsis
1307 Expected:
1308 [0, 1, ..., 9]
1309 Got:
1310 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001311 (1, 2)
1312
1313To turn an option off for an example, follow that example with a
1314comment of the form ``# doctest: -OPTION``:
1315
1316 >>> def f(x): r'''
1317 ... >>> print range(10)
1318 ... [0, 1, ..., 9]
1319 ...
1320 ... >>> # should fail: no ellipsis
1321 ... >>> print range(10) # doctest: -ELLIPSIS
1322 ... [0, 1, ..., 9]
1323 ... '''
1324 >>> test = doctest.DocTestFinder().find(f)[0]
1325 >>> doctest.DocTestRunner(verbose=False,
1326 ... optionflags=doctest.ELLIPSIS).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001327 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001328 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001329 File ..., line 6, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001330 Failed example:
1331 print range(10) # doctest: -ELLIPSIS
1332 Expected:
1333 [0, 1, ..., 9]
1334 Got:
1335 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001336 (1, 2)
1337
1338Option directives affect only the example that they appear with; they
1339do not change the options for surrounding examples:
Edward Loper8e4a34b2004-08-12 02:34:27 +00001340
Edward Loper74bca7a2004-08-12 02:27:44 +00001341 >>> def f(x): r'''
Tim Peters8485b562004-08-04 18:46:34 +00001342 ... >>> print range(10) # Should fail: no ellipsis
1343 ... [0, 1, ..., 9]
1344 ...
Edward Loper74bca7a2004-08-12 02:27:44 +00001345 ... >>> print range(10) # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001346 ... [0, 1, ..., 9]
1347 ...
Tim Peters8485b562004-08-04 18:46:34 +00001348 ... >>> print range(10) # Should fail: no ellipsis
1349 ... [0, 1, ..., 9]
1350 ... '''
1351 >>> test = doctest.DocTestFinder().find(f)[0]
1352 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001353 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001354 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001355 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001356 Failed example:
1357 print range(10) # Should fail: no ellipsis
1358 Expected:
1359 [0, 1, ..., 9]
1360 Got:
1361 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001362 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001363 File ..., line 8, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001364 Failed example:
1365 print range(10) # Should fail: no ellipsis
1366 Expected:
1367 [0, 1, ..., 9]
1368 Got:
1369 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001370 (2, 3)
1371
Edward Loper74bca7a2004-08-12 02:27:44 +00001372Multiple options may be modified by a single option directive. They
1373may be separated by whitespace, commas, or both:
Tim Peters8485b562004-08-04 18:46:34 +00001374
1375 >>> def f(x): r'''
1376 ... >>> print range(10) # Should fail
1377 ... [0, 1, ..., 9]
Tim Peters8485b562004-08-04 18:46:34 +00001378 ... >>> print range(10) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001379 ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001380 ... [0, 1, ..., 9]
1381 ... '''
1382 >>> test = doctest.DocTestFinder().find(f)[0]
1383 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001384 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001385 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001386 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001387 Failed example:
1388 print range(10) # Should fail
1389 Expected:
1390 [0, 1, ..., 9]
1391 Got:
1392 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001393 (1, 2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001394
1395 >>> def f(x): r'''
1396 ... >>> print range(10) # Should fail
1397 ... [0, 1, ..., 9]
1398 ... >>> print range(10) # Should succeed
1399 ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
1400 ... [0, 1, ..., 9]
1401 ... '''
1402 >>> test = doctest.DocTestFinder().find(f)[0]
1403 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001404 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001405 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001406 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001407 Failed example:
1408 print range(10) # Should fail
1409 Expected:
1410 [0, 1, ..., 9]
1411 Got:
1412 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001413 (1, 2)
1414
1415 >>> def f(x): r'''
1416 ... >>> print range(10) # Should fail
1417 ... [0, 1, ..., 9]
1418 ... >>> print range(10) # Should succeed
1419 ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1420 ... [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
Edward Loper74bca7a2004-08-12 02:27:44 +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]
Edward Loper74bca7a2004-08-12 02:27:44 +00001433 (1, 2)
1434
1435The option directive may be put on the line following the source, as
1436long as a continuation prompt is used:
1437
1438 >>> def f(x): r'''
1439 ... >>> print range(10)
1440 ... ... # doctest: +ELLIPSIS
1441 ... [0, 1, ..., 9]
1442 ... '''
1443 >>> test = doctest.DocTestFinder().find(f)[0]
1444 >>> doctest.DocTestRunner(verbose=False).run(test)
1445 (0, 1)
Edward Loper8e4a34b2004-08-12 02:34:27 +00001446
Edward Loper74bca7a2004-08-12 02:27:44 +00001447For examples with multi-line source, the option directive may appear
1448at the end of any line:
1449
1450 >>> def f(x): r'''
1451 ... >>> for x in range(10): # doctest: +ELLIPSIS
1452 ... ... print x,
1453 ... 0 1 2 ... 9
1454 ...
1455 ... >>> for x in range(10):
1456 ... ... print x, # doctest: +ELLIPSIS
1457 ... 0 1 2 ... 9
1458 ... '''
1459 >>> test = doctest.DocTestFinder().find(f)[0]
1460 >>> doctest.DocTestRunner(verbose=False).run(test)
1461 (0, 2)
1462
1463If more than one line of an example with multi-line source has an
1464option directive, then they are combined:
1465
1466 >>> def f(x): r'''
1467 ... Should fail (option directive not on the last line):
1468 ... >>> for x in range(10): # doctest: +ELLIPSIS
1469 ... ... print x, # doctest: +NORMALIZE_WHITESPACE
1470 ... 0 1 2...9
1471 ... '''
1472 >>> test = doctest.DocTestFinder().find(f)[0]
1473 >>> doctest.DocTestRunner(verbose=False).run(test)
1474 (0, 1)
1475
1476It is an error to have a comment of the form ``# doctest:`` that is
1477*not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
1478``OPTION`` is an option that has been registered with
1479`register_option`:
1480
1481 >>> # Error: Option not registered
1482 >>> s = '>>> print 12 #doctest: +BADOPTION'
1483 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1484 Traceback (most recent call last):
1485 ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
1486
1487 >>> # Error: No + or - prefix
1488 >>> s = '>>> print 12 #doctest: ELLIPSIS'
1489 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1490 Traceback (most recent call last):
1491 ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
1492
1493It is an error to use an option directive on a line that contains no
1494source:
1495
1496 >>> s = '>>> # doctest: +ELLIPSIS'
1497 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1498 Traceback (most recent call last):
1499 ValueError: line 0 of the doctest for s has an option directive on a line with no example: '# doctest: +ELLIPSIS'
Tim Peters8485b562004-08-04 18:46:34 +00001500"""
1501
1502def test_testsource(): r"""
1503Unit tests for `testsource()`.
1504
1505The testsource() function takes a module and a name, finds the (first)
Tim Peters19397e52004-08-06 22:02:59 +00001506test with that name in that module, and converts it to a script. The
1507example code is converted to regular Python code. The surrounding
1508words and expected output are converted to comments:
Tim Peters8485b562004-08-04 18:46:34 +00001509
1510 >>> import test.test_doctest
1511 >>> name = 'test.test_doctest.sample_func'
1512 >>> print doctest.testsource(test.test_doctest, name)
Edward Lopera5db6002004-08-12 02:41:30 +00001513 # Blah blah
Tim Peters19397e52004-08-06 22:02:59 +00001514 #
Tim Peters8485b562004-08-04 18:46:34 +00001515 print sample_func(22)
1516 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001517 ## 44
Tim Peters19397e52004-08-06 22:02:59 +00001518 #
Edward Lopera5db6002004-08-12 02:41:30 +00001519 # Yee ha!
Tim Peters8485b562004-08-04 18:46:34 +00001520
1521 >>> name = 'test.test_doctest.SampleNewStyleClass'
1522 >>> print doctest.testsource(test.test_doctest, name)
1523 print '1\n2\n3'
1524 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001525 ## 1
1526 ## 2
1527 ## 3
Tim Peters8485b562004-08-04 18:46:34 +00001528
1529 >>> name = 'test.test_doctest.SampleClass.a_classmethod'
1530 >>> print doctest.testsource(test.test_doctest, name)
1531 print SampleClass.a_classmethod(10)
1532 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001533 ## 12
Tim Peters8485b562004-08-04 18:46:34 +00001534 print SampleClass(0).a_classmethod(10)
1535 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001536 ## 12
Tim Peters8485b562004-08-04 18:46:34 +00001537"""
1538
1539def test_debug(): r"""
1540
1541Create a docstring that we want to debug:
1542
1543 >>> s = '''
1544 ... >>> x = 12
1545 ... >>> print x
1546 ... 12
1547 ... '''
1548
1549Create some fake stdin input, to feed to the debugger:
1550
1551 >>> import tempfile
Tim Peters8485b562004-08-04 18:46:34 +00001552 >>> real_stdin = sys.stdin
Edward Loper2de91ba2004-08-27 02:07:46 +00001553 >>> sys.stdin = _FakeInput(['next', 'print x', 'continue'])
Tim Peters8485b562004-08-04 18:46:34 +00001554
1555Run the debugger on the docstring, and then restore sys.stdin.
1556
Edward Loper2de91ba2004-08-27 02:07:46 +00001557 >>> try: doctest.debug_src(s)
1558 ... finally: sys.stdin = real_stdin
Tim Peters8485b562004-08-04 18:46:34 +00001559 > <string>(1)?()
Edward Loper2de91ba2004-08-27 02:07:46 +00001560 (Pdb) next
1561 12
Tim Peters8485b562004-08-04 18:46:34 +00001562 --Return--
1563 > <string>(1)?()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001564 (Pdb) print x
1565 12
1566 (Pdb) continue
Tim Peters8485b562004-08-04 18:46:34 +00001567
1568"""
1569
Jim Fulton356fd192004-08-09 11:34:47 +00001570def test_pdb_set_trace():
Edward Loper2de91ba2004-08-27 02:07:46 +00001571 """Using pdb.set_trace from a doctest
Jim Fulton356fd192004-08-09 11:34:47 +00001572
Tim Peters413ced62004-08-09 15:43:47 +00001573 You can use pdb.set_trace from a doctest. To do so, you must
Jim Fulton356fd192004-08-09 11:34:47 +00001574 retrieve the set_trace function from the pdb module at the time
Tim Peters413ced62004-08-09 15:43:47 +00001575 you use it. The doctest module changes sys.stdout so that it can
1576 capture program output. It also temporarily replaces pdb.set_trace
1577 with a version that restores stdout. This is necessary for you to
Jim Fulton356fd192004-08-09 11:34:47 +00001578 see debugger output.
1579
1580 >>> doc = '''
1581 ... >>> x = 42
1582 ... >>> import pdb; pdb.set_trace()
1583 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001584 >>> parser = doctest.DocTestParser()
1585 >>> test = parser.get_doctest(doc, {}, "foo", "foo.py", 0)
Jim Fulton356fd192004-08-09 11:34:47 +00001586 >>> runner = doctest.DocTestRunner(verbose=False)
1587
1588 To demonstrate this, we'll create a fake standard input that
1589 captures our debugger input:
1590
1591 >>> import tempfile
Edward Loper2de91ba2004-08-27 02:07:46 +00001592 >>> real_stdin = sys.stdin
1593 >>> sys.stdin = _FakeInput([
Jim Fulton356fd192004-08-09 11:34:47 +00001594 ... 'print x', # print data defined by the example
1595 ... 'continue', # stop debugging
Edward Loper2de91ba2004-08-27 02:07:46 +00001596 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001597
Edward Loper2de91ba2004-08-27 02:07:46 +00001598 >>> try: runner.run(test)
1599 ... finally: sys.stdin = real_stdin
Jim Fulton356fd192004-08-09 11:34:47 +00001600 --Return--
Edward Loper2de91ba2004-08-27 02:07:46 +00001601 > <doctest foo[1]>(1)?()->None
1602 -> import pdb; pdb.set_trace()
1603 (Pdb) print x
1604 42
1605 (Pdb) continue
1606 (0, 2)
Jim Fulton356fd192004-08-09 11:34:47 +00001607
1608 You can also put pdb.set_trace in a function called from a test:
1609
1610 >>> def calls_set_trace():
1611 ... y=2
1612 ... import pdb; pdb.set_trace()
1613
1614 >>> doc = '''
1615 ... >>> x=1
1616 ... >>> calls_set_trace()
1617 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001618 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
Edward Loper2de91ba2004-08-27 02:07:46 +00001619 >>> real_stdin = sys.stdin
1620 >>> sys.stdin = _FakeInput([
Jim Fulton356fd192004-08-09 11:34:47 +00001621 ... 'print y', # print data defined in the function
1622 ... 'up', # out of function
1623 ... 'print x', # print data defined by the example
1624 ... 'continue', # stop debugging
Edward Loper2de91ba2004-08-27 02:07:46 +00001625 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001626
Edward Loper2de91ba2004-08-27 02:07:46 +00001627 >>> try: runner.run(test)
1628 ... finally: sys.stdin = real_stdin
Jim Fulton356fd192004-08-09 11:34:47 +00001629 --Return--
Edward Loper2de91ba2004-08-27 02:07:46 +00001630 > <doctest test.test_doctest.test_pdb_set_trace[8]>(3)calls_set_trace()->None
1631 -> import pdb; pdb.set_trace()
1632 (Pdb) print y
1633 2
1634 (Pdb) up
1635 > <doctest foo[1]>(1)?()
1636 -> calls_set_trace()
1637 (Pdb) print x
1638 1
1639 (Pdb) continue
1640 (0, 2)
1641
1642 During interactive debugging, source code is shown, even for
1643 doctest examples:
1644
1645 >>> doc = '''
1646 ... >>> def f(x):
1647 ... ... g(x*2)
1648 ... >>> def g(x):
1649 ... ... print x+3
1650 ... ... import pdb; pdb.set_trace()
1651 ... >>> f(3)
1652 ... '''
1653 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
1654 >>> real_stdin = sys.stdin
1655 >>> sys.stdin = _FakeInput([
1656 ... 'list', # list source from example 2
1657 ... 'next', # return from g()
1658 ... 'list', # list source from example 1
1659 ... 'next', # return from f()
1660 ... 'list', # list source from example 3
1661 ... 'continue', # stop debugging
1662 ... ''])
1663 >>> try: runner.run(test)
1664 ... finally: sys.stdin = real_stdin
1665 ... # doctest: +NORMALIZE_WHITESPACE
1666 --Return--
1667 > <doctest foo[1]>(3)g()->None
1668 -> import pdb; pdb.set_trace()
1669 (Pdb) list
1670 1 def g(x):
1671 2 print x+3
1672 3 -> import pdb; pdb.set_trace()
1673 [EOF]
1674 (Pdb) next
1675 --Return--
1676 > <doctest foo[0]>(2)f()->None
1677 -> g(x*2)
1678 (Pdb) list
1679 1 def f(x):
1680 2 -> g(x*2)
1681 [EOF]
1682 (Pdb) next
1683 --Return--
1684 > <doctest foo[2]>(1)?()->None
1685 -> f(3)
1686 (Pdb) list
1687 1 -> f(3)
1688 [EOF]
1689 (Pdb) continue
1690 **********************************************************************
1691 File "foo.py", line 7, in foo
1692 Failed example:
1693 f(3)
1694 Expected nothing
1695 Got:
1696 9
1697 (1, 3)
Jim Fulton356fd192004-08-09 11:34:47 +00001698 """
1699
Tim Peters19397e52004-08-06 22:02:59 +00001700def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +00001701 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +00001702
1703 We create a Suite by providing a module. A module can be provided
1704 by passing a module object:
1705
1706 >>> import unittest
1707 >>> import test.sample_doctest
1708 >>> suite = doctest.DocTestSuite(test.sample_doctest)
1709 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001710 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001711
1712 We can also supply the module by name:
1713
1714 >>> suite = doctest.DocTestSuite('test.sample_doctest')
1715 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001716 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001717
1718 We can use the current module:
1719
1720 >>> suite = test.sample_doctest.test_suite()
1721 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001722 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001723
1724 We can supply global variables. If we pass globs, they will be
1725 used instead of the module globals. Here we'll pass an empty
1726 globals, triggering an extra error:
1727
1728 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
1729 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001730 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001731
1732 Alternatively, we can provide extra globals. Here we'll make an
1733 error go away by providing an extra global variable:
1734
1735 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1736 ... extraglobs={'y': 1})
1737 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001738 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001739
1740 You can pass option flags. Here we'll cause an extra error
1741 by disabling the blank-line feature:
1742
1743 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00001744 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00001745 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001746 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001747
Tim Peters1e277ee2004-08-07 05:37:52 +00001748 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00001749
Jim Fultonf54bad42004-08-28 14:57:56 +00001750 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00001751 ... import test.test_doctest
1752 ... test.test_doctest.sillySetup = True
1753
Jim Fultonf54bad42004-08-28 14:57:56 +00001754 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00001755 ... import test.test_doctest
1756 ... del test.test_doctest.sillySetup
1757
1758 Here, we installed a silly variable that the test expects:
1759
1760 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1761 ... setUp=setUp, tearDown=tearDown)
1762 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001763 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001764
1765 But the tearDown restores sanity:
1766
1767 >>> import test.test_doctest
1768 >>> test.test_doctest.sillySetup
1769 Traceback (most recent call last):
1770 ...
1771 AttributeError: 'module' object has no attribute 'sillySetup'
1772
Jim Fultonf54bad42004-08-28 14:57:56 +00001773 The setUp and tearDown funtions are passed test objects. Here
1774 we'll use the setUp function to supply the missing variable y:
1775
1776 >>> def setUp(test):
1777 ... test.globs['y'] = 1
1778
1779 >>> suite = doctest.DocTestSuite('test.sample_doctest', setUp=setUp)
1780 >>> suite.run(unittest.TestResult())
1781 <unittest.TestResult run=9 errors=0 failures=3>
1782
1783 Here, we didn't need to use a tearDown function because we
1784 modified the test globals, which are a copy of the
1785 sample_doctest module dictionary. The test globals are
1786 automatically cleared for us after a test.
1787
Tim Peters19397e52004-08-06 22:02:59 +00001788 Finally, you can provide an alternate test finder. Here we'll
Tim Peters1e277ee2004-08-07 05:37:52 +00001789 use a custom test_finder to to run just the test named bar.
1790 However, the test in the module docstring, and the two tests
1791 in the module __test__ dict, aren't filtered, so we actually
1792 run three tests besides bar's. The filtering mechanisms are
1793 poorly conceived, and will go away someday.
Tim Peters19397e52004-08-06 22:02:59 +00001794
1795 >>> finder = doctest.DocTestFinder(
Tim Petersf727c6c2004-08-08 01:48:59 +00001796 ... _namefilter=lambda prefix, base: base!='bar')
Tim Peters19397e52004-08-06 22:02:59 +00001797 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1798 ... test_finder=finder)
1799 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001800 <unittest.TestResult run=4 errors=0 failures=1>
Tim Peters19397e52004-08-06 22:02:59 +00001801 """
1802
1803def test_DocFileSuite():
1804 """We can test tests found in text files using a DocFileSuite.
1805
1806 We create a suite by providing the names of one or more text
1807 files that include examples:
1808
1809 >>> import unittest
1810 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1811 ... 'test_doctest2.txt')
1812 >>> suite.run(unittest.TestResult())
1813 <unittest.TestResult run=2 errors=0 failures=2>
1814
1815 The test files are looked for in the directory containing the
1816 calling module. A package keyword argument can be provided to
1817 specify a different relative location.
1818
1819 >>> import unittest
1820 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1821 ... 'test_doctest2.txt',
1822 ... package='test')
1823 >>> suite.run(unittest.TestResult())
1824 <unittest.TestResult run=2 errors=0 failures=2>
1825
Edward Loper0273f5b2004-09-18 20:27:04 +00001826 '/' should be used as a path separator. It will be converted
1827 to a native separator at run time:
Tim Peters19397e52004-08-06 22:02:59 +00001828
1829 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
1830 >>> suite.run(unittest.TestResult())
1831 <unittest.TestResult run=1 errors=0 failures=1>
1832
Edward Loper0273f5b2004-09-18 20:27:04 +00001833 If DocFileSuite is used from an interactive session, then files
1834 are resolved relative to the directory of sys.argv[0]:
1835
1836 >>> import new, os.path, test.test_doctest
1837 >>> save_argv = sys.argv
1838 >>> sys.argv = [test.test_doctest.__file__]
1839 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1840 ... package=new.module('__main__'))
1841 >>> sys.argv = save_argv
1842
Edward Loper052d0cd2004-09-19 17:19:33 +00001843 By setting `module_relative=False`, os-specific paths may be
1844 used (including absolute paths and paths relative to the
1845 working directory):
Edward Loper0273f5b2004-09-18 20:27:04 +00001846
1847 >>> # Get the absolute path of the test package.
1848 >>> test_doctest_path = os.path.abspath(test.test_doctest.__file__)
1849 >>> test_pkg_path = os.path.split(test_doctest_path)[0]
1850
1851 >>> # Use it to find the absolute path of test_doctest.txt.
1852 >>> test_file = os.path.join(test_pkg_path, 'test_doctest.txt')
1853
Edward Loper052d0cd2004-09-19 17:19:33 +00001854 >>> suite = doctest.DocFileSuite(test_file, module_relative=False)
Edward Loper0273f5b2004-09-18 20:27:04 +00001855 >>> suite.run(unittest.TestResult())
1856 <unittest.TestResult run=1 errors=0 failures=1>
1857
Edward Loper052d0cd2004-09-19 17:19:33 +00001858 It is an error to specify `package` when `module_relative=False`:
1859
1860 >>> suite = doctest.DocFileSuite(test_file, module_relative=False,
1861 ... package='test')
1862 Traceback (most recent call last):
1863 ValueError: Package may only be specified for module-relative paths.
1864
Tim Peters19397e52004-08-06 22:02:59 +00001865 You can specify initial global variables:
1866
1867 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1868 ... 'test_doctest2.txt',
1869 ... globs={'favorite_color': 'blue'})
1870 >>> suite.run(unittest.TestResult())
1871 <unittest.TestResult run=2 errors=0 failures=1>
1872
1873 In this case, we supplied a missing favorite color. You can
1874 provide doctest options:
1875
1876 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1877 ... 'test_doctest2.txt',
1878 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
1879 ... globs={'favorite_color': 'blue'})
1880 >>> suite.run(unittest.TestResult())
1881 <unittest.TestResult run=2 errors=0 failures=2>
1882
1883 And, you can provide setUp and tearDown functions:
1884
1885 You can supply setUp and teatDoen functions:
1886
Jim Fultonf54bad42004-08-28 14:57:56 +00001887 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00001888 ... import test.test_doctest
1889 ... test.test_doctest.sillySetup = True
1890
Jim Fultonf54bad42004-08-28 14:57:56 +00001891 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00001892 ... import test.test_doctest
1893 ... del test.test_doctest.sillySetup
1894
1895 Here, we installed a silly variable that the test expects:
1896
1897 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1898 ... 'test_doctest2.txt',
1899 ... setUp=setUp, tearDown=tearDown)
1900 >>> suite.run(unittest.TestResult())
1901 <unittest.TestResult run=2 errors=0 failures=1>
1902
1903 But the tearDown restores sanity:
1904
1905 >>> import test.test_doctest
1906 >>> test.test_doctest.sillySetup
1907 Traceback (most recent call last):
1908 ...
1909 AttributeError: 'module' object has no attribute 'sillySetup'
1910
Jim Fultonf54bad42004-08-28 14:57:56 +00001911 The setUp and tearDown funtions are passed test objects.
1912 Here, we'll use a setUp function to set the favorite color in
1913 test_doctest.txt:
1914
1915 >>> def setUp(test):
1916 ... test.globs['favorite_color'] = 'blue'
1917
1918 >>> suite = doctest.DocFileSuite('test_doctest.txt', setUp=setUp)
1919 >>> suite.run(unittest.TestResult())
1920 <unittest.TestResult run=1 errors=0 failures=0>
1921
1922 Here, we didn't need to use a tearDown function because we
1923 modified the test globals. The test globals are
1924 automatically cleared for us after a test.
Tim Petersdf7a2082004-08-29 00:38:17 +00001925
Jim Fultonf54bad42004-08-28 14:57:56 +00001926 """
Tim Peters19397e52004-08-06 22:02:59 +00001927
Jim Fulton07a349c2004-08-22 14:10:00 +00001928def test_trailing_space_in_test():
1929 """
Tim Petersa7def722004-08-23 22:13:22 +00001930 Trailing spaces in expected output are significant:
Tim Petersc6cbab02004-08-22 19:43:28 +00001931
Jim Fulton07a349c2004-08-22 14:10:00 +00001932 >>> x, y = 'foo', ''
1933 >>> print x, y
1934 foo \n
1935 """
Tim Peters19397e52004-08-06 22:02:59 +00001936
Jim Fultonf54bad42004-08-28 14:57:56 +00001937
1938def test_unittest_reportflags():
1939 """Default unittest reporting flags can be set to control reporting
1940
1941 Here, we'll set the REPORT_ONLY_FIRST_FAILURE option so we see
1942 only the first failure of each test. First, we'll look at the
1943 output without the flag. The file test_doctest.txt file has two
1944 tests. They both fail if blank lines are disabled:
1945
1946 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1947 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
1948 >>> import unittest
1949 >>> result = suite.run(unittest.TestResult())
1950 >>> print result.failures[0][1] # doctest: +ELLIPSIS
1951 Traceback ...
1952 Failed example:
1953 favorite_color
1954 ...
1955 Failed example:
1956 if 1:
1957 ...
1958
1959 Note that we see both failures displayed.
1960
1961 >>> old = doctest.set_unittest_reportflags(
1962 ... doctest.REPORT_ONLY_FIRST_FAILURE)
1963
1964 Now, when we run the test:
1965
1966 >>> result = suite.run(unittest.TestResult())
1967 >>> print result.failures[0][1] # doctest: +ELLIPSIS
1968 Traceback ...
1969 Failed example:
1970 favorite_color
1971 Exception raised:
1972 ...
1973 NameError: name 'favorite_color' is not defined
1974 <BLANKLINE>
1975 <BLANKLINE>
Tim Petersdf7a2082004-08-29 00:38:17 +00001976
Jim Fultonf54bad42004-08-28 14:57:56 +00001977 We get only the first failure.
1978
1979 If we give any reporting options when we set up the tests,
1980 however:
1981
1982 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1983 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE | doctest.REPORT_NDIFF)
1984
1985 Then the default eporting options are ignored:
1986
1987 >>> result = suite.run(unittest.TestResult())
1988 >>> print result.failures[0][1] # doctest: +ELLIPSIS
1989 Traceback ...
1990 Failed example:
1991 favorite_color
1992 ...
1993 Failed example:
1994 if 1:
1995 print 'a'
1996 print
1997 print 'b'
1998 Differences (ndiff with -expected +actual):
1999 a
2000 - <BLANKLINE>
2001 +
2002 b
2003 <BLANKLINE>
2004 <BLANKLINE>
2005
2006
2007 Test runners can restore the formatting flags after they run:
2008
2009 >>> ignored = doctest.set_unittest_reportflags(old)
2010
2011 """
2012
Edward Loper052d0cd2004-09-19 17:19:33 +00002013def test_testfile(): r"""
2014Tests for the `testfile()` function. This function runs all the
2015doctest examples in a given file. In its simple invokation, it is
2016called with the name of a file, which is taken to be relative to the
2017calling module. The return value is (#failures, #tests).
2018
2019 >>> doctest.testfile('test_doctest.txt') # doctest: +ELLIPSIS
2020 **********************************************************************
2021 File "...", line 6, in test_doctest.txt
2022 Failed example:
2023 favorite_color
2024 Exception raised:
2025 ...
2026 NameError: name 'favorite_color' is not defined
2027 **********************************************************************
2028 1 items had failures:
2029 1 of 2 in test_doctest.txt
2030 ***Test Failed*** 1 failures.
2031 (1, 2)
2032 >>> doctest.master = None # Reset master.
2033
2034(Note: we'll be clearing doctest.master after each call to
2035`doctest.testfile`, to supress warnings about multiple tests with the
2036same name.)
2037
2038Globals may be specified with the `globs` and `extraglobs` parameters:
2039
2040 >>> globs = {'favorite_color': 'blue'}
2041 >>> doctest.testfile('test_doctest.txt', globs=globs)
2042 (0, 2)
2043 >>> doctest.master = None # Reset master.
2044
2045 >>> extraglobs = {'favorite_color': 'red'}
2046 >>> doctest.testfile('test_doctest.txt', globs=globs,
2047 ... extraglobs=extraglobs) # doctest: +ELLIPSIS
2048 **********************************************************************
2049 File "...", line 6, in test_doctest.txt
2050 Failed example:
2051 favorite_color
2052 Expected:
2053 'blue'
2054 Got:
2055 'red'
2056 **********************************************************************
2057 1 items had failures:
2058 1 of 2 in test_doctest.txt
2059 ***Test Failed*** 1 failures.
2060 (1, 2)
2061 >>> doctest.master = None # Reset master.
2062
2063The file may be made relative to a given module or package, using the
2064optional `module_relative` parameter:
2065
2066 >>> doctest.testfile('test_doctest.txt', globs=globs,
2067 ... module_relative='test')
2068 (0, 2)
2069 >>> doctest.master = None # Reset master.
2070
2071Verbosity can be increased with the optional `verbose` paremter:
2072
2073 >>> doctest.testfile('test_doctest.txt', globs=globs, verbose=True)
2074 Trying:
2075 favorite_color
2076 Expecting:
2077 'blue'
2078 ok
2079 Trying:
2080 if 1:
2081 print 'a'
2082 print
2083 print 'b'
2084 Expecting:
2085 a
2086 <BLANKLINE>
2087 b
2088 ok
2089 1 items passed all tests:
2090 2 tests in test_doctest.txt
2091 2 tests in 1 items.
2092 2 passed and 0 failed.
2093 Test passed.
2094 (0, 2)
2095 >>> doctest.master = None # Reset master.
2096
2097The name of the test may be specified with the optional `name`
2098parameter:
2099
2100 >>> doctest.testfile('test_doctest.txt', name='newname')
2101 ... # doctest: +ELLIPSIS
2102 **********************************************************************
2103 File "...", line 6, in newname
2104 ...
2105 (1, 2)
2106 >>> doctest.master = None # Reset master.
2107
2108The summary report may be supressed with the optional `report`
2109parameter:
2110
2111 >>> doctest.testfile('test_doctest.txt', report=False)
2112 ... # doctest: +ELLIPSIS
2113 **********************************************************************
2114 File "...", line 6, in test_doctest.txt
2115 Failed example:
2116 favorite_color
2117 Exception raised:
2118 ...
2119 NameError: name 'favorite_color' is not defined
2120 (1, 2)
2121 >>> doctest.master = None # Reset master.
2122
2123The optional keyword argument `raise_on_error` can be used to raise an
2124exception on the first error (which may be useful for postmortem
2125debugging):
2126
2127 >>> doctest.testfile('test_doctest.txt', raise_on_error=True)
2128 ... # doctest: +ELLIPSIS
2129 Traceback (most recent call last):
2130 UnexpectedException: ...
2131 >>> doctest.master = None # Reset master.
2132"""
2133
Tim Petersa7def722004-08-23 22:13:22 +00002134# old_test1, ... used to live in doctest.py, but cluttered it. Note
2135# that these use the deprecated doctest.Tester, so should go away (or
2136# be rewritten) someday.
2137
2138# Ignore all warnings about the use of class Tester in this module.
2139# Note that the name of this module may differ depending on how it's
2140# imported, so the use of __name__ is important.
2141warnings.filterwarnings("ignore", "class Tester", DeprecationWarning,
2142 __name__, 0)
2143
2144def old_test1(): r"""
2145>>> from doctest import Tester
2146>>> t = Tester(globs={'x': 42}, verbose=0)
2147>>> t.runstring(r'''
2148... >>> x = x * 2
2149... >>> print x
2150... 42
2151... ''', 'XYZ')
2152**********************************************************************
2153Line 3, in XYZ
2154Failed example:
2155 print x
2156Expected:
2157 42
2158Got:
2159 84
2160(1, 2)
2161>>> t.runstring(">>> x = x * 2\n>>> print x\n84\n", 'example2')
2162(0, 2)
2163>>> t.summarize()
2164**********************************************************************
21651 items had failures:
2166 1 of 2 in XYZ
2167***Test Failed*** 1 failures.
2168(1, 4)
2169>>> t.summarize(verbose=1)
21701 items passed all tests:
2171 2 tests in example2
2172**********************************************************************
21731 items had failures:
2174 1 of 2 in XYZ
21754 tests in 2 items.
21763 passed and 1 failed.
2177***Test Failed*** 1 failures.
2178(1, 4)
2179"""
2180
2181def old_test2(): r"""
2182 >>> from doctest import Tester
2183 >>> t = Tester(globs={}, verbose=1)
2184 >>> test = r'''
2185 ... # just an example
2186 ... >>> x = 1 + 2
2187 ... >>> x
2188 ... 3
2189 ... '''
2190 >>> t.runstring(test, "Example")
2191 Running string Example
Edward Loperaacf0832004-08-26 01:19:50 +00002192 Trying:
2193 x = 1 + 2
2194 Expecting nothing
Tim Petersa7def722004-08-23 22:13:22 +00002195 ok
Edward Loperaacf0832004-08-26 01:19:50 +00002196 Trying:
2197 x
2198 Expecting:
2199 3
Tim Petersa7def722004-08-23 22:13:22 +00002200 ok
2201 0 of 2 examples failed in string Example
2202 (0, 2)
2203"""
2204
2205def old_test3(): r"""
2206 >>> from doctest import Tester
2207 >>> t = Tester(globs={}, verbose=0)
2208 >>> def _f():
2209 ... '''Trivial docstring example.
2210 ... >>> assert 2 == 2
2211 ... '''
2212 ... return 32
2213 ...
2214 >>> t.rundoc(_f) # expect 0 failures in 1 example
2215 (0, 1)
2216"""
2217
2218def old_test4(): """
2219 >>> import new
2220 >>> m1 = new.module('_m1')
2221 >>> m2 = new.module('_m2')
2222 >>> test_data = \"""
2223 ... def _f():
2224 ... '''>>> assert 1 == 1
2225 ... '''
2226 ... def g():
2227 ... '''>>> assert 2 != 1
2228 ... '''
2229 ... class H:
2230 ... '''>>> assert 2 > 1
2231 ... '''
2232 ... def bar(self):
2233 ... '''>>> assert 1 < 2
2234 ... '''
2235 ... \"""
2236 >>> exec test_data in m1.__dict__
2237 >>> exec test_data in m2.__dict__
2238 >>> m1.__dict__.update({"f2": m2._f, "g2": m2.g, "h2": m2.H})
2239
2240 Tests that objects outside m1 are excluded:
2241
2242 >>> from doctest import Tester
2243 >>> t = Tester(globs={}, verbose=0)
2244 >>> t.rundict(m1.__dict__, "rundict_test", m1) # f2 and g2 and h2 skipped
2245 (0, 4)
2246
2247 Once more, not excluding stuff outside m1:
2248
2249 >>> t = Tester(globs={}, verbose=0)
2250 >>> t.rundict(m1.__dict__, "rundict_test_pvt") # None are skipped.
2251 (0, 8)
2252
2253 The exclusion of objects from outside the designated module is
2254 meant to be invoked automagically by testmod.
2255
2256 >>> doctest.testmod(m1, verbose=False)
2257 (0, 4)
2258"""
2259
Tim Peters8485b562004-08-04 18:46:34 +00002260######################################################################
2261## Main
2262######################################################################
2263
2264def test_main():
2265 # Check the doctest cases in doctest itself:
2266 test_support.run_doctest(doctest, verbosity=True)
2267 # Check the doctest cases defined here:
2268 from test import test_doctest
2269 test_support.run_doctest(test_doctest, verbosity=True)
2270
2271import trace, sys, re, StringIO
2272def test_coverage(coverdir):
2273 tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
2274 trace=0, count=1)
2275 tracer.run('reload(doctest); test_main()')
2276 r = tracer.results()
2277 print 'Writing coverage results...'
2278 r.write_results(show_missing=True, summary=True,
2279 coverdir=coverdir)
2280
2281if __name__ == '__main__':
2282 if '-c' in sys.argv:
2283 test_coverage('/tmp/doctest.cover')
2284 else:
2285 test_main()