blob: 01f7acd2f5666b1dce611eeb915bb02d9f46ea91 [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
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000515Empty Tests
516~~~~~~~~~~~
517By default, an object with no doctests doesn't create any tests:
Tim Peters8485b562004-08-04 18:46:34 +0000518
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000519 >>> tests = doctest.DocTestFinder().find(SampleClass)
Tim Peters8485b562004-08-04 18:46:34 +0000520 >>> tests.sort()
521 >>> for t in tests:
522 ... print '%2s %s' % (len(t.examples), t.name)
Edward Loper4ae900f2004-09-21 03:20:34 +0000523 3 SampleClass
Tim Peters8485b562004-08-04 18:46:34 +0000524 3 SampleClass.NestedClass
525 1 SampleClass.NestedClass.__init__
Tim Peters958cc892004-09-13 14:53:28 +0000526 1 SampleClass.__init__
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000527 2 SampleClass.a_classmethod
528 1 SampleClass.a_property
529 1 SampleClass.a_staticmethod
Tim Peters958cc892004-09-13 14:53:28 +0000530 1 SampleClass.double
531 1 SampleClass.get
532
533By default, that excluded objects with no doctests. exclude_empty=False
534tells it to include (empty) tests for objects with no doctests. This feature
535is really to support backward compatibility in what doctest.master.summarize()
536displays.
537
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000538 >>> tests = doctest.DocTestFinder(exclude_empty=False).find(SampleClass)
Tim Peters958cc892004-09-13 14:53:28 +0000539 >>> tests.sort()
540 >>> for t in tests:
541 ... print '%2s %s' % (len(t.examples), t.name)
Edward Loper4ae900f2004-09-21 03:20:34 +0000542 3 SampleClass
Tim Peters958cc892004-09-13 14:53:28 +0000543 3 SampleClass.NestedClass
544 1 SampleClass.NestedClass.__init__
Edward Loper32ddbf72004-09-13 05:47:24 +0000545 0 SampleClass.NestedClass.get
546 0 SampleClass.NestedClass.square
Tim Peters8485b562004-08-04 18:46:34 +0000547 1 SampleClass.__init__
Tim Peters8485b562004-08-04 18:46:34 +0000548 2 SampleClass.a_classmethod
549 1 SampleClass.a_property
550 1 SampleClass.a_staticmethod
551 1 SampleClass.double
552 1 SampleClass.get
553
Tim Peters8485b562004-08-04 18:46:34 +0000554Turning off Recursion
555~~~~~~~~~~~~~~~~~~~~~
556DocTestFinder can be told not to look for tests in contained objects
557using the `recurse` flag:
558
559 >>> tests = doctest.DocTestFinder(recurse=False).find(SampleClass)
560 >>> tests.sort()
561 >>> for t in tests:
562 ... print '%2s %s' % (len(t.examples), t.name)
Edward Loper4ae900f2004-09-21 03:20:34 +0000563 3 SampleClass
Edward Loperb51b2342004-08-17 16:37:12 +0000564
565Line numbers
566~~~~~~~~~~~~
567DocTestFinder finds the line number of each example:
568
569 >>> def f(x):
570 ... '''
571 ... >>> x = 12
572 ...
573 ... some text
574 ...
575 ... >>> # examples are not created for comments & bare prompts.
576 ... >>>
577 ... ...
578 ...
579 ... >>> for x in range(10):
580 ... ... print x,
581 ... 0 1 2 3 4 5 6 7 8 9
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000582 ... >>> x//2
583 ... 6
Edward Loperb51b2342004-08-17 16:37:12 +0000584 ... '''
585 >>> test = doctest.DocTestFinder().find(f)[0]
586 >>> [e.lineno for e in test.examples]
587 [1, 9, 12]
Tim Peters8485b562004-08-04 18:46:34 +0000588"""
589
Edward Loper00f8da72004-08-26 18:05:07 +0000590def test_DocTestParser(): r"""
591Unit tests for the `DocTestParser` class.
592
593DocTestParser is used to parse docstrings containing doctest examples.
594
595The `parse` method divides a docstring into examples and intervening
596text:
597
598 >>> s = '''
599 ... >>> x, y = 2, 3 # no output expected
600 ... >>> if 1:
601 ... ... print x
602 ... ... print y
603 ... 2
604 ... 3
605 ...
606 ... Some text.
607 ... >>> x+y
608 ... 5
609 ... '''
610 >>> parser = doctest.DocTestParser()
611 >>> for piece in parser.parse(s):
612 ... if isinstance(piece, doctest.Example):
613 ... print 'Example:', (piece.source, piece.want, piece.lineno)
614 ... else:
615 ... print ' Text:', `piece`
616 Text: '\n'
617 Example: ('x, y = 2, 3 # no output expected\n', '', 1)
618 Text: ''
619 Example: ('if 1:\n print x\n print y\n', '2\n3\n', 2)
620 Text: '\nSome text.\n'
621 Example: ('x+y\n', '5\n', 9)
622 Text: ''
623
624The `get_examples` method returns just the examples:
625
626 >>> for piece in parser.get_examples(s):
627 ... print (piece.source, piece.want, piece.lineno)
628 ('x, y = 2, 3 # no output expected\n', '', 1)
629 ('if 1:\n print x\n print y\n', '2\n3\n', 2)
630 ('x+y\n', '5\n', 9)
631
632The `get_doctest` method creates a Test from the examples, along with the
633given arguments:
634
635 >>> test = parser.get_doctest(s, {}, 'name', 'filename', lineno=5)
636 >>> (test.name, test.filename, test.lineno)
637 ('name', 'filename', 5)
638 >>> for piece in test.examples:
639 ... print (piece.source, piece.want, piece.lineno)
640 ('x, y = 2, 3 # no output expected\n', '', 1)
641 ('if 1:\n print x\n print y\n', '2\n3\n', 2)
642 ('x+y\n', '5\n', 9)
643"""
644
Tim Peters8485b562004-08-04 18:46:34 +0000645class test_DocTestRunner:
646 def basics(): r"""
647Unit tests for the `DocTestRunner` class.
648
649DocTestRunner is used to run DocTest test cases, and to accumulate
650statistics. Here's a simple DocTest case we can use:
651
652 >>> def f(x):
653 ... '''
654 ... >>> x = 12
655 ... >>> print x
656 ... 12
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000657 ... >>> x//2
658 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000659 ... '''
660 >>> test = doctest.DocTestFinder().find(f)[0]
661
662The main DocTestRunner interface is the `run` method, which runs a
663given DocTest case in a given namespace (globs). It returns a tuple
664`(f,t)`, where `f` is the number of failed tests and `t` is the number
665of tried tests.
666
667 >>> doctest.DocTestRunner(verbose=False).run(test)
668 (0, 3)
669
670If any example produces incorrect output, then the test runner reports
671the failure and proceeds to the next example:
672
673 >>> def f(x):
674 ... '''
675 ... >>> x = 12
676 ... >>> print x
677 ... 14
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000678 ... >>> x//2
679 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000680 ... '''
681 >>> test = doctest.DocTestFinder().find(f)[0]
682 >>> doctest.DocTestRunner(verbose=True).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000683 ... # doctest: +ELLIPSIS
Edward Loperaacf0832004-08-26 01:19:50 +0000684 Trying:
685 x = 12
686 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000687 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000688 Trying:
689 print x
690 Expecting:
691 14
Tim Peters8485b562004-08-04 18:46:34 +0000692 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000693 File ..., line 4, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000694 Failed example:
695 print x
696 Expected:
697 14
698 Got:
699 12
Edward Loperaacf0832004-08-26 01:19:50 +0000700 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000701 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000702 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000703 6
Tim Peters8485b562004-08-04 18:46:34 +0000704 ok
705 (1, 3)
706"""
707 def verbose_flag(): r"""
708The `verbose` flag makes the test runner generate more detailed
709output:
710
711 >>> def f(x):
712 ... '''
713 ... >>> x = 12
714 ... >>> print x
715 ... 12
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000716 ... >>> x//2
717 ... 6
Tim Peters8485b562004-08-04 18:46:34 +0000718 ... '''
719 >>> test = doctest.DocTestFinder().find(f)[0]
720
721 >>> doctest.DocTestRunner(verbose=True).run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000722 Trying:
723 x = 12
724 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000725 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000726 Trying:
727 print x
728 Expecting:
729 12
Tim Peters8485b562004-08-04 18:46:34 +0000730 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000731 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000732 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000733 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000734 6
Tim Peters8485b562004-08-04 18:46:34 +0000735 ok
736 (0, 3)
737
738If the `verbose` flag is unspecified, then the output will be verbose
739iff `-v` appears in sys.argv:
740
741 >>> # Save the real sys.argv list.
742 >>> old_argv = sys.argv
743
744 >>> # If -v does not appear in sys.argv, then output isn't verbose.
745 >>> sys.argv = ['test']
746 >>> doctest.DocTestRunner().run(test)
747 (0, 3)
748
749 >>> # If -v does appear in sys.argv, then output is verbose.
750 >>> sys.argv = ['test', '-v']
751 >>> doctest.DocTestRunner().run(test)
Edward Loperaacf0832004-08-26 01:19:50 +0000752 Trying:
753 x = 12
754 Expecting nothing
Tim Peters8485b562004-08-04 18:46:34 +0000755 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000756 Trying:
757 print x
758 Expecting:
759 12
Tim Peters8485b562004-08-04 18:46:34 +0000760 ok
Edward Loperaacf0832004-08-26 01:19:50 +0000761 Trying:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000762 x//2
Edward Loperaacf0832004-08-26 01:19:50 +0000763 Expecting:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000764 6
Tim Peters8485b562004-08-04 18:46:34 +0000765 ok
766 (0, 3)
767
768 >>> # Restore sys.argv
769 >>> sys.argv = old_argv
770
771In the remaining examples, the test runner's verbosity will be
772explicitly set, to ensure that the test behavior is consistent.
773 """
774 def exceptions(): r"""
775Tests of `DocTestRunner`'s exception handling.
776
777An expected exception is specified with a traceback message. The
778lines between the first line and the type/value may be omitted or
779replaced with any other string:
780
781 >>> def f(x):
782 ... '''
783 ... >>> x = 12
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000784 ... >>> print x//0
Tim Peters8485b562004-08-04 18:46:34 +0000785 ... Traceback (most recent call last):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000786 ... ZeroDivisionError: integer division or modulo by zero
Tim Peters8485b562004-08-04 18:46:34 +0000787 ... '''
788 >>> test = doctest.DocTestFinder().find(f)[0]
789 >>> doctest.DocTestRunner(verbose=False).run(test)
790 (0, 2)
791
Edward Loper19b19582004-08-25 23:07:03 +0000792An example may not generate output before it raises an exception; if
793it does, then the traceback message will not be recognized as
794signaling an expected exception, so the example will be reported as an
795unexpected exception:
Tim Peters8485b562004-08-04 18:46:34 +0000796
797 >>> def f(x):
798 ... '''
799 ... >>> x = 12
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000800 ... >>> print 'pre-exception output', x//0
Tim Peters8485b562004-08-04 18:46:34 +0000801 ... pre-exception output
802 ... Traceback (most recent call last):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000803 ... ZeroDivisionError: integer division or modulo by zero
Tim Peters8485b562004-08-04 18:46:34 +0000804 ... '''
805 >>> test = doctest.DocTestFinder().find(f)[0]
806 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper19b19582004-08-25 23:07:03 +0000807 ... # doctest: +ELLIPSIS
808 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000809 File ..., line 4, in f
Edward Loper19b19582004-08-25 23:07:03 +0000810 Failed example:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000811 print 'pre-exception output', x//0
Edward Loper19b19582004-08-25 23:07:03 +0000812 Exception raised:
813 ...
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000814 ZeroDivisionError: integer division or modulo by zero
Edward Loper19b19582004-08-25 23:07:03 +0000815 (1, 2)
Tim Peters8485b562004-08-04 18:46:34 +0000816
817Exception messages may contain newlines:
818
819 >>> def f(x):
820 ... r'''
821 ... >>> raise ValueError, 'multi\nline\nmessage'
822 ... Traceback (most recent call last):
823 ... ValueError: multi
824 ... line
825 ... message
826 ... '''
827 >>> test = doctest.DocTestFinder().find(f)[0]
828 >>> doctest.DocTestRunner(verbose=False).run(test)
829 (0, 1)
830
831If an exception is expected, but an exception with the wrong type or
832message is raised, then it is reported as a failure:
833
834 >>> def f(x):
835 ... r'''
836 ... >>> raise ValueError, 'message'
837 ... Traceback (most recent call last):
838 ... ValueError: wrong message
839 ... '''
840 >>> test = doctest.DocTestFinder().find(f)[0]
841 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000842 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000843 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000844 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000845 Failed example:
846 raise ValueError, 'message'
Tim Peters8485b562004-08-04 18:46:34 +0000847 Expected:
848 Traceback (most recent call last):
849 ValueError: wrong message
850 Got:
851 Traceback (most recent call last):
Edward Loper8e4a34b2004-08-12 02:34:27 +0000852 ...
Tim Peters8485b562004-08-04 18:46:34 +0000853 ValueError: message
854 (1, 1)
855
Tim Peters1fbf9c52004-09-04 17:21:02 +0000856However, IGNORE_EXCEPTION_DETAIL can be used to allow a mismatch in the
857detail:
858
859 >>> def f(x):
860 ... r'''
861 ... >>> raise ValueError, 'message' #doctest: +IGNORE_EXCEPTION_DETAIL
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)
867 (0, 1)
868
869But IGNORE_EXCEPTION_DETAIL does not allow a mismatch in the exception type:
870
871 >>> def f(x):
872 ... r'''
873 ... >>> raise ValueError, 'message' #doctest: +IGNORE_EXCEPTION_DETAIL
874 ... Traceback (most recent call last):
875 ... TypeError: wrong type
876 ... '''
877 >>> test = doctest.DocTestFinder().find(f)[0]
878 >>> doctest.DocTestRunner(verbose=False).run(test)
879 ... # doctest: +ELLIPSIS
880 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000881 File ..., line 3, in f
Tim Peters1fbf9c52004-09-04 17:21:02 +0000882 Failed example:
883 raise ValueError, 'message' #doctest: +IGNORE_EXCEPTION_DETAIL
884 Expected:
885 Traceback (most recent call last):
886 TypeError: wrong type
887 Got:
888 Traceback (most recent call last):
889 ...
890 ValueError: message
891 (1, 1)
892
Tim Peters8485b562004-08-04 18:46:34 +0000893If an exception is raised but not expected, then it is reported as an
894unexpected exception:
895
Tim Peters8485b562004-08-04 18:46:34 +0000896 >>> def f(x):
897 ... r'''
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000898 ... >>> 1//0
Tim Peters8485b562004-08-04 18:46:34 +0000899 ... 0
900 ... '''
901 >>> test = doctest.DocTestFinder().find(f)[0]
902 >>> doctest.DocTestRunner(verbose=False).run(test)
Edward Loper74bca7a2004-08-12 02:27:44 +0000903 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000904 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000905 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000906 Failed example:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000907 1//0
Tim Peters8485b562004-08-04 18:46:34 +0000908 Exception raised:
909 Traceback (most recent call last):
Jim Fulton07a349c2004-08-22 14:10:00 +0000910 ...
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000911 ZeroDivisionError: integer division or modulo by zero
Tim Peters8485b562004-08-04 18:46:34 +0000912 (1, 1)
Tim Peters8485b562004-08-04 18:46:34 +0000913"""
914 def optionflags(): r"""
915Tests of `DocTestRunner`'s option flag handling.
916
917Several option flags can be used to customize the behavior of the test
918runner. These are defined as module constants in doctest, and passed
919to the DocTestRunner constructor (multiple constants should be or-ed
920together).
921
922The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
923and 1/0:
924
925 >>> def f(x):
926 ... '>>> True\n1\n'
927
928 >>> # Without the flag:
929 >>> test = doctest.DocTestFinder().find(f)[0]
930 >>> doctest.DocTestRunner(verbose=False).run(test)
931 (0, 1)
932
933 >>> # With the flag:
934 >>> test = doctest.DocTestFinder().find(f)[0]
935 >>> flags = doctest.DONT_ACCEPT_TRUE_FOR_1
936 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000937 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000938 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000939 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000940 Failed example:
941 True
942 Expected:
943 1
944 Got:
945 True
Tim Peters8485b562004-08-04 18:46:34 +0000946 (1, 1)
947
948The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines
949and the '<BLANKLINE>' marker:
950
951 >>> def f(x):
952 ... '>>> print "a\\n\\nb"\na\n<BLANKLINE>\nb\n'
953
954 >>> # Without the flag:
955 >>> test = doctest.DocTestFinder().find(f)[0]
956 >>> doctest.DocTestRunner(verbose=False).run(test)
957 (0, 1)
958
959 >>> # With the flag:
960 >>> test = doctest.DocTestFinder().find(f)[0]
961 >>> flags = doctest.DONT_ACCEPT_BLANKLINE
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 print "a\n\nb"
Tim Peters8485b562004-08-04 18:46:34 +0000968 Expected:
969 a
970 <BLANKLINE>
971 b
972 Got:
973 a
974 <BLANKLINE>
975 b
976 (1, 1)
977
978The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be
979treated as equal:
980
981 >>> def f(x):
982 ... '>>> print 1, 2, 3\n 1 2\n 3'
983
984 >>> # Without the flag:
985 >>> test = doctest.DocTestFinder().find(f)[0]
986 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +0000987 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +0000988 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +0000989 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +0000990 Failed example:
991 print 1, 2, 3
Tim Peters8485b562004-08-04 18:46:34 +0000992 Expected:
993 1 2
994 3
Jim Fulton07a349c2004-08-22 14:10:00 +0000995 Got:
996 1 2 3
Tim Peters8485b562004-08-04 18:46:34 +0000997 (1, 1)
998
999 >>> # With the flag:
1000 >>> test = doctest.DocTestFinder().find(f)[0]
1001 >>> flags = doctest.NORMALIZE_WHITESPACE
1002 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1003 (0, 1)
1004
Tim Peters026f8dc2004-08-19 16:38:58 +00001005 An example from the docs:
1006 >>> print range(20) #doctest: +NORMALIZE_WHITESPACE
1007 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
1008 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
1009
Tim Peters8485b562004-08-04 18:46:34 +00001010The ELLIPSIS flag causes ellipsis marker ("...") in the expected
1011output to match any substring in the actual output:
1012
1013 >>> def f(x):
1014 ... '>>> print range(15)\n[0, 1, 2, ..., 14]\n'
1015
1016 >>> # Without the flag:
1017 >>> test = doctest.DocTestFinder().find(f)[0]
1018 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001019 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001020 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001021 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001022 Failed example:
1023 print range(15)
1024 Expected:
1025 [0, 1, 2, ..., 14]
1026 Got:
1027 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
Tim Peters8485b562004-08-04 18:46:34 +00001028 (1, 1)
1029
1030 >>> # With the flag:
1031 >>> test = doctest.DocTestFinder().find(f)[0]
1032 >>> flags = doctest.ELLIPSIS
1033 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1034 (0, 1)
1035
Tim Peterse594bee2004-08-22 01:47:51 +00001036 ... also matches nothing:
Tim Peters1cf3aa62004-08-19 06:49:33 +00001037
1038 >>> for i in range(100):
Tim Peterse594bee2004-08-22 01:47:51 +00001039 ... print i**2, #doctest: +ELLIPSIS
1040 0 1...4...9 16 ... 36 49 64 ... 9801
Tim Peters1cf3aa62004-08-19 06:49:33 +00001041
Tim Peters026f8dc2004-08-19 16:38:58 +00001042 ... can be surprising; e.g., this test passes:
Tim Peters26b3ebb2004-08-19 08:10:08 +00001043
1044 >>> for i in range(21): #doctest: +ELLIPSIS
Tim Peterse594bee2004-08-22 01:47:51 +00001045 ... print i,
1046 0 1 2 ...1...2...0
Tim Peters26b3ebb2004-08-19 08:10:08 +00001047
Tim Peters026f8dc2004-08-19 16:38:58 +00001048 Examples from the docs:
1049
1050 >>> print range(20) # doctest:+ELLIPSIS
1051 [0, 1, ..., 18, 19]
1052
1053 >>> print range(20) # doctest: +ELLIPSIS
1054 ... # doctest: +NORMALIZE_WHITESPACE
1055 [0, 1, ..., 18, 19]
1056
Thomas Wouters477c8d52006-05-27 19:21:47 +00001057The SKIP flag causes an example to be skipped entirely. I.e., the
1058example is not run. It can be useful in contexts where doctest
1059examples serve as both documentation and test cases, and an example
1060should be included for documentation purposes, but should not be
1061checked (e.g., because its output is random, or depends on resources
1062which would be unavailable.) The SKIP flag can also be used for
1063'commenting out' broken examples.
1064
1065 >>> import unavailable_resource # doctest: +SKIP
1066 >>> unavailable_resource.do_something() # doctest: +SKIP
1067 >>> unavailable_resource.blow_up() # doctest: +SKIP
1068 Traceback (most recent call last):
1069 ...
1070 UncheckedBlowUpError: Nobody checks me.
1071
1072 >>> import random
1073 >>> print random.random() # doctest: +SKIP
1074 0.721216923889
1075
Edward Loper71f55af2004-08-26 01:41:51 +00001076The REPORT_UDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001077and actual outputs to be displayed using a unified diff:
1078
1079 >>> def f(x):
1080 ... r'''
1081 ... >>> print '\n'.join('abcdefg')
1082 ... a
1083 ... B
1084 ... c
1085 ... d
1086 ... f
1087 ... g
1088 ... h
1089 ... '''
1090
1091 >>> # Without the flag:
1092 >>> test = doctest.DocTestFinder().find(f)[0]
1093 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001094 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001095 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001096 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001097 Failed example:
1098 print '\n'.join('abcdefg')
Tim Peters8485b562004-08-04 18:46:34 +00001099 Expected:
1100 a
1101 B
1102 c
1103 d
1104 f
1105 g
1106 h
1107 Got:
1108 a
1109 b
1110 c
1111 d
1112 e
1113 f
1114 g
1115 (1, 1)
1116
1117 >>> # With the flag:
1118 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001119 >>> flags = doctest.REPORT_UDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001120 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001121 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001122 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001123 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001124 Failed example:
1125 print '\n'.join('abcdefg')
Edward Loper56629292004-08-26 01:31:56 +00001126 Differences (unified diff with -expected +actual):
Tim Peterse7edcb82004-08-26 05:44:27 +00001127 @@ -1,7 +1,7 @@
Tim Peters8485b562004-08-04 18:46:34 +00001128 a
1129 -B
1130 +b
1131 c
1132 d
1133 +e
1134 f
1135 g
1136 -h
Tim Peters8485b562004-08-04 18:46:34 +00001137 (1, 1)
1138
Edward Loper71f55af2004-08-26 01:41:51 +00001139The REPORT_CDIFF flag causes failures that involve multi-line expected
Tim Peters8485b562004-08-04 18:46:34 +00001140and actual outputs to be displayed using a context diff:
1141
Edward Loper71f55af2004-08-26 01:41:51 +00001142 >>> # Reuse f() from the REPORT_UDIFF example, above.
Tim Peters8485b562004-08-04 18:46:34 +00001143 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001144 >>> flags = doctest.REPORT_CDIFF
Tim Peters8485b562004-08-04 18:46:34 +00001145 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001146 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001147 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001148 File ..., line 3, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001149 Failed example:
1150 print '\n'.join('abcdefg')
Edward Loper56629292004-08-26 01:31:56 +00001151 Differences (context diff with expected followed by actual):
Tim Peters8485b562004-08-04 18:46:34 +00001152 ***************
Tim Peterse7edcb82004-08-26 05:44:27 +00001153 *** 1,7 ****
Tim Peters8485b562004-08-04 18:46:34 +00001154 a
1155 ! B
1156 c
1157 d
1158 f
1159 g
1160 - h
Tim Peterse7edcb82004-08-26 05:44:27 +00001161 --- 1,7 ----
Tim Peters8485b562004-08-04 18:46:34 +00001162 a
1163 ! b
1164 c
1165 d
1166 + e
1167 f
1168 g
Tim Peters8485b562004-08-04 18:46:34 +00001169 (1, 1)
Tim Petersc6cbab02004-08-22 19:43:28 +00001170
1171
Edward Loper71f55af2004-08-26 01:41:51 +00001172The REPORT_NDIFF flag causes failures to use the difflib.Differ algorithm
Tim Petersc6cbab02004-08-22 19:43:28 +00001173used by the popular ndiff.py utility. This does intraline difference
1174marking, as well as interline differences.
1175
1176 >>> def f(x):
1177 ... r'''
1178 ... >>> print "a b c d e f g h i j k l m"
1179 ... a b c d e f g h i j k 1 m
1180 ... '''
1181 >>> test = doctest.DocTestFinder().find(f)[0]
Edward Loper71f55af2004-08-26 01:41:51 +00001182 >>> flags = doctest.REPORT_NDIFF
Tim Petersc6cbab02004-08-22 19:43:28 +00001183 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001184 ... # doctest: +ELLIPSIS
Tim Petersc6cbab02004-08-22 19:43:28 +00001185 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001186 File ..., line 3, in f
Tim Petersc6cbab02004-08-22 19:43:28 +00001187 Failed example:
1188 print "a b c d e f g h i j k l m"
1189 Differences (ndiff with -expected +actual):
1190 - a b c d e f g h i j k 1 m
1191 ? ^
1192 + a b c d e f g h i j k l m
1193 ? + ++ ^
Tim Petersc6cbab02004-08-22 19:43:28 +00001194 (1, 1)
Edward Lopera89f88d2004-08-26 02:45:51 +00001195
1196The REPORT_ONLY_FIRST_FAILURE supresses result output after the first
1197failing example:
1198
1199 >>> def f(x):
1200 ... r'''
1201 ... >>> print 1 # first success
1202 ... 1
1203 ... >>> print 2 # first failure
1204 ... 200
1205 ... >>> print 3 # second failure
1206 ... 300
1207 ... >>> print 4 # second success
1208 ... 4
1209 ... >>> print 5 # third failure
1210 ... 500
1211 ... '''
1212 >>> test = doctest.DocTestFinder().find(f)[0]
1213 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1214 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001215 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001216 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001217 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001218 Failed example:
1219 print 2 # first failure
1220 Expected:
1221 200
1222 Got:
1223 2
1224 (3, 5)
1225
1226However, output from `report_start` is not supressed:
1227
1228 >>> doctest.DocTestRunner(verbose=True, optionflags=flags).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001229 ... # doctest: +ELLIPSIS
Edward Lopera89f88d2004-08-26 02:45:51 +00001230 Trying:
1231 print 1 # first success
1232 Expecting:
1233 1
1234 ok
1235 Trying:
1236 print 2 # first failure
1237 Expecting:
1238 200
1239 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001240 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001241 Failed example:
1242 print 2 # first failure
1243 Expected:
1244 200
1245 Got:
1246 2
1247 (3, 5)
1248
1249For the purposes of REPORT_ONLY_FIRST_FAILURE, unexpected exceptions
1250count as failures:
1251
1252 >>> def f(x):
1253 ... r'''
1254 ... >>> print 1 # first success
1255 ... 1
1256 ... >>> raise ValueError(2) # first failure
1257 ... 200
1258 ... >>> print 3 # second failure
1259 ... 300
1260 ... >>> print 4 # second success
1261 ... 4
1262 ... >>> print 5 # third failure
1263 ... 500
1264 ... '''
1265 >>> test = doctest.DocTestFinder().find(f)[0]
1266 >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
1267 >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
1268 ... # doctest: +ELLIPSIS
1269 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001270 File ..., line 5, in f
Edward Lopera89f88d2004-08-26 02:45:51 +00001271 Failed example:
1272 raise ValueError(2) # first failure
1273 Exception raised:
1274 ...
1275 ValueError: 2
1276 (3, 5)
1277
Thomas Wouters477c8d52006-05-27 19:21:47 +00001278New option flags can also be registered, via register_optionflag(). Here
1279we reach into doctest's internals a bit.
1280
1281 >>> unlikely = "UNLIKELY_OPTION_NAME"
1282 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1283 False
1284 >>> new_flag_value = doctest.register_optionflag(unlikely)
1285 >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
1286 True
1287
1288Before 2.4.4/2.5, registering a name more than once erroneously created
1289more than one flag value. Here we verify that's fixed:
1290
1291 >>> redundant_flag_value = doctest.register_optionflag(unlikely)
1292 >>> redundant_flag_value == new_flag_value
1293 True
1294
1295Clean up.
1296 >>> del doctest.OPTIONFLAGS_BY_NAME[unlikely]
1297
Tim Petersc6cbab02004-08-22 19:43:28 +00001298 """
1299
Tim Peters8485b562004-08-04 18:46:34 +00001300 def option_directives(): r"""
1301Tests of `DocTestRunner`'s option directive mechanism.
1302
Edward Loper74bca7a2004-08-12 02:27:44 +00001303Option directives can be used to turn option flags on or off for a
1304single example. To turn an option on for an example, follow that
1305example with a comment of the form ``# doctest: +OPTION``:
Tim Peters8485b562004-08-04 18:46:34 +00001306
1307 >>> def f(x): r'''
Edward Loper74bca7a2004-08-12 02:27:44 +00001308 ... >>> print range(10) # should fail: no ellipsis
1309 ... [0, 1, ..., 9]
1310 ...
1311 ... >>> print range(10) # doctest: +ELLIPSIS
1312 ... [0, 1, ..., 9]
1313 ... '''
1314 >>> test = doctest.DocTestFinder().find(f)[0]
1315 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001316 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001317 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001318 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001319 Failed example:
1320 print range(10) # should fail: no ellipsis
1321 Expected:
1322 [0, 1, ..., 9]
1323 Got:
1324 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001325 (1, 2)
1326
1327To turn an option off for an example, follow that example with a
1328comment of the form ``# doctest: -OPTION``:
1329
1330 >>> def f(x): r'''
1331 ... >>> print range(10)
1332 ... [0, 1, ..., 9]
1333 ...
1334 ... >>> # should fail: no ellipsis
1335 ... >>> print range(10) # doctest: -ELLIPSIS
1336 ... [0, 1, ..., 9]
1337 ... '''
1338 >>> test = doctest.DocTestFinder().find(f)[0]
1339 >>> doctest.DocTestRunner(verbose=False,
1340 ... optionflags=doctest.ELLIPSIS).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001341 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001342 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001343 File ..., line 6, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001344 Failed example:
1345 print range(10) # doctest: -ELLIPSIS
1346 Expected:
1347 [0, 1, ..., 9]
1348 Got:
1349 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001350 (1, 2)
1351
1352Option directives affect only the example that they appear with; they
1353do not change the options for surrounding examples:
Edward Loper8e4a34b2004-08-12 02:34:27 +00001354
Edward Loper74bca7a2004-08-12 02:27:44 +00001355 >>> def f(x): r'''
Tim Peters8485b562004-08-04 18:46:34 +00001356 ... >>> print range(10) # Should fail: no ellipsis
1357 ... [0, 1, ..., 9]
1358 ...
Edward Loper74bca7a2004-08-12 02:27:44 +00001359 ... >>> print range(10) # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001360 ... [0, 1, ..., 9]
1361 ...
Tim Peters8485b562004-08-04 18:46:34 +00001362 ... >>> print range(10) # Should fail: no ellipsis
1363 ... [0, 1, ..., 9]
1364 ... '''
1365 >>> test = doctest.DocTestFinder().find(f)[0]
1366 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001367 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001368 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001369 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001370 Failed example:
1371 print range(10) # Should fail: no ellipsis
1372 Expected:
1373 [0, 1, ..., 9]
1374 Got:
1375 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001376 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001377 File ..., line 8, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001378 Failed example:
1379 print range(10) # Should fail: no ellipsis
1380 Expected:
1381 [0, 1, ..., 9]
1382 Got:
1383 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001384 (2, 3)
1385
Edward Loper74bca7a2004-08-12 02:27:44 +00001386Multiple options may be modified by a single option directive. They
1387may be separated by whitespace, commas, or both:
Tim Peters8485b562004-08-04 18:46:34 +00001388
1389 >>> def f(x): r'''
1390 ... >>> print range(10) # Should fail
1391 ... [0, 1, ..., 9]
Tim Peters8485b562004-08-04 18:46:34 +00001392 ... >>> print range(10) # Should succeed
Edward Loper74bca7a2004-08-12 02:27:44 +00001393 ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001394 ... [0, 1, ..., 9]
1395 ... '''
1396 >>> test = doctest.DocTestFinder().find(f)[0]
1397 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001398 ... # doctest: +ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001399 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001400 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001401 Failed example:
1402 print range(10) # Should fail
1403 Expected:
1404 [0, 1, ..., 9]
1405 Got:
1406 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim Peters8485b562004-08-04 18:46:34 +00001407 (1, 2)
Edward Loper74bca7a2004-08-12 02:27:44 +00001408
1409 >>> def f(x): r'''
1410 ... >>> print range(10) # Should fail
1411 ... [0, 1, ..., 9]
1412 ... >>> print range(10) # Should succeed
1413 ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
1414 ... [0, 1, ..., 9]
1415 ... '''
1416 >>> test = doctest.DocTestFinder().find(f)[0]
1417 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001418 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001419 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001420 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001421 Failed example:
1422 print range(10) # Should fail
1423 Expected:
1424 [0, 1, ..., 9]
1425 Got:
1426 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001427 (1, 2)
1428
1429 >>> def f(x): r'''
1430 ... >>> print range(10) # Should fail
1431 ... [0, 1, ..., 9]
1432 ... >>> print range(10) # Should succeed
1433 ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
1434 ... [0, 1, ..., 9]
1435 ... '''
1436 >>> test = doctest.DocTestFinder().find(f)[0]
1437 >>> doctest.DocTestRunner(verbose=False).run(test)
Tim Peters17b56372004-09-11 17:33:27 +00001438 ... # doctest: +ELLIPSIS
Edward Loper74bca7a2004-08-12 02:27:44 +00001439 **********************************************************************
Tim Peters17b56372004-09-11 17:33:27 +00001440 File ..., line 2, in f
Jim Fulton07a349c2004-08-22 14:10:00 +00001441 Failed example:
1442 print range(10) # Should fail
1443 Expected:
1444 [0, 1, ..., 9]
1445 Got:
1446 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Edward Loper74bca7a2004-08-12 02:27:44 +00001447 (1, 2)
1448
1449The option directive may be put on the line following the source, as
1450long as a continuation prompt is used:
1451
1452 >>> def f(x): r'''
1453 ... >>> print range(10)
1454 ... ... # doctest: +ELLIPSIS
1455 ... [0, 1, ..., 9]
1456 ... '''
1457 >>> test = doctest.DocTestFinder().find(f)[0]
1458 >>> doctest.DocTestRunner(verbose=False).run(test)
1459 (0, 1)
Edward Loper8e4a34b2004-08-12 02:34:27 +00001460
Edward Loper74bca7a2004-08-12 02:27:44 +00001461For examples with multi-line source, the option directive may appear
1462at the end of any line:
1463
1464 >>> def f(x): r'''
1465 ... >>> for x in range(10): # doctest: +ELLIPSIS
1466 ... ... print x,
1467 ... 0 1 2 ... 9
1468 ...
1469 ... >>> for x in range(10):
1470 ... ... print x, # doctest: +ELLIPSIS
1471 ... 0 1 2 ... 9
1472 ... '''
1473 >>> test = doctest.DocTestFinder().find(f)[0]
1474 >>> doctest.DocTestRunner(verbose=False).run(test)
1475 (0, 2)
1476
1477If more than one line of an example with multi-line source has an
1478option directive, then they are combined:
1479
1480 >>> def f(x): r'''
1481 ... Should fail (option directive not on the last line):
1482 ... >>> for x in range(10): # doctest: +ELLIPSIS
1483 ... ... print x, # doctest: +NORMALIZE_WHITESPACE
1484 ... 0 1 2...9
1485 ... '''
1486 >>> test = doctest.DocTestFinder().find(f)[0]
1487 >>> doctest.DocTestRunner(verbose=False).run(test)
1488 (0, 1)
1489
1490It is an error to have a comment of the form ``# doctest:`` that is
1491*not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
1492``OPTION`` is an option that has been registered with
1493`register_option`:
1494
1495 >>> # Error: Option not registered
1496 >>> s = '>>> print 12 #doctest: +BADOPTION'
1497 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1498 Traceback (most recent call last):
1499 ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
1500
1501 >>> # Error: No + or - prefix
1502 >>> s = '>>> print 12 #doctest: ELLIPSIS'
1503 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1504 Traceback (most recent call last):
1505 ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
1506
1507It is an error to use an option directive on a line that contains no
1508source:
1509
1510 >>> s = '>>> # doctest: +ELLIPSIS'
1511 >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
1512 Traceback (most recent call last):
1513 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 +00001514"""
1515
1516def test_testsource(): r"""
1517Unit tests for `testsource()`.
1518
1519The testsource() function takes a module and a name, finds the (first)
Tim Peters19397e52004-08-06 22:02:59 +00001520test with that name in that module, and converts it to a script. The
1521example code is converted to regular Python code. The surrounding
1522words and expected output are converted to comments:
Tim Peters8485b562004-08-04 18:46:34 +00001523
1524 >>> import test.test_doctest
1525 >>> name = 'test.test_doctest.sample_func'
1526 >>> print doctest.testsource(test.test_doctest, name)
Edward Lopera5db6002004-08-12 02:41:30 +00001527 # Blah blah
Tim Peters19397e52004-08-06 22:02:59 +00001528 #
Tim Peters8485b562004-08-04 18:46:34 +00001529 print sample_func(22)
1530 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001531 ## 44
Tim Peters19397e52004-08-06 22:02:59 +00001532 #
Edward Lopera5db6002004-08-12 02:41:30 +00001533 # Yee ha!
Georg Brandlecf93c72005-06-26 23:09:51 +00001534 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001535
1536 >>> name = 'test.test_doctest.SampleNewStyleClass'
1537 >>> print doctest.testsource(test.test_doctest, name)
1538 print '1\n2\n3'
1539 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001540 ## 1
1541 ## 2
1542 ## 3
Georg Brandlecf93c72005-06-26 23:09:51 +00001543 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001544
1545 >>> name = 'test.test_doctest.SampleClass.a_classmethod'
1546 >>> print doctest.testsource(test.test_doctest, name)
1547 print SampleClass.a_classmethod(10)
1548 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001549 ## 12
Tim Peters8485b562004-08-04 18:46:34 +00001550 print SampleClass(0).a_classmethod(10)
1551 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00001552 ## 12
Georg Brandlecf93c72005-06-26 23:09:51 +00001553 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00001554"""
1555
1556def test_debug(): r"""
1557
1558Create a docstring that we want to debug:
1559
1560 >>> s = '''
1561 ... >>> x = 12
1562 ... >>> print x
1563 ... 12
1564 ... '''
1565
1566Create some fake stdin input, to feed to the debugger:
1567
1568 >>> import tempfile
Tim Peters8485b562004-08-04 18:46:34 +00001569 >>> real_stdin = sys.stdin
Edward Loper2de91ba2004-08-27 02:07:46 +00001570 >>> sys.stdin = _FakeInput(['next', 'print x', 'continue'])
Tim Peters8485b562004-08-04 18:46:34 +00001571
1572Run the debugger on the docstring, and then restore sys.stdin.
1573
Edward Loper2de91ba2004-08-27 02:07:46 +00001574 >>> try: doctest.debug_src(s)
1575 ... finally: sys.stdin = real_stdin
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001576 > <string>(1)<module>()
Edward Loper2de91ba2004-08-27 02:07:46 +00001577 (Pdb) next
1578 12
Tim Peters8485b562004-08-04 18:46:34 +00001579 --Return--
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001580 > <string>(1)<module>()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001581 (Pdb) print x
1582 12
1583 (Pdb) continue
Tim Peters8485b562004-08-04 18:46:34 +00001584
1585"""
1586
Jim Fulton356fd192004-08-09 11:34:47 +00001587def test_pdb_set_trace():
Tim Peters50c6bdb2004-11-08 22:07:37 +00001588 """Using pdb.set_trace from a doctest.
Jim Fulton356fd192004-08-09 11:34:47 +00001589
Tim Peters413ced62004-08-09 15:43:47 +00001590 You can use pdb.set_trace from a doctest. To do so, you must
Jim Fulton356fd192004-08-09 11:34:47 +00001591 retrieve the set_trace function from the pdb module at the time
Tim Peters413ced62004-08-09 15:43:47 +00001592 you use it. The doctest module changes sys.stdout so that it can
1593 capture program output. It also temporarily replaces pdb.set_trace
1594 with a version that restores stdout. This is necessary for you to
Jim Fulton356fd192004-08-09 11:34:47 +00001595 see debugger output.
1596
1597 >>> doc = '''
1598 ... >>> x = 42
1599 ... >>> import pdb; pdb.set_trace()
1600 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001601 >>> parser = doctest.DocTestParser()
1602 >>> test = parser.get_doctest(doc, {}, "foo", "foo.py", 0)
Jim Fulton356fd192004-08-09 11:34:47 +00001603 >>> runner = doctest.DocTestRunner(verbose=False)
1604
1605 To demonstrate this, we'll create a fake standard input that
1606 captures our debugger input:
1607
1608 >>> import tempfile
Edward Loper2de91ba2004-08-27 02:07:46 +00001609 >>> real_stdin = sys.stdin
1610 >>> sys.stdin = _FakeInput([
Jim Fulton356fd192004-08-09 11:34:47 +00001611 ... 'print x', # print data defined by the example
1612 ... 'continue', # stop debugging
Edward Loper2de91ba2004-08-27 02:07:46 +00001613 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001614
Edward Loper2de91ba2004-08-27 02:07:46 +00001615 >>> try: runner.run(test)
1616 ... finally: sys.stdin = real_stdin
Jim Fulton356fd192004-08-09 11:34:47 +00001617 --Return--
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001618 > <doctest foo[1]>(1)<module>()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001619 -> import pdb; pdb.set_trace()
1620 (Pdb) print x
1621 42
1622 (Pdb) continue
1623 (0, 2)
Jim Fulton356fd192004-08-09 11:34:47 +00001624
1625 You can also put pdb.set_trace in a function called from a test:
1626
1627 >>> def calls_set_trace():
1628 ... y=2
1629 ... import pdb; pdb.set_trace()
1630
1631 >>> doc = '''
1632 ... >>> x=1
1633 ... >>> calls_set_trace()
1634 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +00001635 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
Edward Loper2de91ba2004-08-27 02:07:46 +00001636 >>> real_stdin = sys.stdin
1637 >>> sys.stdin = _FakeInput([
Jim Fulton356fd192004-08-09 11:34:47 +00001638 ... 'print y', # print data defined in the function
1639 ... 'up', # out of function
1640 ... 'print x', # print data defined by the example
1641 ... 'continue', # stop debugging
Edward Loper2de91ba2004-08-27 02:07:46 +00001642 ... ''])
Jim Fulton356fd192004-08-09 11:34:47 +00001643
Tim Peters50c6bdb2004-11-08 22:07:37 +00001644 >>> try:
1645 ... runner.run(test)
1646 ... finally:
1647 ... sys.stdin = real_stdin
Jim Fulton356fd192004-08-09 11:34:47 +00001648 --Return--
Edward Loper2de91ba2004-08-27 02:07:46 +00001649 > <doctest test.test_doctest.test_pdb_set_trace[8]>(3)calls_set_trace()->None
1650 -> import pdb; pdb.set_trace()
1651 (Pdb) print y
1652 2
1653 (Pdb) up
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001654 > <doctest foo[1]>(1)<module>()
Edward Loper2de91ba2004-08-27 02:07:46 +00001655 -> calls_set_trace()
1656 (Pdb) print x
1657 1
1658 (Pdb) continue
1659 (0, 2)
1660
1661 During interactive debugging, source code is shown, even for
1662 doctest examples:
1663
1664 >>> doc = '''
1665 ... >>> def f(x):
1666 ... ... g(x*2)
1667 ... >>> def g(x):
1668 ... ... print x+3
1669 ... ... import pdb; pdb.set_trace()
1670 ... >>> f(3)
1671 ... '''
1672 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
1673 >>> real_stdin = sys.stdin
1674 >>> sys.stdin = _FakeInput([
1675 ... 'list', # list source from example 2
1676 ... 'next', # return from g()
1677 ... 'list', # list source from example 1
1678 ... 'next', # return from f()
1679 ... 'list', # list source from example 3
1680 ... 'continue', # stop debugging
1681 ... ''])
1682 >>> try: runner.run(test)
1683 ... finally: sys.stdin = real_stdin
1684 ... # doctest: +NORMALIZE_WHITESPACE
1685 --Return--
1686 > <doctest foo[1]>(3)g()->None
1687 -> import pdb; pdb.set_trace()
1688 (Pdb) list
1689 1 def g(x):
1690 2 print x+3
1691 3 -> import pdb; pdb.set_trace()
1692 [EOF]
1693 (Pdb) next
1694 --Return--
1695 > <doctest foo[0]>(2)f()->None
1696 -> g(x*2)
1697 (Pdb) list
1698 1 def f(x):
1699 2 -> g(x*2)
1700 [EOF]
1701 (Pdb) next
1702 --Return--
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001703 > <doctest foo[2]>(1)<module>()->None
Edward Loper2de91ba2004-08-27 02:07:46 +00001704 -> f(3)
1705 (Pdb) list
1706 1 -> f(3)
1707 [EOF]
1708 (Pdb) continue
1709 **********************************************************************
1710 File "foo.py", line 7, in foo
1711 Failed example:
1712 f(3)
1713 Expected nothing
1714 Got:
1715 9
1716 (1, 3)
Jim Fulton356fd192004-08-09 11:34:47 +00001717 """
1718
Tim Peters50c6bdb2004-11-08 22:07:37 +00001719def test_pdb_set_trace_nested():
1720 """This illustrates more-demanding use of set_trace with nested functions.
1721
1722 >>> class C(object):
1723 ... def calls_set_trace(self):
1724 ... y = 1
1725 ... import pdb; pdb.set_trace()
1726 ... self.f1()
1727 ... y = 2
1728 ... def f1(self):
1729 ... x = 1
1730 ... self.f2()
1731 ... x = 2
1732 ... def f2(self):
1733 ... z = 1
1734 ... z = 2
1735
1736 >>> calls_set_trace = C().calls_set_trace
1737
1738 >>> doc = '''
1739 ... >>> a = 1
1740 ... >>> calls_set_trace()
1741 ... '''
1742 >>> parser = doctest.DocTestParser()
1743 >>> runner = doctest.DocTestRunner(verbose=False)
1744 >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
1745 >>> real_stdin = sys.stdin
1746 >>> sys.stdin = _FakeInput([
1747 ... 'print y', # print data defined in the function
1748 ... 'step', 'step', 'step', 'step', 'step', 'step', 'print z',
1749 ... 'up', 'print x',
1750 ... 'up', 'print y',
1751 ... 'up', 'print foo',
1752 ... 'continue', # stop debugging
1753 ... ''])
1754
1755 >>> try:
1756 ... runner.run(test)
1757 ... finally:
1758 ... sys.stdin = real_stdin
1759 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
1760 -> self.f1()
1761 (Pdb) print y
1762 1
1763 (Pdb) step
1764 --Call--
1765 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(7)f1()
1766 -> def f1(self):
1767 (Pdb) step
1768 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(8)f1()
1769 -> x = 1
1770 (Pdb) step
1771 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
1772 -> self.f2()
1773 (Pdb) step
1774 --Call--
1775 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(11)f2()
1776 -> def f2(self):
1777 (Pdb) step
1778 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(12)f2()
1779 -> z = 1
1780 (Pdb) step
1781 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(13)f2()
1782 -> z = 2
1783 (Pdb) print z
1784 1
1785 (Pdb) up
1786 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
1787 -> self.f2()
1788 (Pdb) print x
1789 1
1790 (Pdb) up
1791 > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
1792 -> self.f1()
1793 (Pdb) print y
1794 1
1795 (Pdb) up
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001796 > <doctest foo[1]>(1)<module>()
Tim Peters50c6bdb2004-11-08 22:07:37 +00001797 -> calls_set_trace()
1798 (Pdb) print foo
1799 *** NameError: name 'foo' is not defined
1800 (Pdb) continue
1801 (0, 2)
1802"""
1803
Tim Peters19397e52004-08-06 22:02:59 +00001804def test_DocTestSuite():
Tim Peters1e277ee2004-08-07 05:37:52 +00001805 """DocTestSuite creates a unittest test suite from a doctest.
Tim Peters19397e52004-08-06 22:02:59 +00001806
1807 We create a Suite by providing a module. A module can be provided
1808 by passing a module object:
1809
1810 >>> import unittest
1811 >>> import test.sample_doctest
1812 >>> suite = doctest.DocTestSuite(test.sample_doctest)
1813 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001814 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001815
1816 We can also supply the module by name:
1817
1818 >>> suite = doctest.DocTestSuite('test.sample_doctest')
1819 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001820 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001821
1822 We can use the current module:
1823
1824 >>> suite = test.sample_doctest.test_suite()
1825 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001826 <unittest.TestResult run=9 errors=0 failures=4>
Tim Peters19397e52004-08-06 22:02:59 +00001827
1828 We can supply global variables. If we pass globs, they will be
1829 used instead of the module globals. Here we'll pass an empty
1830 globals, triggering an extra error:
1831
1832 >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
1833 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001834 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001835
1836 Alternatively, we can provide extra globals. Here we'll make an
1837 error go away by providing an extra global variable:
1838
1839 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1840 ... extraglobs={'y': 1})
1841 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001842 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001843
1844 You can pass option flags. Here we'll cause an extra error
1845 by disabling the blank-line feature:
1846
1847 >>> suite = doctest.DocTestSuite('test.sample_doctest',
Tim Peters1e277ee2004-08-07 05:37:52 +00001848 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
Tim Peters19397e52004-08-06 22:02:59 +00001849 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001850 <unittest.TestResult run=9 errors=0 failures=5>
Tim Peters19397e52004-08-06 22:02:59 +00001851
Tim Peters1e277ee2004-08-07 05:37:52 +00001852 You can supply setUp and tearDown functions:
Tim Peters19397e52004-08-06 22:02:59 +00001853
Jim Fultonf54bad42004-08-28 14:57:56 +00001854 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00001855 ... import test.test_doctest
1856 ... test.test_doctest.sillySetup = True
1857
Jim Fultonf54bad42004-08-28 14:57:56 +00001858 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00001859 ... import test.test_doctest
1860 ... del test.test_doctest.sillySetup
1861
1862 Here, we installed a silly variable that the test expects:
1863
1864 >>> suite = doctest.DocTestSuite('test.sample_doctest',
1865 ... setUp=setUp, tearDown=tearDown)
1866 >>> suite.run(unittest.TestResult())
Tim Peters1e277ee2004-08-07 05:37:52 +00001867 <unittest.TestResult run=9 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001868
1869 But the tearDown restores sanity:
1870
1871 >>> import test.test_doctest
1872 >>> test.test_doctest.sillySetup
1873 Traceback (most recent call last):
1874 ...
1875 AttributeError: 'module' object has no attribute 'sillySetup'
1876
Jim Fultonf54bad42004-08-28 14:57:56 +00001877 The setUp and tearDown funtions are passed test objects. Here
1878 we'll use the setUp function to supply the missing variable y:
1879
1880 >>> def setUp(test):
1881 ... test.globs['y'] = 1
1882
1883 >>> suite = doctest.DocTestSuite('test.sample_doctest', setUp=setUp)
1884 >>> suite.run(unittest.TestResult())
1885 <unittest.TestResult run=9 errors=0 failures=3>
1886
1887 Here, we didn't need to use a tearDown function because we
1888 modified the test globals, which are a copy of the
1889 sample_doctest module dictionary. The test globals are
1890 automatically cleared for us after a test.
Tim Peters19397e52004-08-06 22:02:59 +00001891 """
1892
1893def test_DocFileSuite():
1894 """We can test tests found in text files using a DocFileSuite.
1895
1896 We create a suite by providing the names of one or more text
1897 files that include examples:
1898
1899 >>> import unittest
1900 >>> suite = doctest.DocFileSuite('test_doctest.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001901 ... 'test_doctest2.txt',
1902 ... 'test_doctest4.txt')
Tim Peters19397e52004-08-06 22:02:59 +00001903 >>> suite.run(unittest.TestResult())
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001904 <unittest.TestResult run=3 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001905
1906 The test files are looked for in the directory containing the
1907 calling module. A package keyword argument can be provided to
1908 specify a different relative location.
1909
1910 >>> import unittest
1911 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1912 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001913 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00001914 ... package='test')
1915 >>> suite.run(unittest.TestResult())
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001916 <unittest.TestResult run=3 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001917
Edward Loper0273f5b2004-09-18 20:27:04 +00001918 '/' should be used as a path separator. It will be converted
1919 to a native separator at run time:
Tim Peters19397e52004-08-06 22:02:59 +00001920
1921 >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
1922 >>> suite.run(unittest.TestResult())
1923 <unittest.TestResult run=1 errors=0 failures=1>
1924
Edward Loper0273f5b2004-09-18 20:27:04 +00001925 If DocFileSuite is used from an interactive session, then files
1926 are resolved relative to the directory of sys.argv[0]:
1927
1928 >>> import new, os.path, test.test_doctest
1929 >>> save_argv = sys.argv
1930 >>> sys.argv = [test.test_doctest.__file__]
1931 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1932 ... package=new.module('__main__'))
1933 >>> sys.argv = save_argv
1934
Edward Loper052d0cd2004-09-19 17:19:33 +00001935 By setting `module_relative=False`, os-specific paths may be
1936 used (including absolute paths and paths relative to the
1937 working directory):
Edward Loper0273f5b2004-09-18 20:27:04 +00001938
1939 >>> # Get the absolute path of the test package.
1940 >>> test_doctest_path = os.path.abspath(test.test_doctest.__file__)
1941 >>> test_pkg_path = os.path.split(test_doctest_path)[0]
1942
1943 >>> # Use it to find the absolute path of test_doctest.txt.
1944 >>> test_file = os.path.join(test_pkg_path, 'test_doctest.txt')
1945
Edward Loper052d0cd2004-09-19 17:19:33 +00001946 >>> suite = doctest.DocFileSuite(test_file, module_relative=False)
Edward Loper0273f5b2004-09-18 20:27:04 +00001947 >>> suite.run(unittest.TestResult())
1948 <unittest.TestResult run=1 errors=0 failures=1>
1949
Edward Loper052d0cd2004-09-19 17:19:33 +00001950 It is an error to specify `package` when `module_relative=False`:
1951
1952 >>> suite = doctest.DocFileSuite(test_file, module_relative=False,
1953 ... package='test')
1954 Traceback (most recent call last):
1955 ValueError: Package may only be specified for module-relative paths.
1956
Tim Peters19397e52004-08-06 22:02:59 +00001957 You can specify initial global variables:
1958
1959 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1960 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001961 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00001962 ... globs={'favorite_color': 'blue'})
1963 >>> suite.run(unittest.TestResult())
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001964 <unittest.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00001965
1966 In this case, we supplied a missing favorite color. You can
1967 provide doctest options:
1968
1969 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1970 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001971 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00001972 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
1973 ... globs={'favorite_color': 'blue'})
1974 >>> suite.run(unittest.TestResult())
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001975 <unittest.TestResult run=3 errors=0 failures=3>
Tim Peters19397e52004-08-06 22:02:59 +00001976
1977 And, you can provide setUp and tearDown functions:
1978
1979 You can supply setUp and teatDoen functions:
1980
Jim Fultonf54bad42004-08-28 14:57:56 +00001981 >>> def setUp(t):
Tim Peters19397e52004-08-06 22:02:59 +00001982 ... import test.test_doctest
1983 ... test.test_doctest.sillySetup = True
1984
Jim Fultonf54bad42004-08-28 14:57:56 +00001985 >>> def tearDown(t):
Tim Peters19397e52004-08-06 22:02:59 +00001986 ... import test.test_doctest
1987 ... del test.test_doctest.sillySetup
1988
1989 Here, we installed a silly variable that the test expects:
1990
1991 >>> suite = doctest.DocFileSuite('test_doctest.txt',
1992 ... 'test_doctest2.txt',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001993 ... 'test_doctest4.txt',
Tim Peters19397e52004-08-06 22:02:59 +00001994 ... setUp=setUp, tearDown=tearDown)
1995 >>> suite.run(unittest.TestResult())
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001996 <unittest.TestResult run=3 errors=0 failures=2>
Tim Peters19397e52004-08-06 22:02:59 +00001997
1998 But the tearDown restores sanity:
1999
2000 >>> import test.test_doctest
2001 >>> test.test_doctest.sillySetup
2002 Traceback (most recent call last):
2003 ...
2004 AttributeError: 'module' object has no attribute 'sillySetup'
2005
Jim Fultonf54bad42004-08-28 14:57:56 +00002006 The setUp and tearDown funtions are passed test objects.
2007 Here, we'll use a setUp function to set the favorite color in
2008 test_doctest.txt:
2009
2010 >>> def setUp(test):
2011 ... test.globs['favorite_color'] = 'blue'
2012
2013 >>> suite = doctest.DocFileSuite('test_doctest.txt', setUp=setUp)
2014 >>> suite.run(unittest.TestResult())
2015 <unittest.TestResult run=1 errors=0 failures=0>
2016
2017 Here, we didn't need to use a tearDown function because we
2018 modified the test globals. The test globals are
2019 automatically cleared for us after a test.
Tim Petersdf7a2082004-08-29 00:38:17 +00002020
Fred Drake7c404a42004-12-21 23:46:34 +00002021 Tests in a file run using `DocFileSuite` can also access the
2022 `__file__` global, which is set to the name of the file
2023 containing the tests:
2024
2025 >>> suite = doctest.DocFileSuite('test_doctest3.txt')
2026 >>> suite.run(unittest.TestResult())
2027 <unittest.TestResult run=1 errors=0 failures=0>
2028
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002029 If the tests contain non-ASCII characters, we have to specify which
2030 encoding the file is encoded with. We do so by using the `encoding`
2031 parameter:
2032
2033 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2034 ... 'test_doctest2.txt',
2035 ... 'test_doctest4.txt',
2036 ... encoding='utf-8')
2037 >>> suite.run(unittest.TestResult())
2038 <unittest.TestResult run=3 errors=0 failures=2>
2039
Jim Fultonf54bad42004-08-28 14:57:56 +00002040 """
Tim Peters19397e52004-08-06 22:02:59 +00002041
Jim Fulton07a349c2004-08-22 14:10:00 +00002042def test_trailing_space_in_test():
2043 """
Tim Petersa7def722004-08-23 22:13:22 +00002044 Trailing spaces in expected output are significant:
Tim Petersc6cbab02004-08-22 19:43:28 +00002045
Jim Fulton07a349c2004-08-22 14:10:00 +00002046 >>> x, y = 'foo', ''
2047 >>> print x, y
2048 foo \n
2049 """
Tim Peters19397e52004-08-06 22:02:59 +00002050
Jim Fultonf54bad42004-08-28 14:57:56 +00002051
2052def test_unittest_reportflags():
2053 """Default unittest reporting flags can be set to control reporting
2054
2055 Here, we'll set the REPORT_ONLY_FIRST_FAILURE option so we see
2056 only the first failure of each test. First, we'll look at the
2057 output without the flag. The file test_doctest.txt file has two
2058 tests. They both fail if blank lines are disabled:
2059
2060 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2061 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
2062 >>> import unittest
2063 >>> result = suite.run(unittest.TestResult())
2064 >>> print result.failures[0][1] # doctest: +ELLIPSIS
2065 Traceback ...
2066 Failed example:
2067 favorite_color
2068 ...
2069 Failed example:
2070 if 1:
2071 ...
2072
2073 Note that we see both failures displayed.
2074
2075 >>> old = doctest.set_unittest_reportflags(
2076 ... doctest.REPORT_ONLY_FIRST_FAILURE)
2077
2078 Now, when we run the test:
2079
2080 >>> result = suite.run(unittest.TestResult())
2081 >>> print result.failures[0][1] # doctest: +ELLIPSIS
2082 Traceback ...
2083 Failed example:
2084 favorite_color
2085 Exception raised:
2086 ...
2087 NameError: name 'favorite_color' is not defined
2088 <BLANKLINE>
2089 <BLANKLINE>
Tim Petersdf7a2082004-08-29 00:38:17 +00002090
Jim Fultonf54bad42004-08-28 14:57:56 +00002091 We get only the first failure.
2092
2093 If we give any reporting options when we set up the tests,
2094 however:
2095
2096 >>> suite = doctest.DocFileSuite('test_doctest.txt',
2097 ... optionflags=doctest.DONT_ACCEPT_BLANKLINE | doctest.REPORT_NDIFF)
2098
2099 Then the default eporting options are ignored:
2100
2101 >>> result = suite.run(unittest.TestResult())
2102 >>> print result.failures[0][1] # doctest: +ELLIPSIS
2103 Traceback ...
2104 Failed example:
2105 favorite_color
2106 ...
2107 Failed example:
2108 if 1:
2109 print 'a'
2110 print
2111 print 'b'
2112 Differences (ndiff with -expected +actual):
2113 a
2114 - <BLANKLINE>
2115 +
2116 b
2117 <BLANKLINE>
2118 <BLANKLINE>
2119
2120
2121 Test runners can restore the formatting flags after they run:
2122
2123 >>> ignored = doctest.set_unittest_reportflags(old)
2124
2125 """
2126
Edward Loper052d0cd2004-09-19 17:19:33 +00002127def test_testfile(): r"""
2128Tests for the `testfile()` function. This function runs all the
2129doctest examples in a given file. In its simple invokation, it is
2130called with the name of a file, which is taken to be relative to the
2131calling module. The return value is (#failures, #tests).
2132
2133 >>> doctest.testfile('test_doctest.txt') # doctest: +ELLIPSIS
2134 **********************************************************************
2135 File "...", line 6, in test_doctest.txt
2136 Failed example:
2137 favorite_color
2138 Exception raised:
2139 ...
2140 NameError: name 'favorite_color' is not defined
2141 **********************************************************************
2142 1 items had failures:
2143 1 of 2 in test_doctest.txt
2144 ***Test Failed*** 1 failures.
2145 (1, 2)
2146 >>> doctest.master = None # Reset master.
2147
2148(Note: we'll be clearing doctest.master after each call to
2149`doctest.testfile`, to supress warnings about multiple tests with the
2150same name.)
2151
2152Globals may be specified with the `globs` and `extraglobs` parameters:
2153
2154 >>> globs = {'favorite_color': 'blue'}
2155 >>> doctest.testfile('test_doctest.txt', globs=globs)
2156 (0, 2)
2157 >>> doctest.master = None # Reset master.
2158
2159 >>> extraglobs = {'favorite_color': 'red'}
2160 >>> doctest.testfile('test_doctest.txt', globs=globs,
2161 ... extraglobs=extraglobs) # doctest: +ELLIPSIS
2162 **********************************************************************
2163 File "...", line 6, in test_doctest.txt
2164 Failed example:
2165 favorite_color
2166 Expected:
2167 'blue'
2168 Got:
2169 'red'
2170 **********************************************************************
2171 1 items had failures:
2172 1 of 2 in test_doctest.txt
2173 ***Test Failed*** 1 failures.
2174 (1, 2)
2175 >>> doctest.master = None # Reset master.
2176
2177The file may be made relative to a given module or package, using the
2178optional `module_relative` parameter:
2179
2180 >>> doctest.testfile('test_doctest.txt', globs=globs,
2181 ... module_relative='test')
2182 (0, 2)
2183 >>> doctest.master = None # Reset master.
2184
2185Verbosity can be increased with the optional `verbose` paremter:
2186
2187 >>> doctest.testfile('test_doctest.txt', globs=globs, verbose=True)
2188 Trying:
2189 favorite_color
2190 Expecting:
2191 'blue'
2192 ok
2193 Trying:
2194 if 1:
2195 print 'a'
2196 print
2197 print 'b'
2198 Expecting:
2199 a
2200 <BLANKLINE>
2201 b
2202 ok
2203 1 items passed all tests:
2204 2 tests in test_doctest.txt
2205 2 tests in 1 items.
2206 2 passed and 0 failed.
2207 Test passed.
2208 (0, 2)
2209 >>> doctest.master = None # Reset master.
2210
2211The name of the test may be specified with the optional `name`
2212parameter:
2213
2214 >>> doctest.testfile('test_doctest.txt', name='newname')
2215 ... # doctest: +ELLIPSIS
2216 **********************************************************************
2217 File "...", line 6, in newname
2218 ...
2219 (1, 2)
2220 >>> doctest.master = None # Reset master.
2221
2222The summary report may be supressed with the optional `report`
2223parameter:
2224
2225 >>> doctest.testfile('test_doctest.txt', report=False)
2226 ... # doctest: +ELLIPSIS
2227 **********************************************************************
2228 File "...", line 6, in test_doctest.txt
2229 Failed example:
2230 favorite_color
2231 Exception raised:
2232 ...
2233 NameError: name 'favorite_color' is not defined
2234 (1, 2)
2235 >>> doctest.master = None # Reset master.
2236
2237The optional keyword argument `raise_on_error` can be used to raise an
2238exception on the first error (which may be useful for postmortem
2239debugging):
2240
2241 >>> doctest.testfile('test_doctest.txt', raise_on_error=True)
2242 ... # doctest: +ELLIPSIS
2243 Traceback (most recent call last):
2244 UnexpectedException: ...
2245 >>> doctest.master = None # Reset master.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002246
2247If the tests contain non-ASCII characters, the tests might fail, since
2248it's unknown which encoding is used. The encoding can be specified
2249using the optional keyword argument `encoding`:
2250
2251 >>> doctest.testfile('test_doctest4.txt') # doctest: +ELLIPSIS
2252 **********************************************************************
2253 File "...", line 7, in test_doctest4.txt
2254 Failed example:
2255 u'...'
2256 Expected:
2257 u'f\xf6\xf6'
2258 Got:
2259 u'f\xc3\xb6\xc3\xb6'
2260 **********************************************************************
2261 ...
2262 **********************************************************************
2263 1 items had failures:
2264 2 of 4 in test_doctest4.txt
2265 ***Test Failed*** 2 failures.
2266 (2, 4)
2267 >>> doctest.master = None # Reset master.
2268
2269 >>> doctest.testfile('test_doctest4.txt', encoding='utf-8')
2270 (0, 4)
2271 >>> doctest.master = None # Reset master.
Edward Loper052d0cd2004-09-19 17:19:33 +00002272"""
2273
Tim Petersa7def722004-08-23 22:13:22 +00002274# old_test1, ... used to live in doctest.py, but cluttered it. Note
2275# that these use the deprecated doctest.Tester, so should go away (or
2276# be rewritten) someday.
2277
2278# Ignore all warnings about the use of class Tester in this module.
2279# Note that the name of this module may differ depending on how it's
2280# imported, so the use of __name__ is important.
2281warnings.filterwarnings("ignore", "class Tester", DeprecationWarning,
2282 __name__, 0)
2283
2284def old_test1(): r"""
2285>>> from doctest import Tester
2286>>> t = Tester(globs={'x': 42}, verbose=0)
2287>>> t.runstring(r'''
2288... >>> x = x * 2
2289... >>> print x
2290... 42
2291... ''', 'XYZ')
2292**********************************************************************
2293Line 3, in XYZ
2294Failed example:
2295 print x
2296Expected:
2297 42
2298Got:
2299 84
2300(1, 2)
2301>>> t.runstring(">>> x = x * 2\n>>> print x\n84\n", 'example2')
2302(0, 2)
2303>>> t.summarize()
2304**********************************************************************
23051 items had failures:
2306 1 of 2 in XYZ
2307***Test Failed*** 1 failures.
2308(1, 4)
2309>>> t.summarize(verbose=1)
23101 items passed all tests:
2311 2 tests in example2
2312**********************************************************************
23131 items had failures:
2314 1 of 2 in XYZ
23154 tests in 2 items.
23163 passed and 1 failed.
2317***Test Failed*** 1 failures.
2318(1, 4)
2319"""
2320
2321def old_test2(): r"""
2322 >>> from doctest import Tester
2323 >>> t = Tester(globs={}, verbose=1)
2324 >>> test = r'''
2325 ... # just an example
2326 ... >>> x = 1 + 2
2327 ... >>> x
2328 ... 3
2329 ... '''
2330 >>> t.runstring(test, "Example")
2331 Running string Example
Edward Loperaacf0832004-08-26 01:19:50 +00002332 Trying:
2333 x = 1 + 2
2334 Expecting nothing
Tim Petersa7def722004-08-23 22:13:22 +00002335 ok
Edward Loperaacf0832004-08-26 01:19:50 +00002336 Trying:
2337 x
2338 Expecting:
2339 3
Tim Petersa7def722004-08-23 22:13:22 +00002340 ok
2341 0 of 2 examples failed in string Example
2342 (0, 2)
2343"""
2344
2345def old_test3(): r"""
2346 >>> from doctest import Tester
2347 >>> t = Tester(globs={}, verbose=0)
2348 >>> def _f():
2349 ... '''Trivial docstring example.
2350 ... >>> assert 2 == 2
2351 ... '''
2352 ... return 32
2353 ...
2354 >>> t.rundoc(_f) # expect 0 failures in 1 example
2355 (0, 1)
2356"""
2357
2358def old_test4(): """
2359 >>> import new
2360 >>> m1 = new.module('_m1')
2361 >>> m2 = new.module('_m2')
2362 >>> test_data = \"""
2363 ... def _f():
2364 ... '''>>> assert 1 == 1
2365 ... '''
2366 ... def g():
2367 ... '''>>> assert 2 != 1
2368 ... '''
2369 ... class H:
2370 ... '''>>> assert 2 > 1
2371 ... '''
2372 ... def bar(self):
2373 ... '''>>> assert 1 < 2
2374 ... '''
2375 ... \"""
2376 >>> exec test_data in m1.__dict__
2377 >>> exec test_data in m2.__dict__
2378 >>> m1.__dict__.update({"f2": m2._f, "g2": m2.g, "h2": m2.H})
2379
2380 Tests that objects outside m1 are excluded:
2381
2382 >>> from doctest import Tester
2383 >>> t = Tester(globs={}, verbose=0)
2384 >>> t.rundict(m1.__dict__, "rundict_test", m1) # f2 and g2 and h2 skipped
2385 (0, 4)
2386
2387 Once more, not excluding stuff outside m1:
2388
2389 >>> t = Tester(globs={}, verbose=0)
2390 >>> t.rundict(m1.__dict__, "rundict_test_pvt") # None are skipped.
2391 (0, 8)
2392
2393 The exclusion of objects from outside the designated module is
2394 meant to be invoked automagically by testmod.
2395
2396 >>> doctest.testmod(m1, verbose=False)
2397 (0, 4)
2398"""
2399
Tim Peters8485b562004-08-04 18:46:34 +00002400######################################################################
2401## Main
2402######################################################################
2403
2404def test_main():
2405 # Check the doctest cases in doctest itself:
2406 test_support.run_doctest(doctest, verbosity=True)
2407 # Check the doctest cases defined here:
2408 from test import test_doctest
2409 test_support.run_doctest(test_doctest, verbosity=True)
2410
2411import trace, sys, re, StringIO
2412def test_coverage(coverdir):
2413 tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
2414 trace=0, count=1)
2415 tracer.run('reload(doctest); test_main()')
2416 r = tracer.results()
2417 print 'Writing coverage results...'
2418 r.write_results(show_missing=True, summary=True,
2419 coverdir=coverdir)
2420
2421if __name__ == '__main__':
2422 if '-c' in sys.argv:
2423 test_coverage('/tmp/doctest.cover')
2424 else:
2425 test_main()