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